@bastani/atomic 0.10.7 → 0.10.8
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 +42 -0
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +5 -5
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
- package/dist/_shared/mode-shared-2QJSCUM6.js +5 -5
- package/dist/_shared/p1a-prewarm-UQY3X2UK.js +3 -3
- package/dist/_shared/runtime-O4KCSG4C.js +2 -2
- package/dist/_shared/{sdk-WQIOHVKO.js → sdk-OSBEPR3Q.js} +2875 -12
- package/dist/_shared/sdk-OSBEPR3Q.js.map +1 -0
- package/dist/_shared/session-data-AHTU7IS6.js +3 -3
- package/dist/_shared/startup-0-0-TYUFUOJZ.js +2 -2
- package/dist/_shared/startup-0-1-W2G2UY7R.js +163 -163
- package/dist/_shared/startup-0-1-W2G2UY7R.js.map +1 -1
- package/dist/_shared/{startup-0-2-SZGQIWHI.js → startup-0-2-UXBUEOXW.js} +4 -4
- package/dist/_shared/{startup-0-2-SZGQIWHI.js.map → startup-0-2-UXBUEOXW.js.map} +1 -1
- package/dist/_shared/startup-0-3-T4DVFYWX.js +3 -3
- package/dist/_shared/startup-0-4-HN5EB4K7.js +3 -3
- package/dist/_shared/{startup-0-5-OHJNE6JH.js → startup-0-5-FD2P735I.js} +5 -5
- package/dist/_shared/{startup-0-5-OHJNE6JH.js.map → startup-0-5-FD2P735I.js.map} +1 -1
- package/dist/_shared/startup-10-0-TDQNBDDL.js +5 -5
- package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
- package/dist/_shared/startup-14-0-MLX36RBG.js +17 -4
- package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
- package/dist/_shared/startup-15-0-YUKGAC63.js +3 -3
- package/dist/_shared/startup-15-1-4S7FLMNG.js +5 -5
- package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
- package/dist/_shared/{startup-8-1-SJW2GMAM.js → startup-8-1-4KANEHRA.js} +6 -6
- package/dist/_shared/{startup-8-1-SJW2GMAM.js.map → startup-8-1-4KANEHRA.js.map} +1 -1
- package/dist/_shared/storage-command-7MGXLJGZ.js +3 -3
- package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/index.bundle.mjs +1 -1
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/auth-cli.code.js +3 -3
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.code.js +2 -2
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +3 -3
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +1 -1
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +1 -1
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +2 -2
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +2 -2
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.code.js +1 -1
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +2 -2
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/extensions/loader-virtual-modules.js +1 -1
- package/dist/core/extensions/runner-context.js +1 -1
- package/dist/core/intercom-broker-control-host.code.js +1 -1
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +2 -2
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/model-registry.js +1 -1
- package/dist/core/package-manager-storage-adapters.code.js +1 -1
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/sdk.code.js +3 -3
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-claims.d.ts +30 -0
- package/dist/core/session-lifecycle-work.d.ts +74 -0
- package/dist/core/session-manager-core.js +4 -4
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-storage.code.js +1 -1
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/storage/index.js +2 -2
- package/dist/core/storage/node-sqlite-thread.js +2 -2
- package/dist/core/storage/node-sqlite.js +2 -2
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +2 -2
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +2 -2
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/expanded-child-details.code.js +3 -3
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-staging.code.js +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-window.code.js +2 -2
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +1 -1
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/session-search-index.d.ts +39 -0
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +2 -2
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts +400 -0
- package/dist/core/storage/session/sql-session-store.impl.js +3 -3
- package/dist/core/storage/session/sql-session-store.js +3 -3
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.code.js +1 -1
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/session/yield-turn.d.ts +3 -0
- package/dist/core/storage/storage-status.code.js +1 -1
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.code.js +1 -1
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/storage/transfer-files.d.ts +74 -0
- package/dist/core/structured-output/index.code.js +1 -1
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.code.js +1 -1
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +2 -2
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +3 -3
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.code.js +1 -1
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/read-url.code.js +1 -1
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/worktree-snapshot/blob-store.js +2 -2
- package/dist/core/worktree-snapshot/errors.code.js +1 -1
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.code.js +1 -1
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.code.js +1 -1
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +2 -2
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.code.js +1 -1
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.d.ts +13 -3
- package/dist/index.js +11 -11
- package/dist/main-first-time-setup.code.js +1 -1
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/main.js +1 -1
- package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/modes/print-mode.js +1 -1
- package/dist/package-manager-cli.code.js +4 -4
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/10.js +1 -1
- package/dist/startup-stages/12.js +1 -1
- package/dist/startup-stages/8.js +1 -1
- package/dist/utils/startup-database-spare.code.js +1 -1
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/docs/sdk/reference.md +85 -0
- package/docs/sdk.md +23 -1
- package/package.json +8 -8
- package/dist/_shared/fork-staging-maintenance-AIIUXOZQ.js +0 -19
- package/dist/_shared/fork-staging-maintenance-AIIUXOZQ.js.map +0 -1
- package/dist/_shared/sdk-WQIOHVKO.js.map +0 -1
- package/dist/_shared/sql-session-store-5FD3WBMZ.js +0 -2903
- package/dist/_shared/sql-session-store-5FD3WBMZ.js.map +0 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { __name } from "./rolldown-runtime-BGM3D5V3.js";
|
|
2
2
|
import { APP_NAME, CONFIG_DIR_NAME, createChildProcessEnvironment, findHelperExecutable, getAgentDir, helperLaunch, helperLaunchAsync, missingHelperOptions, startedWithHangupIgnored, stripBom } from "./p0-cli-BB45ZQY6.js";
|
|
3
|
-
import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, blueprintBuildsSettled, canonicalEventBusFor, collectDeclaredDisplaySecrets, extractHeaderSecrets, flushRawStdout, isObject, isSensitiveKeyNameForMasking, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, resolveDecisionDeadlineMs, scrubFetchError, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout } from "./startup-0-0-TYUFUOJZ.js";
|
|
4
|
-
import { CommandDeliveries, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-W2G2UY7R.js";
|
|
3
|
+
import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, sha256Hex, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-TYUFUOJZ.js";
|
|
4
|
+
import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-W2G2UY7R.js";
|
|
5
5
|
import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
|
|
6
6
|
import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
|
|
7
|
-
import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-
|
|
7
|
+
import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-UXBUEOXW.js";
|
|
8
8
|
import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-T4DVFYWX.js";
|
|
9
|
-
import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, isDecisionError, isDecisionProviderError } from "./settings-startup-4QCVCI53.js";
|
|
10
|
-
import "./startup-8-0-34CBHPZH.js";
|
|
11
|
-
import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-
|
|
9
|
+
import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-4QCVCI53.js";
|
|
10
|
+
import { RESUME_UPGRADE_SOURCES, branchRanges, childCatalogCut, foldSessionResume, foreignResumeIds, isSessionResumeIndex, isUpgradableSessionResumeIndex, latestCompactionOf, readEarlierCompletionIntents, selectedPagePlan, sessionResumeFrom, sessionResumePlan, sessionResumeUpgrade, sessionTailFrom, snapshotCutOf, stateSeqsBefore, transcriptBranchSpan, validateSessionEntries, validateSessionHeader, validateSessionText } from "./startup-8-0-34CBHPZH.js";
|
|
11
|
+
import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-FD2P735I.js";
|
|
12
12
|
import { assertWorkspaceGitAvailable, formatModelLabel, gitOutput, runWorkspaceGit } from "./startup-0-4-HN5EB4K7.js";
|
|
13
|
-
import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-
|
|
13
|
+
import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-4KANEHRA.js";
|
|
14
14
|
import "./startup-15-0-YUKGAC63.js";
|
|
15
15
|
import "./startup-10-0-TDQNBDDL.js";
|
|
16
16
|
import "./p1a-prewarm-UQY3X2UK.js";
|
|
@@ -28,16 +28,23 @@ import { execFile, execFileSync } from "node:child_process";
|
|
|
28
28
|
import { existsSync, mkdirSync, promises, readFileSync } from "node:fs";
|
|
29
29
|
import { GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, OAuthRefreshRejectedError, classifyGitHubCopilotFailure, containsKnownEnvCredential, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, getCurrentTools, getGitHubCopilotError, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isModelType, isOAuthRefreshRejectedError, isRetryableGitHubCopilotError, jsonSchemasEqual, normalizeProviderId, omitOptionalNulls, retryAssistantCall, serializeGitHubCopilotError } from "@bastani/atomic-ai";
|
|
30
30
|
import { Container, Input, Spacer, Text, truncateToWidth, visibleWidth } from "@bastani/atomic-tui";
|
|
31
|
+
import { SessionBlobError, StorageError, StorageInvalidTextError, StorageSchemaVersionError } from "../core/storage/errors.js";
|
|
32
|
+
import { renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix } from "../core/storage/prefix.js";
|
|
31
33
|
import { createHash, randomUUID } from "node:crypto";
|
|
32
34
|
import lockfile from "proper-lockfile";
|
|
33
35
|
import { clampThinkingLevel, clampThinkingLevel as clampThinkingLevel$1, getSupportedThinkingLevels } from "@bastani/atomic-ai/compat";
|
|
34
36
|
import { once } from "node:events";
|
|
35
|
-
import {
|
|
37
|
+
import { SessionConflictError, SessionConflictError as SessionConflictError$1, SessionExistsError, SessionExistsError as SessionExistsError$1, SessionFormatVersionError, SessionIdMismatchError, SessionIdMismatchError as SessionIdMismatchError$1, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionNotFoundError as SessionNotFoundError$1, StorageUnavailableError as StorageUnavailableError$1, StoreClosedError as StoreClosedError$1 } from "../core/storage/session/errors.js";
|
|
38
|
+
import { MemorySnapshotBlobStore, SNAPSHOT_COLLECTION_BATCH, SqlSnapshotBlobStore, SqlSnapshotBlobStore as SqlSnapshotBlobStore$1, snapshotBlobHashes, snapshotIndexTables, snapshotIndexTables as snapshotIndexTables$1 } from "../core/worktree-snapshot/blob-store.js";
|
|
36
39
|
import { publishExtensionContextEffect, registerExtensionContextRetirementEffect } from "../core/extensions/runner-context.js";
|
|
37
40
|
import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
|
|
38
41
|
import { ModelRegistry } from "../core/model-registry.js";
|
|
42
|
+
import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
|
|
43
|
+
import { sequenceRunner } from "../core/storage/statement-sequence.js";
|
|
39
44
|
import { createServer } from "node:http";
|
|
40
45
|
import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
|
|
46
|
+
import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
|
|
47
|
+
import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
|
|
41
48
|
import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch } from "@bastani/atomic-ai/api/cloudflare-gateway-binding";
|
|
42
49
|
import { configuredSecretRedactor } from "../core/storage/sqlite-facade.js";
|
|
43
50
|
import { oauthErrorHtml, oauthSuccessHtml } from "@bastani/atomic-ai/utils/oauth-page";
|
|
@@ -907,6 +914,2862 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
|
|
|
907
914
|
}], options);
|
|
908
915
|
return root;
|
|
909
916
|
}
|
|
917
|
+
/** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
|
|
918
|
+
* cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
|
|
919
|
+
async function tryCleanupForkStaging(database, dialect, table) {
|
|
920
|
+
if (!database.tryMaintenance) return;
|
|
921
|
+
const lease = 0;
|
|
922
|
+
const lapsed = `SELECT transfer_id FROM ${table} WHERE kind=${lease} AND size<${dialect.nowMs} LIMIT 1`;
|
|
923
|
+
if (!await database.get(lapsed)) return;
|
|
924
|
+
await database.tryMaintenance(async (tx) => {
|
|
925
|
+
const expired = await tx.get(lapsed);
|
|
926
|
+
if (!expired) return;
|
|
927
|
+
const id = String(expired.transfer_id);
|
|
928
|
+
await tx.run(`UPDATE ${table} SET body=?,size=0 WHERE transfer_id=? AND kind=${lease}`, crypto.randomUUID(), id);
|
|
929
|
+
if ((await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind>${lease} AND (kind,seq,idx) IN (SELECT kind,seq,idx FROM ${table} WHERE transfer_id=? AND kind>${lease} LIMIT ?)`, id, id, 32)).changes < 32) await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind=${lease}`, id);
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
// dist/core/storage/session/sql-chat-records.js
|
|
933
|
+
/** Rows one read fetches at most. */
|
|
934
|
+
const READ_PAGE_ROWS = 64;
|
|
935
|
+
/**
|
|
936
|
+
* The stored bytes (anchor and record) one read returns at most, after its first row. With the server's own overhead
|
|
937
|
+
* for 64 rows it stays under a libSQL server configured for 150 KB responses; a capped record is under 25 KB.
|
|
938
|
+
*/
|
|
939
|
+
const CHAT_READ_PAGE_BYTES = 12e4;
|
|
940
|
+
/** Prompt ids one reverse lookup binds at most. */
|
|
941
|
+
const ORDER_BATCH = 128;
|
|
942
|
+
/**
|
|
943
|
+
* The stored keys of a position's records (`L`) and of a prompt's reverse edge (`O`). Entry ids are any text, so only
|
|
944
|
+
* a tag of its own keeps every position's key apart from every prompt's: a reverse lookup never matches a body.
|
|
945
|
+
*/
|
|
946
|
+
const lineKey = (anchor) => `L${anchor}`;
|
|
947
|
+
const orderKey = (promptId) => `O${promptId}`;
|
|
948
|
+
/**
|
|
949
|
+
* Each write runs in a transaction of its own, as every session write does, on the session writer's connection and
|
|
950
|
+
* in its order. A statement outside a transaction would wait for another process's write lock in node:sqlite's busy
|
|
951
|
+
* handler, which blocks the event loop for up to the busy timeout (#5682); a transaction waits for the lock without
|
|
952
|
+
* blocking it. A transient failure runs the write again, as one statement outside a transaction would.
|
|
953
|
+
*/
|
|
954
|
+
const SIDE_WRITE = { retryTransientFailures: true };
|
|
955
|
+
/** A new physical table per format version; the main sessions schema (and all its old readers) stay unchanged. */
|
|
956
|
+
function sqlChatRecords(database, sessions, table, index) {
|
|
957
|
+
const dialect = dialectOf(database);
|
|
958
|
+
let initialized;
|
|
959
|
+
function initialize() {
|
|
960
|
+
const create = () => database.transaction(async (tx) => {
|
|
961
|
+
await tx.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
962
|
+
position ${dialect.types.serialKey}, session_id TEXT NOT NULL REFERENCES ${sessions}(id) ON DELETE CASCADE,
|
|
963
|
+
epoch TEXT NOT NULL, anchor TEXT NOT NULL, data TEXT NOT NULL)`);
|
|
964
|
+
await tx.exec(`CREATE INDEX IF NOT EXISTS ${index} ON ${table}(session_id, epoch, anchor, position)`);
|
|
965
|
+
}, SIDE_WRITE);
|
|
966
|
+
initialized ??= create().catch(() => create()).catch((error) => {
|
|
967
|
+
initialized = void 0;
|
|
968
|
+
throw error;
|
|
969
|
+
});
|
|
970
|
+
return initialized;
|
|
971
|
+
}
|
|
972
|
+
const current = dialect.jsonText("summary_state", "epoch");
|
|
973
|
+
const bytes = (column) => dialect.textByteLength(column);
|
|
974
|
+
return {
|
|
975
|
+
async append(owner, anchor, record) {
|
|
976
|
+
record = boundedChatRecord(record);
|
|
977
|
+
await initialize();
|
|
978
|
+
const rows = [[lineKey(anchor), JSON.stringify({
|
|
979
|
+
v: 1,
|
|
980
|
+
...record
|
|
981
|
+
})]];
|
|
982
|
+
if (record.kind === "promptBefore") rows.push([orderKey(record.promptId), encodeChatOrder({
|
|
983
|
+
anchor,
|
|
984
|
+
promptId: record.promptId
|
|
985
|
+
})]);
|
|
986
|
+
await database.transaction((tx) => tx.run(`INSERT INTO ${table} (session_id,epoch,anchor,data) ${rows.map(() => `SELECT id,?,?,? FROM ${sessions} WHERE id=? AND ${current}=?`).join(" UNION ALL ")}`, ...rows.flatMap(([key, data]) => [
|
|
987
|
+
owner.epoch,
|
|
988
|
+
key,
|
|
989
|
+
data,
|
|
990
|
+
owner.id,
|
|
991
|
+
owner.epoch
|
|
992
|
+
])), SIDE_WRITE);
|
|
993
|
+
},
|
|
994
|
+
async has(owner) {
|
|
995
|
+
return !!await database.get(`SELECT 1 AS present FROM ${table} WHERE session_id=? AND epoch=? LIMIT 1`, owner.id, owner.epoch).catch(() => void 0);
|
|
996
|
+
},
|
|
997
|
+
async read(owner, anchors) {
|
|
998
|
+
if (!anchors.length) return [];
|
|
999
|
+
const result = [];
|
|
1000
|
+
let after = 0;
|
|
1001
|
+
for (;;) {
|
|
1002
|
+
const rows = await database.all(`SELECT position,anchor,data,fetched FROM (
|
|
1003
|
+
SELECT position,anchor,data,count(*) OVER () AS fetched,
|
|
1004
|
+
row_number() OVER (ORDER BY position) AS page_row,
|
|
1005
|
+
sum(${bytes("anchor")}+${bytes("data")}) OVER (ORDER BY position) AS page_bytes
|
|
1006
|
+
FROM (SELECT position,anchor,data FROM ${table}
|
|
1007
|
+
WHERE session_id=? AND epoch=? AND position>? AND anchor IN (${anchors.map(() => "?").join(",")})
|
|
1008
|
+
ORDER BY position LIMIT ${READ_PAGE_ROWS}) AS candidates
|
|
1009
|
+
) AS page WHERE page_row=1 OR page_bytes<=? ORDER BY position`, owner.id, owner.epoch, after, ...anchors.map(lineKey), CHAT_READ_PAGE_BYTES);
|
|
1010
|
+
for (const { anchor, data } of rows) {
|
|
1011
|
+
const record = decodeChatRecord(data);
|
|
1012
|
+
if (record) result.push({
|
|
1013
|
+
anchor: anchor.slice(1),
|
|
1014
|
+
record
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
const last = rows[rows.length - 1];
|
|
1018
|
+
if (!last || Number(last.fetched) < READ_PAGE_ROWS && rows.length === Number(last.fetched)) return result;
|
|
1019
|
+
after = last.position;
|
|
1020
|
+
}
|
|
1021
|
+
},
|
|
1022
|
+
async readOrders(owner, promptIds) {
|
|
1023
|
+
const orders = [];
|
|
1024
|
+
for (let i = 0; i < promptIds.length; i += ORDER_BATCH) {
|
|
1025
|
+
const keys = promptIds.slice(i, i + ORDER_BATCH).map(orderKey);
|
|
1026
|
+
const rows = await database.all(`SELECT data FROM ${table} WHERE session_id=? AND epoch=? AND anchor IN (${keys.map(() => "?").join(",")}) ORDER BY position`, owner.id, owner.epoch, ...keys);
|
|
1027
|
+
for (const { data } of rows) {
|
|
1028
|
+
const order = decodeChatOrder(data);
|
|
1029
|
+
if (order) orders.push(order);
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return firstChatOrders(orders, promptIds);
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
// dist/core/storage/session/sql-session-store.js
|
|
1037
|
+
/**
|
|
1038
|
+
* The newest sessions schema this build reads and writes. Version 2 stores long entries in chunks (#4954), which a build
|
|
1039
|
+
* that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
|
|
1040
|
+
* this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
|
|
1041
|
+
* when next opened with `StorageSchemaVersionError`. Builds before 2 check only the meta row, on SQLite and Postgres alike.
|
|
1042
|
+
*/
|
|
1043
|
+
const SESSION_SCHEMA_VERSION = 2;
|
|
1044
|
+
/** The sessions schema of a database without chunked entries, which older builds read too. */
|
|
1045
|
+
const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
|
|
1046
|
+
/** The schema domain of the session tables in the prefix's migration ledger. */
|
|
1047
|
+
const SESSION_DOMAIN = "sessions";
|
|
1048
|
+
/**
|
|
1049
|
+
* The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
|
|
1050
|
+
* so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
|
|
1051
|
+
* 5 MB) and a statement's response (10 MB), and the HTTP protocol carries a blob as base64 in JSON, about 1.4 MB for
|
|
1052
|
+
* this size. A different size needs different table names, because a blob's rows are addressed by their index.
|
|
1053
|
+
*/
|
|
1054
|
+
const SESSION_BLOB_CHUNK_BYTES = 1048576;
|
|
1055
|
+
/**
|
|
1056
|
+
* The most bytes of an entry's JSON one row of the entries table holds. A longer entry is stored as a stub in its
|
|
1057
|
+
* entries row, which keeps its `type`, `id` and `parentId` for the snapshot reference index, and its UTF-8 JSON in
|
|
1058
|
+
* rows of at most this many bytes in the entry chunks table, written in the entry's transaction (#4954). Like
|
|
1059
|
+
* {@link SESSION_BLOB_CHUNK_BYTES} it stays well under the smallest backend limit, sqld's 5,000,000 bytes per value
|
|
1060
|
+
* and per row. Snapshot entries are never split: the reference index reads their whole JSON.
|
|
1061
|
+
*/
|
|
1062
|
+
const SESSION_ENTRY_CHUNK_BYTES = 1048576;
|
|
1063
|
+
/**
|
|
1064
|
+
* The bytes of a chunked message's JSON an unindexed fork reads to learn its role. The role follows the entry's type,
|
|
1065
|
+
* IDs and timestamp, a few hundred bytes in.
|
|
1066
|
+
*/
|
|
1067
|
+
const FORK_ROLE_PREFIX_BYTES = 4096;
|
|
1068
|
+
/**
|
|
1069
|
+
* The most characters one read of entries or listing rows returns, by the stored text's `length()`. A character is at
|
|
1070
|
+
* most four bytes of UTF-8 and a JSON escape at most doubles a character on a server's wire, so a page stays under
|
|
1071
|
+
* sqld's 10 MB response limit; a single row longer than this is a page of its own (#4954).
|
|
1072
|
+
*/
|
|
1073
|
+
const SESSION_READ_PAGE_CHARS = 1048576;
|
|
1074
|
+
/** Maximum entries folded per resume metadata query. */
|
|
1075
|
+
const SESSION_RESUME_REBUILD = { pageEntries: 512 };
|
|
1076
|
+
/** Bound each write transaction while reusing the bytes already supplied to putBlob. */
|
|
1077
|
+
const LEGACY_BLOB_BATCH_CHUNKS = 16;
|
|
1078
|
+
const SESSION_TABLES = Object.freeze({
|
|
1079
|
+
meta: "meta",
|
|
1080
|
+
sessions: "sessions",
|
|
1081
|
+
entries: "entries",
|
|
1082
|
+
searchTexts: "search_texts",
|
|
1083
|
+
blobs: "blobs",
|
|
1084
|
+
blobChunks: "blob_chunks",
|
|
1085
|
+
entryChunks: "entry_chunks"
|
|
1086
|
+
});
|
|
1087
|
+
/**
|
|
1088
|
+
* The staging table of full-session clones from a handle this store cannot prove to be its own connection (#5594):
|
|
1089
|
+
* `<prefix>session_fork_staging`, created by the first such clone, never by an open, and not part of the sessions schema.
|
|
1090
|
+
*/
|
|
1091
|
+
const SESSION_FORK_STAGING_TABLES = Object.freeze({ forkStaging: "fork_staging" });
|
|
1092
|
+
/** The schema domain, in the prefix's migration ledger, of the table of open sessions (#4971). */
|
|
1093
|
+
const SESSION_PRESENCE_DOMAIN = "session-presence";
|
|
1094
|
+
const SESSION_PRESENCE_TABLES = Object.freeze({ open: "open" });
|
|
1095
|
+
function windowIndex(state, seq) {
|
|
1096
|
+
return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
|
|
1097
|
+
}
|
|
1098
|
+
/** An older client rebuilds summary_state.resume in its own format. Do not evict that valid projection
|
|
1099
|
+
* on a read: once either side sees a version-5 index, keep this version in its own field. */
|
|
1100
|
+
function windowFields(previous, index, seq, epoch) {
|
|
1101
|
+
if (previous?.resume?.version === 5 || previous?.windowResume) {
|
|
1102
|
+
const older = previous.resume;
|
|
1103
|
+
return {
|
|
1104
|
+
...older?.version === 5 && older.seq === seq && older.epoch === epoch ? { resume: older } : {},
|
|
1105
|
+
...index ? { windowResume: index } : {}
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
return index ? { resume: index } : {};
|
|
1109
|
+
}
|
|
1110
|
+
const SEQ_BATCH = 500;
|
|
1111
|
+
/**
|
|
1112
|
+
* The rows one statement of a paged read fetches, by key after the previous page, before it keeps those that fit in
|
|
1113
|
+
* {@link SESSION_READ_PAGE_CHARS}: each statement reads a bounded batch rather than every remaining row, so a long
|
|
1114
|
+
* session or listing is read in linear time. A full batch quadruples the next fetch. A clipped batch keeps its fetch
|
|
1115
|
+
* size when its unreturned text is at most four pages; otherwise the next fetch is twice the returned rows.
|
|
1116
|
+
*/
|
|
1117
|
+
const SESSION_READ_FETCH = {
|
|
1118
|
+
first: 1024,
|
|
1119
|
+
min: 1,
|
|
1120
|
+
max: 8192
|
|
1121
|
+
};
|
|
1122
|
+
const SESSION_READ_INLINE_BYTES = 4096;
|
|
1123
|
+
function nextFetch(limit, rows) {
|
|
1124
|
+
const kept = rows.length;
|
|
1125
|
+
const fetched = Number(rows[0]?.fetched ?? 0);
|
|
1126
|
+
const more = kept > 0 && kept < fetched;
|
|
1127
|
+
const batchChars = Number(rows[0]?.batch_chars ?? 0);
|
|
1128
|
+
const pageChars = Number(rows.at(-1)?.page_chars ?? 0);
|
|
1129
|
+
const next = kept === Math.min(limit, fetched) ? limit * 4 : batchChars - pageChars <= 4194304 ? limit : Math.max(SESSION_READ_FETCH.min, kept * 2);
|
|
1130
|
+
return {
|
|
1131
|
+
more,
|
|
1132
|
+
limit: Math.min(SESSION_READ_FETCH.max, next)
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
/** `rows` split into runs, in order, of at most {@link SESSION_READ_PAGE_CHARS}; a longer row is a run of its own. */
|
|
1136
|
+
function pagesOf(rows) {
|
|
1137
|
+
const pages = [];
|
|
1138
|
+
let page = [];
|
|
1139
|
+
let chars = 0;
|
|
1140
|
+
for (const row of rows) {
|
|
1141
|
+
const size = Number(row.size ?? 0);
|
|
1142
|
+
if (page.length > 0 && chars + size > 1048576) {
|
|
1143
|
+
pages.push(page);
|
|
1144
|
+
page = [];
|
|
1145
|
+
chars = 0;
|
|
1146
|
+
}
|
|
1147
|
+
page.push(row);
|
|
1148
|
+
chars += size;
|
|
1149
|
+
}
|
|
1150
|
+
if (page.length > 0) pages.push(page);
|
|
1151
|
+
return pages;
|
|
1152
|
+
}
|
|
1153
|
+
/** An entry's JSON as its entries row stores it, and the UTF-8 chunks of a long one. */
|
|
1154
|
+
function storedEntry(entry, json) {
|
|
1155
|
+
if (json.length * 3 <= 1048576 || entry.type === "worktree_snapshot") return {
|
|
1156
|
+
json,
|
|
1157
|
+
chunks: []
|
|
1158
|
+
};
|
|
1159
|
+
const bytes = Buffer.from(json, "utf8");
|
|
1160
|
+
if (bytes.byteLength <= 1048576) return {
|
|
1161
|
+
json,
|
|
1162
|
+
chunks: []
|
|
1163
|
+
};
|
|
1164
|
+
const chunks = [];
|
|
1165
|
+
for (let offset = 0; offset < bytes.byteLength; offset += SESSION_ENTRY_CHUNK_BYTES) chunks.push(bytes.subarray(offset, offset + SESSION_ENTRY_CHUNK_BYTES));
|
|
1166
|
+
const stub = {
|
|
1167
|
+
type: entry.type,
|
|
1168
|
+
id: entry.id,
|
|
1169
|
+
parentId: entry.parentId ?? null
|
|
1170
|
+
};
|
|
1171
|
+
return {
|
|
1172
|
+
json: JSON.stringify(stub),
|
|
1173
|
+
chunks
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
/** Each committed batch is its own durable checkpoint; the legacy bytes stay readable until publication. */
|
|
1177
|
+
async function migrateLegacyBlobBatch(tx, tables, sessionId, hash, data) {
|
|
1178
|
+
const params = [sessionId, hash];
|
|
1179
|
+
const row = await tx.get(`SELECT bytes FROM ${tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, ...params);
|
|
1180
|
+
if (!row) return false;
|
|
1181
|
+
const progress = await tx.get(`SELECT COALESCE(max(idx) + 1, 0) AS next FROM ${tables.blobChunks} WHERE session_id = ? AND hash = ?`, ...params);
|
|
1182
|
+
const next = Number(progress.next);
|
|
1183
|
+
const chunks = Math.ceil(Number(row.bytes) / SESSION_BLOB_CHUNK_BYTES);
|
|
1184
|
+
const end = Math.min(next + LEGACY_BLOB_BATCH_CHUNKS, chunks);
|
|
1185
|
+
for (let index = next; index < end; index++) await tx.run(`INSERT INTO ${tables.blobChunks} (session_id, hash, idx, data) VALUES (?, ?, ?, ?)`, ...params, index, data.subarray(index * SESSION_BLOB_CHUNK_BYTES, (index + 1) * SESSION_BLOB_CHUNK_BYTES));
|
|
1186
|
+
if (end === chunks) await tx.run(`UPDATE ${tables.blobs} SET chunks = ?, data = X'' WHERE session_id = ? AND hash = ?`, chunks, ...params);
|
|
1187
|
+
return true;
|
|
1188
|
+
}
|
|
1189
|
+
/** Every listing column except search text, so an unchanged row keeps its cached summary. */
|
|
1190
|
+
const LISTING_COLUMNS = "id, cwd, internal, header_json, last_seq, modified_at, message_count, first_message, name, has_name, summary, summarized_through_id, revision";
|
|
1191
|
+
const LISTING_SELECT_COLUMNS = LISTING_COLUMNS.split(", ").map((column) => `s.${column}`).join(", ");
|
|
1192
|
+
/** The characters a listing row holds, its search text aside, for reading listings in pages (#4954). */
|
|
1193
|
+
const LISTING_SIZE = "length(id) + length(cwd) + length(header_json) + length(modified_at) + length(first_message) + COALESCE(length(name), 0) + COALESCE(length(summary), 0) + COALESCE(length(summarized_through_id), 0) + length(revision) + 256";
|
|
1194
|
+
/** Rows whose search text is read per query; well under SQLite's bound-parameter limit. */
|
|
1195
|
+
const LISTING_FETCH_BATCH = 500;
|
|
1196
|
+
/** Sessions one statement of a paced listing's project scan reads over a database server. */
|
|
1197
|
+
const LISTING_CWD_PAGE = 2e3;
|
|
1198
|
+
/**
|
|
1199
|
+
* Sessions one statement of a paced listing scans over this process's own SQLite connection, with a turn of the event
|
|
1200
|
+
* loop after each (#5480). Such a statement runs on the event loop and reads every row it scans; on a large store whose
|
|
1201
|
+
* pages are not cached a row can cost a disk read, so a few thousand rows per statement held the event loop for
|
|
1202
|
+
* seconds. A database server's statements do not hold the event loop, so listings over one keep larger statements.
|
|
1203
|
+
*/
|
|
1204
|
+
const LISTING_SCAN_ROWS = 256;
|
|
1205
|
+
/** Stored project spellings a paced listing resolves at once; each is a chain of file system calls. */
|
|
1206
|
+
const LISTING_CWD_MATCHES = 64;
|
|
1207
|
+
const STUB_ENTRY = {
|
|
1208
|
+
type: "custom",
|
|
1209
|
+
id: "",
|
|
1210
|
+
parentId: null,
|
|
1211
|
+
timestamp: "1970-01-01T00:00:00.000Z",
|
|
1212
|
+
customType: ""
|
|
1213
|
+
};
|
|
1214
|
+
/** Listing scopes (visibility and project) kept at once; the picker uses two. */
|
|
1215
|
+
const LISTING_SCOPES = 8;
|
|
1216
|
+
/**
|
|
1217
|
+
* Session reads and writes use nothing but their transaction, so one that a transient failure of a database server
|
|
1218
|
+
* ended before it committed runs again (#4383); `append` and `replace` check `expectSeq` again on each run.
|
|
1219
|
+
*/
|
|
1220
|
+
const SESSION_TRANSACTION = { retryTransientFailures: true };
|
|
1221
|
+
/** The largest content index or suffix length a task-reference query binds, an SQL `INTEGER` on every backend. */
|
|
1222
|
+
const TASK_REFERENCE_INTEGER = 2 ** 31 - 1;
|
|
1223
|
+
/**
|
|
1224
|
+
* A task-reference duplicate query's bounds, checked, and its candidates as `[seq, block or -1, suffix or 0]` rows:
|
|
1225
|
+
* integers only, so no entry ID is ever bound.
|
|
1226
|
+
*/
|
|
1227
|
+
function taskReferenceDuplicateQuery(query) {
|
|
1228
|
+
const within = (value, min, max) => Number.isSafeInteger(value) && value >= min && value <= max;
|
|
1229
|
+
const { throughSeq, afterSeq = 0, limit = 64 } = query;
|
|
1230
|
+
const invalid = (what) => /* @__PURE__ */ new RangeError(`Invalid task-reference duplicate query: ${what}`);
|
|
1231
|
+
if (!within(throughSeq, 0, Number.MAX_SAFE_INTEGER)) throw invalid("throughSeq");
|
|
1232
|
+
if (!within(afterSeq, 0, Number.MAX_SAFE_INTEGER)) throw invalid("afterSeq");
|
|
1233
|
+
if (!within(limit, 1, 64)) throw invalid("limit");
|
|
1234
|
+
if (query.candidates.length > 100) throw invalid("too many candidates");
|
|
1235
|
+
return {
|
|
1236
|
+
candidates: query.candidates.map(({ seq, contentIndex, suffixChars }) => {
|
|
1237
|
+
if (!within(seq, 1, throughSeq)) throw invalid("candidate seq");
|
|
1238
|
+
if (contentIndex !== void 0 && !within(contentIndex, 0, TASK_REFERENCE_INTEGER)) throw invalid("candidate contentIndex");
|
|
1239
|
+
if (suffixChars !== void 0 && !within(suffixChars, 0, TASK_REFERENCE_INTEGER)) throw invalid("candidate suffixChars");
|
|
1240
|
+
return [
|
|
1241
|
+
seq,
|
|
1242
|
+
contentIndex ?? -1,
|
|
1243
|
+
contentIndex === void 0 ? suffixChars ?? 0 : 0
|
|
1244
|
+
];
|
|
1245
|
+
}),
|
|
1246
|
+
afterSeq,
|
|
1247
|
+
limit
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
/** A write revision: 32 random hex digits, the form SQLite's `lower(hex(randomblob(16)))` gave earlier builds. */
|
|
1251
|
+
function newRevision() {
|
|
1252
|
+
return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1253
|
+
}
|
|
1254
|
+
function summaryFromRow(row) {
|
|
1255
|
+
const header = JSON.parse(row.header_json);
|
|
1256
|
+
return {
|
|
1257
|
+
id: header.id,
|
|
1258
|
+
cwd: header.cwd,
|
|
1259
|
+
...header.parentSessionId !== void 0 ? { parentSessionId: header.parentSessionId } : {},
|
|
1260
|
+
internal: header.internal === true,
|
|
1261
|
+
...header.workflow !== void 0 ? { workflow: header.workflow } : {},
|
|
1262
|
+
...row.name !== null ? { name: JSON.parse(row.name) } : {},
|
|
1263
|
+
hasName: row.has_name === 1,
|
|
1264
|
+
createdAt: header.createdAt,
|
|
1265
|
+
modifiedAt: row.modified_at,
|
|
1266
|
+
messageCount: row.message_count,
|
|
1267
|
+
firstMessage: JSON.parse(row.first_message),
|
|
1268
|
+
...row.summary !== null ? { summary: JSON.parse(row.summary) } : {},
|
|
1269
|
+
...row.summarized_through_id !== null ? { summarizedThroughId: row.summarized_through_id } : {},
|
|
1270
|
+
searchText: JSON.parse(row.search_texts_json).join(" ")
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
/** Changes on every write: `revision` catches a rewrite that leaves every other listed column as it was. */
|
|
1274
|
+
function listingVersion(row) {
|
|
1275
|
+
return `${row.revision}\u0000${row.last_seq}\u0000${row.modified_at}\u0000${row.message_count}\u0000${row.has_name}\u0000${row.name}\u0000${row.summarized_through_id}\u0000${row.summary}\u0000${row.first_message}\u0000${row.header_json}`;
|
|
1276
|
+
}
|
|
1277
|
+
async function entryByteLengthOf(database) {
|
|
1278
|
+
const dialect = dialectOf(database);
|
|
1279
|
+
if (dialect.name !== "sqlite") return dialect.textByteLength;
|
|
1280
|
+
try {
|
|
1281
|
+
await database.get("SELECT octet_length('') AS bytes");
|
|
1282
|
+
return (expression) => `octet_length(${expression})`;
|
|
1283
|
+
} catch {
|
|
1284
|
+
return dialect.textByteLength;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* The most bytes of statements a session write sends as one batch: an ordinary message's are far fewer. A larger
|
|
1289
|
+
* write, an import or a fork's whole window, runs its statements one at a time as they are made.
|
|
1290
|
+
*/
|
|
1291
|
+
const STATEMENT_BATCH_BYTES = 1048576;
|
|
1292
|
+
/** About how many bytes `statement` carries: its text and its parameters. */
|
|
1293
|
+
function statementBytes(statement) {
|
|
1294
|
+
let bytes = statement.sql.length;
|
|
1295
|
+
for (const value of statement.params) if (typeof value === "string") bytes += value.length;
|
|
1296
|
+
else if (value instanceof Uint8Array) bytes += value.byteLength;
|
|
1297
|
+
else bytes += 8;
|
|
1298
|
+
return bytes;
|
|
1299
|
+
}
|
|
1300
|
+
var SqlSessionStore = class SqlSessionStore {
|
|
1301
|
+
database;
|
|
1302
|
+
dialect;
|
|
1303
|
+
tables;
|
|
1304
|
+
prefix;
|
|
1305
|
+
legacyBlobData;
|
|
1306
|
+
closed = false;
|
|
1307
|
+
cwdMatcher;
|
|
1308
|
+
snapshotBlobs;
|
|
1309
|
+
/** The blob table of this store's database, which appends check snapshot records against (#5077). */
|
|
1310
|
+
blobTable;
|
|
1311
|
+
/** Set by `open`, once the store exists (#4971). */
|
|
1312
|
+
openMarkers;
|
|
1313
|
+
searchIndex;
|
|
1314
|
+
chatStore;
|
|
1315
|
+
/**
|
|
1316
|
+
* Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
|
|
1317
|
+
* lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
|
|
1318
|
+
* ordinary turn-ending notice writes nothing (#5682).
|
|
1319
|
+
*/
|
|
1320
|
+
get chatRecords() {
|
|
1321
|
+
const { adapter, location } = this.database.descriptor;
|
|
1322
|
+
if (adapter === "libsql" && /^file:/i.test(location)) return void 0;
|
|
1323
|
+
if (!this.chatStore) {
|
|
1324
|
+
const names = renderStorageIdentifiers("sessions", {
|
|
1325
|
+
rows: "chat_v1",
|
|
1326
|
+
byAnchor: "chat_v1_anchor"
|
|
1327
|
+
}, this.prefix);
|
|
1328
|
+
this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor);
|
|
1329
|
+
}
|
|
1330
|
+
return this.chatStore;
|
|
1331
|
+
}
|
|
1332
|
+
entryByteLength;
|
|
1333
|
+
chunkRowids;
|
|
1334
|
+
/** Session ids of each recently listed scope, valid while the store's change token is unchanged. */
|
|
1335
|
+
scopes = /* @__PURE__ */ new Map();
|
|
1336
|
+
/** Listed summaries of sessions that still exist at the cached version; never more than the store holds. */
|
|
1337
|
+
summaries = /* @__PURE__ */ new Map();
|
|
1338
|
+
/**
|
|
1339
|
+
* Settles when the latest listing has read and updated the caches. Listings take turns, so one listing's
|
|
1340
|
+
* pruning never drops summaries that another has fetched but not yet recorded under its scope.
|
|
1341
|
+
*/
|
|
1342
|
+
listing = Promise.resolve();
|
|
1343
|
+
resumeIndexes = /* @__PURE__ */ new Map();
|
|
1344
|
+
forkStagingTable;
|
|
1345
|
+
/** The generation each recently read session's row held at a revision: see `generation`. */
|
|
1346
|
+
generations = /* @__PURE__ */ new Map();
|
|
1347
|
+
constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength) {
|
|
1348
|
+
this.database = database;
|
|
1349
|
+
this.dialect = dialectOf(database);
|
|
1350
|
+
this.entryByteLength = entryByteLength;
|
|
1351
|
+
this.tables = tables;
|
|
1352
|
+
this.prefix = prefix ?? "";
|
|
1353
|
+
registerForkScope(this, () => ({
|
|
1354
|
+
kind: "sql",
|
|
1355
|
+
backing: this.database,
|
|
1356
|
+
prefix: this.prefix
|
|
1357
|
+
}));
|
|
1358
|
+
this.cwdMatcher = cwdMatcher;
|
|
1359
|
+
this.snapshotBlobs = snapshotBlobs;
|
|
1360
|
+
this.blobTable = snapshotBlobs;
|
|
1361
|
+
this.legacyBlobData = legacyBlobData;
|
|
1362
|
+
if (searchIndex !== void 0) this.searchIndex = searchIndex;
|
|
1363
|
+
registerHistorySnapshot(this, (sessionId, project) => {
|
|
1364
|
+
this.assertOpen();
|
|
1365
|
+
validateSessionText("sessionId", sessionId);
|
|
1366
|
+
return this.transaction(async (tx) => {
|
|
1367
|
+
const head = await this.historyHead(tx, sessionId);
|
|
1368
|
+
return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
|
|
1369
|
+
}, SESSION_TRANSACTION);
|
|
1370
|
+
});
|
|
1371
|
+
this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
|
|
1372
|
+
}
|
|
1373
|
+
/** Bind an existing transcript for the storage search command. No schema setup, markers or search index. */
|
|
1374
|
+
static async openTranscriptReader(database) {
|
|
1375
|
+
const tables = renderStorageIdentifiers("sessions", SESSION_TABLES);
|
|
1376
|
+
const reader = new SqlSessionStore(database, tables, void 0, void 0, SqlSnapshotBlobStore$1.forTranscriptReader(database), false, void 0, await entryByteLengthOf(database));
|
|
1377
|
+
await reader.assertReadableSchema(database);
|
|
1378
|
+
return reader;
|
|
1379
|
+
}
|
|
1380
|
+
static async open(database, options = {}) {
|
|
1381
|
+
validateStoragePrefix(options.prefix, dialectOf(database).name);
|
|
1382
|
+
const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
|
|
1383
|
+
let legacyBlobData = false;
|
|
1384
|
+
const createTables = async (tx, dialect) => {
|
|
1385
|
+
const { int, text, blob } = dialect.types;
|
|
1386
|
+
const strict = dialect.tableOptions;
|
|
1387
|
+
const json = (column) => dialect.jsonValid(column);
|
|
1388
|
+
const columnExists = (table, column) => {
|
|
1389
|
+
const probe = dialect.columnExists(table, column);
|
|
1390
|
+
return async () => await tx.get(probe.sql, ...probe.params) !== void 0;
|
|
1391
|
+
};
|
|
1392
|
+
const [versions] = await statementBatch(tx, [`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`], [() => tx.all(`SELECT schema_version FROM ${tables.meta}`)]);
|
|
1393
|
+
for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1394
|
+
const tablesScript = `
|
|
1395
|
+
CREATE TABLE IF NOT EXISTS ${tables.sessions} (
|
|
1396
|
+
id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
|
|
1397
|
+
header_json ${text} NOT NULL CHECK(${json("header_json")}), internal ${int} NOT NULL,
|
|
1398
|
+
last_seq ${int} NOT NULL, modified_at ${text} NOT NULL, message_count ${int} NOT NULL,
|
|
1399
|
+
first_message ${text} NOT NULL CHECK(${json("first_message")}),
|
|
1400
|
+
name ${text} CHECK(name IS NULL OR ${json("name")}), has_name ${int} NOT NULL,
|
|
1401
|
+
summary ${text} CHECK(summary IS NULL OR ${json("summary")}), summarized_through_id ${text},
|
|
1402
|
+
summary_state ${text} NOT NULL CHECK(${json("summary_state")}), revision ${text} NOT NULL DEFAULT ''${dialect.rowOrderColumn}
|
|
1403
|
+
)${strict};
|
|
1404
|
+
CREATE TABLE IF NOT EXISTS ${tables.entries} (
|
|
1405
|
+
session_id ${text} NOT NULL, seq ${int} NOT NULL, entry_id ${text} NOT NULL,
|
|
1406
|
+
entry_json ${text} NOT NULL CHECK(${json("entry_json")}), PRIMARY KEY(session_id, seq)${dialect.rowOrderColumn}
|
|
1407
|
+
)${strict};
|
|
1408
|
+
CREATE TABLE IF NOT EXISTS ${tables.searchTexts} (
|
|
1409
|
+
session_id ${text} NOT NULL, seq ${int} NOT NULL,
|
|
1410
|
+
text_json ${text} NOT NULL CHECK(${json("text_json")}), PRIMARY KEY(session_id, seq)
|
|
1411
|
+
)${strict};
|
|
1412
|
+
CREATE TABLE IF NOT EXISTS ${tables.blobs} (
|
|
1413
|
+
session_id ${text} NOT NULL, hash ${text} NOT NULL, bytes ${int} NOT NULL, chunks ${int} NOT NULL,
|
|
1414
|
+
PRIMARY KEY(session_id, hash)
|
|
1415
|
+
)${strict};
|
|
1416
|
+
CREATE TABLE IF NOT EXISTS ${tables.blobChunks} (
|
|
1417
|
+
session_id ${text} NOT NULL, hash ${text} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
|
|
1418
|
+
PRIMARY KEY(session_id, hash, idx)
|
|
1419
|
+
)${strict};
|
|
1420
|
+
`;
|
|
1421
|
+
const [revision, data] = await statementBatch(tx, [versions.length === 0 && {
|
|
1422
|
+
sql: `INSERT INTO ${tables.meta} VALUES (?)`,
|
|
1423
|
+
params: [SESSION_SCHEMA_VERSION_UNCHUNKED]
|
|
1424
|
+
}, tablesScript], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
|
|
1425
|
+
legacyBlobData = data;
|
|
1426
|
+
const [chunks] = legacyBlobData ? await statementBatch(tx, [], [columnExists(tables.blobs, "chunks")]) : [true];
|
|
1427
|
+
await statementBatch(tx, [!revision && `ALTER TABLE ${tables.sessions} ADD COLUMN revision ${text} NOT NULL DEFAULT ''`, !chunks && `ALTER TABLE ${tables.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT -1`], []);
|
|
1428
|
+
};
|
|
1429
|
+
const orphanedEntryKeys = `SELECT k.session_id, k.seq
|
|
1430
|
+
FROM (SELECT DISTINCT session_id, seq FROM ${tables.entryChunks}) AS k
|
|
1431
|
+
WHERE NOT EXISTS (
|
|
1432
|
+
SELECT 1 FROM ${tables.entries} AS e
|
|
1433
|
+
WHERE e.session_id = k.session_id AND e.seq = k.seq AND e.chunks > 0
|
|
1434
|
+
)`;
|
|
1435
|
+
const removeOrphanedEntryChunks = {
|
|
1436
|
+
sql: `DELETE FROM ${tables.entryChunks} WHERE (session_id, seq) IN (${orphanedEntryKeys})`,
|
|
1437
|
+
params: []
|
|
1438
|
+
};
|
|
1439
|
+
/**
|
|
1440
|
+
* Long entries in chunks (#4954): the entry chunks table and the entries table's `chunks` column, 0 for an entry
|
|
1441
|
+
* stored whole, as every entry written before it was. Older builds read and write these tables unchanged, so the
|
|
1442
|
+
* sessions meta stays where it is until the first chunked entry (`insertEntries`). Setup is idempotent and runs
|
|
1443
|
+
* when the open finds the schema not current (`currentSchema`).
|
|
1444
|
+
*/
|
|
1445
|
+
const addEntryChunks = async (tx, dialect) => {
|
|
1446
|
+
const { int, text, blob } = dialect.types;
|
|
1447
|
+
const probe = dialect.columnExists(tables.entries, "chunks");
|
|
1448
|
+
const [chunks] = await statementBatch(tx, [`
|
|
1449
|
+
CREATE TABLE IF NOT EXISTS ${tables.entryChunks} (
|
|
1450
|
+
session_id ${text} NOT NULL, seq ${int} NOT NULL, idx ${int} NOT NULL, data ${blob} NOT NULL,
|
|
1451
|
+
PRIMARY KEY(session_id, seq, idx)
|
|
1452
|
+
)${dialect.tableOptions};
|
|
1453
|
+
`], [() => tx.get(probe.sql, ...probe.params)]);
|
|
1454
|
+
await statementBatch(tx, [chunks === void 0 && `ALTER TABLE ${tables.entries} ADD COLUMN chunks ${int} NOT NULL DEFAULT 0`, database.readOnly !== true && removeOrphanedEntryChunks], []);
|
|
1455
|
+
};
|
|
1456
|
+
const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
|
|
1457
|
+
const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
|
|
1458
|
+
if (current !== void 0) {
|
|
1459
|
+
legacyBlobData = current.legacyBlobData;
|
|
1460
|
+
if (current.orphaned) await database.transaction(async (tx) => {
|
|
1461
|
+
await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1462
|
+
await tx.run(removeOrphanedEntryChunks.sql);
|
|
1463
|
+
}).catch((error) => {
|
|
1464
|
+
if (error instanceof StorageSchemaVersionError) throw error;
|
|
1465
|
+
});
|
|
1466
|
+
} else await applyStorageMigrationsTogether(database, [{
|
|
1467
|
+
domain: SESSION_DOMAIN,
|
|
1468
|
+
steps: [{
|
|
1469
|
+
version: 1,
|
|
1470
|
+
up: createTables
|
|
1471
|
+
}, {
|
|
1472
|
+
version: 2,
|
|
1473
|
+
up: addEntryChunks
|
|
1474
|
+
}],
|
|
1475
|
+
options: { table: storageMigrationTable(options.prefix) }
|
|
1476
|
+
}, {
|
|
1477
|
+
domain: SESSION_PRESENCE_DOMAIN,
|
|
1478
|
+
steps: [{
|
|
1479
|
+
version: 1,
|
|
1480
|
+
up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
|
|
1481
|
+
}, {
|
|
1482
|
+
version: 2,
|
|
1483
|
+
up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
|
|
1484
|
+
}],
|
|
1485
|
+
options: {
|
|
1486
|
+
table: storageMigrationTable(options.prefix),
|
|
1487
|
+
acceptNewer: true
|
|
1488
|
+
}
|
|
1489
|
+
}]);
|
|
1490
|
+
const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
|
|
1491
|
+
const stagingProbe = dialectOf(database).tableExists(staging);
|
|
1492
|
+
const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
|
|
1493
|
+
const opening = current === void 0 ? await SqlSnapshotBlobStore$1.open(database, options.prefix) : void 0;
|
|
1494
|
+
const [blobs, searchIndex, entryByteLength] = await Promise.all([
|
|
1495
|
+
opening ?? SqlSnapshotBlobStore$1.open(database, options.prefix),
|
|
1496
|
+
SqlSessionSearchIndex.open(database, tables, options.prefix),
|
|
1497
|
+
entryByteLengthOf(database)
|
|
1498
|
+
]);
|
|
1499
|
+
const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength);
|
|
1500
|
+
store.openMarkers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
|
|
1501
|
+
if (await staged) await store.cleanupForkStaging();
|
|
1502
|
+
return store;
|
|
1503
|
+
}
|
|
1504
|
+
/**
|
|
1505
|
+
* Removes, in a bounded number of short transactions, the staged rows of clones that stopped mid-copy and whose lease
|
|
1506
|
+
* lapsed (#5594). Housekeeping: nothing reads those rows, so a failure leaves them to a later open or clone.
|
|
1507
|
+
*/
|
|
1508
|
+
async cleanupForkStaging() {
|
|
1509
|
+
try {
|
|
1510
|
+
await tryCleanupForkStaging(this.database, this.dialect, this.forkStagingTable);
|
|
1511
|
+
} catch {}
|
|
1512
|
+
}
|
|
1513
|
+
/**
|
|
1514
|
+
* What the open's setup would find, read without the write lock, when its schema steps would change nothing: every
|
|
1515
|
+
* table and column of both domains exists and the sessions meta holds only versions this build supports. Undefined
|
|
1516
|
+
* otherwise, and always on a database with versioned migrations, whose ledger the setup checks. Leftover entry
|
|
1517
|
+
* chunks are not part of the schema: `orphaned` tells whether the query `orphans` finds any, for the open to remove
|
|
1518
|
+
* them separately, and is false when it is not asked. The probes are read together, then the versions with that
|
|
1519
|
+
* query, so a current schema waits for two answers.
|
|
1520
|
+
*/
|
|
1521
|
+
static async currentSchema(database, tables, open, orphans) {
|
|
1522
|
+
const dialect = dialectOf(database);
|
|
1523
|
+
if (dialect.versionedMigrations) return void 0;
|
|
1524
|
+
const probes = [
|
|
1525
|
+
...[...Object.values(tables), open].map((table) => dialect.tableExists(table)),
|
|
1526
|
+
dialect.columnExists(tables.sessions, "revision"),
|
|
1527
|
+
dialect.columnExists(tables.entries, "chunks"),
|
|
1528
|
+
dialect.columnExists(tables.blobs, "chunks"),
|
|
1529
|
+
dialect.columnExists(open, "schema_version")
|
|
1530
|
+
];
|
|
1531
|
+
const legacy = dialect.columnExists(tables.blobs, "data");
|
|
1532
|
+
const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
|
|
1533
|
+
if (!found.every((row) => row !== void 0)) return void 0;
|
|
1534
|
+
const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
|
|
1535
|
+
orphaned?.catch(() => {});
|
|
1536
|
+
const versions = await database.all(`SELECT schema_version FROM ${tables.meta}`);
|
|
1537
|
+
if (versions.length === 0 || versions.some((row) => row.schema_version !== SESSION_SCHEMA_VERSION_UNCHUNKED && row.schema_version !== 2)) return void 0;
|
|
1538
|
+
return {
|
|
1539
|
+
legacyBlobData: legacyFound !== void 0,
|
|
1540
|
+
orphaned: await orphaned !== void 0
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* A transaction that first checks the sessions schema version again: a newer build may have upgraded the database
|
|
1545
|
+
* since this store opened it, and what it writes then is not this build's to read or write (#5065).
|
|
1546
|
+
*/
|
|
1547
|
+
transaction(body, options) {
|
|
1548
|
+
return this.database.transaction(async (tx) => {
|
|
1549
|
+
await this.assertReadableSchema(tx);
|
|
1550
|
+
return body(tx);
|
|
1551
|
+
}, options);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* `transaction` for a body that only reads and writes the database. The version check is sent first, as there, but on
|
|
1555
|
+
* a connection thread the body's first reads go behind it without waiting for its answer: one wait for the thread
|
|
1556
|
+
* fewer. The body awaits `checked` before its first write, so nothing is written unless the version is one this build
|
|
1557
|
+
* reads (its answer came before the reads', so that costs no wait); a version this build does not support is the
|
|
1558
|
+
* failure reported, whatever the body met.
|
|
1559
|
+
*/
|
|
1560
|
+
transactionCheckedAlongside(body, options) {
|
|
1561
|
+
return this.database.transaction(async (tx) => {
|
|
1562
|
+
if (sequenceRunner(tx) === void 0) {
|
|
1563
|
+
await this.assertReadableSchema(tx);
|
|
1564
|
+
return body(tx, Promise.resolve());
|
|
1565
|
+
}
|
|
1566
|
+
const checked = this.assertReadableSchema(tx);
|
|
1567
|
+
checked.catch(() => {});
|
|
1568
|
+
const outcome = await body(tx, checked).then((value) => ({ value }), (failure) => ({ failure }));
|
|
1569
|
+
await checked;
|
|
1570
|
+
if ("failure" in outcome) throw outcome.failure;
|
|
1571
|
+
return outcome.value;
|
|
1572
|
+
}, options);
|
|
1573
|
+
}
|
|
1574
|
+
assertReadableSchema(executor) {
|
|
1575
|
+
return assertStoredSchemaVersion(executor, { sql: `SELECT schema_version FROM ${this.tables.meta}` }, "sessions", 2, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1576
|
+
}
|
|
1577
|
+
get descriptor() {
|
|
1578
|
+
return {
|
|
1579
|
+
...this.database.descriptor,
|
|
1580
|
+
...this.prefix === "" ? {} : { prefix: this.prefix }
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
async create(header, entries) {
|
|
1584
|
+
this.assertOpen();
|
|
1585
|
+
validateSessionHeader(header);
|
|
1586
|
+
validateSessionEntries(entries);
|
|
1587
|
+
return this.transactionCheckedAlongside(async (tx, checked) => {
|
|
1588
|
+
if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError$1(header.id);
|
|
1589
|
+
const summary = this.summaryWrite(header.id, {
|
|
1590
|
+
header,
|
|
1591
|
+
entries,
|
|
1592
|
+
lastSeq: entries.length
|
|
1593
|
+
});
|
|
1594
|
+
await checked;
|
|
1595
|
+
await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts));
|
|
1596
|
+
return {
|
|
1597
|
+
lastSeq: entries.length,
|
|
1598
|
+
epoch: summary.epoch
|
|
1599
|
+
};
|
|
1600
|
+
}, SESSION_TRANSACTION);
|
|
1601
|
+
}
|
|
1602
|
+
async createFork(header, entries, source) {
|
|
1603
|
+
if (this.create !== SqlSessionStore.prototype.create) return void 0;
|
|
1604
|
+
if (source.store !== this) {
|
|
1605
|
+
if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
|
|
1606
|
+
if (source.receipts.size < 2) return void 0;
|
|
1607
|
+
return this.createStagedFork(header, { async *read() {
|
|
1608
|
+
for (const entry of entries) yield {
|
|
1609
|
+
entry,
|
|
1610
|
+
reference: source.receipts.get(entry.id)
|
|
1611
|
+
};
|
|
1612
|
+
} }, source);
|
|
1613
|
+
}
|
|
1614
|
+
if ("read" in entries) return this.createStreamedFork(header, entries, source);
|
|
1615
|
+
this.assertOpen();
|
|
1616
|
+
validateSessionHeader(header);
|
|
1617
|
+
validateSessionEntries(entries);
|
|
1618
|
+
return this.transaction(async (tx) => {
|
|
1619
|
+
if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, header.id)) throw new SessionExistsError$1(header.id);
|
|
1620
|
+
const donor = await this.historyHead(tx, source.sessionId);
|
|
1621
|
+
if (source.epoch !== void 0 && donor.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, donor.lastSeq);
|
|
1622
|
+
const { texts, epoch } = await this.saveSummary(tx, header.id, {
|
|
1623
|
+
header,
|
|
1624
|
+
entries,
|
|
1625
|
+
lastSeq: entries.length
|
|
1626
|
+
});
|
|
1627
|
+
await this.insertEntries(tx, header.id, entries, 0, texts);
|
|
1628
|
+
for (const [i, entry] of entries.entries()) {
|
|
1629
|
+
const ref = source.receipts.get(entry.id);
|
|
1630
|
+
if (!ref) continue;
|
|
1631
|
+
if (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
|
|
1632
|
+
const original = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND entry_id=?`, ref.sessionId, ref.seq, entry.id);
|
|
1633
|
+
if (!original) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
|
|
1634
|
+
await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1);
|
|
1635
|
+
await tx.run(`INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id,entry_json,chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1, ref.sessionId, ref.seq);
|
|
1636
|
+
for (let part = 0; part < original.chunks; part++) {
|
|
1637
|
+
const { changes } = await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, header.id, i + 1, ref.sessionId, ref.seq, part);
|
|
1638
|
+
if (changes !== 1) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${ref.seq}`));
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
const remainingBlobs = [];
|
|
1642
|
+
for (const hash of source.hashes) if (!await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.push(hash);
|
|
1643
|
+
return {
|
|
1644
|
+
lastSeq: entries.length,
|
|
1645
|
+
epoch,
|
|
1646
|
+
remainingBlobs
|
|
1647
|
+
};
|
|
1648
|
+
}, SESSION_TRANSACTION);
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Clone a complete session, as `create` with every source entry and blob would, from a store on a handle this one
|
|
1652
|
+
* cannot prove to be its own connection (#5594). The source is read a page at a time into the staging table, never
|
|
1653
|
+
* while a transaction of this store is open, and the child is published in one transaction: see `fork-staging.ts`.
|
|
1654
|
+
* `remainingBlobs` names the blobs left to copy with `copySessionBlobs`: those the source no longer holds.
|
|
1655
|
+
*/
|
|
1656
|
+
async createStagedFork(header, stream, source) {
|
|
1657
|
+
this.assertOpen();
|
|
1658
|
+
validateSessionHeader(header);
|
|
1659
|
+
const { createStagedFork } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1660
|
+
return createStagedFork(this.forkStagingTarget(), header, stream, source);
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Creates the fork staging table unless it exists, as `atomic storage migrate` does as the owner role (#5594): a
|
|
1664
|
+
* runtime role without DDL privileges then stages bounded clones too. Opens never create it.
|
|
1665
|
+
*/
|
|
1666
|
+
async prepareForkStaging() {
|
|
1667
|
+
this.assertOpen();
|
|
1668
|
+
const { cleanupForkStaging, ensureForkStagingTable } = await import("../core/storage/session/fork-staging.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1669
|
+
await ensureForkStagingTable(this.database, this.dialect, this.forkStagingTable);
|
|
1670
|
+
await cleanupForkStaging(this.database, this.dialect, this.forkStagingTable, Number.POSITIVE_INFINITY);
|
|
1671
|
+
}
|
|
1672
|
+
forkStagingTarget() {
|
|
1673
|
+
return {
|
|
1674
|
+
database: this.database,
|
|
1675
|
+
dialect: this.dialect,
|
|
1676
|
+
table: this.forkStagingTable,
|
|
1677
|
+
tables: this.tables,
|
|
1678
|
+
legacyBlobData: this.legacyBlobData,
|
|
1679
|
+
entryChunkBytes: SESSION_ENTRY_CHUNK_BYTES,
|
|
1680
|
+
blobChunkBytes: SESSION_BLOB_CHUNK_BYTES,
|
|
1681
|
+
unchunkedSchemaVersion: SESSION_SCHEMA_VERSION_UNCHUNKED,
|
|
1682
|
+
chunkedSchemaVersion: 2,
|
|
1683
|
+
ownsBlobs: this.getBlob === SqlSessionStore.prototype.getBlob && this.putBlob === SqlSessionStore.prototype.putBlob,
|
|
1684
|
+
transaction: (body) => this.transaction(body, SESSION_TRANSACTION),
|
|
1685
|
+
saveSummary: (tx, header, lastSeq, summary, index) => this.saveSummary(tx, header.id, {
|
|
1686
|
+
header,
|
|
1687
|
+
entries: [],
|
|
1688
|
+
lastSeq
|
|
1689
|
+
}, summary, index),
|
|
1690
|
+
create: (header, entries) => this.create(header, entries),
|
|
1691
|
+
sourceStoredEntryChunks: (source) => {
|
|
1692
|
+
const store = nativeForkReader(source, "entry");
|
|
1693
|
+
return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference, index) => store.readStoredEntryChunk(reference, index) : void 0;
|
|
1694
|
+
},
|
|
1695
|
+
rebuildResume: async (sessionId) => {
|
|
1696
|
+
await this.prepareResume(sessionId);
|
|
1697
|
+
},
|
|
1698
|
+
storedEntry,
|
|
1699
|
+
encode: (value) => this.encode(value),
|
|
1700
|
+
sourceEntryChunks: (source) => {
|
|
1701
|
+
const store = nativeForkReader(source, "entry");
|
|
1702
|
+
return store instanceof SqlSessionStore && store.readEntryChunk === SqlSessionStore.prototype.readEntryChunk ? (reference) => store.readStoredChunks(reference) : void 0;
|
|
1703
|
+
},
|
|
1704
|
+
sourceBlobParts: (source) => {
|
|
1705
|
+
const store = nativeForkReader(source, "blob");
|
|
1706
|
+
return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hash, offset, legacyBytes) => store.readBlobPart(sessionId, hash, offset, legacyBytes) : void 0;
|
|
1707
|
+
}
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
/**
|
|
1711
|
+
* The stored chunk row `index` of the entry `reference` names, whole, in its generation; undefined when the entry is
|
|
1712
|
+
* stored whole. One read where `readEntryChunk` would take one per 64 KiB of it (#5594).
|
|
1713
|
+
*/
|
|
1714
|
+
async readStoredEntryChunk(reference, index) {
|
|
1715
|
+
this.assertOpen();
|
|
1716
|
+
return this.transaction(async (tx) => {
|
|
1717
|
+
const { sessionId, epoch, seq } = reference;
|
|
1718
|
+
const head = await this.historyHead(tx, sessionId);
|
|
1719
|
+
if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
|
|
1720
|
+
const row = await tx.get(`SELECT e.chunks, c.data FROM ${this.tables.entries} e LEFT JOIN ${this.tables.entryChunks} c
|
|
1721
|
+
ON c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ? WHERE e.session_id = ? AND e.seq = ?`, index, sessionId, seq);
|
|
1722
|
+
if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
1723
|
+
if (Number(row.chunks) === 0) return void 0;
|
|
1724
|
+
if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
|
|
1725
|
+
return row.data;
|
|
1726
|
+
}, SESSION_TRANSACTION);
|
|
1727
|
+
}
|
|
1728
|
+
/** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
|
|
1729
|
+
async readStoredChunks(reference) {
|
|
1730
|
+
this.assertOpen();
|
|
1731
|
+
return this.transaction(async (tx) => {
|
|
1732
|
+
const { sessionId, epoch, seq } = reference;
|
|
1733
|
+
const head = await this.historyHead(tx, sessionId);
|
|
1734
|
+
if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
|
|
1735
|
+
const row = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
|
|
1736
|
+
if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
1737
|
+
return Number(row.chunks);
|
|
1738
|
+
}, SESSION_TRANSACTION);
|
|
1739
|
+
}
|
|
1740
|
+
/**
|
|
1741
|
+
* The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
|
|
1742
|
+
* the whole of a large one (#5594): the stored chunk row there, or for a blob in the legacy one-row layout (`chunks`
|
|
1743
|
+
* -1), at most `legacyBytes` cut from its data column by the database, which loads that one value itself for each
|
|
1744
|
+
* cut; with `legacyBytes` 0, only its header. Nothing is converted or written.
|
|
1745
|
+
*/
|
|
1746
|
+
async readBlobPart(sessionId, hash, offset, legacyBytes) {
|
|
1747
|
+
this.assertOpen();
|
|
1748
|
+
const cut = this.legacyBlobData && legacyBytes > 0;
|
|
1749
|
+
const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
|
|
1750
|
+
const row = await this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data FROM ${this.tables.blobs} b LEFT JOIN ${this.tables.blobChunks} c
|
|
1751
|
+
ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ? WHERE b.session_id = ? AND b.hash = ?`, ...cut ? [offset + 1, legacyBytes] : [], Math.floor(offset / SESSION_BLOB_CHUNK_BYTES), sessionId, hash);
|
|
1752
|
+
if (row === void 0) return void 0;
|
|
1753
|
+
return {
|
|
1754
|
+
bytes: Number(row.bytes),
|
|
1755
|
+
chunks: Number(row.chunks),
|
|
1756
|
+
...row.data == null ? {} : { data: row.data }
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
async copyForkBlob(tx, sessionId, childId, hash) {
|
|
1760
|
+
if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return false;
|
|
1761
|
+
const blob = await tx.get(`SELECT bytes,chunks FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, sessionId, hash);
|
|
1762
|
+
if (!blob) return false;
|
|
1763
|
+
if (await tx.get(`SELECT hash FROM ${this.tables.blobs} WHERE session_id=? AND hash=?`, childId, hash)) return true;
|
|
1764
|
+
const columns = this.legacyBlobData ? ", data" : "";
|
|
1765
|
+
const { changes } = await tx.run(`INSERT INTO ${this.tables.blobs} (session_id,hash,bytes,chunks${columns}) SELECT ?,hash,bytes,chunks${columns} FROM ${this.tables.blobs} WHERE session_id=? AND hash=?${this.legacyBlobData ? " AND (chunks<>-1 OR length(data)=bytes)" : ""}`, childId, sessionId, hash);
|
|
1766
|
+
if (changes !== 1 || blob.chunks >= 0 && blob.chunks !== Math.ceil(blob.bytes / 1048576)) throw new SessionBlobError("blob-incomplete", {
|
|
1767
|
+
sessionId,
|
|
1768
|
+
hash,
|
|
1769
|
+
bytes: blob.bytes
|
|
1770
|
+
});
|
|
1771
|
+
for (let part = 0; part < blob.chunks; part++) if ((await tx.run(`INSERT INTO ${this.tables.blobChunks} (session_id,hash,idx,data) SELECT ?,hash,idx,data FROM ${this.tables.blobChunks} WHERE session_id=? AND hash=? AND idx=? AND length(data)=?`, childId, sessionId, hash, part, Math.min(1048576, blob.bytes - part * 1048576))).changes !== 1) throw new SessionBlobError("blob-incomplete", {
|
|
1772
|
+
sessionId,
|
|
1773
|
+
hash,
|
|
1774
|
+
bytes: blob.bytes
|
|
1775
|
+
});
|
|
1776
|
+
return true;
|
|
1777
|
+
}
|
|
1778
|
+
async createStreamedFork(header, stream, source) {
|
|
1779
|
+
this.assertOpen();
|
|
1780
|
+
validateSessionHeader(header);
|
|
1781
|
+
const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1782
|
+
const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1783
|
+
return this.transaction(async (tx) => {
|
|
1784
|
+
if (await tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id=?`, header.id)) throw new SessionExistsError$1(header.id);
|
|
1785
|
+
const head = await this.historyHead(tx, source.sessionId);
|
|
1786
|
+
if (source.epoch !== void 0 && head.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, head.lastSeq);
|
|
1787
|
+
const reader = new SqlSessionStore({
|
|
1788
|
+
descriptor: this.database.descriptor,
|
|
1789
|
+
dialect: this.dialect,
|
|
1790
|
+
readOnly: true,
|
|
1791
|
+
exec: tx.exec.bind(tx),
|
|
1792
|
+
get: tx.get.bind(tx),
|
|
1793
|
+
run: tx.run.bind(tx),
|
|
1794
|
+
all: tx.all.bind(tx),
|
|
1795
|
+
transaction: async (cb) => cb(tx),
|
|
1796
|
+
close: async () => {}
|
|
1797
|
+
}, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
|
|
1798
|
+
const { index: donorIndex } = await reader.prepareResume(source.sessionId);
|
|
1799
|
+
reader.readBranchSpan = async (id, cut) => transcriptBranchSpan(id, donorIndex, cut);
|
|
1800
|
+
const lookup = (id) => this.seqOfEntry(tx, header.id, id);
|
|
1801
|
+
let summary = applySessionSummaryEntries(void 0, []).state;
|
|
1802
|
+
let index = foldSessionResume(void 0, []);
|
|
1803
|
+
let seq = 0;
|
|
1804
|
+
const remainingBlobs = /* @__PURE__ */ new Set();
|
|
1805
|
+
const inlineSnapshot = async (ref) => {
|
|
1806
|
+
const text = (key) => this.dialect.jsonText("entry_json", key);
|
|
1807
|
+
const ty = (key) => this.dialect.jsonType("entry_json", key);
|
|
1808
|
+
const s = await tx.get(`SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND chunks=0 AND ${text("type")}='worktree_snapshot'`, ref.sessionId, ref.seq);
|
|
1809
|
+
if (!s) return void 0;
|
|
1810
|
+
return {
|
|
1811
|
+
type: "worktree_snapshot",
|
|
1812
|
+
id: s.id,
|
|
1813
|
+
parentId: s.parent,
|
|
1814
|
+
timestamp: s.stamp,
|
|
1815
|
+
root: s.root,
|
|
1816
|
+
snapshotId: s.snapshot,
|
|
1817
|
+
...s.capture !== null ? { captureMs: Number(s.capture) } : {},
|
|
1818
|
+
...s.record === "object" ? { snapshot: {} } : {},
|
|
1819
|
+
...s.restore === "object" ? { restore: {} } : {},
|
|
1820
|
+
...s.unrestored === "object" ? { unrestored: {} } : {},
|
|
1821
|
+
...s.degraded ? { degradedFrom: s.degraded } : {}
|
|
1822
|
+
};
|
|
1823
|
+
};
|
|
1824
|
+
for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
|
|
1825
|
+
index = await foldForkRow(index, row, lookup);
|
|
1826
|
+
const entry = row.entry;
|
|
1827
|
+
const listed = applySessionSummaryEntries(summary, [entry]);
|
|
1828
|
+
summary = listed.state;
|
|
1829
|
+
if (entry.type === "custom" && entry.customType === "atomic.tool-output") {
|
|
1830
|
+
const hash = entry.data?.hash;
|
|
1831
|
+
if (typeof hash === "string" && !remainingBlobs.has(hash) && !await this.copyForkBlob(tx, source.sessionId, header.id, hash)) remainingBlobs.add(hash);
|
|
1832
|
+
}
|
|
1833
|
+
if (!row.reference) await this.insertEntries(tx, header.id, [entry], seq, listed.texts);
|
|
1834
|
+
else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
|
|
1835
|
+
else {
|
|
1836
|
+
const encoded = await encodedForkRow(reader, row);
|
|
1837
|
+
const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
|
|
1838
|
+
await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
|
|
1839
|
+
type: entry.type,
|
|
1840
|
+
id: entry.id,
|
|
1841
|
+
parentId: entry.parentId ?? null
|
|
1842
|
+
}), chunks);
|
|
1843
|
+
let n = 0;
|
|
1844
|
+
let used = 0;
|
|
1845
|
+
let buffer = new Uint8Array(SESSION_ENTRY_CHUNK_BYTES);
|
|
1846
|
+
const write = async () => {
|
|
1847
|
+
await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id,seq,idx,data) VALUES (?,?,?,?)`, header.id, seq + 1, n++, buffer.subarray(0, used));
|
|
1848
|
+
used = 0;
|
|
1849
|
+
};
|
|
1850
|
+
for await (const part of encoded.chunks()) for (let start = 0; start < part.length;) {
|
|
1851
|
+
const count = Math.min(part.length - start, buffer.length - used);
|
|
1852
|
+
buffer.set(part.subarray(start, start + count), used);
|
|
1853
|
+
start += count;
|
|
1854
|
+
used += count;
|
|
1855
|
+
if (used === buffer.length) await write();
|
|
1856
|
+
}
|
|
1857
|
+
if (used) await write();
|
|
1858
|
+
if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
|
|
1859
|
+
for (const { text } of listed.texts) await tx.run(`INSERT INTO ${this.tables.searchTexts} (session_id,seq,text_json) VALUES (?,?,?)`, header.id, seq + 1, this.encode(text));
|
|
1860
|
+
await tx.run(`UPDATE ${this.tables.meta} SET schema_version=? WHERE schema_version=?`, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1861
|
+
}
|
|
1862
|
+
seq++;
|
|
1863
|
+
}
|
|
1864
|
+
const { epoch } = await this.saveSummary(tx, header.id, {
|
|
1865
|
+
header,
|
|
1866
|
+
entries: [],
|
|
1867
|
+
lastSeq: seq
|
|
1868
|
+
}, summary, index);
|
|
1869
|
+
return {
|
|
1870
|
+
lastSeq: seq,
|
|
1871
|
+
epoch,
|
|
1872
|
+
remainingBlobs: [...remainingBlobs]
|
|
1873
|
+
};
|
|
1874
|
+
}, SESSION_TRANSACTION);
|
|
1875
|
+
}
|
|
1876
|
+
/** Keep the legacy inline payload outside the iterator's yielded value and the caller's async frame:
|
|
1877
|
+
* neither may retain this row while the next SQLite result is being delivered. */
|
|
1878
|
+
async writeInlineForkSnapshot(tx, reader, ref, child, seq, texts, edits) {
|
|
1879
|
+
const original = (await reader.readRange(ref.sessionId, ref.seq, ref.seq, ref.epoch)).entries[0];
|
|
1880
|
+
if (original?.type !== "worktree_snapshot") throw new SessionConflictError$1(ref.sessionId, ref.seq, seq);
|
|
1881
|
+
await this.insertEntries(tx, child, [edits ? {
|
|
1882
|
+
...original,
|
|
1883
|
+
...edits
|
|
1884
|
+
} : original], seq, texts);
|
|
1885
|
+
}
|
|
1886
|
+
async append(sessionId, entries, options) {
|
|
1887
|
+
this.assertOpen();
|
|
1888
|
+
validateSessionText("sessionId", sessionId);
|
|
1889
|
+
return this.transactionCheckedAlongside(async (tx, checked) => {
|
|
1890
|
+
const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true);
|
|
1891
|
+
validateSessionEntries(entries);
|
|
1892
|
+
await this.blobTable.assertStored(tx, entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
|
|
1893
|
+
const lastSeq = previous.last_seq + entries.length;
|
|
1894
|
+
const summary = this.summaryWrite(sessionId, {
|
|
1895
|
+
header: JSON.parse(previous.header_json),
|
|
1896
|
+
entries,
|
|
1897
|
+
lastSeq
|
|
1898
|
+
}, summaryState, await this.appendedResume(tx, sessionId, windowIndex(summaryState, previous.last_seq), previous.last_seq, entries));
|
|
1899
|
+
const written = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts);
|
|
1900
|
+
await checked;
|
|
1901
|
+
await this.writeEntries(tx, summary.statement, written);
|
|
1902
|
+
return { lastSeq };
|
|
1903
|
+
}, SESSION_TRANSACTION);
|
|
1904
|
+
}
|
|
1905
|
+
async replace(sessionId, header, entries, options) {
|
|
1906
|
+
this.assertOpen();
|
|
1907
|
+
validateSessionText("sessionId", sessionId);
|
|
1908
|
+
return this.transaction(async (tx) => {
|
|
1909
|
+
await this.forWrite(tx, sessionId, options);
|
|
1910
|
+
validateSessionHeader(header);
|
|
1911
|
+
validateSessionEntries(entries);
|
|
1912
|
+
if (header.id !== sessionId) throw new SessionIdMismatchError$1(sessionId, header.id);
|
|
1913
|
+
await this.searchIndex?.forgetWithin(tx, sessionId);
|
|
1914
|
+
await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
|
|
1915
|
+
await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
|
|
1916
|
+
await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
|
|
1917
|
+
const { texts, epoch } = await this.saveSummary(tx, sessionId, {
|
|
1918
|
+
header,
|
|
1919
|
+
entries,
|
|
1920
|
+
lastSeq: entries.length
|
|
1921
|
+
});
|
|
1922
|
+
await this.insertEntries(tx, sessionId, entries, 0, texts);
|
|
1923
|
+
return {
|
|
1924
|
+
lastSeq: entries.length,
|
|
1925
|
+
epoch
|
|
1926
|
+
};
|
|
1927
|
+
}, SESSION_TRANSACTION);
|
|
1928
|
+
}
|
|
1929
|
+
async updateHeader(header, options) {
|
|
1930
|
+
this.assertOpen();
|
|
1931
|
+
validateSessionHeader(header);
|
|
1932
|
+
return this.transaction(async (tx) => {
|
|
1933
|
+
const { row, state } = await this.forWrite(tx, header.id, options, true);
|
|
1934
|
+
const epoch = newRevision();
|
|
1935
|
+
const resume = windowIndex(state, row.last_seq);
|
|
1936
|
+
await this.saveSummary(tx, header.id, {
|
|
1937
|
+
header,
|
|
1938
|
+
entries: [],
|
|
1939
|
+
lastSeq: row.last_seq
|
|
1940
|
+
}, {
|
|
1941
|
+
...state,
|
|
1942
|
+
epoch
|
|
1943
|
+
}, resume && {
|
|
1944
|
+
...resume,
|
|
1945
|
+
epoch
|
|
1946
|
+
});
|
|
1947
|
+
return {
|
|
1948
|
+
lastSeq: row.last_seq,
|
|
1949
|
+
epoch
|
|
1950
|
+
};
|
|
1951
|
+
}, SESSION_TRANSACTION);
|
|
1952
|
+
}
|
|
1953
|
+
async load(sessionId) {
|
|
1954
|
+
this.assertOpen();
|
|
1955
|
+
validateSessionText("sessionId", sessionId);
|
|
1956
|
+
if (hasHistoryLoadObserver()) {
|
|
1957
|
+
const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
1958
|
+
if (row) announceHistoryLoad(row.last_seq);
|
|
1959
|
+
}
|
|
1960
|
+
return this.transaction((tx) => this.read(tx, sessionId), SESSION_TRANSACTION);
|
|
1961
|
+
}
|
|
1962
|
+
async readEntryRange(sessionId, query) {
|
|
1963
|
+
this.assertOpen();
|
|
1964
|
+
validateSessionText("sessionId", sessionId);
|
|
1965
|
+
query.signal?.throwIfAborted();
|
|
1966
|
+
const session = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
1967
|
+
if (!session) throw new SessionNotFoundError$1(sessionId);
|
|
1968
|
+
const lastSeq = Number(session.last_seq);
|
|
1969
|
+
const fromSeq = Math.max(1, query.fromSeq);
|
|
1970
|
+
const toSeq = Math.min(query.toSeq, lastSeq);
|
|
1971
|
+
if (fromSeq > toSeq) return {
|
|
1972
|
+
lastSeq,
|
|
1973
|
+
entries: [],
|
|
1974
|
+
throughSeq: Math.max(toSeq, fromSeq - 1)
|
|
1975
|
+
};
|
|
1976
|
+
if (query.maxChars !== void 0 && query.maxChars <= 0) return {
|
|
1977
|
+
lastSeq,
|
|
1978
|
+
entries: [],
|
|
1979
|
+
throughSeq: fromSeq - 1
|
|
1980
|
+
};
|
|
1981
|
+
const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
|
|
1982
|
+
const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
|
|
1983
|
+
const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
|
|
1984
|
+
const rows = await this.database.all(`WITH sized AS (
|
|
1985
|
+
SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
|
|
1986
|
+
${this.entryByteLength("entry_json")} + chunks * ? AS bytes
|
|
1987
|
+
FROM ${this.tables.entries}
|
|
1988
|
+
WHERE session_id = ? AND seq >= ? AND seq <= ?
|
|
1989
|
+
),
|
|
1990
|
+
paged AS (
|
|
1991
|
+
SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
|
|
1992
|
+
sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
|
|
1993
|
+
FROM sized
|
|
1994
|
+
)
|
|
1995
|
+
SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
|
|
1996
|
+
substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
|
|
1997
|
+
CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
|
|
1998
|
+
THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
|
|
1999
|
+
FROM paged p
|
|
2000
|
+
JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
|
|
2001
|
+
WHERE p.before_chars < ?
|
|
2002
|
+
ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, toSeq, largeBytes, largeBytes, sessionId, query.maxChars ?? Number.MAX_SAFE_INTEGER);
|
|
2003
|
+
const entries = [];
|
|
2004
|
+
for (const row of rows) {
|
|
2005
|
+
query.signal?.throwIfAborted();
|
|
2006
|
+
if (skippedPrefixes.some((prefix) => row.entry_head.startsWith(prefix))) continue;
|
|
2007
|
+
const seq = Number(row.seq);
|
|
2008
|
+
const chunks = Number(row.chunks);
|
|
2009
|
+
if (chunks > 0) {
|
|
2010
|
+
const rawChunks = await this.readRawEntryChunks(this.database, sessionId, seq, chunks, query.signal);
|
|
2011
|
+
if (rawChunks.reduce((total, chunk) => total + chunk.byteLength, 0) > largeBytes) entries.push({
|
|
2012
|
+
seq,
|
|
2013
|
+
entry: STUB_ENTRY,
|
|
2014
|
+
rawChunks
|
|
2015
|
+
});
|
|
2016
|
+
else {
|
|
2017
|
+
const parsed = JSON.parse(Buffer.concat(rawChunks).toString("utf8"));
|
|
2018
|
+
if (!skippedSet?.has(parsed.type)) entries.push({
|
|
2019
|
+
seq,
|
|
2020
|
+
entry: parsed
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
} else if (row.entry_json === null) {
|
|
2024
|
+
if (row.entry_type !== null && skippedSet?.has(row.entry_type)) continue;
|
|
2025
|
+
const rawChunks = await this.readInlineEntryBytes(sessionId, seq);
|
|
2026
|
+
entries.push({
|
|
2027
|
+
seq,
|
|
2028
|
+
entry: STUB_ENTRY,
|
|
2029
|
+
rawChunks
|
|
2030
|
+
});
|
|
2031
|
+
} else {
|
|
2032
|
+
const parsed = JSON.parse(row.entry_json);
|
|
2033
|
+
if (!skippedSet?.has(parsed.type)) entries.push({
|
|
2034
|
+
seq,
|
|
2035
|
+
entry: parsed
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
const last = rows.at(-1);
|
|
2040
|
+
return {
|
|
2041
|
+
lastSeq,
|
|
2042
|
+
entries,
|
|
2043
|
+
throughSeq: last !== void 0 && rows.length < Number(last.remaining) ? Number(last.seq) : toSeq
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
async readHeader(sessionId) {
|
|
2047
|
+
this.assertOpen();
|
|
2048
|
+
validateSessionText("sessionId", sessionId);
|
|
2049
|
+
const row = await this.database.get(`SELECT header_json FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2050
|
+
return row ? JSON.parse(row.header_json) : void 0;
|
|
2051
|
+
}
|
|
2052
|
+
async delete(sessionId) {
|
|
2053
|
+
this.assertOpen();
|
|
2054
|
+
validateSessionText("sessionId", sessionId);
|
|
2055
|
+
await this.transaction(async (tx) => {
|
|
2056
|
+
await this.searchIndex?.forgetWithin(tx, sessionId);
|
|
2057
|
+
await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
|
|
2058
|
+
await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
|
|
2059
|
+
await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
|
|
2060
|
+
await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
|
|
2061
|
+
await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
|
|
2062
|
+
await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2063
|
+
}, SESSION_TRANSACTION);
|
|
2064
|
+
}
|
|
2065
|
+
/**
|
|
2066
|
+
* Stores the blob as rows of at most {@link SESSION_BLOB_CHUNK_BYTES}, then publishes its header. Every statement
|
|
2067
|
+
* commits by itself and writes only while the session exists, so no transaction stays open across round trips and
|
|
2068
|
+
* `delete`, which removes a session's rows in one transaction, leaves none behind. A blob is readable only once its
|
|
2069
|
+
* header is there, so a writer that stops part way leaves rows of its own session that `delete` removes, and storing
|
|
2070
|
+
* the same bytes again completes or skips them. Bytes a session already holds are not sent again.
|
|
2071
|
+
*/
|
|
2072
|
+
async putBlob(sessionId, data) {
|
|
2073
|
+
this.assertOpen();
|
|
2074
|
+
validateSessionText("sessionId", sessionId);
|
|
2075
|
+
const stored = Uint8Array.from(data);
|
|
2076
|
+
const blob = {
|
|
2077
|
+
hash: await sha256Hex(stored),
|
|
2078
|
+
bytes: stored.byteLength
|
|
2079
|
+
};
|
|
2080
|
+
const previous = await this.blobHeader(sessionId, blob.hash);
|
|
2081
|
+
if (previous) {
|
|
2082
|
+
if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored))) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
2083
|
+
return blob;
|
|
2084
|
+
}
|
|
2085
|
+
const chunks = Math.ceil(blob.bytes / SESSION_BLOB_CHUNK_BYTES);
|
|
2086
|
+
const { sessions, blobs, blobChunks } = this.tables;
|
|
2087
|
+
const sessionExists = `EXISTS (SELECT 1 FROM ${sessions} WHERE id = ?)`;
|
|
2088
|
+
for (let index = 0; index < chunks; index++) await this.database.run(`INSERT INTO ${blobChunks} (session_id, hash, idx, data) SELECT ?, ?, ?, ? WHERE ${sessionExists}
|
|
2089
|
+
ON CONFLICT DO NOTHING`, sessionId, blob.hash, index, stored.subarray(index * SESSION_BLOB_CHUNK_BYTES, (index + 1) * SESSION_BLOB_CHUNK_BYTES), sessionId);
|
|
2090
|
+
const { changes } = await this.database.run(`INSERT INTO ${blobs} (session_id, hash, bytes, chunks${this.legacyBlobData ? ", data" : ""})
|
|
2091
|
+
SELECT ?, ?, ?, ?${this.legacyBlobData ? ", X''" : ""}
|
|
2092
|
+
WHERE ${sessionExists} AND (SELECT count(*) FROM ${blobChunks} WHERE session_id = ? AND hash = ?) = ?
|
|
2093
|
+
ON CONFLICT DO NOTHING`, sessionId, blob.hash, blob.bytes, chunks, sessionId, sessionId, blob.hash, chunks);
|
|
2094
|
+
if (changes === 0 && !await this.blobHeader(sessionId, blob.hash)) throw new SessionNotFoundError$1(sessionId);
|
|
2095
|
+
return blob;
|
|
2096
|
+
}
|
|
2097
|
+
/**
|
|
2098
|
+
* Reads chunked blobs a row at a time, each returning at most {@link SESSION_BLOB_CHUNK_BYTES}. Legacy blobs
|
|
2099
|
+
* are read in one query: slicing their data column repeatedly would reread the entire BLOB for every chunk.
|
|
2100
|
+
* Rows never change once written. A session deleted meanwhile holds nothing; missing bytes are `blob-incomplete`.
|
|
2101
|
+
*/
|
|
2102
|
+
async getBlob(sessionId, hash) {
|
|
2103
|
+
this.assertOpen();
|
|
2104
|
+
validateSessionText("sessionId", sessionId);
|
|
2105
|
+
let header = await this.blobHeader(sessionId, hash);
|
|
2106
|
+
if (header === void 0) return void 0;
|
|
2107
|
+
if (header.chunks === -1) {
|
|
2108
|
+
const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, sessionId, hash);
|
|
2109
|
+
if (row) {
|
|
2110
|
+
if (row.data.byteLength === header.bytes) return row.data;
|
|
2111
|
+
throw new SessionBlobError("blob-incomplete", {
|
|
2112
|
+
sessionId,
|
|
2113
|
+
hash,
|
|
2114
|
+
bytes: header.bytes
|
|
2115
|
+
});
|
|
2116
|
+
}
|
|
2117
|
+
header = await this.blobHeader(sessionId, hash);
|
|
2118
|
+
if (header === void 0) return void 0;
|
|
2119
|
+
}
|
|
2120
|
+
const data = new Uint8Array(header.bytes);
|
|
2121
|
+
let offset = 0;
|
|
2122
|
+
for (let index = 0; index < header.chunks; index++) {
|
|
2123
|
+
const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, sessionId, hash);
|
|
2124
|
+
if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
|
|
2125
|
+
data.set(row.data, offset);
|
|
2126
|
+
offset += row.data.byteLength;
|
|
2127
|
+
}
|
|
2128
|
+
if (offset === data.byteLength) return data;
|
|
2129
|
+
if (await this.blobHeader(sessionId, hash) === void 0) return void 0;
|
|
2130
|
+
throw new SessionBlobError("blob-incomplete", {
|
|
2131
|
+
sessionId,
|
|
2132
|
+
hash,
|
|
2133
|
+
bytes: header.bytes
|
|
2134
|
+
});
|
|
2135
|
+
}
|
|
2136
|
+
async blobHeader(sessionId, hash) {
|
|
2137
|
+
const row = await this.database.get(`SELECT bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?`, sessionId, hash);
|
|
2138
|
+
return row === void 0 ? void 0 : {
|
|
2139
|
+
bytes: Number(row.bytes),
|
|
2140
|
+
chunks: Number(row.chunks)
|
|
2141
|
+
};
|
|
2142
|
+
}
|
|
2143
|
+
/**
|
|
2144
|
+
* Lists from a per-scope cache revalidated on every call. A cheap change token, which moves on any commit
|
|
2145
|
+
* from this or another connection, decides whether the scope is re-read. A scope listed for the first time
|
|
2146
|
+
* is read exactly as an uncached listing; afterwards only its light columns are re-read and search text is
|
|
2147
|
+
* read only for sessions whose stored listing columns changed. Listings of the same store take turns
|
|
2148
|
+
* reading and updating the caches; the yielding below runs outside that turn.
|
|
2149
|
+
*/
|
|
2150
|
+
async *list(query) {
|
|
2151
|
+
this.assertListing(query);
|
|
2152
|
+
if (query.cwd?.includes("\0")) throw new StorageInvalidTextError(0);
|
|
2153
|
+
if (query.withoutSearchText) {
|
|
2154
|
+
for await (const summary of this.listWithoutSearchText(query)) {
|
|
2155
|
+
this.assertListing(query);
|
|
2156
|
+
yield summary;
|
|
2157
|
+
}
|
|
2158
|
+
this.assertListing(query);
|
|
2159
|
+
return;
|
|
2160
|
+
}
|
|
2161
|
+
const listed = this.listing.then(() => this.listScope(query));
|
|
2162
|
+
this.listing = listed.then(() => {}, () => {});
|
|
2163
|
+
const summaries = await listed;
|
|
2164
|
+
for (const summary of summaries) {
|
|
2165
|
+
this.assertListing(query);
|
|
2166
|
+
yield summary;
|
|
2167
|
+
}
|
|
2168
|
+
this.assertListing(query);
|
|
2169
|
+
}
|
|
2170
|
+
/** Revalidates one scope's cache and resolves its summaries; called for one listing at a time. */
|
|
2171
|
+
async listScope(query) {
|
|
2172
|
+
this.assertListing(query);
|
|
2173
|
+
await this.assertReadableSchema(this.database);
|
|
2174
|
+
const token = await this.changeToken();
|
|
2175
|
+
const key = JSON.stringify([
|
|
2176
|
+
query.includeInternal === true,
|
|
2177
|
+
query.cwd ?? null,
|
|
2178
|
+
query.idPrefix?.toLowerCase() ?? null
|
|
2179
|
+
]);
|
|
2180
|
+
const cached = this.scopes.get(key);
|
|
2181
|
+
const scope = token !== void 0 && cached?.token === token && cached.ids.every((id) => this.summaries.has(id)) ? cached : {
|
|
2182
|
+
token,
|
|
2183
|
+
ids: await this.readScope(query, cached !== void 0)
|
|
2184
|
+
};
|
|
2185
|
+
this.scopes.delete(key);
|
|
2186
|
+
this.scopes.set(key, scope);
|
|
2187
|
+
for (const oldest of this.scopes.keys()) {
|
|
2188
|
+
if (this.scopes.size <= LISTING_SCOPES) break;
|
|
2189
|
+
this.scopes.delete(oldest);
|
|
2190
|
+
}
|
|
2191
|
+
if (scope !== cached) this.pruneSummaries();
|
|
2192
|
+
return scope.ids.flatMap((id) => this.summaries.get(id)?.summary ?? []);
|
|
2193
|
+
}
|
|
2194
|
+
async findMostRecent(query) {
|
|
2195
|
+
let latest;
|
|
2196
|
+
for await (const summary of this.list(query)) if (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt)) latest = summary;
|
|
2197
|
+
return latest;
|
|
2198
|
+
}
|
|
2199
|
+
async close() {
|
|
2200
|
+
this.assertOpen();
|
|
2201
|
+
this.closed = true;
|
|
2202
|
+
this.scopes.clear();
|
|
2203
|
+
this.summaries.clear();
|
|
2204
|
+
}
|
|
2205
|
+
/**
|
|
2206
|
+
* `data_version` moves when another connection commits and `total_changes()` when this one writes, so
|
|
2207
|
+
* together they cover writers in every process, but only on one connection: Atomic's own SQLite adapter serves
|
|
2208
|
+
* every statement from one. Over an adapter that may not, such as a libSQL server whose every HTTP request is a
|
|
2209
|
+
* new stream, neither moves, and no column of the sessions table changes on every write by every version, so
|
|
2210
|
+
* there is no token and each listing revalidates its scope (#4805).
|
|
2211
|
+
*/
|
|
2212
|
+
async changeToken() {
|
|
2213
|
+
if (this.database.descriptor.adapter !== "node-sqlite") return void 0;
|
|
2214
|
+
const { changeMarkers, rowOrder } = this.dialect;
|
|
2215
|
+
const row = await this.database.get(`SELECT ${changeMarkers.columns},
|
|
2216
|
+
(SELECT count(*) FROM ${this.tables.sessions}) AS sessions,
|
|
2217
|
+
(SELECT max(${rowOrder()}) FROM ${this.tables.sessions}) AS last_row
|
|
2218
|
+
${changeMarkers.from}`);
|
|
2219
|
+
return JSON.stringify(Object.values(row ?? {}).map(String));
|
|
2220
|
+
}
|
|
2221
|
+
async *listWithoutSearchText(query) {
|
|
2222
|
+
await this.assertReadableSchema(this.database);
|
|
2223
|
+
const scope = await this.scopeOf(query, true);
|
|
2224
|
+
if (scope === void 0) return;
|
|
2225
|
+
const order = this.dialect.rowOrder();
|
|
2226
|
+
const bound = await this.database.get(`SELECT max(${order}) AS upper FROM ${this.tables.sessions}`);
|
|
2227
|
+
const upper = Number(bound?.upper ?? 0);
|
|
2228
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2229
|
+
const scanRows = this.listingScanRows(SESSION_READ_FETCH.max);
|
|
2230
|
+
for (let after = 0, limit = Math.min(scanRows, SESSION_READ_FETCH.first); after < upper;) {
|
|
2231
|
+
this.assertListing(query);
|
|
2232
|
+
const rows = await this.database.all(`WITH scanned AS MATERIALIZED (
|
|
2233
|
+
SELECT ${order} AS ord, CASE WHEN ${scope.where} THEN ${LISTING_SIZE} END AS size
|
|
2234
|
+
FROM ${this.tables.sessions} WHERE ${order} > ? AND ${order} <= ?
|
|
2235
|
+
ORDER BY ${order} LIMIT ?
|
|
2236
|
+
), keyed AS MATERIALIZED (
|
|
2237
|
+
SELECT ord, row_number() OVER (ORDER BY ord) AS key_row, size FROM scanned
|
|
2238
|
+
), bound AS (SELECT max(ord) AS upto FROM keyed),
|
|
2239
|
+
page AS (
|
|
2240
|
+
SELECT ord, key_row, count(*) OVER () AS fetched,
|
|
2241
|
+
row_number() OVER (ORDER BY ord) AS page_row,
|
|
2242
|
+
sum(size) OVER () AS batch_chars,
|
|
2243
|
+
sum(size) OVER (ORDER BY ord) AS page_chars
|
|
2244
|
+
FROM keyed WHERE size IS NOT NULL
|
|
2245
|
+
), kept AS MATERIALIZED (
|
|
2246
|
+
SELECT ord, key_row, fetched, batch_chars, page_chars FROM page
|
|
2247
|
+
WHERE page_chars <= ? OR page_row = 1
|
|
2248
|
+
)
|
|
2249
|
+
SELECT bound.upto, kept.ord, kept.key_row, kept.fetched, kept.batch_chars, kept.page_chars,
|
|
2250
|
+
${LISTING_SELECT_COLUMNS}
|
|
2251
|
+
FROM bound
|
|
2252
|
+
LEFT JOIN kept ON 1 = 1
|
|
2253
|
+
LEFT JOIN ${this.tables.sessions} AS s ON ${this.dialect.rowOrder("s")} = kept.ord
|
|
2254
|
+
ORDER BY kept.ord`, ...scope.params, after, upper, limit, SESSION_READ_PAGE_CHARS);
|
|
2255
|
+
const upto = rows[0]?.upto;
|
|
2256
|
+
if (upto === null || upto === void 0) break;
|
|
2257
|
+
const listed = rows.filter((row) => row.ord !== null);
|
|
2258
|
+
for (const row of listed) if (!seen.has(row.id) && await scope.inScope(row)) {
|
|
2259
|
+
seen.add(row.id);
|
|
2260
|
+
yield summaryFromRow({
|
|
2261
|
+
...row,
|
|
2262
|
+
search_texts_json: "[]"
|
|
2263
|
+
});
|
|
2264
|
+
}
|
|
2265
|
+
const last = listed.at(-1);
|
|
2266
|
+
const clipped = last !== void 0 && listed.length < Number(last.fetched);
|
|
2267
|
+
after = clipped ? Number(last.ord) : Number(upto);
|
|
2268
|
+
const batchChars = Number(listed[0]?.batch_chars ?? 0);
|
|
2269
|
+
const pageChars = Number(last?.page_chars ?? 0);
|
|
2270
|
+
const next = !clipped ? limit * 4 : batchChars - pageChars <= 4194304 ? limit : Math.max(SESSION_READ_FETCH.min, Number(last.key_row) * 2);
|
|
2271
|
+
limit = Math.min(scanRows, next);
|
|
2272
|
+
await yieldTurn();
|
|
2273
|
+
}
|
|
2274
|
+
this.assertListing(query);
|
|
2275
|
+
}
|
|
2276
|
+
async distinctCwds(paced, query) {
|
|
2277
|
+
if (!paced) return (await this.database.all(`SELECT DISTINCT cwd FROM ${this.tables.sessions}`)).map((project) => project.cwd);
|
|
2278
|
+
const order = this.dialect.rowOrder();
|
|
2279
|
+
const page = this.listingScanRows(LISTING_CWD_PAGE);
|
|
2280
|
+
const cwds = /* @__PURE__ */ new Set();
|
|
2281
|
+
for (let after = 0;;) {
|
|
2282
|
+
this.assertListing(query);
|
|
2283
|
+
const rows = await this.database.all(`SELECT ${order} AS ord, cwd FROM ${this.tables.sessions} WHERE ${order} > ? ORDER BY ${order} LIMIT ?`, after, page);
|
|
2284
|
+
for (const row of rows) cwds.add(row.cwd);
|
|
2285
|
+
await yieldTurn();
|
|
2286
|
+
if (rows.length < page) return [...cwds];
|
|
2287
|
+
after = Number(rows.at(-1).ord);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
/** The most sessions one statement of a paced listing scans: fewer when the statement holds the event loop. */
|
|
2291
|
+
listingScanRows(overServer) {
|
|
2292
|
+
return this.database.descriptor.adapter === "node-sqlite" ? LISTING_SCAN_ROWS : overServer;
|
|
2293
|
+
}
|
|
2294
|
+
async scopeOf(query, paced) {
|
|
2295
|
+
const matchesCwd = query.cwd === void 0 ? void 0 : this.cwdMatcher?.(query.cwd) ?? ((candidate) => candidate === query.cwd);
|
|
2296
|
+
let projectCwds;
|
|
2297
|
+
if (matchesCwd) {
|
|
2298
|
+
const distinct = await this.distinctCwds(paced, query);
|
|
2299
|
+
const slice = paced ? LISTING_CWD_MATCHES : Math.max(1, distinct.length);
|
|
2300
|
+
projectCwds = [];
|
|
2301
|
+
for (let start = 0; start < distinct.length; start += slice) {
|
|
2302
|
+
const matched = await Promise.all(distinct.slice(start, start + slice).map(async (cwd) => await matchesCwd(cwd) ? cwd : void 0));
|
|
2303
|
+
for (const cwd of matched) if (cwd !== void 0) projectCwds.push(cwd);
|
|
2304
|
+
if (paced && start + slice < distinct.length) {
|
|
2305
|
+
this.assertListing(query);
|
|
2306
|
+
await yieldTurn();
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
this.assertListing(query);
|
|
2310
|
+
if (projectCwds.length === 0) return void 0;
|
|
2311
|
+
}
|
|
2312
|
+
const idPrefix = query.idPrefix?.toLowerCase();
|
|
2313
|
+
return {
|
|
2314
|
+
where: `(? = 1 OR internal = 0)${projectCwds ? ` AND cwd IN (${projectCwds.map(() => "?").join(", ")})` : ""}${idPrefix === void 0 ? "" : " AND substr(lower(id), 1, ?) = ?"}`,
|
|
2315
|
+
params: [
|
|
2316
|
+
query.includeInternal ? 1 : 0,
|
|
2317
|
+
...projectCwds ?? [],
|
|
2318
|
+
...idPrefix === void 0 ? [] : [idPrefix.length, idPrefix]
|
|
2319
|
+
],
|
|
2320
|
+
inScope: (row) => !matchesCwd || matchesCwd(row.cwd)
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
/** The scope's session ids in store order, with a current summary cached for each. */
|
|
2324
|
+
async readScope(query, listedBefore) {
|
|
2325
|
+
const resolved = await this.scopeOf(query, false);
|
|
2326
|
+
if (resolved === void 0) return [];
|
|
2327
|
+
const { where: scope, params, inScope } = resolved;
|
|
2328
|
+
const filterInScope = async (rows) => {
|
|
2329
|
+
return (await Promise.all(rows.map(async (row) => await inScope(row) ? row : void 0))).filter((row) => row !== void 0);
|
|
2330
|
+
};
|
|
2331
|
+
if (listedBefore) {
|
|
2332
|
+
const rows = await filterInScope(await this.readListingRows(scope, params));
|
|
2333
|
+
this.assertListing(query);
|
|
2334
|
+
const stale = rows.filter((row) => this.summaries.get(row.id)?.version !== listingVersion(row));
|
|
2335
|
+
if (stale.length <= rows.length / 4) {
|
|
2336
|
+
for (let start = 0; start < stale.length; start += 500) {
|
|
2337
|
+
const ids = stale.slice(start, start + 500).map((row) => row.id);
|
|
2338
|
+
const fetched = new Set((await this.readSummaries(`id IN (${ids.map(() => "?").join(", ")})`, ids)).map((row) => row.id));
|
|
2339
|
+
for (const id of ids) if (!fetched.has(id)) this.summaries.delete(id);
|
|
2340
|
+
this.assertListing(query);
|
|
2341
|
+
}
|
|
2342
|
+
return rows.flatMap((row) => this.summaries.has(row.id) ? [row.id] : []);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
const rows = await filterInScope(await this.readSummaries(scope, params));
|
|
2346
|
+
this.assertListing(query);
|
|
2347
|
+
return rows.map((row) => row.id);
|
|
2348
|
+
}
|
|
2349
|
+
/**
|
|
2350
|
+
* The listing rows `where` selects, without search text, in store order, a page per statement: each fetches the next
|
|
2351
|
+
* {@link SESSION_READ_FETCH} rows by key and returns those whose cumulative text fits in
|
|
2352
|
+
* {@link SESSION_READ_PAGE_CHARS}, the first always, so that no response passes a libSQL server's limit however many
|
|
2353
|
+
* sessions there are (#4954) and no statement reads more than its batch.
|
|
2354
|
+
*/
|
|
2355
|
+
async readListingRows(where, params) {
|
|
2356
|
+
const order = this.dialect.rowOrder();
|
|
2357
|
+
const rows = [];
|
|
2358
|
+
for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
|
|
2359
|
+
const page = await this.database.all(`WITH sized AS MATERIALIZED (
|
|
2360
|
+
SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
|
|
2361
|
+
FROM ${this.tables.sessions} WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
|
|
2362
|
+
) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars FROM (
|
|
2363
|
+
SELECT ${LISTING_COLUMNS}, ord, count(*) OVER () AS fetched,
|
|
2364
|
+
row_number() OVER (ORDER BY ord) AS page_row,
|
|
2365
|
+
sum(size) OVER () AS batch_chars,
|
|
2366
|
+
sum(size) OVER (ORDER BY ord) AS page_chars
|
|
2367
|
+
FROM sized
|
|
2368
|
+
) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, limit);
|
|
2369
|
+
rows.push(...page);
|
|
2370
|
+
const next = nextFetch(limit, page);
|
|
2371
|
+
if (!next.more) return rows;
|
|
2372
|
+
after = Number(page.at(-1).ord);
|
|
2373
|
+
limit = next.limit;
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Reads full listing rows, search text included, and caches their summaries, a page per statement as
|
|
2378
|
+
* {@link readListingRows} reads, search text counted. A session whose search text alone is longer than a page has
|
|
2379
|
+
* it read in pages of its own and joined here rather than by the database, whose string limit it may pass (#4954).
|
|
2380
|
+
*/
|
|
2381
|
+
async readSummaries(where, params) {
|
|
2382
|
+
const order = this.dialect.rowOrder();
|
|
2383
|
+
const rows = [];
|
|
2384
|
+
for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
|
|
2385
|
+
const page = await this.database.all(`WITH keyed AS MATERIALIZED (
|
|
2386
|
+
SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
|
|
2387
|
+
FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
|
|
2388
|
+
), sized AS MATERIALIZED (
|
|
2389
|
+
SELECT ${LISTING_COLUMNS}, ord, size,
|
|
2390
|
+
(SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${this.tables.searchTexts} WHERE session_id = keyed.id) AS search_size
|
|
2391
|
+
FROM keyed
|
|
2392
|
+
) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars, CASE WHEN search_size <= ? THEN (
|
|
2393
|
+
SELECT COALESCE('[' || ${this.dialect.orderedConcat("text_json", "','", "seq")} || ']', '[]')
|
|
2394
|
+
FROM (SELECT text_json, seq FROM ${this.tables.searchTexts} WHERE session_id = page.id ORDER BY seq)
|
|
2395
|
+
) END AS search_texts_json
|
|
2396
|
+
FROM (
|
|
2397
|
+
SELECT ${LISTING_COLUMNS}, ord, search_size, count(*) OVER () AS fetched,
|
|
2398
|
+
row_number() OVER (ORDER BY ord) AS page_row,
|
|
2399
|
+
sum(size + search_size) OVER () AS batch_chars,
|
|
2400
|
+
sum(size + search_size) OVER (ORDER BY ord) AS page_chars
|
|
2401
|
+
FROM sized
|
|
2402
|
+
) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
|
|
2403
|
+
for (const row of page) {
|
|
2404
|
+
const summaryRow = row.search_texts_json === null ? {
|
|
2405
|
+
...row,
|
|
2406
|
+
search_texts_json: await this.readSearchTexts(row.id)
|
|
2407
|
+
} : row;
|
|
2408
|
+
this.summaries.set(row.id, {
|
|
2409
|
+
version: listingVersion(summaryRow),
|
|
2410
|
+
summary: summaryFromRow(summaryRow)
|
|
2411
|
+
});
|
|
2412
|
+
rows.push(summaryRow);
|
|
2413
|
+
}
|
|
2414
|
+
const next = nextFetch(limit, page);
|
|
2415
|
+
if (!next.more) return rows;
|
|
2416
|
+
after = Number(page.at(-1).ord);
|
|
2417
|
+
limit = next.limit;
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
/** A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}. */
|
|
2421
|
+
async readSearchTexts(sessionId) {
|
|
2422
|
+
const sizes = await this.database.all(`SELECT seq, length(text_json) AS size FROM ${this.tables.searchTexts} WHERE session_id = ? ORDER BY seq`, sessionId);
|
|
2423
|
+
const texts = [];
|
|
2424
|
+
for (const page of pagesOf(sizes)) {
|
|
2425
|
+
const rows = await this.database.all(`SELECT text_json FROM ${this.tables.searchTexts} WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq`, sessionId, page[0].seq, page.at(-1).seq);
|
|
2426
|
+
for (const row of rows) texts.push(row.text_json);
|
|
2427
|
+
}
|
|
2428
|
+
return `[${texts.join(",")}]`;
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* Keeps only summaries some cached scope still lists, so memory follows the live sessions. Runs in a
|
|
2432
|
+
* listing's turn after it records its scope, when no other listing holds summaries it has not recorded.
|
|
2433
|
+
*/
|
|
2434
|
+
pruneSummaries() {
|
|
2435
|
+
const listed = new Set([...this.scopes.values()].flatMap((scope) => scope.ids));
|
|
2436
|
+
for (const id of this.summaries.keys()) if (!listed.has(id)) this.summaries.delete(id);
|
|
2437
|
+
}
|
|
2438
|
+
assertOpen() {
|
|
2439
|
+
if (this.closed) throw new StoreClosedError$1(this.descriptor);
|
|
2440
|
+
}
|
|
2441
|
+
assertListing(query) {
|
|
2442
|
+
this.assertOpen();
|
|
2443
|
+
query.signal?.throwIfAborted();
|
|
2444
|
+
}
|
|
2445
|
+
async read(tx, sessionId) {
|
|
2446
|
+
const row = await tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2447
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
2448
|
+
const snapshot = {
|
|
2449
|
+
header: JSON.parse(row.header_json),
|
|
2450
|
+
entries: (await this.readRows(tx, sessionId)).map(({ entry }) => entry),
|
|
2451
|
+
lastSeq: row.last_seq
|
|
2452
|
+
};
|
|
2453
|
+
if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
|
|
2454
|
+
return noteSnapshotGeneration(this, snapshot, nativeLoad, row, "revision");
|
|
2455
|
+
}
|
|
2456
|
+
async readRows(tx, sessionId, filter = "", params = []) {
|
|
2457
|
+
const entries = [];
|
|
2458
|
+
for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
|
|
2459
|
+
const rows = await tx.all(`WITH sized AS MATERIALIZED (
|
|
2460
|
+
SELECT seq, chunks, length(entry_json) AS size,
|
|
2461
|
+
CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
|
|
2462
|
+
FROM ${this.tables.entries} WHERE session_id = ? AND seq > ?${filter === "" ? "" : ` AND ${filter}`} ORDER BY seq LIMIT ?
|
|
2463
|
+
), batch AS MATERIALIZED (
|
|
2464
|
+
SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
|
|
2465
|
+
), page AS (
|
|
2466
|
+
SELECT seq, chunks, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
|
|
2467
|
+
FROM (SELECT seq, chunks, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
|
|
2468
|
+
WHERE batch.chars <= ?
|
|
2469
|
+
UNION ALL
|
|
2470
|
+
SELECT seq, chunks, inline_json, fetched, batch_chars, page_chars FROM (
|
|
2471
|
+
SELECT seq, chunks, inline_json, batch.fetched, batch.chars AS batch_chars,
|
|
2472
|
+
row_number() OVER (ORDER BY seq) AS page_row,
|
|
2473
|
+
sum(size) OVER (ORDER BY seq) AS page_chars
|
|
2474
|
+
FROM sized CROSS JOIN batch WHERE batch.chars > ?
|
|
2475
|
+
) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
|
|
2476
|
+
) SELECT seq, COALESCE(inline_json, (
|
|
2477
|
+
SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = ? AND e.seq = page.seq
|
|
2478
|
+
)) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`, SESSION_READ_INLINE_BYTES, sessionId, after, ...params, limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit, sessionId);
|
|
2479
|
+
for (const entry of rows) {
|
|
2480
|
+
const chunks = Number(entry.chunks);
|
|
2481
|
+
const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, sessionId, entry.seq, chunks);
|
|
2482
|
+
entries.push({
|
|
2483
|
+
seq: Number(entry.seq),
|
|
2484
|
+
entry: JSON.parse(json)
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
const next = nextFetch(limit, rows);
|
|
2488
|
+
if (!next.more) return entries;
|
|
2489
|
+
after = Number(rows.at(-1).seq);
|
|
2490
|
+
limit = next.limit;
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
async readSeqs(tx, sessionId, seqs) {
|
|
2494
|
+
const entries = [];
|
|
2495
|
+
for (let start = 0; start < seqs.length; start += SEQ_BATCH) {
|
|
2496
|
+
const batch = seqs.slice(start, start + SEQ_BATCH);
|
|
2497
|
+
entries.push(...await this.readRows(tx, sessionId, `seq IN (${batch.map(() => "?").join(", ")})`, batch));
|
|
2498
|
+
}
|
|
2499
|
+
return entries;
|
|
2500
|
+
}
|
|
2501
|
+
async resumeSource(tx, sessionId) {
|
|
2502
|
+
const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
|
|
2503
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
2504
|
+
const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
|
|
2505
|
+
const remembered = this.resumeIndexes.get(sessionId);
|
|
2506
|
+
const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
|
|
2507
|
+
if (!index || !isSessionResumeIndex(index, Number(row.last_seq))) throw new SessionConflictError$1(sessionId, Number(row.last_seq), Number(row.last_seq));
|
|
2508
|
+
return {
|
|
2509
|
+
header: JSON.parse(row.header_json),
|
|
2510
|
+
index,
|
|
2511
|
+
row
|
|
2512
|
+
};
|
|
2513
|
+
}
|
|
2514
|
+
async prepareResume(sessionId, leafId, throughSeq) {
|
|
2515
|
+
attempts: for (let attempt = 0; attempt < 3; attempt++) {
|
|
2516
|
+
const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2517
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
2518
|
+
const state = JSON.parse(row.summary_state);
|
|
2519
|
+
const remembered = this.resumeIndexes.get(sessionId);
|
|
2520
|
+
const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
|
|
2521
|
+
const limit = throughSeq ?? Number(row.last_seq);
|
|
2522
|
+
if (limit > Number(row.last_seq)) throw new SessionConflictError$1(sessionId, limit, Number(row.last_seq));
|
|
2523
|
+
const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, sessionId, leafId) ?? 0;
|
|
2524
|
+
const requested = selected !== void 0 && selected > limit ? 0 : selected;
|
|
2525
|
+
if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
|
|
2526
|
+
index: currentIndex,
|
|
2527
|
+
revision: row.revision
|
|
2528
|
+
};
|
|
2529
|
+
let index;
|
|
2530
|
+
const sqlite = this.dialect.name === "sqlite";
|
|
2531
|
+
const j = (...path) => sqlite ? this.dialect.jsonText("entry_json", ...path) : this.dialect.jsonAt({
|
|
2532
|
+
column: "entry_json",
|
|
2533
|
+
element: "parsed"
|
|
2534
|
+
}, ...path);
|
|
2535
|
+
const jsonType = (...path) => sqlite ? this.dialect.jsonType("entry_json", ...path) : `jsonb_typeof(parsed.value #> '{${path.join(",")}}')`;
|
|
2536
|
+
const projected = [
|
|
2537
|
+
"type",
|
|
2538
|
+
"parentId",
|
|
2539
|
+
"timestamp",
|
|
2540
|
+
"customType",
|
|
2541
|
+
"firstKeptEntryId",
|
|
2542
|
+
"coveredThroughEntryId",
|
|
2543
|
+
"provider",
|
|
2544
|
+
"modelId",
|
|
2545
|
+
"thinkingLevel",
|
|
2546
|
+
"targetId",
|
|
2547
|
+
"label",
|
|
2548
|
+
"stageAdmissionKey",
|
|
2549
|
+
"root",
|
|
2550
|
+
"snapshotId",
|
|
2551
|
+
"degradedFrom",
|
|
2552
|
+
"captureMs"
|
|
2553
|
+
].map((key) => [key, j(key)]);
|
|
2554
|
+
const messageKeys = [
|
|
2555
|
+
"role",
|
|
2556
|
+
"provider",
|
|
2557
|
+
"model",
|
|
2558
|
+
"usage",
|
|
2559
|
+
"toolCallId"
|
|
2560
|
+
];
|
|
2561
|
+
const dataKeys = [
|
|
2562
|
+
"childId",
|
|
2563
|
+
"version",
|
|
2564
|
+
"index",
|
|
2565
|
+
"agent",
|
|
2566
|
+
"cwd",
|
|
2567
|
+
"state",
|
|
2568
|
+
"intercomSessionId",
|
|
2569
|
+
"homeGroup",
|
|
2570
|
+
"kind",
|
|
2571
|
+
"worktree",
|
|
2572
|
+
"type",
|
|
2573
|
+
"timestamp",
|
|
2574
|
+
"completionId",
|
|
2575
|
+
"sessionId",
|
|
2576
|
+
"askId",
|
|
2577
|
+
"messageId",
|
|
2578
|
+
"attemptId",
|
|
2579
|
+
"runId",
|
|
2580
|
+
"requestId",
|
|
2581
|
+
"id",
|
|
2582
|
+
"protectedReconciliationOf",
|
|
2583
|
+
"historyOnly",
|
|
2584
|
+
"toolCallId",
|
|
2585
|
+
"ownerId",
|
|
2586
|
+
"taskId",
|
|
2587
|
+
"terminalStatus"
|
|
2588
|
+
];
|
|
2589
|
+
const op = `CASE WHEN ${jsonType("data", "op")} = '${sqlite ? "text" : "string"}' THEN ${j("data", "op")} END`;
|
|
2590
|
+
const deliveryOp = `chunks > 0 AND ${j("type")} = 'custom' AND ${j("customType")} = 'atomic-pooled-delivery-op'`;
|
|
2591
|
+
const dataExpr = this.dialect.jsonObject([
|
|
2592
|
+
...dataKeys.map((key) => [key, [
|
|
2593
|
+
"version",
|
|
2594
|
+
"index",
|
|
2595
|
+
"timestamp"
|
|
2596
|
+
].includes(key) ? `CASE WHEN ${jsonType("data", key)} IN ('integer','real','number') THEN CAST(${j("data", key)} AS ${this.dialect.types.real}) END` : key === "runId" ? `CASE WHEN ${j("customType")} NOT IN ('workflow.run.start','workflow.run.end') OR ${jsonType("data", key)} = '${sqlite ? "text" : "string"}' THEN ${j("data", key)} END` : j("data", key)]),
|
|
2597
|
+
["name", `CASE WHEN ${jsonType("data", "name")} = '${sqlite ? "text" : "string"}' THEN '' END`],
|
|
2598
|
+
["ts", `CASE WHEN ${jsonType("data", "ts")} IN ('integer','real','number') THEN 0 END`],
|
|
2599
|
+
["message", this.dialect.jsonObject([
|
|
2600
|
+
"id",
|
|
2601
|
+
"replyTo",
|
|
2602
|
+
"expectsReply"
|
|
2603
|
+
].map((key) => [key, j("data", "message", key)]))],
|
|
2604
|
+
["op", op],
|
|
2605
|
+
...[
|
|
2606
|
+
["owner", "object"],
|
|
2607
|
+
["tasks", "array"],
|
|
2608
|
+
["groups", "array"]
|
|
2609
|
+
].map(([key, type]) => [key, `CASE WHEN ${jsonType("data", key)} = '${type}' THEN ${j("data", key)} WHEN ${jsonType("data", key)} IS NULL OR ${jsonType("data", key)} = 'null' THEN NULL ELSE '' END`]),
|
|
2610
|
+
...["messageIds", "askIds"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN ${j("data", key)} END`]),
|
|
2611
|
+
...["queries", "urls"].map((key) => [key, `CASE WHEN ${jsonType("data", key)} = 'array' THEN '[]' ELSE NULL END`])
|
|
2612
|
+
]);
|
|
2613
|
+
const detailsExpr = this.dialect.jsonObject([...dataKeys.map((key) => [key, j("details", key)]), ["message", this.dialect.jsonObject([
|
|
2614
|
+
"id",
|
|
2615
|
+
"replyTo",
|
|
2616
|
+
"expectsReply"
|
|
2617
|
+
].map((key) => [key, j("details", "message", key)]))]]);
|
|
2618
|
+
const dataFieldNames = this.dialect.name === "sqlite" ? `(SELECT COALESCE(json_group_array(key),'[]') FROM json_each(entry_json,'$.data'))` : `(SELECT COALESCE(json_agg(key)::text,'[]') FROM jsonb_object_keys(CASE WHEN jsonb_typeof(parsed.value->'data')='object' THEN parsed.value->'data' ELSE '{}'::jsonb END) AS key)`;
|
|
2619
|
+
const binaryContent = sqlite && Number(row.last_seq) > 0 && this.database.supportsJsonbExtract && await this.database.supportsJsonbExtract();
|
|
2620
|
+
const toolBlocks = sqlite ? this.dialect.jsonValues(binaryContent ? "jsonb_extract(entry_json, '$.message.content')" : j("message", "content")) : "jsonb_array_elements_text(parsed.value #> '{message,content}') AS blocks(value)";
|
|
2621
|
+
const blockType = this.dialect.jsonText("value", "type");
|
|
2622
|
+
const toolType = `CASE WHEN chunks > 0 AND ${sqlite ? "type = 'text' AND instr(value, '{')" : "strpos(value, '{')"} = 0 THEN NULL ELSE ${blockType} END`;
|
|
2623
|
+
const columns = [
|
|
2624
|
+
["dataFields", `CASE WHEN ${deliveryOp} THEN '["op"]' WHEN ${j("type")} = 'custom' THEN ${dataFieldNames} ELSE '[]' END`],
|
|
2625
|
+
...projected,
|
|
2626
|
+
["message", this.dialect.jsonObject([...messageKeys.map((key) => [key, j("message", key)]), ...["toolsAdded", "toolsRemoved"].map((key) => [key, `CASE WHEN ${jsonType("message", key)}='array' THEN 1 END`])])],
|
|
2627
|
+
["data", `CASE WHEN ${deliveryOp} THEN ${this.dialect.jsonObject([["op", op]])} ELSE ${dataExpr} END`],
|
|
2628
|
+
["details", detailsExpr],
|
|
2629
|
+
["usage", j("usage")],
|
|
2630
|
+
["protectedReconciliation", j("protectedReconciliation")],
|
|
2631
|
+
["snapshot", `CASE WHEN ${jsonType("snapshot")} = 'object' THEN '{}' ELSE NULL END`],
|
|
2632
|
+
["restore", `CASE WHEN ${jsonType("restore")} = 'object' THEN 1 END`],
|
|
2633
|
+
["unrestored", `CASE WHEN ${jsonType("unrestored")} = 'object' THEN 1 END`],
|
|
2634
|
+
["compactionDetails", j("details", "strategy")],
|
|
2635
|
+
["toolCalls", `CASE WHEN ${j("message", "role")} = 'assistant' AND ${jsonType("message", "content")} = 'array' THEN
|
|
2636
|
+
(SELECT count(*) FROM ${toolBlocks}
|
|
2637
|
+
WHERE ${toolType} = 'toolCall') ELSE 0 END`]
|
|
2638
|
+
];
|
|
2639
|
+
const select = columns.map(([key, expr]) => `${expr} AS ${this.dialect.identifier(`resume_${key.toLowerCase()}`)}`).join(", ");
|
|
2640
|
+
const upgrade = requested === void 0 && limit === Number(row.last_seq) && isUpgradableSessionResumeIndex(state.resume, limit) ? sessionResumeUpgrade(state.resume) : void 0;
|
|
2641
|
+
const list = (values) => values.map((value) => `'${value.replaceAll("'", "''")}'`).join(",");
|
|
2642
|
+
const source = `chunks > 0 OR ${j("type")} IN (${list(RESUME_UPGRADE_SOURCES.types)})
|
|
2643
|
+
OR (${j("type")} = 'message' AND ${j("message", "role")} = 'system')
|
|
2644
|
+
OR (${j("type")} = 'custom' AND (${j("customType")} IN (${list(RESUME_UPGRADE_SOURCES.customTypes)})
|
|
2645
|
+
OR ${j("customType")} NOT IN (${list(RESUME_UPGRADE_SOURCES.atomicCustomTypes)})))`;
|
|
2646
|
+
const sources = !upgrade ? "" : sqlite ? ` AND (${source})` : ` AND EXISTS (SELECT 1 FROM (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed WHERE ${source})`;
|
|
2647
|
+
const where = `WHERE session_id = ? AND seq > ? AND seq <= ?${sources}`;
|
|
2648
|
+
const owner = "(SELECT id FROM bounds)";
|
|
2649
|
+
const lo = "(SELECT lo FROM bounds)";
|
|
2650
|
+
const hi = "(SELECT hi FROM bounds)";
|
|
2651
|
+
const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
|
|
2652
|
+
const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
|
|
2653
|
+
SELECT ${sqlite ? "" : "CASE WHEN chunks > 0 THEN session_id END AS session_id,"}seq,entry_id,chunks,entry_json FROM ${this.tables.entries}
|
|
2654
|
+
${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
|
|
2655
|
+
)`;
|
|
2656
|
+
const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite ? owner : `${source}.session_id`}
|
|
2657
|
+
AND seq = ${source}.seq AND idx >= 0 AND idx < ${source}.chunks`;
|
|
2658
|
+
const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
|
|
2659
|
+
CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
|
|
2660
|
+
const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
|
|
2661
|
+
const joined = sqlite ? `(SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text ${parts("sized")} ORDER BY idx))` : `(SELECT convert_from(string_agg(data, ''::bytea ORDER BY idx), 'UTF8') ${parts("sized")})`;
|
|
2662
|
+
const directPage = `${page}, sized AS ${sqlite ? "NOT MATERIALIZED" : "MATERIALIZED"} (
|
|
2663
|
+
SELECT page.*, CASE WHEN chunks = 0 OR EXISTS (SELECT 1 ${parts("page")} GROUP BY seq
|
|
2664
|
+
HAVING count(*) = page.chunks AND ${fits}) THEN 0 ELSE chunks END AS remaining FROM page${sqlite ? " LIMIT -1 OFFSET 0" : ""}
|
|
2665
|
+
), payloads AS MATERIALIZED (
|
|
2666
|
+
SELECT seq,entry_id,CASE WHEN remaining = 0 THEN chunks ELSE -chunks END AS chunks,
|
|
2667
|
+
CASE WHEN chunks > 0 AND remaining = 0 THEN ${joined} ELSE entry_json END AS entry_json
|
|
2668
|
+
FROM sized
|
|
2669
|
+
) ${projection}`;
|
|
2670
|
+
const keysPerEntry = 64;
|
|
2671
|
+
const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
|
|
2672
|
+
const wide = sqlite && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
|
|
2673
|
+
let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
|
|
2674
|
+
payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
|
|
2675
|
+
UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
|
|
2676
|
+
const rowidPage = wide && this.chunkRowids !== false ? `${page},
|
|
2677
|
+
keys AS MATERIALIZED (SELECT seq,idx,rowid AS rid FROM ${this.tables.entryChunks}
|
|
2678
|
+
WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi} AND seq <= ${through} AND idx >= 0 AND idx < ${keysPerEntry}
|
|
2679
|
+
ORDER BY seq,idx),
|
|
2680
|
+
sized AS NOT MATERIALIZED (SELECT page.*, CASE WHEN chunks = 0 THEN NULL
|
|
2681
|
+
WHEN seq <= ${through} AND chunks <= ${keysPerEntry} THEN (
|
|
2682
|
+
SELECT CASE WHEN count(*) = page.chunks AND length(zeroblob(sum(length(c.data)))) IS NOT NULL
|
|
2683
|
+
THEN CASE WHEN min(k.rid) > 0 AND min(k.rid - k.idx) = max(k.rid - k.idx) THEN min(k.rid) ELSE 0 END END
|
|
2684
|
+
FROM keys k CROSS JOIN ${this.tables.entryChunks} c WHERE k.seq = page.seq AND k.idx < page.chunks AND c.rowid = k.rid)
|
|
2685
|
+
WHEN EXISTS (SELECT 1 ${parts("page")} GROUP BY seq HAVING count(*) = page.chunks AND ${fits}) THEN -1 END AS first_rid
|
|
2686
|
+
FROM page LIMIT -1 OFFSET 0),
|
|
2687
|
+
payloads AS MATERIALIZED (SELECT seq,entry_id,CASE WHEN chunks > 0 AND first_rid IS NULL THEN -chunks ELSE chunks END AS chunks,
|
|
2688
|
+
CASE WHEN first_rid IS NULL THEN entry_json WHEN first_rid < 0 THEN ${joined}
|
|
2689
|
+
WHEN first_rid > 0 THEN (SELECT group_concat(text, '') FROM (SELECT CAST(data AS TEXT) AS text FROM ${this.tables.entryChunks}
|
|
2690
|
+
WHERE rowid BETWEEN sized.first_rid AND sized.first_rid + (sized.chunks - 1) ORDER BY rowid))
|
|
2691
|
+
ELSE (SELECT group_concat(CAST((SELECT data FROM ${this.tables.entryChunks} WHERE rowid = ids.rid) AS TEXT), '')
|
|
2692
|
+
FROM (SELECT rid FROM keys k WHERE k.seq = sized.seq AND k.idx < sized.chunks ORDER BY k.idx LIMIT -1 OFFSET 0) ids)
|
|
2693
|
+
END AS entry_json FROM sized)
|
|
2694
|
+
${projection}` : directPage;
|
|
2695
|
+
const stubPage = `${page}, payloads AS (SELECT seq,entry_id,-chunks AS chunks,entry_json FROM page) ${projection}`;
|
|
2696
|
+
let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
|
|
2697
|
+
for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
|
|
2698
|
+
for (let after = 0; after < limit;) {
|
|
2699
|
+
const args = [
|
|
2700
|
+
sessionId,
|
|
2701
|
+
after,
|
|
2702
|
+
limit
|
|
2703
|
+
];
|
|
2704
|
+
let rows;
|
|
2705
|
+
try {
|
|
2706
|
+
rows = await this.database.all(inlinePage ?? (this.chunkRowids ? rowidPage : directPage), ...args);
|
|
2707
|
+
if (inlinePage && Number(rows[0]?.seq) === 0) {
|
|
2708
|
+
inlinePage = void 0;
|
|
2709
|
+
try {
|
|
2710
|
+
this.chunkRowids = await this.database.get(`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM pragma_index_xinfo(?))
|
|
2711
|
+
AND NOT EXISTS (SELECT 1 FROM pragma_table_xinfo(?) WHERE name = 'rowid' COLLATE NOCASE)`, this.tables.entryChunks, this.tables.entryChunks) !== void 0;
|
|
2712
|
+
} catch {}
|
|
2713
|
+
continue;
|
|
2714
|
+
}
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
|
|
2717
|
+
if (!await this.database.get(`SELECT 1 FROM ${this.tables.entryChunks}
|
|
2718
|
+
WHERE session_id = ? AND seq IN (SELECT seq FROM ${this.tables.entries} ${where}
|
|
2719
|
+
ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) LIMIT 1`, sessionId, ...args).catch(() => void 0)) throw error;
|
|
2720
|
+
rows = await this.database.all(stubPage, ...args);
|
|
2721
|
+
}
|
|
2722
|
+
if (rows.length === 0) break;
|
|
2723
|
+
const batch = [];
|
|
2724
|
+
let toolCalls = 0;
|
|
2725
|
+
for (const entry of rows) {
|
|
2726
|
+
const chunks = Number(entry.chunks);
|
|
2727
|
+
let projected = entry;
|
|
2728
|
+
if (chunks < 0) try {
|
|
2729
|
+
const { chunkedResumeProjection } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
2730
|
+
projected = await chunkedResumeProjection(entry, this.dialect.name === "postgres", () => this.entryChunks(sessionId, Number(entry.seq), -chunks, row.revision));
|
|
2731
|
+
} catch (error) {
|
|
2732
|
+
if ((await this.database.get(`SELECT revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId))?.revision !== row.revision) continue attempts;
|
|
2733
|
+
throw error;
|
|
2734
|
+
}
|
|
2735
|
+
const parsed = { id: entry.entry_id };
|
|
2736
|
+
const decode = (value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? JSON.parse(value) : value;
|
|
2737
|
+
for (const [key] of columns) {
|
|
2738
|
+
const value = projected[`resume_${key.toLowerCase()}`];
|
|
2739
|
+
parsed[key] = [
|
|
2740
|
+
"dataFields",
|
|
2741
|
+
"message",
|
|
2742
|
+
"data",
|
|
2743
|
+
"details",
|
|
2744
|
+
"usage",
|
|
2745
|
+
"snapshot",
|
|
2746
|
+
"protectedReconciliation"
|
|
2747
|
+
].includes(key) ? decode(value) : value;
|
|
2748
|
+
}
|
|
2749
|
+
const message = parsed.message;
|
|
2750
|
+
if (message && typeof message === "object") {
|
|
2751
|
+
message.usage = decode(message.usage);
|
|
2752
|
+
if (parsed.type === "message" && message.role === "assistant") toolCalls += Number(parsed.toolCalls ?? 0);
|
|
2753
|
+
}
|
|
2754
|
+
if (parsed.snapshot === null) delete parsed.snapshot;
|
|
2755
|
+
if (parsed.type === "compaction") parsed.details = { strategy: parsed.compactionDetails };
|
|
2756
|
+
if (parsed.type === "custom") {
|
|
2757
|
+
const data = parsed.data;
|
|
2758
|
+
const keys = parsed.dataFields ?? [];
|
|
2759
|
+
for (const key of Object.keys(data)) if (!keys.includes(key)) delete data[key];
|
|
2760
|
+
for (const key of keys) if (!(key in data)) data[key] = null;
|
|
2761
|
+
}
|
|
2762
|
+
for (const key of ["data", "details"]) {
|
|
2763
|
+
const data = parsed[key];
|
|
2764
|
+
if (data && typeof data === "object") {
|
|
2765
|
+
data.message = decode(data.message);
|
|
2766
|
+
data.owner = decode(data.owner);
|
|
2767
|
+
data.tasks = decode(data.tasks);
|
|
2768
|
+
for (const field of [
|
|
2769
|
+
"groups",
|
|
2770
|
+
"queries",
|
|
2771
|
+
"urls",
|
|
2772
|
+
"messageIds",
|
|
2773
|
+
"askIds"
|
|
2774
|
+
]) if (field in data) data[field] = decode(data[field]);
|
|
2775
|
+
if (data.timestamp !== null && data.timestamp !== void 0 && typeof data.timestamp === "string") data.timestamp = Number(data.timestamp);
|
|
2776
|
+
if (parsed.type === "custom" && parsed.customType === "subagent-child") {
|
|
2777
|
+
if (data.version !== null && data.version !== void 0) data.version = Number(data.version);
|
|
2778
|
+
if (data.index !== null && data.index !== void 0) data.index = Number(data.index);
|
|
2779
|
+
}
|
|
2780
|
+
const message = data.message;
|
|
2781
|
+
if (message?.expectsReply === 1 || message?.expectsReply === "true") message.expectsReply = true;
|
|
2782
|
+
if (data.historyOnly === 1 || data.historyOnly === "true") data.historyOnly = true;
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
if (upgrade) upgrade.add(parsed, Number(entry.seq));
|
|
2786
|
+
else batch.push(parsed);
|
|
2787
|
+
}
|
|
2788
|
+
if (upgrade) {
|
|
2789
|
+
after = Number(rows.at(-1).seq);
|
|
2790
|
+
if (after < limit) await yieldTurn();
|
|
2791
|
+
continue;
|
|
2792
|
+
}
|
|
2793
|
+
const old = index ?? foldSessionResume(void 0, []);
|
|
2794
|
+
const seqs = /* @__PURE__ */ new Map();
|
|
2795
|
+
for (const id of foreignResumeIds(old, batch)) {
|
|
2796
|
+
const seq = await this.seqOfEntry(this.database, sessionId, id);
|
|
2797
|
+
if (seq !== void 0) seqs.set(id, seq);
|
|
2798
|
+
}
|
|
2799
|
+
index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
|
|
2800
|
+
if (toolCalls > 0) index = {
|
|
2801
|
+
...index,
|
|
2802
|
+
totals: {
|
|
2803
|
+
...index.totals,
|
|
2804
|
+
toolCalls: index.totals.toolCalls + toolCalls
|
|
2805
|
+
}
|
|
2806
|
+
};
|
|
2807
|
+
after = Number(rows.at(-1).seq);
|
|
2808
|
+
if (after < Number(row.last_seq)) await yieldTurn();
|
|
2809
|
+
}
|
|
2810
|
+
if (pass !== 0 || !index || index.jumps.length === 0 && (requested === void 0 || requested === index.leafSeq)) break;
|
|
2811
|
+
topology = branchRanges(index, requested ?? index.leafSeq);
|
|
2812
|
+
index = void 0;
|
|
2813
|
+
}
|
|
2814
|
+
if (upgrade) index = upgrade.finish();
|
|
2815
|
+
index = {
|
|
2816
|
+
...index ?? foldSessionResume(void 0, []),
|
|
2817
|
+
epoch: state.epoch ?? row.revision
|
|
2818
|
+
};
|
|
2819
|
+
const current = await this.database.get(`SELECT revision,last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2820
|
+
if (current?.revision !== row.revision || Number(current.last_seq) !== Number(row.last_seq)) continue;
|
|
2821
|
+
if (requested !== void 0) return {
|
|
2822
|
+
index: {
|
|
2823
|
+
...index,
|
|
2824
|
+
leafSeq: requested
|
|
2825
|
+
},
|
|
2826
|
+
revision: row.revision
|
|
2827
|
+
};
|
|
2828
|
+
this.resumeIndexes.set(sessionId, {
|
|
2829
|
+
revision: row.revision,
|
|
2830
|
+
index
|
|
2831
|
+
});
|
|
2832
|
+
while (this.resumeIndexes.size > 16) this.resumeIndexes.delete(this.resumeIndexes.keys().next().value);
|
|
2833
|
+
await this.database.run(`UPDATE ${this.tables.sessions} SET summary_state = ? WHERE id = ? AND revision = ? AND last_seq = ?`, JSON.stringify({
|
|
2834
|
+
...state,
|
|
2835
|
+
...windowFields(state, index, index.seq, index.epoch),
|
|
2836
|
+
epoch: index.epoch
|
|
2837
|
+
}), sessionId, row.revision, row.last_seq).catch(() => void 0);
|
|
2838
|
+
this.generations.delete(sessionId);
|
|
2839
|
+
return {
|
|
2840
|
+
index,
|
|
2841
|
+
revision: row.revision
|
|
2842
|
+
};
|
|
2843
|
+
}
|
|
2844
|
+
throw new SessionConflictError$1(sessionId, 0, 0);
|
|
2845
|
+
}
|
|
2846
|
+
async readTail(sessionId, fromSeq) {
|
|
2847
|
+
this.assertOpen();
|
|
2848
|
+
validateSessionText("sessionId", sessionId);
|
|
2849
|
+
await this.prepareResume(sessionId);
|
|
2850
|
+
const start = Math.max(1, fromSeq);
|
|
2851
|
+
const { tail } = await this.transaction(async (tx) => {
|
|
2852
|
+
const source = await this.resumeSource(tx, sessionId);
|
|
2853
|
+
const stateSeqs = stateSeqsBefore(source.index, start);
|
|
2854
|
+
if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
|
|
2855
|
+
const state = await this.readSeqs(tx, sessionId, stateSeqs);
|
|
2856
|
+
const entries = (await this.readRows(tx, sessionId, "seq >= ?", [start])).map(({ entry }) => entry);
|
|
2857
|
+
return {
|
|
2858
|
+
tail: sessionTailFrom(source.index, source.header, start, state, entries),
|
|
2859
|
+
source
|
|
2860
|
+
};
|
|
2861
|
+
}, SESSION_TRANSACTION);
|
|
2862
|
+
return tail;
|
|
2863
|
+
}
|
|
2864
|
+
async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
|
|
2865
|
+
this.assertOpen();
|
|
2866
|
+
validateSessionText("sessionId", sessionId);
|
|
2867
|
+
const start = Math.max(1, startSeq);
|
|
2868
|
+
return this.transaction(async (tx) => {
|
|
2869
|
+
const head = await this.historyHead(tx, sessionId);
|
|
2870
|
+
if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
|
|
2871
|
+
const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, endSeq]);
|
|
2872
|
+
return {
|
|
2873
|
+
startSeq: start,
|
|
2874
|
+
entries: entries.map(({ entry }) => entry),
|
|
2875
|
+
seqs: entries.map(({ seq }) => seq),
|
|
2876
|
+
...head
|
|
2877
|
+
};
|
|
2878
|
+
}, SESSION_TRANSACTION);
|
|
2879
|
+
}
|
|
2880
|
+
async historyHead(tx, sessionId, readOnly = false) {
|
|
2881
|
+
const generation = this.generation(sessionId);
|
|
2882
|
+
const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
|
|
2883
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
2884
|
+
this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
|
|
2885
|
+
return {
|
|
2886
|
+
lastSeq: Number(row.last_seq),
|
|
2887
|
+
epoch: row.epoch
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
/** Size at most one page and return only fitting bodies, in the same snapshot as the header. The first
|
|
2891
|
+
* oversized row is a chunk reference; its full inline value never crosses the driver boundary. */
|
|
2892
|
+
async historyPacket(tx, sessionId, epoch, from, through, backward) {
|
|
2893
|
+
const edge = backward ? through : from;
|
|
2894
|
+
const rows = await tx.all(`WITH sizes AS MATERIALIZED (
|
|
2895
|
+
SELECT e.seq, e.chunks, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
|
|
2896
|
+
(SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1) END AS bytes
|
|
2897
|
+
FROM ${this.tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ?
|
|
2898
|
+
), sized_page AS (
|
|
2899
|
+
SELECT seq, chunks, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
|
|
2900
|
+
) SELECT p.seq, p.chunks, p.bytes, CASE WHEN p.chunks = 0 AND p.bytes <= ? THEN e.entry_json END AS body
|
|
2901
|
+
FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
|
|
2902
|
+
WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, from, through, SESSION_HISTORY_PAGE_BYTES, sessionId, SESSION_HISTORY_PAGE_BYTES, edge);
|
|
2903
|
+
const items = [];
|
|
2904
|
+
for (const row of rows) {
|
|
2905
|
+
const seq = Number(row.seq);
|
|
2906
|
+
const bytes = Number(row.bytes);
|
|
2907
|
+
if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${seq}`));
|
|
2908
|
+
if (bytes > 1048576) items.push({
|
|
2909
|
+
kind: "oversized",
|
|
2910
|
+
sessionId,
|
|
2911
|
+
epoch,
|
|
2912
|
+
seq,
|
|
2913
|
+
bytes
|
|
2914
|
+
});
|
|
2915
|
+
else items.push({
|
|
2916
|
+
seq,
|
|
2917
|
+
entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, sessionId, seq, Number(row.chunks)))
|
|
2918
|
+
});
|
|
2919
|
+
}
|
|
2920
|
+
return items;
|
|
2921
|
+
}
|
|
2922
|
+
async readChildDisplayCut(sessionId, launch) {
|
|
2923
|
+
const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
2924
|
+
const { index } = await this.prepareResume(sessionId);
|
|
2925
|
+
if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
|
|
2926
|
+
return this.transaction(async (tx) => {
|
|
2927
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
2928
|
+
if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
|
|
2929
|
+
const row = await tx.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id=? AND entry_id=? AND seq<=? ORDER BY seq DESC LIMIT 1`, sessionId, launch.launchLeafId, index.seq);
|
|
2930
|
+
return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
|
|
2931
|
+
}, {
|
|
2932
|
+
...SESSION_TRANSACTION,
|
|
2933
|
+
readOnly: true
|
|
2934
|
+
});
|
|
2935
|
+
}
|
|
2936
|
+
/**
|
|
2937
|
+
* A column expression of a sessions row's generation, `COALESCE(epoch, resume.epoch, revision)` of its summary state,
|
|
2938
|
+
* that parses that state only when the row's revision or watermark is not the one this store last saw it at: every
|
|
2939
|
+
* write gives the row a new revision, so the generation it held then still stands. A long session's summary state is
|
|
2940
|
+
* hundreds of kilobytes, which a server would otherwise parse for every page and chunk an export reads (#5571).
|
|
2941
|
+
*/
|
|
2942
|
+
generation(sessionId) {
|
|
2943
|
+
const known = this.generations.get(sessionId);
|
|
2944
|
+
return {
|
|
2945
|
+
sql: `CASE WHEN revision = ? AND last_seq = ? THEN ? ELSE COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision) END`,
|
|
2946
|
+
params: [
|
|
2947
|
+
known?.revision ?? null,
|
|
2948
|
+
known?.lastSeq ?? null,
|
|
2949
|
+
known?.epoch ?? null
|
|
2950
|
+
]
|
|
2951
|
+
};
|
|
2952
|
+
}
|
|
2953
|
+
noteGeneration(sessionId, revision, lastSeq, epoch) {
|
|
2954
|
+
this.generations.delete(sessionId);
|
|
2955
|
+
this.generations.set(sessionId, {
|
|
2956
|
+
revision,
|
|
2957
|
+
lastSeq,
|
|
2958
|
+
epoch
|
|
2959
|
+
});
|
|
2960
|
+
while (this.generations.size > 16) this.generations.delete(this.generations.keys().next().value);
|
|
2961
|
+
}
|
|
2962
|
+
async readBranchSpan(sessionId, cut) {
|
|
2963
|
+
this.assertOpen();
|
|
2964
|
+
validateSessionText("sessionId", sessionId);
|
|
2965
|
+
const { index } = await this.prepareResume(sessionId);
|
|
2966
|
+
return transcriptBranchSpan(sessionId, index, cut);
|
|
2967
|
+
}
|
|
2968
|
+
/** Send only tree headings over the database connection. A chunk stub has no message role or
|
|
2969
|
+
* timestamp; its caller streams those fields instead of joining or decoding the stored body. */
|
|
2970
|
+
async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
|
|
2971
|
+
this.assertOpen();
|
|
2972
|
+
return this.transaction(async (tx) => {
|
|
2973
|
+
const head = await this.historyHead(tx, sessionId);
|
|
2974
|
+
if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
|
|
2975
|
+
const sqlite = this.dialect.name === "sqlite";
|
|
2976
|
+
const j = (...path) => this.dialect.jsonText("entry_json", ...path);
|
|
2977
|
+
const role = j("message", "role");
|
|
2978
|
+
const content = j("message", "content");
|
|
2979
|
+
const ctype = this.dialect.jsonType("entry_json", "message", "content");
|
|
2980
|
+
const whites = " \n\v\f\r \xA0 \u2028\u2029 ";
|
|
2981
|
+
const trim = sqlite ? "trim" : "btrim";
|
|
2982
|
+
const hasText = sqlite ? `EXISTS(SELECT 1 FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' AND json_extract(b.value,'$.type')='text' THEN length(trim(json_extract(b.value,'$.text'),?))>0 END)` : `EXISTS(SELECT 1 FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='text' AND length(btrim(b->>'text',?))>0)`;
|
|
2983
|
+
const callIds = sqlite ? `(SELECT json_group_array(json_extract(b.value,'$.id')) FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' THEN json_extract(b.value,'$.type')='toolCall' AND json_type(b.value,'$.id')='text' END)` : `(SELECT json_agg(b->>'id')::text FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='toolCall' AND jsonb_typeof(b->'id')='string')`;
|
|
2984
|
+
return (await tx.all(`SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
|
|
2985
|
+
CASE WHEN ${role}='assistant' AND COALESCE(${j("message", "stopReason")},'') IN ('','toolUse','stop') AND CASE WHEN ${ctype}='array' THEN NOT ${hasText} WHEN ${ctype}='${sqlite ? "text" : "string"}' THEN length(${trim}(${content},?))=0 ELSE TRUE END THEN 1 ELSE 0 END hidden,
|
|
2986
|
+
CASE WHEN ${j("type")}='custom' AND ${j("customType")}='atomic.leaf' THEN 1 ELSE 0 END leaf_move,
|
|
2987
|
+
CASE WHEN ${j("type")}='custom' AND ${j("customType")}='subagent-child' THEN 1 ELSE 0 END child_record,
|
|
2988
|
+
CASE WHEN ${j("type")}='label' THEN ${j("targetId")} END target,CASE WHEN ${j("type")}='label' THEN substr(${j("label")},1,128) END label
|
|
2989
|
+
FROM ${this.tables.entries} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
|
|
2990
|
+
seq: Number(row.seq),
|
|
2991
|
+
streamed: true
|
|
2992
|
+
} : {
|
|
2993
|
+
seq: Number(row.seq),
|
|
2994
|
+
id: String(row.entry_id),
|
|
2995
|
+
parentId: row.parent === null ? null : String(row.parent),
|
|
2996
|
+
timestamp: String(row.stamp),
|
|
2997
|
+
type: row.kind,
|
|
2998
|
+
...typeof row.role === "string" ? { role: row.role } : {},
|
|
2999
|
+
...Number(row.hidden) === 1 ? { hideAssistant: true } : {},
|
|
3000
|
+
...typeof row.calls === "string" && row.calls !== "[]" ? { callIds: JSON.parse(row.calls) } : {},
|
|
3001
|
+
...Number(row.leaf_move) === 1 ? { leafMove: true } : {},
|
|
3002
|
+
...Number(row.child_record) === 1 ? { childRecord: true } : {},
|
|
3003
|
+
...typeof row.target === "string" ? {
|
|
3004
|
+
labelTarget: row.target,
|
|
3005
|
+
label: typeof row.label === "string" ? row.label : void 0
|
|
3006
|
+
} : {}
|
|
3007
|
+
});
|
|
3008
|
+
}, SESSION_TRANSACTION);
|
|
3009
|
+
}
|
|
3010
|
+
/** Sparse page of child state in one fenced read, bounded by the same byte and row caps as a transcript page. */
|
|
3011
|
+
async readSelectedPage(sessionId, seqs, epoch, options = {}) {
|
|
3012
|
+
this.assertOpen();
|
|
3013
|
+
const limit = entrySizeLimit(options.limit);
|
|
3014
|
+
const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
|
|
3015
|
+
if (!wanted.length) return { items: [] };
|
|
3016
|
+
return this.transaction(async (tx) => {
|
|
3017
|
+
const head = await this.historyHead(tx, sessionId);
|
|
3018
|
+
if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
|
|
3019
|
+
const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.session_id AND c.seq=e.seq AND c.idx=e.chunks-1)`;
|
|
3020
|
+
const rows = await tx.all(`SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${this.tables.entries} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
|
|
3021
|
+
const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
|
|
3022
|
+
const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
|
|
3023
|
+
const bytes = sizes.get(seq);
|
|
3024
|
+
if (bytes === void 0) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
|
|
3025
|
+
return bytes;
|
|
3026
|
+
}, options.backward);
|
|
3027
|
+
if ("oversized" in plan) return { items: [{
|
|
3028
|
+
kind: "oversized",
|
|
3029
|
+
sessionId,
|
|
3030
|
+
epoch,
|
|
3031
|
+
...plan.oversized
|
|
3032
|
+
}] };
|
|
3033
|
+
return { items: await this.readSeqs(tx, sessionId, plan.seqs) };
|
|
3034
|
+
}, SESSION_TRANSACTION);
|
|
3035
|
+
}
|
|
3036
|
+
/**
|
|
3037
|
+
* The snapshot entries of the session's resume index, read with the index and nothing else: no entry is read, and an
|
|
3038
|
+
* index that does not cover the session as it stands is not rebuilt here (#5554).
|
|
3039
|
+
*/
|
|
3040
|
+
async readSnapshotCut(sessionId, options = {}) {
|
|
3041
|
+
this.assertOpen();
|
|
3042
|
+
validateSessionText("sessionId", sessionId);
|
|
3043
|
+
const row = await this.database.get(`SELECT last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
3044
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3045
|
+
const lastSeq = Number(row.last_seq);
|
|
3046
|
+
const remembered = this.resumeIndexes.get(sessionId);
|
|
3047
|
+
const index = windowIndex(JSON.parse(row.summary_state), lastSeq) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, lastSeq) ? remembered.index : void 0);
|
|
3048
|
+
if (index === void 0 || options.leafSeq !== void 0 && options.leafSeq > lastSeq) return void 0;
|
|
3049
|
+
return snapshotCutOf(index, options.leafSeq);
|
|
3050
|
+
}
|
|
3051
|
+
async readEntrySizes(sessionId, startSeq, endSeq, limit) {
|
|
3052
|
+
this.assertOpen();
|
|
3053
|
+
validateSessionText("sessionId", sessionId);
|
|
3054
|
+
return this.transaction(async (tx) => {
|
|
3055
|
+
const head = await this.historyHead(tx, sessionId);
|
|
3056
|
+
const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = e.chunks - 1)`;
|
|
3057
|
+
const rows = await tx.all(`SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${this.tables.entries} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
|
|
3058
|
+
return {
|
|
3059
|
+
...head,
|
|
3060
|
+
sizes: rows.map((row) => {
|
|
3061
|
+
if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
|
|
3062
|
+
return {
|
|
3063
|
+
seq: Number(row.seq),
|
|
3064
|
+
bytes: Number(row.bytes)
|
|
3065
|
+
};
|
|
3066
|
+
})
|
|
3067
|
+
};
|
|
3068
|
+
}, SESSION_TRANSACTION);
|
|
3069
|
+
}
|
|
3070
|
+
/**
|
|
3071
|
+
* One statement, so one snapshot without a transaction: the session row (its generation, watermark and schema version)
|
|
3072
|
+
* sorts first as sequence 0, then the page's entries with their sizes. The page ends at the last of up to `limit`
|
|
3073
|
+
* entries whose running size fits a page, or is the first entry alone, whose JSON is left out when it is larger. Each
|
|
3074
|
+
* page of a scan is then one round trip to a database server (#5571). With `select`, only the entries `selected` keeps
|
|
3075
|
+
* are sized and read; the session row then also says how many were sized and the last of them, so the page knows how
|
|
3076
|
+
* far it accounts for the range.
|
|
3077
|
+
*/
|
|
3078
|
+
async readScanPage(sessionId, startSeq, endSeq, epoch, limit, options = {}) {
|
|
3079
|
+
this.assertOpen();
|
|
3080
|
+
validateSessionText("sessionId", sessionId);
|
|
3081
|
+
const { select, trailingReference, referencePrefix } = options;
|
|
3082
|
+
const generation = this.generation(sessionId);
|
|
3083
|
+
const count = entrySizeLimit(limit);
|
|
3084
|
+
const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.session_id AND c.seq = ${row}.seq AND c.idx = ${row}.chunks - 1) END`;
|
|
3085
|
+
const head = `SELECT 0 AS seq, NULL AS bytes, NULL AS chunks, header_json AS entry_json, last_seq, revision,
|
|
3086
|
+
${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version`;
|
|
3087
|
+
const filter = (row) => select ? ` AND ${this.selected(row, select)}` : "";
|
|
3088
|
+
const selectParams = select === void 0 ? [] : this.selectedParams(select);
|
|
3089
|
+
const json = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json, 'UTF8')";
|
|
3090
|
+
const prefixLength = Math.max(1, Math.trunc(referencePrefix ?? 1) || 1);
|
|
3091
|
+
const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(`${head} FROM ${this.tables.sessions} WHERE id = ?
|
|
3092
|
+
UNION ALL
|
|
3093
|
+
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL FROM (
|
|
3094
|
+
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
|
|
3095
|
+
-- The cut bounds the range itself, so the read stops there, however far the range goes.
|
|
3096
|
+
WHERE e.session_id = ? AND e.seq BETWEEN ? AND (
|
|
3097
|
+
SELECT COALESCE(max(CASE WHEN total <= ? THEN seq END), min(seq)) FROM (
|
|
3098
|
+
SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM (
|
|
3099
|
+
SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
|
|
3100
|
+
WHERE s.session_id = ? AND s.seq BETWEEN ? AND ? ORDER BY s.seq LIMIT ?
|
|
3101
|
+
) AS sized
|
|
3102
|
+
) AS run
|
|
3103
|
+
)
|
|
3104
|
+
) AS page
|
|
3105
|
+
ORDER BY seq`, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, count) : await this.database.all(`WITH sized AS MATERIALIZED (
|
|
3106
|
+
SELECT s.seq, ${bytes("s")} AS bytes FROM ${this.tables.entries} s
|
|
3107
|
+
WHERE s.session_id = ? AND s.seq BETWEEN ? AND ?${filter("s")} ORDER BY s.seq LIMIT ?
|
|
3108
|
+
), cut AS (
|
|
3109
|
+
SELECT COALESCE(
|
|
3110
|
+
(SELECT max(seq) FROM (SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM sized) AS run WHERE total <= ?),
|
|
3111
|
+
(SELECT min(seq) FROM sized)
|
|
3112
|
+
) AS seq
|
|
3113
|
+
), tail AS (
|
|
3114
|
+
SELECT seq FROM sized
|
|
3115
|
+
WHERE ${trailingReference ? "" : "1 = 0 AND "}seq = (SELECT min(seq) FROM sized WHERE seq > (SELECT seq FROM cut))
|
|
3116
|
+
AND bytes > ? AND (SELECT bytes FROM sized WHERE seq = (SELECT seq FROM cut)) <= ?
|
|
3117
|
+
)
|
|
3118
|
+
${head}, (SELECT count(*) FROM sized) AS sized, (SELECT max(seq) FROM sized) AS sized_last, NULL AS prefix
|
|
3119
|
+
FROM ${this.tables.sessions} WHERE id = ?
|
|
3120
|
+
UNION ALL
|
|
3121
|
+
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL, NULL, NULL,
|
|
3122
|
+
${referencePrefix === void 0 ? "NULL" : `CASE WHEN bytes > ? THEN CASE WHEN chunks > 0
|
|
3123
|
+
THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = ? AND c.seq = page.seq AND c.idx = 0)
|
|
3124
|
+
ELSE substr(${json}, 1, CAST(? AS INTEGER)) END END`}
|
|
3125
|
+
FROM (
|
|
3126
|
+
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
|
|
3127
|
+
WHERE e.session_id = ? AND e.seq BETWEEN ? AND (SELECT seq FROM cut)${filter("e")}
|
|
3128
|
+
UNION ALL
|
|
3129
|
+
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${this.tables.entries} e
|
|
3130
|
+
WHERE e.session_id = ? AND e.seq = (SELECT seq FROM tail)
|
|
3131
|
+
) AS page
|
|
3132
|
+
ORDER BY seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
|
|
3133
|
+
SESSION_HISTORY_PAGE_BYTES,
|
|
3134
|
+
prefixLength,
|
|
3135
|
+
sessionId,
|
|
3136
|
+
prefixLength
|
|
3137
|
+
], SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, ...selectParams, SESSION_ENTRY_CHUNK_BYTES, sessionId);
|
|
3138
|
+
const first = rows[0];
|
|
3139
|
+
if (first === void 0 || Number(first.seq) !== 0) throw new SessionNotFoundError$1(sessionId);
|
|
3140
|
+
assertStorageSchemaVersion("sessions", first.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
3141
|
+
const lastSeq = Number(first.last_seq);
|
|
3142
|
+
this.noteGeneration(sessionId, first.revision, lastSeq, first.epoch);
|
|
3143
|
+
if (epoch !== void 0 && first.epoch !== epoch) throw new SessionConflictError$1(sessionId, endSeq, lastSeq);
|
|
3144
|
+
const read = {
|
|
3145
|
+
header: JSON.parse(first.entry_json),
|
|
3146
|
+
epoch: first.epoch,
|
|
3147
|
+
lastSeq
|
|
3148
|
+
};
|
|
3149
|
+
const page = rows.slice(1);
|
|
3150
|
+
for (const row of page) if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
|
|
3151
|
+
const top = page.at(-1);
|
|
3152
|
+
if (top === void 0) return {
|
|
3153
|
+
...read,
|
|
3154
|
+
throughSeq: endSeq,
|
|
3155
|
+
items: []
|
|
3156
|
+
};
|
|
3157
|
+
const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? endSeq : Number(top.seq);
|
|
3158
|
+
const prefixes = /* @__PURE__ */ new Map();
|
|
3159
|
+
const reference = (row) => {
|
|
3160
|
+
if (row.prefix) prefixes.set(Number(row.seq), row.prefix);
|
|
3161
|
+
return {
|
|
3162
|
+
kind: "oversized",
|
|
3163
|
+
sessionId,
|
|
3164
|
+
epoch: read.epoch,
|
|
3165
|
+
seq: Number(row.seq),
|
|
3166
|
+
bytes: Number(row.bytes)
|
|
3167
|
+
};
|
|
3168
|
+
};
|
|
3169
|
+
const oversized = (row) => Number(row.bytes) > SESSION_HISTORY_PAGE_BYTES;
|
|
3170
|
+
const run = page.filter((row) => !oversized(row));
|
|
3171
|
+
const references = page.filter(oversized).map(reference);
|
|
3172
|
+
const withPrefixes = {
|
|
3173
|
+
...read,
|
|
3174
|
+
throughSeq,
|
|
3175
|
+
...prefixes.size ? { prefixes } : {}
|
|
3176
|
+
};
|
|
3177
|
+
if (!run.length) return {
|
|
3178
|
+
...withPrefixes,
|
|
3179
|
+
items: references
|
|
3180
|
+
};
|
|
3181
|
+
if (run.some((row) => Number(row.chunks) > 0)) {
|
|
3182
|
+
const range = await this.readRange(sessionId, Number(run[0].seq), Number(run.at(-1).seq), read.epoch);
|
|
3183
|
+
const seqs = new Set(run.map((row) => Number(row.seq)));
|
|
3184
|
+
return {
|
|
3185
|
+
...withPrefixes,
|
|
3186
|
+
lastSeq: range.lastSeq,
|
|
3187
|
+
items: [...range.entries.map((entry, i) => ({
|
|
3188
|
+
seq: range.seqs[i],
|
|
3189
|
+
entry
|
|
3190
|
+
})).filter((item) => seqs.has(item.seq)), ...references]
|
|
3191
|
+
};
|
|
3192
|
+
}
|
|
3193
|
+
return {
|
|
3194
|
+
...withPrefixes,
|
|
3195
|
+
items: [...run.map((row) => ({
|
|
3196
|
+
seq: Number(row.seq),
|
|
3197
|
+
entry: JSON.parse(row.entry_json)
|
|
3198
|
+
})), ...references]
|
|
3199
|
+
};
|
|
3200
|
+
}
|
|
3201
|
+
/**
|
|
3202
|
+
* A condition on an entries row that holds for every entry `select` selects (and more): an entry larger than a page;
|
|
3203
|
+
* on SQLite and libSQL, a message whose stored type and role say it is a tool result, or an assistant message with a
|
|
3204
|
+
* tool call named other than `exceptCalls`, and any row that is not valid JSON; on Postgres, which would parse each
|
|
3205
|
+
* row's JSON to read those, any row whose JSON holds a tool call block's `"toolCall"` or a result's `"toolResult"`,
|
|
3206
|
+
* which `JSON.stringify`, the only writer of a row, always writes as such (it never escapes a letter).
|
|
3207
|
+
*/
|
|
3208
|
+
selected(row, select) {
|
|
3209
|
+
const json = `${row}.entry_json`;
|
|
3210
|
+
if (this.dialect.name !== "sqlite") return `(${row}.chunks > 0 OR ${this.dialect.contains(json, `'"toolCall"'`)} OR ${this.dialect.contains(json, `'"toolResult"'`)})`;
|
|
3211
|
+
return `(${row}.chunks > 0 OR NOT json_valid(${json}) OR json_extract(${json}, '$.type') = 'message' AND (
|
|
3212
|
+
json_extract(${json}, '$.message.role') = 'toolResult'
|
|
3213
|
+
OR json_extract(${json}, '$.message.role') = 'assistant' AND EXISTS (
|
|
3214
|
+
SELECT 1 FROM json_each(${json}, '$.message.content') b
|
|
3215
|
+
WHERE b.type = 'object' AND json_extract(b.value, '$.type') = 'toolCall' AND (${select.exceptCalls.length ? `json_type(b.value, '$.name') IS NOT 'text' OR json_extract(b.value, '$.name') NOT IN (${select.exceptCalls.map(() => "?").join(", ")})` : "1"})
|
|
3216
|
+
)
|
|
3217
|
+
))`;
|
|
3218
|
+
}
|
|
3219
|
+
selectedParams(select) {
|
|
3220
|
+
return this.dialect.name === "sqlite" ? select.exceptCalls : [];
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* One statement, so one snapshot without a transaction: the session row's generation, watermark and schema version
|
|
3224
|
+
* with the bytes, from the entry's own JSON or from the one stored chunk that holds `offset`.
|
|
3225
|
+
*/
|
|
3226
|
+
async readEntryChunk(reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) {
|
|
3227
|
+
this.assertOpen();
|
|
3228
|
+
const { sessionId, epoch, seq } = reference;
|
|
3229
|
+
const length = Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES);
|
|
3230
|
+
const generation = this.generation(sessionId);
|
|
3231
|
+
const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
|
|
3232
|
+
const row = await this.database.get(`SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
|
|
3233
|
+
(SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version, e.chunks,
|
|
3234
|
+
CASE WHEN e.chunks > 0
|
|
3235
|
+
THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx = ?)
|
|
3236
|
+
ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
|
|
3237
|
+
FROM ${this.tables.sessions} s LEFT JOIN ${this.tables.entries} e ON e.session_id = s.id AND e.seq = ?
|
|
3238
|
+
WHERE s.id = ?`, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, seq, sessionId);
|
|
3239
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3240
|
+
assertStorageSchemaVersion("sessions", row.schema_version, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
3241
|
+
this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
|
|
3242
|
+
if (row.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, Number(row.last_seq));
|
|
3243
|
+
if (row.chunks === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
3244
|
+
if (row.data === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
|
|
3245
|
+
return row.data;
|
|
3246
|
+
}
|
|
3247
|
+
async findEntrySeq(sessionId, entryId) {
|
|
3248
|
+
this.assertOpen();
|
|
3249
|
+
validateSessionText("sessionId", sessionId);
|
|
3250
|
+
validateSessionText("entry.id", entryId);
|
|
3251
|
+
if (!await this.readHeader(sessionId)) throw new SessionNotFoundError$1(sessionId);
|
|
3252
|
+
return this.seqOfEntry(this.database, sessionId, entryId);
|
|
3253
|
+
}
|
|
3254
|
+
/**
|
|
3255
|
+
* Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
|
|
3256
|
+
* links' entry-ID index: the statement reads each candidate's ID at its sequence itself, so no entry ID is bound or
|
|
3257
|
+
* returned, and no entry body is read. `undefined` while that index is still being built.
|
|
3258
|
+
*/
|
|
3259
|
+
async findTaskReferenceDuplicateCandidates(sessionId, query) {
|
|
3260
|
+
this.assertOpen();
|
|
3261
|
+
validateSessionText("sessionId", sessionId);
|
|
3262
|
+
const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
|
|
3263
|
+
return this.transaction(async (tx) => {
|
|
3264
|
+
const head = await this.historyHead(tx, sessionId);
|
|
3265
|
+
if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
|
|
3266
|
+
if (candidates.length === 0) return { seqs: [] };
|
|
3267
|
+
const t = snapshotIndexTables$1(this.prefix);
|
|
3268
|
+
const links = t.sessionLinks;
|
|
3269
|
+
/**
|
|
3270
|
+
* For each candidate `c`, the links row `s` at its sequence and then, with `earlier`, the rows `e` before it
|
|
3271
|
+
* under an ID, each found through an index, never by walking the session. Postgres plans a lateral subquery
|
|
3272
|
+
* behind `OFFSET 0` once per row before it; SQLite keeps a `CROSS JOIN`'s order. `+e.seq` keeps either from
|
|
3273
|
+
* reading the session's rows by sequence instead of by ID.
|
|
3274
|
+
*/
|
|
3275
|
+
const rowsOf = (earlier) => {
|
|
3276
|
+
const keys = [[
|
|
3277
|
+
"s",
|
|
3278
|
+
"entry_id",
|
|
3279
|
+
"s.session_id = ? AND s.seq = c.seq"
|
|
3280
|
+
]];
|
|
3281
|
+
if (earlier !== void 0) keys.push([
|
|
3282
|
+
"e",
|
|
3283
|
+
"seq",
|
|
3284
|
+
`e.session_id = ? AND e.entry_id = ${earlier} AND +e.seq < c.seq AND +e.seq > ?`
|
|
3285
|
+
]);
|
|
3286
|
+
if (this.dialect.name !== "postgres") return `c ${keys.map(([alias]) => `CROSS JOIN ${links} ${alias}`).join(" ")} WHERE ${keys.map(([, , key]) => key).join(" AND ")}`;
|
|
3287
|
+
return `c ${keys.map(([alias, column, key]) => `CROSS JOIN LATERAL (SELECT ${alias}.${column} FROM ${links} ${alias} WHERE ${key} OFFSET 0) ${alias}`).join(" ")}`;
|
|
3288
|
+
};
|
|
3289
|
+
const other = `CASE WHEN c.idx >= 0 THEN s.entry_id || ':' || CAST(c.idx AS TEXT)
|
|
3290
|
+
WHEN c.suffix > 0 AND c.suffix <= length(s.entry_id) AND substr(s.entry_id, length(s.entry_id) - c.suffix + 1, 1) = ':'
|
|
3291
|
+
THEN substr(s.entry_id, 1, length(s.entry_id) - c.suffix) END`;
|
|
3292
|
+
const values = candidates.map(() => `(CAST(? AS ${this.dialect.types.int}), CAST(? AS INTEGER), CAST(? AS INTEGER))`);
|
|
3293
|
+
const rows = await tx.all(`WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
|
|
3294
|
+
hits AS (SELECT e.seq AS seq FROM ${rowsOf("s.entry_id")} UNION SELECT e.seq FROM ${rowsOf(other)})
|
|
3295
|
+
SELECT 0 AS kind, (SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END FROM ${t.sources} WHERE source = 'session-entries') AS seq
|
|
3296
|
+
UNION ALL SELECT 1, count(*) FROM ${rowsOf()}
|
|
3297
|
+
UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`, ...candidates.flat(), ...[
|
|
3298
|
+
sessionId,
|
|
3299
|
+
sessionId,
|
|
3300
|
+
afterSeq,
|
|
3301
|
+
sessionId,
|
|
3302
|
+
sessionId,
|
|
3303
|
+
afterSeq,
|
|
3304
|
+
sessionId,
|
|
3305
|
+
limit + 1
|
|
3306
|
+
]);
|
|
3307
|
+
let indexed = false;
|
|
3308
|
+
let found = 0;
|
|
3309
|
+
const seqs = [];
|
|
3310
|
+
for (const row of rows) if (Number(row.kind) === 0) indexed = Number(row.seq) === 1;
|
|
3311
|
+
else if (Number(row.kind) === 1) found = Number(row.seq);
|
|
3312
|
+
else seqs.push(Number(row.seq));
|
|
3313
|
+
if (!indexed) return void 0;
|
|
3314
|
+
if (found !== candidates.length) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
|
|
3315
|
+
seqs.sort((a, b) => a - b);
|
|
3316
|
+
return seqs.length > limit ? {
|
|
3317
|
+
seqs: seqs.slice(0, limit),
|
|
3318
|
+
nextAfterSeq: seqs[limit - 1]
|
|
3319
|
+
} : { seqs };
|
|
3320
|
+
}, SESSION_TRANSACTION);
|
|
3321
|
+
}
|
|
3322
|
+
async readForkWindow(sessionId, entryId, options) {
|
|
3323
|
+
this.assertOpen();
|
|
3324
|
+
validateSessionText("sessionId", sessionId);
|
|
3325
|
+
const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3326
|
+
return this.transaction(async (tx) => {
|
|
3327
|
+
const snapshots = snapshotIndexTables$1(this.prefix);
|
|
3328
|
+
const row = await tx.get(`SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM ${snapshots.sessionLinks} WHERE session_id=s.id AND entry_id=?) ELSE (SELECT max(seq) FROM ${this.tables.entries} WHERE session_id=s.id AND entry_id=?) END AS leaf_seq FROM ${this.tables.sessions} s WHERE s.id=?${this.dialect.lockClause("share")}`, entryId, entryId, sessionId);
|
|
3329
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3330
|
+
const header = JSON.parse(row.header_json);
|
|
3331
|
+
const state = JSON.parse(row.summary_state);
|
|
3332
|
+
const count = Number(row.last_seq);
|
|
3333
|
+
const cached = this.resumeIndexes.get(sessionId);
|
|
3334
|
+
const ready = windowIndex(state, count) ?? (cached?.revision === row.revision ? cached.index : void 0);
|
|
3335
|
+
const leaf = Number(row.leaf_seq);
|
|
3336
|
+
if (!leaf) return void 0;
|
|
3337
|
+
const metadata = async (seqs) => {
|
|
3338
|
+
const result = [];
|
|
3339
|
+
if (!seqs.length) return result;
|
|
3340
|
+
const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
|
|
3341
|
+
const size = this.dialect.textByteLength("entry_json");
|
|
3342
|
+
const rows = await tx.all(`SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${this.tables.entries} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`, sessionId, ...seqs);
|
|
3343
|
+
for (const row of rows) {
|
|
3344
|
+
const seq = Number(row.seq);
|
|
3345
|
+
if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
|
|
3346
|
+
else if (Number(row.chunks) > 0) {
|
|
3347
|
+
const { projectForkMetadata } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3348
|
+
result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, sessionId, seq, Number(row.chunks))));
|
|
3349
|
+
} else result.push(await byteMetadata(seq, Number(row.bytes), async (offset, n) => {
|
|
3350
|
+
const piece = await tx.get(`SELECT substr(${raw},?,?) AS part FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, offset + 1, n, sessionId, seq);
|
|
3351
|
+
if (!piece) throw new StorageError(`Session ${sessionId} entry ${seq} disappeared during its fork`);
|
|
3352
|
+
return piece.part;
|
|
3353
|
+
}));
|
|
3354
|
+
}
|
|
3355
|
+
return result;
|
|
3356
|
+
};
|
|
3357
|
+
const entries = this.tables.entries;
|
|
3358
|
+
const j = (field) => this.dialect.jsonText("entry_json", field);
|
|
3359
|
+
const selected = ready ? {
|
|
3360
|
+
index: ready,
|
|
3361
|
+
leaf,
|
|
3362
|
+
extras: void 0
|
|
3363
|
+
} : await locateFork({
|
|
3364
|
+
...foldSessionResume(void 0, []),
|
|
3365
|
+
seq: count,
|
|
3366
|
+
epoch: state.epoch ?? row.revision,
|
|
3367
|
+
needsBranchRebuild: true
|
|
3368
|
+
}, entryId, async (seqs) => {
|
|
3369
|
+
const pg = this.dialect.name === "postgres";
|
|
3370
|
+
const key = (...path) => pg ? this.dialect.jsonAt({
|
|
3371
|
+
column: "entry_json",
|
|
3372
|
+
element: "parsed"
|
|
3373
|
+
}, ...path) : this.dialect.jsonText("entry_json", ...path);
|
|
3374
|
+
const projection = this.dialect.jsonArray([
|
|
3375
|
+
"entry_id",
|
|
3376
|
+
key("parentId"),
|
|
3377
|
+
key("type"),
|
|
3378
|
+
key("customType"),
|
|
3379
|
+
key("firstKeptEntryId"),
|
|
3380
|
+
key("coveredThroughEntryId"),
|
|
3381
|
+
key("details", "strategy"),
|
|
3382
|
+
`CASE WHEN ${key("customType")} IN ('task-completion-intent','task-completion-ack') AND ${this.dialect.jsonAtIsText(pg ? {
|
|
3383
|
+
column: "entry_json",
|
|
3384
|
+
element: "parsed"
|
|
3385
|
+
} : { column: "entry_json" }, "data", "completionId")} THEN ${key("data", "completionId")} END`,
|
|
3386
|
+
key("message", "role")
|
|
3387
|
+
]);
|
|
3388
|
+
const parsed = (await tx.all(`WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${entries} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
|
|
3389
|
+
seq: Number(r.seq),
|
|
3390
|
+
chunked: Number(r.chunks) > 0,
|
|
3391
|
+
link: r.link === null ? void 0 : JSON.parse(r.link)
|
|
3392
|
+
}));
|
|
3393
|
+
const roles = /* @__PURE__ */ new Map();
|
|
3394
|
+
const chunkedMessages = parsed.filter((r) => r.chunked && r.link?.[2] === "message").map((r) => r.seq);
|
|
3395
|
+
if (chunkedMessages.length) {
|
|
3396
|
+
const { messageRoleIn } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3397
|
+
for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
|
|
3398
|
+
const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
|
|
3399
|
+
const prefixes = await tx.all(`SELECT seq,substr(data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${this.tables.entryChunks} WHERE session_id=? AND idx=0 AND seq IN (${batch.map(() => "?").join(",")})`, sessionId, ...batch);
|
|
3400
|
+
for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
const page = [];
|
|
3404
|
+
for (const { seq, chunked, link } of parsed) {
|
|
3405
|
+
const role = chunked ? roles.get(seq) : link?.[8];
|
|
3406
|
+
if (!link || chunked && (link[2] === "custom" || link[2] === "compaction" || link[2] === "message" && role === void 0)) page.push(...await metadata([seq]));
|
|
3407
|
+
else {
|
|
3408
|
+
const [id, parentId, type, customType, first, covered, strategy, completionId] = link;
|
|
3409
|
+
page.push({
|
|
3410
|
+
seq,
|
|
3411
|
+
id,
|
|
3412
|
+
parentId,
|
|
3413
|
+
type,
|
|
3414
|
+
customType: customType ?? void 0,
|
|
3415
|
+
completionId: completionId ?? void 0,
|
|
3416
|
+
...type === "message" && role === "system" ? { system: true } : {},
|
|
3417
|
+
...type === "compaction" && strategy === "verbatim-lines" ? { boundary: {
|
|
3418
|
+
first,
|
|
3419
|
+
covered: covered ?? void 0
|
|
3420
|
+
} } : {}
|
|
3421
|
+
});
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
return page;
|
|
3425
|
+
}, true, SESSION_READ_FETCH.max);
|
|
3426
|
+
const labelBody = `CASE WHEN chunks=0 AND ${this.dialect.textByteLength("entry_json")}<=512 THEN entry_json END`;
|
|
3427
|
+
return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, "seq BETWEEN ? AND ?", [lo, hi]), (seqs) => this.readSeqs(tx, sessionId, seqs), metadata, async function* (ranges, kinds, types = []) {
|
|
3428
|
+
const filters = [];
|
|
3429
|
+
if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
|
|
3430
|
+
if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
|
|
3431
|
+
for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
|
|
3432
|
+
const labels = types.length === 1 && types[0] === "label";
|
|
3433
|
+
const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
|
|
3434
|
+
const rows = await tx.all(`SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${entries} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`, sessionId, seq, hi, ...types, ...kinds);
|
|
3435
|
+
const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
|
|
3436
|
+
const projected = /* @__PURE__ */ new Map();
|
|
3437
|
+
for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
|
|
3438
|
+
for (const row of rows) yield projected.get(Number(row.seq)) ?? (row.body ? forkMetadata(Number(row.seq), JSON.parse(row.body)) : {
|
|
3439
|
+
type: row.kind,
|
|
3440
|
+
seq: Number(row.seq)
|
|
3441
|
+
});
|
|
3442
|
+
if (rows.length < limit) break;
|
|
3443
|
+
seq = Number(rows.at(-1).seq) + 1;
|
|
3444
|
+
}
|
|
3445
|
+
}, {
|
|
3446
|
+
...selected.extras,
|
|
3447
|
+
...options
|
|
3448
|
+
});
|
|
3449
|
+
}, SESSION_TRANSACTION);
|
|
3450
|
+
}
|
|
3451
|
+
async *forkEntryChunks(tx, id, seq, count) {
|
|
3452
|
+
for (let i = 0; i < count; i++) {
|
|
3453
|
+
const row = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, id, seq, i);
|
|
3454
|
+
if (!row) throw new StorageError(`Session ${id} entry ${seq} is missing chunk ${i} of ${count}`);
|
|
3455
|
+
yield row.data;
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
async readChildCatalogCut(sessionId) {
|
|
3459
|
+
this.assertOpen();
|
|
3460
|
+
return childCatalogCut((await this.prepareResume(sessionId)).index);
|
|
3461
|
+
}
|
|
3462
|
+
readResumeAt(sessionId, leafId, throughSeq, options) {
|
|
3463
|
+
return this.resumeWindow(sessionId, leafId, throughSeq, options);
|
|
3464
|
+
}
|
|
3465
|
+
readResume(sessionId, leafId, options) {
|
|
3466
|
+
return this.resumeWindow(sessionId, leafId, void 0, options);
|
|
3467
|
+
}
|
|
3468
|
+
async resumeWindow(sessionId, leafId, throughSeq, options) {
|
|
3469
|
+
this.assertOpen();
|
|
3470
|
+
validateSessionText("sessionId", sessionId);
|
|
3471
|
+
if (leafId !== void 0) validateSessionText("entry.id", leafId);
|
|
3472
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
3473
|
+
const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
|
|
3474
|
+
const resume = await this.transaction(async (tx) => {
|
|
3475
|
+
const head = await tx.get(`SELECT header_json,revision FROM ${this.tables.sessions} WHERE id = ?${this.dialect.lockClause("share")}`, sessionId);
|
|
3476
|
+
if (!head) throw new SessionNotFoundError$1(sessionId);
|
|
3477
|
+
if (revision !== head.revision) return void 0;
|
|
3478
|
+
const header = JSON.parse(head.header_json);
|
|
3479
|
+
const { leafSeq } = index;
|
|
3480
|
+
const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
|
|
3481
|
+
announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
|
|
3482
|
+
const branch = [];
|
|
3483
|
+
for (const [start, end] of plan.branch) branch.push(...await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]));
|
|
3484
|
+
const state = await this.readSeqs(tx, sessionId, plan.state);
|
|
3485
|
+
const leaf = leafSeq <= 0 ? void 0 : await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
|
|
3486
|
+
const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
|
|
3487
|
+
if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
|
|
3488
|
+
return resume;
|
|
3489
|
+
}, SESSION_TRANSACTION);
|
|
3490
|
+
if (resume !== void 0) return resume;
|
|
3491
|
+
}
|
|
3492
|
+
throw new SessionConflictError$1(sessionId, 0, 0);
|
|
3493
|
+
}
|
|
3494
|
+
async findLatestCompaction(sessionId, leafId) {
|
|
3495
|
+
this.assertOpen();
|
|
3496
|
+
validateSessionText("sessionId", sessionId);
|
|
3497
|
+
if (leafId !== void 0) validateSessionText("entry.id", leafId);
|
|
3498
|
+
await this.prepareResume(sessionId);
|
|
3499
|
+
const { point } = await this.transaction(async (tx) => {
|
|
3500
|
+
const source = await this.resumeSource(tx, sessionId);
|
|
3501
|
+
const { index } = source;
|
|
3502
|
+
const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
|
|
3503
|
+
const found = latestCompactionOf(index, leafSeq);
|
|
3504
|
+
if (found === void 0) return {
|
|
3505
|
+
point: void 0,
|
|
3506
|
+
source
|
|
3507
|
+
};
|
|
3508
|
+
const [boundary] = await this.readSeqs(tx, sessionId, [found.seq]);
|
|
3509
|
+
const leaf = await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
|
|
3510
|
+
if (boundary === void 0 || leaf === void 0) return {
|
|
3511
|
+
point: void 0,
|
|
3512
|
+
source
|
|
3513
|
+
};
|
|
3514
|
+
return {
|
|
3515
|
+
point: {
|
|
3516
|
+
...found,
|
|
3517
|
+
entry: boundary.entry,
|
|
3518
|
+
leafId: leaf.entry_id,
|
|
3519
|
+
lastSeq: index.seq
|
|
3520
|
+
},
|
|
3521
|
+
source
|
|
3522
|
+
};
|
|
3523
|
+
}, SESSION_TRANSACTION);
|
|
3524
|
+
return point;
|
|
3525
|
+
}
|
|
3526
|
+
/** The JSON of a long entry, from its chunks, one statement each. */
|
|
3527
|
+
async readEntryChunks(tx, sessionId, seq, count) {
|
|
3528
|
+
return Buffer.concat(await this.readRawEntryChunks(tx, sessionId, seq, count)).toString("utf8");
|
|
3529
|
+
}
|
|
3530
|
+
async readRawEntryChunks(tx, sessionId, seq, count, signal) {
|
|
3531
|
+
const chunks = [];
|
|
3532
|
+
for (let index = 0; index < count; index++) {
|
|
3533
|
+
signal?.throwIfAborted();
|
|
3534
|
+
const chunk = await tx.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?`, sessionId, seq, index);
|
|
3535
|
+
if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
|
|
3536
|
+
chunks.push(chunk.data);
|
|
3537
|
+
if (signal !== void 0 && index + 1 < count) await yieldTurn();
|
|
3538
|
+
}
|
|
3539
|
+
return chunks;
|
|
3540
|
+
}
|
|
3541
|
+
async *entryChunks(sessionId, seq, count, revision) {
|
|
3542
|
+
for (let index = 0; index < count; index++) {
|
|
3543
|
+
const chunk = await this.database.get(`SELECT data FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ? AND idx = ?
|
|
3544
|
+
AND EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`, sessionId, seq, index, sessionId, revision);
|
|
3545
|
+
if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
|
|
3546
|
+
yield chunk.data;
|
|
3547
|
+
if (index + 1 < count) await yieldTurn();
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
async readInlineEntryBytes(sessionId, seq) {
|
|
3551
|
+
if (this.dialect.name === "sqlite") {
|
|
3552
|
+
const row = await this.database.get(`SELECT CAST(entry_json AS BLOB) AS data FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
|
|
3553
|
+
return row ? [row.data] : [];
|
|
3554
|
+
}
|
|
3555
|
+
const row = await this.database.get(`SELECT entry_json FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, seq);
|
|
3556
|
+
return row ? [new TextEncoder().encode(row.entry_json)] : [];
|
|
3557
|
+
}
|
|
3558
|
+
async forWrite(tx, sessionId, options, includeSummaryState = false) {
|
|
3559
|
+
const row = await tx.get(`SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}
|
|
3560
|
+
FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
3561
|
+
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3562
|
+
const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
|
|
3563
|
+
if (row.last_seq !== options.expectSeq || options.epoch !== void 0 && state?.epoch !== options.epoch) throw new SessionConflictError$1(sessionId, options.expectSeq, row.last_seq);
|
|
3564
|
+
return {
|
|
3565
|
+
row,
|
|
3566
|
+
state
|
|
3567
|
+
};
|
|
3568
|
+
}
|
|
3569
|
+
async appendedResume(tx, sessionId, previous, lastSeq, entries) {
|
|
3570
|
+
if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
|
|
3571
|
+
const seqs = /* @__PURE__ */ new Map();
|
|
3572
|
+
for (const id of foreignResumeIds(previous, entries)) {
|
|
3573
|
+
const seq = await this.seqOfEntry(tx, sessionId, id);
|
|
3574
|
+
if (seq !== void 0) seqs.set(id, seq);
|
|
3575
|
+
}
|
|
3576
|
+
return foldSessionResume(previous, entries, (id) => seqs.get(id));
|
|
3577
|
+
}
|
|
3578
|
+
async seqOfEntry(executor, sessionId, entryId) {
|
|
3579
|
+
const tables = snapshotIndexTables$1(this.prefix);
|
|
3580
|
+
const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${tables.sources} WHERE source = 'session-entries'`);
|
|
3581
|
+
if (Number(source?.complete) === 1) {
|
|
3582
|
+
const linked = await executor.get(`SELECT seq FROM ${tables.sessionLinks} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
|
|
3583
|
+
return linked === void 0 ? void 0 : Number(linked.seq);
|
|
3584
|
+
}
|
|
3585
|
+
const row = await executor.get(`SELECT seq FROM ${this.tables.entries} WHERE session_id = ? AND entry_id = ? ORDER BY seq DESC LIMIT 1`, sessionId, entryId);
|
|
3586
|
+
return row === void 0 ? void 0 : Number(row.seq);
|
|
3587
|
+
}
|
|
3588
|
+
async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
|
|
3589
|
+
const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
|
|
3590
|
+
await tx.run(statement.sql, ...statement.params);
|
|
3591
|
+
return {
|
|
3592
|
+
texts,
|
|
3593
|
+
epoch
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
/** The statement that saves the session's row as `saveSummary` saves it, with what `saveSummary` returns. */
|
|
3597
|
+
summaryWrite(sessionId, snapshot, previous, appendedResume) {
|
|
3598
|
+
const { header, lastSeq } = snapshot;
|
|
3599
|
+
const { state: listed, texts } = applySessionSummaryEntries(previous, snapshot.entries);
|
|
3600
|
+
const resume = previous === void 0 ? foldSessionResume(void 0, snapshot.entries) : appendedResume;
|
|
3601
|
+
const epoch = resume?.epoch ?? previous?.epoch ?? newRevision();
|
|
3602
|
+
const state = {
|
|
3603
|
+
...listed,
|
|
3604
|
+
...windowFields(previous, resume, lastSeq, epoch),
|
|
3605
|
+
epoch
|
|
3606
|
+
};
|
|
3607
|
+
const summary = materializeSessionSummaryMetadata(header, state);
|
|
3608
|
+
return {
|
|
3609
|
+
statement: {
|
|
3610
|
+
sql: `INSERT INTO ${this.tables.sessions}
|
|
3611
|
+
(id, cwd, created_at, header_json, internal, last_seq, modified_at, message_count,
|
|
3612
|
+
first_message, name, has_name, summary, summarized_through_id, summary_state, revision)
|
|
3613
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3614
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
3615
|
+
cwd = excluded.cwd, created_at = excluded.created_at, header_json = excluded.header_json,
|
|
3616
|
+
internal = excluded.internal, last_seq = excluded.last_seq, modified_at = excluded.modified_at,
|
|
3617
|
+
message_count = excluded.message_count, first_message = excluded.first_message, name = excluded.name,
|
|
3618
|
+
has_name = excluded.has_name, summary = excluded.summary,
|
|
3619
|
+
summarized_through_id = excluded.summarized_through_id,
|
|
3620
|
+
summary_state = excluded.summary_state, revision = excluded.revision`,
|
|
3621
|
+
params: [
|
|
3622
|
+
sessionId,
|
|
3623
|
+
header.cwd,
|
|
3624
|
+
header.createdAt,
|
|
3625
|
+
this.encode(header),
|
|
3626
|
+
header.internal ? 1 : 0,
|
|
3627
|
+
lastSeq,
|
|
3628
|
+
summary.modifiedAt,
|
|
3629
|
+
summary.messageCount,
|
|
3630
|
+
this.encode(summary.firstMessage),
|
|
3631
|
+
summary.name === void 0 ? null : this.encode(summary.name),
|
|
3632
|
+
summary.hasName ? 1 : 0,
|
|
3633
|
+
summary.summary === void 0 ? null : this.encode(summary.summary),
|
|
3634
|
+
summary.summarizedThroughId ?? null,
|
|
3635
|
+
this.encode(state),
|
|
3636
|
+
newRevision()
|
|
3637
|
+
]
|
|
3638
|
+
},
|
|
3639
|
+
texts,
|
|
3640
|
+
epoch
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
3643
|
+
async insertEntries(tx, sessionId, entries, lastSeq, texts) {
|
|
3644
|
+
for (const { sql, params } of this.entryWrites(sessionId, entries, lastSeq, texts)) await tx.run(sql, ...params);
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
|
|
3648
|
+
* taken: each entry's row and its chunks, the version step a first chunked entry takes, then the entries' search
|
|
3649
|
+
* texts.
|
|
3650
|
+
*/
|
|
3651
|
+
*entryWrites(sessionId, entries, lastSeq, texts) {
|
|
3652
|
+
let chunked = false;
|
|
3653
|
+
for (const [index, entry] of entries.entries()) {
|
|
3654
|
+
const seq = lastSeq + index + 1;
|
|
3655
|
+
const stored = storedEntry(entry, this.encode(entry));
|
|
3656
|
+
chunked ||= stored.chunks.length > 0;
|
|
3657
|
+
yield {
|
|
3658
|
+
sql: `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) VALUES (?, ?, ?, ?, ?)`,
|
|
3659
|
+
params: [
|
|
3660
|
+
sessionId,
|
|
3661
|
+
seq,
|
|
3662
|
+
entry.id,
|
|
3663
|
+
stored.json,
|
|
3664
|
+
stored.chunks.length
|
|
3665
|
+
]
|
|
3666
|
+
};
|
|
3667
|
+
if (stored.chunks.length > 0) yield {
|
|
3668
|
+
sql: `DELETE FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ?`,
|
|
3669
|
+
params: [sessionId, seq]
|
|
3670
|
+
};
|
|
3671
|
+
for (const [chunk, data] of stored.chunks.entries()) yield {
|
|
3672
|
+
sql: `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) VALUES (?, ?, ?, ?)`,
|
|
3673
|
+
params: [
|
|
3674
|
+
sessionId,
|
|
3675
|
+
seq,
|
|
3676
|
+
chunk,
|
|
3677
|
+
data
|
|
3678
|
+
]
|
|
3679
|
+
};
|
|
3680
|
+
}
|
|
3681
|
+
if (chunked) yield {
|
|
3682
|
+
sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
|
|
3683
|
+
params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
|
|
3684
|
+
};
|
|
3685
|
+
for (const { index, text } of texts) yield {
|
|
3686
|
+
sql: `INSERT INTO ${this.tables.searchTexts} (session_id, seq, text_json) VALUES (?, ?, ?)`,
|
|
3687
|
+
params: [
|
|
3688
|
+
sessionId,
|
|
3689
|
+
lastSeq + index + 1,
|
|
3690
|
+
this.encode(text)
|
|
3691
|
+
]
|
|
3692
|
+
};
|
|
3693
|
+
}
|
|
3694
|
+
/**
|
|
3695
|
+
* Runs the session row's statement, then `entries`' statements, in order. A write of up to
|
|
3696
|
+
* {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes to a connection thread as one batch that waits for
|
|
3697
|
+
* it once. A larger one runs its statements one at a time as they are made, as before, so it never holds more than
|
|
3698
|
+
* about that much of them, or sends it, at once.
|
|
3699
|
+
*/
|
|
3700
|
+
async writeEntries(tx, summary, entries) {
|
|
3701
|
+
const batch = [summary];
|
|
3702
|
+
let bytes = statementBytes(summary);
|
|
3703
|
+
const pending = entries[Symbol.iterator]();
|
|
3704
|
+
for (let next = pending.next(); next.done !== true; next = pending.next()) {
|
|
3705
|
+
batch.push(next.value);
|
|
3706
|
+
bytes += statementBytes(next.value);
|
|
3707
|
+
if (bytes <= STATEMENT_BATCH_BYTES) continue;
|
|
3708
|
+
for (const { sql, params } of batch) await tx.run(sql, ...params);
|
|
3709
|
+
for (let rest = pending.next(); rest.done !== true; rest = pending.next()) await tx.run(rest.value.sql, ...rest.value.params);
|
|
3710
|
+
return;
|
|
3711
|
+
}
|
|
3712
|
+
await statementBatch(tx, batch, []);
|
|
3713
|
+
}
|
|
3714
|
+
encode(value) {
|
|
3715
|
+
try {
|
|
3716
|
+
return JSON.stringify(value);
|
|
3717
|
+
} catch (cause) {
|
|
3718
|
+
throw new StorageUnavailableError$1(this.descriptor, cause);
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3721
|
+
};
|
|
3722
|
+
const nativeLoad = registerArchiveLoad(SqlSessionStore.prototype.load);
|
|
3723
|
+
/** The running sessions that have a SQL store's sessions open, in a table every host sharing the store reads (#4971). */
|
|
3724
|
+
var SqlSessionOpenMarkers = class {
|
|
3725
|
+
static async createTable(tx, dialect, table) {
|
|
3726
|
+
const { int, text } = dialect.types;
|
|
3727
|
+
await tx.exec(`
|
|
3728
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
3729
|
+
session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
|
|
3730
|
+
heartbeat_at ${int} NOT NULL, PRIMARY KEY(session_id, token)
|
|
3731
|
+
)${dialect.tableOptions};
|
|
3732
|
+
`);
|
|
3733
|
+
}
|
|
3734
|
+
/**
|
|
3735
|
+
* Each marker records the sessions schema version its process reads, so a build that upgrades the schema can tell
|
|
3736
|
+
* that a process which would misread the upgraded schema still has a session open (#5065). Null for markers of
|
|
3737
|
+
* builds before it. Additive, as every step of this domain must be.
|
|
3738
|
+
*/
|
|
3739
|
+
static async addSchemaVersion(tx, dialect, table) {
|
|
3740
|
+
const probe = dialect.columnExists(table, "schema_version");
|
|
3741
|
+
if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN schema_version ${dialect.types.int}`);
|
|
3742
|
+
}
|
|
3743
|
+
database;
|
|
3744
|
+
table;
|
|
3745
|
+
assertOpen;
|
|
3746
|
+
constructor(database, table, assertOpen) {
|
|
3747
|
+
this.database = database;
|
|
3748
|
+
this.table = table;
|
|
3749
|
+
this.assertOpen = assertOpen;
|
|
3750
|
+
}
|
|
3751
|
+
async put(sessionId, marker) {
|
|
3752
|
+
this.assertOpen();
|
|
3753
|
+
const now = dialectOf(this.database).nowMs;
|
|
3754
|
+
await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version) VALUES (?, ?, ?, ?, ${now}, ?)
|
|
3755
|
+
ON CONFLICT(session_id, token) DO UPDATE SET pid = excluded.pid, host = excluded.host,
|
|
3756
|
+
heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version`, sessionId, marker.token, marker.pid, marker.host, 2);
|
|
3757
|
+
}
|
|
3758
|
+
async remove(sessionId, token) {
|
|
3759
|
+
this.assertOpen();
|
|
3760
|
+
await this.database.run(`DELETE FROM ${this.table} WHERE session_id = ? AND token = ?`, sessionId, token);
|
|
3761
|
+
}
|
|
3762
|
+
async list(sessionId) {
|
|
3763
|
+
this.assertOpen();
|
|
3764
|
+
const now = dialectOf(this.database).nowMs;
|
|
3765
|
+
return (await this.database.all(`SELECT token, pid, host, ${now} - heartbeat_at AS age_ms FROM ${this.table} WHERE session_id = ?`, sessionId)).map((row) => ({
|
|
3766
|
+
token: row.token,
|
|
3767
|
+
pid: Number(row.pid),
|
|
3768
|
+
host: row.host,
|
|
3769
|
+
ageMs: Number(row.age_ms)
|
|
3770
|
+
}));
|
|
3771
|
+
}
|
|
3772
|
+
};
|
|
910
3773
|
// dist/core/transcript.js
|
|
911
3774
|
/** A detached, JSON-shaped copy, so callers cannot mutate transcript state and parts always serialize. */
|
|
912
3775
|
function toJson(value) {
|
|
@@ -7401,16 +10264,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
|
|
|
7401
10264
|
});
|
|
7402
10265
|
}
|
|
7403
10266
|
};
|
|
7404
|
-
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SNAPSHOT_COLLECTION_BATCH, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
|
|
10267
|
+
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
|
|
7405
10268
|
|
|
7406
|
-
//# sourceMappingURL=sdk-
|
|
10269
|
+
//# sourceMappingURL=sdk-OSBEPR3Q.js.map
|
|
7407
10270
|
// __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
|
|
7408
10271
|
// demand that fails in a process an in-place update left running says to restart.
|
|
7409
10272
|
function __atomicOnDemandFailed(error, feature) {
|
|
7410
10273
|
return (async () => {
|
|
7411
10274
|
const root = new URL("../", import.meta.url);
|
|
7412
10275
|
const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
|
|
7413
|
-
const key = `${root.href}#0.10.
|
|
10276
|
+
const key = `${root.href}#0.10.8`;
|
|
7414
10277
|
let release = releases.get(key);
|
|
7415
10278
|
if (release === undefined) {
|
|
7416
10279
|
const current = (async () => {
|
|
@@ -7438,7 +10301,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
7438
10301
|
} catch {
|
|
7439
10302
|
// No installation to read, as in a bundle of the package: the release the process runs decides.
|
|
7440
10303
|
}
|
|
7441
|
-
const updatedTo = typeof installed === "string" && installed !== "0.10.
|
|
10304
|
+
const updatedTo = typeof installed === "string" && installed !== "0.10.8" ? installed : running !== undefined && running.version !== "0.10.8" ? "0.10.8" : undefined;
|
|
7442
10305
|
if (updatedTo === undefined) throw error;
|
|
7443
10306
|
const application = typeof running?.name === "string" ? running.name : "atomic";
|
|
7444
10307
|
const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
|