@qqbrowser/qbot-dsh 0.0.10 → 0.0.12
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/lib/bin.js +1 -1
- package/lib/{dump-config-BD79jvHi.js → dump-config-xQTUTTDD.js} +1 -1
- package/lib/{plugin-B3Ecl7VN.js → plugin-DNAeLZbb.js} +1 -1
- package/lib/profile-boot-BkordgJK.js +1 -0
- package/node_modules/@deepseek-ai/cordis/package.json +1 -1
- package/node_modules/@deepseek-ai/cordis-plugin-hmr/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/cordis-plugin-hmr/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-agent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-default-model/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-instructions/lib/index.js +3 -3
- package/node_modules/@deepseek-ai/dsh-agent-instructions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-loop/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-agent-tool-presentation/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-anonymous-user-id/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-api-gateway/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-api-remotes/lib/client.js +2 -2
- package/node_modules/@deepseek-ai/dsh-api-remotes/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-app-boot/lib/index.js +12 -12
- package/node_modules/@deepseek-ai/dsh-app-boot/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-atomic-write/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment-local/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-attachment-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-base/cordis.patch.yml +4 -4
- package/node_modules/@deepseek-ai/dsh-base/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-bash-local/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-bash-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-bash-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-brand/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-connection/lib/client.js +6 -6
- package/node_modules/@deepseek-ai/dsh-client-connection/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-client-connection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-hmr/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-locale/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-locale/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-modules/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-runtime/lib/client.js +2 -2
- package/node_modules/@deepseek-ai/dsh-client-runtime/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-schema-form/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-agent-preset/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-attachment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-commands/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-commands/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-conversation/lib/client.js +6 -6
- package/node_modules/@deepseek-ai/dsh-client-ui-conversation/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-cordis/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-cordis/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-deliverables/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-browse/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-directory-picker-native/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-goal/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-input-trigger/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-jobs/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-layout/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-layout/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-message-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-model-selection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-permission-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-plan/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-plan/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-primitives/lib/index.js +11 -11
- package/node_modules/@deepseek-ai/dsh-client-ui-primitives/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-general/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-models/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugin-inventory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-settings-plugins/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-sidebar/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-skill/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-slots/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-slots/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-subagent/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-theme/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-theme/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-tool/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-tool/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/lib/client.js +13 -13
- package/node_modules/@deepseek-ai/dsh-client-ui-trajectory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-user-questions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workflow-run/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workspace/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-ui-workspace/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-client-web-react/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-client-web-react/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cmdline/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-code-runtime/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/lib/worker.cjs +4 -2
- package/node_modules/@deepseek-ai/dsh-code-runtime-worker-thread/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-compact/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-command-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-commands/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction-basic/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction-basic/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-compaction-tool-result-pruner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-content-review/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cordis-client-runner/lib/client.js +7 -7
- package/node_modules/@deepseek-ai/dsh-cordis-client-runner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-cordis-host-runner/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-credentials/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-credentials-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-local/lib/index.js +4 -4
- package/node_modules/@deepseek-ai/dsh-fs-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-observation-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-fs-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-goal-round-driver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-headless/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-home-paths/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-home-quarantine-macos/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-home-quarantine-macos/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-apiproxy/lib/index.js +4 -4
- package/node_modules/@deepseek-ai/dsh-host-apiproxy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-auto/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-browse/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-native/lib/worker.cjs +9 -7
- package/node_modules/@deepseek-ai/dsh-host-directory-picker-native/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-frontend-static/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-plugin-inventory/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-host-webserver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-invariants/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-jobs-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-launch-environment/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-deepseek/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-deepseek/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-gateway-openai/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-gateway-openai/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-pi-ai/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-pi-ai/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-llm-retry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-mcp-client/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-mcp-client/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-message-feedback/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-native-command/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-output-retention/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-output-retention/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-permission-presets/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-permission-presets/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-persona/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-plan-mode/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-pwsh-local/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-pwsh-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-pwsh-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-qb-auth/lib/index.js +3 -3
- package/node_modules/@deepseek-ai/dsh-qb-auth/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-repeat-tool-reminder/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/runner.js +1 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/types-D2_FQYSK.js +1 -0
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-schedule/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-schedule/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-scope/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-session/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-session/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-checkpoint-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-log-export/lib/client.js +1 -1
- package/node_modules/@deepseek-ai/dsh-session-log-export/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence-jsonl/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-session-persistence-jsonl/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-projection/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-projection-cache/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-query/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-query-sqlite/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-reference/lib/index.js +4 -4
- package/node_modules/@deepseek-ai/dsh-session-reference/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-stats/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-telemetry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-telemetry-otel/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-session-title/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title-first-prompt-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-session-title-llm/lib/index.js +3 -3
- package/node_modules/@deepseek-ai/dsh-session-title-llm/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-settings/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-settings/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-settings-file/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-shell/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-shell-env/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill-badge/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-skill-filesystem/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-skill-filesystem/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill-local/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-spill-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-spill-policy/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-spill-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage-domain/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-storage-domain/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-storage-json/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-fork-in-process/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-in-process-driver/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subagent-spawn-in-process/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subprocess/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-subprocess-local/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-system-prompt/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-terminal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-terminal-bash/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-terminal-bash/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-time-context/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-time-context/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-time-context/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-timeout/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tmux-context/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-token-meter/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-token-meter/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-ask-user/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-bash/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-bash-persistent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-call-timeout-policy/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-cordis/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-fs/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-tool-fs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-fs-search/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-fs-search/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-goal/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-jobs/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-pwsh/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-ralph/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-ralph/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-skill/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-str-replace-editor/lib/index.js +6 -6
- package/node_modules/@deepseek-ai/dsh-tool-str-replace-editor/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent-control/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-subagent-report/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-todo/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tool-workflow/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-tool-workflow/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-tools/lib/index.js +26 -26
- package/node_modules/@deepseek-ai/dsh-tools/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-loader/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-protocol/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-typert-registry/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-user-approval/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-user-questions/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-web/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-app/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/{index-Dqw48FrP.js → index-BQQQ5Qt-.js} +2 -2
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/cpp-DddhVWhK.js +1 -0
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/{php-D-uCvoST.js → php-9bx0az3O.js} +1 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/{ruby-DEItuUFs.js → ruby-HDLHRjSL.js} +1 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/swift-C2oV4EkX.js +1 -0
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/{vendor-Cjbwl5VI.js → vendor-CeMKrCZm.js} +24 -24
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/index.html +2 -2
- package/node_modules/@deepseek-ai/dsh-web-frontend/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-web-search-deepseek/LICENSE +21 -0
- package/node_modules/@deepseek-ai/dsh-web-search-deepseek/lib/index.js +1 -0
- package/node_modules/@deepseek-ai/dsh-web-search-deepseek/lib/invariant.js +1 -0
- package/node_modules/@deepseek-ai/dsh-web-search-deepseek/package.json +1 -0
- package/node_modules/@deepseek-ai/dsh-web-search-dsh/lib/index.js +1 -1
- package/node_modules/@deepseek-ai/dsh-web-search-dsh/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workflow/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/lib/index.js +2 -2
- package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/lib/worker.cjs +3 -4
- package/node_modules/@deepseek-ai/dsh-workflow-worker-thread/package.json +1 -1
- package/node_modules/@deepseek-ai/dsh-workspace/lib/invariant.js +1 -1
- package/node_modules/@deepseek-ai/dsh-workspace/package.json +1 -1
- package/node_modules/@deepseek-ai/node-addon-landlock-run/package.json +1 -1
- package/package.json +1 -1
- package/lib/profile-boot-_PCyp_wB.js +0 -1
- package/node_modules/@deepseek-ai/dsh-sandbox-windows-acl/lib/types-BjBvdldw.js +0 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/cpp-DIPi6g--.js +0 -1
- package/node_modules/@deepseek-ai/dsh-web-frontend/dist/assets/langs/swift-D82vCrfD.js +0 -1
- /package/lib/{profile-boot-B71dQloK.js → profile-boot-DDo03lXi.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
var Z=Object.defineProperty;var i=(t,e)=>Z(t,"name",{value:e,configurable:!0});import{Service as ee}from"@deepseek-ai/cordis";import{isAbsolute as te}from"node:path";import{CallId as se,MessageId as re,assertNever as ne,callConfigEquals as oe,deepFreeze as m,freezeMessage as ae}from"@deepseek-ai/dsh-llm";import{scopeOf as ie,scopeTarget as ce}from"@deepseek-ai/dsh-scope";function de(t){return t}i(de,"SessionId");const le=0;function A(t,e){const s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s!="function")return!1;try{return s.name===e&&s.prototype===t&&Function.prototype.toString.call(s)===`function ${e}() { [native code] }`}catch{return!1}}i(A,"hasIntrinsicConstructor");function j(t){return Object.getPrototypeOf(t)===null&&A(t,"Object")}i(j,"isIntrinsicObjectPrototype");function ue(t){const e=Object.getPrototypeOf(t);if(!Array.isArray(e)||!A(e,"Array"))return!1;const s=Object.getPrototypeOf(e);return typeof s=="object"&&s!==null&&j(s)}i(ue,"hasPlainArrayPrototype");function fe(t){const e=Object.getPrototypeOf(t);return e===null||typeof e=="object"&&j(e)}i(fe,"hasPlainObjectPrototype");function he(t){const e=Reflect.ownKeys(t);if(!e.some(s=>typeof s!="string"||!Object.prototype.propertyIsEnumerable.call(t,s)))return e}i(he,"enumerableStringKeys");function I(t,e){const s=new Set;let n;const r=i((a,c)=>{a!==void 0&&(a.kind==="root"?n=c:a.kind==="array"?a.target[a.index]=c:Object.defineProperty(a.target,a.key,{value:c,enumerable:!0,configurable:!0,writable:!0}))},"assign"),o=[{kind:"visit",value:t,...e?{destination:{kind:"root"}}:{}}];for(let a=o.pop();a!==void 0;a=o.pop()){if(a.kind==="leave"){s.delete(a.source);continue}if(a.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(a.source,a.index))return;o.push({kind:"visit",value:a.source[a.index],...a.target===void 0?{}:{destination:{kind:"array",target:a.target,index:a.index}}});continue}if(a.kind==="object-property"){o.push({kind:"visit",value:a.source[a.key],...a.target===void 0?{}:{destination:{kind:"object",target:a.target,key:a.key}}});continue}const c=a.value;if(c===null){r(a.destination,null);continue}if(typeof c=="boolean"||typeof c=="string"){r(a.destination,c);continue}if(typeof c=="number"){if(!Number.isFinite(c)||Object.is(c,-0))return;r(a.destination,c);continue}if(typeof c!="object"||s.has(c))return;if(Array.isArray(c)){if(!ue(c))return;const f=c.length;if(Reflect.ownKeys(c).length!==f+1)return;const u=e?[]:void 0;u!==void 0&&r(a.destination,u),s.add(c),o.push({kind:"leave",source:c});for(let y=f-1;y>=0;y--)o.push({kind:"array-item",source:c,index:y,...u===void 0?{}:{target:u}});continue}if(!fe(c))return;const d=he(c);if(d===void 0)return;const l=e?{}:void 0;l!==void 0&&r(a.destination,l),s.add(c),o.push({kind:"leave",source:c});for(let f=d.length-1;f>=0;f--){const u=d[f];if(u===void 0)return;o.push({kind:"object-property",source:c,key:u,...l===void 0?{}:{target:l}})}}return e?n:!0}i(I,"walkJsonValue");function w(t){return I(t,!0)}i(w,"snapshotJsonValue");function pe(t){return I(t,!1)===!0}i(pe,"isJsonValue");const _=new Set(["user/message","assistant/message","tool/result"]);function R(t){return _.has(t)}i(R,"isSurfaceEligibleType");function q(t){return _.has(t.type)?t.surfaceOp!==void 0:!1}i(q,"isSurfaceEvent");function ge(t){return q(t)&&t.surfaceOp==="append"}i(ge,"isAppendSurfaceEvent");function me(t){return q(t)&&t.surfaceOp!=="append"}i(me,"isReplacementSurfaceEvent");function D(t){switch(t.type){case"user/message":return t.data;case"assistant/message":return t.data.message.content.length===0?null:t.data.message;case"tool/result":return t.data.message;default:return null}}i(D,"deriveEventMessage");function P(){return{nodes:[],replaceGeneration:0}}i(P,"createFoldState");function E(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}i(E,"isEventSeq");function ye(t){const e=t;return Object.keys(e).length===3&&Object.hasOwn(e,"op")&&Object.hasOwn(e,"start")&&Object.hasOwn(e,"end")&&e.op==="replace"&&E(e.start)&&E(e.end)}i(ye,"isReplaceOp");function we(t){const e=t;if(!R(t.type)){if(e.surfaceOp!==void 0)throw new Error(`session event "${t.type}" is not surface-eligible and cannot carry surfaceOp`);if(e.sourceEventSeqs!==void 0)throw new Error(`session event "${t.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}const s=e.surfaceOp;if(s===void 0)throw new Error(`session event "${t.type}" is surface-eligible and requires a surfaceOp marker`);if(s==="append")return s;if(s===null||typeof s!="object"||Array.isArray(s))throw new Error(`session event "${t.type}" carries an invalid surfaceOp`);if(!ye(s))throw new Error(`session event "${t.type}" carries an invalid replace surfaceOp`);return s}i(we,"surfaceOpOf");function T(t,e){const s=t.sourceEventSeqs,n=new Set;if(s!==void 0){if(!Array.isArray(s))throw new Error(`sourceEventSeqs on event at seq ${t.seq} must be an array when present`);if(s.length===0&&t.type!=="assistant/message")throw new Error("sourceEventSeqs must not be empty except on assistant/message");let o;for(const a of s){if(!E(a))throw new Error(`session event "${t.type}" sourceEventSeqs must densely contain non-negative safe integers`);n.add(a),o===void 0&&a>=t.seq&&(o=a)}if(n.size!==s.length)throw new Error("sourceEventSeqs must not contain duplicates");if(o!==void 0)throw new Error(`sourceEventSeqs must reference earlier events: ${o} >= current seq ${t.seq}`)}const r=e.filter(o=>!n.has(o));if(r.length>0)throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${r.join(", ")}`)}i(T,"assertProvenance");function ve(t,e){const s=t.nodes.indexOf(e.start);if(s===-1)throw new Error(`surface replace: start seq ${e.start} not found in surface`);const n=t.nodes.indexOf(e.end);if(n===-1)throw new Error(`surface replace: end seq ${e.end} not found in surface`);if(s>n)throw new Error(`surface replace: start seq ${e.start} (index ${s}) is after end seq ${e.end} (index ${n})`);return{startIdx:s,endIdx:n,shadowedSeqs:t.nodes.slice(s,n+1)}}i(ve,"replacementRange");function k(t,e){if(t===e)return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((r,o)=>k(r,e[o]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;const s=Object.keys(t),n=e;return s.length!==Object.keys(e).length?!1:s.every(r=>Object.hasOwn(e,r)&&k(t[r],n[r]))}i(k,"isDeepEqualJson");function be(t,e,s,n){if(t.type==="tool/result"){if(e.length!==1)throw new Error("tool/result surface replacement must rewrite exactly one current node");for(const r of e){const o=s[r-n];if(o?.type!=="tool/result")throw new Error("tool/result surface replacement must target a current tool/result");const a={...o.data},c={...t.data},d=o.data.message.content[0],l=t.data.message.content[0];if(a.message={...o.data.message,content:[{...d,content:null}]},c.message={...t.data.message,content:[{...l,content:null}]},!k(a,c))throw new Error("tool/result surface replacement may change only content")}}}i(be,"assertToolResultRewrite");function F(t,e,s,n,r){if(e.seq!==s)throw new Error(`session event seq ${e.seq} is not contiguous; expected ${s}`);const o=we(e);if(o===void 0)return;if(o==="append")return T(e,[]),{kind:"append",seq:e.seq};const a=ve(t,o);return T(e,a.shadowedSeqs),be(e,a.shadowedSeqs,n,r),{kind:"replace",seq:e.seq,start:o.start,end:o.end,...a}}i(F,"planSurfaceEvent");function L(t,e,s,n,r){return M(t,F(t,e,s,n,r))}i(L,"applySurfaceEvent");function M(t,e){if(e?.kind==="append"?t.nodes.push(e.seq):e?.kind==="replace"&&(t.nodes.splice(e.startIdx,e.endIdx-e.startIdx+1,e.seq),t.replaceGeneration+=1),e?.kind==="replace")return{seq:e.seq,start:e.start,end:e.end,shadowedSeqs:e.shadowedSeqs}}i(M,"applySurfacePlan");function Se(t){const e=P(),s=[];for(const[n,r]of t.entries()){const o=L(e,r,n,t,0);o!==void 0&&s.push(o)}return{nodes:[...e.nodes],replacements:s}}i(Se,"foldSurface");var qe=class{static{i(this,"SurfaceManager")}log;baseSeq;_state=P();_lastProcessedSeq;_pendingPlan;constructor(t,e=0){this.log=t,this.baseSeq=e,this._lastProcessedSeq=e-1}validateNext(t){this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta();const e=this.baseSeq+this.log.length;this._pendingPlan={event:t,expectedSeq:e,plan:F(this._state,t,e,this.log,this.baseSeq)}}get replaceGeneration(){return this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta(),this._state.replaceGeneration}get nodes(){return this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta(),this._state.nodes}_processDelta(){const t=this.baseSeq+this.log.length-1;for(let e=this._lastProcessedSeq+1;e<=t;e++){const s=e-this.baseSeq,n=this.log[s],r=this._pendingPlan;r?.event===n&&r.expectedSeq===e?M(this._state,r.plan):L(this._state,n,e,this.log,this.baseSeq),r!==void 0&&r.expectedSeq<=e&&(this._pendingPlan=void 0),this._lastProcessedSeq=e}}};function C(t){const e=t.adapterDefaults;return{config:t.config,...e?.reasoningEffort===!0||e?.maxTokens===!0?{adapterDefaults:e}:{},...t.system!==void 0&&t.system.length>0?{system:t.system}:{},...t.tools!==void 0&&t.tools.length>0?{tools:t.tools}:{}}}i(C,"canonicalHeader");function Ee(t,e){return JSON.stringify(t)===JSON.stringify(e)}i(Ee,"sameSchema");function ke(t,e){if(!oe(t.config,e.config)||t.adapterDefaults?.reasoningEffort!==e.adapterDefaults?.reasoningEffort||t.adapterDefaults?.maxTokens!==e.adapterDefaults?.maxTokens||t.system!==e.system)return!1;const s=t.tools??[],n=e.tools??[];return s.length===n.length&&s.every((r,o)=>Ee(r,n[o]))}i(ke,"headerEquals");function U(t,e){let s=e;for(const n of t)n.type==="request/header"&&(s=C(n.data.header));return s}i(U,"foldRequestHeader");var Oe=class Q{static{i(this,"SessionPreparation")}options;released=!1;session;constructor(e,s){this.options=s,this.session=e}static create(e,s){return new Q(e,s??{})}[Symbol.dispose](){this.released||(this.released=!0,this.options.release?.())}};const J="TOOL_NOT_STARTED",z="TOOL_OUTCOME_UNKNOWN";function xe(t){let e=null,s=null;const n=new Map;for(const d of t)switch(d.type){case"turn/start":e=d.data.turn,s=null,n.clear();break;case"turn/end":e=null,s=null,n.clear();break;case"step/start":s=d.data.step;break;case"step/end":n.clear(),s=null;break;case"assistant/message":for(const l of d.data.message.content)l.type==="tool-call"&&n.set(l.id,{step:d.data.step});break;case"tool/call":{const l=n.get(d.data.callId);l&&(l.callSeq=d.seq)}break;case"tool/result":n.delete(d.data.message.source.callId);break;default:break}const r=t.at(-1);if(e===null||r===void 0)return[];let o=r.seq+1;const a=r.time,c=[];for(const[d,{step:l,callSeq:f}]of n){const u=f!==void 0,y=ae({id:re(`interrupted-tool-result-${d}-${o}`),role:"user",source:{kind:"tool",callId:d},content:[{type:"tool-result",toolCallId:d,isError:!0,content:[{type:"text",text:u?"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly.":"The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed."}]}]});c.push({type:"tool/result",seq:o++,time:a,data:{turn:e,step:l,message:y,error:u?{name:"ToolOutcomeUnknownError",code:z}:{name:"ToolNotStartedError",code:J}},surfaceOp:"append",...u?{sourceEventSeqs:[f]}:{}})}return s!==null&&c.push({type:"step/end",seq:o++,time:a,data:{turn:e,step:s}}),c.push({type:"turn/end",seq:o++,time:a,data:{turn:e,reason:{kind:"interrupted"}}}),c}i(xe,"interruptedTurnClosers");const $e=3;function b(t){return typeof t=="object"&&t!==null}i(b,"isRecord");function p(t,e){return Object.keys(t).length===e.length&&e.every(s=>Object.hasOwn(t,s))}i(p,"hasExactKeys");function Ne(t){if(t.type!=="assistant/chunk"||!p(t,["type","seq","time","data"])||!Number.isSafeInteger(t.seq)||t.seq<0||!Number.isSafeInteger(t.time))return;const e=t.data;if(!b(e)||!p(e,["turn","step","chunk"])||typeof e.turn!="number"||typeof e.step!="number")return;const s=e.chunk;if(!(!b(s)||typeof s.index!="number"))switch(s.type){case"text-delta":case"reasoning-delta":return p(s,["type","index","text"])&&typeof s.text=="string"?s.type:void 0;case"tool-call-delta":return(p(s,["type","index","id","argumentsDelta"])||p(s,["type","index","id","name","argumentsDelta"])&&typeof s.name=="string")&&typeof s.id=="string"&&typeof s.argumentsDelta=="string"?s.type:void 0;default:return}}i(Ne,"classify");function O(t){return t.data.chunk}i(O,"toolCallOf");function x(t){return t.data.chunk.index}i(x,"indexOf");function Ae(t,e,s){if(e.seq!==t.seq+1||!Number.isSafeInteger(e.time-t.time)||e.data.turn!==t.data.turn||e.data.step!==t.data.step||x(e)!==x(t))return!1;if(s!=="tool-call-delta")return!0;const n=O(t),r=O(e);return n.id===r.id&&Object.hasOwn(n,"name")===Object.hasOwn(r,"name")&&n.name===r.name}i(Ae,"continues");function je(t,e){const s=e[0],n={turn:s.data.turn,step:s.data.step,index:x(s),dt:e.slice(1).map((a,c)=>a.time-e[c].time)},r={seq0:s.seq,time0:s.time};if(t==="tool-call-delta"){const a=O(s);return{type:"tool-call-chunks",...r,data:{...n,id:se(a.id),...Object.hasOwn(a,"name")?{name:a.name}:{},args:e.map(c=>c.data.chunk.argumentsDelta)}}}const o={...n,texts:e.map(a=>a.data.chunk.text)};return t==="text-delta"?{type:"text-chunks",...r,data:o}:{type:"reasoning-chunks",...r,data:o}}i(je,"buildRow");function Ie(t){const e=[];let s,n=[];const r=i(()=>{s!==void 0&&n.length>=$e?e.push(je(s,n)):e.push(...n),s=void 0,n=[]},"flush");for(const o of t){const a=Ne(o);if(a===void 0){r(),e.push(o);continue}const c=o,d=n[n.length-1];if(a===s&&d!==void 0&&Ae(d,c,a)){n.push(c);continue}r(),s=a,n=[c]}return r(),e}i(Ie,"packChunkRuns");function h(t,e){throw new Error(`malformed ${t} storage row: ${e}`)}i(h,"malformed");function V(t,e,s){(typeof e.turn!="number"||typeof e.step!="number"||typeof e.index!="number")&&h(t,"turn/step/index must be numbers");const n=e[s];(!Array.isArray(n)||n.length===0||n.some(o=>typeof o!="string"))&&h(t,`${s} must be a non-empty string array`);const r=e.dt;return(!Array.isArray(r)||r.some(o=>!Number.isSafeInteger(o)))&&h(t,"dt must be an array of safe integers"),r.length!==n.length-1&&h(t,`dt length ${r.length} does not match ${n.length} members`),n}i(V,"validateRunData");function _e(t,e){p(t,["type","seq0","time0","data"])||h(e,"envelope must be exactly {type, seq0, time0, data}"),(!Number.isSafeInteger(t.seq0)||t.seq0<0)&&h(e,"seq0 must be a non-negative safe integer"),Number.isSafeInteger(t.time0)||h(e,"time0 must be a safe integer");const s=t.data;b(s)||h(e,"data must be an object");let n;if(e==="tool-call-chunks"){const o=p(s,["turn","step","index","id","name","dt","args"]);!o&&!p(s,["turn","step","index","id","dt","args"])&&h(e,"data must be exactly {turn, step, index, id, name?, dt, args}"),(typeof s.id!="string"||o&&typeof s.name!="string")&&h(e,"id (and name when present) must be strings"),n=V(e,s,"args")}else p(s,["turn","step","index","dt","texts"])||h(e,"data must be exactly {turn, step, index, dt, texts}"),n=V(e,s,"texts");Number.isSafeInteger(t.seq0+n.length-1)||h(e,"member seqs must stay safe integers");let r=t.time0;for(const o of s.dt)r+=o,Number.isSafeInteger(r)||h(e,"member times must stay safe integers");return t}i(_e,"validateRow");function Re(t){const e=t.type==="tool-call-chunks"?t.data.args:t.data.texts,s=[];let n=t.time0;for(let r=0;r<e.length;r++){r>0&&(n+=t.data.dt[r-1]);let o;switch(t.type){case"text-chunks":o={type:"text-delta",index:t.data.index,text:e[r]};break;case"reasoning-chunks":o={type:"reasoning-delta",index:t.data.index,text:e[r]};break;case"tool-call-chunks":o={type:"tool-call-delta",index:t.data.index,id:t.data.id,...Object.hasOwn(t.data,"name")?{name:t.data.name}:{},argumentsDelta:e[r]};break;default:return ne(t,"chunk-rows expandRow")}s.push({type:"assistant/chunk",seq:t.seq0+r,time:n,data:{turn:t.data.turn,step:t.data.step,chunk:o}})}return s}i(Re,"expandRow");function De(t){if(!b(t))return[t];const e=t.type;return e!=="text-chunks"&&e!=="reasoning-chunks"&&e!=="tool-call-chunks"?[t]:Re(_e(t,e))}i(De,"decodeStorageRecord");const Pe=new Set(["agent-preset/selected","agent/inbox/spliced","approval/asked","approval/decided","approval/policy","assistant/chunk","assistant/message","command/done","command/run","compaction/end","compaction/prune","compaction/start","compaction/summary","feedback/record","goal/change","hook/invoked","hook/result","llm/retry","llm/retry-started","permission/preset","plan/mode","request/context","request/header","sandbox/mode","schedule/change","session/end-seed","session/title","session/title-llm-request","step/end","step/start","subagent/descriptor","todo/write","tool-workflow/agent-end","tool-workflow/agent-start","tool-workflow/run-end","tool-workflow/run-start","tool/call","tool/code-dispatch","tool/code-dispatch-start","tool/result","turn/end","turn/start","user/message","web/deepseek-search-llm-request"]);function H(t,e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("session header is not a plain JSON record");const s=e;if(s.version!==0)throw new Error(`session header version must be 0, got ${String(s.version)}`);if(s.id!==t)throw new Error(`session header id "${String(s.id)}" does not match session id "${t}"`);if(typeof s.createdAt!="number"||!Number.isSafeInteger(s.createdAt)||s.createdAt<0)throw new Error("session header createdAt must be a non-negative safe integer");if(s.cwd!==void 0){if(typeof s.cwd!="string")throw new Error("session header cwd must be a string");if(!te(s.cwd))throw new Error(`session header cwd must be an absolute path, got "${s.cwd}"`)}if(s.parentSession!==void 0&&typeof s.parentSession!="string")throw new Error("session header parentSession must be a string");if(s.seedLength!==void 0&&(typeof s.seedLength!="number"||!Number.isSafeInteger(s.seedLength)||s.seedLength<0))throw new Error("session header seedLength must be a non-negative safe integer");if(s.origin!==void 0&&s.origin!=="subagent")throw new Error('session header origin must be "subagent"');if(s.delegationDepth!==void 0&&(typeof s.delegationDepth!="number"||!Number.isSafeInteger(s.delegationDepth)||s.delegationDepth<0))throw new Error("session header delegationDepth must be a non-negative safe integer");if(s.agentPreset!==void 0&&typeof s.agentPreset!="string")throw new Error("session header agentPreset must be a string");return m(s)}i(H,"validateSessionHeader");function Te(t,e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const s=Reflect.getPrototypeOf(e);if(s!==Object.prototype&&s!==null)throw new Error("session header is not a plain JSON record")}return H(t,e)}i(Te,"validateRestoredSessionHeader");function Fe(t,e){const s=w(e===void 0?{version:0,id:t,createdAt:Date.now()}:e);if(s===void 0)throw new Error("session header is not losslessly JSON-serializable");return H(t,s)}i(Fe,"snapshotSessionHeader");function G(t){switch(K(t,`session event at seq ${t.seq}`),t.type){case"user/message":m(t.data);break;case"assistant/message":case"tool/result":m(t.data.message);break;default:break}return t}i(G,"adoptSessionEvent");function Le(t){return G(structuredClone(t))}i(Le,"snapshotSessionEvent");function Me(t){const e=[t];for(;e.length>0;){const s=e.pop();Object.freeze(s);for(const n in s){const r=s[n];r!==null&&typeof r=="object"&&e.push(r)}}return t}i(Me,"freezeRestoredObject");function Ce(t,e){const s=t;if(s.type==="request/header-delta")throw new Error(`seed event at index ${e} uses unsupported legacy request/header-delta format`);for(const a in s)switch(a){case"type":case"seq":case"time":case"data":case"surfaceOp":case"sourceEventSeqs":case"ignorable":break;default:throw new Error(`seed event at index ${e} has an invalid event envelope`)}const n=s.type,r=s.seq,o=s.time;if(typeof n!="string"||typeof r!="number"||!Number.isSafeInteger(r)||r<0||typeof o!="number"||!Number.isSafeInteger(o)||s.data===void 0||s.ignorable!==void 0&&s.ignorable!==!0)throw new Error(`seed event at index ${e} has an invalid event envelope`);switch(n){case"request/header":case"user/message":case"assistant/message":case"tool/result":Ue(s,e);break}}i(Ce,"assertSessionEventEnvelope");function Ue(t,e){const s=t.data,n=typeof s=="object"&&s!==null?s:void 0;if(t.type==="request/header"){const o=n?.header,a=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:void 0,c=a?.config;if(!Y(c))throw new Error(`seed request/header at index ${e} lacks provider/model`);const d=c,l=d.reasoningEffort;if(l!==void 0&&(typeof l!="string"||l.length===0))throw new Error(`seed request/header at index ${e} has an invalid reasoningEffort`);ze(a?.adapterDefaults,d,e)}const r=t.type;r!=="user/message"&&r!=="assistant/message"&&r!=="tool/result"||K(t,`seed ${r} at index ${e}`)}i(Ue,"assertCurrentLlmShape");const Je=new Set(["reasoningEffort","maxTokens"]);function ze(t,e,s){if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`seed request/header at index ${s} has invalid adapterDefaults`);const n=t;if(Object.keys(n).some(r=>!Je.has(r))||Object.values(n).some(r=>r!==!0)||n.reasoningEffort===!0&&e.reasoningEffort===void 0||n.maxTokens===!0&&e.maxTokens===void 0)throw new Error(`seed request/header at index ${s} has invalid adapterDefaults`)}i(ze,"assertAdapterDefaults");function K(t,e){const s=t.type;if(s!=="user/message"&&s!=="assistant/message"&&s!=="tool/result")return;const n=t.data,r=typeof n=="object"&&n!==null?n:void 0,o=s==="user/message"?r:r?.message;if(typeof o!="object"||o===null||typeof o.id!="string"||o.id==="")throw new Error(`${e} lacks an identified message`);const a=o,c=s==="assistant/message"?"assistant":"user";if(a.role!==c)throw new Error(`${e} message must have role "${c}"`);const d=a.source;if(typeof d!="object"||d===null||typeof d.kind!="string"||d.kind==="")throw new Error(`${e} message has invalid source`);if(!Array.isArray(a.content))throw new Error(`${e} message has invalid content`);const l=d;if(s==="assistant/message"){if(l.kind!=="model"||!Y(l))throw new Error(`${e} message must have model source`);return}if(s!=="tool/result")return;if(l.kind!=="tool"||typeof l.callId!="string"||l.callId==="")throw new Error(`${e} message must have tool source`);const f=a.content,u=f[0];if(f.length!==1||typeof u!="object"||u===null||u.type!=="tool-result"||!Array.isArray(u.content))throw new Error(`${e} message must contain one tool-result block`);if(u.toolCallId!==l.callId)throw new Error(`${e} message has mismatched tool call ids`)}i(K,"assertMessageEventShape");function Y(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.provider=="string"&&e.provider.length>0&&typeof e.model=="string"&&e.model.length>0}i(Y,"hasProviderModel");function W(t,e,s){if(t==="request/header-delta")throw new Error(`${s} uses unsupported legacy request/header-delta format`);if(t==="request/header"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.reason==="fallback")throw new Error(`${s} uses unsupported legacy request/header reason "fallback"`)}i(W,"assertSupportedRequestHeader");function S(t,e){return[...t.events.dispatch("emit",e)]}i(S,"collectSessionCallbacks");function B(t,e,s,n,r){for(const o of r)try{const a=o(...n);Promise.resolve(a).catch(c=>{t.logger.warn(`session "${s}": ${e} listener rejected: ${String(c)}`)})}catch(a){t.logger.warn(`session "${s}": ${e} listener threw: ${String(a)}`)}}i(B,"invokeContainedSessionObservers");const v=new WeakMap;var $=class N{static{i(this,"Session")}log=[];surfaceManager=new qe(this.log);get surface(){return this.surfaceManager}header;get id(){return this.header.id}firstLiveSeq;static create(e,s,n){return new N(e,s,n)}static fromRestore(e,s,n){return new N(e,s,n,"restore")}constructor(e,s,n,r="snapshot"){const o=r==="restore"?Te(e,n):void 0;if(s!==void 0)for(const[a,c]of s.entries()){const d=r==="restore"?c:w(c);if(d===void 0)throw new Error(`seed event at index ${a} is not losslessly JSON-serializable`);if(Ce(d,a),W(d.type,d.data,`seed event at index ${a}`),d.seq!==a)throw new Error(`seed event at index ${a} has seq ${d.seq} (expected ${a}); seed must be contiguous from 0`);try{this.surfaceManager.validateNext(d)}catch(l){throw new Error(`invalid seed event at index ${a}: ${l instanceof Error?l.message:"invalid surface metadata"}`)}this.log.push(r==="restore"?Me(d):m(d))}this.firstLiveSeq=this.log.length,this.header=o??Fe(e,n),s!==void 0&&this.log.at(-1)?.type!=="session/end-seed"&&this.append("session/end-seed",{})}eventsSnapshot;get events(){return this.eventsSnapshot??=Object.freeze([...this.log]),this.eventsSnapshot}get seq(){return this.log.length}append(e,s,...n){const r=n[0],o={...r?.sourceEventSeqs===void 0?{}:{sourceEventSeqs:r.sourceEventSeqs},...r?.surfaceOp===void 0?{}:{surfaceOp:r.surfaceOp}},a=w(s);if(a===void 0)throw new Error(`session event "${e}" carries non-JSON-serializable data`);W(e,a,`session event "${e}"`);const c=w(o);if(c===void 0)throw new Error(`session event "${e}" carries non-JSON-serializable surface metadata`);const d=v.get(this);if(d?.appending)throw new Error("session append cannot reenter while another append is being published");const l=m({type:e,seq:this.log.length,time:Date.now(),data:a,...c});this.surfaceManager.validateNext(l),d!==void 0&&(d.appending=!0);try{let f;const u=[this,l];return d!==void 0&&(f=S(d.emitCtx,[d.carrier,"session/event",...u])),this.log.push(l),this.eventsSnapshot=void 0,f!==void 0&&d!==void 0&&B(d.emitCtx,"session/event",d.id,u,f),l}finally{d!==void 0&&(d.appending=!1,d.detachRequested&&!d.announcing&&d.detach())}}headerFold;headerFoldSeq=0;requestHeader(){return this.headerFoldSeq<this.log.length&&(this.headerFold=m(U(this.log.slice(this.headerFoldSeq),this.headerFold)),this.headerFoldSeq=this.log.length),this.headerFold}contextFold;contextFoldSeq=0;requestContext(){if(this.contextFoldSeq<this.log.length){for(const e of this.log.slice(this.contextFoldSeq))e.type==="request/context"&&(this.contextFold=m({...e.data}));this.contextFoldSeq=this.log.length}return this.contextFold}derived=[];derivedNodes=0;derivedGeneration=0;deriveMessages(){const e=this.surface,s=e.nodes,n=e.replaceGeneration;n!==this.derivedGeneration&&(this.derived=[],this.derivedNodes=0,this.derivedGeneration=n);for(const r of s.slice(this.derivedNodes)){const o=this.deriveEventMessage(this.log[r]);o&&this.derived.push(o)}return this.derivedNodes=s.length,[...this.derived]}deriveEventMessage(e){return D(e)}},g=class extends Error{static{i(this,"SessionForkError")}code;constructor(t,e){super(t),this.code=e,this.name="SessionForkError"}},X=class extends ee{static{i(this,"SessionStore")}store=new Map;counter=0;constructor(t){super(t,"sessions"),t.inject(["typert"],e=>{e.typert.lookups.register("session",{parameter:"session",wire:"sessionId",hostTypeSymbol:"@deepseek-ai/dsh-session#Session",wireTypeSymbol:"@deepseek-ai/dsh-session/types#SessionId",resolve:i(s=>this.get(s),"resolve")})})}create(t,e){const s=this.prepare(t,e);return this.ctx.effect(function*(){yield this.enter(s),this.announce(s)}.bind(this),"sessions.create()"),s}prepare(t,e){let s;if(t===void 0)do s=`session-${++this.counter}`;while(this.store.has(s));else s=t;if(this.store.has(s))throw new Error(`session "${s}" already exists`);if(e?.seedSource==="persistence")return $.fromRestore(s,e.seed,e.meta);const n=e?.seed,r=e?.meta,o={version:0,id:s,createdAt:r?.createdAt??Date.now(),...r?.cwd===void 0?{}:{cwd:r.cwd},...r?.parentSession===void 0?{}:{parentSession:r.parentSession},...r?.seedLength===void 0?{}:{seedLength:r.seedLength},...r?.origin===void 0?{}:{origin:r.origin},...r?.delegationDepth===void 0?{}:{delegationDepth:r.delegationDepth},...r?.agentPreset===void 0?{}:{agentPreset:r.agentPreset}};return $.create(s,n,o)}enter(t){const e=t.id,s=ce(t,ie(this.ctx));if(this.store.has(e))throw new Error(`session "${e}" already exists`);if(v.has(t))throw new Error(`session "${e}" is already attached to a store`);const n={id:e,session:t,carrier:s,emitCtx:this.ctx,announced:!1,announcing:!1,appending:!1,detachRequested:!1,detach:i(()=>{this.detachEntered(n)},"detach")};this.store.set(e,n),v.set(t,n);let r=!0;return i(()=>{if(r){if(r=!1,n.announcing||n.appending){n.detachRequested=!0;return}n.detach()}},"detach")}detachEntered(t){t.detachRequested=!1,this.store.get(t.id)===t&&(this.store.delete(t.id),v.delete(t.session),t.announced&&this.emitDisposed(t))}announce(t){const e=this.liveEntryFor(t);if(e.announced||e.announcing)throw new Error(`session "${e.id}" was already announced`);e.announced=!0;const s=[t];e.announcing=!0;try{const n=S(this.ctx,[e.carrier,"session/created",t]);for(const r of n){const o=r(...s);Promise.resolve(o).catch(a=>{this.ctx.logger.warn(`session "${e.id}": session/created listener rejected: ${String(a)}`)})}}finally{e.announcing=!1,e.detachRequested&&!e.appending&&e.detach()}}emitDisposed(t){const e=[t.session];try{const s=S(this.ctx,[t.carrier,"session/disposed",t.session]);B(this.ctx,"session/disposed",t.id,e,s)}catch(s){this.ctx.logger.warn(`session "${t.id}": session/disposed dispatch threw: ${String(s)}`)}}async flush(t){const{carrier:e}=this.liveEntryFor(t),s=[t],n=S(this.ctx,[e,"session/flush",t]),r=(await Promise.allSettled(n.map(o=>{try{return o(...s)}catch(a){return Promise.reject(a)}}))).find(o=>o.status==="rejected");if(r!==void 0)throw r.reason;return n.length>0}liveEntryFor(t){const e=v.get(t);if(e===void 0||this.store.get(e.id)!==e)throw new Error(`session "${t.id}" is not live in this store`);return e}get(t){return this.store.get(t)?.session}list(){return[...this.store.values()].map(t=>t.session)}fork(t,e,s){if(s!==void 0&&this.get(s)!==void 0)throw new g(`session "${s}" already exists`,"SESSION_ALREADY_EXISTS");const n=this._resolveForkSource(t),r=this._forkSeed(n,e);return this.create(s,{seed:r,meta:{...n.header.cwd!==void 0?{cwd:n.header.cwd}:{},parentSession:n.id,seedLength:r.length}})}_forkSeed(t,e){const s=t.events,n=s.at(-1);let r;if(e!==void 0)r=e;else{if(n===void 0)return[];r=n.seq}if(!Number.isSafeInteger(r)||r<0)throw new g(`fork boundary for session "${t.id}" must be a non-negative safe integer, got ${String(r)}`,"INVALID_BOUNDARY");if(r>=s.length){const c=s.at(-1)?.seq;throw new g(`fork boundary ${r} does not exist in session "${t.id}" (last seq: ${c??"none"})`,"INVALID_BOUNDARY")}const o=s[r];if(o===void 0||o.seq!==r)throw new g(`fork boundary ${r} does not match a contiguous event seq in session "${t.id}"`,"INVALID_BOUNDARY");const a=s.slice(0,r+1).findLast(c=>c.type==="turn/start"||c.type==="turn/end");if(a?.type==="turn/start")throw new g(`fork boundary ${r} in session "${t.id}" ends inside open turn ${a.data.turn}`,"OPEN_TURN");return s.slice(0,r+1)}_resolveForkSource(t){if(typeof t=="string"){const s=this.get(t);if(s===void 0)throw new g(`session "${t}" not found`,"SESSION_NOT_FOUND");return s}const e=this.get(t.id);if(e===void 0)throw new g(`session "${t.id}" not found`,"SESSION_NOT_FOUND");if(e!==t)throw new g(`session "${t.id}" is not the live store instance`,"SESSION_NOT_LIVE");return t}};export{Pe as KNOWN_SESSION_EVENT_TYPES,le as SESSION_FORMAT_VERSION,$ as Session,g as SessionForkError,de as SessionId,Oe as SessionPreparation,X as SessionStore,X as default,J as TOOL_NOT_STARTED,z as TOOL_OUTCOME_UNKNOWN,G as adoptSessionEvent,C as canonicalHeader,De as decodeStorageRecord,D as deriveEventMessage,U as foldRequestHeader,Se as foldSurface,ke as headerEquals,xe as interruptedTurnClosers,ge as isAppendSurfaceEvent,pe as isJsonValue,me as isReplacementSurfaceEvent,R as isSurfaceEligibleType,q as isSurfaceEvent,Ie as packChunkRuns,w as snapshotJsonValue,Le as snapshotSessionEvent};
|
|
1
|
+
var Z=Object.defineProperty;var i=(t,e)=>Z(t,"name",{value:e,configurable:!0});import{Service as ee}from"@deepseek-ai/cordis";import{isAbsolute as te}from"node:path";import{CallId as se,MessageId as re,assertNever as ne,callConfigEquals as oe,deepFreeze as m,freezeMessage as ae}from"@deepseek-ai/dsh-llm";import{scopeOf as ie,scopeTarget as ce}from"@deepseek-ai/dsh-scope";function de(t){return t}i(de,"SessionId");const le=0;function A(t,e){const s=Object.getOwnPropertyDescriptor(t,"constructor")?.value;if(typeof s!="function")return!1;try{return s.name===e&&s.prototype===t&&Function.prototype.toString.call(s)===`function ${e}() { [native code] }`}catch{return!1}}i(A,"hasIntrinsicConstructor");function j(t){return Object.getPrototypeOf(t)===null&&A(t,"Object")}i(j,"isIntrinsicObjectPrototype");function ue(t){const e=Object.getPrototypeOf(t);if(!Array.isArray(e)||!A(e,"Array"))return!1;const s=Object.getPrototypeOf(e);return typeof s=="object"&&s!==null&&j(s)}i(ue,"hasPlainArrayPrototype");function fe(t){const e=Object.getPrototypeOf(t);return e===null||typeof e=="object"&&j(e)}i(fe,"hasPlainObjectPrototype");function he(t){const e=Reflect.ownKeys(t);if(!e.some(s=>typeof s!="string"||!Object.prototype.propertyIsEnumerable.call(t,s)))return e}i(he,"enumerableStringKeys");function I(t,e){const s=new Set;let n;const r=i((a,c)=>{a!==void 0&&(a.kind==="root"?n=c:a.kind==="array"?a.target[a.index]=c:Object.defineProperty(a.target,a.key,{value:c,enumerable:!0,configurable:!0,writable:!0}))},"assign"),o=[{kind:"visit",value:t,...e?{destination:{kind:"root"}}:{}}];for(let a=o.pop();a!==void 0;a=o.pop()){if(a.kind==="leave"){s.delete(a.source);continue}if(a.kind==="array-item"){if(!Object.prototype.hasOwnProperty.call(a.source,a.index))return;o.push({kind:"visit",value:a.source[a.index],...a.target===void 0?{}:{destination:{kind:"array",target:a.target,index:a.index}}});continue}if(a.kind==="object-property"){o.push({kind:"visit",value:a.source[a.key],...a.target===void 0?{}:{destination:{kind:"object",target:a.target,key:a.key}}});continue}const c=a.value;if(c===null){r(a.destination,null);continue}if(typeof c=="boolean"||typeof c=="string"){r(a.destination,c);continue}if(typeof c=="number"){if(!Number.isFinite(c)||Object.is(c,-0))return;r(a.destination,c);continue}if(typeof c!="object"||s.has(c))return;if(Array.isArray(c)){if(!ue(c))return;const f=c.length;if(Reflect.ownKeys(c).length!==f+1)return;const u=e?[]:void 0;u!==void 0&&r(a.destination,u),s.add(c),o.push({kind:"leave",source:c});for(let y=f-1;y>=0;y--)o.push({kind:"array-item",source:c,index:y,...u===void 0?{}:{target:u}});continue}if(!fe(c))return;const d=he(c);if(d===void 0)return;const l=e?{}:void 0;l!==void 0&&r(a.destination,l),s.add(c),o.push({kind:"leave",source:c});for(let f=d.length-1;f>=0;f--){const u=d[f];if(u===void 0)return;o.push({kind:"object-property",source:c,key:u,...l===void 0?{}:{target:l}})}}return e?n:!0}i(I,"walkJsonValue");function w(t){return I(t,!0)}i(w,"snapshotJsonValue");function pe(t){return I(t,!1)===!0}i(pe,"isJsonValue");const _=new Set(["user/message","assistant/message","tool/result"]);function R(t){return _.has(t)}i(R,"isSurfaceEligibleType");function q(t){return _.has(t.type)?t.surfaceOp!==void 0:!1}i(q,"isSurfaceEvent");function ge(t){return q(t)&&t.surfaceOp==="append"}i(ge,"isAppendSurfaceEvent");function me(t){return q(t)&&t.surfaceOp!=="append"}i(me,"isReplacementSurfaceEvent");function D(t){switch(t.type){case"user/message":return t.data;case"assistant/message":return t.data.message.content.length===0?null:t.data.message;case"tool/result":return t.data.message;default:return null}}i(D,"deriveEventMessage");function P(){return{nodes:[],replaceGeneration:0}}i(P,"createFoldState");function E(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}i(E,"isEventSeq");function ye(t){const e=t;return Object.keys(e).length===3&&Object.hasOwn(e,"op")&&Object.hasOwn(e,"start")&&Object.hasOwn(e,"end")&&e.op==="replace"&&E(e.start)&&E(e.end)}i(ye,"isReplaceOp");function we(t){const e=t;if(!R(t.type)){if(e.surfaceOp!==void 0)throw new Error(`session event "${t.type}" is not surface-eligible and cannot carry surfaceOp`);if(e.sourceEventSeqs!==void 0)throw new Error(`session event "${t.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}const s=e.surfaceOp;if(s===void 0)throw new Error(`session event "${t.type}" is surface-eligible and requires a surfaceOp marker`);if(s==="append")return s;if(s===null||typeof s!="object"||Array.isArray(s))throw new Error(`session event "${t.type}" carries an invalid surfaceOp`);if(!ye(s))throw new Error(`session event "${t.type}" carries an invalid replace surfaceOp`);return s}i(we,"surfaceOpOf");function T(t,e){const s=t.sourceEventSeqs,n=new Set;if(s!==void 0){if(!Array.isArray(s))throw new Error(`sourceEventSeqs on event at seq ${t.seq} must be an array when present`);if(s.length===0&&t.type!=="assistant/message")throw new Error("sourceEventSeqs must not be empty except on assistant/message");let o;for(const a of s){if(!E(a))throw new Error(`session event "${t.type}" sourceEventSeqs must densely contain non-negative safe integers`);n.add(a),o===void 0&&a>=t.seq&&(o=a)}if(n.size!==s.length)throw new Error("sourceEventSeqs must not contain duplicates");if(o!==void 0)throw new Error(`sourceEventSeqs must reference earlier events: ${o} >= current seq ${t.seq}`)}const r=e.filter(o=>!n.has(o));if(r.length>0)throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${r.join(", ")}`)}i(T,"assertProvenance");function ve(t,e){const s=t.nodes.indexOf(e.start);if(s===-1)throw new Error(`surface replace: start seq ${e.start} not found in surface`);const n=t.nodes.indexOf(e.end);if(n===-1)throw new Error(`surface replace: end seq ${e.end} not found in surface`);if(s>n)throw new Error(`surface replace: start seq ${e.start} (index ${s}) is after end seq ${e.end} (index ${n})`);return{startIdx:s,endIdx:n,shadowedSeqs:t.nodes.slice(s,n+1)}}i(ve,"replacementRange");function k(t,e){if(t===e)return!0;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((r,o)=>k(r,e[o]));if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;const s=Object.keys(t),n=e;return s.length!==Object.keys(e).length?!1:s.every(r=>Object.hasOwn(e,r)&&k(t[r],n[r]))}i(k,"isDeepEqualJson");function be(t,e,s,n){if(t.type==="tool/result"){if(e.length!==1)throw new Error("tool/result surface replacement must rewrite exactly one current node");for(const r of e){const o=s[r-n];if(o?.type!=="tool/result")throw new Error("tool/result surface replacement must target a current tool/result");const a={...o.data},c={...t.data},d=o.data.message.content[0],l=t.data.message.content[0];if(a.message={...o.data.message,content:[{...d,content:null}]},c.message={...t.data.message,content:[{...l,content:null}]},!k(a,c))throw new Error("tool/result surface replacement may change only content")}}}i(be,"assertToolResultRewrite");function F(t,e,s,n,r){if(e.seq!==s)throw new Error(`session event seq ${e.seq} is not contiguous; expected ${s}`);const o=we(e);if(o===void 0)return;if(o==="append")return T(e,[]),{kind:"append",seq:e.seq};const a=ve(t,o);return T(e,a.shadowedSeqs),be(e,a.shadowedSeqs,n,r),{kind:"replace",seq:e.seq,start:o.start,end:o.end,...a}}i(F,"planSurfaceEvent");function L(t,e,s,n,r){return M(t,F(t,e,s,n,r))}i(L,"applySurfaceEvent");function M(t,e){if(e?.kind==="append"?t.nodes.push(e.seq):e?.kind==="replace"&&(t.nodes.splice(e.startIdx,e.endIdx-e.startIdx+1,e.seq),t.replaceGeneration+=1),e?.kind==="replace")return{seq:e.seq,start:e.start,end:e.end,shadowedSeqs:e.shadowedSeqs}}i(M,"applySurfacePlan");function Se(t){const e=P(),s=[];for(const[n,r]of t.entries()){const o=L(e,r,n,t,0);o!==void 0&&s.push(o)}return{nodes:[...e.nodes],replacements:s}}i(Se,"foldSurface");var qe=class{static{i(this,"SurfaceManager")}log;baseSeq;_state=P();_lastProcessedSeq;_pendingPlan;constructor(t,e=0){this.log=t,this.baseSeq=e,this._lastProcessedSeq=e-1}validateNext(t){this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta();const e=this.baseSeq+this.log.length;this._pendingPlan={event:t,expectedSeq:e,plan:F(this._state,t,e,this.log,this.baseSeq)}}get replaceGeneration(){return this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta(),this._state.replaceGeneration}get nodes(){return this._lastProcessedSeq<this.baseSeq+this.log.length-1&&this._processDelta(),this._state.nodes}_processDelta(){const t=this.baseSeq+this.log.length-1;for(let e=this._lastProcessedSeq+1;e<=t;e++){const s=e-this.baseSeq,n=this.log[s],r=this._pendingPlan;r?.event===n&&r.expectedSeq===e?M(this._state,r.plan):L(this._state,n,e,this.log,this.baseSeq),r!==void 0&&r.expectedSeq<=e&&(this._pendingPlan=void 0),this._lastProcessedSeq=e}}};function C(t){const e=t.adapterDefaults;return{config:t.config,...e?.reasoningEffort===!0||e?.maxTokens===!0?{adapterDefaults:e}:{},...t.system!==void 0&&t.system.length>0?{system:t.system}:{},...t.tools!==void 0&&t.tools.length>0?{tools:t.tools}:{}}}i(C,"canonicalHeader");function Ee(t,e){return JSON.stringify(t)===JSON.stringify(e)}i(Ee,"sameSchema");function ke(t,e){if(!oe(t.config,e.config)||t.adapterDefaults?.reasoningEffort!==e.adapterDefaults?.reasoningEffort||t.adapterDefaults?.maxTokens!==e.adapterDefaults?.maxTokens||t.system!==e.system)return!1;const s=t.tools??[],n=e.tools??[];return s.length===n.length&&s.every((r,o)=>Ee(r,n[o]))}i(ke,"headerEquals");function U(t,e){let s=e;for(const n of t)n.type==="request/header"&&(s=C(n.data.header));return s}i(U,"foldRequestHeader");var Oe=class Q{static{i(this,"SessionPreparation")}options;released=!1;session;constructor(e,s){this.options=s,this.session=e}static create(e,s){return new Q(e,s??{})}[Symbol.dispose](){this.released||(this.released=!0,this.options.release?.())}};const J="TOOL_NOT_STARTED",z="TOOL_OUTCOME_UNKNOWN";function xe(t){let e=null,s=null;const n=new Map;for(const d of t)switch(d.type){case"turn/start":e=d.data.turn,s=null,n.clear();break;case"turn/end":e=null,s=null,n.clear();break;case"step/start":s=d.data.step;break;case"step/end":n.clear(),s=null;break;case"assistant/message":for(const l of d.data.message.content)l.type==="tool-call"&&n.set(l.id,{step:d.data.step});break;case"tool/call":{const l=n.get(d.data.callId);l&&(l.callSeq=d.seq)}break;case"tool/result":n.delete(d.data.message.source.callId)}const r=t.at(-1);if(e===null||r===void 0)return[];let o=r.seq+1;const a=r.time,c=[];for(const[d,{step:l,callSeq:f}]of n){const u=f!==void 0,y=ae({id:re(`interrupted-tool-result-${d}-${o}`),role:"user",source:{kind:"tool",callId:d},content:[{type:"tool-result",toolCallId:d,isError:!0,content:[{type:"text",text:u?"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly.":"The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed."}]}]});c.push({type:"tool/result",seq:o++,time:a,data:{turn:e,step:l,message:y,error:u?{name:"ToolOutcomeUnknownError",code:z}:{name:"ToolNotStartedError",code:J}},surfaceOp:"append",...u?{sourceEventSeqs:[f]}:{}})}return s!==null&&c.push({type:"step/end",seq:o++,time:a,data:{turn:e,step:s}}),c.push({type:"turn/end",seq:o++,time:a,data:{turn:e,reason:{kind:"interrupted"}}}),c}i(xe,"interruptedTurnClosers");const $e=3;function b(t){return typeof t=="object"&&t!==null}i(b,"isRecord");function p(t,e){return Object.keys(t).length===e.length&&e.every(s=>Object.hasOwn(t,s))}i(p,"hasExactKeys");function Ne(t){if(t.type!=="assistant/chunk"||!p(t,["type","seq","time","data"])||!Number.isSafeInteger(t.seq)||t.seq<0||!Number.isSafeInteger(t.time))return;const e=t.data;if(!b(e)||!p(e,["turn","step","chunk"])||typeof e.turn!="number"||typeof e.step!="number")return;const s=e.chunk;if(!(!b(s)||typeof s.index!="number"))switch(s.type){case"text-delta":case"reasoning-delta":return p(s,["type","index","text"])&&typeof s.text=="string"?s.type:void 0;case"tool-call-delta":return(p(s,["type","index","id","argumentsDelta"])||p(s,["type","index","id","name","argumentsDelta"])&&typeof s.name=="string")&&typeof s.id=="string"&&typeof s.argumentsDelta=="string"?s.type:void 0;default:return}}i(Ne,"classify");function O(t){return t.data.chunk}i(O,"toolCallOf");function x(t){return t.data.chunk.index}i(x,"indexOf");function Ae(t,e,s){if(e.seq!==t.seq+1||!Number.isSafeInteger(e.time-t.time)||e.data.turn!==t.data.turn||e.data.step!==t.data.step||x(e)!==x(t))return!1;if(s!=="tool-call-delta")return!0;const n=O(t),r=O(e);return n.id===r.id&&Object.hasOwn(n,"name")===Object.hasOwn(r,"name")&&n.name===r.name}i(Ae,"continues");function je(t,e){const s=e[0],n={turn:s.data.turn,step:s.data.step,index:x(s),dt:e.slice(1).map((a,c)=>a.time-e[c].time)},r={seq0:s.seq,time0:s.time};if(t==="tool-call-delta"){const a=O(s);return{type:"tool-call-chunks",...r,data:{...n,id:se(a.id),...Object.hasOwn(a,"name")?{name:a.name}:{},args:e.map(c=>c.data.chunk.argumentsDelta)}}}const o={...n,texts:e.map(a=>a.data.chunk.text)};return t==="text-delta"?{type:"text-chunks",...r,data:o}:{type:"reasoning-chunks",...r,data:o}}i(je,"buildRow");function Ie(t){const e=[];let s,n=[];const r=i(()=>{s!==void 0&&n.length>=$e?e.push(je(s,n)):e.push(...n),s=void 0,n=[]},"flush");for(const o of t){const a=Ne(o);if(a===void 0){r(),e.push(o);continue}const c=o,d=n[n.length-1];if(a===s&&d!==void 0&&Ae(d,c,a)){n.push(c);continue}r(),s=a,n=[c]}return r(),e}i(Ie,"packChunkRuns");function h(t,e){throw new Error(`malformed ${t} storage row: ${e}`)}i(h,"malformed");function V(t,e,s){(typeof e.turn!="number"||typeof e.step!="number"||typeof e.index!="number")&&h(t,"turn/step/index must be numbers");const n=e[s];(!Array.isArray(n)||n.length===0||n.some(o=>typeof o!="string"))&&h(t,`${s} must be a non-empty string array`);const r=e.dt;return(!Array.isArray(r)||r.some(o=>!Number.isSafeInteger(o)))&&h(t,"dt must be an array of safe integers"),r.length!==n.length-1&&h(t,`dt length ${r.length} does not match ${n.length} members`),n}i(V,"validateRunData");function _e(t,e){p(t,["type","seq0","time0","data"])||h(e,"envelope must be exactly {type, seq0, time0, data}"),(!Number.isSafeInteger(t.seq0)||t.seq0<0)&&h(e,"seq0 must be a non-negative safe integer"),Number.isSafeInteger(t.time0)||h(e,"time0 must be a safe integer");const s=t.data;b(s)||h(e,"data must be an object");let n;if(e==="tool-call-chunks"){const o=p(s,["turn","step","index","id","name","dt","args"]);!o&&!p(s,["turn","step","index","id","dt","args"])&&h(e,"data must be exactly {turn, step, index, id, name?, dt, args}"),(typeof s.id!="string"||o&&typeof s.name!="string")&&h(e,"id (and name when present) must be strings"),n=V(e,s,"args")}else p(s,["turn","step","index","dt","texts"])||h(e,"data must be exactly {turn, step, index, dt, texts}"),n=V(e,s,"texts");Number.isSafeInteger(t.seq0+n.length-1)||h(e,"member seqs must stay safe integers");let r=t.time0;for(const o of s.dt)r+=o,Number.isSafeInteger(r)||h(e,"member times must stay safe integers");return t}i(_e,"validateRow");function Re(t){const e=t.type==="tool-call-chunks"?t.data.args:t.data.texts,s=[];let n=t.time0;for(let r=0;r<e.length;r++){r>0&&(n+=t.data.dt[r-1]);let o;switch(t.type){case"text-chunks":o={type:"text-delta",index:t.data.index,text:e[r]};break;case"reasoning-chunks":o={type:"reasoning-delta",index:t.data.index,text:e[r]};break;case"tool-call-chunks":o={type:"tool-call-delta",index:t.data.index,id:t.data.id,...Object.hasOwn(t.data,"name")?{name:t.data.name}:{},argumentsDelta:e[r]};break;default:return ne(t,"chunk-rows expandRow")}s.push({type:"assistant/chunk",seq:t.seq0+r,time:n,data:{turn:t.data.turn,step:t.data.step,chunk:o}})}return s}i(Re,"expandRow");function De(t){if(!b(t))return[t];const e=t.type;return e!=="text-chunks"&&e!=="reasoning-chunks"&&e!=="tool-call-chunks"?[t]:Re(_e(t,e))}i(De,"decodeStorageRecord");const Pe=new Set(["agent-preset/selected","agent/inbox/spliced","approval/asked","approval/decided","approval/policy","assistant/chunk","assistant/message","command/done","command/run","compaction/end","compaction/prune","compaction/start","compaction/summary","feedback/record","goal/change","hook/invoked","hook/result","llm/retry","llm/retry-started","permission/preset","plan/mode","request/context","request/header","sandbox/mode","schedule/change","session/end-seed","session/title","session/title-llm-request","step/end","step/start","subagent/descriptor","todo/write","tool-workflow/agent-end","tool-workflow/agent-start","tool-workflow/run-end","tool-workflow/run-start","tool/call","tool/code-dispatch","tool/code-dispatch-start","tool/result","turn/end","turn/start","user/message","web/deepseek-search-llm-request"]);function H(t,e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("session header is not a plain JSON record");const s=e;if(s.version!==0)throw new Error(`session header version must be 0, got ${String(s.version)}`);if(s.id!==t)throw new Error(`session header id "${String(s.id)}" does not match session id "${t}"`);if(typeof s.createdAt!="number"||!Number.isSafeInteger(s.createdAt)||s.createdAt<0)throw new Error("session header createdAt must be a non-negative safe integer");if(s.cwd!==void 0){if(typeof s.cwd!="string")throw new Error("session header cwd must be a string");if(!te(s.cwd))throw new Error(`session header cwd must be an absolute path, got "${s.cwd}"`)}if(s.parentSession!==void 0&&typeof s.parentSession!="string")throw new Error("session header parentSession must be a string");if(s.seedLength!==void 0&&(typeof s.seedLength!="number"||!Number.isSafeInteger(s.seedLength)||s.seedLength<0))throw new Error("session header seedLength must be a non-negative safe integer");if(s.origin!==void 0&&s.origin!=="subagent")throw new Error('session header origin must be "subagent"');if(s.delegationDepth!==void 0&&(typeof s.delegationDepth!="number"||!Number.isSafeInteger(s.delegationDepth)||s.delegationDepth<0))throw new Error("session header delegationDepth must be a non-negative safe integer");if(s.agentPreset!==void 0&&typeof s.agentPreset!="string")throw new Error("session header agentPreset must be a string");return m(s)}i(H,"validateSessionHeader");function Te(t,e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const s=Reflect.getPrototypeOf(e);if(s!==Object.prototype&&s!==null)throw new Error("session header is not a plain JSON record")}return H(t,e)}i(Te,"validateRestoredSessionHeader");function Fe(t,e){const s=w(e===void 0?{version:0,id:t,createdAt:Date.now()}:e);if(s===void 0)throw new Error("session header is not losslessly JSON-serializable");return H(t,s)}i(Fe,"snapshotSessionHeader");function G(t){switch(K(t,`session event at seq ${t.seq}`),t.type){case"user/message":m(t.data);break;case"assistant/message":case"tool/result":m(t.data.message)}return t}i(G,"adoptSessionEvent");function Le(t){return G(structuredClone(t))}i(Le,"snapshotSessionEvent");function Me(t){const e=[t];for(;e.length>0;){const s=e.pop();Object.freeze(s);for(const n in s){const r=s[n];r!==null&&typeof r=="object"&&e.push(r)}}return t}i(Me,"freezeRestoredObject");function Ce(t,e){const s=t;if(s.type==="request/header-delta")throw new Error(`seed event at index ${e} uses unsupported legacy request/header-delta format`);for(const a in s)switch(a){case"type":case"seq":case"time":case"data":case"surfaceOp":case"sourceEventSeqs":case"ignorable":break;default:throw new Error(`seed event at index ${e} has an invalid event envelope`)}const n=s.type,r=s.seq,o=s.time;if(typeof n!="string"||typeof r!="number"||!Number.isSafeInteger(r)||r<0||typeof o!="number"||!Number.isSafeInteger(o)||s.data===void 0||s.ignorable!==void 0&&s.ignorable!==!0)throw new Error(`seed event at index ${e} has an invalid event envelope`);switch(n){case"request/header":case"user/message":case"assistant/message":case"tool/result":Ue(s,e)}}i(Ce,"assertSessionEventEnvelope");function Ue(t,e){const s=t.data,n=typeof s=="object"&&s!==null?s:void 0;if(t.type==="request/header"){const o=n?.header,a=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:void 0,c=a?.config;if(!Y(c))throw new Error(`seed request/header at index ${e} lacks provider/model`);const d=c,l=d.reasoningEffort;if(l!==void 0&&(typeof l!="string"||l.length===0))throw new Error(`seed request/header at index ${e} has an invalid reasoningEffort`);ze(a?.adapterDefaults,d,e)}const r=t.type;r!=="user/message"&&r!=="assistant/message"&&r!=="tool/result"||K(t,`seed ${r} at index ${e}`)}i(Ue,"assertCurrentLlmShape");const Je=new Set(["reasoningEffort","maxTokens"]);function ze(t,e,s){if(t===void 0)return;if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`seed request/header at index ${s} has invalid adapterDefaults`);const n=t;if(Object.keys(n).some(r=>!Je.has(r))||Object.values(n).some(r=>r!==!0)||n.reasoningEffort===!0&&e.reasoningEffort===void 0||n.maxTokens===!0&&e.maxTokens===void 0)throw new Error(`seed request/header at index ${s} has invalid adapterDefaults`)}i(ze,"assertAdapterDefaults");function K(t,e){const s=t.type;if(s!=="user/message"&&s!=="assistant/message"&&s!=="tool/result")return;const n=t.data,r=typeof n=="object"&&n!==null?n:void 0,o=s==="user/message"?r:r?.message;if(typeof o!="object"||o===null||typeof o.id!="string"||o.id==="")throw new Error(`${e} lacks an identified message`);const a=o,c=s==="assistant/message"?"assistant":"user";if(a.role!==c)throw new Error(`${e} message must have role "${c}"`);const d=a.source;if(typeof d!="object"||d===null||typeof d.kind!="string"||d.kind==="")throw new Error(`${e} message has invalid source`);if(!Array.isArray(a.content))throw new Error(`${e} message has invalid content`);const l=d;if(s==="assistant/message"){if(l.kind!=="model"||!Y(l))throw new Error(`${e} message must have model source`);return}if(s!=="tool/result")return;if(l.kind!=="tool"||typeof l.callId!="string"||l.callId==="")throw new Error(`${e} message must have tool source`);const f=a.content,u=f[0];if(f.length!==1||typeof u!="object"||u===null||u.type!=="tool-result"||!Array.isArray(u.content))throw new Error(`${e} message must contain one tool-result block`);if(u.toolCallId!==l.callId)throw new Error(`${e} message has mismatched tool call ids`)}i(K,"assertMessageEventShape");function Y(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.provider=="string"&&e.provider.length>0&&typeof e.model=="string"&&e.model.length>0}i(Y,"hasProviderModel");function W(t,e,s){if(t==="request/header-delta")throw new Error(`${s} uses unsupported legacy request/header-delta format`);if(t==="request/header"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.reason==="fallback")throw new Error(`${s} uses unsupported legacy request/header reason "fallback"`)}i(W,"assertSupportedRequestHeader");function S(t,e){return[...t.events.dispatch("emit",e)]}i(S,"collectSessionCallbacks");function B(t,e,s,n,r){for(const o of r)try{const a=o(...n);Promise.resolve(a).catch(c=>{t.logger.warn(`session "${s}": ${e} listener rejected: ${String(c)}`)})}catch(a){t.logger.warn(`session "${s}": ${e} listener threw: ${String(a)}`)}}i(B,"invokeContainedSessionObservers");const v=new WeakMap;var $=class N{static{i(this,"Session")}log=[];surfaceManager=new qe(this.log);get surface(){return this.surfaceManager}header;get id(){return this.header.id}firstLiveSeq;static create(e,s,n){return new N(e,s,n)}static fromRestore(e,s,n){return new N(e,s,n,"restore")}constructor(e,s,n,r="snapshot"){const o=r==="restore"?Te(e,n):void 0;if(s!==void 0)for(const[a,c]of s.entries()){const d=r==="restore"?c:w(c);if(d===void 0)throw new Error(`seed event at index ${a} is not losslessly JSON-serializable`);if(Ce(d,a),W(d.type,d.data,`seed event at index ${a}`),d.seq!==a)throw new Error(`seed event at index ${a} has seq ${d.seq} (expected ${a}); seed must be contiguous from 0`);try{this.surfaceManager.validateNext(d)}catch(l){throw new Error(`invalid seed event at index ${a}: ${l instanceof Error?l.message:"invalid surface metadata"}`)}this.log.push(r==="restore"?Me(d):m(d))}this.firstLiveSeq=this.log.length,this.header=o??Fe(e,n),s!==void 0&&this.log.at(-1)?.type!=="session/end-seed"&&this.append("session/end-seed",{})}eventsSnapshot;get events(){return this.eventsSnapshot??=Object.freeze([...this.log]),this.eventsSnapshot}get seq(){return this.log.length}append(e,s,...n){const r=n[0],o={...r?.sourceEventSeqs===void 0?{}:{sourceEventSeqs:r.sourceEventSeqs},...r?.surfaceOp===void 0?{}:{surfaceOp:r.surfaceOp}},a=w(s);if(a===void 0)throw new Error(`session event "${e}" carries non-JSON-serializable data`);W(e,a,`session event "${e}"`);const c=w(o);if(c===void 0)throw new Error(`session event "${e}" carries non-JSON-serializable surface metadata`);const d=v.get(this);if(d?.appending)throw new Error("session append cannot reenter while another append is being published");const l=m({type:e,seq:this.log.length,time:Date.now(),data:a,...c});this.surfaceManager.validateNext(l),d!==void 0&&(d.appending=!0);try{let f;const u=[this,l];return d!==void 0&&(f=S(d.emitCtx,[d.carrier,"session/event",...u])),this.log.push(l),this.eventsSnapshot=void 0,f!==void 0&&d!==void 0&&B(d.emitCtx,"session/event",d.id,u,f),l}finally{d!==void 0&&(d.appending=!1,d.detachRequested&&!d.announcing&&d.detach())}}headerFold;headerFoldSeq=0;requestHeader(){return this.headerFoldSeq<this.log.length&&(this.headerFold=m(U(this.log.slice(this.headerFoldSeq),this.headerFold)),this.headerFoldSeq=this.log.length),this.headerFold}contextFold;contextFoldSeq=0;requestContext(){if(this.contextFoldSeq<this.log.length){for(const e of this.log.slice(this.contextFoldSeq))e.type==="request/context"&&(this.contextFold=m({...e.data}));this.contextFoldSeq=this.log.length}return this.contextFold}derived=[];derivedNodes=0;derivedGeneration=0;deriveMessages(){const e=this.surface,s=e.nodes,n=e.replaceGeneration;n!==this.derivedGeneration&&(this.derived=[],this.derivedNodes=0,this.derivedGeneration=n);for(const r of s.slice(this.derivedNodes)){const o=this.deriveEventMessage(this.log[r]);o&&this.derived.push(o)}return this.derivedNodes=s.length,[...this.derived]}deriveEventMessage(e){return D(e)}},g=class extends Error{static{i(this,"SessionForkError")}code;constructor(t,e){super(t),this.code=e,this.name="SessionForkError"}},X=class extends ee{static{i(this,"SessionStore")}store=new Map;counter=0;constructor(t){super(t,"sessions"),t.inject(["typert"],e=>{e.typert.lookups.register("session",{parameter:"session",wire:"sessionId",hostTypeSymbol:"@deepseek-ai/dsh-session#Session",wireTypeSymbol:"@deepseek-ai/dsh-session/types#SessionId",resolve:i(s=>this.get(s),"resolve")})})}create(t,e){const s=this.prepare(t,e);return this.ctx.effect(function*(){yield this.enter(s),this.announce(s)}.bind(this),"sessions.create()"),s}prepare(t,e){let s;if(t===void 0)do s=`session-${++this.counter}`;while(this.store.has(s));else s=t;if(this.store.has(s))throw new Error(`session "${s}" already exists`);if(e?.seedSource==="persistence")return $.fromRestore(s,e.seed,e.meta);const n=e?.seed,r=e?.meta,o={version:0,id:s,createdAt:r?.createdAt??Date.now(),...r?.cwd===void 0?{}:{cwd:r.cwd},...r?.parentSession===void 0?{}:{parentSession:r.parentSession},...r?.seedLength===void 0?{}:{seedLength:r.seedLength},...r?.origin===void 0?{}:{origin:r.origin},...r?.delegationDepth===void 0?{}:{delegationDepth:r.delegationDepth},...r?.agentPreset===void 0?{}:{agentPreset:r.agentPreset}};return $.create(s,n,o)}enter(t){const e=t.id,s=ce(t,ie(this.ctx));if(this.store.has(e))throw new Error(`session "${e}" already exists`);if(v.has(t))throw new Error(`session "${e}" is already attached to a store`);const n={id:e,session:t,carrier:s,emitCtx:this.ctx,announced:!1,announcing:!1,appending:!1,detachRequested:!1,detach:i(()=>{this.detachEntered(n)},"detach")};this.store.set(e,n),v.set(t,n);let r=!0;return i(()=>{if(r){if(r=!1,n.announcing||n.appending){n.detachRequested=!0;return}n.detach()}},"detach")}detachEntered(t){t.detachRequested=!1,this.store.get(t.id)===t&&(this.store.delete(t.id),v.delete(t.session),t.announced&&this.emitDisposed(t))}announce(t){const e=this.liveEntryFor(t);if(e.announced||e.announcing)throw new Error(`session "${e.id}" was already announced`);e.announced=!0;const s=[t];e.announcing=!0;try{const n=S(this.ctx,[e.carrier,"session/created",t]);for(const r of n){const o=r(...s);Promise.resolve(o).catch(a=>{this.ctx.logger.warn(`session "${e.id}": session/created listener rejected: ${String(a)}`)})}}finally{e.announcing=!1,e.detachRequested&&!e.appending&&e.detach()}}emitDisposed(t){const e=[t.session];try{const s=S(this.ctx,[t.carrier,"session/disposed",t.session]);B(this.ctx,"session/disposed",t.id,e,s)}catch(s){this.ctx.logger.warn(`session "${t.id}": session/disposed dispatch threw: ${String(s)}`)}}async flush(t){const{carrier:e}=this.liveEntryFor(t),s=[t],n=S(this.ctx,[e,"session/flush",t]),r=(await Promise.allSettled(n.map(o=>{try{return o(...s)}catch(a){return Promise.reject(a)}}))).find(o=>o.status==="rejected");if(r!==void 0)throw r.reason;return n.length>0}liveEntryFor(t){const e=v.get(t);if(e===void 0||this.store.get(e.id)!==e)throw new Error(`session "${t.id}" is not live in this store`);return e}get(t){return this.store.get(t)?.session}list(){return[...this.store.values()].map(t=>t.session)}fork(t,e,s){if(s!==void 0&&this.get(s)!==void 0)throw new g(`session "${s}" already exists`,"SESSION_ALREADY_EXISTS");const n=this._resolveForkSource(t),r=this._forkSeed(n,e);return this.create(s,{seed:r,meta:{...n.header.cwd!==void 0?{cwd:n.header.cwd}:{},parentSession:n.id,seedLength:r.length}})}_forkSeed(t,e){const s=t.events,n=s.at(-1);let r;if(e!==void 0)r=e;else{if(n===void 0)return[];r=n.seq}if(!Number.isSafeInteger(r)||r<0)throw new g(`fork boundary for session "${t.id}" must be a non-negative safe integer, got ${String(r)}`,"INVALID_BOUNDARY");if(r>=s.length){const c=s.at(-1)?.seq;throw new g(`fork boundary ${r} does not exist in session "${t.id}" (last seq: ${c??"none"})`,"INVALID_BOUNDARY")}const o=s[r];if(o===void 0||o.seq!==r)throw new g(`fork boundary ${r} does not match a contiguous event seq in session "${t.id}"`,"INVALID_BOUNDARY");const a=s.slice(0,r+1).findLast(c=>c.type==="turn/start"||c.type==="turn/end");if(a?.type==="turn/start")throw new g(`fork boundary ${r} in session "${t.id}" ends inside open turn ${a.data.turn}`,"OPEN_TURN");return s.slice(0,r+1)}_resolveForkSource(t){if(typeof t=="string"){const s=this.get(t);if(s===void 0)throw new g(`session "${t}" not found`,"SESSION_NOT_FOUND");return s}const e=this.get(t.id);if(e===void 0)throw new g(`session "${t.id}" not found`,"SESSION_NOT_FOUND");if(e!==t)throw new g(`session "${t.id}" is not the live store instance`,"SESSION_NOT_LIVE");return t}};export{Pe as KNOWN_SESSION_EVENT_TYPES,le as SESSION_FORMAT_VERSION,$ as Session,g as SessionForkError,de as SessionId,Oe as SessionPreparation,X as SessionStore,X as default,J as TOOL_NOT_STARTED,z as TOOL_OUTCOME_UNKNOWN,G as adoptSessionEvent,C as canonicalHeader,De as decodeStorageRecord,D as deriveEventMessage,U as foldRequestHeader,Se as foldSurface,ke as headerEquals,xe as interruptedTurnClosers,ge as isAppendSurfaceEvent,pe as isJsonValue,me as isReplacementSurfaceEvent,R as isSurfaceEligibleType,q as isSurfaceEvent,Ie as packChunkRuns,w as snapshotJsonValue,Le as snapshotSessionEvent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var S=Object.defineProperty;var p=(s
|
|
1
|
+
var S=Object.defineProperty;var p=(e,s)=>S(e,"name",{value:s,configurable:!0});import{assertNever as h}from"@deepseek-ai/dsh-llm";const m="@deepseek-ai/dsh-session",f="session-invariant",w=["invariants"];function i(e,s,n,o,l){(e.openTurn!==n||e.openStep!==o)&&l(`${s} names turn ${n}/step ${o} but open is turn ${e.openTurn}/step ${e.openStep}`)}p(i,"requireOpenStep");function T(e,s,n){s.seq<=e.lastSeq&&n(`seq must strictly increase: saw ${s.seq} after ${e.lastSeq}`);let o=e.openTurn,l=e.openStep,d=e.nextTurn,u=e.nextStep,t={kind:"none"};switch(s.type){case"turn/start":e.openTurn!==null&&n(`turn/start ${s.data.turn} while turn ${e.openTurn} is still open`),s.data.turn!==e.nextTurn&&n(`turn/start expected turn ${e.nextTurn}, got ${s.data.turn}`),o=s.data.turn,u=1;break;case"turn/end":e.openTurn!==s.data.turn&&n(`turn/end ${s.data.turn} does not match open turn ${e.openTurn}`),e.openStep!==null&&n(`turn/end ${s.data.turn} while step ${e.openStep} is still open`),o=null,d+=1;break;case"step/start":e.openTurn!==s.data.turn&&n(`step/start in turn ${s.data.turn} but open turn is ${e.openTurn}`),e.openStep!==null&&n(`step/start ${s.data.step} while step ${e.openStep} is still open`),s.data.step!==e.nextStep&&n(`step/start expected step ${e.nextStep} in turn ${s.data.turn}, got ${s.data.step}`),l=s.data.step;break;case"step/end":i(e,"step/end",s.data.turn,s.data.step,n),t={kind:"clear"},l=null,u+=1;break;case"assistant/chunk":i(e,"assistant/chunk",s.data.turn,s.data.step,n);break;case"assistant/message":i(e,"assistant/message",s.data.turn,s.data.step,n);break;case"tool/call":i(e,"tool/call",s.data.turn,s.data.step,n),t={kind:"add",callId:s.data.callId};break;case"tool/result":{if(s.surfaceOp!=="append"){e.openTurn===null&&n("tool/result surface replacement appended outside any open turn");break}i(e,"tool/result",s.data.turn,s.data.step,n);const a=s.data.message.source.callId,r=s.data.message.content[0].isError===!0&&s.data.error?.code==="TOOL_NOT_STARTED";!e.pendingCalls.has(a)&&!r&&n(`tool/result for ${a} with no prior tool/call in this step`),t={kind:"delete",callId:a};break}case"user/message":break;case"session/end-seed":break;case"todo/write":case"request/header":case"request/context":e.openTurn===null&&n(`${s.type} appended outside any open turn (core execution events must be turn-enclosed)`)}return{scalars:{lastSeq:s.seq,openTurn:o,openStep:l,nextTurn:d,nextStep:u},pendingCalls:t}}p(T,"validateEvent");function b(e,s){switch(Object.assign(e,s.scalars),s.pendingCalls.kind){case"none":break;case"add":e.pendingCalls.add(s.pendingCalls.callId);break;case"delete":e.pendingCalls.delete(s.pendingCalls.callId);break;case"clear":e.pendingCalls.clear();break;default:h(s.pendingCalls,"session trace pending-call transition")}}p(b,"applyTransition");const x=Object.assign((e,s)=>{const n=new WeakMap,o=new WeakMap,l=p(()=>({lastSeq:-1,openTurn:null,openStep:null,nextTurn:1,nextStep:1,pendingCalls:new Set}),"freshTrace"),d=p(t=>{const a=l();n.set(t,a);for(const r of t.events)b(a,T(a,r,s));return a},"seedSession"),u=p(t=>n.get(t)??d(t),"traceFor");for(const t of e.sessions.list())d(t);e.on("session/created",t=>{d(t)},{global:!0}),e.on("session/event",(t,a)=>{const r=o.get(a);if(r===void 0||r.session!==t)return s("session/event reached publication without matching pre-commit validation");o.delete(a),b(r.trace,r.transition)},{global:!0}),e.on("internal/dispatch",(t,a,r)=>{if(a!=="session/event")return;const[c,g]=r,k=u(c),$=T(k,g,s);o.set(g,{session:c,trace:k,transition:$})},{global:!0})},{inject:["sessions"]}),q=p(e=>Promise.resolve(e.invariants.register(m,x)),"apply");export{q as apply,w as inject,f as name};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./types":{"types":"./lib/types/types.d.ts","default":"./lib/types/types.js"},"./src/*":"./src/*","./package.json":"./package.json","./surface":{"types":"./lib/types/surface.d.ts","default":"./lib/types/surface.js"}},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-brand":"^0.0.12","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-scope":"^0.0.12","@deepseek-ai/dsh-llm":"^0.0.12","@deepseek-ai/cordis":"^4.0.1","@deepseek-ai/dsh-typert-protocol":"^0.0.12"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-checkpoint-policy","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-checkpoint-policy","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-agent":"^0.0.12","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/dsh-session-persistence":"^0.0.12","@deepseek-ai/dsh-tools":"^0.0.12","@deepseek-ai/cordis":"^4.0.1","@deepseek-ai/dsh-llm":"^0.0.12"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var U=Object.defineProperty;var n=(l,d)=>U(l,"name",{value:d,configurable:!0});window.__ModuleLoader__.load({id:"@deepseek-ai/dsh-session-log-export",factory:n(l=>{var d={exports:{}},c=d.exports;Object.defineProperty(c,Symbol.toStringTag,{value:"Module"});let h=l("@deepseek-ai/dsh-client-runtime/client"),r=l("react/jsx-runtime"),u=l("@deepseek-ai/dsh-client-ui-primitives");const w={bySession:{}};function m(e){return`dsh-session-${String(e).replace(/[^A-Za-z0-9_-]/g,"_")}.zip`}n(m,"sessionLogZipFilename");function f(e,s){const o=document.createElement("a");o.href=e,o.download=s,o.click()}n(f,"downloadUrl");function S(){const e=globalThis.location?.origin;return e!==void 0&&e!=="null"?e:"http://dsh.internal"}n(S,"hostBase");function b(e){return e instanceof Error?e.message:String(e)}n(b,"messageOf");var v=class{static{n(this,"SessionLogDownloadController")}fetcher;save;store=(0,h.createSnapshotStore)(w);active=new Map;disposed=!1;constructor(e=(o,t)=>fetch(o,t),s=f){this.fetcher=e,this.save=s}download(e){const s=this.active.get(e);if(s!==void 0)return s.done;if(this.disposed)return Promise.resolve();const o=new AbortController,t=this.run(e,o.signal).finally(()=>{this.active.delete(e)});return this.active.set(e,{abort:o,done:t}),t}dismiss(e){const s=this.store.getSnapshot().bySession[String(e)];s===void 0||!s.open||this.publish(e,{...s,open:!1})}async dispose(){this.disposed=!0;const e=[...this.active.values()];for(const s of e)s.abort.abort();await Promise.allSettled(e.map(s=>s.done))}async run(e,s){this.publish(e,{open:!0,status:"downloading",error:null});try{const o=new URL("/api/session.export",S());o.searchParams.set("sessionId",e),o.searchParams.set("includeDescendants","true");const t=await this.fetcher(o,{method:"HEAD",signal:s});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Export failed: HTTP ${t.status}${a===""?"":` ${a}`}`)}this.save(o.toString(),m(e));const i=this.store.getSnapshot().bySession[String(e)]?.open??!0;this.publish(e,{open:i,status:"success",error:null})}catch(o){if(s.aborted)return;const t=this.store.getSnapshot().bySession[String(e)]?.open??!0;this.publish(e,{open:t,status:"error",error:b(o)})}}publish(e,s){this.store.update(o=>{o.bySession={...o.bySession,[String(e)]:s}})}};function y({sessionId:e,useSessionLogDownload:s,dismiss:o,t}){const i=s(C=>C.bySession[String(e)]),a=i?.status,F=i?.open===!0,B=a==="error"?i?.error||t("dialog.commandFailed"):null,N=t(a==="downloading"?"dialog.preparingTitle":a==="success"?"dialog.successTitle":"dialog.errorTitle"),P=a==="downloading"?t("dialog.preparingDescription"):a==="success"?t("dialog.successDescription"):B??t("dialog.commandFailed");return(0,r.jsx)(u.Modal,{open:F,onClose:n(()=>{o(e)},"onClose"),title:N,description:P,closeLabel:t("dialog.close"),footer:(0,r.jsx)(u.Button,{variant:"primary",onClick:n(()=>{o(e)},"onClick"),children:t("dialog.close")})})}n(y,"SessionLogDownloadDialog");const x=".UFwDNa_sessionLogButton{border:1px solid var(--dsw-alias-border-l2);min-width:111px;height:32px;color:var(--dsw-alias-label-primary);font-family:var(--dsw-font-family);cursor:pointer;background:0 0;border-radius:18px;justify-content:center;align-items:center;gap:4px;padding:6px 12px;font-size:13px;font-weight:400;line-height:20px;display:inline-flex}.UFwDNa_sessionLogButton:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.UFwDNa_sessionLogButton:disabled{color:var(--dsw-alias-label-dimmed);cursor:wait}.UFwDNa_sessionLogButton span,.UFwDNa_sessionLogButton svg{flex:none}.UFwDNa_sessionLogButton span{white-space:nowrap}",p="@deepseek-ai/dsh-session-log-export/HeaderAction.module.css";if(typeof document<"u"&&document.querySelector("style[data-plugin-css="+JSON.stringify(p)+"]")===null){const e=document.createElement("style");e.dataset.plugin="@deepseek-ai/dsh-session-log-export",e.dataset.pluginCss=p,e.textContent=x,document.head.appendChild(e)}var _={sessionLogButton:"UFwDNa_sessionLogButton"};function D(e){const{sessionId:s,useSessionLogDownload:o,request:t}=e,i=o(a=>a.bySession[String(s)])?.status==="downloading";return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:_.sessionLogButton,disabled:i,"aria-busy":i,onClick:n(()=>{t(s)},"onClick"),children:[(0,r.jsx)("span",{children:"Session log"}),(0,r.jsx)(u.IconDownloadOutline16,{size:12})]}),(0,r.jsx)(y,{...e})]})}n(D,"SessionLogDownloadHeaderAction");const g="session-log-download",L={"dialog.preparingTitle":"正在导出 Session","dialog.preparingDescription":"正在准备包含当前 Session、子 Session 和附件的 ZIP 文件。","dialog.successTitle":"Session 导出已开始下载","dialog.successDescription":"浏览器正在下载 Session ZIP 文件。","dialog.errorTitle":"Session 导出失败","dialog.close":"关闭","dialog.commandFailed":"无法启动 Session 导出。"},j={"dialog.preparingTitle":"Exporting Session","dialog.preparingDescription":"Preparing a ZIP containing this Session, its sub-Sessions, and attachments.","dialog.successTitle":"Session download started","dialog.successDescription":"The browser is downloading the Session ZIP.","dialog.errorTitle":"Session export failed","dialog.close":"Close","dialog.commandFailed":"Could not start the Session export."},k=["slots","locale"];function T(e){const s=new v;e.provide("sessionLogDownload",s),e.effect(()=>async()=>{await s.dispose()},"session-log-download: browser download lifecycle"),e.effect(()=>e.locale.register(g,{zh:L,en:j}),"session-log-download: browser dictionaries"),e.on("command/executed",(o,t,i)=>{t==="export"&&i.kind==="success"&&s.download(o)}),e.slots.inject("conversation.session.header.utilities",()=>e.slots.register({name:"conversation.session.header.utilities",id:"session-log-download",locale:g,inject:n(()=>({hooks:{sessionLogDownload:s.store},request:n(o=>s.download(o),"request"),dismiss:n(o=>{s.dismiss(o)},"dismiss")}),"inject")},D))}return n(T,"apply"),c.apply=T,c.inject=k,d.exports},"factory")});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-log-export","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-log-export","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./client":{"types":"./lib/types/client/index.d.ts","default":"./lib/client.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"react":"^18.2.0","@deepseek-ai/dsh-client-ui-commands":"^0.0.12","@deepseek-ai/dsh-client-runtime":"^0.0.12","@deepseek-ai/dsh-client-locale":"^0.0.12","@deepseek-ai/dsh-client-ui-slots":"^0.0.12","@deepseek-ai/dsh-client-ui-primitives":"^0.0.12","@deepseek-ai/dsh-client-ui-conversation":"^0.0.12","@deepseek-ai/cordis":"^4.0.1","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-commands":"^0.0.12"},"dsh":{"client":{"inject":["@deepseek-ai/dsh-client-locale","@deepseek-ai/dsh-client-runtime","@deepseek-ai/dsh-client-ui-commands","@deepseek-ai/dsh-client-ui-conversation"],"platform":"web"}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{Service as z}from"@deepseek-ai/cordis";import{KNOWN_SESSION_EVENT_TYPES as T,SESSION_FORMAT_VERSION as f,SessionPreparation as b,adoptSessionEvent as S,interruptedTurnClosers as E,snapshotJsonValue as k,snapshotSessionEvent as F}from"@deepseek-ai/dsh-session";import{MAX_TIMER_DELAY_MS as L}from"@deepseek-ai/dsh-timeout";function B(e){return e}o(B,"SessionPersistenceRevision");var N=class{static{o(this,"SessionPreparations")}capacity;entries=new Map;constructor(e){this.capacity=e}has(e){return this.entries.has(e)}async inspect(e,t,r){const s=this.entryFor(e,t),i=r===void 0?await s.result:await p(s.result,r),n=s.source??i;return this.entries.get(e)===s&&s.phase==="ready"&&this.touch(s),n}async reserve(e,t,r,s){const i=this.entryFor(e,t);for(await(s===void 0?i.result:p(i.result,s));this.entries.get(e)===i&&i.phase!=="ready";){const u=i.reservationSettled;if(u===void 0)throw new Error(`session "${e}" preparation lost its reservation waiter`);s===void 0?await u:await p(u,s)}if(this.entries.get(e)!==i)return;const n=i.source,a=Promise.withResolvers();i.phase="committing",i.reservationSettled=a.promise,i.settleReservation=a.resolve;let c;try{c=await r(n)}catch(u){throw this.remove(i),u}if(c===void 0){this.remove(i);return}i.source=c.source;try{s?.throwIfAborted()}catch(u){throw this.makeReady(i),u}if(this.entries.get(e)!==i)return;const d={entry:i,source:c.source,state:c.state};return i.phase="reserved",i.reservation=d,d}reservationFor(e){const t=this.entries.get(e.id);if(t!==void 0){if(t.phase==="reserved"&&t.source?.session===e&&t.reservation!==void 0)return t.reservation;throw new Error(`cannot publish session "${e.id}": persisted state already owns this identity`)}}attach(e){const{entry:t}=e;if(this.entries.get(t.id)!==t||t.reservation!==e)throw new Error(`session "${t.id}" preparation is no longer reserved`);this.remove(t)}discard(e){const{entry:t}=e;this.entries.get(t.id)!==t||t.reservation!==e||this.remove(t)}release(e,t){const{entry:r}=e;if(!(this.entries.get(r.id)!==r||r.reservation!==e||r.phase!=="reserved")){if(!t){this.remove(r);return}delete r.reservation,this.makeReady(r)}}invalidate(e){const t=this.entries.get(e);t!==void 0&&this.remove(t)}discardReady(e,t){const r=this.entries.get(e);return r===void 0||r.source!==t?"missing":r.phase!=="ready"?"retained":(this.remove(r),"discarded")}assertWritable(e){const t=this.entries.get(e)?.phase;if(t==="committing"||t==="reserved")throw new Error(`cannot append session "${e}" while its persisted preparation is reserved`)}takeReady(e){const t=this.entries.get(e);if(!(t===void 0||t.phase!=="ready"||t.source===void 0))return this.remove(t),t.source}entryFor(e,t){const r=this.entries.get(e);if(r!==void 0)return r;const s=Promise.withResolvers(),i={id:e,result:s.promise,phase:"loading"};this.entries.set(e,i);let n;try{n=t()}catch(a){return this.remove(i),s.reject(a),i}return n.then(a=>{this.entries.get(e)===i&&(i.source=a,this.makeReady(i)),s.resolve(a)},a=>{this.remove(i),s.reject(a)}),i}makeReady(e){if(this.entries.get(e.id)!==e)return;e.phase="ready";const t=e.settleReservation;delete e.reservationSettled,delete e.settleReservation,t?.(),this.touch(e)}remove(e){if(this.entries.get(e.id)!==e)return;this.entries.delete(e.id);const t=e.settleReservation;delete e.reservationSettled,delete e.settleReservation,t?.()}touch(e){this.entries.delete(e.id),this.entries.set(e.id,e);let t=0;for(const r of this.entries.values())r.phase==="ready"&&(t+=1);if(!(t<=this.capacity)){for(const[r,s]of this.entries)if(s.phase==="ready"){this.entries.delete(r);return}}}};function p(e,t,r=()=>!1){return new Promise((s,i)=>{let n=!1;const a=o(d=>{n||(n=!0,t.removeEventListener("abort",c),d())},"finish"),c=o(()=>{r()||a(()=>{try{t.throwIfAborted()}catch(d){$(i,d);return}i(new Error("queued observation abort event lacked an aborted signal"))})},"onAbort");t.addEventListener("abort",c,{once:!0}),e.then(d=>{a(()=>{s(d)})},d=>{a(()=>{$(i,d)})}),t.aborted&&c()})}o(p,"observeQueuedAbort");function $(e,t){e(t)}o($,"rejectObservation");var _=class{static{o(this,"SessionWriteBehind")}options;pending=[];timer;active;barrier;deadlineExpired=!1;automaticPaused=!1;constructor(e){this.options=e}get hasWork(){return this.pending.length>0||this.active!==void 0}enqueue(e){const t=this.pending.length===0;this.pending.push(structuredClone(e)),this.barrier===void 0&&(this.automaticPaused?(this.automaticPaused=!1,this.deadlineExpired=!1,this.armTimer()):t&&this.armTimer())}flush(){if(this.barrier!==void 0)return this.barrier;this.cancelTimer(),this.deadlineExpired=!1,this.automaticPaused=!1;const e=Promise.withResolvers();return this.barrier=e.promise,this.drainBarrier(e.resolve,e.reject),e.promise}cancelAutomaticWait(){this.cancelTimer(),this.deadlineExpired=!1}armTimer(){this.timer=setTimeout(()=>{this.onDeadline()},this.options.maxDelayMs)}cancelTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}onDeadline(){if(this.timer=void 0,this.active!==void 0){this.deadlineExpired=!0;return}this.startBackground()}startBackground(){this.startWrite(!0).then(()=>{this.continueAutomatic()},()=>{})}continueAutomatic(){this.barrier!==void 0||this.pending.length===0||this.deadlineExpired&&(this.deadlineExpired=!1,this.startBackground())}async drainBarrier(e,t){try{const r=this.active;for(r!==void 0&&(await Promise.allSettled([r]),this.automaticPaused=!1);this.pending.length>0;)await this.startWrite(!1)}catch(r){this.barrier=void 0,t(r);return}this.barrier=void 0,e()}startWrite(e){const t=this.pending.splice(0);this.cancelTimer(),this.deadlineExpired=!1;const r=Promise.resolve().then(()=>this.options.write(t)).catch(s=>{throw this.pending=t.concat(this.pending),this.cancelTimer(),this.deadlineExpired=!1,this.automaticPaused=!0,e&&this.options.reportBackgroundFailure(s),s}).finally(()=>{this.active=void 0});return this.active=r,r}};const D=5,W=200,v=L;var O=class extends Error{static{o(this,"SessionPersistenceCorruptionError")}constructor(e,t){super(e,t),this.name="SessionPersistenceCorruptionError"}},g=class extends Error{static{o(this,"SessionFormatUnsupportedError")}location;constructor(e,t){super(e),this.location=t,this.name="SessionFormatUnsupportedError"}};function x(e,t){return t>f?`session "${e}" uses log format v${t}, but this harness reads only v${f}: the log was written by a newer harness — upgrade the harness to open it`:`session "${e}" uses log format v${t}, older than the supported v${f}, and this build ships no upgrade path for it`}o(x,"sessionFormatVersionRefusal");async function V(e){const t=await Promise.allSettled([...e]),r=[];for(const s of t)s.status==="rejected"&&r.push(s.reason);return r}o(V,"settledErrors");function P(e,t){return t.length<=e.length&&t.every((r,s)=>{const i=e[s];return i!==void 0&&JSON.stringify(i)===JSON.stringify(r)})}o(P,"seedCoversPrefix");function y(e,t){const r="request/header-delta",s=e.find(c=>c.type===r);if(s!==void 0)throw new Error(`session "${t}" contains unsupported legacy request/header-delta event at seq ${s.seq}`);const i="mode/set",n=e.find(c=>c.type===i);if(n!==void 0)throw new Error(`session "${t}" contains unsupported legacy mode/set event at seq ${n.seq}`);const a=e.find(c=>c.type==="request/header"&&c.data.reason==="fallback");if(a!==void 0)throw new Error(`session "${t}" contains unsupported legacy request/header reason "fallback" at seq ${a.seq}`)}o(y,"assertSupportedEvents");function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}o(h,"asRecord");function l(e,t,r=[]){const s=[...t,...r];return Object.keys(e).every(i=>s.includes(i))&&t.every(i=>Object.hasOwn(e,i))}o(l,"hasOnlyKeys");function w(e,t){return`legacy-message:${e}:${t}`}o(w,"legacyMessageId");function J(e){const t=h(e.surfaceOp);return t?.op==="replace"&&typeof t.start=="number"?t.start:void 0}o(J,"replacementStart");function U(e){const t=h(e.data);if(e.type==="steering/message")return!0;if(t===void 0)return!1;switch(e.type){case"user/message":return!Object.hasOwn(t,"id")&&Object.hasOwn(t,"content");case"assistant/message":return!Object.hasOwn(t,"message")&&Object.hasOwn(t,"content");case"tool/result":return!Object.hasOwn(t,"message")&&Object.hasOwn(t,"callId");default:return!1}}o(U,"needsLegacyPrefix");function I(e,t){if(e.type!=="steering/message")return e;const r=h(e.data);if(r===void 0)throw new Error(`session "${t}" contains malformed pre-react-loop steering/message at seq ${e.seq}`);const s=h(r.message);if(s!==void 0&&Number.isSafeInteger(r.turn)&&l(r,["turn","message"]))return{...e,type:"user/message",data:s};if(!Number.isSafeInteger(r.turn)||!l(r,["turn","content","source"]))throw new Error(`session "${t}" contains malformed pre-react-loop steering/message at seq ${e.seq}`);const{turn:i,...n}=r;return{...e,type:"user/message",data:{...n,id:w(t,e.seq),role:"user"}}}o(I,"migrateLegacySteeringEvent");function M(e,t){if(e.type!=="turn/start")return e;const r=h(e.data);if(r===void 0||!Object.hasOwn(r,"trigger"))return e;const s=h(r.trigger);if(!Number.isSafeInteger(r.turn)||r.turn<1||!l(r,["turn","trigger"])||s===void 0||typeof s.kind!="string"||s.kind.length===0)throw new Error(`session "${t}" contains malformed pre-react-loop turn/start at seq ${e.seq}`);return{...e,data:{turn:r.turn}}}o(M,"migrateLegacyTurnStartEvent");function C(e,t){if(e.type!=="turn/end")return e;const r=h(e.data);if(r===void 0)return e;const s=o(()=>{throw new Error(`session "${t}" contains malformed pre-react-loop turn/end at seq ${e.seq}`)},"malformed"),i=h(r.reason);if(!Number.isSafeInteger(r.turn)||r.turn<1||!l(r,["turn","reason"])||i===void 0||typeof i.kind!="string")return s();let n;switch(i.kind){case"completed":case"blocked":case"max-tokens":case"interrupted":return l(i,["kind"])?e:s();case"aborted":if(Object.hasOwn(i,"reason"))return e;if(!l(i,["kind"]))return s();n={kind:"aborted",reason:{kind:"legacy"}};break;case"disposed":if(!l(i,["kind"]))return s();n={kind:"aborted",reason:{kind:"disposed"}};break;case"error":{if(Object.hasOwn(i,"error"))return e;if(!Number.isSafeInteger(i.step)||i.step<0)return s();const a=h(i.failure);if(a!==void 0&&l(i,["kind","step","failure"])&&l(a,["message","code"],["status","providerRetryAfterMs","requestId"])&&typeof a.message=="string"&&typeof a.code=="string"&&(a.status===void 0||typeof a.status=="number")&&(a.providerRetryAfterMs===void 0||typeof a.providerRetryAfterMs=="number")&&(a.requestId===void 0||typeof a.requestId=="string")){n={kind:"error",error:a};break}if(!l(i,i.code===void 0?["kind","step","message"]:["kind","step","message","code"])||typeof i.message!="string"||i.code!==void 0&&typeof i.code!="string")return s();n={kind:"error",error:{message:i.message,code:typeof i.code=="string"?i.code:"UNKNOWN"}};break}default:return e}return{...e,data:{...r,reason:n}}}o(C,"migrateLegacyTurnEndEvent");function A(e,t,r){const s=h(e.data);if(s===void 0)return e;switch(e.type){case"user/message":return Object.hasOwn(s,"id")||Object.hasOwn(s,"role")||Object.hasOwn(s,"message")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"source")?e:{...e,data:{...s,id:w(t,e.seq),role:"user"}};case"assistant/message":{if(Object.hasOwn(s,"message")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"provenance"))return e;const{content:i,provenance:n,...a}=s;return{...e,data:{...a,message:{id:w(t,e.seq),role:"assistant",content:i,source:{...h(n),kind:"model"}}}}}case"tool/result":{if(Object.hasOwn(s,"message")||!Object.hasOwn(s,"callId")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"isError"))return e;const{callId:i,content:n,isError:a,...c}=s,d=J(e);return{...e,data:{...c,message:{id:d===void 0?w(t,e.seq):r.get(d),role:"user",content:[{type:"tool-result",toolCallId:i,content:n,isError:a}],source:{kind:"tool",callId:i}}}}}default:return e}}o(A,"migrateLegacyMessageEvent");function R(e){const t=h(e.data),r=e.type==="user/message"?t:h(t?.message);return typeof r?.id=="string"?r.id:void 0}o(R,"eventMessageId");function m(e,t){y(e,t);const r=new Map;return e.map(s=>{const i=F(A(I(C(M(s,t),t),t),t,r)),n=R(i);return n!==void 0&&r.set(i.seq,n),i})}o(m,"snapshotStoredEvents");function Y(e,t){y(e,t);const r=new Map;for(const[s,i]of e.entries()){const n=S(A(I(C(M(i,t),t),t),t,r));e[s]=n;const a=R(n);a!==void 0&&r.set(n.seq,a)}return e}o(Y,"adoptStoredEvents");var H=class{static{o(this,"PersistenceCoordinator")}ctx;backend;states=new Map;live=new Map;retirements=new Map;preparations;chains=new Map;writeBatchMaxDelayMs;constructor(e,t,r={preparedSessionCacheSize:5,writeBatchMaxDelayMs:200}){if(this.ctx=e,this.backend=t,!Number.isSafeInteger(r.preparedSessionCacheSize)||r.preparedSessionCacheSize<1)throw new TypeError("preparedSessionCacheSize must be a positive safe integer");if(!Number.isSafeInteger(r.writeBatchMaxDelayMs)||r.writeBatchMaxDelayMs<1||r.writeBatchMaxDelayMs>v)throw new TypeError(`writeBatchMaxDelayMs must be an integer between 1 and ${v}`);this.writeBatchMaxDelayMs=r.writeBatchMaxDelayMs,this.preparations=new N(r.preparedSessionCacheSize),this.installWritePath()}create(e){const t=k(e);return t===void 0?Promise.reject(new TypeError("session metadata must be losslessly JSON-serializable")):!Number.isSafeInteger(t.createdAt)||t.createdAt<0?Promise.reject(new TypeError("session metadata createdAt must be a non-negative safe integer")):this.serialize(t.id,()=>this.createCore(t))}async createCore(e){if(this.states.has(e.id)||this.preparations.has(e.id))throw new Error(`session "${e.id}" already exists in this backend`);if(await this.backend.loadStored(e.id)!==void 0)throw new Error(`session "${e.id}" already has a persisted log on disk; load/resume it instead of creating`);this.states.set(e.id,{meta:e,cursor:0,materialized:!1})}async append(e,t){const r=k(t);if(r===void 0)throw new TypeError("session event batch is not losslessly JSON-serializable because it contains non-JSON-serializable data");return this.serialize(e,()=>this.appendCore(e,r))}async appendCore(e,t){if(y(t,e),t.length===0)return;this.preparations.assertWritable(e);let r=this.states.get(e);r===void 0&&(r=await this.adopt(e));for(const[s,i]of t.entries())if(i.seq!==r.cursor+s)throw new Error(`append seq mismatch for "${e}": expected ${r.cursor+s} at index ${s}, got ${i.seq}`);await this.backend.appendBatch(r.meta,t,r.materialized),r.materialized=!0,r.cursor+=t.length,this.preparations.invalidate(e)}async prepare(e,t){for(;;){if(await this.waitForRetirement(e,t),this.ctx.sessions.get(e)!==void 0)throw new Error(`cannot prepare session "${e}" while it is live`);const r=await this.preparations.reserve(e,()=>this.serialize(e,()=>this.prepareCore(e)),s=>this.serialize(e,()=>this.commitPrepared(s),t),t);if(r!==void 0){if(this.ctx.sessions.get(e)!==void 0)throw this.preparations.release(r,!1),new Error(`cannot prepare session "${e}" while it is live`);return b.create(r.source.session,{release:o(()=>{this.preparations.release(r,r.state.owner===void 0&&r.source.session.events.length===r.source.sessionLength)},"release")})}}}async load(e){for(;;){await this.waitForRetirement(e);const t=this.ctx.sessions.get(e);if(t!==void 0)return this.loadLiveSnapshot(t);const r=await this.preparations.reserve(e,()=>this.serialize(e,()=>this.prepareCore(e)),i=>this.serialize(e,()=>this.commitPrepared(i)));if(r===void 0)continue;const s=this.ctx.sessions.get(e);return s!==void 0?(this.preparations.discard(r),this.loadLiveSnapshot(s)):(this.preparations.discard(r),r.source.inspection)}}async inspect(e,t){for(;;){t?.throwIfAborted(),this.retirements.has(e)&&await this.waitForRetirement(e,t);const r=this.ctx.sessions.get(e);if(r!==void 0)return this.inspectLive(r);try{const s=await this.preparations.inspect(e,()=>this.serialize(e,()=>this.prepareCore(e)),t),i=this.ctx.sessions.get(e);if(i!==void 0)return this.inspectLive(i);const n=await this.serialize(e,()=>this.isPreparedSourceCurrent(s,t),t),a=this.ctx.sessions.get(e);if(a!==void 0)return this.inspectLive(a);if(n||this.preparations.discardReady(e,s)==="retained")return s.inspection}catch(s){t?.throwIfAborted();const i=this.ctx.sessions.get(e);if(i!==void 0)return this.inspectLive(i);throw s}}}readFrom(e,t,r){if(!Number.isSafeInteger(t)||t<0)return Promise.reject(new TypeError(`readFrom fromSeq must be a non-negative safe integer, got ${String(t)}`));const s=Promise.resolve(this.retirements.get(e));return(r===void 0?s:p(s,r,()=>!1)).then(()=>this.serialize(e,()=>this.readFromCore(e,t,r),r))}async readFromCore(e,t,r){if(r?.throwIfAborted(),this.backend.loadStoredFrom!==void 0){let i;try{i=await this.backend.loadStoredFrom(e,t,r)}catch(a){throw r?.aborted&&r.throwIfAborted(),a}if(r?.throwIfAborted(),i===void 0)throw new Error(`session "${e}" not found`);if(this.assertStoredId(e,i.meta),this.assertVersion(i.meta),i.events.some(U)){const a=await this.readStoredPrefix(e,r);return{meta:a.meta,events:a.events.filter(c=>c.seq>=t)}}const n=m(i.events,e);return this.assertEventsSupported(i.meta,n),{meta:structuredClone(i.meta),events:n}}const s=await this.readStoredPrefix(e,r);return{meta:s.meta,events:s.events.slice(t)}}async readStoredPrefix(e,t){t?.throwIfAborted();const r=await this.backend.loadStored(e,t);if(t?.throwIfAborted(),r===void 0)throw new Error(`session "${e}" not found`);this.assertStoredId(e,r.meta),this.assertVersion(r.meta);const s=m(r.events,e);return this.assertEventsSupported(r.meta,s),{meta:structuredClone(r.meta),events:s}}async prepareCore(e){const t=await this.backend.loadStored(e);if(t===void 0)throw new Error(`session "${e}" not found`);try{const{meta:r,events:s,revision:i,tornMarker:n}=t;this.assertStoredId(e,r),this.assertVersion(r);const a=Y(s,e);this.assertEventsSupported(r,a);const c=E(a).map(S),d=[...a,...c],u=this.ctx.sessions.prepare(e,{seed:d,meta:r,seedSource:"persistence"});return{inspection:Object.freeze({meta:u.header,events:Object.freeze(d)}),session:u,revision:i,sessionLength:u.events.length,tornMarker:n,closers:c}}catch(r){throw r instanceof g?r:new O(`stored session "${e}" failed validation: ${String(r)}`,{cause:r})}}async commitPrepared(e){const t=e.inspection.meta.id,r=e.inspection.events.length,s=this.states.get(t);if(s?.owner!==void 0)throw new Error(`session "${t}" already has a live persistence owner`);if(!await this.isPreparedSourceCurrent(e))return;if(e.tornMarker!==void 0||e.closers.length>0){await this.backend.commitRepair(e.inspection.meta,e.tornMarker,e.closers);return}const i=s??{meta:e.inspection.meta,cursor:r,materialized:!0};return i.meta=e.inspection.meta,i.cursor=r,i.materialized=!0,this.states.set(t,i),{source:e,state:i}}async isPreparedSourceCurrent(e,t){return await this.backend.readStoredRevision(e.inspection.meta.id,t)===e.revision}async loadLiveSnapshot(e){const t=e.events;await this.flush(e);const r=this.states.get(e.id);if(r===void 0)throw new Error(`session "${e.id}" lost persistence state during load`);if(t.length===0)throw new Error(`session "${e.id}" not found`);if(E(t).length>0)throw new Error(`cannot load session "${e.id}" while its live turn is open; use the live Session or wait for the turn to close`);return Object.freeze({meta:r.meta,events:t})}inspectLive(e){return Object.freeze({meta:e.header,events:e.events})}waitForRetirement(e,t){const r=Promise.resolve(this.retirements.get(e));return t===void 0?r:p(r,t,()=>!1)}serialize(e,t,r){const s=this.chains.get(e)??Promise.resolve();let i=!1;const n=o(()=>(r?.throwIfAborted(),i=!0,t()),"run"),a=s.then(n,n),c=a.then(()=>{},()=>{});return this.chains.set(e,c),c.then(()=>{this.chains.get(e)===c&&this.chains.delete(e)}),r===void 0?a:p(a,r,()=>i)}async adopt(e){for(;;){const t=this.preparations.takeReady(e)??await this.prepareCore(e),r=await this.commitPrepared(t);if(r!==void 0)return r.state}}assertVersion(e){if(e.version!==f)throw this.unsupported(e,x(e.id,e.version))}assertEventsSupported(e,t){for(const r of t)if(!(T.has(r.type)||r.ignorable===!0))throw this.unsupported(e,`session "${e.id}" contains event type "${r.type}" (seq ${r.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`)}unsupported(e,t){const r=this.backend.locate?.(e);return new g(r===void 0?t:`${t} (raw log: ${r.path})`,r)}assertStoredId(e,t){if(t.id!==e)throw new Error(`stored session identity mismatch: requested "${e}", header contains "${t.id}"`)}installWritePath(){const e=this.ctx;e.effect(()=>async()=>{let t;try{const r=await V([...this.live.keys()].map(s=>this.flush(s)));for(;this.chains.size>0;)await Promise.allSettled([...this.chains.values()]);if(r.length>0)throw new AggregateError(r,`${this.backend.name} dispose failed`)}catch(r){throw t=r,r}finally{try{await this.backend.close?.()}catch(r){if(t===void 0)throw r}}},`${this.backend.name} write path`),e.on("session/created",t=>{this.initFor(t)}),e.on("session/event",(t,r)=>{this.initFor(t).writes.enqueue(r)}),e.on("session/flush",t=>this.flush(t)),e.on("session/disposed",t=>{this.retire(t)});for(const t of e.sessions.list())this.initFor(t)}retire(e){if(!this.live.has(e))return;const t=this.retireCore(e);this.retirements.set(e.id,t);const r=o(()=>{this.retirements.get(e.id)===t&&this.retirements.delete(e.id)},"forget");t.then(r,r),t.catch(s=>{this.ctx.logger.warn(`${this.backend.name}: session "${e.id}" retirement failed: ${String(s)}`)})}async retireCore(e){await this.flush(e);const t=e.header.id;await this.serialize(t,()=>{this.live.delete(e),this.states.get(t)?.owner===e&&this.states.delete(t)})}initFor(e){const t=this.live.get(e);if(t)return t;const r=this.preparations.reservationFor(e);if(r!==void 0){const n=this.attachPrepared(e,r);return this.live.set(e,n),n}const s=e.events.map(n=>structuredClone(n)),i={init:Promise.resolve(),writes:this.createWriteBehind(e,()=>i.init)};return this.live.set(e,i),i.init=this.serialize(e.header.id,()=>this.onCreated(e,s)),i.init.catch(()=>{}),i}attachPrepared(e,t){const{source:r,state:s}=t;if(r.session!==e||s.owner!==void 0||s.cursor!==r.inspection.events.length||e.firstLiveSeq!==s.cursor)throw new Error(`session "${e.id}" preparation no longer matches its persistence state`);const i=e.events.slice(s.cursor).map(a=>structuredClone(a));this.preparations.attach(t),s.owner=e;const n={init:Promise.resolve(),writes:this.createWriteBehind(e,()=>n.init)};return i.length>0&&(n.init=this.serialize(e.id,()=>this.appendCore(e.id,i)),n.init.catch(()=>{})),n}async seedMatchesPersisted(e,t,r){if(r===0)return!0;const s=await this.backend.loadStored(e);return s===void 0?!1:(this.assertStoredId(e,s.meta),P(t,m(s.events,e).slice(0,r)))}async onCreated(e,t){const r=e.header.id,s=this.states.get(r);if(s!==void 0){if(s.owner===e)return;if(s.owner===void 0){if(s.meta.cwd!==e.header.cwd)throw new Error(`session "${r}" is already persisted at a different cwd (persisted: ${String(s.meta.cwd)}, live: ${String(e.header.cwd)}) (id collision)`);if(!await this.seedMatchesPersisted(r,t,s.cursor))throw new Error(`session "${r}" is already persisted with ${s.cursor} event(s) that do not match this live session (id collision)`);s.owner=e;const d=t.slice(s.cursor);d.length>0&&await this.appendCore(r,d);return}const c=this.live.get(s.owner);if(!s.materialized&&!c?.writes.hasWork)this.states.delete(r);else throw new Error(`session "${r}" is already bound to a different live session in this backend (id collision)`)}const i=await this.backend.loadStored(r);if(i!==void 0){await this.adoptLivePrefix(e,t,i);return}const n={...e.header};await this.createCore(n);const a=this.states.get(r);a!==void 0&&(a.owner=e),t.length>0&&await this.appendCore(r,t)}async adoptLivePrefix(e,t,r){const{meta:s,events:i,tornMarker:n}=r;if(this.assertStoredId(e.header.id,s),s.cwd!==e.header.cwd)throw new Error(`session "${e.header.id}" is already persisted at a different cwd (persisted: ${String(s.cwd)}, live: ${String(e.header.cwd)}) (id collision)`);this.assertVersion(s);const a=m(i,e.header.id);if(this.assertEventsSupported(s,a),!P(t,a))throw new Error(`session "${e.header.id}" already has a persisted log on disk that does not match this live session (id collision)`);n!==void 0&&await this.backend.commitRepair(s,n,[]),this.states.set(e.header.id,{meta:{...s},cursor:a.length,materialized:!0,owner:e});const c=t.slice(a.length);c.length>0&&await this.appendCore(e.header.id,c)}async flush(e){const t=this.initFor(e);t.writes.cancelAutomaticWait();try{await t.init}catch(r){throw t.writes.cancelAutomaticWait(),r}await t.writes.flush()}createWriteBehind(e,t){return new _({maxDelayMs:this.writeBatchMaxDelayMs,write:o(async r=>{await t(),await this.serialize(e.header.id,()=>this.appendLiveBatch(e.header.id,r))},"write"),reportBackgroundFailure:o(r=>{this.ctx.logger.warn(`${this.backend.name}: background write for session "${e.id}" failed (buffered events retained): ${String(r)}`)},"reportBackgroundFailure")})}async appendLiveBatch(e,t){const r=this.states.get(e)?.cursor??0,s=t.filter(i=>i.seq>=r);await this.appendCore(e,s)}},j=class extends z{static{o(this,"SessionPersistence")}constructor(e){super(e,"sessionPersistence")}readRaw(e,t){return t?.aborted===!0?Promise.reject(t.reason instanceof Error?t.reason:new Error("aborted")):Promise.reject(new Error("this session persistence backend does not expose raw artifacts"))}async prepare(e,t){t?.throwIfAborted();const r=await this.load(e);t?.throwIfAborted();const s=this.ctx.get("sessions");if(s===void 0)throw new Error("cannot prepare a session: SessionStore is not configured");return b.create(s.prepare(e,{seed:r.events.map(i=>structuredClone(i)),meta:structuredClone(r.meta),seedSource:"persistence"}))}};export{D as DEFAULT_PREPARED_SESSION_CACHE_SIZE,W as DEFAULT_WRITE_BATCH_MAX_DELAY_MS,v as MAX_WRITE_BATCH_DELAY_MS,H as PersistenceCoordinator,g as SessionFormatUnsupportedError,j as SessionPersistence,j as default,O as SessionPersistenceCorruptionError,B as SessionPersistenceRevision,x as sessionFormatVersionRefusal};
|
|
1
|
+
var q=Object.defineProperty;var c=(e,t)=>q(e,"name",{value:t,configurable:!0});import{Service as z}from"@deepseek-ai/cordis";import{KNOWN_SESSION_EVENT_TYPES as T,SESSION_FORMAT_VERSION as f,SessionPreparation as b,adoptSessionEvent as S,interruptedTurnClosers as E,snapshotJsonValue as k,snapshotSessionEvent as F}from"@deepseek-ai/dsh-session";import{MAX_TIMER_DELAY_MS as L}from"@deepseek-ai/dsh-timeout";function B(e){return e}c(B,"SessionPersistenceRevision");var N=class{static{c(this,"SessionPreparations")}capacity;entries=new Map;constructor(e){this.capacity=e}has(e){return this.entries.has(e)}async inspect(e,t,r){const s=this.entryFor(e,t),i=r===void 0?await s.result:await p(s.result,r),n=s.source??i;return this.entries.get(e)===s&&s.phase==="ready"&&this.touch(s),n}async reserve(e,t,r,s){const i=this.entryFor(e,t);for(await(s===void 0?i.result:p(i.result,s));this.entries.get(e)===i&&i.phase!=="ready";){const u=i.reservationSettled;if(u===void 0)throw new Error(`session "${e}" preparation lost its reservation waiter`);s===void 0?await u:await p(u,s)}if(this.entries.get(e)!==i)return;const n=i.source,a=Promise.withResolvers();i.phase="committing",i.reservationSettled=a.promise,i.settleReservation=a.resolve;let o;try{o=await r(n)}catch(u){throw this.remove(i),u}if(o===void 0){this.remove(i);return}i.source=o.source;try{s?.throwIfAborted()}catch(u){throw this.makeReady(i),u}if(this.entries.get(e)!==i)return;const d={entry:i,source:o.source,state:o.state};return i.phase="reserved",i.reservation=d,d}reservationFor(e){const t=this.entries.get(e.id);if(t!==void 0){if(t.phase==="reserved"&&t.source?.session===e&&t.reservation!==void 0)return t.reservation;throw new Error(`cannot publish session "${e.id}": persisted state already owns this identity`)}}attach(e){const{entry:t}=e;if(this.entries.get(t.id)!==t||t.reservation!==e)throw new Error(`session "${t.id}" preparation is no longer reserved`);this.remove(t)}discard(e){const{entry:t}=e;this.entries.get(t.id)!==t||t.reservation!==e||this.remove(t)}release(e,t){const{entry:r}=e;if(!(this.entries.get(r.id)!==r||r.reservation!==e||r.phase!=="reserved")){if(!t){this.remove(r);return}delete r.reservation,this.makeReady(r)}}invalidate(e){const t=this.entries.get(e);t!==void 0&&this.remove(t)}discardReady(e,t){const r=this.entries.get(e);return r===void 0||r.source!==t?"missing":r.phase!=="ready"?"retained":(this.remove(r),"discarded")}assertWritable(e){const t=this.entries.get(e)?.phase;if(t==="committing"||t==="reserved")throw new Error(`cannot append session "${e}" while its persisted preparation is reserved`)}takeReady(e){const t=this.entries.get(e);if(!(t===void 0||t.phase!=="ready"||t.source===void 0))return this.remove(t),t.source}entryFor(e,t){const r=this.entries.get(e);if(r!==void 0)return r;const s=Promise.withResolvers(),i={id:e,result:s.promise,phase:"loading"};this.entries.set(e,i);let n;try{n=t()}catch(a){return this.remove(i),s.reject(a),i}return n.then(a=>{this.entries.get(e)===i&&(i.source=a,this.makeReady(i)),s.resolve(a)},a=>{this.remove(i),s.reject(a)}),i}makeReady(e){if(this.entries.get(e.id)!==e)return;e.phase="ready";const t=e.settleReservation;delete e.reservationSettled,delete e.settleReservation,t?.(),this.touch(e)}remove(e){if(this.entries.get(e.id)!==e)return;this.entries.delete(e.id);const t=e.settleReservation;delete e.reservationSettled,delete e.settleReservation,t?.()}touch(e){this.entries.delete(e.id),this.entries.set(e.id,e);let t=0;for(const r of this.entries.values())r.phase==="ready"&&(t+=1);if(!(t<=this.capacity)){for(const[r,s]of this.entries)if(s.phase==="ready"){this.entries.delete(r);return}}}};function p(e,t,r=()=>!1){return new Promise((s,i)=>{let n=!1;const a=c(d=>{n||(n=!0,t.removeEventListener("abort",o),d())},"finish"),o=c(()=>{r()||a(()=>{try{t.throwIfAborted()}catch(d){$(i,d);return}i(new Error("queued observation abort event lacked an aborted signal"))})},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(d=>{a(()=>{s(d)})},d=>{a(()=>{$(i,d)})}),t.aborted&&o()})}c(p,"observeQueuedAbort");function $(e,t){e(t)}c($,"rejectObservation");var _=class{static{c(this,"SessionWriteBehind")}options;pending=[];timer;active;barrier;deadlineExpired=!1;automaticPaused=!1;constructor(e){this.options=e}get hasWork(){return this.pending.length>0||this.active!==void 0}enqueue(e){const t=this.pending.length===0;this.pending.push(structuredClone(e)),this.barrier===void 0&&(this.automaticPaused?(this.automaticPaused=!1,this.deadlineExpired=!1,this.armTimer()):t&&this.armTimer())}flush(){if(this.barrier!==void 0)return this.barrier;this.cancelTimer(),this.deadlineExpired=!1,this.automaticPaused=!1;const e=Promise.withResolvers();return this.barrier=e.promise,this.drainBarrier(e.resolve,e.reject),e.promise}cancelAutomaticWait(){this.cancelTimer(),this.deadlineExpired=!1}armTimer(){this.timer=setTimeout(()=>{this.onDeadline()},this.options.maxDelayMs)}cancelTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}onDeadline(){if(this.timer=void 0,this.active!==void 0){this.deadlineExpired=!0;return}this.startBackground()}startBackground(){this.startWrite(!0).then(()=>{this.continueAutomatic()},()=>{})}continueAutomatic(){this.barrier!==void 0||this.pending.length===0||this.deadlineExpired&&(this.deadlineExpired=!1,this.startBackground())}async drainBarrier(e,t){try{const r=this.active;for(r!==void 0&&(await Promise.allSettled([r]),this.automaticPaused=!1);this.pending.length>0;)await this.startWrite(!1)}catch(r){this.barrier=void 0,t(r);return}this.barrier=void 0,e()}startWrite(e){const t=this.pending.splice(0);this.cancelTimer(),this.deadlineExpired=!1;const r=Promise.resolve().then(()=>this.options.write(t)).catch(s=>{throw this.pending=t.concat(this.pending),this.cancelTimer(),this.deadlineExpired=!1,this.automaticPaused=!0,e&&this.options.reportBackgroundFailure(s),s}).finally(()=>{this.active=void 0});return this.active=r,r}};const D=5,W=200,v=L;var O=class extends Error{static{c(this,"SessionPersistenceCorruptionError")}constructor(e,t){super(e,t),this.name="SessionPersistenceCorruptionError"}},g=class extends Error{static{c(this,"SessionFormatUnsupportedError")}location;constructor(e,t){super(e),this.location=t,this.name="SessionFormatUnsupportedError"}};function x(e,t){return t>f?`session "${e}" uses log format v${t}, but this harness reads only v${f}: the log was written by a newer harness — upgrade the harness to open it`:`session "${e}" uses log format v${t}, older than the supported v${f}, and this build ships no upgrade path for it`}c(x,"sessionFormatVersionRefusal");async function V(e){const t=await Promise.allSettled([...e]),r=[];for(const s of t)s.status==="rejected"&&r.push(s.reason);return r}c(V,"settledErrors");function P(e,t){return t.length<=e.length&&t.every((r,s)=>{const i=e[s];return i!==void 0&&JSON.stringify(i)===JSON.stringify(r)})}c(P,"seedCoversPrefix");function y(e,t){const r="request/header-delta",s=e.find(o=>o.type===r);if(s!==void 0)throw new Error(`session "${t}" contains unsupported legacy request/header-delta event at seq ${s.seq}`);const i="mode/set",n=e.find(o=>o.type===i);if(n!==void 0)throw new Error(`session "${t}" contains unsupported legacy mode/set event at seq ${n.seq}`);const a=e.find(o=>o.type==="request/header"&&o.data.reason==="fallback");if(a!==void 0)throw new Error(`session "${t}" contains unsupported legacy request/header reason "fallback" at seq ${a.seq}`)}c(y,"assertSupportedEvents");function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}c(h,"asRecord");function l(e,t,r=[]){const s=[...t,...r];return Object.keys(e).every(i=>s.includes(i))&&t.every(i=>Object.hasOwn(e,i))}c(l,"hasOnlyKeys");function w(e,t){return`legacy-message:${e}:${t}`}c(w,"legacyMessageId");function J(e){const t=h(e.surfaceOp);return t?.op==="replace"&&typeof t.start=="number"?t.start:void 0}c(J,"replacementStart");function U(e){const t=h(e.data);if(e.type==="steering/message")return!0;if(t===void 0)return!1;switch(e.type){case"user/message":return!Object.hasOwn(t,"id")&&Object.hasOwn(t,"content");case"assistant/message":return!Object.hasOwn(t,"message")&&Object.hasOwn(t,"content");case"tool/result":return!Object.hasOwn(t,"message")&&Object.hasOwn(t,"callId");default:return!1}}c(U,"needsLegacyPrefix");function I(e,t){if(e.type!=="steering/message")return e;const r=h(e.data);if(r===void 0)throw new Error(`session "${t}" contains malformed pre-react-loop steering/message at seq ${e.seq}`);const s=h(r.message);if(s!==void 0&&Number.isSafeInteger(r.turn)&&l(r,["turn","message"]))return{...e,type:"user/message",data:s};if(!Number.isSafeInteger(r.turn)||!l(r,["turn","content","source"]))throw new Error(`session "${t}" contains malformed pre-react-loop steering/message at seq ${e.seq}`);const{turn:i,...n}=r;return{...e,type:"user/message",data:{...n,id:w(t,e.seq),role:"user"}}}c(I,"migrateLegacySteeringEvent");function M(e,t){if(e.type!=="turn/start")return e;const r=h(e.data);if(r===void 0||!Object.hasOwn(r,"trigger"))return e;const s=h(r.trigger);if(!Number.isSafeInteger(r.turn)||r.turn<1||!l(r,["turn","trigger"])||s===void 0||typeof s.kind!="string"||s.kind.length===0)throw new Error(`session "${t}" contains malformed pre-react-loop turn/start at seq ${e.seq}`);return{...e,data:{turn:r.turn}}}c(M,"migrateLegacyTurnStartEvent");function C(e,t){if(e.type!=="turn/end")return e;const r=h(e.data);if(r===void 0)return e;const s=c(()=>{throw new Error(`session "${t}" contains malformed pre-react-loop turn/end at seq ${e.seq}`)},"malformed"),i=h(r.reason);if(!Number.isSafeInteger(r.turn)||r.turn<1||!l(r,["turn","reason"])||i===void 0||typeof i.kind!="string")return s();let n;switch(i.kind){case"completed":case"blocked":case"max-tokens":case"interrupted":return l(i,["kind"])?e:s();case"aborted":if(Object.hasOwn(i,"reason"))return e;if(!l(i,["kind"]))return s();n={kind:"aborted",reason:{kind:"legacy"}};break;case"disposed":if(!l(i,["kind"]))return s();n={kind:"aborted",reason:{kind:"disposed"}};break;case"error":{if(Object.hasOwn(i,"error"))return e;if(!Number.isSafeInteger(i.step)||i.step<0)return s();const a=h(i.failure);if(a!==void 0&&l(i,["kind","step","failure"])&&l(a,["message","code"],["status","providerRetryAfterMs","requestId"])&&typeof a.message=="string"&&typeof a.code=="string"&&(a.status===void 0||typeof a.status=="number")&&(a.providerRetryAfterMs===void 0||typeof a.providerRetryAfterMs=="number")&&(a.requestId===void 0||typeof a.requestId=="string")){n={kind:"error",error:a};break}if(!l(i,i.code===void 0?["kind","step","message"]:["kind","step","message","code"])||typeof i.message!="string"||i.code!==void 0&&typeof i.code!="string")return s();n={kind:"error",error:{message:i.message,code:typeof i.code=="string"?i.code:"UNKNOWN"}};break}default:return e}return{...e,data:{...r,reason:n}}}c(C,"migrateLegacyTurnEndEvent");function A(e,t,r){const s=h(e.data);if(s===void 0)return e;switch(e.type){case"user/message":return Object.hasOwn(s,"id")||Object.hasOwn(s,"role")||Object.hasOwn(s,"message")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"source")?e:{...e,data:{...s,id:w(t,e.seq),role:"user"}};case"assistant/message":{if(Object.hasOwn(s,"message")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"provenance"))return e;const{content:i,provenance:n,...a}=s;return{...e,data:{...a,message:{id:w(t,e.seq),role:"assistant",content:i,source:{...h(n),kind:"model"}}}}}case"tool/result":{if(Object.hasOwn(s,"message")||!Object.hasOwn(s,"callId")||!Object.hasOwn(s,"content")||!Object.hasOwn(s,"isError"))return e;const{callId:i,content:n,isError:a,...o}=s,d=J(e);return{...e,data:{...o,message:{id:d===void 0?w(t,e.seq):r.get(d),role:"user",content:[{type:"tool-result",toolCallId:i,content:n,isError:a}],source:{kind:"tool",callId:i}}}}}default:return e}}c(A,"migrateLegacyMessageEvent");function R(e){const t=h(e.data),r=e.type==="user/message"?t:h(t?.message);return typeof r?.id=="string"?r.id:void 0}c(R,"eventMessageId");function m(e,t){y(e,t);const r=new Map;return e.map(s=>{const i=I(C(M(s,t),t),t),n=F(A(i,t,r)),a=R(n);return a!==void 0&&r.set(n.seq,a),n})}c(m,"snapshotStoredEvents");function Y(e,t){y(e,t);const r=new Map;for(const[s,i]of e.entries()){const n=I(C(M(i,t),t),t),a=S(A(n,t,r));e[s]=a;const o=R(a);o!==void 0&&r.set(a.seq,o)}return e}c(Y,"adoptStoredEvents");var H=class{static{c(this,"PersistenceCoordinator")}ctx;backend;states=new Map;live=new Map;retirements=new Map;preparations;chains=new Map;writeBatchMaxDelayMs;constructor(e,t,r={preparedSessionCacheSize:5,writeBatchMaxDelayMs:200}){if(this.ctx=e,this.backend=t,!Number.isSafeInteger(r.preparedSessionCacheSize)||r.preparedSessionCacheSize<1)throw new TypeError("preparedSessionCacheSize must be a positive safe integer");if(!Number.isSafeInteger(r.writeBatchMaxDelayMs)||r.writeBatchMaxDelayMs<1||r.writeBatchMaxDelayMs>v)throw new TypeError(`writeBatchMaxDelayMs must be an integer between 1 and ${v}`);this.writeBatchMaxDelayMs=r.writeBatchMaxDelayMs,this.preparations=new N(r.preparedSessionCacheSize),this.installWritePath()}create(e){const t=k(e);return t===void 0?Promise.reject(new TypeError("session metadata must be losslessly JSON-serializable")):!Number.isSafeInteger(t.createdAt)||t.createdAt<0?Promise.reject(new TypeError("session metadata createdAt must be a non-negative safe integer")):this.serialize(t.id,()=>this.createCore(t))}async createCore(e){if(this.states.has(e.id)||this.preparations.has(e.id))throw new Error(`session "${e.id}" already exists in this backend`);if(await this.backend.loadStored(e.id)!==void 0)throw new Error(`session "${e.id}" already has a persisted log on disk; load/resume it instead of creating`);this.states.set(e.id,{meta:e,cursor:0,materialized:!1})}async append(e,t){const r=k(t);if(r===void 0)throw new TypeError("session event batch is not losslessly JSON-serializable because it contains non-JSON-serializable data");return this.serialize(e,()=>this.appendCore(e,r))}async appendCore(e,t){if(y(t,e),t.length===0)return;this.preparations.assertWritable(e);let r=this.states.get(e);r===void 0&&(r=await this.adopt(e));for(const[s,i]of t.entries())if(i.seq!==r.cursor+s)throw new Error(`append seq mismatch for "${e}": expected ${r.cursor+s} at index ${s}, got ${i.seq}`);await this.backend.appendBatch(r.meta,t,r.materialized),r.materialized=!0,r.cursor+=t.length,this.preparations.invalidate(e)}async prepare(e,t){for(;;){if(await this.waitForRetirement(e,t),this.ctx.sessions.get(e)!==void 0)throw new Error(`cannot prepare session "${e}" while it is live`);const r=await this.preparations.reserve(e,()=>this.serialize(e,()=>this.prepareCore(e)),s=>this.serialize(e,()=>this.commitPrepared(s),t),t);if(r!==void 0){if(this.ctx.sessions.get(e)!==void 0)throw this.preparations.release(r,!1),new Error(`cannot prepare session "${e}" while it is live`);return b.create(r.source.session,{release:c(()=>{this.preparations.release(r,r.state.owner===void 0&&r.source.session.events.length===r.source.sessionLength)},"release")})}}}async load(e){for(;;){await this.waitForRetirement(e);const t=this.ctx.sessions.get(e);if(t!==void 0)return this.loadLiveSnapshot(t);const r=await this.preparations.reserve(e,()=>this.serialize(e,()=>this.prepareCore(e)),i=>this.serialize(e,()=>this.commitPrepared(i)));if(r===void 0)continue;const s=this.ctx.sessions.get(e);return s!==void 0?(this.preparations.discard(r),this.loadLiveSnapshot(s)):(this.preparations.discard(r),r.source.inspection)}}async inspect(e,t){for(;;){t?.throwIfAborted(),this.retirements.has(e)&&await this.waitForRetirement(e,t);const r=this.ctx.sessions.get(e);if(r!==void 0)return this.inspectLive(r);try{const s=await this.preparations.inspect(e,()=>this.serialize(e,()=>this.prepareCore(e)),t),i=this.ctx.sessions.get(e);if(i!==void 0)return this.inspectLive(i);const n=await this.serialize(e,()=>this.isPreparedSourceCurrent(s,t),t),a=this.ctx.sessions.get(e);if(a!==void 0)return this.inspectLive(a);if(n||this.preparations.discardReady(e,s)==="retained")return s.inspection}catch(s){t?.throwIfAborted();const i=this.ctx.sessions.get(e);if(i!==void 0)return this.inspectLive(i);throw s}}}readFrom(e,t,r){if(!Number.isSafeInteger(t)||t<0)return Promise.reject(new TypeError(`readFrom fromSeq must be a non-negative safe integer, got ${String(t)}`));const s=Promise.resolve(this.retirements.get(e));return(r===void 0?s:p(s,r,()=>!1)).then(()=>this.serialize(e,()=>this.readFromCore(e,t,r),r))}async readFromCore(e,t,r){if(r?.throwIfAborted(),this.backend.loadStoredFrom!==void 0){let i;try{i=await this.backend.loadStoredFrom(e,t,r)}catch(a){throw r?.aborted&&r.throwIfAborted(),a}if(r?.throwIfAborted(),i===void 0)throw new Error(`session "${e}" not found`);if(this.assertStoredId(e,i.meta),this.assertVersion(i.meta),i.events.some(U)){const a=await this.readStoredPrefix(e,r);return{meta:a.meta,events:a.events.filter(o=>o.seq>=t)}}const n=m(i.events,e);return this.assertEventsSupported(i.meta,n),{meta:structuredClone(i.meta),events:n}}const s=await this.readStoredPrefix(e,r);return{meta:s.meta,events:s.events.slice(t)}}async readStoredPrefix(e,t){t?.throwIfAborted();const r=await this.backend.loadStored(e,t);if(t?.throwIfAborted(),r===void 0)throw new Error(`session "${e}" not found`);this.assertStoredId(e,r.meta),this.assertVersion(r.meta);const s=m(r.events,e);return this.assertEventsSupported(r.meta,s),{meta:structuredClone(r.meta),events:s}}async prepareCore(e){const t=await this.backend.loadStored(e);if(t===void 0)throw new Error(`session "${e}" not found`);try{const{meta:r,events:s,revision:i,tornMarker:n}=t;this.assertStoredId(e,r),this.assertVersion(r);const a=Y(s,e);this.assertEventsSupported(r,a);const o=E(a).map(S),d=[...a,...o],u=this.ctx.sessions.prepare(e,{seed:d,meta:r,seedSource:"persistence"});return{inspection:Object.freeze({meta:u.header,events:Object.freeze(d)}),session:u,revision:i,sessionLength:u.events.length,tornMarker:n,closers:o}}catch(r){throw r instanceof g?r:new O(`stored session "${e}" failed validation: ${String(r)}`,{cause:r})}}async commitPrepared(e){const t=e.inspection.meta.id,r=e.inspection.events.length,s=this.states.get(t);if(s?.owner!==void 0)throw new Error(`session "${t}" already has a live persistence owner`);if(!await this.isPreparedSourceCurrent(e))return;if(e.tornMarker!==void 0||e.closers.length>0){await this.backend.commitRepair(e.inspection.meta,e.tornMarker,e.closers);return}const i=s??{meta:e.inspection.meta,cursor:r,materialized:!0};return i.meta=e.inspection.meta,i.cursor=r,i.materialized=!0,this.states.set(t,i),{source:e,state:i}}async isPreparedSourceCurrent(e,t){return await this.backend.readStoredRevision(e.inspection.meta.id,t)===e.revision}async loadLiveSnapshot(e){const t=e.events;await this.flush(e);const r=this.states.get(e.id);if(r===void 0)throw new Error(`session "${e.id}" lost persistence state during load`);if(t.length===0)throw new Error(`session "${e.id}" not found`);if(E(t).length>0)throw new Error(`cannot load session "${e.id}" while its live turn is open; use the live Session or wait for the turn to close`);return Object.freeze({meta:r.meta,events:t})}inspectLive(e){return Object.freeze({meta:e.header,events:e.events})}waitForRetirement(e,t){const r=Promise.resolve(this.retirements.get(e));return t===void 0?r:p(r,t,()=>!1)}serialize(e,t,r){const s=this.chains.get(e)??Promise.resolve();let i=!1;const n=c(()=>(r?.throwIfAborted(),i=!0,t()),"run"),a=s.then(n,n),o=a.then(()=>{},()=>{});return this.chains.set(e,o),o.then(()=>{this.chains.get(e)===o&&this.chains.delete(e)}),r===void 0?a:p(a,r,()=>i)}async adopt(e){for(;;){const t=this.preparations.takeReady(e)??await this.prepareCore(e),r=await this.commitPrepared(t);if(r!==void 0)return r.state}}assertVersion(e){if(e.version!==f)throw this.unsupported(e,x(e.id,e.version))}assertEventsSupported(e,t){for(const r of t)if(!(T.has(r.type)||r.ignorable===!0))throw this.unsupported(e,`session "${e.id}" contains event type "${r.type}" (seq ${r.seq}) unknown to this harness and not marked ignorable; refusing to interpret the log — it was likely written by a newer harness`)}unsupported(e,t){const r=this.backend.locate?.(e);return new g(r===void 0?t:`${t} (raw log: ${r.path})`,r)}assertStoredId(e,t){if(t.id!==e)throw new Error(`stored session identity mismatch: requested "${e}", header contains "${t.id}"`)}installWritePath(){const e=this.ctx;e.effect(()=>async()=>{let t;try{const r=await V([...this.live.keys()].map(s=>this.flush(s)));for(;this.chains.size>0;)await Promise.allSettled([...this.chains.values()]);if(r.length>0)throw new AggregateError(r,`${this.backend.name} dispose failed`)}catch(r){throw t=r,r}finally{try{await this.backend.close?.()}catch(r){if(t===void 0)throw r}}},`${this.backend.name} write path`),e.on("session/created",t=>{this.initFor(t)}),e.on("session/event",(t,r)=>{this.initFor(t).writes.enqueue(r)}),e.on("session/flush",t=>this.flush(t)),e.on("session/disposed",t=>{this.retire(t)});for(const t of e.sessions.list())this.initFor(t)}retire(e){if(!this.live.has(e))return;const t=this.retireCore(e);this.retirements.set(e.id,t);const r=c(()=>{this.retirements.get(e.id)===t&&this.retirements.delete(e.id)},"forget");t.then(r,r),t.catch(s=>{this.ctx.logger.warn(`${this.backend.name}: session "${e.id}" retirement failed: ${String(s)}`)})}async retireCore(e){await this.flush(e);const t=e.header.id;await this.serialize(t,()=>{this.live.delete(e),this.states.get(t)?.owner===e&&this.states.delete(t)})}initFor(e){const t=this.live.get(e);if(t)return t;const r=this.preparations.reservationFor(e);if(r!==void 0){const n=this.attachPrepared(e,r);return this.live.set(e,n),n}const s=e.events.map(n=>structuredClone(n)),i={init:Promise.resolve(),writes:this.createWriteBehind(e,()=>i.init)};return this.live.set(e,i),i.init=this.serialize(e.header.id,()=>this.onCreated(e,s)),i.init.catch(()=>{}),i}attachPrepared(e,t){const{source:r,state:s}=t;if(r.session!==e||s.owner!==void 0||s.cursor!==r.inspection.events.length||e.firstLiveSeq!==s.cursor)throw new Error(`session "${e.id}" preparation no longer matches its persistence state`);const i=e.events.slice(s.cursor).map(a=>structuredClone(a));this.preparations.attach(t),s.owner=e;const n={init:Promise.resolve(),writes:this.createWriteBehind(e,()=>n.init)};return i.length>0&&(n.init=this.serialize(e.id,()=>this.appendCore(e.id,i)),n.init.catch(()=>{})),n}async seedMatchesPersisted(e,t,r){if(r===0)return!0;const s=await this.backend.loadStored(e);return s===void 0?!1:(this.assertStoredId(e,s.meta),P(t,m(s.events,e).slice(0,r)))}async onCreated(e,t){const r=e.header.id,s=this.states.get(r);if(s!==void 0){if(s.owner===e)return;if(s.owner===void 0){if(s.meta.cwd!==e.header.cwd)throw new Error(`session "${r}" is already persisted at a different cwd (persisted: ${String(s.meta.cwd)}, live: ${String(e.header.cwd)}) (id collision)`);if(!await this.seedMatchesPersisted(r,t,s.cursor))throw new Error(`session "${r}" is already persisted with ${s.cursor} event(s) that do not match this live session (id collision)`);s.owner=e;const d=t.slice(s.cursor);d.length>0&&await this.appendCore(r,d);return}const o=this.live.get(s.owner);if(!s.materialized&&!o?.writes.hasWork)this.states.delete(r);else throw new Error(`session "${r}" is already bound to a different live session in this backend (id collision)`)}const i=await this.backend.loadStored(r);if(i!==void 0){await this.adoptLivePrefix(e,t,i);return}const n={...e.header};await this.createCore(n);const a=this.states.get(r);a!==void 0&&(a.owner=e),t.length>0&&await this.appendCore(r,t)}async adoptLivePrefix(e,t,r){const{meta:s,events:i,tornMarker:n}=r;if(this.assertStoredId(e.header.id,s),s.cwd!==e.header.cwd)throw new Error(`session "${e.header.id}" is already persisted at a different cwd (persisted: ${String(s.cwd)}, live: ${String(e.header.cwd)}) (id collision)`);this.assertVersion(s);const a=m(i,e.header.id);if(this.assertEventsSupported(s,a),!P(t,a))throw new Error(`session "${e.header.id}" already has a persisted log on disk that does not match this live session (id collision)`);n!==void 0&&await this.backend.commitRepair(s,n,[]),this.states.set(e.header.id,{meta:{...s},cursor:a.length,materialized:!0,owner:e});const o=t.slice(a.length);o.length>0&&await this.appendCore(e.header.id,o)}async flush(e){const t=this.initFor(e);t.writes.cancelAutomaticWait();try{await t.init}catch(r){throw t.writes.cancelAutomaticWait(),r}await t.writes.flush()}createWriteBehind(e,t){return new _({maxDelayMs:this.writeBatchMaxDelayMs,write:c(async r=>{await t(),await this.serialize(e.header.id,()=>this.appendLiveBatch(e.header.id,r))},"write"),reportBackgroundFailure:c(r=>{this.ctx.logger.warn(`${this.backend.name}: background write for session "${e.id}" failed (buffered events retained): ${String(r)}`)},"reportBackgroundFailure")})}async appendLiveBatch(e,t){const r=this.states.get(e)?.cursor??0,s=t.filter(i=>i.seq>=r);await this.appendCore(e,s)}},j=class extends z{static{c(this,"SessionPersistence")}constructor(e){super(e,"sessionPersistence")}readRaw(e,t){return t?.aborted===!0?Promise.reject(t.reason instanceof Error?t.reason:new Error("aborted")):Promise.reject(new Error("this session persistence backend does not expose raw artifacts"))}async prepare(e,t){t?.throwIfAborted();const r=await this.load(e);t?.throwIfAborted();const s=this.ctx.get("sessions");if(s===void 0)throw new Error("cannot prepare a session: SessionStore is not configured");return b.create(s.prepare(e,{seed:r.events.map(i=>structuredClone(i)),meta:structuredClone(r.meta),seedSource:"persistence"}))}};export{D as DEFAULT_PREPARED_SESSION_CACHE_SIZE,W as DEFAULT_WRITE_BATCH_MAX_DELAY_MS,v as MAX_WRITE_BATCH_DELAY_MS,H as PersistenceCoordinator,g as SessionFormatUnsupportedError,j as SessionPersistence,j as default,O as SessionPersistenceCorruptionError,B as SessionPersistenceRevision,x as sessionFormatVersionRefusal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-persistence","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-persistence","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-brand":"^0.0.12","@deepseek-ai/dsh-timeout":"^0.0.12","@deepseek-ai/cordis":"^4.0.1"}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var ut=Object.defineProperty;var a=(t,e)=>ut(t,"name",{value:e,configurable:!0});import m from"@deepseek-ai/schemastery";import{readdirSync as wt}from"node:fs";import{link as lt,mkdir as _,mkdtemp as pt,open as y,readFile as mt,readdir as $,realpath as k,rm as S,stat as A,truncate as yt}from"node:fs/promises";import{dirname as P,join as f,parse as Z,resolve as j,toNamespacedPath as I}from"node:path";import{performance as F}from"node:perf_hooks";import{scheduler as Et}from"node:timers/promises";import{randomBytes as bt}from"node:crypto";import{DEFAULT_PREPARED_SESSION_CACHE_SIZE as z,DEFAULT_WRITE_BATCH_MAX_DELAY_MS as M,MAX_WRITE_BATCH_DELAY_MS as At,PersistenceCoordinator as gt,SessionFormatUnsupportedError as L,SessionPersistence as St,SessionPersistenceRevision as It,sessionFormatVersionRefusal as vt}from"@deepseek-ai/dsh-session-persistence";import{SESSION_FORMAT_VERSION as Dt,decodeStorageRecord as _t,packChunkRuns as Ft}from"@deepseek-ai/dsh-session";import{constants as H,createZstdDecompress as Lt,zstdCompress as xt,zstdDecompress as Ot,zstdDecompressSync as Rt}from"node:zlib";import{promisify as U}from"node:util";import{constants as W}from"node:buffer";function E(t){return t==="zstd"?".jsonl.zstd":".jsonl"}a(E,"logSuffix");function Nt(t){return{type:"session",version:t.version,id:t.id,createdAt:t.createdAt,...t.cwd!==void 0?{cwd:t.cwd}:{},...t.parentSession!==void 0?{parentSession:t.parentSession}:{},...t.seedLength!==void 0?{seedLength:t.seedLength}:{},...t.origin!==void 0?{origin:t.origin}:{},delegationDepth:t.delegationDepth??0,...t.agentPreset!==void 0?{agentPreset:t.agentPreset}:{}}}a(Nt,"toHeaderLine");function J(t){if(Object.hasOwn(t,"sandboxMode")||Object.hasOwn(t,"approvalPolicy"))throw new Error("session header uses retired policy baseline fields");return{version:t.version,id:t.id,createdAt:t.createdAt,...t.cwd!==void 0?{cwd:t.cwd}:{},...t.parentSession!==void 0?{parentSession:t.parentSession}:{},...t.seedLength!==void 0?{seedLength:t.seedLength}:{},...t.origin!==void 0?{origin:t.origin}:{},delegationDepth:t.delegationDepth,...t.agentPreset!==void 0?{agentPreset:t.agentPreset}:{}}}a(J,"fromHeaderLine");function K(t){return typeof t=="object"&&t!==null&&t.type==="session"&&typeof t.version=="number"&&typeof t.id=="string"&&typeof t.createdAt=="number"&&Number.isSafeInteger(t.createdAt)&&t.createdAt>=0&&!Object.is(t.createdAt,-0)&&typeof t.delegationDepth=="number"&&Number.isSafeInteger(t.delegationDepth)&&t.delegationDepth>=0&&!Object.is(t.delegationDepth,-0)&&(t.origin===void 0||t.origin==="subagent")&&(t.agentPreset===void 0||typeof t.agentPreset=="string")}a(K,"isHeaderLine");function x(t){if(t.length===0)throw new Error("cannot encode an empty path segment");if(t===".")return"~002E";if(t==="..")return"~002E~002E";let e="";for(let r=0;r<t.length;r++){const o=t.charCodeAt(r),s=String.fromCharCode(o);s!=="~"&&/^[A-Za-z0-9._-]$/.test(s)?e+=s:e+="~"+o.toString(16).toUpperCase().padStart(4,"0")}return e}a(x,"encodeSegment");function Ct(t){if(t.length===0)throw new Error("cannot encode an empty project path");let e="",r=!1;for(let o=0;o<t.length;o++){const s=t.charCodeAt(o),i=String.fromCharCode(s);i==="/"||i==="\\"||i===":"?(r||(e+="-"),r=!0):i!=="~"&&/^[A-Za-z0-9._-]$/.test(i)?(e+=i,r=!1):(e+="~"+s.toString(16).toUpperCase().padStart(4,"0"),r=!1)}return`--${(e.replace(/^-+/,"")||"root").slice(0,251)}--`}a(Ct,"projectKey");function V(t,e){return e===void 0?f(t,"_no-cwd"):f(t,Ct(e))}a(V,"projectDir");function X(t,e,r){return f(V(t,e),x(r))}a(X,"sessionDir");function g(t,e,r,o){return f(X(t,e,r),`session${E(o)}`)}a(g,"logPath");function q(t,e){return(e?Ft(t):t).map(r=>JSON.stringify(r)).join(`
|
|
2
|
-
`)}a(q,"eventLines");function Bt(t){if(typeof t!="object"||t===null)return;const{version:e,id:r}=t;if(!(typeof e!="number"||e===Dt))throw new L(vt(typeof r=="string"?r:String(r),e))}a(Bt,"refuseForeignFormatVersion");function Tt(t){if(t.length===0||t.at(-1)!==10||t.indexOf(10)!==t.length-1)throw new Error("empty or header-less session log");let e;try{e=JSON.parse(t.subarray(0,-1).toString("utf8"))}catch{throw new Error("corrupt session log: header line is not valid JSON")}if(Bt(e),!K(e))throw new Error("corrupt session log: first line is not a session header");return J(e)}a(Tt,"parseHeaderRecord");var G=class{static{a(this,"SessionLogScanner")}meta;events=[];fragments=[];fragmentBytes=0;inputBytes;committedBytes;eventLine=0;issue;finished=!1;constructor(t){this.meta=Tt(t),this.inputBytes=t.length,this.committedBytes=t.length}write(t){if(this.finished)throw new Error("cannot write to a finished session log scanner");const e=this.inputBytes;this.inputBytes+=t.length;let r=0;for(let o=t.indexOf(10);o!==-1;o=t.indexOf(10,r)){const s=t.subarray(r,o);let i=s;this.fragments.length>0&&(s.length>0&&this.fragments.push(s),i=Buffer.concat(this.fragments,this.fragmentBytes+s.length),this.fragments=[],this.fragmentBytes=0),this.consumeEventLine(i,e+o+1),r=o+1}if(r<t.length){const o=Buffer.from(t.subarray(r));this.fragments.push(o),this.fragmentBytes+=o.length}}checkpoint(){return{inputBytes:this.inputBytes,committedBytes:this.committedBytes,eventCount:this.events.length}}finish(){return this.finished=!0,{meta:this.meta,events:this.events,committedBytes:this.committedBytes}}consumeEventLine(t,e){this.eventLine+=1;let r;try{r=_t(JSON.parse(t.toString("utf8")))}catch{this.issue??=new Error(`corrupt session log: unparsable committed event at line ${this.eventLine}`);return}if(this.issue!==void 0){if(r.some(s=>s.type==="turn/end"))throw this.issue;return}const o=this.events.length;for(const s of r){if(s.seq!==this.events.length){const i=this.events.length;if(this.events.length=o,this.issue=new Error(`corrupt session log: seq gap in committed region at line ${this.eventLine} (expected ${i}, got ${s.seq})`),r.some(n=>n.type==="turn/end"))throw this.issue;return}this.events.push(s)}this.committedBytes=e}};function $t(t){const e=t.indexOf(10);if(e===-1)throw new Error("empty or header-less session log");const r=new G(t.subarray(0,e+1));return r.write(t.subarray(e+1)),r.finish()}a($t,"scanLog");function Y(t){let e;try{e=JSON.parse(t)}catch{return}if(K(e))return J(e)}a(Y,"parseHeaderMeta");const Q=1024*1024;function kt(t){const e=t,r=e._handle,o=Reflect.ownKeys(t).find(s=>typeof s=="symbol"&&s.description==="kError");if(!(typeof r!="object"||r===null||typeof r.writeSync!="function"||!(e._writeState instanceof Uint32Array)||e._writeState.length<2||typeof e._defaultFlushFlag!="number"||o===void 0||e[o]!==null))return{stream:t,errorKey:o}}a(kt,"privateZstdStream");var Pt=class dt{static{a(this,"NodePrivateZstdFrameDecoder")}stream;errorKey;output=Buffer.allocUnsafe(Q);decoderError;started=!1;closed=!1;constructor(e,r){this.stream=e,this.errorKey=r,this.stream.on("error",o=>{this.decoderError??=o})}static create(){const e=Lt({chunkSize:Q}),r=kt(e);if(r!==void 0)return new dt(r.stream,r.errorKey);e.close()}*decode(e,r){if(this.started)throw new Error("Zstandard frame decoder was already started");if(this.closed)throw new Error("cannot start a closed Zstandard frame decoder");this.started=!0;try{for(const o of r)try{yield this.decodeFrame(e.subarray(o.start,o.end))}catch(s){throw new Error(`corrupt Zstandard session log: frame at byte ${o.start} failed validation`,{cause:s})}}finally{this.close()}}decodeFrame(e){const r=this.stream._handle;if(this.closed||r===null)throw new Error("cannot decode with a closed Zstandard frame decoder");let o=0,s=e.length,i=0;const n=[];for(;;){if(r.writeSync(this.stream._defaultFlushFlag,e,o,s,this.output,0,this.output.length),this.decoderError!==void 0)throw this.decoderError;const c=this.stream[this.errorKey];if(c!==null)throw c instanceof Error?c:new Error("Zstandard decoder exposed a non-Error internal failure");const d=this.stream._writeState[0],h=this.stream._writeState[1],u=s-h,l=this.output.length-d;if(l>0&&(i+=l,i>W.MAX_LENGTH))throw new Error(`Zstandard frame output exceeds ${W.MAX_LENGTH} bytes`);if(d!==0){if(h!==0)throw new Error("Zstandard frame decoder left trailing input");const p=this.output.subarray(0,l);if(n.length===0)return p;l>0&&n.push(Buffer.from(p));const w=n[0];return n.length===1?w:Buffer.concat(n,i)}n.push(Buffer.from(this.output)),o+=u,s=h}}close(){this.closed||(this.closed=!0,this.stream.close())}},Zt=class{static{a(this,"PublicZstdFrameDecoder")}started=!1;closed=!1;*decode(t,e){if(this.started)throw new Error("Zstandard frame decoder was already started");if(this.closed)throw new Error("cannot start a closed Zstandard frame decoder");this.started=!0;try{for(const{start:r,end:o}of e){let s;try{s=Rt(t.subarray(r,o))}catch(i){throw new Error(`corrupt Zstandard session log: frame at byte ${r} failed validation`,{cause:i})}yield s}}finally{this.close()}}close(){this.closed=!0}};const jt=4247762216,zt=U(xt),tt=U(Ot),Mt={params:{[H.ZSTD_c_checksumFlag]:1}},Ht={finishFlush:H.ZSTD_e_flush};function O(t,e=Number.POSITIVE_INFINITY){const r=[];let o=0;for(;o<t.length;){const s=o;if(t.length-o<4)return{frames:r,tornStart:s};if(t.readUInt32LE(o)!==jt)throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${o}`);if(o+=4,o===t.length)return{frames:r,tornStart:s};const i=t.readUInt8(o);if(o+=1,(i&24)!==0)throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${o-1}`);const n=i>>>6,c=(i&32)!==0,d=(i&4)!==0,h=i&3,u=h===3?4:h,l=n===0?c?1:0:1<<n,p=(c?0:1)+u+l;if(t.length-o<p)return{frames:r,tornStart:s};for(o+=p;;){if(t.length-o<3)return{frames:r,tornStart:s};const w=t.readUIntLE(o,3);o+=3;const ht=(w&1)!==0,B=w>>>1&3,ft=w>>>3;if(B===3)throw new Error(`corrupt Zstandard session log: reserved block type at byte ${o-3}`);const T=B===1?1:ft;if(t.length-o<T)return{frames:r,tornStart:s};if(o+=T,ht)break}if(d){if(t.length-o<4)return{frames:r,tornStart:s};o+=4}if(r.push({start:s,end:o}),r.length===e)return{frames:r}}return{frames:r}}a(O,"scanZstdFrames");async function R(t){return zt(t,Mt)}a(R,"compressZstdFrame");async function Ut(t){return tt(t)}a(Ut,"decompressZstdFrame");function et(){return Pt.create()??new Zt}a(et,"createZstdFrameDecoder");async function Wt(t){return tt(t,Ht)}a(Wt,"decompressZstdPrefix");const Jt=8,Kt=2,Vt=3,Xt=5,qt=17,Gt=80,Yt=123,Qt=183;let v;async function te(){if(v!==void 0)return v;const t=(await import("koffi")).default.load("kernel32.dll");return v={moveFileExW:t.func("__stdcall","MoveFileExW","int",["str16","str16","uint"]),getLastError:t.func("__stdcall","GetLastError","uint",[])},v}a(te,"win32");function ee(t){switch(t){case Kt:case Vt:return"ENOENT";case Xt:return"EACCES";case qt:return"EXDEV";case Gt:case Qt:return"EEXIST";case Yt:return"EINVAL";default:return"EIO"}}a(ee,"errnoCode");function re(t,e,r,o){const s=ee(e),i=new Error(`${t} ${s} (Win32 ${e}): ${r} -> ${o}`);return i.code=s,i.errno=e,i.syscall=t,i.path=r,i.dest=o,i.win32Code=e,i}a(re,"win32Error");function oe(t){return t?.code==="ENOENT"}a(oe,"isENOENT$1");function se(t){return t?.code==="EEXIST"}a(se,"isEEXIST");async function N(t){try{if((await A(t===Z(t).root?t:I(t))).isDirectory())return!0;const e=new Error(`path exists but is not a directory: ${t}`);throw e.code="ENOTDIR",e.path=t,e}catch(e){if(oe(e))return!1;throw e}}a(N,"assertDirectory");async function rt(t,e){const r=await te();if(r.moveFileExW(I(t),I(e),Jt)===0)throw re("MoveFileExW",r.getLastError(),t,e)}a(rt,"publishNewFileWin32");async function C(t){const e=j(t),r=Z(e).root;await N(r);const o=e.slice(r.length).split(/[\\/]+/).filter(i=>i.length>0);let s=r;for(const i of o){const n=f(s,i);await N(n)||await ie(s,n),s=n}}a(C,"ensureDurableDirectoryWin32");async function ie(t,e){const r=await pt(I(f(t,".dsh-mkdir-")));try{await rt(r,e)}catch(o){if(await S(r,{recursive:!0,force:!0}),se(o)&&await N(e))return;throw o}}a(ie,"createLeafDirectoryWin32");const ot=!0,st="zstd",it=500;function nt(t){if(t.length===0||t.indexOf(10)!==t.length-1)throw new Error("corrupt Zstandard session log: first frame is not exactly one header line")}a(nt,"assertZstdHeaderFrame");const at=m.union([m.const("zstd"),m.const("none")]).default(st);function D(t){return It([t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":"))}a(D,"fileRevision");function b(t){return t?.code==="ENOENT"}a(b,"isENOENT");var ct=class extends St{static{a(this,"JsonlSessionPersistence")}config;supportsRawArtifacts=!0;static inject=["sessions"];static Config=m.object({root:m.string().required(),packChunks:m.boolean().default(ot),compression:at,preparedSessionCacheSize:m.number().step(1).min(1).default(z),writeBatchMaxDelayMs:m.number().step(1).min(1).max(At).default(M)});name="session-persistence-jsonl";root;packChunks;compression;coordinator;rootEncodingCheck;constructor(t,e){super(t),this.config=e,this.root=j(e.root);const r=e.preparedSessionCacheSize??z,o=e.writeBatchMaxDelayMs??M;this.packChunks=e.packChunks??ot,this.compression=e.compression??st,this.assertUsableRoot(),this.coordinator=new gt(this.ctx,this,{preparedSessionCacheSize:r,writeBatchMaxDelayMs:o})}locate(t){return{kind:"jsonl",path:g(this.root,t.cwd,t.id,this.compression)}}create(t){return this.coordinator.create(t)}append(t,e){return this.coordinator.append(t,e)}prepare(t,e){return this.coordinator.prepare(t,e)}load(t){return this.coordinator.load(t)}inspect(t,e){return this.coordinator.inspect(t,e)}readFrom(t,e,r){return this.coordinator.readFrom(t,e,r)}async loadStored(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r!==void 0)return this.readPrefix(r,t,e)}async readStoredRevision(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r!==void 0)try{const o=await A(r,{bigint:!0});return e?.throwIfAborted(),D(o)}catch(o){if(e?.throwIfAborted(),b(o))return;throw o}}async readRaw(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r===void 0)return;const{buffer:o}=await this.readStableFile(r,e);let s;if(this.compression==="zstd"){const{frames:n}=O(o);if(n.length===0)throw new Error("empty or header-less Zstandard session log");const c=et(),d=[];for(const h of c.decode(o,n))e?.throwIfAborted(),d.push(Buffer.from(h));s=Buffer.concat(d).toString("utf8")}else s=o.toString("utf8");const i=Y(s.split(`
|
|
2
|
+
`)}a(q,"eventLines");function Bt(t){if(typeof t!="object"||t===null)return;const{version:e,id:r}=t;if(!(typeof e!="number"||e===Dt))throw new L(vt(typeof r=="string"?r:String(r),e))}a(Bt,"refuseForeignFormatVersion");function Tt(t){if(t.length===0||t.at(-1)!==10||t.indexOf(10)!==t.length-1)throw new Error("empty or header-less session log");let e;try{e=JSON.parse(t.subarray(0,-1).toString("utf8"))}catch{throw new Error("corrupt session log: header line is not valid JSON")}if(Bt(e),!K(e))throw new Error("corrupt session log: first line is not a session header");return J(e)}a(Tt,"parseHeaderRecord");var G=class{static{a(this,"SessionLogScanner")}meta;events=[];fragments=[];fragmentBytes=0;inputBytes;committedBytes;eventLine=0;issue;finished=!1;constructor(t){this.meta=Tt(t),this.inputBytes=t.length,this.committedBytes=t.length}write(t){if(this.finished)throw new Error("cannot write to a finished session log scanner");const e=this.inputBytes;this.inputBytes+=t.length;let r=0;for(let o=t.indexOf(10);o!==-1;o=t.indexOf(10,r)){const s=t.subarray(r,o);let i=s;this.fragments.length>0&&(s.length>0&&this.fragments.push(s),i=Buffer.concat(this.fragments,this.fragmentBytes+s.length),this.fragments=[],this.fragmentBytes=0),this.consumeEventLine(i,e+o+1),r=o+1}if(r<t.length){const o=Buffer.from(t.subarray(r));this.fragments.push(o),this.fragmentBytes+=o.length}}checkpoint(){return{inputBytes:this.inputBytes,committedBytes:this.committedBytes,eventCount:this.events.length}}finish(){return this.finished=!0,{meta:this.meta,events:this.events,committedBytes:this.committedBytes}}consumeEventLine(t,e){this.eventLine+=1;let r;try{r=_t(JSON.parse(t.toString("utf8")))}catch{this.issue??=new Error(`corrupt session log: unparsable committed event at line ${this.eventLine}`);return}if(this.issue!==void 0){if(r.some(s=>s.type==="turn/end"))throw this.issue;return}const o=this.events.length;for(const s of r){if(s.seq!==this.events.length){const i=this.events.length;if(this.events.length=o,this.issue=new Error(`corrupt session log: seq gap in committed region at line ${this.eventLine} (expected ${i}, got ${s.seq})`),r.some(n=>n.type==="turn/end"))throw this.issue;return}this.events.push(s)}this.committedBytes=e}};function $t(t){const e=t.indexOf(10);if(e===-1)throw new Error("empty or header-less session log");const r=new G(t.subarray(0,e+1));return r.write(t.subarray(e+1)),r.finish()}a($t,"scanLog");function Y(t){let e;try{e=JSON.parse(t)}catch{return}if(K(e))return J(e)}a(Y,"parseHeaderMeta");const Q=1048576;function kt(t){const e=t,r=e._handle,o=Reflect.ownKeys(t).find(s=>typeof s=="symbol"&&s.description==="kError");if(!(typeof r!="object"||r===null||typeof r.writeSync!="function"||!(e._writeState instanceof Uint32Array)||e._writeState.length<2||typeof e._defaultFlushFlag!="number"||o===void 0||e[o]!==null))return{stream:t,errorKey:o}}a(kt,"privateZstdStream");var Pt=class dt{static{a(this,"NodePrivateZstdFrameDecoder")}stream;errorKey;output=Buffer.allocUnsafe(Q);decoderError;started=!1;closed=!1;constructor(e,r){this.stream=e,this.errorKey=r,this.stream.on("error",o=>{this.decoderError??=o})}static create(){const e=Lt({chunkSize:Q}),r=kt(e);if(r!==void 0)return new dt(r.stream,r.errorKey);e.close()}*decode(e,r){if(this.started)throw new Error("Zstandard frame decoder was already started");if(this.closed)throw new Error("cannot start a closed Zstandard frame decoder");this.started=!0;try{for(const o of r)try{yield this.decodeFrame(e.subarray(o.start,o.end))}catch(s){throw new Error(`corrupt Zstandard session log: frame at byte ${o.start} failed validation`,{cause:s})}}finally{this.close()}}decodeFrame(e){const r=this.stream._handle;if(this.closed||r===null)throw new Error("cannot decode with a closed Zstandard frame decoder");let o=0,s=e.length,i=0;const n=[];for(;;){if(r.writeSync(this.stream._defaultFlushFlag,e,o,s,this.output,0,this.output.length),this.decoderError!==void 0)throw this.decoderError;const c=this.stream[this.errorKey];if(c!==null)throw c instanceof Error?c:new Error("Zstandard decoder exposed a non-Error internal failure");const d=this.stream._writeState[0],h=this.stream._writeState[1],u=s-h,l=this.output.length-d;if(l>0&&(i+=l,i>W.MAX_LENGTH))throw new Error(`Zstandard frame output exceeds ${W.MAX_LENGTH} bytes`);if(d!==0){if(h!==0)throw new Error("Zstandard frame decoder left trailing input");const p=this.output.subarray(0,l);if(n.length===0)return p;l>0&&n.push(Buffer.from(p));const w=n[0];return n.length===1?w:Buffer.concat(n,i)}n.push(Buffer.from(this.output)),o+=u,s=h}}close(){this.closed||(this.closed=!0,this.stream.close())}},Zt=class{static{a(this,"PublicZstdFrameDecoder")}started=!1;closed=!1;*decode(t,e){if(this.started)throw new Error("Zstandard frame decoder was already started");if(this.closed)throw new Error("cannot start a closed Zstandard frame decoder");this.started=!0;try{for(const{start:r,end:o}of e){let s;try{s=Rt(t.subarray(r,o))}catch(i){throw new Error(`corrupt Zstandard session log: frame at byte ${r} failed validation`,{cause:i})}yield s}}finally{this.close()}}close(){this.closed=!0}};const jt=4247762216,zt=U(xt),tt=U(Ot),Mt={params:{[H.ZSTD_c_checksumFlag]:1}},Ht={finishFlush:H.ZSTD_e_flush};function O(t,e=Number.POSITIVE_INFINITY){const r=[];let o=0;for(;o<t.length;){const s=o;if(t.length-o<4)return{frames:r,tornStart:s};if(t.readUInt32LE(o)!==jt)throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${o}`);if(o+=4,o===t.length)return{frames:r,tornStart:s};const i=t.readUInt8(o);if(o+=1,(i&24)!==0)throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${o-1}`);const n=i>>>6,c=(i&32)!==0,d=(i&4)!==0,h=i&3,u=h===3?4:h,l=n===0?c?1:0:1<<n,p=(c?0:1)+u+l;if(t.length-o<p)return{frames:r,tornStart:s};for(o+=p;;){if(t.length-o<3)return{frames:r,tornStart:s};const w=t.readUIntLE(o,3);o+=3;const ht=(w&1)!==0,B=w>>>1&3,ft=w>>>3;if(B===3)throw new Error(`corrupt Zstandard session log: reserved block type at byte ${o-3}`);const T=B===1?1:ft;if(t.length-o<T)return{frames:r,tornStart:s};if(o+=T,ht)break}if(d){if(t.length-o<4)return{frames:r,tornStart:s};o+=4}if(r.push({start:s,end:o}),r.length===e)return{frames:r}}return{frames:r}}a(O,"scanZstdFrames");async function R(t){return zt(t,Mt)}a(R,"compressZstdFrame");async function Ut(t){return tt(t)}a(Ut,"decompressZstdFrame");function et(){return Pt.create()??new Zt}a(et,"createZstdFrameDecoder");async function Wt(t){return tt(t,Ht)}a(Wt,"decompressZstdPrefix");const Jt=8,Kt=2,Vt=3,Xt=5,qt=17,Gt=80,Yt=123,Qt=183;let v;async function te(){if(v!==void 0)return v;const t=(await import("koffi")).default.load("kernel32.dll");return v={moveFileExW:t.func("__stdcall","MoveFileExW","int",["str16","str16","uint"]),getLastError:t.func("__stdcall","GetLastError","uint",[])},v}a(te,"win32");function ee(t){switch(t){case Kt:case Vt:return"ENOENT";case Xt:return"EACCES";case qt:return"EXDEV";case Gt:case Qt:return"EEXIST";case Yt:return"EINVAL";default:return"EIO"}}a(ee,"errnoCode");function re(t,e,r,o){const s=ee(e),i=new Error(`${t} ${s} (Win32 ${e}): ${r} -> ${o}`);return i.code=s,i.errno=e,i.syscall=t,i.path=r,i.dest=o,i.win32Code=e,i}a(re,"win32Error");function oe(t){return t?.code==="ENOENT"}a(oe,"isENOENT$1");function se(t){return t?.code==="EEXIST"}a(se,"isEEXIST");async function N(t){try{const e=t===Z(t).root?t:I(t);if((await A(e)).isDirectory())return!0;const r=new Error(`path exists but is not a directory: ${t}`);throw r.code="ENOTDIR",r.path=t,r}catch(e){if(oe(e))return!1;throw e}}a(N,"assertDirectory");async function rt(t,e){const r=await te();if(r.moveFileExW(I(t),I(e),Jt)===0)throw re("MoveFileExW",r.getLastError(),t,e)}a(rt,"publishNewFileWin32");async function C(t){const e=j(t),r=Z(e).root;await N(r);const o=e.slice(r.length).split(/[\\/]+/).filter(i=>i.length>0);let s=r;for(const i of o){const n=f(s,i);await N(n)||await ie(s,n),s=n}}a(C,"ensureDurableDirectoryWin32");async function ie(t,e){const r=await pt(I(f(t,".dsh-mkdir-")));try{await rt(r,e)}catch(o){if(await S(r,{recursive:!0,force:!0}),se(o)&&await N(e))return;throw o}}a(ie,"createLeafDirectoryWin32");const ot=!0,st="zstd",it=500;function nt(t){if(t.length===0||t.indexOf(10)!==t.length-1)throw new Error("corrupt Zstandard session log: first frame is not exactly one header line")}a(nt,"assertZstdHeaderFrame");const at=m.union([m.const("zstd"),m.const("none")]).default(st);function D(t){return It([t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":"))}a(D,"fileRevision");function b(t){return t?.code==="ENOENT"}a(b,"isENOENT");var ct=class extends St{static{a(this,"JsonlSessionPersistence")}config;supportsRawArtifacts=!0;static inject=["sessions"];static Config=m.object({root:m.string().required(),packChunks:m.boolean().default(ot),compression:at,preparedSessionCacheSize:m.number().step(1).min(1).default(z),writeBatchMaxDelayMs:m.number().step(1).min(1).max(At).default(M)});name="session-persistence-jsonl";root;packChunks;compression;coordinator;rootEncodingCheck;constructor(t,e){super(t),this.config=e,this.root=j(e.root);const r=e.preparedSessionCacheSize??z,o=e.writeBatchMaxDelayMs??M;this.packChunks=e.packChunks??ot,this.compression=e.compression??st,this.assertUsableRoot(),this.coordinator=new gt(this.ctx,this,{preparedSessionCacheSize:r,writeBatchMaxDelayMs:o})}locate(t){return{kind:"jsonl",path:g(this.root,t.cwd,t.id,this.compression)}}create(t){return this.coordinator.create(t)}append(t,e){return this.coordinator.append(t,e)}prepare(t,e){return this.coordinator.prepare(t,e)}load(t){return this.coordinator.load(t)}inspect(t,e){return this.coordinator.inspect(t,e)}readFrom(t,e,r){return this.coordinator.readFrom(t,e,r)}async loadStored(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r!==void 0)return this.readPrefix(r,t,e)}async readStoredRevision(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r!==void 0)try{const o=await A(r,{bigint:!0});return e?.throwIfAborted(),D(o)}catch(o){if(e?.throwIfAborted(),b(o))return;throw o}}async readRaw(t,e){e?.throwIfAborted(),await this.ensureRootEncoding(),e?.throwIfAborted();const r=await this.findLog(t,e);if(r===void 0)return;const{buffer:o}=await this.readStableFile(r,e);let s;if(this.compression==="zstd"){const{frames:n}=O(o);if(n.length===0)throw new Error("empty or header-less Zstandard session log");const c=et(),d=[];for(const h of c.decode(o,n))e?.throwIfAborted(),d.push(Buffer.from(h));s=Buffer.concat(d).toString("utf8")}else s=o.toString("utf8");const i=Y(s.split(`
|
|
3
3
|
`,1)[0]);if(i===void 0||i.id!==t)throw new Error(`corrupt session log: invalid header line in "${r}"`);return{meta:i,filename:"session.jsonl",content:s}}async readStableFile(t,e){for(;;){e?.throwIfAborted();const r=D(await A(t,{bigint:!0})),o=await mt(t,{signal:e});e?.throwIfAborted();const s=D(await A(t,{bigint:!0}));if(r===s)return{buffer:o,revision:s}}}async readPrefix(t,e,r){const{buffer:o,revision:s}=await this.readStableFile(t,r);let i;try{if(this.compression==="zstd")i=await this.readZstdPrefix(o,r);else{r?.throwIfAborted();const{meta:n,events:c,committedBytes:d}=$t(o);r?.throwIfAborted(),i={meta:n,events:c,...d<o.byteLength?{tornMarker:{truncateTo:d,recoveredEvents:[]}}:{}}}}catch(n){throw n instanceof L&&n.location===void 0?new L(`${n.message} (raw log: ${t})`,{kind:"jsonl",path:t}):n}return r?.throwIfAborted(),await this.assertStoredIdentity(t,i.meta,e,r),r?.throwIfAborted(),{...i,revision:s}}async readZstdPrefix(t,e){e?.throwIfAborted();const{frames:r,tornStart:o}=O(t);if(e?.throwIfAborted(),r.length===0)throw new Error("empty or header-less Zstandard session log");const s=et();let i=F.now()+it;try{const n=s.decode(t,r);e?.throwIfAborted();const c=n.next();if(e?.throwIfAborted(),c.done)throw new Error("empty or header-less Zstandard session log");nt(c.value);const d=new G(c.value);let h=r.length-1;for(const w of n)e?.throwIfAborted(),d.write(w),h-=1,h>0&&F.now()>=i&&(await Et.yield(),e?.throwIfAborted(),i=F.now()+it);e?.throwIfAborted();const u=d.checkpoint();if(u.committedBytes!==u.inputBytes)throw new Error("corrupt Zstandard session log: complete frame contains a torn JSONL record");if(o===void 0){const w=d.finish();return{meta:w.meta,events:w.events}}let l=Buffer.alloc(0);try{e?.throwIfAborted(),l=await Wt(t.subarray(o))}catch{e?.aborted&&e.throwIfAborted()}e?.throwIfAborted(),d.write(l);const p=d.finish();return e?.throwIfAborted(),{meta:p.meta,events:p.events,tornMarker:{truncateTo:o,recoveredEvents:p.events.slice(u.eventCount)}}}catch(n){throw e?.aborted&&e.throwIfAborted(),n}finally{s.close()}}async appendBatch(t,e,r){await this.ensureRootEncoding(),r?await this.appendLines(t,e):await this.materialize(t,e)}async commitRepair(t,e,r){e!==void 0&&await this.repair(t,e.truncateTo);const o=[...e?.recoveredEvents??[],...r];o.length>0&&await this.appendLines(t,o)}async list(t){return(await this.listArtifacts(t)).map(e=>e.header)}async listSnapshots(t){const e=[];for(const r of await this.listArtifacts(t)){t?.throwIfAborted();try{const o=await A(r.path,{bigint:!0});t?.throwIfAborted(),e.push({header:r.header,revision:D(o)})}catch(o){if(t?.throwIfAborted(),!b(o))throw o}}return t?.throwIfAborted(),e}async listArtifacts(t){t?.throwIfAborted(),await this.ensureRootEncoding(),t?.throwIfAborted();const e=[],r=new Set;for(const o of await this.listProjectDirs(t)){t?.throwIfAborted();for(const s of await this.listSessionDirs(o,t)){t?.throwIfAborted();const i=f(s,`session${E(this.oppositeCompression())}`),n=await this.exists(i);if(t?.throwIfAborted(),n)throw this.encodingMismatch(i);const c=f(s,`session${E(this.compression)}`),d=await this.exists(c);if(t?.throwIfAborted(),!d)continue;const h=this.compression==="zstd"?await this.readFirstZstdLine(c,t):await this.readFirstLine(c,t);if(t?.throwIfAborted(),h===void 0)continue;const u=Y(h);if(u!==void 0){if(await this.assertStoredIdentity(c,u,void 0,t),t?.throwIfAborted(),r.has(u.id))throw new Error(`duplicate JSONL session id "${u.id}" appears in multiple project directories`);r.add(u.id),e.push({header:u,path:c})}}}return t?.throwIfAborted(),e}async materialize(t,e){const r=V(this.root,t.cwd),o=X(this.root,t.cwd,t.id),s=g(this.root,t.cwd,t.id,this.compression);await this.rejectOppositeArtifact(t.cwd,t.id);const i=await this.encodeMaterialization(t,e);process.platform==="win32"?await this.materializeWin32(r,o,s,t.id,i):await this.materializePosix(r,o,s,t.id,i)}async materializePosix(t,e,r,o,s){await _(this.root,{recursive:!0,mode:448}),await this.syncDirPosix(P(this.root)),await _(t,{recursive:!0,mode:448}),await this.syncDirPosix(this.root),await _(e,{recursive:!0,mode:448}),await this.syncDirPosix(t),await this.rejectExistingLog(r,o);const i=await this.writeSyncedTempFile(r,s);let n=!1;try{await lt(i,r),n=!0}finally{n||await S(i,{force:!0})}await this.syncDirPosix(e);try{await S(i,{force:!0})}catch{}}async materializeWin32(t,e,r,o,s){await C(this.root),await C(t),await C(e),await this.rejectExistingLog(r,o);const i=await this.writeSyncedTempFile(r,s);try{await rt(i,r)}catch(n){throw await S(i,{force:!0}),n}}async rejectExistingLog(t,e){if(await this.exists(t))throw new Error(`refusing to materialize "${e}": a log already exists on disk (load/resume it instead)`)}async writeSyncedTempFile(t,e){const r=`${t}.${bt(6).toString("hex")}.tmp`,o=await y(r,"wx",384);try{await o.writeFile(e),await o.sync()}finally{await o.close()}return r}async encodeMaterialization(t,e){const r=JSON.stringify(Nt(t))+`
|
|
4
4
|
`,o=q(e,this.packChunks)+`
|
|
5
5
|
`;if(this.compression==="none")return r+o;const s=await R(r),i=await R(o);return Buffer.concat([s,i])}async encodeEventBatch(t){const e=q(t,this.packChunks)+`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-persistence-jsonl","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-persistence-jsonl","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-session-persistence":"^0.0.12","@deepseek-ai/cordis":"^4.0.1","@deepseek-ai/dsh-session":"^0.0.12"},"dependencies":{"koffi":"^3.1.0","@deepseek-ai/schemastery":"^3.18.1"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-projection","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-projection","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./types":{"types":"./lib/types/types.d.ts","default":"./lib/types/types.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","dependencies":{"zod":"^4.4.3"},"peerDependencies":{"@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/cordis":"^4.0.1"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-projection-cache","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-projection-cache","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","dependencies":{"zod":"^4.4.3","@deepseek-ai/schemastery":"^3.18.1"},"peerDependencies":{"@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-storage-domain":"^0.0.12","@deepseek-ai/dsh-session-projection":"^0.0.12","@deepseek-ai/cordis":"^4.0.1","@deepseek-ai/dsh-session-persistence":"^0.0.12"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-query","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-query","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-brand":"^0.0.12","@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-llm":"^0.0.12","@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/dsh-session-persistence":"^0.0.12","@deepseek-ai/dsh-session-title":"^0.0.12","@deepseek-ai/cordis":"^4.0.1"},"peerDependenciesMeta":{"@deepseek-ai/dsh-session-persistence":{"optional":true}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@deepseek-ai/dsh-session-query-sqlite","version":"0.0.
|
|
1
|
+
{"name":"@deepseek-ai/dsh-session-query-sqlite","version":"0.0.12","publishConfig":{"access":"public"},"type":"module","main":"lib/index.js","exports":{".":{"types":"./lib/types/index.d.ts","default":"./lib/index.js"},"./invariant":{"types":"./lib/types/invariant.d.ts","default":"./lib/invariant.js"},"./src/*":"./src/*","./package.json":"./package.json"},"license":"MIT","peerDependencies":{"@deepseek-ai/dsh-invariants":"^0.0.12","@deepseek-ai/dsh-session":"^0.0.12","@deepseek-ai/dsh-session-persistence":"^0.0.12","@deepseek-ai/dsh-session-query":"^0.0.12","@deepseek-ai/cordis":"^4.0.1"},"peerDependenciesMeta":{"@deepseek-ai/dsh-session-persistence":{"optional":true}},"dependencies":{"@deepseek-ai/schemastery":"^3.18.1"}}
|