@code-yeongyu/senpi 2026.9.5 → 2026.9.7-2
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 +104 -0
- package/dist/core/agent-session.d.ts +60 -5
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +262 -78
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +6 -2
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +6 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/stuck-overflow.d.ts +11 -0
- package/dist/core/compaction/stuck-overflow.d.ts.map +1 -0
- package/dist/core/compaction/stuck-overflow.js +17 -0
- package/dist/core/compaction/stuck-overflow.js.map +1 -0
- package/dist/core/extensions/builtin/cache-keepalive/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/cache-keepalive/index.js +3 -21
- package/dist/core/extensions/builtin/cache-keepalive/index.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.js +2 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/prompt-bridge.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js +36 -19
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-binding.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js +21 -10
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-commit-boundary.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts +4 -17
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js +23 -33
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-continuity.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.js +15 -2
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-registry-pump.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js +1 -0
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-stream.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js +5 -3
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-sync.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js +8 -3
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-attempt.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.d.ts +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.js +2 -3
- package/dist/core/extensions/builtin/claude-sdk-oauth/session-turn-claim.js.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts +6 -5
- package/dist/core/extensions/builtin/claude-sdk-oauth/tools.d.ts.map +1 -1
- package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js +6 -5
- package/dist/core/extensions/builtin/claude-sdk-oauth/tools.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts +8 -0
- package/dist/core/extensions/builtin/compaction/circuit-breaker.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/circuit-breaker.js +8 -0
- package/dist/core/extensions/builtin/compaction/circuit-breaker.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +4 -0
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +40 -20
- package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts +18 -0
- package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.d.ts.map +1 -0
- package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js +20 -0
- package/dist/core/extensions/builtin/compaction/fallback-failed-turn-normalization.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/index.js +2 -2
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/lane-policy.d.ts +12 -0
- package/dist/core/extensions/builtin/compaction/lane-policy.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/lane-policy.js +47 -18
- package/dist/core/extensions/builtin/compaction/lane-policy.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/openai-remote-convert.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/openai-remote-convert.js +2 -0
- package/dist/core/extensions/builtin/compaction/openai-remote-convert.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/retained-message-safety.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/retained-message-safety.js +14 -1
- package/dist/core/extensions/builtin/compaction/retained-message-safety.js.map +1 -1
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.js +6 -4
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.js.map +1 -1
- package/dist/core/extensions/builtin/goal/cache-warm.d.ts +19 -1
- package/dist/core/extensions/builtin/goal/cache-warm.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/cache-warm.js +23 -10
- package/dist/core/extensions/builtin/goal/cache-warm.js.map +1 -1
- package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts +1 -0
- package/dist/core/extensions/builtin/goal/continuation-recovery.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/continuation-recovery.js +2 -0
- package/dist/core/extensions/builtin/goal/continuation-recovery.js.map +1 -1
- package/dist/core/extensions/builtin/goal/continuation.d.ts +3 -1
- package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/continuation.js +4 -0
- package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts +3 -0
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +14 -3
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.js +7 -3
- package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/plugin-manifest.js +2 -2
- package/dist/core/extensions/builtin/hooks/plugin-manifest.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/safety.js +2 -2
- package/dist/core/extensions/builtin/hooks/safety.js.map +1 -1
- package/dist/core/extensions/builtin/permission-system/external-dir.d.ts.map +1 -1
- package/dist/core/extensions/builtin/permission-system/external-dir.js +5 -22
- package/dist/core/extensions/builtin/permission-system/external-dir.js.map +1 -1
- package/dist/core/extensions/builtin/permission-system/parsers.d.ts.map +1 -1
- package/dist/core/extensions/builtin/permission-system/parsers.js +5 -7
- package/dist/core/extensions/builtin/permission-system/parsers.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +2 -2
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +8 -2
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-registry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/monitor-registry.js +14 -7
- package/dist/core/extensions/builtin/terminal/monitor-registry.js.map +1 -1
- package/dist/core/messages.d.ts +7 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +2 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/core/package-identity.d.ts +12 -0
- package/dist/core/package-identity.d.ts.map +1 -0
- package/dist/core/package-identity.js +57 -0
- package/dist/core/package-identity.js.map +1 -0
- package/dist/core/resource-loader.d.ts +0 -2
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -60
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/retry-fallback/controller.d.ts.map +1 -1
- package/dist/core/retry-fallback/controller.js +5 -4
- package/dist/core/retry-fallback/controller.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +5 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +12 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +29 -3
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +6 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +4 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/bounded-realpath.d.ts +28 -0
- package/dist/core/tools/bounded-realpath.d.ts.map +1 -0
- package/dist/core/tools/bounded-realpath.js +53 -0
- package/dist/core/tools/bounded-realpath.js.map +1 -0
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js +15 -13
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/filesystem-policy.d.ts +7 -0
- package/dist/core/tools/filesystem-policy.d.ts.map +1 -1
- package/dist/core/tools/filesystem-policy.js +25 -15
- package/dist/core/tools/filesystem-policy.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +13 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/memory-tips.d.ts.map +1 -1
- package/dist/modes/interactive/tips/catalog/memory-tips.js +6 -0
- package/dist/modes/interactive/tips/catalog/memory-tips.js.map +1 -1
- package/dist/modes/interactive/tips/catalog/subagent-tips.d.ts.map +1 -1
- package/dist/modes/interactive/tips/catalog/subagent-tips.js +6 -0
- package/dist/modes/interactive/tips/catalog/subagent-tips.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +31 -5
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/host-watchdog.d.ts +11 -0
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -1
- package/dist/modes/rpc/host-watchdog.js +16 -2
- package/dist/modes/rpc/host-watchdog.js.map +1 -1
- package/dist/modes/rpc/multi-session-host.d.ts +3 -7
- package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +57 -29
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +1 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js +0 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +1 -4
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +0 -15
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/dist/modes/rpc/socket-ownership.d.ts +46 -0
- package/dist/modes/rpc/socket-ownership.d.ts.map +1 -0
- package/dist/modes/rpc/socket-ownership.js +178 -0
- package/dist/modes/rpc/socket-ownership.js.map +1 -0
- package/dist/utils/fs-watch.d.ts +17 -0
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js +38 -10
- package/dist/utils/fs-watch.js.map +1 -1
- package/dist/utils/paths.d.ts +33 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +109 -3
- package/dist/utils/paths.js.map +1 -1
- package/docs/compaction-guide.md +2 -2
- package/docs/compaction.md +2 -2
- package/docs/development.md +3 -2
- package/docs/providers.md +1 -1
- package/docs/rpc.md +6 -7
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +74 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +34 -5
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/protocol.ts +1 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/bridge/reserved.ts +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/extension/runtime-factory.ts +3 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/extension/session-manager.ts +7 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +7 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/kernel.ts +6 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +73 -129
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +2 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/interrupt-bounds.ts +66 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +3 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/run-queue.ts +18 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +59 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +10 -6
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +16 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.d.ts +25 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-shell-capture.js +70 -8
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-slot.ts +106 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-startup.ts +70 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel-contract.ts +3 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +11 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/kernel.ts +6 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/session-env.ts +56 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/runtime-asset.ts +40 -14
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-contract.ts +3 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +9 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/output/output-meta.ts +26 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -5
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-execution.ts +9 -11
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-contract.ts +45 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +43 -71
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-notification.ts +4 -5
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-snapshot.ts +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-status.ts +30 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +1 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-notification-queue.ts +2 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/image.ts +12 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/interrupt-note.ts +29 -15
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +2 -0
- 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 +3 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +17 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +6 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.d.ts +2 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +5 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts +7 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +2 -0
- 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/mistral-conversations.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/mistral-conversations.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +15 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +4 -4
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cerebras.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/moonshotai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.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/providers/data/vercel-ai-gateway.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/faux.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/faux.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/faux.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +8 -1
- 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/estimate.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js +14 -3
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-helpers.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"lifecycle-helpers.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAIlE,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAErE,OAAO,EAGN,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAE5B,MAAM,mBAAmB,CAAC;AAa3B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAEvC,KAAK,iCAAiC,GAAG,OAAO,CAAC,uBAAuB,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAEhG,KAAK,+BAA+B,GAAG;IACtC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;IACpD,QAAQ,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,iCAAiC,KAAK,MAAM,CAAC;IACzE,QAAQ,CAAC,uBAAuB,EAAE,MAAM,IAAI,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,+BAA+B,GAAG;IAC7C,QAAQ,CAAC,mBAAmB,EAAE,OAAO,CAAC;IACtC,QAAQ,CAAC,uBAAuB,EAAE,MAAM,IAAI,CAAC;CAC7C,CAAC;AAQF;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACpC,GAAG,EAAE,gBAAgB,EACrB,kBAAkB,EAAE,MAAM,EAC1B,IAAI,EAAE,IAAI,GAAG,IAAI,GACf,IAAI,IAAI,IAAI,CASd;AAED,sFAAsF;AACtF,wBAAsB,6BAA6B,CAClD,EAAE,EAAE,YAAY,EAChB,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,+BAA+B,GACtC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAiBtB;AAED,mHAAmH;AACnH,wBAAsB,qBAAqB,CAC1C,EAAE,EAAE,YAAY,EAChB,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,+BAA+B,GACtC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CA2BtB;AAED,wBAAgB,qCAAqC,CACpD,GAAG,EAAE,gBAAgB,EACrB,IAAI,EAAE,IAAI,EACV,iBAAiB,EAAE,MAAM,GACvB,MAAM,CAKR;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,CAM3E;AAiBD,wBAAgB,gCAAgC,CAC/C,GAAG,EAAE,gBAAgB,EACrB,aAAa,EAAE,OAAO,CAAC,YAAY,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC,GAAG,SAAS,GACrE,OAAO,CAET;AAuDD,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAK7E"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { isTurnStuckOnContextOverflow } from "../../../compaction/stuck-overflow.js";
|
|
1
2
|
import { GOAL_CONTINUATION_MESSAGE_TYPE } from "../../../messages.js";
|
|
2
3
|
import { getLatestPhasesFromBranchEntries } from "../todotools/state.js";
|
|
3
4
|
import { buildGoalContinuationSignature, evaluateGoalContinuation, hashAssistantText, } from "./continuation.js";
|
|
4
|
-
import { CONTINUATION_CAP_BLOCKED_REASON, continuationCapRecoveryHint, LENGTH_EXHAUSTED_BLOCKED_REASON, REPETITION_BLOCKED_REASON, UNATTENDED_CONTINUATION_BLOCKED_REASON, } from "./continuation-recovery.js";
|
|
5
|
+
import { CONTEXT_OVERFLOW_BLOCKED_REASON, CONTINUATION_CAP_BLOCKED_REASON, continuationCapRecoveryHint, LENGTH_EXHAUSTED_BLOCKED_REASON, REPETITION_BLOCKED_REASON, UNATTENDED_CONTINUATION_BLOCKED_REASON, } from "./continuation-recovery.js";
|
|
5
6
|
import { buildContinuationPrompt } from "./prompt.js";
|
|
6
7
|
import { recordContinuationDelivered, updateGoal } from "./store.js";
|
|
7
8
|
import { goalStoreRef } from "./store-ref.js";
|
|
@@ -56,6 +57,7 @@ export async function queueGoalContinuation(pi, ctx, goal, options) {
|
|
|
56
57
|
recentNormalizedOutputHashes: [],
|
|
57
58
|
toollessContinuationStreak: 0,
|
|
58
59
|
continuationPending: options.continuationPending,
|
|
60
|
+
lastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistantFromEntries(ctx.sessionManager.getBranch())),
|
|
59
61
|
},
|
|
60
62
|
content: () => buildContinuationPrompt(goal),
|
|
61
63
|
markContinuationPending: options.markContinuationPending,
|
|
@@ -76,12 +78,19 @@ export function lastAssistantText(messages) {
|
|
|
76
78
|
return "";
|
|
77
79
|
}
|
|
78
80
|
function lastAssistantTextFromEntries(entries) {
|
|
81
|
+
const assistant = lastAssistantFromEntries(entries);
|
|
82
|
+
return assistant === undefined ? "" : textContent(assistant);
|
|
83
|
+
}
|
|
84
|
+
function lastAssistantFromEntries(entries) {
|
|
79
85
|
for (let index = entries.length - 1; index >= 0; index--) {
|
|
80
86
|
const entry = entries[index];
|
|
81
87
|
if (entry?.type === "message" && entry.message.role === "assistant")
|
|
82
|
-
return
|
|
88
|
+
return entry.message;
|
|
83
89
|
}
|
|
84
|
-
return
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
export function isLastTurnStuckOnContextOverflow(ctx, lastAssistant) {
|
|
93
|
+
return lastAssistant !== undefined && isTurnStuckOnContextOverflow(lastAssistant, ctx.model?.contextWindow ?? 0);
|
|
85
94
|
}
|
|
86
95
|
function textContent(message) {
|
|
87
96
|
return message.content
|
|
@@ -114,6 +123,8 @@ function blockedReasonForContinuationGuard(reason) {
|
|
|
114
123
|
return REPETITION_BLOCKED_REASON;
|
|
115
124
|
case "length-exhausted":
|
|
116
125
|
return LENGTH_EXHAUSTED_BLOCKED_REASON;
|
|
126
|
+
case "context-overflow":
|
|
127
|
+
return CONTEXT_OVERFLOW_BLOCKED_REASON;
|
|
117
128
|
case "not-eligible":
|
|
118
129
|
case "single-flight":
|
|
119
130
|
case "stale":
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle-helpers.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAGtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EACN,8BAA8B,EAC9B,wBAAwB,EAGxB,iBAAiB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,yBAAyB,EACzB,sCAAsC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAgBtD;;;GAGG;AACH,MAAM,gCAAgC,GAA8B,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;AAE1F;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CACpC,GAAqB,EACrB,kBAA0B,EAC1B,IAAiB;IAEjB,OAAO,CACN,kBAAkB,KAAK,QAAQ;QAC/B,IAAI,KAAK,IAAI;QACb,gCAAgC,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC;QACtD,GAAG,CAAC,KAAK;QACT,GAAG,CAAC,MAAM,EAAE;QACZ,CAAC,GAAG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EAC5C,OAAO,CACP,CAAC;IACF,IAAI,GAAG,CAAC,KAAK;QAAE,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,2BAA2B,CAAC,aAAa,CAAC,EAAE,SAAS,CAAC,CAAC;IACpF,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,iCAAiC,EAAE;QAClD,MAAM,EAAE,IAAI,CAAC,EAAE;QACf,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,wBAAwB;QACrC,uBAAuB,EAAE,IAAI,CAAC,uBAAuB,IAAI,CAAC;KAC1D,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,iCAAiC,CACzC,MAAoE;IAEpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,KAAK;YACT,OAAO,+BAA+B,CAAC;QACxC,KAAK,YAAY;YAChB,OAAO,sCAAsC,CAAC;QAC/C,KAAK,YAAY;YAChB,OAAO,yBAAyB,CAAC;QAClC,KAAK,kBAAkB;YACtB,OAAO,+BAA+B,CAAC;QACxC,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe,CAAC;QACrB,KAAK,OAAO;YACX,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,EAAgB,EAAE,OAAe;IACtE,EAAE,CAAC,WAAW,CACb,EAAE,UAAU,EAAE,8BAA8B,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,EACvE,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAC5C,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { GOAL_CONTINUATION_MESSAGE_TYPE } from \"../../../messages.ts\";\nimport type { SessionEntry } from \"../../../session-manager.ts\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport { getLatestPhasesFromBranchEntries } from \"../todotools/state.ts\";\nimport {\n\tbuildGoalContinuationSignature,\n\tevaluateGoalContinuation,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationVerdict,\n\thashAssistantText,\n} from \"./continuation.ts\";\nimport {\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tcontinuationCapRecoveryHint,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n\tUNATTENDED_CONTINUATION_BLOCKED_REASON,\n} from \"./continuation-recovery.ts\";\nimport { buildContinuationPrompt } from \"./prompt.ts\";\nimport { recordContinuationDelivered, updateGoal } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { openTodoTaskContents } from \"./todo-gate.ts\";\nimport type { Goal } from \"./types.ts\";\n\ntype ContinuingGoalContinuationVerdict = Extract<GoalContinuationVerdict, { kind: \"continue\" }>;\n\ntype GoalContinuationDeliveryOptions = {\n\treadonly input: Omit<GoalContinuationInput, \"goal\">;\n\treadonly content: (verdict: ContinuingGoalContinuationVerdict) => string;\n\treadonly markContinuationPending: () => void;\n};\n\nexport type SessionStartContinuationOptions = {\n\treadonly continuationPending: boolean;\n\treadonly markContinuationPending: () => void;\n};\n\n/**\n * Statuses that leave a goal stopped without finishing it. A restart is the only\n * moment the user can act on them, so both earn the resume prompt.\n */\nconst STOPPED_UNFINISHED_GOAL_STATUSES: readonly Goal[\"status\"][] = [\"paused\", \"blocked\"];\n\n/**\n * Mirrors codex `maybe_prompt_resume_paused_goal_after_resume`\n * (codex-rs/tui/src/app/thread_goal_actions.rs), which prompts on resume for every\n * stopped-but-unfinished status. senpi is budget-free, so codex's `UsageLimited`\n * has no counterpart here and the stopped set is `paused | blocked`.\n */\nexport function isResumeOfStoppedGoal(\n\tctx: ExtensionContext,\n\tsessionStartReason: string,\n\tgoal: Goal | null,\n): goal is Goal {\n\treturn (\n\t\tsessionStartReason === \"resume\" &&\n\t\tgoal !== null &&\n\t\tSTOPPED_UNFINISHED_GOAL_STATUSES.includes(goal.status) &&\n\t\tctx.hasUI &&\n\t\tctx.isIdle() &&\n\t\t!ctx.hasPendingMessages()\n\t);\n}\n\n/** Evaluates and delivers a continuation only after all guardrail checks admit it. */\nexport async function admitAndQueueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: GoalContinuationDeliveryOptions,\n): Promise<Goal | null> {\n\tconst verdict = evaluateGoalContinuation({ goal, ...options.input });\n\tif (verdict.kind === \"deny\") return handleDeniedContinuation(pi, ctx, goal, options.input, verdict.reason);\n\n\tif (options.input.currentSignature === undefined) {\n\t\tthrow new Error(\"Cannot queue a goal continuation without a progress signature\");\n\t}\n\tconst recordedGoal = await recordContinuationDelivered(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\toptions.input.currentSignature,\n\t\tgoal.id,\n\t\t{ countUnattended: options.input.path !== \"monitorDelayed\" },\n\t);\n\tif (recordedGoal === null) return null;\n\toptions.markContinuationPending();\n\tqueueHiddenGoalPrompt(pi, options.content(verdict));\n\treturn recordedGoal;\n}\n\n/** Routes startup and resume continuations through the same verdict and delivery accounting as agent-end paths. */\nexport async function queueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: SessionStartContinuationOptions,\n): Promise<Goal | null> {\n\tconst signature = buildCurrentGoalContinuationSignature(\n\t\tctx,\n\t\tgoal,\n\t\tlastAssistantTextFromEntries(ctx.sessionManager.getBranch()),\n\t);\n\treturn admitAndQueueGoalContinuation(pi, ctx, goal, {\n\t\tinput: {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath: \"sessionStart\",\n\t\t\tlastStopReason: undefined,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: signature,\n\t\t\tconsecutiveLengthRecoveries: 0,\n\t\t\trecentNormalizedOutputHashes: [],\n\t\t\ttoollessContinuationStreak: 0,\n\t\t\tcontinuationPending: options.continuationPending,\n\t\t},\n\t\tcontent: () => buildContinuationPrompt(goal),\n\t\tmarkContinuationPending: options.markContinuationPending,\n\t});\n}\n\nexport function buildCurrentGoalContinuationSignature(\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tlastAssistantText: string,\n): string {\n\tconst entries = ctx.sessionManager.getBranch();\n\tconst openTodos = openTodoTaskContents(entries).length;\n\tconst totalTodos = getLatestPhasesFromBranchEntries(entries).reduce((count, phase) => count + phase.tasks.length, 0);\n\treturn buildGoalContinuationSignature(goal, openTodos, totalTodos, hashAssistantText(lastAssistantText));\n}\n\nexport function lastAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") return textContent(message);\n\t}\n\treturn \"\";\n}\n\nfunction lastAssistantTextFromEntries(entries: readonly SessionEntry[]): string {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"message\" && entry.message.role === \"assistant\") return textContent(entry.message);\n\t}\n\treturn \"\";\n}\n\nfunction textContent(message: Extract<AgentMessage, { role: \"assistant\" }>): string {\n\treturn message.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n\nasync function handleDeniedContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tinput: Omit<GoalContinuationInput, \"goal\">,\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): Promise<Goal> {\n\tconst blockedReason = blockedReasonForContinuationGuard(reason);\n\tif (blockedReason === undefined) return goal;\n\n\tconst blocked = await updateGoal(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\t{ status: \"blocked\", reason: blockedReason },\n\t\t\"model\",\n\t);\n\tif (ctx.hasUI) ctx.ui.notify(continuationCapRecoveryHint(blockedReason), \"warning\");\n\tpi.events?.emit(\"goal_continuation_guard_tripped\", {\n\t\tgoalId: goal.id,\n\t\treason,\n\t\tcount: input.consecutiveContinuations,\n\t\tunattendedContinuations: goal.unattendedContinuations ?? 0,\n\t});\n\treturn blocked;\n}\n\nfunction blockedReasonForContinuationGuard(\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): string | undefined {\n\tswitch (reason) {\n\t\tcase \"cap\":\n\t\t\treturn CONTINUATION_CAP_BLOCKED_REASON;\n\t\tcase \"unattended\":\n\t\t\treturn UNATTENDED_CONTINUATION_BLOCKED_REASON;\n\t\tcase \"repetition\":\n\t\t\treturn REPETITION_BLOCKED_REASON;\n\t\tcase \"length-exhausted\":\n\t\t\treturn LENGTH_EXHAUSTED_BLOCKED_REASON;\n\t\tcase \"not-eligible\":\n\t\tcase \"single-flight\":\n\t\tcase \"stale\":\n\t\t\treturn undefined;\n\t}\n}\n\nexport function queueHiddenGoalPrompt(pi: ExtensionAPI, content: string): void {\n\tpi.sendMessage(\n\t\t{ customType: GOAL_CONTINUATION_MESSAGE_TYPE, content, display: false },\n\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lifecycle-helpers.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/lifecycle-helpers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EAAE,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAGtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EACN,8BAA8B,EAC9B,wBAAwB,EAGxB,iBAAiB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACN,+BAA+B,EAC/B,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,yBAAyB,EACzB,sCAAsC,GACtC,MAAM,4BAA4B,CAAC;AACpC,O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AAC,iCAAiC,EAAE;QAClD,MAAM,EAAE,IAAI,CAAC,EAAE;QACf,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,wBAAwB;QACrC,uBAAuB,EAAE,IAAI,CAAC,uBAAuB,IAAI,CAAC;KAC1D,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,iCAAiC,CACzC,MAAoE;IAEpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,KAAK;YACT,OAAO,+BAA+B,CAAC;QACxC,KAAK,YAAY;YAChB,OAAO,sCAAsC,CAAC;QAC/C,KAAK,YAAY;YAChB,OAAO,yBAAyB,CAAC;QAClC,KAAK,kBAAkB;YACtB,OAAO,+BAA+B,CAAC;QACxC,KAAK,kBAAkB;YACtB,OAAO,+BAA+B,CAAC;QACxC,KAAK,cAAc,CAAC;QACpB,KAAK,eAAe,CAAC;QACrB,KAAK,OAAO;YACX,OAAO,SAAS,CAAC;IACnB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,EAAgB,EAAE,OAAe;IACtE,EAAE,CAAC,WAAW,CACb,EAAE,UAAU,EAAE,8BAA8B,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,EACvE,EAAE,WAAW,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAC5C,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { isTurnStuckOnContextOverflow } from \"../../../compaction/stuck-overflow.ts\";\nimport { GOAL_CONTINUATION_MESSAGE_TYPE } from \"../../../messages.ts\";\nimport type { SessionEntry } from \"../../../session-manager.ts\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport { getLatestPhasesFromBranchEntries } from \"../todotools/state.ts\";\nimport {\n\tbuildGoalContinuationSignature,\n\tevaluateGoalContinuation,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationVerdict,\n\thashAssistantText,\n} from \"./continuation.ts\";\nimport {\n\tCONTEXT_OVERFLOW_BLOCKED_REASON,\n\tCONTINUATION_CAP_BLOCKED_REASON,\n\tcontinuationCapRecoveryHint,\n\tLENGTH_EXHAUSTED_BLOCKED_REASON,\n\tREPETITION_BLOCKED_REASON,\n\tUNATTENDED_CONTINUATION_BLOCKED_REASON,\n} from \"./continuation-recovery.ts\";\nimport { buildContinuationPrompt } from \"./prompt.ts\";\nimport { recordContinuationDelivered, updateGoal } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { openTodoTaskContents } from \"./todo-gate.ts\";\nimport type { Goal } from \"./types.ts\";\n\ntype ContinuingGoalContinuationVerdict = Extract<GoalContinuationVerdict, { kind: \"continue\" }>;\n\ntype GoalContinuationDeliveryOptions = {\n\treadonly input: Omit<GoalContinuationInput, \"goal\">;\n\treadonly content: (verdict: ContinuingGoalContinuationVerdict) => string;\n\treadonly markContinuationPending: () => void;\n};\n\nexport type SessionStartContinuationOptions = {\n\treadonly continuationPending: boolean;\n\treadonly markContinuationPending: () => void;\n};\n\n/**\n * Statuses that leave a goal stopped without finishing it. A restart is the only\n * moment the user can act on them, so both earn the resume prompt.\n */\nconst STOPPED_UNFINISHED_GOAL_STATUSES: readonly Goal[\"status\"][] = [\"paused\", \"blocked\"];\n\n/**\n * Mirrors codex `maybe_prompt_resume_paused_goal_after_resume`\n * (codex-rs/tui/src/app/thread_goal_actions.rs), which prompts on resume for every\n * stopped-but-unfinished status. senpi is budget-free, so codex's `UsageLimited`\n * has no counterpart here and the stopped set is `paused | blocked`.\n */\nexport function isResumeOfStoppedGoal(\n\tctx: ExtensionContext,\n\tsessionStartReason: string,\n\tgoal: Goal | null,\n): goal is Goal {\n\treturn (\n\t\tsessionStartReason === \"resume\" &&\n\t\tgoal !== null &&\n\t\tSTOPPED_UNFINISHED_GOAL_STATUSES.includes(goal.status) &&\n\t\tctx.hasUI &&\n\t\tctx.isIdle() &&\n\t\t!ctx.hasPendingMessages()\n\t);\n}\n\n/** Evaluates and delivers a continuation only after all guardrail checks admit it. */\nexport async function admitAndQueueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: GoalContinuationDeliveryOptions,\n): Promise<Goal | null> {\n\tconst verdict = evaluateGoalContinuation({ goal, ...options.input });\n\tif (verdict.kind === \"deny\") return handleDeniedContinuation(pi, ctx, goal, options.input, verdict.reason);\n\n\tif (options.input.currentSignature === undefined) {\n\t\tthrow new Error(\"Cannot queue a goal continuation without a progress signature\");\n\t}\n\tconst recordedGoal = await recordContinuationDelivered(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\toptions.input.currentSignature,\n\t\tgoal.id,\n\t\t{ countUnattended: options.input.path !== \"monitorDelayed\" },\n\t);\n\tif (recordedGoal === null) return null;\n\toptions.markContinuationPending();\n\tqueueHiddenGoalPrompt(pi, options.content(verdict));\n\treturn recordedGoal;\n}\n\n/** Routes startup and resume continuations through the same verdict and delivery accounting as agent-end paths. */\nexport async function queueGoalContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\toptions: SessionStartContinuationOptions,\n): Promise<Goal | null> {\n\tconst signature = buildCurrentGoalContinuationSignature(\n\t\tctx,\n\t\tgoal,\n\t\tlastAssistantTextFromEntries(ctx.sessionManager.getBranch()),\n\t);\n\treturn admitAndQueueGoalContinuation(pi, ctx, goal, {\n\t\tinput: {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath: \"sessionStart\",\n\t\t\tlastStopReason: undefined,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: signature,\n\t\t\tconsecutiveLengthRecoveries: 0,\n\t\t\trecentNormalizedOutputHashes: [],\n\t\t\ttoollessContinuationStreak: 0,\n\t\t\tcontinuationPending: options.continuationPending,\n\t\t\tlastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(\n\t\t\t\tctx,\n\t\t\t\tlastAssistantFromEntries(ctx.sessionManager.getBranch()),\n\t\t\t),\n\t\t},\n\t\tcontent: () => buildContinuationPrompt(goal),\n\t\tmarkContinuationPending: options.markContinuationPending,\n\t});\n}\n\nexport function buildCurrentGoalContinuationSignature(\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tlastAssistantText: string,\n): string {\n\tconst entries = ctx.sessionManager.getBranch();\n\tconst openTodos = openTodoTaskContents(entries).length;\n\tconst totalTodos = getLatestPhasesFromBranchEntries(entries).reduce((count, phase) => count + phase.tasks.length, 0);\n\treturn buildGoalContinuationSignature(goal, openTodos, totalTodos, hashAssistantText(lastAssistantText));\n}\n\nexport function lastAssistantText(messages: readonly AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role === \"assistant\") return textContent(message);\n\t}\n\treturn \"\";\n}\n\nfunction lastAssistantTextFromEntries(entries: readonly SessionEntry[]): string {\n\tconst assistant = lastAssistantFromEntries(entries);\n\treturn assistant === undefined ? \"\" : textContent(assistant);\n}\n\nfunction lastAssistantFromEntries(\n\tentries: readonly SessionEntry[],\n): Extract<AgentMessage, { role: \"assistant\" }> | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry?.type === \"message\" && entry.message.role === \"assistant\") return entry.message;\n\t}\n\treturn undefined;\n}\n\nexport function isLastTurnStuckOnContextOverflow(\n\tctx: ExtensionContext,\n\tlastAssistant: Extract<AgentMessage, { role: \"assistant\" }> | undefined,\n): boolean {\n\treturn lastAssistant !== undefined && isTurnStuckOnContextOverflow(lastAssistant, ctx.model?.contextWindow ?? 0);\n}\n\nfunction textContent(message: Extract<AgentMessage, { role: \"assistant\" }>): string {\n\treturn message.content\n\t\t.filter((content) => content.type === \"text\")\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n\nasync function handleDeniedContinuation(\n\tpi: ExtensionAPI,\n\tctx: ExtensionContext,\n\tgoal: Goal,\n\tinput: Omit<GoalContinuationInput, \"goal\">,\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): Promise<Goal> {\n\tconst blockedReason = blockedReasonForContinuationGuard(reason);\n\tif (blockedReason === undefined) return goal;\n\n\tconst blocked = await updateGoal(\n\t\tgoalStoreRef(ctx.sessionManager, ctx.cwd),\n\t\t{ status: \"blocked\", reason: blockedReason },\n\t\t\"model\",\n\t);\n\tif (ctx.hasUI) ctx.ui.notify(continuationCapRecoveryHint(blockedReason), \"warning\");\n\tpi.events?.emit(\"goal_continuation_guard_tripped\", {\n\t\tgoalId: goal.id,\n\t\treason,\n\t\tcount: input.consecutiveContinuations,\n\t\tunattendedContinuations: goal.unattendedContinuations ?? 0,\n\t});\n\treturn blocked;\n}\n\nfunction blockedReasonForContinuationGuard(\n\treason: Extract<GoalContinuationVerdict, { kind: \"deny\" }>[\"reason\"],\n): string | undefined {\n\tswitch (reason) {\n\t\tcase \"cap\":\n\t\t\treturn CONTINUATION_CAP_BLOCKED_REASON;\n\t\tcase \"unattended\":\n\t\t\treturn UNATTENDED_CONTINUATION_BLOCKED_REASON;\n\t\tcase \"repetition\":\n\t\t\treturn REPETITION_BLOCKED_REASON;\n\t\tcase \"length-exhausted\":\n\t\t\treturn LENGTH_EXHAUSTED_BLOCKED_REASON;\n\t\tcase \"context-overflow\":\n\t\t\treturn CONTEXT_OVERFLOW_BLOCKED_REASON;\n\t\tcase \"not-eligible\":\n\t\tcase \"single-flight\":\n\t\tcase \"stale\":\n\t\t\treturn undefined;\n\t}\n}\n\nexport function queueHiddenGoalPrompt(pi: ExtensionAPI, content: string): void {\n\tpi.sendMessage(\n\t\t{ customType: GOAL_CONTINUATION_MESSAGE_TYPE, content, display: false },\n\t\t{ triggerTurn: true, deliverAs: \"followUp\" },\n\t);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "../../types.ts";
|
|
2
|
-
export { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from "./cache-warm.ts";
|
|
2
|
+
export { GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS, GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS, } from "./cache-warm.ts";
|
|
3
3
|
import type { AgentEndOptions, ProviderRecoveryOptions, SystemAbortOptions } from "./monitor-continuation-types.ts";
|
|
4
4
|
import type { Goal } from "./types.ts";
|
|
5
5
|
import type { GoalWaitTicker } from "./wait-ticker.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monitor-continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAarE,OAAO,
|
|
1
|
+
{"version":3,"file":"monitor-continuation.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAarE,OAAO,EACN,sCAAsC,EACtC,2CAA2C,GAC3C,MAAM,iBAAiB,CAAC;AAmBzB,OAAO,KAAK,EACX,eAAe,EAIf,uBAAuB,EAEvB,kBAAkB,EAClB,MAAM,iCAAiC,CAAC;AAMzC,OAAO,KAAK,EAAE,IAAI,EAAsB,MAAM,YAAY,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAEvD,eAAO,MAAM,iCAAiC,gCAAgC,CAAC;AAC/E,eAAO,MAAM,+BAA+B,8BAA8B,CAAC;AAC3E,eAAO,MAAM,mCAAmC,kCAAkC,CAAC;AACnF,eAAO,MAAM,wBAAwB,oCAAoC,CAAC;AAE1E,qBAAa,4BAA4B;;gBAiCvC,EAAE,EAAE,YAAY,EAChB,qBAAqB,GAAE,MAAM,OAAqB,EAClD,uBAAuB,GAAE,MAAM,IAAe,EAC9C,UAAU,CAAC,EAAE,cAAc;IAS5B,KAAK,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI;IAW5B,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IA0D7D,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAoBnE,oBAAoB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAgB5E,iBAAiB,IAAI,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;IA2B3D,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI;IASjC,sGAAsG;IACtG,oBAAoB,IAAI,OAAO;IAI/B;;;;;OAKG;IACH,oBAAoB,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;IAMtC,mGAAmG;IACnG,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAwBtC,6FAA6F;IAC7F,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,IAAI;IAc5D,sEAAsE;IACtE,cAAc,IAAI,IAAI;IAOtB,mGAAmG;IACnG,uBAAuB,IAAI,IAAI;IAI/B,OAAO,IAAI,IAAI;CAmWf"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createGoalCacheWarmScheduleData, estimateCacheWarmMetrics, GOAL_CACHE_WARMUP_ENTRY_TYPE, GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS, resolveGoalMonitorContinuationDelayMs, } from "./cache-warm.js";
|
|
2
2
|
import { subscribeGoalChannelState } from "./channel-state-subscriptions.js";
|
|
3
|
-
export { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from "./cache-warm.js";
|
|
3
|
+
export { GOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS, GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS, } from "./cache-warm.js";
|
|
4
4
|
import { continuationTurnUsedTools, evaluateGoalContinuation, GOAL_USER_GRACE_DELAY_MS, hasGoalContinuationProgress, hashAssistantText, normalizeAssistantText, } from "./continuation.js";
|
|
5
5
|
import { lastAssistantMessage } from "./last-assistant-message.js";
|
|
6
|
-
import { admitAndQueueGoalContinuation, buildCurrentGoalContinuationSignature, lastAssistantText, } from "./lifecycle-helpers.js";
|
|
6
|
+
import { admitAndQueueGoalContinuation, buildCurrentGoalContinuationSignature, isLastTurnStuckOnContextOverflow, lastAssistantText, } from "./lifecycle-helpers.js";
|
|
7
7
|
import { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from "./prompt.js";
|
|
8
8
|
import { isStaleExtensionContextError } from "./stale-context.js";
|
|
9
9
|
import { resetContinuationStreak } from "./store.js";
|
|
@@ -262,8 +262,11 @@ export class MonitorAwareGoalContinuation {
|
|
|
262
262
|
#schedule(goal, kind) {
|
|
263
263
|
if (this.#scheduledContinuationKind !== undefined)
|
|
264
264
|
return;
|
|
265
|
+
// A live wake source arms the stall backstop only: the normal resumption is
|
|
266
|
+
// the drain fire in #setWakeSourceCount, so the model is not invoked on the
|
|
267
|
+
// prompt-cache safe-wait interval while the session waits.
|
|
265
268
|
const delayMs = kind === "monitor"
|
|
266
|
-
? resolveGoalMonitorContinuationDelayMs(this.#ctx?.
|
|
269
|
+
? resolveGoalMonitorContinuationDelayMs(this.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.())
|
|
267
270
|
: GOAL_USER_GRACE_DELAY_MS;
|
|
268
271
|
this.#scheduledDelayMs = delayMs;
|
|
269
272
|
if (kind === "monitor") {
|
|
@@ -432,6 +435,7 @@ export class MonitorAwareGoalContinuation {
|
|
|
432
435
|
recentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,
|
|
433
436
|
toollessContinuationStreak: this.#toollessContinuationStreak,
|
|
434
437
|
continuationPending: this.#isContinuationPending(),
|
|
438
|
+
lastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistant),
|
|
435
439
|
};
|
|
436
440
|
}
|
|
437
441
|
#buildContinuationContent(ctx, goal, verdict) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EAAE,2CAA2C,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qCAAqC,EACrC,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAIxD,MAAM,CAAC,MAAM,iCAAiC,GAAG,6BAA6B,CAAC;AAC/E,MAAM,CAAC,MAAM,+BAA+B,GAAG,2BAA2B,CA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CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport { GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS } from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\t#pendingProviderRecovery: ProviderRecoveryOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\":\n\t\t\t\tcase \"unattended\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterProviderFailure(options: ProviderRecoveryOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (!options.willRetry) this.#pendingProviderRecovery = options;\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pendingSystem = this.#pendingSystemRecovery;\n\t\tconst pendingProvider = this.#pendingProviderRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tif (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== \"user\") {\n\t\t\treturn (\n\t\t\t\tawait this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, \"systemRecovery\", pendingSystem.messages)\n\t\t\t).goal;\n\t\t}\n\t\tif (\n\t\t\tpendingProvider === undefined ||\n\t\t\tpendingProvider.goal === null ||\n\t\t\tpendingProvider.event.abortSource === \"user\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn (\n\t\t\tawait this.#admitAndQueue(\n\t\t\t\tpendingProvider.ctx,\n\t\t\t\tpendingProvider.goal,\n\t\t\t\t\"providerRecovery\",\n\t\t\t\tpendingProvider.messages,\n\t\t\t)\n\t\t).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheSafeWaitSeconds?.(),\n\t\t\t\t\t\tthis.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.(),\n\t\t\t\t\t)\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t/**\n\t * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session\n\t * replacement or reload THROWS instead of reporting false. Optional chaining\n\t * only guards an undefined ctx (what `dispose()` leaves behind), never a stale\n\t * object left by a replacement that never disposed this monitor. Callers reach\n\t * this from timer and event callbacks where a throw is fatal, so a retired ctx\n\t * reports \"no UI\" and any other failure keeps its current behavior.\n\t */\n\t#ctxHasUI(ctx: ExtensionContext | undefined = this.#ctx): boolean {\n\t\ttry {\n\t\t\treturn ctx?.hasUI === true;\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx !== undefined && this.#ctxHasUI(ctx)) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\t// Runs from a bare setTimeout: anything thrown here escapes as an\n\t\t\t\t// uncaughtException and kills the session. A retired ctx cannot be\n\t\t\t\t// notified, and its own staleness is the expected cause of this\n\t\t\t\t// rejection after a session replacement, so drop it quietly.\n\t\t\t\tif (isStaleExtensionContextError(error) || !this.#ctxHasUI()) return;\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tthis.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (this.#ctxHasUI(ctx)) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EACN,sCAAsC,EACtC,2CAA2C,GAC3C,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qCAAqC,EACrC,gCAAgC,EAChC,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,E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CAAC,4BAA4B,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED,gCAAgC;QAC/B,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;IACnC,CAAC;IAED,YAAY;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC7C,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport {\n\tGOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n} from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tisLastTurnStuckOnContextOverflow,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\nexport const GOAL_CONTINUATION_SCHEDULED_EVENT = \"goal_continuation_scheduled\";\nexport const GOAL_CONTINUATION_RESUMED_EVENT = \"goal_continuation_resumed\";\nexport const GOAL_CONTINUATION_TIMER_STATE_EVENT = \"goal_continuation_timer_state\";\nexport const GOAL_MONITOR_STALL_EVENT = \"goal_monitor_continuation_stall\";\n\nexport class MonitorAwareGoalContinuation {\n\treadonly #pi: ExtensionAPI;\n\treadonly #isContinuationPending: () => boolean;\n\treadonly #markContinuationPending: () => void;\n\treadonly #waitTicker: GoalWaitTicker | undefined;\n\t#wakeSources = new Map<string, number>();\n\t#hasStarted = false;\n\t#ctx: ExtensionContext | undefined;\n\t#goal: Goal | null = null;\n\t#timer: ReturnType<typeof setTimeout> | undefined;\n\t#scheduledContinuationKind: DelayedContinuationKind | undefined;\n\t#channelStateUnsubscribers: Array<() => void> = [];\n\t#lastAgentEndMessages: readonly AgentMessage[] = [];\n\t#consecutiveLengthRecoveries = new Map<string, number>();\n\t#recentNormalizedOutputHashes: string[] = [];\n\t#toollessContinuationStreak = 0;\n\t#toollessStreakGoalId: string | null = null;\n\t#endedTurnWasUserInitiated = false;\n\t#lastTurnUsage: TokenUsageSnapshot | undefined;\n\t#scheduledAtMs: number | undefined;\n\t#scheduledDueAtMs: number | undefined;\n\t#scheduledCache: GoalCacheWarmMetrics | undefined;\n\t#scheduledDelayMs: number | undefined;\n\t#cacheWarmIteration = 0;\n\t#scheduledCacheWarmIteration: number | undefined;\n\t#heldTimer:\n\t\t| { kind: DelayedContinuationKind; remainingMs: number; heldAtMs: number; totalMs: number; drainFire: boolean }\n\t\t| undefined;\n\t#directInputHolds = new Set<string>();\n\t#pendingSystemRecovery: SystemAbortOptions | undefined;\n\t#pendingProviderRecovery: ProviderRecoveryOptions | undefined;\n\n\tconstructor(\n\t\tpi: ExtensionAPI,\n\t\tisContinuationPending: () => boolean = () => false,\n\t\tmarkContinuationPending: () => void = () => {},\n\t\twaitTicker?: GoalWaitTicker,\n\t) {\n\t\tthis.#pi = pi;\n\t\tthis.#isContinuationPending = isContinuationPending;\n\t\tthis.#markContinuationPending = markContinuationPending;\n\t\tthis.#waitTicker = waitTicker;\n\t\tthis.#subscribeToChannelState();\n\t}\n\n\tstart(ctx: ExtensionContext): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#ctx = ctx;\n\t\tif (this.#hasStarted) this.#wakeSources.clear();\n\t\telse this.#hasStarted = true;\n\t\tthis.#goal = null;\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\tasync afterAgentEnd(options: AgentEndOptions): Promise<Goal | null> {\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tthis.#resetLengthRecoveryAfterCleanStop(options.goal, options.messages);\n\t\tconst turnUsedTools = continuationTurnUsedTools(options.messages);\n\t\tthis.#recordAssistantOutput(options.messages, turnUsedTools);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tthis.#recordToollessContinuationTurn(options.goal, turnUsedTools);\n\t\tconst immediateInput = this.#buildVerdictInput(options.ctx, options.goal, \"immediate\", options.messages);\n\t\tconst goal =\n\t\t\t!this.#endedTurnWasUserInitiated && (turnUsedTools || hasGoalContinuationProgress(immediateInput))\n\t\t\t\t? ((await resetContinuationStreak(goalStoreRef(options.ctx.sessionManager, options.ctx.cwd))) ??\n\t\t\t\t\toptions.goal)\n\t\t\t\t: options.goal;\n\t\tthis.#goal = goal;\n\t\tconst immediateVerdict = evaluateGoalContinuation({\n\t\t\tgoal,\n\t\t\t...this.#buildVerdictInput(options.ctx, goal, \"immediate\", options.messages),\n\t\t});\n\t\tif (this.#endedTurnWasUserInitiated) {\n\t\t\tthis.#endedTurnWasUserInitiated = false;\n\t\t\tthis.#cancelTimer();\n\t\t\tif (immediateVerdict.kind === \"continue\") {\n\t\t\t\tthis.#schedule(goal, \"userGrace\");\n\t\t\t\treturn goal;\n\t\t\t}\n\t\t\tswitch (immediateVerdict.reason) {\n\t\t\t\tcase \"not-eligible\":\n\t\t\t\tcase \"single-flight\":\n\t\t\t\tcase \"stale\":\n\t\t\t\t\treturn goal;\n\t\t\t\tcase \"cap\":\n\t\t\t\tcase \"repetition\":\n\t\t\t\tcase \"length-exhausted\":\n\t\t\t\tcase \"unattended\": {\n\t\t\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\t\t\treturn admission.goal;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (immediateVerdict.kind === \"deny\" && immediateVerdict.reason === \"not-eligible\") return goal;\n\n\t\tif (this.#activeWakeSourceCount() === 0) {\n\t\t\tthis.#cancelTimer();\n\t\t\tconst admission = await this.#admitAndQueue(options.ctx, goal, \"immediate\", options.messages);\n\t\t\treturn admission.goal;\n\t\t}\n\t\tthis.#schedule(goal, \"monitor\");\n\t\treturn goal;\n\t}\n\n\tasync afterSystemAbort(options: SystemAbortOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (options.willRetry) return options.goal;\n\t\tif (this.#activeWakeSourceCount() > 0) this.#schedule(options.goal, \"monitor\");\n\t\telse if (lastAssistantMessage(options.messages)?.stopReason === \"error\") {\n\t\t\tthis.#pendingSystemRecovery = options;\n\t\t}\n\t\treturn options.goal;\n\t}\n\n\tasync afterProviderFailure(options: ProviderRecoveryOptions): Promise<Goal | null> {\n\t\tthis.noteContinuationStarted();\n\t\tif (options.goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#ctx = options.ctx;\n\t\tthis.#goal = options.goal;\n\t\tthis.#lastAgentEndMessages = options.messages;\n\t\tthis.#lastTurnUsage = collectAssistantUsage([...options.messages]);\n\t\tif (options.goal?.status !== \"active\") {\n\t\t\tthis.#resetContinuationState();\n\t\t\treturn options.goal;\n\t\t}\n\t\tif (!options.willRetry) this.#pendingProviderRecovery = options;\n\t\treturn options.goal;\n\t}\n\n\tasync afterAgentSettled(): Promise<Goal | null | undefined> {\n\t\tconst pendingSystem = this.#pendingSystemRecovery;\n\t\tconst pendingProvider = this.#pendingProviderRecovery;\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tif (pendingSystem !== undefined && pendingSystem.goal !== null && pendingSystem.event.abortSource !== \"user\") {\n\t\t\treturn (\n\t\t\t\tawait this.#admitAndQueue(pendingSystem.ctx, pendingSystem.goal, \"systemRecovery\", pendingSystem.messages)\n\t\t\t).goal;\n\t\t}\n\t\tif (\n\t\t\tpendingProvider === undefined ||\n\t\t\tpendingProvider.goal === null ||\n\t\t\tpendingProvider.event.abortSource === \"user\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn (\n\t\t\tawait this.#admitAndQueue(\n\t\t\t\tpendingProvider.ctx,\n\t\t\t\tpendingProvider.goal,\n\t\t\t\t\"providerRecovery\",\n\t\t\t\tpendingProvider.messages,\n\t\t\t)\n\t\t).goal;\n\t}\n\n\tsyncGoal(goal: Goal | null): void {\n\t\tif (goal?.id !== this.#goal?.id) this.#resetContinuationState();\n\t\tthis.#goal = goal;\n\t\tif (goal?.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetContinuationState();\n\t\t}\n\t}\n\n\t/** Live resumption channels known to this generation (e.g. terminal snapshots replayed on reload). */\n\thasActiveWakeSources(): boolean {\n\t\treturn this.#activeWakeSourceCount() > 0;\n\t}\n\n\t/**\n\t * Re-arms the monitor-delayed backstop a reload tore down with the retired\n\t * generation, so a later wake-source drain can still deliver the goal\n\t * continuation. No-op unless the goal is active, a wake source is live, and\n\t * no continuation is already scheduled.\n\t */\n\trearmMonitorBackstop(goal: Goal): void {\n\t\tif (goal.status !== \"active\" || this.#activeWakeSourceCount() === 0) return;\n\t\tthis.#goal = goal;\n\t\tthis.#schedule(goal, \"monitor\");\n\t}\n\n\t/** Temporarily prevents a scheduled continuation from racing unresolved direct-input admission. */\n\tholdDirectInput(inputId: string): void {\n\t\tif (this.#directInputHolds.has(inputId)) return;\n\t\tthis.#directInputHolds.add(inputId);\n\t\tif (\n\t\t\tthis.#directInputHolds.size !== 1 ||\n\t\t\tthis.#timer === undefined ||\n\t\t\tthis.#scheduledContinuationKind === undefined\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst heldAtMs = Date.now();\n\t\tthis.#heldTimer = {\n\t\t\tkind: this.#scheduledContinuationKind,\n\t\t\tremainingMs: Math.max(0, (this.#scheduledDueAtMs ?? heldAtMs) - heldAtMs),\n\t\t\theldAtMs,\n\t\t\ttotalMs: this.#scheduledDelayMs ?? GOAL_USER_GRACE_DELAY_MS,\n\t\t\tdrainFire: false,\n\t\t};\n\t\tclearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t}\n\n\t/** Resolves one admission hold without allowing overlapping inputs to consume each other. */\n\tresolveDirectInput(inputId: string, accepted: boolean): void {\n\t\tif (!this.#directInputHolds.delete(inputId)) return;\n\t\tif (accepted) {\n\t\t\tthis.#heldTimer = undefined;\n\t\t\tthis.noteUserPrompt();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#directInputHolds.size > 0 || this.#heldTimer === undefined) return;\n\t\tconst held = this.#heldTimer;\n\t\tthis.#heldTimer = undefined;\n\t\tconst elapsedWhileHeldMs = Math.max(0, Date.now() - held.heldAtMs);\n\t\tthis.#armTimer(held.kind, Math.max(0, held.remainingMs - elapsedWhileHeldMs), held.totalMs, held.drainFire);\n\t}\n\n\t/** An accepted real user prompt starts a grace-governed user turn. */\n\tnoteUserPrompt(): void {\n\t\tthis.#cancelTimer();\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#endedTurnWasUserInitiated = true;\n\t\tthis.#resetContinuationState();\n\t}\n\n\t/** A hidden continuation or system recovery has started, so the next end is not user-initiated. */\n\tnoteContinuationStarted(): void {\n\t\tthis.#endedTurnWasUserInitiated = false;\n\t}\n\n\tdispose(): void {\n\t\tthis.#cancelTimer();\n\t\tfor (const unsubscribe of this.#channelStateUnsubscribers) unsubscribe();\n\t\tthis.#channelStateUnsubscribers = [];\n\t\tthis.#ctx = undefined;\n\t\tthis.#goal = null;\n\t\tthis.#wakeSources.clear();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\t// A live wake source arms the stall backstop only: the normal resumption is\n\t\t// the drain fire in #setWakeSourceCount, so the model is not invoked on the\n\t\t// prompt-cache safe-wait interval while the session waits.\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? resolveGoalMonitorContinuationDelayMs(this.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.())\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t/**\n\t * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session\n\t * replacement or reload THROWS instead of reporting false. Optional chaining\n\t * only guards an undefined ctx (what `dispose()` leaves behind), never a stale\n\t * object left by a replacement that never disposed this monitor. Callers reach\n\t * this from timer and event callbacks where a throw is fatal, so a retired ctx\n\t * reports \"no UI\" and any other failure keeps its current behavior.\n\t */\n\t#ctxHasUI(ctx: ExtensionContext | undefined = this.#ctx): boolean {\n\t\ttry {\n\t\t\treturn ctx?.hasUI === true;\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx !== undefined && this.#ctxHasUI(ctx)) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\t// Runs from a bare setTimeout: anything thrown here escapes as an\n\t\t\t\t// uncaughtException and kills the session. A retired ctx cannot be\n\t\t\t\t// notified, and its own staleness is the expected cause of this\n\t\t\t\t// rejection after a session replacement, so drop it quietly.\n\t\t\t\tif (isStaleExtensionContextError(error) || !this.#ctxHasUI()) return;\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tthis.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t\tlastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistant),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (this.#ctxHasUI(ctx)) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tthis.#wakeSources.set(source, activeCount);\n\t\tconst nextTotal = this.#activeWakeSourceCount();\n\t\tif (previousTotal > 0 && nextTotal === 0) {\n\t\t\tif (this.#scheduledContinuationKind === \"monitor\") this.#armDrainFire();\n\t\t\telse this.#resetCacheWarmIteration();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#scheduledContinuationKind === \"monitor\") {\n\t\t\tthis.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());\n\t\t}\n\t}\n\n\t#armDrainFire(): void {\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = {\n\t\t\t\tkind: \"monitor\",\n\t\t\t\tremainingMs: 1_000,\n\t\t\t\theldAtMs: Date.now(),\n\t\t\t\ttotalMs: 1_000,\n\t\t\t\tdrainFire: true,\n\t\t\t};\n\t\t\treturn;\n\t\t}\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#waitTicker?.stop();\n\t\tthis.#armTimer(\"monitor\", 1_000, 1_000, true);\n\t}\n\n\t#activeWakeSourceCount(): number {\n\t\tlet total = 0;\n\t\tfor (const count of this.#wakeSources.values()) total += count;\n\t\treturn total;\n\t}\n\n\t#wakeSourceSnapshot(): ResumptionChannelCounts {\n\t\treturn Object.fromEntries([...this.#wakeSources.entries()].sort(([left], [right]) => left.localeCompare(right)));\n\t}\n\n\t#liveWakeSources(): string[] {\n\t\treturn [...this.#wakeSources.entries()]\n\t\t\t.filter(([, count]) => count > 0)\n\t\t\t.map(([source]) => source)\n\t\t\t.sort();\n\t}\n\n\t#resetContinuationState(): void {\n\t\tthis.#pendingSystemRecovery = undefined;\n\t\tthis.#pendingProviderRecovery = undefined;\n\t\tthis.#consecutiveLengthRecoveries.clear();\n\t\tthis.#recentNormalizedOutputHashes = [];\n\t\tthis.#resetToollessContinuationStreak();\n\t\tthis.#resetCacheWarmIteration();\n\t}\n\n\t#resetCacheWarmIteration(): void {\n\t\tthis.#cacheWarmIteration = 0;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t}\n\n\t#resetToollessContinuationStreak(): void {\n\t\tthis.#toollessContinuationStreak = 0;\n\t\tthis.#toollessStreakGoalId = null;\n\t}\n\n\t#cancelTimer(): void {\n\t\tconst kind = this.#scheduledContinuationKind;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tthis.#heldTimer = undefined;\n\t\tif (this.#timer !== undefined) clearTimeout(this.#timer);\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tif (kind !== undefined) this.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t}\n}\n"]}
|
|
@@ -45,8 +45,8 @@ export function resolveContainedPath(pluginRootInput, manifestPathInput) {
|
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
47
|
if (fileExists(resolvedPath)) {
|
|
48
|
-
const realPath = realpathSync(resolvedPath);
|
|
49
|
-
if (!isContained(realpathSync(pluginRoot), realPath)) {
|
|
48
|
+
const realPath = realpathSync.native(resolvedPath);
|
|
49
|
+
if (!isContained(realpathSync.native(pluginRoot), realPath)) {
|
|
50
50
|
return {
|
|
51
51
|
message: `Plugin hook path is outside plugin root: ${manifestPathInput}`,
|
|
52
52
|
ok: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-manifest.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/plugin-manifest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAG9C,MAAM,CAAC,MAAM,aAAa,GAAG,2BAA2B,CAAC;AACzD,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AAqBpD,MAAM,UAAU,cAAc,CAAC,UAAkB,EAAE,QAA4B;IAC9E,MAAM,UAAU,GAAG,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACjG,OAAO;QACN,kBAAkB,EAAE,UAAU;QAC9B,kBAAkB,EAAE,UAAU;QAC9B,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU;KACvB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,KAO5B;IACA,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,YAAY,EAAE,KAAK,CAAC,YAAY;QA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, join, relative, resolve } from \"node:path\";\nimport { diagnostic } from \"./diagnostics.ts\";\nimport type { HookDiagnostic, HookDiscoveryTiming, HookSourceMetadata } from \"./types.ts\";\n\nexport const MANIFEST_PATH = \".codex-plugin/plugin.json\";\nexport const DEFAULT_HOOK_PATH = \"hooks/hooks.json\";\n\nexport type PluginHookEnv = {\n\treadonly PLUGIN_ROOT: string;\n\treadonly PLUGIN_DATA: string;\n\treadonly CLAUDE_PLUGIN_ROOT: string;\n\treadonly CLAUDE_PLUGIN_DATA: string;\n};\n\nexport type PluginHookSourceMetadata = HookSourceMetadata & {\n\treadonly pluginEnv: PluginHookEnv;\n};\n\nexport type LoadPluginHookManifestOptions = {\n\treadonly pluginRoot: string;\n\treadonly displayOrder: number;\n\treadonly discoveredAt?: HookDiscoveryTiming;\n\treadonly dataRoot?: string;\n\treadonly includeDefaultHooks?: boolean;\n};\n\nexport function buildPluginEnv(pluginRoot: string, dataRoot: string | undefined): PluginHookEnv {\n\tconst pluginData = dataRoot === undefined ? join(pluginRoot, \".plugin-data\") : resolve(dataRoot);\n\treturn {\n\t\tCLAUDE_PLUGIN_DATA: pluginData,\n\t\tCLAUDE_PLUGIN_ROOT: pluginRoot,\n\t\tPLUGIN_DATA: pluginData,\n\t\tPLUGIN_ROOT: pluginRoot,\n\t};\n}\n\nexport function pluginSource(input: {\n\treadonly discoveredAt: HookDiscoveryTiming;\n\treadonly displayOrder: number;\n\treadonly env: PluginHookEnv;\n\treadonly manifestPath: string;\n\treadonly pluginRoot: string;\n\treadonly sourcePath: string;\n}): PluginHookSourceMetadata {\n\treturn {\n\t\tdiscoveredAt: input.discoveredAt,\n\t\tdisplayOrder: input.displayOrder,\n\t\tmanifestPath: input.manifestPath,\n\t\tpluginEnv: input.env,\n\t\tpluginRoot: input.pluginRoot,\n\t\tscope: \"plugin\",\n\t\tsourcePath: input.sourcePath,\n\t};\n}\n\nexport function sourceForPath(\n\toptions: LoadPluginHookManifestOptions,\n\tenv: PluginHookEnv,\n\tsourcePath: string,\n): PluginHookSourceMetadata {\n\tconst pluginRoot = resolve(options.pluginRoot);\n\treturn pluginSource({\n\t\tdiscoveredAt: options.discoveredAt ?? \"pre-session\",\n\t\tdisplayOrder: options.displayOrder,\n\t\tenv,\n\t\tmanifestPath: join(pluginRoot, MANIFEST_PATH),\n\t\tpluginRoot,\n\t\tsourcePath,\n\t});\n}\n\nexport function resolveContainedPath(\n\tpluginRootInput: string,\n\tmanifestPathInput: string,\n): { readonly ok: true; readonly path: string } | { readonly ok: false; readonly message: string } {\n\tconst pluginRoot = resolve(pluginRootInput);\n\tconst normalizedInput = manifestPathInput.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//, \"\");\n\tconst resolvedPath = isAbsolute(normalizedInput) ? resolve(normalizedInput) : resolve(pluginRoot, normalizedInput);\n\tif (!isContained(pluginRoot, resolvedPath)) {\n\t\treturn {\n\t\t\tmessage: `Plugin hook path is outside plugin root: ${manifestPathInput}`,\n\t\t\tok: false,\n\t\t};\n\t}\n\tif (fileExists(resolvedPath)) {\n\t\tconst realPath = realpathSync.native(resolvedPath);\n\t\tif (!isContained(realpathSync.native(pluginRoot), realPath)) {\n\t\t\treturn {\n\t\t\t\tmessage: `Plugin hook path is outside plugin root: ${manifestPathInput}`,\n\t\t\t\tok: false,\n\t\t\t};\n\t\t}\n\t}\n\treturn { ok: true, path: resolvedPath };\n}\n\nexport function readJsonFile(\n\tpath: string,\n\tmanifestPath: string,\n\tsource: PluginHookSourceMetadata,\n): { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly diagnostic: HookDiagnostic } {\n\ttry {\n\t\tconst value: unknown = JSON.parse(readFileSync(path, \"utf-8\"));\n\t\treturn { ok: true, value };\n\t} catch (error) {\n\t\tif (error instanceof Error) {\n\t\t\treturn {\n\t\t\t\tdiagnostic: diagnostic(\n\t\t\t\t\t{ code: \"invalid_root\", message: `Could not read plugin hook JSON: ${error.message}`, path: \"$\" },\n\t\t\t\t\t{ ...source, manifestPath },\n\t\t\t\t),\n\t\t\t\tok: false,\n\t\t\t};\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport function fileExists(path: string): boolean {\n\treturn existsSync(path) && statSync(path).isFile();\n}\n\nexport function directoryExists(path: string): boolean {\n\treturn existsSync(path) && statSync(path).isDirectory();\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isContained(root: string, target: string): boolean {\n\tconst rel = relative(root, target);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n"]}
|
|
@@ -87,8 +87,8 @@ function validateCommandField(handler, field, command) {
|
|
|
87
87
|
}, handler.source));
|
|
88
88
|
continue;
|
|
89
89
|
}
|
|
90
|
-
const realTarget = realpathSync(target.resolvedPath);
|
|
91
|
-
const realRoot = realpathSync(resolve(handler.source.pluginRoot ?? ""));
|
|
90
|
+
const realTarget = realpathSync.native(target.resolvedPath);
|
|
91
|
+
const realRoot = realpathSync.native(resolve(handler.source.pluginRoot ?? ""));
|
|
92
92
|
if (!isContained(realRoot, realTarget)) {
|
|
93
93
|
diagnostics.push(diagnostic({
|
|
94
94
|
code: "invalid_command_target",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safety.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/safety.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAI9C,OAAO,EACN,qBAAqB,EACrB,0BAA0B,EAC1B,0BAA0B,GAK1B,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEhD,MAAM,qBAAqB,GAAG;IAC7B,MAAM;IACN,MAA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,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,kBAAkB,CAAC,MAA0B;IACrD,IAAI,CAAC,CAAC,WAAW,IAAI,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC/C,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IACnC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IAClD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACtC,OAAO,CACN,QAAQ,CAAC,KAAK,CAAC;QACf,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ;QACrC,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ;QACrC,OAAO,KAAK,CAAC,kBAAkB,KAAK,QAAQ;QAC5C,OAAO,KAAK,CAAC,kBAAkB,KAAK,QAAQ,CAC5C,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { diagnostic } from \"./diagnostics.ts\";\nimport type { PluginHookEnv } from \"./plugin-manifest.ts\";\nimport type { ExecutableHookHandler, HookDiagnostic, HookInputWire, HookSourceMetadata } from \"./types.ts\";\n\nexport {\n\tapplyHookOutputSafety,\n\tDEFAULT_STDERR_LIMIT_BYTES,\n\tDEFAULT_STDOUT_LIMIT_BYTES,\n\ttype HookOutputPolicy,\n\ttype HookOutputSafetyMetadata,\n\ttype HookSafeOutput,\n\ttype HookStreamSafetyMetadata,\n} from \"./output-bounds.ts\";\n\nexport const DEFAULT_HOOK_TIMEOUT_SECONDS = 600;\n\nconst MINIMAL_INHERITED_ENV = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USER\",\n\t\"USERNAME\",\n\t\"LOGNAME\",\n\t\"SHELL\",\n\t\"TMPDIR\",\n\t\"TMP\",\n\t\"TEMP\",\n\t\"SystemRoot\",\n\t\"ComSpec\",\n\t\"PATHEXT\",\n] as const;\nconst PLUGIN_ROOT_TEMPLATE_TOKEN = \"$\" + \"{PLUGIN_ROOT}\";\nconst PLUGIN_ROOT_TOKENS = [PLUGIN_ROOT_TEMPLATE_TOKEN, \"$PLUGIN_ROOT\", \"%PLUGIN_ROOT%\"] as const;\n\ntype HookEnvironmentOptions = {\n\treadonly handler: ExecutableHookHandler;\n\treadonly input: HookInputWire;\n\treadonly sourceEnv: NodeJS.ProcessEnv;\n\treadonly envPassthrough?: readonly string[];\n};\n\ntype PluginRootTarget = {\n\treadonly raw: string;\n\treadonly resolvedPath: string;\n};\n\nexport function resolveHookTimeoutSeconds(handler: ExecutableHookHandler): number {\n\tconst timeout = handler.config.timeout;\n\tif (timeout === undefined) {\n\t\treturn DEFAULT_HOOK_TIMEOUT_SECONDS;\n\t}\n\tif (!isValidHookTimeoutSeconds(timeout)) {\n\t\tthrow new Error(\"Invalid command hook timeout reached runtime execution.\");\n\t}\n\treturn timeout;\n}\n\nexport function isValidHookTimeoutSeconds(timeout: number): boolean {\n\treturn Number.isFinite(timeout) && timeout > 0;\n}\n\nexport function buildHookEnvironment(options: HookEnvironmentOptions): NodeJS.ProcessEnv {\n\tconst env: NodeJS.ProcessEnv = {};\n\tfor (const key of MINIMAL_INHERITED_ENV) {\n\t\tconst value = options.sourceEnv[key];\n\t\tif (value !== undefined) env[key] = value;\n\t}\n\tfor (const key of options.envPassthrough ?? []) {\n\t\tconst value = options.sourceEnv[key];\n\t\tif (value !== undefined) env[key] = value;\n\t}\n\tconst pluginEnv = pluginEnvForSource(options.handler.source);\n\tif (pluginEnv !== undefined) {\n\t\tenv.PLUGIN_ROOT = pluginEnv.PLUGIN_ROOT;\n\t\tenv.PLUGIN_DATA = pluginEnv.PLUGIN_DATA;\n\t\tenv.CLAUDE_PLUGIN_ROOT = pluginEnv.CLAUDE_PLUGIN_ROOT;\n\t\tenv.CLAUDE_PLUGIN_DATA = pluginEnv.CLAUDE_PLUGIN_DATA;\n\t}\n\tenv.SENPI_HOOK_SOURCE = options.handler.source.sourcePath;\n\tenv.SENPI_HOOK_EVENT = options.input.event;\n\treturn env;\n}\n\nexport function validateHookHandlerSafety(handler: ExecutableHookHandler): readonly HookDiagnostic[] {\n\tif (handler.source.scope !== \"plugin\" || handler.source.pluginRoot === undefined) return [];\n\treturn [\n\t\t...validateCommandField(handler, \"command\", handler.config.command),\n\t\t...(handler.config.commandWindows === undefined\n\t\t\t? []\n\t\t\t: validateCommandField(handler, \"commandWindows\", handler.config.commandWindows)),\n\t];\n}\n\nfunction validateCommandField(\n\thandler: ExecutableHookHandler,\n\tfield: \"command\" | \"commandWindows\",\n\tcommand: string,\n): readonly HookDiagnostic[] {\n\tconst diagnostics: HookDiagnostic[] = [];\n\tfor (const target of extractPluginRootTargets(command, handler.source.pluginRoot ?? \"\")) {\n\t\tconst path = `hooks.${handler.event}[${handler.groupIndex}].hooks[${handler.handlerIndex}].${field}`;\n\t\tif (!isContained(resolve(handler.source.pluginRoot ?? \"\"), target.resolvedPath)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target is outside plugin root: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!existsSync(target.resolvedPath)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"missing_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target does not exist: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst realTarget = realpathSync(target.resolvedPath);\n\t\tconst realRoot = realpathSync(resolve(handler.source.pluginRoot ?? \"\"));\n\t\tif (!isContained(realRoot, realTarget)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target resolves outside plugin root: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn diagnostics;\n}\n\nfunction extractPluginRootTargets(command: string, pluginRoot: string): readonly PluginRootTarget[] {\n\tconst targets: PluginRootTarget[] = [];\n\tfor (const word of readCommandWords(command)) {\n\t\tfor (const token of PLUGIN_ROOT_TOKENS) {\n\t\t\tif (!word.expanded.includes(token)) continue;\n\t\t\tconst expanded = word.expanded.replaceAll(token, pluginRoot).replaceAll(\"\\\\\", \"/\");\n\t\t\ttargets.push({ raw: word.raw, resolvedPath: resolve(expanded) });\n\t\t}\n\t}\n\treturn targets;\n}\n\nfunction readCommandWords(command: string): readonly { readonly expanded: string; readonly raw: string }[] {\n\tconst words: { readonly expanded: string; readonly raw: string }[] = [];\n\tlet index = 0;\n\twhile (index < command.length) {\n\t\twhile (index < command.length && isCommandWordTerminator(command[index])) index += 1;\n\t\tif (index >= command.length) break;\n\n\t\tconst start = index;\n\t\tlet expanded = \"\";\n\t\twhile (index < command.length && !isCommandWordTerminator(command[index])) {\n\t\t\tconst char = command[index];\n\t\t\tif (char === \"'\" || char === '\"' || char === \"`\") {\n\t\t\t\tconst quote = char;\n\t\t\t\tindex += 1;\n\t\t\t\twhile (index < command.length && command[index] !== quote) {\n\t\t\t\t\texpanded += command[index];\n\t\t\t\t\tindex += 1;\n\t\t\t\t}\n\t\t\t\tif (command[index] === quote) index += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\texpanded += char;\n\t\t\tindex += 1;\n\t\t}\n\t\twords.push({ expanded, raw: command.slice(start, index) });\n\t}\n\treturn words;\n}\n\nfunction isCommandWordTerminator(char: string | undefined): boolean {\n\treturn (\n\t\tchar === undefined ||\n\t\tchar === \" \" ||\n\t\tchar === \"\\t\" ||\n\t\tchar === \"\\n\" ||\n\t\tchar === \";\" ||\n\t\tchar === \"&\" ||\n\t\tchar === \"|\" ||\n\t\tchar === \"<\" ||\n\t\tchar === \">\" ||\n\t\tchar === \")\"\n\t);\n}\n\nfunction isContained(root: string, target: string): boolean {\n\tconst rel = relative(root, target);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\nfunction pluginEnvForSource(source: HookSourceMetadata): PluginHookEnv | undefined {\n\tif (!(\"pluginEnv\" in source)) return undefined;\n\tconst pluginEnv = source.pluginEnv;\n\tif (!isPluginHookEnv(pluginEnv)) return undefined;\n\treturn pluginEnv;\n}\n\nfunction isPluginHookEnv(value: unknown): value is PluginHookEnv {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.PLUGIN_ROOT === \"string\" &&\n\t\ttypeof value.PLUGIN_DATA === \"string\" &&\n\t\ttypeof value.CLAUDE_PLUGIN_ROOT === \"string\" &&\n\t\ttypeof value.CLAUDE_PLUGIN_DATA === \"string\"\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"safety.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/safety.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EA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AAK,GAAG;QACZ,IAAI,KAAK,GAAG;QACZ,IAAI,KAAK,GAAG,CACZ,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,IAAY,EAAE,MAAc;IAChD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,kBAAkB,CAAC,MAA0B;IACrD,IAAI,CAAC,CAAC,WAAW,IAAI,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IAC/C,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IACnC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IAClD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,SAAS,eAAe,CAAC,KAAc;IACtC,OAAO,CACN,QAAQ,CAAC,KAAK,CAAC;QACf,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ;QACrC,OAAO,KAAK,CAAC,WAAW,KAAK,QAAQ;QACrC,OAAO,KAAK,CAAC,kBAAkB,KAAK,QAAQ;QAC5C,OAAO,KAAK,CAAC,kBAAkB,KAAK,QAAQ,CAC5C,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC/B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve } from \"node:path\";\nimport { diagnostic } from \"./diagnostics.ts\";\nimport type { PluginHookEnv } from \"./plugin-manifest.ts\";\nimport type { ExecutableHookHandler, HookDiagnostic, HookInputWire, HookSourceMetadata } from \"./types.ts\";\n\nexport {\n\tapplyHookOutputSafety,\n\tDEFAULT_STDERR_LIMIT_BYTES,\n\tDEFAULT_STDOUT_LIMIT_BYTES,\n\ttype HookOutputPolicy,\n\ttype HookOutputSafetyMetadata,\n\ttype HookSafeOutput,\n\ttype HookStreamSafetyMetadata,\n} from \"./output-bounds.ts\";\n\nexport const DEFAULT_HOOK_TIMEOUT_SECONDS = 600;\n\nconst MINIMAL_INHERITED_ENV = [\n\t\"PATH\",\n\t\"HOME\",\n\t\"USER\",\n\t\"USERNAME\",\n\t\"LOGNAME\",\n\t\"SHELL\",\n\t\"TMPDIR\",\n\t\"TMP\",\n\t\"TEMP\",\n\t\"SystemRoot\",\n\t\"ComSpec\",\n\t\"PATHEXT\",\n] as const;\nconst PLUGIN_ROOT_TEMPLATE_TOKEN = \"$\" + \"{PLUGIN_ROOT}\";\nconst PLUGIN_ROOT_TOKENS = [PLUGIN_ROOT_TEMPLATE_TOKEN, \"$PLUGIN_ROOT\", \"%PLUGIN_ROOT%\"] as const;\n\ntype HookEnvironmentOptions = {\n\treadonly handler: ExecutableHookHandler;\n\treadonly input: HookInputWire;\n\treadonly sourceEnv: NodeJS.ProcessEnv;\n\treadonly envPassthrough?: readonly string[];\n};\n\ntype PluginRootTarget = {\n\treadonly raw: string;\n\treadonly resolvedPath: string;\n};\n\nexport function resolveHookTimeoutSeconds(handler: ExecutableHookHandler): number {\n\tconst timeout = handler.config.timeout;\n\tif (timeout === undefined) {\n\t\treturn DEFAULT_HOOK_TIMEOUT_SECONDS;\n\t}\n\tif (!isValidHookTimeoutSeconds(timeout)) {\n\t\tthrow new Error(\"Invalid command hook timeout reached runtime execution.\");\n\t}\n\treturn timeout;\n}\n\nexport function isValidHookTimeoutSeconds(timeout: number): boolean {\n\treturn Number.isFinite(timeout) && timeout > 0;\n}\n\nexport function buildHookEnvironment(options: HookEnvironmentOptions): NodeJS.ProcessEnv {\n\tconst env: NodeJS.ProcessEnv = {};\n\tfor (const key of MINIMAL_INHERITED_ENV) {\n\t\tconst value = options.sourceEnv[key];\n\t\tif (value !== undefined) env[key] = value;\n\t}\n\tfor (const key of options.envPassthrough ?? []) {\n\t\tconst value = options.sourceEnv[key];\n\t\tif (value !== undefined) env[key] = value;\n\t}\n\tconst pluginEnv = pluginEnvForSource(options.handler.source);\n\tif (pluginEnv !== undefined) {\n\t\tenv.PLUGIN_ROOT = pluginEnv.PLUGIN_ROOT;\n\t\tenv.PLUGIN_DATA = pluginEnv.PLUGIN_DATA;\n\t\tenv.CLAUDE_PLUGIN_ROOT = pluginEnv.CLAUDE_PLUGIN_ROOT;\n\t\tenv.CLAUDE_PLUGIN_DATA = pluginEnv.CLAUDE_PLUGIN_DATA;\n\t}\n\tenv.SENPI_HOOK_SOURCE = options.handler.source.sourcePath;\n\tenv.SENPI_HOOK_EVENT = options.input.event;\n\treturn env;\n}\n\nexport function validateHookHandlerSafety(handler: ExecutableHookHandler): readonly HookDiagnostic[] {\n\tif (handler.source.scope !== \"plugin\" || handler.source.pluginRoot === undefined) return [];\n\treturn [\n\t\t...validateCommandField(handler, \"command\", handler.config.command),\n\t\t...(handler.config.commandWindows === undefined\n\t\t\t? []\n\t\t\t: validateCommandField(handler, \"commandWindows\", handler.config.commandWindows)),\n\t];\n}\n\nfunction validateCommandField(\n\thandler: ExecutableHookHandler,\n\tfield: \"command\" | \"commandWindows\",\n\tcommand: string,\n): readonly HookDiagnostic[] {\n\tconst diagnostics: HookDiagnostic[] = [];\n\tfor (const target of extractPluginRootTargets(command, handler.source.pluginRoot ?? \"\")) {\n\t\tconst path = `hooks.${handler.event}[${handler.groupIndex}].hooks[${handler.handlerIndex}].${field}`;\n\t\tif (!isContained(resolve(handler.source.pluginRoot ?? \"\"), target.resolvedPath)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target is outside plugin root: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!existsSync(target.resolvedPath)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"missing_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target does not exist: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\tconst realTarget = realpathSync.native(target.resolvedPath);\n\t\tconst realRoot = realpathSync.native(resolve(handler.source.pluginRoot ?? \"\"));\n\t\tif (!isContained(realRoot, realTarget)) {\n\t\t\tdiagnostics.push(\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_command_target\",\n\t\t\t\t\t\tevent: handler.event,\n\t\t\t\t\t\tmessage: `Plugin command target resolves outside plugin root: ${target.raw}`,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t\thandler.source,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn diagnostics;\n}\n\nfunction extractPluginRootTargets(command: string, pluginRoot: string): readonly PluginRootTarget[] {\n\tconst targets: PluginRootTarget[] = [];\n\tfor (const word of readCommandWords(command)) {\n\t\tfor (const token of PLUGIN_ROOT_TOKENS) {\n\t\t\tif (!word.expanded.includes(token)) continue;\n\t\t\tconst expanded = word.expanded.replaceAll(token, pluginRoot).replaceAll(\"\\\\\", \"/\");\n\t\t\ttargets.push({ raw: word.raw, resolvedPath: resolve(expanded) });\n\t\t}\n\t}\n\treturn targets;\n}\n\nfunction readCommandWords(command: string): readonly { readonly expanded: string; readonly raw: string }[] {\n\tconst words: { readonly expanded: string; readonly raw: string }[] = [];\n\tlet index = 0;\n\twhile (index < command.length) {\n\t\twhile (index < command.length && isCommandWordTerminator(command[index])) index += 1;\n\t\tif (index >= command.length) break;\n\n\t\tconst start = index;\n\t\tlet expanded = \"\";\n\t\twhile (index < command.length && !isCommandWordTerminator(command[index])) {\n\t\t\tconst char = command[index];\n\t\t\tif (char === \"'\" || char === '\"' || char === \"`\") {\n\t\t\t\tconst quote = char;\n\t\t\t\tindex += 1;\n\t\t\t\twhile (index < command.length && command[index] !== quote) {\n\t\t\t\t\texpanded += command[index];\n\t\t\t\t\tindex += 1;\n\t\t\t\t}\n\t\t\t\tif (command[index] === quote) index += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\texpanded += char;\n\t\t\tindex += 1;\n\t\t}\n\t\twords.push({ expanded, raw: command.slice(start, index) });\n\t}\n\treturn words;\n}\n\nfunction isCommandWordTerminator(char: string | undefined): boolean {\n\treturn (\n\t\tchar === undefined ||\n\t\tchar === \" \" ||\n\t\tchar === \"\\t\" ||\n\t\tchar === \"\\n\" ||\n\t\tchar === \";\" ||\n\t\tchar === \"&\" ||\n\t\tchar === \"|\" ||\n\t\tchar === \"<\" ||\n\t\tchar === \">\" ||\n\t\tchar === \")\"\n\t);\n}\n\nfunction isContained(root: string, target: string): boolean {\n\tconst rel = relative(root, target);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n}\n\nfunction pluginEnvForSource(source: HookSourceMetadata): PluginHookEnv | undefined {\n\tif (!(\"pluginEnv\" in source)) return undefined;\n\tconst pluginEnv = source.pluginEnv;\n\tif (!isPluginHookEnv(pluginEnv)) return undefined;\n\treturn pluginEnv;\n}\n\nfunction isPluginHookEnv(value: unknown): value is PluginHookEnv {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.PLUGIN_ROOT === \"string\" &&\n\t\ttypeof value.PLUGIN_DATA === \"string\" &&\n\t\ttypeof value.CLAUDE_PLUGIN_ROOT === \"string\" &&\n\t\ttypeof value.CLAUDE_PLUGIN_DATA === \"string\"\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-dir.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/permission-system/external-dir.ts"],"names":[],"mappings":"AAIA,wBAAgB,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAcpD;
|
|
1
|
+
{"version":3,"file":"external-dir.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/permission-system/external-dir.ts"],"names":[],"mappings":"AAIA,wBAAgB,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAcpD;AAED,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAetE;AAgFD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAgC3E"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
1
|
import * as os from "node:os";
|
|
3
2
|
import * as path from "node:path";
|
|
3
|
+
import { realpathWithoutOpen } from "../../../../utils/paths.js";
|
|
4
4
|
export function expandHome(inputPath) {
|
|
5
5
|
if (inputPath === "~") {
|
|
6
6
|
return os.homedir();
|
|
@@ -16,30 +16,13 @@ export function expandHome(inputPath) {
|
|
|
16
16
|
}
|
|
17
17
|
return inputPath;
|
|
18
18
|
}
|
|
19
|
-
function normalizePath(inputPath) {
|
|
20
|
-
let candidate = path.normalize(inputPath);
|
|
21
|
-
const suffix = [];
|
|
22
|
-
for (;;) {
|
|
23
|
-
try {
|
|
24
|
-
const resolved = fs.realpathSync(candidate);
|
|
25
|
-
return suffix.length === 0 ? resolved : path.join(resolved, ...suffix.reverse());
|
|
26
|
-
}
|
|
27
|
-
catch (error) {
|
|
28
|
-
if (error?.code !== "ENOENT")
|
|
29
|
-
return candidate;
|
|
30
|
-
const parent = path.dirname(candidate);
|
|
31
|
-
if (parent === candidate)
|
|
32
|
-
return candidate;
|
|
33
|
-
suffix.push(path.basename(candidate));
|
|
34
|
-
candidate = parent;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
19
|
export function isExternalPath(inputPath, cwd) {
|
|
39
20
|
const expandedPath = expandHome(inputPath);
|
|
40
|
-
|
|
21
|
+
// Resolution must never open(2) a component (autofs triggers block, execute-only dirs EACCES):
|
|
22
|
+
// realpathWithoutOpen walks lstat/readlink only, exactly what the classifier needs.
|
|
23
|
+
const normalizedCwd = realpathWithoutOpen(cwd);
|
|
41
24
|
const absolutePath = path.isAbsolute(expandedPath) ? expandedPath : path.resolve(normalizedCwd, expandedPath);
|
|
42
|
-
const normalizedTarget =
|
|
25
|
+
const normalizedTarget = realpathWithoutOpen(absolutePath);
|
|
43
26
|
if (normalizedTarget === normalizedCwd) {
|
|
44
27
|
return false;
|
|
45
28
|
}
|