@otium-team/negotium 0.0.0-stage → 0.23.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +329 -2
- package/bin/codex-sdk-window-hide.mjs +40 -0
- package/bin/negotium.mjs +22 -0
- package/dist/agent-helpers.js +23090 -0
- package/dist/agent-helpers.js.map +171 -0
- package/dist/background-bash.js +535 -0
- package/dist/background-bash.js.map +16 -0
- package/dist/browser-runtime.js +2334 -0
- package/dist/browser-runtime.js.map +35 -0
- package/dist/canonical-mcp-bridge.js +13 -0
- package/dist/canonical-mcp-bridge.js.map +9 -0
- package/dist/chunk-22kg3fsw.js +79 -0
- package/dist/chunk-22kg3fsw.js.map +9 -0
- package/dist/chunk-d4j77adx.js +336 -0
- package/dist/chunk-d4j77adx.js.map +13 -0
- package/dist/chunk-mk9x18jn.js +172 -0
- package/dist/chunk-mk9x18jn.js.map +12 -0
- package/dist/chunk-qd0vtfm2.js +3923 -0
- package/dist/chunk-qd0vtfm2.js.map +47 -0
- package/dist/chunk-wf7ny8eq.js +206 -0
- package/dist/chunk-wf7ny8eq.js.map +10 -0
- package/dist/chunk-ww8a4ej4.js +54 -0
- package/dist/chunk-ww8a4ej4.js.map +10 -0
- package/dist/cron.js +1 -0
- package/dist/hosted-agent.js +5982 -0
- package/dist/hosted-agent.js.map +62 -0
- package/dist/main.js +60229 -0
- package/dist/main.js.map +340 -0
- package/dist/mcp-catalog.js +39 -0
- package/dist/mcp-catalog.js.map +10 -0
- package/dist/mcp-factories.js +25767 -0
- package/dist/mcp-factories.js.map +181 -0
- package/dist/mcp-servers.js +50 -0
- package/dist/mcp-servers.js.map +10 -0
- package/dist/media.js +570 -0
- package/dist/media.js.map +15 -0
- package/dist/outbox.js +354 -0
- package/dist/outbox.js.map +15 -0
- package/dist/platform-runtime.js +73 -0
- package/dist/platform-runtime.js.map +12 -0
- package/dist/prompts.js +892 -0
- package/dist/prompts.js.map +15 -0
- package/dist/query-runtime.js +1071 -0
- package/dist/query-runtime.js.map +26 -0
- package/dist/registry.js +335 -0
- package/dist/registry.js.map +14 -0
- package/dist/rollout.js +57 -0
- package/dist/rollout.js.map +10 -0
- package/dist/runtime/cron/background-sessions.ts +119 -0
- package/dist/runtime/cron/context.ts +123 -0
- package/dist/runtime/cron/host.ts +67 -0
- package/dist/runtime/cron/index.ts +95 -0
- package/dist/runtime/cron/mcp-server.ts +556 -0
- package/dist/runtime/cron/module.ts +174 -0
- package/dist/runtime/cron/package.json +6 -0
- package/dist/runtime/cron/schedule.ts +211 -0
- package/dist/runtime/cron/scheduler.ts +444 -0
- package/dist/runtime/cron/scripts.ts +203 -0
- package/dist/runtime/cron/store.ts +1163 -0
- package/dist/runtime/cron/summarize.ts +115 -0
- package/dist/runtime/package.json +6 -0
- package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
- package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
- package/dist/runtime/src/agents/archiver.ts +677 -0
- package/dist/runtime/src/agents/auth-check.ts +156 -0
- package/dist/runtime/src/agents/claude-notices.ts +130 -0
- package/dist/runtime/src/agents/claude-provider.ts +941 -0
- package/dist/runtime/src/agents/claude-registry.ts +117 -0
- package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
- package/dist/runtime/src/agents/codex-app-server.ts +138 -0
- package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
- package/dist/runtime/src/agents/codex-provider.ts +1193 -0
- package/dist/runtime/src/agents/codex-registry.ts +116 -0
- package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
- package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
- package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
- package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
- package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
- package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
- package/dist/runtime/src/agents/compaction-support.ts +75 -0
- package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
- package/dist/runtime/src/agents/contracts.ts +75 -0
- package/dist/runtime/src/agents/deep-map.ts +13 -0
- package/dist/runtime/src/agents/execution-host.ts +118 -0
- package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
- package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
- package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
- package/dist/runtime/src/agents/fork.ts +100 -0
- package/dist/runtime/src/agents/hosted-agent.ts +78 -0
- package/dist/runtime/src/agents/idle-archiver.ts +225 -0
- package/dist/runtime/src/agents/idle-compact.ts +225 -0
- package/dist/runtime/src/agents/index.ts +225 -0
- package/dist/runtime/src/agents/maestro-provider.ts +246 -0
- package/dist/runtime/src/agents/maestro-registry.ts +189 -0
- package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
- package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
- package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
- package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
- package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
- package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
- package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
- package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
- package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
- package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
- package/dist/runtime/src/agents/model-catalog.ts +439 -0
- package/dist/runtime/src/agents/public-helpers.ts +149 -0
- package/dist/runtime/src/agents/registry.ts +35 -0
- package/dist/runtime/src/agents/rollout/claude.ts +336 -0
- package/dist/runtime/src/agents/rollout/codex.ts +910 -0
- package/dist/runtime/src/agents/rollout/index.ts +26 -0
- package/dist/runtime/src/agents/rollout/shared.ts +293 -0
- package/dist/runtime/src/agents/self-config-core.ts +704 -0
- package/dist/runtime/src/agents/task-events.ts +59 -0
- package/dist/runtime/src/agents/tool-format.ts +613 -0
- package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
- package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
- package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
- package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
- package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
- package/dist/runtime/src/application/submit-user-message.ts +60 -0
- package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
- package/dist/runtime/src/application/switch-topic-model.ts +79 -0
- package/dist/runtime/src/application/topic-service.ts +190 -0
- package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
- package/dist/runtime/src/application/vault-command.ts +170 -0
- package/dist/runtime/src/bus.ts +409 -0
- package/dist/runtime/src/config-public.ts +2 -0
- package/dist/runtime/src/cron-host.ts +33 -0
- package/dist/runtime/src/cron-mcp-host.ts +5 -0
- package/dist/runtime/src/identifiers.ts +49 -0
- package/dist/runtime/src/index.ts +573 -0
- package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
- package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
- package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
- package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
- package/dist/runtime/src/mcp/decision-server.ts +21 -0
- package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
- package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
- package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
- package/dist/runtime/src/mcp/factories/decision.ts +186 -0
- package/dist/runtime/src/mcp/factories/index.ts +73 -0
- package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
- package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
- package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
- package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
- package/dist/runtime/src/mcp/factories/task.ts +185 -0
- package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
- package/dist/runtime/src/mcp/factories/vault.ts +32 -0
- package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
- package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
- package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
- package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
- package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
- package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
- package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
- package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
- package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
- package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
- package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
- package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
- package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
- package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
- package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
- package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
- package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
- package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
- package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
- package/dist/runtime/src/mcp/session-history-server.ts +19 -0
- package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
- package/dist/runtime/src/mcp/system-health-server.ts +5 -0
- package/dist/runtime/src/mcp/task-server.ts +17 -0
- package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
- package/dist/runtime/src/mcp/vault-server.ts +12 -0
- package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
- package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
- package/dist/runtime/src/mcp-runtime-host.ts +81 -0
- package/dist/runtime/src/media/file-events.ts +33 -0
- package/dist/runtime/src/media/text-extractor.ts +334 -0
- package/dist/runtime/src/media/video.ts +92 -0
- package/dist/runtime/src/node-host.ts +211 -0
- package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
- package/dist/runtime/src/outbox/file-ops.ts +267 -0
- package/dist/runtime/src/outbox/index.ts +26 -0
- package/dist/runtime/src/outbox/utils.ts +74 -0
- package/dist/runtime/src/platform/background-bash/context.ts +9 -0
- package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
- package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
- package/dist/runtime/src/platform/config-helpers.ts +47 -0
- package/dist/runtime/src/platform/config.ts +618 -0
- package/dist/runtime/src/platform/constants.ts +30 -0
- package/dist/runtime/src/platform/debug-users.ts +14 -0
- package/dist/runtime/src/platform/delay.ts +1 -0
- package/dist/runtime/src/platform/error.ts +9 -0
- package/dist/runtime/src/platform/file-utils.ts +35 -0
- package/dist/runtime/src/platform/ipc.ts +55 -0
- package/dist/runtime/src/platform/jsonl.ts +277 -0
- package/dist/runtime/src/platform/lifecycle.ts +176 -0
- package/dist/runtime/src/platform/log-rotation.ts +45 -0
- package/dist/runtime/src/platform/logger.ts +42 -0
- package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
- package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
- package/dist/runtime/src/platform/mcp-config.ts +1329 -0
- package/dist/runtime/src/platform/memoize-import.ts +26 -0
- package/dist/runtime/src/platform/modules.ts +145 -0
- package/dist/runtime/src/platform/node-plugins.ts +46 -0
- package/dist/runtime/src/platform/paths.ts +62 -0
- package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
- package/dist/runtime/src/platform/playwright/capability.ts +5 -0
- package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
- package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
- package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
- package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
- package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
- package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
- package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
- package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
- package/dist/runtime/src/platform/public-runtime.ts +18 -0
- package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
- package/dist/runtime/src/prompts/builders.ts +696 -0
- package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
- package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
- package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
- package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
- package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
- package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
- package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
- package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
- package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
- package/dist/runtime/src/query/active-rooms.ts +514 -0
- package/dist/runtime/src/query/index.ts +23 -0
- package/dist/runtime/src/query/public-runtime.ts +28 -0
- package/dist/runtime/src/query/room-query-registry.ts +217 -0
- package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
- package/dist/runtime/src/query/session-inbox-path.ts +42 -0
- package/dist/runtime/src/query/state.ts +116 -0
- package/dist/runtime/src/query/types.ts +8 -0
- package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
- package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
- package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
- package/dist/runtime/src/runtime/attachments.ts +149 -0
- package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
- package/dist/runtime/src/runtime/background-sessions.ts +288 -0
- package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
- package/dist/runtime/src/runtime/channel-context.ts +115 -0
- package/dist/runtime/src/runtime/context-warning.ts +131 -0
- package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
- package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
- package/dist/runtime/src/runtime/errors.ts +70 -0
- package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
- package/dist/runtime/src/runtime/file-hooks.ts +81 -0
- package/dist/runtime/src/runtime/footer.ts +23 -0
- package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
- package/dist/runtime/src/runtime/inbox.ts +1307 -0
- package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
- package/dist/runtime/src/runtime/public-helpers.ts +78 -0
- package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
- package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
- package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
- package/dist/runtime/src/runtime/task-format.ts +18 -0
- package/dist/runtime/src/runtime/tasks.ts +53 -0
- package/dist/runtime/src/runtime/thread-context.ts +123 -0
- package/dist/runtime/src/runtime/thread-read.ts +67 -0
- package/dist/runtime/src/runtime/topic-config.ts +29 -0
- package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
- package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
- package/dist/runtime/src/runtime/turn-session.ts +116 -0
- package/dist/runtime/src/runtime/usage-alert.ts +51 -0
- package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
- package/dist/runtime/src/runtime/visual-html.ts +175 -0
- package/dist/runtime/src/runtime/visual-store.ts +480 -0
- package/dist/runtime/src/runtime/visuals.ts +209 -0
- package/dist/runtime/src/runtime-gateway.ts +1045 -0
- package/dist/runtime/src/security/sanitize.ts +27 -0
- package/dist/runtime/src/security/sensitive-path.ts +41 -0
- package/dist/runtime/src/storage/activity-log.ts +167 -0
- package/dist/runtime/src/storage/api-messages.ts +766 -0
- package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
- package/dist/runtime/src/storage/api-topic-config.ts +197 -0
- package/dist/runtime/src/storage/api-topics.ts +1647 -0
- package/dist/runtime/src/storage/app-settings.ts +50 -0
- package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
- package/dist/runtime/src/storage/browser-profiles.ts +186 -0
- package/dist/runtime/src/storage/conversation-migration.ts +180 -0
- package/dist/runtime/src/storage/conversations.ts +377 -0
- package/dist/runtime/src/storage/decisions.ts +231 -0
- package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
- package/dist/runtime/src/storage/forum/index.ts +4 -0
- package/dist/runtime/src/storage/forum/repository.ts +283 -0
- package/dist/runtime/src/storage/forum/schema.ts +314 -0
- package/dist/runtime/src/storage/forum-db.ts +4 -0
- package/dist/runtime/src/storage/remote-session.ts +1028 -0
- package/dist/runtime/src/storage/runtime-events.ts +209 -0
- package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
- package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
- package/dist/runtime/src/storage/runtime-leases.ts +190 -0
- package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
- package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
- package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
- package/dist/runtime/src/storage/self-schedules.ts +306 -0
- package/dist/runtime/src/storage/session-asks.ts +468 -0
- package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
- package/dist/runtime/src/storage/session-inbox.ts +161 -0
- package/dist/runtime/src/storage/sqlite.ts +154 -0
- package/dist/runtime/src/storage/storage-contract.ts +54 -0
- package/dist/runtime/src/storage/storage-host.ts +336 -0
- package/dist/runtime/src/storage/storage-public-host.ts +16 -0
- package/dist/runtime/src/storage/storage-public.ts +66 -0
- package/dist/runtime/src/storage/tasks.ts +172 -0
- package/dist/runtime/src/storage/token-stats.ts +432 -0
- package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
- package/dist/runtime/src/storage/topic-archive.ts +169 -0
- package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
- package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
- package/dist/runtime/src/storage/topic-settings.ts +67 -0
- package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
- package/dist/runtime/src/storage/topic-transcript.ts +98 -0
- package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
- package/dist/runtime/src/storage/vault-crypto.ts +31 -0
- package/dist/runtime/src/storage/vault-public.ts +27 -0
- package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
- package/dist/runtime/src/storage/vault.ts +388 -0
- package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
- package/dist/runtime/src/storage/wiki.ts +90 -0
- package/dist/runtime/src/topics/claim-abort.ts +190 -0
- package/dist/runtime/src/topics/create.ts +192 -0
- package/dist/runtime/src/topics/derive.ts +600 -0
- package/dist/runtime/src/topics/lifecycle.ts +425 -0
- package/dist/runtime/src/topics/links.ts +7 -0
- package/dist/runtime/src/topics/personal-general.ts +91 -0
- package/dist/runtime/src/topics/session.ts +1041 -0
- package/dist/runtime/src/topics/update.ts +287 -0
- package/dist/runtime/src/types/api.ts +591 -0
- package/dist/runtime/src/types.ts +418 -0
- package/dist/runtime/src/version.ts +1 -0
- package/dist/runtime/tsconfig.json +13 -0
- package/dist/runtime-gateway.js +514 -0
- package/dist/runtime-gateway.js.map +10 -0
- package/dist/runtime-helpers.js +1792 -0
- package/dist/runtime-helpers.js.map +40 -0
- package/dist/sqlite.js +66 -0
- package/dist/sqlite.js.map +10 -0
- package/dist/storage.js +5223 -0
- package/dist/storage.js.map +47 -0
- package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
- package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
- package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
- package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
- package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
- package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
- package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
- package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
- package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
- package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
- package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
- package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
- package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
- package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
- package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
- package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
- package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
- package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
- package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
- package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
- package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
- package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
- package/dist/types/packages/core/src/agents/index.d.ts +8 -0
- package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
- package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
- package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
- package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
- package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
- package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
- package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
- package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
- package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
- package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
- package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
- package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
- package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
- package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
- package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
- package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
- package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
- package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
- package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
- package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
- package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
- package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
- package/dist/types/packages/core/src/bus.d.ts +141 -0
- package/dist/types/packages/core/src/identifiers.d.ts +27 -0
- package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
- package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
- package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
- package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
- package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
- package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
- package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
- package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
- package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
- package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
- package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
- package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
- package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
- package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
- package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
- package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
- package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
- package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
- package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
- package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
- package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
- package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
- package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
- package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
- package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
- package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
- package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
- package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
- package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
- package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
- package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
- package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
- package/dist/types/packages/core/src/platform/config.d.ts +178 -0
- package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
- package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
- package/dist/types/packages/core/src/platform/error.d.ts +6 -0
- package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
- package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
- package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
- package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
- package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
- package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
- package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
- package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
- package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
- package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
- package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
- package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
- package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
- package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
- package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
- package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
- package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
- package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
- package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
- package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
- package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
- package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
- package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
- package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
- package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
- package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
- package/dist/types/packages/core/src/query/state.d.ts +25 -0
- package/dist/types/packages/core/src/query/types.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
- package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
- package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
- package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
- package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
- package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
- package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
- package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
- package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
- package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
- package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
- package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
- package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
- package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
- package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
- package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
- package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
- package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
- package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
- package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
- package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
- package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
- package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
- package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
- package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
- package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
- package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
- package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
- package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
- package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
- package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
- package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
- package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
- package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
- package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
- package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
- package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
- package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
- package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
- package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
- package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
- package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
- package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
- package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
- package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
- package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
- package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
- package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
- package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
- package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
- package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
- package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
- package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
- package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
- package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
- package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
- package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
- package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
- package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
- package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
- package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
- package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
- package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
- package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
- package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
- package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
- package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
- package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
- package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
- package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
- package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
- package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
- package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
- package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
- package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
- package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
- package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
- package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
- package/dist/types/packages/core/src/topics/links.d.ts +2 -0
- package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
- package/dist/types/packages/core/src/topics/session.d.ts +70 -0
- package/dist/types/packages/core/src/types/api.d.ts +551 -0
- package/dist/types/packages/core/src/types.d.ts +405 -0
- package/dist/types/packages/core/src/version.d.ts +1 -0
- package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
- package/dist/types/packages/module-cron/src/context.d.ts +15 -0
- package/dist/types/packages/module-cron/src/host.d.ts +23 -0
- package/dist/types/packages/module-cron/src/index.d.ts +14 -0
- package/dist/types/packages/module-cron/src/module.d.ts +13 -0
- package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
- package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
- package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
- package/dist/types/packages/module-cron/src/store.d.ts +152 -0
- package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
- package/dist/vault.js +848 -0
- package/dist/vault.js.map +18 -0
- package/install-bash-rs.mjs +90 -0
- package/install-browser-rs.mjs +83 -0
- package/package.json +171 -4
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../packages/core/src/media/text-extractor.ts", "../../../packages/core/src/platform/config.ts", "../../../packages/core/src/types.ts", "../../../packages/core/src/platform/config-helpers.ts", "../../../packages/core/src/platform/logger.ts", "../../../packages/core/src/platform/error.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { execFile } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { extname, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport {\n FASTER_WHISPER_WRAPPER,\n FFMPEG_BIN as FFMPEG_BIN_ENV,\n MLX_WHISPER_BIN,\n PDFTOTEXT_BIN,\n PYTHON_BIN,\n TESSERACT_BIN,\n WHISPER_BACKEND,\n WHISPER_MODEL,\n WHISPER_MODEL_MLX,\n type WhisperBackend,\n} from \"#platform/config\";\nimport { errMsg } from \"#platform/error\";\nimport { logger } from \"#platform/logger\";\n\nconst execFileAsync = promisify(execFile);\n\n// FFMPEG_BIN은 이 모듈에서 필수 — 미설정 시 기존처럼 spawn 시점에 실패한다.\nconst FFMPEG_BIN = FFMPEG_BIN_ENV as string;\n\n/** Text-readable file extensions */\nconst TEXT_EXTENSIONS = new Set([\n \".txt\",\n \".md\",\n \".csv\",\n \".tsv\",\n \".json\",\n \".jsonl\",\n \".xml\",\n \".html\",\n \".htm\",\n \".yaml\",\n \".yml\",\n \".toml\",\n \".ini\",\n \".cfg\",\n \".conf\",\n \".log\",\n \".env\",\n \".js\",\n \".ts\",\n \".jsx\",\n \".tsx\",\n \".py\",\n \".rb\",\n \".go\",\n \".java\",\n \".c\",\n \".cpp\",\n \".h\",\n \".hpp\",\n \".rs\",\n \".swift\",\n \".sh\",\n \".bash\",\n \".zsh\",\n \".fish\",\n \".ps1\",\n \".sql\",\n \".graphql\",\n \".proto\",\n \".css\",\n \".scss\",\n \".less\",\n \".sass\",\n \".r\",\n \".R\",\n \".m\",\n \".pl\",\n \".lua\",\n \".dart\",\n]);\n\n/** Image extensions for OCR */\nconst IMAGE_EXTENSIONS = new Set([\".jpg\", \".jpeg\", \".png\", \".bmp\", \".tiff\", \".tif\", \".webp\"]);\n\nexport interface ExtractionResult {\n text: string | null;\n method: \"text-read\" | \"pdf\" | \"ocr\" | \"whisper\" | \"unsupported\";\n error?: string;\n}\n\n/** Extract text from a file based on its type */\nexport async function extractText(filePath: string): Promise<ExtractionResult> {\n const ext = extname(filePath).toLowerCase();\n\n if (TEXT_EXTENSIONS.has(ext)) {\n return extractFromTextFile(filePath);\n }\n\n if (ext === \".pdf\") {\n return extractFromPdf(filePath);\n }\n\n if (IMAGE_EXTENSIONS.has(ext)) {\n return extractFromImage(filePath);\n }\n\n if (\n [\n \".mp3\",\n \".wav\",\n \".ogg\",\n \".m4a\",\n \".flac\",\n \".aac\",\n \".wma\",\n \".mp4\",\n \".webm\",\n \".mkv\",\n \".avi\",\n \".mov\",\n ].includes(ext)\n ) {\n return extractFromAudio(filePath);\n }\n\n // Try reading as text (might work for unknown text formats)\n try {\n const buf = await readFile(filePath);\n if (buf.length === 0) {\n return { text: null, method: \"unsupported\", error: \"Empty file\" };\n }\n // Check first 8KB for binary content (non-printable chars)\n const sample = buf.subarray(0, 8192);\n let nonPrintable = 0;\n for (let i = 0; i < sample.length; i++) {\n const b = sample[i];\n if (b < 32 && b !== 9 && b !== 10 && b !== 13) nonPrintable++;\n }\n if (nonPrintable / sample.length > 0.1) {\n return { text: null, method: \"unsupported\", error: \"Binary file, cannot extract text\" };\n }\n return { text: buf.toString(\"utf-8\"), method: \"text-read\" };\n } catch (e) {\n logger.warn({ err: e, filePath, ext }, \"Text extraction failed\");\n return { text: null, method: \"unsupported\", error: `Unsupported file type: ${ext}` };\n }\n}\n\n/** Read a text file directly */\nfunction extractFromTextFile(filePath: string): ExtractionResult {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n return { text: content, method: \"text-read\" };\n } catch (e) {\n return {\n text: null,\n method: \"text-read\",\n error: `Failed to read: ${errMsg(e)}`,\n };\n }\n}\n\n/** Extract text from PDF using pdftotext */\nasync function extractFromPdf(filePath: string): Promise<ExtractionResult> {\n try {\n const { stdout } = await execFileAsync(PDFTOTEXT_BIN, [\"-layout\", filePath, \"-\"], {\n timeout: 30000,\n });\n const text = stdout.trim();\n if (!text) {\n // PDF might be image-based, try OCR approach\n return {\n text: null,\n method: \"pdf\",\n error: \"PDF contains no extractable text (may be image-based)\",\n };\n }\n return { text, method: \"pdf\" };\n } catch (e) {\n logger.debug({ err: e, filePath }, \"pdftotext failed\");\n return {\n text: null,\n method: \"pdf\",\n error: `pdftotext failed: ${errMsg(e)}`,\n };\n }\n}\n\n/** Extract text from image using tesseract OCR */\nasync function extractFromImage(filePath: string): Promise<ExtractionResult> {\n try {\n const { stdout } = await execFileAsync(\n TESSERACT_BIN,\n [filePath, \"stdout\", \"-l\", \"kor+eng\", \"--psm\", \"3\"],\n { timeout: 60000 },\n );\n const text = stdout.trim();\n if (!text) {\n return { text: null, method: \"ocr\", error: \"OCR produced no text\" };\n }\n return { text, method: \"ocr\" };\n } catch (e) {\n logger.debug({ err: e, filePath }, \"tesseract OCR failed\");\n return {\n text: null,\n method: \"ocr\",\n error: `OCR failed: ${errMsg(e)}`,\n };\n }\n}\n\n/** Injectable binaries/paths for {@link transcribeAudio} — defaults come from\n * `#platform/config` env. Two backends are supported (see `WHISPER_BACKEND`):\n * `faster-whisper` (PYTHON_BIN + FASTER_WHISPER_WRAPPER + FFMPEG_BIN,\n * CPU-friendly, any host) and `mlx-whisper` (MLX_WHISPER_BIN + FFMPEG_BIN,\n * Apple Silicon only — mirrors clawgram's transcribe.ts). Overrides exist\n * for custom hosts and token-free tests. */\nexport interface TranscribeAudioOptions {\n backend?: WhisperBackend;\n ffmpegBin?: string;\n pythonBin?: string;\n wrapperPath?: string;\n mlxWhisperBin?: string;\n model?: string;\n language?: string;\n}\n\n/** True when the configured whisper backend can actually run on this host:\n * an ffmpeg binary plus that backend's interpreter/CLI both resolve. */\nexport function isTranscriptionConfigured(opts: TranscribeAudioOptions = {}): boolean {\n const ffmpeg = opts.ffmpegBin ?? FFMPEG_BIN_ENV;\n if (!ffmpeg) return false;\n const backend = opts.backend ?? WHISPER_BACKEND;\n if (backend === \"mlx-whisper\") {\n return Boolean(opts.mlxWhisperBin ?? MLX_WHISPER_BIN);\n }\n const wrapper = opts.wrapperPath ?? FASTER_WHISPER_WRAPPER;\n return existsSync(wrapper);\n}\n\n/**\n * Transcribe an audio/voice file with the local whisper pipeline (see\n * {@link TranscribeAudioOptions} for the backend choice). Returns `null` when\n * transcription is not configured on this node (missing ffmpeg/backend CLI)\n * or when the pipeline fails/produces no text — callers treat null as \"no\n * transcript available\", never as an error.\n */\nexport async function transcribeAudio(\n filePath: string,\n opts: TranscribeAudioOptions = {},\n): Promise<string | null> {\n if (!isTranscriptionConfigured(opts)) return null;\n const result = await extractFromAudio(filePath, opts);\n return result.text;\n}\n\n/** Extract text from audio/video using whisper (faster-whisper or mlx-whisper,\n * per {@link isTranscriptionConfigured}'s backend resolution). Both CLIs\n * accept the same `INPUT --model M --language L --output-dir D\n * --output-format txt` shape and write `{basename}.txt`, so only the\n * binary/model selection differs between backends. */\nasync function extractFromAudio(\n filePath: string,\n opts: TranscribeAudioOptions = {},\n): Promise<ExtractionResult> {\n const tmpDir = `${filePath}_whisper_tmp`;\n const backend = opts.backend ?? WHISPER_BACKEND;\n try {\n mkdirSync(tmpDir, { recursive: true });\n\n const mp3Path = join(tmpDir, \"audio.mp3\");\n await execFileAsync(\n opts.ffmpegBin ?? FFMPEG_BIN,\n [\n \"-y\",\n \"-i\",\n filePath,\n \"-acodec\",\n \"libmp3lame\",\n \"-q:a\",\n \"4\",\n \"-ac\",\n \"1\",\n \"-ar\",\n \"16000\",\n mp3Path,\n ],\n { timeout: 60000 },\n );\n\n const whisperArgs = [\n mp3Path,\n \"--model\",\n opts.model ?? (backend === \"mlx-whisper\" ? WHISPER_MODEL_MLX : WHISPER_MODEL),\n \"--language\",\n opts.language ?? \"ko\",\n \"--output-dir\",\n tmpDir,\n \"--output-format\",\n \"txt\",\n ];\n if (backend === \"mlx-whisper\") {\n const mlxWhisperBin = opts.mlxWhisperBin ?? MLX_WHISPER_BIN;\n if (!mlxWhisperBin) {\n return { text: null, method: \"whisper\", error: \"MLX_WHISPER_BIN not configured\" };\n }\n await execFileAsync(mlxWhisperBin, whisperArgs, { timeout: 300000 });\n } else {\n await execFileAsync(\n opts.pythonBin ?? PYTHON_BIN,\n [opts.wrapperPath ?? FASTER_WHISPER_WRAPPER, ...whisperArgs],\n { timeout: 120000 },\n );\n }\n\n const txtPath = join(tmpDir, \"audio.txt\");\n const text = existsSync(txtPath) ? readFileSync(txtPath, \"utf-8\").trim() : null;\n\n if (!text) {\n return { text: null, method: \"whisper\", error: \"Whisper produced no text\" };\n }\n return { text, method: \"whisper\" };\n } catch (e) {\n logger.debug({ err: e, filePath, backend }, \"whisper extraction failed\");\n return {\n text: null,\n method: \"whisper\",\n error: `Whisper failed: ${errMsg(e)}`,\n };\n } finally {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch (e) {\n logger.warn({ err: e, tmpDir }, \"Failed to cleanup whisper tmpDir\");\n }\n }\n}\n",
|
|
6
|
+
"import { execFileSync } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n accessSync,\n chmodSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n parseRuntimePort,\n readEnvText,\n resolveFallbackAgent,\n safeRuntimePathSegment,\n} from \"#platform/config-helpers\";\nimport { logger } from \"#platform/logger\";\nimport { type AgentKind, EFFORT_VALUES, type EffortLevel } from \"#types\";\n\nexport function envText(envKey: string): string | undefined {\n return readEnvText(process.env, envKey);\n}\n\nconst HOME = homedir();\n\nfunction resolveStateDir(): string {\n const configured = envText(\"NEGOTIUM_STATE_DIR\");\n if (process.env.NODE_ENV === \"test\" && !configured) {\n throw new Error(\n \"NEGOTIUM_STATE_DIR must be set before importing #platform/config in test processes\",\n );\n }\n return configured ? resolve(configured) : resolve(HOME, \".negotium\");\n}\n\n// new URL(\"../..\", import.meta.url) causes webpack to treat \"../..\" as a module import.\n// Split into fileURLToPath → dirname → resolve to avoid that.\nfunction resolveProjectRoot(): string {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const packagedRuntime = resolve(moduleDir, \"runtime\");\n if (existsSync(resolve(packagedRuntime, \"src\"))) return packagedRuntime;\n return resolve(moduleDir, \"../..\");\n}\n\nexport const PROJECT_ROOT = resolveProjectRoot();\n\n/** Resolve a dependency executable from either a package-local or hoisted install. */\n/**\n * Names a package-manager shim can carry in `node_modules/.bin`.\n *\n * POSIX gets one extension-less executable. Windows has no execute bit, so the\n * installer writes an extension instead — bun produces `<name>.exe` plus a\n * `<name>.bunx` stub, npm a `.cmd`/`.ps1` pair — and probing only the bare name\n * finds nothing, leaving the resolved path pointing at a file that does not\n * exist.\n */\nfunction dependencyBinNames(name: string): string[] {\n if (process.platform !== \"win32\") return [name];\n return [name, `${name}.exe`, `${name}.cmd`, `${name}.bat`, `${name}.bunx`];\n}\n\nfunction resolveDependencyBin(name: string): string {\n let dir = PROJECT_ROOT;\n while (true) {\n const binDir = resolve(dir, \"node_modules\", \".bin\");\n for (const candidate of dependencyBinNames(name)) {\n const path = resolve(binDir, candidate);\n if (existsSync(path)) return path;\n }\n const parent = dirname(dir);\n // Exhausted: hand back the canonical spelling so the failure names the\n // path that was expected.\n if (parent === dir) return resolve(binDir, name);\n dir = parent;\n }\n}\n\n// Each machine is one negotium node; all node state lives in one dotdir.\n// NEGOTIUM_STATE_DIR overrides (useful for tests and multi-node-on-one-box).\nexport const STATE_DIR = resolveStateDir();\n\nfunction resolveLocalStateDir(envKey: string, stateName: string): string {\n const envValue = envText(envKey);\n if (envValue) return resolve(envValue);\n return resolve(STATE_DIR, stateName);\n}\n\nfunction parsePortEnv(envValue: string | undefined, fallback: number): number {\n return parseRuntimePort(envValue, fallback);\n}\n\nexport const WORKSPACE_DIR = resolveLocalStateDir(\"NEGOTIUM_WORKSPACE_DIR\", \"workspace\");\nexport const TOPIC_WORKSPACE_DIR = resolve(WORKSPACE_DIR, \"topics\");\nexport const SHARED_WIKI_DIR = resolve(WORKSPACE_DIR, \"wiki\");\nexport const CRON_WORKSPACE_DIR = resolve(WORKSPACE_DIR, \"cron\");\nexport const BROWSER_DIR = resolveLocalStateDir(\"NEGOTIUM_BROWSER_DIR\", \"browser\");\nexport const BROWSER_PROFILES_DIR = resolve(BROWSER_DIR, \"profiles\");\nexport const BINARIES_DIR = resolve(STATE_DIR, \"binaries\");\nexport const SECRETS_DIR = resolve(STATE_DIR, \"secrets\");\n// Legacy names remain public, but their durable contents now live under data.\nexport const DM_WORKSPACE_DIR = resolve(STATE_DIR, \"data\", \"dm\");\nexport const SESSION_WORKSPACE_DIR = resolve(STATE_DIR, \"data\", \"sessions\");\n// The Claude Agent SDK ships a platform-matched Claude Code binary. Keep that\n// SDK/CLI pair together by default; only use an external executable when an\n// operator explicitly opts in. This avoids silently pairing an older SDK with\n// a newer globally installed Claude Code release.\nconst CLAUDE_EXECUTABLE_ENV = envText(\"NEGOTIUM_CLAUDE_EXECUTABLE\");\nexport const CLAUDE_EXECUTABLE = CLAUDE_EXECUTABLE_ENV ? resolve(CLAUDE_EXECUTABLE_ENV) : undefined;\n\n// Fallback output language for model-generated prose (topic/channel/manager\n// replies and the archiver's summaries, briefs, articles, completion reply).\n// Defaults to English; set `NEGOTIUM_LANG` to the user's mother tongue (e.g.\n// `Korean`, `ko`). The assistant still mirrors whatever language the user\n// writes in; `NEGOTIUM_MEMORY_LANG` can narrow just the archiver. Fixed system\n// chrome / degraded-path strings emitted by code stay English (can't translate\n// an arbitrary value at runtime).\nexport const DEFAULT_OUTPUT_LANGUAGE = \"English\";\n\nexport function resolveOutputLanguage(): string {\n const raw = envText(\"NEGOTIUM_LANG\")?.trim();\n return raw && raw.length > 0 ? raw : DEFAULT_OUTPUT_LANGUAGE;\n}\n\n/**\n * Suffix the managed Rust helpers carry on this platform.\n *\n * The installers write the binary under its plain name, which on Windows is\n * not executable — the release asset is `browser-rs.exe` and the resolver has\n * to look for exactly that. Empty everywhere else, so POSIX paths are\n * unchanged.\n */\nexport const BINARY_EXTENSION = process.platform === \"win32\" ? \".exe\" : \"\";\n\n/** Browser.rs release tested with this Negotium version. */\nexport const BROWSER_RS_VERSION = \"v0.7.7\";\n/** Require the authenticated listener and the current Browser.rs tool contract. */\nexport const BROWSER_RS_MIN_SECURE_VERSION = \"0.2.1\";\n\nfunction versionAtLeast(actualVersion: string, minimumVersion: string): boolean {\n const actual = actualVersion.split(\".\").map(Number);\n const minimum = minimumVersion.split(\".\").map(Number);\n if (actual.some(Number.isNaN) || minimum.some(Number.isNaN)) return false;\n for (let index = 0; index < minimum.length; index += 1) {\n if ((actual[index] ?? 0) > (minimum[index] ?? 0)) return true;\n if ((actual[index] ?? 0) < (minimum[index] ?? 0)) return false;\n }\n return true;\n}\n\n/**\n * Ceiling for the `--version` probe, not a latency expectation.\n *\n * The probe exists so a wedged binary cannot hang startup; a healthy one\n * answers in milliseconds. At 2s it also failed whenever the machine was merely\n * busy — process startup under a loaded test suite regularly exceeds that —\n * which turned a correctness check into a load measurement and made\n * `resolveBrowserRsBin` intermittently report a perfectly good binary as\n * unusable. Generous enough that only a genuinely stuck process trips it.\n */\nconst BROWSER_RS_VERSION_PROBE_TIMEOUT_MS = 15_000;\n\nfunction browserRsMeetsMinimumVersion(candidate: string): boolean {\n try {\n const output = execFileSync(candidate, [\"--version\"], {\n encoding: \"utf8\",\n timeout: BROWSER_RS_VERSION_PROBE_TIMEOUT_MS,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n // This module is imported by every CLI invocation, so on Windows the\n // probe blinked a console window each time `negotium` was run. Ignored\n // on POSIX.\n windowsHide: true,\n }).trim();\n const match = output.match(/^browser-rs (\\d+)\\.(\\d+)\\.(\\d+)$/);\n if (!match) return false;\n return versionAtLeast(match.slice(1).join(\".\"), BROWSER_RS_MIN_SECURE_VERSION);\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the preferred Browser.rs engine without consulting PATH. The\n * versioned private location keeps different Negotium releases reproducible\n * and avoids changing a user's global browser-rs installation.\n */\nexport function resolveBrowserRsBin(envValue?: string): string | undefined {\n const override = envValue?.trim();\n if (\n !override &&\n !versionAtLeast(BROWSER_RS_VERSION.replace(/^v/, \"\"), BROWSER_RS_MIN_SECURE_VERSION)\n ) {\n return undefined;\n }\n const candidate = override\n ? resolve(override)\n : resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return browserRsMeetsMinimumVersion(candidate) ? candidate : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Backend that stores documents published by `publish_html` and serves them\n * at `<base>/snippets/<id>`. Unset means the deployment has nowhere to\n * publish, and the publish tools are omitted from the catalog rather than\n * offering a link that cannot be minted.\n */\nexport const SNIPPETS_API_URL = (\n envText(\"NEGOTIUM_SNIPPETS_API_URL\") ??\n envText(\"SNIPPETS_API_URL\") ??\n \"\"\n).replace(/\\/+$/, \"\");\n\nexport const BROWSER_RS_BIN = resolveBrowserRsBin(envText(\"NEGOTIUM_BROWSER_RS_BIN\"));\n\n/** bash-rs release tested with this Negotium version — see apps/negotium/install-bash-rs.mjs. */\nexport const BASH_RS_VERSION = \"v0.1.10\";\n\n/**\n * Resolve the bash-rs binary the same way `resolveBrowserRsBin` resolves\n * Browser.rs: a versioned private location, no PATH lookup, `undefined`\n * (rather than throwing) when it's missing. There is no substitute: the manager\n * throws when a turn tries to prepare background-bash without a binary (see\n * `background-bash/manager.ts`), the turn runner catches that and continues\n * with a reminder that the tools are gone, so background-bash is simply\n * unavailable on a platform without a prebuilt binary.\n */\nexport function resolveBashRsBin(envValue?: string): string | undefined {\n const override = envValue?.trim();\n const candidate = override\n ? resolve(override)\n : resolve(BINARIES_DIR, \"bash-rs\", BASH_RS_VERSION, `bash-rs${BINARY_EXTENSION}`);\n try {\n accessSync(candidate, constants.X_OK);\n return candidate;\n } catch {\n return undefined;\n }\n}\n\nexport const BASH_RS_BIN = resolveBashRsBin(envText(\"NEGOTIUM_BASH_RS_BIN\"));\n\n// Managed Browser.rs terminates MCP transports and security policy itself.\nexport function resolveBrowserMcpBin(envValue?: string): string {\n const override = envValue?.trim();\n if (override) return resolve(override);\n return (\n BROWSER_RS_BIN ??\n resolve(BINARIES_DIR, \"browser-rs\", BROWSER_RS_VERSION, `browser-rs${BINARY_EXTENSION}`)\n );\n}\n\nexport const PLAYWRIGHT_MCP_BIN = resolveBrowserMcpBin(envText(\"NEGOTIUM_BROWSER_MCP_BIN\"));\n\n// --- Browser egress proxy ---\n//\n// On a datacenter host (AWS) the browser's egress IP is a known cloud range,\n// so anti-bot services (Cloudflare, DataDome, reCAPTCHA) challenge or block it\n// far more than a residential IP would. Routing the automation browser through\n// a residential/ISP proxy moves the egress IP out of the datacenter range.\n//\n// Operators set BROWSER_PROXY_URL, e.g. http://user:pass@proxy.host:8080 or\n// socks5://proxy.host:1080. Credentials in the URL are split out because\n// Playwright takes them as separate fields. BROWSER_PROXY_BYPASS is an optional\n// comma-separated no-proxy list (e.g. \"localhost,127.0.0.1,*.internal\").\n//\n// NOTE: Chromium does not support authentication for SOCKS proxies — put\n// credentials only on http/https proxy URLs.\nexport type BrowserProxyConfig = {\n server: string;\n username?: string;\n password?: string;\n bypass?: string;\n};\n\nexport function resolveBrowserProxy(): BrowserProxyConfig | null {\n const raw = envText(\"BROWSER_PROXY_URL\");\n if (!raw) return null;\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n logger.warn({ raw }, \"Ignoring malformed BROWSER_PROXY_URL\");\n return null;\n }\n // Playwright wants the server without embedded credentials.\n const server = `${url.protocol}//${url.host}`;\n const proxy: BrowserProxyConfig = { server };\n if (url.username) proxy.username = decodeURIComponent(url.username);\n if (url.password) proxy.password = decodeURIComponent(url.password);\n const bypass = envText(\"BROWSER_PROXY_BYPASS\");\n if (bypass) proxy.bypass = bypass;\n return proxy;\n}\n\n// --- Node/tsx runtime for the `codex` agent's MCP servers ---\n//\n// codex 0.135's rmcp stdio MCP client cannot reliably complete the initialize\n// handshake with servers spawned via `bun` (the JSON-RPC initialize is\n// dropped/raced and no tools ever reach the model). Pure-node servers connect\n// reliably, so codex turns launch the SAME .ts servers via node + tsx instead\n// of `bun run`. claude/maestro keep using `bun run` (fast, native, unaffected).\n//\n// tsx transpiles .ts on the fly and resolves the `@/*` tsconfig path aliases,\n// but only when it can find the tsconfig — and MCP servers run with cwd set to\n// the user's workspace dir, not PROJECT_ROOT — so we pass TSX_TSCONFIG_PATH\n// explicitly via env. Requires package.json `\"type\": \"module\"` so the servers'\n// top-level `await` loads as ESM under node.\nexport const TSX_BIN = resolveDependencyBin(\"tsx\");\n/**\n * In-process tsx loader used by Node MCP entrypoints (avoids the tsx CLI child\n * process).\n *\n * `node --import` takes a module specifier, not a filesystem path. A POSIX\n * absolute path happens to be a valid one; a Windows `C:\\…` is not — Node reads\n * the drive letter as a URL scheme and refuses it with\n * ERR_UNSUPPORTED_ESM_URL_SCHEME, which took out every tsx-hosted MCP server\n * (the Codex tool surface) at spawn. Hand it a `file://` URL there, and leave\n * the POSIX value exactly as it was.\n */\nconst TSX_LOADER_PATH = createRequire(import.meta.url).resolve(\"tsx\");\nexport const TSX_LOADER =\n process.platform === \"win32\" ? pathToFileURL(TSX_LOADER_PATH).href : TSX_LOADER_PATH;\nexport const TSCONFIG_PATH = resolve(PROJECT_ROOT, \"tsconfig.json\");\n\nexport const SESSION_COMM_SERVER = resolve(PROJECT_ROOT, \"src/mcp/session-comm/server.ts\");\n\nexport const TASK_SERVER = resolve(PROJECT_ROOT, \"src/mcp/task-server.ts\");\nexport const DECISION_SERVER = resolve(PROJECT_ROOT, \"src/mcp/decision-server.ts\");\nexport const CANONICAL_MCP_PROXY_SERVER = resolve(\n PROJECT_ROOT,\n \"src/mcp/canonical-proxy-server.ts\",\n);\n\nexport const WIKI_SERVER = resolve(PROJECT_ROOT, \"src/mcp/wiki-server.ts\");\n\nexport const TOKEN_STATS_SERVER = resolve(PROJECT_ROOT, \"src/mcp/token-stats-server.ts\");\n\nexport const COMPACTION_LOG_SERVER = resolve(PROJECT_ROOT, \"src/mcp/compaction-log-server.ts\");\n\nexport const SESSION_HISTORY_SERVER = resolve(PROJECT_ROOT, \"src/mcp/session-history-server.ts\");\n\nexport const SYSTEM_HEALTH_SERVER = resolve(PROJECT_ROOT, \"src/mcp/system-health-server.ts\");\n\nexport const AGENT_HEALTH_SERVER = resolve(PROJECT_ROOT, \"src/mcp/agent-health-server.ts\");\n\nexport const VAULT_SERVER = resolve(PROJECT_ROOT, \"src/mcp/vault-server.ts\");\n\nexport const BG_BASH_BASE_PORT = parsePortEnv(process.env.BG_BASH_BASE_PORT, 9700);\nexport const BG_BASH_MAX_PORT = parsePortEnv(process.env.BG_BASH_MAX_PORT, 9799);\n\nfunction safeWorkspaceSegment(value: string, fallback: string): string {\n return safeRuntimePathSegment(value, fallback);\n}\n\n/** Resolve the shared filesystem workspace for an API topic. */\nexport function resolveTopicWorkspaceDir(topicId: string): string {\n return join(TOPIC_WORKSPACE_DIR, safeWorkspaceSegment(topicId, \"topic\"));\n}\n\nexport function isProductionEnv(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\nfunction loadOrCreateLocalSecret(\n envKey: string,\n filename: string,\n options: { persistEnvValue?: boolean } = {},\n): string {\n const envValue = envText(envKey);\n const secretFile = resolve(SECRETS_DIR, filename);\n mkdirSync(dirname(secretFile), { recursive: true });\n if (envValue) {\n if (options.persistEnvValue) {\n writeFileSync(secretFile, `${envValue}\\n`, { mode: 0o600 });\n chmodSync(secretFile, 0o600);\n }\n return envValue;\n }\n\n if (existsSync(secretFile)) {\n const stored = readFileSync(secretFile, \"utf-8\").trim();\n if (stored) {\n chmodSync(secretFile, 0o600);\n return stored;\n }\n }\n\n const secret = randomBytes(32).toString(\"base64url\");\n try {\n writeFileSync(secretFile, `${secret}\\n`, { mode: 0o600, flag: \"wx\" });\n return secret;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n const stored = readFileSync(secretFile, \"utf-8\").trim();\n if (!stored) throw new Error(`Secret file exists but is empty: ${secretFile}`);\n chmodSync(secretFile, 0o600);\n return stored;\n }\n}\n\nexport const RUNTIME_MCP_SECRET = loadOrCreateLocalSecret(\n \"RUNTIME_MCP_SECRET\",\n \"runtime-mcp-secret\",\n);\n/** Local bearer token for the loopback node-control API. */\nexport const NODE_CONTROL_TOKEN = loadOrCreateLocalSecret(\n \"NEGOTIUM_CONTROL_TOKEN\",\n \"node-control-token\",\n);\n/**\n * Stable identity of this node's store, minted once and kept across restarts.\n *\n * Deliberately not a secret: it is published in the gateway health response so a\n * host can tell \"the node I recorded a mapping against\" apart from \"whatever is\n * answering on that port today\". Without it, pointing a host at a different node\n * makes every existing mapping look like a topic whose owner withdrew it, and the\n * same topics come back as duplicate rooms. It shares the secrets directory only\n * because that is already where per-install state that must survive restarts\n * lives; the stricter file mode costs nothing.\n */\nexport const NODE_ID = loadOrCreateLocalSecret(\"NEGOTIUM_NODE_ID\", \"node-id\");\nexport const VAULT_MASTER_KEY = loadOrCreateLocalSecret(\n \"NEGOTIUM_VAULT_MASTER_KEY\",\n \"vault-master-key\",\n { persistEnvValue: true },\n);\n// Agent/tool subprocesses inherit process.env. Keep the loaded key in this\n// process only so `env`/`ps` inside an agent workspace cannot reveal it.\ndelete process.env.NEGOTIUM_VAULT_MASTER_KEY;\n\n/** The node's single open port: runtime MCP endpoint + node API. */\nexport const NEGOTIUM_PORT = parseInt(process.env.NEGOTIUM_PORT || \"7777\", 10);\nexport const hostname = process.env.HOSTNAME || \"127.0.0.1\";\n\n// Persistent state (survives restarts, long-lived)\nexport const DATA_DIR = resolveLocalStateDir(\"NEGOTIUM_DATA_DIR\", \"data\");\nexport const LOG_DIR = resolveLocalStateDir(\"NEGOTIUM_LOG_DIR\", \"logs\");\nexport const UPLOADS_DIR = resolve(DATA_DIR, \"uploads\");\nexport const VAULT_DIR = resolve(DATA_DIR, \"vault\");\n// SESSIONS_DB_PATH env override lets tests point the DB singleton at a temp file.\nexport const SESSIONS_DB = process.env.SESSIONS_DB_PATH\n ? resolve(process.env.SESSIONS_DB_PATH)\n : resolve(DATA_DIR, \"sessions.db\");\nexport const DEBUG_FILE = resolve(DATA_DIR, \"debug-users.json\");\nexport const USERS_LOG_DIR = resolve(DATA_DIR, \"users\");\n\n// Runtime IPC queues (transient, safe to clear on restart)\n/** @deprecated Use the runtime layout name; NEGOTIUM_RUN_DIR remains a compatibility override. */\nexport const RUN_DIR = resolveLocalStateDir(\"NEGOTIUM_RUN_DIR\", \"runtime\");\nexport const RUNTIME_DIR = RUN_DIR;\nexport const PROGRESS_DIR = resolve(RUN_DIR, \"progress\");\nexport const DM_CMD_DIR = resolve(RUN_DIR, \"dm-commands\");\nexport const DM_RESP_DIR = resolve(RUN_DIR, \"dm-responses\");\nexport const SESSION_INBOX_DIR = resolve(RUN_DIR, \"session-inbox\");\nexport const SESSION_ASKS_DIR = resolve(RUN_DIR, \"session-asks\");\n/**\n * Passed to `bash-rs` as `BASHRS_SPILL_ROOT`. Each job gets a subdirectory\n * here (`{bash_id}/meta.json`, `result.json`, `stdout.log`, `stderr.log`) —\n * see bash-rs-mcp's `journal.rs`. `runtime/bashrs-completions.ts` watches\n * this directory and turns `result.json` into a session-inbox `tell`. The\n * retired TypeScript server used to write one directly instead.\n */\nexport const BASHRS_SPILL_ROOT = resolve(RUN_DIR, \"bashrs\");\nexport const PLAYWRIGHT_BASE_PORT = parsePortEnv(process.env.PLAYWRIGHT_BASE_PORT, 9100);\nexport const PLAYWRIGHT_MAX_PORT = parsePortEnv(process.env.PLAYWRIGHT_MAX_PORT, 9499);\nexport const PLAYWRIGHT_PORTS_DIR = resolve(RUN_DIR, \"playwright-ports\");\nmkdirSync(STATE_DIR, { recursive: true });\nmkdirSync(DATA_DIR, { recursive: true });\nmkdirSync(UPLOADS_DIR, { recursive: true });\nmkdirSync(VAULT_DIR, { recursive: true, mode: 0o700 });\nmkdirSync(LOG_DIR, { recursive: true });\nmkdirSync(PROGRESS_DIR, { recursive: true });\nmkdirSync(DM_CMD_DIR, { recursive: true });\nmkdirSync(DM_RESP_DIR, { recursive: true });\nmkdirSync(SESSION_INBOX_DIR, { recursive: true });\nmkdirSync(SESSION_ASKS_DIR, { recursive: true });\nmkdirSync(PLAYWRIGHT_PORTS_DIR, { recursive: true });\nmkdirSync(WORKSPACE_DIR, { recursive: true });\nmkdirSync(TOPIC_WORKSPACE_DIR, { recursive: true });\nmkdirSync(SHARED_WIKI_DIR, { recursive: true });\nmkdirSync(CRON_WORKSPACE_DIR, { recursive: true });\nmkdirSync(DM_WORKSPACE_DIR, { recursive: true });\nmkdirSync(SESSION_WORKSPACE_DIR, { recursive: true });\nmkdirSync(BROWSER_DIR, { recursive: true });\nmkdirSync(BROWSER_PROFILES_DIR, { recursive: true });\nmkdirSync(BINARIES_DIR, { recursive: true });\nmkdirSync(SECRETS_DIR, { recursive: true, mode: 0o700 });\n\n/** Stale threshold for active-query state files (crash recovery) */\nexport const ACTIVE_QUERY_STALE_MS = 10 * 60 * 1000; // 10 minutes\n\nexport const AGENTS_PROMPTS_DIR = resolve(PROJECT_ROOT, \"src/prompts/agents\");\nexport const RESOURCES_DIR = resolve(PROJECT_ROOT, \"src/resources\");\n\n/** Returns process.env without CLAUDECODE, to prevent nested claude-code detection in subprocesses. */\nexport function getCleanEnv(): NodeJS.ProcessEnv {\n const env = { ...process.env };\n delete env.CLAUDECODE;\n return env;\n}\n\n/**\n * How an absolute path can start.\n *\n * A POSIX root (`/`) is not the only form once the runtime also runs on\n * Windows, where the same tag carries `C:\\…` or a `\\\\server\\share` UNC path.\n * Anchoring on `/` alone silently dropped every Windows attachment: the tag\n * stayed in the visible text and no file was ever sent.\n */\nconst ABSOLUTE_PATH_PREFIX = String.raw`(?:[A-Za-z]:[\\\\/]|\\\\\\\\|\\/)`;\n\nexport const FILE_EXTENSIONS_REGEX = new RegExp(\n `(?:${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))`,\n \"gi\",\n);\n\nexport const FILE_TAG_REGEX = new RegExp(`\\\\[FILE:(${ABSOLUTE_PATH_PREFIX}[^\\\\]]+)\\\\]`, \"gi\");\n\n// Canonical Claude model IDs — update here when Anthropic releases new versions\nexport const MODEL_SONNET = \"claude-sonnet-5\";\nexport const MODEL_OPUS = \"claude-opus-5-5\";\nexport const MODEL_HAIKU = \"claude-haiku-4-5-20251001\";\nexport const MODEL_FABLE = \"claude-fable-5-1\"; // Mythos-class, Fable 5.1 announced 2026-09-01 (was claude-fable-5)\n\n// DeepSeek V4 (released 2026-04-24). API is OpenAI-compatible at\n// https://api.deepseek.com/v1/chat/completions; thinking mode is enabled via\n// `extra_body.thinking.type` + `reasoning_effort`. Legacy `deepseek-chat` /\n// `deepseek-reasoner` are deprecated 2026-07-24.\nexport const MODEL_DEEPSEEK_V4_PRO = \"deepseek-v4-pro\";\nexport const MODEL_DEEPSEEK_V4_FLASH = \"deepseek-v4-flash\";\n\n// Single agent + model default for the whole node. DEFAULT_* remains a legacy alias.\nexport const FALLBACK_AGENT: AgentKind = resolveFallbackAgent(process.env);\nexport const FALLBACK_MODEL = envText(\"FALLBACK_MODEL\") ?? envText(\"DEFAULT_MODEL\");\n\n/**\n * Effort used when a caller (or an archiver assignment) names a model but no\n * effort. Deliberately one fixed node-wide value instead of each agent's\n * registry default: a model-derived agent switch would otherwise move effort —\n * and therefore cost — without anyone asking for it.\n */\nexport const DEFAULT_TOPIC_EFFORT: EffortLevel = ((): EffortLevel => {\n const raw = envText(\"NEGOTIUM_DEFAULT_EFFORT\")?.toLowerCase();\n return raw && (EFFORT_VALUES as readonly string[]).includes(raw)\n ? (raw as EffortLevel)\n : \"medium\";\n})();\n\n// ── External tool binaries + media pipeline env ───────────────────\n// (src/media/* 에서 사용. 미설정 시 fallback 의미는 기존 그대로:\n// FFMPEG_BIN은 text-extractor에서 필수(undefined면 spawn 시점 실패),\n// video.ts에서는 PATH의 ffmpeg/ffprobe로 fallback.)\nexport const FFMPEG_BIN = envText(\"FFMPEG_BIN\");\nexport const FFPROBE_BIN = envText(\"FFPROBE_BIN\");\nexport const PYTHON_BIN = envText(\"PYTHON_BIN\") ?? \"python3\";\nexport const FASTER_WHISPER_WRAPPER =\n envText(\"FASTER_WHISPER_WRAPPER\") ?? resolve(PROJECT_ROOT, \"scripts/faster-whisper-wrapper.py\");\nexport const WHISPER_MODEL = envText(\"WHISPER_MODEL_FILE\") ?? \"turbo\";\nexport const TESSERACT_BIN = envText(\"TESSERACT_BIN\") ?? \"tesseract\";\nexport const PDFTOTEXT_BIN = envText(\"PDFTOTEXT_BIN\") ?? \"pdftotext\";\n\n// ── Whisper backend selection ──────────────────────────────────────\n// Different hosts want different whisper runtimes: Apple Silicon Macs get\n// real acceleration from mlx-whisper (see clawgram's transcribe.ts, which\n// this mirrors), while Linux/Ubuntu hubs have no MLX and use the CPU-friendly\n// faster-whisper wrapper instead. Both CLIs accept the same\n// `INPUT --model M --language L --output-dir D --output-format txt` shape\n// and write `{basename}.txt`, so extractFromAudio only needs to pick which\n// binary/args to use — no per-backend parsing logic.\nexport type WhisperBackend = \"faster-whisper\" | \"mlx-whisper\";\nfunction resolveWhisperBackend(): WhisperBackend {\n return envText(\"WHISPER_BACKEND\") === \"mlx-whisper\" ? \"mlx-whisper\" : \"faster-whisper\";\n}\nexport const WHISPER_BACKEND = resolveWhisperBackend();\n/** Path to the `mlx_whisper` CLI (only used when WHISPER_BACKEND=mlx-whisper). */\nexport const MLX_WHISPER_BIN = envText(\"MLX_WHISPER_BIN\");\n/** mlx-whisper model id, e.g. \"mlx-community/whisper-large-v3-turbo\".\n *\n * Deliberately does NOT fall back to WHISPER_MODEL: that env defaults to the\n * bare alias \"turbo\", which faster-whisper's own model-name normalization\n * accepts but mlx_whisper's `--model` does not — it expects a full\n * HuggingFace repo id and otherwise fails hard with a 401\n * RepositoryNotFoundError trying to resolve \"turbo\" as a repo. Confirmed by\n * actually running mlx_whisper with each value while wiring up the\n * mlx-whisper hub in production. */\nexport const WHISPER_MODEL_MLX =\n envText(\"WHISPER_MODEL_MLX\") ?? \"mlx-community/whisper-large-v3-turbo\";\n\n// Max tell_session relay depth from origin user. ask_session forks reset to\n// depth=0, so this only caps tell_session chains. Override via MAX_TELL_DEPTH\n// (positive int); defaults to 20 when unset or invalid.\nconst _envMaxTellDepth = Number.parseInt(process.env.MAX_TELL_DEPTH ?? \"\", 10);\nexport const MAX_TELL_DEPTH =\n Number.isInteger(_envMaxTellDepth) && _envMaxTellDepth > 0 ? _envMaxTellDepth : 20;\n\n/** Codex CLI auth file. 호출 시점에 env를 읽는다 — 테스트가 런타임에\n * NEGOTIUM_CODEX_AUTH_FILE을 바꾸므로 모듈 로드 상수로 만들면 안 된다. */\nexport function codexAuthFilePath(): string {\n return (\n process.env.NEGOTIUM_CODEX_AUTH_FILE ||\n join(process.env.CODEX_HOME || join(homedir(), \".codex\"), \"auth.json\")\n );\n}\n\n// System defaults moved to per-agent registries\n// (`src/agents/{claude,codex}-registry.ts`). Read via\n// `getRegistry(agent).defaultModel` / `.defaultEffort`.\n\n// MCP server builders -> src/platform/mcp-config.ts\n",
|
|
7
|
+
"import type { HostMcpServerSpec } from \"#runtime-gateway\";\n\nexport interface TokenUsage {\n /** Aggregate billable input across every model call made during this turn. */\n inputTokens: number;\n outputTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n /** Provider-reported query cost when available. */\n costUsd?: number;\n /** Tokens occupied by the latest model call, not aggregate turn spend. */\n contextTokens?: number;\n /** Provider-reported context window for the latest model call. */\n contextWindow?: number;\n}\n\n/** Agent identifier — one of the supported AI provider backends. */\nexport type AgentKind = \"maestro\" | \"claude\" | \"codex\";\n\nexport const SUPPORTED_AGENTS: readonly AgentKind[] = [\"maestro\", \"claude\", \"codex\"] as const;\n\nexport function isAgentKind(value: unknown): value is AgentKind {\n return typeof value === \"string\" && (SUPPORTED_AGENTS as readonly string[]).includes(value);\n}\n\n/**\n * Per-agent supported reasoning efforts. Single source of truth for both the\n * `EffortLevel` type and each registry's `validEfforts` runtime list — the\n * registries import these directly so adding a value in one place\n * propagates to validation, footer rendering, and zod enums.\n *\n * Claude SDK rejects 'minimal'; Codex SDK rejects 'max'. The two sets\n * intersect on low/medium/high/xhigh. Maestro (TS port) currently piggybacks\n * on the Anthropic provider, so its efforts mirror the Claude set; this can\n * narrow per-provider once Phase 5 lands.\n *\n * 'minimal' removed from codex: Codex API rejects it when default tools\n * (image_gen, web_search) are active, making agent sessions unusable.\n */\nexport const CLAUDE_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const CODEX_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const MAESTRO_EFFORT_VALUES = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\n\nexport type EffortLevel =\n | (typeof CLAUDE_EFFORT_VALUES)[number]\n | (typeof CODEX_EFFORT_VALUES)[number]\n | (typeof MAESTRO_EFFORT_VALUES)[number];\n\n/**\n * Runtime iteration list (used by zod enums and any callers that need to\n * loop over every accepted value). Manually ordered for readability; the\n * `satisfies` check fails the build if an entry here isn't covered by the\n * per-agent unions above.\n */\nexport const EFFORT_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n] as const satisfies readonly EffortLevel[];\n\n/**\n * Normalized events yielded by any agent provider (claudeProvider, codexProvider).\n * The handler/event-processor consumes these without caring which backend produced them.\n *\n * `user_message` is the lone \"into-the-log\" variant — no provider yields it.\n * The query handler writes it directly to the conversation log right before\n * `runAgent()` starts, so cross-agent rollout reconstruction can pair every\n * assistant turn with the user prompt that triggered it. Consumers that only\n * react to provider output (e.g. processAgentEvent) can safely ignore it.\n */\n/**\n * Wire-safe projection of one task, carried by the `tasks` UnifiedEvent.\n *\n * This is also the on-disk shape of Otium's shared task store, so claude,\n * codex, and maestro render the same live panel from the same source of truth.\n */\nexport interface TaskSnapshot {\n id: string;\n subject: string;\n status: \"pending\" | \"in_progress\" | \"completed\";\n /** Task ids this one is blocked by; omitted when empty. */\n blockedBy?: string[];\n /** Present-continuous label for spinners, when set. */\n activeForm?: string;\n /** Owner / agent name for multi-agent runs, when set. */\n owner?: string;\n}\n\n/** One topic-scoped decision and its incoming causal edges. */\nexport interface DecisionSnapshot {\n id: string;\n action: string;\n reasoning: string;\n agent: AgentKind;\n model?: string;\n status: \"proposed\" | \"accepted\" | \"executed\" | \"rejected\" | \"superseded\";\n /** Upstream decision ids. Each entry forms a directed upstream -> this edge. */\n causedBy?: string[];\n timestamp: number;\n}\n\nexport type UnifiedEvent =\n | {\n type: \"user_message\";\n content: string;\n synthetic?: \"compaction\";\n /** Total ordered user submissions represented by one preempting provider turn. */\n consecutiveBatchSize?: number;\n /** Zero-based position within the ordered preemption batch. */\n consecutiveBatchIndex?: number;\n }\n | { type: \"session\"; sessionId: string }\n | {\n type: \"tool_use\";\n name: string;\n input: Record<string, unknown>;\n /** Provider-assigned id so the client can match tool_use→tool_result pairs. */\n toolUseId?: string;\n }\n | { type: \"tool_progress\"; toolName: string; elapsed: number }\n | { type: \"tool_use_summary\"; summary: string }\n // Provider reasoning/thinking summary text (Codex `reasoning` items; Claude\n // extended-thinking). Surfaced so background runs (cron/archiver) show the\n // agent's thought process, not just tool calls.\n | { type: \"reasoning\"; content: string }\n // Full task-list snapshot (replace, not delta) from Otium's shared task\n // store. Provider-native task/todo stores are not authoritative.\n | { type: \"tasks\"; tasks: TaskSnapshot[] }\n | {\n type: \"tool_result\";\n toolUseId: string;\n content: string;\n /** True when the tool call failed; absent/false means success. */\n isError?: boolean;\n metadata?: {\n truncatedForModel: boolean;\n originalBytes: number;\n returnedBytes: number;\n omittedBytes?: number;\n outputPath?: string;\n };\n }\n | { type: \"text_delta\"; content: string }\n /**\n * Live display text for the assistant block being written. Only room\n * previews (`message_stream`) use it; it is never saved, archived or\n * replayed. The provider still emits the completed block as `text`, which\n * replaces this preview. For providers whose completed message is the only\n * source of block order (Claude).\n */\n | { type: \"text_preview\"; content: string }\n | { type: \"text\"; content: string }\n | { type: \"result\"; content: string; stopReason: string; usage?: TokenUsage }\n | { type: \"file\"; path: string; source: string; origin: \"tag\" | \"extension\" }\n | {\n type: \"error\";\n content: string;\n usage?: TokenUsage;\n /**\n * - `budget_exceeded`: the Claude spend budget (max USD) was hit.\n * - `context_budget_exceeded`: maestro-agent-sdk refused a request that is\n * still over the model's context budget after trimming (SDK >= 0.5.4).\n */\n code?: \"budget_exceeded\" | \"context_budget_exceeded\";\n }\n | { type: \"status\"; content: string };\n\nexport interface AgentInputAttachment {\n id: string;\n type: \"image\" | \"file\" | \"audio\";\n filename: string;\n mimeType: string;\n sizeBytes: number;\n path: string;\n}\n\n/** Worker-side runtime tools proxy user-facing state back to the canonical\n * hub topic identified here. */\nexport interface PeerRuntimeBridgeContext {\n hubCellId: string;\n hostTopicId: string;\n hostQueryId: string;\n canSpawnSubagents: boolean;\n}\n\n/**\n * The rooms the turn's human actor may reach on this node, asserted by the\n * hub that owns per-person membership for the `otium` surface.\n *\n * Node topic ids, valid on the node the turn was submitted to. `visible` is\n * every room the actor participates in (owner or member); `owned` is the\n * subset the actor owns. The assertion rides the signed per-turn MCP token,\n * so the agent can never widen it. With one, it is authoritative: reachable is\n * exactly the current room plus `visible`, owned exactly `owned` — the node\n * adds nothing of its own, not even subagent lineage. A turn without one\n * (older hub, or a turn no person started: cron, self-schedule, a subagent's\n * spawn/report/follow-up) is fail-closed to the current room plus the node's\n * own subagent lineage (direct parent, `grant_subagent_tell` targets, own\n * child workers).\n *\n * `issuedAt` (epoch ms) bounds how long the assertion is believed: this node\n * stamps it when the turn request arrives (the earlier of the hub's own\n * `issuedAt`, if sent, and the receipt time). Past\n * `actorTopicScopeMaxAgeMs()` — or with no `issuedAt` at all — the assertion\n * is stale and grants no cross-room reach (see `isActorTopicScopeFresh`).\n */\nexport interface ActorTopicScope {\n visibleNodeTopicIds: string[];\n ownedNodeTopicIds: string[];\n issuedAt?: number;\n}\n\n/**\n * Hub-issued authority for the `node/topic` branches of `session-comm` on\n * the `otium` surface, one per turn. `capability` is an opaque bearer\n * (`rsc1.<payload>.<hmac>`) only the hub can verify: it binds the person who\n * spoke, the origin room and this turn's request id, and the hub re-checks\n * the person's membership of the origin and target rooms on every call. The\n * node holds no key, so it can neither mint nor verify one; the only thing it\n * reads out of the payload is `e` (expiry), base64-decoded untrusted to order\n * grants when several requests fold into one turn. `hubUrl` is where the\n * node presents it (`/api/v1/session-comm/remote/*`). Absent — an older hub,\n * a hub with the feature off, or a turn no person started (cron,\n * self-schedule, subagent lineage) — remote session-comm stays fail-closed.\n */\nexport interface RemoteSessionGrant {\n hubUrl: string;\n capability: string;\n}\n\n/** A message a person sent while a turn runs, for that turn to read at its next step. */\nexport interface MidTurnMessage {\n /** Canonical message id. The provider names it back once the turn has read it. */\n id: string;\n /** The rendered prompt, as the turn's own first message is rendered. */\n text: string;\n}\n\n/**\n * How a running turn takes messages sent while it works (Codex-style steer: the\n * work goes on, and the agent reads the message after the step it is on).\n * Only a provider that can feed a live turn opens it; for any other the\n * message stays queued for the next turn.\n */\nexport interface MidTurnInput {\n /** The turn can take messages from now on. `deliver` returns false once it no longer can. */\n open(deliver: (message: MidTurnMessage) => boolean): void;\n /** The turn ended. `read` are the delivered ids it read inside the turn; the rest were not read. */\n close(read: readonly string[]): void;\n}\n\nexport interface AgentQueryOptions {\n agent: AgentKind;\n prompt: string;\n /** Present on a person's turn: messages they send while it runs are read inside it. */\n midTurn?: MidTurnInput;\n attachments?: AgentInputAttachment[];\n sessionId?: string | null;\n cwd: string;\n systemPrompt: string;\n /**\n * Trusted system-level instructions for this Maestro invocation only.\n * Maestro projects them onto the invocation-start user message without\n * persisting them in session history or compaction. Omitted for Claude/Codex.\n */\n ephemeralSystemPrompt?: string;\n userId?: string;\n /** Product actor identity when execution uses a canonical node principal. */\n actorUserId?: string;\n /** Hub-asserted rooms the product actor may reach; absent means fail-closed. */\n actorTopicScope?: ActorTopicScope;\n /** Hub-issued per-turn authority for remote (`node/topic`) session-comm. */\n remoteSession?: RemoteSessionGrant;\n /** Credential namespace when it differs from the execution principal. */\n vaultUserId?: string;\n session?: string;\n playwrightPort?: number;\n playwrightCapability?: string;\n bgBashPort?: number;\n sessionType?: \"dm\" | \"forum\" | \"ephemeral\" | \"manager\" | \"cron\";\n /** API topic id (REST/WS world). Carries per-query topic context for MCP servers. */\n topicId?: string;\n /** Direct parent topic id when this query runs inside a subagent room. */\n subagentParentTopicId?: string;\n /** API query id for the currently running turn. Used by runtime MCP tools. */\n queryId?: string;\n /** Optional wiki-memory topic id. Derived topics use their root origin here\n * while other per-topic MCP servers keep `topicId` bound to the live room. */\n wikiTopicId?: string;\n /** Whether self-config MCP may enqueue an automatic continue turn after set_* changes. */\n autoContinue?: boolean;\n /** Expose Otium-only visual panel tools for this turn. Default-deny. */\n visualTools?: boolean;\n /** Expose adapter-backed file-delivery tools for this turn. Default-deny. */\n fileDeliveryTools?: boolean;\n /** Validated host MCPs resolved from durable manager-room grants at execution time. */\n hostMcpServers?: Record<string, HostMcpServerSpec>;\n /**\n * Thread this turn answers inside, so the turn's runtime MCP can default\n * `thread_read` to it. Turn-scoped, unlike the session, which is per topic.\n */\n threadRootId?: string;\n abortController?: AbortController;\n model?: string;\n /** Provider-side hard budget when the selected SDK supports one. */\n maxBudgetUsd?: number;\n depth?: number;\n agents?: Record<\n string,\n {\n description: string;\n prompt: string;\n model?: string;\n tools?: string[];\n maxTurns?: number;\n effort?: EffortLevel | number;\n }\n >;\n effort?: EffortLevel;\n /**\n * Per-API-call `max_tokens` ceiling on the assistant's output. Wired\n * through to the underlying provider request body for every agent\n * (claude/codex/maestro). Omit to inherit each provider SDK's per-model\n * default — for maestro that's the v0.1.21+ `getNativeMaxOutputTokens`\n * catalog (deepseek-pro=64K, kimi-k3=64K, kimi-k2.7-code=32K).\n *\n * Pass an explicit number when a specific topic / surface needs a tighter\n * latency cap or a higher ceiling for long-form generation (legal\n * report writing, multi-K Write/Edit file bodies). Pre-0.1.21 maestro\n * builds silently clamped at 4096 and truncated outputs mid-string;\n * setting this field is now the supported way to lift that ceiling.\n */\n maxTokens?: number;\n /**\n * v0.1.22+: Claude-Code-style deferred tool catalog + `ToolSearch` built-in.\n *\n * Wired straight through to `maestro-agent-sdk`'s\n * `AgentQueryOptions.enableToolSearch`. When `true`, the maestro provider\n * registers every MCP tool as deferred — schemas stay off the wire until\n * the model promotes them via `ToolSearch(\"select:Name1,Name2\")` or\n * `ToolSearch(\"keyword\")`. Active set persists across resume.\n *\n * Otium's maestro provider supplies `true` when the caller leaves this\n * option unset, because most forum turns carry enough MCP surface for the\n * reminder-token savings to outweigh the first-use `ToolSearch` round-trip.\n * Callers can still pass `false` per call when a narrow surface or\n * latency-sensitive workflow is better served by eager MCP schemas.\n *\n * No-op for claude / codex agents — they have their own deferred-tool\n * machinery owned by their respective SDKs.\n */\n enableToolSearch?: boolean;\n /**\n * Bounded tool results with the full output kept on disk.\n *\n * Wired to `maestro-agent-sdk`'s `AgentQueryOptions.toolResultTruncation`.\n * The SDK caps a string tool result, writes the untruncated bytes to a file,\n * and splices an opaque `maestro://tool-output/<id>` reference into the text\n * that the `ReadToolOutput` tool can page back through.\n *\n * The maestro provider enables it by default. Left unset, every tool result\n * — a whole-file `Read`, a wide `Grep`, a `WebFetch` of a large page —\n * entered the context at full size, and the `\"ReadToolOutput\"` entry in the\n * provider's builtin list was dead, because the SDK only registers that tool\n * when truncation is on with `saveFullOutput`.\n *\n * Pass an explicit object to tune the budget, or `{ enabled: false }` for a\n * call whose tool results must arrive whole.\n *\n * No-op for claude / codex agents — their SDKs do their own truncation.\n */\n toolResultTruncation?: {\n enabled?: boolean;\n maxBytes?: number;\n headBytes?: number;\n tailBytes?: number;\n saveFullOutput?: boolean;\n outputDir?: string;\n retentionDays?: number;\n ignoreTools?: string[];\n };\n /**\n * Claude-Code-compatible exact tool denylist. Maestro v0.1.42+ hides these\n * tools from provider schemas / ToolSearch and blocks dispatch if a stale\n * call still arrives. Claude maps this to its SDK option. Codex does not\n * support this name-based list; its provider-native multi-agent tool family\n * is disabled separately through the Codex feature config.\n */\n disallowedTools?: readonly string[];\n /**\n * Hard provider tool policy for auxiliary model calls.\n *\n * `\"none\"` removes MCP and provider-native tools before the request is\n * dispatched. `\"compaction-log\"` keeps provider-native tools disabled and\n * exposes only the host-scoped immutable log reader. Use these for untrusted\n * transcript transforms; reacting to tool events after dispatch is not a\n * security boundary.\n */\n toolPolicy?: \"none\" | \"compaction-log\";\n mcpEnabled?: string[] | null;\n peerBridge?: PeerRuntimeBridgeContext;\n mcpExtra?: Record<string, unknown>;\n /**\n * true for silent fork runs generating ask_session replies — restricts session-comm\n * outbound tools (ask/tell/abort) so the forked session can only produce text\n */\n silent?: boolean;\n}\n\n/** State file written to data/users/{userId}/active-queries/{topicId}.json while a query is running. */\nexport interface QueryState {\n topicId?: string;\n topicName?: string;\n task?: string; // first 100 chars of prompt, newlines normalized\n since: string; // ISO timestamp\n}\n",
|
|
8
|
+
"import { resolve } from \"node:path\";\nimport { type AgentKind, isAgentKind } from \"#types\";\n\nexport type RuntimeEnvironment = Readonly<Record<string, string | undefined>>;\n\nexport function readEnvText(env: RuntimeEnvironment, key: string): string | undefined {\n const value = env[key]?.trim();\n return value || undefined;\n}\n\n/**\n * Node-wide default agent (FALLBACK_AGENT env, legacy DEFAULT_AGENT, else\n * \"claude\"). Lives in this side-effect-free leaf module — not #platform/config\n * — so storage layers that only need this one value (e.g. the forum/api-topics\n * repositories, re-exported through the public storage facade) don't drag in\n * config.ts's eager `mkdirSync` of every node data directory just by\n * importing it.\n */\nexport function resolveFallbackAgent(env: RuntimeEnvironment = process.env): AgentKind {\n const value = readEnvText(env, \"FALLBACK_AGENT\") ?? readEnvText(env, \"DEFAULT_AGENT\");\n return isAgentKind(value) ? value : \"claude\";\n}\n\nexport function parseRuntimePort(value: string | undefined, fallback: number): number {\n if (!value) return fallback;\n const port = Number.parseInt(value, 10);\n return Number.isInteger(port) && port > 0 && port <= 65_535 ? port : fallback;\n}\n\nexport function resolveRuntimeStateDir(options: {\n env: RuntimeEnvironment;\n envKey: string;\n fallbackRoot: string;\n fallbackName: string;\n}): string {\n const configured = readEnvText(options.env, options.envKey);\n return configured ? resolve(configured) : resolve(options.fallbackRoot, options.fallbackName);\n}\n\nexport function safeRuntimePathSegment(value: string, fallback: string, maxLength = 160): string {\n const cleaned = value\n .trim()\n .replace(/[^A-Za-z0-9._-]/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, maxLength);\n return cleaned || fallback;\n}\n",
|
|
9
|
+
"import pino from \"pino\";\n\nexport interface StdioLoggerOptions {\n level?: string;\n development?: boolean;\n}\n\n/**\n * Always write logs to stderr (fd 2), never stdout.\n *\n * MCP servers under `src/mcp/**` run as stdio subprocesses where stdout is the\n * JSON-RPC transport channel. A single log line on stdout corrupts the next\n * message and the MCP client closes the transport (\"Transport closed\"). The\n * main bot process is also fine with stderr — pm2 captures both streams.\n *\n * In dev mode pino spawns a `pino-pretty` worker that owns its own sink, so we\n * pass `destination: 2` through transport.options. In prod (no transport) the\n * second arg to `pino()` sets the destination directly.\n */\nexport function createStdioLogger(options: StdioLoggerOptions = {}) {\n const development = options.development ?? process.env.NODE_ENV === \"development\";\n return pino(\n {\n level: options.level ?? process.env.LOG_LEVEL ?? \"info\",\n transport: development\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss\",\n destination: 2,\n },\n }\n : undefined,\n },\n pino.destination(2),\n );\n}\n\nexport type StdioLogger = ReturnType<typeof createStdioLogger>;\n\nexport const logger = createStdioLogger();\n",
|
|
10
|
+
"/**\n * Stringify an unknown thrown value for logging or user-visible messages.\n * Default fallback is `String(e)`. Pass an explicit fallback (e.g. \"unknown\")\n * to override what non-Error throws turn into.\n */\nexport function errMsg(e: unknown, fallback?: string): string {\n if (e instanceof Error) return e.message;\n return fallback ?? String(e);\n}\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";;AAAA;AACA,uBAAS,0BAAY,4BAAW;AAChC;AACA,0BAAkB;AAClB;;;ACJA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA;AACA;AACA;AACA;;;ACKO,IAAM,mBAAyC,CAAC,WAAW,UAAU,OAAO;AAE5E,SAAS,WAAW,CAAC,OAAoC;AAAA,EAC9D,OAAO,OAAO,UAAU,YAAa,iBAAuC,SAAS,KAAK;AAAA;AAgCrF,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACvDO,SAAS,WAAW,CAAC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,MACA,MAAM,cAAc,eAAe,aAAa,EAAE,SAAS,OAAO,CAAC;AAAA,IACrE,EAAO;AAAA,MACL,MAAM,cACJ,KAAK,aAAa,YAClB,CAAC,KAAK,eAAe,wBAAwB,GAAG,WAAW,GAC3D,EAAE,SAAS,OAAO,CACpB;AAAA;AAAA,IAGF,MAAM,UAAU,MAAK,QAAQ,WAAW;AAAA,IACxC,MAAM,OAAO,YAAW,OAAO,IAAI,cAAa,SAAS,OAAO,EAAE,KAAK,IAAI;AAAA,IAE3E,IAAI,CAAC,MAAM;AAAA,MACT,OAAO,EAAE,MAAM,MAAM,QAAQ,WAAW,OAAO,2BAA2B;AAAA,IAC5E;AAAA,IACA,OAAO,EAAE,MAAM,QAAQ,UAAU;AAAA,IACjC,OAAO,GAAG;AAAA,IACV,OAAO,MAAM,EAAE,KAAK,GAAG,UAAU,QAAQ,GAAG,2BAA2B;AAAA,IACvE,OAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,OAAO,mBAAmB,OAAO,CAAC;AAAA,IACpC;AAAA,YACA;AAAA,IACA,IAAI;AAAA,MACF,OAAO,QAAQ,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,MAC/C,OAAO,GAAG;AAAA,MACV,OAAO,KAAK,EAAE,KAAK,GAAG,OAAO,GAAG,kCAAkC;AAAA;AAAA;AAAA;",
|
|
13
|
+
"debugId": "ADC1A2FF8B8EE56164756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
package/dist/outbox.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../packages/core/src/platform/logger.ts
|
|
3
|
+
import pino from "pino";
|
|
4
|
+
function createStdioLogger(options = {}) {
|
|
5
|
+
const development = options.development ?? true;
|
|
6
|
+
return pino({
|
|
7
|
+
level: options.level ?? process.env.LOG_LEVEL ?? "info",
|
|
8
|
+
transport: development ? {
|
|
9
|
+
target: "pino-pretty",
|
|
10
|
+
options: {
|
|
11
|
+
colorize: true,
|
|
12
|
+
translateTime: "SYS:yyyy-mm-dd HH:MM:ss",
|
|
13
|
+
destination: 2
|
|
14
|
+
}
|
|
15
|
+
} : undefined
|
|
16
|
+
}, pino.destination(2));
|
|
17
|
+
}
|
|
18
|
+
var logger = createStdioLogger();
|
|
19
|
+
|
|
20
|
+
// ../../packages/core/src/outbox/coalescing-runner.ts
|
|
21
|
+
function createCoalescingRunner(options) {
|
|
22
|
+
const { run, label, minIntervalMs } = options;
|
|
23
|
+
const log = options.logger ?? logger;
|
|
24
|
+
const now = options.now ?? Date.now;
|
|
25
|
+
let timer = null;
|
|
26
|
+
let running = false;
|
|
27
|
+
let pending = false;
|
|
28
|
+
let stopped = false;
|
|
29
|
+
let lastStart = null;
|
|
30
|
+
let runCount = 0;
|
|
31
|
+
function arm() {
|
|
32
|
+
if (stopped || running || timer)
|
|
33
|
+
return;
|
|
34
|
+
const wait = lastStart === null ? 0 : Math.max(0, lastStart + minIntervalMs - now());
|
|
35
|
+
if (wait <= 0) {
|
|
36
|
+
execute();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
timer = setTimeout(() => {
|
|
40
|
+
timer = null;
|
|
41
|
+
execute();
|
|
42
|
+
}, wait);
|
|
43
|
+
timer.unref?.();
|
|
44
|
+
}
|
|
45
|
+
async function execute() {
|
|
46
|
+
if (stopped || running)
|
|
47
|
+
return;
|
|
48
|
+
running = true;
|
|
49
|
+
pending = false;
|
|
50
|
+
lastStart = now();
|
|
51
|
+
runCount++;
|
|
52
|
+
try {
|
|
53
|
+
await run();
|
|
54
|
+
} catch (err) {
|
|
55
|
+
log.error({ err, label }, `${label}: Unhandled error`);
|
|
56
|
+
} finally {
|
|
57
|
+
running = false;
|
|
58
|
+
if (pending && !stopped) {
|
|
59
|
+
pending = false;
|
|
60
|
+
arm();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
trigger() {
|
|
66
|
+
if (stopped)
|
|
67
|
+
return;
|
|
68
|
+
if (running) {
|
|
69
|
+
pending = true;
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
arm();
|
|
73
|
+
},
|
|
74
|
+
async runNow() {
|
|
75
|
+
if (stopped)
|
|
76
|
+
return;
|
|
77
|
+
if (running) {
|
|
78
|
+
pending = true;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (timer) {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
timer = null;
|
|
84
|
+
}
|
|
85
|
+
await execute();
|
|
86
|
+
},
|
|
87
|
+
stop() {
|
|
88
|
+
stopped = true;
|
|
89
|
+
pending = false;
|
|
90
|
+
if (timer) {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
timer = null;
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
get runCount() {
|
|
96
|
+
return runCount;
|
|
97
|
+
},
|
|
98
|
+
get isRunning() {
|
|
99
|
+
return running;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// ../../packages/core/src/outbox/file-ops.ts
|
|
104
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
105
|
+
import { appendFileSync as appendFileSync2, existsSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync as unlinkSync3 } from "fs";
|
|
106
|
+
|
|
107
|
+
// ../../packages/core/src/platform/jsonl.ts
|
|
108
|
+
import {
|
|
109
|
+
appendFileSync,
|
|
110
|
+
closeSync,
|
|
111
|
+
fsyncSync,
|
|
112
|
+
mkdirSync,
|
|
113
|
+
openSync,
|
|
114
|
+
readFileSync,
|
|
115
|
+
renameSync,
|
|
116
|
+
statSync,
|
|
117
|
+
unlinkSync as unlinkSync2,
|
|
118
|
+
writeFileSync
|
|
119
|
+
} from "fs";
|
|
120
|
+
|
|
121
|
+
// ../../packages/core/src/platform/file-utils.ts
|
|
122
|
+
import { unlinkSync } from "fs";
|
|
123
|
+
function createSafeUnlink(host) {
|
|
124
|
+
return (path, warnLabel) => {
|
|
125
|
+
try {
|
|
126
|
+
host.unlink(path);
|
|
127
|
+
} catch (e) {
|
|
128
|
+
if (e?.code === "ENOENT")
|
|
129
|
+
return;
|
|
130
|
+
if (warnLabel)
|
|
131
|
+
host.warn({ err: e, path }, warnLabel);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
var defaultSafeUnlink = createSafeUnlink({
|
|
136
|
+
unlink: unlinkSync,
|
|
137
|
+
warn: (context, message) => logger.warn(context, message)
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// ../../packages/core/src/platform/jsonl.ts
|
|
141
|
+
function readJsonlLines(filePath) {
|
|
142
|
+
return readFileSync(filePath, "utf-8").trim().split(`
|
|
143
|
+
`).filter(Boolean);
|
|
144
|
+
}
|
|
145
|
+
var LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
146
|
+
|
|
147
|
+
// ../../packages/core/src/outbox/file-ops.ts
|
|
148
|
+
var PROCESSING_SUFFIX = ".processing";
|
|
149
|
+
var defaultHost = { logger, readJsonlLines };
|
|
150
|
+
var hostContext = new AsyncLocalStorage;
|
|
151
|
+
function host() {
|
|
152
|
+
return hostContext.getStore() ?? defaultHost;
|
|
153
|
+
}
|
|
154
|
+
function isProcessingFile(name) {
|
|
155
|
+
return name.endsWith(PROCESSING_SUFFIX);
|
|
156
|
+
}
|
|
157
|
+
function tryUnlink(path, label, reason) {
|
|
158
|
+
try {
|
|
159
|
+
unlinkSync3(path);
|
|
160
|
+
} catch (e) {
|
|
161
|
+
if (e?.code === "ENOENT") {
|
|
162
|
+
host().logger.debug({ path }, `${label}: ${reason} (already gone)`);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
host().logger.warn({ err: e, path }, `${label}: ${reason}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function drainOutboxFile(filePath, label) {
|
|
169
|
+
const processingPath = filePath + PROCESSING_SUFFIX;
|
|
170
|
+
const hasPending = existsSync(filePath);
|
|
171
|
+
const hasLeftover = existsSync(processingPath);
|
|
172
|
+
if (hasLeftover) {
|
|
173
|
+
const logMsg = `${label}: merging leftover .processing before claim`;
|
|
174
|
+
const logCtx = { filePath, processingPath, hadPending: hasPending };
|
|
175
|
+
if (hasPending)
|
|
176
|
+
host().logger.warn(logCtx, logMsg);
|
|
177
|
+
else
|
|
178
|
+
host().logger.info(logCtx, logMsg);
|
|
179
|
+
try {
|
|
180
|
+
const leftover = readFileSync2(processingPath, "utf-8");
|
|
181
|
+
if (leftover)
|
|
182
|
+
appendFileSync2(filePath, leftover.endsWith(`
|
|
183
|
+
`) ? leftover : `${leftover}
|
|
184
|
+
`);
|
|
185
|
+
unlinkSync3(processingPath);
|
|
186
|
+
} catch (e) {
|
|
187
|
+
host().logger.error({ err: e, processingPath }, `${label}: failed to merge leftover \u2014 data may be lost`);
|
|
188
|
+
tryUnlink(processingPath, label, "failed to clean up leftover after merge error");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!existsSync(filePath))
|
|
192
|
+
return null;
|
|
193
|
+
try {
|
|
194
|
+
renameSync2(filePath, processingPath);
|
|
195
|
+
} catch (e) {
|
|
196
|
+
host().logger.warn({ err: e, filePath }, `${label}: failed to rename for processing`);
|
|
197
|
+
return null;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
const lines = host().readJsonlLines(processingPath);
|
|
201
|
+
return { lines, processingPath };
|
|
202
|
+
} catch (e) {
|
|
203
|
+
host().logger.warn({ err: e, processingPath }, `${label}: failed to read processing file`);
|
|
204
|
+
tryUnlink(processingPath, label, "failed to delete corrupt processing file");
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function deleteProcessingFile(processingPath, label, consumedLines) {
|
|
209
|
+
if (consumedLines !== undefined && processingPath.endsWith(PROCESSING_SUFFIX)) {
|
|
210
|
+
try {
|
|
211
|
+
const current = host().readJsonlLines(processingPath);
|
|
212
|
+
if (current.length > consumedLines) {
|
|
213
|
+
const pendingPath = processingPath.slice(0, -PROCESSING_SUFFIX.length);
|
|
214
|
+
const tail = current.slice(consumedLines).join(`
|
|
215
|
+
`);
|
|
216
|
+
appendFileSync2(pendingPath, `${tail}
|
|
217
|
+
`);
|
|
218
|
+
host().logger.warn({ processingPath, salvaged: current.length - consumedLines }, `${label}: writer raced the drain \u2014 salvaged late lines back to pending`);
|
|
219
|
+
}
|
|
220
|
+
} catch (e) {
|
|
221
|
+
host().logger.warn({ err: e, processingPath }, `${label}: writer-race recheck failed`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
tryUnlink(processingPath, label, "failed to delete processing file");
|
|
225
|
+
}
|
|
226
|
+
function parseOutboxLine(line, label) {
|
|
227
|
+
try {
|
|
228
|
+
return JSON.parse(line);
|
|
229
|
+
} catch {
|
|
230
|
+
host().logger.error({ label, line: line.slice(0, 120) }, `${label}: Invalid JSON, dropping`);
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async function processOutboxFile(filePath, label, handler, opts = {}) {
|
|
235
|
+
const drained = drainOutboxFile(filePath, label);
|
|
236
|
+
if (!drained)
|
|
237
|
+
return;
|
|
238
|
+
const { lines, processingPath } = drained;
|
|
239
|
+
if (lines.length === 0) {
|
|
240
|
+
deleteProcessingFile(processingPath, label, 0);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const MAX_RETRIES = opts.maxRetries ?? 0;
|
|
244
|
+
const failedLines = [];
|
|
245
|
+
for (const line of lines) {
|
|
246
|
+
const entry = parseOutboxLine(line, label);
|
|
247
|
+
if (!entry)
|
|
248
|
+
continue;
|
|
249
|
+
const retryCount = entry.retryCount ?? 0;
|
|
250
|
+
try {
|
|
251
|
+
await handler(entry);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
if (MAX_RETRIES > 0) {
|
|
254
|
+
const next = retryCount + 1;
|
|
255
|
+
if (next >= MAX_RETRIES) {
|
|
256
|
+
host().logger.error({ err, label, retryCount: next }, `${label}: Max retries reached, dropping`);
|
|
257
|
+
} else {
|
|
258
|
+
host().logger.warn({ err, label, retryCount: next }, `${label}: Failed, will retry`);
|
|
259
|
+
failedLines.push(JSON.stringify({ ...entry, retryCount: next }));
|
|
260
|
+
}
|
|
261
|
+
} else {
|
|
262
|
+
host().logger.error({ err, label }, `${label}: Failed to process entry`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
deleteProcessingFile(processingPath, label, lines.length);
|
|
267
|
+
if (failedLines.length > 0) {
|
|
268
|
+
try {
|
|
269
|
+
appendFileSync2(filePath, `${failedLines.join(`
|
|
270
|
+
`)}
|
|
271
|
+
`);
|
|
272
|
+
} catch (e) {
|
|
273
|
+
host().logger.error({ err: e, label, count: failedLines.length }, `${label}: Failed to write back entries`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function createOutboxFileOps(boundHost) {
|
|
278
|
+
return {
|
|
279
|
+
isProcessingFile,
|
|
280
|
+
drainOutboxFile: (filePath, label) => hostContext.run(boundHost, () => drainOutboxFile(filePath, label)),
|
|
281
|
+
deleteProcessingFile: (processingPath, label, consumedLines) => hostContext.run(boundHost, () => deleteProcessingFile(processingPath, label, consumedLines)),
|
|
282
|
+
parseOutboxLine: (line, label) => hostContext.run(boundHost, () => parseOutboxLine(line, label)),
|
|
283
|
+
processOutboxFile: (filePath, label, handler, opts = {}) => hostContext.run(boundHost, () => processOutboxFile(filePath, label, handler, opts))
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
// ../../packages/core/src/outbox/utils.ts
|
|
287
|
+
import { mkdirSync as mkdirSync2, watch } from "fs";
|
|
288
|
+
var FALLBACK_INTERVAL_MS = 5000;
|
|
289
|
+
function createOutboxWatchOps(host) {
|
|
290
|
+
function debouncedFlush(fn, label, delayMs) {
|
|
291
|
+
let timer = null;
|
|
292
|
+
let running = false;
|
|
293
|
+
let pending = false;
|
|
294
|
+
async function run() {
|
|
295
|
+
if (running) {
|
|
296
|
+
pending = true;
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
while (true) {
|
|
300
|
+
running = true;
|
|
301
|
+
pending = false;
|
|
302
|
+
try {
|
|
303
|
+
await fn();
|
|
304
|
+
} catch (e) {
|
|
305
|
+
host.logger.error({ err: e }, `${label}: Unhandled error`);
|
|
306
|
+
} finally {
|
|
307
|
+
running = false;
|
|
308
|
+
}
|
|
309
|
+
if (!pending)
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return () => {
|
|
314
|
+
if (timer)
|
|
315
|
+
clearTimeout(timer);
|
|
316
|
+
timer = setTimeout(() => {
|
|
317
|
+
timer = null;
|
|
318
|
+
run();
|
|
319
|
+
}, delayMs);
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function watchDir(dir, onChange) {
|
|
323
|
+
try {
|
|
324
|
+
mkdirSync2(dir, { recursive: true });
|
|
325
|
+
const watcher = watch(dir, { recursive: true }, () => onChange());
|
|
326
|
+
watcher.on("error", (e) => {
|
|
327
|
+
host.logger.warn({ err: e, dir }, "outbox: fs.watch error");
|
|
328
|
+
});
|
|
329
|
+
return watcher;
|
|
330
|
+
} catch (e) {
|
|
331
|
+
host.logger.warn({ err: e, dir }, "outbox: Failed to watch dir");
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return { debouncedFlush, watchDir };
|
|
336
|
+
}
|
|
337
|
+
var defaultWatchOps = createOutboxWatchOps({ logger });
|
|
338
|
+
var debouncedFlush = defaultWatchOps.debouncedFlush;
|
|
339
|
+
var watchDir = defaultWatchOps.watchDir;
|
|
340
|
+
export {
|
|
341
|
+
FALLBACK_INTERVAL_MS,
|
|
342
|
+
createCoalescingRunner,
|
|
343
|
+
createOutboxFileOps,
|
|
344
|
+
createOutboxWatchOps,
|
|
345
|
+
debouncedFlush,
|
|
346
|
+
deleteProcessingFile,
|
|
347
|
+
drainOutboxFile,
|
|
348
|
+
isProcessingFile,
|
|
349
|
+
parseOutboxLine,
|
|
350
|
+
processOutboxFile,
|
|
351
|
+
watchDir
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
//# debugId=1AE22D7E960EF35E64756E2164756E21
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../packages/core/src/platform/logger.ts", "../../../packages/core/src/outbox/coalescing-runner.ts", "../../../packages/core/src/outbox/file-ops.ts", "../../../packages/core/src/platform/jsonl.ts", "../../../packages/core/src/platform/file-utils.ts", "../../../packages/core/src/outbox/utils.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import pino from \"pino\";\n\nexport interface StdioLoggerOptions {\n level?: string;\n development?: boolean;\n}\n\n/**\n * Always write logs to stderr (fd 2), never stdout.\n *\n * MCP servers under `src/mcp/**` run as stdio subprocesses where stdout is the\n * JSON-RPC transport channel. A single log line on stdout corrupts the next\n * message and the MCP client closes the transport (\"Transport closed\"). The\n * main bot process is also fine with stderr — pm2 captures both streams.\n *\n * In dev mode pino spawns a `pino-pretty` worker that owns its own sink, so we\n * pass `destination: 2` through transport.options. In prod (no transport) the\n * second arg to `pino()` sets the destination directly.\n */\nexport function createStdioLogger(options: StdioLoggerOptions = {}) {\n const development = options.development ?? process.env.NODE_ENV === \"development\";\n return pino(\n {\n level: options.level ?? process.env.LOG_LEVEL ?? \"info\",\n transport: development\n ? {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss\",\n destination: 2,\n },\n }\n : undefined,\n },\n pino.destination(2),\n );\n}\n\nexport type StdioLogger = ReturnType<typeof createStdioLogger>;\n\nexport const logger = createStdioLogger();\n",
|
|
6
|
+
"/**\n * Starvation-free trigger coalescing for workers driven by *both* an irregular\n * event source (fs.watch, in-process signals) and a periodic safety net poll.\n *\n * Why this exists instead of `debouncedFlush`\n * -------------------------------------------\n * A trailing-edge debounce re-arms its timer on every trigger. When any trigger\n * source fires faster than the debounce delay the quiet window never arrives\n * and the work is postponed forever — the exact self-starving regression that a\n * 100ms fallback poll feeding a 200ms debounce produced (b919a2e).\n *\n * The invariant here is the opposite one:\n *\n * Once a run is armed, nothing can push it further out.\n *\n * A trigger only ever *creates* a timer; it never clears or reschedules one.\n * Extra triggers arriving before that timer fires are absorbed for free, so a\n * high trigger rate makes the run happen sooner, never later.\n *\n * trigger() ──► running? ── yes ─► pending = true (run again after)\n * │ no\n * ▼\n * armed? ── yes ─► drop (already guaranteed to run)\n * │ no\n * ▼\n * wait = max(0, lastStart + minIntervalMs - now)\n * wait === 0 ─► run immediately (leading edge: ~0 latency)\n * wait > 0 ─► setTimeout(run, wait) (bounded: ≤ minIntervalMs)\n *\n * Consequences:\n * - Latency: an idle worker runs on the *leading* edge, so a single message is\n * picked up immediately. Inside a burst the worst case is `minIntervalMs`.\n * - Throughput cap: runs start at most once per `minIntervalMs`, so a chatty\n * watcher (including events caused by the run's own writes) cannot spin.\n * - Coalescing: triggers landing while a run is in flight collapse into a\n * single follow-up run scheduled once the current one settles.\n */\n\nimport { logger as defaultLogger } from \"#platform/logger\";\n\nexport interface CoalescingRunnerLogger {\n error(fields: Record<string, unknown>, message: string): void;\n}\n\nexport interface CoalescingRunnerOptions {\n /** The work to coalesce. Rejections are logged, never propagated. */\n run: () => Promise<void> | void;\n /** Log label. */\n label: string;\n /**\n * Minimum gap between the *starts* of two consecutive runs, and therefore the\n * upper bound on how long a trigger can wait for one. `0` runs on every\n * trigger.\n */\n minIntervalMs: number;\n logger?: CoalescingRunnerLogger;\n /** Injectable clock, for deterministic tests. */\n now?: () => number;\n}\n\nexport interface CoalescingRunner {\n /** Request a run \"as soon as the rate limit allows\". Never delays a pending one. */\n trigger(): void;\n /** Run now, ignoring the rate limit (boot drain). Resolves when that run settles. */\n runNow(): Promise<void>;\n /** Release timers. Further triggers are ignored; an in-flight run is not cancelled. */\n stop(): void;\n /** Completed + in-flight run count. Test/diagnostics only. */\n readonly runCount: number;\n /** True while a run is in flight. Test/diagnostics only. */\n readonly isRunning: boolean;\n}\n\nexport function createCoalescingRunner(options: CoalescingRunnerOptions): CoalescingRunner {\n const { run, label, minIntervalMs } = options;\n const log = options.logger ?? defaultLogger;\n const now = options.now ?? Date.now;\n\n let timer: ReturnType<typeof setTimeout> | null = null;\n let running = false;\n let pending = false;\n let stopped = false;\n let lastStart: number | null = null;\n let runCount = 0;\n\n function arm(): void {\n if (stopped || running || timer) return;\n const wait = lastStart === null ? 0 : Math.max(0, lastStart + minIntervalMs - now());\n if (wait <= 0) {\n void execute();\n return;\n }\n timer = setTimeout(() => {\n timer = null;\n void execute();\n }, wait);\n timer.unref?.();\n }\n\n async function execute(): Promise<void> {\n if (stopped || running) return;\n running = true;\n pending = false;\n lastStart = now();\n runCount++;\n try {\n await run();\n } catch (err) {\n log.error({ err, label }, `${label}: Unhandled error`);\n } finally {\n running = false;\n if (pending && !stopped) {\n pending = false;\n // Re-arm through the normal path so the rate limit still applies. A run\n // that outlasted `minIntervalMs` re-runs immediately.\n arm();\n }\n }\n }\n\n return {\n trigger(): void {\n if (stopped) return;\n if (running) {\n pending = true;\n return;\n }\n arm();\n },\n async runNow(): Promise<void> {\n if (stopped) return;\n if (running) {\n pending = true;\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n await execute();\n },\n stop(): void {\n stopped = true;\n pending = false;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n },\n get runCount(): number {\n return runCount;\n },\n get isRunning(): boolean {\n return running;\n },\n };\n}\n",
|
|
7
|
+
"import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { appendFileSync, existsSync, readFileSync, renameSync, unlinkSync } from \"node:fs\";\nimport { readJsonlLines } from \"#platform/jsonl\";\nimport { logger } from \"#platform/logger\";\n\nconst PROCESSING_SUFFIX = \".processing\";\n\nexport interface OutboxLogger {\n debug(fields: Record<string, unknown>, message: string): void;\n info(fields: Record<string, unknown>, message: string): void;\n warn(fields: Record<string, unknown>, message: string): void;\n error(fields: Record<string, unknown>, message: string): void;\n}\n\nexport interface OutboxFileHost {\n logger: OutboxLogger;\n readJsonlLines(path: string): string[];\n}\n\nexport interface OutboxFileOps {\n isProcessingFile(name: string): boolean;\n drainOutboxFile(\n filePath: string,\n label: string,\n ): { lines: string[]; processingPath: string } | null;\n deleteProcessingFile(processingPath: string, label: string, consumedLines?: number): void;\n parseOutboxLine<T>(line: string, label: string): T | null;\n processOutboxFile<T extends Record<string, unknown>>(\n filePath: string,\n label: string,\n handler: (entry: T) => Promise<void>,\n opts?: { maxRetries?: number },\n ): Promise<void>;\n}\n\nconst defaultHost: OutboxFileHost = { logger, readJsonlLines };\nconst hostContext = new AsyncLocalStorage<OutboxFileHost>();\n\nfunction host(): OutboxFileHost {\n return hostContext.getStore() ?? defaultHost;\n}\n\n/** True if `name` is an in-flight `.processing` claim file written by drainOutboxFile. */\nexport function isProcessingFile(name: string): boolean {\n return name.endsWith(PROCESSING_SUFFIX);\n}\n\nfunction tryUnlink(path: string, label: string, reason: string) {\n try {\n unlinkSync(path);\n } catch (e) {\n // ENOENT means another path already cleaned this up (e.g. concurrent\n // drain, double-delete in a retry loop). Not worth warning about.\n if ((e as NodeJS.ErrnoException)?.code === \"ENOENT\") {\n host().logger.debug({ path }, `${label}: ${reason} (already gone)`);\n return;\n }\n host().logger.warn({ err: e, path }, `${label}: ${reason}`);\n }\n}\n\n/**\n * Atomically claim a .jsonl outbox file for processing.\n * Recovers leftover .processing files from crashes, renames the pending file\n * to .processing to prevent race conditions, and returns the parsed lines.\n * Returns null if the file doesn't exist or can't be claimed.\n *\n * Partial-failure edge case: when a crash leftover is merged back into pending,\n * `readFileSync` → `appendFileSync` → `unlinkSync` runs sequentially. If\n * `appendFileSync` throws mid-write (e.g. ENOSPC), the pending file receives a\n * partial copy of the leftover and the catch branch still unlinks the leftover\n * to avoid an infinite retry loop — so the tail of the leftover can be lost.\n * In practice the next drain parses the partial line as invalid JSON and drops\n * it via `parseOutboxLine`. This is a deliberate trade-off: we accept the rare\n * partial loss instead of stalling the outbox when the disk is full.\n */\nexport function drainOutboxFile(\n filePath: string,\n label: string,\n): { lines: string[]; processingPath: string } | null {\n const processingPath = filePath + PROCESSING_SUFFIX;\n const hasPending = existsSync(filePath);\n const hasLeftover = existsSync(processingPath);\n\n // Merge leftover into pending before claim.\n // hasPending=false: normal crash recovery — leftover is all we have.\n // hasPending=true: crash + writer race — without merge, the rename below\n // would overwrite leftover and drop its lines.\n if (hasLeftover) {\n // warn on crash+race (rare), info on plain recovery (expected after crash)\n const logMsg = `${label}: merging leftover .processing before claim`;\n const logCtx = { filePath, processingPath, hadPending: hasPending };\n if (hasPending) host().logger.warn(logCtx, logMsg);\n else host().logger.info(logCtx, logMsg);\n try {\n const leftover = readFileSync(processingPath, \"utf-8\");\n if (leftover) appendFileSync(filePath, leftover.endsWith(\"\\n\") ? leftover : `${leftover}\\n`);\n unlinkSync(processingPath);\n } catch (e) {\n host().logger.error(\n { err: e, processingPath },\n `${label}: failed to merge leftover — data may be lost`,\n );\n tryUnlink(processingPath, label, \"failed to clean up leftover after merge error\");\n }\n }\n\n if (!existsSync(filePath)) return null;\n\n // Atomically rename to prevent race condition with writer\n try {\n renameSync(filePath, processingPath);\n } catch (e) {\n host().logger.warn({ err: e, filePath }, `${label}: failed to rename for processing`);\n return null;\n }\n\n try {\n const lines = host().readJsonlLines(processingPath);\n return { lines, processingPath };\n } catch (e) {\n host().logger.warn({ err: e, processingPath }, `${label}: failed to read processing file`);\n tryUnlink(processingPath, label, \"failed to delete corrupt processing file\");\n return null;\n }\n}\n\n/**\n * Delete the .processing file after all entries are consumed.\n *\n * Writer-race salvage: `appendFileSync` racing `drainOutboxFile`'s rename can\n * land a line on the claimed inode AFTER the drainer already read it. Without\n * a recheck, unlinking here would silently destroy that entry. When\n * `consumedLines` is provided, any lines beyond it are appended back to the\n * original pending file before the claim is deleted (at-least-once preserved).\n */\nexport function deleteProcessingFile(\n processingPath: string,\n label: string,\n consumedLines?: number,\n) {\n if (consumedLines !== undefined && processingPath.endsWith(PROCESSING_SUFFIX)) {\n try {\n const current = host().readJsonlLines(processingPath);\n if (current.length > consumedLines) {\n const pendingPath = processingPath.slice(0, -PROCESSING_SUFFIX.length);\n const tail = current.slice(consumedLines).join(\"\\n\");\n appendFileSync(pendingPath, `${tail}\\n`);\n host().logger.warn(\n { processingPath, salvaged: current.length - consumedLines },\n `${label}: writer raced the drain — salvaged late lines back to pending`,\n );\n }\n } catch (e) {\n host().logger.warn({ err: e, processingPath }, `${label}: writer-race recheck failed`);\n }\n }\n tryUnlink(processingPath, label, \"failed to delete processing file\");\n}\n\n/**\n * Parse a single JSONL line. Returns null (and logs an error) on invalid JSON.\n * Keeps the parse + error-log pattern in one place instead of repeating it in\n * every flush function.\n */\nexport function parseOutboxLine<T>(line: string, label: string): T | null {\n try {\n return JSON.parse(line) as T;\n } catch {\n host().logger.error({ label, line: line.slice(0, 120) }, `${label}: Invalid JSON, dropping`);\n return null;\n }\n}\n\n/**\n * Drain an outbox file and invoke `handler` for each parsed entry.\n * Handles drain → parse → process → delete-processing → write-back-failures in one call.\n *\n * `handler` should throw to signal a retryable failure.\n * Failed entries are written back to `filePath` for the next flush cycle.\n * Pass `maxRetries` to drop entries that have exceeded the retry budget.\n *\n * Delivery: at-least-once. The `.processing` claim is deleted only AFTER all\n * entries were handled — a crash mid-processing leaves the claim on disk and\n * the next drain's leftover-merge redelivers the whole batch (including\n * already-handled entries). Handlers must therefore be idempotent or accept\n * duplicates; deleting the claim up-front would instead silently lose every\n * unprocessed entry on crash, which is worse for every queue using this path.\n */\nexport async function processOutboxFile<T extends Record<string, unknown>>(\n filePath: string,\n label: string,\n handler: (entry: T) => Promise<void>,\n opts: { maxRetries?: number } = {},\n): Promise<void> {\n const drained = drainOutboxFile(filePath, label);\n if (!drained) return;\n const { lines, processingPath } = drained;\n\n if (lines.length === 0) {\n deleteProcessingFile(processingPath, label, 0);\n return;\n }\n\n const MAX_RETRIES = opts.maxRetries ?? 0;\n const failedLines: string[] = [];\n\n for (const line of lines) {\n const entry = parseOutboxLine<T>(line, label);\n if (!entry) continue;\n\n const retryCount = (entry.retryCount as number | undefined) ?? 0;\n try {\n await handler(entry);\n } catch (err) {\n if (MAX_RETRIES > 0) {\n const next = retryCount + 1;\n if (next >= MAX_RETRIES) {\n host().logger.error(\n { err, label, retryCount: next },\n `${label}: Max retries reached, dropping`,\n );\n } else {\n host().logger.warn({ err, label, retryCount: next }, `${label}: Failed, will retry`);\n failedLines.push(JSON.stringify({ ...entry, retryCount: next }));\n }\n } else {\n host().logger.error({ err, label }, `${label}: Failed to process entry`);\n }\n }\n }\n\n // Drop the claim before writing failures back (same order as dm-queue):\n // a crash between the two redelivers nothing extra, while the reverse\n // order could double the failed entries (write-back + leftover merge).\n deleteProcessingFile(processingPath, label, lines.length);\n\n if (failedLines.length > 0) {\n try {\n appendFileSync(filePath, `${failedLines.join(\"\\n\")}\\n`);\n } catch (e) {\n host().logger.error(\n { err: e, label, count: failedLines.length },\n `${label}: Failed to write back entries`,\n );\n }\n }\n}\n\n/** Bind outbox processing to caller-owned logging and JSONL parsing dependencies. */\nexport function createOutboxFileOps(boundHost: OutboxFileHost): OutboxFileOps {\n return {\n isProcessingFile,\n drainOutboxFile: (filePath, label) =>\n hostContext.run(boundHost, () => drainOutboxFile(filePath, label)),\n deleteProcessingFile: (processingPath, label, consumedLines) =>\n hostContext.run(boundHost, () => deleteProcessingFile(processingPath, label, consumedLines)),\n parseOutboxLine: <T>(line: string, label: string) =>\n hostContext.run(boundHost, () => parseOutboxLine<T>(line, label)),\n processOutboxFile: <T extends Record<string, unknown>>(\n filePath: string,\n label: string,\n handler: (entry: T) => Promise<void>,\n opts: { maxRetries?: number } = {},\n ) => hostContext.run(boundHost, () => processOutboxFile(filePath, label, handler, opts)),\n };\n}\n",
|
|
8
|
+
"import {\n appendFileSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { safeUnlink } from \"#platform/file-utils\";\n\nexport function readJsonlLines(filePath: string): string[] {\n return readFileSync(filePath, \"utf-8\").trim().split(\"\\n\").filter(Boolean);\n}\n\n/**\n * Parse a JSONL string (one JSON value per line) into an array of `T`.\n * Throws on malformed lines — use when a corrupt fixture/log should fail\n * loudly rather than silently drop entries (paired with `readJsonlLines`'\n * resilient counterpart for live data streams).\n */\nexport function parseJsonlText<T = unknown>(raw: string): T[] {\n return raw\n .trim()\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => JSON.parse(line) as T);\n}\n\n/**\n * Read and JSON-parse a file. Returns null if the file is missing or contains\n * invalid JSON. Use when a missing/corrupt file should fall through to a\n * default rather than throw.\n */\nexport function readJsonFile<T = unknown>(filePath: string): T | null {\n try {\n return JSON.parse(readFileSync(filePath, \"utf-8\")) as T;\n } catch {\n return null;\n }\n}\n\n/** Atomically replace a JSON file and fsync the new contents before rename. */\nexport function writeJsonFileAtomic(filePath: string, value: unknown): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"wx\", 0o600);\n writeFileSync(fd, JSON.stringify(value, null, 2));\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n safeUnlink(tmpPath);\n throw err;\n }\n}\n\n// --- Cross-process append lock ---\n// POSIX `O_APPEND` is only atomic when the write payload fits in PIPE_BUF\n// (Linux 4096, macOS 512). MCP servers and the bot run as separate\n// processes that all `appendFileSync` to shared inbox/outbox files; a long\n// `tell_session` prompt or large `ask_session` reply is comfortably above\n// PIPE_BUF, and a concurrent append from another process can interleave at\n// the byte level — the result fails JSON parse and the entire entry is\n// silently dropped by `parseOutboxLine`.\n//\n// Mitigation: a sidecar `<filePath>.lock` created with `O_EXCL` serializes\n// every append at the OS level. Lock is held for the duration of one\n// `appendFileSync`, so the contention window is microseconds. Stale locks\n// (process crashed mid-write) are detected via mtime and forcibly removed\n// after `LOCK_STALE_MS`.\n//\n// When the lock still cannot be acquired within `LOCK_TIMEOUT_MS`, the append\n// FAILS. It used to fall through to an unlocked `appendFileSync` on the theory\n// that a possibly-interleaved entry beats a dropped one — but an interleaved\n// write is exactly the corruption the lock exists to prevent, it can damage a\n// neighbouring well-formed entry as well as its own, and `parseOutboxLine`\n// discards the wreckage later and far from the cause. The caller was told the\n// write succeeded. Failing loudly lets each caller choose: surface the error to\n// its client, or log and continue.\n//\n// The timeout MUST outlast the staleness threshold. A writer killed while\n// holding the lock leaves the file behind, and only the mtime check reclaims\n// it. With a timeout shorter than `LOCK_STALE_MS` every append issued in the\n// first few seconds after such a crash gave up *before* the reclaim could fire\n// — measured as a ~3.5s window in which every append to that file failed, all\n// of which the pre-throw fallback used to deliver. Waiting past the staleness\n// threshold means a dead holder is always reclaimed rather than waited out, so\n// a timeout now means a *live* holder has been stuck for over five seconds,\n// which is a genuine fault worth reporting.\nconst LOCK_SUFFIX = \".lock\";\nconst LOCK_RETRY_MS = 5;\nconst DEFAULT_LOCK_STALE_MS = 5000;\n/** Headroom so a waiter never gives up exactly as the reclaim becomes due. */\nconst LOCK_TIMEOUT_HEADROOM_MS = 1500;\n\n/**\n * Staleness threshold, overridable so tests can exercise the timeout path\n * without blocking a real five seconds.\n *\n * Read per call rather than captured at import: the constants are consulted\n * once per append, which is nothing next to the file I/O that follows, and a\n * module-level snapshot could not be adjusted by a test that imports this\n * module transitively.\n */\nfunction lockStaleMs(): number {\n const raw = Number.parseInt(process.env.NEGOTIUM_JSONL_LOCK_STALE_MS ?? \"\", 10);\n return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_LOCK_STALE_MS;\n}\n\n/** Always > `lockStaleMs()`, so a dead holder is reclaimed rather than waited out. */\nfunction lockTimeoutMs(): number {\n return lockStaleMs() + LOCK_TIMEOUT_HEADROOM_MS;\n}\nconst LOCK_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\n/**\n * The append lock could not be acquired, so nothing was written.\n *\n * Distinguishable from an I/O error so callers can retry, degrade, or report\n * contention specifically. Nothing was appended when this is thrown.\n */\nexport class JsonlLockTimeoutError extends Error {\n constructor(\n readonly filePath: string,\n readonly timeoutMs: number,\n ) {\n super(`jsonl append lock busy after ${timeoutMs}ms; nothing written to ${filePath}`);\n this.name = \"JsonlLockTimeoutError\";\n }\n}\n\n/** Synchronous, non-spinning sleep supported by both Bun and Node MCP workers. */\nfunction sleepForAppendLock(ms: number): void {\n Atomics.wait(LOCK_SLEEP, 0, 0, ms);\n}\n\nfunction tryAcquireAppendLock(lockPath: string): boolean {\n try {\n closeSync(openSync(lockPath, \"wx\")); // O_CREAT | O_EXCL — atomic\n return true;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") throw e;\n return false;\n }\n}\n\nfunction isStaleLock(lockPath: string): boolean {\n try {\n return Date.now() - statSync(lockPath).mtimeMs > lockStaleMs();\n } catch {\n return false;\n }\n}\n\n/**\n * Append a JSON-encoded entry + newline to a JSONL file. Ensures the parent\n * directory exists and serializes concurrent multi-process appends through a\n * sidecar lock so payloads larger than PIPE_BUF do not interleave.\n *\n * The drainer side (`outbox/file-ops.ts`) claims the file via atomic rename\n * and handles recovery of leftover `.processing` files from crashes.\n */\nexport function appendJsonlEntry(filePath: string, entry: unknown): void {\n appendJsonlLine(filePath, `${JSON.stringify(entry)}\\n`);\n}\n\n/**\n * Append an already-serialized JSONL line (must end with \"\\n\") under the\n * same cross-process append lock as `appendJsonlEntry`. Use when you\n * want to write back a raw line **exactly** — e.g. flusher tail-writeback\n * preserving lines that current parser can't decode, so a future parser\n * release still sees them.\n */\nexport function appendJsonlLine(filePath: string, line: string): void {\n mkdirSync(dirname(filePath), { recursive: true });\n const lockPath = `${filePath}${LOCK_SUFFIX}`;\n const payload = line.endsWith(\"\\n\") ? line : `${line}\\n`;\n\n let acquired = tryAcquireAppendLock(lockPath);\n // Pre-check: if the existing lock is already stale (writer crashed before\n // unlinking), reclaim it before sleeping. Saves the entire retry budget\n // for the common stale-leftover case.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n if (!acquired) {\n const start = Date.now();\n const timeoutMs = lockTimeoutMs();\n while (!acquired && Date.now() - start < timeoutMs) {\n // Codex launches built-in stdio MCPs under Node+tsx while the runtime\n // itself uses Bun. Atomics.wait gives both processes a blocking sleep\n // without a CPU-spinning fallback or a Bun-only global.\n sleepForAppendLock(LOCK_RETRY_MS);\n acquired = tryAcquireAppendLock(lockPath);\n // Recheck staleness inside the loop so a writer that crashes mid-wait\n // doesn't leave us spinning the whole timeout.\n if (!acquired && isStaleLock(lockPath)) {\n safeUnlink(lockPath);\n acquired = tryAcquireAppendLock(lockPath);\n }\n }\n }\n\n if (!acquired) throw new JsonlLockTimeoutError(filePath, lockTimeoutMs());\n\n try {\n appendFileSync(filePath, payload);\n } finally {\n safeUnlink(lockPath);\n }\n}\n\n/** Overwrite a JSONL file with the given entries. Trailing newline included. */\nexport function writeJsonlFile(filePath: string, entries: readonly unknown[]): void {\n const dir = dirname(filePath);\n mkdirSync(dir, { recursive: true });\n const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.random()\n .toString(16)\n .slice(2)}`;\n const payload = `${entries.map((e) => JSON.stringify(e)).join(\"\\n\")}\\n`;\n let fd: number | null = null;\n try {\n fd = openSync(tmpPath, \"w\");\n writeFileSync(fd, payload);\n fsyncSync(fd);\n closeSync(fd);\n fd = null;\n renameSync(tmpPath, filePath);\n fsyncDirectoryBestEffort(dir);\n } catch (err) {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n try {\n unlinkSync(tmpPath);\n } catch {}\n throw err;\n }\n}\n\nfunction fsyncDirectoryBestEffort(dir: string): void {\n let fd: number | null = null;\n try {\n fd = openSync(dir, \"r\");\n fsyncSync(fd);\n } catch {\n // Directory fsync is not portable across every runtime/filesystem. The\n // file fsync + rename above is the important integrity boundary; this is\n // best-effort durability for the directory entry.\n } finally {\n if (fd !== null) {\n try {\n closeSync(fd);\n } catch {}\n }\n }\n}\n",
|
|
9
|
+
"import { unlinkSync } from \"node:fs\";\nimport { logger } from \"#platform/logger\";\n\nexport interface SafeUnlinkHost {\n unlink(path: string): void;\n warn(context: { err: unknown; path: string }, message: string): void;\n}\n\nexport type SafeUnlink = (path: string, warnLabel?: string) => void;\n\n/** Create an isolated best-effort unlink helper using caller-owned I/O and logging. */\nexport function createSafeUnlink(host: SafeUnlinkHost): SafeUnlink {\n return (path, warnLabel) => {\n try {\n host.unlink(path);\n } catch (e) {\n if ((e as NodeJS.ErrnoException)?.code === \"ENOENT\") return;\n if (warnLabel) host.warn({ err: e, path }, warnLabel);\n }\n };\n}\n\nconst defaultSafeUnlink = createSafeUnlink({\n unlink: unlinkSync,\n warn: (context, message) => logger.warn(context, message),\n});\n\n/**\n * Best-effort unlink. ENOENT is always swallowed (the file is already gone).\n * Other errors are silent unless `warnLabel` is provided, in which case they\n * are logged at warn level with `{ err, path }` context.\n */\nexport function safeUnlink(path: string, warnLabel?: string): void {\n defaultSafeUnlink(path, warnLabel);\n}\n",
|
|
10
|
+
"import { type FSWatcher, mkdirSync, watch } from \"node:fs\";\nimport { logger } from \"#platform/logger\";\n\nexport const FALLBACK_INTERVAL_MS = 5_000; // fallback poll every 5s in case fs.watch misses events\n\nexport interface OutboxWatchLogger {\n error(fields: Record<string, unknown>, message: string): void;\n warn(fields: Record<string, unknown>, message: string): void;\n}\n\nexport interface OutboxWatchHost {\n logger: OutboxWatchLogger;\n}\n\nexport interface OutboxWatchOps {\n debouncedFlush(fn: () => Promise<void>, label: string, delayMs: number): () => void;\n watchDir(dir: string, onChange: () => void): FSWatcher | null;\n}\n\nexport function createOutboxWatchOps(host: OutboxWatchHost): OutboxWatchOps {\n function debouncedFlush(fn: () => Promise<void>, label: string, delayMs: number) {\n let timer: ReturnType<typeof setTimeout> | null = null;\n let running = false;\n let pending = false;\n\n async function run(): Promise<void> {\n if (running) {\n pending = true;\n return;\n }\n while (true) {\n running = true;\n pending = false;\n try {\n await fn();\n } catch (e) {\n host.logger.error({ err: e }, `${label}: Unhandled error`);\n } finally {\n running = false;\n }\n if (!pending) break;\n }\n }\n\n return () => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n run();\n }, delayMs);\n };\n }\n\n function watchDir(dir: string, onChange: () => void): FSWatcher | null {\n try {\n mkdirSync(dir, { recursive: true });\n const watcher = watch(dir, { recursive: true }, () => onChange());\n watcher.on(\"error\", (e) => {\n host.logger.warn({ err: e, dir }, \"outbox: fs.watch error\");\n });\n return watcher;\n } catch (e) {\n host.logger.warn({ err: e, dir }, \"outbox: Failed to watch dir\");\n return null;\n }\n }\n\n return { debouncedFlush, watchDir };\n}\n\nconst defaultWatchOps = createOutboxWatchOps({ logger });\n\nexport const debouncedFlush = defaultWatchOps.debouncedFlush;\nexport const watchDir = defaultWatchOps.watchDir;\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";;AAAA;AAmBO,SAAS,iBAAiB,CAAC,UAA8B,CAAC,GAAG;AAAA,EAClE,MAAM,cAAc,QAAQ,eAAe;AAAA,EAC3C,OAAO,KACL;AAAA,IACE,OAAO,QAAQ,SAAS,QAAQ,IAAI,aAAa;AAAA,IACjD,WAAW,cACP;AAAA,MACE,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,UAAU;AAAA,QACV,eAAe;AAAA,QACf,aAAa;AAAA,MACf;AAAA,IACF,IACA;AAAA,EACN,GACA,KAAK,YA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