@code-yeongyu/senpi 2026.9.27-2 → 2026.9.27-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/bundle/chunks/anthropic-messages-3FGAXYJS.js +8 -0
- package/dist/bundle/chunks/{app-server-command-ATWHNOOO.js → app-server-command-ZVB35UIJ.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-4SUOOZZ4.js +2 -0
- package/dist/bundle/chunks/{chunk-KMJXSXRX.js → chunk-357I4IUU.js} +2 -2
- package/dist/bundle/chunks/chunk-3SIQIY57.js +8 -0
- package/dist/bundle/chunks/chunk-45SZOLCU.js +2 -0
- package/dist/bundle/chunks/{chunk-77ACEMYL.js → chunk-6J6RDMBY.js} +1 -1
- package/dist/bundle/chunks/{chunk-FD34HSJJ.js → chunk-C6LQNMRB.js} +1 -1
- package/dist/bundle/chunks/chunk-ELM77A26.js +2 -0
- package/dist/bundle/chunks/chunk-GZVCRV7I.js +3 -0
- package/dist/bundle/chunks/{chunk-TTY5BHCG.js → chunk-H2SGCPMD.js} +1 -1
- package/dist/bundle/chunks/chunk-KLBKUBDV.js +2 -0
- package/dist/bundle/chunks/chunk-L6QV7NZI.js +2 -0
- package/dist/bundle/chunks/{chunk-ZKZAATFM.js → chunk-LDB5UMH2.js} +2 -2
- package/dist/bundle/chunks/{chunk-HZAKOVHN.js → chunk-LGKKU4VM.js} +1 -1
- package/dist/bundle/chunks/{chunk-6Q6DGME2.js → chunk-NMDALHXH.js} +1 -1
- package/dist/bundle/chunks/chunk-NNILBBOH.js +18 -0
- package/dist/bundle/chunks/{chunk-SUQDU5KM.js → chunk-OQRUK2DK.js} +1 -1
- package/dist/bundle/chunks/{chunk-67BC7VZV.js → chunk-OZN2KUPR.js} +6 -6
- package/dist/bundle/chunks/{chunk-X3T45623.js → chunk-QK4QKRTF.js} +1 -1
- package/dist/bundle/chunks/{chunk-WM5FVFAP.js → chunk-QPZVJQC5.js} +1 -1
- package/dist/bundle/chunks/{chunk-HPY47AVX.js → chunk-QYAO24GB.js} +1 -1
- package/dist/bundle/chunks/{chunk-6W2DB2GC.js → chunk-RULGEHQM.js} +1 -1
- package/dist/bundle/chunks/{chunk-6SLQ5HFO.js → chunk-RYI6XR6Z.js} +55 -53
- package/dist/bundle/chunks/chunk-U3VOXCGP.js +2 -0
- package/dist/bundle/chunks/{chunk-LPFZGWG2.js → chunk-Y7EIVDHZ.js} +1 -1
- package/dist/bundle/chunks/chunk-ZIVYE5YK.js +2 -0
- package/dist/bundle/chunks/cli-main-RONHLFWZ.js +3 -0
- package/dist/bundle/chunks/google-generative-ai-ZTGKZTGU.js +2 -0
- package/dist/bundle/chunks/google-vertex-CCZ376YK.js +2 -0
- package/dist/bundle/chunks/help-fast-path-5LRG6FCG.js +2 -0
- package/dist/bundle/chunks/host-command-JVPGQR74.js +2 -0
- package/dist/bundle/chunks/host-lifecycle-R4HLXLBM.js +3 -0
- package/dist/bundle/chunks/host-lifecycle.js +4 -4
- package/dist/bundle/chunks/interactive-host-runtime-FES2G62G.js +4 -0
- package/dist/bundle/chunks/interactive-mode-45EP2FVL.js +2 -0
- package/dist/bundle/chunks/{list-tips-EBRNBPBM.js → list-tips-XXMRDHN6.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-CE3W6COI.js → multi-session-host-EFCMD5OT.js} +6 -6
- package/dist/bundle/chunks/{openai-completions-4CLXDDHJ.js → openai-completions-OP6VFNUR.js} +1 -1
- package/dist/bundle/chunks/openai-images-6U5FCN5S.js +2 -0
- package/dist/bundle/chunks/openai-responses-7PWMBGYX.js +2 -0
- package/dist/bundle/chunks/openrouter-images-QIKWQZUD.js +2 -0
- package/dist/bundle/chunks/{package-manager-cli-2PHRL2SX.js → package-manager-cli-5XJS3TYM.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-KW7PTEC4.js +2 -0
- package/dist/bundle/chunks/rpc-mode-ZHYECU24.js +2 -0
- package/dist/bundle/chunks/session-picker-QHIYVQP4.js +2 -0
- package/dist/bundle/chunks/session-worker.js +245 -238
- package/dist/bundle/chunks/{state-store-Q5EWEAFG.js → state-store-D4GGGT3J.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/continue-moved.d.ts +15 -0
- package/dist/cli/continue-moved.d.ts.map +1 -0
- package/dist/cli/continue-moved.js +26 -0
- package/dist/cli/continue-moved.js.map +1 -0
- package/dist/core/agent-session-runtime.d.ts +3 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +43 -10
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-registry-pump.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-claim.d.ts +13 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-claim.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-claim.js +25 -2
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-claim.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts +1 -0
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-turn-types.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/catalog.d.ts +3 -0
- package/dist/core/extensions/builtin/mcp/catalog.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/catalog.js +9 -0
- package/dist/core/extensions/builtin/mcp/catalog.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/connection-types.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/connection-types.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/connection-types.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/connection.d.ts +1 -1
- package/dist/core/extensions/builtin/mcp/connection.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/connection.js +3 -2
- package/dist/core/extensions/builtin/mcp/connection.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/expose/session.d.ts +3 -0
- package/dist/core/extensions/builtin/mcp/expose/session.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/expose/session.js +9 -2
- package/dist/core/extensions/builtin/mcp/expose/session.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/service-register.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/service-register.js +7 -1
- package/dist/core/extensions/builtin/mcp/service-register.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/service-tools-changed.d.ts +18 -0
- package/dist/core/extensions/builtin/mcp/service-tools-changed.d.ts.map +1 -0
- package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -0
- package/dist/core/extensions/builtin/mcp/service-tools-changed.js.map +1 -0
- package/dist/core/extensions/builtin/mcp/service-types.d.ts +13 -0
- package/dist/core/extensions/builtin/mcp/service-types.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/service-types.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/service.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/service.js +4 -37
- package/dist/core/extensions/builtin/mcp/service.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/shared-lease.js +1 -1
- package/dist/core/extensions/builtin/mcp/shared-lease.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/startup-race.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/startup-race.js +11 -1
- package/dist/core/extensions/builtin/mcp/startup-race.js.map +1 -1
- package/dist/core/moved-sessions.d.ts +10 -0
- package/dist/core/moved-sessions.d.ts.map +1 -0
- package/dist/core/moved-sessions.js +84 -0
- package/dist/core/moved-sessions.js.map +1 -0
- package/dist/core/process-crash-record.d.ts +62 -0
- package/dist/core/process-crash-record.d.ts.map +1 -0
- package/dist/core/process-crash-record.js +216 -0
- package/dist/core/process-crash-record.js.map +1 -0
- package/dist/core/resume-target.d.ts +20 -0
- package/dist/core/resume-target.d.ts.map +1 -0
- package/dist/core/resume-target.js +30 -0
- package/dist/core/resume-target.js.map +1 -0
- package/dist/core/session-discovery.d.ts.map +1 -1
- package/dist/core/session-discovery.js +1 -0
- package/dist/core/session-discovery.js.map +1 -1
- package/dist/core/session-hold-errors.d.ts +20 -0
- package/dist/core/session-hold-errors.d.ts.map +1 -0
- package/dist/core/session-hold-errors.js +28 -0
- package/dist/core/session-hold-errors.js.map +1 -0
- package/dist/core/session-holders.d.ts +22 -0
- package/dist/core/session-holders.d.ts.map +1 -0
- package/dist/core/session-holders.js +234 -0
- package/dist/core/session-holders.js.map +1 -0
- package/dist/core/session-manager.d.ts +5 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-rebind.d.ts +7 -1
- package/dist/core/session-rebind.d.ts.map +1 -1
- package/dist/core/session-rebind.js +21 -5
- package/dist/core/session-rebind.js.map +1 -1
- package/dist/core/session-summary-index-file.d.ts.map +1 -1
- package/dist/core/session-summary-index-file.js +5 -2
- package/dist/core/session-summary-index-file.js.map +1 -1
- package/dist/core/session-summary.d.ts +3 -0
- package/dist/core/session-summary.d.ts.map +1 -1
- package/dist/core/session-summary.js +7 -0
- package/dist/core/session-summary.js.map +1 -1
- package/dist/legacy-dir-copy.d.ts +9 -0
- package/dist/legacy-dir-copy.d.ts.map +1 -0
- package/dist/legacy-dir-copy.js +69 -0
- package/dist/legacy-dir-copy.js.map +1 -0
- package/dist/legacy-senpi-dir-migration.d.ts.map +1 -1
- package/dist/legacy-senpi-dir-migration.js +64 -48
- package/dist/legacy-senpi-dir-migration.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +45 -19
- package/dist/main.js.map +1 -1
- package/dist/migrations-state.d.ts +1 -1
- package/dist/migrations-state.d.ts.map +1 -1
- package/dist/migrations-state.js +5 -1
- package/dist/migrations-state.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +4 -0
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +5 -3
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +8 -4
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/resume-rebind.d.ts +12 -0
- package/dist/modes/interactive/resume-rebind.d.ts.map +1 -0
- package/dist/modes/interactive/resume-rebind.js +37 -0
- package/dist/modes/interactive/resume-rebind.js.map +1 -0
- package/dist/modes/interactive/tips/catalog/computer-tips.d.ts +7 -0
- package/dist/modes/interactive/tips/catalog/computer-tips.d.ts.map +1 -0
- package/dist/modes/interactive/tips/catalog/computer-tips.js +36 -0
- package/dist/modes/interactive/tips/catalog/computer-tips.js.map +1 -0
- package/dist/modes/interactive/tips/registry.d.ts.map +1 -1
- package/dist/modes/interactive/tips/registry.js +2 -0
- package/dist/modes/interactive/tips/registry.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +3 -0
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/host-child-exit.d.ts.map +1 -1
- package/dist/modes/rpc/host-child-exit.js +4 -0
- package/dist/modes/rpc/host-child-exit.js.map +1 -1
- package/dist/modes/rpc/host-crash-record.d.ts +8 -0
- package/dist/modes/rpc/host-crash-record.d.ts.map +1 -1
- package/dist/modes/rpc/host-crash-record.js.map +1 -1
- package/dist/modes/rpc/host-crash-record.test.js +11 -0
- package/dist/modes/rpc/host-crash-record.test.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +2 -2
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +14 -6
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-request-deadline.d.ts +17 -0
- package/dist/modes/rpc/rpc-request-deadline.d.ts.map +1 -0
- package/dist/modes/rpc/rpc-request-deadline.js +27 -0
- package/dist/modes/rpc/rpc-request-deadline.js.map +1 -0
- package/dist/modes/rpc/rpc-types.d.ts +9 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts +3 -6
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +9 -22
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-path-key.d.ts +10 -0
- package/dist/modes/rpc/session-path-key.d.ts.map +1 -0
- package/dist/modes/rpc/session-path-key.js +33 -0
- package/dist/modes/rpc/session-path-key.js.map +1 -0
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +6 -10
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/dist/modes/rpc/session-sweep.d.ts +18 -0
- package/dist/modes/rpc/session-sweep.d.ts.map +1 -0
- package/dist/modes/rpc/session-sweep.js +32 -0
- package/dist/modes/rpc/session-sweep.js.map +1 -0
- package/dist/pi-dir-restore.d.ts +4 -0
- package/dist/pi-dir-restore.d.ts.map +1 -0
- package/dist/pi-dir-restore.js +92 -0
- package/dist/pi-dir-restore.js.map +1 -0
- package/docs/rpc.md +8 -3
- package/docs/sdk.md +29 -0
- package/docs/sessions.md +4 -0
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts +2 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js +7 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.js +3 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/assistant-terminal-state.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +3 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js +10 -7
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +9 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/provider-diagnostic.d.ts +33 -0
- package/node_modules/@earendil-works/pi-ai/dist/provider-diagnostic.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/provider-diagnostic.js +56 -0
- package/node_modules/@earendil-works/pi-ai/dist/provider-diagnostic.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +3 -0
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-carrier.d.ts +5 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-carrier.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-carrier.js +18 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-carrier.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-sources.d.ts +26 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-sources.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-sources.js +103 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-sources.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-vocabulary.d.ts +36 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-vocabulary.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-vocabulary.js +129 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-diagnostic-vocabulary.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js +5 -4
- package/node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
- package/dist/bundle/chunks/anthropic-messages-UYDVRFAS.js +0 -8
- package/dist/bundle/chunks/azure-openai-responses-DODWR4W6.js +0 -2
- package/dist/bundle/chunks/chunk-2L26KPZ6.js +0 -8
- package/dist/bundle/chunks/chunk-3CC5ZOBV.js +0 -13
- package/dist/bundle/chunks/chunk-L6JO4M6J.js +0 -3
- package/dist/bundle/chunks/chunk-SFYHCFRO.js +0 -2
- package/dist/bundle/chunks/chunk-TTHMOL5G.js +0 -2
- package/dist/bundle/chunks/chunk-UYCGOK6M.js +0 -2
- package/dist/bundle/chunks/chunk-ZTVQY5V6.js +0 -2
- package/dist/bundle/chunks/cli-main-HOM6UH3H.js +0 -3
- package/dist/bundle/chunks/google-generative-ai-VIEFECKJ.js +0 -2
- package/dist/bundle/chunks/google-vertex-Q64CKFID.js +0 -2
- package/dist/bundle/chunks/help-fast-path-YGYHMV2W.js +0 -2
- package/dist/bundle/chunks/host-command-XXSAFWBW.js +0 -2
- package/dist/bundle/chunks/host-lifecycle-GOMGJ25O.js +0 -3
- package/dist/bundle/chunks/interactive-host-runtime-IYCZWJGX.js +0 -4
- package/dist/bundle/chunks/interactive-mode-ZMO7YVYU.js +0 -2
- package/dist/bundle/chunks/openai-images-JA5N5DUU.js +0 -2
- package/dist/bundle/chunks/openai-responses-IBFGBAJP.js +0 -2
- package/dist/bundle/chunks/openrouter-images-MW5TXV7L.js +0 -2
- package/dist/bundle/chunks/rotation-stream-NATO6IMN.js +0 -2
- package/dist/bundle/chunks/rpc-mode-WCETTMFV.js +0 -2
- package/dist/bundle/chunks/session-picker-BP7THCWF.js +0 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{HOST_INSTANCE_ID_ENV,MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,engineBuildIdentity}from"./chunk-XKLR7C5B.js";import{require_signal_exit}from"./chunk-U3VOXCGP.js";import{DISPLAY_VERSION,VERSION,envValue,getAgentDir,isBunBinary,isBundledNode}from"./chunk-Y65WFI5H.js";import{__toESM}from"./chunk-IKOFCODM.js";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{existsSync,readFileSync as readFileSync4,realpathSync,writeSync}from"node:fs";import{access,chmod as chmod3,mkdir as mkdir5,readFile as readFile5,rename as rename4,rm as rm5,unlink as unlink2,writeFile as writeFile6}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{tmpdir}from"node:os";import{dirname as dirname3,extname,join as join5,resolve}from"node:path";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";function parseDaemonPidFile(text){let parsed;try{parsed=JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}let unguarded=parsed!==null&&isRecord(parsed)&&parsed.processStartTime===null;if(!(!isRecord(parsed)||typeof parsed.pid!="number"||!unguarded&&typeof parsed.processStartTime!="string")&&!(!Number.isInteger(parsed.pid)||parsed.pid<=0)){if(unguarded)return{pid:parsed.pid,processStartTime:null};if(!(typeof parsed.processStartTime!="string"||parsed.processStartTime.trim()===""))return{pid:parsed.pid,processStartTime:parsed.processStartTime}}}var ProcessIdentityUnreadableError=class extends Error{constructor(pid,attempts,cause){super(`process identity for live pid ${pid} stayed unreadable after ${attempts} probe attempt(s): ${cause instanceof Error?cause.message:String(cause)}`),this.name="ProcessIdentityUnreadableError",this.pid=pid,this.attempts=attempts,this.cause=cause}};async function processMatchesPidFile(pidFile,readStartTime=readProcessStartTime,isLive=processIsLive,retry={}){if(pidFile.processStartTime===null){if(!isLive(pidFile.pid))return!1;throw new ProcessIdentityUnreadableError(pidFile.pid,0,new Error("pidfile carries no process identity guard"))}let attempts=Math.max(1,retry.attempts??5),delayMs=retry.delayMs??200,lastError;for(let attempt=1;attempt<=attempts;attempt++)try{let current=await readStartTime(pidFile.pid);if(current!==void 0)return current===pidFile.processStartTime;if(!isLive(pidFile.pid))return!1;lastError=new Error("process identity probe returned no identity for a live process"),attempt<attempts&&await new Promise(resolve2=>setTimeout(resolve2,delayMs))}catch(error){if(!isLive(pidFile.pid))return!1;lastError=error,attempt<attempts&&await new Promise(resolve2=>setTimeout(resolve2,delayMs))}throw new ProcessIdentityUnreadableError(pidFile.pid,attempts,lastError)}async function readProcessIdentity(pid,platform=process.platform,timeoutMs,isLive=processIsLive){let command=platform==="win32"?{executable:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`$process = Get-CimInstance Win32_Process -Filter "ProcessId=${String(pid)}" -ErrorAction Stop; if ($null -eq $process) { Write-Output '__SENPI_ABSENT__'; exit 0 }; $process.CreationDate.ToFileTimeUtc().ToString("D", [Globalization.CultureInfo]::InvariantCulture)`]}:{executable:"ps",args:["-o","lstart=","-p",String(pid)]};return new Promise(resolve2=>{let effectiveTimeoutMs=timeoutMs??(platform==="win32"?1e3:void 0);execFile(command.executable,command.args,{windowsHide:!0,...effectiveTimeoutMs===void 0?{}:{timeout:effectiveTimeoutMs}},(error,stdout)=>{if(error){let code="code"in error?error.code:void 0;if(platform!=="win32"&&code===1||!isLive(pid)){resolve2({kind:"absent"});return}resolve2({kind:"error",error});return}let output=stdout.trim();if(output==="__SENPI_ABSENT__")return resolve2({kind:"absent"});if(!output||platform==="win32"&&!/^\d+$/.test(output))return resolve2({kind:"error",error:new Error("invalid process identity output")});resolve2({kind:"present",identity:output})}).once("error",error=>resolve2({kind:"error",error}))})}async function stopValidatedPid(pidFile,signal){if(await processMatchesPidFile(pidFile)){try{process.kill(pidFile.pid,signal)}catch(error){if(!isNodeErrorCode(error,"ESRCH"))throw error}signal==="SIGTERM"&&await waitForGone(pidFile,1e4),signal==="SIGKILL"&&await waitForGone(pidFile,2e3)}}async function waitForGone(pidFile,timeoutMs){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(!await processMatchesPidFile(pidFile))return!0;await delay(100)}return!await processMatchesPidFile(pidFile)}async function readProcessStartTime(pid,platform=process.platform,timeoutMs){return readProcessIdentity(pid,platform,timeoutMs).then(result=>{if(result.kind==="error")throw result.error;return result.kind==="present"?result.identity:void 0})}function processIsLive(pid){try{return process.kill(pid,0),!0}catch(error){if(isNodeErrorCode(error,"ESRCH"))return!1;if(isNodeErrorCode(error,"EPERM"))return!0;throw error}}async function waitForStartTime(pid,timeoutMs,readStartTime=readProcessStartTime,isLive=processIsLive){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){let startTime;try{startTime=await readStartTime(pid)}catch{}if(startTime)return startTime;await delay(20)}if(!isLive(pid))throw new Error(`spawned daemon pid ${pid} had no process start time`)}function delay(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode(error,code){return error instanceof Error&&"code"in error&&error.code===code}var import_signal_exit=__toESM(require_signal_exit(),1);import{appendFileSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,statSync,utimesSync,writeFileSync}from"node:fs";import{join}from"node:path";var PROCESS_CRASH_RECORD_LIMIT=50,PROCESS_MARKER_HEARTBEAT_MS=6e4,FILE_MODE=384,DIR_MODE=448,MARKER_SUFFIX=".json";function processCrashPaths(agentDir){let dir=join(agentDir,"process-crashes");return{dir,liveDir:join(dir,"live"),recordsFile:join(dir,"crashes.jsonl")}}function crashingRuntimeVersions(){return{...process.versions.bun===void 0?{}:{bunVersion:process.versions.bun},senpiVersion:VERSION,...DISPLAY_VERSION===VERSION?{}:{productVersion:DISPLAY_VERSION}}}function recordProcessLifetime(agentDir,kind,options){return sweepDeadProcessMarkers(agentDir,options),options.supervised?()=>{}:installProcessLifetimeMarker(agentDir,kind,options)}function installProcessLifetimeMarker(agentDir,kind,options={}){let pid=options.pid??process.pid,now=options.now??Date.now,file=join(processCrashPaths(agentDir).liveDir,`${pid}${MARKER_SUFFIX}`),marker={kind,pid,startedAt:now(),...crashingRuntimeVersions()};try{mkdirSync(processCrashPaths(agentDir).liveDir,{recursive:!0,mode:DIR_MODE}),writeFileSync(file,`${JSON.stringify(marker)}
|
|
3
|
+
`,{mode:FILE_MODE})}catch{return()=>{}}let heartbeat=setInterval(()=>{try{let at=new Date(now());utimesSync(file,at,at)}catch{}},options.heartbeatMs??PROCESS_MARKER_HEARTBEAT_MS);heartbeat.unref();let disposed=!1,dispose=()=>{disposed||(disposed=!0,clearInterval(heartbeat),process.off("exit",onProcessExit),removeSignalHook(),rmSync(file,{force:!0}))},onProcessExit=()=>{try{dispose()}catch{}};process.on("exit",onProcessExit);let removeSignalHook=(0,import_signal_exit.default)(onProcessExit);return dispose}function sweepDeadProcessMarkers(agentDir,options={}){let paths=processCrashPaths(agentDir),selfPid=options.pid??process.pid,isAlive=options.isAlive??isProcessAlive,names;try{names=readdirSync(paths.liveDir)}catch{return 0}let recorded=0;for(let name of names){if(!name.endsWith(MARKER_SUFFIX))continue;let pid=Number(name.slice(0,-MARKER_SUFFIX.length));if(!Number.isSafeInteger(pid)||pid<=0||pid===selfPid||isAlive(pid))continue;let claimed=join(paths.liveDir,`${name}.${selfPid}.sweep`);try{renameSync(join(paths.liveDir,name),claimed)}catch{continue}try{let record=crashRecordFromMarker(readFileSync(claimed,"utf8"),statSync(claimed).mtimeMs);record!==void 0&&(appendProcessCrashRecord(paths,record),recorded+=1)}catch{}finally{rmSync(claimed,{force:!0})}}return recorded}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function crashRecordFromMarker(raw,lastHeartbeatMs){let value=JSON.parse(raw);if(typeof value!="object"||value===null)return;let kind=Reflect.get(value,"kind"),startedAt=Reflect.get(value,"startedAt"),senpiVersion=Reflect.get(value,"senpiVersion"),bunVersion=Reflect.get(value,"bunVersion"),productVersion=Reflect.get(value,"productVersion");if(!(typeof kind!="string"||typeof startedAt!="number"||typeof senpiVersion!="string"))return{at:new Date(lastHeartbeatMs).toISOString(),kind,detection:"unclean_exit",uptimeMs:Math.max(0,Math.round(lastHeartbeatMs-startedAt)),...typeof bunVersion=="string"?{bunVersion}:{},senpiVersion,...typeof productVersion=="string"?{productVersion}:{}}}function appendProcessCrashRecord(paths,record){mkdirSync(paths.dir,{recursive:!0,mode:DIR_MODE}),appendFileSync(paths.recordsFile,`${JSON.stringify(record)}
|
|
4
|
+
`,{mode:FILE_MODE});let records=readProcessCrashRecordsFrom(paths.recordsFile);if(records.length<=PROCESS_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-PROCESS_CRASH_RECORD_LIMIT);writeFileSync(paths.recordsFile,`${kept.join(`
|
|
5
|
+
`)}
|
|
6
|
+
`,{mode:FILE_MODE})}function readProcessCrashRecordsFrom(file){return readFileSync(file,"utf8").split(`
|
|
7
|
+
`).filter(line=>line.trim()!=="")}import{appendFileSync as appendFileSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join2}from"node:path";var HOST_CRASH_RECORD_LIMIT=50,CRASH_RECORD_FILE_MODE=384;function hostCrashRecordFile(daemonDir){return join2(daemonDir,"crashes.jsonl")}function recordHostCrash(daemonDir,record){try{mkdirSync2(daemonDir,{recursive:!0,mode:448}),appendFileSync2(hostCrashRecordFile(daemonDir),`${JSON.stringify(record)}
|
|
8
|
+
`,{mode:CRASH_RECORD_FILE_MODE}),pruneHostCrashRecords(daemonDir)}catch{}}function readHostCrashRecords(daemonDir){let raw;try{raw=readFileSync2(hostCrashRecordFile(daemonDir),"utf8")}catch{return[]}let records=[];for(let line of raw.split(`
|
|
9
|
+
`))if(line.trim()!=="")try{let value=JSON.parse(line);typeof value=="object"&&value!==null&&typeof Reflect.get(value,"at")=="string"&&records.push(value)}catch{}return records}function pruneHostCrashRecords(daemonDir){let records=readHostCrashRecords(daemonDir);if(records.length<=HOST_CRASH_RECORD_LIMIT)return;let kept=records.slice(records.length-HOST_CRASH_RECORD_LIMIT);writeFileSync2(hostCrashRecordFile(daemonDir),`${kept.map(r=>JSON.stringify(r)).join(`
|
|
10
|
+
`)}
|
|
11
|
+
`,{mode:CRASH_RECORD_FILE_MODE})}function classifyChildExit(code,signal){return code===0&&signal===null?{reason:"rpc host exited on its own idle policy",exitCode:0}:{reason:`rpc host process exited unexpectedly (${code??signal})`,exitCode:1}}function noteChildExit(daemonDir,code,signal,childStartedAt,now=Date.now()){classifyChildExit(code,signal).exitCode!==0&&recordHostCrash(daemonDir,{at:new Date(now).toISOString(),...signal===null?{code:code??void 0}:{signal},uptimeMs:Math.max(0,now-childStartedAt),kind:"rpc-host",detection:"supervisor",...crashingRuntimeVersions()})}import{createHash}from"node:crypto";import{chmod,mkdir,writeFile}from"node:fs/promises";import{basename,join as join3,win32}from"node:path";var HOST_DAEMON_LAYOUT=2,HOST_DAEMON_DIR_ENV="SENPI_RPC_HOST_DAEMON_DIR",DIRECTORY_MODE=448,HOST_STATE_FILE_MODE=384;function daemonDirectoryName(socket,platform=process.platform){let canonical=platform==="win32"?win32.normalize(socket).toLowerCase():socket;return createHash("sha256").update(canonical,"utf8").digest("hex").slice(0,16)}function createHostDaemonPaths(target){let flatDir=join3(target.agentDir??getAgentDir(),"rpc-host-daemon");return{flatDir,layoutMarker:join3(flatDir,"layout.json"),legacyPidFile:join3(flatDir,"host.pid"),...hostDaemonDirectoryPaths(join3(flatDir,daemonDirectoryName(target.socket)))}}function hostDaemonDirectoryPaths(dir){return{dir,pointerFile:join3(dir,"host.pid"),lockFile:join3(dir,"daemon.lock"),settingsFile:join3(dir,"settings.json"),stderrLog:join3(dir,"stderr.log"),generationsDir:join3(dir,"generations"),reservationsDir:join3(dir,"reservations")}}function generationPaths(paths,instanceId){let dir=join3(paths.generationsDir,instanceId);return{dir,relativeDir:`generations/${instanceId}`,pidFile:join3(dir,"host.pid"),settingsFile:join3(dir,"settings.json"),scratchDir:join3(dir,"scratch")}}var HostDaemonStateError=class extends Error{constructor(path,cause){super(`RPC daemon state directory ${path} is not usable: ${cause instanceof Error?cause.message:cause}`,{cause}),this.name="HostDaemonStateError",this.path=path}};async function createDaemonDirectories(paths){try{await mkdir(paths.flatDir,{recursive:!0,mode:DIRECTORY_MODE});for(let directory of[paths.dir,paths.generationsDir,paths.reservationsDir])await mkdir(directory,{recursive:!0,mode:DIRECTORY_MODE}),await chmod(directory,DIRECTORY_MODE);await writeFile(paths.layoutMarker,`${JSON.stringify({layout:HOST_DAEMON_LAYOUT,dir:basename(paths.dir)})}
|
|
12
|
+
`,{mode:HOST_STATE_FILE_MODE})}catch(cause){throw new HostDaemonStateError(paths.dir,cause)}}async function createGenerationDirectory(generation){try{await mkdir(generation.scratchDir,{recursive:!0,mode:DIRECTORY_MODE}),await chmod(generation.dir,DIRECTORY_MODE)}catch(cause){throw new HostDaemonStateError(generation.dir,cause)}}import{rename as rename2,rm as rm3}from"node:fs/promises";import{readFile,writeFile as writeFile2}from"node:fs/promises";async function writeHostSettings(paths,settings){let generation=generationPaths(paths,settings.instanceId);await createGenerationDirectory(generation),await writeStateFile(paths.settingsFile,settings),await writeStateFile(generation.settingsFile,settings)}async function readHostSettings(paths){let parsed=parseJson(await readFileOrUndefined(paths.settingsFile));if(parsed)return{...typeof parsed.coldStart=="string"&&{coldStart:parsed.coldStart},...typeof parsed.idleExitMs=="number"&&{idleExitMs:parsed.idleExitMs}}}async function writeStateFile(path,content){try{await writeFile2(path,`${JSON.stringify(content)}
|
|
13
|
+
`,{mode:HOST_STATE_FILE_MODE})}catch(cause){throw new HostDaemonStateError(path,cause)}}async function readFileOrUndefined(path){try{return await readFile(path,"utf8")}catch(error){if(isNodeErrorCode2(error,"ENOENT")||isNodeErrorCode2(error,"ENOTDIR"))return;throw error}}function parseJson(text){if(text!==void 0)try{let parsed=JSON.parse(text);return isRecord2(parsed)?parsed:void 0}catch{return}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNodeErrorCode2(error,code){return error instanceof Error&&"code"in error&&error.code===code}import{readdir as readdir3,rm as rm2}from"node:fs/promises";import{readdir}from"node:fs/promises";import{readdirSync as readdirSync2,readFileSync as readFileSync3}from"node:fs";function supportedPlatform(platform){return platform==="darwin"||platform==="linux"?platform:void 0}async function loadProcessTableReader(platform=process.platform,options={}){let supported=supportedPlatform(platform);return supported===void 0||typeof globalThis.Bun>"u"?void 0:supported==="darwin"?await darwinReader(options):linuxReader}var KINFO_PROC_STRIDE=648,KINFO_PID_OFFSET=40,KINFO_PPID_OFFSET=560,KINFO_STAT_OFFSET=36,SZOMB=5,PROC_PIDTASKINFO=4,TASKINFO_RESIDENT_OFFSET=8,TABLE_START_BYTES=1<<20,TABLE_MAX_BYTES=32<<20;function parseKernelProcessTable(table,rowCount,residentKb){if(rowCount<=0||table.byteLength<rowCount*KINFO_PROC_STRIDE)return;let view=new DataView(table.buffer,table.byteOffset,table.byteLength),rows=[],selfSeen=!1;for(let index=0;index<rowCount;index++){let base=index*KINFO_PROC_STRIDE,pid=view.getUint32(base+KINFO_PID_OFFSET,!0);if(!Number.isInteger(pid)||pid<=0)continue;let ppid=view.getUint32(base+KINFO_PPID_OFFSET,!0),zombie=table[base+KINFO_STAT_OFFSET]===SZOMB;if(pid===process.pid){if(ppid!==process.ppid||zombie)return;selfSeen=!0}rows.push({pid,ppid,state:zombie?"Z":"U",rssKb:residentKb(pid)})}return selfSeen?rows:void 0}async function darwinReader(options){let{dlopen,FFIType,ptr}=await import("bun:ffi"),library=dlopen("libSystem.B.dylib",{sysctl:{args:[FFIType.ptr,FFIType.u32,FFIType.ptr,FFIType.ptr,FFIType.ptr,FFIType.i32],returns:FFIType.i32},proc_pidinfo:{args:[FFIType.i32,FFIType.i32,FFIType.u32,FFIType.ptr,FFIType.i32],returns:FFIType.i32}}),mib=new Int32Array([1,14,0]),none=new Uint8Array(1),requested=options.initialTableBytes,table=new Uint8Array(Number.isFinite(requested)&&requested!==void 0&&requested>0?Math.min(Math.floor(requested),TABLE_MAX_BYTES):TABLE_START_BYTES),length=new Uint32Array(1),taskInfo=new Uint8Array(256),taskView=new DataView(taskInfo.buffer),residentKb=pid=>(taskInfo.fill(0),library.symbols.proc_pidinfo(pid,PROC_PIDTASKINFO,0,ptr(taskInfo),taskInfo.byteLength)>0?Math.round(Number(taskView.getBigUint64(TASKINFO_RESIDENT_OFFSET,!0))/1024):0);return()=>{for(;;){if(length[0]=table.byteLength,library.symbols.sysctl(ptr(mib),mib.length,ptr(table),ptr(length),ptr(none),0)!==0){if(table.byteLength>=TABLE_MAX_BYTES)return;let reported=length[0]>table.byteLength?length[0]:0;table=new Uint8Array(Math.min(TABLE_MAX_BYTES,Math.max(table.byteLength*2,reported)));continue}return parseKernelProcessTable(table,Math.floor(length[0]/KINFO_PROC_STRIDE),residentKb)}}}function linuxReader(){let rows=[];for(let entry of readdirSync2("/proc")){let pid=Number(entry);if(!Number.isInteger(pid)||pid<=0)continue;let stat2;try{stat2=readFileSync3(`/proc/${pid}/stat`,"utf8")}catch{continue}let tail=stat2.slice(stat2.lastIndexOf(")")+2).split(" "),state=tail[0],ppid=Number(tail[1]);if(state===void 0||!Number.isInteger(ppid))continue;let rssPages=Number(tail[21]);rows.push({pid,ppid,state,rssKb:Number.isFinite(rssPages)?Math.round(rssPages*4):0})}return rows}var UNOBSERVED={rss_mb:null,open_fds:null,zombies:null},readers=new Map;function tableReader(platform){let cached=readers.get(platform);if(cached!==void 0)return cached;let loading=loadProcessTableReader(platform);return readers.set(platform,loading),loading}async function readHostProcessMetrics(pid,platform=process.platform){if(platform==="win32")return UNOBSERVED;let read=await tableReader(platform);if(read===void 0)return UNOBSERVED;let rows=read();if(rows===void 0)return UNOBSERVED;let tree=descendants(rows,pid);return tree.length===0?UNOBSERVED:{rss_mb:Math.round(tree.reduce((total,row)=>total+row.rssKb,0)/KILOBYTES_PER_MEGABYTE),open_fds:platform==="linux"?await openDescriptors(tree):null,zombies:tree.filter(row=>row.state.startsWith("Z")).length}}function descendants(rows,root){let tree=rows.filter(row=>row.pid===root);if(tree.length===0)return tree;for(let index=0;index<tree.length;index++){let parent=tree[index].pid;for(let row of rows)row.ppid===parent&&!tree.includes(row)&&tree.push(row)}return tree}var KILOBYTES_PER_MEGABYTE=1024;async function openDescriptors(tree){let total=0,counted=!1;for(let row of tree){let entries=await readdir(`/proc/${row.pid}/fd`).catch(()=>{});entries!==void 0&&(counted=!0,total+=entries.length)}return counted?total:null}import{createHash as createHash2}from"node:crypto";import{mkdir as mkdir2,readdir as readdir2,readFile as readFile2,rename,rm,writeFile as writeFile3}from"node:fs/promises";import{join as join4}from"node:path";var SESSION_PATH_RETRY_AFTER_MS=2e3;function reservationFile(dir,sessionPath){return join4(dir,`${createHash2("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`)}function createEndpointReservations(host){let told=process.env[HOST_DAEMON_DIR_ENV],dir=told!==void 0&&told.trim()!==""?told:host.socket===void 0?void 0:createHostDaemonPaths({socket:host.socket,agentDir:host.agentDir}).dir;if(dir!==void 0)return createSessionPathReservations({daemonDir:dir,instanceId:host.instanceId,...host.onFailure?{onFailure:host.onFailure}:{}})}function createSessionPathReservations(options){let paths=hostDaemonDirectoryPaths(options.daemonDir),dir=paths.reservationsDir,pid=options.pid??process.pid,startTime=readProcessStartTime(pid).then(value=>value??null,()=>null),held=new Set,report=message=>options.onFailure?.(message),publish=async(sessionPath,attached,stillHeld)=>{let owner={instanceId:options.instanceId,pid,processStartTime:await startTime,sessionPath,attached},file=reservationFile(dir,sessionPath);await mkdir2(dir,{recursive:!0,mode:448});let staging=`${file}.${pid}.tmp`;if(await writeFile3(staging,`${JSON.stringify(owner)}
|
|
14
|
+
`,{mode:384}),stillHeld?.()===!1){await rm(staging,{force:!0});return}await rename(staging,file)};return{async claim(sessionPath,attached=!0){let existing=await readOwner(reservationFile(dir,sessionPath));if(existing&&existing.pid!==pid){let standing=await standingOwner(existing,paths.pointerFile);if(standing)return standing}try{await publish(sessionPath,attached),held.add(sessionPath)}catch(cause){report(`session path reservation for ${sessionPath} could not be written (${errorMessage(cause)})`)}},release(sessionPath){held.delete(sessionPath)&&rm(reservationFile(dir,sessionPath),{force:!0}).catch(cause=>{report(`session path reservation for ${sessionPath} could not be removed (${errorMessage(cause)})`)})},setAttached(sessionPath,attached){held.has(sessionPath)&&publish(sessionPath,attached,()=>held.has(sessionPath)).catch(cause=>{report(`session path reservation for ${sessionPath} could not be updated (${errorMessage(cause)})`)})}}}async function readSessionPathClaims(dir){let entries=await readdir2(dir).catch(()=>[]),claims=[];for(let entry of entries){if(!entry.endsWith(".json"))continue;let file=join4(dir,entry),owner=await readOwner(file);owner&&claims.push({file,owner})}return claims}async function standingOwner(owner,pointerFile){if(!await claimOwnerIsLive(owner))return;let current=await currentInstanceId(pointerFile)===owner.instanceId;return current||owner.attached!==!1?{...owner,current}:void 0}async function currentInstanceId(pointerFile){let pointer=parseJson(await readFileOrUndefined(pointerFile).catch(()=>{}));return typeof pointer?.instance_id=="string"?pointer.instance_id:void 0}async function readOwner(file){let parsed;try{parsed=JSON.parse(await readFile2(file,"utf8"))}catch{return}if(typeof parsed!="object"||parsed===null)return;let{instanceId,pid,processStartTime,sessionPath,attached}=parsed;if(!(typeof instanceId!="string"||typeof pid!="number"||typeof sessionPath!="string"))return{instanceId,pid,processStartTime:typeof processStartTime=="string"?processStartTime:null,sessionPath,...typeof attached=="boolean"?{attached}:{}}}async function claimOwnerIsLive(owner){if(!processIsLive(owner.pid))return!1;if(owner.processStartTime===null)return!0;let current=await readProcessStartTime(owner.pid).catch(()=>{});return current===void 0||current===owner.processStartTime}function errorMessage(cause){return cause instanceof Error?cause.message:String(cause)}async function pruneDeadGenerations(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile).catch(()=>{})),pointedAt=typeof pointer?.instance_id=="string"?pointer.instance_id:void 0,generations=[];for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){let record=parseJson(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));typeof record?.pid!="number"||processIsLive(record.pid)||(await rm2(generationPaths(paths,instanceId).dir,{recursive:!0,force:!0}).catch(()=>{}),generations.push(instanceId))}let pointerRemoved=pointedAt!==void 0&&generations.includes(pointedAt);pointerRemoved&&await rm2(paths.pointerFile,{force:!0}).catch(()=>{});let claims=[];for(let claim of await readSessionPathClaims(paths.reservationsDir))await claimOwnerIsLive(claim.owner)||(await rm2(claim.file,{force:!0}).catch(()=>{}),claims.push(claim.owner.sessionPath));return{generations,claims,pointer:pointerRemoved}}async function readGenerationRows(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile).catch(()=>{})),currentId=typeof pointer?.instance_id=="string"?pointer.instance_id:void 0,claims=await readSessionPathClaims(paths.reservationsDir),rows=[];for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){let record=parseJson(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));typeof record?.pid!="number"||!processIsLive(record.pid)||rows.push({instanceId,generation:typeof record.generation=="number"?record.generation:0,pid:record.pid,engineVersion:typeof record.engineVersion=="string"?record.engineVersion:null,rss_mb:(await readHostProcessMetrics(record.pid)).rss_mb,sessions:claims.filter(claim=>claim.owner.instanceId===instanceId).length,current:instanceId===currentId,alive:!0})}return rows.sort((left,right)=>left.generation-right.generation)}async function readHostRegistration(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile));if(!pointer||typeof pointer.instance_id!="string")return;let text=await readFileOrUndefined(generationPaths(paths,pointer.instance_id).pidFile),record=text===void 0?void 0:parseDaemonPidFile(text);if(record===void 0)return;let parsed=parseJson(text)??{},writer=parseWriter(parsed);return{record,...writer&&{writer},...typeof parsed.socket=="string"&&{socket:parsed.socket},instanceId:pointer.instance_id,generation:typeof parsed.generation=="number"?parsed.generation:0}}async function writeHostRegistration(paths,registration){await pruneDeadGenerations(paths);let generation=generationPaths(paths,registration.instanceId),writer={pid:process.pid,startTime:await thisProcessStartTime()},build=engineBuildIdentity();await createGenerationDirectory(generation),await writeStateFile(generation.pidFile,{...registration.record,instance_id:registration.instanceId,generation:registration.generation,engineVersion:build.text,engineOrdinal:build.ordinal,launchProfileId:registration.launchProfileId,socket:registration.socket,writer}),await writeStateFile(`${paths.pointerFile}.${process.pid}.tmp`,{layout:HOST_DAEMON_LAYOUT,instance_id:registration.instanceId,generation_dir:generation.relativeDir,writer}),await rename2(`${paths.pointerFile}.${process.pid}.tmp`,paths.pointerFile)}async function clearHostRegistration(paths){let pointer=parseJson(await readFileOrUndefined(paths.pointerFile));typeof pointer?.instance_id=="string"&&await rm3(generationPaths(paths,pointer.instance_id).dir,{recursive:!0,force:!0}),await rm3(paths.pointerFile,{force:!0}),await rm3(paths.settingsFile,{force:!0})}async function releaseGeneration(paths,owner){let generation=generationPaths(paths,owner.instanceId),record=parseDaemonPidFile(await readFileOrUndefined(generation.pidFile)??"");if(record!==void 0&&record.pid!==owner.pid)return;parseJson(await readFileOrUndefined(paths.pointerFile))?.instance_id===owner.instanceId&&(await rm3(paths.pointerFile,{force:!0}),await rm3(paths.settingsFile,{force:!0})),await rm3(generation.dir,{recursive:!0,force:!0})}async function readLegacyHostRecord(paths){let text=await readFileOrUndefined(paths.legacyPidFile);return text===void 0?void 0:parseDaemonPidFile(text)}async function provenOwner(registered,socket){let record=registered?.record;if(!record||record.processStartTime===null||registered?.socket!==void 0&®istered.socket!==socket)return;let identity={pid:record.pid,processStartTime:record.processStartTime};return await processMatchesPidFile(identity,readProcessStartTime).catch(()=>!1)?{...identity,instanceId:registered.instanceId}:void 0}async function legacyHostIsLive(paths,probe){let record=await readLegacyHostRecord(paths);if(record===void 0)return!1;try{return await processMatchesPidFile(record,probe)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}}async function writtenByThisProcess(writer){return writer===void 0||writer.pid!==process.pid||writer.startTime===null?!1:writer.startTime===await thisProcessStartTime()}var selfStartTime;function thisProcessStartTime(){return selfStartTime??=readProcessStartTime(process.pid).then(value=>value??null,()=>null),selfStartTime}function parseWriter(parsed){if(!isRecord2(parsed.writer)||typeof parsed.writer.pid!="number")return;let{pid,startTime}=parsed.writer;return{pid,startTime:typeof startTime=="string"?startTime:null}}import{mkdir as mkdir3,readFile as readFile3,rename as rename3,stat,unlink,writeFile as writeFile4}from"node:fs/promises";import{dirname}from"node:path";var PUBLIC_SOCKET_IDENTITY_FILE="public-socket.owner",SOCKET_IDENTITY_WAIT_MS=3e4,MAX_SOCKET_PATH_BYTES=103;function generationBindPath(publicSocket,generation){return`${publicSocket}.next-${generation}`}function sameSocketIdentity(a,b){return a.dev===b.dev&&a.ino===b.ino}async function statSocketIdentity(socketPath){try{let{dev,ino}=await stat(socketPath);return{dev,ino}}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}}async function classifyEndpointOwnership(socketPath,identity){if(identity===void 0||process.platform==="win32"||socketPath.startsWith("\0"))return"unknown";let current;try{current=await statSocketIdentity(socketPath)}catch{return"unknown"}return current===void 0?"absent":sameSocketIdentity(current,identity)?"held":"replaced"}async function socketEntryReplaced(socketPath,identity){return await classifyEndpointOwnership(socketPath,identity)==="replaced"}async function writeSocketIdentityFile(path,identity){await mkdir3(dirname(path),{recursive:!0,mode:448});let tmpPath=`${path}.${process.pid}.tmp`;await writeFile4(tmpPath,`${JSON.stringify(identity)}
|
|
15
|
+
`,{mode:384}),await rename3(tmpPath,path)}async function readSocketIdentityFile(path){let raw;try{raw=await readFile3(path,"utf8")}catch(cause){if(isNodeErrorCode3(cause,"ENOENT"))return;throw cause}let parsed;try{parsed=JSON.parse(raw)}catch{return}if(!(typeof parsed!="object"||parsed===null||typeof parsed.dev!="number"||typeof parsed.ino!="number"))return{dev:parsed.dev,ino:parsed.ino}}async function waitForSocketIdentityFile(path,timeoutMs=SOCKET_IDENTITY_WAIT_MS,intervalMs=25){let deadline=Date.now()+timeoutMs;for(;;){let identity=await readSocketIdentityFile(path);if(identity!==void 0)return identity;if(Date.now()>=deadline)return;await delayUnrefed(intervalMs)}}async function unlinkOwnedSocket(socketPath,identity,log){if(process.platform==="win32"||socketPath.startsWith("\0"))return;let current;try{current=await statSocketIdentity(socketPath)}catch(cause){log(`socket ${socketPath} ownership could not be verified (${errorMessage2(cause)}); leaving it`);return}if(current!==void 0){if(identity===void 0){log(`socket path ${socketPath} ownership unknown; leaving it`);return}if(!sameSocketIdentity(current,identity)){log(`socket path ${socketPath} now owned by another host; leaving it`);return}try{await unlink(socketPath)}catch(cause){isNodeErrorCode3(cause,"ENOENT")||log(`socket ${socketPath} removal failed (${errorMessage2(cause)})`)}}}async function shieldSocketDuringClose(socketPath,close){if(process.platform==="win32"||socketPath.startsWith("\0"))return close();let shieldPath=`${socketPath}.shield-${process.pid}`,shielded=!1;try{await statSocketIdentity(socketPath)!==void 0&&(await rename3(socketPath,shieldPath),shielded=!0)}catch{}try{await close()}finally{if(shielded)try{await rename3(shieldPath,socketPath)}catch{}}}function delayUnrefed(ms){return new Promise(resolve2=>{setTimeout(resolve2,ms).unref?.()})}function errorMessage2(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode3(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}var SUPERSESSION_POLL_MS=1e3,ABSENT_CONFIRMATIONS=3;function watchForSupersession(endpoint,onLost){if(endpoint.identity===void 0||process.platform==="win32")return()=>{};let absentPolls=0,lost=!1,lose=loss=>{lost||(lost=!0,stop(),onLost(loss))},timer=setInterval(()=>{endpoint.settled?.()!==!0&&classifyEndpointOwnership(endpoint.path,endpoint.identity).then(ownership=>{if(endpoint.settled?.()!==!0)switch(ownership){case"replaced":lose("replaced");return;case"absent":if(absentPolls+=1,absentPolls<ABSENT_CONFIRMATIONS)return;lose("absent");return;case"held":case"unknown":absentPolls=0;return}},ignore)},SUPERSESSION_POLL_MS);timer.unref?.();let stop=()=>clearInterval(timer);return stop}function ignore(){}import{rmSync as rmSync2}from"node:fs";import{rm as rm4}from"node:fs/promises";import{Socket}from"node:net";var HOST_WATCH_FD_ENV="SENPI_RPC_HOST_WATCH_FD",HOST_SCRATCH_DIR_ENV="SENPI_RPC_HOST_SCRATCH_DIR",HOST_PUBLIC_SOCKET_ENV="SENPI_RPC_HOST_PUBLIC_SOCKET",HOST_WATCH_PPID_ENV="SENPI_RPC_HOST_WATCH_PPID",HOST_WATCH_PPID_INTERVAL_MS=250,HOST_CLEANUP_PATHS_ENV="SENPI_RPC_HOST_CLEANUP_PATHS";function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function readHostWatchdogConfig(env=process.env){let fd=parsePositiveInteger(env[HOST_WATCH_FD_ENV]),ppid=parsePositiveInteger(env[HOST_WATCH_PPID_ENV]);if(fd===void 0&&ppid===void 0)return;let scratchDir=env[HOST_SCRATCH_DIR_ENV],cleanupPaths=env[HOST_CLEANUP_PATHS_ENV]?.split(`
|
|
16
|
+
`).filter(Boolean),publicSocket=env[HOST_PUBLIC_SOCKET_ENV];return{fd,ppid,scratchDir:scratchDir===void 0||scratchDir===""?void 0:scratchDir,cleanupPaths,publicSocket:publicSocket===""?void 0:publicSocket}}function readHostWatchdogConfigFromBrandEnv(){return readHostWatchdogConfig({[HOST_WATCH_FD_ENV]:process.env[HOST_WATCH_FD_ENV]??envValue("RPC_HOST_WATCH_FD"),[HOST_WATCH_PPID_ENV]:process.env[HOST_WATCH_PPID_ENV]??envValue("RPC_HOST_WATCH_PPID"),[HOST_SCRATCH_DIR_ENV]:process.env[HOST_SCRATCH_DIR_ENV]??envValue("RPC_HOST_SCRATCH_DIR"),[HOST_PUBLIC_SOCKET_ENV]:process.env[HOST_PUBLIC_SOCKET_ENV]??envValue("RPC_HOST_PUBLIC_SOCKET"),[HOST_CLEANUP_PATHS_ENV]:process.env[HOST_CLEANUP_PATHS_ENV]??envValue("RPC_HOST_CLEANUP_PATHS")})}function armHostWatchdog(config,onSupervisorGone){if(!config)return()=>{};let fire=reason=>{disarm();let captured=captureBeforeCleanup(config);if(process.platform==="win32"){let cleanup=captured.then(()=>cleanupWatchdogPaths(config));onSupervisorGone(reason,cleanup)}else captured.then(()=>cleanupWatchdogPaths(config)).finally(()=>onSupervisorGone(reason))},disarmers=[],disarm=()=>{for(let stop of disarmers.splice(0))stop()};return config.fd!==void 0&&disarmers.push(watchFdForEof(config.fd,fire)),config.ppid!==void 0&&disarmers.push(watchPpid(config.ppid,fire)),disarm}function watchFdForEof(fd,fire){let stream,streamFailed=!1,fired=!1,fireOnce=reason=>{fired||(fired=!0,fire(reason))};try{stream=new Socket({fd,readable:!0,writable:!1})}catch{return()=>{}}stream.resume();let onEnd=()=>fireOnce(`supervisor pipe fd ${fd} closed`),onClose=()=>{streamFailed||onEnd()},onError=()=>{streamFailed=!0};return stream.once("end",onEnd),process.platform==="win32"&&stream.once("close",onClose),stream.once("error",onError),()=>{stream.off("end",onEnd),stream.off("close",onClose),stream.off("error",onError),stream.destroy()}}function watchPpid(supervisorPid,fire){if(supervisorPid===process.pid)return()=>{};let timer=setInterval(()=>{if(!processAlive(supervisorPid)){fire(`supervisor pid ${supervisorPid} is gone (ppid=${process.ppid})`);return}process.ppid!==supervisorPid&&fire(`supervisor pid ${supervisorPid} is gone (ppid=${process.ppid})`)},HOST_WATCH_PPID_INTERVAL_MS);return timer.unref?.(),()=>clearInterval(timer)}function processAlive(pid){try{return process.kill(pid,0),!0}catch(cause){return cause instanceof Error&&"code"in cause&&cause.code!=="ESRCH"}}function captureBeforeCleanup(config){return config.beforeCleanup===void 0?Promise.resolve():Promise.resolve().then(config.beforeCleanup).catch(()=>{})}async function cleanupWatchdogPaths(config){let paths=[...config.cleanupPaths??[],...config.scratchDir?[config.scratchDir]:[]];if(process.platform==="win32"){for(let path of paths)try{rmSync2(path,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}return}await Promise.all(paths.map(async path=>{try{await rm4(path,{recursive:!0,force:!0})}catch{}}))}function activeTurnsForIdleDecision(input){return input.healthy?input.observedBusy:input.unhealthySince===void 0||input.now-input.unhealthySince<input.unknownGraceMs?1:0}function createObserverLink(options){let current,healthy=!1,unhealthySince,retry,armRetry=()=>{retry!==void 0||options.settled()||(retry=options.setTimer(()=>{retry=void 0,open().catch(armRetry)},options.retryDelayMs))};async function open(){let socket=await options.open();current=socket,healthy=!0,unhealthySince=void 0,socket.onLost(()=>{current!==socket||options.settled()||(healthy=!1,unhealthySince??=options.now(),current=void 0,armRetry())})}return{open,healthy:()=>healthy,unhealthySince:()=>unhealthySince,stop:()=>{retry?.cancel(),retry=void 0,current=void 0}}}import{createHash as createHash3,randomBytes,timingSafeEqual}from"node:crypto";import{chmod as chmod2,mkdir as mkdir4,readFile as readFile4,writeFile as writeFile5}from"node:fs/promises";import{dirname as dirname2,win32 as win322}from"node:path";var WINDOWS_PIPE_PREFIX="\\\\.\\pipe\\senpi-rpc-",SOCKET_SECRET_BYTES=32,SOCKET_SECRET_SUFFIX=".secret",SOCKET_SECRET_FILE_ENV="SENPI_RPC_SOCKET_SECRET_FILE",SOCKET_HANDSHAKE_TIMEOUT_MS=2e3;function socketSecretPath(logicalPath){if(logicalPath.toLowerCase().startsWith("\\\\.\\pipe\\"))throw new Error(`Windows RPC named-pipe addresses need a logical filesystem path for their secret: ${logicalPath}`);return`${logicalPath}${SOCKET_SECRET_SUFFIX}`}async function ensureSocketSecret(path){try{let existing=await readFile4(path);if(existing.length===SOCKET_SECRET_BYTES)return existing}catch(error){if(!isNodeErrorCode4(error,"ENOENT"))throw error}return createSocketSecret(path)}async function createSocketSecret(path){await mkdir4(dirname2(path),{recursive:!0});let secret=randomBytes(SOCKET_SECRET_BYTES);return await writeFile5(path,secret,{mode:384}),await chmod2(path,384),secret}async function readSocketSecret(path){let secret=await readFile4(path);if(secret.length!==SOCKET_SECRET_BYTES)throw new Error(`invalid RPC socket secret: ${path}`);return secret}function resolveSocketTransportAddress(socketPath,platform,secret){if(platform!=="win32"||socketPath.toLowerCase().startsWith("\\\\.\\pipe\\"))return socketPath;if(!/^[a-zA-Z]:[\\/]/.test(socketPath)&&!/^\\\\[^/]/.test(socketPath))throw new Error(`Windows RPC socket path must be drive-qualified or UNC: ${socketPath}`);let canonical=win322.normalize(socketPath).toLowerCase(),identity=Buffer.concat([Buffer.from(canonical,"utf8"),Buffer.from(secret??[])]),name=createHash3("sha256").update(identity).digest("hex").slice(0,32);return`${WINDOWS_PIPE_PREFIX}${name}`}function authenticateSocket(socket,secret,onAuthenticated){let received=Buffer.alloc(0),finish=()=>{clearTimeout(timer),socket.off("data",onData),socket.off("error",onError)},onError=()=>{finish(),socket.destroy()},timer=setTimeout(()=>{finish(),socket.destroy()},SOCKET_HANDSHAKE_TIMEOUT_MS),onData=chunk=>{if(received=Buffer.concat([received,chunk]),received.length<secret.length)return;if(finish(),!timingSafeEqual(received.subarray(0,secret.length),Buffer.from(secret))){socket.destroy();return}let remainder=received.subarray(secret.length);remainder.length>0&&socket.unshift(remainder),onAuthenticated()};socket.on("data",onData),socket.once("error",onError),socket.once("close",finish)}function sendSocketHandshake(socket,secret){socket.write(Buffer.from(secret))}function isNodeErrorCode4(error,code){return error instanceof Error&&"code"in error&&error.code===code}var HOST_COLD_START_ENV="SENPI_RPC_HOST_COLD_START",HOST_IDLE_EXIT_MS_ENV="SENPI_RPC_HOST_IDLE_EXIT_MS",DEFAULT_HOST_IDLE_EXIT_MS=15*6e4,HANDOFF_GRACE_MS_ENV="SENPI_RPC_HANDOFF_GRACE_MS",DEFAULT_HANDOFF_GRACE_MS=10*6e4,CHILD_STOP_TIMEOUT_MS=5e3,WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS=2e3,CHILD_WATCH_FD=3;async function createInternalSocketPath(baseDir=tmpdir(),platform=process.platform){if(platform==="win32"){let dir2=join5(baseDir,`internal-${randomUUID()}`);return await mkdir5(dir2,{recursive:!0,mode:448}),{socket:`\\\\.\\pipe\\senpi-rpc-internal-${randomUUID()}`,dir:dir2,secretPath:join5(dir2,"secret")}}let dir=join5(tmpdir(),`senpi-rpc-host-internal-${randomUUID().slice(0,8)}`);return await mkdir5(dir,{recursive:!1,mode:448}),await writeFile6(join5(dir,".owner"),JSON.stringify({pid:process.pid,processStartTime:await readProcessStartTime(process.pid),createdAt:Date.now()}),{mode:384}),{socket:join5(dir,"host.sock"),dir,secretPath:join5(dir,".secret")}}function parseColdStart(value){return value==="transient"||value==="persistent"?value:void 0}function parseIdleExitMs(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}function resolveHostPolicy(settings,env){let record=isRecord3(settings)?settings:{},coldStart=parseColdStart(env[HOST_COLD_START_ENV])??parseColdStart(asOptionalString(record.coldStart))??"transient",idleExitMs=parseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV])??parseIdleExitMs(asOptionalString(record.idleExitMs))??DEFAULT_HOST_IDLE_EXIT_MS;return{coldStart,idleExitMs}}var IdleExitDecider=class{constructor(idleExitMs,now=Date.now){this.idleExitMs=idleExitMs,this.now=now}update(activity){return activity.connections>0||activity.activeTurns>0?(this.idleSince=void 0,"active"):this.idleExitMs===Number.POSITIVE_INFINITY?"idle":this.idleSince===void 0?(this.idleSince=this.now(),"idle"):this.now()-this.idleSince>=this.idleExitMs?"exit":"idle"}},INTERNAL_SUPERVISOR_FLAG="--internal-rpc-host-supervisor",INJECTABLE_PREFIX_FLAGS=new Set(["--extension"]);function findInternalSupervisorArgs(argv){for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg===INTERNAL_SUPERVISOR_FLAG)return argv.slice(index+1);if(!INJECTABLE_PREFIX_FLAGS.has(arg)||index+1>=argv.length)return;index++}}function parseSupervisorArgs(argv){let hostArgs=[],socket,childCommand,childArgs,agentDir,bindSocket,replaceIdentity;for(let index=0;index<argv.length;index++){let arg=argv[index];if(arg==="--socket"&&index+1<argv.length){socket=argv[++index];continue}if(arg==="--child-command"&&index+1<argv.length){childCommand=argv[++index];continue}if(arg==="--child-args"&&index+1<argv.length){try{let parsed=JSON.parse(argv[++index]);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(childArgs=parsed)}catch{return}continue}if(arg==="--agent-dir"&&index+1<argv.length){agentDir=argv[++index];continue}if(arg==="--bind"&&index+1<argv.length){bindSocket=argv[++index];continue}if(arg==="--replace"&&index+1<argv.length){replaceIdentity=parseSocketIdentity(argv[++index]);continue}hostArgs.push(arg)}return socket===void 0?void 0:{socket,hostArgs,childCommand,childArgs,agentDir,bindSocket,replaceIdentity}}function parseSocketIdentity(value){let match=/^(\d+):(\d+)$/.exec(value);return match?{dev:Number(match[1]),ino:Number(match[2])}:void 0}function resolveCliMainPath(){let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",unbundled=resolve(dirname3(modulePath),"..","..",`cli-main${extension}`);return existsSync(unbundled)?unbundled:resolveDeclaredCliEntry(modulePath)??unbundled}function resolveDeclaredCliEntry(modulePath){let dir=dirname3(modulePath);for(let depth=0;depth<8;depth+=1){let manifestPath=resolve(dir,"package.json");if(existsSync(manifestPath)){try{let declared=JSON.parse(readFileSync4(manifestPath,"utf8")).bin,candidates=typeof declared=="string"?[declared]:Object.values(declared??{});for(let candidate of candidates){let entry=resolve(dir,candidate);if(existsSync(entry))return entry}}catch{}return}let parent=dirname3(dir);if(parent===dir)return;dir=parent}}function resolveHostChildLaunch(launch,internalSocket,compiled=isBunBinary){return launch.childCommand?{command:launch.childCommand,args:[...launch.childArgs??[],"--listen",`unix://${internalSocket}`]}:{command:process.execPath,args:[...compiled?[]:[...process.execArgv,resolveCliMainPath()],"--mode","rpc","--multi-session","--listen",`unix://${internalSocket}`,...launch.hostArgs]}}function quoteWindowsShellArg(value){return`"${value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1").replace(/([()%!^"<>&|;,])/g,"^$1")}"`}function spawnableChildLaunch(launch,platform=process.platform){let extension=extname(launch.command).toLowerCase();return platform!=="win32"||extension!==".cmd"&&extension!==".bat"?{...launch,shell:!1}:{command:quoteWindowsShellArg(launch.command),args:launch.args.map(quoteWindowsShellArg),shell:!0}}async function runHostSupervisor(launch){let paths=createHostDaemonPaths({socket:launch.socket,agentDir:launch.agentDir??getAgentDir()}),told=process.env[HOST_INSTANCE_ID_ENV],instanceId=told!==void 0&&told.trim()!==""?told:randomUUID(),generation=generationPaths(paths,instanceId),policy=resolveHostPolicy(await readSettingsFile(paths.settingsFile),process.env),publicSocket=launch.socket,bindSocket=launch.bindSocket??publicSocket,successor=launch.bindSocket!==void 0,publicSecret=process.platform==="win32"?await ensurePublicSocketSecret(publicSocket):void 0,internal=await createInternalSocketPath(paths.dir),internalSocket=internal.socket,internalSecretPath=internal.secretPath??socketSecretPath(internalSocket),internalSecret=process.platform==="win32"?await createSocketSecret(internalSecretPath):void 0,clientSockets=new Set,busySessions=new Map,observerSocket,observerLink=createObserverLink({open:async()=>{let secret=internalSecret,next=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,secret));return secret&&sendSocketHandshake(next,secret),await waitForConnect(next,5e3),observerSocket=next,attachJsonlLineReader(next,observeHostEvent,{maxLineLength:MAX_RPC_LINE_CHARACTERS}),{onLost:handler=>{next.once("close",handler),next.once("error",handler)}}},settled:()=>shuttingDown,retryDelayMs:250,now:Date.now,setTimer:(run,ms)=>{let timer=setTimeout(run,ms);return timer.unref?.(),{cancel:()=>clearTimeout(timer)}}}),childExitWatchTimer,stopSupersessionWatch,shuttingDown=!1,draining=!1,handoffGraceTimer,shutdownPromise,childLaunch=spawnableChildLaunch(resolveHostChildLaunch(launch,internalSocket)),child=spawn(childLaunch.command,childLaunch.args,{env:{...process.env,...launch.agentDir?{SENPI_CODING_AGENT_DIR:launch.agentDir}:{},[HOST_DAEMON_DIR_ENV]:paths.dir,[HOST_INSTANCE_ID_ENV]:instanceId,[HOST_WATCH_FD_ENV]:String(CHILD_WATCH_FD),[HOST_WATCH_PPID_ENV]:String(process.pid),...internal.dir?{[HOST_SCRATCH_DIR_ENV]:internal.dir}:{},...internalSecret?{[SOCKET_SECRET_FILE_ENV]:internalSecretPath}:{},[HOST_CLEANUP_PATHS_ENV]:[...successor?[]:[paths.pointerFile,generation.pidFile,paths.settingsFile],...process.platform==="win32"?[publicSocket]:[]].join(`
|
|
17
|
+
`),...process.platform==="win32"?{}:{[HOST_PUBLIC_SOCKET_ENV]:publicSocket}},shell:childLaunch.shell,stdio:["ignore","ignore","inherit","pipe"],windowsHide:!0}),childStartedAt=Date.now();child.stdio[CHILD_WATCH_FD]?.on("error",()=>{}),child.once("exit",(code,signal)=>{if(shuttingDown)return;let{reason,exitCode}=classifyChildExit(code,signal);noteChildExit(paths.dir,code,signal,childStartedAt),shutdown(reason,exitCode)});let server=createServer(client=>{let accept=()=>{if(shuttingDown||draining){client.destroy();return}let internal2=createConnection(resolveSocketTransportAddress(internalSocket,process.platform,internalSecret));internalSecret&&sendSocketHandshake(internal2,internalSecret),clientSockets.add(client),decider.update(currentActivity());let detach=()=>{clientSockets.delete(client),decider.update(currentActivity()),internal2.destroy(),client.destroy()};client.pipe(internal2),internal2.pipe(client),client.once("close",detach),client.once("error",detach),internal2.once("end",()=>client.end(()=>client.destroy())),internal2.once("close",()=>{internal2.readableEnded||detach()}),internal2.once("error",detach)};publicSecret?authenticateSocket(client,publicSecret,accept):accept()});server.once("error",cause=>{shuttingDown||shutdown(`public socket listener failed: ${errorMessage3(cause)}`,1)});let decider=new IdleExitDecider(policy.coldStart==="persistent"?Number.POSITIVE_INFINITY:policy.idleExitMs),tickIntervalMs=Math.max(20,Math.min(1e3,policy.idleExitMs/4)),ticker=setInterval(()=>{!draining&&decider.update(currentActivity())==="exit"&&shutdown("idle",0)},tickIntervalMs);function currentActivity(){return{connections:clientSockets.size,activeTurns:activeTurnsForIdleDecision({healthy:observerLink.healthy(),unhealthySince:observerLink.unhealthySince(),now:Date.now(),unknownGraceMs:decider.idleExitMs,observedBusy:countBusySessions()})}}function countBusySessions(){let busy=0;for(let count of busySessions.values())count>0&&busy++;return busy}function observeHostEvent(line){let event;try{event=JSON.parse(line)}catch{return}if(typeof event!="object"||event===null)return;let{type,sessionId}=event;if(typeof sessionId=="string"){if(type==="agent_start")busySessions.set(sessionId,(busySessions.get(sessionId)??0)+1);else if(type==="agent_settled")busySessions.set(sessionId,Math.max(0,(busySessions.get(sessionId)??1)-1));else return;decider.update(currentActivity())}}async function shutdown(reason,exitCode){return shutdownPromise??=performShutdown(reason,exitCode),shutdownPromise}async function performShutdown(reason,exitCode){shuttingDown&&process.exit(exitCode),shuttingDown=!0,clearInterval(ticker),handoffGraceTimer&&clearTimeout(handoffGraceTimer),childExitWatchTimer&&clearInterval(childExitWatchTimer),stopSupersessionWatch?.();let hardExit=process.platform==="win32"?setTimeout(()=>process.exit(exitCode),WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS):void 0;try{writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);for(let client of clientSockets)client.destroy();draining||await shieldSocketDuringClose(publicSocket,()=>closeServer(server)),internal.dir&&await rm5(internal.dir,{recursive:!0,force:!0}),await stopChild(child),observerLink.stop(),observerSocket?.destroy(),publicSocketOwned&&process.platform!=="win32"&&await unlinkOwnedSocket(publicSocket,publicSocketIdentity,supervisorLog),await releaseGeneration(paths,{instanceId,pid:process.pid})}finally{hardExit&&clearTimeout(hardExit),process.exit(exitCode)}}let publicSocketOwned=!1,publicSocketIdentity;function supervisorLog(message){writeStderrLine(`senpi rpc host supervisor: ${message}`)}function drainForHandoff(){if(draining||shuttingDown)return;draining=!0,supervisorLog("draining into the next generation");let graceMs=parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV])??DEFAULT_HANDOFF_GRACE_MS;handoffGraceTimer=setTimeout(()=>{supervisorLog(JSON.stringify({event:"handoff_grace_expired",graceMs})),requestChildDrain()},graceMs),handoffGraceTimer.unref(),requestChildDrain()}function requestChildDrain(){if(child.pid!==void 0&&child.exitCode===null&&child.signalCode===null)try{process.kill(child.pid,"SIGUSR1")}catch(cause){supervisorLog(`could not ask the host to drain: ${errorMessage3(cause)}`)}}registerSupervisorSignals(shutdown,drainForHandoff);try{await waitForListener(internalSocket,3e4,internalSecret),await observerLink.open(),await prepareSocketPath(bindSocket),await listen(server,bindSocket,publicSecret),publicSocketOwned=!0,successor&&await adoptPublicSocket(bindSocket,publicSocket,launch.replaceIdentity),publicSocketIdentity=await statSocketIdentity(publicSocket),publicSocketIdentity&&internal.dir&&await writeSocketIdentityFile(join5(internal.dir,PUBLIC_SOCKET_IDENTITY_FILE),publicSocketIdentity),stopSupersessionWatch=watchForSupersession({path:publicSocket,identity:publicSocketIdentity,settled:()=>shuttingDown||draining},loss=>{supervisorLog(loss==="absent"?"the public socket entry is gone; nothing can reach this generation; draining":"another generation owns the public socket; draining this one"),drainForHandoff()})}catch(cause){await shutdown(`startup failed: ${errorMessage3(cause)}`,1)}if(process.platform==="win32"&&child.pid!==void 0){let childStartTime=await readProcessStartTime(child.pid,process.platform,1e3).catch(()=>{}),missingIdentityChecks=0,checkingChildIdentity=!1;childExitWatchTimer=setInterval(()=>{shuttingDown||checkingChildIdentity||child.exitCode!==null||child.signalCode!==null||(checkingChildIdentity=!0,readProcessStartTime(child.pid,process.platform,1e3).then(currentStartTime=>{currentStartTime===void 0&&!processIsLive(child.pid)?missingIdentityChecks++:currentStartTime!==void 0&&(missingIdentityChecks=0),(childStartTime!==void 0&¤tStartTime!==void 0&¤tStartTime!==childStartTime||missingIdentityChecks>=2)&&shutdown("rpc host child exit observed by identity watchdog",0)}).catch(()=>{}).finally(()=>{checkingChildIdentity=!1}))},500),childExitWatchTimer.unref?.()}writeStderrLine(`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${policy.coldStart==="persistent"?"never":String(policy.idleExitMs)})`),await new Promise(()=>{})}function registerSupervisorSignals(shutdown,drain){for(let signal of process.platform==="win32"?["SIGTERM"]:["SIGTERM","SIGHUP"])process.on(signal,()=>{shutdown(`signal:${signal}`,signal==="SIGHUP"?129:143)});process.platform!=="win32"&&process.on("SIGUSR1",drain)}async function adoptPublicSocket(bindSocket,publicSocket,expected){if(expected===void 0)throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);let current=await statSocketIdentity(publicSocket);if(current===void 0||current.dev!==expected.dev||current.ino!==expected.ino)throw new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);await rename4(bindSocket,publicSocket)}async function ensurePublicSocketSecret(publicSocket){let secretPath=socketSecretPath(publicSocket);try{return await ensureSocketSecret(secretPath)}catch(cause){throw new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`,{cause})}}async function readSettingsFile(settingsFile){try{return JSON.parse(await readFile5(settingsFile,"utf8"))}catch{return}}async function stopChild(child){if(!(child.exitCode!==null||child.signalCode!==null)){try{child.kill("SIGTERM")}catch{return}if(!await waitForChildExit(child,CHILD_STOP_TIMEOUT_MS)){try{child.kill("SIGKILL")}catch{return}await waitForChildExit(child,2e3)}}}function waitForChildExit(child,timeoutMs){return child.exitCode!==null||child.signalCode!==null?Promise.resolve(!0):new Promise(resolve2=>{let timer=setTimeout(()=>{child.off("exit",onExit2),resolve2(!1)},timeoutMs),onExit2=()=>{clearTimeout(timer),resolve2(!0)};child.once("exit",onExit2)})}async function waitForListener(socketPath,timeoutMs,secret){let deadline=Date.now()+timeoutMs;for(;Date.now()<=deadline;){if(await canConnect(socketPath,secret))return;await delay2(50)}throw new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`)}function canConnect(socketPath,secret){return new Promise(resolve2=>{let socket=createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret));secret&&sendSocketHandshake(socket,secret);let settle=value=>{socket.destroy(),resolve2(value)};socket.once("connect",()=>settle(!0)),socket.once("error",()=>settle(!1))})}function waitForConnect(socket,timeoutMs){return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{cleanup(),reject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`))},timeoutMs),onConnect=()=>{cleanup(),resolve2()},onError=cause=>{cleanup(),reject(cause)},cleanup=()=>{clearTimeout(timer),socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)})}async function prepareSocketPath(socketPath){if(process.platform!=="win32"){if(Buffer.byteLength(socketPath)>MAX_SOCKET_PATH_BYTES)throw new Error(`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`);await mkdir5(dirname3(socketPath),{recursive:!0,mode:448});try{await access(socketPath)}catch(cause){if(isNodeErrorCode5(cause,"ENOENT"))return;throw cause}if(await canConnect(socketPath))throw new Error(`${socketPath}: address already in use by a live server.`);await unlink2(socketPath)}}function listen(server,socketPath,secret){return new Promise((resolve2,reject)=>{server.once("error",reject),server.listen({path:resolveSocketTransportAddress(socketPath,process.platform,secret),readableAll:!1,writableAll:!1},async()=>{server.off("error",reject);try{process.platform!=="win32"&&!socketPath.startsWith("\0")&&await chmod3(socketPath,384),resolve2()}catch(cause){reject(cause)}})})}function closeServer(server){return new Promise(resolve2=>{server.close(()=>resolve2())})}function writeStderrLine(text){try{writeSync(2,`${text}
|
|
18
|
+
`)}catch{}}function delay2(ms){return new Promise(resolveDelay=>setTimeout(resolveDelay,ms))}function errorMessage3(cause){return cause instanceof Error?cause.message:String(cause)}function isNodeErrorCode5(cause,code){return cause instanceof Error&&"code"in cause&&cause.code===code}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function asOptionalString(value){return typeof value=="string"?value:typeof value=="number"?String(value):void 0}function isEntryScript(){let entry=process.argv[1];if(!entry)return!1;try{return fileURLToPath(import.meta.url)===realpathSync(entry)}catch{return!1}}if(!isBundledNode&&isEntryScript()){let launch=parseSupervisorArgs(process.argv.slice(2));launch||(writeStderrLine("usage: host-lifecycle.ts --socket <path> [host cli args...]"),process.exit(2)),runHostSupervisor(launch)}export{HOST_DAEMON_DIR_ENV,createHostDaemonPaths,createDaemonDirectories,writeHostSettings,readHostSettings,writeStateFile,readFileOrUndefined,parseJson,parseDaemonPidFile,ProcessIdentityUnreadableError,processMatchesPidFile,stopValidatedPid,waitForGone,readProcessStartTime,processIsLive,waitForStartTime,readHostProcessMetrics,SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,pruneDeadGenerations,readGenerationRows,readHostRegistration,writeHostRegistration,clearHostRegistration,releaseGeneration,provenOwner,legacyHostIsLive,writtenByThisProcess,SOCKET_SECRET_FILE_ENV,socketSecretPath,ensureSocketSecret,createSocketSecret,readSocketSecret,resolveSocketTransportAddress,authenticateSocket,sendSocketHandshake,recordProcessLifetime,classifyChildExit,PUBLIC_SOCKET_IDENTITY_FILE,MAX_SOCKET_PATH_BYTES,generationBindPath,statSocketIdentity,socketEntryReplaced,readSocketIdentityFile,waitForSocketIdentityFile,unlinkOwnedSocket,shieldSocketDuringClose,readHostWatchdogConfigFromBrandEnv,armHostWatchdog,HOST_COLD_START_ENV,HOST_IDLE_EXIT_MS_ENV,DEFAULT_HOST_IDLE_EXIT_MS,HANDOFF_GRACE_MS_ENV,DEFAULT_HANDOFF_GRACE_MS,createInternalSocketPath,parseColdStart,parseIdleExitMs,resolveHostPolicy,IdleExitDecider,INTERNAL_SUPERVISOR_FLAG,findInternalSupervisorArgs,parseSupervisorArgs,resolveCliMainPath,resolveHostChildLaunch,spawnableChildLaunch,runHostSupervisor};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{require_proper_lockfile}from"./chunk-
|
|
2
|
+
import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{CONFIG_DIR_NAME,canonicalizePath,canonicalizePathStrict,resolvePath,stripBom}from"./chunk-Y65WFI5H.js";import{__toESM}from"./chunk-IKOFCODM.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function normalizeCwd(cwd){let resolved=resolvePath(cwd);try{return canonicalizePathStrict(resolved)}catch{return resolved}}function findNearestTrustEntry(data,cwd){let currentDir=normalizeCwd(cwd);for(;;){let value=data[currentDir];if(value===!0||value===!1)return{path:currentDir,decision:value};let parentDir=dirname(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=normalizeCwd(cwd),parentDir=dirname(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=normalizeCwd(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function readTrustFile(path){if(!existsSync(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
|
|
3
3
|
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let homeDir=canonicalizePath(resolvePath(process.env.HOME||homedir())),userAgentsSkillsDir=join(homeDir,".agents","skills"),currentDir=canonicalizePath(resolvePath(cwd)),configDir=join(currentDir,CONFIG_DIR_NAME);if(TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join(configDir,entry))))return!0;for(;;){let agentsSkillsDir=join(currentDir,".agents","skills");if(agentsSkillsDir!==userAgentsSkillsDir&&existsSync(agentsSkillsDir))return!0;let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{constructor(agentDir){this.trustPath=join(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};export{getProjectTrustOptions,hasTrustRequiringProjectResources,ProjectTrustStore};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-
|
|
2
|
+
import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-NNILBBOH.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-XKLR7C5B.js";import{sanitizeBinaryOutput}from"./chunk-FHXKBENX.js";import{dropFailedAssistantTurns}from"./chunk-357I4IUU.js";import{copyContextProvenance}from"./chunk-ELFCNCBY.js";import{APP_NAME,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-Y65WFI5H.js";import{normalizeProviderId}from"./chunk-WL5EQYNL.js";var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context";function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
3
3
|
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}var PROVIDER_IMAGE_REJECTION_PATTERN=/does not represent a valid image|image_parse_error|invalid_image|unsupported image|could not process image|unable to process input image|image_url'?\.?[^\n]*invalid base64|expected a base64-encoded data url|image was specified using the image\/[a-z]+ media type|unsupported media type for base64 image|invalid data url for image/i;function isProviderImageRejection(errorMessage){return errorMessage!==void 0&&PROVIDER_IMAGE_REJECTION_PATTERN.test(errorMessage)}function rejectedImagePlaceholder(source){return`[Image omitted: the provider rejected this image (${source}) as invalid, so it is no longer sent with the conversation.]`}function field(message,key){return key in message?message[key]:void 0}function contentBlocks2(message){let content=field(message,"content");return Array.isArray(content)?content:[]}function toolCallSource(block){let args=block.arguments;if(typeof args!="object"||args===null)return;let record=args;for(let key of["path","file_path","filePath"]){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value}}function imageSource(message,toolCallSources){if(message.role!=="toolResult")return"an attached image";let toolCallId=field(message,"toolCallId"),known=typeof toolCallId=="string"?toolCallSources.get(toolCallId):void 0;if(known)return known;let toolName=field(message,"toolName");return typeof toolName=="string"?`${toolName} tool result`:"a tool result"}function scanRejectedImages(messages){let toolCallSources=new Map,rejections=new Map,unconfirmed=[];return messages.forEach((message,messageIndex)=>{if(message.role==="assistant"){for(let block of contentBlocks2(message)){let source=block.type==="toolCall"?toolCallSource(block):void 0;source&&typeof block.id=="string"&&toolCallSources.set(block.id,source)}let stopReason=field(message,"stopReason"),errorMessage=field(message,"errorMessage");stopReason==="error"&&isProviderImageRejection(typeof errorMessage=="string"?errorMessage:void 0)?(unconfirmed.length>0&&rejections.set(messageIndex,unconfirmed),unconfirmed=[]):stopReason!=="error"&&stopReason!=="aborted"&&(unconfirmed=[]);return}message.role!=="user"&&message.role!=="toolResult"||contentBlocks2(message).forEach((block,blockIndex)=>{block.type==="image"&&unconfirmed.push({messageIndex,blockIndex,source:imageSource(message,toolCallSources)})})}),rejections}function rejectedImageSources(messages,failedTurn){let failedIndex=messages.lastIndexOf(failedTurn);return(scanRejectedImages(messages).get(failedIndex)??[]).map(image=>image.source)}function omitProviderRejectedImages(messages){let rejected=new Map;for(let images of scanRejectedImages(messages).values())for(let image of images){let blocks=rejected.get(image.messageIndex)??new Map;blocks.set(image.blockIndex,image.source),rejected.set(image.messageIndex,blocks)}return rejected.size===0?messages:messages.map((message,messageIndex)=>{let blocks=rejected.get(messageIndex);if(!blocks)return message;let content=contentBlocks2(message).map((block,blockIndex)=>{let source=blocks.get(blockIndex);return source===void 0?block:{type:"text",text:rejectedImagePlaceholder(source)}});return{...message,content}})}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
4
4
|
|
|
5
5
|
<summary>
|
|
@@ -16,13 +16,13 @@ ${msg.output}
|
|
|
16
16
|
|
|
17
17
|
Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
|
|
18
18
|
|
|
19
|
-
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(dropFailedAssistantTurns(omitProviderRejectedImages(converted)),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readFileSync as readFileSync2,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{readdir as readdir2}from"fs/promises";import{join as join4,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
19
|
+
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"user":case"assistant":case"toolResult":return m;default:let _exhaustiveCheck=m;return}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(dropFailedAssistantTurns(omitProviderRejectedImages(converted)),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,limitHistory=maxHistoricalImages!==void 0,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),imagesToElide=new Set,keptImages=0,keptHistoricalImages=0,imageBytes=0,cutoffReached=!1;for(let messageIndex=messages.length-1;messageIndex>=0;messageIndex--){let message=messages[messageIndex];if(!(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)))for(let blockIndex=message.content.length-1;blockIndex>=0;blockIndex--){let block=message.content[blockIndex];if(block.type!=="image")continue;let isCurrentTurn=limitHistory&&messageIndex>lastAssistantIndex,isProtectedHistory=limitHistory&&!isCurrentTurn&&keptHistoricalImages<maxHistoricalImages;if(limitHistory&&!isCurrentTurn&&!isProtectedHistory||cutoffReached&&!isCurrentTurn&&!isProtectedHistory){imagesToElide.add(`${messageIndex}:${blockIndex}`);continue}if(isCurrentTurn||isProtectedHistory||keptImages<alwaysKeepNewest||imageBytes+block.data.length<=budgetBytes){keptImages++,isCurrentTurn||keptHistoricalImages++,imageBytes+=block.data.length;continue}cutoffReached=!0,imagesToElide.add(`${messageIndex}:${blockIndex}`)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)))return message;let replaced=message.content.map((block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`)?{type:"text",text:IMAGE_ELISION_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,IMAGE_ELISION_PLACEHOLDER)}})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readFileSync as readFileSync2,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{readdir as readdir2}from"fs/promises";import{join as join4,resolve as resolve2}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";import{execFile}from"node:child_process";var REPOSITORY_IDENTITY_ENTRY_TYPE="repository-identity",GIT_TIMEOUT_MS=5e3,COMMIT_HASH=/^[0-9a-f]{40,64}$/,GIT_LOCATION_ENV=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]),runGit=(dir,args)=>new Promise(resolve3=>{let env=Object.fromEntries(Object.entries(process.env).filter(([name])=>!GIT_LOCATION_ENV.has(name)));execFile("git",["-C",dir,...args],{env,timeout:GIT_TIMEOUT_MS,windowsHide:!0},(error,stdout)=>{resolve3(error?void 0:stdout)})});async function readRepositoryIdentity(dir,run=runGit){let[roots,origin]=await Promise.all([run(dir,["rev-list","--max-parents=0","HEAD"]),run(dir,["config","--get","remote.origin.url"])]),rootCommits=(roots??"").split(/\s+/).filter(line=>COMMIT_HASH.test(line)).sort(),originUrl=origin?.trim()?normalizeRemoteUrl(origin):void 0;if(!(rootCommits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits}:{rootCommits,originUrl}}function normalizeRemoteUrl(url){let trimmed=url.trim(),scpLike=/^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(trimmed);return(scpLike?`${scpLike[1]}/${scpLike[2]}`:trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").replace(/^[^@/]+@/,"").replace(/^([^/:]+):\d+\//,"$1/")).replace(/\/+$/,"").replace(/\.git$/i,"").toLowerCase()}function compareRepositoryIdentities(a,b){return a===void 0||b===void 0?"unknown":a.rootCommits.length>0&&b.rootCommits.length>0?a.rootCommits.some(commit=>b.rootCommits.includes(commit))?"same":"different":a.originUrl!==void 0&&b.originUrl!==void 0?a.originUrl===b.originUrl?"same":"different":"unknown"}function parseRepositoryIdentity(value){if(typeof value!="object"||value===null)return;let{rootCommits,originUrl}=value;if(!Array.isArray(rootCommits)||!rootCommits.every(commit=>typeof commit=="string")||originUrl!==void 0&&typeof originUrl!="string")return;let commits=rootCommits.filter(commit=>COMMIT_HASH.test(commit)).sort();if(!(commits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits:commits}:{rootCommits:commits,originUrl}}function sameRepositoryIdentity(a,b){return a===void 0||b===void 0?a===b:a.originUrl===b.originUrl&&a.rootCommits.join(",")===b.rootCommits.join(",")}function parseEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function isMessageWithContent(message){return typeof message=="object"&&message!==null&&typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function visibleMessage(entry){if(entry.type!=="message")return null;let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return null;let messageTime=message.timestamp,entryTime=Date.parse(entry.timestamp),time=typeof messageTime=="number"?messageTime:Number.isNaN(entryTime)?void 0:entryTime;return{text:extractTextContent(message),role:message.role,time}}function sessionInfoName(entry){return entry.type!=="session_info"?null:entry.name?.trim()||void 0}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,repositoryIdentity:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);if(entry.type==="custom"&&entry.customType===REPOSITORY_IDENTITY_ENTRY_TYPE)return accumulator.repositoryIdentity=parseRepositoryIdentity(entry.data)??accumulator.repositoryIdentity,!0;let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
20
20
|
`,searchFrom);for(;newlineIndex!==-1;){if(!emit(pending.slice(lineStart,newlineIndex)))return{completed:!1,bytes,endsWithNewline:!1};lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
21
|
-
`,lineStart)}pending=pending.slice(lineStart)}return pending+=decoder.end(),pending&&!emit(pending)?{completed:!1,bytes,endsWithNewline:!1}:{completed:!0,bytes,endsWithNewline:lastByte===10}}finally{await handle.close()}}async function readSessionSummary(filePath){let accumulator=newAccumulator();try{if(!(await readFileLines(filePath,line=>accumulateLine(accumulator,line))).completed)return null}catch(error){if(error instanceof Error)return null;throw error}let header=accumulator.header;return header?{header,name:accumulator.name,firstUserMessage:accumulator.firstUserMessage,messageCount:accumulator.messageCount,lastActivityTime:accumulator.lastActivityTime,allMessagesText:accumulator.texts.join(" ")}:null}import{stat}from"fs/promises";import{basename,join}from"path";import{appendFile,rename,rm,writeFile}from"fs/promises";var SESSION_SUMMARY_INDEX_FILE=".session-summaries.index",INDEX_VERSION=
|
|
22
|
-
`,UNUSABLE={usable:!1,entries:new Map,entryBytes:0,endsWithNewline:!0};function isObject(value){return typeof value=="object"&&value!==null}function isOptional(value,type){return value===void 0||typeof value===type}function isSessionSummary(value){return!isObject(value)||!isObject(value.header)?!1:value.header.type==="session"&&typeof value.header.id=="string"&&typeof value.firstUserMessage=="string"&&typeof value.messageCount=="number"&&typeof value.allMessagesText=="string"&&isOptional(value.name,"string")&&isOptional(value.lastActivityTime,"number")}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function toIndexEntry(file,stamp,summary){if(!(summary.lastActivityTime!==void 0&&!Number.isFinite(summary.lastActivityTime)))return withLine(file,stamp,summary,`${JSON.stringify({file,size:stamp.size,mtimeMs:stamp.mtimeMs,summary})}
|
|
21
|
+
`,lineStart)}pending=pending.slice(lineStart)}return pending+=decoder.end(),pending&&!emit(pending)?{completed:!1,bytes,endsWithNewline:!1}:{completed:!0,bytes,endsWithNewline:lastByte===10}}finally{await handle.close()}}async function readSessionSummary(filePath){let accumulator=newAccumulator();try{if(!(await readFileLines(filePath,line=>accumulateLine(accumulator,line))).completed)return null}catch(error){if(error instanceof Error)return null;throw error}let header=accumulator.header;return header?{header,name:accumulator.name,firstUserMessage:accumulator.firstUserMessage,messageCount:accumulator.messageCount,lastActivityTime:accumulator.lastActivityTime,allMessagesText:accumulator.texts.join(" "),...accumulator.repositoryIdentity?{repositoryIdentity:accumulator.repositoryIdentity}:{}}:null}import{stat}from"fs/promises";import{basename,join}from"path";import{appendFile,rename,rm,writeFile}from"fs/promises";var SESSION_SUMMARY_INDEX_FILE=".session-summaries.index",INDEX_VERSION=2,HEADER_LINE=`${JSON.stringify({version:INDEX_VERSION})}
|
|
22
|
+
`,UNUSABLE={usable:!1,entries:new Map,entryBytes:0,endsWithNewline:!0};function isObject(value){return typeof value=="object"&&value!==null}function isOptional(value,type){return value===void 0||typeof value===type}function isSessionSummary(value){return!isObject(value)||!isObject(value.header)?!1:value.header.type==="session"&&typeof value.header.id=="string"&&typeof value.firstUserMessage=="string"&&typeof value.messageCount=="number"&&typeof value.allMessagesText=="string"&&isOptional(value.name,"string")&&isOptional(value.lastActivityTime,"number")&&(value.repositoryIdentity===void 0||parseRepositoryIdentity(value.repositoryIdentity)!==void 0)}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function toIndexEntry(file,stamp,summary){if(!(summary.lastActivityTime!==void 0&&!Number.isFinite(summary.lastActivityTime)))return withLine(file,stamp,summary,`${JSON.stringify({file,size:stamp.size,mtimeMs:stamp.mtimeMs,summary})}
|
|
23
23
|
`)}function withLine(file,stamp,summary,line){return{file,stamp,summary,line,lineBytes:Buffer.byteLength(line,"utf8")}}function parseEntryLine2(line){let parsed;try{parsed=JSON.parse(line)}catch{return}if(!(!isObject(parsed)||typeof parsed.file!="string"||parsed.file.includes("/"))&&!(!isFiniteNumber(parsed.size)||!isFiniteNumber(parsed.mtimeMs)||!isSessionSummary(parsed.summary)))return withLine(parsed.file,{size:parsed.size,mtimeMs:parsed.mtimeMs},parsed.summary,`${line}
|
|
24
24
|
`)}function isCurrentHeader(line){try{let parsed=JSON.parse(line);return isObject(parsed)&&parsed.version===INDEX_VERSION}catch{return!1}}async function loadIndexFile(path){let entries=new Map,headerSeen=!1,headerBytes=0;try{let read=await readFileLines(path,line=>{if(!headerSeen)return headerSeen=!0,headerBytes=Buffer.byteLength(line,"utf8")+1,isCurrentHeader(line);let entry=parseEntryLine2(line);return entry&&entries.set(entry.file,entry),!0});return!read.completed||!headerSeen?UNUSABLE:{usable:!0,entries,entryBytes:Math.max(0,read.bytes-headerBytes),endsWithNewline:read.endsWithNewline}}catch(error){if(error instanceof Error)return UNUSABLE;throw error}}async function appendIndexEntries(path,entries,endsWithNewline){let prefix=endsWithNewline?"":`
|
|
25
|
-
`;for(let entry of entries)await appendFile(path,prefix+entry.line),prefix=""}async function rewriteIndexFile(path,entries){let temp=`${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;try{await writeFile(temp,HEADER_LINE+entries.map(entry=>entry.line).join("")),await rename(temp,path)}catch(error){throw await rm(temp,{force:!0}).catch(()=>{}),error}}var SESSION_SUMMARY_INDEX_MAX_BYTES=256*1024*1024,snapshots=new Map;function stampsMatch(left,right){return left.size===right.size&&left.mtimeMs===right.mtimeMs}async function statStamp(path){try{let stats=await stat(path);return{size:stats.size,mtimeMs:stats.mtimeMs}}catch(error){if(error instanceof Error)return;throw error}}function recency(entry){let headerTime=Date.parse(entry.summary.header.timestamp);return entry.summary.lastActivityTime??(Number.isNaN(headerTime)?0:headerTime)}function selectWithinBudget(entries,maxBytes){let kept=[],bytes=0;for(let entry of[...entries].sort((left,right)=>recency(right)-recency(left)))if(!(entry.lineBytes>maxBytes)){if(bytes+entry.lineBytes>maxBytes)break;kept.push(entry),bytes+=entry.lineBytes}return kept}var SessionSummaryIndex=class{constructor(dir,options={}){this.recorded=[],this.path=join(dir,SESSION_SUMMARY_INDEX_FILE),this.maxBytes=options.maxBytes??SESSION_SUMMARY_INDEX_MAX_BYTES}async lookup(filePath,stamp){let file=basename(filePath);if(!this.loading){this.snapshot??=this.currentSnapshot();let known=await this.snapshot,indexed=known?.entryStamps.get(file);if(known&&!(indexed&&stampsMatch(indexed,stamp)))return}this.loading??=this.load();let entry=(await this.loading).entries.get(file);return entry&&stampsMatch(entry.stamp,stamp)?entry.summary:void 0}record(filePath,stamp,summary){this.recorded.push({file:basename(filePath),stamp,summary})}async persist(presentFiles){if(!this.loading)return;let loaded=await this.loading,entries=new Map(loaded.entries),added=new Set;for(let{file,stamp,summary}of this.recorded){let existing=entries.get(file);if(existing&&stampsMatch(existing.stamp,stamp))continue;let entry=toIndexEntry(file,stamp,summary);entry&&(entries.set(file,entry),added.add(entry))}let present=new Set(presentFiles.map(path=>basename(path))),live=[...entries.values()].filter(entry=>present.has(entry.file)),kept=selectWithinBudget(live,this.maxBytes),keptBytes=kept.reduce((total,entry)=>total+entry.lineBytes,0),appended=kept.filter(entry=>added.has(entry)),appendedBytes=appended.reduce((total,entry)=>total+entry.lineBytes,0);try{if(!loaded.usable&&kept.length>0||loaded.usable&&loaded.entryBytes+appendedBytes>2*keptBytes)await rewriteIndexFile(this.path,kept),this.remember(await statStamp(this.path),kept);else if(loaded.usable&&appended.length>0){await appendIndexEntries(this.path,appended,loaded.endsWithNewline);let inFile=new Map(loaded.entries);for(let entry of appended)inFile.set(entry.file,entry);this.remember(await statStamp(this.path),inFile.values())}}catch(error){if(!(error instanceof Error))throw error;snapshots.delete(this.path)}}async currentSnapshot(){let recorded=snapshots.get(this.path);if(!recorded)return;let current=await statStamp(this.path);return current&&stampsMatch(current,recorded.indexStamp)?recorded:void 0}async load(){let before=await statStamp(this.path),loaded=await loadIndexFile(this.path);return this.remember(before,loaded.usable?loaded.entries.values():void 0),loaded}remember(indexStamp,entries){if(!indexStamp||!entries){snapshots.delete(this.path);return}let entryStamps=new Map;for(let entry of entries)entryStamps.set(entry.file,entry.stamp);snapshots.set(this.path,{indexStamp,entryStamps})}};var SessionSummaryLru=class{constructor(budget){this.entries=new Map,this.retainedTextBytes=0,this.budget=budget}get size(){return this.entries.size}get textBytes(){return this.retainedTextBytes}get(key){let retained=this.entries.get(key);if(retained)return this.entries.delete(key),this.entries.set(key,retained),retained.entry}drop(key){let retained=this.entries.get(key);retained&&(this.entries.delete(key),this.retainedTextBytes-=retained.textBytes)}retain(key,entry){this.drop(key);let textBytes=Buffer.byteLength(entry.summary.allMessagesText,"utf8");textBytes>this.budget.maxTextBytes||(this.entries.set(key,{entry,textBytes}),this.retainedTextBytes+=textBytes,this.evictUntilWithinBudget())}clear(){this.entries.clear(),this.retainedTextBytes=0}evictUntilWithinBudget(){for(;this.entries.size>this.budget.maxEntries||this.retainedTextBytes>this.budget.maxTextBytes;){let oldest=this.entries.keys().next();if(oldest.done)break;this.drop(oldest.value)}}};var SESSION_SUMMARY_CACHE_LIMIT=4096,SESSION_SUMMARY_CACHE_MAX_TEXT_BYTES=64*1024*1024,cache=new SessionSummaryLru({maxEntries:SESSION_SUMMARY_CACHE_LIMIT,maxTextBytes:SESSION_SUMMARY_CACHE_MAX_TEXT_BYTES}),streamedSummaries=0;function stampsMatch2(left,right){return left.size===right.size&&left.mtimeMs===right.mtimeMs}async function readCachedSessionSummary(filePath,store){let key=resolve(filePath),stamp,mtime;try{let stats=await stat2(filePath);stamp={size:stats.size,mtimeMs:stats.mtimeMs},mtime=stats.mtime}catch(error){if(!(error instanceof Error))throw error;return cache.drop(key),null}let cached=cache.get(key);if(cached&&stampsMatch2(cached.stamp,stamp))return store?.record(filePath,stamp,cached.summary),{summary:cached.summary,mtime:cached.mtime};let stored=await store?.lookup(filePath,stamp);if(stored)return cache.retain(key,{stamp,summary:stored,mtime}),{summary:stored,mtime};streamedSummaries++;let summary=await readSessionSummary(filePath);return summary?(cache.retain(key,{stamp,summary,mtime}),store?.record(filePath,stamp,summary),{summary,mtime}):(cache.drop(key),null)}var MAX_CONCURRENT_SESSION_INFO_LOADS=10;function resolveModified(activityTime,header,mtime){if(typeof activityTime=="number"&&activityTime>0)return new Date(activityTime);let headerTime=typeof header.timestamp=="string"?Date.parse(header.timestamp):Number.NaN;return Number.isNaN(headerTime)?mtime:new Date(headerTime)}async function buildSessionInfo(filePath,store){let cached=await readCachedSessionSummary(filePath,store);if(!cached)return null;let{summary,mtime}=cached,header=summary.header;return{path:filePath,id:header.id,cwd:typeof header.cwd=="string"?header.cwd:"",name:summary.name,parentSessionPath:header.parentSession,created:new Date(header.timestamp),modified:resolveModified(summary.lastActivityTime,header,mtime),messageCount:summary.messageCount,firstMessage:summary.firstUserMessage||"(no messages)",allMessagesText:summary.allMessagesText}}async function buildSessionInfosWithConcurrency(files,onLoaded,store){let results=new Array(files.length).fill(null),inFlight=new Set,nextIndex=0,startNext=()=>{let index=nextIndex++,file=files[index];if(!file)return;let task;task=buildSessionInfo(file,store).then(info=>{results[index]=info}).catch(()=>{results[index]=null}).finally(()=>{inFlight.delete(task),onLoaded()}),inFlight.add(task)};for(;nextIndex<files.length||inFlight.size>0;){for(;nextIndex<files.length&&inFlight.size<MAX_CONCURRENT_SESSION_INFO_LOADS;)startNext();inFlight.size>0&&await Promise.race(inFlight)}return results}async function listSessionInfos(files,onLoaded,store){let results=await buildSessionInfosWithConcurrency(files,onLoaded,store),sessions=[];for(let info of results)info&&sessions.push(info);return sessions}async function listSessionFilesInDir(dir,files,onLoaded){let index=new SessionSummaryIndex(dir),sessions=await listSessionInfos(files,onLoaded,index);return await index.persist(files),sessions}async function listSessionsFromDir(dir,onProgress,progressOffset=0,progressTotal){if(!existsSync(dir))return[];try{let files=(await readdir(dir)).filter(name=>name.endsWith(".jsonl")).map(name=>join2(dir,name)),total=progressTotal??files.length,loaded=0;return await listSessionFilesInDir(dir,files,()=>{loaded++,onProgress?.(progressOffset+loaded,total)})}catch{return[]}}function materializeSessionEntries(entries,options){let{residentStore,loadHistoryEntries,onMaterialized}=options,missingEntryIds=new Set,materialized=entries.map(entry=>residentStore.materialize(entry,()=>{missingEntryIds.add(entry.id)}));if(missingEntryIds.size===0){for(let entry of materialized)onMaterialized(entry);return materialized}let persistedById=new Map(loadHistoryEntries().filter(entry=>entry.type!=="session").map(entry=>[entry.id,entry])),repaired=materialized.map(entry=>{if(!missingEntryIds.has(entry.id))return entry;let persisted=persistedById.get(entry.id);return persisted===void 0?entry:residentStore.materialize(persisted)});for(let entry of repaired)onMaterialized(entry);return repaired}import{createHash}from"node:crypto";import{existsSync as existsSync2,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join as join3}from"node:path";import{Buffer as Buffer2}from"buffer";var RESIDENT_STRING_MIN_BYTES=32*1024,DEFAULT_RESIDENT_STRING_BUDGET_BYTES=64*1024*1024,RESIDENT_STRING_PREFIX="\0senpi-resident-string:v1:",OMIT_JSON_VALUE=Symbol("omit-json-value"),ResidentStringStore=class{constructor(options={}){this.strings=new Map,this.bytes=0,this.evictedCount=0,this.evictedBytes=0,this.maxBytes=options.maxBytes??DEFAULT_RESIDENT_STRING_BUDGET_BYTES,this.blobsDir=options.blobsDir}configure(options){this.blobsDir=options.blobsDir}clear(){this.strings.clear(),this.bytes=0,this.evictedCount=0,this.evictedBytes=0;let dir=this.blobsDir?.();if(dir)try{rmSync(dir,{force:!0,recursive:!0})}catch{}}spillResident(){if(this.blobsDir?.())for(let[id,text]of this.strings)this._writeBlob(id,text)&&(this.strings.delete(id),this.bytes-=Buffer2.byteLength(text,"utf8"))}stats(){return{blobCount:this.strings.size,blobBytes:this.bytes,evictedCount:this.evictedCount,evictedBytes:this.evictedBytes}}externalize(value){return transformJson(value,text=>this.externalizeString(text))}materialize(value,onMissing){return transformJson(value,text=>this.materializeString(text,onMissing))}resolvedBlobsDir(){return this.blobsDir?.()}externalizeInPlace(value){this._mutateStringsInPlace(value,new Set,text=>this.externalizeString(text))}materializeInPlace(value){this._mutateStringsInPlace(value,new Set,text=>this.materializeString(text))}_mutateStringsInPlace(value,seen,mutate){if(typeof value!="object"||value===null||seen.has(value))return;seen.add(value);let record=value;for(let key of Object.keys(record)){let current=record[key];typeof current=="string"?record[key]=mutate(current):typeof current=="object"&¤t!==null&&this._mutateStringsInPlace(current,seen,mutate)}}externalizeString(text){if(text.length<RESIDENT_STRING_MIN_BYTES||text.startsWith(RESIDENT_STRING_PREFIX))return text;let id=createHash("sha256").update(text,"utf8").digest("hex"),token=`${RESIDENT_STRING_PREFIX}${id}`;return this.strings.has(id)?(this.strings.delete(id),this.strings.set(id,text),token):(this.strings.set(id,text),this.bytes+=Buffer2.byteLength(text,"utf8"),this._enforceBudget(),token)}materializeString(text,onMissing){if(!text.startsWith(RESIDENT_STRING_PREFIX))return text;let id=text.slice(RESIDENT_STRING_PREFIX.length),resident=this.strings.get(id);if(resident!==void 0)return this.strings.delete(id),this.strings.set(id,resident),resident;let hydrated=this._readBlob(id);return hydrated!==void 0?hydrated:onMissing?.(id)??text}_enforceBudget(){for(;this.bytes>this.maxBytes&&this.strings.size>0;){let[oldestId,oldest]=this.strings.entries().next().value;if(!this._writeBlob(oldestId,oldest))return;this.strings.delete(oldestId),this.bytes-=Buffer2.byteLength(oldest,"utf8")}}_writeBlob(id,text){let dir=this.blobsDir?.();if(!dir)return!1;let final=join3(dir,`${id}.blob`),temp=`${final}.tmp`;try{mkdirSync(dir,{recursive:!0}),existsSync2(final)||(writeFileSync(temp,JSON.stringify({v:1,text}),"utf8"),renameSync(temp,final))}catch{try{rmSync(temp,{force:!0})}catch{}return!1}return this.evictedCount++,this.evictedBytes+=Buffer2.byteLength(text,"utf8"),!0}_readBlob(id){let dir=this.blobsDir?.();if(!dir)return;let file=join3(dir,`${id}.blob`);try{let parsed=JSON.parse(readFileSync(file,"utf8"));if(typeof parsed.text=="string")return parsed.text}catch{}try{rmSync(file,{force:!0})}catch{}}};function transformJson(value,transformString){let transformed=transformJsonValue(value,transformString,"",new WeakSet);if(transformed===OMIT_JSON_VALUE){let serialized=JSON.stringify(value);if(serialized===void 0)throw new SyntaxError("JSON-compatible value expected");return JSON.parse(serialized)}return transformed}function transformJsonValue(value,transformString,key,seen){if(typeof value=="string")return transformString(value);if(typeof value=="number")return Number.isFinite(value)?value:null;if(value===null||typeof value=="boolean")return value;if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value>"u"||typeof value=="function"||typeof value=="symbol")return OMIT_JSON_VALUE;if(seen.has(value))throw new TypeError("Converting circular structure to JSON");seen.add(value);let jsonValue=hasJsonSerializer(value)?value.toJSON(key):value;if(jsonValue!==value){let transformed2=transformJsonValue(jsonValue,transformString,key,seen);return seen.delete(value),transformed2}if(Array.isArray(value)){let transformed2=Array.from({length:value.length},(_item,index)=>{let item=value[index],transformedItem=transformJsonValue(item,transformString,String(index),seen);return transformedItem===OMIT_JSON_VALUE?null:transformedItem});return seen.delete(value),transformed2}let transformed={};for(let[key2,item]of Object.entries(value)){let transformedItem=transformJsonValue(item,transformString,String(key2),seen);transformedItem!==OMIT_JSON_VALUE&&Object.defineProperty(transformed,key2,{configurable:!0,enumerable:!0,value:transformedItem,writable:!0})}return seen.delete(value),transformed}function hasJsonSerializer(value){return"toJSON"in value&&typeof value.toJSON=="function"}var reserve;function reserveSessionWrite(path){reserve?.(path)}var liveWriters=new Set,writerRefs=new WeakMap;function registerSessionWriter(owner){if(writerRefs.has(owner))return;let ref=new WeakRef(owner);writerRefs.set(owner,ref),liveWriters.add(ref)}function unregisterSessionWriter(owner){let ref=writerRefs.get(owner);ref&&(writerRefs.delete(owner),liveWriters.delete(ref))}function hasOtherLiveSessionWriter(path,self){for(let ref of liveWriters){let owner=ref.deref();if(!owner){liveWriters.delete(ref);continue}if(owner!==self&&owner.isPersisted()&&owner.getSessionFile()===path)return!0}return!1}function uuidv7(){let ts=BigInt(Date.now()),bytes=randomBytes(10),hex=[(ts>>40n&0xffn).toString(16).padStart(2,"0"),(ts>>32n&0xffn).toString(16).padStart(2,"0"),(ts>>24n&0xffn).toString(16).padStart(2,"0"),(ts>>16n&0xffn).toString(16).padStart(2,"0"),(ts>>8n&0xffn).toString(16).padStart(2,"0"),(ts&0xffn).toString(16).padStart(2,"0"),(112|bytes[0]&15).toString(16).padStart(2,"0"),bytes[1].toString(16).padStart(2,"0"),(128|bytes[2]&63).toString(16).padStart(2,"0"),bytes[3].toString(16).padStart(2,"0"),...Array.from(bytes.slice(4),b=>b.toString(16).padStart(2,"0"))].join("");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20,32)}`}var contextMessageEntryIds=new WeakMap,SESSION_CONTEXT_ENTRY_ID="__piSessionContextEntryId";function withContextEntryId(entryId,message){return contextMessageEntryIds.set(message,entryId),message}function getSessionContextEntryId(message){return contextMessageEntryIds.get(message)}var CURRENT_SESSION_VERSION=3;function createSessionId(){return uuidv7()}function assertValidSessionId(id){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}function generateId(byId){for(let i=0;i<100;i++){let id=randomUUID().slice(0,8);if(!byId.has(id))return id}return randomUUID()}function migrateV1ToV2(entries){let ids=new Set,prevId=null;for(let entry of entries){if(entry.type==="session"){entry.version=2;continue}if(entry.id=generateId(ids),entry.parentId=prevId,prevId=entry.id,entry.type==="compaction"){let comp=entry;if(typeof comp.firstKeptEntryIndex=="number"){let targetEntry=entries[comp.firstKeptEntryIndex];targetEntry&&targetEntry.type!=="session"&&(comp.firstKeptEntryId=targetEntry.id),delete comp.firstKeptEntryIndex}}}}function migrateV2ToV3(entries){for(let entry of entries){if(entry.type==="session"){entry.version=3;continue}if(entry.type==="message"){let msgEntry=entry;msgEntry.message&&msgEntry.message.role==="hookMessage"&&(msgEntry.message.role="custom")}}}function migrateToCurrentVersion(entries){let version=entries.find(e=>e.type==="session")?.version??1;return version>=CURRENT_SESSION_VERSION?!1:(version<2&&migrateV1ToV2(entries),version<3&&migrateV2ToV3(entries),!0)}function migrateSessionEntries(entries){migrateToCurrentVersion(entries)}function parseSessionEntries(content){let entries=[],lines=content.trim().split(`
|
|
25
|
+
`;for(let entry of entries)await appendFile(path,prefix+entry.line),prefix=""}async function rewriteIndexFile(path,entries){let temp=`${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;try{await writeFile(temp,HEADER_LINE+entries.map(entry=>entry.line).join("")),await rename(temp,path)}catch(error){throw await rm(temp,{force:!0}).catch(()=>{}),error}}var SESSION_SUMMARY_INDEX_MAX_BYTES=256*1024*1024,snapshots=new Map;function stampsMatch(left,right){return left.size===right.size&&left.mtimeMs===right.mtimeMs}async function statStamp(path){try{let stats=await stat(path);return{size:stats.size,mtimeMs:stats.mtimeMs}}catch(error){if(error instanceof Error)return;throw error}}function recency(entry){let headerTime=Date.parse(entry.summary.header.timestamp);return entry.summary.lastActivityTime??(Number.isNaN(headerTime)?0:headerTime)}function selectWithinBudget(entries,maxBytes){let kept=[],bytes=0;for(let entry of[...entries].sort((left,right)=>recency(right)-recency(left)))if(!(entry.lineBytes>maxBytes)){if(bytes+entry.lineBytes>maxBytes)break;kept.push(entry),bytes+=entry.lineBytes}return kept}var SessionSummaryIndex=class{constructor(dir,options={}){this.recorded=[],this.path=join(dir,SESSION_SUMMARY_INDEX_FILE),this.maxBytes=options.maxBytes??SESSION_SUMMARY_INDEX_MAX_BYTES}async lookup(filePath,stamp){let file=basename(filePath);if(!this.loading){this.snapshot??=this.currentSnapshot();let known=await this.snapshot,indexed=known?.entryStamps.get(file);if(known&&!(indexed&&stampsMatch(indexed,stamp)))return}this.loading??=this.load();let entry=(await this.loading).entries.get(file);return entry&&stampsMatch(entry.stamp,stamp)?entry.summary:void 0}record(filePath,stamp,summary){this.recorded.push({file:basename(filePath),stamp,summary})}async persist(presentFiles){if(!this.loading)return;let loaded=await this.loading,entries=new Map(loaded.entries),added=new Set;for(let{file,stamp,summary}of this.recorded){let existing=entries.get(file);if(existing&&stampsMatch(existing.stamp,stamp))continue;let entry=toIndexEntry(file,stamp,summary);entry&&(entries.set(file,entry),added.add(entry))}let present=new Set(presentFiles.map(path=>basename(path))),live=[...entries.values()].filter(entry=>present.has(entry.file)),kept=selectWithinBudget(live,this.maxBytes),keptBytes=kept.reduce((total,entry)=>total+entry.lineBytes,0),appended=kept.filter(entry=>added.has(entry)),appendedBytes=appended.reduce((total,entry)=>total+entry.lineBytes,0);try{if(!loaded.usable&&kept.length>0||loaded.usable&&loaded.entryBytes+appendedBytes>2*keptBytes)await rewriteIndexFile(this.path,kept),this.remember(await statStamp(this.path),kept);else if(loaded.usable&&appended.length>0){await appendIndexEntries(this.path,appended,loaded.endsWithNewline);let inFile=new Map(loaded.entries);for(let entry of appended)inFile.set(entry.file,entry);this.remember(await statStamp(this.path),inFile.values())}}catch(error){if(!(error instanceof Error))throw error;snapshots.delete(this.path)}}async currentSnapshot(){let recorded=snapshots.get(this.path);if(!recorded)return;let current=await statStamp(this.path);return current&&stampsMatch(current,recorded.indexStamp)?recorded:void 0}async load(){let before=await statStamp(this.path),loaded=await loadIndexFile(this.path);return this.remember(before,loaded.usable?loaded.entries.values():void 0),loaded}remember(indexStamp,entries){if(!indexStamp||!entries){snapshots.delete(this.path);return}let entryStamps=new Map;for(let entry of entries)entryStamps.set(entry.file,entry.stamp);snapshots.set(this.path,{indexStamp,entryStamps})}};var SessionSummaryLru=class{constructor(budget){this.entries=new Map,this.retainedTextBytes=0,this.budget=budget}get size(){return this.entries.size}get textBytes(){return this.retainedTextBytes}get(key){let retained=this.entries.get(key);if(retained)return this.entries.delete(key),this.entries.set(key,retained),retained.entry}drop(key){let retained=this.entries.get(key);retained&&(this.entries.delete(key),this.retainedTextBytes-=retained.textBytes)}retain(key,entry){this.drop(key);let textBytes=Buffer.byteLength(entry.summary.allMessagesText,"utf8");textBytes>this.budget.maxTextBytes||(this.entries.set(key,{entry,textBytes}),this.retainedTextBytes+=textBytes,this.evictUntilWithinBudget())}clear(){this.entries.clear(),this.retainedTextBytes=0}evictUntilWithinBudget(){for(;this.entries.size>this.budget.maxEntries||this.retainedTextBytes>this.budget.maxTextBytes;){let oldest=this.entries.keys().next();if(oldest.done)break;this.drop(oldest.value)}}};var SESSION_SUMMARY_CACHE_LIMIT=4096,SESSION_SUMMARY_CACHE_MAX_TEXT_BYTES=64*1024*1024,cache=new SessionSummaryLru({maxEntries:SESSION_SUMMARY_CACHE_LIMIT,maxTextBytes:SESSION_SUMMARY_CACHE_MAX_TEXT_BYTES}),streamedSummaries=0;function stampsMatch2(left,right){return left.size===right.size&&left.mtimeMs===right.mtimeMs}async function readCachedSessionSummary(filePath,store){let key=resolve(filePath),stamp,mtime;try{let stats=await stat2(filePath);stamp={size:stats.size,mtimeMs:stats.mtimeMs},mtime=stats.mtime}catch(error){if(!(error instanceof Error))throw error;return cache.drop(key),null}let cached=cache.get(key);if(cached&&stampsMatch2(cached.stamp,stamp))return store?.record(filePath,stamp,cached.summary),{summary:cached.summary,mtime:cached.mtime};let stored=await store?.lookup(filePath,stamp);if(stored)return cache.retain(key,{stamp,summary:stored,mtime}),{summary:stored,mtime};streamedSummaries++;let summary=await readSessionSummary(filePath);return summary?(cache.retain(key,{stamp,summary,mtime}),store?.record(filePath,stamp,summary),{summary,mtime}):(cache.drop(key),null)}var MAX_CONCURRENT_SESSION_INFO_LOADS=10;function resolveModified(activityTime,header,mtime){if(typeof activityTime=="number"&&activityTime>0)return new Date(activityTime);let headerTime=typeof header.timestamp=="string"?Date.parse(header.timestamp):Number.NaN;return Number.isNaN(headerTime)?mtime:new Date(headerTime)}async function buildSessionInfo(filePath,store){let cached=await readCachedSessionSummary(filePath,store);if(!cached)return null;let{summary,mtime}=cached,header=summary.header;return{path:filePath,id:header.id,cwd:typeof header.cwd=="string"?header.cwd:"",name:summary.name,parentSessionPath:header.parentSession,created:new Date(header.timestamp),modified:resolveModified(summary.lastActivityTime,header,mtime),messageCount:summary.messageCount,firstMessage:summary.firstUserMessage||"(no messages)",allMessagesText:summary.allMessagesText,...summary.repositoryIdentity?{repositoryIdentity:summary.repositoryIdentity}:{}}}async function buildSessionInfosWithConcurrency(files,onLoaded,store){let results=new Array(files.length).fill(null),inFlight=new Set,nextIndex=0,startNext=()=>{let index=nextIndex++,file=files[index];if(!file)return;let task;task=buildSessionInfo(file,store).then(info=>{results[index]=info}).catch(()=>{results[index]=null}).finally(()=>{inFlight.delete(task),onLoaded()}),inFlight.add(task)};for(;nextIndex<files.length||inFlight.size>0;){for(;nextIndex<files.length&&inFlight.size<MAX_CONCURRENT_SESSION_INFO_LOADS;)startNext();inFlight.size>0&&await Promise.race(inFlight)}return results}async function listSessionInfos(files,onLoaded,store){let results=await buildSessionInfosWithConcurrency(files,onLoaded,store),sessions=[];for(let info of results)info&&sessions.push(info);return sessions}async function listSessionFilesInDir(dir,files,onLoaded){let index=new SessionSummaryIndex(dir),sessions=await listSessionInfos(files,onLoaded,index);return await index.persist(files),sessions}async function listSessionsFromDir(dir,onProgress,progressOffset=0,progressTotal){if(!existsSync(dir))return[];try{let files=(await readdir(dir)).filter(name=>name.endsWith(".jsonl")).map(name=>join2(dir,name)),total=progressTotal??files.length,loaded=0;return await listSessionFilesInDir(dir,files,()=>{loaded++,onProgress?.(progressOffset+loaded,total)})}catch{return[]}}function materializeSessionEntries(entries,options){let{residentStore,loadHistoryEntries,onMaterialized}=options,missingEntryIds=new Set,materialized=entries.map(entry=>residentStore.materialize(entry,()=>{missingEntryIds.add(entry.id)}));if(missingEntryIds.size===0){for(let entry of materialized)onMaterialized(entry);return materialized}let persistedById=new Map(loadHistoryEntries().filter(entry=>entry.type!=="session").map(entry=>[entry.id,entry])),repaired=materialized.map(entry=>{if(!missingEntryIds.has(entry.id))return entry;let persisted=persistedById.get(entry.id);return persisted===void 0?entry:residentStore.materialize(persisted)});for(let entry of repaired)onMaterialized(entry);return repaired}import{createHash}from"node:crypto";import{existsSync as existsSync2,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join as join3}from"node:path";import{Buffer as Buffer2}from"buffer";var RESIDENT_STRING_MIN_BYTES=32*1024,DEFAULT_RESIDENT_STRING_BUDGET_BYTES=64*1024*1024,RESIDENT_STRING_PREFIX="\0senpi-resident-string:v1:",OMIT_JSON_VALUE=Symbol("omit-json-value"),ResidentStringStore=class{constructor(options={}){this.strings=new Map,this.bytes=0,this.evictedCount=0,this.evictedBytes=0,this.maxBytes=options.maxBytes??DEFAULT_RESIDENT_STRING_BUDGET_BYTES,this.blobsDir=options.blobsDir}configure(options){this.blobsDir=options.blobsDir}clear(){this.strings.clear(),this.bytes=0,this.evictedCount=0,this.evictedBytes=0;let dir=this.blobsDir?.();if(dir)try{rmSync(dir,{force:!0,recursive:!0})}catch{}}spillResident(){if(this.blobsDir?.())for(let[id,text]of this.strings)this._writeBlob(id,text)&&(this.strings.delete(id),this.bytes-=Buffer2.byteLength(text,"utf8"))}stats(){return{blobCount:this.strings.size,blobBytes:this.bytes,evictedCount:this.evictedCount,evictedBytes:this.evictedBytes}}externalize(value){return transformJson(value,text=>this.externalizeString(text))}materialize(value,onMissing){return transformJson(value,text=>this.materializeString(text,onMissing))}resolvedBlobsDir(){return this.blobsDir?.()}externalizeInPlace(value){this._mutateStringsInPlace(value,new Set,text=>this.externalizeString(text))}materializeInPlace(value){this._mutateStringsInPlace(value,new Set,text=>this.materializeString(text))}_mutateStringsInPlace(value,seen,mutate){if(typeof value!="object"||value===null||seen.has(value))return;seen.add(value);let record=value;for(let key of Object.keys(record)){let current=record[key];typeof current=="string"?record[key]=mutate(current):typeof current=="object"&¤t!==null&&this._mutateStringsInPlace(current,seen,mutate)}}externalizeString(text){if(text.length<RESIDENT_STRING_MIN_BYTES||text.startsWith(RESIDENT_STRING_PREFIX))return text;let id=createHash("sha256").update(text,"utf8").digest("hex"),token=`${RESIDENT_STRING_PREFIX}${id}`;return this.strings.has(id)?(this.strings.delete(id),this.strings.set(id,text),token):(this.strings.set(id,text),this.bytes+=Buffer2.byteLength(text,"utf8"),this._enforceBudget(),token)}materializeString(text,onMissing){if(!text.startsWith(RESIDENT_STRING_PREFIX))return text;let id=text.slice(RESIDENT_STRING_PREFIX.length),resident=this.strings.get(id);if(resident!==void 0)return this.strings.delete(id),this.strings.set(id,resident),resident;let hydrated=this._readBlob(id);return hydrated!==void 0?hydrated:onMissing?.(id)??text}_enforceBudget(){for(;this.bytes>this.maxBytes&&this.strings.size>0;){let[oldestId,oldest]=this.strings.entries().next().value;if(!this._writeBlob(oldestId,oldest))return;this.strings.delete(oldestId),this.bytes-=Buffer2.byteLength(oldest,"utf8")}}_writeBlob(id,text){let dir=this.blobsDir?.();if(!dir)return!1;let final=join3(dir,`${id}.blob`),temp=`${final}.tmp`;try{mkdirSync(dir,{recursive:!0}),existsSync2(final)||(writeFileSync(temp,JSON.stringify({v:1,text}),"utf8"),renameSync(temp,final))}catch{try{rmSync(temp,{force:!0})}catch{}return!1}return this.evictedCount++,this.evictedBytes+=Buffer2.byteLength(text,"utf8"),!0}_readBlob(id){let dir=this.blobsDir?.();if(!dir)return;let file=join3(dir,`${id}.blob`);try{let parsed=JSON.parse(readFileSync(file,"utf8"));if(typeof parsed.text=="string")return parsed.text}catch{}try{rmSync(file,{force:!0})}catch{}}};function transformJson(value,transformString){let transformed=transformJsonValue(value,transformString,"",new WeakSet);if(transformed===OMIT_JSON_VALUE){let serialized=JSON.stringify(value);if(serialized===void 0)throw new SyntaxError("JSON-compatible value expected");return JSON.parse(serialized)}return transformed}function transformJsonValue(value,transformString,key,seen){if(typeof value=="string")return transformString(value);if(typeof value=="number")return Number.isFinite(value)?value:null;if(value===null||typeof value=="boolean")return value;if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value>"u"||typeof value=="function"||typeof value=="symbol")return OMIT_JSON_VALUE;if(seen.has(value))throw new TypeError("Converting circular structure to JSON");seen.add(value);let jsonValue=hasJsonSerializer(value)?value.toJSON(key):value;if(jsonValue!==value){let transformed2=transformJsonValue(jsonValue,transformString,key,seen);return seen.delete(value),transformed2}if(Array.isArray(value)){let transformed2=Array.from({length:value.length},(_item,index)=>{let item=value[index],transformedItem=transformJsonValue(item,transformString,String(index),seen);return transformedItem===OMIT_JSON_VALUE?null:transformedItem});return seen.delete(value),transformed2}let transformed={};for(let[key2,item]of Object.entries(value)){let transformedItem=transformJsonValue(item,transformString,String(key2),seen);transformedItem!==OMIT_JSON_VALUE&&Object.defineProperty(transformed,key2,{configurable:!0,enumerable:!0,value:transformedItem,writable:!0})}return seen.delete(value),transformed}function hasJsonSerializer(value){return"toJSON"in value&&typeof value.toJSON=="function"}var reserve;function reserveSessionWrite(path){reserve?.(path)}var liveWriters=new Set,writerRefs=new WeakMap;function registerSessionWriter(owner){if(writerRefs.has(owner))return;let ref=new WeakRef(owner);writerRefs.set(owner,ref),liveWriters.add(ref)}function unregisterSessionWriter(owner){let ref=writerRefs.get(owner);ref&&(writerRefs.delete(owner),liveWriters.delete(ref))}function hasOtherLiveSessionWriter(path,self){for(let ref of liveWriters){let owner=ref.deref();if(!owner){liveWriters.delete(ref);continue}if(owner!==self&&owner.isPersisted()&&owner.getSessionFile()===path)return!0}return!1}function uuidv7(){let ts=BigInt(Date.now()),bytes=randomBytes(10),hex=[(ts>>40n&0xffn).toString(16).padStart(2,"0"),(ts>>32n&0xffn).toString(16).padStart(2,"0"),(ts>>24n&0xffn).toString(16).padStart(2,"0"),(ts>>16n&0xffn).toString(16).padStart(2,"0"),(ts>>8n&0xffn).toString(16).padStart(2,"0"),(ts&0xffn).toString(16).padStart(2,"0"),(112|bytes[0]&15).toString(16).padStart(2,"0"),bytes[1].toString(16).padStart(2,"0"),(128|bytes[2]&63).toString(16).padStart(2,"0"),bytes[3].toString(16).padStart(2,"0"),...Array.from(bytes.slice(4),b=>b.toString(16).padStart(2,"0"))].join("");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20,32)}`}var contextMessageEntryIds=new WeakMap,SESSION_CONTEXT_ENTRY_ID="__piSessionContextEntryId";function withContextEntryId(entryId,message){return contextMessageEntryIds.set(message,entryId),message}function getSessionContextEntryId(message){return contextMessageEntryIds.get(message)}var CURRENT_SESSION_VERSION=3;function createSessionId(){return uuidv7()}function assertValidSessionId(id){if(!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id))throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character")}function generateId(byId){for(let i=0;i<100;i++){let id=randomUUID().slice(0,8);if(!byId.has(id))return id}return randomUUID()}function migrateV1ToV2(entries){let ids=new Set,prevId=null;for(let entry of entries){if(entry.type==="session"){entry.version=2;continue}if(entry.id=generateId(ids),entry.parentId=prevId,prevId=entry.id,entry.type==="compaction"){let comp=entry;if(typeof comp.firstKeptEntryIndex=="number"){let targetEntry=entries[comp.firstKeptEntryIndex];targetEntry&&targetEntry.type!=="session"&&(comp.firstKeptEntryId=targetEntry.id),delete comp.firstKeptEntryIndex}}}}function migrateV2ToV3(entries){for(let entry of entries){if(entry.type==="session"){entry.version=3;continue}if(entry.type==="message"){let msgEntry=entry;msgEntry.message&&msgEntry.message.role==="hookMessage"&&(msgEntry.message.role="custom")}}}function migrateToCurrentVersion(entries){let version=entries.find(e=>e.type==="session")?.version??1;return version>=CURRENT_SESSION_VERSION?!1:(version<2&&migrateV1ToV2(entries),version<3&&migrateV2ToV3(entries),!0)}function migrateSessionEntries(entries){migrateToCurrentVersion(entries)}function parseSessionEntries(content){let entries=[],lines=content.trim().split(`
|
|
26
26
|
`);for(let line of lines)if(line.trim())try{let entry=JSON.parse(line);entries.push(entry)}catch{}return entries}function getLatestCompactionEntry(entries){for(let i=entries.length-1;i>=0;i--)if(entries[i].type==="compaction")return entries[i];return null}function buildEntryIndex(entries,byId){if(byId)return byId;let index=new Map;for(let entry of entries)index.set(entry.id,entry);return index}function buildSessionPath(entries,leafId,byId){let index=buildEntryIndex(entries,byId),leaf;if(leafId===null)return[];if(leafId&&(leaf=index.get(leafId)),leaf??=entries[entries.length-1],!leaf)return[];let path=[],current=leaf;for(;current;)path.push(current),current=current.parentId?index.get(current.parentId):void 0;return path.reverse(),path}function getSessionContextSettings(path){let thinkingLevel="off",thinkingSelection,configurationUpdate,model=null,isModelSelectionExplicit=!1,isInFallbackWindow=!1,preFallbackThinkingLevel=thinkingLevel,preFallbackThinkingSelection=thinkingSelection;for(let entry of path)if(entry.type==="thinking_level_change")thinkingLevel=entry.thinkingLevel,thinkingSelection=entry.thinkingSelection;else if(entry.type==="configuration_update")configurationUpdate={effort:entry.reasoning.effort};else if(entry.type==="model_change")entry.reason==="fallback"?(isInFallbackWindow||(preFallbackThinkingLevel=thinkingLevel,preFallbackThinkingSelection=thinkingSelection,entry.originalProvider&&entry.originalModelId&&(model={provider:normalizeProviderId(entry.originalProvider),modelId:entry.originalModelId},isModelSelectionExplicit=!0)),isInFallbackWindow=!0):entry.reason==="fallback-revert"?(isInFallbackWindow&&(thinkingLevel=preFallbackThinkingLevel,thinkingSelection=preFallbackThinkingSelection),isInFallbackWindow=!1):(isInFallbackWindow=!1,entry.provider&&entry.modelId&&(model={provider:normalizeProviderId(entry.provider),modelId:entry.modelId},isModelSelectionExplicit=!0));else if(entry.type==="message"&&entry.message.role==="assistant"&&!isInFallbackWindow){if(isModelSelectionExplicit&&model?.provider===normalizeProviderId(entry.message.provider))continue;model={provider:normalizeProviderId(entry.message.provider),modelId:entry.message.model},isModelSelectionExplicit=!1}return isInFallbackWindow&&(thinkingLevel=preFallbackThinkingLevel,thinkingSelection=preFallbackThinkingSelection),{thinkingLevel,thinkingSelection,configurationUpdate,model}}function sessionEntryToContextMessages(entry){if(entry.type==="message"){let message=entry.message;return(message.role==="user"||message.role==="assistant"||message.role==="toolResult")&&message.content==null?[withContextEntryId(entry.id,{...message,content:[]})]:[withContextEntryId(entry.id,message)]}return entry.type==="configuration_update"?[withContextEntryId(entry.id,{role:"configurationUpdate",content:[],effort:entry.reasoning.effort,timestamp:new Date(entry.timestamp).getTime()})]:entry.type==="custom_message"?[withContextEntryId(entry.id,createCustomMessage(entry.customType,entry.content??[],entry.display,entry.details,entry.timestamp))]:entry.type==="branch_summary"&&entry.summary?[withContextEntryId(entry.id,createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp))]:entry.type==="compaction"?[withContextEntryId(entry.id,createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp,entry.details))]:[]}function buildContextEntries(entries,leafId,byId){let path=buildSessionPath(entries,leafId,byId),compaction=null;for(let entry of path)entry.type==="compaction"&&(compaction=entry);if(!compaction)return path;let compactionIdx=path.findIndex(entry=>entry.id===compaction.id);if(compactionIdx<0)return path;let contextEntries=[compaction],foundFirstKept=!1;for(let i=0;i<compactionIdx;i++){let entry=path[i];entry.type!=="compaction"&&(entry.id===compaction.firstKeptEntryId&&(foundFirstKept=!0),foundFirstKept&&contextEntries.push(entry))}return contextEntries.push(...path.slice(compactionIdx+1)),contextEntries}function buildSessionContext(entries,leafId,byId){let path=buildSessionPath(entries,leafId,byId),{thinkingLevel,thinkingSelection,model,configurationUpdate}=getSessionContextSettings(path);return{messages:buildContextEntries(entries,leafId,byId).flatMap(sessionEntryToContextMessages),thinkingLevel,thinkingSelection,model,configurationUpdate}}function getDefaultSessionDirPath(cwd,agentDir=getAgentDir()){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),safePath=`--${resolvedCwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return join4(resolvedAgentDir,"sessions",safePath)}function getDefaultSessionDir(cwd,agentDir=getAgentDir()){let sessionDir=getDefaultSessionDirPath(cwd,agentDir);return existsSync3(sessionDir)||mkdirSync2(sessionDir,{recursive:!0}),sessionDir}var SESSION_READ_BUFFER_SIZE=1024*1024,SESSION_HEADER_READ_BUFFER_SIZE=4096,MAX_SESSION_HEADER_SCAN_BYTES=1024*1024,SessionHeaderScanLimitError=class extends Error{constructor(filePath){super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`),this.name="SessionHeaderScanLimitError"}};function parseSessionEntryLine(line){if(!line.trim())return null;try{return JSON.parse(line)}catch{return null}}function loadEntriesFromFile(filePath){let resolvedFilePath=normalizePath(filePath);if(!existsSync3(resolvedFilePath))return[];let entries=[],pending="",fd=openSync(resolvedFilePath,"r");try{let decoder=new StringDecoder2("utf8"),buffer=Buffer.allocUnsafe(SESSION_READ_BUFFER_SIZE);for(;;){let bytesRead=readSync(fd,buffer,0,buffer.length,null);if(bytesRead===0)break;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
27
27
|
`,lineStart);for(;newlineIndex!==-1;){let entry=parseSessionEntryLine(pending.slice(lineStart,newlineIndex));entry&&entries.push(entry),lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
28
28
|
`,lineStart)}pending=pending.slice(lineStart)}pending+=decoder.end();let finalEntry=parseSessionEntryLine(pending);finalEntry&&entries.push(finalEntry)}finally{closeSync(fd)}if(entries.length===0)return entries;let header=entries[0];return header.type!=="session"||typeof header.id!="string"?[]:entries}function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync(filePath,"r");try{let decoder=new StringDecoder2("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
|
|
@@ -44,4 +44,4 @@ Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCw
|
|
|
44
44
|
${issue.sessionCwd}
|
|
45
45
|
|
|
46
46
|
continue in current cwd
|
|
47
|
-
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve3=>setTimeout(resolve3,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve3=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve3()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve3()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve3,reject)=>{let onConnect=()=>{cleanup(),resolve3()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3())})})}collectEvents(timeout=6e4){return new Promise((resolve3,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve3,reject)=>{let timeout=setTimeout(()=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id);let timeoutError=new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`);pending?.onReject?.(timeoutError),reject(timeoutError)},3e4);this.pendingRequests.set(id,{resolve:response=>{clearTimeout(timeout),resolve3(response)},reject:error=>{clearTimeout(timeout),reject(error)},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{stripAnsi,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,rejectedImageSources,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
|
|
47
|
+
${issue.fallbackCwd}`}var MissingSessionCwdError=class extends Error{constructor(issue){super(formatMissingSessionCwdError(issue)),this.name="MissingSessionCwdError",this.issue=issue}};function assertSessionCwdExists(sessionManager,fallbackCwd){let issue=getMissingSessionCwdIssue(sessionManager,fallbackCwd);if(issue)throw new MissingSessionCwdError(issue)}import{spawn}from"node:child_process";import{createConnection}from"node:net";function openStalledMessage(position){let queued=typeof position=="number"?` at queue position ${position}`:"",minutes=6e5/6e4;return`open_session was accepted by the host${queued} but not answered within ${minutes} minutes`}function armRequestDeadline(ms,message,expire){let timer=setTimeout(()=>expire(new Error(message())),ms);return{extend(nextMs,nextMessage){clearTimeout(timer),timer=setTimeout(()=>expire(new Error(nextMessage())),nextMs)},clear(){clearTimeout(timer)}}}var RpcCommandError=class extends Error{constructor(message,errorCode,errorData){super(message),this.name="RpcCommandError",this.errorCode=errorCode,this.errorData=errorData}};function isProviderAccountEvent(event){return event.type==="auth_accounts_changed"||event.type==="account_failover"}var RpcTransportGoneError=class extends Error{constructor(message="Shared RPC host is unavailable"){super(message),this.code="rpc_transport_gone",this.name="RpcTransportGoneError"}};function isTransportGoneError(error){return error instanceof RpcTransportGoneError||error instanceof Error&&(error.message==="Client not started"||error.message.startsWith("RPC transport is not writable.")||error.message==="RPC socket closed")}var RpcClientOpenInFlightError=class extends Error{constructor(){super("An open_session request is already in flight"),this.code="open_session_in_flight",this.name="RpcClientOpenInFlightError"}},MAX_PENDING_SESSION_EVENTS=512,MAX_PENDING_SESSION_EVENT_BYTES=1024*1024,RpcClient=class{constructor(options={}){this.process=null,this.socket=null,this.stopReadingStdout=null,this.eventListeners=[],this.pendingRequests=new Map,this.requestId=0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.stderr="",this.exitError=null,this.disconnectNotified=!1,this.stopping=!1,this.options=options}async start(){if(this.process||this.socket)throw new Error("Client already started");if(this.exitError=null,this.stopping=!1,this.disconnectNotified=!1,this.options.socketPath){await this.startSocket(this.options.socketPath);return}let cliPath=this.options.cliPath??"dist/cli.js",args=["--mode","rpc"];this.options.provider&&args.push("--provider",this.options.provider),this.options.model&&args.push("--model",this.options.model),this.options.args&&args.push(...this.options.args);let childProcess=spawn("node",[cliPath,...args],{cwd:this.options.cwd,env:{...process.env,SENPI_RUNTIME:"node",...this.options.env},stdio:["pipe","pipe","pipe"],windowsHide:!0});if(this.process=childProcess,childProcess.stderr?.on("data",data=>{this.stderr+=data.toString(),process.stderr.write(data)}),childProcess.once("exit",(code,signal)=>{if(this.process!==childProcess)return;let error=this.createProcessExitError(code,signal);this.exitError=error,this.rejectPendingRequests(error)}),childProcess.once("error",error=>{if(this.process!==childProcess)return;let processError=new Error(`Agent process error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=processError,this.rejectPendingRequests(processError)}),childProcess.stdin?.on("error",error=>{if(this.process!==childProcess)return;let stdinError=this.exitError??new Error(`Agent process stdin error: ${error.message}. Stderr: ${this.stderr}`);this.exitError=stdinError,this.rejectPendingRequests(stdinError)}),this.stopReadingStdout=attachJsonlLineReader(childProcess.stdout,line=>{this.handleLine(line)}),await new Promise(resolve3=>setTimeout(resolve3,100)),this.process.exitCode!==null){let error=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=error,error}}async stop(){if(this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,this.socket){this.stopping=!0,this.stopReadingStdout?.(),this.stopReadingStdout=null,this.socket.destroy(),this.socket=null,this.sessionId=void 0,this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.notifyDisconnect(new RpcTransportGoneError);return}this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.process.kill("SIGTERM"),await new Promise(resolve3=>{let timeout=setTimeout(()=>{this.process?.kill("SIGKILL"),resolve3()},1e3);this.process?.on("exit",()=>{clearTimeout(timeout),resolve3()})}),this.process=null,this.pendingRequests.clear())}async startSocket(path){let secret=process.platform==="win32"?await readSocketSecret(socketSecretPath(path)):void 0,socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));this.socket=socket,await new Promise((resolve3,reject)=>{let onConnect=()=>{cleanup(),resolve3()},onError=error=>{cleanup(),this.socket=null,reject(error)},cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)};socket.once("connect",onConnect),socket.once("error",onError)}),secret&&sendSocketHandshake(socket,secret),this.stopReadingStdout=attachJsonlLineReader(socket,line=>this.handleLine(line)),socket.once("close",()=>{this.socket===socket&&(this.socket=null,this.notifyDisconnect(new RpcTransportGoneError))}),socket.once("error",error=>{this.socket===socket&&this.notifyDisconnect(new RpcTransportGoneError)})}onEvent(listener){return this.eventListeners.push(listener),()=>{let index=this.eventListeners.indexOf(listener);index!==-1&&this.eventListeners.splice(index,1)}}getStderr(){return this.stderr}async setClientInfo(width,capabilities){await this.send({type:"set_client_info",width,capabilities},this.sessionId!==void 0)}async openSession(options){if(this.pendingOpenSession)throw new RpcClientOpenInFlightError;this.pendingOpenSession=!0;try{let response=await this.send({type:"open_session",...options},!1),opened=this.getData(response);return this.sessionId=opened.sessionId,this.pendingOpenSession=!1,this.flushPendingSessionEvents(),opened}catch(error){throw this.pendingOpenSession=!1,this.pendingSessionEvents=[],this.pendingSessionEventBytes=0,error}}async sendExtensionUIResponse(response){await this.send(response,!0,void 0,!1)}async sendExtensionUIProgress(progress){await this.send(progress,!0,void 0,!1)}async closeSession(sessionId=this.sessionId){if(sessionId){try{await this.send({type:"close_session",sessionId},!1)}catch(error){if(!isTransportGoneError(error))throw error}this.sessionId===sessionId&&(this.sessionId=void 0)}}async listSessions(){let response=await this.send({type:"list_sessions"},!1);return this.getData(response).sessions}async prompt(message,optionsOrImages){let options=Array.isArray(optionsOrImages)?{images:optionsOrImages}:optionsOrImages??{},response=await this.send({type:"prompt",message,...options.images?{images:options.images}:{},...options.streamingBehavior?{streamingBehavior:options.streamingBehavior}:{},...options.thinkingLevel?{thinkingLevel:options.thinkingLevel}:{},...options.sessionTitlePrompt!==void 0?{sessionTitlePrompt:options.sessionTitlePrompt}:{},...options.expandPromptTemplates!==void 0?{expandPromptTemplates:options.expandPromptTemplates}:{}},!0,{onResponse:wireResponse=>{if(!wireResponse.success){options?.preflightResult?.(!1);return}let data=wireResponse.data;options?.promptDisposition?.(data?.disposition??"handled"),options?.preflightResult?.(!0)},onReject:()=>{options?.preflightResult?.(!1)}});if(!response.success)throw new Error(response.error)}async appendUserMessage(content){await this.send({type:"append_user_message",content})}async appendSessionEntry(entry){await this.send({type:"append_session_entry",entry})}async sendCustomMessage(message,options){await this.send({type:"send_custom_message",...message,...options})}async steer(message,images,recovery){await this.send({type:"steer",message,images,enqueueOrder:recovery?.enqueueOrder})}async followUp(message,images,recovery){await this.send({type:"follow_up",message,images,enqueueOrder:recovery?.enqueueOrder})}async abort(){try{await this.send({type:"abort"})}catch(error){if(!isTransportGoneError(error))throw error}}async abortCompaction(){await this.send({type:"abort_compaction"})}async reload(){let response=await this.send({type:"reload"});return this.getData(response)}async checkReloadVeto(){let response=await this.send({type:"check_reload_veto"});return this.getData(response)}async clearQueue(options){let response=await this.send({type:"clear_queue",abortWillFollow:options?.abortWillFollow});return this.getData(response)}async getSteeringMessages(){let response=await this.send({type:"get_steering_messages"});return this.getData(response).messages}async getFollowUpMessages(){let response=await this.send({type:"get_follow_up_messages"});return this.getData(response).messages}async abortBranchSummary(){await this.send({type:"abort_branch_summary"})}async recordBashResult(command,result,excludeFromContext){await this.send({type:"record_bash_result",command,result,excludeFromContext})}async setLabel(entryId,label){await this.send({type:"set_label",entryId,label})}async newSession(parentSession){let response=await this.send({type:"new_session",parentSession});return this.getData(response)}async getState(){let response=await this.send({type:"get_state"});return this.getData(response)}async setModel(provider,modelId){let response=await this.send({type:"set_model",provider,modelId});return this.getData(response)}async setFavoriteModels(models){await this.send({type:"set_favorite_models",models})}async setScopedModels(models){await this.send({type:"set_scoped_models",models})}async cycleModel(direction="forward"){let response=await this.send({type:"cycle_model",direction});return this.getData(response)}async getAvailableModels(){let response=await this.send({type:"get_available_models"});return this.getData(response).models}async setThinkingLevel(level,options){let response=await this.send({type:"set_thinking_level",level,scope:options?.scope});if(!response.success)throw new Error(response.error)}async cycleThinkingLevel(){let response=await this.send({type:"cycle_thinking_level"});return this.getData(response)}async getAvailableThinkingLevels(){let response=await this.send({type:"get_available_thinking_levels"});return this.getData(response).levels}async setFastMode(enabled){let response=await this.send({type:"set_fast_mode",enabled});return this.getData(response)}async getFastMode(){let response=await this.send({type:"get_fast_mode"});return this.getData(response)}async setSteeringMode(mode){await this.send({type:"set_steering_mode",mode})}async setFollowUpMode(mode){await this.send({type:"set_follow_up_mode",mode})}async compact(customInstructions){let response=await this.send({type:"compact",customInstructions});return this.getData(response)}async setAutoCompaction(enabled){await this.send({type:"set_auto_compaction",enabled})}async setAutoRetry(enabled){await this.send({type:"set_auto_retry",enabled})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(command,options){let response=await this.send({type:"bash",command,excludeFromContext:options?.excludeFromContext,executionId:options?.executionId,operations:options?.operations});return this.getData(response)}async navigateTree(targetId,options){let response=await this.send({type:"navigate_tree",targetId,...options});return this.getData(response)}async abortBash(){await this.send({type:"abort_bash"})}async cleanupBashOutput(path){await this.send({type:"cleanup_bash_output",path})}async getSessionStats(){let response=await this.send({type:"get_session_stats"});return this.getData(response)}async exportHtml(outputPath,themeName){let response=await this.send({type:"export_html",outputPath,themeName});return this.getData(response)}async exportJsonl(outputPath){let response=await this.send({type:"export_jsonl",outputPath});return this.getData(response)}async switchSession(sessionPath,options){let response=await this.send({type:"switch_session",sessionPath,cwdOverride:options?.cwdOverride});return this.getData(response)}async fork(entryId,options){let response=await this.send({type:"fork",entryId,position:options?.position});return this.getData(response)}async clone(){let response=await this.send({type:"clone"});return this.getData(response)}async getForkMessages(){let response=await this.send({type:"get_fork_messages"});return this.getData(response).messages}async getEntries(since){let response=await this.send({type:"get_entries",since});return this.getData(response)}async getTree(){let response=await this.send({type:"get_tree"});return this.getData(response)}async editAssistantMessage(entryId,text,options={}){let response=await this.send({type:"edit_assistant_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async editUserMessage(entryId,text,options={}){let response=await this.send({type:"edit_user_message",entryId,text,expectedLeafId:options.expectedLeafId,summarize:options.summarize,customInstructions:options.customInstructions});return this.getData(response)}async getLastAssistantText(){let response=await this.send({type:"get_last_assistant_text"});return this.getData(response).text}async setSessionName(name){await this.send({type:"set_session_name",name})}async importJsonl(inputPath,cwdOverride){let response=await this.send({type:"import_jsonl",inputPath,cwdOverride});return this.getData(response)}async getMessages(){let response=await this.send({type:"get_messages"});return this.getData(response).messages}async getMedia(toolCallId,contentIndex){let response=await this.send({type:"get_media",toolCallId,contentIndex});return this.getData(response).content}async getCommands(){let response=await this.send({type:"get_commands"});return this.getData(response).commands}async requestExtension(name,data){let response=await this.send({type:"extension_request",name,...data===void 0?{}:{data}});return this.getData(response)}async getProviderAccounts(provider){let response=await this.send({type:"get_provider_accounts",provider});return this.getData(response).accounts}async pinProviderAccount(provider,name){await this.send({type:"account_pin",provider,name})}async removeProviderAccount(provider,name){await this.send({type:"account_remove",provider,name})}waitForIdle(timeout=6e4){return new Promise((resolve3,reject)=>{let timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3())})})}collectEvents(timeout=6e4){return new Promise((resolve3,reject)=>{let events=[],timer=setTimeout(()=>{unsubscribe(),reject(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},timeout),unsubscribe=this.onEvent(event=>{isProviderAccountEvent(event)||event.type==="extension_event"||event.type==="bash_start"||event.type==="bash_end"||event.type==="extension_ui_request"||event.type==="session_replaced"||event.type==="session_parked"||event.type==="queued"||(events.push(event),event.type==="agent_settled"&&(clearTimeout(timer),unsubscribe(),resolve3(events)))})})}async promptAndWait(message,images,timeout=6e4){let eventsPromise=this.collectEvents(timeout);return await this.prompt(message,images?{images}:void 0),eventsPromise}handleLine(line){try{let data=JSON.parse(line);if(data.type==="response"&&data.id&&this.pendingRequests.has(data.id)){let pending=this.pendingRequests.get(data.id);this.pendingRequests.delete(data.id),pending.onResponse?.(data),pending.resolve(data);return}if(data.type==="queued"&&typeof data.for_request=="string"&&this.pendingRequests.get(data.for_request)?.onQueued?.(data.position),typeof data.sessionId=="string"&&data.sessionId!==this.sessionId){if(this.pendingOpenSession){let bytes=Buffer.byteLength(line);for(this.pendingSessionEvents.push({sessionId:data.sessionId,event:data,bytes}),this.pendingSessionEventBytes+=bytes;this.pendingSessionEvents.length>MAX_PENDING_SESSION_EVENTS||this.pendingSessionEventBytes>MAX_PENDING_SESSION_EVENT_BYTES;){let oldest=this.pendingSessionEvents.shift();if(!oldest)break;this.pendingSessionEventBytes-=oldest.bytes}}return}for(let listener of this.eventListeners)listener(data)}catch{}}flushPendingSessionEvents(){let pending=this.pendingSessionEvents;this.pendingSessionEvents=[],this.pendingSessionEventBytes=0;for(let{sessionId,event}of pending)if(sessionId===this.sessionId)for(let listener of this.eventListeners)listener(event)}createProcessExitError(code,signal){return new Error(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`)}notifyDisconnect(error){this.rejectPendingRequests(error),!this.disconnectNotified&&!this.stopping&&(this.disconnectNotified=!0,this.options.onDisconnect?.(error))}rejectPendingRequests(error){for(let pending of this.pendingRequests.values())pending.onReject?.(error),pending.reject(error);this.pendingRequests.clear()}async send(command,route=!0,hooks,expectResponse=!0){let childProcess=this.process,stream=this.socket??childProcess?.stdin;if(!stream)throw new RpcTransportGoneError;if(this.exitError)throw this.exitError;if(childProcess?.exitCode!==null&&childProcess?.exitCode!==void 0){let error=this.createProcessExitError(childProcess.exitCode,childProcess.signalCode);throw this.exitError=error,error}if(stream.destroyed||!stream.writable){let error=new RpcTransportGoneError;throw this.notifyDisconnect(error),error}let ownId=command.type==="extension_ui_response"||command.type==="extension_ui_progress"?command.id:void 0,id=ownId??`req_${++this.requestId}`,fullCommand={...command,...route&&this.sessionId&&!("sessionId"in command)?{sessionId:this.sessionId}:{},...ownId===void 0?{id}:{}};return expectResponse?new Promise((resolve3,reject)=>{let deadline=armRequestDeadline(3e4,()=>`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`,timeoutError=>{let pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(timeoutError),reject(timeoutError)});this.pendingRequests.set(id,{resolve:response=>{deadline.clear(),resolve3(response)},reject:error=>{deadline.clear(),reject(error)},...command.type==="open_session"?{onQueued:position=>deadline.extend(6e5,()=>openStalledMessage(position))}:{},...hooks?.onResponse?{onResponse:hooks.onResponse}:{},...hooks?.onReject?{onReject:hooks.onReject}:{}});try{stream.write(serializeJsonLine(fullCommand))}catch(error){let writeError=error instanceof Error?error:new Error(String(error)),pending=this.pendingRequests.get(id);this.pendingRequests.delete(id),pending?.onReject?.(writeError),pending?.reject(writeError)}}):(stream.write(serializeJsonLine(fullCommand)),Promise.resolve({type:"response",command:command.type,success:!0}))}getData(response){if(!response.success){let errorResponse=response;throw errorResponse.errorCode==="missing_session_cwd"&&errorResponse.errorData?new MissingSessionCwdError(errorResponse.errorData):new RpcCommandError(errorResponse.error,errorResponse.errorCode,errorResponse.errorData)}return response.data}};export{REPOSITORY_IDENTITY_ENTRY_TYPE,readRepositoryIdentity,compareRepositoryIdentities,parseRepositoryIdentity,sameRepositoryIdentity,readFileLines,listSessionsFromDir,reserveSessionWrite,unregisterSessionWriter,resolveEnvironmentContext,environmentContextMessageIfChanged,rejectedImageSources,GOAL_CONTINUATION_MESSAGE_TYPE,isContextExcludedCustomMessage,createBranchSummaryMessage,createCompactionSummaryMessage,createCustomMessage,convertToLlm,TRANSPORT_IMAGE_BUDGET_BYTES,convertToLlmForTransport,SESSION_CONTEXT_ENTRY_ID,getSessionContextEntryId,CURRENT_SESSION_VERSION,assertValidSessionId,migrateSessionEntries,parseSessionEntries,getLatestCompactionEntry,sessionEntryToContextMessages,buildContextEntries,buildSessionContext,getDefaultSessionDir,loadEntriesFromFile,SessionManager,stripAnsi,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,executeBashWithOperations,getMissingSessionCwdIssue,formatMissingSessionCwdPrompt,MissingSessionCwdError,assertSessionCwdExists,RpcCommandError,RpcTransportGoneError,isTransportGoneError,RpcClientOpenInFlightError,RpcClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CredentialStoreBusyError,FILE_STORAGE_LOCK_OPTIONS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-7X72IACK.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{require_proper_lockfile}from"./chunk-
|
|
2
|
+
import{CredentialStoreBusyError,FILE_STORAGE_LOCK_OPTIONS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-7X72IACK.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import{getAgentDir}from"./chunk-Y65WFI5H.js";import{__toESM}from"./chunk-IKOFCODM.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{createHmac,randomBytes,randomUUID}from"node:crypto";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";var CREDENTIAL_POOL_STATE_FILENAME="credential-pool-state.json",HEX_256_BIT=/^[0-9a-f]{64}$/,leaseSchema=external_exports.strictObject({id:external_exports.string().min(1).max(128),expiresAt:external_exports.number().int().positive()}),slotStateSchema=external_exports.strictObject({stateVersion:external_exports.number().int().nonnegative(),blockedUntil:external_exports.number().int().positive().optional(),blockReason:external_exports.enum(["auth_error","rate_limit","account_disabled"]).optional(),failureCount:external_exports.number().int().nonnegative().optional(),lastSuccessAt:external_exports.number().int().positive().optional(),credentialRevision:external_exports.string().regex(HEX_256_BIT).optional(),lease:leaseSchema.optional()}),documentSchema=external_exports.strictObject({schemaVersion:external_exports.literal(1),installationKey:external_exports.string().regex(HEX_256_BIT),providers:external_exports.record(external_exports.string(),external_exports.strictObject({lanes:external_exports.record(external_exports.string(),external_exports.strictObject({slots:external_exports.record(external_exports.string(),slotStateSchema)}))}))});function credentialPoolStatePath(agentDir=getAgentDir()){return join(agentDir,CREDENTIAL_POOL_STATE_FILENAME)}var FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384};function freshDocument(){return{schemaVersion:1,installationKey:randomBytes(32).toString("hex"),providers:{}}}function parseDocument(content){try{let parsed=documentSchema.safeParse(JSON.parse(content));return parsed.success?parsed.data:freshDocument()}catch{return freshDocument()}}function slotHealth(state,now){return state?state.blockReason==="auth_error"||state.blockReason==="account_disabled"||state.blockedUntil!==void 0&&state.blockedUntil>now?"blocked":state.blockedUntil!==void 0&&state.lease!==void 0&&state.lease.expiresAt>now?"half_open":"ready":"ready"}var CredentialSlotRepository=class{constructor(path=credentialPoolStatePath()){this.path=path}ensureFile(){existsSync(this.path)||(mkdirSync(dirname(this.path),{recursive:!0,mode:448}),writeFileSync(this.path,JSON.stringify(freshDocument(),null,2),FILE_WRITE_OPTIONS))}async withDocument(fn){this.ensureFile();let release=await this.acquire();try{let document=parseDocument(readFileSync(this.path,"utf-8")),{result,next}=fn(document);return next&&writeFileSync(this.path,JSON.stringify(next,null,2),FILE_WRITE_OPTIONS),result}finally{await release()}}async acquire(){let startedAt=Date.now(),attempt=0;for(;;)try{return await import_proper_lockfile.default.lock(this.path,FILE_STORAGE_LOCK_OPTIONS)}catch(error){if(!isLockError(error))throw error;let waitedMs=Date.now()-startedAt;if(waitedMs>=FILE_STORAGE_LOCK_RETRY_BUDGET_MS)throw new CredentialStoreBusyError(this.path,waitedMs,error);let delayMs=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_BUDGET_MS-waitedMs);attempt++,await new Promise(resolve=>setTimeout(resolve,delayMs))}}async installationKey(){return this.withDocument(document=>({result:document.installationKey,next:document}))}async envCredentialRevision(envVarName,envValue){let key=await this.installationKey();return createHmac("sha256",key).update(`${envVarName}\0${envValue}`).digest("hex")}async storedCredentialRevision(providerId,slotName,material){let key=await this.installationKey();return createHmac("sha256",key).update(`${providerId}\0${slotName}\0${material.key??""}\0${material.access??""}\0${material.refresh??""}`).digest("hex")}async listSlots(providerId,laneId){return this.withDocument(document=>({result:{...document.providers[providerId]?.lanes[laneId]?.slots}}))}async mutateSlotState(providerId,laneId,slotId,fn){return this.withDocument(document=>{let provider=document.providers[providerId]??{lanes:{}},lane=provider.lanes[laneId]??{slots:{}},current=lane.slots[slotId],mutated=fn(current),slots={...lane.slots},result;mutated===void 0?delete slots[slotId]:(result={...mutated,stateVersion:(current?.stateVersion??0)+1},slots[slotId]=result);let next={...document,providers:{...document.providers,[providerId]:{lanes:{...provider.lanes,[laneId]:{slots}}}}};return{result,next}})}};async function acquireHalfOpenLease(repository,providerId,laneId,slotId,options={}){let now=options.now??Date.now(),leaseTtlMs=options.leaseTtlMs??3e4,lease;return await repository.mutateSlotState(providerId,laneId,slotId,current=>{if(!current)return current;let expired=current.blockedUntil!==void 0&¤t.blockedUntil<=now,leaseLive=current.lease!==void 0&¤t.lease.expiresAt>now;return!expired||leaseLive||current.blockReason==="auth_error"?current:(lease={leaseId:randomUUID(),expiresAt:now+leaseTtlMs},{...current,lease:{id:lease.leaseId,expiresAt:lease.expiresAt}})}),lease}export{CREDENTIAL_POOL_STATE_FILENAME,credentialPoolStatePath,slotHealth,CredentialSlotRepository,acquireHalfOpenLease};
|