@otium-team/negotium 0.0.0-stage → 0.23.11
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 +23903 -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 +2336 -0
- package/dist/browser-runtime.js.map +35 -0
- package/dist/canonical-mcp-bridge.js +14 -0
- package/dist/canonical-mcp-bridge.js.map +9 -0
- package/dist/chunk-0fenxbe6.js +173 -0
- package/dist/chunk-0fenxbe6.js.map +12 -0
- package/dist/chunk-2mx7fq49.js +6 -0
- package/dist/chunk-2mx7fq49.js.map +9 -0
- package/dist/chunk-ad7kxsaq.js +202 -0
- package/dist/chunk-ad7kxsaq.js.map +9 -0
- package/dist/chunk-da9ad838.js +3927 -0
- package/dist/chunk-da9ad838.js.map +47 -0
- package/dist/chunk-f7p0h1gs.js +54 -0
- package/dist/chunk-f7p0h1gs.js.map +10 -0
- package/dist/chunk-jtv8yzy1.js +206 -0
- package/dist/chunk-jtv8yzy1.js.map +10 -0
- package/dist/chunk-mxxwx5mg.js +375 -0
- package/dist/chunk-mxxwx5mg.js.map +13 -0
- package/dist/cron.js +1 -0
- package/dist/hosted-agent.js +5919 -0
- package/dist/hosted-agent.js.map +62 -0
- package/dist/main.js +60536 -0
- package/dist/main.js.map +338 -0
- package/dist/mcp-catalog.js +39 -0
- package/dist/mcp-catalog.js.map +10 -0
- package/dist/mcp-factories.js +26572 -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 +1073 -0
- package/dist/query-runtime.js.map +26 -0
- package/dist/registry.js +336 -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 +866 -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 +420 -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 +186 -0
- package/dist/runtime/src/application/vault-command.ts +170 -0
- package/dist/runtime/src/bus.ts +403 -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 +200 -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 +508 -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 +2284 -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 +848 -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-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 +805 -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 +582 -0
- package/dist/runtime/src/types.ts +395 -0
- package/dist/runtime/src/version.ts +1 -0
- package/dist/runtime/tsconfig.json +13 -0
- package/dist/runtime-gateway.js +453 -0
- package/dist/runtime-gateway.js.map +10 -0
- package/dist/runtime-helpers.js +1794 -0
- package/dist/runtime-helpers.js.map +40 -0
- package/dist/sqlite.js +68 -0
- package/dist/sqlite.js.map +10 -0
- package/dist/storage.js +5194 -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 +138 -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 +234 -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 +224 -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 +138 -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 +546 -0
- package/dist/types/packages/core/src/types.d.ts +384 -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 +850 -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,2336 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __require = import.meta.require;
|
|
3
|
+
|
|
4
|
+
// ../../packages/core/src/platform/playwright/browser-processes.ts
|
|
5
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
6
|
+
import { readdirSync, unlinkSync } from "fs";
|
|
7
|
+
import { createServer } from "net";
|
|
8
|
+
import { resolve as resolve4, sep } from "path";
|
|
9
|
+
|
|
10
|
+
// ../../packages/core/src/platform/config.ts
|
|
11
|
+
import { execFileSync } from "child_process";
|
|
12
|
+
import { randomBytes } from "crypto";
|
|
13
|
+
import {
|
|
14
|
+
accessSync,
|
|
15
|
+
chmodSync,
|
|
16
|
+
constants,
|
|
17
|
+
existsSync,
|
|
18
|
+
mkdirSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
writeFileSync
|
|
21
|
+
} from "fs";
|
|
22
|
+
import { createRequire } from "module";
|
|
23
|
+
import { homedir } from "os";
|
|
24
|
+
import { dirname, join, resolve } from "path";
|
|
25
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
26
|
+
|
|
27
|
+
// ../../packages/core/src/types.ts
|
|
28
|
+
var SUPPORTED_AGENTS = ["maestro", "claude", "codex"];
|
|
29
|
+
function isAgentKind(value) {
|
|
30
|
+
return typeof value === "string" && SUPPORTED_AGENTS.includes(value);
|
|
31
|
+
}
|
|
32
|
+
var EFFORT_VALUES = [
|
|
33
|
+
"low",
|
|
34
|
+
"medium",
|
|
35
|
+
"high",
|
|
36
|
+
"xhigh",
|
|
37
|
+
"max"
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
// ../../packages/core/src/platform/config-helpers.ts
|
|
41
|
+
function readEnvText(env, key) {
|
|
42
|
+
const value = env[key]?.trim();
|
|
43
|
+
return value || undefined;
|
|
44
|
+
}
|
|
45
|
+
function resolveFallbackAgent(env = process.env) {
|
|
46
|
+
const value = readEnvText(env, "FALLBACK_AGENT") ?? readEnvText(env, "DEFAULT_AGENT");
|
|
47
|
+
return isAgentKind(value) ? value : "claude";
|
|
48
|
+
}
|
|
49
|
+
function parseRuntimePort(value, fallback) {
|
|
50
|
+
if (!value)
|
|
51
|
+
return fallback;
|
|
52
|
+
const port = Number.parseInt(value, 10);
|
|
53
|
+
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : fallback;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ../../packages/core/src/platform/logger.ts
|
|
57
|
+
import pino from "pino";
|
|
58
|
+
function createStdioLogger(options = {}) {
|
|
59
|
+
const development = options.development ?? true;
|
|
60
|
+
return pino({
|
|
61
|
+
level: options.level ?? process.env.LOG_LEVEL ?? "info",
|
|
62
|
+
transport: development ? {
|
|
63
|
+
target: "pino-pretty",
|
|
64
|
+
options: {
|
|
65
|
+
colorize: true,
|
|
66
|
+
translateTime: "SYS:yyyy-mm-dd HH:MM:ss",
|
|
67
|
+
destination: 2
|
|
68
|
+
}
|
|
69
|
+
} : undefined
|
|
70
|
+
}, pino.destination(2));
|
|
71
|
+
}
|
|
72
|
+
var logger = createStdioLogger();
|
|
73
|
+
|
|
74
|
+
// ../../packages/core/src/platform/config.ts
|
|
75
|
+
function envText(envKey) {
|
|
76
|
+
return readEnvText(process.env, envKey);
|
|
77
|
+
}
|
|
78
|
+
var HOME = homedir();
|
|
79
|
+
function resolveStateDir() {
|
|
80
|
+
const configured = envText("NEGOTIUM_STATE_DIR");
|
|
81
|
+
if (false) {}
|
|
82
|
+
return configured ? resolve(configured) : resolve(HOME, ".negotium");
|
|
83
|
+
}
|
|
84
|
+
function resolveProjectRoot() {
|
|
85
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
86
|
+
const packagedRuntime = resolve(moduleDir, "runtime");
|
|
87
|
+
if (existsSync(resolve(packagedRuntime, "src")))
|
|
88
|
+
return packagedRuntime;
|
|
89
|
+
return resolve(moduleDir, "../..");
|
|
90
|
+
}
|
|
91
|
+
var PROJECT_ROOT = resolveProjectRoot();
|
|
92
|
+
function dependencyBinNames(name) {
|
|
93
|
+
if (process.platform !== "win32")
|
|
94
|
+
return [name];
|
|
95
|
+
return [name, `${name}.exe`, `${name}.cmd`, `${name}.bat`, `${name}.bunx`];
|
|
96
|
+
}
|
|
97
|
+
function resolveDependencyBin(name) {
|
|
98
|
+
let dir = PROJECT_ROOT;
|
|
99
|
+
while (true) {
|
|
100
|
+
const binDir = resolve(dir, "node_modules", ".bin");
|
|
101
|
+
for (const candidate of dependencyBinNames(name)) {
|
|
102
|
+
const path = resolve(binDir, candidate);
|
|
103
|
+
if (existsSync(path))
|
|
104
|
+
return path;
|
|
105
|
+
}
|
|
106
|
+
const parent = dirname(dir);
|
|
107
|
+
if (parent === dir)
|
|
108
|
+
return resolve(binDir, name);
|
|
109
|
+
dir = parent;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
var STATE_DIR = resolveStateDir();
|
|
113
|
+
function resolveLocalStateDir(envKey, stateName) {
|
|
114
|
+
const envValue = envText(envKey);
|
|
115
|
+
if (envValue)
|
|
116
|
+
return resolve(envValue);
|
|
117
|
+
return resolve(STATE_DIR, stateName);
|
|
118
|
+
}
|
|
119
|
+
function parsePortEnv(envValue, fallback) {
|
|
120
|
+
return parseRuntimePort(envValue, fallback);
|
|
121
|
+
}
|
|
122
|
+
var WORKSPACE_DIR = resolveLocalStateDir("NEGOTIUM_WORKSPACE_DIR", "workspace");
|
|
123
|
+
var TOPIC_WORKSPACE_DIR = resolve(WORKSPACE_DIR, "topics");
|
|
124
|
+
var SHARED_WIKI_DIR = resolve(WORKSPACE_DIR, "wiki");
|
|
125
|
+
var CRON_WORKSPACE_DIR = resolve(WORKSPACE_DIR, "cron");
|
|
126
|
+
var BROWSER_DIR = resolveLocalStateDir("NEGOTIUM_BROWSER_DIR", "browser");
|
|
127
|
+
var BROWSER_PROFILES_DIR = resolve(BROWSER_DIR, "profiles");
|
|
128
|
+
var BINARIES_DIR = resolve(STATE_DIR, "binaries");
|
|
129
|
+
var SECRETS_DIR = resolve(STATE_DIR, "secrets");
|
|
130
|
+
var DM_WORKSPACE_DIR = resolve(STATE_DIR, "data", "dm");
|
|
131
|
+
var SESSION_WORKSPACE_DIR = resolve(STATE_DIR, "data", "sessions");
|
|
132
|
+
var CLAUDE_EXECUTABLE_ENV = envText("NEGOTIUM_CLAUDE_EXECUTABLE");
|
|
133
|
+
var CLAUDE_EXECUTABLE = CLAUDE_EXECUTABLE_ENV ? resolve(CLAUDE_EXECUTABLE_ENV) : undefined;
|
|
134
|
+
var BINARY_EXTENSION = process.platform === "win32" ? ".exe" : "";
|
|
135
|
+
var BROWSER_RS_VERSION = "v0.7.7";
|
|
136
|
+
var BROWSER_RS_MIN_SECURE_VERSION = "0.2.1";
|
|
137
|
+
function versionAtLeast(actualVersion, minimumVersion) {
|
|
138
|
+
const actual = actualVersion.split(".").map(Number);
|
|
139
|
+
const minimum = minimumVersion.split(".").map(Number);
|
|
140
|
+
if (actual.some(Number.isNaN) || minimum.some(Number.isNaN))
|
|
141
|
+
return false;
|
|
142
|
+
for (let index = 0;index < minimum.length; index += 1) {
|
|
143
|
+
if ((actual[index] ?? 0) > (minimum[index] ?? 0))
|
|
144
|
+
return true;
|
|
145
|
+
if ((actual[index] ?? 0) < (minimum[index] ?? 0))
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
var BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15000;
|
|
151
|
+
function browserRsMeetsMinimumVersion(candidate) {
|
|
152
|
+
try {
|
|
153
|
+
const output = execFileSync(candidate, ["--version"], {
|
|
154
|
+
encoding: "utf8",
|
|
155
|
+
timeout: BROWSER_RS_VERSION_PROBE_TIMEOUT_MS,
|
|
156
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
157
|
+
windowsHide: true
|
|
158
|
+
}).trim();
|
|
159
|
+
const match = output.match(/^browser-rs (\d+)\.(\d+)\.(\d+)$/);
|
|
160
|
+
if (!match)
|
|
161
|
+
return false;
|
|
162
|
+
return versionAtLeast(match.slice(1).join("."), BROWSER_RS_MIN_SECURE_VERSION);
|
|
163
|
+
} catch {
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function resolveBrowserRsBin(envValue) {
|
|
168
|
+
const override = envValue?.trim();
|
|
169
|
+
if (!override && !versionAtLeast(BROWSER_RS_VERSION.replace(/^v/, ""), BROWSER_RS_MIN_SECURE_VERSION)) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
const candidate = override ? resolve(override) : resolve(BINARIES_DIR, "browser-rs", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`);
|
|
173
|
+
try {
|
|
174
|
+
accessSync(candidate, constants.X_OK);
|
|
175
|
+
return browserRsMeetsMinimumVersion(candidate) ? candidate : undefined;
|
|
176
|
+
} catch {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
var SNIPPETS_API_URL = (envText("NEGOTIUM_SNIPPETS_API_URL") ?? envText("SNIPPETS_API_URL") ?? "").replace(/\/+$/, "");
|
|
181
|
+
var BROWSER_RS_BIN = resolveBrowserRsBin(envText("NEGOTIUM_BROWSER_RS_BIN"));
|
|
182
|
+
var BASH_RS_VERSION = "v0.1.10";
|
|
183
|
+
function resolveBashRsBin(envValue) {
|
|
184
|
+
const override = envValue?.trim();
|
|
185
|
+
const candidate = override ? resolve(override) : resolve(BINARIES_DIR, "bash-rs", BASH_RS_VERSION, `bash-rs${BINARY_EXTENSION}`);
|
|
186
|
+
try {
|
|
187
|
+
accessSync(candidate, constants.X_OK);
|
|
188
|
+
return candidate;
|
|
189
|
+
} catch {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
var BASH_RS_BIN = resolveBashRsBin(envText("NEGOTIUM_BASH_RS_BIN"));
|
|
194
|
+
function resolveBrowserMcpBin(envValue) {
|
|
195
|
+
const override = envValue?.trim();
|
|
196
|
+
if (override)
|
|
197
|
+
return resolve(override);
|
|
198
|
+
return BROWSER_RS_BIN ?? resolve(BINARIES_DIR, "browser-rs", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`);
|
|
199
|
+
}
|
|
200
|
+
var PLAYWRIGHT_MCP_BIN = resolveBrowserMcpBin(envText("NEGOTIUM_BROWSER_MCP_BIN"));
|
|
201
|
+
function resolveBrowserProxy() {
|
|
202
|
+
const raw = envText("BROWSER_PROXY_URL");
|
|
203
|
+
if (!raw)
|
|
204
|
+
return null;
|
|
205
|
+
let url;
|
|
206
|
+
try {
|
|
207
|
+
url = new URL(raw);
|
|
208
|
+
} catch {
|
|
209
|
+
logger.warn({ raw }, "Ignoring malformed BROWSER_PROXY_URL");
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
const server = `${url.protocol}//${url.host}`;
|
|
213
|
+
const proxy = { server };
|
|
214
|
+
if (url.username)
|
|
215
|
+
proxy.username = decodeURIComponent(url.username);
|
|
216
|
+
if (url.password)
|
|
217
|
+
proxy.password = decodeURIComponent(url.password);
|
|
218
|
+
const bypass = envText("BROWSER_PROXY_BYPASS");
|
|
219
|
+
if (bypass)
|
|
220
|
+
proxy.bypass = bypass;
|
|
221
|
+
return proxy;
|
|
222
|
+
}
|
|
223
|
+
var TSX_BIN = resolveDependencyBin("tsx");
|
|
224
|
+
var TSX_LOADER_PATH = createRequire(import.meta.url).resolve("tsx");
|
|
225
|
+
var TSX_LOADER = process.platform === "win32" ? pathToFileURL(TSX_LOADER_PATH).href : TSX_LOADER_PATH;
|
|
226
|
+
var TSCONFIG_PATH = resolve(PROJECT_ROOT, "tsconfig.json");
|
|
227
|
+
var SESSION_COMM_SERVER = resolve(PROJECT_ROOT, "src/mcp/session-comm/server.ts");
|
|
228
|
+
var TASK_SERVER = resolve(PROJECT_ROOT, "src/mcp/task-server.ts");
|
|
229
|
+
var DECISION_SERVER = resolve(PROJECT_ROOT, "src/mcp/decision-server.ts");
|
|
230
|
+
var CANONICAL_MCP_PROXY_SERVER = resolve(PROJECT_ROOT, "src/mcp/canonical-proxy-server.ts");
|
|
231
|
+
var WIKI_SERVER = resolve(PROJECT_ROOT, "src/mcp/wiki-server.ts");
|
|
232
|
+
var TOKEN_STATS_SERVER = resolve(PROJECT_ROOT, "src/mcp/token-stats-server.ts");
|
|
233
|
+
var COMPACTION_LOG_SERVER = resolve(PROJECT_ROOT, "src/mcp/compaction-log-server.ts");
|
|
234
|
+
var SESSION_HISTORY_SERVER = resolve(PROJECT_ROOT, "src/mcp/session-history-server.ts");
|
|
235
|
+
var SYSTEM_HEALTH_SERVER = resolve(PROJECT_ROOT, "src/mcp/system-health-server.ts");
|
|
236
|
+
var AGENT_HEALTH_SERVER = resolve(PROJECT_ROOT, "src/mcp/agent-health-server.ts");
|
|
237
|
+
var VAULT_SERVER = resolve(PROJECT_ROOT, "src/mcp/vault-server.ts");
|
|
238
|
+
var BG_BASH_BASE_PORT = parsePortEnv(process.env.BG_BASH_BASE_PORT, 9700);
|
|
239
|
+
var BG_BASH_MAX_PORT = parsePortEnv(process.env.BG_BASH_MAX_PORT, 9799);
|
|
240
|
+
function loadOrCreateLocalSecret(envKey, filename, options = {}) {
|
|
241
|
+
const envValue = envText(envKey);
|
|
242
|
+
const secretFile = resolve(SECRETS_DIR, filename);
|
|
243
|
+
mkdirSync(dirname(secretFile), { recursive: true });
|
|
244
|
+
if (envValue) {
|
|
245
|
+
if (options.persistEnvValue) {
|
|
246
|
+
writeFileSync(secretFile, `${envValue}
|
|
247
|
+
`, { mode: 384 });
|
|
248
|
+
chmodSync(secretFile, 384);
|
|
249
|
+
}
|
|
250
|
+
return envValue;
|
|
251
|
+
}
|
|
252
|
+
if (existsSync(secretFile)) {
|
|
253
|
+
const stored = readFileSync(secretFile, "utf-8").trim();
|
|
254
|
+
if (stored) {
|
|
255
|
+
chmodSync(secretFile, 384);
|
|
256
|
+
return stored;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const secret = randomBytes(32).toString("base64url");
|
|
260
|
+
try {
|
|
261
|
+
writeFileSync(secretFile, `${secret}
|
|
262
|
+
`, { mode: 384, flag: "wx" });
|
|
263
|
+
return secret;
|
|
264
|
+
} catch (error) {
|
|
265
|
+
if (error.code !== "EEXIST")
|
|
266
|
+
throw error;
|
|
267
|
+
const stored = readFileSync(secretFile, "utf-8").trim();
|
|
268
|
+
if (!stored)
|
|
269
|
+
throw new Error(`Secret file exists but is empty: ${secretFile}`);
|
|
270
|
+
chmodSync(secretFile, 384);
|
|
271
|
+
return stored;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
var RUNTIME_MCP_SECRET = loadOrCreateLocalSecret("RUNTIME_MCP_SECRET", "runtime-mcp-secret");
|
|
275
|
+
var NODE_CONTROL_TOKEN = loadOrCreateLocalSecret("NEGOTIUM_CONTROL_TOKEN", "node-control-token");
|
|
276
|
+
var NODE_ID = loadOrCreateLocalSecret("NEGOTIUM_NODE_ID", "node-id");
|
|
277
|
+
var VAULT_MASTER_KEY = loadOrCreateLocalSecret("NEGOTIUM_VAULT_MASTER_KEY", "vault-master-key", { persistEnvValue: true });
|
|
278
|
+
delete process.env.NEGOTIUM_VAULT_MASTER_KEY;
|
|
279
|
+
var NEGOTIUM_PORT = parseInt(process.env.NEGOTIUM_PORT || "7777", 10);
|
|
280
|
+
var hostname = process.env.HOSTNAME || "127.0.0.1";
|
|
281
|
+
var DATA_DIR = resolveLocalStateDir("NEGOTIUM_DATA_DIR", "data");
|
|
282
|
+
var LOG_DIR = resolveLocalStateDir("NEGOTIUM_LOG_DIR", "logs");
|
|
283
|
+
var UPLOADS_DIR = resolve(DATA_DIR, "uploads");
|
|
284
|
+
var VAULT_DIR = resolve(DATA_DIR, "vault");
|
|
285
|
+
var SESSIONS_DB = process.env.SESSIONS_DB_PATH ? resolve(process.env.SESSIONS_DB_PATH) : resolve(DATA_DIR, "sessions.db");
|
|
286
|
+
var DEBUG_FILE = resolve(DATA_DIR, "debug-users.json");
|
|
287
|
+
var USERS_LOG_DIR = resolve(DATA_DIR, "users");
|
|
288
|
+
var RUN_DIR = resolveLocalStateDir("NEGOTIUM_RUN_DIR", "runtime");
|
|
289
|
+
var PROGRESS_DIR = resolve(RUN_DIR, "progress");
|
|
290
|
+
var DM_CMD_DIR = resolve(RUN_DIR, "dm-commands");
|
|
291
|
+
var DM_RESP_DIR = resolve(RUN_DIR, "dm-responses");
|
|
292
|
+
var SESSION_INBOX_DIR = resolve(RUN_DIR, "session-inbox");
|
|
293
|
+
var SESSION_ASKS_DIR = resolve(RUN_DIR, "session-asks");
|
|
294
|
+
var BASHRS_SPILL_ROOT = resolve(RUN_DIR, "bashrs");
|
|
295
|
+
var PLAYWRIGHT_BASE_PORT = parsePortEnv(process.env.PLAYWRIGHT_BASE_PORT, 9100);
|
|
296
|
+
var PLAYWRIGHT_MAX_PORT = parsePortEnv(process.env.PLAYWRIGHT_MAX_PORT, 9499);
|
|
297
|
+
var PLAYWRIGHT_PORTS_DIR = resolve(RUN_DIR, "playwright-ports");
|
|
298
|
+
mkdirSync(STATE_DIR, { recursive: true });
|
|
299
|
+
mkdirSync(DATA_DIR, { recursive: true });
|
|
300
|
+
mkdirSync(UPLOADS_DIR, { recursive: true });
|
|
301
|
+
mkdirSync(VAULT_DIR, { recursive: true, mode: 448 });
|
|
302
|
+
mkdirSync(LOG_DIR, { recursive: true });
|
|
303
|
+
mkdirSync(PROGRESS_DIR, { recursive: true });
|
|
304
|
+
mkdirSync(DM_CMD_DIR, { recursive: true });
|
|
305
|
+
mkdirSync(DM_RESP_DIR, { recursive: true });
|
|
306
|
+
mkdirSync(SESSION_INBOX_DIR, { recursive: true });
|
|
307
|
+
mkdirSync(SESSION_ASKS_DIR, { recursive: true });
|
|
308
|
+
mkdirSync(PLAYWRIGHT_PORTS_DIR, { recursive: true });
|
|
309
|
+
mkdirSync(WORKSPACE_DIR, { recursive: true });
|
|
310
|
+
mkdirSync(TOPIC_WORKSPACE_DIR, { recursive: true });
|
|
311
|
+
mkdirSync(SHARED_WIKI_DIR, { recursive: true });
|
|
312
|
+
mkdirSync(CRON_WORKSPACE_DIR, { recursive: true });
|
|
313
|
+
mkdirSync(DM_WORKSPACE_DIR, { recursive: true });
|
|
314
|
+
mkdirSync(SESSION_WORKSPACE_DIR, { recursive: true });
|
|
315
|
+
mkdirSync(BROWSER_DIR, { recursive: true });
|
|
316
|
+
mkdirSync(BROWSER_PROFILES_DIR, { recursive: true });
|
|
317
|
+
mkdirSync(BINARIES_DIR, { recursive: true });
|
|
318
|
+
mkdirSync(SECRETS_DIR, { recursive: true, mode: 448 });
|
|
319
|
+
var ACTIVE_QUERY_STALE_MS = 10 * 60 * 1000;
|
|
320
|
+
var AGENTS_PROMPTS_DIR = resolve(PROJECT_ROOT, "src/prompts/agents");
|
|
321
|
+
var RESOURCES_DIR = resolve(PROJECT_ROOT, "src/resources");
|
|
322
|
+
var ABSOLUTE_PATH_PREFIX = String.raw`(?:[A-Za-z]:[\\/]|\\\\|\/)`;
|
|
323
|
+
var FILE_EXTENSIONS_REGEX = new RegExp(`(?:${ABSOLUTE_PATH_PREFIX}[^\\s"'<>|*?[\\]]+\\.(?:png|jpg|jpeg|gif|webp|svg|pdf|csv|xlsx|xls|json|txt|md|html|zip|py|js|ts|tsx|jsx|css|xml|yaml|yml|docx|pptx))`, "gi");
|
|
324
|
+
var FILE_TAG_REGEX = new RegExp(`\\[FILE:(${ABSOLUTE_PATH_PREFIX}[^\\]]+)\\]`, "gi");
|
|
325
|
+
var FALLBACK_AGENT = resolveFallbackAgent(process.env);
|
|
326
|
+
var FALLBACK_MODEL = envText("FALLBACK_MODEL") ?? envText("DEFAULT_MODEL");
|
|
327
|
+
var DEFAULT_TOPIC_EFFORT = (() => {
|
|
328
|
+
const raw = envText("NEGOTIUM_DEFAULT_EFFORT")?.toLowerCase();
|
|
329
|
+
return raw && EFFORT_VALUES.includes(raw) ? raw : "medium";
|
|
330
|
+
})();
|
|
331
|
+
var FFMPEG_BIN = envText("FFMPEG_BIN");
|
|
332
|
+
var FFPROBE_BIN = envText("FFPROBE_BIN");
|
|
333
|
+
var PYTHON_BIN = envText("PYTHON_BIN") ?? "python3";
|
|
334
|
+
var FASTER_WHISPER_WRAPPER = envText("FASTER_WHISPER_WRAPPER") ?? resolve(PROJECT_ROOT, "scripts/faster-whisper-wrapper.py");
|
|
335
|
+
var WHISPER_MODEL = envText("WHISPER_MODEL_FILE") ?? "turbo";
|
|
336
|
+
var TESSERACT_BIN = envText("TESSERACT_BIN") ?? "tesseract";
|
|
337
|
+
var PDFTOTEXT_BIN = envText("PDFTOTEXT_BIN") ?? "pdftotext";
|
|
338
|
+
function resolveWhisperBackend() {
|
|
339
|
+
return envText("WHISPER_BACKEND") === "mlx-whisper" ? "mlx-whisper" : "faster-whisper";
|
|
340
|
+
}
|
|
341
|
+
var WHISPER_BACKEND = resolveWhisperBackend();
|
|
342
|
+
var MLX_WHISPER_BIN = envText("MLX_WHISPER_BIN");
|
|
343
|
+
var WHISPER_MODEL_MLX = envText("WHISPER_MODEL_MLX") ?? "mlx-community/whisper-large-v3-turbo";
|
|
344
|
+
var _envMaxTellDepth = Number.parseInt(process.env.MAX_TELL_DEPTH ?? "", 10);
|
|
345
|
+
var MAX_TELL_DEPTH = Number.isInteger(_envMaxTellDepth) && _envMaxTellDepth > 0 ? _envMaxTellDepth : 20;
|
|
346
|
+
|
|
347
|
+
// ../../packages/core/src/platform/playwright/manager-utils.ts
|
|
348
|
+
import { resolve as resolve2 } from "path";
|
|
349
|
+
function isLiveOwnedChildProcess(current, expected) {
|
|
350
|
+
return current?.process === expected && expected.exitCode === null && expected.signalCode === null && !expected.killed;
|
|
351
|
+
}
|
|
352
|
+
function matchesSpawnedBrowserHealth(health, expectedSpawnNonce) {
|
|
353
|
+
if (!health || typeof health !== "object")
|
|
354
|
+
return false;
|
|
355
|
+
const candidate = health;
|
|
356
|
+
return candidate.ok === true && candidate.name === "negotium-browser-gateway" && candidate.spawnNonce === expectedSpawnNonce;
|
|
357
|
+
}
|
|
358
|
+
function browserCdpIsLost(health) {
|
|
359
|
+
if (!health || typeof health !== "object")
|
|
360
|
+
return false;
|
|
361
|
+
const browser = health.browser;
|
|
362
|
+
if (!browser || typeof browser !== "object")
|
|
363
|
+
return false;
|
|
364
|
+
const candidate = browser;
|
|
365
|
+
return candidate.launched === true && candidate.connected === false;
|
|
366
|
+
}
|
|
367
|
+
function selectIdleEvictionKey(candidates, pinnedKeys, busyKeys, now, maxIdleMs) {
|
|
368
|
+
const pinned = new Set(pinnedKeys);
|
|
369
|
+
const busy = new Set(busyKeys);
|
|
370
|
+
let oldest = null;
|
|
371
|
+
for (const [key, instance] of candidates) {
|
|
372
|
+
if (pinned.has(key) || busy.has(key))
|
|
373
|
+
continue;
|
|
374
|
+
if (now - instance.lastUsedAt < maxIdleMs)
|
|
375
|
+
continue;
|
|
376
|
+
if (!oldest || instance.lastUsedAt < oldest.lastUsedAt) {
|
|
377
|
+
oldest = { key, lastUsedAt: instance.lastUsedAt };
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return oldest?.key ?? null;
|
|
381
|
+
}
|
|
382
|
+
function selectReusablePort(minPort, maxPort, reservedPorts, isOccupied) {
|
|
383
|
+
for (let port = minPort;port <= maxPort; port++) {
|
|
384
|
+
if (reservedPorts.has(port) || isOccupied(port))
|
|
385
|
+
continue;
|
|
386
|
+
return port;
|
|
387
|
+
}
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
function extractUserDataDirArg(cmdline) {
|
|
391
|
+
const match = cmdline.match(/--user-data-dir(?:\s+|=)(\S+)/);
|
|
392
|
+
return match ? match[1] : null;
|
|
393
|
+
}
|
|
394
|
+
function browserProcessMatchesExpectedProfile(cmdline, expectedUserDataDir) {
|
|
395
|
+
const actualUserDataDir = extractUserDataDirArg(cmdline);
|
|
396
|
+
return actualUserDataDir !== null && resolve2(actualUserDataDir) === resolve2(expectedUserDataDir);
|
|
397
|
+
}
|
|
398
|
+
function waitForChildProcessExit(proc, timeoutMs) {
|
|
399
|
+
if (proc.exitCode !== null || proc.signalCode !== null)
|
|
400
|
+
return Promise.resolve(true);
|
|
401
|
+
return new Promise((resolveWait) => {
|
|
402
|
+
let settled = false;
|
|
403
|
+
let timer;
|
|
404
|
+
const finish = (exited) => {
|
|
405
|
+
if (settled)
|
|
406
|
+
return;
|
|
407
|
+
settled = true;
|
|
408
|
+
clearTimeout(timer);
|
|
409
|
+
proc.off("exit", onExit);
|
|
410
|
+
resolveWait(exited);
|
|
411
|
+
};
|
|
412
|
+
const onExit = () => finish(true);
|
|
413
|
+
proc.once("exit", onExit);
|
|
414
|
+
timer = setTimeout(() => finish(proc.exitCode !== null || proc.signalCode !== null), timeoutMs);
|
|
415
|
+
if (typeof timer === "object")
|
|
416
|
+
timer.unref?.();
|
|
417
|
+
if (proc.exitCode !== null || proc.signalCode !== null)
|
|
418
|
+
finish(true);
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
function waitForChildProcessSpawnError(proc) {
|
|
422
|
+
return new Promise((_resolve, reject) => {
|
|
423
|
+
proc.once("error", reject);
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// ../../packages/core/src/storage/storage-host.ts
|
|
428
|
+
import { mkdirSync as mkdirSync2 } from "fs";
|
|
429
|
+
import { homedir as homedir2 } from "os";
|
|
430
|
+
import { dirname as dirname2, join as join2, resolve as resolve3 } from "path";
|
|
431
|
+
|
|
432
|
+
// ../../packages/core/src/storage/sqlite.ts
|
|
433
|
+
var isBun = typeof process.versions.bun === "string";
|
|
434
|
+
var Database;
|
|
435
|
+
if (isBun) {
|
|
436
|
+
({ Database } = await import("bun:sqlite"));
|
|
437
|
+
} else {
|
|
438
|
+
const nodeSqliteSpecifier = ["node", "sqlite"].join(":");
|
|
439
|
+
const { DatabaseSync } = await import(nodeSqliteSpecifier);
|
|
440
|
+
|
|
441
|
+
class NodeDatabase {
|
|
442
|
+
#db;
|
|
443
|
+
constructor(path, options = {}) {
|
|
444
|
+
this.#db = options.readonly ? new DatabaseSync(path, { readOnly: true }) : new DatabaseSync(path);
|
|
445
|
+
}
|
|
446
|
+
query(sql) {
|
|
447
|
+
return this.#db.prepare(sql);
|
|
448
|
+
}
|
|
449
|
+
prepare(sql) {
|
|
450
|
+
return this.#db.prepare(sql);
|
|
451
|
+
}
|
|
452
|
+
exec(sql) {
|
|
453
|
+
this.#db.exec(sql);
|
|
454
|
+
}
|
|
455
|
+
run(sql, ...params) {
|
|
456
|
+
return this.#db.prepare(sql).run(...params);
|
|
457
|
+
}
|
|
458
|
+
transaction(fn) {
|
|
459
|
+
const run = (begin) => (...args) => {
|
|
460
|
+
this.#db.exec(begin);
|
|
461
|
+
try {
|
|
462
|
+
const result = fn(...args);
|
|
463
|
+
this.#db.exec("COMMIT");
|
|
464
|
+
return result;
|
|
465
|
+
} catch (err) {
|
|
466
|
+
this.#db.exec("ROLLBACK");
|
|
467
|
+
throw err;
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
const tx = run("BEGIN");
|
|
471
|
+
tx.deferred = run("BEGIN DEFERRED");
|
|
472
|
+
tx.immediate = run("BEGIN IMMEDIATE");
|
|
473
|
+
tx.exclusive = run("BEGIN EXCLUSIVE");
|
|
474
|
+
return tx;
|
|
475
|
+
}
|
|
476
|
+
close() {
|
|
477
|
+
this.#db.close();
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
Database = NodeDatabase;
|
|
481
|
+
}
|
|
482
|
+
function closeDatabase(database) {
|
|
483
|
+
try {
|
|
484
|
+
database.close(true);
|
|
485
|
+
} catch {
|
|
486
|
+
try {
|
|
487
|
+
database.close();
|
|
488
|
+
} catch {}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// ../../packages/core/src/storage/storage-host.ts
|
|
493
|
+
var STORAGE_HOST_STATE = Symbol.for("negotium.storage-host.state.v1");
|
|
494
|
+
function storageState() {
|
|
495
|
+
const holder = globalThis;
|
|
496
|
+
const existing = holder[STORAGE_HOST_STATE];
|
|
497
|
+
if (existing)
|
|
498
|
+
return existing;
|
|
499
|
+
const created = {
|
|
500
|
+
configuredHost: {},
|
|
501
|
+
fallbackDatabase: null,
|
|
502
|
+
fallbackDatabasePath: null,
|
|
503
|
+
frames: [],
|
|
504
|
+
schemaInitializers: [],
|
|
505
|
+
initializedSchemas: new WeakMap,
|
|
506
|
+
initializingDatabases: new WeakSet
|
|
507
|
+
};
|
|
508
|
+
Object.defineProperty(holder, STORAGE_HOST_STATE, {
|
|
509
|
+
value: created,
|
|
510
|
+
enumerable: false,
|
|
511
|
+
writable: false,
|
|
512
|
+
configurable: false
|
|
513
|
+
});
|
|
514
|
+
return created;
|
|
515
|
+
}
|
|
516
|
+
function envPath(name, fallback) {
|
|
517
|
+
const value = process.env[name]?.trim();
|
|
518
|
+
return resolve3(value || fallback);
|
|
519
|
+
}
|
|
520
|
+
function defaultStateDir() {
|
|
521
|
+
return envPath("NEGOTIUM_STATE_DIR", join2(homedir2(), ".negotium"));
|
|
522
|
+
}
|
|
523
|
+
function defaultDataDir() {
|
|
524
|
+
return envPath("NEGOTIUM_DATA_DIR", join2(defaultStateDir(), "data"));
|
|
525
|
+
}
|
|
526
|
+
function defaultSessionsDatabasePath() {
|
|
527
|
+
return envPath("SESSIONS_DB_PATH", join2(resolveStorageDataDir(), "sessions.db"));
|
|
528
|
+
}
|
|
529
|
+
var SQLITE_INIT_RETRY_MS = 25;
|
|
530
|
+
var SQLITE_INIT_TIMEOUT_MS = 5000;
|
|
531
|
+
var SQLITE_INIT_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
532
|
+
function isSqliteBusy(error) {
|
|
533
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
534
|
+
return /database is (?:locked|busy)|SQLITE_(?:BUSY|LOCKED)/i.test(message);
|
|
535
|
+
}
|
|
536
|
+
function execWithBusyRetry(database, sql, timeoutMs = SQLITE_INIT_TIMEOUT_MS) {
|
|
537
|
+
const deadline = Date.now() + timeoutMs;
|
|
538
|
+
while (true) {
|
|
539
|
+
try {
|
|
540
|
+
database.exec(sql);
|
|
541
|
+
return;
|
|
542
|
+
} catch (error) {
|
|
543
|
+
if (!isSqliteBusy(error) || Date.now() >= deadline)
|
|
544
|
+
throw error;
|
|
545
|
+
Atomics.wait(SQLITE_INIT_SLEEP, 0, 0, Math.min(SQLITE_INIT_RETRY_MS, deadline - Date.now()));
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
function initializeDatabase(database) {
|
|
550
|
+
database.exec("PRAGMA busy_timeout = 5000");
|
|
551
|
+
execWithBusyRetry(database, "PRAGMA journal_mode = WAL");
|
|
552
|
+
database.exec("PRAGMA foreign_keys = ON");
|
|
553
|
+
database.exec("PRAGMA wal_autocheckpoint = 1000");
|
|
554
|
+
try {
|
|
555
|
+
database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
556
|
+
} catch {}
|
|
557
|
+
}
|
|
558
|
+
function defaultDatabase() {
|
|
559
|
+
const path = defaultSessionsDatabasePath();
|
|
560
|
+
const state = storageState();
|
|
561
|
+
if (state.fallbackDatabase && state.fallbackDatabasePath === path)
|
|
562
|
+
return state.fallbackDatabase;
|
|
563
|
+
if (state.fallbackDatabase)
|
|
564
|
+
closeDatabase(state.fallbackDatabase);
|
|
565
|
+
mkdirSync2(dirname2(path), { recursive: true });
|
|
566
|
+
state.fallbackDatabase = new Database(path, { create: true });
|
|
567
|
+
state.fallbackDatabasePath = path;
|
|
568
|
+
initializeDatabase(state.fallbackDatabase);
|
|
569
|
+
return state.fallbackDatabase;
|
|
570
|
+
}
|
|
571
|
+
function resolveStorageDatabase() {
|
|
572
|
+
return storageState().configuredHost.database ?? defaultDatabase();
|
|
573
|
+
}
|
|
574
|
+
function resolveStorageDataDir() {
|
|
575
|
+
return storageState().configuredHost.dataDir ?? defaultDataDir();
|
|
576
|
+
}
|
|
577
|
+
function registerStorageSchemaInitializer(initialize, priority = 100) {
|
|
578
|
+
const initializers = storageState().schemaInitializers;
|
|
579
|
+
initializers.push({ initialize, priority });
|
|
580
|
+
initializers.sort((a, b) => a.priority - b.priority);
|
|
581
|
+
}
|
|
582
|
+
function ensureStorageSchemas(database = resolveStorageDatabase()) {
|
|
583
|
+
const state = storageState();
|
|
584
|
+
if (state.initializingDatabases.has(database))
|
|
585
|
+
return;
|
|
586
|
+
let initialized = state.initializedSchemas.get(database);
|
|
587
|
+
if (!initialized) {
|
|
588
|
+
initialized = new Set;
|
|
589
|
+
state.initializedSchemas.set(database, initialized);
|
|
590
|
+
}
|
|
591
|
+
state.initializingDatabases.add(database);
|
|
592
|
+
try {
|
|
593
|
+
for (const entry of state.schemaInitializers) {
|
|
594
|
+
if (initialized.has(entry.initialize))
|
|
595
|
+
continue;
|
|
596
|
+
initialized.add(entry.initialize);
|
|
597
|
+
try {
|
|
598
|
+
entry.initialize(database);
|
|
599
|
+
} catch (error) {
|
|
600
|
+
initialized.delete(entry.initialize);
|
|
601
|
+
throw error;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
} finally {
|
|
605
|
+
state.initializingDatabases.delete(database);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
var internalStorageDatabase = new Proxy({}, {
|
|
609
|
+
get(_target, property) {
|
|
610
|
+
const database = resolveStorageDatabase();
|
|
611
|
+
ensureStorageSchemas(database);
|
|
612
|
+
const value = Reflect.get(database, property, database);
|
|
613
|
+
return typeof value === "function" ? value.bind(database) : value;
|
|
614
|
+
},
|
|
615
|
+
set(_target, property, value) {
|
|
616
|
+
const database = resolveStorageDatabase();
|
|
617
|
+
ensureStorageSchemas(database);
|
|
618
|
+
return Reflect.set(database, property, value, database);
|
|
619
|
+
}
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
// ../../packages/core/src/storage/forum-db.ts
|
|
623
|
+
var db = internalStorageDatabase;
|
|
624
|
+
|
|
625
|
+
// ../../packages/core/src/storage/runtime-leases.ts
|
|
626
|
+
import { randomUUID } from "crypto";
|
|
627
|
+
|
|
628
|
+
// ../../packages/core/src/storage/runtime-topic-state.ts
|
|
629
|
+
registerStorageSchemaInitializer((database) => {
|
|
630
|
+
database.exec(`
|
|
631
|
+
CREATE TABLE IF NOT EXISTS runtime_topic_state (
|
|
632
|
+
topic_id TEXT PRIMARY KEY,
|
|
633
|
+
epoch INTEGER NOT NULL DEFAULT 0,
|
|
634
|
+
maintenance INTEGER NOT NULL DEFAULT 0 CHECK (maintenance IN (0, 1)),
|
|
635
|
+
maintenance_owner TEXT,
|
|
636
|
+
heartbeat_at INTEGER
|
|
637
|
+
)
|
|
638
|
+
`);
|
|
639
|
+
}, 32);
|
|
640
|
+
var maintenanceReleasedListeners = new Set;
|
|
641
|
+
|
|
642
|
+
// ../../packages/core/src/storage/runtime-leases.ts
|
|
643
|
+
var RUNTIME_INSTANCE_ID = `${process.pid}-${randomUUID()}`;
|
|
644
|
+
registerStorageSchemaInitializer((database) => {
|
|
645
|
+
database.exec(`
|
|
646
|
+
CREATE TABLE IF NOT EXISTS runtime_turn_leases (
|
|
647
|
+
topic_id TEXT PRIMARY KEY,
|
|
648
|
+
query_id TEXT NOT NULL UNIQUE,
|
|
649
|
+
owner_id TEXT NOT NULL,
|
|
650
|
+
origin TEXT NOT NULL,
|
|
651
|
+
started_at INTEGER NOT NULL,
|
|
652
|
+
heartbeat_at INTEGER NOT NULL,
|
|
653
|
+
abort_requested INTEGER NOT NULL DEFAULT 0 CHECK (abort_requested IN (0, 1)),
|
|
654
|
+
abort_reason TEXT CHECK (abort_reason IS NULL OR abort_reason IN ('internal', 'external'))
|
|
655
|
+
);
|
|
656
|
+
CREATE INDEX IF NOT EXISTS idx_runtime_turn_leases_heartbeat ON runtime_turn_leases(heartbeat_at);
|
|
657
|
+
`);
|
|
658
|
+
}, 33);
|
|
659
|
+
|
|
660
|
+
// ../../packages/core/src/storage/runtime-process-leases.ts
|
|
661
|
+
var PROCESS_LEASE_STALE_MS = 5000;
|
|
662
|
+
registerStorageSchemaInitializer((database) => {
|
|
663
|
+
database.exec(`
|
|
664
|
+
CREATE TABLE IF NOT EXISTS runtime_process_leases (
|
|
665
|
+
role TEXT PRIMARY KEY,
|
|
666
|
+
owner_id TEXT NOT NULL UNIQUE,
|
|
667
|
+
pid INTEGER NOT NULL,
|
|
668
|
+
started_at INTEGER NOT NULL,
|
|
669
|
+
heartbeat_at INTEGER NOT NULL
|
|
670
|
+
);
|
|
671
|
+
CREATE INDEX IF NOT EXISTS idx_runtime_process_leases_heartbeat ON runtime_process_leases(heartbeat_at);
|
|
672
|
+
`);
|
|
673
|
+
}, 34);
|
|
674
|
+
function rowToLease(row) {
|
|
675
|
+
return {
|
|
676
|
+
role: row.role,
|
|
677
|
+
ownerId: row.owner_id,
|
|
678
|
+
pid: Number(row.pid),
|
|
679
|
+
startedAt: Number(row.started_at),
|
|
680
|
+
heartbeatAt: Number(row.heartbeat_at)
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
function getRuntimeProcessLease(role, now = Date.now(), staleMs = PROCESS_LEASE_STALE_MS) {
|
|
684
|
+
const row = db.query("SELECT * FROM runtime_process_leases WHERE role = ?").get(role);
|
|
685
|
+
if (!row)
|
|
686
|
+
return null;
|
|
687
|
+
const lease = rowToLease(row);
|
|
688
|
+
return now - lease.heartbeatAt <= staleMs ? lease : null;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// ../../packages/core/src/platform/playwright/browser-processes.ts
|
|
692
|
+
function isPortInUse(port) {
|
|
693
|
+
return new Promise((resolveProbe) => {
|
|
694
|
+
const server = createServer();
|
|
695
|
+
let settled = false;
|
|
696
|
+
const finish = (occupied) => {
|
|
697
|
+
if (settled)
|
|
698
|
+
return;
|
|
699
|
+
settled = true;
|
|
700
|
+
server.removeAllListeners();
|
|
701
|
+
resolveProbe(occupied);
|
|
702
|
+
};
|
|
703
|
+
server.unref();
|
|
704
|
+
server.once("error", () => finish(true));
|
|
705
|
+
server.listen({ host: "127.0.0.1", port, exclusive: true }, () => {
|
|
706
|
+
server.close((error) => finish(error !== undefined));
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
async function reserveAvailableLoopbackPort(minPort, maxPort, reservedPorts, probeOccupied = isPortInUse) {
|
|
711
|
+
for (let port = minPort;port <= maxPort; port++) {
|
|
712
|
+
if (reservedPorts.has(port))
|
|
713
|
+
continue;
|
|
714
|
+
reservedPorts.add(port);
|
|
715
|
+
if (await probeOccupied(port)) {
|
|
716
|
+
reservedPorts.delete(port);
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
return port;
|
|
720
|
+
}
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
function killBrowserProcsForUserDataDir(userDataDir) {
|
|
724
|
+
const target = resolve4(userDataDir);
|
|
725
|
+
const profileRoot = resolve4(BROWSER_PROFILES_DIR);
|
|
726
|
+
if (target !== profileRoot && !target.startsWith(`${profileRoot}${sep}`))
|
|
727
|
+
return;
|
|
728
|
+
let pids;
|
|
729
|
+
try {
|
|
730
|
+
pids = execFileSync2("pgrep", ["-f", "--", userDataDir], { stdio: "pipe" }).toString().trim();
|
|
731
|
+
} catch {
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (!pids)
|
|
735
|
+
return;
|
|
736
|
+
for (const pid of pids.split(`
|
|
737
|
+
`)) {
|
|
738
|
+
const pidNum = parseInt(pid.trim(), 10);
|
|
739
|
+
if (Number.isNaN(pidNum) || pidNum === process.pid)
|
|
740
|
+
continue;
|
|
741
|
+
try {
|
|
742
|
+
const cmdline = execFileSync2("ps", ["-p", String(pidNum), "-o", "command="], {
|
|
743
|
+
stdio: "pipe"
|
|
744
|
+
}).toString().trim();
|
|
745
|
+
const argDir = extractUserDataDirArg(cmdline);
|
|
746
|
+
if (!argDir || resolve4(argDir) !== target)
|
|
747
|
+
continue;
|
|
748
|
+
killProcessTreeChildren(pidNum);
|
|
749
|
+
process.kill(pidNum, "SIGKILL");
|
|
750
|
+
logger.info({ pid: pidNum, userDataDir }, "Reaped orphaned browser process by user-data-dir");
|
|
751
|
+
} catch (e) {
|
|
752
|
+
logger.debug({ err: e, pid: pidNum, userDataDir }, "Failed to reap browser proc by dir");
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
function selectOrphanBrowserPids(procs, liveUserDataDirs, profileRoot, selfPid) {
|
|
757
|
+
const root = resolve4(profileRoot);
|
|
758
|
+
const live = new Set([...liveUserDataDirs].map((d) => resolve4(d)));
|
|
759
|
+
const out = [];
|
|
760
|
+
for (const { pid, userDataDir } of procs) {
|
|
761
|
+
if (pid === selfPid || !userDataDir)
|
|
762
|
+
continue;
|
|
763
|
+
const dir = resolve4(userDataDir);
|
|
764
|
+
if (dir !== root && !dir.startsWith(`${root}${sep}`))
|
|
765
|
+
continue;
|
|
766
|
+
if (live.has(dir))
|
|
767
|
+
continue;
|
|
768
|
+
out.push(pid);
|
|
769
|
+
}
|
|
770
|
+
return out;
|
|
771
|
+
}
|
|
772
|
+
function isBrowserJanitorOwner(leaseOwnerPid, selfPid) {
|
|
773
|
+
return leaseOwnerPid === selfPid;
|
|
774
|
+
}
|
|
775
|
+
function reapOrphanBrowsers(liveUserDataDirs) {
|
|
776
|
+
const daemonLease = getRuntimeProcessLease("node-daemon", Date.now(), Number.POSITIVE_INFINITY);
|
|
777
|
+
if (!isBrowserJanitorOwner(daemonLease?.pid ?? null, process.pid))
|
|
778
|
+
return;
|
|
779
|
+
const profileRoot = resolve4(BROWSER_PROFILES_DIR);
|
|
780
|
+
let pids;
|
|
781
|
+
try {
|
|
782
|
+
pids = execFileSync2("pgrep", ["-f", "--", profileRoot], { stdio: "pipe" }).toString().trim();
|
|
783
|
+
} catch {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (!pids)
|
|
787
|
+
return;
|
|
788
|
+
const procs = [];
|
|
789
|
+
for (const pid of pids.split(`
|
|
790
|
+
`)) {
|
|
791
|
+
const pidNum = parseInt(pid.trim(), 10);
|
|
792
|
+
if (Number.isNaN(pidNum))
|
|
793
|
+
continue;
|
|
794
|
+
try {
|
|
795
|
+
const cmdline = execFileSync2("ps", ["-p", String(pidNum), "-o", "command="], {
|
|
796
|
+
stdio: "pipe"
|
|
797
|
+
}).toString().trim();
|
|
798
|
+
procs.push({ pid: pidNum, userDataDir: extractUserDataDirArg(cmdline) });
|
|
799
|
+
} catch {}
|
|
800
|
+
}
|
|
801
|
+
const orphanPids = selectOrphanBrowserPids(procs, liveUserDataDirs, profileRoot, process.pid);
|
|
802
|
+
for (const pid of orphanPids) {
|
|
803
|
+
try {
|
|
804
|
+
killProcessTreeChildren(pid);
|
|
805
|
+
process.kill(pid, "SIGKILL");
|
|
806
|
+
logger.info({ pid }, "Reaped orphaned browser process (janitor)");
|
|
807
|
+
} catch (e) {
|
|
808
|
+
logger.debug({ err: e, pid }, "Janitor failed to reap orphaned browser process");
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
function cleanSingletonFiles(userDataDir) {
|
|
813
|
+
try {
|
|
814
|
+
const files = readdirSync(userDataDir);
|
|
815
|
+
for (const f of files) {
|
|
816
|
+
if (f.startsWith("Singleton")) {
|
|
817
|
+
try {
|
|
818
|
+
unlinkSync(resolve4(userDataDir, f));
|
|
819
|
+
logger.info({ file: f, userDataDir }, "Removed stale Singleton file");
|
|
820
|
+
} catch (e) {
|
|
821
|
+
logger.warn({ err: e, file: f }, "Failed to remove stale Chrome Singleton file");
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
} catch {}
|
|
826
|
+
}
|
|
827
|
+
function killProcessTreeChildren(pid) {
|
|
828
|
+
try {
|
|
829
|
+
const children = execFileSync2("pgrep", ["-P", String(pid)], { stdio: "pipe" }).toString().trim();
|
|
830
|
+
if (!children)
|
|
831
|
+
return;
|
|
832
|
+
const childPids = children.split(`
|
|
833
|
+
`).map((cpid) => parseInt(cpid, 10)).filter((pidNum) => !Number.isNaN(pidNum));
|
|
834
|
+
for (const childPid of childPids) {
|
|
835
|
+
killProcessTreeChildren(childPid);
|
|
836
|
+
}
|
|
837
|
+
for (const signal of ["SIGTERM", "SIGKILL"]) {
|
|
838
|
+
for (const childPid of childPids) {
|
|
839
|
+
try {
|
|
840
|
+
process.kill(childPid, signal);
|
|
841
|
+
} catch (e) {
|
|
842
|
+
logger.debug({ err: e, pid: childPid, signal }, "Failed to signal browser child process");
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
logger.info({ parentPid: pid, childPids }, "Killed browser-MCP child process tree");
|
|
847
|
+
} catch {}
|
|
848
|
+
}
|
|
849
|
+
// ../../packages/core/src/platform/playwright/manager.ts
|
|
850
|
+
import { execFileSync as execFileSync3, spawn } from "child_process";
|
|
851
|
+
import { createHash as createHash3, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
852
|
+
import {
|
|
853
|
+
cpSync,
|
|
854
|
+
existsSync as existsSync2,
|
|
855
|
+
mkdirSync as mkdirSync4,
|
|
856
|
+
readFileSync as readFileSync2,
|
|
857
|
+
rmSync,
|
|
858
|
+
unlinkSync as unlinkSync2,
|
|
859
|
+
writeFileSync as writeFileSync2
|
|
860
|
+
} from "fs";
|
|
861
|
+
import { dirname as dirname3, join as join5, resolve as resolve6 } from "path";
|
|
862
|
+
|
|
863
|
+
// ../../packages/core/src/platform/delay.ts
|
|
864
|
+
var delay = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
865
|
+
|
|
866
|
+
// ../../packages/core/src/platform/playwright/headed-launch.ts
|
|
867
|
+
import { accessSync as accessSync2, constants as constants2 } from "fs";
|
|
868
|
+
import { delimiter, isAbsolute, resolve as resolve5 } from "path";
|
|
869
|
+
function findExecutableOnPath(command, environment = process.env) {
|
|
870
|
+
const candidates = isAbsolute(command) ? [command] : (environment.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => resolve5(directory, command));
|
|
871
|
+
for (const candidate of candidates) {
|
|
872
|
+
try {
|
|
873
|
+
accessSync2(candidate, constants2.X_OK);
|
|
874
|
+
return candidate;
|
|
875
|
+
} catch {}
|
|
876
|
+
}
|
|
877
|
+
return null;
|
|
878
|
+
}
|
|
879
|
+
function resolveHeadedPlaywrightSpawn(command, args, options = {}) {
|
|
880
|
+
const platform = options.platform ?? process.platform;
|
|
881
|
+
const environment = options.environment ?? process.env;
|
|
882
|
+
const hasDisplay = Boolean(environment.DISPLAY?.trim() || environment.WAYLAND_DISPLAY?.trim());
|
|
883
|
+
if (platform !== "linux" || hasDisplay) {
|
|
884
|
+
return { command, args: [...args], virtualDisplay: false };
|
|
885
|
+
}
|
|
886
|
+
const xvfbRun = (options.findExecutable ?? findExecutableOnPath)("xvfb-run", environment);
|
|
887
|
+
if (!xvfbRun) {
|
|
888
|
+
throw new Error("Headed Playwright on Linux requires DISPLAY/WAYLAND_DISPLAY or xvfb-run; install Xvfb and ensure xvfb-run is on PATH");
|
|
889
|
+
}
|
|
890
|
+
return {
|
|
891
|
+
command: xvfbRun,
|
|
892
|
+
args: ["-a", "-s", "-screen 0 1440x1000x24", command, ...args],
|
|
893
|
+
virtualDisplay: true
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// ../../packages/core/src/platform/playwright/transport-probe.ts
|
|
898
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
899
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
900
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
901
|
+
|
|
902
|
+
// ../../packages/core/src/platform/playwright/capability.ts
|
|
903
|
+
import { createHmac } from "crypto";
|
|
904
|
+
function browserOwnerCapability(capability, owner) {
|
|
905
|
+
return createHmac("sha256", capability).update(owner).digest("hex");
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// ../../packages/core/src/platform/playwright/transport-probe.ts
|
|
909
|
+
var PROBE_OWNER = "__negotium_transport_probe__";
|
|
910
|
+
var PROBE_TIMEOUT_MS = 3000;
|
|
911
|
+
async function probeMcpTransport(transport, options = {}) {
|
|
912
|
+
const client = new Client({ name: "negotium-browser-healthcheck", version: "1.0.0" });
|
|
913
|
+
let timeout;
|
|
914
|
+
try {
|
|
915
|
+
const tools = await Promise.race([
|
|
916
|
+
(async () => {
|
|
917
|
+
await client.connect(transport);
|
|
918
|
+
const result = await client.listTools();
|
|
919
|
+
if (result.tools.length === 0)
|
|
920
|
+
throw new Error("browser MCP returned no tools");
|
|
921
|
+
await options.terminate?.();
|
|
922
|
+
return result.tools;
|
|
923
|
+
})(),
|
|
924
|
+
new Promise((_, reject) => {
|
|
925
|
+
timeout = setTimeout(() => reject(new Error("browser MCP transport probe timed out")), options.timeoutMs ?? PROBE_TIMEOUT_MS);
|
|
926
|
+
timeout.unref?.();
|
|
927
|
+
})
|
|
928
|
+
]);
|
|
929
|
+
return tools.length > 0;
|
|
930
|
+
} catch {
|
|
931
|
+
return false;
|
|
932
|
+
} finally {
|
|
933
|
+
if (timeout)
|
|
934
|
+
clearTimeout(timeout);
|
|
935
|
+
try {
|
|
936
|
+
await client.close();
|
|
937
|
+
} catch {}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
async function probePlaywrightMcpTransports(port, capability, fetchImpl = fetch) {
|
|
941
|
+
const query = new URLSearchParams({ owner: PROBE_OWNER });
|
|
942
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
943
|
+
const ownerCapability = browserOwnerCapability(capability, PROBE_OWNER);
|
|
944
|
+
const capabilityHeaders = { "X-Browser-Capability": ownerCapability };
|
|
945
|
+
const authenticatedFetch = (input, init) => {
|
|
946
|
+
const headers = new Headers(init?.headers);
|
|
947
|
+
headers.set("X-Browser-Capability", ownerCapability);
|
|
948
|
+
return fetchImpl(input, { ...init, headers });
|
|
949
|
+
};
|
|
950
|
+
const sseTransport = new SSEClientTransport(new URL(`${baseUrl}/sse?${query}`), {
|
|
951
|
+
fetch: authenticatedFetch,
|
|
952
|
+
eventSourceInit: { fetch: authenticatedFetch },
|
|
953
|
+
requestInit: { headers: capabilityHeaders }
|
|
954
|
+
});
|
|
955
|
+
if (!await probeMcpTransport(sseTransport))
|
|
956
|
+
return false;
|
|
957
|
+
const streamableTransport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp?${query}`), {
|
|
958
|
+
fetch: authenticatedFetch,
|
|
959
|
+
requestInit: { headers: capabilityHeaders }
|
|
960
|
+
});
|
|
961
|
+
return probeMcpTransport(streamableTransport, {
|
|
962
|
+
terminate: () => streamableTransport.terminateSession()
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// ../../packages/core/src/platform/playwright/vault-broker.ts
|
|
967
|
+
import { randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
968
|
+
import { createServer as createServer2 } from "net";
|
|
969
|
+
import { tmpdir } from "os";
|
|
970
|
+
import { join as join4 } from "path";
|
|
971
|
+
|
|
972
|
+
// ../../packages/core/src/platform/ipc.ts
|
|
973
|
+
import { createHash } from "crypto";
|
|
974
|
+
import { chmodSync as chmodSync2 } from "fs";
|
|
975
|
+
import { basename } from "path";
|
|
976
|
+
var IS_WINDOWS = process.platform === "win32";
|
|
977
|
+
function ipcEndpoint(posixSocketPath) {
|
|
978
|
+
if (!IS_WINDOWS)
|
|
979
|
+
return posixSocketPath;
|
|
980
|
+
const label = basename(posixSocketPath).replace(/\.sock$/, "").replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "endpoint";
|
|
981
|
+
const digest = createHash("sha256").update(posixSocketPath).digest("hex").slice(0, 16);
|
|
982
|
+
return `\\\\.\\pipe\\negotium-${label}-${digest}`;
|
|
983
|
+
}
|
|
984
|
+
function restrictIpcEndpoint(endpoint) {
|
|
985
|
+
if (IS_WINDOWS)
|
|
986
|
+
return;
|
|
987
|
+
chmodSync2(endpoint, 384);
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// ../../packages/core/src/storage/vault.ts
|
|
991
|
+
import { chmodSync as chmodSync3, mkdirSync as mkdirSync3 } from "fs";
|
|
992
|
+
import { join as join3 } from "path";
|
|
993
|
+
|
|
994
|
+
// ../../packages/core/src/storage/vault-crypto-core.ts
|
|
995
|
+
import { createCipheriv, createDecipheriv, createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
996
|
+
var ENVELOPE_PREFIX = "otium-vault:v1:";
|
|
997
|
+
var IV_BYTES = 12;
|
|
998
|
+
var KEY_BYTES = 32;
|
|
999
|
+
function encryptionKey(masterKey) {
|
|
1000
|
+
return createHash2("sha256").update("otium-vault-value-v1\x00", "utf8").update(masterKey, "utf8").digest().subarray(0, KEY_BYTES);
|
|
1001
|
+
}
|
|
1002
|
+
function aad(userId, key) {
|
|
1003
|
+
return Buffer.from(`${userId}\x00${key.toUpperCase()}`, "utf8");
|
|
1004
|
+
}
|
|
1005
|
+
function isEncryptedVaultValue(value) {
|
|
1006
|
+
return value.startsWith(ENVELOPE_PREFIX);
|
|
1007
|
+
}
|
|
1008
|
+
function encryptVaultValueWithKey(userId, key, value, masterKey) {
|
|
1009
|
+
const iv = randomBytes2(IV_BYTES);
|
|
1010
|
+
const cipher = createCipheriv("aes-256-gcm", encryptionKey(masterKey), iv);
|
|
1011
|
+
cipher.setAAD(aad(userId, key));
|
|
1012
|
+
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
1013
|
+
const tag = cipher.getAuthTag();
|
|
1014
|
+
return `${ENVELOPE_PREFIX}${iv.toString("base64url")}.${ciphertext.toString("base64url")}.${tag.toString("base64url")}`;
|
|
1015
|
+
}
|
|
1016
|
+
function decryptVaultValueWithKey(userId, key, storedValue, masterKey) {
|
|
1017
|
+
if (!isEncryptedVaultValue(storedValue)) {
|
|
1018
|
+
return { value: storedValue, legacyPlaintext: true };
|
|
1019
|
+
}
|
|
1020
|
+
const encoded = storedValue.slice(ENVELOPE_PREFIX.length);
|
|
1021
|
+
const [ivPart, ciphertextPart, tagPart, ...extra] = encoded.split(".");
|
|
1022
|
+
if (!ivPart || ciphertextPart === undefined || !tagPart || extra.length > 0) {
|
|
1023
|
+
throw new Error("Invalid encrypted vault value");
|
|
1024
|
+
}
|
|
1025
|
+
const iv = Buffer.from(ivPart, "base64url");
|
|
1026
|
+
const ciphertext = Buffer.from(ciphertextPart, "base64url");
|
|
1027
|
+
const tag = Buffer.from(tagPart, "base64url");
|
|
1028
|
+
if (iv.length !== IV_BYTES || tag.length !== 16) {
|
|
1029
|
+
throw new Error("Invalid encrypted vault value");
|
|
1030
|
+
}
|
|
1031
|
+
const decipher = createDecipheriv("aes-256-gcm", encryptionKey(masterKey), iv);
|
|
1032
|
+
decipher.setAAD(aad(userId, key));
|
|
1033
|
+
decipher.setAuthTag(tag);
|
|
1034
|
+
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
1035
|
+
return { value: plaintext.toString("utf8"), legacyPlaintext: false };
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// ../../packages/core/src/storage/vault-crypto.ts
|
|
1039
|
+
function encryptVaultValue(userId, key, value, masterKey = VAULT_MASTER_KEY) {
|
|
1040
|
+
return encryptVaultValueWithKey(userId, key, value, masterKey);
|
|
1041
|
+
}
|
|
1042
|
+
function decryptVaultValue(userId, key, storedValue, masterKey = VAULT_MASTER_KEY) {
|
|
1043
|
+
return decryptVaultValueWithKey(userId, key, storedValue, masterKey);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
// ../../packages/core/src/storage/vault.ts
|
|
1047
|
+
var vaultDb;
|
|
1048
|
+
var vaultMasterKey = VAULT_MASTER_KEY;
|
|
1049
|
+
function initializeVaultDatabase(database) {
|
|
1050
|
+
database.exec("PRAGMA journal_mode = WAL");
|
|
1051
|
+
database.exec("PRAGMA busy_timeout = 5000");
|
|
1052
|
+
database.exec(`
|
|
1053
|
+
CREATE TABLE IF NOT EXISTS vault (
|
|
1054
|
+
user_id TEXT NOT NULL,
|
|
1055
|
+
key TEXT NOT NULL,
|
|
1056
|
+
value TEXT NOT NULL,
|
|
1057
|
+
description TEXT NOT NULL DEFAULT '',
|
|
1058
|
+
PRIMARY KEY (user_id, key)
|
|
1059
|
+
)
|
|
1060
|
+
`);
|
|
1061
|
+
{
|
|
1062
|
+
const cols = database.prepare("PRAGMA table_info(vault)").all();
|
|
1063
|
+
const uid = cols.find((c) => c.name === "user_id");
|
|
1064
|
+
if (uid && uid.type.toUpperCase() === "INTEGER") {
|
|
1065
|
+
database.exec("BEGIN");
|
|
1066
|
+
database.exec(`
|
|
1067
|
+
CREATE TABLE vault_migrated (
|
|
1068
|
+
user_id TEXT NOT NULL,
|
|
1069
|
+
key TEXT NOT NULL,
|
|
1070
|
+
value TEXT NOT NULL,
|
|
1071
|
+
description TEXT NOT NULL DEFAULT '',
|
|
1072
|
+
PRIMARY KEY (user_id, key)
|
|
1073
|
+
)
|
|
1074
|
+
`);
|
|
1075
|
+
database.exec("INSERT INTO vault_migrated SELECT CAST(user_id AS TEXT), key, value, description FROM vault");
|
|
1076
|
+
database.exec("DROP TABLE vault");
|
|
1077
|
+
database.exec("ALTER TABLE vault_migrated RENAME TO vault");
|
|
1078
|
+
database.exec("COMMIT");
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
function openVaultDatabase(dataDir) {
|
|
1083
|
+
const vaultDir = join3(dataDir, "vault");
|
|
1084
|
+
const path = join3(vaultDir, "vault.db");
|
|
1085
|
+
mkdirSync3(vaultDir, { recursive: true, mode: 448 });
|
|
1086
|
+
const database = new Database(path, { create: true });
|
|
1087
|
+
chmodSync3(path, 384);
|
|
1088
|
+
initializeVaultDatabase(database);
|
|
1089
|
+
return database;
|
|
1090
|
+
}
|
|
1091
|
+
function activeVaultDatabase() {
|
|
1092
|
+
if (!vaultDb) {
|
|
1093
|
+
vaultDb = openVaultDatabase(resolveStorageDataDir());
|
|
1094
|
+
}
|
|
1095
|
+
return vaultDb;
|
|
1096
|
+
}
|
|
1097
|
+
var VAULT_VALUE_MAX_BYTES = 64 * 1024;
|
|
1098
|
+
function normalizeVaultKey(key) {
|
|
1099
|
+
return key.trim().toUpperCase();
|
|
1100
|
+
}
|
|
1101
|
+
function decryptRow(userId, key, storedValue) {
|
|
1102
|
+
const database = activeVaultDatabase();
|
|
1103
|
+
const decoded = decryptVaultValue(userId, key, storedValue, vaultMasterKey);
|
|
1104
|
+
if (decoded.legacyPlaintext) {
|
|
1105
|
+
database.prepare("UPDATE vault SET value = ? WHERE user_id = ? AND key = ? AND value = ?").run(encryptVaultValue(userId, key, decoded.value, vaultMasterKey), userId, key, storedValue);
|
|
1106
|
+
}
|
|
1107
|
+
return decoded.value;
|
|
1108
|
+
}
|
|
1109
|
+
function vaultListDecryptableValues(userId) {
|
|
1110
|
+
const rows = activeVaultDatabase().prepare("SELECT key, description, value FROM vault WHERE user_id = ? ORDER BY key").all(userId);
|
|
1111
|
+
const entries = [];
|
|
1112
|
+
for (const row of rows) {
|
|
1113
|
+
try {
|
|
1114
|
+
entries.push({
|
|
1115
|
+
key: row.key,
|
|
1116
|
+
description: row.description,
|
|
1117
|
+
value: decryptRow(userId, row.key, row.value)
|
|
1118
|
+
});
|
|
1119
|
+
} catch {}
|
|
1120
|
+
}
|
|
1121
|
+
return entries;
|
|
1122
|
+
}
|
|
1123
|
+
function vaultGetValue(userId, key) {
|
|
1124
|
+
const normalizedKey = normalizeVaultKey(key);
|
|
1125
|
+
const row = activeVaultDatabase().prepare("SELECT key, value FROM vault WHERE user_id = ? AND key = ?").get(userId, normalizedKey);
|
|
1126
|
+
return row ? decryptRow(userId, row.key, row.value) : undefined;
|
|
1127
|
+
}
|
|
1128
|
+
function vaultSubstituteDetailed(userId, text) {
|
|
1129
|
+
const entries = new Map;
|
|
1130
|
+
const usedKeys = new Set;
|
|
1131
|
+
const substituted = text.replace(/\{\{([^}]+)\}\}/g, (match, rawKey) => {
|
|
1132
|
+
const key = normalizeVaultKey(rawKey);
|
|
1133
|
+
if (!entries.has(key))
|
|
1134
|
+
entries.set(key, vaultGetValue(userId, key));
|
|
1135
|
+
const value = entries.get(key);
|
|
1136
|
+
if (value === undefined)
|
|
1137
|
+
return match;
|
|
1138
|
+
usedKeys.add(key);
|
|
1139
|
+
return value;
|
|
1140
|
+
});
|
|
1141
|
+
return { text: substituted, usedKeys: [...usedKeys] };
|
|
1142
|
+
}
|
|
1143
|
+
function encodedSecretForms(value) {
|
|
1144
|
+
const forms = new Set([
|
|
1145
|
+
value,
|
|
1146
|
+
encodeURIComponent(value),
|
|
1147
|
+
Buffer.from(value, "utf8").toString("base64"),
|
|
1148
|
+
Buffer.from(value, "utf8").toString("base64url"),
|
|
1149
|
+
Buffer.from(value, "utf8").toString("hex")
|
|
1150
|
+
]);
|
|
1151
|
+
forms.delete("");
|
|
1152
|
+
return [...forms].sort((a, b) => b.length - a.length);
|
|
1153
|
+
}
|
|
1154
|
+
function redactVaultSecrets(userId, text) {
|
|
1155
|
+
const candidates = vaultListDecryptableValues(userId).flatMap((entry) => encodedSecretForms(entry.value).map((form) => ({ form, key: entry.key }))).sort((a, b) => b.form.length - a.form.length || a.key.localeCompare(b.key));
|
|
1156
|
+
if (candidates.length === 0)
|
|
1157
|
+
return text;
|
|
1158
|
+
const candidatesByFirstCharacter = new Map;
|
|
1159
|
+
for (const candidate of candidates) {
|
|
1160
|
+
const first = candidate.form[0];
|
|
1161
|
+
if (!first)
|
|
1162
|
+
continue;
|
|
1163
|
+
const bucket = candidatesByFirstCharacter.get(first) ?? [];
|
|
1164
|
+
bucket.push(candidate);
|
|
1165
|
+
candidatesByFirstCharacter.set(first, bucket);
|
|
1166
|
+
}
|
|
1167
|
+
let redacted = "";
|
|
1168
|
+
let offset = 0;
|
|
1169
|
+
while (offset < text.length) {
|
|
1170
|
+
const match = candidatesByFirstCharacter.get(text[offset] ?? "")?.find((candidate) => text.startsWith(candidate.form, offset));
|
|
1171
|
+
if (!match) {
|
|
1172
|
+
redacted += text[offset];
|
|
1173
|
+
offset += 1;
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
redacted += `[REDACTED:${match.key}]`;
|
|
1177
|
+
offset += match.form.length;
|
|
1178
|
+
}
|
|
1179
|
+
return redacted;
|
|
1180
|
+
}
|
|
1181
|
+
// ../../packages/core/src/platform/playwright/vault-broker.ts
|
|
1182
|
+
var MAX_REQUEST_BYTES = 16 * 1024 * 1024;
|
|
1183
|
+
var DEFAULT_OUTPUT_LIMIT = 1e5;
|
|
1184
|
+
var LEASE_TTL_MS = 5 * 60000;
|
|
1185
|
+
var MAX_ACTIVE_LEASES = 1024;
|
|
1186
|
+
var BOUNDED_OUTPUTS = {
|
|
1187
|
+
browser_snapshot: { argument: "maxLength", field: "snapshot" },
|
|
1188
|
+
browser_api_request: { argument: "maxBytes", field: "body" },
|
|
1189
|
+
browser_get_visible_text: { argument: "maxLength", field: "text" },
|
|
1190
|
+
browser_get_visible_html: { argument: "maxLength", field: "html" },
|
|
1191
|
+
browser_iframe_read: { argument: "maxLength", field: "content" }
|
|
1192
|
+
};
|
|
1193
|
+
function deepMapStrings(value, transform) {
|
|
1194
|
+
if (typeof value === "string")
|
|
1195
|
+
return transform(value);
|
|
1196
|
+
if (Array.isArray(value))
|
|
1197
|
+
return value.map((entry) => deepMapStrings(entry, transform));
|
|
1198
|
+
if (!value || typeof value !== "object")
|
|
1199
|
+
return value;
|
|
1200
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1201
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
1202
|
+
return value;
|
|
1203
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, deepMapStrings(entry, transform)]));
|
|
1204
|
+
}
|
|
1205
|
+
function encodedSecretForms2(value) {
|
|
1206
|
+
return [
|
|
1207
|
+
...new Set([
|
|
1208
|
+
value,
|
|
1209
|
+
encodeURIComponent(value),
|
|
1210
|
+
Buffer.from(value, "utf8").toString("base64"),
|
|
1211
|
+
Buffer.from(value, "utf8").toString("base64url"),
|
|
1212
|
+
Buffer.from(value, "utf8").toString("hex")
|
|
1213
|
+
])
|
|
1214
|
+
].filter(Boolean).sort((left, right) => right.length - left.length);
|
|
1215
|
+
}
|
|
1216
|
+
function prepareInput(tool, value) {
|
|
1217
|
+
const config = BOUNDED_OUTPUTS[tool];
|
|
1218
|
+
if (!config || !value || typeof value !== "object" || Array.isArray(value))
|
|
1219
|
+
return { value };
|
|
1220
|
+
const input = value;
|
|
1221
|
+
const requested = input[config.argument];
|
|
1222
|
+
if (requested !== undefined && (!Number.isSafeInteger(requested) || Number(requested) <= 0)) {
|
|
1223
|
+
return { value };
|
|
1224
|
+
}
|
|
1225
|
+
const limit = requested === undefined ? DEFAULT_OUTPUT_LIMIT : Number(requested);
|
|
1226
|
+
return {
|
|
1227
|
+
value: { ...input, [config.argument]: Number.MAX_SAFE_INTEGER },
|
|
1228
|
+
boundary: { field: config.field, limit }
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
function redactTextEntry(entry, redact, boundary) {
|
|
1232
|
+
if (!entry || typeof entry !== "object")
|
|
1233
|
+
return redact(entry);
|
|
1234
|
+
const content = entry;
|
|
1235
|
+
if (content.type !== "text" || typeof content.text !== "string")
|
|
1236
|
+
return redact(entry);
|
|
1237
|
+
try {
|
|
1238
|
+
const parsed = redact(JSON.parse(content.text));
|
|
1239
|
+
if (boundary && parsed && typeof parsed === "object") {
|
|
1240
|
+
const object = parsed;
|
|
1241
|
+
const fieldValue = object[boundary.field];
|
|
1242
|
+
if (typeof fieldValue === "string") {
|
|
1243
|
+
const originalExceeded = typeof object.length === "number" && object.length > boundary.limit;
|
|
1244
|
+
if (fieldValue.length > boundary.limit)
|
|
1245
|
+
object[boundary.field] = fieldValue.slice(0, boundary.limit);
|
|
1246
|
+
if (originalExceeded || fieldValue.length > boundary.limit)
|
|
1247
|
+
object.truncated = true;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
return { ...content, text: JSON.stringify(parsed, null, 2) };
|
|
1251
|
+
} catch {
|
|
1252
|
+
const redacted = redact(content.text);
|
|
1253
|
+
if (boundary && typeof redacted === "string" && redacted.length > boundary.limit) {
|
|
1254
|
+
return {
|
|
1255
|
+
...content,
|
|
1256
|
+
text: `${redacted.slice(0, boundary.limit)}
|
|
1257
|
+
[truncated]`
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
return { ...content, text: redacted };
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
function secureOutput(result, redact, boundary) {
|
|
1264
|
+
if (!result || typeof result !== "object")
|
|
1265
|
+
return redact(result);
|
|
1266
|
+
const object = result;
|
|
1267
|
+
const content = Array.isArray(object.content) ? object.content.map((entry) => redactTextEntry(entry, redact, boundary)) : object.content;
|
|
1268
|
+
return redact({ ...object, content });
|
|
1269
|
+
}
|
|
1270
|
+
function authorized(actual, expected) {
|
|
1271
|
+
if (typeof actual !== "string")
|
|
1272
|
+
return false;
|
|
1273
|
+
const left = Buffer.from(actual);
|
|
1274
|
+
const right = Buffer.from(expected);
|
|
1275
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
1276
|
+
}
|
|
1277
|
+
async function createBrowserVaultBroker(userId) {
|
|
1278
|
+
const token = randomBytes3(32).toString("hex");
|
|
1279
|
+
const socketPath = ipcEndpoint(join4(process.platform === "win32" ? tmpdir() : "/tmp", `negotium-browser-vault-${process.pid}-${randomBytes3(8).toString("hex")}.sock`));
|
|
1280
|
+
const retainedForms = new Map;
|
|
1281
|
+
const leases = new Map;
|
|
1282
|
+
const sockets = new Set;
|
|
1283
|
+
const redactRetained = (text) => {
|
|
1284
|
+
let output = text;
|
|
1285
|
+
for (const [form, key] of [...retainedForms].sort(([left], [right]) => right.length - left.length)) {
|
|
1286
|
+
output = output.replaceAll(form, `[REDACTED:${key}]`);
|
|
1287
|
+
}
|
|
1288
|
+
return output;
|
|
1289
|
+
};
|
|
1290
|
+
const redact = (value) => deepMapStrings(value, (text) => redactRetained(redactVaultSecrets(userId, text)));
|
|
1291
|
+
const handleRequest = (request) => {
|
|
1292
|
+
const id = request.id;
|
|
1293
|
+
if (!authorized(request.token, token))
|
|
1294
|
+
return { id, ok: false, error: "unauthorized" };
|
|
1295
|
+
if (request.op === "transform_input") {
|
|
1296
|
+
if (typeof request.tool !== "string")
|
|
1297
|
+
return { id, ok: false, error: "invalid tool" };
|
|
1298
|
+
const leaseCutoff = Date.now() - LEASE_TTL_MS;
|
|
1299
|
+
for (const [lease2, binding] of leases) {
|
|
1300
|
+
if (binding.createdAt < leaseCutoff)
|
|
1301
|
+
leases.delete(lease2);
|
|
1302
|
+
}
|
|
1303
|
+
if (leases.size >= MAX_ACTIVE_LEASES) {
|
|
1304
|
+
return { id, ok: false, error: "too many active leases" };
|
|
1305
|
+
}
|
|
1306
|
+
const substituted = deepMapStrings(request.value, (text) => {
|
|
1307
|
+
const result = vaultSubstituteDetailed(userId, text);
|
|
1308
|
+
for (const key of result.usedKeys) {
|
|
1309
|
+
const secret = vaultGetValue(userId, key);
|
|
1310
|
+
if (secret === undefined)
|
|
1311
|
+
continue;
|
|
1312
|
+
for (const form of encodedSecretForms2(secret))
|
|
1313
|
+
retainedForms.set(form, key);
|
|
1314
|
+
}
|
|
1315
|
+
return result.text;
|
|
1316
|
+
});
|
|
1317
|
+
const prepared = prepareInput(request.tool, substituted);
|
|
1318
|
+
const lease = randomBytes3(24).toString("hex");
|
|
1319
|
+
leases.set(lease, { boundary: prepared.boundary, createdAt: Date.now() });
|
|
1320
|
+
return {
|
|
1321
|
+
id,
|
|
1322
|
+
ok: true,
|
|
1323
|
+
value: prepared.value,
|
|
1324
|
+
lease,
|
|
1325
|
+
boundary: prepared.boundary
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
if (request.op === "redact_output") {
|
|
1329
|
+
if (typeof request.lease !== "string") {
|
|
1330
|
+
return { id, ok: false, error: "invalid lease" };
|
|
1331
|
+
}
|
|
1332
|
+
const binding = leases.get(request.lease);
|
|
1333
|
+
leases.delete(request.lease);
|
|
1334
|
+
if (!binding || binding.createdAt < Date.now() - LEASE_TTL_MS) {
|
|
1335
|
+
return { id, ok: false, error: "invalid lease" };
|
|
1336
|
+
}
|
|
1337
|
+
try {
|
|
1338
|
+
const value = secureOutput(request.value, redact, binding.boundary);
|
|
1339
|
+
const serialized = JSON.stringify(value);
|
|
1340
|
+
if (redactRetained(serialized) !== serialized) {
|
|
1341
|
+
return { id, ok: false, error: "redaction verification failed" };
|
|
1342
|
+
}
|
|
1343
|
+
return { id, ok: true, value };
|
|
1344
|
+
} catch {
|
|
1345
|
+
return { id, ok: false, error: "redaction failed" };
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
return { id, ok: false, error: "unknown operation" };
|
|
1349
|
+
};
|
|
1350
|
+
const server = createServer2((socket) => {
|
|
1351
|
+
sockets.add(socket);
|
|
1352
|
+
let pending = "";
|
|
1353
|
+
socket.setEncoding("utf8");
|
|
1354
|
+
socket.on("data", (chunk) => {
|
|
1355
|
+
pending += chunk;
|
|
1356
|
+
if (Buffer.byteLength(pending) > MAX_REQUEST_BYTES) {
|
|
1357
|
+
socket.destroy();
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
while (true) {
|
|
1361
|
+
const newline = pending.indexOf(`
|
|
1362
|
+
`);
|
|
1363
|
+
if (newline < 0)
|
|
1364
|
+
break;
|
|
1365
|
+
const line = pending.slice(0, newline);
|
|
1366
|
+
pending = pending.slice(newline + 1);
|
|
1367
|
+
if (!line)
|
|
1368
|
+
continue;
|
|
1369
|
+
let response;
|
|
1370
|
+
try {
|
|
1371
|
+
response = handleRequest(JSON.parse(line));
|
|
1372
|
+
} catch {
|
|
1373
|
+
response = { ok: false, error: "invalid request" };
|
|
1374
|
+
}
|
|
1375
|
+
socket.write(`${JSON.stringify(response)}
|
|
1376
|
+
`);
|
|
1377
|
+
}
|
|
1378
|
+
});
|
|
1379
|
+
socket.once("close", () => sockets.delete(socket));
|
|
1380
|
+
});
|
|
1381
|
+
await new Promise((resolveListen, reject) => {
|
|
1382
|
+
server.once("error", reject);
|
|
1383
|
+
server.listen(socketPath, resolveListen);
|
|
1384
|
+
});
|
|
1385
|
+
restrictIpcEndpoint(socketPath);
|
|
1386
|
+
let closed = false;
|
|
1387
|
+
return {
|
|
1388
|
+
socketPath,
|
|
1389
|
+
token,
|
|
1390
|
+
async close() {
|
|
1391
|
+
if (closed)
|
|
1392
|
+
return;
|
|
1393
|
+
closed = true;
|
|
1394
|
+
leases.clear();
|
|
1395
|
+
retainedForms.clear();
|
|
1396
|
+
for (const socket of sockets)
|
|
1397
|
+
socket.destroy();
|
|
1398
|
+
await new Promise((resolveClose) => server.close(() => resolveClose()));
|
|
1399
|
+
}
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
// ../../packages/core/src/security/sanitize.ts
|
|
1404
|
+
function sanitizeTopicName(name, lowercase = false) {
|
|
1405
|
+
const safe = name.replace(/[^a-zA-Z0-9\uAC00-\uD7A3_-]/g, "_") || "_";
|
|
1406
|
+
return lowercase ? safe.toLowerCase() : safe;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
// ../../packages/core/src/storage/browser-profiles.ts
|
|
1410
|
+
var DEFAULT_BROWSER_PROFILE = "default";
|
|
1411
|
+
function normalizeBrowserProfileName(name) {
|
|
1412
|
+
const value = name.trim().toLowerCase();
|
|
1413
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,47}$/.test(value)) {
|
|
1414
|
+
throw new Error("Profile name must be 1-48 lowercase letters, numbers, '-' or '_'.");
|
|
1415
|
+
}
|
|
1416
|
+
return value;
|
|
1417
|
+
}
|
|
1418
|
+
registerStorageSchemaInitializer((database) => {
|
|
1419
|
+
database.exec(`
|
|
1420
|
+
CREATE TABLE IF NOT EXISTS browser_profiles (
|
|
1421
|
+
owner_id TEXT NOT NULL,
|
|
1422
|
+
name TEXT NOT NULL,
|
|
1423
|
+
created_at TEXT NOT NULL,
|
|
1424
|
+
PRIMARY KEY (owner_id, name)
|
|
1425
|
+
)
|
|
1426
|
+
`);
|
|
1427
|
+
});
|
|
1428
|
+
function getBrowserProfileOwner(topicId, fallbackUserId) {
|
|
1429
|
+
return db.query("SELECT browser_profile_owner FROM api_topics WHERE id = ?").get(topicId)?.browser_profile_owner ?? fallbackUserId;
|
|
1430
|
+
}
|
|
1431
|
+
function getTopicBrowserProfile(topicId) {
|
|
1432
|
+
const value = db.query("SELECT browser_profile FROM api_topics WHERE id = ?").get(topicId)?.browser_profile;
|
|
1433
|
+
return value || DEFAULT_BROWSER_PROFILE;
|
|
1434
|
+
}
|
|
1435
|
+
function isBrowserConnectPort(value) {
|
|
1436
|
+
return Number.isInteger(value) && value >= 1024 && value <= 65535;
|
|
1437
|
+
}
|
|
1438
|
+
function getTopicBrowserConnectPort(topicId) {
|
|
1439
|
+
const value = db.query("SELECT browser_connect_port FROM api_topics WHERE id = ?").get(topicId)?.browser_connect_port;
|
|
1440
|
+
return isBrowserConnectPort(value) ? value : undefined;
|
|
1441
|
+
}
|
|
1442
|
+
function assertBrowserProfileDeletable(ownerId, rawName) {
|
|
1443
|
+
const name = normalizeBrowserProfileName(rawName);
|
|
1444
|
+
if (name === DEFAULT_BROWSER_PROFILE)
|
|
1445
|
+
throw new Error("The default profile cannot be deleted.");
|
|
1446
|
+
const topics = db.query(`SELECT t.id, t.title FROM api_topics t
|
|
1447
|
+
WHERE t.browser_profile = ?
|
|
1448
|
+
ORDER BY t.title`).all(name);
|
|
1449
|
+
if (topics.length > 0) {
|
|
1450
|
+
const assigned = topics.map((topic) => `${topic.title} (${topic.id})`).join(", ");
|
|
1451
|
+
throw new Error(`Profile "${name}" is assigned to ${topics.length} topic(s): ${assigned}.`);
|
|
1452
|
+
}
|
|
1453
|
+
return name;
|
|
1454
|
+
}
|
|
1455
|
+
function deleteBrowserProfile(ownerId, rawName) {
|
|
1456
|
+
const name = assertBrowserProfileDeletable(ownerId, rawName);
|
|
1457
|
+
const result = db.query("DELETE FROM browser_profiles WHERE owner_id = ? AND name = ?").run("local", name);
|
|
1458
|
+
return Number(result.changes ?? 0) > 0;
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
// ../../packages/core/src/platform/playwright/manager.ts
|
|
1462
|
+
function removeDefaultProfileDataDir(userDataDir) {
|
|
1463
|
+
const root = resolve6(BROWSER_PROFILES_DIR);
|
|
1464
|
+
const target = resolve6(userDataDir);
|
|
1465
|
+
if (dirname3(target) !== root) {
|
|
1466
|
+
throw new Error(`Refusing to delete browser profile outside managed root: ${target}`);
|
|
1467
|
+
}
|
|
1468
|
+
const existed = existsSync2(target);
|
|
1469
|
+
rmSync(target, { recursive: true, force: true });
|
|
1470
|
+
return existed;
|
|
1471
|
+
}
|
|
1472
|
+
function makeInstanceKey(userId, topic) {
|
|
1473
|
+
return resolvePlaywrightTopicBinding(userId, topic).instanceKey;
|
|
1474
|
+
}
|
|
1475
|
+
function resolvePlaywrightTopicBinding(userId, topic) {
|
|
1476
|
+
return validateProfileBinding(managerHost.resolveTopicBinding(userId, topic));
|
|
1477
|
+
}
|
|
1478
|
+
function defaultTopicBinding(userId, topic) {
|
|
1479
|
+
if (!topic)
|
|
1480
|
+
return managerHost.resolveNamedBinding(userId, "default");
|
|
1481
|
+
const connectPort = getTopicBrowserConnectPort(topic);
|
|
1482
|
+
if (connectPort !== undefined)
|
|
1483
|
+
return connectBinding(connectPort);
|
|
1484
|
+
const ownerId = getBrowserProfileOwner(topic, userId);
|
|
1485
|
+
const profile = getTopicBrowserProfile(topic);
|
|
1486
|
+
return managerHost.resolveNamedBinding(ownerId, profile);
|
|
1487
|
+
}
|
|
1488
|
+
function makeBrowserProfileInstanceKey(ownerId, rawProfile) {
|
|
1489
|
+
return resolvePlaywrightProfileBinding(ownerId, rawProfile).instanceKey;
|
|
1490
|
+
}
|
|
1491
|
+
function resolvePlaywrightProfileBinding(ownerId, rawProfile) {
|
|
1492
|
+
return validateProfileBinding(managerHost.resolveNamedBinding(ownerId, rawProfile));
|
|
1493
|
+
}
|
|
1494
|
+
function validateProfileBinding(binding) {
|
|
1495
|
+
if (!binding || typeof binding.instanceKey !== "string" || !binding.instanceKey.trim() || typeof binding.ownerId !== "string" || !binding.ownerId.trim() || typeof binding.profile !== "string" || !binding.profile.trim()) {
|
|
1496
|
+
throw new Error("invalid Playwright profile binding");
|
|
1497
|
+
}
|
|
1498
|
+
return Object.freeze({ ...binding });
|
|
1499
|
+
}
|
|
1500
|
+
function connectBinding(port) {
|
|
1501
|
+
return { instanceKey: `connect:${port}`, ownerId: "local", profile: `connect-${port}` };
|
|
1502
|
+
}
|
|
1503
|
+
function parseConnectInstanceKey(instanceKey) {
|
|
1504
|
+
const match = /^connect:(\d+)$/.exec(instanceKey);
|
|
1505
|
+
return match ? Number(match[1]) : undefined;
|
|
1506
|
+
}
|
|
1507
|
+
function browserRsArgs(instanceKey, port, userDataDir) {
|
|
1508
|
+
const connectPort = parseConnectInstanceKey(instanceKey);
|
|
1509
|
+
return [
|
|
1510
|
+
"--port",
|
|
1511
|
+
String(port),
|
|
1512
|
+
"--host",
|
|
1513
|
+
"127.0.0.1",
|
|
1514
|
+
"--headed",
|
|
1515
|
+
"--user-data-dir",
|
|
1516
|
+
userDataDir,
|
|
1517
|
+
...connectPort === undefined ? [] : ["--connect", String(connectPort)]
|
|
1518
|
+
];
|
|
1519
|
+
}
|
|
1520
|
+
function defaultNamedBinding(_ownerId, rawProfile) {
|
|
1521
|
+
const profile = normalizeBrowserProfileName(rawProfile);
|
|
1522
|
+
const instanceKey = `profile:${profile}`;
|
|
1523
|
+
return {
|
|
1524
|
+
instanceKey,
|
|
1525
|
+
ownerId: "local",
|
|
1526
|
+
profile
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
var CHILD_ENVIRONMENT_KEYS = [
|
|
1530
|
+
"HOME",
|
|
1531
|
+
"PATH",
|
|
1532
|
+
"TMPDIR",
|
|
1533
|
+
"TMP",
|
|
1534
|
+
"TEMP",
|
|
1535
|
+
"LANG",
|
|
1536
|
+
"LC_ALL",
|
|
1537
|
+
"LC_CTYPE",
|
|
1538
|
+
"DISPLAY",
|
|
1539
|
+
"WAYLAND_DISPLAY",
|
|
1540
|
+
"XAUTHORITY",
|
|
1541
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
1542
|
+
"XDG_RUNTIME_DIR",
|
|
1543
|
+
"XDG_CONFIG_HOME",
|
|
1544
|
+
"XDG_CACHE_HOME",
|
|
1545
|
+
"XDG_DATA_HOME",
|
|
1546
|
+
"AB_CHROME",
|
|
1547
|
+
"AB_CONNECT",
|
|
1548
|
+
"RUST_LOG",
|
|
1549
|
+
"RUST_BACKTRACE"
|
|
1550
|
+
];
|
|
1551
|
+
var WINDOWS_CHILD_ENVIRONMENT_KEYS = [
|
|
1552
|
+
"SystemRoot",
|
|
1553
|
+
"windir",
|
|
1554
|
+
"SystemDrive",
|
|
1555
|
+
"ProgramFiles",
|
|
1556
|
+
"ProgramFiles(x86)",
|
|
1557
|
+
"ProgramW6432",
|
|
1558
|
+
"ProgramData",
|
|
1559
|
+
"LOCALAPPDATA",
|
|
1560
|
+
"APPDATA",
|
|
1561
|
+
"USERPROFILE",
|
|
1562
|
+
"ComSpec",
|
|
1563
|
+
"PATHEXT",
|
|
1564
|
+
"NUMBER_OF_PROCESSORS",
|
|
1565
|
+
"PROCESSOR_ARCHITECTURE"
|
|
1566
|
+
];
|
|
1567
|
+
function defaultChildEnvironment(context) {
|
|
1568
|
+
const childEnvironment = {};
|
|
1569
|
+
const keys = process.platform === "win32" ? [...CHILD_ENVIRONMENT_KEYS, ...WINDOWS_CHILD_ENVIRONMENT_KEYS] : CHILD_ENVIRONMENT_KEYS;
|
|
1570
|
+
for (const key of keys) {
|
|
1571
|
+
if (context.environment[key] !== undefined)
|
|
1572
|
+
childEnvironment[key] = context.environment[key];
|
|
1573
|
+
}
|
|
1574
|
+
return childEnvironment;
|
|
1575
|
+
}
|
|
1576
|
+
var defaultManagerHost = Object.freeze({
|
|
1577
|
+
portsDir: PLAYWRIGHT_PORTS_DIR,
|
|
1578
|
+
basePort: PLAYWRIGHT_BASE_PORT,
|
|
1579
|
+
maxPort: PLAYWRIGHT_MAX_PORT,
|
|
1580
|
+
browserBin: PLAYWRIGHT_MCP_BIN,
|
|
1581
|
+
browserRsBin: BROWSER_RS_BIN,
|
|
1582
|
+
resolveProxy: resolveBrowserProxy,
|
|
1583
|
+
resolveTopicBinding: defaultTopicBinding,
|
|
1584
|
+
resolveNamedBinding: defaultNamedBinding,
|
|
1585
|
+
resolveInstanceDataDir(instanceKey) {
|
|
1586
|
+
const { ownerId, profile } = parseInstanceKey(instanceKey);
|
|
1587
|
+
return defaultProfileDir(ownerId, profile);
|
|
1588
|
+
},
|
|
1589
|
+
createChildEnvironment: defaultChildEnvironment,
|
|
1590
|
+
cleanupBrowserProcessesForDataDir: killBrowserProcsForUserDataDir,
|
|
1591
|
+
removeProfileDataDir: removeDefaultProfileDataDir,
|
|
1592
|
+
reapOrphanBrowsers
|
|
1593
|
+
});
|
|
1594
|
+
var managerHost = defaultManagerHost;
|
|
1595
|
+
function configurePlaywrightManagerHost(overrides) {
|
|
1596
|
+
if (instances.size > 0 || spawning.size > 0 || pinnedInstances.size > 0) {
|
|
1597
|
+
throw new Error("cannot configure Playwright manager while browser instances are active");
|
|
1598
|
+
}
|
|
1599
|
+
const next = { ...managerHost, ...overrides };
|
|
1600
|
+
if (!next.portsDir || !Number.isInteger(next.basePort) || !Number.isInteger(next.maxPort)) {
|
|
1601
|
+
throw new Error("invalid Playwright manager paths or port range");
|
|
1602
|
+
}
|
|
1603
|
+
if (next.basePort < 1 || next.maxPort > 65535 || next.basePort > next.maxPort) {
|
|
1604
|
+
throw new Error("invalid Playwright manager port range");
|
|
1605
|
+
}
|
|
1606
|
+
if (!next.browserBin) {
|
|
1607
|
+
throw new Error("Browser manager gateway is required");
|
|
1608
|
+
}
|
|
1609
|
+
if (next.resolveInstanceDataDir !== defaultManagerHost.resolveInstanceDataDir && (next.cleanupBrowserProcessesForDataDir === defaultManagerHost.cleanupBrowserProcessesForDataDir || !next.removeProfileDataDir || next.removeProfileDataDir === defaultManagerHost.removeProfileDataDir || next.reapOrphanBrowsers === defaultManagerHost.reapOrphanBrowsers)) {
|
|
1610
|
+
throw new Error("custom Playwright profile paths require host crash cleanup, profile removal, and orphan sweep hooks");
|
|
1611
|
+
}
|
|
1612
|
+
managerHost = Object.freeze(next);
|
|
1613
|
+
return managerHost;
|
|
1614
|
+
}
|
|
1615
|
+
function getPlaywrightManagerHost() {
|
|
1616
|
+
return managerHost;
|
|
1617
|
+
}
|
|
1618
|
+
function resetPlaywrightManagerHost() {
|
|
1619
|
+
configurePlaywrightManagerHost(defaultManagerHost);
|
|
1620
|
+
}
|
|
1621
|
+
function parseInstanceKey(instanceKey) {
|
|
1622
|
+
const connectPort = parseConnectInstanceKey(instanceKey);
|
|
1623
|
+
if (connectPort !== undefined)
|
|
1624
|
+
return { ownerId: "local", profile: `_connect-${connectPort}` };
|
|
1625
|
+
const shared = /^profile:(.+)$/.exec(instanceKey);
|
|
1626
|
+
if (shared && !shared[1].includes(":")) {
|
|
1627
|
+
return { ownerId: "local", profile: normalizeBrowserProfileName(shared[1]) };
|
|
1628
|
+
}
|
|
1629
|
+
const match = /^profile:([^:]+):(.+)$/.exec(instanceKey);
|
|
1630
|
+
if (!match)
|
|
1631
|
+
return { ownerId: "legacy", profile: sanitizeTopicName(instanceKey) };
|
|
1632
|
+
return {
|
|
1633
|
+
ownerId: decodeURIComponent(match[1]),
|
|
1634
|
+
profile: normalizeBrowserProfileName(match[2])
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
function portFileName(instanceKey) {
|
|
1638
|
+
return createHash3("sha256").update(instanceKey).digest("hex").slice(0, 24);
|
|
1639
|
+
}
|
|
1640
|
+
function writePortFile(instanceKey, port) {
|
|
1641
|
+
try {
|
|
1642
|
+
mkdirSync4(managerHost.portsDir, { recursive: true });
|
|
1643
|
+
writeFileSync2(join5(managerHost.portsDir, portFileName(instanceKey)), String(port));
|
|
1644
|
+
} catch (e) {
|
|
1645
|
+
logger.warn({ err: e, instanceKey, port }, "Failed to save playwright port file");
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
function deletePortFile(instanceKey) {
|
|
1649
|
+
try {
|
|
1650
|
+
unlinkSync2(join5(managerHost.portsDir, portFileName(instanceKey)));
|
|
1651
|
+
} catch (e) {
|
|
1652
|
+
if (e.code === "ENOENT")
|
|
1653
|
+
return;
|
|
1654
|
+
logger.warn({ err: e, instanceKey }, "Failed to delete playwright port file");
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
function readPortFile(instanceKey) {
|
|
1658
|
+
try {
|
|
1659
|
+
const port = Number.parseInt(readFileSync2(join5(managerHost.portsDir, portFileName(instanceKey)), "utf8").trim(), 10);
|
|
1660
|
+
return Number.isInteger(port) ? port : null;
|
|
1661
|
+
} catch {
|
|
1662
|
+
return null;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
var MAX_IDLE_MS = 2 * 60 * 60 * 1000;
|
|
1666
|
+
var instances = new Map;
|
|
1667
|
+
function assertInstanceOwner(instanceKey, ownerId) {
|
|
1668
|
+
const existing = instances.get(instanceKey);
|
|
1669
|
+
if (existing && existing.ownerId !== ownerId) {
|
|
1670
|
+
throw new Error(`Playwright profile binding owner changed for "${instanceKey}" (${existing.ownerId} -> ${ownerId})`);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
var usedPorts = new Set;
|
|
1674
|
+
var spawning = new Map;
|
|
1675
|
+
async function withPlaywrightInstanceMaintenance(rawKeys, operation) {
|
|
1676
|
+
const keys = [...new Set(rawKeys)].sort();
|
|
1677
|
+
const lockedKeys = new Set(keys);
|
|
1678
|
+
for (;; ) {
|
|
1679
|
+
const pending = keys.map((key) => spawning.get(key)).filter((promise) => promise !== undefined);
|
|
1680
|
+
if (pending.length > 0) {
|
|
1681
|
+
await Promise.allSettled(pending);
|
|
1682
|
+
continue;
|
|
1683
|
+
}
|
|
1684
|
+
let releaseBarrier;
|
|
1685
|
+
const barrier = new Promise((resolveBarrier) => {
|
|
1686
|
+
releaseBarrier = () => resolveBarrier(null);
|
|
1687
|
+
});
|
|
1688
|
+
for (const key of keys)
|
|
1689
|
+
spawning.set(key, barrier);
|
|
1690
|
+
try {
|
|
1691
|
+
return await operation({
|
|
1692
|
+
async stopInstance(instanceKey) {
|
|
1693
|
+
if (!lockedKeys.has(instanceKey)) {
|
|
1694
|
+
throw new Error(`Playwright maintenance does not own instance "${instanceKey}"`);
|
|
1695
|
+
}
|
|
1696
|
+
const process2 = instances.get(instanceKey)?.process;
|
|
1697
|
+
if (!process2)
|
|
1698
|
+
return false;
|
|
1699
|
+
killInstance(instanceKey);
|
|
1700
|
+
if (!await waitForChildProcessExit(process2, 3000)) {
|
|
1701
|
+
logger.warn({ instanceKey, pid: process2.pid }, "Playwright MCP ignored SIGTERM during profile maintenance");
|
|
1702
|
+
try {
|
|
1703
|
+
process2.kill("SIGKILL");
|
|
1704
|
+
} catch (error) {
|
|
1705
|
+
logger.warn({ err: error, instanceKey, pid: process2.pid }, "Failed to SIGKILL Playwright MCP during profile maintenance");
|
|
1706
|
+
}
|
|
1707
|
+
await waitForChildProcessExit(process2, 1000);
|
|
1708
|
+
}
|
|
1709
|
+
return true;
|
|
1710
|
+
}
|
|
1711
|
+
});
|
|
1712
|
+
} finally {
|
|
1713
|
+
for (const key of keys) {
|
|
1714
|
+
if (spawning.get(key) === barrier)
|
|
1715
|
+
spawning.delete(key);
|
|
1716
|
+
}
|
|
1717
|
+
releaseBarrier();
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
function stopPlaywrightInstance(instanceKey) {
|
|
1722
|
+
return withPlaywrightInstanceMaintenance([instanceKey], ({ stopInstance }) => stopInstance(instanceKey));
|
|
1723
|
+
}
|
|
1724
|
+
function withPlaywrightProfileMaintenance(ownerId, rawProfile, operation) {
|
|
1725
|
+
const binding = resolvePlaywrightProfileBinding(ownerId, rawProfile);
|
|
1726
|
+
return withPlaywrightInstanceMaintenance([binding.instanceKey], async (control) => {
|
|
1727
|
+
assertInstanceOwner(binding.instanceKey, binding.ownerId);
|
|
1728
|
+
return operation(binding, control);
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
function stopPlaywrightProfile(ownerId, rawProfile) {
|
|
1732
|
+
return withPlaywrightProfileMaintenance(ownerId, rawProfile, (binding, { stopInstance }) => stopInstance(binding.instanceKey));
|
|
1733
|
+
}
|
|
1734
|
+
function removePlaywrightProfileData(ownerId, rawProfile, options = {}) {
|
|
1735
|
+
return withPlaywrightProfileMaintenance(ownerId, rawProfile, async (binding, { stopInstance }) => {
|
|
1736
|
+
const dataDir = resolveUserDataDir(binding.instanceKey);
|
|
1737
|
+
const processStopped = await stopInstance(binding.instanceKey);
|
|
1738
|
+
managerHost.cleanupBrowserProcessesForDataDir(dataDir);
|
|
1739
|
+
deletePortFile(binding.instanceKey);
|
|
1740
|
+
options.beforeRemove?.();
|
|
1741
|
+
const removeProfileDataDir = managerHost.removeProfileDataDir;
|
|
1742
|
+
if (!removeProfileDataDir) {
|
|
1743
|
+
throw new Error("Browser profile deletion is not configured for this host.");
|
|
1744
|
+
}
|
|
1745
|
+
const dataRemoved = removeProfileDataDir(dataDir);
|
|
1746
|
+
options.afterRemove?.();
|
|
1747
|
+
return { dataDir, processStopped, dataRemoved };
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
var pinnedInstances = new Map;
|
|
1751
|
+
function pinPlaywrightInstance(instanceKey) {
|
|
1752
|
+
pinnedInstances.set(instanceKey, (pinnedInstances.get(instanceKey) ?? 0) + 1);
|
|
1753
|
+
}
|
|
1754
|
+
function unpinPlaywrightInstance(instanceKey) {
|
|
1755
|
+
const count = pinnedInstances.get(instanceKey);
|
|
1756
|
+
if (count === undefined)
|
|
1757
|
+
return;
|
|
1758
|
+
if (count <= 1)
|
|
1759
|
+
pinnedInstances.delete(instanceKey);
|
|
1760
|
+
else
|
|
1761
|
+
pinnedInstances.set(instanceKey, count - 1);
|
|
1762
|
+
}
|
|
1763
|
+
function getPlaywrightCapability(instanceKey) {
|
|
1764
|
+
return instances.get(instanceKey)?.capability;
|
|
1765
|
+
}
|
|
1766
|
+
function resolvePlaywrightCapabilityOwner(capability) {
|
|
1767
|
+
if (!capability)
|
|
1768
|
+
return;
|
|
1769
|
+
const provided = Buffer.from(capability);
|
|
1770
|
+
for (const instance of instances.values()) {
|
|
1771
|
+
const expected = Buffer.from(instance.capability);
|
|
1772
|
+
if (provided.length === expected.length && timingSafeEqual2(provided, expected)) {
|
|
1773
|
+
return instance.ownerId;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
function reapPlaywrightOrphans() {
|
|
1779
|
+
managerHost.reapOrphanBrowsers([...instances.keys()].map(resolveUserDataDir));
|
|
1780
|
+
}
|
|
1781
|
+
var playwrightFailureHandlers = new Set;
|
|
1782
|
+
function onPlaywrightFailure(handler) {
|
|
1783
|
+
playwrightFailureHandlers.add(handler);
|
|
1784
|
+
return () => playwrightFailureHandlers.delete(handler);
|
|
1785
|
+
}
|
|
1786
|
+
function notifyPlaywrightFailure(instanceKey, failure) {
|
|
1787
|
+
for (const handler of playwrightFailureHandlers) {
|
|
1788
|
+
try {
|
|
1789
|
+
handler(instanceKey, failure);
|
|
1790
|
+
} catch (err) {
|
|
1791
|
+
logger.warn({ err, instanceKey, failure }, "Playwright failure handler failed");
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
function evictIdleInstance() {
|
|
1796
|
+
const now = Date.now();
|
|
1797
|
+
const oldestKey = selectIdleEvictionKey(instances, pinnedInstances.keys(), spawning.keys(), now, MAX_IDLE_MS);
|
|
1798
|
+
if (oldestKey) {
|
|
1799
|
+
const instance = instances.get(oldestKey);
|
|
1800
|
+
if (!instance)
|
|
1801
|
+
return null;
|
|
1802
|
+
const idleMin = ((now - instance.lastUsedAt) / 60000).toFixed(0);
|
|
1803
|
+
logger.info({ key: oldestKey, idleMin }, "Evicting idle playwright instance");
|
|
1804
|
+
killInstance(oldestKey);
|
|
1805
|
+
return instance.port;
|
|
1806
|
+
}
|
|
1807
|
+
return null;
|
|
1808
|
+
}
|
|
1809
|
+
async function allocatePort() {
|
|
1810
|
+
const port = await reserveAvailableLoopbackPort(managerHost.basePort, managerHost.maxPort, usedPorts, async (candidate) => {
|
|
1811
|
+
const occupied = await isPortInUse(candidate);
|
|
1812
|
+
if (occupied)
|
|
1813
|
+
logger.warn({ port: candidate }, "Port occupied by external process, skipping");
|
|
1814
|
+
return occupied;
|
|
1815
|
+
});
|
|
1816
|
+
if (port !== null)
|
|
1817
|
+
return port;
|
|
1818
|
+
const evictedPort = evictIdleInstance();
|
|
1819
|
+
if (evictedPort !== null) {
|
|
1820
|
+
await waitForPortRelease(evictedPort);
|
|
1821
|
+
return allocatePort();
|
|
1822
|
+
}
|
|
1823
|
+
throw new Error(`No available ports for Playwright MCP (${instances.size} active instances, range ${managerHost.basePort}-${managerHost.maxPort})`);
|
|
1824
|
+
}
|
|
1825
|
+
function releasePort(port) {
|
|
1826
|
+
usedPorts.delete(port);
|
|
1827
|
+
}
|
|
1828
|
+
function defaultProfileDir(_ownerId, profile) {
|
|
1829
|
+
return resolve6(BROWSER_PROFILES_DIR, profile);
|
|
1830
|
+
}
|
|
1831
|
+
function resolveUserDataDir(instanceKey) {
|
|
1832
|
+
return managerHost.resolveInstanceDataDir(instanceKey);
|
|
1833
|
+
}
|
|
1834
|
+
function killInstance(instanceKey, opts) {
|
|
1835
|
+
const inst = instances.get(instanceKey);
|
|
1836
|
+
if (!inst)
|
|
1837
|
+
return;
|
|
1838
|
+
if (inst.process.pid) {
|
|
1839
|
+
killProcessTreeChildren(inst.process.pid);
|
|
1840
|
+
}
|
|
1841
|
+
try {
|
|
1842
|
+
inst.process.kill("SIGTERM");
|
|
1843
|
+
} catch (e) {
|
|
1844
|
+
logger.warn({ err: e, instanceKey }, "Failed to kill playwright instance");
|
|
1845
|
+
}
|
|
1846
|
+
inst.vaultBroker.close();
|
|
1847
|
+
inst.process.removeAllListeners("error");
|
|
1848
|
+
inst.process.removeAllListeners("exit");
|
|
1849
|
+
cleanSingletonFiles(resolveUserDataDir(instanceKey));
|
|
1850
|
+
if (!opts?.keepPort)
|
|
1851
|
+
releasePort(inst.port);
|
|
1852
|
+
instances.delete(instanceKey);
|
|
1853
|
+
deletePortFile(instanceKey);
|
|
1854
|
+
logger.info({ instanceKey, port: inst.port, keepPort: !!opts?.keepPort }, "Killed Playwright MCP (with cleanup)");
|
|
1855
|
+
}
|
|
1856
|
+
var PLAYWRIGHT_STARTUP_STDERR_LIMIT = 8 * 1024;
|
|
1857
|
+
function captureBoundedStderr(proc) {
|
|
1858
|
+
let tail = Buffer.alloc(0);
|
|
1859
|
+
proc.stderr?.on("data", (chunk) => {
|
|
1860
|
+
const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1861
|
+
tail = Buffer.concat([tail, next]);
|
|
1862
|
+
if (tail.byteLength > PLAYWRIGHT_STARTUP_STDERR_LIMIT) {
|
|
1863
|
+
tail = tail.subarray(tail.byteLength - PLAYWRIGHT_STARTUP_STDERR_LIMIT);
|
|
1864
|
+
}
|
|
1865
|
+
});
|
|
1866
|
+
return () => tail.toString("utf8").trim();
|
|
1867
|
+
}
|
|
1868
|
+
function watchChildStartup(proc, stderrTail) {
|
|
1869
|
+
let stopped = false;
|
|
1870
|
+
let rejectFailure = () => {
|
|
1871
|
+
return;
|
|
1872
|
+
};
|
|
1873
|
+
const diagnostics = () => {
|
|
1874
|
+
const stderr = stderrTail();
|
|
1875
|
+
return stderr ? `
|
|
1876
|
+
stderr (last ${PLAYWRIGHT_STARTUP_STDERR_LIMIT} bytes):
|
|
1877
|
+
${stderr}` : "";
|
|
1878
|
+
};
|
|
1879
|
+
const onError = (error) => {
|
|
1880
|
+
rejectFailure(new Error(`Playwright MCP failed to spawn: ${error.message}${diagnostics()}`, {
|
|
1881
|
+
cause: error
|
|
1882
|
+
}));
|
|
1883
|
+
};
|
|
1884
|
+
const onExit = (code, signal) => {
|
|
1885
|
+
rejectFailure(new Error(`Playwright MCP exited during startup (code=${code ?? "null"}, signal=${signal ?? "null"})${diagnostics()}`));
|
|
1886
|
+
};
|
|
1887
|
+
const failure = new Promise((_resolve, reject) => {
|
|
1888
|
+
rejectFailure = reject;
|
|
1889
|
+
proc.once("error", onError);
|
|
1890
|
+
proc.once("exit", onExit);
|
|
1891
|
+
});
|
|
1892
|
+
const stop = () => {
|
|
1893
|
+
if (stopped)
|
|
1894
|
+
return;
|
|
1895
|
+
stopped = true;
|
|
1896
|
+
proc.off("error", onError);
|
|
1897
|
+
proc.off("exit", onExit);
|
|
1898
|
+
};
|
|
1899
|
+
return { failure, stop };
|
|
1900
|
+
}
|
|
1901
|
+
async function spawnPlaywright(instanceKey, ownerId, reservedPort, browserBin = managerHost.browserBin) {
|
|
1902
|
+
if (!managerHost.browserRsBin) {
|
|
1903
|
+
throw new Error("Browser.rs is unavailable or below the minimum secure version");
|
|
1904
|
+
}
|
|
1905
|
+
const userDataDir = resolveUserDataDir(instanceKey);
|
|
1906
|
+
const port = reservedPort ?? await allocatePort();
|
|
1907
|
+
mkdirSync4(userDataDir, { recursive: true });
|
|
1908
|
+
const mcpArgs = browserRsArgs(instanceKey, port, userDataDir);
|
|
1909
|
+
const proxy = managerHost.resolveProxy();
|
|
1910
|
+
if (proxy) {
|
|
1911
|
+
releasePort(port);
|
|
1912
|
+
throw new Error("Browser.rs managed mode does not support authenticated egress proxies");
|
|
1913
|
+
}
|
|
1914
|
+
const capability = randomBytes4(32).toString("hex");
|
|
1915
|
+
const spawnNonce = randomBytes4(32).toString("hex");
|
|
1916
|
+
let vaultBroker;
|
|
1917
|
+
try {
|
|
1918
|
+
vaultBroker = await createBrowserVaultBroker(ownerId);
|
|
1919
|
+
} catch (error) {
|
|
1920
|
+
releasePort(port);
|
|
1921
|
+
throw error;
|
|
1922
|
+
}
|
|
1923
|
+
const childEnv = {
|
|
1924
|
+
...managerHost.createChildEnvironment({
|
|
1925
|
+
instanceKey,
|
|
1926
|
+
ownerId,
|
|
1927
|
+
capability,
|
|
1928
|
+
proxy,
|
|
1929
|
+
browserRsBin: managerHost.browserRsBin,
|
|
1930
|
+
environment: process.env
|
|
1931
|
+
}),
|
|
1932
|
+
AB_MANAGED: "1",
|
|
1933
|
+
AB_HTTP_CAPABILITY: capability,
|
|
1934
|
+
AB_SPAWN_NONCE: spawnNonce,
|
|
1935
|
+
AB_SECRET_BROKER_SOCKET: vaultBroker.socketPath,
|
|
1936
|
+
AB_SECRET_BROKER_TOKEN: vaultBroker.token
|
|
1937
|
+
};
|
|
1938
|
+
const command = browserBin.endsWith(".mjs") ? process.execPath : browserBin;
|
|
1939
|
+
const args = browserBin.endsWith(".mjs") ? [browserBin, ...mcpArgs] : mcpArgs;
|
|
1940
|
+
let spawnSpec;
|
|
1941
|
+
try {
|
|
1942
|
+
spawnSpec = resolveHeadedPlaywrightSpawn(command, args, { environment: childEnv });
|
|
1943
|
+
} catch (err) {
|
|
1944
|
+
await vaultBroker.close();
|
|
1945
|
+
releasePort(port);
|
|
1946
|
+
throw err;
|
|
1947
|
+
}
|
|
1948
|
+
let proc;
|
|
1949
|
+
try {
|
|
1950
|
+
proc = spawn(spawnSpec.command, spawnSpec.args, {
|
|
1951
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1952
|
+
detached: false,
|
|
1953
|
+
env: childEnv,
|
|
1954
|
+
windowsHide: true
|
|
1955
|
+
});
|
|
1956
|
+
} catch (err) {
|
|
1957
|
+
await vaultBroker.close();
|
|
1958
|
+
releasePort(port);
|
|
1959
|
+
throw err;
|
|
1960
|
+
}
|
|
1961
|
+
const stderrTail = captureBoundedStderr(proc);
|
|
1962
|
+
const startup = watchChildStartup(proc, stderrTail);
|
|
1963
|
+
const reapCrashedBrowser = () => {
|
|
1964
|
+
const userDataDir2 = resolveUserDataDir(instanceKey);
|
|
1965
|
+
managerHost.cleanupBrowserProcessesForDataDir(userDataDir2);
|
|
1966
|
+
cleanSingletonFiles(userDataDir2);
|
|
1967
|
+
};
|
|
1968
|
+
proc.once("error", (err) => {
|
|
1969
|
+
logger.error({ err, instanceKey, stderr: stderrTail() || undefined }, "Playwright MCP error");
|
|
1970
|
+
if (instances.get(instanceKey)?.process === proc) {
|
|
1971
|
+
releasePort(port);
|
|
1972
|
+
instances.delete(instanceKey);
|
|
1973
|
+
vaultBroker.close();
|
|
1974
|
+
reapCrashedBrowser();
|
|
1975
|
+
notifyPlaywrightFailure(instanceKey, {
|
|
1976
|
+
reason: "process-error",
|
|
1977
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1978
|
+
});
|
|
1979
|
+
}
|
|
1980
|
+
});
|
|
1981
|
+
proc.once("exit", (code) => {
|
|
1982
|
+
logger.info({ instanceKey, code, stderr: stderrTail() || undefined }, "Playwright MCP exited");
|
|
1983
|
+
const wasOurs = instances.get(instanceKey)?.process === proc;
|
|
1984
|
+
if (wasOurs) {
|
|
1985
|
+
releasePort(port);
|
|
1986
|
+
instances.delete(instanceKey);
|
|
1987
|
+
vaultBroker.close();
|
|
1988
|
+
reapCrashedBrowser();
|
|
1989
|
+
notifyPlaywrightFailure(instanceKey, { reason: "exit", code });
|
|
1990
|
+
}
|
|
1991
|
+
});
|
|
1992
|
+
const now = Date.now();
|
|
1993
|
+
instances.set(instanceKey, {
|
|
1994
|
+
process: proc,
|
|
1995
|
+
port,
|
|
1996
|
+
ownerId,
|
|
1997
|
+
startedAt: now,
|
|
1998
|
+
lastUsedAt: now,
|
|
1999
|
+
capability,
|
|
2000
|
+
vaultBroker
|
|
2001
|
+
});
|
|
2002
|
+
let startupError;
|
|
2003
|
+
let ready = false;
|
|
2004
|
+
try {
|
|
2005
|
+
ready = await Promise.race([
|
|
2006
|
+
(async () => await waitForServer(port, spawnNonce, 1e4) && await supportsOwnerCleanup(port, capability) && await probePlaywrightMcpTransports(port, capability))(),
|
|
2007
|
+
startup.failure
|
|
2008
|
+
]);
|
|
2009
|
+
} catch (error) {
|
|
2010
|
+
startupError = error instanceof Error ? error : new Error(String(error));
|
|
2011
|
+
} finally {
|
|
2012
|
+
startup.stop();
|
|
2013
|
+
}
|
|
2014
|
+
if (ready && !isLiveOwnedChildProcess(instances.get(instanceKey), proc)) {
|
|
2015
|
+
ready = false;
|
|
2016
|
+
startupError = new Error(`Playwright MCP exited after readiness but before publication on port ${port}` + (stderrTail() ? `
|
|
2017
|
+
stderr:
|
|
2018
|
+
${stderrTail()}` : ""));
|
|
2019
|
+
}
|
|
2020
|
+
if (!ready) {
|
|
2021
|
+
const exitCode = proc.exitCode;
|
|
2022
|
+
killInstance(instanceKey);
|
|
2023
|
+
if (startupError)
|
|
2024
|
+
throw startupError;
|
|
2025
|
+
throw new Error(`Playwright MCP failed health check after spawn on port ${port}` + (exitCode === null ? "" : ` (exitCode=${exitCode})`) + (stderrTail() ? `
|
|
2026
|
+
stderr:
|
|
2027
|
+
${stderrTail()}` : ""));
|
|
2028
|
+
}
|
|
2029
|
+
writePortFile(instanceKey, port);
|
|
2030
|
+
logger.info({ instanceKey, port, pid: proc.pid, ready, virtualDisplay: spawnSpec.virtualDisplay }, "Playwright MCP started");
|
|
2031
|
+
return port;
|
|
2032
|
+
}
|
|
2033
|
+
async function supportsOwnerCleanup(port, capability) {
|
|
2034
|
+
try {
|
|
2035
|
+
const query = new URLSearchParams({ owner: "__negotium_capability_probe__" });
|
|
2036
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
|
|
2037
|
+
method: "DELETE",
|
|
2038
|
+
headers: {
|
|
2039
|
+
"X-Browser-Capability": capability
|
|
2040
|
+
},
|
|
2041
|
+
signal: AbortSignal.timeout(2000)
|
|
2042
|
+
});
|
|
2043
|
+
await response.body?.cancel();
|
|
2044
|
+
return response.ok;
|
|
2045
|
+
} catch {
|
|
2046
|
+
return false;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
async function ensurePlaywright(userId, topic) {
|
|
2050
|
+
const binding = resolvePlaywrightTopicBinding(userId, topic);
|
|
2051
|
+
const { instanceKey, ownerId } = binding;
|
|
2052
|
+
const inProgress = spawning.get(instanceKey);
|
|
2053
|
+
if (inProgress) {
|
|
2054
|
+
const port = await inProgress;
|
|
2055
|
+
assertInstanceOwner(instanceKey, ownerId);
|
|
2056
|
+
if (port !== null)
|
|
2057
|
+
return port;
|
|
2058
|
+
return ensurePlaywright(userId, topic);
|
|
2059
|
+
}
|
|
2060
|
+
const promise = (async () => {
|
|
2061
|
+
const existing = instances.get(instanceKey);
|
|
2062
|
+
assertInstanceOwner(instanceKey, ownerId);
|
|
2063
|
+
if (existing && !existing.process.killed && existing.process.exitCode === null) {
|
|
2064
|
+
if (await probePlaywrightMcpTransports(existing.port, existing.capability) && !await browserTransportLost(existing.port)) {
|
|
2065
|
+
existing.lastUsedAt = Date.now();
|
|
2066
|
+
return existing.port;
|
|
2067
|
+
}
|
|
2068
|
+
logger.warn({ instanceKey }, "Playwright MCP unresponsive, restarting");
|
|
2069
|
+
const oldPort = existing.port;
|
|
2070
|
+
killInstance(instanceKey);
|
|
2071
|
+
notifyPlaywrightFailure(instanceKey, { reason: "unhealthy" });
|
|
2072
|
+
await waitForPortRelease(oldPort);
|
|
2073
|
+
cleanSingletonFiles(resolveUserDataDir(instanceKey));
|
|
2074
|
+
} else if (existing) {
|
|
2075
|
+
releasePort(existing.port);
|
|
2076
|
+
instances.delete(instanceKey);
|
|
2077
|
+
cleanSingletonFiles(resolveUserDataDir(instanceKey));
|
|
2078
|
+
notifyPlaywrightFailure(instanceKey, {
|
|
2079
|
+
reason: "exit",
|
|
2080
|
+
code: existing.process.exitCode
|
|
2081
|
+
});
|
|
2082
|
+
}
|
|
2083
|
+
return spawnPlaywright(instanceKey, ownerId);
|
|
2084
|
+
})().finally(() => spawning.delete(instanceKey));
|
|
2085
|
+
spawning.set(instanceKey, promise);
|
|
2086
|
+
return promise;
|
|
2087
|
+
}
|
|
2088
|
+
async function waitForPortRelease(port, timeoutMs = 3000) {
|
|
2089
|
+
const start = Date.now();
|
|
2090
|
+
while (Date.now() - start < timeoutMs) {
|
|
2091
|
+
if (!await isPortInUse(port))
|
|
2092
|
+
return;
|
|
2093
|
+
await delay(200);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
async function ensureBrowserProfile(ownerId, rawProfile) {
|
|
2097
|
+
const binding = resolvePlaywrightProfileBinding(ownerId, rawProfile);
|
|
2098
|
+
const instanceKey = binding.instanceKey;
|
|
2099
|
+
const inProgress = spawning.get(instanceKey);
|
|
2100
|
+
if (inProgress) {
|
|
2101
|
+
const port = await inProgress;
|
|
2102
|
+
assertInstanceOwner(instanceKey, binding.ownerId);
|
|
2103
|
+
const capability = instances.get(instanceKey)?.capability;
|
|
2104
|
+
if (port !== null && capability && await probePlaywrightMcpTransports(port, capability)) {
|
|
2105
|
+
return port;
|
|
2106
|
+
}
|
|
2107
|
+
if (port === null)
|
|
2108
|
+
return ensureBrowserProfile(ownerId, rawProfile);
|
|
2109
|
+
throw new Error(`Browser profile "${rawProfile}" failed to start.`);
|
|
2110
|
+
}
|
|
2111
|
+
const promise = (async () => {
|
|
2112
|
+
const publishedPort = readPortFile(instanceKey);
|
|
2113
|
+
const existing = instances.get(instanceKey);
|
|
2114
|
+
assertInstanceOwner(instanceKey, binding.ownerId);
|
|
2115
|
+
if (publishedPort !== null && !existing) {
|
|
2116
|
+
logger.warn({ instanceKey, publishedPort }, "Recycling untracked browser profile process from stale port file");
|
|
2117
|
+
managerHost.cleanupBrowserProcessesForDataDir(resolveUserDataDir(instanceKey));
|
|
2118
|
+
await waitForPortRelease(publishedPort);
|
|
2119
|
+
deletePortFile(instanceKey);
|
|
2120
|
+
}
|
|
2121
|
+
if (existing && !existing.process.killed && existing.process.exitCode === null) {
|
|
2122
|
+
if (await probePlaywrightMcpTransports(existing.port, existing.capability) && !await browserTransportLost(existing.port)) {
|
|
2123
|
+
existing.lastUsedAt = Date.now();
|
|
2124
|
+
return existing.port;
|
|
2125
|
+
}
|
|
2126
|
+
const oldPort = existing.port;
|
|
2127
|
+
killInstance(instanceKey);
|
|
2128
|
+
notifyPlaywrightFailure(instanceKey, { reason: "unhealthy" });
|
|
2129
|
+
await waitForPortRelease(oldPort);
|
|
2130
|
+
cleanSingletonFiles(resolveUserDataDir(instanceKey));
|
|
2131
|
+
} else if (existing) {
|
|
2132
|
+
releasePort(existing.port);
|
|
2133
|
+
instances.delete(instanceKey);
|
|
2134
|
+
cleanSingletonFiles(resolveUserDataDir(instanceKey));
|
|
2135
|
+
notifyPlaywrightFailure(instanceKey, {
|
|
2136
|
+
reason: "exit",
|
|
2137
|
+
code: existing.process.exitCode
|
|
2138
|
+
});
|
|
2139
|
+
}
|
|
2140
|
+
const port = await spawnPlaywright(instanceKey, binding.ownerId);
|
|
2141
|
+
const capability = instances.get(instanceKey)?.capability;
|
|
2142
|
+
if (!capability || !await probePlaywrightMcpTransports(port, capability)) {
|
|
2143
|
+
killInstance(instanceKey);
|
|
2144
|
+
throw new Error(`Browser profile "${rawProfile}" did not pass its health check.`);
|
|
2145
|
+
}
|
|
2146
|
+
return port;
|
|
2147
|
+
})().finally(() => spawning.delete(instanceKey));
|
|
2148
|
+
spawning.set(instanceKey, promise);
|
|
2149
|
+
return promise;
|
|
2150
|
+
}
|
|
2151
|
+
async function closeBrowserOwnerTabs(ownerId, rawProfile, owner) {
|
|
2152
|
+
return closeBindingOwnerTabs(resolvePlaywrightProfileBinding(ownerId, rawProfile), owner);
|
|
2153
|
+
}
|
|
2154
|
+
async function closeBindingOwnerTabs(binding, owner) {
|
|
2155
|
+
const instanceKey = binding.instanceKey;
|
|
2156
|
+
const inProgress = spawning.get(instanceKey);
|
|
2157
|
+
if (inProgress)
|
|
2158
|
+
await inProgress;
|
|
2159
|
+
assertInstanceOwner(instanceKey, binding.ownerId);
|
|
2160
|
+
const instance = instances.get(instanceKey);
|
|
2161
|
+
if (!instance)
|
|
2162
|
+
return 0;
|
|
2163
|
+
const port = instance.port;
|
|
2164
|
+
const query = new URLSearchParams({ owner });
|
|
2165
|
+
const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
|
|
2166
|
+
method: "DELETE",
|
|
2167
|
+
headers: {
|
|
2168
|
+
"X-Browser-Capability": instance.capability
|
|
2169
|
+
},
|
|
2170
|
+
signal: AbortSignal.timeout(5000)
|
|
2171
|
+
});
|
|
2172
|
+
if (!response.ok)
|
|
2173
|
+
throw new Error(`browser MCP owner cleanup failed (${response.status})`);
|
|
2174
|
+
const result = await response.json();
|
|
2175
|
+
return typeof result.closed === "number" ? result.closed : 0;
|
|
2176
|
+
}
|
|
2177
|
+
async function browserTransportLost(port) {
|
|
2178
|
+
try {
|
|
2179
|
+
const response = await fetch(`http://127.0.0.1:${port}/health`, {
|
|
2180
|
+
signal: AbortSignal.timeout(1000)
|
|
2181
|
+
});
|
|
2182
|
+
if (!response.ok) {
|
|
2183
|
+
await response.body?.cancel();
|
|
2184
|
+
return false;
|
|
2185
|
+
}
|
|
2186
|
+
return browserCdpIsLost(await response.json());
|
|
2187
|
+
} catch {
|
|
2188
|
+
return false;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
async function waitForServer(port, expectedSpawnNonce, timeoutMs) {
|
|
2192
|
+
const start = Date.now();
|
|
2193
|
+
while (Date.now() - start < timeoutMs) {
|
|
2194
|
+
try {
|
|
2195
|
+
const response = await fetch(`http://127.0.0.1:${port}/health`, {
|
|
2196
|
+
signal: AbortSignal.timeout(1000)
|
|
2197
|
+
});
|
|
2198
|
+
if (response.ok) {
|
|
2199
|
+
const health = await response.json();
|
|
2200
|
+
if (matchesSpawnedBrowserHealth(health, expectedSpawnNonce)) {
|
|
2201
|
+
return true;
|
|
2202
|
+
}
|
|
2203
|
+
} else {
|
|
2204
|
+
await response.body?.cancel();
|
|
2205
|
+
}
|
|
2206
|
+
} catch {}
|
|
2207
|
+
await delay(300);
|
|
2208
|
+
}
|
|
2209
|
+
logger.warn({ port, timeoutMs }, "Playwright MCP not ready before timeout");
|
|
2210
|
+
return false;
|
|
2211
|
+
}
|
|
2212
|
+
function resolveTopicProfileDir(userId, topic) {
|
|
2213
|
+
return resolveUserDataDir(makeInstanceKey(userId, topic));
|
|
2214
|
+
}
|
|
2215
|
+
async function killAllPlaywright() {
|
|
2216
|
+
const procs = [...instances.entries()].map(([key, inst]) => ({ key, proc: inst.process }));
|
|
2217
|
+
for (const { key } of procs)
|
|
2218
|
+
killInstance(key);
|
|
2219
|
+
await Promise.all(procs.map(async ({ key, proc }) => {
|
|
2220
|
+
if (await waitForChildProcessExit(proc, 3000))
|
|
2221
|
+
return;
|
|
2222
|
+
logger.warn({ instanceKey: key, pid: proc.pid }, "Playwright MCP ignored SIGTERM");
|
|
2223
|
+
try {
|
|
2224
|
+
proc.kill("SIGKILL");
|
|
2225
|
+
} catch (err) {
|
|
2226
|
+
logger.warn({ err, instanceKey: key, pid: proc.pid }, "Failed to SIGKILL Playwright MCP");
|
|
2227
|
+
}
|
|
2228
|
+
if (!await waitForChildProcessExit(proc, 1000)) {
|
|
2229
|
+
logger.warn({ instanceKey: key, pid: proc.pid }, "Playwright MCP did not report exit");
|
|
2230
|
+
}
|
|
2231
|
+
}));
|
|
2232
|
+
}
|
|
2233
|
+
async function drainPlaywrightManager() {
|
|
2234
|
+
pinnedInstances.clear();
|
|
2235
|
+
await Promise.allSettled([...spawning.values()]);
|
|
2236
|
+
try {
|
|
2237
|
+
await killAllPlaywright();
|
|
2238
|
+
} catch (err) {
|
|
2239
|
+
logger.warn({ err }, "drainPlaywrightManager: killAllPlaywright failed; continuing");
|
|
2240
|
+
}
|
|
2241
|
+
await Promise.allSettled([...spawning.values()]);
|
|
2242
|
+
spawning.clear();
|
|
2243
|
+
pinnedInstances.clear();
|
|
2244
|
+
}
|
|
2245
|
+
setInterval(() => {
|
|
2246
|
+
while (evictIdleInstance() !== null) {}
|
|
2247
|
+
try {
|
|
2248
|
+
reapPlaywrightOrphans();
|
|
2249
|
+
} catch (e) {
|
|
2250
|
+
logger.debug({ err: e }, "reapOrphanBrowsers sweep failed");
|
|
2251
|
+
}
|
|
2252
|
+
}, 30 * 60 * 1000).unref();
|
|
2253
|
+
// ../../packages/core/src/platform/playwright/mcp-transport.ts
|
|
2254
|
+
var CODEX_BROWSER_CAPABILITY_ENV = "NEGOTIUM_BROWSER_CAPABILITY";
|
|
2255
|
+
function buildPlaywrightMcpTransport(port, owner, capability, agent) {
|
|
2256
|
+
const query = new URLSearchParams({ owner });
|
|
2257
|
+
const ownerCapability = browserOwnerCapability(capability, owner);
|
|
2258
|
+
if (agent === "codex") {
|
|
2259
|
+
return {
|
|
2260
|
+
url: `http://127.0.0.1:${port}/mcp?${query}`,
|
|
2261
|
+
env_http_headers: { "X-Browser-Capability": CODEX_BROWSER_CAPABILITY_ENV }
|
|
2262
|
+
};
|
|
2263
|
+
}
|
|
2264
|
+
if (agent === "maestro") {
|
|
2265
|
+
return {
|
|
2266
|
+
type: "http",
|
|
2267
|
+
url: `http://127.0.0.1:${port}/mcp?${query}`,
|
|
2268
|
+
headers: { "X-Browser-Capability": ownerCapability }
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
return {
|
|
2272
|
+
type: "sse",
|
|
2273
|
+
url: `http://127.0.0.1:${port}/sse?${query}`,
|
|
2274
|
+
headers: { "X-Browser-Capability": ownerCapability }
|
|
2275
|
+
};
|
|
2276
|
+
}
|
|
2277
|
+
// ../../packages/core/src/platform/playwright/profile-management.ts
|
|
2278
|
+
async function deleteManagedBrowserProfile(ownerId, rawProfile) {
|
|
2279
|
+
const profile = assertBrowserProfileDeletable(ownerId, rawProfile);
|
|
2280
|
+
let metadataRemoved = false;
|
|
2281
|
+
const removed = await removePlaywrightProfileData(ownerId, profile, {
|
|
2282
|
+
beforeRemove: () => {
|
|
2283
|
+
assertBrowserProfileDeletable(ownerId, profile);
|
|
2284
|
+
},
|
|
2285
|
+
afterRemove: () => {
|
|
2286
|
+
metadataRemoved = deleteBrowserProfile(ownerId, profile);
|
|
2287
|
+
}
|
|
2288
|
+
});
|
|
2289
|
+
return {
|
|
2290
|
+
profile,
|
|
2291
|
+
metadataRemoved,
|
|
2292
|
+
dataRemoved: removed.dataRemoved,
|
|
2293
|
+
processStopped: removed.processStopped
|
|
2294
|
+
};
|
|
2295
|
+
}
|
|
2296
|
+
export {
|
|
2297
|
+
withPlaywrightProfileMaintenance,
|
|
2298
|
+
withPlaywrightInstanceMaintenance,
|
|
2299
|
+
waitForChildProcessSpawnError,
|
|
2300
|
+
waitForChildProcessExit,
|
|
2301
|
+
unpinPlaywrightInstance,
|
|
2302
|
+
stopPlaywrightProfile,
|
|
2303
|
+
stopPlaywrightInstance,
|
|
2304
|
+
selectReusablePort,
|
|
2305
|
+
selectOrphanBrowserPids,
|
|
2306
|
+
selectIdleEvictionKey,
|
|
2307
|
+
resolveTopicProfileDir,
|
|
2308
|
+
resolvePlaywrightTopicBinding,
|
|
2309
|
+
resolvePlaywrightProfileBinding,
|
|
2310
|
+
resolvePlaywrightCapabilityOwner,
|
|
2311
|
+
resetPlaywrightManagerHost,
|
|
2312
|
+
removePlaywrightProfileData,
|
|
2313
|
+
reapPlaywrightOrphans,
|
|
2314
|
+
probePlaywrightMcpTransports,
|
|
2315
|
+
probeMcpTransport,
|
|
2316
|
+
pinPlaywrightInstance,
|
|
2317
|
+
onPlaywrightFailure,
|
|
2318
|
+
makeInstanceKey,
|
|
2319
|
+
makeBrowserProfileInstanceKey,
|
|
2320
|
+
killAllPlaywright,
|
|
2321
|
+
isBrowserJanitorOwner,
|
|
2322
|
+
getPlaywrightManagerHost,
|
|
2323
|
+
getPlaywrightCapability,
|
|
2324
|
+
extractUserDataDirArg,
|
|
2325
|
+
ensurePlaywright,
|
|
2326
|
+
ensureBrowserProfile,
|
|
2327
|
+
drainPlaywrightManager,
|
|
2328
|
+
deleteManagedBrowserProfile,
|
|
2329
|
+
configurePlaywrightManagerHost,
|
|
2330
|
+
closeBrowserOwnerTabs,
|
|
2331
|
+
buildPlaywrightMcpTransport,
|
|
2332
|
+
browserProcessMatchesExpectedProfile,
|
|
2333
|
+
CODEX_BROWSER_CAPABILITY_ENV
|
|
2334
|
+
};
|
|
2335
|
+
|
|
2336
|
+
//# debugId=25993FBC227401FD64756E2164756E21
|