@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303
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.md +32 -0
- package/README.md +284 -0
- package/dist/acp/agent.d.ts +48 -0
- package/dist/acp/agent.js +414 -0
- package/dist/acp/errors.d.ts +3 -0
- package/dist/acp/errors.js +11 -0
- package/dist/acp/event-mapper.d.ts +28 -0
- package/dist/acp/event-mapper.js +274 -0
- package/dist/acp/index.d.ts +9 -0
- package/dist/acp/index.js +21 -0
- package/dist/acp/runtime.d.ts +5 -0
- package/dist/acp/runtime.js +91 -0
- package/dist/acp/server.d.ts +4 -0
- package/dist/acp/server.js +35 -0
- package/dist/acp/skills.d.ts +6 -0
- package/dist/acp/skills.js +30 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.js +1 -0
- package/dist/agent-connections/messaging-processor.d.ts +17 -0
- package/dist/agent-connections/messaging-processor.js +131 -0
- package/dist/agent-connections/ownership.d.ts +24 -0
- package/dist/agent-connections/ownership.js +96 -0
- package/dist/agent-connections/registry.d.ts +20 -0
- package/dist/agent-connections/registry.js +167 -0
- package/dist/agent-connections/session-advertisement.d.ts +27 -0
- package/dist/agent-connections/session-advertisement.js +86 -0
- package/dist/agent-connections/signal-provider.d.ts +141 -0
- package/dist/agent-connections/signal-provider.js +35 -0
- package/dist/agent-connections/state-processor.d.ts +23 -0
- package/dist/agent-connections/state-processor.js +270 -0
- package/dist/agent-connections/thread-state.d.ts +41 -0
- package/dist/agent-connections/thread-state.js +157 -0
- package/dist/agent-connections/tools.d.ts +133 -0
- package/dist/agent-connections/tools.js +616 -0
- package/dist/agent-connections/types.d.ts +99 -0
- package/dist/agent-connections/types.js +4 -0
- package/dist/agent-connections/untrusted-text.d.ts +5 -0
- package/dist/agent-connections/untrusted-text.js +19 -0
- package/dist/agents/background-completion-events.d.ts +16 -0
- package/dist/agents/background-completion-events.js +16 -0
- package/dist/agents/background-completion.d.ts +22 -0
- package/dist/agents/background-completion.js +73 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.js +115 -0
- package/dist/agents/credential-resolver.d.ts +74 -0
- package/dist/agents/credential-resolver.js +142 -0
- package/dist/agents/custom-provider-source.d.ts +35 -0
- package/dist/agents/custom-provider-source.js +22 -0
- package/dist/agents/fastembed-subprocess.d.ts +52 -0
- package/dist/agents/fastembed-subprocess.js +282 -0
- package/dist/agents/instructions.d.ts +42 -0
- package/dist/agents/instructions.js +69 -0
- package/dist/agents/mastracode-gateway.d.ts +85 -0
- package/dist/agents/mastracode-gateway.js +500 -0
- package/dist/agents/memory.d.ts +36 -0
- package/dist/agents/memory.js +248 -0
- package/dist/agents/model.d.ts +158 -0
- package/dist/agents/model.js +382 -0
- package/dist/agents/modes/build.d.ts +12 -0
- package/dist/agents/modes/build.js +33 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.js +25 -0
- package/dist/agents/modes/plan.d.ts +8 -0
- package/dist/agents/modes/plan.js +43 -0
- package/dist/agents/prompts/agent-instructions.d.ts +122 -0
- package/dist/agents/prompts/agent-instructions.js +617 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.js +73 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.js +23 -0
- package/dist/agents/prompts/index.d.ts +61 -0
- package/dist/agents/prompts/index.js +141 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.js +20 -0
- package/dist/agents/prompts/plan.d.ts +11 -0
- package/dist/agents/prompts/plan.js +132 -0
- package/dist/agents/prompts/tool-guidance.d.ts +18 -0
- package/dist/agents/prompts/tool-guidance.js +158 -0
- package/dist/agents/sandbox-filesystem.d.ts +232 -0
- package/dist/agents/sandbox-filesystem.js +851 -0
- package/dist/agents/subagents/execute.d.ts +3 -0
- package/dist/agents/subagents/execute.js +24 -0
- package/dist/agents/subagents/explore.d.ts +3 -0
- package/dist/agents/subagents/explore.js +15 -0
- package/dist/agents/subagents/index.d.ts +6 -0
- package/dist/agents/subagents/index.js +15 -0
- package/dist/agents/subagents/plan.d.ts +3 -0
- package/dist/agents/subagents/plan.js +15 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.js +104 -0
- package/dist/agents/tool-availability.d.ts +17 -0
- package/dist/agents/tool-availability.js +134 -0
- package/dist/agents/tools.d.ts +37 -0
- package/dist/agents/tools.js +154 -0
- package/dist/agents/workflow-builder-agent.d.ts +2 -0
- package/dist/agents/workflow-builder-agent.js +79 -0
- package/dist/agents/workspace.d.ts +35 -0
- package/dist/agents/workspace.js +207 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.js +159 -0
- package/dist/auth/account-rotation-processor.d.ts +210 -0
- package/dist/auth/account-rotation-processor.js +662 -0
- package/dist/auth/account-routing-context.d.ts +17 -0
- package/dist/auth/account-routing-context.js +38 -0
- package/dist/auth/authorization-input.d.ts +16 -0
- package/dist/auth/authorization-input.js +39 -0
- package/dist/auth/device-code.d.ts +93 -0
- package/dist/auth/device-code.js +126 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +9 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.js +29 -0
- package/dist/auth/provider-auth-error.d.ts +24 -0
- package/dist/auth/provider-auth-error.js +44 -0
- package/dist/auth/providers/anthropic.d.ts +40 -0
- package/dist/auth/providers/anthropic.js +117 -0
- package/dist/auth/providers/github-copilot.d.ts +154 -0
- package/dist/auth/providers/github-copilot.js +359 -0
- package/dist/auth/providers/kimi-coding.d.ts +38 -0
- package/dist/auth/providers/kimi-coding.js +225 -0
- package/dist/auth/providers/openai-codex.d.ts +141 -0
- package/dist/auth/providers/openai-codex.js +531 -0
- package/dist/auth/providers/xai.d.ts +64 -0
- package/dist/auth/providers/xai.js +223 -0
- package/dist/auth/storage.d.ts +222 -0
- package/dist/auth/storage.js +805 -0
- package/dist/auth/types.d.ts +164 -0
- package/dist/auth/types.js +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.js +224 -0
- package/dist/constants.d.ts +29 -0
- package/dist/constants.js +34 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.js +19 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.js +156 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.js +5 -0
- package/dist/evals/scorers/classify-command.d.ts +30 -0
- package/dist/evals/scorers/classify-command.js +61 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.js +256 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.js +57 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.js +3 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.js +360 -0
- package/dist/experimental-agent.d.ts +19 -0
- package/dist/experimental-agent.js +45 -0
- package/dist/factory/client.d.ts +44 -0
- package/dist/factory/client.js +110 -0
- package/dist/factory/remote-controller.d.ts +34 -0
- package/dist/factory/remote-controller.js +40 -0
- package/dist/factory/remote-session.d.ts +210 -0
- package/dist/factory/remote-session.js +415 -0
- package/dist/goal-manager.d.ts +114 -0
- package/dist/goal-manager.js +351 -0
- package/dist/goal-signal.d.ts +14 -0
- package/dist/goal-signal.js +14 -0
- package/dist/headless/cli.d.ts +55 -0
- package/dist/headless/cli.js +261 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.js +207 -0
- package/dist/headless/format.d.ts +41 -0
- package/dist/headless/format.js +94 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.js +6 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.js +39 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.js +438 -0
- package/dist/headless/types.d.ts +175 -0
- package/dist/headless/types.js +16 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.js +77 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.js +128 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/manager.d.ts +75 -0
- package/dist/hooks/manager.js +289 -0
- package/dist/hooks/types.d.ts +180 -0
- package/dist/hooks/types.js +5 -0
- package/dist/index.d.ts +537 -0
- package/dist/index.js +1399 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.js +18 -0
- package/dist/knowledge-inspector.d.ts +139 -0
- package/dist/knowledge-inspector.js +533 -0
- package/dist/knowledge-scope-id.d.ts +7 -0
- package/dist/knowledge-scope-id.js +10 -0
- package/dist/knowledge-scope.d.ts +41 -0
- package/dist/knowledge-scope.js +85 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.js +248 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.js +4 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.js +41 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.js +79 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.js +158 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.js +52 -0
- package/dist/mcp/config.d.ts +77 -0
- package/dist/mcp/config.js +313 -0
- package/dist/mcp/index.d.ts +6 -0
- package/dist/mcp/index.js +3 -0
- package/dist/mcp/manager.d.ts +104 -0
- package/dist/mcp/manager.js +693 -0
- package/dist/mcp/state.d.ts +35 -0
- package/dist/mcp/state.js +94 -0
- package/dist/mcp/types.d.ts +139 -0
- package/dist/mcp/types.js +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.js +17 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.js +27 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.js +3 -0
- package/dist/onboarding/om-settings.d.ts +47 -0
- package/dist/onboarding/om-settings.js +80 -0
- package/dist/onboarding/pack-activation.d.ts +43 -0
- package/dist/onboarding/pack-activation.js +105 -0
- package/dist/onboarding/packs.d.ts +106 -0
- package/dist/onboarding/packs.js +283 -0
- package/dist/onboarding/settings.d.ts +563 -0
- package/dist/onboarding/settings.js +1110 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.js +139 -0
- package/dist/platform/index.d.ts +74 -0
- package/dist/platform/index.js +199 -0
- package/dist/plugin.d.ts +156 -0
- package/dist/plugin.js +27 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.js +84 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.js +187 -0
- package/dist/plugins/loader.d.ts +25 -0
- package/dist/plugins/loader.js +264 -0
- package/dist/plugins/manager.d.ts +115 -0
- package/dist/plugins/manager.js +507 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.js +47 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.js +58 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.js +22 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +109 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.js +115 -0
- package/dist/plugins/signal-lane.d.ts +59 -0
- package/dist/plugins/signal-lane.js +163 -0
- package/dist/plugins/types.d.ts +95 -0
- package/dist/plugins/types.js +1 -0
- package/dist/process-memory-diagnostics.d.ts +136 -0
- package/dist/process-memory-diagnostics.js +497 -0
- package/dist/processors/plan-rejection-abort.d.ts +16 -0
- package/dist/processors/plan-rejection-abort.js +62 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
- package/dist/providers/amazon-bedrock-gateway.js +142 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.js +99 -0
- package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
- package/dist/providers/anthropic-prompt-cache.js +8 -0
- package/dist/providers/anthropic-thinking.d.ts +5 -0
- package/dist/providers/anthropic-thinking.js +22 -0
- package/dist/providers/claude-max.d.ts +67 -0
- package/dist/providers/claude-max.js +232 -0
- package/dist/providers/github-copilot-gateway.d.ts +35 -0
- package/dist/providers/github-copilot-gateway.js +58 -0
- package/dist/providers/github-copilot.d.ts +60 -0
- package/dist/providers/github-copilot.js +320 -0
- package/dist/providers/google-thinking.d.ts +31 -0
- package/dist/providers/google-thinking.js +64 -0
- package/dist/providers/google-vertex-gateway.d.ts +23 -0
- package/dist/providers/google-vertex-gateway.js +49 -0
- package/dist/providers/google-vertex.d.ts +6 -0
- package/dist/providers/google-vertex.js +51 -0
- package/dist/providers/kimi-coding.d.ts +14 -0
- package/dist/providers/kimi-coding.js +80 -0
- package/dist/providers/model-ids.d.ts +53 -0
- package/dist/providers/model-ids.js +132 -0
- package/dist/providers/openai-codex.d.ts +114 -0
- package/dist/providers/openai-codex.js +427 -0
- package/dist/providers/provider-thinking.d.ts +23 -0
- package/dist/providers/provider-thinking.js +61 -0
- package/dist/providers/thinking-request.d.ts +14 -0
- package/dist/providers/thinking-request.js +87 -0
- package/dist/providers/xai.d.ts +33 -0
- package/dist/providers/xai.js +72 -0
- package/dist/schedules/index.d.ts +10 -0
- package/dist/schedules/index.js +6 -0
- package/dist/schedules/interval.d.ts +49 -0
- package/dist/schedules/interval.js +212 -0
- package/dist/schedules/prompt.d.ts +36 -0
- package/dist/schedules/prompt.js +36 -0
- package/dist/schedules/run-script.d.ts +8 -0
- package/dist/schedules/run-script.js +80 -0
- package/dist/schedules/scheduler.d.ts +101 -0
- package/dist/schedules/scheduler.js +167 -0
- package/dist/schedules/tools.d.ts +57 -0
- package/dist/schedules/tools.js +217 -0
- package/dist/schema.d.ts +499 -0
- package/dist/schema.js +131 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.js +18 -0
- package/dist/thinking-catalog.d.ts +4 -0
- package/dist/thinking-catalog.js +13 -0
- package/dist/thinking.d.ts +37 -0
- package/dist/thinking.js +134 -0
- package/dist/tool-names.d.ts +77 -0
- package/dist/tool-names.js +53 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.js +80 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.js +31 -0
- package/dist/tools/web-search.d.ts +116 -0
- package/dist/tools/web-search.js +158 -0
- package/dist/tools/workflows/create-workflow.d.ts +7 -0
- package/dist/tools/workflows/create-workflow.js +82 -0
- package/dist/tools/workflows/delete-workflow.d.ts +7 -0
- package/dist/tools/workflows/delete-workflow.js +18 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
- package/dist/tools/workflows/ephemeral-memory.js +41 -0
- package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
- package/dist/tools/workflows/extract-json-schema.js +19 -0
- package/dist/tools/workflows/get-workflow.d.ts +11 -0
- package/dist/tools/workflows/get-workflow.js +31 -0
- package/dist/tools/workflows/list-available-agents.d.ts +8 -0
- package/dist/tools/workflows/list-available-agents.js +29 -0
- package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
- package/dist/tools/workflows/list-available-classifiers.js +53 -0
- package/dist/tools/workflows/list-available-tools.d.ts +9 -0
- package/dist/tools/workflows/list-available-tools.js +37 -0
- package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-available-workflows.js +29 -0
- package/dist/tools/workflows/list-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-workflows.js +30 -0
- package/dist/tools/workflows/run-workflow.d.ts +9 -0
- package/dist/tools/workflows/run-workflow.js +49 -0
- package/dist/tools/workflows/save-workflow.d.ts +1125 -0
- package/dist/tools/workflows/save-workflow.js +25 -0
- package/dist/tools/workflows/tool-ids.d.ts +16 -0
- package/dist/tools/workflows/tool-ids.js +17 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.js +97 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.js +56 -0
- package/dist/utils/discarding-scores-storage.d.ts +33 -0
- package/dist/utils/discarding-scores-storage.js +51 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.js +215 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.js +58 -0
- package/dist/utils/local-observability.d.ts +19 -0
- package/dist/utils/local-observability.js +54 -0
- package/dist/utils/maintenance-lock.d.ts +42 -0
- package/dist/utils/maintenance-lock.js +196 -0
- package/dist/utils/notification-dispatch.d.ts +74 -0
- package/dist/utils/notification-dispatch.js +128 -0
- package/dist/utils/open-url.d.ts +10 -0
- package/dist/utils/open-url.js +27 -0
- package/dist/utils/path-security.d.ts +2 -0
- package/dist/utils/path-security.js +7 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.js +59 -0
- package/dist/utils/plans.d.ts +61 -0
- package/dist/utils/plans.js +120 -0
- package/dist/utils/project.d.ts +160 -0
- package/dist/utils/project.js +361 -0
- package/dist/utils/prune-cli.d.ts +24 -0
- package/dist/utils/prune-cli.js +124 -0
- package/dist/utils/signals-pubsub.d.ts +103 -0
- package/dist/utils/signals-pubsub.js +409 -0
- package/dist/utils/slash-command-loader.d.ts +52 -0
- package/dist/utils/slash-command-loader.js +139 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.js +106 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.js +93 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.js +118 -0
- package/dist/utils/storage-maintenance.d.ts +121 -0
- package/dist/utils/storage-maintenance.js +352 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.js +109 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.js +19 -0
- package/dist/utils/update-check.d.ts +151 -0
- package/dist/utils/update-check.js +430 -0
- package/dist/utils/wake-session.d.ts +44 -0
- package/dist/utils/wake-session.js +83 -0
- package/dist/voice/stt-registry.d.ts +67 -0
- package/dist/voice/stt-registry.js +144 -0
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.js +75 -0
- package/dist/workflows/register-primitives.d.ts +52 -0
- package/dist/workflows/register-primitives.js +40 -0
- package/dist/workflows/service.d.ts +64 -0
- package/dist/workflows/service.js +50 -0
- package/package.json +117 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `mastracode prune` — storage maintenance from a non-interactive shell.
|
|
3
|
+
*
|
|
4
|
+
* The in-TUI `/prune` command has to stop the UI, quiesce background writers
|
|
5
|
+
* (MCP, workers, intervals) and then exit the process, because retention
|
|
6
|
+
* deletes and VACUUM need the database to themselves. A standalone process
|
|
7
|
+
* already satisfies that contract — and, unlike `/prune`, it does not require a
|
|
8
|
+
* rendered prompt first, so maintenance stays reachable when the TUI cannot
|
|
9
|
+
* start. Without it a large mastra.db has no in-app remedy (issue #22056).
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* mastracode prune delete rows older than the retention policies
|
|
13
|
+
* mastracode prune --vacuum prune, then checkpoint WAL + VACUUM to return disk to the OS
|
|
14
|
+
* (local libsql only; remote libsql and Postgres only prune rows)
|
|
15
|
+
* mastracode prune --keep-memory prune, but keep chat history (messages/threads)
|
|
16
|
+
*/
|
|
17
|
+
import type { StorageConfig } from './project.js';
|
|
18
|
+
/**
|
|
19
|
+
* Run storage maintenance for the project in the current directory.
|
|
20
|
+
* Returns the process exit code (0 on success).
|
|
21
|
+
*/
|
|
22
|
+
export declare function runPruneCommand(args: string[]): Promise<number>;
|
|
23
|
+
export declare function describeStorageTarget(config: StorageConfig): string;
|
|
24
|
+
//# sourceMappingURL=prune-cli.d.ts.map
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { DEFAULT_CONFIG_DIR } from "../constants.js";
|
|
2
|
+
import { loadSettings } from "../onboarding/settings.js";
|
|
3
|
+
import { acquireMaintenanceLock } from "./maintenance-lock.js";
|
|
4
|
+
import { detectProject, getStorageConfig } from "./project.js";
|
|
5
|
+
import { createStorage, createVectorStore } from "./storage-factory.js";
|
|
6
|
+
import { DEFAULT_RETENTION, createStorageMaintenance, resolveLocalDbFiles, runStorageMaintenance } from "./storage-maintenance.js";
|
|
7
|
+
import path from "path";
|
|
8
|
+
import { LibSQLVector } from "@mastra/libsql";
|
|
9
|
+
// src/utils/prune-cli.ts
|
|
10
|
+
/**
|
|
11
|
+
* `mastracode prune` — storage maintenance from a non-interactive shell.
|
|
12
|
+
*
|
|
13
|
+
* The in-TUI `/prune` command has to stop the UI, quiesce background writers
|
|
14
|
+
* (MCP, workers, intervals) and then exit the process, because retention
|
|
15
|
+
* deletes and VACUUM need the database to themselves. A standalone process
|
|
16
|
+
* already satisfies that contract — and, unlike `/prune`, it does not require a
|
|
17
|
+
* rendered prompt first, so maintenance stays reachable when the TUI cannot
|
|
18
|
+
* start. Without it a large mastra.db has no in-app remedy (issue #22056).
|
|
19
|
+
*
|
|
20
|
+
* Usage:
|
|
21
|
+
* mastracode prune delete rows older than the retention policies
|
|
22
|
+
* mastracode prune --vacuum prune, then checkpoint WAL + VACUUM to return disk to the OS
|
|
23
|
+
* (local libsql only; remote libsql and Postgres only prune rows)
|
|
24
|
+
* mastracode prune --keep-memory prune, but keep chat history (messages/threads)
|
|
25
|
+
*/
|
|
26
|
+
const USAGE = `Usage: mastracode prune [--vacuum] [--keep-memory]
|
|
27
|
+
|
|
28
|
+
--vacuum After pruning, compact the local database files so freed
|
|
29
|
+
pages are returned to the OS. Needs free disk for the copy.
|
|
30
|
+
Local libsql only; remote libsql and Postgres only prune rows.
|
|
31
|
+
--keep-memory Prune everything except chat history (messages/threads).
|
|
32
|
+
`;
|
|
33
|
+
/**
|
|
34
|
+
* Run storage maintenance for the project in the current directory.
|
|
35
|
+
* Returns the process exit code (0 on success).
|
|
36
|
+
*/
|
|
37
|
+
async function runPruneCommand(args) {
|
|
38
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
39
|
+
console.log(USAGE);
|
|
40
|
+
return 0;
|
|
41
|
+
}
|
|
42
|
+
const flags = new Set(args.map((a) => a.toLowerCase()));
|
|
43
|
+
const unknown = [...flags].filter((f) => f !== "--vacuum" && f !== "--keep-memory");
|
|
44
|
+
if (unknown.length > 0) {
|
|
45
|
+
console.error(`Unknown prune option: ${unknown.join(", ")}\n${USAGE}`);
|
|
46
|
+
return 1;
|
|
47
|
+
}
|
|
48
|
+
const vacuum = flags.has("--vacuum");
|
|
49
|
+
const keepMemory = flags.has("--keep-memory");
|
|
50
|
+
try {
|
|
51
|
+
process.loadEnvFile(path.join(process.cwd(), ".env"));
|
|
52
|
+
} catch {}
|
|
53
|
+
let releaseLock;
|
|
54
|
+
try {
|
|
55
|
+
releaseLock = acquireMaintenanceLock();
|
|
56
|
+
} catch (err) {
|
|
57
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return await prune({
|
|
62
|
+
vacuum,
|
|
63
|
+
keepMemory
|
|
64
|
+
});
|
|
65
|
+
} finally {
|
|
66
|
+
releaseLock();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function prune({ vacuum, keepMemory }) {
|
|
70
|
+
const settings = loadSettings();
|
|
71
|
+
const project = detectProject(process.cwd());
|
|
72
|
+
const storageConfig = getStorageConfig(project.rootPath, settings.storage, DEFAULT_CONFIG_DIR);
|
|
73
|
+
console.log(`Storage target: ${describeStorageTarget(storageConfig)}`);
|
|
74
|
+
const { storage, backend, warning } = await createStorage(storageConfig);
|
|
75
|
+
if (warning) console.log(warning);
|
|
76
|
+
let vector;
|
|
77
|
+
try {
|
|
78
|
+
await storage.init();
|
|
79
|
+
const localDbFiles = resolveLocalDbFiles(storageConfig, backend);
|
|
80
|
+
if (localDbFiles.length > 0) console.log(`Database: ${localDbFiles.join(", ")}`);
|
|
81
|
+
if (vacuum && localDbFiles.length > 0) vector = await createVectorStore(storageConfig, backend);
|
|
82
|
+
const libsqlVector = vector instanceof LibSQLVector ? vector : void 0;
|
|
83
|
+
const maintenance = createStorageMaintenance({
|
|
84
|
+
storage,
|
|
85
|
+
backend,
|
|
86
|
+
retention: DEFAULT_RETENTION,
|
|
87
|
+
localDbFiles,
|
|
88
|
+
...libsqlVector ? { closeVector: () => libsqlVector.close() } : {}
|
|
89
|
+
});
|
|
90
|
+
await runStorageMaintenance({
|
|
91
|
+
maintenance,
|
|
92
|
+
vacuum,
|
|
93
|
+
keepMemory,
|
|
94
|
+
log: (line) => console.log(line)
|
|
95
|
+
});
|
|
96
|
+
console.log("Storage maintenance complete.");
|
|
97
|
+
return 0;
|
|
98
|
+
} catch (err) {
|
|
99
|
+
console.error(`Storage maintenance failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
100
|
+
try {
|
|
101
|
+
await storage.close?.();
|
|
102
|
+
if (vector instanceof LibSQLVector) await vector.close();
|
|
103
|
+
} catch {}
|
|
104
|
+
return 1;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Credential-free URL: drops userinfo and the query string (e.g. ?authToken=). */
|
|
108
|
+
function redactUrl(raw) {
|
|
109
|
+
try {
|
|
110
|
+
const url = new URL(raw);
|
|
111
|
+
url.username = "";
|
|
112
|
+
url.password = "";
|
|
113
|
+
url.search = "";
|
|
114
|
+
return url.toString();
|
|
115
|
+
} catch {
|
|
116
|
+
return "<unparseable URL>";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function describeStorageTarget(config) {
|
|
120
|
+
if (config.backend === "libsql") return config.url.startsWith("file:") ? `libsql file ${config.url.slice(5)}` : `libsql ${redactUrl(config.url)}`;
|
|
121
|
+
if (config.connectionString) return `pg ${redactUrl(config.connectionString)}`;
|
|
122
|
+
return `pg postgres://${`${config.host ?? "localhost"}${config.port ? `:${config.port}` : ""}`}/${config.database ?? ""}`;
|
|
123
|
+
}
|
|
124
|
+
export { describeStorageTarget, runPruneCommand };
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { PubSub, UnixSocketPubSub } from '@mastra/core/events';
|
|
2
|
+
import type { Event, EventCallback, LeaseProvider, PubSubDeliveryMode, SubscribeOptions } from '@mastra/core/events';
|
|
3
|
+
export type SignalsPubSubOptions = {
|
|
4
|
+
/**
|
|
5
|
+
* Also list this process's threads to, and find threads in, other projects on
|
|
6
|
+
* this machine: peer discovery runs in `<root>/_shared/` instead of this
|
|
7
|
+
* resource's directory.
|
|
8
|
+
*/
|
|
9
|
+
sharedAgentDiscovery?: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Directory that holds every resource's socket directory. Defaults to the
|
|
12
|
+
* absolute path in `MASTRACODE_SIGNALS_SOCKET_ROOT`, else `/tmp/mc`.
|
|
13
|
+
*/
|
|
14
|
+
rootDir?: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The lease that lets exactly one process dispatch a resource's due
|
|
18
|
+
* notifications: those of the resource's threads that carry `scope` (a
|
|
19
|
+
* `threadScopeKey`, one project's threads), or with no `scope`, those of its
|
|
20
|
+
* threads that carry none. Held in that resource's directory, so every process
|
|
21
|
+
* serving the resource contends for it whichever project it was started in.
|
|
22
|
+
*/
|
|
23
|
+
export declare function notificationDispatchLeaseKey(resourceId: string, scope?: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* A PubSub that manages one Unix socket per topic for cross-process signal
|
|
26
|
+
* coordination between mastracode processes on this machine.
|
|
27
|
+
*
|
|
28
|
+
* Socket paths use `<root>/<dir>/<sanitized-topic>.sock` (root `/tmp/mc`)
|
|
29
|
+
* for inspectability and automatic OS cleanup. Each topic gets its own
|
|
30
|
+
* socket, so broker election and message routing are per-topic.
|
|
31
|
+
*
|
|
32
|
+
* Every process shares one database, so any process can act on any project's
|
|
33
|
+
* thread — the notification dispatcher, for one, delivers whatever is due.
|
|
34
|
+
* Whatever coordinates a thread therefore lives with the thread, not with the
|
|
35
|
+
* process touching it:
|
|
36
|
+
*
|
|
37
|
+
* - A thread's stream topic and its leases (the run lease and the claim
|
|
38
|
+
* lease) live in the directory of the resource that owns the thread, so a
|
|
39
|
+
* process from another project sees that thread's active run and claim.
|
|
40
|
+
* - Thread-owner discovery lives in `<root>/_shared/`, so a process that finds
|
|
41
|
+
* a thread claimed can reach the owner and hand it the signal. It only
|
|
42
|
+
* answers for a thread the asker names, so it discloses nothing new.
|
|
43
|
+
* - Peer discovery (which lists threads) runs in `<root>/_shared/` when
|
|
44
|
+
* `sharedAgentDiscovery` is set, so processes in every project can list each
|
|
45
|
+
* other's threads. Without it, it stays in this resource's directory.
|
|
46
|
+
* - Everything else stays in this process's own resource directory.
|
|
47
|
+
*
|
|
48
|
+
* Stale sockets from crashed processes are handled by
|
|
49
|
+
* {@link UnixSocketPubSub}'s built-in election logic: it detects
|
|
50
|
+
* ECONNREFUSED on a dead broker socket, unlinks it, and re-elects.
|
|
51
|
+
* No blanket cleanup is needed here — that would break concurrent
|
|
52
|
+
* mc instances sharing a directory.
|
|
53
|
+
*
|
|
54
|
+
* One-shot reply topics (discovery and idle-acceptance replies) are
|
|
55
|
+
* reference-counted: every in-flight publish/subscribe and every live
|
|
56
|
+
* subscription holds a reference, and the topic's socket is closed as soon as
|
|
57
|
+
* the count drops to zero. Without this each request would keep a socket, a
|
|
58
|
+
* file descriptor and (for the broker) a socket file for the process lifetime.
|
|
59
|
+
* With `sharedAgentDiscovery`, another resource's thread topics are counted the
|
|
60
|
+
* same way, so a process that signals many threads elsewhere does not keep a
|
|
61
|
+
* socket open for each.
|
|
62
|
+
*/
|
|
63
|
+
declare class SignalsPubSub extends PubSub {
|
|
64
|
+
#private;
|
|
65
|
+
constructor(resourceId: string, options?: SignalsPubSubOptions);
|
|
66
|
+
get supportedModes(): ReadonlyArray<PubSubDeliveryMode>;
|
|
67
|
+
/**
|
|
68
|
+
* Filesystem leases. A thread's run and claim leases are held in the
|
|
69
|
+
* directory of the thread's resource, so every process contends for the
|
|
70
|
+
* same lease; any other key stays in this resource's directory.
|
|
71
|
+
*/
|
|
72
|
+
getLeaseProvider(): LeaseProvider;
|
|
73
|
+
publish(topic: string, event: Omit<Event, 'id' | 'createdAt'>, options?: {
|
|
74
|
+
localOnly?: boolean;
|
|
75
|
+
}): Promise<void>;
|
|
76
|
+
subscribe(topic: string, cb: EventCallback, options?: SubscribeOptions): Promise<void>;
|
|
77
|
+
unsubscribe(topic: string, cb: EventCallback): Promise<void>;
|
|
78
|
+
/**
|
|
79
|
+
* Drops a one-shot reply topic: its remaining subscriptions release their
|
|
80
|
+
* references and the socket closes once no operation still uses it. Other
|
|
81
|
+
* topics (workflow events, thread streams) have subscribers in other
|
|
82
|
+
* processes that need the broker, so clearing them is a no-op.
|
|
83
|
+
*/
|
|
84
|
+
clearTopic(topic: string): Promise<void>;
|
|
85
|
+
flush(): Promise<void>;
|
|
86
|
+
close(): Promise<void>;
|
|
87
|
+
/** Get the underlying socket for a topic (for testing/inspection). */
|
|
88
|
+
getSocket(topic: string): UnixSocketPubSub | undefined;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Creates a per-topic PubSub backed by Unix sockets for cross-process signal
|
|
92
|
+
* and workflow event coordination between mastracode processes.
|
|
93
|
+
*
|
|
94
|
+
* Topics live under `/tmp/mc/<resourceId>/`, except that a thread's stream and
|
|
95
|
+
* leases live under its own resource's directory and thread-owner discovery
|
|
96
|
+
* under `/tmp/mc/_shared/` (see {@link SignalsPubSub}). With
|
|
97
|
+
* `sharedAgentDiscovery`, peer discovery runs there too. Stale sockets from
|
|
98
|
+
* crashed processes are handled by the underlying {@link UnixSocketPubSub}'s
|
|
99
|
+
* broker election logic.
|
|
100
|
+
*/
|
|
101
|
+
export declare function createSignalsPubSub(resourceId: string, options?: SignalsPubSubOptions): SignalsPubSub;
|
|
102
|
+
export {};
|
|
103
|
+
//# sourceMappingURL=signals-pubsub.d.ts.map
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import { isAbsolute, join } from "path";
|
|
2
|
+
import { mkdir } from "fs/promises";
|
|
3
|
+
import { PubSub, UnixSocketPubSub } from "@mastra/core/events";
|
|
4
|
+
// src/utils/signals-pubsub.ts
|
|
5
|
+
const DEFAULT_SOCKET_ROOT = "/tmp/mc";
|
|
6
|
+
const SHARED_SCOPE_DIR = "_shared";
|
|
7
|
+
const THREAD_STREAM_PREFIX = "agent.thread-stream.";
|
|
8
|
+
const THREAD_KEY_SEPARATOR = "\0";
|
|
9
|
+
const THREAD_CLAIM_LEASE_PREFIX = "thread-claim:";
|
|
10
|
+
const NOTIFICATION_DISPATCH_LEASE_PREFIX = "notification-dispatch:";
|
|
11
|
+
const LEASE_SOCKET_NAME = ".leases.sock";
|
|
12
|
+
const OWNER_DISCOVERY_TOPIC = "agent.thread-owner-discovery";
|
|
13
|
+
const PEER_DISCOVERY_TOPIC = "agent.thread-peer-discovery";
|
|
14
|
+
const RESERVED_SOCKET_NAME = /^agent_thread-(?:peer|owner)-discovery(?:_|$)/i;
|
|
15
|
+
const MAX_PATH_SEGMENT_LENGTH = 128;
|
|
16
|
+
const UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
17
|
+
const DISCOVERY_REPLY_TOPIC = new RegExp(`^agent\\.thread-(?:peer|owner)-discovery\\.${UUID_PATTERN}$`, "i");
|
|
18
|
+
const IDLE_ACCEPTANCE_REPLY_TOPIC = new RegExp(`^agent\\.thread-stream\\..+\\.idle-acceptance\\.${UUID_PATTERN}$`, "i");
|
|
19
|
+
/**
|
|
20
|
+
* One-shot reply topics are minted per request (`<topic>.<uuid>`), used for a
|
|
21
|
+
* single round trip, and never published to again once the request settles.
|
|
22
|
+
*/
|
|
23
|
+
function isEphemeralTopic(topic) {
|
|
24
|
+
return DISCOVERY_REPLY_TOPIC.test(topic) || IDLE_ACCEPTANCE_REPLY_TOPIC.test(topic);
|
|
25
|
+
}
|
|
26
|
+
function socketRootFromEnv() {
|
|
27
|
+
const root = process.env.MASTRACODE_SIGNALS_SOCKET_ROOT;
|
|
28
|
+
return root && isAbsolute(root) ? root : DEFAULT_SOCKET_ROOT;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Whether an id can name a single directory: no path separators or control
|
|
32
|
+
* characters, not `.`/`..`, and bounded in length.
|
|
33
|
+
*/
|
|
34
|
+
function isSafePathSegment(value) {
|
|
35
|
+
if (!value || value.length > MAX_PATH_SEGMENT_LENGTH || value === "." || value === "..") return false;
|
|
36
|
+
for (const char of value) {
|
|
37
|
+
const code = char.charCodeAt(0);
|
|
38
|
+
if (char === "/" || char === "\\" || code < 32 || code === 127) return false;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
/** The resource a thread key (`<resourceId>\0<threadId>`) belongs to. */
|
|
43
|
+
function resourceOfThreadKey(key) {
|
|
44
|
+
const separatorIdx = key.indexOf(THREAD_KEY_SEPARATOR);
|
|
45
|
+
if (separatorIdx <= 0) return void 0;
|
|
46
|
+
const resourceId = key.slice(0, separatorIdx);
|
|
47
|
+
return isSafePathSegment(resourceId) ? resourceId : void 0;
|
|
48
|
+
}
|
|
49
|
+
/** Decodes `agent.thread-stream.<encoded resourceId\0threadId>[...]`. */
|
|
50
|
+
function decodeThreadTopic(topic) {
|
|
51
|
+
if (!topic.startsWith(THREAD_STREAM_PREFIX)) return void 0;
|
|
52
|
+
try {
|
|
53
|
+
return decodeURIComponent(topic.slice(20));
|
|
54
|
+
} catch {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The lease that lets exactly one process dispatch a resource's due
|
|
60
|
+
* notifications: those of the resource's threads that carry `scope` (a
|
|
61
|
+
* `threadScopeKey`, one project's threads), or with no `scope`, those of its
|
|
62
|
+
* threads that carry none. Held in that resource's directory, so every process
|
|
63
|
+
* serving the resource contends for it whichever project it was started in.
|
|
64
|
+
*/
|
|
65
|
+
function notificationDispatchLeaseKey(resourceId, scope) {
|
|
66
|
+
return `${NOTIFICATION_DISPATCH_LEASE_PREFIX}${resourceId}${scope === void 0 ? "" : `${THREAD_KEY_SEPARATOR}${scope}`}`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The resource a lease key belongs to: a thread's run lease and claim lease,
|
|
70
|
+
* and a resource's notification dispatch leases.
|
|
71
|
+
*/
|
|
72
|
+
function resourceOfLeaseKey(key) {
|
|
73
|
+
if (key.startsWith(NOTIFICATION_DISPATCH_LEASE_PREFIX)) {
|
|
74
|
+
const [resourceId = ""] = key.slice(22).split(THREAD_KEY_SEPARATOR, 1);
|
|
75
|
+
return isSafePathSegment(resourceId) ? resourceId : void 0;
|
|
76
|
+
}
|
|
77
|
+
return resourceOfThreadKey(key.startsWith(THREAD_CLAIM_LEASE_PREFIX) ? key.slice(13) : key);
|
|
78
|
+
}
|
|
79
|
+
function isOwnerDiscoveryTopic(topic) {
|
|
80
|
+
return topic === OWNER_DISCOVERY_TOPIC || topic.startsWith(`${OWNER_DISCOVERY_TOPIC}.`);
|
|
81
|
+
}
|
|
82
|
+
function isPeerDiscoveryTopic(topic) {
|
|
83
|
+
return topic === PEER_DISCOVERY_TOPIC || topic.startsWith(`${PEER_DISCOVERY_TOPIC}.`);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Whether a threadId can be the base name of a thread's socket file: no
|
|
87
|
+
* separators or control characters, not `.`/`..`, and not a name another
|
|
88
|
+
* socket in the same directory already uses (the lease socket, and the
|
|
89
|
+
* sanitized peer/owner discovery topics and their reply topics), compared
|
|
90
|
+
* case-insensitively because default macOS and Windows filesystems are.
|
|
91
|
+
*/
|
|
92
|
+
function isSafeFileName(value) {
|
|
93
|
+
if (!value || value === "." || value === ".." || `${value}.sock`.toLowerCase() === LEASE_SOCKET_NAME) return false;
|
|
94
|
+
if (RESERVED_SOCKET_NAME.test(value)) return false;
|
|
95
|
+
for (const char of value) {
|
|
96
|
+
const code = char.charCodeAt(0);
|
|
97
|
+
if (char === "/" || char === "\\" || code < 32 || code === 127) return false;
|
|
98
|
+
}
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Derive a filesystem-safe key for the topic. Thread-stream topics embed
|
|
103
|
+
* a threadId; all other topics use a sanitized version of the topic name.
|
|
104
|
+
*/
|
|
105
|
+
function topicKey(topic) {
|
|
106
|
+
const decoded = decodeThreadTopic(topic);
|
|
107
|
+
if (decoded !== void 0) {
|
|
108
|
+
const separatorIdx = decoded.indexOf(THREAD_KEY_SEPARATOR);
|
|
109
|
+
if (separatorIdx !== -1) return decoded.slice(separatorIdx + 1);
|
|
110
|
+
}
|
|
111
|
+
return topic.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
112
|
+
}
|
|
113
|
+
function socketKey(dir, topic) {
|
|
114
|
+
return `${dir}/${topicKey(topic)}`;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* A PubSub that manages one Unix socket per topic for cross-process signal
|
|
118
|
+
* coordination between mastracode processes on this machine.
|
|
119
|
+
*
|
|
120
|
+
* Socket paths use `<root>/<dir>/<sanitized-topic>.sock` (root `/tmp/mc`)
|
|
121
|
+
* for inspectability and automatic OS cleanup. Each topic gets its own
|
|
122
|
+
* socket, so broker election and message routing are per-topic.
|
|
123
|
+
*
|
|
124
|
+
* Every process shares one database, so any process can act on any project's
|
|
125
|
+
* thread — the notification dispatcher, for one, delivers whatever is due.
|
|
126
|
+
* Whatever coordinates a thread therefore lives with the thread, not with the
|
|
127
|
+
* process touching it:
|
|
128
|
+
*
|
|
129
|
+
* - A thread's stream topic and its leases (the run lease and the claim
|
|
130
|
+
* lease) live in the directory of the resource that owns the thread, so a
|
|
131
|
+
* process from another project sees that thread's active run and claim.
|
|
132
|
+
* - Thread-owner discovery lives in `<root>/_shared/`, so a process that finds
|
|
133
|
+
* a thread claimed can reach the owner and hand it the signal. It only
|
|
134
|
+
* answers for a thread the asker names, so it discloses nothing new.
|
|
135
|
+
* - Peer discovery (which lists threads) runs in `<root>/_shared/` when
|
|
136
|
+
* `sharedAgentDiscovery` is set, so processes in every project can list each
|
|
137
|
+
* other's threads. Without it, it stays in this resource's directory.
|
|
138
|
+
* - Everything else stays in this process's own resource directory.
|
|
139
|
+
*
|
|
140
|
+
* Stale sockets from crashed processes are handled by
|
|
141
|
+
* {@link UnixSocketPubSub}'s built-in election logic: it detects
|
|
142
|
+
* ECONNREFUSED on a dead broker socket, unlinks it, and re-elects.
|
|
143
|
+
* No blanket cleanup is needed here — that would break concurrent
|
|
144
|
+
* mc instances sharing a directory.
|
|
145
|
+
*
|
|
146
|
+
* One-shot reply topics (discovery and idle-acceptance replies) are
|
|
147
|
+
* reference-counted: every in-flight publish/subscribe and every live
|
|
148
|
+
* subscription holds a reference, and the topic's socket is closed as soon as
|
|
149
|
+
* the count drops to zero. Without this each request would keep a socket, a
|
|
150
|
+
* file descriptor and (for the broker) a socket file for the process lifetime.
|
|
151
|
+
* With `sharedAgentDiscovery`, another resource's thread topics are counted the
|
|
152
|
+
* same way, so a process that signals many threads elsewhere does not keep a
|
|
153
|
+
* socket open for each.
|
|
154
|
+
*/
|
|
155
|
+
var SignalsPubSub = class extends PubSub {
|
|
156
|
+
#resourceId;
|
|
157
|
+
#rootDir;
|
|
158
|
+
#leaseSockets = /* @__PURE__ */ new Map();
|
|
159
|
+
#sockets = /* @__PURE__ */ new Map();
|
|
160
|
+
#pending = /* @__PURE__ */ new Map();
|
|
161
|
+
#refs = /* @__PURE__ */ new Map();
|
|
162
|
+
#liveSubscriptions = /* @__PURE__ */ new Map();
|
|
163
|
+
#clearGenerations = /* @__PURE__ */ new Map();
|
|
164
|
+
#closing = /* @__PURE__ */ new Map();
|
|
165
|
+
#leaseProvider;
|
|
166
|
+
#sharedPeerDiscovery;
|
|
167
|
+
#closed = false;
|
|
168
|
+
constructor(resourceId, options = {}) {
|
|
169
|
+
super();
|
|
170
|
+
this.#resourceId = resourceId;
|
|
171
|
+
this.#rootDir = options.rootDir ?? socketRootFromEnv();
|
|
172
|
+
this.#sharedPeerDiscovery = Boolean(options.sharedAgentDiscovery) && this.#canShareDiscovery();
|
|
173
|
+
this.#leasesFor(resourceId);
|
|
174
|
+
const route = (key) => {
|
|
175
|
+
if (this.#closed) throw new Error("SignalsPubSub is closed");
|
|
176
|
+
return this.#leasesFor(resourceOfLeaseKey(key) ?? this.#resourceId);
|
|
177
|
+
};
|
|
178
|
+
this.#leaseProvider = {
|
|
179
|
+
acquireLease: async (key, owner, ttlMs) => route(key).acquireLease(key, owner, ttlMs),
|
|
180
|
+
getLeaseOwner: async (key) => route(key).getLeaseOwner(key),
|
|
181
|
+
releaseLease: async (key, owner) => route(key).releaseLease(key, owner),
|
|
182
|
+
renewLease: async (key, owner, ttlMs) => route(key).renewLease(key, owner, ttlMs),
|
|
183
|
+
transferLease: async (key, fromOwner, toOwner, ttlMs) => route(key).transferLease(key, fromOwner, toOwner, ttlMs)
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
get supportedModes() {
|
|
187
|
+
return ["push"];
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Filesystem leases. A thread's run and claim leases are held in the
|
|
191
|
+
* directory of the thread's resource, so every process contends for the
|
|
192
|
+
* same lease; any other key stays in this resource's directory.
|
|
193
|
+
*/
|
|
194
|
+
getLeaseProvider() {
|
|
195
|
+
return this.#leaseProvider;
|
|
196
|
+
}
|
|
197
|
+
async publish(topic, event, options) {
|
|
198
|
+
await this.#publishTo(topic, this.#dirFor(topic), event, options);
|
|
199
|
+
}
|
|
200
|
+
async subscribe(topic, cb, options) {
|
|
201
|
+
await this.#subscribeTo(topic, this.#dirFor(topic), cb, options);
|
|
202
|
+
}
|
|
203
|
+
async unsubscribe(topic, cb) {
|
|
204
|
+
await this.#unsubscribeFrom(topic, this.#dirFor(topic), cb);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Drops a one-shot reply topic: its remaining subscriptions release their
|
|
208
|
+
* references and the socket closes once no operation still uses it. Other
|
|
209
|
+
* topics (workflow events, thread streams) have subscribers in other
|
|
210
|
+
* processes that need the broker, so clearing them is a no-op.
|
|
211
|
+
*/
|
|
212
|
+
async clearTopic(topic) {
|
|
213
|
+
if (!isEphemeralTopic(topic)) return;
|
|
214
|
+
const key = socketKey(this.#dirFor(topic), topic);
|
|
215
|
+
if (!this.#refs.has(key)) return;
|
|
216
|
+
this.#clearGenerations.set(key, (this.#clearGenerations.get(key) ?? 0) + 1);
|
|
217
|
+
const subscriptions = this.#liveSubscriptions.get(key);
|
|
218
|
+
if (!subscriptions) return;
|
|
219
|
+
this.#liveSubscriptions.delete(key);
|
|
220
|
+
for (let i = 0; i < subscriptions.size; i++) this.#release(key);
|
|
221
|
+
}
|
|
222
|
+
async flush() {
|
|
223
|
+
await Promise.all([...this.#sockets.values()].map((s) => s.flush()));
|
|
224
|
+
}
|
|
225
|
+
async close() {
|
|
226
|
+
this.#closed = true;
|
|
227
|
+
await Promise.allSettled([
|
|
228
|
+
...[...this.#leaseSockets.values()].map((s) => s.close()),
|
|
229
|
+
...[...this.#sockets.values()].map((s) => s.close()),
|
|
230
|
+
...this.#closing.values()
|
|
231
|
+
]);
|
|
232
|
+
this.#sockets.clear();
|
|
233
|
+
this.#leaseSockets.clear();
|
|
234
|
+
this.#refs.clear();
|
|
235
|
+
this.#liveSubscriptions.clear();
|
|
236
|
+
this.#clearGenerations.clear();
|
|
237
|
+
}
|
|
238
|
+
/** Get the underlying socket for a topic (for testing/inspection). */
|
|
239
|
+
getSocket(topic) {
|
|
240
|
+
return this.#sockets.get(socketKey(this.#dirFor(topic), topic));
|
|
241
|
+
}
|
|
242
|
+
#canShareDiscovery() {
|
|
243
|
+
if (isSafePathSegment(this.#resourceId) && this.#resourceId !== SHARED_SCOPE_DIR) return true;
|
|
244
|
+
console.warn(`Cross-project agent discovery is disabled: resource id ${JSON.stringify(this.#resourceId)} cannot be used as a directory name, so other projects could not reach this instance.`);
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* One-shot reply topics close once unused. With shared discovery, so do thread
|
|
249
|
+
* topics routed to another resource; without it, they behave as before.
|
|
250
|
+
*/
|
|
251
|
+
#isRefCounted(topic) {
|
|
252
|
+
if (isEphemeralTopic(topic)) return true;
|
|
253
|
+
if (!this.#sharedPeerDiscovery) return false;
|
|
254
|
+
const decoded = decodeThreadTopic(topic);
|
|
255
|
+
if (decoded === void 0) return false;
|
|
256
|
+
const resourceId = resourceOfThreadKey(decoded);
|
|
257
|
+
return resourceId !== void 0 && resourceId !== this.#resourceId;
|
|
258
|
+
}
|
|
259
|
+
async #publishTo(topic, dir, event, options) {
|
|
260
|
+
if (!this.#isRefCounted(topic)) {
|
|
261
|
+
await (await this.#getOrCreate(topic, dir)).publish(topic, event, options);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const key = socketKey(dir, topic);
|
|
265
|
+
this.#retain(key);
|
|
266
|
+
try {
|
|
267
|
+
await (await this.#getOrCreate(topic, dir)).publish(topic, event, options);
|
|
268
|
+
} finally {
|
|
269
|
+
this.#release(key);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async #subscribeTo(topic, dir, cb, options) {
|
|
273
|
+
if (!this.#isRefCounted(topic)) {
|
|
274
|
+
await (await this.#getOrCreate(topic, dir)).subscribe(topic, cb, options);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const key = socketKey(dir, topic);
|
|
278
|
+
this.#retain(key);
|
|
279
|
+
const generation = this.#clearGenerations.get(key) ?? 0;
|
|
280
|
+
try {
|
|
281
|
+
const socket = await this.#getOrCreate(topic, dir);
|
|
282
|
+
await socket.subscribe(topic, cb, options);
|
|
283
|
+
if ((this.#clearGenerations.get(key) ?? 0) !== generation) {
|
|
284
|
+
await socket.unsubscribe(topic, cb);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
let subscriptions = this.#liveSubscriptions.get(key);
|
|
288
|
+
if (!subscriptions) {
|
|
289
|
+
subscriptions = /* @__PURE__ */ new Set();
|
|
290
|
+
this.#liveSubscriptions.set(key, subscriptions);
|
|
291
|
+
}
|
|
292
|
+
if (!subscriptions.has(cb)) {
|
|
293
|
+
subscriptions.add(cb);
|
|
294
|
+
this.#retain(key);
|
|
295
|
+
}
|
|
296
|
+
} finally {
|
|
297
|
+
this.#release(key);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
async #unsubscribeFrom(topic, dir, cb) {
|
|
301
|
+
const key = socketKey(dir, topic);
|
|
302
|
+
const socket = this.#sockets.get(key);
|
|
303
|
+
const subscriptions = this.#isRefCounted(topic) ? this.#liveSubscriptions.get(key) : void 0;
|
|
304
|
+
if (!subscriptions?.delete(cb)) {
|
|
305
|
+
if (!socket) return;
|
|
306
|
+
await socket.unsubscribe(topic, cb);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (subscriptions.size === 0) this.#liveSubscriptions.delete(key);
|
|
310
|
+
try {
|
|
311
|
+
await socket?.unsubscribe(topic, cb);
|
|
312
|
+
} finally {
|
|
313
|
+
this.#release(key);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
#leasesFor(resourceId) {
|
|
317
|
+
let socket = this.#leaseSockets.get(resourceId);
|
|
318
|
+
if (!socket) {
|
|
319
|
+
socket = new UnixSocketPubSub(join(this.#rootDir, resourceId, LEASE_SOCKET_NAME));
|
|
320
|
+
this.#leaseSockets.set(resourceId, socket);
|
|
321
|
+
}
|
|
322
|
+
return socket;
|
|
323
|
+
}
|
|
324
|
+
/** The directory, under the root, that holds a topic's socket. */
|
|
325
|
+
#dirFor(topic) {
|
|
326
|
+
if (isOwnerDiscoveryTopic(topic)) return SHARED_SCOPE_DIR;
|
|
327
|
+
if (this.#sharedPeerDiscovery && isPeerDiscoveryTopic(topic)) return SHARED_SCOPE_DIR;
|
|
328
|
+
const decoded = decodeThreadTopic(topic);
|
|
329
|
+
if (decoded !== void 0) return resourceOfThreadKey(decoded) ?? this.#resourceId;
|
|
330
|
+
return this.#resourceId;
|
|
331
|
+
}
|
|
332
|
+
#retain(key) {
|
|
333
|
+
this.#refs.set(key, (this.#refs.get(key) ?? 0) + 1);
|
|
334
|
+
}
|
|
335
|
+
#release(key) {
|
|
336
|
+
const refs = (this.#refs.get(key) ?? 0) - 1;
|
|
337
|
+
if (refs > 0) {
|
|
338
|
+
this.#refs.set(key, refs);
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
this.#refs.delete(key);
|
|
342
|
+
this.#clearGenerations.delete(key);
|
|
343
|
+
this.#liveSubscriptions.delete(key);
|
|
344
|
+
const socket = this.#sockets.get(key);
|
|
345
|
+
if (!socket) return;
|
|
346
|
+
this.#sockets.delete(key);
|
|
347
|
+
const closing = socket.close().catch(() => {}).finally(() => {
|
|
348
|
+
if (this.#closing.get(key) === closing) this.#closing.delete(key);
|
|
349
|
+
});
|
|
350
|
+
this.#closing.set(key, closing);
|
|
351
|
+
}
|
|
352
|
+
async #getOrCreate(topic, dir) {
|
|
353
|
+
if (this.#closed) throw new Error("SignalsPubSub is closed");
|
|
354
|
+
const key = socketKey(dir, topic);
|
|
355
|
+
const closing = this.#closing.get(key);
|
|
356
|
+
if (closing) {
|
|
357
|
+
await closing;
|
|
358
|
+
if (this.#closed) throw new Error("SignalsPubSub is closed");
|
|
359
|
+
}
|
|
360
|
+
const existing = this.#sockets.get(key);
|
|
361
|
+
if (existing) return existing;
|
|
362
|
+
let inflight = this.#pending.get(key);
|
|
363
|
+
if (!inflight) {
|
|
364
|
+
inflight = this.#initSocket(topic, dir, key);
|
|
365
|
+
this.#pending.set(key, inflight);
|
|
366
|
+
}
|
|
367
|
+
const socket = await inflight;
|
|
368
|
+
if (this.#closed) throw new Error("SignalsPubSub is closed");
|
|
369
|
+
return socket;
|
|
370
|
+
}
|
|
371
|
+
async #initSocket(topic, dir, key) {
|
|
372
|
+
try {
|
|
373
|
+
const socketPath = await this.#socketPath(topic, dir);
|
|
374
|
+
if (this.#closed) throw new Error("SignalsPubSub is closed");
|
|
375
|
+
const socket = new UnixSocketPubSub(socketPath);
|
|
376
|
+
this.#sockets.set(key, socket);
|
|
377
|
+
return socket;
|
|
378
|
+
} finally {
|
|
379
|
+
this.#pending.delete(key);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async #socketPath(topic, scope) {
|
|
383
|
+
let key = topicKey(topic);
|
|
384
|
+
if (decodeThreadTopic(topic) !== void 0 && !isSafeFileName(key)) throw new Error("Cannot route an agent thread topic whose threadId is not a safe file name");
|
|
385
|
+
const dir = join(this.#rootDir, scope);
|
|
386
|
+
await mkdir(dir, { recursive: true });
|
|
387
|
+
const candidate = join(dir, `${key}.sock`);
|
|
388
|
+
if (Buffer.byteLength(candidate) > 104) {
|
|
389
|
+
key = Buffer.from(await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(key))).toString("hex").slice(0, 16);
|
|
390
|
+
return join(dir, `${key}.sock`);
|
|
391
|
+
}
|
|
392
|
+
return candidate;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
/**
|
|
396
|
+
* Creates a per-topic PubSub backed by Unix sockets for cross-process signal
|
|
397
|
+
* and workflow event coordination between mastracode processes.
|
|
398
|
+
*
|
|
399
|
+
* Topics live under `/tmp/mc/<resourceId>/`, except that a thread's stream and
|
|
400
|
+
* leases live under its own resource's directory and thread-owner discovery
|
|
401
|
+
* under `/tmp/mc/_shared/` (see {@link SignalsPubSub}). With
|
|
402
|
+
* `sharedAgentDiscovery`, peer discovery runs there too. Stale sockets from
|
|
403
|
+
* crashed processes are handled by the underlying {@link UnixSocketPubSub}'s
|
|
404
|
+
* broker election logic.
|
|
405
|
+
*/
|
|
406
|
+
function createSignalsPubSub(resourceId, options) {
|
|
407
|
+
return new SignalsPubSub(resourceId, options);
|
|
408
|
+
}
|
|
409
|
+
export { createSignalsPubSub, notificationDispatchLeaseKey };
|