@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,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage maintenance — retention defaults and disk reclamation for mastracode.
|
|
3
|
+
*
|
|
4
|
+
* Retention (`DEFAULT_RETENTION`) is wired into the inner store by the storage
|
|
5
|
+
* factory so `storage.prune()` can delete aged rows across every domain,
|
|
6
|
+
* including the legacy libsql observability spans table.
|
|
7
|
+
*
|
|
8
|
+
* `prune()` only deletes rows — SQLite keeps the freed pages inside the file.
|
|
9
|
+
* `reclaimLibSQLDisk()` returns that space to the OS by streaming a
|
|
10
|
+
* `VACUUM INTO` copy of each file and swapping it into place. It requires all
|
|
11
|
+
* connections to be closed first, so it only runs from the post-TUI
|
|
12
|
+
* maintenance flow. We deliberately do NOT expose VACUUM as a public API on
|
|
13
|
+
* LibSQLStore.
|
|
14
|
+
*/
|
|
15
|
+
import type { MastraCompositeStore, PruneOptions, PruneResult, RetentionConfig } from '@mastra/core/storage';
|
|
16
|
+
import type { StorageConfig } from './project.js';
|
|
17
|
+
/**
|
|
18
|
+
* Default retention for mastracode's own storage. Tables not listed are kept
|
|
19
|
+
* forever. Ages chosen for a local dev tool where observability data dwarfs
|
|
20
|
+
* everything else (spans have been observed at 17+ GB):
|
|
21
|
+
* - spans/logs: short-lived debugging telemetry → 14d
|
|
22
|
+
* - scorer results & workflow snapshots: medium-lived run records → 30d
|
|
23
|
+
* - chat history (messages/threads): long-lived, user-visible → 90d
|
|
24
|
+
*/
|
|
25
|
+
export declare const DEFAULT_RETENTION: RetentionConfig;
|
|
26
|
+
/** Result of reclaiming disk for one database file (sizes include the WAL). */
|
|
27
|
+
export interface ReclaimResult {
|
|
28
|
+
file: string;
|
|
29
|
+
bytesBefore: number;
|
|
30
|
+
bytesAfter: number;
|
|
31
|
+
/**
|
|
32
|
+
* Set when the file was left untouched instead of compacted.
|
|
33
|
+
*
|
|
34
|
+
* `'vector-index'`: the database carries a `libsql_vector_idx` index.
|
|
35
|
+
* Vacuuming such a database corrupts its `libsql_vector_meta_shadow` table
|
|
36
|
+
* (`PRAGMA integrity_check` → `row not in PRIMARY KEY order`), silently at
|
|
37
|
+
* first, so we never compact it. See
|
|
38
|
+
* https://github.com/mastra-ai/mastra/issues/23439.
|
|
39
|
+
*
|
|
40
|
+
* `'detection-failed'`: the schema could not be inspected, so we cannot
|
|
41
|
+
* prove the database is safe to vacuum and skip it as a precaution.
|
|
42
|
+
*/
|
|
43
|
+
skipped?: 'vector-index' | 'detection-failed';
|
|
44
|
+
}
|
|
45
|
+
/** Handle the TUI uses to run storage maintenance without reaching into store internals. */
|
|
46
|
+
export interface StorageMaintenance {
|
|
47
|
+
backend: 'libsql' | 'pg';
|
|
48
|
+
/** Retention policies in effect (for display in /prune output). */
|
|
49
|
+
retention: RetentionConfig;
|
|
50
|
+
/** Delete rows older than the retention policies. Safe to re-run; batched and cancellable. `options.retention` replaces the standing policies for this call only. */
|
|
51
|
+
prune: (options?: PruneOptions) => Promise<PruneResult[]>;
|
|
52
|
+
/** Close the long-lived storage connection (checkpoints WAL for local libsql). Nothing can use the store afterwards. */
|
|
53
|
+
closeStorage?: () => Promise<void>;
|
|
54
|
+
/** Compact local libsql files (VACUUM INTO + swap) to return freed pages to the OS. Only set for local libsql backends. */
|
|
55
|
+
reclaimDisk?: (onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void) => Promise<ReclaimResult[]>;
|
|
56
|
+
}
|
|
57
|
+
/** Free bytes required before compacting: the compacted copy plus 20% + 256 MB headroom. */
|
|
58
|
+
export declare function requiredFreeBytes(liveBytes: number): number;
|
|
59
|
+
/**
|
|
60
|
+
* Compact each local libsql db file by streaming a `VACUUM INTO` copy next to
|
|
61
|
+
* it, then swapping the copy into place. Reports before/after sizes.
|
|
62
|
+
*
|
|
63
|
+
* Deliberately NOT an in-place `VACUUM`: that copies all live content into a
|
|
64
|
+
* temp store (held in memory by libsql builds with `temp_store=MEMORY`) and
|
|
65
|
+
* then rewrites the entire database back through the WAL — on multi-GB
|
|
66
|
+
* databases that has frozen whole machines via memory/IO exhaustion.
|
|
67
|
+
* `VACUUM INTO` reads the logical database once and writes the compacted copy
|
|
68
|
+
* sequentially with bounded memory, and the WAL never grows.
|
|
69
|
+
*
|
|
70
|
+
* Each file is preflighted: live bytes are estimated from
|
|
71
|
+
* `page_count - freelist_count` and the copy is refused unless the volume has
|
|
72
|
+
* `requiredFreeBytes()` available.
|
|
73
|
+
*
|
|
74
|
+
* MUST run with every connection to these files closed (the swap replaces the
|
|
75
|
+
* inode — a surviving connection would keep writing to the unlinked old file).
|
|
76
|
+
* `runStorageMaintenance()` closes storage before calling this.
|
|
77
|
+
*
|
|
78
|
+
* Databases carrying a `libsql_vector_idx` index are skipped, not compacted:
|
|
79
|
+
* any VACUUM over one corrupts its `libsql_vector_meta_shadow` table (issue
|
|
80
|
+
* #23439). Detection fails closed — a file we cannot inspect is skipped too.
|
|
81
|
+
* Skipped files come back with `skipped` set so the caller can report them.
|
|
82
|
+
*/
|
|
83
|
+
export declare function reclaimLibSQLDisk(dbFiles: string[], onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void): Promise<ReclaimResult[]>;
|
|
84
|
+
/**
|
|
85
|
+
* Resolve the local libsql db files eligible for checkpoint + VACUUM.
|
|
86
|
+
* Returns [] for remote (turso) urls and PG backends. When PG was requested
|
|
87
|
+
* but the factory fell back to libsql, the fallback uses the default files.
|
|
88
|
+
*/
|
|
89
|
+
export declare function resolveLocalDbFiles(config: StorageConfig, effectiveBackend: 'libsql' | 'pg'): string[];
|
|
90
|
+
/**
|
|
91
|
+
* Build the maintenance handle for the effective storage backend.
|
|
92
|
+
* `localDbFiles` are the local libsql file paths eligible for VACUUM;
|
|
93
|
+
* pass an empty array for remote (turso) or PG backends.
|
|
94
|
+
*/
|
|
95
|
+
export declare function createStorageMaintenance(opts: {
|
|
96
|
+
storage: MastraCompositeStore;
|
|
97
|
+
backend: 'libsql' | 'pg';
|
|
98
|
+
retention: RetentionConfig;
|
|
99
|
+
localDbFiles: string[];
|
|
100
|
+
/** Closes the vector store's connection; required for local libsql so the compaction swap isn't blocked by our own handle. */
|
|
101
|
+
closeVector?: () => Promise<void>;
|
|
102
|
+
}): StorageMaintenance;
|
|
103
|
+
export declare function formatBytes(bytes: number): string;
|
|
104
|
+
/**
|
|
105
|
+
* Run storage maintenance with exclusive access to the database, reporting
|
|
106
|
+
* progress through `log` (one line per pass so large deletes are visible).
|
|
107
|
+
*
|
|
108
|
+
* Must run AFTER the TUI is stopped and background writers are quiesced —
|
|
109
|
+
* batched deletes and VACUUM contend with live writes (SQLITE_BUSY) and can
|
|
110
|
+
* starve the event loop that renders the TUI. The storage connection is
|
|
111
|
+
* closed at the end (checkpointing the WAL for local libsql), so the process
|
|
112
|
+
* must exit afterwards.
|
|
113
|
+
*/
|
|
114
|
+
export declare function runStorageMaintenance(opts: {
|
|
115
|
+
maintenance: StorageMaintenance;
|
|
116
|
+
vacuum: boolean;
|
|
117
|
+
/** Skip the memory domain (messages/threads) so chat history is preserved. */
|
|
118
|
+
keepMemory?: boolean;
|
|
119
|
+
log: (line: string) => void;
|
|
120
|
+
}): Promise<void>;
|
|
121
|
+
//# sourceMappingURL=storage-maintenance.d.ts.map
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { getDatabasePath, getVectorDatabasePath } from "./project.js";
|
|
2
|
+
import { dirname } from "path";
|
|
3
|
+
import { closeSync, existsSync, openSync, readSync, renameSync, rmSync, statSync, statfsSync } from "fs";
|
|
4
|
+
import { setFlagsFromString } from "v8";
|
|
5
|
+
import { runInNewContext } from "vm";
|
|
6
|
+
import Database from "libsql";
|
|
7
|
+
// src/utils/storage-maintenance.ts
|
|
8
|
+
/**
|
|
9
|
+
* Storage maintenance — retention defaults and disk reclamation for mastracode.
|
|
10
|
+
*
|
|
11
|
+
* Retention (`DEFAULT_RETENTION`) is wired into the inner store by the storage
|
|
12
|
+
* factory so `storage.prune()` can delete aged rows across every domain,
|
|
13
|
+
* including the legacy libsql observability spans table.
|
|
14
|
+
*
|
|
15
|
+
* `prune()` only deletes rows — SQLite keeps the freed pages inside the file.
|
|
16
|
+
* `reclaimLibSQLDisk()` returns that space to the OS by streaming a
|
|
17
|
+
* `VACUUM INTO` copy of each file and swapping it into place. It requires all
|
|
18
|
+
* connections to be closed first, so it only runs from the post-TUI
|
|
19
|
+
* maintenance flow. We deliberately do NOT expose VACUUM as a public API on
|
|
20
|
+
* LibSQLStore.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Default retention for mastracode's own storage. Tables not listed are kept
|
|
24
|
+
* forever. Ages chosen for a local dev tool where observability data dwarfs
|
|
25
|
+
* everything else (spans have been observed at 17+ GB):
|
|
26
|
+
* - spans/logs: short-lived debugging telemetry → 14d
|
|
27
|
+
* - scorer results & workflow snapshots: medium-lived run records → 30d
|
|
28
|
+
* - chat history (messages/threads): long-lived, user-visible → 90d
|
|
29
|
+
*/
|
|
30
|
+
const DEFAULT_RETENTION = {
|
|
31
|
+
memory: {
|
|
32
|
+
messages: { maxAge: "90d" },
|
|
33
|
+
threads: { maxAge: "90d" }
|
|
34
|
+
},
|
|
35
|
+
observability: {
|
|
36
|
+
spans: { maxAge: "14d" },
|
|
37
|
+
logs: { maxAge: "14d" }
|
|
38
|
+
},
|
|
39
|
+
scores: { scorers: { maxAge: "30d" } },
|
|
40
|
+
workflows: { workflowSnapshot: { maxAge: "30d" } }
|
|
41
|
+
};
|
|
42
|
+
/** db file size + its WAL sidecar, in bytes. Missing files count as 0. */
|
|
43
|
+
function fileSizeWithWal(dbFile) {
|
|
44
|
+
let total = 0;
|
|
45
|
+
for (const candidate of [dbFile, `${dbFile}-wal`]) try {
|
|
46
|
+
total += statSync(candidate).size;
|
|
47
|
+
} catch {}
|
|
48
|
+
return total;
|
|
49
|
+
}
|
|
50
|
+
/** Free bytes required before compacting: the compacted copy plus 20% + 256 MB headroom. */
|
|
51
|
+
function requiredFreeBytes(liveBytes) {
|
|
52
|
+
return Math.ceil(liveBytes * 1.2) + 268435456;
|
|
53
|
+
}
|
|
54
|
+
/** First column of the first row of a PRAGMA result, as a number. */
|
|
55
|
+
function pragmaNumber(db, pragma) {
|
|
56
|
+
const row = db.pragma(pragma)?.[0];
|
|
57
|
+
return row ? Number(Object.values(row)[0]) : 0;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Journal mode straight from the SQLite file header (bytes 18/19:
|
|
61
|
+
* 1 = rollback journal, 2 = WAL) — readable without opening a connection.
|
|
62
|
+
*/
|
|
63
|
+
function journalModeFromHeader(file) {
|
|
64
|
+
const fd = openSync(file, "r");
|
|
65
|
+
try {
|
|
66
|
+
const buf = Buffer.alloc(2);
|
|
67
|
+
if (readSync(fd, buf, 0, 2, 18) !== 2) return "unknown";
|
|
68
|
+
if (buf[0] === 2 && buf[1] === 2) return "wal";
|
|
69
|
+
if (buf[0] === 1 && buf[1] === 1) return "delete";
|
|
70
|
+
return "unknown";
|
|
71
|
+
} finally {
|
|
72
|
+
closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Collect our own closed-but-unfinalized libsql connections before probing.
|
|
77
|
+
*
|
|
78
|
+
* libsql-js does not finalize prepared statements on `close()` (they are only
|
|
79
|
+
* released by GC; tursodatabase/libsql-js#228), so a connection we already
|
|
80
|
+
* closed can still hold the WAL lock and make the reclaim probe fail.
|
|
81
|
+
*
|
|
82
|
+
* `gc` is only global under `--expose-gc`, so we set that V8 flag at runtime
|
|
83
|
+
* and read `gc` from a fresh VM context. The flag is process-wide, but it only
|
|
84
|
+
* makes `gc` available to contexts created afterward (the main context's
|
|
85
|
+
* globals are untouched) and changes no GC behavior. A forced
|
|
86
|
+
* collection only frees unreachable objects. This runs only on the explicit
|
|
87
|
+
* vacuum path (`mastracode prune --vacuum` or `/prune vacuum`), and both exit
|
|
88
|
+
* the process right after, so the flag never outlives maintenance in practice.
|
|
89
|
+
*
|
|
90
|
+
* Remove this once libsql-js#228 lands and `close()` finalizes statements.
|
|
91
|
+
*/
|
|
92
|
+
async function releaseClosedConnections() {
|
|
93
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
94
|
+
const gc = globalThis.gc ?? (() => {
|
|
95
|
+
setFlagsFromString("--expose-gc");
|
|
96
|
+
return runInNewContext("gc");
|
|
97
|
+
})();
|
|
98
|
+
gc();
|
|
99
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
100
|
+
gc();
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Does this database carry a libsql vector index?
|
|
104
|
+
*
|
|
105
|
+
* Takes an already-open connection on purpose: the query needs a prepared
|
|
106
|
+
* statement, and a statement opened before the exclusivity probe pins the
|
|
107
|
+
* connection past close() (libsql-js#228) and makes the probe's
|
|
108
|
+
* `journal_mode = DELETE` fail with SQLITE_BUSY on files nobody else has open.
|
|
109
|
+
* The caller's connection must therefore already be in rollback mode — a
|
|
110
|
+
* pinned statement holds no lock there.
|
|
111
|
+
*
|
|
112
|
+
* Matched by schema, not filename — the main database can carry vector indexes
|
|
113
|
+
* too. SQLite stores `CREATE INDEX` SQL verbatim, so the match is deliberately
|
|
114
|
+
* loose (no trailing `(`): an index written `libsql_vector_idx (embedding)`
|
|
115
|
+
* must not slip through. The two errors are not symmetric — a false positive
|
|
116
|
+
* costs one uncompacted file that we tell the user about, a false negative
|
|
117
|
+
* silently corrupts their vector index.
|
|
118
|
+
*/
|
|
119
|
+
function hasVectorIndex(db) {
|
|
120
|
+
return db.prepare(`SELECT 1 AS hit FROM sqlite_master WHERE type = 'index' AND sql LIKE '%libsql_vector_idx%' LIMIT 1`).get() !== void 0;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Compact each local libsql db file by streaming a `VACUUM INTO` copy next to
|
|
124
|
+
* it, then swapping the copy into place. Reports before/after sizes.
|
|
125
|
+
*
|
|
126
|
+
* Deliberately NOT an in-place `VACUUM`: that copies all live content into a
|
|
127
|
+
* temp store (held in memory by libsql builds with `temp_store=MEMORY`) and
|
|
128
|
+
* then rewrites the entire database back through the WAL — on multi-GB
|
|
129
|
+
* databases that has frozen whole machines via memory/IO exhaustion.
|
|
130
|
+
* `VACUUM INTO` reads the logical database once and writes the compacted copy
|
|
131
|
+
* sequentially with bounded memory, and the WAL never grows.
|
|
132
|
+
*
|
|
133
|
+
* Each file is preflighted: live bytes are estimated from
|
|
134
|
+
* `page_count - freelist_count` and the copy is refused unless the volume has
|
|
135
|
+
* `requiredFreeBytes()` available.
|
|
136
|
+
*
|
|
137
|
+
* MUST run with every connection to these files closed (the swap replaces the
|
|
138
|
+
* inode — a surviving connection would keep writing to the unlinked old file).
|
|
139
|
+
* `runStorageMaintenance()` closes storage before calling this.
|
|
140
|
+
*
|
|
141
|
+
* Databases carrying a `libsql_vector_idx` index are skipped, not compacted:
|
|
142
|
+
* any VACUUM over one corrupts its `libsql_vector_meta_shadow` table (issue
|
|
143
|
+
* #23439). Detection fails closed — a file we cannot inspect is skipped too.
|
|
144
|
+
* Skipped files come back with `skipped` set so the caller can report them.
|
|
145
|
+
*/
|
|
146
|
+
async function reclaimLibSQLDisk(dbFiles, onFileStart) {
|
|
147
|
+
const results = [];
|
|
148
|
+
for (const file of dbFiles) {
|
|
149
|
+
if (!existsSync(file) || statSync(file).size < 100) continue;
|
|
150
|
+
const bytesBefore = fileSizeWithWal(file);
|
|
151
|
+
const tmp = `${file}.vacuum-tmp`;
|
|
152
|
+
rmSync(tmp, { force: true });
|
|
153
|
+
await releaseClosedConnections();
|
|
154
|
+
const probe = new Database(file);
|
|
155
|
+
try {
|
|
156
|
+
probe.exec("PRAGMA busy_timeout = 2000");
|
|
157
|
+
probe.exec("PRAGMA journal_mode = WAL");
|
|
158
|
+
probe.exec("PRAGMA journal_mode = DELETE");
|
|
159
|
+
} catch {} finally {
|
|
160
|
+
probe.close();
|
|
161
|
+
}
|
|
162
|
+
if (journalModeFromHeader(file) !== "delete") throw new Error(`${file} is in use by another process — is another Mastra Code session running? Close other sessions, then run /prune vacuum (or mastracode prune --vacuum) again.`);
|
|
163
|
+
const db = new Database(file);
|
|
164
|
+
try {
|
|
165
|
+
db.exec("PRAGMA busy_timeout = 2000");
|
|
166
|
+
let skipped;
|
|
167
|
+
try {
|
|
168
|
+
if (hasVectorIndex(db)) skipped = "vector-index";
|
|
169
|
+
} catch {
|
|
170
|
+
skipped = "detection-failed";
|
|
171
|
+
}
|
|
172
|
+
if (skipped) {
|
|
173
|
+
results.push({
|
|
174
|
+
file,
|
|
175
|
+
bytesBefore,
|
|
176
|
+
bytesAfter: bytesBefore,
|
|
177
|
+
skipped
|
|
178
|
+
});
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const pageSize = pragmaNumber(db, "page_size");
|
|
182
|
+
const pageCount = pragmaNumber(db, "page_count");
|
|
183
|
+
const freelistCount = pragmaNumber(db, "freelist_count");
|
|
184
|
+
const liveBytes = Math.max(0, pageCount - freelistCount) * pageSize;
|
|
185
|
+
const { bsize, bavail } = statfsSync(dirname(file));
|
|
186
|
+
const freeBytes = bsize * bavail;
|
|
187
|
+
if (freeBytes < requiredFreeBytes(liveBytes)) throw new Error(`Not enough free disk space to compact ${file}: need ${formatBytes(requiredFreeBytes(liveBytes))} for a ${formatBytes(liveBytes)} compacted copy, but only ${formatBytes(freeBytes)} is free.`);
|
|
188
|
+
onFileStart?.(file, bytesBefore, liveBytes);
|
|
189
|
+
db.exec(`VACUUM INTO '${tmp.replace(/'/g, "''")}'`);
|
|
190
|
+
} catch (err) {
|
|
191
|
+
rmSync(tmp, { force: true });
|
|
192
|
+
throw err;
|
|
193
|
+
} finally {
|
|
194
|
+
db.close();
|
|
195
|
+
}
|
|
196
|
+
if (journalModeFromHeader(file) !== "delete") {
|
|
197
|
+
rmSync(tmp, { force: true });
|
|
198
|
+
throw new Error(`${file} was opened by another process during compaction — is another Mastra Code session running? Close other sessions, then run /prune vacuum (or mastracode prune --vacuum) again.`);
|
|
199
|
+
}
|
|
200
|
+
renameSync(file, `${file}.old`);
|
|
201
|
+
try {
|
|
202
|
+
rmSync(`${file}-wal`, { force: true });
|
|
203
|
+
rmSync(`${file}-shm`, { force: true });
|
|
204
|
+
renameSync(tmp, file);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
try {
|
|
207
|
+
renameSync(`${file}.old`, file);
|
|
208
|
+
} catch {
|
|
209
|
+
throw new Error(`Failed to swap compacted copy into place AND failed to restore the original — your data is intact at ${file}.old; rename it back to ${file} manually. Original error: ${err instanceof Error ? err.message : String(err)}`);
|
|
210
|
+
}
|
|
211
|
+
rmSync(tmp, { force: true });
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
rmSync(`${file}.old`, { force: true });
|
|
215
|
+
results.push({
|
|
216
|
+
file,
|
|
217
|
+
bytesBefore,
|
|
218
|
+
bytesAfter: fileSizeWithWal(file)
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return results;
|
|
222
|
+
}
|
|
223
|
+
/** `file:/path` or `file:///path` → filesystem path; undefined for non-file urls. */
|
|
224
|
+
function fileUrlToPath(url) {
|
|
225
|
+
if (!url.startsWith("file:")) return void 0;
|
|
226
|
+
return url.replace(/^file:\/\//, "").replace(/^file:/, "");
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Resolve the local libsql db files eligible for checkpoint + VACUUM.
|
|
230
|
+
* Returns [] for remote (turso) urls and PG backends. When PG was requested
|
|
231
|
+
* but the factory fell back to libsql, the fallback uses the default files.
|
|
232
|
+
*/
|
|
233
|
+
function resolveLocalDbFiles(config, effectiveBackend) {
|
|
234
|
+
if (effectiveBackend !== "libsql") return [];
|
|
235
|
+
if (config.backend === "pg") return [getDatabasePath(), getVectorDatabasePath()];
|
|
236
|
+
if (config.isRemote) return [];
|
|
237
|
+
const files = [];
|
|
238
|
+
const main = fileUrlToPath(config.url);
|
|
239
|
+
if (main) files.push(main);
|
|
240
|
+
const vector = config.vectorUrl ? fileUrlToPath(config.vectorUrl) : getVectorDatabasePath();
|
|
241
|
+
if (vector) files.push(vector);
|
|
242
|
+
return files;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Build the maintenance handle for the effective storage backend.
|
|
246
|
+
* `localDbFiles` are the local libsql file paths eligible for VACUUM;
|
|
247
|
+
* pass an empty array for remote (turso) or PG backends.
|
|
248
|
+
*/
|
|
249
|
+
function createStorageMaintenance(opts) {
|
|
250
|
+
const { storage, backend, retention, localDbFiles, closeVector } = opts;
|
|
251
|
+
return {
|
|
252
|
+
backend,
|
|
253
|
+
retention,
|
|
254
|
+
prune: (options) => storage.prune(options),
|
|
255
|
+
closeStorage: async () => {
|
|
256
|
+
await storage.close?.();
|
|
257
|
+
await closeVector?.();
|
|
258
|
+
},
|
|
259
|
+
...backend === "libsql" && localDbFiles.length > 0 ? { reclaimDisk: (onFileStart) => reclaimLibSQLDisk(localDbFiles, onFileStart) } : {}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function formatBytes(bytes) {
|
|
263
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
264
|
+
const units = [
|
|
265
|
+
"KB",
|
|
266
|
+
"MB",
|
|
267
|
+
"GB",
|
|
268
|
+
"TB"
|
|
269
|
+
];
|
|
270
|
+
let value = bytes;
|
|
271
|
+
let unit = "B";
|
|
272
|
+
for (const next of units) {
|
|
273
|
+
if (value < 1024) break;
|
|
274
|
+
value /= 1024;
|
|
275
|
+
unit = next;
|
|
276
|
+
}
|
|
277
|
+
return `${value.toFixed(1)} ${unit}`;
|
|
278
|
+
}
|
|
279
|
+
/** Rows deleted per table per pass: default batchSize (1000) × 20 batches. */
|
|
280
|
+
const PASS_MAX_BATCHES = 20;
|
|
281
|
+
/**
|
|
282
|
+
* Run storage maintenance with exclusive access to the database, reporting
|
|
283
|
+
* progress through `log` (one line per pass so large deletes are visible).
|
|
284
|
+
*
|
|
285
|
+
* Must run AFTER the TUI is stopped and background writers are quiesced —
|
|
286
|
+
* batched deletes and VACUUM contend with live writes (SQLITE_BUSY) and can
|
|
287
|
+
* starve the event loop that renders the TUI. The storage connection is
|
|
288
|
+
* closed at the end (checkpointing the WAL for local libsql), so the process
|
|
289
|
+
* must exit afterwards.
|
|
290
|
+
*/
|
|
291
|
+
async function runStorageMaintenance(opts) {
|
|
292
|
+
const { maintenance, vacuum, keepMemory = false, log } = opts;
|
|
293
|
+
const { memory: _memory, ...withoutMemory } = maintenance.retention;
|
|
294
|
+
const retentionForRun = keepMemory ? { retention: withoutMemory } : {};
|
|
295
|
+
log("Pruning rows older than the retention policies:");
|
|
296
|
+
for (const [domain, tables] of Object.entries(maintenance.retention)) for (const [table, policy] of Object.entries(tables ?? {})) log(` ${domain}.${table}: ${keepMemory && domain === "memory" ? "kept (keep-memory)" : policy.maxAge}`);
|
|
297
|
+
const totals = /* @__PURE__ */ new Map();
|
|
298
|
+
for (;;) {
|
|
299
|
+
const results = await maintenance.prune({
|
|
300
|
+
maxBatches: PASS_MAX_BATCHES,
|
|
301
|
+
...retentionForRun
|
|
302
|
+
});
|
|
303
|
+
if (results.length === 0) break;
|
|
304
|
+
let remaining = false;
|
|
305
|
+
let deletedThisPass = 0;
|
|
306
|
+
for (const r of results) {
|
|
307
|
+
const key = `${r.domain}.${r.table}`;
|
|
308
|
+
totals.set(key, (totals.get(key) ?? 0) + r.deleted);
|
|
309
|
+
deletedThisPass += r.deleted;
|
|
310
|
+
if (!r.done) remaining = true;
|
|
311
|
+
if (r.deleted > 0) log(` ${key}: ${totals.get(key)} rows deleted${r.done ? "" : " so far…"}`);
|
|
312
|
+
}
|
|
313
|
+
if (!remaining) break;
|
|
314
|
+
if (deletedThisPass === 0) {
|
|
315
|
+
log(" stopping: no progress in the last pass.");
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const totalDeleted = [...totals.values()].reduce((sum, n) => sum + n, 0);
|
|
320
|
+
log(totalDeleted === 0 ? "Nothing to prune — no retention-eligible rows found." : `Prune complete: ${totalDeleted} rows deleted.`);
|
|
321
|
+
await maintenance.closeStorage?.();
|
|
322
|
+
if (!vacuum) {
|
|
323
|
+
if (maintenance.reclaimDisk) log("Deleted rows free pages inside the db file but not on disk. Run /prune vacuum (or mastracode prune --vacuum) to reclaim disk space.");
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
if (!maintenance.reclaimDisk) {
|
|
327
|
+
log("Disk reclamation (VACUUM) is only available for local libsql storage.");
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
log("Reclaiming disk (compacting database files)… this can take several minutes on large databases.");
|
|
331
|
+
const reclaimed = await maintenance.reclaimDisk((file, bytesBefore, liveBytes) => {
|
|
332
|
+
log(` vacuuming ${file} (${formatBytes(bytesBefore)}, ~${formatBytes(liveBytes)} live)…`);
|
|
333
|
+
});
|
|
334
|
+
if (reclaimed.length === 0) {
|
|
335
|
+
log("No local database files found to vacuum.");
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
for (const r of reclaimed) if (r.skipped === "vector-index") log(` ${r.file}: skipped — it contains a vector index, and compacting it would corrupt that index.`);
|
|
339
|
+
else if (r.skipped === "detection-failed") log(` ${r.file}: skipped — it could not be inspected, so it was left untouched as a precaution.`);
|
|
340
|
+
else log(` ${r.file}: ${formatBytes(r.bytesBefore)} → ${formatBytes(r.bytesAfter)}`);
|
|
341
|
+
const compacted = reclaimed.filter((r) => !r.skipped);
|
|
342
|
+
const vectorSkips = reclaimed.filter((r) => r.skipped === "vector-index").length;
|
|
343
|
+
const failedSkips = reclaimed.filter((r) => r.skipped === "detection-failed").length;
|
|
344
|
+
const skipSummary = [vectorSkips > 0 ? `${vectorSkips} skipped because ${vectorSkips === 1 ? "it contains" : "they contain"} a vector index` : "", failedSkips > 0 ? `${failedSkips} skipped because ${failedSkips === 1 ? "it" : "they"} could not be inspected` : ""].filter(Boolean).join("; ");
|
|
345
|
+
if (compacted.length === 0) {
|
|
346
|
+
log(`No database files were compacted; ${skipSummary}.`);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const saved = compacted.reduce((sum, r) => sum + Math.max(0, r.bytesBefore - r.bytesAfter), 0);
|
|
350
|
+
log(skipSummary ? `Reclaimed ${formatBytes(saved)}; ${skipSummary}.` : `Reclaimed ${formatBytes(saved)}.`);
|
|
351
|
+
}
|
|
352
|
+
export { DEFAULT_RETENTION, createStorageMaintenance, formatBytes, reclaimLibSQLDisk, requiredFreeBytes, resolveLocalDbFiles, runStorageMaintenance };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare class ThreadLockError extends Error {
|
|
2
|
+
readonly threadId: string;
|
|
3
|
+
readonly ownerPid: number;
|
|
4
|
+
constructor(threadId: string, ownerPid: number);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Attempt to acquire a lock for the given thread.
|
|
8
|
+
* Throws ThreadLockError if another live process holds the lock.
|
|
9
|
+
* Reclaims stale locks from dead processes.
|
|
10
|
+
*/
|
|
11
|
+
export declare function acquireThreadLock(threadId: string): void;
|
|
12
|
+
/**
|
|
13
|
+
* Release the lock for the given thread (only if we own it).
|
|
14
|
+
*/
|
|
15
|
+
export declare function releaseThreadLock(threadId: string): void;
|
|
16
|
+
/**
|
|
17
|
+
* Check if a thread is locked by another process.
|
|
18
|
+
* Returns the PID of the owner if locked, null otherwise.
|
|
19
|
+
*/
|
|
20
|
+
export declare function getThreadLockOwner(threadId: string): number | null;
|
|
21
|
+
/**
|
|
22
|
+
* Release all thread locks owned by this process.
|
|
23
|
+
* Call this on process exit.
|
|
24
|
+
*/
|
|
25
|
+
export declare function releaseAllThreadLocks(): void;
|
|
26
|
+
//# sourceMappingURL=thread-lock.d.ts.map
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { getAppDataDir } from "./project.js";
|
|
2
|
+
import * as path$1 from "path";
|
|
3
|
+
import * as fs$1 from "fs";
|
|
4
|
+
// src/utils/thread-lock.ts
|
|
5
|
+
/**
|
|
6
|
+
* Thread lock — ensures only one process writes to a thread at a time.
|
|
7
|
+
*
|
|
8
|
+
* Uses filesystem lock files: <appDataDir>/locks/<threadId>.lock
|
|
9
|
+
* Each lock file contains the PID of the owning process.
|
|
10
|
+
* Stale locks (from crashed processes) are detected and reclaimed.
|
|
11
|
+
*/
|
|
12
|
+
var ThreadLockError = class extends Error {
|
|
13
|
+
threadId;
|
|
14
|
+
ownerPid;
|
|
15
|
+
constructor(threadId, ownerPid) {
|
|
16
|
+
super(`Thread ${threadId} is locked by another process (PID ${ownerPid})`);
|
|
17
|
+
this.threadId = threadId;
|
|
18
|
+
this.ownerPid = ownerPid;
|
|
19
|
+
this.name = "ThreadLockError";
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
function getLocksDir() {
|
|
23
|
+
const dir = path$1.join(getAppDataDir(), "locks");
|
|
24
|
+
if (!fs$1.existsSync(dir)) fs$1.mkdirSync(dir, { recursive: true });
|
|
25
|
+
return dir;
|
|
26
|
+
}
|
|
27
|
+
function getLockPath(threadId) {
|
|
28
|
+
const safeId = threadId.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
29
|
+
return path$1.join(getLocksDir(), `${safeId}.lock`);
|
|
30
|
+
}
|
|
31
|
+
function isProcessAlive(pid) {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(pid, 0);
|
|
34
|
+
return true;
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Attempt to acquire a lock for the given thread.
|
|
41
|
+
* Throws ThreadLockError if another live process holds the lock.
|
|
42
|
+
* Reclaims stale locks from dead processes.
|
|
43
|
+
*/
|
|
44
|
+
function acquireThreadLock(threadId) {
|
|
45
|
+
const lockPath = getLockPath(threadId);
|
|
46
|
+
const myPid = process.pid;
|
|
47
|
+
if (fs$1.existsSync(lockPath)) try {
|
|
48
|
+
const content = fs$1.readFileSync(lockPath, "utf-8").trim();
|
|
49
|
+
const ownerPid = parseInt(content, 10);
|
|
50
|
+
if (!isNaN(ownerPid) && ownerPid !== myPid && isProcessAlive(ownerPid)) throw new ThreadLockError(threadId, ownerPid);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error instanceof ThreadLockError) throw error;
|
|
53
|
+
}
|
|
54
|
+
fs$1.writeFileSync(lockPath, String(myPid), { mode: 420 });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Release the lock for the given thread (only if we own it).
|
|
58
|
+
*/
|
|
59
|
+
function releaseThreadLock(threadId) {
|
|
60
|
+
const lockPath = getLockPath(threadId);
|
|
61
|
+
const myPid = process.pid;
|
|
62
|
+
try {
|
|
63
|
+
if (!fs$1.existsSync(lockPath)) return;
|
|
64
|
+
const content = fs$1.readFileSync(lockPath, "utf-8").trim();
|
|
65
|
+
if (parseInt(content, 10) === myPid) fs$1.unlinkSync(lockPath);
|
|
66
|
+
} catch {}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Check if a thread is locked by another process.
|
|
70
|
+
* Returns the PID of the owner if locked, null otherwise.
|
|
71
|
+
*/
|
|
72
|
+
function getThreadLockOwner(threadId) {
|
|
73
|
+
const lockPath = getLockPath(threadId);
|
|
74
|
+
try {
|
|
75
|
+
if (!fs$1.existsSync(lockPath)) return null;
|
|
76
|
+
const content = fs$1.readFileSync(lockPath, "utf-8").trim();
|
|
77
|
+
const ownerPid = parseInt(content, 10);
|
|
78
|
+
if (isNaN(ownerPid)) return null;
|
|
79
|
+
if (ownerPid === process.pid) return null;
|
|
80
|
+
if (!isProcessAlive(ownerPid)) {
|
|
81
|
+
try {
|
|
82
|
+
fs$1.unlinkSync(lockPath);
|
|
83
|
+
} catch {}
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return ownerPid;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Release all thread locks owned by this process.
|
|
93
|
+
* Call this on process exit.
|
|
94
|
+
*/
|
|
95
|
+
function releaseAllThreadLocks() {
|
|
96
|
+
try {
|
|
97
|
+
const locksDir = getLocksDir();
|
|
98
|
+
const files = fs$1.readdirSync(locksDir);
|
|
99
|
+
const myPid = String(process.pid);
|
|
100
|
+
for (const file of files) {
|
|
101
|
+
if (!file.endsWith(".lock")) continue;
|
|
102
|
+
const lockPath = path$1.join(locksDir, file);
|
|
103
|
+
try {
|
|
104
|
+
if (fs$1.readFileSync(lockPath, "utf-8").trim() === myPid) fs$1.unlinkSync(lockPath);
|
|
105
|
+
} catch {}
|
|
106
|
+
}
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
export { ThreadLockError, acquireThreadLock, getThreadLockOwner, releaseAllThreadLocks, releaseThreadLock };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { estimateTokenCount, sliceByTokens } from "tokenx";
|
|
2
|
+
// src/utils/token-estimator.ts
|
|
3
|
+
const UNPAIRED_SURROGATE_RE = /[\uD800-\uDFFF]/gu;
|
|
4
|
+
function sanitizeInput(text) {
|
|
5
|
+
if (!text) return "";
|
|
6
|
+
return (typeof text === `string` ? text : JSON.stringify(text)).replaceAll(`<|endoftext|>`, ``).replaceAll(`<|endofprompt|>`, ``);
|
|
7
|
+
}
|
|
8
|
+
function tokenEstimate(text) {
|
|
9
|
+
return estimateTokenCount(sanitizeInput(text));
|
|
10
|
+
}
|
|
11
|
+
function truncateStringForTokenEstimate(text, desiredTokenCount, fromEnd = true) {
|
|
12
|
+
const sanitized = sanitizeInput(text);
|
|
13
|
+
const totalTokens = estimateTokenCount(sanitized);
|
|
14
|
+
if (totalTokens <= desiredTokenCount) return sanitized;
|
|
15
|
+
const kept = (fromEnd ? sliceByTokens(sanitized, -desiredTokenCount) : sliceByTokens(sanitized, 0, desiredTokenCount)).replace(UNPAIRED_SURROGATE_RE, "�");
|
|
16
|
+
return `[Truncated ~${totalTokens - desiredTokenCount} tokens]
|
|
17
|
+
${kept}`;
|
|
18
|
+
}
|
|
19
|
+
export { tokenEstimate, truncateStringForTokenEstimate };
|