@bastani/atomic 0.9.70 → 0.9.71
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/CHANGELOG.md +130 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +16 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +12 -0
- package/dist/builtin/subagents/package.json +3 -3
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +8 -5
- package/dist/builtin/web-access/index.bundle.mjs +14750 -6455
- package/dist/builtin/web-access/package.json +3 -3
- package/dist/builtin/workflows/CHANGELOG.md +20 -0
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +27 -10
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +19 -5
- package/dist/builtin/workflows/src/index.js +19 -5
- package/dist/builtin/workflows/src/local-worker-entry.mjs +19 -5
- package/dist/cli/list-models.d.ts +7 -2
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +22 -50
- package/dist/cli/list-models.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +2 -0
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts +9 -8
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +24 -7
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +4 -7
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js +6 -10
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +9 -8
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +5 -0
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-transfer.d.ts.map +1 -1
- package/dist/core/agent-session-transfer.js +2 -0
- package/dist/core/agent-session-transfer.js.map +1 -1
- package/dist/core/agent-session-typed-queue.d.ts +19 -0
- package/dist/core/agent-session-typed-queue.d.ts.map +1 -0
- package/dist/core/agent-session-typed-queue.js +34 -0
- package/dist/core/agent-session-typed-queue.js.map +1 -0
- package/dist/core/agent-session-types.d.ts +20 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/cache-warmer.d.ts.map +1 -1
- package/dist/core/cache-warmer.js +2 -0
- package/dist/core/cache-warmer.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +13 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/extensions/api-types.d.ts +6 -3
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/api-types.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader-api.d.ts.map +1 -1
- package/dist/core/extensions/loader-api.js +6 -2
- package/dist/core/extensions/loader-api.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +2 -0
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/extensions/message-types.d.ts +18 -1
- package/dist/core/extensions/message-types.d.ts.map +1 -1
- package/dist/core/extensions/message-types.js.map +1 -1
- package/dist/core/extensions/runner-registries.d.ts.map +1 -1
- package/dist/core/extensions/runner-registries.js +8 -1
- package/dist/core/extensions/runner-registries.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +1 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/runtime-types.d.ts +2 -2
- package/dist/core/extensions/runtime-types.d.ts.map +1 -1
- package/dist/core/extensions/runtime-types.js.map +1 -1
- package/dist/core/fast-model-variants.d.ts +0 -9
- package/dist/core/fast-model-variants.d.ts.map +1 -1
- package/dist/core/fast-model-variants.js +0 -14
- package/dist/core/fast-model-variants.js.map +1 -1
- package/dist/core/model-config.d.ts +14 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-label.d.ts +38 -0
- package/dist/core/model-label.d.ts.map +1 -0
- package/dist/core/model-label.js +46 -0
- package/dist/core/model-label.js.map +1 -0
- package/dist/core/model-resolver-initial.d.ts +5 -0
- package/dist/core/model-resolver-initial.d.ts.map +1 -1
- package/dist/core/model-resolver-initial.js +26 -1
- package/dist/core/model-resolver-initial.js.map +1 -1
- package/dist/core/model-resolver.d.ts +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts +5 -7
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +14 -19
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/model-switch-thinking-level.d.ts +23 -0
- package/dist/core/model-switch-thinking-level.d.ts.map +1 -0
- package/dist/core/model-switch-thinking-level.js +19 -0
- package/dist/core/model-switch-thinking-level.js.map +1 -0
- package/dist/core/package-manager-git.d.ts +2 -0
- package/dist/core/package-manager-git.d.ts.map +1 -1
- package/dist/core/package-manager-git.js +32 -4
- package/dist/core/package-manager-git.js.map +1 -1
- package/dist/core/package-manager-operations.d.ts.map +1 -1
- package/dist/core/package-manager-operations.js +37 -5
- package/dist/core/package-manager-operations.js.map +1 -1
- package/dist/core/package-manager-types.d.ts +7 -1
- package/dist/core/package-manager-types.d.ts.map +1 -1
- package/dist/core/package-manager-types.js.map +1 -1
- package/dist/core/remote-catalog-provider.d.ts +14 -0
- package/dist/core/remote-catalog-provider.d.ts.map +1 -1
- package/dist/core/remote-catalog-provider.js +73 -0
- package/dist/core/remote-catalog-provider.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +11 -4
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/skills.js +1 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/storage/index.d.ts +1 -0
- package/dist/core/storage/index.d.ts.map +1 -1
- package/dist/core/storage/index.js +1 -0
- package/dist/core/storage/index.js.map +1 -1
- package/dist/core/storage/node-sqlite.d.ts.map +1 -1
- package/dist/core/storage/node-sqlite.js +13 -8
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/write-ahead-log.d.ts +25 -0
- package/dist/core/storage/write-ahead-log.d.ts.map +1 -0
- package/dist/core/storage/write-ahead-log.js +78 -0
- package/dist/core/storage/write-ahead-log.js.map +1 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +3 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/completion.d.ts +3 -2
- package/dist/core/tasks/completion.d.ts.map +1 -1
- package/dist/core/tasks/completion.js +7 -2
- package/dist/core/tasks/completion.js.map +1 -1
- package/dist/core/tasks/heartbeat-notice.d.ts +2 -0
- package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -1
- package/dist/core/tasks/heartbeat-notice.js +8 -4
- package/dist/core/tasks/heartbeat-notice.js.map +1 -1
- package/dist/core/tasks/heartbeat.d.ts.map +1 -1
- package/dist/core/tasks/heartbeat.js +1 -0
- package/dist/core/tasks/heartbeat.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +4 -4
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +13 -16
- package/dist/core/tools/write.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +6 -2
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/llama/huggingface-ui.d.ts +1 -0
- package/dist/extensions/llama/huggingface-ui.d.ts.map +1 -1
- package/dist/extensions/llama/huggingface-ui.js +13 -4
- package/dist/extensions/llama/huggingface-ui.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +3 -0
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/client/transports/stdio.d.ts.map +1 -1
- package/dist/extensions/mcp/client/transports/stdio.js +13 -2
- package/dist/extensions/mcp/client/transports/stdio.js.map +1 -1
- package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
- package/dist/extensions/mcp/client/transports/streamable-http.js +41 -3
- package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +1 -0
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +33 -24
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main-deferred-startup.d.ts +23 -1
- package/dist/main-deferred-startup.d.ts.map +1 -1
- package/dist/main-deferred-startup.js +28 -0
- package/dist/main-deferred-startup.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +8 -14
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +1 -3
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +17 -9
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +15 -3
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.d.ts +4 -0
- package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-message-renderer.js +23 -7
- package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts +5 -2
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +12 -2
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +7 -9
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +1 -2
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.js +2 -1
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +2 -1
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +9 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +46 -16
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +13 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +32 -11
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +1 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +3 -0
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-items.js +6 -5
- package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector-submenus.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector-submenus.js +2 -0
- package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +15 -3
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/task-row.d.ts +1 -0
- package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-row.js +3 -1
- package/dist/modes/interactive/components/task-row.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-component.js +3 -0
- package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.js +2 -1
- package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +9 -1
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.js +1 -1
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +3 -4
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +6 -4
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/interactive-editor-actions.js +2 -2
- package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
- package/dist/modes/interactive/interactive-extension-context.js +1 -1
- package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
- package/dist/modes/interactive/interactive-input-handling.js +11 -1
- package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +11 -2
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +11 -2
- package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +4 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +18 -4
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-prompt-turn.js +5 -1
- package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
- package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-queueing.js +17 -6
- package/dist/modes/interactive/interactive-queueing.js.map +1 -1
- package/dist/modes/interactive/interactive-render-chat.js +51 -5
- package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
- package/dist/modes/interactive/interactive-slash-commands.js +2 -2
- package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +9 -12
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-tui.js +6 -5
- package/dist/modes/interactive/interactive-tui.js.map +1 -1
- package/dist/modes/interactive/theme/global-theme.d.ts +1 -0
- package/dist/modes/interactive/theme/global-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/global-theme.js +3 -0
- package/dist/modes/interactive/theme/global-theme.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -1
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/interactive/theme/tui-theme.d.ts +5 -0
- package/dist/modes/interactive/theme/tui-theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/tui-theme.js +21 -2
- package/dist/modes/interactive/theme/tui-theme.js.map +1 -1
- package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +2 -5
- package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
- package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts +2 -6
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +39 -14
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client-api.d.ts +2 -5
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts +2 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +11 -4
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-input.d.ts +3 -2
- package/dist/modes/rpc/rpc-input.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-input.js +5 -1
- package/dist/modes/rpc/rpc-input.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +45 -16
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.d.ts +3 -1
- package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-session-binding.js +5 -1
- package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -5
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +26 -4
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts +0 -2
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +0 -5
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +5 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +7 -0
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/extensions/api-reference.md +21 -7
- package/docs/extensions/events.md +2 -0
- package/docs/extensions/examples.md +0 -1
- package/docs/extensions.md +7 -0
- package/docs/keybindings.md +1 -1
- package/docs/models/reference.md +8 -6
- package/docs/models-configuration.md +1 -0
- package/docs/models.md +2 -0
- package/docs/packages.md +2 -0
- package/docs/providers.md +14 -5
- package/docs/rpc/protocol.md +8 -2
- package/docs/rpc.md +4 -0
- package/docs/sdk.md +2 -0
- package/docs/storage.md +2 -0
- package/docs/tmux.md +6 -0
- package/docs/tui/reference.md +2 -0
- package/docs/windows.md +26 -0
- package/examples/extensions/README.md +2 -1
- package/examples/extensions/preset.ts +2 -0
- package/examples/extensions/tools.ts +2 -0
- package/npm-shrinkwrap.json +90 -72
- package/package.json +14 -15
- package/schemas/models.schema.json +4 -0
- package/examples/extensions/sandbox/index.ts +0 -323
- package/examples/extensions/sandbox/package-lock.json +0 -92
- package/examples/extensions/sandbox/package.json +0 -19
package/dist/core/skills.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"skills.js","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAmB,MAAM,kBAAkB,CAAC;AAElG,+BAA+B;AAC/B,MAAM,eAAe,GAAG,EAAE,CAAC;AAE3B,sCAAsC;AACtC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,MAAM,iBAAiB,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;AAIjE,SAAS,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS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AAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QACvE,CAAC;IACF,CAAC;IAED,OAAO;QACN,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,UAAU;QACV,WAAW,EAAE,CAAC,GAAG,cAAc,EAAE,GAAG,oBAAoB,CAAC;KACzD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport ignore from \"ignore\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { isPathWithin, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { createSyntheticSourceInfo, getResourcePathKey, type SourceInfo } from \"./source-info.ts\";\n\n/** Max name length per spec */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\t/** Every distinct real skill file in discovery order, including name-collision losers. */\n\tcandidates: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: unknown): string[] {\n\tconst errors: string[] = [];\n\n\tif (typeof description !== \"string\" || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, true);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn { skills, candidates: skills, diagnostics };\n\t}\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (!isFile || ig.ignores(relPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\treturn { skills, candidates: skills, diagnostics };\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip node_modules to avoid scanning dependencies\n\t\t\tif (entry.name === \"node_modules\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a directory and follow them\n\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDirectory = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDirectory ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isDirectory) {\n\t\t\t\tconst subResult = loadSkillsFromDirInternal(fullPath, source, false, ig, root);\n\t\t\t\tskills.push(...subResult.skills);\n\t\t\t\tdiagnostics.push(...subResult.diagnostics);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isFile || !includeRootFiles || !entry.name.endsWith(\".md\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t}\n\t} catch {}\n\n\treturn { skills, candidates: skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tconst isDeclaredSkill = basename(filePath) === \"SKILL.md\";\n\n\tlet rawContent: string;\n\ttry {\n\t\trawContent = readFileSync(filePath, \"utf-8\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tlet frontmatter: SkillFrontmatter;\n\ttry {\n\t\t({ frontmatter } = parseFrontmatter<SkillFrontmatter>(rawContent));\n\t} catch (error) {\n\t\tif (isDeclaredSkill) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\t}\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst description = frontmatter.description;\n\tconst hasDescription = typeof description === \"string\" && description.trim() !== \"\";\n\tif (!isDeclaredSkill && !hasDescription) {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst skillDir = dirname(filePath);\n\tconst parentDirName = basename(skillDir);\n\n\t// Validate description\n\tconst descErrors = validateDescription(description);\n\tfor (const error of descErrors) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Use name from frontmatter, or fall back to parent directory name\n\tconst frontmatterName = typeof frontmatter.name === \"string\" ? frontmatter.name : undefined;\n\tconst name = frontmatterName || parentDirName;\n\n\t// Validate name\n\tconst nameErrors = validateName(name);\n\tfor (const error of nameErrors) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Still load the skill even with warnings, unless description is missing or empty.\n\tif (!hasDescription) {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\treturn {\n\t\tskill: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tfilePath,\n\t\t\tbaseDir: skillDir,\n\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Format skills for inclusion in a system prompt.\n * Uses XML format per Agent Skills standard.\n * See: https://agentskills.io/integrate-skills\n *\n * Skills with disableModelInvocation=true are excluded from the prompt\n * (they can only be invoked explicitly via /skill:name commands).\n */\nexport function formatSkillsForPrompt(skills: Skill[], fileReadTool: \"read\" | \"bash\" | \"indirect\" = \"read\"): string {\n\tconst visibleSkills = skills.filter((s) => !s.disableModelInvocation);\n\n\tif (visibleSkills.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\tfileReadTool === \"read\"\n\t\t\t? \"Use the read tool to load a skill's file when the task matches its description.\"\n\t\t\t: fileReadTool === \"bash\"\n\t\t\t\t? \"Use bash to load a skill's file when the task matches its description.\"\n\t\t\t\t: \"Load a skill's file when the task matches its description.\",\n\t\t\"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\",\n\t\t\"\",\n\t\t\"<available_skills>\",\n\t];\n\n\tfor (const skill of visibleSkills) {\n\t\tlines.push(\" <skill>\");\n\t\tlines.push(` <name>${escapeXml(skill.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(skill.description)}</description>`);\n\t\tlines.push(` <location>${escapeXml(skill.filePath)}</location>`);\n\t\tlines.push(\" </skill>\");\n\t}\n\n\tlines.push(\"</available_skills>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&\")\n\t\t.replace(/</g, \"<\")\n\t\t.replace(/>/g, \">\")\n\t\t.replace(/\"/g, \""\")\n\t\t.replace(/'/g, \"'\");\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map<string, Skill>();\n\tconst candidates: Skill[] = [];\n\tconst realPathSet = new Set<string>();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = getResourcePathKey(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trealPathSet.add(realPath);\n\t\t\tcandidates.push(skill);\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", true));\n\t\taddSkills(loadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", true));\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isPathWithin(userSkillsDir, resolvedPath)) return \"user\";\n\t\t\tif (isPathWithin(projectSkillsDir, resolvedPath)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, true));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], candidates: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tcandidates,\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"skills.js","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACrE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAmB,MAAM,kBAAkB,CAAC;AA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gBACP,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mCAAmC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;YAC5G,CAAC;QACF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,2BAA2B,CAAC;YACrF,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QACvE,CAAC;IACF,CAAC;IAED,OAAO;QACN,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,UAAU;QACV,WAAW,EAAE,CAAC,GAAG,cAAc,EAAE,GAAG,oBAAoB,CAAC;KACzD,CAAC;AACH,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport ignore from \"ignore\";\nimport { basename, dirname, join, relative, resolve, sep } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.js\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { isPathWithin, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { createSyntheticSourceInfo, getResourcePathKey, type SourceInfo } from \"./source-info.ts\";\n\n/** Max name length per spec */\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\nconst IGNORE_FILE_NAMES = [\".gitignore\", \".ignore\", \".fdignore\"];\n\ntype IgnoreMatcher = ReturnType<typeof ignore>;\n\nfunction toPosixPath(p: string): string {\n\treturn p.split(sep).join(\"/\");\n}\n\nfunction prefixIgnorePattern(line: string, prefix: string): string | null {\n\tconst trimmed = line.trim();\n\tif (!trimmed) return null;\n\tif (trimmed.startsWith(\"#\") && !trimmed.startsWith(\"\\\\#\")) return null;\n\n\tlet pattern = line;\n\tlet negated = false;\n\n\tif (pattern.startsWith(\"!\")) {\n\t\tnegated = true;\n\t\tpattern = pattern.slice(1);\n\t} else if (pattern.startsWith(\"\\\\!\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tif (pattern.startsWith(\"/\")) {\n\t\tpattern = pattern.slice(1);\n\t}\n\n\tconst prefixed = prefix ? `${prefix}${pattern}` : pattern;\n\treturn negated ? `!${prefixed}` : prefixed;\n}\n\nfunction addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {\n\tconst relativeDir = relative(rootDir, dir);\n\tconst prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : \"\";\n\n\tfor (const filename of IGNORE_FILE_NAMES) {\n\t\tconst ignorePath = join(dir, filename);\n\t\tif (!existsSync(ignorePath)) continue;\n\t\ttry {\n\t\t\tconst content = readFileSync(ignorePath, \"utf-8\");\n\t\t\tconst patterns = content\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => prefixIgnorePattern(line, prefix))\n\t\t\t\t.filter((line): line is string => Boolean(line));\n\t\t\tif (patterns.length > 0) {\n\t\t\t\tig.add(patterns);\n\t\t\t}\n\t\t} catch {}\n\t}\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\t/** Every distinct real skill file in discovery order, including name-collision losers. */\n\tcandidates: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nfunction validateName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: unknown): string[] {\n\tconst errors: string[] = [];\n\n\tif (typeof description !== \"string\" || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, true);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tincludeRootFiles: boolean,\n\tignoreMatcher?: IgnoreMatcher,\n\trootDir?: string,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\tif (!existsSync(dir)) {\n\t\treturn { skills, candidates: skills, diagnostics };\n\t}\n\n\tconst root = rootDir ?? dir;\n\tconst ig = ignoreMatcher ?? ignore();\n\taddIgnoreRules(ig, dir, root);\n\n\ttry {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true });\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name !== \"SKILL.md\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tisFile = statSync(fullPath).isFile();\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tif (!isFile || ig.ignores(relPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t\treturn { skills, candidates: skills, diagnostics };\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.name.startsWith(\".\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Skip node_modules to avoid scanning dependencies\n\t\t\tif (entry.name === \"node_modules\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst fullPath = join(dir, entry.name);\n\n\t\t\t// For symlinks, check if they point to a directory and follow them\n\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\tlet isFile = entry.isFile();\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst stats = statSync(fullPath);\n\t\t\t\t\tisDirectory = stats.isDirectory();\n\t\t\t\t\tisFile = stats.isFile();\n\t\t\t\t} catch {\n\t\t\t\t\t// Broken symlink, skip it\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst relPath = toPosixPath(relative(root, fullPath));\n\t\t\tconst ignorePath = isDirectory ? `${relPath}/` : relPath;\n\t\t\tif (ig.ignores(ignorePath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (isDirectory) {\n\t\t\t\tconst subResult = loadSkillsFromDirInternal(fullPath, source, false, ig, root);\n\t\t\t\tskills.push(...subResult.skills);\n\t\t\t\tdiagnostics.push(...subResult.diagnostics);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!isFile || !includeRootFiles || !entry.name.endsWith(\".md\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst result = loadSkillFromFile(fullPath, source);\n\t\t\tif (result.skill) {\n\t\t\t\tskills.push(result.skill);\n\t\t\t}\n\t\t\tdiagnostics.push(...result.diagnostics);\n\t\t}\n\t} catch {}\n\n\treturn { skills, candidates: skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tconst isDeclaredSkill = basename(filePath) === \"SKILL.md\";\n\n\tlet rawContent: string;\n\ttry {\n\t\trawContent = readFileSync(filePath, \"utf-8\");\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to read skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tlet frontmatter: SkillFrontmatter;\n\ttry {\n\t\t({ frontmatter } = parseFrontmatter<SkillFrontmatter>(rawContent));\n\t} catch (error) {\n\t\tif (isDeclaredSkill) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\t}\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst description = frontmatter.description;\n\tconst hasDescription = typeof description === \"string\" && description.trim() !== \"\";\n\tif (!isDeclaredSkill && !hasDescription) {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\tconst skillDir = dirname(filePath);\n\tconst parentDirName = basename(skillDir);\n\n\t// Validate description\n\tconst descErrors = validateDescription(description);\n\tfor (const error of descErrors) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Use name from frontmatter, or fall back to parent directory name\n\tconst frontmatterName = typeof frontmatter.name === \"string\" ? frontmatter.name : undefined;\n\tconst name = frontmatterName || parentDirName;\n\n\t// Validate name\n\tconst nameErrors = validateName(name);\n\tfor (const error of nameErrors) {\n\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t}\n\n\t// Still load the skill even with warnings, unless description is missing or empty.\n\tif (!hasDescription) {\n\t\treturn { skill: null, diagnostics };\n\t}\n\n\treturn {\n\t\tskill: {\n\t\t\tname,\n\t\t\tdescription,\n\t\t\tfilePath,\n\t\t\tbaseDir: skillDir,\n\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t},\n\t\tdiagnostics,\n\t};\n}\n\n/**\n * Format skills for inclusion in a system prompt.\n * Uses XML format per Agent Skills standard.\n * See: https://agentskills.io/integrate-skills\n *\n * Skills with disableModelInvocation=true are excluded from the prompt\n * (they can only be invoked explicitly via /skill:name commands).\n */\nexport function formatSkillsForPrompt(skills: Skill[], fileReadTool: \"read\" | \"bash\" | \"indirect\" = \"read\"): string {\n\tconst visibleSkills = skills.filter((s) => !s.disableModelInvocation);\n\n\tif (visibleSkills.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\tfileReadTool === \"read\"\n\t\t\t? \"Use the read tool to load a skill's file when the task matches its description.\"\n\t\t\t: fileReadTool === \"bash\"\n\t\t\t\t? \"Use bash to load a skill's file when the task matches its description.\"\n\t\t\t\t: \"Load a skill's file when the task matches its description.\",\n\t\t\"Resolve relative paths against the skill's directory (parent of SKILL.md). Use absolute paths in tool calls.\",\n\t\t\"\",\n\t\t\"<available_skills>\",\n\t];\n\n\tfor (const skill of visibleSkills) {\n\t\tlines.push(\" <skill>\");\n\t\tlines.push(` <name>${escapeXml(skill.name)}</name>`);\n\t\tlines.push(` <description>${escapeXml(skill.description)}</description>`);\n\t\tlines.push(` <location>${escapeXml(skill.filePath)}</location>`);\n\t\tlines.push(\" </skill>\");\n\t}\n\n\tlines.push(\"</available_skills>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&\")\n\t\t.replace(/</g, \"<\")\n\t\t.replace(/>/g, \">\")\n\t\t.replace(/\"/g, \""\")\n\t\t.replace(/'/g, \"'\");\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map<string, Skill>();\n\tconst candidates: Skill[] = [];\n\tconst realPathSet = new Set<string>();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = getResourcePathKey(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trealPathSet.add(realPath);\n\t\t\tcandidates.push(skill);\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", true));\n\t\taddSkills(loadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", true));\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isPathWithin(userSkillsDir, resolvedPath)) return \"user\";\n\t\t\tif (isPathWithin(projectSkillsDir, resolvedPath)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, true));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], candidates: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tcandidates,\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]}
|
|
@@ -8,4 +8,5 @@ export { assertStorageSchemaVersion } from "./schema.js";
|
|
|
8
8
|
export * from "./selection.js";
|
|
9
9
|
export type { SessionStore } from "./session/types.js";
|
|
10
10
|
export * from "./sqlite-facade.js";
|
|
11
|
+
export { switchToWriteAheadLog } from "./write-ahead-log.js";
|
|
11
12
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACX,cAAc,EACd,cAAc,EACd,SAAS,EACT,eAAe,EACf,eAAe,EACf,wBAAwB,EACxB,WAAW,EACX,iBAAiB,GACjB,MAAM,eAAe,CAAC;AACvB,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC9E,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AACzD,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,cAAc,oBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACX,cAAc,EACd,cAAc,EACd,SAAS,EACT,eAAe,EACf,eAAe,EACf,wBAAwB,EACxB,WAAW,EACX,iBAAiB,GACjB,MAAM,eAAe,CAAC;AACvB,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC9E,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AACzD,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AAUA,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC9E,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AACzD,cAAc,gBAAgB,CAAC;AAE/B,cAAc,oBAAoB,CAAC","sourcesContent":["export type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteRunResult,\n\tSqliteStatement,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nexport * from \"./errors.js\";\nexport { openNodeSqliteDatabase, wrapNodeSqliteDatabase } from \"./node-sqlite.js\";\nexport { renderStorageIdentifiers, validateStoragePrefix } from \"./prefix.js\";\nexport * from \"./provider.js\";\nexport * from \"./run-journal.js\";\nexport { assertStorageSchemaVersion } from \"./schema.js\";\nexport * from \"./selection.js\";\nexport type { SessionStore } from \"./session/types.js\";\nexport * from \"./sqlite-facade.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/storage/index.ts"],"names":[],"mappings":"AAUA,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAC9E,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC;AACzD,cAAc,gBAAgB,CAAC;AAE/B,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteRunResult,\n\tSqliteStatement,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nexport * from \"./errors.js\";\nexport { openNodeSqliteDatabase, wrapNodeSqliteDatabase } from \"./node-sqlite.js\";\nexport { renderStorageIdentifiers, validateStoragePrefix } from \"./prefix.js\";\nexport * from \"./provider.js\";\nexport * from \"./run-journal.js\";\nexport { assertStorageSchemaVersion } from \"./schema.js\";\nexport * from \"./selection.js\";\nexport type { SessionStore } from \"./session/types.js\";\nexport * from \"./sqlite-facade.js\";\nexport { switchToWriteAheadLog } from \"./write-ahead-log.js\";\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EACX,cAAc,EAMd,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EACX,cAAc,EAMd,MAAM,eAAe,CAAC;AAiuBvB,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,MAAM,EACZ,EACC,aAAoB,EACpB,UAA6C,EAC7C,QAAgB,GAChB,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAO,GACzE,OAAO,CAAC,cAAc,CAAC,CAgCzB;AAKD,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,YAAY,GAAG,cAAc,CAY/E"}
|
|
@@ -2,6 +2,7 @@ import { closeSync, mkdirSync, openSync, readdirSync, readFileSync, statSync, un
|
|
|
2
2
|
import { mkdir, realpath } from "node:fs/promises";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { StorageAdapterLoadError, StorageInvalidTextError, StorageRollbackError, StorageTransactionClosedError, StorageUnavailableError, StoreClosedError, } from "./errors.js";
|
|
5
|
+
import { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from "./write-ahead-log.js";
|
|
5
6
|
/** A ticket its owner has not refreshed for this long belongs to a process that died or stopped waiting. */
|
|
6
7
|
const TICKET_STALE_MS = 2_000;
|
|
7
8
|
/** Stale tickets older than this are removed by whichever writer notices them. */
|
|
@@ -278,11 +279,6 @@ const MAX_GROUP_COMMIT_TRANSACTIONS = 128;
|
|
|
278
279
|
* checked between members, so one member's own work, however long, is never split.
|
|
279
280
|
*/
|
|
280
281
|
const GROUP_COMMIT_HOLD_MS = 100;
|
|
281
|
-
/** SQLITE_BUSY, including its extended codes: another connection holds the lock this statement needs. */
|
|
282
|
-
function isSqliteBusy(cause) {
|
|
283
|
-
const code = cause?.errcode;
|
|
284
|
-
return typeof code === "number" && (code & 0xff) === 5;
|
|
285
|
-
}
|
|
286
282
|
/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */
|
|
287
283
|
function sqliteFailureDetail(cause) {
|
|
288
284
|
if (!(cause instanceof Error) || cause.message === "")
|
|
@@ -694,8 +690,12 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
|
|
|
694
690
|
await mkdir(dirname(path), { recursive: true });
|
|
695
691
|
connection = new Database(path, { readOnly });
|
|
696
692
|
connection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);
|
|
697
|
-
if (!readOnly)
|
|
698
|
-
|
|
693
|
+
if (!readOnly) {
|
|
694
|
+
const writable = connection;
|
|
695
|
+
// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.
|
|
696
|
+
await switchToWriteAheadLog((sql) => writable.exec(sql), busyTimeoutMs);
|
|
697
|
+
writable.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
|
|
698
|
+
}
|
|
699
699
|
const location = connection.location();
|
|
700
700
|
const identity = location === null ? connection : await realpath(location);
|
|
701
701
|
return new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs);
|
|
@@ -710,11 +710,16 @@ export async function openNodeSqliteDatabase(path, { busyTimeoutMs = 5000, lockW
|
|
|
710
710
|
throw unavailable(descriptor, cause);
|
|
711
711
|
}
|
|
712
712
|
}
|
|
713
|
+
/** The busy timeout `wrapNodeSqliteDatabase` sets on a caller's connection. */
|
|
714
|
+
const WRAPPED_BUSY_TIMEOUT_MS = 5000;
|
|
713
715
|
export function wrapNodeSqliteDatabase(connection) {
|
|
714
716
|
const descriptor = { adapter: "node-sqlite", location: ":memory:" };
|
|
715
717
|
try {
|
|
716
718
|
descriptor.location = connection.location() || ":memory:";
|
|
717
|
-
connection.exec(
|
|
719
|
+
connection.exec(`PRAGMA busy_timeout=${WRAPPED_BUSY_TIMEOUT_MS}`);
|
|
720
|
+
// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.
|
|
721
|
+
switchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);
|
|
722
|
+
connection.exec("PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON");
|
|
718
723
|
return new NodeSqliteDatabase(connection, descriptor, false);
|
|
719
724
|
}
|
|
720
725
|
catch (cause) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,SAAS,EACT,SAAS,EACT,QAAQ,EACR,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,UAAU,EACV,aAAa,EACb,SAAS,GACT,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,KAAK,EAAE,QAA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IAC9D,MAAM,UAAU,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACpE,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,UAAU,CAAC;QAC1D,UAAU,CAAC,IAAI,CACd,oGAAoG,CACpG,CAAC;QACF,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC","sourcesContent":["import {\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\treadFileSync,\n\tstatSync,\n\tunlinkSync,\n\tutimesSync,\n\twriteFileSync,\n\twriteSync,\n} from \"node:fs\";\nimport { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\n/** A ticket its owner has not refreshed for this long belongs to a process that died or stopped waiting. */\nconst TICKET_STALE_MS = 2_000;\n/** Stale tickets older than this are removed by whichever writer notices them. */\nconst TICKET_REMOVE_AFTER_MS = 10 * TICKET_STALE_MS;\n\nlet ticketSequence = 0;\n\nfunction ticketName(): string {\n\tticketSequence += 1;\n\treturn `${String(Date.now()).padStart(15, \"0\")}-${process.pid}-${ticketSequence}`;\n}\n\n/**\n * First come, first served for SQLite's write lock across processes. SQLite has no queue for `BEGIN IMMEDIATE`: a\n * writer that polls after `SQLITE_BUSY` loses to one that begins the moment the lock is free, and a busy process\n * can take the lock again and again while another waits for its whole deadline (#3978). A writer that has been\n * refused takes a ticket, a file named by the time it started waiting, in a directory next to the database; it then\n * attempts the lock only once no live older ticket is ahead of it, and a writer that arrives while tickets wait\n * queues behind them instead of overtaking. Uncontended writers only list an absent or empty directory.\n */\nclass SqliteWriteQueue {\n\tprivate readonly directory: string;\n\n\tconstructor(databasePath: string) {\n\t\tthis.directory = `${databasePath}-writers`;\n\t}\n\n\t/** Whether another writer's live ticket is waiting, so a new writer must queue behind it. */\n\tothersWaiting(): boolean {\n\t\treturn this.liveTickets().length > 0;\n\t}\n\n\tjoin(): SqliteWriteTicket {\n\t\tmkdirSync(this.directory, { recursive: true });\n\t\tconst name = ticketName();\n\t\tconst path = join(this.directory, name);\n\t\twriteFileSync(path, \"\", { flag: \"wx\" });\n\t\treturn new SqliteWriteTicket(this, name, path);\n\t}\n\n\t/** Live tickets, oldest first; stale ones long abandoned are removed on the way. */\n\tliveTickets(except?: string): string[] {\n\t\tlet names: string[];\n\t\ttry {\n\t\t\tnames = readdirSync(this.directory);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\tconst now = Date.now();\n\t\tconst live: string[] = [];\n\t\tfor (const name of names) {\n\t\t\tif (name === except) continue;\n\t\t\tlet age: number;\n\t\t\ttry {\n\t\t\t\tage = now - statSync(join(this.directory, name)).mtimeMs;\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (age < TICKET_STALE_MS) live.push(name);\n\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(join(this.directory, name));\n\t\t\t\t} catch {\n\t\t\t\t\t// Another writer removed it first.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn live.sort();\n\t}\n}\n\nclass SqliteWriteTicket {\n\tprivate left = false;\n\tprivate readonly queue: SqliteWriteQueue;\n\tprivate readonly name: string;\n\tprivate readonly path: string;\n\n\tconstructor(queue: SqliteWriteQueue, name: string, path: string) {\n\t\tthis.queue = queue;\n\t\tthis.name = name;\n\t\tthis.path = path;\n\t}\n\n\t/** Marks this ticket live and reports whether an older live ticket is still ahead of it. */\n\tbehindOthers(): boolean {\n\t\tif (this.left) return false;\n\t\tconst now = new Date();\n\t\ttry {\n\t\t\tutimesSync(this.path, now, now);\n\t\t} catch {\n\t\t\t// The ticket was removed as stale while this writer stalled: take the place it would have had.\n\t\t\twriteFileSync(this.path, \"\");\n\t\t}\n\t\treturn this.queue.liveTickets(this.name).some((other) => other < this.name);\n\t}\n\n\tleave(): void {\n\t\tif (this.left) return;\n\t\tthis.left = true;\n\t\ttry {\n\t\t\tunlinkSync(this.path);\n\t\t} catch {\n\t\t\t// Already removed.\n\t\t}\n\t}\n}\n\nlet holderSequence = 0;\nconst HOLDER_RECORD = /^held (\\d{15})\\n/;\n\nfunction processAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\n/**\n * Which process holds the write lock, for the error of a writer that gives up waiting for it. Each connection that\n * takes the lock records when it took it in a file of its own next to the database, named by its process, and marks\n * the record free once it lets go; only the holder writes its record, so records never race. Nothing reads them\n * until a writer gives up: the live record taken most recently names the holder. A connection removes the records\n * of exited processes when it creates its own, so the killed ones do not pile up. Recording is a diagnostic: a\n * record that cannot be written is dropped, never a failed transaction.\n */\nclass SqliteHolderRecord {\n\tprivate descriptor?: number;\n\tprivate broken = false;\n\tprivate readonly directory: string;\n\tprivate readonly path: string;\n\n\tconstructor(databasePath: string) {\n\t\tthis.directory = holderDirectory(databasePath);\n\t\tholderSequence += 1;\n\t\tthis.path = join(this.directory, `${process.pid}-${holderSequence}`);\n\t}\n\n\theld(): void {\n\t\tthis.write(`held ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\tfree(): void {\n\t\tif (this.descriptor !== undefined) this.write(`free ${\"0\".repeat(15)}\\n`);\n\t}\n\n\tclose(): void {\n\t\tif (this.descriptor === undefined) return;\n\t\ttry {\n\t\t\tcloseSync(this.descriptor);\n\t\t\tunlinkSync(this.path);\n\t\t} catch {\n\t\t\t// Already gone; a leftover record of an exited process is ignored and removed by whoever reads it.\n\t\t}\n\t\tthis.descriptor = undefined;\n\t}\n\n\t/** Every record has the same length and is written in place, so a reader never sees a shorter, stale tail. */\n\tprivate write(record: string): void {\n\t\tif (this.broken) return;\n\t\ttry {\n\t\t\tif (this.descriptor === undefined) {\n\t\t\t\tmkdirSync(this.directory, { recursive: true });\n\t\t\t\tliveHolderRecords(this.directory);\n\t\t\t\tthis.descriptor = openSync(this.path, \"w\");\n\t\t\t}\n\t\t\twriteSync(this.descriptor, record, 0);\n\t\t} catch {\n\t\t\tthis.broken = true;\n\t\t\tthis.close();\n\t\t}\n\t}\n}\n\nfunction holderDirectory(databasePath: string): string {\n\treturn `${databasePath}-holders`;\n}\n\n/** The records of live processes, as pid and the time each took the lock (undefined when free); others are removed. */\nfunction liveHolderRecords(directory: string): { readonly pid: number; readonly since?: number }[] {\n\tlet names: string[];\n\ttry {\n\t\tnames = readdirSync(directory);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst live: { pid: number; since?: number }[] = [];\n\tfor (const name of names) {\n\t\tconst pid = Number(/^(\\d+)-/.exec(name)?.[1] ?? Number.NaN);\n\t\tif (!Number.isSafeInteger(pid) || pid <= 0) continue;\n\t\tif (!processAlive(pid)) {\n\t\t\ttry {\n\t\t\t\tunlinkSync(join(directory, name));\n\t\t\t} catch {\n\t\t\t\t// Another connection removed it first.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet record: string;\n\t\ttry {\n\t\t\trecord = readFileSync(join(directory, name), \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst since = HOLDER_RECORD.exec(record)?.[1];\n\t\tlive.push({ pid, ...(since === undefined ? {} : { since: Number(since) }) });\n\t}\n\treturn live;\n}\n\n/** The live process whose record says it took the write lock most recently, and for how long it has held it. */\nfunction writeLockHolder(databasePath: string): { readonly pid: number; readonly heldMs: number } | undefined {\n\tlet holder: { pid: number; since: number } | undefined;\n\tfor (const { pid, since } of liveHolderRecords(holderDirectory(databasePath)))\n\t\tif (since !== undefined && (holder === undefined || since > holder.since)) holder = { pid, since };\n\treturn holder === undefined ? undefined : { pid: holder.pid, heldMs: Math.max(0, Date.now() - holder.since) };\n}\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/**\n * Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while the write lock is held and nobody makes\n * progress through it: every commit by another connection restarts the wait, so only a lock held without commits\n * for this long fails the transaction.\n */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\nconst LOCK_RETRY_BASE_DELAY_MS = 5;\nconst LOCK_RETRY_MAX_DELAY_MS = 100;\n/** A writer at the head of the cross-process queue retries at least this often, so the lock it is owed does not sit idle. */\nconst LOCK_RETRY_HEAD_MAX_DELAY_MS = 20;\n/**\n * Retry cap once a writer has waited out the connection's lock wait for a transaction that waits longer: every waiter\n * polling a stalled lock at the usual rate would burn the CPU the stalled holder needs. It stays well under\n * `TICKET_STALE_MS`, so the writer's place in the queue stays live.\n */\nconst LOCK_RETRY_PATIENT_MAX_DELAY_MS = 500;\n/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */\nconst MAX_GROUP_COMMIT_TRANSACTIONS = 128;\n/**\n * Longest a group commit runs its members before it commits them and takes the lock again for the rest: a batch of\n * cheap transactions in a process starved of CPU still lets other processes' writers in between. The bound is\n * checked between members, so one member's own work, however long, is never split.\n */\nconst GROUP_COMMIT_HOLD_MS = 100;\n\ninterface QueuedTransaction {\n\treadonly callback: (transaction: SqliteExecutor) => Promise<unknown>;\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: unknown) => void;\n\treadonly lockWaitMs?: number;\n}\n\ntype TransactionOutcome =\n\t| { readonly ok: true; readonly value: unknown }\n\t| { readonly ok: false; readonly error: unknown };\n\n/** SQLITE_BUSY, including its extended codes: another connection holds the lock this statement needs. */\nfunction isSqliteBusy(cause: unknown): boolean {\n\tconst code = (cause as { errcode?: unknown } | null | undefined)?.errcode;\n\treturn typeof code === \"number\" && (code & 0xff) === 5;\n}\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate openBatch?: QueuedTransaction[];\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\tprivate readonly lockWaitMs: number;\n\t/** Cross-process first-come-first-served order for the write lock; absent for in-memory databases. */\n\tprivate readonly writeQueue?: SqliteWriteQueue;\n\t/** This connection's record of when it holds the write lock, named in the error of a writer that gives up. */\n\tprivate readonly holderRecord?: SqliteHolderRecord;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t\tif (typeof transactionIdentity === \"string\") {\n\t\t\tthis.writeQueue = new SqliteWriteQueue(transactionIdentity);\n\t\t\tthis.holderRecord = new SqliteHolderRecord(transactionIdentity);\n\t\t}\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`\n\t * and the connection's own value is restored before returning or throwing, so single statements outside a\n\t * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs\n\t * on the connection in between.\n\t */\n\tprivate tryBegin(): void {\n\t\tthis.driver(() => {\n\t\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\t\tlet began = false;\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tbegan = true;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t\t} catch (restoreFailure) {\n\t\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\t\tthrow restoreFailure;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Changes whenever another connection commits to the database: the lock is being used, not held idle. */\n\tprivate dataVersion(): number {\n\t\treturn this.driver(() => Number(this.connection.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0));\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried after a timer. A refused writer queues with writers in other processes\n\t * and attempts the lock only when no earlier writer is still waiting, so none starves (#3978). The wait ends only\n\t * when no other connection has committed for `lockWaitMs`, whether this writer is still queued or already trying\n\t * the lock: a queued writer counts only real commits as progress, not older tickets ahead of it. A transaction that\n\t * waits longer than the connection's lock wait retries less often past it. The error of a writer that gives up\n\t * names the process holding the lock. Every other failure, including a writers' queue that cannot be used,\n\t * rejects at once with its cause.\n\t */\n\tprivate async begin(lockWaitMs = this.lockWaitMs): Promise<void> {\n\t\tlet ticket: SqliteWriteTicket | undefined;\n\t\ttry {\n\t\t\t// Writers already waiting in other processes go first.\n\t\t\tif (this.queueOp(() => this.writeQueue?.othersWaiting())) ticket = this.queueOp(() => this.writeQueue?.join());\n\t\t\t// Read only once this writer waits, so an uncontended transaction pays nothing for it.\n\t\t\tlet version = ticket === undefined ? undefined : this.dataVersion();\n\t\t\tlet stalledSince = Date.now();\n\t\t\tlet backoff = LOCK_RETRY_BASE_DELAY_MS;\n\t\t\tlet lastCause: unknown;\n\t\t\tfor (;;) {\n\t\t\t\tconst behind = ticket !== undefined && this.queueOp(() => ticket!.behindOthers());\n\t\t\t\tif (!behind) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.tryBegin();\n\t\t\t\t\t\tthis.holderRecord?.held();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\t\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\t\t\t\tlastCause = cause;\n\t\t\t\t\t\tticket ??= this.queueOp(() => this.writeQueue?.join());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Only another connection's commit is progress; a queued writer measures its stall the same way.\n\t\t\t\tconst current = this.dataVersion();\n\t\t\t\tif (version === undefined) version = current;\n\t\t\t\telse if (current !== version) {\n\t\t\t\t\tversion = current;\n\t\t\t\t\tstalledSince = Date.now();\n\t\t\t\t}\n\t\t\t\tconst stalledMs = Date.now() - stalledSince;\n\t\t\t\tif (stalledMs >= lockWaitMs) {\n\t\t\t\t\tconst holder =\n\t\t\t\t\t\ttypeof this.transactionIdentity === \"string\" ? writeLockHolder(this.transactionIdentity) : undefined;\n\t\t\t\t\tconst heldBy =\n\t\t\t\t\t\tholder === undefined ? \"\" : `by process ${holder.pid} (which took it ${holder.heldMs} ms ago) `;\n\t\t\t\t\tthrow unavailable(\n\t\t\t\t\t\tthis.descriptor,\n\t\t\t\t\t\tlastCause,\n\t\t\t\t\t\t`${sqliteFailureDetail(lastCause) ?? \"database is locked\"}; gave up after ${stalledMs} ms waiting for the write lock${behind ? \" in the writers' queue\" : \"\"}, held all that time ${heldBy}with no other connection committing`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst patient = stalledMs >= this.lockWaitMs;\n\t\t\t\tconst cap = patient\n\t\t\t\t\t? LOCK_RETRY_PATIENT_MAX_DELAY_MS\n\t\t\t\t\t: ticket !== undefined && !behind\n\t\t\t\t\t\t? LOCK_RETRY_HEAD_MAX_DELAY_MS\n\t\t\t\t\t\t: LOCK_RETRY_MAX_DELAY_MS;\n\t\t\t\tconst delay = Math.min(backoff, cap);\n\t\t\t\tbackoff = Math.min(patient ? LOCK_RETRY_PATIENT_MAX_DELAY_MS : LOCK_RETRY_MAX_DELAY_MS, backoff * 2);\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay * (0.5 + Math.random() / 2)));\n\t\t\t}\n\t\t} finally {\n\t\t\tticket?.leave();\n\t\t}\n\t}\n\n\t/** Runs a writers'-queue file operation; a failure (an unwritable queue directory, say) is a storage failure. */\n\tprivate queueOp<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(\n\t\t\t\tthis.descriptor,\n\t\t\t\tcause,\n\t\t\t\t`the writers' queue next to the database is unusable: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** A statement queued after open transactions runs after them, so later transactions start a new batch. */\n\tprivate enqueueStatement<T>(operation: () => Promise<T>): Promise<T> {\n\t\tthis.openBatch = undefined;\n\t\treturn this.enqueue(operation);\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueueStatement(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\t/**\n\t * Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,\n\t * each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only\n\t * its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the\n\t * same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch. A batch\n\t * waits for the lock as long as the most patient of its transactions.\n\t */\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst queued: QueuedTransaction = {\n\t\t\t\tcallback,\n\t\t\t\tresolve: resolve as (value: unknown) => void,\n\t\t\t\treject,\n\t\t\t\tlockWaitMs: options?.lockWaitMs,\n\t\t\t};\n\t\t\tif (this.openBatch !== undefined && this.openBatch.length < MAX_GROUP_COMMIT_TRANSACTIONS) {\n\t\t\t\tthis.openBatch.push(queued);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.startBatch([queued]);\n\t\t});\n\t}\n\n\tprivate startBatch(batch: QueuedTransaction[]): void {\n\t\tthis.openBatch = batch;\n\t\tvoid this.enqueue(() => this.commitBatch(batch));\n\t}\n\n\tprivate commitBatch(batch: QueuedTransaction[]): Promise<void> {\n\t\tif (this.openBatch === batch) this.openBatch = undefined;\n\t\treturn gateTransaction(this.transactionIdentity, async () => {\n\t\t\ttry {\n\t\t\t\tawait (batch.length === 1 ? this.commitAlone(batch[0]!) : this.commitMembers(batch));\n\t\t\t} finally {\n\t\t\t\tthis.holderRecord?.free();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate lockWait(batch: readonly QueuedTransaction[]): number {\n\t\treturn Math.max(...batch.map((queued) => queued.lockWaitMs ?? this.lockWaitMs));\n\t}\n\n\t/** A transaction with nobody queued behind it commits on its own, without savepoints. */\n\tprivate async commitAlone(queued: QueuedTransaction): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait([queued]));\n\t\t} catch (cause) {\n\t\t\tqueued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tlet active = true;\n\t\ttry {\n\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\tactive = false;\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\tqueued.resolve(value);\n\t\t} catch (cause) {\n\t\t\tactive = false;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t} catch (rollbackCause) {\n\t\t\t\tqueued.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tqueued.reject(cause);\n\t\t}\n\t}\n\n\t/**\n\t * Runs the batch's members in one transaction, for at most `GROUP_COMMIT_HOLD_MS`: members left when it runs out\n\t * wait for the lock again, in a transaction of their own, still ahead of anything queued after them.\n\t */\n\tprivate async commitMembers(batch: QueuedTransaction[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait(batch));\n\t\t} catch (cause) {\n\t\t\tfor (const queued of batch) queued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tconst began = performance.now();\n\t\tconst outcomes: TransactionOutcome[] = [];\n\t\tfor (const queued of batch) {\n\t\t\tif (outcomes.length > 0 && performance.now() - began >= GROUP_COMMIT_HOLD_MS) break;\n\t\t\tconst savepoint = `atomic_group_${outcomes.length}`;\n\t\t\tlet active = true;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(`SAVEPOINT ${savepoint}`);\n\t\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\t\tactive = false;\n\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\toutcomes.push({ ok: true, value });\n\t\t\t} catch (cause) {\n\t\t\t\tactive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.executor.exec(`ROLLBACK TO ${savepoint}`);\n\t\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tawait this.abandonMembers(batch, outcomes, cause, rollbackCause);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.push({ ok: false, error: cause });\n\t\t\t}\n\t\t}\n\t\tconst ran = batch.slice(0, outcomes.length);\n\t\tconst remaining = batch.slice(outcomes.length);\n\t\tlet commitCause: unknown;\n\t\tlet committed = true;\n\t\ttry {\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t} catch (cause) {\n\t\t\tcommitted = false;\n\t\t\tcommitCause = cause;\n\t\t\tawait this.rollbackQuietly();\n\t\t}\n\t\t// Let go of the record too: members left over wait for the lock again, and another process may take it first.\n\t\tthis.holderRecord?.free();\n\t\tran.forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tif (!committed) queued.reject(outcome.ok ? commitCause : outcome.error);\n\t\t\telse if (outcome.ok) queued.resolve(outcome.value);\n\t\t\telse queued.reject(outcome.error);\n\t\t});\n\t\tif (remaining.length > 0) await this.commitMembers(remaining);\n\t}\n\n\t/**\n\t * A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their\n\t * uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a\n\t * fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.\n\t */\n\tprivate async abandonMembers(\n\t\tbatch: QueuedTransaction[],\n\t\toutcomes: TransactionOutcome[],\n\t\tcause: unknown,\n\t\trollbackCause: unknown,\n\t): Promise<void> {\n\t\tawait this.rollbackQuietly();\n\t\tconst failed = outcomes.length;\n\t\tbatch.slice(0, failed).forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tqueued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);\n\t\t});\n\t\tbatch[failed]!.reject(\n\t\t\tnew StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause),\n\t\t);\n\t\tconst remaining = batch.slice(failed + 1);\n\t\tif (remaining.length > 0) await this.commitMembers(remaining);\n\t}\n\n\tprivate async rollbackQuietly(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// SQLite already rolled the transaction back; there is nothing left to undo.\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tthis.holderRecord?.close();\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t}: { busyTimeoutMs?: number; lockWaitMs?: number; readOnly?: boolean } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path, { readOnly });\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) connection.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(\n\t\t\t\"PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\",\n\t\t);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow unavailable(descriptor, cause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3E,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;IACnF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC;YACJ,UAAU,EAAE,KAAK,EAAE,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACR,sDAAsD;QACvD,CAAC;QACD,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC;AAED,+EAA+E;AAC/E,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAErC,MAAM,UAAU,sBAAsB,CAAC,UAAwB;IAC9D,MAAM,UAAU,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACpE,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,UAAU,CAAC;QAC1D,UAAU,CAAC,IAAI,CAAC,uBAAuB,uBAAuB,EAAE,CAAC,CAAC;QAClE,sGAAsG;QACtG,yBAAyB,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,uBAAuB,CAAC,CAAC;QAClF,UAAU,CAAC,IAAI,CAAC,iDAAiD,CAAC,CAAC;QACnE,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,WAAW,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;AACF,CAAC","sourcesContent":["import {\n\tcloseSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\treadFileSync,\n\tstatSync,\n\tunlinkSync,\n\tutimesSync,\n\twriteFileSync,\n\twriteSync,\n} from \"node:fs\";\nimport { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type {\n\tSqliteDatabase,\n\tSqliteExecutor,\n\tSqliteRow,\n\tSqliteTransactionOptions,\n\tSqliteValue,\n\tStorageDescriptor,\n} from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\nimport { isSqliteBusy, switchToWriteAheadLog, switchToWriteAheadLogSync } from \"./write-ahead-log.js\";\n\n/** A ticket its owner has not refreshed for this long belongs to a process that died or stopped waiting. */\nconst TICKET_STALE_MS = 2_000;\n/** Stale tickets older than this are removed by whichever writer notices them. */\nconst TICKET_REMOVE_AFTER_MS = 10 * TICKET_STALE_MS;\n\nlet ticketSequence = 0;\n\nfunction ticketName(): string {\n\tticketSequence += 1;\n\treturn `${String(Date.now()).padStart(15, \"0\")}-${process.pid}-${ticketSequence}`;\n}\n\n/**\n * First come, first served for SQLite's write lock across processes. SQLite has no queue for `BEGIN IMMEDIATE`: a\n * writer that polls after `SQLITE_BUSY` loses to one that begins the moment the lock is free, and a busy process\n * can take the lock again and again while another waits for its whole deadline (#3978). A writer that has been\n * refused takes a ticket, a file named by the time it started waiting, in a directory next to the database; it then\n * attempts the lock only once no live older ticket is ahead of it, and a writer that arrives while tickets wait\n * queues behind them instead of overtaking. Uncontended writers only list an absent or empty directory.\n */\nclass SqliteWriteQueue {\n\tprivate readonly directory: string;\n\n\tconstructor(databasePath: string) {\n\t\tthis.directory = `${databasePath}-writers`;\n\t}\n\n\t/** Whether another writer's live ticket is waiting, so a new writer must queue behind it. */\n\tothersWaiting(): boolean {\n\t\treturn this.liveTickets().length > 0;\n\t}\n\n\tjoin(): SqliteWriteTicket {\n\t\tmkdirSync(this.directory, { recursive: true });\n\t\tconst name = ticketName();\n\t\tconst path = join(this.directory, name);\n\t\twriteFileSync(path, \"\", { flag: \"wx\" });\n\t\treturn new SqliteWriteTicket(this, name, path);\n\t}\n\n\t/** Live tickets, oldest first; stale ones long abandoned are removed on the way. */\n\tliveTickets(except?: string): string[] {\n\t\tlet names: string[];\n\t\ttry {\n\t\t\tnames = readdirSync(this.directory);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\tconst now = Date.now();\n\t\tconst live: string[] = [];\n\t\tfor (const name of names) {\n\t\t\tif (name === except) continue;\n\t\t\tlet age: number;\n\t\t\ttry {\n\t\t\t\tage = now - statSync(join(this.directory, name)).mtimeMs;\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (age < TICKET_STALE_MS) live.push(name);\n\t\t\telse if (age > TICKET_REMOVE_AFTER_MS) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(join(this.directory, name));\n\t\t\t\t} catch {\n\t\t\t\t\t// Another writer removed it first.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn live.sort();\n\t}\n}\n\nclass SqliteWriteTicket {\n\tprivate left = false;\n\tprivate readonly queue: SqliteWriteQueue;\n\tprivate readonly name: string;\n\tprivate readonly path: string;\n\n\tconstructor(queue: SqliteWriteQueue, name: string, path: string) {\n\t\tthis.queue = queue;\n\t\tthis.name = name;\n\t\tthis.path = path;\n\t}\n\n\t/** Marks this ticket live and reports whether an older live ticket is still ahead of it. */\n\tbehindOthers(): boolean {\n\t\tif (this.left) return false;\n\t\tconst now = new Date();\n\t\ttry {\n\t\t\tutimesSync(this.path, now, now);\n\t\t} catch {\n\t\t\t// The ticket was removed as stale while this writer stalled: take the place it would have had.\n\t\t\twriteFileSync(this.path, \"\");\n\t\t}\n\t\treturn this.queue.liveTickets(this.name).some((other) => other < this.name);\n\t}\n\n\tleave(): void {\n\t\tif (this.left) return;\n\t\tthis.left = true;\n\t\ttry {\n\t\t\tunlinkSync(this.path);\n\t\t} catch {\n\t\t\t// Already removed.\n\t\t}\n\t}\n}\n\nlet holderSequence = 0;\nconst HOLDER_RECORD = /^held (\\d{15})\\n/;\n\nfunction processAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\n/**\n * Which process holds the write lock, for the error of a writer that gives up waiting for it. Each connection that\n * takes the lock records when it took it in a file of its own next to the database, named by its process, and marks\n * the record free once it lets go; only the holder writes its record, so records never race. Nothing reads them\n * until a writer gives up: the live record taken most recently names the holder. A connection removes the records\n * of exited processes when it creates its own, so the killed ones do not pile up. Recording is a diagnostic: a\n * record that cannot be written is dropped, never a failed transaction.\n */\nclass SqliteHolderRecord {\n\tprivate descriptor?: number;\n\tprivate broken = false;\n\tprivate readonly directory: string;\n\tprivate readonly path: string;\n\n\tconstructor(databasePath: string) {\n\t\tthis.directory = holderDirectory(databasePath);\n\t\tholderSequence += 1;\n\t\tthis.path = join(this.directory, `${process.pid}-${holderSequence}`);\n\t}\n\n\theld(): void {\n\t\tthis.write(`held ${String(Date.now()).padStart(15, \"0\")}\\n`);\n\t}\n\n\tfree(): void {\n\t\tif (this.descriptor !== undefined) this.write(`free ${\"0\".repeat(15)}\\n`);\n\t}\n\n\tclose(): void {\n\t\tif (this.descriptor === undefined) return;\n\t\ttry {\n\t\t\tcloseSync(this.descriptor);\n\t\t\tunlinkSync(this.path);\n\t\t} catch {\n\t\t\t// Already gone; a leftover record of an exited process is ignored and removed by whoever reads it.\n\t\t}\n\t\tthis.descriptor = undefined;\n\t}\n\n\t/** Every record has the same length and is written in place, so a reader never sees a shorter, stale tail. */\n\tprivate write(record: string): void {\n\t\tif (this.broken) return;\n\t\ttry {\n\t\t\tif (this.descriptor === undefined) {\n\t\t\t\tmkdirSync(this.directory, { recursive: true });\n\t\t\t\tliveHolderRecords(this.directory);\n\t\t\t\tthis.descriptor = openSync(this.path, \"w\");\n\t\t\t}\n\t\t\twriteSync(this.descriptor, record, 0);\n\t\t} catch {\n\t\t\tthis.broken = true;\n\t\t\tthis.close();\n\t\t}\n\t}\n}\n\nfunction holderDirectory(databasePath: string): string {\n\treturn `${databasePath}-holders`;\n}\n\n/** The records of live processes, as pid and the time each took the lock (undefined when free); others are removed. */\nfunction liveHolderRecords(directory: string): { readonly pid: number; readonly since?: number }[] {\n\tlet names: string[];\n\ttry {\n\t\tnames = readdirSync(directory);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst live: { pid: number; since?: number }[] = [];\n\tfor (const name of names) {\n\t\tconst pid = Number(/^(\\d+)-/.exec(name)?.[1] ?? Number.NaN);\n\t\tif (!Number.isSafeInteger(pid) || pid <= 0) continue;\n\t\tif (!processAlive(pid)) {\n\t\t\ttry {\n\t\t\t\tunlinkSync(join(directory, name));\n\t\t\t} catch {\n\t\t\t\t// Another connection removed it first.\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet record: string;\n\t\ttry {\n\t\t\trecord = readFileSync(join(directory, name), \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tconst since = HOLDER_RECORD.exec(record)?.[1];\n\t\tlive.push({ pid, ...(since === undefined ? {} : { since: Number(since) }) });\n\t}\n\treturn live;\n}\n\n/** The live process whose record says it took the write lock most recently, and for how long it has held it. */\nfunction writeLockHolder(databasePath: string): { readonly pid: number; readonly heldMs: number } | undefined {\n\tlet holder: { pid: number; since: number } | undefined;\n\tfor (const { pid, since } of liveHolderRecords(holderDirectory(databasePath)))\n\t\tif (since !== undefined && (holder === undefined || since > holder.since)) holder = { pid, since };\n\treturn holder === undefined ? undefined : { pid: holder.pid, heldMs: Math.max(0, Date.now() - holder.since) };\n}\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\n/**\n * Default for how long a transaction keeps retrying `BEGIN IMMEDIATE` while the write lock is held and nobody makes\n * progress through it: every commit by another connection restarts the wait, so only a lock held without commits\n * for this long fails the transaction.\n */\nconst DEFAULT_NODE_SQLITE_LOCK_WAIT_MS = 30_000;\nconst LOCK_RETRY_BASE_DELAY_MS = 5;\nconst LOCK_RETRY_MAX_DELAY_MS = 100;\n/** A writer at the head of the cross-process queue retries at least this often, so the lock it is owed does not sit idle. */\nconst LOCK_RETRY_HEAD_MAX_DELAY_MS = 20;\n/**\n * Retry cap once a writer has waited out the connection's lock wait for a transaction that waits longer: every waiter\n * polling a stalled lock at the usual rate would burn the CPU the stalled holder needs. It stays well under\n * `TICKET_STALE_MS`, so the writer's place in the queue stays live.\n */\nconst LOCK_RETRY_PATIENT_MAX_DELAY_MS = 500;\n/** Most transactions one group commit carries, so a batch cannot keep the write lock from other processes for long. */\nconst MAX_GROUP_COMMIT_TRANSACTIONS = 128;\n/**\n * Longest a group commit runs its members before it commits them and takes the lock again for the rest: a batch of\n * cheap transactions in a process starved of CPU still lets other processes' writers in between. The bound is\n * checked between members, so one member's own work, however long, is never split.\n */\nconst GROUP_COMMIT_HOLD_MS = 100;\n\ninterface QueuedTransaction {\n\treadonly callback: (transaction: SqliteExecutor) => Promise<unknown>;\n\treadonly resolve: (value: unknown) => void;\n\treadonly reject: (error: unknown) => void;\n\treadonly lockWaitMs?: number;\n}\n\ntype TransactionOutcome =\n\t| { readonly ok: true; readonly value: unknown }\n\t| { readonly ok: false; readonly error: unknown };\n\n/** The driver's own reason, kept in the error message so it survives relays that forward only `message`. */\nfunction sqliteFailureDetail(cause: unknown): string | undefined {\n\tif (!(cause instanceof Error) || cause.message === \"\") return undefined;\n\tconst code = (cause as { errcode?: unknown }).errcode;\n\treturn typeof code === \"number\" ? `${cause.message} (SQLite code ${code})` : cause.message;\n}\n\nfunction unavailable(descriptor: StorageDescriptor, cause: unknown, detail = sqliteFailureDetail(cause)) {\n\treturn new StorageUnavailableError(descriptor, cause as StorageFailureCause, detail);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate openBatch?: QueuedTransaction[];\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\tprivate readonly lockWaitMs: number;\n\t/** Cross-process first-come-first-served order for the write lock; absent for in-memory databases. */\n\tprivate readonly writeQueue?: SqliteWriteQueue;\n\t/** This connection's record of when it holds the write lock, named in the error of a writer that gives up. */\n\tprivate readonly holderRecord?: SqliteHolderRecord;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t) {\n\t\tthis.lockWaitMs = lockWaitMs;\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t\tif (typeof transactionIdentity === \"string\") {\n\t\t\tthis.writeQueue = new SqliteWriteQueue(transactionIdentity);\n\t\t\tthis.holderRecord = new SqliteHolderRecord(transactionIdentity);\n\t\t}\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(this.descriptor, cause);\n\t\t}\n\t}\n\n\t/**\n\t * One non-blocking `BEGIN IMMEDIATE`. node:sqlite runs `busy_timeout` synchronously, so a lock held by another\n\t * process would freeze this process's event loop for the whole timeout. The attempt runs with `busy_timeout=0`\n\t * and the connection's own value is restored before returning or throwing, so single statements outside a\n\t * transaction keep it. Callers reach this only through `enqueue` and the transaction gate, so nothing else runs\n\t * on the connection in between.\n\t */\n\tprivate tryBegin(): void {\n\t\tthis.driver(() => {\n\t\t\tconst configured = Number(this.connection.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\t\tthis.connection.exec(\"PRAGMA busy_timeout=0\");\n\t\t\tlet began = false;\n\t\t\ttry {\n\t\t\t\tthis.connection.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tbegan = true;\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tthis.connection.exec(`PRAGMA busy_timeout=${configured}`);\n\t\t\t\t} catch (restoreFailure) {\n\t\t\t\t\t// Never hand back a transaction on a connection whose lock wait is no longer the configured one.\n\t\t\t\t\tif (began) this.connection.exec(\"ROLLBACK\");\n\t\t\t\t\t// biome-ignore lint/correctness/noUnsafeFinally: a failed restore must replace the attempt's outcome.\n\t\t\t\t\tthrow restoreFailure;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Changes whenever another connection commits to the database: the lock is being used, not held idle. */\n\tprivate dataVersion(): number {\n\t\treturn this.driver(() => Number(this.connection.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0));\n\t}\n\n\t/**\n\t * Takes the write lock without blocking the event loop. Nothing has run yet when `BEGIN IMMEDIATE` reports\n\t * SQLITE_BUSY, so the attempt is retried after a timer. A refused writer queues with writers in other processes\n\t * and attempts the lock only when no earlier writer is still waiting, so none starves (#3978). The wait ends only\n\t * when no other connection has committed for `lockWaitMs`, whether this writer is still queued or already trying\n\t * the lock: a queued writer counts only real commits as progress, not older tickets ahead of it. A transaction that\n\t * waits longer than the connection's lock wait retries less often past it. The error of a writer that gives up\n\t * names the process holding the lock. Every other failure, including a writers' queue that cannot be used,\n\t * rejects at once with its cause.\n\t */\n\tprivate async begin(lockWaitMs = this.lockWaitMs): Promise<void> {\n\t\tlet ticket: SqliteWriteTicket | undefined;\n\t\ttry {\n\t\t\t// Writers already waiting in other processes go first.\n\t\t\tif (this.queueOp(() => this.writeQueue?.othersWaiting())) ticket = this.queueOp(() => this.writeQueue?.join());\n\t\t\t// Read only once this writer waits, so an uncontended transaction pays nothing for it.\n\t\t\tlet version = ticket === undefined ? undefined : this.dataVersion();\n\t\t\tlet stalledSince = Date.now();\n\t\t\tlet backoff = LOCK_RETRY_BASE_DELAY_MS;\n\t\t\tlet lastCause: unknown;\n\t\t\tfor (;;) {\n\t\t\t\tconst behind = ticket !== undefined && this.queueOp(() => ticket!.behindOthers());\n\t\t\t\tif (!behind) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.tryBegin();\n\t\t\t\t\t\tthis.holderRecord?.held();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst cause = error instanceof StorageUnavailableError ? error.cause : undefined;\n\t\t\t\t\t\tif (!isSqliteBusy(cause)) throw error;\n\t\t\t\t\t\tlastCause = cause;\n\t\t\t\t\t\tticket ??= this.queueOp(() => this.writeQueue?.join());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Only another connection's commit is progress; a queued writer measures its stall the same way.\n\t\t\t\tconst current = this.dataVersion();\n\t\t\t\tif (version === undefined) version = current;\n\t\t\t\telse if (current !== version) {\n\t\t\t\t\tversion = current;\n\t\t\t\t\tstalledSince = Date.now();\n\t\t\t\t}\n\t\t\t\tconst stalledMs = Date.now() - stalledSince;\n\t\t\t\tif (stalledMs >= lockWaitMs) {\n\t\t\t\t\tconst holder =\n\t\t\t\t\t\ttypeof this.transactionIdentity === \"string\" ? writeLockHolder(this.transactionIdentity) : undefined;\n\t\t\t\t\tconst heldBy =\n\t\t\t\t\t\tholder === undefined ? \"\" : `by process ${holder.pid} (which took it ${holder.heldMs} ms ago) `;\n\t\t\t\t\tthrow unavailable(\n\t\t\t\t\t\tthis.descriptor,\n\t\t\t\t\t\tlastCause,\n\t\t\t\t\t\t`${sqliteFailureDetail(lastCause) ?? \"database is locked\"}; gave up after ${stalledMs} ms waiting for the write lock${behind ? \" in the writers' queue\" : \"\"}, held all that time ${heldBy}with no other connection committing`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst patient = stalledMs >= this.lockWaitMs;\n\t\t\t\tconst cap = patient\n\t\t\t\t\t? LOCK_RETRY_PATIENT_MAX_DELAY_MS\n\t\t\t\t\t: ticket !== undefined && !behind\n\t\t\t\t\t\t? LOCK_RETRY_HEAD_MAX_DELAY_MS\n\t\t\t\t\t\t: LOCK_RETRY_MAX_DELAY_MS;\n\t\t\t\tconst delay = Math.min(backoff, cap);\n\t\t\t\tbackoff = Math.min(patient ? LOCK_RETRY_PATIENT_MAX_DELAY_MS : LOCK_RETRY_MAX_DELAY_MS, backoff * 2);\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay * (0.5 + Math.random() / 2)));\n\t\t\t}\n\t\t} finally {\n\t\t\tticket?.leave();\n\t\t}\n\t}\n\n\t/** Runs a writers'-queue file operation; a failure (an unwritable queue directory, say) is a storage failure. */\n\tprivate queueOp<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow unavailable(\n\t\t\t\tthis.descriptor,\n\t\t\t\tcause,\n\t\t\t\t`the writers' queue next to the database is unusable: ${cause instanceof Error ? cause.message : String(cause)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\t/** A statement queued after open transactions runs after them, so later transactions start a new batch. */\n\tprivate enqueueStatement<T>(operation: () => Promise<T>): Promise<T> {\n\t\tthis.openBatch = undefined;\n\t\treturn this.enqueue(operation);\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueueStatement(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueueStatement(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\t/**\n\t * Group commit: transactions queued while earlier work holds the connection join one `BEGIN IMMEDIATE … COMMIT`,\n\t * each inside its own savepoint and in the order they were requested. A transaction that throws rolls back only\n\t * its savepoint and rejects only its caller; every caller settles after the shared commit, so durability is the\n\t * same as a transaction of its own. Under load one lock acquisition and one sync serve the whole batch. A batch\n\t * waits for the lock as long as the most patient of its transactions.\n\t */\n\ttransaction<T>(\n\t\tcallback: (transaction: SqliteExecutor) => Promise<T>,\n\t\toptions?: SqliteTransactionOptions,\n\t): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tconst queued: QueuedTransaction = {\n\t\t\t\tcallback,\n\t\t\t\tresolve: resolve as (value: unknown) => void,\n\t\t\t\treject,\n\t\t\t\tlockWaitMs: options?.lockWaitMs,\n\t\t\t};\n\t\t\tif (this.openBatch !== undefined && this.openBatch.length < MAX_GROUP_COMMIT_TRANSACTIONS) {\n\t\t\t\tthis.openBatch.push(queued);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.startBatch([queued]);\n\t\t});\n\t}\n\n\tprivate startBatch(batch: QueuedTransaction[]): void {\n\t\tthis.openBatch = batch;\n\t\tvoid this.enqueue(() => this.commitBatch(batch));\n\t}\n\n\tprivate commitBatch(batch: QueuedTransaction[]): Promise<void> {\n\t\tif (this.openBatch === batch) this.openBatch = undefined;\n\t\treturn gateTransaction(this.transactionIdentity, async () => {\n\t\t\ttry {\n\t\t\t\tawait (batch.length === 1 ? this.commitAlone(batch[0]!) : this.commitMembers(batch));\n\t\t\t} finally {\n\t\t\t\tthis.holderRecord?.free();\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate lockWait(batch: readonly QueuedTransaction[]): number {\n\t\treturn Math.max(...batch.map((queued) => queued.lockWaitMs ?? this.lockWaitMs));\n\t}\n\n\t/** A transaction with nobody queued behind it commits on its own, without savepoints. */\n\tprivate async commitAlone(queued: QueuedTransaction): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait([queued]));\n\t\t} catch (cause) {\n\t\t\tqueued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tlet active = true;\n\t\ttry {\n\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\tactive = false;\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\tqueued.resolve(value);\n\t\t} catch (cause) {\n\t\t\tactive = false;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t} catch (rollbackCause) {\n\t\t\t\tqueued.reject(new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tqueued.reject(cause);\n\t\t}\n\t}\n\n\t/**\n\t * Runs the batch's members in one transaction, for at most `GROUP_COMMIT_HOLD_MS`: members left when it runs out\n\t * wait for the lock again, in a transaction of their own, still ahead of anything queued after them.\n\t */\n\tprivate async commitMembers(batch: QueuedTransaction[]): Promise<void> {\n\t\ttry {\n\t\t\tawait this.begin(this.lockWait(batch));\n\t\t} catch (cause) {\n\t\t\tfor (const queued of batch) queued.reject(cause);\n\t\t\treturn;\n\t\t}\n\t\tconst began = performance.now();\n\t\tconst outcomes: TransactionOutcome[] = [];\n\t\tfor (const queued of batch) {\n\t\t\tif (outcomes.length > 0 && performance.now() - began >= GROUP_COMMIT_HOLD_MS) break;\n\t\t\tconst savepoint = `atomic_group_${outcomes.length}`;\n\t\t\tlet active = true;\n\t\t\ttry {\n\t\t\t\tawait this.executor.exec(`SAVEPOINT ${savepoint}`);\n\t\t\t\tconst value = await queued.callback(this.createExecutor(() => active));\n\t\t\t\tactive = false;\n\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\toutcomes.push({ ok: true, value });\n\t\t\t} catch (cause) {\n\t\t\t\tactive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.executor.exec(`ROLLBACK TO ${savepoint}`);\n\t\t\t\t\tawait this.executor.exec(`RELEASE ${savepoint}`);\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tawait this.abandonMembers(batch, outcomes, cause, rollbackCause);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\toutcomes.push({ ok: false, error: cause });\n\t\t\t}\n\t\t}\n\t\tconst ran = batch.slice(0, outcomes.length);\n\t\tconst remaining = batch.slice(outcomes.length);\n\t\tlet commitCause: unknown;\n\t\tlet committed = true;\n\t\ttry {\n\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t} catch (cause) {\n\t\t\tcommitted = false;\n\t\t\tcommitCause = cause;\n\t\t\tawait this.rollbackQuietly();\n\t\t}\n\t\t// Let go of the record too: members left over wait for the lock again, and another process may take it first.\n\t\tthis.holderRecord?.free();\n\t\tran.forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tif (!committed) queued.reject(outcome.ok ? commitCause : outcome.error);\n\t\t\telse if (outcome.ok) queued.resolve(outcome.value);\n\t\t\telse queued.reject(outcome.error);\n\t\t});\n\t\tif (remaining.length > 0) await this.commitMembers(remaining);\n\t}\n\n\t/**\n\t * A savepoint that cannot be rolled back leaves the whole transaction unusable: earlier members lose their\n\t * uncommitted writes and fail, the failing member reports both causes, and members that have not run yet get a\n\t * fresh transaction right away, still ahead of anything queued after them, because nothing of theirs has happened.\n\t */\n\tprivate async abandonMembers(\n\t\tbatch: QueuedTransaction[],\n\t\toutcomes: TransactionOutcome[],\n\t\tcause: unknown,\n\t\trollbackCause: unknown,\n\t): Promise<void> {\n\t\tawait this.rollbackQuietly();\n\t\tconst failed = outcomes.length;\n\t\tbatch.slice(0, failed).forEach((queued, index) => {\n\t\t\tconst outcome = outcomes[index]!;\n\t\t\tqueued.reject(outcome.ok ? unavailable(this.descriptor, rollbackCause) : outcome.error);\n\t\t});\n\t\tbatch[failed]!.reject(\n\t\t\tnew StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause),\n\t\t);\n\t\tconst remaining = batch.slice(failed + 1);\n\t\tif (remaining.length > 0) await this.commitMembers(remaining);\n\t}\n\n\tprivate async rollbackQuietly(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t} catch {\n\t\t\t// SQLite already rolled the transaction back; there is nothing left to undo.\n\t\t}\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tthis.holderRecord?.close();\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{\n\t\tbusyTimeoutMs = 5000,\n\t\tlockWaitMs = DEFAULT_NODE_SQLITE_LOCK_WAIT_MS,\n\t\treadOnly = false,\n\t}: { busyTimeoutMs?: number; lockWaitMs?: number; readOnly?: boolean } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path, { readOnly });\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) {\n\t\t\tconst writable = connection;\n\t\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\t\tawait switchToWriteAheadLog((sql) => writable.exec(sql), busyTimeoutMs);\n\t\t\twritable.exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\t}\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity, lockWaitMs);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n\n/** The busy timeout `wrapNodeSqliteDatabase` sets on a caller's connection. */\nconst WRAPPED_BUSY_TIMEOUT_MS = 5000;\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(`PRAGMA busy_timeout=${WRAPPED_BUSY_TIMEOUT_MS}`);\n\t\t// SQLite does not wait for another process's lock while it changes the mode; the switch waits itself.\n\t\tswitchToWriteAheadLogSync((sql) => connection.exec(sql), WRAPPED_BUSY_TIMEOUT_MS);\n\t\tconnection.exec(\"PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow unavailable(descriptor, cause);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
type Awaitable<T> = T | Promise<T>;
|
|
2
|
+
/**
|
|
3
|
+
* SQLITE_BUSY, including its extended codes: another connection holds a lock the statement needs. Reads node:sqlite's
|
|
4
|
+
* `errcode` and libSQL's `rawCode` on the error or on a cause it wraps, such as the facade's `StorageUnavailableError`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isSqliteBusy(error: unknown): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Switches a database file to the write-ahead log through `exec`, waiting up to `busyTimeoutMs` for a lock another
|
|
9
|
+
* connection holds, as every other statement on a connection with that busy timeout waits.
|
|
10
|
+
*
|
|
11
|
+
* SQLite switches a file still in the rollback journal by reading its header and then upgrading that read to a write.
|
|
12
|
+
* An upgrade never calls the busy handler, so while another connection holds a lock on the file, such as another
|
|
13
|
+
* process switching the same new file or writing an older one, the switch fails at once with SQLITE_BUSY however long
|
|
14
|
+
* the busy timeout is. It has changed nothing then, so it is tried again after a short wait until the busy timeout has
|
|
15
|
+
* passed. Once the file is in WAL mode, switched by this connection or another, the switch writes nothing and cannot
|
|
16
|
+
* meet that lock. Any other failure is thrown at once.
|
|
17
|
+
*/
|
|
18
|
+
export declare function switchToWriteAheadLog(exec: (sql: string) => Awaitable<unknown>, busyTimeoutMs: number): Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* `switchToWriteAheadLog` for a synchronous caller: it waits on the calling thread between attempts, as a statement
|
|
21
|
+
* on a node:sqlite connection waits on it for the busy timeout.
|
|
22
|
+
*/
|
|
23
|
+
export declare function switchToWriteAheadLogSync(exec: (sql: string) => unknown, busyTimeoutMs: number): void;
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=write-ahead-log.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"write-ahead-log.d.ts","sourceRoot":"","sources":["../../../src/core/storage/write-ahead-log.ts"],"names":[],"mappings":"AAAA,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAMnC;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAUpD;AAoBD;;;;;;;;;;GAUG;AACH,wBAAsB,qBAAqB,CAC1C,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,SAAS,CAAC,OAAO,CAAC,EACzC,aAAa,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC,CAWf;AAID;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CAUrG"}
|