@otium-team/negotium 0.0.0-stage → 0.23.13
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/LICENSE +202 -0
- package/README.md +329 -2
- package/bin/codex-sdk-window-hide.mjs +40 -0
- package/bin/negotium.mjs +22 -0
- package/dist/agent-helpers.js +23090 -0
- package/dist/agent-helpers.js.map +171 -0
- package/dist/background-bash.js +535 -0
- package/dist/background-bash.js.map +16 -0
- package/dist/browser-runtime.js +2334 -0
- package/dist/browser-runtime.js.map +35 -0
- package/dist/canonical-mcp-bridge.js +13 -0
- package/dist/canonical-mcp-bridge.js.map +9 -0
- package/dist/chunk-22kg3fsw.js +79 -0
- package/dist/chunk-22kg3fsw.js.map +9 -0
- package/dist/chunk-d4j77adx.js +336 -0
- package/dist/chunk-d4j77adx.js.map +13 -0
- package/dist/chunk-mk9x18jn.js +172 -0
- package/dist/chunk-mk9x18jn.js.map +12 -0
- package/dist/chunk-qd0vtfm2.js +3923 -0
- package/dist/chunk-qd0vtfm2.js.map +47 -0
- package/dist/chunk-wf7ny8eq.js +206 -0
- package/dist/chunk-wf7ny8eq.js.map +10 -0
- package/dist/chunk-ww8a4ej4.js +54 -0
- package/dist/chunk-ww8a4ej4.js.map +10 -0
- package/dist/cron.js +1 -0
- package/dist/hosted-agent.js +5982 -0
- package/dist/hosted-agent.js.map +62 -0
- package/dist/main.js +60229 -0
- package/dist/main.js.map +340 -0
- package/dist/mcp-catalog.js +39 -0
- package/dist/mcp-catalog.js.map +10 -0
- package/dist/mcp-factories.js +25767 -0
- package/dist/mcp-factories.js.map +181 -0
- package/dist/mcp-servers.js +50 -0
- package/dist/mcp-servers.js.map +10 -0
- package/dist/media.js +570 -0
- package/dist/media.js.map +15 -0
- package/dist/outbox.js +354 -0
- package/dist/outbox.js.map +15 -0
- package/dist/platform-runtime.js +73 -0
- package/dist/platform-runtime.js.map +12 -0
- package/dist/prompts.js +892 -0
- package/dist/prompts.js.map +15 -0
- package/dist/query-runtime.js +1071 -0
- package/dist/query-runtime.js.map +26 -0
- package/dist/registry.js +335 -0
- package/dist/registry.js.map +14 -0
- package/dist/rollout.js +57 -0
- package/dist/rollout.js.map +10 -0
- package/dist/runtime/cron/background-sessions.ts +119 -0
- package/dist/runtime/cron/context.ts +123 -0
- package/dist/runtime/cron/host.ts +67 -0
- package/dist/runtime/cron/index.ts +95 -0
- package/dist/runtime/cron/mcp-server.ts +556 -0
- package/dist/runtime/cron/module.ts +174 -0
- package/dist/runtime/cron/package.json +6 -0
- package/dist/runtime/cron/schedule.ts +211 -0
- package/dist/runtime/cron/scheduler.ts +444 -0
- package/dist/runtime/cron/scripts.ts +203 -0
- package/dist/runtime/cron/store.ts +1163 -0
- package/dist/runtime/cron/summarize.ts +115 -0
- package/dist/runtime/package.json +6 -0
- package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
- package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
- package/dist/runtime/src/agents/archiver.ts +677 -0
- package/dist/runtime/src/agents/auth-check.ts +156 -0
- package/dist/runtime/src/agents/claude-notices.ts +130 -0
- package/dist/runtime/src/agents/claude-provider.ts +941 -0
- package/dist/runtime/src/agents/claude-registry.ts +117 -0
- package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
- package/dist/runtime/src/agents/codex-app-server.ts +138 -0
- package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
- package/dist/runtime/src/agents/codex-provider.ts +1193 -0
- package/dist/runtime/src/agents/codex-registry.ts +116 -0
- package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
- package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
- package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
- package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
- package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
- package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
- package/dist/runtime/src/agents/compaction-support.ts +75 -0
- package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
- package/dist/runtime/src/agents/contracts.ts +75 -0
- package/dist/runtime/src/agents/deep-map.ts +13 -0
- package/dist/runtime/src/agents/execution-host.ts +118 -0
- package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
- package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
- package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
- package/dist/runtime/src/agents/fork.ts +100 -0
- package/dist/runtime/src/agents/hosted-agent.ts +78 -0
- package/dist/runtime/src/agents/idle-archiver.ts +225 -0
- package/dist/runtime/src/agents/idle-compact.ts +225 -0
- package/dist/runtime/src/agents/index.ts +225 -0
- package/dist/runtime/src/agents/maestro-provider.ts +246 -0
- package/dist/runtime/src/agents/maestro-registry.ts +189 -0
- package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
- package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
- package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
- package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
- package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
- package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
- package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
- package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
- package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
- package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
- package/dist/runtime/src/agents/model-catalog.ts +439 -0
- package/dist/runtime/src/agents/public-helpers.ts +149 -0
- package/dist/runtime/src/agents/registry.ts +35 -0
- package/dist/runtime/src/agents/rollout/claude.ts +336 -0
- package/dist/runtime/src/agents/rollout/codex.ts +910 -0
- package/dist/runtime/src/agents/rollout/index.ts +26 -0
- package/dist/runtime/src/agents/rollout/shared.ts +293 -0
- package/dist/runtime/src/agents/self-config-core.ts +704 -0
- package/dist/runtime/src/agents/task-events.ts +59 -0
- package/dist/runtime/src/agents/tool-format.ts +613 -0
- package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
- package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
- package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
- package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
- package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
- package/dist/runtime/src/application/submit-user-message.ts +60 -0
- package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
- package/dist/runtime/src/application/switch-topic-model.ts +79 -0
- package/dist/runtime/src/application/topic-service.ts +190 -0
- package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
- package/dist/runtime/src/application/vault-command.ts +170 -0
- package/dist/runtime/src/bus.ts +409 -0
- package/dist/runtime/src/config-public.ts +2 -0
- package/dist/runtime/src/cron-host.ts +33 -0
- package/dist/runtime/src/cron-mcp-host.ts +5 -0
- package/dist/runtime/src/identifiers.ts +49 -0
- package/dist/runtime/src/index.ts +573 -0
- package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
- package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
- package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
- package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
- package/dist/runtime/src/mcp/decision-server.ts +21 -0
- package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
- package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
- package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
- package/dist/runtime/src/mcp/factories/decision.ts +186 -0
- package/dist/runtime/src/mcp/factories/index.ts +73 -0
- package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
- package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
- package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
- package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
- package/dist/runtime/src/mcp/factories/task.ts +185 -0
- package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
- package/dist/runtime/src/mcp/factories/vault.ts +32 -0
- package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
- package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
- package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
- package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
- package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
- package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
- package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
- package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
- package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
- package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
- package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
- package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
- package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
- package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
- package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
- package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
- package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
- package/dist/runtime/src/mcp/session-history-server.ts +19 -0
- package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
- package/dist/runtime/src/mcp/system-health-server.ts +5 -0
- package/dist/runtime/src/mcp/task-server.ts +17 -0
- package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
- package/dist/runtime/src/mcp/vault-server.ts +12 -0
- package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
- package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
- package/dist/runtime/src/mcp-runtime-host.ts +81 -0
- package/dist/runtime/src/media/file-events.ts +33 -0
- package/dist/runtime/src/media/text-extractor.ts +334 -0
- package/dist/runtime/src/media/video.ts +92 -0
- package/dist/runtime/src/node-host.ts +211 -0
- package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
- package/dist/runtime/src/outbox/file-ops.ts +267 -0
- package/dist/runtime/src/outbox/index.ts +26 -0
- package/dist/runtime/src/outbox/utils.ts +74 -0
- package/dist/runtime/src/platform/background-bash/context.ts +9 -0
- package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
- package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
- package/dist/runtime/src/platform/config-helpers.ts +47 -0
- package/dist/runtime/src/platform/config.ts +618 -0
- package/dist/runtime/src/platform/constants.ts +30 -0
- package/dist/runtime/src/platform/debug-users.ts +14 -0
- package/dist/runtime/src/platform/delay.ts +1 -0
- package/dist/runtime/src/platform/error.ts +9 -0
- package/dist/runtime/src/platform/file-utils.ts +35 -0
- package/dist/runtime/src/platform/ipc.ts +55 -0
- package/dist/runtime/src/platform/jsonl.ts +277 -0
- package/dist/runtime/src/platform/lifecycle.ts +176 -0
- package/dist/runtime/src/platform/log-rotation.ts +45 -0
- package/dist/runtime/src/platform/logger.ts +42 -0
- package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
- package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
- package/dist/runtime/src/platform/mcp-config.ts +1329 -0
- package/dist/runtime/src/platform/memoize-import.ts +26 -0
- package/dist/runtime/src/platform/modules.ts +145 -0
- package/dist/runtime/src/platform/node-plugins.ts +46 -0
- package/dist/runtime/src/platform/paths.ts +62 -0
- package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
- package/dist/runtime/src/platform/playwright/capability.ts +5 -0
- package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
- package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
- package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
- package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
- package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
- package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
- package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
- package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
- package/dist/runtime/src/platform/public-runtime.ts +18 -0
- package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
- package/dist/runtime/src/prompts/builders.ts +696 -0
- package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
- package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
- package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
- package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
- package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
- package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
- package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
- package/dist/runtime/src/query/active-rooms.ts +514 -0
- package/dist/runtime/src/query/index.ts +23 -0
- package/dist/runtime/src/query/public-runtime.ts +28 -0
- package/dist/runtime/src/query/room-query-registry.ts +217 -0
- package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
- package/dist/runtime/src/query/session-inbox-path.ts +42 -0
- package/dist/runtime/src/query/state.ts +116 -0
- package/dist/runtime/src/query/types.ts +8 -0
- package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
- package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
- package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
- package/dist/runtime/src/runtime/attachments.ts +149 -0
- package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
- package/dist/runtime/src/runtime/background-sessions.ts +288 -0
- package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
- package/dist/runtime/src/runtime/channel-context.ts +115 -0
- package/dist/runtime/src/runtime/context-warning.ts +131 -0
- package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
- package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
- package/dist/runtime/src/runtime/errors.ts +70 -0
- package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
- package/dist/runtime/src/runtime/file-hooks.ts +81 -0
- package/dist/runtime/src/runtime/footer.ts +23 -0
- package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
- package/dist/runtime/src/runtime/inbox.ts +1307 -0
- package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
- package/dist/runtime/src/runtime/public-helpers.ts +78 -0
- package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
- package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
- package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
- package/dist/runtime/src/runtime/task-format.ts +18 -0
- package/dist/runtime/src/runtime/tasks.ts +53 -0
- package/dist/runtime/src/runtime/thread-context.ts +123 -0
- package/dist/runtime/src/runtime/thread-read.ts +67 -0
- package/dist/runtime/src/runtime/topic-config.ts +29 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
- package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
- package/dist/runtime/src/runtime/turn-session.ts +116 -0
- package/dist/runtime/src/runtime/usage-alert.ts +51 -0
- package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
- package/dist/runtime/src/runtime/visual-html.ts +175 -0
- package/dist/runtime/src/runtime/visual-store.ts +480 -0
- package/dist/runtime/src/runtime/visuals.ts +209 -0
- package/dist/runtime/src/runtime-gateway.ts +1045 -0
- package/dist/runtime/src/security/sanitize.ts +27 -0
- package/dist/runtime/src/security/sensitive-path.ts +41 -0
- package/dist/runtime/src/storage/activity-log.ts +167 -0
- package/dist/runtime/src/storage/api-messages.ts +766 -0
- package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
- package/dist/runtime/src/storage/api-topic-config.ts +197 -0
- package/dist/runtime/src/storage/api-topics.ts +1647 -0
- package/dist/runtime/src/storage/app-settings.ts +50 -0
- package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
- package/dist/runtime/src/storage/browser-profiles.ts +186 -0
- package/dist/runtime/src/storage/conversation-migration.ts +180 -0
- package/dist/runtime/src/storage/conversations.ts +377 -0
- package/dist/runtime/src/storage/decisions.ts +231 -0
- package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
- package/dist/runtime/src/storage/forum/index.ts +4 -0
- package/dist/runtime/src/storage/forum/repository.ts +283 -0
- package/dist/runtime/src/storage/forum/schema.ts +314 -0
- package/dist/runtime/src/storage/forum-db.ts +4 -0
- package/dist/runtime/src/storage/remote-session.ts +1028 -0
- package/dist/runtime/src/storage/runtime-events.ts +209 -0
- package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
- package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
- package/dist/runtime/src/storage/runtime-leases.ts +190 -0
- package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
- package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
- package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
- package/dist/runtime/src/storage/self-schedules.ts +306 -0
- package/dist/runtime/src/storage/session-asks.ts +468 -0
- package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
- package/dist/runtime/src/storage/session-inbox.ts +161 -0
- package/dist/runtime/src/storage/sqlite.ts +154 -0
- package/dist/runtime/src/storage/storage-contract.ts +54 -0
- package/dist/runtime/src/storage/storage-host.ts +336 -0
- package/dist/runtime/src/storage/storage-public-host.ts +16 -0
- package/dist/runtime/src/storage/storage-public.ts +66 -0
- package/dist/runtime/src/storage/tasks.ts +172 -0
- package/dist/runtime/src/storage/token-stats.ts +432 -0
- package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
- package/dist/runtime/src/storage/topic-archive.ts +169 -0
- package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
- package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
- package/dist/runtime/src/storage/topic-settings.ts +67 -0
- package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
- package/dist/runtime/src/storage/topic-transcript.ts +98 -0
- package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
- package/dist/runtime/src/storage/vault-crypto.ts +31 -0
- package/dist/runtime/src/storage/vault-public.ts +27 -0
- package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
- package/dist/runtime/src/storage/vault.ts +388 -0
- package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
- package/dist/runtime/src/storage/wiki.ts +90 -0
- package/dist/runtime/src/topics/claim-abort.ts +190 -0
- package/dist/runtime/src/topics/create.ts +192 -0
- package/dist/runtime/src/topics/derive.ts +600 -0
- package/dist/runtime/src/topics/lifecycle.ts +425 -0
- package/dist/runtime/src/topics/links.ts +7 -0
- package/dist/runtime/src/topics/personal-general.ts +91 -0
- package/dist/runtime/src/topics/session.ts +1041 -0
- package/dist/runtime/src/topics/update.ts +287 -0
- package/dist/runtime/src/types/api.ts +591 -0
- package/dist/runtime/src/types.ts +418 -0
- package/dist/runtime/src/version.ts +1 -0
- package/dist/runtime/tsconfig.json +13 -0
- package/dist/runtime-gateway.js +514 -0
- package/dist/runtime-gateway.js.map +10 -0
- package/dist/runtime-helpers.js +1792 -0
- package/dist/runtime-helpers.js.map +40 -0
- package/dist/sqlite.js +66 -0
- package/dist/sqlite.js.map +10 -0
- package/dist/storage.js +5223 -0
- package/dist/storage.js.map +47 -0
- package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
- package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
- package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
- package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
- package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
- package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
- package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
- package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
- package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
- package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
- package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
- package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
- package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
- package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
- package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
- package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
- package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
- package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
- package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
- package/dist/types/packages/core/src/agents/index.d.ts +8 -0
- package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
- package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
- package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
- package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
- package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
- package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
- package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
- package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
- package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
- package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
- package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
- package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
- package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
- package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
- package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
- package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
- package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
- package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
- package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
- package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
- package/dist/types/packages/core/src/bus.d.ts +141 -0
- package/dist/types/packages/core/src/identifiers.d.ts +27 -0
- package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
- package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
- package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
- package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
- package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
- package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
- package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
- package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
- package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
- package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
- package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
- package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
- package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
- package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
- package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
- package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
- package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
- package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
- package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
- package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
- package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
- package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
- package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
- package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
- package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
- package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
- package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
- package/dist/types/packages/core/src/platform/config.d.ts +178 -0
- package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
- package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
- package/dist/types/packages/core/src/platform/error.d.ts +6 -0
- package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
- package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
- package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
- package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
- package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
- package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
- package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
- package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
- package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
- package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
- package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
- package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
- package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
- package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
- package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
- package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
- package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
- package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
- package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
- package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
- package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
- package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
- package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
- package/dist/types/packages/core/src/query/state.d.ts +25 -0
- package/dist/types/packages/core/src/query/types.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
- package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
- package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
- package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
- package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
- package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
- package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
- package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
- package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
- package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
- package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
- package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
- package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
- package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
- package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
- package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
- package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
- package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
- package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
- package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
- package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
- package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
- package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
- package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
- package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
- package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
- package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
- package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
- package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
- package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
- package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
- package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
- package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
- package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
- package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
- package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
- package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
- package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
- package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
- package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
- package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
- package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
- package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
- package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
- package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
- package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
- package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
- package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
- package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
- package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
- package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
- package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
- package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
- package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
- package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
- package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
- package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
- package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
- package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
- package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
- package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
- package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
- package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
- package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
- package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
- package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
- package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
- package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
- package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
- package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
- package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
- package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
- package/dist/types/packages/core/src/topics/links.d.ts +2 -0
- package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
- package/dist/types/packages/core/src/topics/session.d.ts +70 -0
- package/dist/types/packages/core/src/types/api.d.ts +551 -0
- package/dist/types/packages/core/src/types.d.ts +405 -0
- package/dist/types/packages/core/src/version.d.ts +1 -0
- package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
- package/dist/types/packages/module-cron/src/context.d.ts +15 -0
- package/dist/types/packages/module-cron/src/host.d.ts +23 -0
- package/dist/types/packages/module-cron/src/index.d.ts +14 -0
- package/dist/types/packages/module-cron/src/module.d.ts +13 -0
- package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
- package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
- package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
- package/dist/types/packages/module-cron/src/store.d.ts +152 -0
- package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
- package/dist/vault.js +848 -0
- package/dist/vault.js.map +18 -0
- package/install-bash-rs.mjs +90 -0
- package/install-browser-rs.mjs +83 -0
- package/package.json +171 -4
|
@@ -0,0 +1,1647 @@
|
|
|
1
|
+
// Persistent topic store backed by shared SQLite.
|
|
2
|
+
|
|
3
|
+
import { resolveFallbackAgent } from "#platform/config-helpers";
|
|
4
|
+
import { GENERAL_TOPIC_ID } from "#platform/constants";
|
|
5
|
+
import { logger } from "#platform/logger";
|
|
6
|
+
import { db } from "#storage/forum-db";
|
|
7
|
+
import { onRuntimeTopicMaintenanceReleased } from "#storage/runtime-topic-state";
|
|
8
|
+
import { registerStorageSchemaInitializer } from "#storage/storage-host";
|
|
9
|
+
// Also registers the claim/tombstone schema and the api_topics tombstone and
|
|
10
|
+
// scope-immutability triggers wherever topics can be written (topic-link PR7).
|
|
11
|
+
import { repairUnscopedOtiumTopicScopes } from "#storage/topic-link-records";
|
|
12
|
+
import type { AgentKind, EffortLevel } from "#types";
|
|
13
|
+
import type {
|
|
14
|
+
AiMode,
|
|
15
|
+
ParticipantDto,
|
|
16
|
+
SubagentReportMode,
|
|
17
|
+
TopicDto,
|
|
18
|
+
TopicKind,
|
|
19
|
+
TopicSurface,
|
|
20
|
+
TopicVisibility,
|
|
21
|
+
} from "#types/api";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Surface used when a caller does not name one — and the value every existing
|
|
25
|
+
* row is backfilled with on first boot after the surface migration.
|
|
26
|
+
*
|
|
27
|
+
* Hosts that only ever serve one surface declare it once in their environment
|
|
28
|
+
* (`NEGOTIUM_DEFAULT_SURFACE=otium` on the Otium hub and worker); a developer
|
|
29
|
+
* Mac leaves it unset and gets `terminal`, with the telegram adapter
|
|
30
|
+
* reclassifying its own mapped rooms afterwards.
|
|
31
|
+
*/
|
|
32
|
+
export function defaultTopicSurface(): TopicSurface {
|
|
33
|
+
return normalizeTopicSurface(process.env.NEGOTIUM_DEFAULT_SURFACE);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function normalizeTopicSurface(value: unknown): TopicSurface {
|
|
37
|
+
return value === "telegram" || value === "otium" || value === "terminal" ? value : "terminal";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The surface instance new rooms are filed under when the caller names none.
|
|
42
|
+
*
|
|
43
|
+
* `surface` alone is not enough once a node may be attached to several Otium
|
|
44
|
+
* workspaces (M-2): two workspaces are two independent namespaces on the same
|
|
45
|
+
* surface. The adapter that owns the attachment installs the active scope at
|
|
46
|
+
* mount time; `terminal` and `telegram` are singletons and stay null.
|
|
47
|
+
*
|
|
48
|
+
* Kept as process state rather than an argument threaded through every creation
|
|
49
|
+
* path because the value is a property of *this process's attachment*, not of
|
|
50
|
+
* any individual call — the same reason `defaultTopicSurface()` exists.
|
|
51
|
+
*/
|
|
52
|
+
let activeSurfaceScope: string | null = null;
|
|
53
|
+
|
|
54
|
+
export function normalizeSurfaceScope(value: unknown): string | null {
|
|
55
|
+
if (typeof value !== "string") return null;
|
|
56
|
+
const trimmed = value.trim();
|
|
57
|
+
return trimmed ? trimmed : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function defaultSurfaceScope(): string | null {
|
|
61
|
+
return activeSurfaceScope ?? normalizeSurfaceScope(process.env.NEGOTIUM_SURFACE_SCOPE);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Install (or clear) the scope new rooms inherit. Returns the previous value. */
|
|
65
|
+
export function setDefaultSurfaceScope(scope: string | null): string | null {
|
|
66
|
+
const previous = activeSurfaceScope;
|
|
67
|
+
activeSurfaceScope = normalizeSurfaceScope(scope);
|
|
68
|
+
return previous;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Whether an Otium room must name a workspace to be created at all (M-3).
|
|
73
|
+
*
|
|
74
|
+
* Off by default, and off for every single-workspace host: an unscoped room is
|
|
75
|
+
* then legacy, reachable, and perfectly usable. The adapter turns it on only
|
|
76
|
+
* while several workspaces are attached, because there an unscoped room is
|
|
77
|
+
* reachable from none of them (M-10) — a room nobody can see is worse than a
|
|
78
|
+
* refusal that says so.
|
|
79
|
+
*/
|
|
80
|
+
let surfaceScopeRequired = false;
|
|
81
|
+
|
|
82
|
+
export function setSurfaceScopeRequired(required: boolean): void {
|
|
83
|
+
surfaceScopeRequired = required;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function isSurfaceScopeRequired(): boolean {
|
|
87
|
+
return surfaceScopeRequired;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* How many Otium workspaces the adapter currently has mounted, or null when no
|
|
92
|
+
* adapter ever reported (a node without the Otium adapter). Lets a loopback
|
|
93
|
+
* caller tell "one workspace, scope not resolved yet" apart from "no
|
|
94
|
+
* workspace at all" (topic-link design v2 §4.6, `GET /surface-scope`).
|
|
95
|
+
*/
|
|
96
|
+
let mountedSurfaceScopeCount: number | null = null;
|
|
97
|
+
|
|
98
|
+
export function setMountedSurfaceScopeCount(count: number | null): void {
|
|
99
|
+
mountedSurfaceScopeCount = count === null ? null : Math.max(0, Math.floor(count));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface LocalSurfaceScopeStatus {
|
|
103
|
+
/** The workspace an unscoped (loopback) caller's otium rooms are filed under. */
|
|
104
|
+
surfaceScope: string | null;
|
|
105
|
+
/** False while the scope cannot be stated (several workspaces, or one not resolved yet). */
|
|
106
|
+
resolved: boolean;
|
|
107
|
+
/** True while several workspaces are mounted: a room must name one. */
|
|
108
|
+
scopeRequired: boolean;
|
|
109
|
+
/** Mounted Otium workspaces; 0 when no adapter reported. */
|
|
110
|
+
joinsMounted: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The scope a loopback (no scope header) gateway caller gets. */
|
|
114
|
+
export function localSurfaceScopeStatus(): LocalSurfaceScopeStatus {
|
|
115
|
+
const joinsMounted = mountedSurfaceScopeCount ?? 0;
|
|
116
|
+
if (surfaceScopeRequired) {
|
|
117
|
+
return { surfaceScope: null, resolved: false, scopeRequired: true, joinsMounted };
|
|
118
|
+
}
|
|
119
|
+
const surfaceScope = defaultSurfaceScope();
|
|
120
|
+
return {
|
|
121
|
+
surfaceScope,
|
|
122
|
+
resolved: joinsMounted === 1 ? surfaceScope !== null : true,
|
|
123
|
+
scopeRequired: false,
|
|
124
|
+
joinsMounted,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function tableColumns(table: string): Set<string> {
|
|
129
|
+
const rows = db.query(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
|
|
130
|
+
return new Set(rows.map((row) => row.name));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Persist the authoritative agent and, when supplied, its normalized base defaults. */
|
|
134
|
+
export function setApiTopicAgent(
|
|
135
|
+
topicId: string,
|
|
136
|
+
agent: AgentKind,
|
|
137
|
+
defaults?: { model: string; effort?: EffortLevel },
|
|
138
|
+
): void {
|
|
139
|
+
if (!defaults) {
|
|
140
|
+
db.query("UPDATE api_topics SET agent = ? WHERE id = ?").run(agent, topicId);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
db.query("UPDATE api_topics SET agent = ?, base_model = ?, base_effort = ? WHERE id = ?").run(
|
|
144
|
+
agent,
|
|
145
|
+
defaults.model,
|
|
146
|
+
defaults.effort ?? null,
|
|
147
|
+
topicId,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function initializeApiTopicsSchema(): void {
|
|
152
|
+
db.exec(`
|
|
153
|
+
CREATE TABLE IF NOT EXISTS api_topics (
|
|
154
|
+
id TEXT PRIMARY KEY,
|
|
155
|
+
title TEXT NOT NULL,
|
|
156
|
+
kind TEXT NOT NULL DEFAULT 'channel',
|
|
157
|
+
description TEXT,
|
|
158
|
+
agent TEXT,
|
|
159
|
+
default_model TEXT,
|
|
160
|
+
default_effort TEXT,
|
|
161
|
+
participants TEXT,
|
|
162
|
+
created_at TEXT NOT NULL,
|
|
163
|
+
last_message_at TEXT,
|
|
164
|
+
is_archived INTEGER NOT NULL DEFAULT 0,
|
|
165
|
+
ai_mention INTEGER NOT NULL DEFAULT 0,
|
|
166
|
+
ai_mode TEXT
|
|
167
|
+
)
|
|
168
|
+
`);
|
|
169
|
+
|
|
170
|
+
const initialTopicColumns = tableColumns("api_topics");
|
|
171
|
+
const legacyTopicSchema = !initialTopicColumns.has("response_policy");
|
|
172
|
+
const needsCanonicalTopicRebuild = legacyTopicSchema || !initialTopicColumns.has("agent");
|
|
173
|
+
if (legacyTopicSchema) {
|
|
174
|
+
// Rename the legacy column once; new databases are created with `agent`.
|
|
175
|
+
try {
|
|
176
|
+
db.exec("ALTER TABLE api_topics RENAME COLUMN default_agent TO agent");
|
|
177
|
+
} catch {
|
|
178
|
+
// Already migrated or freshly created.
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Migrate existing DBs that predate the ai_mention column (team-mode topics).
|
|
182
|
+
try {
|
|
183
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN ai_mention INTEGER NOT NULL DEFAULT 0");
|
|
184
|
+
} catch {
|
|
185
|
+
// Column already exists — nothing to do.
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Migrate for spawn/fork tracking (R1).
|
|
189
|
+
try {
|
|
190
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN parent_topic_id TEXT");
|
|
191
|
+
} catch {}
|
|
192
|
+
try {
|
|
193
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN is_fork INTEGER NOT NULL DEFAULT 0");
|
|
194
|
+
} catch {}
|
|
195
|
+
|
|
196
|
+
// Migrate for agent-spawned subagent worker rooms.
|
|
197
|
+
try {
|
|
198
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN is_subagent INTEGER NOT NULL DEFAULT 0");
|
|
199
|
+
} catch {}
|
|
200
|
+
|
|
201
|
+
// Migrate for session persistence.
|
|
202
|
+
try {
|
|
203
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN session_id TEXT");
|
|
204
|
+
} catch {}
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN kind TEXT NOT NULL DEFAULT 'channel'");
|
|
208
|
+
} catch {}
|
|
209
|
+
|
|
210
|
+
try {
|
|
211
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN ai_mode TEXT");
|
|
212
|
+
} catch {}
|
|
213
|
+
|
|
214
|
+
db.exec(`
|
|
215
|
+
CREATE TABLE IF NOT EXISTS api_schema_migrations (
|
|
216
|
+
key TEXT PRIMARY KEY,
|
|
217
|
+
applied_at TEXT NOT NULL
|
|
218
|
+
)
|
|
219
|
+
`);
|
|
220
|
+
|
|
221
|
+
const ALWAYS_RESPOND_MIGRATION = "api_topics_ai_invited_default_always_respond_20260623";
|
|
222
|
+
const alwaysRespondMigration = db
|
|
223
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
224
|
+
.get(ALWAYS_RESPOND_MIGRATION);
|
|
225
|
+
if (!alwaysRespondMigration) {
|
|
226
|
+
db.transaction(() => {
|
|
227
|
+
db.query("UPDATE api_topics SET ai_mention = 0 WHERE agent IS NOT NULL").run();
|
|
228
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
229
|
+
ALWAYS_RESPOND_MIGRATION,
|
|
230
|
+
new Date().toISOString(),
|
|
231
|
+
);
|
|
232
|
+
})();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const GENERAL_AGENT_KIND_MIGRATION = "api_topics_general_agent_kind_20260704";
|
|
236
|
+
const generalAgentKindMigration = db
|
|
237
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
238
|
+
.get(GENERAL_AGENT_KIND_MIGRATION);
|
|
239
|
+
if (!generalAgentKindMigration) {
|
|
240
|
+
db.transaction(() => {
|
|
241
|
+
db.query("UPDATE api_topics SET kind = 'agent', ai_mention = 0 WHERE id = ?").run(
|
|
242
|
+
GENERAL_TOPIC_ID,
|
|
243
|
+
);
|
|
244
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
245
|
+
GENERAL_AGENT_KIND_MIGRATION,
|
|
246
|
+
new Date().toISOString(),
|
|
247
|
+
);
|
|
248
|
+
})();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const AI_MODE_MIGRATION = "api_topics_ai_mode_20260704";
|
|
252
|
+
const aiModeMigration = db
|
|
253
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
254
|
+
.get(AI_MODE_MIGRATION);
|
|
255
|
+
if (!aiModeMigration) {
|
|
256
|
+
db.transaction(() => {
|
|
257
|
+
db.query(
|
|
258
|
+
`UPDATE api_topics
|
|
259
|
+
SET
|
|
260
|
+
kind = CASE
|
|
261
|
+
WHEN id = ? THEN 'agent'
|
|
262
|
+
WHEN kind = 'channel' AND agent IS NOT NULL AND ai_mention = 0 THEN 'agent'
|
|
263
|
+
ELSE kind
|
|
264
|
+
END,
|
|
265
|
+
ai_mode = CASE
|
|
266
|
+
WHEN id = ? THEN 'always'
|
|
267
|
+
WHEN agent IS NULL THEN 'off'
|
|
268
|
+
WHEN kind = 'agent' THEN 'always'
|
|
269
|
+
WHEN kind = 'channel' AND ai_mention != 0 THEN 'mention'
|
|
270
|
+
WHEN kind = 'channel' AND ai_mention = 0 THEN 'always'
|
|
271
|
+
WHEN ai_mention != 0 THEN 'mention'
|
|
272
|
+
ELSE 'always'
|
|
273
|
+
END`,
|
|
274
|
+
).run(GENERAL_TOPIC_ID, GENERAL_TOPIC_ID);
|
|
275
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
276
|
+
AI_MODE_MIGRATION,
|
|
277
|
+
new Date().toISOString(),
|
|
278
|
+
);
|
|
279
|
+
})();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const GENERAL_MANAGER_KIND_MIGRATION = "api_topics_general_manager_kind_20260704";
|
|
283
|
+
const generalManagerKindMigration = db
|
|
284
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
285
|
+
.get(GENERAL_MANAGER_KIND_MIGRATION);
|
|
286
|
+
if (!generalManagerKindMigration) {
|
|
287
|
+
db.transaction(() => {
|
|
288
|
+
db.query(
|
|
289
|
+
"UPDATE api_topics SET kind = 'manager', ai_mention = 0, ai_mode = 'always' WHERE id = ?",
|
|
290
|
+
).run(GENERAL_TOPIC_ID);
|
|
291
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
292
|
+
GENERAL_MANAGER_KIND_MIGRATION,
|
|
293
|
+
new Date().toISOString(),
|
|
294
|
+
);
|
|
295
|
+
})();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function createCanonicalTopicsTable(name: string): void {
|
|
300
|
+
db.exec(`
|
|
301
|
+
CREATE TABLE IF NOT EXISTS ${name} (
|
|
302
|
+
id TEXT PRIMARY KEY,
|
|
303
|
+
title TEXT NOT NULL,
|
|
304
|
+
kind TEXT NOT NULL CHECK (kind IN ('channel','agent','manager')),
|
|
305
|
+
description TEXT,
|
|
306
|
+
agent TEXT CHECK (agent IS NULL OR agent IN ('maestro','claude','codex')),
|
|
307
|
+
base_model TEXT,
|
|
308
|
+
base_effort TEXT CHECK (base_effort IS NULL OR base_effort IN ('low','medium','high','xhigh','max')),
|
|
309
|
+
response_policy TEXT NOT NULL CHECK (response_policy IN ('off','mention','always')),
|
|
310
|
+
created_at TEXT NOT NULL,
|
|
311
|
+
last_message_at TEXT,
|
|
312
|
+
parent_topic_id TEXT,
|
|
313
|
+
memory_topic_id TEXT,
|
|
314
|
+
memory_key TEXT,
|
|
315
|
+
is_fork INTEGER NOT NULL DEFAULT 0 CHECK (is_fork IN (0,1)),
|
|
316
|
+
is_subagent INTEGER NOT NULL DEFAULT 0 CHECK (is_subagent IN (0,1)),
|
|
317
|
+
visibility TEXT NOT NULL DEFAULT 'visible' CHECK (visibility IN ('visible','hidden')),
|
|
318
|
+
surface TEXT NOT NULL DEFAULT 'terminal' CHECK (surface IN ('terminal','telegram','otium')),
|
|
319
|
+
surface_scope TEXT,
|
|
320
|
+
browser_profile TEXT NOT NULL DEFAULT 'default',
|
|
321
|
+
browser_profile_owner TEXT,
|
|
322
|
+
browser_connect_port INTEGER,
|
|
323
|
+
session_id TEXT,
|
|
324
|
+
CHECK (
|
|
325
|
+
(kind = 'channel' AND response_policy = 'off' AND agent IS NULL) OR
|
|
326
|
+
(kind = 'channel' AND response_policy = 'mention' AND agent IS NOT NULL) OR
|
|
327
|
+
(kind IN ('agent','manager') AND response_policy = 'always' AND agent IS NOT NULL)
|
|
328
|
+
)
|
|
329
|
+
)
|
|
330
|
+
`);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function createTopicMembersTable(): void {
|
|
334
|
+
db.exec(`
|
|
335
|
+
CREATE TABLE IF NOT EXISTS topic_members (
|
|
336
|
+
topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,
|
|
337
|
+
user_id TEXT NOT NULL,
|
|
338
|
+
role TEXT NOT NULL CHECK (role IN ('owner','member')),
|
|
339
|
+
PRIMARY KEY (topic_id, user_id)
|
|
340
|
+
)
|
|
341
|
+
`);
|
|
342
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_topic_members_user ON topic_members(user_id)");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (needsCanonicalTopicRebuild) {
|
|
346
|
+
const legacyRows = db.query("SELECT * FROM api_topics").all() as Array<Record<string, unknown>>;
|
|
347
|
+
const existingMemberRows = tableColumns("topic_members").has("topic_id")
|
|
348
|
+
? (db.query("SELECT topic_id, user_id, role FROM topic_members").all() as Array<{
|
|
349
|
+
topic_id: string;
|
|
350
|
+
user_id: string;
|
|
351
|
+
role: string;
|
|
352
|
+
}>)
|
|
353
|
+
: [];
|
|
354
|
+
const configColumns = tableColumns("api_topic_config");
|
|
355
|
+
const legacyAgentOverrides = configColumns.has("agent")
|
|
356
|
+
? new Map(
|
|
357
|
+
(
|
|
358
|
+
db
|
|
359
|
+
.query("SELECT topic_id, agent FROM api_topic_config WHERE agent IS NOT NULL")
|
|
360
|
+
.all() as Array<{ topic_id: string; agent: AgentKind }>
|
|
361
|
+
).map((row) => [row.topic_id, row.agent]),
|
|
362
|
+
)
|
|
363
|
+
: new Map<string, AgentKind>();
|
|
364
|
+
const previousForeignKeys = db
|
|
365
|
+
.query<{ foreign_keys: number }, []>("PRAGMA foreign_keys")
|
|
366
|
+
.get()?.foreign_keys;
|
|
367
|
+
db.exec("PRAGMA foreign_keys = OFF");
|
|
368
|
+
try {
|
|
369
|
+
db.transaction(() => {
|
|
370
|
+
createCanonicalTopicsTable("api_topics_next");
|
|
371
|
+
for (const row of legacyRows) {
|
|
372
|
+
const selectedAgent = (legacyAgentOverrides.get(String(row.id)) ??
|
|
373
|
+
row.agent ??
|
|
374
|
+
row.runtime_agent ??
|
|
375
|
+
row.default_agent ??
|
|
376
|
+
undefined) as AgentKind | undefined;
|
|
377
|
+
const normalized = normalizeTopicState({
|
|
378
|
+
id: String(row.id),
|
|
379
|
+
kind: normalizeTopicKind(row.kind),
|
|
380
|
+
agent: selectedAgent,
|
|
381
|
+
aiMode: normalizeAiMode(row.response_policy ?? row.ai_mode),
|
|
382
|
+
aiMention: Number(row.ai_mention ?? 0) !== 0,
|
|
383
|
+
});
|
|
384
|
+
const legacyBaseModel = row.base_model ?? row.default_model;
|
|
385
|
+
const legacyBaseEffort = row.base_effort ?? row.default_effort;
|
|
386
|
+
db.query(
|
|
387
|
+
`INSERT INTO api_topics_next
|
|
388
|
+
(id,title,kind,description,agent,base_model,base_effort,response_policy,
|
|
389
|
+
created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,surface_scope,session_id)
|
|
390
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|
391
|
+
).run(
|
|
392
|
+
String(row.id),
|
|
393
|
+
String(row.title),
|
|
394
|
+
normalized.kind,
|
|
395
|
+
typeof row.description === "string" ? row.description : null,
|
|
396
|
+
normalized.agent ?? null,
|
|
397
|
+
typeof legacyBaseModel === "string" ? legacyBaseModel : null,
|
|
398
|
+
typeof legacyBaseEffort === "string" ? legacyBaseEffort : null,
|
|
399
|
+
normalized.aiMode,
|
|
400
|
+
String(row.created_at),
|
|
401
|
+
typeof row.last_message_at === "string" ? row.last_message_at : null,
|
|
402
|
+
typeof row.parent_topic_id === "string" ? row.parent_topic_id : null,
|
|
403
|
+
typeof row.memory_topic_id === "string" ? row.memory_topic_id : null,
|
|
404
|
+
typeof row.memory_key === "string" ? row.memory_key : null,
|
|
405
|
+
Number(row.is_fork ?? 0) !== 0 ? 1 : 0,
|
|
406
|
+
Number(row.is_subagent ?? 0) !== 0 ? 1 : 0,
|
|
407
|
+
row.visibility === "hidden" ? "hidden" : "visible",
|
|
408
|
+
row.surface === undefined ? defaultTopicSurface() : normalizeTopicSurface(row.surface),
|
|
409
|
+
normalizeSurfaceScope(row.surface_scope),
|
|
410
|
+
typeof row.session_id === "string" ? row.session_id : null,
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
db.exec("DROP TABLE IF EXISTS topic_members");
|
|
414
|
+
db.exec("DROP TABLE api_topics");
|
|
415
|
+
db.exec("ALTER TABLE api_topics_next RENAME TO api_topics");
|
|
416
|
+
createTopicMembersTable();
|
|
417
|
+
if (existingMemberRows.length > 0) {
|
|
418
|
+
for (const member of existingMemberRows) {
|
|
419
|
+
db.query(
|
|
420
|
+
"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)",
|
|
421
|
+
).run(member.topic_id, member.user_id, member.role === "owner" ? "owner" : "member");
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
for (const row of legacyRows) {
|
|
425
|
+
let participants: ParticipantDto[] = [];
|
|
426
|
+
try {
|
|
427
|
+
const parsed = JSON.parse(String(row.participants ?? "[]"));
|
|
428
|
+
if (Array.isArray(parsed)) participants = parsed as ParticipantDto[];
|
|
429
|
+
} catch {
|
|
430
|
+
participants = [];
|
|
431
|
+
}
|
|
432
|
+
for (const participant of participants) {
|
|
433
|
+
if (!participant?.userId) continue;
|
|
434
|
+
db.query(
|
|
435
|
+
"INSERT OR REPLACE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)",
|
|
436
|
+
).run(
|
|
437
|
+
String(row.id),
|
|
438
|
+
participant.userId,
|
|
439
|
+
participant.role === "owner" ? "owner" : "member",
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
})();
|
|
445
|
+
} finally {
|
|
446
|
+
db.exec(`PRAGMA foreign_keys = ${previousForeignKeys ? "ON" : "OFF"}`);
|
|
447
|
+
}
|
|
448
|
+
} else {
|
|
449
|
+
createCanonicalTopicsTable("api_topics");
|
|
450
|
+
createTopicMembersTable();
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
db.exec(`
|
|
454
|
+
CREATE TABLE IF NOT EXISTS subagent_tell_grants (
|
|
455
|
+
subagent_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,
|
|
456
|
+
target_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,
|
|
457
|
+
granted_by_topic_id TEXT NOT NULL REFERENCES api_topics(id) ON DELETE CASCADE,
|
|
458
|
+
created_at TEXT NOT NULL,
|
|
459
|
+
PRIMARY KEY (subagent_topic_id, target_topic_id)
|
|
460
|
+
)
|
|
461
|
+
`);
|
|
462
|
+
db.exec(`
|
|
463
|
+
DELETE FROM subagent_tell_grants
|
|
464
|
+
WHERE subagent_topic_id NOT IN (SELECT id FROM api_topics)
|
|
465
|
+
OR target_topic_id NOT IN (SELECT id FROM api_topics)
|
|
466
|
+
OR granted_by_topic_id NOT IN (SELECT id FROM api_topics)
|
|
467
|
+
`);
|
|
468
|
+
db.exec("DELETE FROM topic_members WHERE topic_id NOT IN (SELECT id FROM api_topics)");
|
|
469
|
+
|
|
470
|
+
// Canonical databases created before explicit adapter visibility need a
|
|
471
|
+
// lightweight additive migration; fresh/rebuilt databases already have it.
|
|
472
|
+
if (!tableColumns("api_topics").has("visibility")) {
|
|
473
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN visibility TEXT NOT NULL DEFAULT 'visible'");
|
|
474
|
+
}
|
|
475
|
+
if (!tableColumns("api_topics").has("surface")) {
|
|
476
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN surface TEXT NOT NULL DEFAULT 'terminal'");
|
|
477
|
+
}
|
|
478
|
+
if (!tableColumns("api_topics").has("surface_scope")) {
|
|
479
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN surface_scope TEXT");
|
|
480
|
+
}
|
|
481
|
+
// `access_mode` was replaced by `surface`: a topic is reachable from Otium
|
|
482
|
+
// because it lives there, not because a flag was flipped (S-4). Dropping the
|
|
483
|
+
// column removes the second, now-contradictory source of truth.
|
|
484
|
+
if (tableColumns("api_topics").has("access_mode")) {
|
|
485
|
+
try {
|
|
486
|
+
db.exec("ALTER TABLE api_topics DROP COLUMN access_mode");
|
|
487
|
+
} catch (err) {
|
|
488
|
+
logger.warn({ err }, "api_topics: could not drop the retired access_mode column");
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (!tableColumns("api_topics").has("browser_profile")) {
|
|
492
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN browser_profile TEXT NOT NULL DEFAULT 'default'");
|
|
493
|
+
}
|
|
494
|
+
if (!tableColumns("api_topics").has("browser_profile_owner")) {
|
|
495
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN browser_profile_owner TEXT");
|
|
496
|
+
}
|
|
497
|
+
if (!tableColumns("api_topics").has("browser_connect_port")) {
|
|
498
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN browser_connect_port INTEGER");
|
|
499
|
+
}
|
|
500
|
+
if (!tableColumns("api_topics").has("subagent_report_mode")) {
|
|
501
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN subagent_report_mode TEXT NOT NULL DEFAULT 'auto'");
|
|
502
|
+
}
|
|
503
|
+
if (!tableColumns("api_topics").has("derived_by_user_id")) {
|
|
504
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN derived_by_user_id TEXT");
|
|
505
|
+
}
|
|
506
|
+
if (!tableColumns("api_topics").has("memory_topic_id")) {
|
|
507
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN memory_topic_id TEXT");
|
|
508
|
+
}
|
|
509
|
+
if (!tableColumns("api_topics").has("memory_key")) {
|
|
510
|
+
db.exec("ALTER TABLE api_topics ADD COLUMN memory_key TEXT");
|
|
511
|
+
}
|
|
512
|
+
db.exec(`
|
|
513
|
+
UPDATE api_topics
|
|
514
|
+
SET browser_profile_owner = (
|
|
515
|
+
SELECT m.user_id FROM topic_members m
|
|
516
|
+
WHERE m.topic_id = api_topics.id AND m.role = 'owner'
|
|
517
|
+
ORDER BY m.rowid
|
|
518
|
+
LIMIT 1
|
|
519
|
+
)
|
|
520
|
+
WHERE browser_profile_owner IS NULL
|
|
521
|
+
`);
|
|
522
|
+
backfillTopicSurfaces();
|
|
523
|
+
ensureSurfaceScopeStampTables();
|
|
524
|
+
db.exec(
|
|
525
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topics_last_message ON api_topics(last_message_at DESC)",
|
|
526
|
+
);
|
|
527
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_api_topics_surface ON api_topics(surface)");
|
|
528
|
+
db.exec(
|
|
529
|
+
"CREATE INDEX IF NOT EXISTS idx_api_topics_surface_scope ON api_topics(surface, surface_scope)",
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const SURFACE_SCOPE_STAMP_MIGRATION = "api_topics_surface_scope_stamp_20260809";
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Minimum spacing between two unforced retries of an incomplete M-9 stamp.
|
|
537
|
+
* The retry is driven by timers / scope refreshes, never by request traffic,
|
|
538
|
+
* and this bound keeps even a tight caller from turning it into a hot path.
|
|
539
|
+
*/
|
|
540
|
+
export const SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS = 30_000;
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Refusals that leave a room pending: the room is still an unscoped otium room
|
|
544
|
+
* and the stamp may succeed later (maintenance ends, an operator renames the
|
|
545
|
+
* conflicting room or resolves a duplicate manager room, the row settles).
|
|
546
|
+
* Every other refusal (`not_found`, `not_otium`, `scope_not_null`) means there
|
|
547
|
+
* is nothing left to stamp.
|
|
548
|
+
*/
|
|
549
|
+
const SURFACE_SCOPE_STAMP_RETRYABLE = new Set([
|
|
550
|
+
"maintenance_in_progress",
|
|
551
|
+
"title_conflict",
|
|
552
|
+
"duplicate_manager",
|
|
553
|
+
"row_changed",
|
|
554
|
+
"invalid_scope",
|
|
555
|
+
]);
|
|
556
|
+
|
|
557
|
+
function ensureSurfaceScopeStampTables(): void {
|
|
558
|
+
db.exec(`
|
|
559
|
+
CREATE TABLE IF NOT EXISTS api_schema_migrations (
|
|
560
|
+
key TEXT PRIMARY KEY,
|
|
561
|
+
applied_at TEXT NOT NULL
|
|
562
|
+
)
|
|
563
|
+
`);
|
|
564
|
+
// Rooms the M-9 stamp could not file yet (revision 5). `scope` is pinned at
|
|
565
|
+
// the first attempt: a retry never re-reads the current workspace, so a
|
|
566
|
+
// second workspace joined later cannot swallow the first one's rooms.
|
|
567
|
+
db.exec(`
|
|
568
|
+
CREATE TABLE IF NOT EXISTS api_surface_scope_stamp_pending (
|
|
569
|
+
topic_id TEXT PRIMARY KEY,
|
|
570
|
+
scope TEXT NOT NULL,
|
|
571
|
+
reason TEXT NOT NULL,
|
|
572
|
+
detail TEXT,
|
|
573
|
+
attempts INTEGER NOT NULL DEFAULT 1,
|
|
574
|
+
first_seen_at TEXT NOT NULL,
|
|
575
|
+
last_attempt_at TEXT NOT NULL
|
|
576
|
+
)
|
|
577
|
+
`);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
export interface SurfaceScopeStampStatus {
|
|
581
|
+
/** The completion marker is written: every pre-existing room was filed. */
|
|
582
|
+
complete: boolean;
|
|
583
|
+
/** Rooms the stamp skipped and will retry (maintenance, title conflict ...). */
|
|
584
|
+
pending: number;
|
|
585
|
+
/** Workspace the pending rooms will be filed under (pinned at first attempt). */
|
|
586
|
+
scope: string | null;
|
|
587
|
+
pendingTopics: Array<{
|
|
588
|
+
topicId: string;
|
|
589
|
+
reason: string;
|
|
590
|
+
detail: string | null;
|
|
591
|
+
attempts: number;
|
|
592
|
+
}>;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Operator view of the M-9 stamp (diagnostics; `unscopedPending` on
|
|
597
|
+
* `GET /surface-scope`). Read-only: the tables exist from schema init.
|
|
598
|
+
*/
|
|
599
|
+
export function surfaceScopeStampStatus(): SurfaceScopeStampStatus {
|
|
600
|
+
const complete = Boolean(
|
|
601
|
+
db
|
|
602
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
603
|
+
.get(SURFACE_SCOPE_STAMP_MIGRATION),
|
|
604
|
+
);
|
|
605
|
+
const rows = db
|
|
606
|
+
.query<
|
|
607
|
+
{ topic_id: string; scope: string; reason: string; detail: string | null; attempts: number },
|
|
608
|
+
[]
|
|
609
|
+
>(
|
|
610
|
+
"SELECT topic_id, scope, reason, detail, attempts FROM api_surface_scope_stamp_pending ORDER BY topic_id",
|
|
611
|
+
)
|
|
612
|
+
.all();
|
|
613
|
+
return {
|
|
614
|
+
complete,
|
|
615
|
+
pending: rows.length,
|
|
616
|
+
scope: rows[0]?.scope ?? null,
|
|
617
|
+
pendingTopics: rows.map((row) => ({
|
|
618
|
+
topicId: row.topic_id,
|
|
619
|
+
reason: row.reason,
|
|
620
|
+
detail: row.detail,
|
|
621
|
+
attempts: Number(row.attempts),
|
|
622
|
+
})),
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* M-9 — file every pre-existing Otium room under the workspace attached now.
|
|
628
|
+
*
|
|
629
|
+
* Deliberately *not* a schema-init step. The scope is only knowable after the
|
|
630
|
+
* first successful Central contact (M-3), which happens long after the store
|
|
631
|
+
* opens; a boot-time migration would see no scope, record itself as applied and
|
|
632
|
+
* leave every room unstamped forever. The Otium runtime calls this instead, once,
|
|
633
|
+
* as soon as it has resolved its workspace.
|
|
634
|
+
*
|
|
635
|
+
* Completes at most once per store: rooms created after this point are stamped
|
|
636
|
+
* at creation, and a second workspace joined later must not swallow the first
|
|
637
|
+
* one's rooms. Unlike the surface migration this can never rename anything —
|
|
638
|
+
* the scope enters the uniqueness key in the same release, so nothing can start
|
|
639
|
+
* colliding because of it.
|
|
640
|
+
*
|
|
641
|
+
* Revision 5: the completion marker is written only when NO room was skipped.
|
|
642
|
+
* A room refused for a retryable reason (live maintenance, title conflict) is
|
|
643
|
+
* recorded in `api_surface_scope_stamp_pending` with the first attempt's scope,
|
|
644
|
+
* and later calls retry exactly those rooms under that pinned scope — never a
|
|
645
|
+
* fresh sweep, never the caller's (possibly different) scope. Rooms already
|
|
646
|
+
* stamped are no longer unscoped and drop out, so every pass is idempotent. The
|
|
647
|
+
* whole pass is one `BEGIN IMMEDIATE`, so concurrent boots serialize: the
|
|
648
|
+
* second sees the first one's marker or pending set and re-checks it.
|
|
649
|
+
*/
|
|
650
|
+
export function stampUnscopedOtiumTopics(scope: string): number {
|
|
651
|
+
const normalized = normalizeSurfaceScope(scope);
|
|
652
|
+
if (!normalized) return 0;
|
|
653
|
+
ensureSurfaceScopeStampTables();
|
|
654
|
+
// Cheap unlocked pre-check: a completed store never takes the write lock.
|
|
655
|
+
if (
|
|
656
|
+
db
|
|
657
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
658
|
+
.get(SURFACE_SCOPE_STAMP_MIGRATION)
|
|
659
|
+
) {
|
|
660
|
+
return 0;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
let stamped = 0;
|
|
664
|
+
const stillPending: Array<{ topicId: string; reason: string; detail?: string }> = [];
|
|
665
|
+
let effectiveScope = normalized;
|
|
666
|
+
let ran = false;
|
|
667
|
+
db.transaction(() => {
|
|
668
|
+
// Re-check under the write lock: a concurrent boot may have finished.
|
|
669
|
+
if (
|
|
670
|
+
db
|
|
671
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
672
|
+
.get(SURFACE_SCOPE_STAMP_MIGRATION)
|
|
673
|
+
) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
ran = true;
|
|
677
|
+
const pendingRows = db
|
|
678
|
+
.query<{ topic_id: string; scope: string }, []>(
|
|
679
|
+
"SELECT topic_id, scope FROM api_surface_scope_stamp_pending ORDER BY topic_id",
|
|
680
|
+
)
|
|
681
|
+
.all();
|
|
682
|
+
const retry = pendingRows.length > 0;
|
|
683
|
+
if (retry) effectiveScope = pendingRows[0]?.scope ?? normalized;
|
|
684
|
+
// Through the audited scope repair: an otium room's scope is otherwise
|
|
685
|
+
// immutable (topic-link review fix 6); the move is recorded and create
|
|
686
|
+
// claims stay on their original principal.
|
|
687
|
+
const result = repairUnscopedOtiumTopicScopes(
|
|
688
|
+
effectiveScope,
|
|
689
|
+
"m9-stamp",
|
|
690
|
+
"file pre-existing Otium rooms under the resolved workspace",
|
|
691
|
+
retry ? { topicIds: pendingRows.map((row) => row.topic_id) } : {},
|
|
692
|
+
);
|
|
693
|
+
stamped = result.stamped;
|
|
694
|
+
for (const skip of result.skipped) {
|
|
695
|
+
if (skip.ok || !SURFACE_SCOPE_STAMP_RETRYABLE.has(skip.reason)) continue;
|
|
696
|
+
stillPending.push({ topicId: skip.topicId, reason: skip.reason, detail: skip.detail });
|
|
697
|
+
}
|
|
698
|
+
const now = new Date().toISOString();
|
|
699
|
+
const keep = new Set(stillPending.map((row) => row.topicId));
|
|
700
|
+
for (const row of pendingRows) {
|
|
701
|
+
if (!keep.has(row.topic_id)) {
|
|
702
|
+
db.query("DELETE FROM api_surface_scope_stamp_pending WHERE topic_id = ?").run(
|
|
703
|
+
row.topic_id,
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (const row of stillPending) {
|
|
708
|
+
db.query(
|
|
709
|
+
`INSERT INTO api_surface_scope_stamp_pending
|
|
710
|
+
(topic_id, scope, reason, detail, attempts, first_seen_at, last_attempt_at)
|
|
711
|
+
VALUES (?, ?, ?, ?, 1, ?, ?)
|
|
712
|
+
ON CONFLICT(topic_id) DO UPDATE SET
|
|
713
|
+
reason = excluded.reason,
|
|
714
|
+
detail = excluded.detail,
|
|
715
|
+
attempts = api_surface_scope_stamp_pending.attempts + 1,
|
|
716
|
+
last_attempt_at = excluded.last_attempt_at`,
|
|
717
|
+
).run(row.topicId, effectiveScope, row.reason, row.detail ?? null, now, now);
|
|
718
|
+
}
|
|
719
|
+
if (stillPending.length === 0) {
|
|
720
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
721
|
+
SURFACE_SCOPE_STAMP_MIGRATION,
|
|
722
|
+
now,
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
}).immediate();
|
|
726
|
+
if (!ran) return 0;
|
|
727
|
+
if (effectiveScope !== normalized) {
|
|
728
|
+
logger.info(
|
|
729
|
+
{ scope: normalized, pinnedScope: effectiveScope },
|
|
730
|
+
"api_topics: surface scope stamp retry keeps the workspace of its first attempt",
|
|
731
|
+
);
|
|
732
|
+
}
|
|
733
|
+
if (stamped > 0) {
|
|
734
|
+
logger.info({ scope: effectiveScope, stamped }, "api_topics: surface scope stamped");
|
|
735
|
+
}
|
|
736
|
+
if (stillPending.length > 0) {
|
|
737
|
+
// Operator-visible every attempt: a permanent title conflict never
|
|
738
|
+
// completes the migration and needs a rename (or admin repair).
|
|
739
|
+
logger.warn(
|
|
740
|
+
{
|
|
741
|
+
scope: effectiveScope,
|
|
742
|
+
pending: stillPending.length,
|
|
743
|
+
topicIds: stillPending.map((row) => row.topicId),
|
|
744
|
+
skipped: stillPending,
|
|
745
|
+
},
|
|
746
|
+
"api_topics: surface scope stamp incomplete; rooms stay pending and will be retried",
|
|
747
|
+
);
|
|
748
|
+
} else {
|
|
749
|
+
logger.info({ scope: effectiveScope }, "api_topics: surface scope stamp complete");
|
|
750
|
+
}
|
|
751
|
+
return stamped;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
let lastSurfaceScopeStampRetryAt = 0;
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Retry an incomplete M-9 stamp under its pinned scope. No-op (no write lock)
|
|
758
|
+
* when the stamp never started or already completed. Unforced calls run at most
|
|
759
|
+
* once per {@link SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS} per process; `force`
|
|
760
|
+
* is for discrete events (a pending room's maintenance released, a scope
|
|
761
|
+
* refresh). Never throws: a busy database just waits for the next trigger.
|
|
762
|
+
*/
|
|
763
|
+
export function retryPendingSurfaceScopeStamp(
|
|
764
|
+
options: { force?: boolean; now?: number } = {},
|
|
765
|
+
): number {
|
|
766
|
+
const now = options.now ?? Date.now();
|
|
767
|
+
if (
|
|
768
|
+
!options.force &&
|
|
769
|
+
now - lastSurfaceScopeStampRetryAt < SURFACE_SCOPE_STAMP_RETRY_INTERVAL_MS
|
|
770
|
+
) {
|
|
771
|
+
return 0;
|
|
772
|
+
}
|
|
773
|
+
lastSurfaceScopeStampRetryAt = now;
|
|
774
|
+
try {
|
|
775
|
+
ensureSurfaceScopeStampTables();
|
|
776
|
+
const pinned = db
|
|
777
|
+
.query<{ scope: string }, []>("SELECT scope FROM api_surface_scope_stamp_pending LIMIT 1")
|
|
778
|
+
.get();
|
|
779
|
+
if (!pinned) return 0;
|
|
780
|
+
return stampUnscopedOtiumTopics(pinned.scope);
|
|
781
|
+
} catch (err) {
|
|
782
|
+
logger.warn({ err }, "api_topics: surface scope stamp retry failed (will retry)");
|
|
783
|
+
return 0;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Whether `topicId` is waiting for the M-9 stamp (cheap point lookup). */
|
|
788
|
+
export function isSurfaceScopeStampPending(topicId: string): boolean {
|
|
789
|
+
return Boolean(
|
|
790
|
+
db.query("SELECT 1 FROM api_surface_scope_stamp_pending WHERE topic_id = ?").get(topicId),
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// A pending room's maintenance fence was released: retry now instead of
|
|
795
|
+
// waiting for the next timer tick. Deferred so the stamp never runs inside the
|
|
796
|
+
// releasing caller's transaction.
|
|
797
|
+
onRuntimeTopicMaintenanceReleased((topicId) => {
|
|
798
|
+
const timer = setTimeout(() => {
|
|
799
|
+
try {
|
|
800
|
+
if (isSurfaceScopeStampPending(topicId)) retryPendingSurfaceScopeStamp({ force: true });
|
|
801
|
+
} catch (err) {
|
|
802
|
+
logger.warn({ err, topicId }, "api_topics: surface scope stamp retry on release failed");
|
|
803
|
+
}
|
|
804
|
+
}, 0);
|
|
805
|
+
timer.unref?.();
|
|
806
|
+
});
|
|
807
|
+
|
|
808
|
+
const SURFACE_BACKFILL_MIGRATION = "api_topics_surface_backfill_20260808";
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* One-time classification of pre-surface topics.
|
|
812
|
+
*
|
|
813
|
+
* Every row predates the column, so there is no per-row evidence in this store
|
|
814
|
+
* to distinguish surfaces — the host declares it (`NEGOTIUM_DEFAULT_SURFACE`).
|
|
815
|
+
* The telegram adapter owns the second pass: its chat↔topic mapping lives in a
|
|
816
|
+
* different database file, so only it can reclassify the rooms it created.
|
|
817
|
+
*
|
|
818
|
+
* Names are unique per surface from now on, so collapsing three namespaces into
|
|
819
|
+
* one can produce duplicates. Rather than failing the boot, the oldest room
|
|
820
|
+
* keeps the name and the rest are suffixed — a rename is recoverable, a node
|
|
821
|
+
* that refuses to start is not.
|
|
822
|
+
*/
|
|
823
|
+
function backfillTopicSurfaces(): void {
|
|
824
|
+
db.exec(`
|
|
825
|
+
CREATE TABLE IF NOT EXISTS api_schema_migrations (
|
|
826
|
+
key TEXT PRIMARY KEY,
|
|
827
|
+
applied_at TEXT NOT NULL
|
|
828
|
+
)
|
|
829
|
+
`);
|
|
830
|
+
const applied = db
|
|
831
|
+
.query("SELECT key FROM api_schema_migrations WHERE key = ?")
|
|
832
|
+
.get(SURFACE_BACKFILL_MIGRATION);
|
|
833
|
+
if (applied) return;
|
|
834
|
+
|
|
835
|
+
const surface = defaultTopicSurface();
|
|
836
|
+
db.transaction(() => {
|
|
837
|
+
db.query("UPDATE api_topics SET surface = ?").run(surface);
|
|
838
|
+
renameSurfaceTitleCollisions();
|
|
839
|
+
db.query("INSERT INTO api_schema_migrations (key, applied_at) VALUES (?, ?)").run(
|
|
840
|
+
SURFACE_BACKFILL_MIGRATION,
|
|
841
|
+
new Date().toISOString(),
|
|
842
|
+
);
|
|
843
|
+
})();
|
|
844
|
+
logger.info({ surface }, "api_topics: surface backfilled");
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Suffix duplicate `(surface, kind, title)` rows so the new uniqueness rule holds.
|
|
849
|
+
*
|
|
850
|
+
* Manager rooms are excluded: they are one per user, so on a multi-user host
|
|
851
|
+
* every member has a personal room with the same title and none of them is a
|
|
852
|
+
* duplicate. Renaming those relabels real rooms belonging to other people.
|
|
853
|
+
*/
|
|
854
|
+
function renameSurfaceTitleCollisions(): void {
|
|
855
|
+
const rows = db
|
|
856
|
+
.query<{ id: string; title: string; kind: string; surface: string }, []>(
|
|
857
|
+
"SELECT id, title, kind, surface FROM api_topics WHERE kind != 'manager' ORDER BY created_at ASC, rowid ASC",
|
|
858
|
+
)
|
|
859
|
+
.all();
|
|
860
|
+
const keyOf = (surface: string, kind: string, title: string) =>
|
|
861
|
+
[surface, kind, normalizedTitle(title)].join("\u0000");
|
|
862
|
+
// Every original title is reserved up front. Allocating only against the
|
|
863
|
+
// titles seen so far would let an earlier duplicate claim "Foo (2)" while a
|
|
864
|
+
// real room already named "Foo (2)" sits later in the scan — that room would
|
|
865
|
+
// then be pushed to "Foo (2) (2)" for no reason.
|
|
866
|
+
const reserved = new Set(rows.map((row) => keyOf(row.surface, row.kind, row.title)));
|
|
867
|
+
const used = new Set<string>();
|
|
868
|
+
const update = db.query("UPDATE api_topics SET title = ? WHERE id = ?");
|
|
869
|
+
for (const row of rows) {
|
|
870
|
+
const key = (title: string) => keyOf(row.surface, row.kind, title);
|
|
871
|
+
if (!used.has(key(row.title))) {
|
|
872
|
+
used.add(key(row.title));
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
let suffix = 2;
|
|
876
|
+
let candidate = `${row.title} (${suffix})`;
|
|
877
|
+
while (reserved.has(key(candidate)) || used.has(key(candidate))) {
|
|
878
|
+
suffix += 1;
|
|
879
|
+
candidate = `${row.title} (${suffix})`;
|
|
880
|
+
}
|
|
881
|
+
used.add(key(candidate));
|
|
882
|
+
update.run(candidate, row.id);
|
|
883
|
+
logger.warn(
|
|
884
|
+
{ topicId: row.id, surface: row.surface, from: row.title, to: candidate },
|
|
885
|
+
"api_topics: renamed a duplicate title for surface-scoped uniqueness",
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
registerStorageSchemaInitializer(initializeApiTopicsSchema, 20);
|
|
891
|
+
|
|
892
|
+
export interface TopicRow {
|
|
893
|
+
id: string;
|
|
894
|
+
title: string;
|
|
895
|
+
kind: string | null;
|
|
896
|
+
description: string | null;
|
|
897
|
+
agent: string | null;
|
|
898
|
+
base_model: string | null;
|
|
899
|
+
base_effort: string | null;
|
|
900
|
+
response_policy: string;
|
|
901
|
+
created_at: string;
|
|
902
|
+
last_message_at: string | null;
|
|
903
|
+
parent_topic_id: string | null;
|
|
904
|
+
memory_topic_id: string | null;
|
|
905
|
+
memory_key: string | null;
|
|
906
|
+
is_fork: number;
|
|
907
|
+
is_subagent: number;
|
|
908
|
+
subagent_report_mode: string | null;
|
|
909
|
+
derived_by_user_id: string | null;
|
|
910
|
+
visibility: string | null;
|
|
911
|
+
surface: string | null;
|
|
912
|
+
surface_scope: string | null;
|
|
913
|
+
browser_profile_owner: string | null;
|
|
914
|
+
browser_connect_port: number | null;
|
|
915
|
+
session_id: string | null;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
export interface TopicSessionLogContext {
|
|
919
|
+
reason?: string;
|
|
920
|
+
queryId?: string;
|
|
921
|
+
agent?: AgentKind;
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
function shortSessionId(sessionId: string | null | undefined): string | null {
|
|
925
|
+
return sessionId ? sessionId.slice(0, 8) : null;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function getTopicParticipants(topicId: string): ParticipantDto[] {
|
|
929
|
+
return db
|
|
930
|
+
.query<{ user_id: string; role: "owner" | "member" }, string>(
|
|
931
|
+
"SELECT user_id, role FROM topic_members WHERE topic_id = ? ORDER BY rowid",
|
|
932
|
+
)
|
|
933
|
+
.all(topicId)
|
|
934
|
+
.map((row) => ({ userId: row.user_id, role: row.role }));
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function getAllTopicParticipants(): Map<string, ParticipantDto[]> {
|
|
938
|
+
const grouped = new Map<string, ParticipantDto[]>();
|
|
939
|
+
const rows = db
|
|
940
|
+
.query<{ topic_id: string; user_id: string; role: "owner" | "member" }, []>(
|
|
941
|
+
"SELECT topic_id, user_id, role FROM topic_members ORDER BY rowid",
|
|
942
|
+
)
|
|
943
|
+
.all();
|
|
944
|
+
for (const row of rows) {
|
|
945
|
+
const participants = grouped.get(row.topic_id) ?? [];
|
|
946
|
+
participants.push({ userId: row.user_id, role: row.role });
|
|
947
|
+
grouped.set(row.topic_id, participants);
|
|
948
|
+
}
|
|
949
|
+
return grouped;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function getAllSubagentTellTargets(): Map<string, string[]> {
|
|
953
|
+
const rows = db
|
|
954
|
+
.query(
|
|
955
|
+
"SELECT subagent_topic_id, target_topic_id FROM subagent_tell_grants ORDER BY created_at",
|
|
956
|
+
)
|
|
957
|
+
.all() as Array<{ subagent_topic_id: string; target_topic_id: string }>;
|
|
958
|
+
const grouped = new Map<string, string[]>();
|
|
959
|
+
for (const row of rows) {
|
|
960
|
+
const targets = grouped.get(row.subagent_topic_id) ?? [];
|
|
961
|
+
targets.push(row.target_topic_id);
|
|
962
|
+
grouped.set(row.subagent_topic_id, targets);
|
|
963
|
+
}
|
|
964
|
+
return grouped;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
function rowToDto(
|
|
968
|
+
r: TopicRow,
|
|
969
|
+
participants = getTopicParticipants(r.id),
|
|
970
|
+
tellTargets?: Map<string, string[]>,
|
|
971
|
+
): TopicDto {
|
|
972
|
+
const normalized = normalizeTopicState({
|
|
973
|
+
id: r.id,
|
|
974
|
+
kind: normalizeTopicKind(r.kind),
|
|
975
|
+
agent: (r.agent as AgentKind | null) ?? undefined,
|
|
976
|
+
aiMode: normalizeAiMode(r.response_policy),
|
|
977
|
+
});
|
|
978
|
+
return {
|
|
979
|
+
id: r.id,
|
|
980
|
+
title: r.title,
|
|
981
|
+
kind: normalized.kind,
|
|
982
|
+
description: r.description ?? undefined,
|
|
983
|
+
agent: normalized.agent,
|
|
984
|
+
defaultModel: r.base_model ?? "deepseek-pro",
|
|
985
|
+
defaultEffort: (r.base_effort as EffortLevel) ?? undefined,
|
|
986
|
+
aiMode: normalized.aiMode,
|
|
987
|
+
aiMention: aiMentionFromMode(normalized.aiMode),
|
|
988
|
+
participants,
|
|
989
|
+
createdAt: r.created_at,
|
|
990
|
+
lastMessageAt: r.last_message_at ?? new Date().toISOString(),
|
|
991
|
+
parentTopicId: r.parent_topic_id ?? undefined,
|
|
992
|
+
memoryTopicId: r.memory_topic_id ?? undefined,
|
|
993
|
+
memoryKey: r.memory_key ?? undefined,
|
|
994
|
+
isFork: r.is_fork !== 0,
|
|
995
|
+
...(r.derived_by_user_id ? { derivedByUserId: r.derived_by_user_id } : {}),
|
|
996
|
+
...(r.is_subagent !== 0 ? { isSubagent: true } : {}),
|
|
997
|
+
...(r.is_subagent !== 0
|
|
998
|
+
? {
|
|
999
|
+
subagentTellTargetIds: tellTargets
|
|
1000
|
+
? (tellTargets.get(r.id) ?? [])
|
|
1001
|
+
: listSubagentTellTargetIds(r.id),
|
|
1002
|
+
}
|
|
1003
|
+
: {}),
|
|
1004
|
+
...(r.is_subagent !== 0
|
|
1005
|
+
? {
|
|
1006
|
+
subagentReportMode: (r.subagent_report_mode === "tell" ||
|
|
1007
|
+
r.subagent_report_mode === "status-only"
|
|
1008
|
+
? r.subagent_report_mode
|
|
1009
|
+
: "auto") as SubagentReportMode,
|
|
1010
|
+
}
|
|
1011
|
+
: {}),
|
|
1012
|
+
visibility: normalizeTopicVisibility(r.visibility),
|
|
1013
|
+
surface: normalizeTopicSurface(r.surface),
|
|
1014
|
+
surfaceScope: normalizeSurfaceScope(r.surface_scope),
|
|
1015
|
+
...(r.browser_connect_port != null ? { browserConnectPort: r.browser_connect_port } : {}),
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
export function normalizeTopicVisibility(value: unknown): TopicVisibility {
|
|
1020
|
+
return value === "hidden" ? "hidden" : "visible";
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** Discovery boundary shared by user-facing adapters. */
|
|
1024
|
+
export function isTopicVisible(topic: Pick<TopicDto, "visibility">): boolean {
|
|
1025
|
+
return topic.visibility !== "hidden";
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
export function normalizeTopicKind(value: unknown): TopicKind | null {
|
|
1029
|
+
return value === "channel" || value === "agent" || value === "manager" ? value : null;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
export function normalizeAiMode(value: unknown): AiMode | null {
|
|
1033
|
+
return value === "off" || value === "mention" || value === "always" ? value : null;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
export function aiMentionFromMode(mode: AiMode): boolean {
|
|
1037
|
+
return mode === "mention";
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
export function inferTopicKind(input: {
|
|
1041
|
+
agent?: string | null;
|
|
1042
|
+
aiMention?: boolean | null;
|
|
1043
|
+
}): TopicKind {
|
|
1044
|
+
return input.agent && input.aiMention !== true ? "agent" : "channel";
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
export function inferAiMode(input: {
|
|
1048
|
+
kind?: TopicKind | null;
|
|
1049
|
+
agent?: string | null;
|
|
1050
|
+
aiMode?: AiMode | null;
|
|
1051
|
+
aiMention?: boolean | null;
|
|
1052
|
+
}): AiMode {
|
|
1053
|
+
if (input.kind === "manager") return "always";
|
|
1054
|
+
if (input.kind === "agent") return "always";
|
|
1055
|
+
if (input.kind === "channel") {
|
|
1056
|
+
if (!input.agent) return "off";
|
|
1057
|
+
if (input.aiMode === "mention") return "mention";
|
|
1058
|
+
if (input.aiMention === true) return "mention";
|
|
1059
|
+
return "mention";
|
|
1060
|
+
}
|
|
1061
|
+
if (!input.agent) return "off";
|
|
1062
|
+
if (input.aiMode) return input.aiMode;
|
|
1063
|
+
return input.aiMention === true ? "mention" : "always";
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
export function normalizeTopicState(input: {
|
|
1067
|
+
id?: string;
|
|
1068
|
+
kind?: TopicKind | null;
|
|
1069
|
+
agent?: AgentKind | null;
|
|
1070
|
+
aiMode?: AiMode | null;
|
|
1071
|
+
aiMention?: boolean | null;
|
|
1072
|
+
}): { kind: TopicKind; aiMode: AiMode; agent?: AgentKind } {
|
|
1073
|
+
if (input.kind === "manager" || input.id === GENERAL_TOPIC_ID) {
|
|
1074
|
+
return {
|
|
1075
|
+
kind: "manager",
|
|
1076
|
+
aiMode: "always",
|
|
1077
|
+
agent: input.agent ?? resolveFallbackAgent(),
|
|
1078
|
+
};
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const requestedKind = input.kind;
|
|
1082
|
+
const kind =
|
|
1083
|
+
requestedKind ??
|
|
1084
|
+
(input.aiMode === "always"
|
|
1085
|
+
? "agent"
|
|
1086
|
+
: input.aiMode === "mention" || input.aiMode === "off"
|
|
1087
|
+
? "channel"
|
|
1088
|
+
: input.agent && input.aiMention !== true
|
|
1089
|
+
? "agent"
|
|
1090
|
+
: "channel");
|
|
1091
|
+
|
|
1092
|
+
if (kind === "agent") {
|
|
1093
|
+
return {
|
|
1094
|
+
kind: "agent",
|
|
1095
|
+
aiMode: "always",
|
|
1096
|
+
agent: input.agent ?? resolveFallbackAgent(),
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
const agent = input.aiMode === "off" ? undefined : (input.agent ?? undefined);
|
|
1101
|
+
return {
|
|
1102
|
+
kind: "channel",
|
|
1103
|
+
aiMode: agent ? "mention" : "off",
|
|
1104
|
+
agent,
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function normalizedTitle(title: string): string {
|
|
1109
|
+
return title.trim().toLowerCase();
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* The workspace a written row belongs to.
|
|
1114
|
+
*
|
|
1115
|
+
* `surfaceScope` partitions one surface into independent namespaces. Otium
|
|
1116
|
+
* uses a workspace scope and Telegram uses a forum-group scope. Terminal is
|
|
1117
|
+
* normally unscoped. An explicit value always wins; only Otium has a
|
|
1118
|
+
* process-level default because its workspace attachment is host state.
|
|
1119
|
+
*/
|
|
1120
|
+
function surfaceScopeForWrite(t: TopicDto): string | null {
|
|
1121
|
+
if (t.surfaceScope !== undefined) return normalizeSurfaceScope(t.surfaceScope);
|
|
1122
|
+
return normalizeTopicSurface(t.surface ?? defaultTopicSurface()) === "otium"
|
|
1123
|
+
? defaultSurfaceScope()
|
|
1124
|
+
: null;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export function upsertTopic(t: TopicDto): void {
|
|
1128
|
+
const normalized = normalizeTopicState({
|
|
1129
|
+
id: t.id,
|
|
1130
|
+
kind: normalizeTopicKind(t.kind),
|
|
1131
|
+
agent: t.agent ?? undefined,
|
|
1132
|
+
aiMode: normalizeAiMode(t.aiMode),
|
|
1133
|
+
aiMention: t.aiMention,
|
|
1134
|
+
});
|
|
1135
|
+
db.transaction(() => {
|
|
1136
|
+
db.query(
|
|
1137
|
+
`INSERT INTO api_topics
|
|
1138
|
+
(id,title,kind,description,agent,base_model,base_effort,response_policy,
|
|
1139
|
+
created_at,last_message_at,parent_topic_id,memory_topic_id,memory_key,is_fork,is_subagent,visibility,surface,
|
|
1140
|
+
surface_scope,subagent_report_mode,derived_by_user_id)
|
|
1141
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
1142
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1143
|
+
title = excluded.title,
|
|
1144
|
+
kind = excluded.kind,
|
|
1145
|
+
description = excluded.description,
|
|
1146
|
+
agent = excluded.agent,
|
|
1147
|
+
base_model = excluded.base_model,
|
|
1148
|
+
base_effort = excluded.base_effort,
|
|
1149
|
+
response_policy = excluded.response_policy,
|
|
1150
|
+
created_at = excluded.created_at,
|
|
1151
|
+
last_message_at = excluded.last_message_at,
|
|
1152
|
+
parent_topic_id = excluded.parent_topic_id,
|
|
1153
|
+
memory_topic_id = excluded.memory_topic_id,
|
|
1154
|
+
memory_key = excluded.memory_key,
|
|
1155
|
+
is_fork = excluded.is_fork,
|
|
1156
|
+
is_subagent = excluded.is_subagent,
|
|
1157
|
+
visibility = excluded.visibility,
|
|
1158
|
+
surface = excluded.surface,
|
|
1159
|
+
-- A room's workspace is fixed at creation (M-1). COALESCE, not
|
|
1160
|
+
-- assignment: an update may fill in a scope that was unknown when the
|
|
1161
|
+
-- room was created, but may never move a room to another workspace.
|
|
1162
|
+
-- An otium room is stricter (topic-link review fix 6): its scope never
|
|
1163
|
+
-- changes through an upsert, not even NULL -> scope; only the audited
|
|
1164
|
+
-- repair (adminRepairOtiumTopicScope / the M-9 stamp) may assign it.
|
|
1165
|
+
surface_scope = CASE
|
|
1166
|
+
WHEN excluded.surface = 'otium' OR api_topics.surface = 'otium'
|
|
1167
|
+
THEN api_topics.surface_scope
|
|
1168
|
+
ELSE COALESCE(api_topics.surface_scope, excluded.surface_scope)
|
|
1169
|
+
END,
|
|
1170
|
+
subagent_report_mode = excluded.subagent_report_mode,
|
|
1171
|
+
-- Who asked for the derive is a fact about creation; a later update
|
|
1172
|
+
-- that omits it must not erase it.
|
|
1173
|
+
derived_by_user_id = COALESCE(excluded.derived_by_user_id, api_topics.derived_by_user_id)`,
|
|
1174
|
+
).run(
|
|
1175
|
+
t.id,
|
|
1176
|
+
t.title,
|
|
1177
|
+
normalized.kind,
|
|
1178
|
+
t.description ?? null,
|
|
1179
|
+
normalized.agent ?? null,
|
|
1180
|
+
t.defaultModel ?? null,
|
|
1181
|
+
t.defaultEffort ?? null,
|
|
1182
|
+
normalized.aiMode,
|
|
1183
|
+
t.createdAt,
|
|
1184
|
+
t.lastMessageAt ?? null,
|
|
1185
|
+
t.parentTopicId ?? null,
|
|
1186
|
+
t.memoryTopicId ?? null,
|
|
1187
|
+
t.memoryKey ?? null,
|
|
1188
|
+
t.isFork ? 1 : 0,
|
|
1189
|
+
t.isSubagent ? 1 : 0,
|
|
1190
|
+
normalizeTopicVisibility(t.visibility),
|
|
1191
|
+
// A DTO without a surface means "wherever this host puts rooms", not
|
|
1192
|
+
// "terminal": embedding hosts (Otium) build topic literals by hand and
|
|
1193
|
+
// never name one, so defaulting to the literal would file every hub room
|
|
1194
|
+
// on the wrong surface.
|
|
1195
|
+
normalizeTopicSurface(t.surface ?? defaultTopicSurface()),
|
|
1196
|
+
surfaceScopeForWrite(t),
|
|
1197
|
+
t.subagentReportMode ?? "auto",
|
|
1198
|
+
t.derivedByUserId ?? null,
|
|
1199
|
+
);
|
|
1200
|
+
db.query("DELETE FROM topic_members WHERE topic_id = ?").run(t.id);
|
|
1201
|
+
for (const participant of t.participants) {
|
|
1202
|
+
db.query("INSERT INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)").run(
|
|
1203
|
+
t.id,
|
|
1204
|
+
participant.userId,
|
|
1205
|
+
participant.role,
|
|
1206
|
+
);
|
|
1207
|
+
}
|
|
1208
|
+
const initialBrowserProfileOwner = t.participants.find(
|
|
1209
|
+
(participant) => participant.role === "owner",
|
|
1210
|
+
)?.userId;
|
|
1211
|
+
if (initialBrowserProfileOwner) {
|
|
1212
|
+
db.query(
|
|
1213
|
+
`UPDATE api_topics
|
|
1214
|
+
SET browser_profile_owner = COALESCE(browser_profile_owner, ?)
|
|
1215
|
+
WHERE id = ?`,
|
|
1216
|
+
).run(initialBrowserProfileOwner, t.id);
|
|
1217
|
+
}
|
|
1218
|
+
})();
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/**
|
|
1222
|
+
* List topics, optionally restricted to one surface.
|
|
1223
|
+
*
|
|
1224
|
+
* The filter lives here rather than in each adapter so a forgotten call site
|
|
1225
|
+
* cannot leak a telegram room into the terminal picker; adapters pass their own
|
|
1226
|
+
* surface and get a closed world back.
|
|
1227
|
+
*/
|
|
1228
|
+
export function listTopics(
|
|
1229
|
+
opts: { surface?: TopicSurface; surfaceScope?: string | null } = {},
|
|
1230
|
+
): TopicDto[] {
|
|
1231
|
+
// `surfaceScope: null` is a real filter ("the unscoped rooms"), so presence —
|
|
1232
|
+
// not truthiness — decides whether the scope narrows the query at all.
|
|
1233
|
+
const scoped = Object.hasOwn(opts, "surfaceScope");
|
|
1234
|
+
const rows = (
|
|
1235
|
+
opts.surface
|
|
1236
|
+
? db
|
|
1237
|
+
.query(
|
|
1238
|
+
`SELECT * FROM api_topics WHERE surface = ?${scoped ? " AND surface_scope IS ?" : ""} ORDER BY last_message_at DESC`,
|
|
1239
|
+
)
|
|
1240
|
+
.all(
|
|
1241
|
+
...(scoped
|
|
1242
|
+
? [normalizeTopicSurface(opts.surface), normalizeSurfaceScope(opts.surfaceScope)]
|
|
1243
|
+
: [normalizeTopicSurface(opts.surface)]),
|
|
1244
|
+
)
|
|
1245
|
+
: db.query("SELECT * FROM api_topics ORDER BY last_message_at DESC").all()
|
|
1246
|
+
) as TopicRow[];
|
|
1247
|
+
const participants = getAllTopicParticipants();
|
|
1248
|
+
// Batch-load tell grants once: per-row queries would make every listTopics()
|
|
1249
|
+
// call O(N) extra statements as subagent counts grow.
|
|
1250
|
+
const tellTargets = rows.some((row) => row.is_subagent !== 0)
|
|
1251
|
+
? getAllSubagentTellTargets()
|
|
1252
|
+
: undefined;
|
|
1253
|
+
return rows.map((row) => rowToDto(row, participants.get(row.id) ?? [], tellTargets));
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
export function getTopic(id: string): TopicDto | null {
|
|
1257
|
+
const r = db.query("SELECT * FROM api_topics WHERE id = ?").get(id) as TopicRow | undefined;
|
|
1258
|
+
return r ? rowToDto(r) : null;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/** Return the private manager room owned by a user, excluding the retired shared General row. */
|
|
1262
|
+
/**
|
|
1263
|
+
* The user's own manager room, optionally on one surface.
|
|
1264
|
+
*
|
|
1265
|
+
* A manager room is one per user **per surface**: Terminal and Telegram each
|
|
1266
|
+
* give the same person their own personal room, and returning one surface's
|
|
1267
|
+
* room to the other adapter lets that adapter bind to — and reclassify — a room
|
|
1268
|
+
* belonging to a different surface. Callers that represent an adapter pass
|
|
1269
|
+
* theirs; unscoped lookups stay for maintenance paths that work by user alone.
|
|
1270
|
+
*/
|
|
1271
|
+
export function getManagerTopicForUser(
|
|
1272
|
+
userId: string,
|
|
1273
|
+
surface?: TopicSurface,
|
|
1274
|
+
opts: { surfaceScope?: string | null } = {},
|
|
1275
|
+
): TopicDto | null {
|
|
1276
|
+
const scoped = Object.hasOwn(opts, "surfaceScope");
|
|
1277
|
+
const sql = `SELECT t.* FROM api_topics t
|
|
1278
|
+
JOIN topic_members m ON m.topic_id = t.id
|
|
1279
|
+
WHERE t.kind = 'manager'
|
|
1280
|
+
AND t.id != ?
|
|
1281
|
+
AND m.user_id = ?
|
|
1282
|
+
AND m.role = 'owner'
|
|
1283
|
+
${surface ? "AND t.surface = ?" : ""}
|
|
1284
|
+
${scoped ? "AND t.surface_scope IS ?" : ""}
|
|
1285
|
+
ORDER BY t.created_at ASC
|
|
1286
|
+
LIMIT 1`;
|
|
1287
|
+
const params: Array<string | null> = [GENERAL_TOPIC_ID, userId];
|
|
1288
|
+
if (surface) params.push(surface);
|
|
1289
|
+
if (scoped) params.push(normalizeSurfaceScope(opts.surfaceScope));
|
|
1290
|
+
const row = db.query<TopicRow, Array<string | null>>(sql).get(...params);
|
|
1291
|
+
return row ? rowToDto(row) : null;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Resolve the topic whose wiki memory should be used for this topic.
|
|
1296
|
+
*
|
|
1297
|
+
* Derived rooms keep `parentTopicId` as an immediate UI link. Memory normally
|
|
1298
|
+
* follows the chain to its original root, while `memoryTopicId` can redirect a
|
|
1299
|
+
* subagent to another accessible topic's accumulated knowledge.
|
|
1300
|
+
*/
|
|
1301
|
+
export function getTopicMemoryOrigin(id: string): TopicDto | null {
|
|
1302
|
+
let current = getTopic(id);
|
|
1303
|
+
if (!current) return null;
|
|
1304
|
+
|
|
1305
|
+
const seen = new Set<string>([current.id]);
|
|
1306
|
+
while (true) {
|
|
1307
|
+
const nextId = current.memoryTopicId ?? current.parentTopicId;
|
|
1308
|
+
if (!nextId || seen.has(nextId)) break;
|
|
1309
|
+
const next = getTopic(nextId);
|
|
1310
|
+
if (!next) {
|
|
1311
|
+
// An explicitly selected memory topic that no longer resolves must not
|
|
1312
|
+
// silently fall back to the parent chain — that would leak the parent
|
|
1313
|
+
// room's memory to a subagent that asked for something else. Stop at the
|
|
1314
|
+
// current topic instead so the broken source is visible.
|
|
1315
|
+
if (current.memoryTopicId) {
|
|
1316
|
+
console.warn(
|
|
1317
|
+
`[topics] memory topic ${current.memoryTopicId} for ${current.id} is unresolvable; using the topic's own memory`,
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
break;
|
|
1321
|
+
}
|
|
1322
|
+
current = next;
|
|
1323
|
+
seen.add(current.id);
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
return current;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/** Look up a topic by its user-visible title (case-insensitive exact match). */
|
|
1330
|
+
export function getTopicByName(title: string): TopicDto | null {
|
|
1331
|
+
const r = db.query("SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?)").get(title) as
|
|
1332
|
+
| TopicRow
|
|
1333
|
+
| undefined;
|
|
1334
|
+
return r ? rowToDto(r) : null;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
export function getTopicByNameAndKind(title: string, kind: TopicKind): TopicDto | null {
|
|
1338
|
+
const r = db
|
|
1339
|
+
.query("SELECT * FROM api_topics WHERE LOWER(title) = LOWER(?) AND kind = ?")
|
|
1340
|
+
.get(title, kind) as TopicRow | undefined;
|
|
1341
|
+
return r ? rowToDto(r) : null;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* Titles are unique **per surface namespace**, not per node: the same title may
|
|
1346
|
+
* exist on terminal, in multiple Telegram groups, and in each attached Otium
|
|
1347
|
+
* workspace. Independent namespaces never see each other, so a name taken in
|
|
1348
|
+
* one says nothing about another.
|
|
1349
|
+
*/
|
|
1350
|
+
export function findTopicTitleConflict(
|
|
1351
|
+
title: string,
|
|
1352
|
+
kind: TopicKind,
|
|
1353
|
+
opts: { excludeTopicId?: string; surface?: TopicSurface; surfaceScope?: string | null } = {},
|
|
1354
|
+
): TopicDto | null {
|
|
1355
|
+
const wanted = normalizedTitle(title);
|
|
1356
|
+
const surface = normalizeTopicSurface(opts.surface ?? defaultTopicSurface());
|
|
1357
|
+
const surfaceScope = Object.hasOwn(opts, "surfaceScope")
|
|
1358
|
+
? normalizeSurfaceScope(opts.surfaceScope)
|
|
1359
|
+
: surface === "otium"
|
|
1360
|
+
? defaultSurfaceScope()
|
|
1361
|
+
: null;
|
|
1362
|
+
const generalTitleRequested = wanted === normalizedTitle(GENERAL_TOPIC_ID);
|
|
1363
|
+
if (generalTitleRequested && opts.excludeTopicId !== GENERAL_TOPIC_ID) {
|
|
1364
|
+
const general = db.query("SELECT * FROM api_topics WHERE id = ?").get(GENERAL_TOPIC_ID) as
|
|
1365
|
+
| TopicRow
|
|
1366
|
+
| undefined;
|
|
1367
|
+
if (general) return rowToDto(general);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// Manager rooms are one-per-user and system-created, so several of them
|
|
1371
|
+
// legitimately share a title (every member's personal "General"). Comparing
|
|
1372
|
+
// them against each other is not a conflict, it is the design — on a
|
|
1373
|
+
// multi-user host it renamed real rooms out from under their owners.
|
|
1374
|
+
if (kind === "manager") return null;
|
|
1375
|
+
|
|
1376
|
+
const params: Array<string | null> = [wanted, surface, surfaceScope, kind, GENERAL_TOPIC_ID];
|
|
1377
|
+
let sql =
|
|
1378
|
+
"SELECT * FROM api_topics WHERE LOWER(TRIM(title)) = ? AND surface = ? AND surface_scope IS ? AND (kind = ? OR id = ?)";
|
|
1379
|
+
if (opts.excludeTopicId) {
|
|
1380
|
+
sql += " AND id != ?";
|
|
1381
|
+
params.push(opts.excludeTopicId);
|
|
1382
|
+
}
|
|
1383
|
+
sql += " LIMIT 1";
|
|
1384
|
+
const row = db.query<TopicRow, string[]>(sql).get(...params);
|
|
1385
|
+
return row ? rowToDto(row) : null;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/**
|
|
1389
|
+
* Move topics onto a surface. Used by adapters that own a classification the
|
|
1390
|
+
* canonical store cannot derive on its own (the telegram chat↔topic mapping
|
|
1391
|
+
* lives in that adapter's database, not this one).
|
|
1392
|
+
*/
|
|
1393
|
+
export function setTopicSurfaces(topicIds: readonly string[], surface: TopicSurface): number {
|
|
1394
|
+
if (topicIds.length === 0) return 0;
|
|
1395
|
+
const normalized = normalizeTopicSurface(surface);
|
|
1396
|
+
let changed = 0;
|
|
1397
|
+
db.transaction(() => {
|
|
1398
|
+
const update = db.query("UPDATE api_topics SET surface = ? WHERE id = ? AND surface != ?");
|
|
1399
|
+
for (const topicId of topicIds) {
|
|
1400
|
+
changed += Number(update.run(normalized, topicId, normalized).changes ?? 0);
|
|
1401
|
+
}
|
|
1402
|
+
})();
|
|
1403
|
+
return changed;
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
/**
|
|
1407
|
+
* File an existing topic into one surface namespace without changing its id.
|
|
1408
|
+
* Adapter-owned migrations use this when their local mapping store is the only
|
|
1409
|
+
* authority capable of deriving the namespace (for example Telegram chat id).
|
|
1410
|
+
*/
|
|
1411
|
+
export function setTopicSurfaceScope(
|
|
1412
|
+
topicId: string,
|
|
1413
|
+
surface: TopicSurface,
|
|
1414
|
+
surfaceScope: string | null,
|
|
1415
|
+
): boolean {
|
|
1416
|
+
const normalizedSurface = normalizeTopicSurface(surface);
|
|
1417
|
+
const normalizedScope = normalizeSurfaceScope(surfaceScope);
|
|
1418
|
+
const result = db
|
|
1419
|
+
.query(
|
|
1420
|
+
`UPDATE api_topics SET surface = ?, surface_scope = ?
|
|
1421
|
+
WHERE id = ? AND (surface IS NOT ? OR surface_scope IS NOT ?)`,
|
|
1422
|
+
)
|
|
1423
|
+
.run(normalizedSurface, normalizedScope, topicId, normalizedSurface, normalizedScope);
|
|
1424
|
+
return Number(result.changes ?? 0) > 0;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/**
|
|
1428
|
+
* How wide a title lookup is allowed to reach.
|
|
1429
|
+
*
|
|
1430
|
+
* `surface` is required rather than optional. It used to default to "search
|
|
1431
|
+
* every surface", which contradicted S-6's promise that a missed call site
|
|
1432
|
+
* "cannot leak a topic across surfaces" — the guarantee only held where a
|
|
1433
|
+
* caller remembered to opt in, and four did not: Telegram's `/load` and `/del`
|
|
1434
|
+
* (the latter could delete a terminal room), the runtime MCP id path, the cron
|
|
1435
|
+
* id path, and the session inbox. Every one of those was a silent leak with a
|
|
1436
|
+
* correct-looking call. Making the parameter explicit turns each future
|
|
1437
|
+
* omission into a compile error instead.
|
|
1438
|
+
*
|
|
1439
|
+
* `{ scope: "all" }` is the deliberate way to search every surface. It exists
|
|
1440
|
+
* for operator tooling — the CLI manages jobs across surfaces on purpose — and
|
|
1441
|
+
* reads as a decision at the call site rather than as an oversight.
|
|
1442
|
+
*/
|
|
1443
|
+
export type TopicNameLookupScope =
|
|
1444
|
+
| { surface: TopicSurface; surfaceScope?: string | null }
|
|
1445
|
+
| { scope: "all" };
|
|
1446
|
+
|
|
1447
|
+
/**
|
|
1448
|
+
* Look up a topic by title, restricted to topics where `userId` participates.
|
|
1449
|
+
*
|
|
1450
|
+
* Answers only on a single match: a title is unique per surface (S-3), so an
|
|
1451
|
+
* `{ scope: "all" }` lookup of a name used on two surfaces resolves to null
|
|
1452
|
+
* rather than picking one.
|
|
1453
|
+
*/
|
|
1454
|
+
export function getTopicByNameForUser(
|
|
1455
|
+
title: string,
|
|
1456
|
+
userId: string,
|
|
1457
|
+
lookupScope: TopicNameLookupScope,
|
|
1458
|
+
): TopicDto | null {
|
|
1459
|
+
const opts: { surface?: TopicSurface; surfaceScope?: string | null } =
|
|
1460
|
+
"scope" in lookupScope ? {} : lookupScope;
|
|
1461
|
+
const trimmed = title.trim();
|
|
1462
|
+
const qualified = /^(agent|channel|manager):(.+)$/i.exec(trimmed);
|
|
1463
|
+
const requestedKind = qualified ? normalizeTopicKind(qualified[1]?.toLowerCase()) : null;
|
|
1464
|
+
const requestedTitle = qualified ? qualified[2]!.trim() : trimmed;
|
|
1465
|
+
const scoped = Object.hasOwn(opts, "surfaceScope");
|
|
1466
|
+
const rows = db
|
|
1467
|
+
.query(
|
|
1468
|
+
`SELECT t.* FROM api_topics t
|
|
1469
|
+
WHERE LOWER(t.title) = LOWER(?)
|
|
1470
|
+
AND t.id != ?
|
|
1471
|
+
AND t.visibility != 'hidden'
|
|
1472
|
+
AND (? IS NULL OR t.surface = ?)
|
|
1473
|
+
${scoped ? "AND t.surface_scope IS ?" : ""}
|
|
1474
|
+
AND EXISTS (
|
|
1475
|
+
SELECT 1 FROM topic_members m WHERE m.topic_id = t.id AND m.user_id = ?
|
|
1476
|
+
)`,
|
|
1477
|
+
)
|
|
1478
|
+
.all(
|
|
1479
|
+
requestedTitle,
|
|
1480
|
+
GENERAL_TOPIC_ID,
|
|
1481
|
+
opts.surface ?? null,
|
|
1482
|
+
opts.surface ?? null,
|
|
1483
|
+
...(scoped ? [normalizeSurfaceScope(opts.surfaceScope)] : []),
|
|
1484
|
+
userId,
|
|
1485
|
+
) as TopicRow[];
|
|
1486
|
+
const matches = requestedKind ? rows.filter((row) => row.kind === requestedKind) : rows;
|
|
1487
|
+
return matches.length === 1 ? rowToDto(matches[0]!) : null;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/** Persist the agent session ID for a topic after a successful turn. */
|
|
1491
|
+
export function setTopicSessionId(
|
|
1492
|
+
topicId: string,
|
|
1493
|
+
sessionId: string,
|
|
1494
|
+
context: TopicSessionLogContext = {},
|
|
1495
|
+
): void {
|
|
1496
|
+
const previous = getTopicSessionId(topicId);
|
|
1497
|
+
const result = db
|
|
1498
|
+
.query("UPDATE api_topics SET session_id = ? WHERE id = ?")
|
|
1499
|
+
.run(sessionId, topicId);
|
|
1500
|
+
const changes = Number(result.changes ?? 0);
|
|
1501
|
+
const logContext = {
|
|
1502
|
+
topicId,
|
|
1503
|
+
previousSessionId: shortSessionId(previous),
|
|
1504
|
+
sessionId: shortSessionId(sessionId),
|
|
1505
|
+
reason: context.reason,
|
|
1506
|
+
queryId: context.queryId,
|
|
1507
|
+
agent: context.agent,
|
|
1508
|
+
};
|
|
1509
|
+
if (changes === 0) {
|
|
1510
|
+
logger.warn(logContext, "api-topic session_id update missed topic");
|
|
1511
|
+
} else if (previous !== sessionId) {
|
|
1512
|
+
logger.debug(logContext, "api-topic session_id updated");
|
|
1513
|
+
} else {
|
|
1514
|
+
logger.debug(logContext, "api-topic session_id unchanged");
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/** Clear the session ID (e.g. on topic reset). */
|
|
1519
|
+
export function clearTopicSessionId(topicId: string, reason = "unspecified"): void {
|
|
1520
|
+
const previous = getTopicSessionId(topicId);
|
|
1521
|
+
const result = db.query("UPDATE api_topics SET session_id = NULL WHERE id = ?").run(topicId);
|
|
1522
|
+
const changes = Number(result.changes ?? 0);
|
|
1523
|
+
const logContext = { topicId, previousSessionId: shortSessionId(previous), reason };
|
|
1524
|
+
if (changes === 0) {
|
|
1525
|
+
logger.warn(logContext, "api-topic session_id clear missed topic");
|
|
1526
|
+
} else if (previous) {
|
|
1527
|
+
logger.info(logContext, "api-topic session_id cleared");
|
|
1528
|
+
} else {
|
|
1529
|
+
logger.debug(logContext, "api-topic session_id already clear");
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
/** Read the persisted session ID for a topic, or null if none. */
|
|
1534
|
+
export function getTopicSessionId(topicId: string): string | null {
|
|
1535
|
+
const r = db
|
|
1536
|
+
.query<{ session_id: string | null }, string>("SELECT session_id FROM api_topics WHERE id = ?")
|
|
1537
|
+
.get(topicId);
|
|
1538
|
+
return r?.session_id ?? null;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/**
|
|
1542
|
+
* Hard-delete a topic row. Irreversible — the caller is responsible for also
|
|
1543
|
+
* deleting the topic's messages (see `deleteMessagesForTopic`). Returns false
|
|
1544
|
+
* if the topic didn't exist.
|
|
1545
|
+
*/
|
|
1546
|
+
export function deleteTopic(id: string, options: { allowManager?: boolean } = {}): boolean {
|
|
1547
|
+
const r = db
|
|
1548
|
+
.query<{ id: string; kind: string }, string>("SELECT id, kind FROM api_topics WHERE id = ?")
|
|
1549
|
+
.get(id);
|
|
1550
|
+
if (!r) return false;
|
|
1551
|
+
if (id === GENERAL_TOPIC_ID || (r.kind === "manager" && !options.allowManager)) return false;
|
|
1552
|
+
db.query(
|
|
1553
|
+
`DELETE FROM subagent_tell_grants
|
|
1554
|
+
WHERE subagent_topic_id = ? OR target_topic_id = ? OR granted_by_topic_id = ?`,
|
|
1555
|
+
).run(id, id, id);
|
|
1556
|
+
db.query("DELETE FROM topic_members WHERE topic_id = ?").run(id);
|
|
1557
|
+
db.query("DELETE FROM api_topics WHERE id = ?").run(id);
|
|
1558
|
+
return true;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
export function listSubagentTellTargetIds(subagentTopicId: string): string[] {
|
|
1562
|
+
return db
|
|
1563
|
+
.query<{ target_topic_id: string }, string>(
|
|
1564
|
+
"SELECT target_topic_id FROM subagent_tell_grants WHERE subagent_topic_id = ? ORDER BY created_at",
|
|
1565
|
+
)
|
|
1566
|
+
.all(subagentTopicId)
|
|
1567
|
+
.map((row) => row.target_topic_id);
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
export function grantSubagentTellTarget(
|
|
1571
|
+
subagentTopicId: string,
|
|
1572
|
+
targetTopicId: string,
|
|
1573
|
+
grantedByTopicId: string,
|
|
1574
|
+
): void {
|
|
1575
|
+
db.query(
|
|
1576
|
+
`INSERT INTO subagent_tell_grants
|
|
1577
|
+
(subagent_topic_id,target_topic_id,granted_by_topic_id,created_at)
|
|
1578
|
+
VALUES (?,?,?,?)
|
|
1579
|
+
ON CONFLICT(subagent_topic_id,target_topic_id) DO UPDATE SET
|
|
1580
|
+
granted_by_topic_id = excluded.granted_by_topic_id`,
|
|
1581
|
+
).run(subagentTopicId, targetTopicId, grantedByTopicId, new Date().toISOString());
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
export function revokeSubagentTellTarget(subagentTopicId: string, targetTopicId: string): boolean {
|
|
1585
|
+
return (
|
|
1586
|
+
db
|
|
1587
|
+
.query("DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? AND target_topic_id = ?")
|
|
1588
|
+
.run(subagentTopicId, targetTopicId).changes > 0
|
|
1589
|
+
);
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
/**
|
|
1593
|
+
* Preserve a derived-topic chain when an intermediate parent is deleted.
|
|
1594
|
+
* Direct children move to the deleted topic's parent (or become roots) rather
|
|
1595
|
+
* than retaining a dangling parent id that would break memory-origin lookup.
|
|
1596
|
+
*/
|
|
1597
|
+
/** Ids of the subagent worker rooms spawned directly from `parentTopicId`. */
|
|
1598
|
+
export function listSubagentChildTopicIds(parentTopicId: string): string[] {
|
|
1599
|
+
return db
|
|
1600
|
+
.query<{ id: string }, string>(
|
|
1601
|
+
"SELECT id FROM api_topics WHERE parent_topic_id = ? AND is_subagent = 1 ORDER BY created_at",
|
|
1602
|
+
)
|
|
1603
|
+
.all(parentTopicId)
|
|
1604
|
+
.map((row) => row.id);
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
export function reparentTopicChildren(
|
|
1608
|
+
deletedTopicId: string,
|
|
1609
|
+
replacementParentTopicId: string | null,
|
|
1610
|
+
): string[] {
|
|
1611
|
+
const rows = db
|
|
1612
|
+
.query<{ id: string }, string>("SELECT id FROM api_topics WHERE parent_topic_id = ?")
|
|
1613
|
+
.all(deletedTopicId);
|
|
1614
|
+
if (rows.length === 0) return [];
|
|
1615
|
+
db.query("UPDATE api_topics SET parent_topic_id = ? WHERE parent_topic_id = ?").run(
|
|
1616
|
+
replacementParentTopicId,
|
|
1617
|
+
deletedTopicId,
|
|
1618
|
+
);
|
|
1619
|
+
// Reparenting can move a topic out of the subtree whose manager granted its
|
|
1620
|
+
// tell edges; purge involved grants (fail closed) — an ancestor can re-grant.
|
|
1621
|
+
for (const row of rows) {
|
|
1622
|
+
db.query(
|
|
1623
|
+
"DELETE FROM subagent_tell_grants WHERE subagent_topic_id = ? OR target_topic_id = ?",
|
|
1624
|
+
).run(row.id, row.id);
|
|
1625
|
+
}
|
|
1626
|
+
return rows.map((row) => row.id);
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
export function addParticipantToDB(
|
|
1630
|
+
topicId: string,
|
|
1631
|
+
userId: string,
|
|
1632
|
+
role: "member" | "owner",
|
|
1633
|
+
): boolean {
|
|
1634
|
+
if (!db.query("SELECT 1 FROM api_topics WHERE id = ?").get(topicId)) return false;
|
|
1635
|
+
db.query("INSERT OR IGNORE INTO topic_members (topic_id,user_id,role) VALUES (?,?,?)").run(
|
|
1636
|
+
topicId,
|
|
1637
|
+
userId,
|
|
1638
|
+
role,
|
|
1639
|
+
);
|
|
1640
|
+
return true;
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
export function removeParticipantFromDB(topicId: string, userId: string): boolean {
|
|
1644
|
+
if (!db.query("SELECT 1 FROM api_topics WHERE id = ?").get(topicId)) return false;
|
|
1645
|
+
db.query("DELETE FROM topic_members WHERE topic_id = ? AND user_id = ?").run(topicId, userId);
|
|
1646
|
+
return true;
|
|
1647
|
+
}
|