@code-yeongyu/senpi 2026.8.26 → 2026.8.28
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 +76 -0
- package/README.md +3 -3
- package/dist/cli/args.d.ts +3 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +14 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +10 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +67 -29
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/credential-accounts.d.ts +31 -0
- package/dist/core/credential-accounts.d.ts.map +1 -0
- package/dist/core/credential-accounts.js +125 -0
- package/dist/core/credential-accounts.js.map +1 -0
- package/dist/core/credential-pool/classify.d.ts +42 -0
- package/dist/core/credential-pool/classify.d.ts.map +1 -0
- package/dist/core/credential-pool/classify.js +75 -0
- package/dist/core/credential-pool/classify.js.map +1 -0
- package/dist/core/credential-pool/env-slots.d.ts +22 -0
- package/dist/core/credential-pool/env-slots.d.ts.map +1 -0
- package/dist/core/credential-pool/env-slots.js +37 -0
- package/dist/core/credential-pool/env-slots.js.map +1 -0
- package/dist/core/credential-pool/failover.d.ts +54 -0
- package/dist/core/credential-pool/failover.d.ts.map +1 -0
- package/dist/core/credential-pool/failover.js +106 -0
- package/dist/core/credential-pool/failover.js.map +1 -0
- package/dist/core/credential-pool/rotation-stream.d.ts +43 -0
- package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -0
- package/dist/core/credential-pool/rotation-stream.js +96 -0
- package/dist/core/credential-pool/rotation-stream.js.map +1 -0
- package/dist/core/credential-pool/state-store.d.ts +89 -0
- package/dist/core/credential-pool/state-store.d.ts.map +1 -0
- package/dist/core/credential-pool/state-store.js +166 -0
- package/dist/core/credential-pool/state-store.js.map +1 -0
- package/dist/core/extensions/builtin/account/index.d.ts +9 -0
- package/dist/core/extensions/builtin/account/index.d.ts.map +1 -0
- package/dist/core/extensions/builtin/account/index.js +69 -0
- package/dist/core/extensions/builtin/account/index.js.map +1 -0
- package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/index.js +67 -0
- package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts +1 -1
- package/dist/core/extensions/builtin/compaction/log.d.ts.map +1 -1
- package/dist/core/extensions/builtin/compaction/log.js +1 -0
- package/dist/core/extensions/builtin/compaction/log.js.map +1 -1
- package/dist/core/extensions/builtin/config-reload/index.js +14 -22
- package/dist/core/extensions/builtin/config-reload/index.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 +8 -1
- package/dist/core/extensions/builtin/goal/continuation.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/continuation.js +15 -0
- package/dist/core/extensions/builtin/goal/continuation.js.map +1 -1
- package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +2 -2
- package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js.map +1 -1
- package/dist/core/extensions/builtin/goal/format.d.ts +6 -1
- package/dist/core/extensions/builtin/goal/format.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/format.js +6 -0
- package/dist/core/extensions/builtin/goal/format.js.map +1 -1
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +5 -2
- package/dist/core/extensions/builtin/goal/lifecycle-helpers.js.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.js +31 -7
- package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
- package/dist/core/extensions/builtin/goal/persistence.js +2 -0
- package/dist/core/extensions/builtin/goal/persistence.js.map +1 -1
- package/dist/core/extensions/builtin/goal/renderers.d.ts +14 -0
- package/dist/core/extensions/builtin/goal/renderers.d.ts.map +1 -0
- package/dist/core/extensions/builtin/goal/renderers.js +153 -0
- package/dist/core/extensions/builtin/goal/renderers.js.map +1 -0
- package/dist/core/extensions/builtin/goal/store.d.ts +6 -2
- package/dist/core/extensions/builtin/goal/store.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/store.js +8 -2
- package/dist/core/extensions/builtin/goal/store.js.map +1 -1
- package/dist/core/extensions/builtin/goal/tool-registration.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/tool-registration.js +16 -6
- package/dist/core/extensions/builtin/goal/tool-registration.js.map +1 -1
- package/dist/core/extensions/builtin/goal/types.d.ts +1 -0
- package/dist/core/extensions/builtin/goal/types.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/types.js.map +1 -1
- package/dist/core/extensions/builtin/imagegen/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/imagegen/index.js +10 -3
- package/dist/core/extensions/builtin/imagegen/index.js.map +1 -1
- package/dist/core/extensions/builtin/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/index.js +4 -0
- package/dist/core/extensions/builtin/index.js.map +1 -1
- package/dist/core/extensions/builtin/todotools/index.js +1 -1
- package/dist/core/extensions/builtin/todotools/index.js.map +1 -1
- package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts +1 -1
- package/dist/core/extensions/builtin/todotools/native-todo-mirror.d.ts.map +1 -1
- package/dist/core/extensions/builtin/todotools/native-todo-mirror.js +1 -1
- package/dist/core/extensions/builtin/todotools/native-todo-mirror.js.map +1 -1
- package/dist/core/hidden-stdout-log.d.ts +10 -0
- package/dist/core/hidden-stdout-log.d.ts.map +1 -1
- package/dist/core/hidden-stdout-log.js +36 -5
- package/dist/core/hidden-stdout-log.js.map +1 -1
- package/dist/core/model-config-schema.d.ts +85 -12
- package/dist/core/model-config-schema.d.ts.map +1 -1
- package/dist/core/model-config-schema.js +25 -0
- package/dist/core/model-config-schema.js.map +1 -1
- package/dist/core/model-runtime.d.ts +34 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +98 -5
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +2 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +32 -7
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +38 -3
- package/dist/main.js.map +1 -1
- package/dist/modes/app-server/server/account.d.ts.map +1 -1
- package/dist/modes/app-server/server/account.js +5 -5
- package/dist/modes/app-server/server/account.js.map +1 -1
- package/dist/modes/index.d.ts +1 -0
- package/dist/modes/index.d.ts.map +1 -1
- package/dist/modes/index.js +1 -0
- package/dist/modes/index.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +11 -3
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +31 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution-fallback.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution-fallback.js +82 -1
- package/dist/modes/interactive/components/tool-execution-fallback.js.map +1 -1
- package/dist/modes/interactive/grok/chrome.d.ts +4 -4
- package/dist/modes/interactive/grok/chrome.d.ts.map +1 -1
- package/dist/modes/interactive/grok/chrome.js.map +1 -1
- package/dist/modes/interactive/grok/footer.d.ts +3 -3
- package/dist/modes/interactive/grok/footer.d.ts.map +1 -1
- package/dist/modes/interactive/grok/footer.js.map +1 -1
- package/dist/modes/interactive/interactive-host-runtime.d.ts +44 -0
- package/dist/modes/interactive/interactive-host-runtime.d.ts.map +1 -0
- package/dist/modes/interactive/interactive-host-runtime.js +271 -0
- package/dist/modes/interactive/interactive-host-runtime.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +65 -21
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/connection-handler.d.ts.map +1 -1
- package/dist/modes/rpc/connection-handler.js +19 -6
- package/dist/modes/rpc/connection-handler.js.map +1 -1
- package/dist/modes/rpc/host-ensure.d.ts +41 -0
- package/dist/modes/rpc/host-ensure.d.ts.map +1 -0
- package/dist/modes/rpc/host-ensure.js +245 -0
- package/dist/modes/rpc/host-ensure.js.map +1 -0
- package/dist/modes/rpc/host-lifecycle.d.ts +57 -0
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -0
- package/dist/modes/rpc/host-lifecycle.js +491 -0
- package/dist/modes/rpc/host-lifecycle.js.map +1 -0
- package/dist/modes/rpc/host-watchdog.d.ts +33 -0
- package/dist/modes/rpc/host-watchdog.d.ts.map +1 -0
- package/dist/modes/rpc/host-watchdog.js +142 -0
- package/dist/modes/rpc/host-watchdog.js.map +1 -0
- package/dist/modes/rpc/multi-session-host.d.ts +7 -1
- package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
- package/dist/modes/rpc/multi-session-host.js +206 -32
- package/dist/modes/rpc/multi-session-host.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +41 -3
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +125 -14
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +1 -1
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +6 -2
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
- package/dist/modes/rpc/session-command-router.js +24 -6
- package/dist/modes/rpc/session-command-router.js.map +1 -1
- package/dist/modes/rpc/session-event-writer.d.ts +13 -2
- package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
- package/dist/modes/rpc/session-event-writer.js +65 -25
- package/dist/modes/rpc/session-event-writer.js.map +1 -1
- package/dist/modes/rpc/session-registry.d.ts +9 -0
- package/dist/modes/rpc/session-registry.d.ts.map +1 -1
- package/dist/modes/rpc/session-registry.js +31 -3
- package/dist/modes/rpc/session-registry.js.map +1 -1
- package/docs/providers.md +48 -0
- package/docs/rpc.md +59 -5
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +44 -0
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +13 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/inline-worker.ts +15 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-indirect-eval.js +711 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/transport.ts +14 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +10 -10
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +9 -3
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +6 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +20 -4
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts +21 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js +27 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/post-mutate.js.map +1 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts +24 -0
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +7 -2
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js +46 -14
- package/node_modules/@earendil-works/pi-ai/dist/api/anthropic-tool-pairs.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts +11 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js +30 -16
- package/node_modules/@earendil-works/pi-ai/dist/api/cursor-agent.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts +16 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js +75 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/classify.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +45 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +81 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts +31 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js +65 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/select.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +12 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +37 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts +6 -0
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js +32 -6
- package/node_modules/@earendil-works/pi-ai/dist/auth/resolve.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts +3 -2
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/auth/types.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +6 -0
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +6 -1
- package/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts +75 -0
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +75 -0
- 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/alibaba-token-plan.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/baseten.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/cloudflare-workers-ai.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.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/huggingface.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/minimax.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/mistral.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.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/qwen-token-plan-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/qwen-token-plan.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.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/data/zai-coding-cn.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +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 +4 -0
- package/node_modules/@earendil-works/pi-ai/dist/utils/overflow.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +5 -5
- 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/dist/terminal.d.ts +5 -0
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js +90 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.js +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
|
@@ -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,CA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AAI,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 { 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 { 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\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#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?.hasUI) {\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\tif (this.#ctx?.hasUI) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tthis.#ctx.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t\t}\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 (ctx.hasUI) {\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,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,CAAC;AAC3E,MAAM,CAAC,MAAM,mCAAmC,GAAG,+BAA+B,CAAC;AACnF,MAAM,CAAC,MAAM,wBAAwB,GAAG,iCAAiC,C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,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"]}
|
|
@@ -310,6 +310,8 @@ function sanitizeContinuationState(goal) {
|
|
|
310
310
|
const next = { ...goal };
|
|
311
311
|
if (!isNonNegativeSafeInteger(next.consecutiveContinuations))
|
|
312
312
|
delete next.consecutiveContinuations;
|
|
313
|
+
if (!isNonNegativeSafeInteger(next.unattendedContinuations))
|
|
314
|
+
delete next.unattendedContinuations;
|
|
313
315
|
if (typeof next.lastContinuationSignature !== "string")
|
|
314
316
|
delete next.lastContinuationSignature;
|
|
315
317
|
return next;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,MAAM,aAA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AC,KAAK,CAAC,aAAa,CAAC,CAAC;QACpF,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,wBAAwB,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAChF,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAAC,KAA8B,EAAE,MAAkB;IAChF,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,CACN,OAAO,KAAK,CAAC,aAAa,KAAK,QAAQ;YACvC,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;YACrC,wBAAwB,CAAC,KAAK,CAAC,SAAS,CAAC,CACzC,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC,aAAa,KAAK,SAAS,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CAAC;AAC3E,CAAC;AAED,SAAS,yBAAyB,CAAC,IAAU;IAC5C,MAAM,IAAI,GAAS,EAAE,GAAG,IAAI,EAAE,CAAC;IAC/B,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,wBAAwB,CAAC;QAAE,OAAO,IAAI,CAAC,wBAAwB,CAAC;IACnG,IAAI,OAAO,IAAI,CAAC,yBAAyB,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,yBAAyB,CAAC;IAC9F,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,IAAY;IACtD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\nconst CURRENT_STORE_DIRECTORY = \"goal\";\nconst LEGACY_STORE_DIRECTORY = \"pi-goal\";\nconst LEGACY_BUDGET_LIMITED_STATUSES = [\"budgetLimited\", \"budget_limited\"];\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Imports legacy standalone `pi-goal` state into the current budget-free store.\n *\n * The current store always wins and legacy normalization is confined to this path.\n * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:\n * they remain untouched and do not block the live current store. Unexpected filesystem\n * failures still propagate.\n *\n * Session-backed stores use their stable thread id. No-session stores enumerate the\n * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they\n * inspect both the redirected Senpi-root sibling and the standalone pi agent root.\n * Multiple valid live candidates are reported as a conflict rather than guessed.\n *\n * Returns the imported goal, or null when nothing was migrated.\n */\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyCandidates = await readLegacyGoalCandidates(ref);\n\tif (legacyCandidates.length > 1) {\n\t\tthrow new Error(\n\t\t\t`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(\", \")}`,\n\t\t);\n\t}\n\tconst candidate = legacyCandidates[0];\n\tif (candidate === undefined) return null;\n\tconst published = await publishMigratedGoalFile(ref, candidate.goal);\n\tawait retireLegacyGoalFile(candidate.path);\n\treturn published ? candidate.goal : null;\n}\n\ninterface LegacyGoalCandidate {\n\tpath: string;\n\tgoal: Goal;\n}\n\nasync function readLegacyGoalCandidates(ref: GoalStoreRef): Promise<LegacyGoalCandidate[]> {\n\tconst legacyBaseDir = legacyBaseDirFor(ref.baseDir);\n\tif (legacyBaseDir === undefined) return [];\n\tconst cwdKey = noSessionCwdKey(ref.baseDir);\n\tif (cwdKey === undefined) {\n\t\tconst candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));\n\t\treturn candidate === null ? [] : [candidate];\n\t}\n\n\tconst standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), \".pi\", \"agent\");\n\tconst baseDirs = new Set([\n\t\tlegacyBaseDir,\n\t\tjoin(standaloneAgentDir, \"extensions\", LEGACY_STORE_DIRECTORY, \"no-session\", cwdKey),\n\t]);\n\tconst candidatePaths: string[] = [];\n\tfor (const baseDir of baseDirs) {\n\t\tlet entries: Dirent<string>[];\n\t\ttry {\n\t\t\tentries = await readdir(baseDir, { withFileTypes: true });\n\t\t} catch (error) {\n\t\t\tif (isMissingFile(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".json\")) candidatePaths.push(join(baseDir, entry.name));\n\t\t}\n\t}\n\n\tconst candidates: LegacyGoalCandidate[] = [];\n\tfor (const path of candidatePaths.sort()) {\n\t\tconst candidate = await readLegacyGoalCandidate(path);\n\t\tif (candidate !== null) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\nasync function readLegacyGoalCandidate(path: string): Promise<LegacyGoalCandidate | null> {\n\tlet goal: Goal | null;\n\ttry {\n\t\tgoal = parseGoalFile(await readFile(path, \"utf8\"), { legacy: true }).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error) || isIgnoredLegacyStoreError(error)) return null;\n\t\tthrow error;\n\t}\n\tif (goal === null) {\n\t\tawait retireLegacyGoalFile(path);\n\t\treturn null;\n\t}\n\treturn { path, goal };\n}\n\nasync function retireLegacyGoalFile(path: string): Promise<void> {\n\ttry {\n\t\tawait rename(path, `${path}.migrated`);\n\t} catch {\n\t\t// Retirement is best-effort: a preserved legacy file must never fail live migration.\n\t}\n}\n\nfunction isIgnoredLegacyStoreError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof InvalidGoalStoreError ||\n\t\terror instanceof UnsupportedGoalStoreVersionError ||\n\t\terror instanceof SyntaxError\n\t);\n}\n\n/**\n * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing\n * the `goal` path segment itself.\n *\n * Both store layouts must map correctly:\n * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal\n * <agentDir>/extensions/goal/no-session/<cwdKey>\n * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>\n *\n * Swapping `dirname(baseDir)` only works for the first layout; in the no-session\n * fallback it points inside the current store tree, which both misses real legacy\n * state and can import an unrelated nested directory.\n */\nfunction legacyBaseDirFor(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1) return undefined;\n\tsegments[goalIndex] = LEGACY_STORE_DIRECTORY;\n\treturn segments.join(sep);\n}\n\nfunction noSessionCwdKey(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1 || segments[goalIndex + 1] !== \"no-session\") return undefined;\n\treturn segments[goalIndex + 2];\n}\n\nfunction pathSegments(path: string): string[] {\n\treturn path.split(/[\\\\/]/);\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function publishMigratedGoalFile(ref: GoalStoreRef, goal: Goal): Promise<boolean> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tconst contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`;\n\ttry {\n\t\tawait writeFile(filePath, contents, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"EEXIST\")) return false;\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string, { legacy = false }: { legacy?: boolean } = {}): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;\n\tif (goal !== null && !isGoal(goal)) throw new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\n/**\n * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and\n * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes\n * as `active`. This runs only on the legacy import path.\n */\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (typeof normalized.status === \"string\" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn isFileSystemError(error, \"ENOENT\");\n}\n\nfunction isFileSystemError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAEtF,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAEzE,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AACzC,MAAM,8BAA8B,GAAG,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;AAE3E,MAAM,UAAU,eAAe,CAAC,GAAiB;IAChD,OAAO,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAiB;IAC7C,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC1D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,GAAiB;IACnD,IAAI,CAAC;QACJ,OAAO,aAAa,CAAC,MAAM,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,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,wBAAwB,CAAC;IACnG,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,uBAAuB,CAAC;QAAE,OAAO,IAAI,CAAC,uBAAuB,CAAC;IACjG,IAAI,OAAO,IAAI,CAAC,yBAAyB,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,yBAAyB,CAAC;IAC9F,OAAO,IAAI,CAAC;AACb,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,IAAY;IACtD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACzE,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Dirent } from \"node:fs\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, sep } from \"node:path\";\nimport { InvalidGoalStoreError, UnsupportedGoalStoreVersionError } from \"./errors.ts\";\nimport type { Goal, GoalFile, GoalStatus, GoalStoreRef } from \"./types.ts\";\nimport { isRecord } from \"./types.ts\";\nimport { isGoalStatus, isNonNegativeSafeInteger } from \"./validation.ts\";\n\nconst STORE_VERSION = 1;\nconst CURRENT_STORE_DIRECTORY = \"goal\";\nconst LEGACY_STORE_DIRECTORY = \"pi-goal\";\nconst LEGACY_BUDGET_LIMITED_STATUSES = [\"budgetLimited\", \"budget_limited\"];\n\nexport function encodedThreadId(ref: GoalStoreRef): string {\n\treturn encodeURIComponent(ref.threadId);\n}\n\nexport function goalFilePath(ref: GoalStoreRef): string {\n\treturn join(ref.baseDir, `${encodedThreadId(ref)}.json`);\n}\n\nexport async function readGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\treturn parseGoalFile(await readFile(goalFilePath(ref), \"utf8\")).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error)) return null;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Imports legacy standalone `pi-goal` state into the current budget-free store.\n *\n * The current store always wins and legacy normalization is confined to this path.\n * Invalid, unsupported, or malformed legacy files are best-effort dead-data imports:\n * they remain untouched and do not block the live current store. Unexpected filesystem\n * failures still propagate.\n *\n * Session-backed stores use their stable thread id. No-session stores enumerate the\n * cwd-keyed legacy bucket because each ephemeral run receives a new thread id, and they\n * inspect both the redirected Senpi-root sibling and the standalone pi agent root.\n * Multiple valid live candidates are reported as a conflict rather than guessed.\n *\n * Returns the imported goal, or null when nothing was migrated.\n */\nexport async function migrateLegacyGoalFile(ref: GoalStoreRef): Promise<Goal | null> {\n\ttry {\n\t\tawait readFile(goalFilePath(ref), \"utf8\");\n\t\treturn null;\n\t} catch (error) {\n\t\tif (!isMissingFile(error)) throw error;\n\t}\n\n\tconst legacyCandidates = await readLegacyGoalCandidates(ref);\n\tif (legacyCandidates.length > 1) {\n\t\tthrow new Error(\n\t\t\t`multiple legacy goals found for no-session store: ${legacyCandidates.map(({ path }) => path).join(\", \")}`,\n\t\t);\n\t}\n\tconst candidate = legacyCandidates[0];\n\tif (candidate === undefined) return null;\n\tconst published = await publishMigratedGoalFile(ref, candidate.goal);\n\tawait retireLegacyGoalFile(candidate.path);\n\treturn published ? candidate.goal : null;\n}\n\ninterface LegacyGoalCandidate {\n\tpath: string;\n\tgoal: Goal;\n}\n\nasync function readLegacyGoalCandidates(ref: GoalStoreRef): Promise<LegacyGoalCandidate[]> {\n\tconst legacyBaseDir = legacyBaseDirFor(ref.baseDir);\n\tif (legacyBaseDir === undefined) return [];\n\tconst cwdKey = noSessionCwdKey(ref.baseDir);\n\tif (cwdKey === undefined) {\n\t\tconst candidate = await readLegacyGoalCandidate(goalFilePath({ ...ref, baseDir: legacyBaseDir }));\n\t\treturn candidate === null ? [] : [candidate];\n\t}\n\n\tconst standaloneAgentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), \".pi\", \"agent\");\n\tconst baseDirs = new Set([\n\t\tlegacyBaseDir,\n\t\tjoin(standaloneAgentDir, \"extensions\", LEGACY_STORE_DIRECTORY, \"no-session\", cwdKey),\n\t]);\n\tconst candidatePaths: string[] = [];\n\tfor (const baseDir of baseDirs) {\n\t\tlet entries: Dirent<string>[];\n\t\ttry {\n\t\t\tentries = await readdir(baseDir, { withFileTypes: true });\n\t\t} catch (error) {\n\t\t\tif (isMissingFile(error)) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isFile() && entry.name.endsWith(\".json\")) candidatePaths.push(join(baseDir, entry.name));\n\t\t}\n\t}\n\n\tconst candidates: LegacyGoalCandidate[] = [];\n\tfor (const path of candidatePaths.sort()) {\n\t\tconst candidate = await readLegacyGoalCandidate(path);\n\t\tif (candidate !== null) candidates.push(candidate);\n\t}\n\treturn candidates;\n}\n\nasync function readLegacyGoalCandidate(path: string): Promise<LegacyGoalCandidate | null> {\n\tlet goal: Goal | null;\n\ttry {\n\t\tgoal = parseGoalFile(await readFile(path, \"utf8\"), { legacy: true }).goal;\n\t} catch (error) {\n\t\tif (isMissingFile(error) || isIgnoredLegacyStoreError(error)) return null;\n\t\tthrow error;\n\t}\n\tif (goal === null) {\n\t\tawait retireLegacyGoalFile(path);\n\t\treturn null;\n\t}\n\treturn { path, goal };\n}\n\nasync function retireLegacyGoalFile(path: string): Promise<void> {\n\ttry {\n\t\tawait rename(path, `${path}.migrated`);\n\t} catch {\n\t\t// Retirement is best-effort: a preserved legacy file must never fail live migration.\n\t}\n}\n\nfunction isIgnoredLegacyStoreError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof InvalidGoalStoreError ||\n\t\terror instanceof UnsupportedGoalStoreVersionError ||\n\t\terror instanceof SyntaxError\n\t);\n}\n\n/**\n * Maps a current goal-store directory to its legacy `pi-goal` counterpart by replacing\n * the `goal` path segment itself.\n *\n * Both store layouts must map correctly:\n * <sessionDir>/extensions/goal -> <sessionDir>/extensions/pi-goal\n * <agentDir>/extensions/goal/no-session/<cwdKey>\n * -> <agentDir>/extensions/pi-goal/no-session/<cwdKey>\n *\n * Swapping `dirname(baseDir)` only works for the first layout; in the no-session\n * fallback it points inside the current store tree, which both misses real legacy\n * state and can import an unrelated nested directory.\n */\nfunction legacyBaseDirFor(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1) return undefined;\n\tsegments[goalIndex] = LEGACY_STORE_DIRECTORY;\n\treturn segments.join(sep);\n}\n\nfunction noSessionCwdKey(baseDir: string): string | undefined {\n\tconst segments = pathSegments(baseDir);\n\tconst goalIndex = segments.lastIndexOf(CURRENT_STORE_DIRECTORY);\n\tif (goalIndex === -1 || segments[goalIndex + 1] !== \"no-session\") return undefined;\n\treturn segments[goalIndex + 2];\n}\n\nfunction pathSegments(path: string): string[] {\n\treturn path.split(/[\\\\/]/);\n}\n\nexport async function writeGoalFile(ref: GoalStoreRef, goal: Goal | null): Promise<void> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tawait writeGoalFileAtomic(filePath, `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`);\n}\n\nasync function writeGoalFileAtomic(filePath: string, contents: string): Promise<void> {\n\tconst tempPath = join(dirname(filePath), `.goal-${randomUUID()}.tmp`);\n\ttry {\n\t\tawait writeFile(tempPath, contents, { encoding: \"utf8\", mode: 0o600 });\n\t\tawait rename(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait rm(tempPath, { force: true });\n\t\t} catch (cleanupError) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, cleanupError],\n\t\t\t\t\"goal store write failed and its temporary file could not be removed\",\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nasync function publishMigratedGoalFile(ref: GoalStoreRef, goal: Goal): Promise<boolean> {\n\tconst filePath = goalFilePath(ref);\n\tawait mkdir(dirname(filePath), { recursive: true });\n\tconst contents = `${JSON.stringify({ version: STORE_VERSION, goal }, null, 2)}\\n`;\n\ttry {\n\t\tawait writeFile(filePath, contents, { encoding: \"utf8\", mode: 0o600, flag: \"wx\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"EEXIST\")) return false;\n\t\tthrow error;\n\t}\n}\n\nfunction parseGoalFile(raw: string, { legacy = false }: { legacy?: boolean } = {}): GoalFile {\n\tconst parsed = parseGoalFileJson(raw);\n\tif (!isRecord(parsed)) throw new InvalidGoalStoreError(\"goal store must be a JSON object\");\n\tif (parsed.version !== STORE_VERSION) throw new UnsupportedGoalStoreVersionError(\"unsupported goal store version\");\n\tconst goal = legacy ? normalizeLegacyGoal(parsed.goal) : parsed.goal;\n\tif (goal !== null && !isGoal(goal)) throw new InvalidGoalStoreError(\"goal store contains an invalid goal\");\n\treturn { version: STORE_VERSION, goal: goal === null ? null : sanitizeContinuationState(goal) };\n}\n\nfunction parseGoalFileJson(raw: string): unknown {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (error) {\n\t\tif (!(error instanceof SyntaxError)) throw error;\n\t\tconst recovered = recoverGoalFileWithStaleClosingBraces(raw);\n\t\tif (recovered === undefined) throw error;\n\t\ttry {\n\t\t\tparsed = JSON.parse(recovered);\n\t\t} catch {\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn parsed;\n}\n\n/**\n * Drops legacy budget enforcement: `tokenBudget` is a budgeting input in `pi-goal`, and\n * `budgetLimited` is a status this fork removed, so a budget-limited legacy goal resumes\n * as `active`. This runs only on the legacy import path.\n */\nfunction normalizeLegacyGoal(value: unknown): unknown {\n\tif (!isRecord(value)) return value;\n\tconst normalized = { ...value };\n\tdelete normalized.tokenBudget;\n\tif (typeof normalized.status === \"string\" && LEGACY_BUDGET_LIMITED_STATUSES.includes(normalized.status)) {\n\t\tnormalized.status = \"active\";\n\t}\n\treturn normalized;\n}\n\nfunction recoverGoalFileWithStaleClosingBraces(raw: string): string | undefined {\n\tlet rootStart = 0;\n\twhile (rootStart < raw.length && /[\\t\\n\\r ]/.test(raw[rootStart] ?? \"\")) rootStart += 1;\n\tif (raw[rootStart] !== \"{\") return undefined;\n\n\tlet depth = 0;\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = rootStart; index < raw.length; index += 1) {\n\t\tconst character = raw[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') inString = true;\n\t\telse if (character === \"{\" || character === \"[\") depth += 1;\n\t\telse if (character === \"}\" || character === \"]\") {\n\t\t\tdepth -= 1;\n\t\t\tif (depth < 0) return undefined;\n\t\t\tif (depth === 0) {\n\t\t\t\tlet hasStaleClosingBrace = false;\n\t\t\t\tfor (let suffixIndex = index + 1; suffixIndex < raw.length; suffixIndex += 1) {\n\t\t\t\t\tconst suffix = raw[suffixIndex];\n\t\t\t\t\tif (suffix === \"}\") hasStaleClosingBrace = true;\n\t\t\t\t\telse if (suffix !== \" \" && suffix !== \"\\t\" && suffix !== \"\\n\" && suffix !== \"\\r\") return undefined;\n\t\t\t\t}\n\t\t\t\treturn hasStaleClosingBrace ? raw.slice(0, index + 1) : undefined;\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction isGoal(value: unknown): value is Goal {\n\tif (!isRecord(value)) return false;\n\treturn (\n\t\ttypeof value.id === \"string\" &&\n\t\ttypeof value.threadId === \"string\" &&\n\t\ttypeof value.objective === \"string\" &&\n\t\tisGoalStatus(value.status) &&\n\t\t(value.tokenBudget === undefined || isNonNegativeSafeInteger(value.tokenBudget)) &&\n\t\thasValidBlockedFields(value, value.status) &&\n\t\tisNonNegativeSafeInteger(value.tokensUsed) &&\n\t\tisNonNegativeSafeInteger(value.timeUsedSeconds) &&\n\t\tisNonNegativeSafeInteger(value.createdAt) &&\n\t\tisNonNegativeSafeInteger(value.updatedAt) &&\n\t\t(value.lastStartedAt === undefined || isNonNegativeSafeInteger(value.lastStartedAt)) &&\n\t\t(value.completedAt === undefined || isNonNegativeSafeInteger(value.completedAt))\n\t);\n}\n\nfunction hasValidBlockedFields(value: Record<string, unknown>, status: GoalStatus): boolean {\n\tif (status === \"blocked\") {\n\t\treturn (\n\t\t\ttypeof value.blockedReason === \"string\" &&\n\t\t\tvalue.blockedReason.trim().length > 0 &&\n\t\t\tisNonNegativeSafeInteger(value.blockedAt)\n\t\t);\n\t}\n\treturn value.blockedReason === undefined && value.blockedAt === undefined;\n}\n\nfunction sanitizeContinuationState(goal: Goal): Goal {\n\tconst next: Goal = { ...goal };\n\tif (!isNonNegativeSafeInteger(next.consecutiveContinuations)) delete next.consecutiveContinuations;\n\tif (!isNonNegativeSafeInteger(next.unattendedContinuations)) delete next.unattendedContinuations;\n\tif (typeof next.lastContinuationSignature !== \"string\") delete next.lastContinuationSignature;\n\treturn next;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n\treturn isFileSystemError(error, \"ENOENT\");\n}\n\nfunction isFileSystemError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { Theme } from "../../../../modes/interactive/theme/theme.ts";
|
|
3
|
+
import type { ToolRenderResultOptions } from "../../types.ts";
|
|
4
|
+
interface ResultLike {
|
|
5
|
+
content: ReadonlyArray<{
|
|
6
|
+
type: string;
|
|
7
|
+
text?: string;
|
|
8
|
+
}>;
|
|
9
|
+
details?: unknown;
|
|
10
|
+
}
|
|
11
|
+
export declare function renderGoalToolCall(toolName: string, args: unknown, theme: Theme): Text;
|
|
12
|
+
export declare function renderGoalToolResult(result: ResultLike, options: ToolRenderResultOptions, theme: Theme): Text;
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=renderers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"renderers.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/renderers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAC9C,OAAO,KAAK,EAAE,KAAK,EAAc,MAAM,8CAA8C,CAAC;AACtF,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAS9D,UAAU,UAAU;IACnB,OAAO,EAAE,aAAa,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAgBtF;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAY7G"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
2
|
+
import { formatGoalElapsedSeconds, formatTokensCompact } from "./format.js";
|
|
3
|
+
import { GOAL_STATUS_VALUES, isRecord } from "./types.js";
|
|
4
|
+
const OBJECTIVE_PREVIEW_WIDTH = 120;
|
|
5
|
+
const COLLAPSED_OBJECTIVE_LINES = 2;
|
|
6
|
+
const CALL_OBJECTIVE_BUDGET = 80;
|
|
7
|
+
const CALL_REASON_BUDGET = 60;
|
|
8
|
+
export function renderGoalToolCall(toolName, args, theme) {
|
|
9
|
+
const title = theme.fg("toolTitle", theme.bold(toolName));
|
|
10
|
+
const params = isRecord(args) ? args : {};
|
|
11
|
+
if (toolName === "create_goal" && typeof params.objective === "string") {
|
|
12
|
+
const preview = objectiveCallPreview(params.objective);
|
|
13
|
+
return new Text(preview === "" ? title : `${title} ${theme.fg("muted", preview)}`, 0, 0);
|
|
14
|
+
}
|
|
15
|
+
if (toolName === "update_goal" && typeof params.status === "string") {
|
|
16
|
+
const statusColor = params.status === "complete" ? "success" : "error";
|
|
17
|
+
let line = `${title} ${theme.fg("muted", "→")} ${theme.fg(statusColor, params.status)}`;
|
|
18
|
+
if (typeof params.reason === "string" && params.reason.trim().length > 0) {
|
|
19
|
+
line += ` ${theme.fg("muted", `— ${shorten(params.reason.trim(), CALL_REASON_BUDGET)}`)}`;
|
|
20
|
+
}
|
|
21
|
+
return new Text(line, 0, 0);
|
|
22
|
+
}
|
|
23
|
+
return new Text(title, 0, 0);
|
|
24
|
+
}
|
|
25
|
+
export function renderGoalToolResult(result, options, theme) {
|
|
26
|
+
const text = result.content.find((block) => block.type === "text")?.text ?? "";
|
|
27
|
+
const details = resolveRenderDetails(result.details, text);
|
|
28
|
+
if (details === undefined)
|
|
29
|
+
return new Text(theme.fg("toolOutput", text), 0, 0);
|
|
30
|
+
if (details.goal === null) {
|
|
31
|
+
const lines = [theme.fg("dim", "No active goal is set.")];
|
|
32
|
+
appendNotice(lines, details.notice, theme);
|
|
33
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
34
|
+
}
|
|
35
|
+
const lines = goalWidgetLines(details.goal, options.expanded, theme);
|
|
36
|
+
appendNotice(lines, details.notice, theme);
|
|
37
|
+
return new Text(lines.join("\n"), 0, 0);
|
|
38
|
+
}
|
|
39
|
+
function goalWidgetLines(goal, expanded, theme) {
|
|
40
|
+
const status = theme.fg(statusColor(goal.status), theme.bold(`${statusGlyph(goal.status)} ${goal.status}`));
|
|
41
|
+
const usage = ` • ${formatTokensCompact(goal.tokensUsed)} tokens • ${formatGoalElapsedSeconds(goal.timeUsedSeconds)}`;
|
|
42
|
+
const lines = [`${status}${theme.fg("muted", usage)}`];
|
|
43
|
+
const objectiveLines = goal.objective
|
|
44
|
+
.split("\n")
|
|
45
|
+
.map((line) => line.trim())
|
|
46
|
+
.filter((line) => line.length > 0);
|
|
47
|
+
if (expanded) {
|
|
48
|
+
for (const line of objectiveLines)
|
|
49
|
+
lines.push(theme.fg("toolOutput", ` ${line}`));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
for (const line of objectiveLines.slice(0, COLLAPSED_OBJECTIVE_LINES)) {
|
|
53
|
+
lines.push(theme.fg("toolOutput", ` ${shorten(line, OBJECTIVE_PREVIEW_WIDTH)}`));
|
|
54
|
+
}
|
|
55
|
+
const hidden = objectiveLines.length - COLLAPSED_OBJECTIVE_LINES;
|
|
56
|
+
if (hidden > 0)
|
|
57
|
+
lines.push(theme.fg("dim", ` … +${hidden} more lines`));
|
|
58
|
+
}
|
|
59
|
+
if (goal.blockedReason !== undefined && goal.blockedReason.length > 0) {
|
|
60
|
+
lines.push(theme.fg("warning", ` ⚠ ${goal.blockedReason}`));
|
|
61
|
+
}
|
|
62
|
+
if (expanded) {
|
|
63
|
+
const created = isoTimestamp(goal.createdAt);
|
|
64
|
+
const updated = isoTimestamp(goal.updatedAt);
|
|
65
|
+
lines.push(theme.fg("dim", ` created ${created} • updated ${updated}`));
|
|
66
|
+
}
|
|
67
|
+
return lines;
|
|
68
|
+
}
|
|
69
|
+
function appendNotice(lines, notice, theme) {
|
|
70
|
+
if (notice !== undefined && notice.length > 0)
|
|
71
|
+
lines.push(theme.fg("dim", ` ${notice}`));
|
|
72
|
+
}
|
|
73
|
+
function resolveRenderDetails(details, text) {
|
|
74
|
+
const direct = parseRenderDetails(details);
|
|
75
|
+
if (direct !== undefined)
|
|
76
|
+
return direct;
|
|
77
|
+
const trimmed = text.trim();
|
|
78
|
+
if (!trimmed.startsWith("{"))
|
|
79
|
+
return undefined;
|
|
80
|
+
try {
|
|
81
|
+
return parseRenderDetails(JSON.parse(trimmed));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function parseRenderDetails(value) {
|
|
88
|
+
if (!isRecord(value) || !("goal" in value))
|
|
89
|
+
return undefined;
|
|
90
|
+
const goal = value.goal;
|
|
91
|
+
const notice = typeof value.notice === "string" ? value.notice : undefined;
|
|
92
|
+
if (goal === null)
|
|
93
|
+
return { goal: null, ...(notice === undefined ? {} : { notice }) };
|
|
94
|
+
if (!isGoalSnapshotLike(goal))
|
|
95
|
+
return undefined;
|
|
96
|
+
return { goal, ...(notice === undefined ? {} : { notice }) };
|
|
97
|
+
}
|
|
98
|
+
function isGoalSnapshotLike(value) {
|
|
99
|
+
return (isRecord(value) &&
|
|
100
|
+
typeof value.objective === "string" &&
|
|
101
|
+
typeof value.status === "string" &&
|
|
102
|
+
GOAL_STATUS_VALUES.includes(value.status) &&
|
|
103
|
+
typeof value.tokensUsed === "number" &&
|
|
104
|
+
typeof value.timeUsedSeconds === "number" &&
|
|
105
|
+
typeof value.createdAt === "number" &&
|
|
106
|
+
typeof value.updatedAt === "number");
|
|
107
|
+
}
|
|
108
|
+
function statusGlyph(status) {
|
|
109
|
+
switch (status) {
|
|
110
|
+
case "active":
|
|
111
|
+
return "●";
|
|
112
|
+
case "paused":
|
|
113
|
+
return "◌";
|
|
114
|
+
case "blocked":
|
|
115
|
+
return "■";
|
|
116
|
+
case "complete":
|
|
117
|
+
return "✓";
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function statusColor(status) {
|
|
121
|
+
switch (status) {
|
|
122
|
+
case "active":
|
|
123
|
+
return "accent";
|
|
124
|
+
case "paused":
|
|
125
|
+
return "muted";
|
|
126
|
+
case "blocked":
|
|
127
|
+
return "error";
|
|
128
|
+
case "complete":
|
|
129
|
+
return "success";
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function objectiveCallPreview(objective) {
|
|
133
|
+
const lines = objective
|
|
134
|
+
.split("\n")
|
|
135
|
+
.map((line) => line.trim())
|
|
136
|
+
.filter((line) => line.length > 0);
|
|
137
|
+
const first = lines[0] ?? "";
|
|
138
|
+
if (first === "")
|
|
139
|
+
return "";
|
|
140
|
+
const truncated = shorten(first, CALL_OBJECTIVE_BUDGET);
|
|
141
|
+
if (lines.length > 1 && truncated === first)
|
|
142
|
+
return `${first}…`;
|
|
143
|
+
return truncated;
|
|
144
|
+
}
|
|
145
|
+
function isoTimestamp(epochSeconds) {
|
|
146
|
+
return new Date(epochSeconds * 1000).toISOString();
|
|
147
|
+
}
|
|
148
|
+
function shorten(value, max) {
|
|
149
|
+
if (value.length <= max)
|
|
150
|
+
return value;
|
|
151
|
+
return `${value.slice(0, max - 1)}…`;
|
|
152
|
+
}
|
|
153
|
+
//# sourceMappingURL=renderers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"renderers.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/renderers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAG9C,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAA8B,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,kBAAkB,EAA0C,QAAQ,EAAE,MAAM,YAAY,CAAC;AAElG,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AACpC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACjC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAO9B,MAAM,UAAU,kBAAkB,CAAC,QAAgB,EAAE,IAAa,EAAE,KAAY;IAC/E,MAAM,KAAK,GAAG,KAAK,CAAC,EAAE,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1C,IAAI,QAAQ,KAAK,aAAa,IAAI,OAAO,MAAM,CAAC,SAA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CAAC;AACtC,CAAC","sourcesContent":["import { Text } from \"@earendil-works/pi-tui\";\nimport type { Theme, ThemeColor } from \"../../../../modes/interactive/theme/theme.ts\";\nimport type { ToolRenderResultOptions } from \"../../types.ts\";\nimport { formatGoalElapsedSeconds, formatTokensCompact, type GoalToolRenderDetails } from \"./format.ts\";\nimport { GOAL_STATUS_VALUES, type GoalStatus, type GoalToolSnapshot, isRecord } from \"./types.ts\";\n\nconst OBJECTIVE_PREVIEW_WIDTH = 120;\nconst COLLAPSED_OBJECTIVE_LINES = 2;\nconst CALL_OBJECTIVE_BUDGET = 80;\nconst CALL_REASON_BUDGET = 60;\n\ninterface ResultLike {\n\tcontent: ReadonlyArray<{ type: string; text?: string }>;\n\tdetails?: unknown;\n}\n\nexport function renderGoalToolCall(toolName: string, args: unknown, theme: Theme): Text {\n\tconst title = theme.fg(\"toolTitle\", theme.bold(toolName));\n\tconst params = isRecord(args) ? args : {};\n\tif (toolName === \"create_goal\" && typeof params.objective === \"string\") {\n\t\tconst preview = objectiveCallPreview(params.objective);\n\t\treturn new Text(preview === \"\" ? title : `${title} ${theme.fg(\"muted\", preview)}`, 0, 0);\n\t}\n\tif (toolName === \"update_goal\" && typeof params.status === \"string\") {\n\t\tconst statusColor: ThemeColor = params.status === \"complete\" ? \"success\" : \"error\";\n\t\tlet line = `${title} ${theme.fg(\"muted\", \"→\")} ${theme.fg(statusColor, params.status)}`;\n\t\tif (typeof params.reason === \"string\" && params.reason.trim().length > 0) {\n\t\t\tline += ` ${theme.fg(\"muted\", `— ${shorten(params.reason.trim(), CALL_REASON_BUDGET)}`)}`;\n\t\t}\n\t\treturn new Text(line, 0, 0);\n\t}\n\treturn new Text(title, 0, 0);\n}\n\nexport function renderGoalToolResult(result: ResultLike, options: ToolRenderResultOptions, theme: Theme): Text {\n\tconst text = result.content.find((block) => block.type === \"text\")?.text ?? \"\";\n\tconst details = resolveRenderDetails(result.details, text);\n\tif (details === undefined) return new Text(theme.fg(\"toolOutput\", text), 0, 0);\n\tif (details.goal === null) {\n\t\tconst lines = [theme.fg(\"dim\", \"No active goal is set.\")];\n\t\tappendNotice(lines, details.notice, theme);\n\t\treturn new Text(lines.join(\"\\n\"), 0, 0);\n\t}\n\tconst lines = goalWidgetLines(details.goal, options.expanded, theme);\n\tappendNotice(lines, details.notice, theme);\n\treturn new Text(lines.join(\"\\n\"), 0, 0);\n}\n\nfunction goalWidgetLines(goal: GoalToolSnapshot, expanded: boolean, theme: Theme): string[] {\n\tconst status = theme.fg(statusColor(goal.status), theme.bold(`${statusGlyph(goal.status)} ${goal.status}`));\n\tconst usage = ` • ${formatTokensCompact(goal.tokensUsed)} tokens • ${formatGoalElapsedSeconds(goal.timeUsedSeconds)}`;\n\tconst lines = [`${status}${theme.fg(\"muted\", usage)}`];\n\n\tconst objectiveLines = goal.objective\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tif (expanded) {\n\t\tfor (const line of objectiveLines) lines.push(theme.fg(\"toolOutput\", ` ${line}`));\n\t} else {\n\t\tfor (const line of objectiveLines.slice(0, COLLAPSED_OBJECTIVE_LINES)) {\n\t\t\tlines.push(theme.fg(\"toolOutput\", ` ${shorten(line, OBJECTIVE_PREVIEW_WIDTH)}`));\n\t\t}\n\t\tconst hidden = objectiveLines.length - COLLAPSED_OBJECTIVE_LINES;\n\t\tif (hidden > 0) lines.push(theme.fg(\"dim\", ` … +${hidden} more lines`));\n\t}\n\n\tif (goal.blockedReason !== undefined && goal.blockedReason.length > 0) {\n\t\tlines.push(theme.fg(\"warning\", ` ⚠ ${goal.blockedReason}`));\n\t}\n\tif (expanded) {\n\t\tconst created = isoTimestamp(goal.createdAt);\n\t\tconst updated = isoTimestamp(goal.updatedAt);\n\t\tlines.push(theme.fg(\"dim\", ` created ${created} • updated ${updated}`));\n\t}\n\treturn lines;\n}\n\nfunction appendNotice(lines: string[], notice: string | undefined, theme: Theme): void {\n\tif (notice !== undefined && notice.length > 0) lines.push(theme.fg(\"dim\", ` ${notice}`));\n}\n\nfunction resolveRenderDetails(details: unknown, text: string): GoalToolRenderDetails | undefined {\n\tconst direct = parseRenderDetails(details);\n\tif (direct !== undefined) return direct;\n\tconst trimmed = text.trim();\n\tif (!trimmed.startsWith(\"{\")) return undefined;\n\ttry {\n\t\treturn parseRenderDetails(JSON.parse(trimmed));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction parseRenderDetails(value: unknown): GoalToolRenderDetails | undefined {\n\tif (!isRecord(value) || !(\"goal\" in value)) return undefined;\n\tconst goal = value.goal;\n\tconst notice = typeof value.notice === \"string\" ? value.notice : undefined;\n\tif (goal === null) return { goal: null, ...(notice === undefined ? {} : { notice }) };\n\tif (!isGoalSnapshotLike(goal)) return undefined;\n\treturn { goal, ...(notice === undefined ? {} : { notice }) };\n}\n\nfunction isGoalSnapshotLike(value: unknown): value is GoalToolSnapshot {\n\treturn (\n\t\tisRecord(value) &&\n\t\ttypeof value.objective === \"string\" &&\n\t\ttypeof value.status === \"string\" &&\n\t\t(GOAL_STATUS_VALUES as readonly string[]).includes(value.status) &&\n\t\ttypeof value.tokensUsed === \"number\" &&\n\t\ttypeof value.timeUsedSeconds === \"number\" &&\n\t\ttypeof value.createdAt === \"number\" &&\n\t\ttypeof value.updatedAt === \"number\"\n\t);\n}\n\nfunction statusGlyph(status: GoalStatus): string {\n\tswitch (status) {\n\t\tcase \"active\":\n\t\t\treturn \"●\";\n\t\tcase \"paused\":\n\t\t\treturn \"◌\";\n\t\tcase \"blocked\":\n\t\t\treturn \"■\";\n\t\tcase \"complete\":\n\t\t\treturn \"✓\";\n\t}\n}\n\nfunction statusColor(status: GoalStatus): ThemeColor {\n\tswitch (status) {\n\t\tcase \"active\":\n\t\t\treturn \"accent\";\n\t\tcase \"paused\":\n\t\t\treturn \"muted\";\n\t\tcase \"blocked\":\n\t\t\treturn \"error\";\n\t\tcase \"complete\":\n\t\t\treturn \"success\";\n\t}\n}\n\nfunction objectiveCallPreview(objective: string): string {\n\tconst lines = objective\n\t\t.split(\"\\n\")\n\t\t.map((line) => line.trim())\n\t\t.filter((line) => line.length > 0);\n\tconst first = lines[0] ?? \"\";\n\tif (first === \"\") return \"\";\n\tconst truncated = shorten(first, CALL_OBJECTIVE_BUDGET);\n\tif (lines.length > 1 && truncated === first) return `${first}…`;\n\treturn truncated;\n}\n\nfunction isoTimestamp(epochSeconds: number): string {\n\treturn new Date(epochSeconds * 1000).toISOString();\n}\n\nfunction shorten(value: string, max: number): string {\n\tif (value.length <= max) return value;\n\treturn `${value.slice(0, max - 1)}…`;\n}\n"]}
|
|
@@ -11,6 +11,10 @@ export declare function updateGoal(ref: GoalStoreRef, update: GoalUpdate, source
|
|
|
11
11
|
export declare function archiveGoal(ref: GoalStoreRef, goal: Goal): Promise<void>;
|
|
12
12
|
export declare function clearGoal(ref: GoalStoreRef): Promise<boolean>;
|
|
13
13
|
export declare function accountGoalUsage(ref: GoalStoreRef, usage: TokenUsageSnapshot, elapsedSeconds: number, mode?: GoalAccountingMode, expectedGoalId?: string): Promise<Goal | null>;
|
|
14
|
-
export declare function recordContinuationDelivered(ref: GoalStoreRef, signature: string, expectedGoalId?: string
|
|
15
|
-
|
|
14
|
+
export declare function recordContinuationDelivered(ref: GoalStoreRef, signature: string, expectedGoalId?: string, options?: {
|
|
15
|
+
countUnattended?: boolean;
|
|
16
|
+
}): Promise<Goal | null>;
|
|
17
|
+
export declare function resetContinuationStreak(ref: GoalStoreRef, options?: {
|
|
18
|
+
unattended?: boolean;
|
|
19
|
+
}): Promise<Goal | null>;
|
|
16
20
|
//# sourceMappingURL=store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/store.ts"],"names":[],"mappings":"AAIA,OAAO,EAAmB,YAAY,EAA+B,MAAM,kBAAkB,CAAC;AAE9F,OAAO,KAAK,EACX,IAAI,EACJ,kBAAkB,EAClB,YAAY,EACZ,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