@code-yeongyu/senpi 2026.9.12-3 → 2026.9.13-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/README.md +3 -1
- package/dist/bun/cli.js +2 -3
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/runtime-modules.d.ts +3 -0
- package/dist/bun/runtime-modules.d.ts.map +1 -0
- package/dist/bun/runtime-modules.js +17 -0
- package/dist/bun/runtime-modules.js.map +1 -0
- package/dist/bun/runtime-setup.js +2 -5
- package/dist/bun/runtime-setup.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +38 -30
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/discovered-resource-scope.d.ts +23 -0
- package/dist/core/discovered-resource-scope.d.ts.map +1 -0
- package/dist/core/discovered-resource-scope.js +44 -0
- package/dist/core/discovered-resource-scope.js.map +1 -0
- package/dist/core/extensions/builtin/ask-user/notify.d.ts +24 -0
- package/dist/core/extensions/builtin/ask-user/notify.d.ts.map +1 -0
- package/dist/core/extensions/builtin/ask-user/notify.js +11 -0
- package/dist/core/extensions/builtin/ask-user/notify.js.map +1 -0
- package/dist/core/extensions/builtin/ask-user/registry.d.ts +2 -0
- package/dist/core/extensions/builtin/ask-user/registry.d.ts.map +1 -1
- package/dist/core/extensions/builtin/ask-user/registry.js.map +1 -1
- package/dist/core/extensions/builtin/ask-user/resume.d.ts +1 -1
- package/dist/core/extensions/builtin/ask-user/resume.d.ts.map +1 -1
- package/dist/core/extensions/builtin/ask-user/resume.js +10 -20
- package/dist/core/extensions/builtin/ask-user/resume.js.map +1 -1
- package/dist/core/extensions/builtin/ask-user/tool.d.ts +5 -2
- package/dist/core/extensions/builtin/ask-user/tool.d.ts.map +1 -1
- package/dist/core/extensions/builtin/ask-user/tool.js +41 -6
- package/dist/core/extensions/builtin/ask-user/tool.js.map +1 -1
- package/dist/core/extensions/builtin/goal/channel-state-subscriptions.d.ts +2 -1
- package/dist/core/extensions/builtin/goal/channel-state-subscriptions.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/channel-state-subscriptions.js +1 -1
- package/dist/core/extensions/builtin/goal/channel-state-subscriptions.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 +27 -13
- package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/config-loader.d.ts +2 -0
- package/dist/core/extensions/builtin/hooks/config-loader.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/config-loader.js +27 -0
- package/dist/core/extensions/builtin/hooks/config-loader.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/dispatcher.js +1 -0
- package/dist/core/extensions/builtin/hooks/dispatcher.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/index.js +51 -2
- package/dist/core/extensions/builtin/hooks/index.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/lifecycle-adapter.d.ts +18 -1
- package/dist/core/extensions/builtin/hooks/lifecycle-adapter.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/lifecycle-adapter.js +36 -1
- package/dist/core/extensions/builtin/hooks/lifecycle-adapter.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/matcher.js +1 -0
- package/dist/core/extensions/builtin/hooks/matcher.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/output-parser.js +6 -0
- package/dist/core/extensions/builtin/hooks/output-parser.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust-storage.d.ts +2 -0
- package/dist/core/extensions/builtin/hooks/trust-storage.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/trust-storage.js +13 -0
- package/dist/core/extensions/builtin/hooks/trust-storage.js.map +1 -1
- package/dist/core/extensions/builtin/hooks/types.d.ts +14 -2
- package/dist/core/extensions/builtin/hooks/types.d.ts.map +1 -1
- package/dist/core/extensions/builtin/hooks/types.js +1 -1
- package/dist/core/extensions/builtin/hooks/types.js.map +1 -1
- package/dist/core/extensions/builtin/monitor-state-event.d.ts +1 -0
- package/dist/core/extensions/builtin/monitor-state-event.d.ts.map +1 -1
- package/dist/core/extensions/builtin/monitor-state-event.js.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +1 -0
- package/dist/core/extensions/builtin/terminal/tools/bash.d.ts.map +1 -1
- package/dist/core/extensions/builtin/terminal/tools/bash.js +13 -2
- package/dist/core/extensions/builtin/terminal/tools/bash.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +5 -16
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +16 -5
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +28 -5
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts +8 -3
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +12 -6
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/keybindings.d.ts +8 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +7 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/package-manager.d.ts +4 -2
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +7 -2
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-manifest.d.ts +2 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +3 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/resource-loader.d.ts +9 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +69 -21
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/settings-manager.d.ts +1 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +1 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-shapes.d.ts +1 -0
- package/dist/core/settings-shapes.d.ts.map +1 -1
- package/dist/core/settings-shapes.js.map +1 -1
- package/dist/core/source-info.d.ts +5 -1
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +5 -0
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/modes/app-server/server/skills.d.ts.map +1 -1
- package/dist/modes/app-server/server/skills.js +1 -0
- package/dist/modes/app-server/server/skills.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-answer-chip.d.ts +17 -0
- package/dist/modes/interactive/components/ask-user-answer-chip.d.ts.map +1 -0
- package/dist/modes/interactive/components/ask-user-answer-chip.js +86 -0
- package/dist/modes/interactive/components/ask-user-answer-chip.js.map +1 -0
- package/dist/modes/interactive/components/ask-user-answer-key.d.ts +3 -1
- package/dist/modes/interactive/components/ask-user-answer-key.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-answer-key.js +11 -1
- package/dist/modes/interactive/components/ask-user-answer-key.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-async-widget.d.ts +5 -2
- package/dist/modes/interactive/components/ask-user-async-widget.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-async-widget.js +18 -12
- package/dist/modes/interactive/components/ask-user-async-widget.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-countdown.d.ts +8 -0
- package/dist/modes/interactive/components/ask-user-countdown.d.ts.map +1 -0
- package/dist/modes/interactive/components/ask-user-countdown.js +23 -0
- package/dist/modes/interactive/components/ask-user-countdown.js.map +1 -0
- package/dist/modes/interactive/components/ask-user-question-keys.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-question-keys.js +85 -17
- package/dist/modes/interactive/components/ask-user-question-keys.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-question-render.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-question-render.js +22 -7
- package/dist/modes/interactive/components/ask-user-question-render.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-question-state.d.ts +15 -0
- package/dist/modes/interactive/components/ask-user-question-state.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-question-state.js +57 -13
- package/dist/modes/interactive/components/ask-user-question-state.js.map +1 -1
- package/dist/modes/interactive/components/ask-user-question.d.ts +8 -2
- package/dist/modes/interactive/components/ask-user-question.d.ts.map +1 -1
- package/dist/modes/interactive/components/ask-user-question.js +16 -8
- package/dist/modes/interactive/components/ask-user-question.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts +2 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +10 -1
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/loaded-resource-section.d.ts +14 -0
- package/dist/modes/interactive/components/loaded-resource-section.d.ts.map +1 -0
- package/dist/modes/interactive/components/loaded-resource-section.js +25 -0
- package/dist/modes/interactive/components/loaded-resource-section.js.map +1 -0
- package/dist/modes/interactive/components/user-message.d.ts +2 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +12 -2
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +14 -11
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +263 -165
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/loaded-resource-scopes.d.ts +28 -0
- package/dist/modes/interactive/loaded-resource-scopes.d.ts.map +1 -0
- package/dist/modes/interactive/loaded-resource-scopes.js +107 -0
- package/dist/modes/interactive/loaded-resource-scopes.js.map +1 -0
- package/dist/modes/interactive/tips/catalog/input-tips.d.ts +1 -1
- package/dist/modes/interactive/tips/catalog/input-tips.js +2 -2
- package/dist/modes/interactive/tips/catalog/input-tips.js.map +1 -1
- package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
- package/dist/modes/rpc/host-lifecycle.js +7 -0
- package/dist/modes/rpc/host-lifecycle.js.map +1 -1
- package/dist/modes/rpc/session-worker.js +5 -0
- package/dist/modes/rpc/session-worker.js.map +1 -1
- package/docs/environment-variables.md +5 -1
- package/docs/extensions.md +43 -5
- package/docs/keybindings.md +5 -2
- package/docs/packages.md +17 -0
- package/docs/rpc.md +6 -3
- package/docs/settings.md +5 -1
- package/docs/tui.md +15 -3
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +28 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +16 -4
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +2 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/session-env.ts +6 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +6 -1
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/run-eval-cell.ts +31 -12
- package/node_modules/@earendil-works/chord/package.json +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.d.ts +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +1 -1
- package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js.map +1 -1
- package/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
- package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.d.ts +2 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.js +6 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +55 -17
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts +2 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +9 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.d.ts +30 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.js +94 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.d.ts +48 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.js +104 -0
- package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/devin-provider.d.ts +6 -0
- package/node_modules/@earendil-works/pi-ai/dist/devin-provider.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/devin-provider.js +4 -0
- package/node_modules/@earendil-works/pi-ai/dist/devin-provider.js.map +1 -0
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.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/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/utils/retry.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +7 -3
- package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +10 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/README.md +11 -3
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +2 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/index.js +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/mouse-input.d.ts +37 -0
- package/node_modules/@earendil-works/pi-tui/dist/mouse-input.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/mouse-input.js +97 -0
- package/node_modules/@earendil-works/pi-tui/dist/mouse-input.js.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +2 -0
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +38 -0
- package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +25 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js +110 -4
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +5 -50
- package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts +12 -0
- package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +129 -3
- package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +28 -0
- package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/tui.js +160 -0
- 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 +13 -9
- package/dist/bun/register-cursor-agent.d.ts +0 -2
- package/dist/bun/register-cursor-agent.d.ts.map +0 -1
- package/dist/bun/register-cursor-agent.js +0 -4
- package/dist/bun/register-cursor-agent.js.map +0 -1
|
@@ -264,7 +264,7 @@ export class MonitorAwareGoalContinuation {
|
|
|
264
264
|
this.#directInputHolds.clear();
|
|
265
265
|
this.#resetContinuationState();
|
|
266
266
|
}
|
|
267
|
-
#schedule(goal, kind) {
|
|
267
|
+
#schedule(goal, kind, repark = false) {
|
|
268
268
|
if (this.#scheduledContinuationKind !== undefined)
|
|
269
269
|
return;
|
|
270
270
|
// A live wake source arms the periodic backstop only: the normal resumption
|
|
@@ -280,7 +280,8 @@ export class MonitorAwareGoalContinuation {
|
|
|
280
280
|
: GOAL_USER_GRACE_DELAY_MS;
|
|
281
281
|
this.#scheduledDelayMs = delayMs;
|
|
282
282
|
if (kind === "monitor") {
|
|
283
|
-
|
|
283
|
+
if (!repark)
|
|
284
|
+
this.#cacheWarmIteration += 1;
|
|
284
285
|
this.#scheduledCacheWarmIteration = this.#cacheWarmIteration;
|
|
285
286
|
const iteration = this.#scheduledCacheWarmIteration;
|
|
286
287
|
const cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);
|
|
@@ -297,10 +298,13 @@ export class MonitorAwareGoalContinuation {
|
|
|
297
298
|
...(cache !== undefined ? { cache } : {}),
|
|
298
299
|
});
|
|
299
300
|
this.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);
|
|
300
|
-
this
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
301
|
+
// Progress adjusts this wait; it is not another cache-warm iteration
|
|
302
|
+
// or transcript entry for every keystroke in the answer composer.
|
|
303
|
+
if (!repark)
|
|
304
|
+
this.#appendWarmupEntry({
|
|
305
|
+
phase: "scheduled",
|
|
306
|
+
...scheduleData,
|
|
307
|
+
});
|
|
304
308
|
}
|
|
305
309
|
else {
|
|
306
310
|
this.#scheduledAtMs = undefined;
|
|
@@ -500,7 +504,7 @@ export class MonitorAwareGoalContinuation {
|
|
|
500
504
|
if (events === undefined)
|
|
501
505
|
return;
|
|
502
506
|
this.#channelStateUnsubscribers.push(...subscribeGoalChannelState(events, {
|
|
503
|
-
onWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),
|
|
507
|
+
onWakeSource: (source, activeCount, event) => this.#setWakeSourceCount(source, activeCount, event?.items),
|
|
504
508
|
onContinuationHold: (source, active) => {
|
|
505
509
|
const inputId = `external:${source}`;
|
|
506
510
|
if (active)
|
|
@@ -534,15 +538,19 @@ export class MonitorAwareGoalContinuation {
|
|
|
534
538
|
return resolved * 60_000;
|
|
535
539
|
}
|
|
536
540
|
/**
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
* so the next schedule uses the periodic backstop again.
|
|
541
|
+
* Prefer the earliest authoritative request deadline. Legacy count-only
|
|
542
|
+
* emitters retain the settings-window heuristic; zero clears the deadline.
|
|
540
543
|
*/
|
|
541
|
-
#noteAskUserWait(activeCount) {
|
|
544
|
+
#noteAskUserWait(activeCount, items) {
|
|
542
545
|
if (activeCount <= 0) {
|
|
543
546
|
this.#askUserDeadlineAtMs = undefined;
|
|
544
547
|
return;
|
|
545
548
|
}
|
|
549
|
+
const deadlines = items?.flatMap((item) => (item.deadlineAtMs === undefined ? [] : [item.deadlineAtMs])) ?? [];
|
|
550
|
+
if (deadlines.length > 0) {
|
|
551
|
+
this.#askUserDeadlineAtMs = Math.min(...deadlines);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
546
554
|
const previousCount = this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0;
|
|
547
555
|
if (activeCount > previousCount || this.#askUserDeadlineAtMs === undefined) {
|
|
548
556
|
this.#askUserDeadlineAtMs = Date.now() + this.#askUserIdleTimeoutMs();
|
|
@@ -552,10 +560,11 @@ export class MonitorAwareGoalContinuation {
|
|
|
552
560
|
this.#wakeSources.clear();
|
|
553
561
|
this.#askUserDeadlineAtMs = undefined;
|
|
554
562
|
}
|
|
555
|
-
#setWakeSourceCount(source, activeCount) {
|
|
563
|
+
#setWakeSourceCount(source, activeCount, items) {
|
|
556
564
|
const previousTotal = this.#activeWakeSourceCount();
|
|
565
|
+
const previousDeadline = this.#askUserDeadlineAtMs;
|
|
557
566
|
if (source === ASK_USER_WAKE_SOURCE)
|
|
558
|
-
this.#noteAskUserWait(activeCount);
|
|
567
|
+
this.#noteAskUserWait(activeCount, items);
|
|
559
568
|
this.#wakeSources.set(source, activeCount);
|
|
560
569
|
const nextTotal = this.#activeWakeSourceCount();
|
|
561
570
|
if (previousTotal > 0 && nextTotal === 0) {
|
|
@@ -567,6 +576,11 @@ export class MonitorAwareGoalContinuation {
|
|
|
567
576
|
return;
|
|
568
577
|
}
|
|
569
578
|
if (this.#scheduledContinuationKind === "monitor") {
|
|
579
|
+
if (previousDeadline !== this.#askUserDeadlineAtMs && this.#goal !== null) {
|
|
580
|
+
this.#cancelTimer();
|
|
581
|
+
this.#schedule(this.#goal, "monitor", true);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
570
584
|
this.#waitTicker?.setChannelCounts(this.#wakeSourceSnapshot());
|
|
571
585
|
}
|
|
572
586
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monitor-continuation.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/goal/monitor-continuation.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EACN,sCAAsC,EACtC,2CAA2C,GAC3C,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BAA6B,EAC7B,qCAAqC,EACrC,gCAAgC,EAChC,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAUhC,OAAO,EAAE,uBAAuB,EAAE,oBAAoB,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,uFAAuF;AACvF,MAAM,oBAAoB,GAAG,UAAU,CAAC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AAS,CAAC;QAC1C,IAAI,CAAC,4BAA4B,CAAC,KAAK,EAAE,CAAC;QAC1C,IAAI,CAAC,6BAA6B,GAAG,EAAE,CAAC;QACxC,IAAI,CAAC,gCAAgC,EAAE,CAAC;QACxC,IAAI,CAAC,wBAAwB,EAAE,CAAC;IACjC,CAAC;IAED,wBAAwB;QACvB,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED,gCAAgC;QAC/B,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAC;QACrC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;IACnC,CAAC;IAED,YAAY;QACX,MAAM,IAAI,GAAG,IAAI,CAAC,0BAA0B,CAAC;QAC7C,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QACnC,IAAI,CAAC,4BAA4B,GAAG,SAAS,CAAC;QAC9C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS;YAAE,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,0BAA0B,GAAG,SAAS,CAAC;QAC5C,IAAI,IAAI,KAAK,SAAS;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,mCAAmC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3G,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;CACD","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport {\n\tGOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n} from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tisMalformedToolUseTurn,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tisLastTurnStuckOnContextOverflow,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\n/** Wake source the ask-user extension publishes while an async question is pending. */\nconst ASK_USER_WAKE_SOURCE = \"ask-user\";\n/** `askUser.timeoutMinutes` default (settings-manager.ts), used when the session exposes no ask-user settings. */\nconst ASK_USER_DEFAULT_TIMEOUT_MINUTES = 30;\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#askUserDeadlineAtMs: 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.#clearWakeSources();\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.#clearWakeSources();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\t// A live wake source arms the periodic backstop only: the normal resumption\n\t\t// is the drain fire in #setWakeSourceCount, and the backstop re-checks the\n\t\t// goal every `promptCache.goalBackstopMaxSeconds` in case the source never\n\t\t// delivers. A pending ask-user question is the exception: re-prompting the\n\t\t// model every backstop while the user is deciding is noise it cannot act\n\t\t// on, so the wait is parked on the question's own deadline instead.\n\t\tconst askUserWaitMs = kind === \"monitor\" ? this.#askUserWaitMs() : undefined;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? (askUserWaitMs ??\n\t\t\t\t\tresolveGoalMonitorContinuationDelayMs(this.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.()))\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tthis.#cacheWarmIteration += 1;\n\t\t\tthis.#scheduledCacheWarmIteration = this.#cacheWarmIteration;\n\t\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\t\tconst cache = estimateCacheWarmMetrics(this.#ctx?.model, process.env, this.#lastTurnUsage);\n\t\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\t\tthis.#scheduledCache = cache;\n\t\t\tthis.#scheduledAtMs = Date.now();\n\t\t\tconst scheduleData = createGoalCacheWarmScheduleData({\n\t\t\t\tgoalId: goal.id,\n\t\t\t\tdelayMs,\n\t\t\t\tscheduledAtMs: this.#scheduledAtMs,\n\t\t\t\titeration,\n\t\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\t\twakeSources,\n\t\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t\t});\n\t\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_SCHEDULED_EVENT, scheduleData);\n\t\t\tthis.#appendWarmupEntry({\n\t\t\t\tphase: \"scheduled\",\n\t\t\t\t...scheduleData,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#scheduledAtMs = undefined;\n\t\t\tthis.#scheduledCache = undefined;\n\t\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\t}\n\t\tthis.#scheduledContinuationKind = kind;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: true, kind });\n\t\tif (this.#directInputHolds.size > 0) {\n\t\t\tthis.#heldTimer = { kind, remainingMs: delayMs, heldAtMs: Date.now(), totalMs: delayMs, drainFire: false };\n\t\t\treturn;\n\t\t}\n\t\tthis.#armTimer(kind, delayMs, delayMs);\n\t}\n\n\t/**\n\t * `hasUI` is an `assertActive()`-guarded getter, so a ctx retired by session\n\t * replacement or reload THROWS instead of reporting false. Optional chaining\n\t * only guards an undefined ctx (what `dispose()` leaves behind), never a stale\n\t * object left by a replacement that never disposed this monitor. Callers reach\n\t * this from timer and event callbacks where a throw is fatal, so a retired ctx\n\t * reports \"no UI\" and any other failure keeps its current behavior.\n\t */\n\t#ctxHasUI(ctx: ExtensionContext | undefined = this.#ctx): boolean {\n\t\ttry {\n\t\t\treturn ctx?.hasUI === true;\n\t\t} catch (error) {\n\t\t\tif (isStaleExtensionContextError(error)) return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t#armTimer(kind: DelayedContinuationKind, delayMs: number, totalMs: number, drainFire = false): void {\n\t\tthis.#scheduledDueAtMs = Date.now() + delayMs;\n\t\tconst ctx = this.#ctx;\n\t\tif (ctx !== undefined && this.#ctxHasUI(ctx)) {\n\t\t\tthis.#waitTicker?.sync(ctx, {\n\t\t\t\tkind,\n\t\t\t\tremainingMs: delayMs,\n\t\t\t\ttotalMs,\n\t\t\t\tchannelCounts: this.#wakeSourceSnapshot(),\n\t\t\t});\n\t\t}\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tvoid this.#continueIfEligible(kind, drainFire).catch((error: unknown) => {\n\t\t\t\t// Runs from a bare setTimeout: anything thrown here escapes as an\n\t\t\t\t// uncaughtException and kills the session. A retired ctx cannot be\n\t\t\t\t// notified, and its own staleness is the expected cause of this\n\t\t\t\t// rejection after a session replacement, so drop it quietly.\n\t\t\t\tif (isStaleExtensionContextError(error) || !this.#ctxHasUI()) return;\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tthis.#ctx?.ui.notify(`Goal continuation delivery failed: ${message}`, \"error\");\n\t\t\t});\n\t\t}, delayMs);\n\t}\n\n\tasync #continueIfEligible(kind: DelayedContinuationKind, drainFire = false): Promise<void> {\n\t\tthis.#timer = undefined;\n\t\tthis.#scheduledDueAtMs = undefined;\n\t\tthis.#scheduledContinuationKind = undefined;\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_TIMER_STATE_EVENT, { armed: false, kind });\n\t\tthis.#waitTicker?.stop();\n\t\tconst delayMs =\n\t\t\tthis.#scheduledDelayMs ??\n\t\t\t(kind === \"monitor\" ? GOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS : GOAL_USER_GRACE_DELAY_MS);\n\t\tconst waitedMs = this.#scheduledAtMs === undefined ? delayMs : Math.max(0, Date.now() - this.#scheduledAtMs);\n\t\tconst cache = this.#scheduledCache;\n\t\tconst iteration = this.#scheduledCacheWarmIteration;\n\t\tthis.#scheduledAtMs = undefined;\n\t\tthis.#scheduledCache = undefined;\n\t\tthis.#scheduledDelayMs = undefined;\n\t\tthis.#scheduledCacheWarmIteration = undefined;\n\t\tconst ctx = this.#ctx;\n\t\tconst goal = this.#goal;\n\t\tif (ctx === undefined || goal?.status !== \"active\" || !ctx.isIdle() || ctx.hasPendingMessages()) return;\n\t\tif (kind === \"monitor\" && this.#activeWakeSourceCount() === 0 && !drainFire) return;\n\t\tconst admission = await this.#admitAndQueue(\n\t\t\tctx,\n\t\t\tgoal,\n\t\t\tkind === \"monitor\" ? \"monitorDelayed\" : \"userGrace\",\n\t\t\tthis.#lastAgentEndMessages,\n\t\t);\n\t\tif (kind !== \"monitor\" || !admission.admitted || iteration === undefined) return;\n\t\tconst wakeSources = this.#wakeSourceSnapshot();\n\t\tthis.#pi.events?.emit(GOAL_CONTINUATION_RESUMED_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\tcache,\n\t\t});\n\t\tthis.#appendWarmupEntry({\n\t\t\tphase: \"resumed\",\n\t\t\tgoalId: goal.id,\n\t\t\tdelayMs,\n\t\t\twaitedMs,\n\t\t\titeration,\n\t\t\tactiveMonitorCount: this.#activeWakeSourceCount(),\n\t\t\twakeSources,\n\t\t\t...(cache !== undefined ? { cache } : {}),\n\t\t});\n\t\tif (drainFire || admission.goal.status !== \"active\") this.#resetCacheWarmIteration();\n\t}\n\n\tasync #admitAndQueue(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Promise<GoalContinuationAdmission> {\n\t\tconst input = this.#buildVerdictInput(ctx, goal, path, messages);\n\t\tconst verdict = evaluateGoalContinuation({ goal, ...input });\n\t\tconst admittedGoal = await admitAndQueueGoalContinuation(this.#pi, ctx, goal, {\n\t\t\tinput,\n\t\t\tcontent: (continuationVerdict) => this.#buildContinuationContent(ctx, goal, continuationVerdict),\n\t\t\tmarkContinuationPending: this.#markContinuationPending,\n\t\t});\n\t\tif (admittedGoal === null) {\n\t\t\tthis.#goal = null;\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t\treturn { goal, admitted: false };\n\t\t}\n\t\tif (verdict.kind === \"continue\" && input.lastStopReason === \"length\") {\n\t\t\tthis.#consecutiveLengthRecoveries.set(goal.id, input.consecutiveLengthRecoveries + 1);\n\t\t}\n\t\tthis.#goal = admittedGoal;\n\t\tif (admittedGoal.status !== \"active\") {\n\t\t\tthis.#cancelTimer();\n\t\t\tthis.#resetToollessContinuationStreak();\n\t\t}\n\t\treturn { goal: admittedGoal, admitted: verdict.kind === \"continue\" };\n\t}\n\n\t#appendWarmupEntry(data: LiveGoalCacheWarmupEntryData): void {\n\t\tthis.#pi.appendEntry?.<GoalCacheWarmupEntryData>(GOAL_CACHE_WARMUP_ENTRY_TYPE, data);\n\t}\n\n\t#buildVerdictInput(\n\t\tctx: ExtensionContext,\n\t\tgoal: Goal,\n\t\tpath: GoalContinuationPath,\n\t\tmessages: readonly AgentMessage[],\n\t): Omit<GoalContinuationInput, \"goal\"> {\n\t\tconst lastAssistant = lastAssistantMessage(messages);\n\t\treturn {\n\t\t\tisIdle: ctx.isIdle(),\n\t\t\thasPendingMessages: ctx.hasPendingMessages(),\n\t\t\tpath,\n\t\t\tlastStopReason: lastAssistant?.stopReason,\n\t\t\tlastTurnWasMalformedToolUse: lastAssistant?.role === \"assistant\" && isMalformedToolUseTurn(lastAssistant),\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t\tlastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistant),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (this.#ctxHasUI(ctx)) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount) => this.#setWakeSourceCount(source, activeCount),\n\t\t\t\tonContinuationHold: (source, active) => {\n\t\t\t\t\tconst inputId = `external:${source}`;\n\t\t\t\t\tif (active) this.holdDirectInput(inputId);\n\t\t\t\t\telse this.resolveDirectInput(inputId, false);\n\t\t\t\t},\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Remaining wait on a pending async ask-user question, or `undefined` when no\n\t * question is live. A deadline already in the past means the question outlived\n\t * its first idle window - the extension restarts that timer whenever the user\n\t * interacts - so the goal parks for one more window instead of falling back to\n\t * the periodic backstop. Clamped through the shared monitor bounds so a\n\t * misconfigured `askUser.timeoutMinutes` cannot park the goal past the\n\t * monitor's own ceiling.\n\t */\n\t#askUserWaitMs(): number | undefined {\n\t\tif ((this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0) <= 0) return undefined;\n\t\tconst remainingMs = (this.#askUserDeadlineAtMs ?? 0) - Date.now();\n\t\tconst waitMs = remainingMs > 0 ? remainingMs : this.#askUserIdleTimeoutMs();\n\t\treturn resolveGoalMonitorContinuationDelayMs(waitMs / 1000);\n\t}\n\n\t#askUserIdleTimeoutMs(): number {\n\t\tconst minutes = this.#ctx?.getAskUserSettings?.().timeoutMinutes;\n\t\tconst resolved =\n\t\t\ttypeof minutes === \"number\" && Number.isFinite(minutes) && minutes > 0\n\t\t\t\t? minutes\n\t\t\t\t: ASK_USER_DEFAULT_TIMEOUT_MINUTES;\n\t\treturn resolved * 60_000;\n\t}\n\n\t/**\n\t * Tracks when the pending question's idle timeout expires. A higher count is a\n\t * newly asked question, which restarts the window; dropping to zero clears it\n\t * so the next schedule uses the periodic backstop again.\n\t */\n\t#noteAskUserWait(activeCount: number): void {\n\t\tif (activeCount <= 0) {\n\t\t\tthis.#askUserDeadlineAtMs = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst previousCount = this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0;\n\t\tif (activeCount > previousCount || this.#askUserDeadlineAtMs === undefined) {\n\t\t\tthis.#askUserDeadlineAtMs = Date.now() + this.#askUserIdleTimeoutMs();\n\t\t}\n\t}\n\n\t#clearWakeSources(): void {\n\t\tthis.#wakeSources.clear();\n\t\tthis.#askUserDeadlineAtMs = undefined;\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tif (source === ASK_USER_WAKE_SOURCE) this.#noteAskUserWait(activeCount);\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":"AAGA,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,4BAA4B,EAC5B,2CAA2C,EAI3C,qCAAqC,GACrC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAE7E,OAAO,EACN,sCAAsC,EACtC,2CAA2C,GAC3C,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACN,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EAGxB,2BAA2B,EAC3B,iBAAiB,EACjB,sBAAsB,EACtB,sBAAsB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EACN,6BA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";\nimport type { ExtensionAPI, ExtensionContext } from \"../../types.ts\";\nimport type { WakeSourceStateItem } from \"../monitor-state-event.ts\";\nimport {\n\tcreateGoalCacheWarmScheduleData,\n\testimateCacheWarmMetrics,\n\tGOAL_CACHE_WARMUP_ENTRY_TYPE,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n\ttype GoalCacheWarmMetrics,\n\ttype GoalCacheWarmupEntryData,\n\ttype LiveGoalCacheWarmupEntryData,\n\tresolveGoalMonitorContinuationDelayMs,\n} from \"./cache-warm.ts\";\nimport { subscribeGoalChannelState } from \"./channel-state-subscriptions.ts\";\n\nexport {\n\tGOAL_MONITOR_BACKSTOP_DEFAULT_DELAY_MS,\n\tGOAL_MONITOR_CONTINUATION_FALLBACK_DELAY_MS,\n} from \"./cache-warm.ts\";\n\nimport {\n\tcontinuationTurnUsedTools,\n\tevaluateGoalContinuation,\n\tGOAL_USER_GRACE_DELAY_MS,\n\ttype GoalContinuationInput,\n\ttype GoalContinuationPath,\n\thasGoalContinuationProgress,\n\thashAssistantText,\n\tisMalformedToolUseTurn,\n\tnormalizeAssistantText,\n} from \"./continuation.ts\";\nimport { lastAssistantMessage } from \"./last-assistant-message.ts\";\nimport {\n\tadmitAndQueueGoalContinuation,\n\tbuildCurrentGoalContinuationSignature,\n\tisLastTurnStuckOnContextOverflow,\n\tlastAssistantText,\n} from \"./lifecycle-helpers.ts\";\nimport type {\n\tAgentEndOptions,\n\tContinuingGoalContinuationVerdict,\n\tDelayedContinuationKind,\n\tGoalContinuationAdmission,\n\tProviderRecoveryOptions,\n\tResumptionChannelCounts,\n\tSystemAbortOptions,\n} from \"./monitor-continuation-types.ts\";\nimport { buildContinuationPrompt, buildGoalStallNotice, buildTruncationRecoveryPrompt } from \"./prompt.ts\";\nimport { isStaleExtensionContextError } from \"./stale-context.ts\";\nimport { resetContinuationStreak } from \"./store.ts\";\nimport { goalStoreRef } from \"./store-ref.ts\";\nimport { collectAssistantUsage } from \"./turn-usage.ts\";\nimport type { Goal, TokenUsageSnapshot } from \"./types.ts\";\nimport type { GoalWaitTicker } from \"./wait-ticker.ts\";\n\n/** Wake source the ask-user extension publishes while an async question is pending. */\nconst ASK_USER_WAKE_SOURCE = \"ask-user\";\n/** `askUser.timeoutMinutes` default (settings-manager.ts), used when the session exposes no ask-user settings. */\nconst ASK_USER_DEFAULT_TIMEOUT_MINUTES = 30;\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#askUserDeadlineAtMs: 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.#clearWakeSources();\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.#clearWakeSources();\n\t\tthis.#lastAgentEndMessages = [];\n\t\tthis.#directInputHolds.clear();\n\t\tthis.#resetContinuationState();\n\t}\n\n\t#schedule(goal: Goal, kind: DelayedContinuationKind, repark = false): void {\n\t\tif (this.#scheduledContinuationKind !== undefined) return;\n\t\t// A live wake source arms the periodic backstop only: the normal resumption\n\t\t// is the drain fire in #setWakeSourceCount, and the backstop re-checks the\n\t\t// goal every `promptCache.goalBackstopMaxSeconds` in case the source never\n\t\t// delivers. A pending ask-user question is the exception: re-prompting the\n\t\t// model every backstop while the user is deciding is noise it cannot act\n\t\t// on, so the wait is parked on the question's own deadline instead.\n\t\tconst askUserWaitMs = kind === \"monitor\" ? this.#askUserWaitMs() : undefined;\n\t\tconst delayMs =\n\t\t\tkind === \"monitor\"\n\t\t\t\t? (askUserWaitMs ??\n\t\t\t\t\tresolveGoalMonitorContinuationDelayMs(this.#ctx?.getPromptCacheGoalBackstopMaxSeconds?.()))\n\t\t\t\t: GOAL_USER_GRACE_DELAY_MS;\n\t\tthis.#scheduledDelayMs = delayMs;\n\t\tif (kind === \"monitor\") {\n\t\t\tif (!repark) this.#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\t// Progress adjusts this wait; it is not another cache-warm iteration\n\t\t\t// or transcript entry for every keystroke in the answer composer.\n\t\t\tif (!repark)\n\t\t\t\tthis.#appendWarmupEntry({\n\t\t\t\t\tphase: \"scheduled\",\n\t\t\t\t\t...scheduleData,\n\t\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\tlastTurnWasMalformedToolUse: lastAssistant?.role === \"assistant\" && isMalformedToolUseTurn(lastAssistant),\n\t\t\tconsecutiveContinuations: goal.consecutiveContinuations ?? 0,\n\t\t\tlastContinuationSignature: goal.lastContinuationSignature,\n\t\t\tcurrentSignature: buildCurrentGoalContinuationSignature(ctx, goal, lastAssistantText(messages)),\n\t\t\tconsecutiveLengthRecoveries: this.#consecutiveLengthRecoveries.get(goal.id) ?? 0,\n\t\t\trecentNormalizedOutputHashes: this.#recentNormalizedOutputHashes,\n\t\t\ttoollessContinuationStreak: this.#toollessContinuationStreak,\n\t\t\tcontinuationPending: this.#isContinuationPending(),\n\t\t\tlastTurnStuckOnContextOverflow: isLastTurnStuckOnContextOverflow(ctx, lastAssistant),\n\t\t};\n\t}\n\n\t#buildContinuationContent(ctx: ExtensionContext, goal: Goal, verdict: ContinuingGoalContinuationVerdict): string {\n\t\tlet content = verdict.prompt === \"minimal\" ? buildTruncationRecoveryPrompt() : buildContinuationPrompt(goal);\n\t\tif (!verdict.stallNotice) return content;\n\n\t\tconst liveSources = this.#liveWakeSources();\n\t\tthis.#pi.events?.emit(GOAL_MONITOR_STALL_EVENT, {\n\t\t\tgoalId: goal.id,\n\t\t\tconsecutiveContinuations: this.#toollessContinuationStreak,\n\t\t\ttoolless: true,\n\t\t});\n\t\tif (this.#ctxHasUI(ctx)) {\n\t\t\tconst context =\n\t\t\t\tliveSources.length > 0 ? `while ${liveSources.join(\", \")} channels stayed active` : \"without tool use\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal continuation repeated ${this.#toollessContinuationStreak} toolless turns ${context} - injected a stall check.`,\n\t\t\t\t\"info\",\n\t\t\t);\n\t\t}\n\t\tcontent = `${buildGoalStallNotice(this.#toollessContinuationStreak, { liveSources })}\\n\\n${content}`;\n\t\treturn content;\n\t}\n\n\t/** A tool-using turn is forward progress, so it clears the repetition window instead of extending it. */\n\t#recordAssistantOutput(messages: readonly AgentMessage[], turnUsedTools: boolean): void {\n\t\tif (turnUsedTools) {\n\t\t\tthis.#recentNormalizedOutputHashes = [];\n\t\t\treturn;\n\t\t}\n\t\tconst text = lastAssistantText(messages);\n\t\tif (normalizeAssistantText(text).length === 0) return;\n\t\tthis.#recentNormalizedOutputHashes = [...this.#recentNormalizedOutputHashes, hashAssistantText(text)].slice(-3);\n\t}\n\n\t#recordToollessContinuationTurn(goal: Goal, turnUsedTools: boolean): void {\n\t\tif (goal.id !== this.#toollessStreakGoalId) {\n\t\t\tthis.#toollessStreakGoalId = goal.id;\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t}\n\t\tif (this.#endedTurnWasUserInitiated) return;\n\t\tif (turnUsedTools) {\n\t\t\tthis.#toollessContinuationStreak = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.#toollessContinuationStreak += 1;\n\t}\n\n\t#resetLengthRecoveryAfterCleanStop(goal: Goal | null, messages: readonly AgentMessage[]): void {\n\t\tif (goal === null || lastAssistantMessage(messages)?.stopReason !== \"stop\") return;\n\t\tthis.#consecutiveLengthRecoveries.delete(goal.id);\n\t}\n\n\t#subscribeToChannelState(): void {\n\t\tconst events = this.#pi.events;\n\t\tif (events === undefined) return;\n\t\tthis.#channelStateUnsubscribers.push(\n\t\t\t...subscribeGoalChannelState(events, {\n\t\t\t\tonWakeSource: (source, activeCount, event) => this.#setWakeSourceCount(source, activeCount, event?.items),\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/**\n\t * Remaining wait on a pending async ask-user question, or `undefined` when no\n\t * question is live. A deadline already in the past means the question outlived\n\t * its first idle window - the extension restarts that timer whenever the user\n\t * interacts - so the goal parks for one more window instead of falling back to\n\t * the periodic backstop. Clamped through the shared monitor bounds so a\n\t * misconfigured `askUser.timeoutMinutes` cannot park the goal past the\n\t * monitor's own ceiling.\n\t */\n\t#askUserWaitMs(): number | undefined {\n\t\tif ((this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0) <= 0) return undefined;\n\t\tconst remainingMs = (this.#askUserDeadlineAtMs ?? 0) - Date.now();\n\t\tconst waitMs = remainingMs > 0 ? remainingMs : this.#askUserIdleTimeoutMs();\n\t\treturn resolveGoalMonitorContinuationDelayMs(waitMs / 1000);\n\t}\n\n\t#askUserIdleTimeoutMs(): number {\n\t\tconst minutes = this.#ctx?.getAskUserSettings?.().timeoutMinutes;\n\t\tconst resolved =\n\t\t\ttypeof minutes === \"number\" && Number.isFinite(minutes) && minutes > 0\n\t\t\t\t? minutes\n\t\t\t\t: ASK_USER_DEFAULT_TIMEOUT_MINUTES;\n\t\treturn resolved * 60_000;\n\t}\n\n\t/**\n\t * Prefer the earliest authoritative request deadline. Legacy count-only\n\t * emitters retain the settings-window heuristic; zero clears the deadline.\n\t */\n\t#noteAskUserWait(activeCount: number, items?: readonly WakeSourceStateItem[]): void {\n\t\tif (activeCount <= 0) {\n\t\t\tthis.#askUserDeadlineAtMs = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst deadlines = items?.flatMap((item) => (item.deadlineAtMs === undefined ? [] : [item.deadlineAtMs])) ?? [];\n\t\tif (deadlines.length > 0) {\n\t\t\tthis.#askUserDeadlineAtMs = Math.min(...deadlines);\n\t\t\treturn;\n\t\t}\n\t\tconst previousCount = this.#wakeSources.get(ASK_USER_WAKE_SOURCE) ?? 0;\n\t\tif (activeCount > previousCount || this.#askUserDeadlineAtMs === undefined) {\n\t\t\tthis.#askUserDeadlineAtMs = Date.now() + this.#askUserIdleTimeoutMs();\n\t\t}\n\t}\n\n\t#clearWakeSources(): void {\n\t\tthis.#wakeSources.clear();\n\t\tthis.#askUserDeadlineAtMs = undefined;\n\t}\n\n\t#setWakeSourceCount(source: string, activeCount: number, items?: readonly WakeSourceStateItem[]): void {\n\t\tconst previousTotal = this.#activeWakeSourceCount();\n\t\tconst previousDeadline = this.#askUserDeadlineAtMs;\n\t\tif (source === ASK_USER_WAKE_SOURCE) this.#noteAskUserWait(activeCount, items);\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\tif (previousDeadline !== this.#askUserDeadlineAtMs && this.#goal !== null) {\n\t\t\t\tthis.#cancelTimer();\n\t\t\t\tthis.#schedule(this.#goal, \"monitor\", true);\n\t\t\t\treturn;\n\t\t\t}\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"]}
|
|
@@ -16,4 +16,6 @@ export type HookConfigLoaderOptions = {
|
|
|
16
16
|
readonly runtimeHookSourcePaths?: readonly string[];
|
|
17
17
|
};
|
|
18
18
|
export declare function loadHookConfigSources(options: HookConfigLoaderOptions): ParsedHookConfig;
|
|
19
|
+
/** Read files asynchronously, retaining the synchronous parser's source order and diagnostics. */
|
|
20
|
+
export declare function loadHookConfigSourcesAsync(options: Omit<HookConfigLoaderOptions, "fileSystem">): Promise<ParsedHookConfig>;
|
|
19
21
|
//# sourceMappingURL=config-loader.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/config-loader.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/config-loader.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAsC,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEvF,MAAM,MAAM,oBAAoB,GAAG;IAClC,QAAQ,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CAC5D,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG;IACrC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,oBAAoB,CAAC;IAC1C,QAAQ,CAAC,mBAAmB,CAAC,EAAE,OAAO,CAAC;IACvC,QAAQ,CAAC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IACxC,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACpD,QAAQ,CAAC,yBAAyB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvD,QAAQ,CAAC,sBAAsB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACpD,CAAC;AAsBF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,uBAAuB,GAAG,gBAAgB,CAyBxF;AAED,kGAAkG;AAClG,wBAAsB,0BAA0B,CAC/C,OAAO,EAAE,IAAI,CAAC,uBAAuB,EAAE,YAAY,CAAC,GAClD,OAAO,CAAC,gBAAgB,CAAC,CAuB3B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
1
2
|
import { diagnostic } from "./diagnostics.js";
|
|
2
3
|
import { parseHookConfig } from "./schema.js";
|
|
3
4
|
export function loadHookConfigSources(options) {
|
|
@@ -24,6 +25,32 @@ export function loadHookConfigSources(options) {
|
|
|
24
25
|
}
|
|
25
26
|
return { executableHandlers, diagnostics };
|
|
26
27
|
}
|
|
28
|
+
/** Read files asynchronously, retaining the synchronous parser's source order and diagnostics. */
|
|
29
|
+
export async function loadHookConfigSourcesAsync(options) {
|
|
30
|
+
const files = new Map();
|
|
31
|
+
const candidates = createSourceCandidates(options);
|
|
32
|
+
await Promise.all(candidates.map(async (candidate) => {
|
|
33
|
+
if (candidate.kind !== "file")
|
|
34
|
+
return;
|
|
35
|
+
try {
|
|
36
|
+
files.set(candidate.sourcePath, { text: await readFile(candidate.sourcePath, "utf8") });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
files.set(candidate.sourcePath, error.code === "ENOENT" ? {} : { error });
|
|
40
|
+
}
|
|
41
|
+
}));
|
|
42
|
+
return loadHookConfigSources({
|
|
43
|
+
...options,
|
|
44
|
+
fileSystem: {
|
|
45
|
+
readTextFile(path) {
|
|
46
|
+
const file = files.get(path);
|
|
47
|
+
if (file?.error !== undefined)
|
|
48
|
+
throw file.error;
|
|
49
|
+
return file?.text;
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
}
|
|
27
54
|
function createSourceCandidates(options) {
|
|
28
55
|
const candidates = [];
|
|
29
56
|
if (options.globalSettingsHooks !== undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAyC9C,MAAM,UAAU,qBAAqB,CAAC,OAAgC;IACrE,MAAM,kBAAkB,GAAqD,EAAE,CAAC;IAChF,MAAM,WAAW,GAAqB,EAAE,CAAC;IACzC,IAAI,YAAY,GAAG,CAAC,CAAC;IAErB,KAAK,MAAM,SAAS,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,MAAM,MAAM,GAAuB;YAClC,YAAY,EAAE,SAAS,CAAC,YAAY;YACpC,YAAY;YACZ,KAAK,EAAE,SAAS,CAAC,KAAK;YACtB,UAAU,EAAE,SAAS,CAAC,UAAU;SAChC,CAAC;QACF,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,SAAS;QACV,CAAC;QACD,YAAY,IAAI,CAAC,CAAC;QAClB,kBAAkB,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,kBAAkB,CAAC,CAAC;QACtD,WAAW,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;QACxC,IAAI,MAAM,CAAC,YAAY,KAAK,SAAS,EAAE,CAAC;YACvC,WAAW,CAAC,IAAI,CAAC,GAAG,8BAA8B,CAAC,MAAM,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC,CAA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;SACnB,EACD,MAAM,CACN;KACD,CAAC;AACH,CAAC","sourcesContent":["import { diagnostic } from \"./diagnostics.ts\";\nimport { parseHookConfig } from \"./schema.ts\";\nimport type { HookDiagnostic, HookSourceMetadata, ParsedHookConfig } from \"./types.ts\";\n\nexport type HookConfigFileSystem = {\n\treadonly readTextFile: (path: string) => string | undefined;\n};\n\nexport type HookConfigLoaderOptions = {\n\treadonly cwd: string;\n\treadonly agentDir: string;\n\treadonly fileSystem: HookConfigFileSystem;\n\treadonly globalSettingsHooks?: unknown;\n\treadonly projectSettingsHooks?: unknown;\n\treadonly globalHooksPath?: string;\n\treadonly projectHooksPath?: string;\n\treadonly globalHookSourcePaths?: readonly string[];\n\treadonly projectHookSourcePaths?: readonly string[];\n\treadonly preSessionHookSourcePaths?: readonly string[];\n\treadonly runtimeHookSourcePaths?: readonly string[];\n};\n\ntype SourceScope = HookSourceMetadata[\"scope\"];\ntype SourceTiming = HookSourceMetadata[\"discoveredAt\"];\n\ntype InlineSource = {\n\treadonly kind: \"inline\";\n\treadonly hooks: unknown;\n\treadonly scope: SourceScope;\n\treadonly sourcePath: string;\n\treadonly discoveredAt: SourceTiming;\n};\n\ntype FileSource = {\n\treadonly kind: \"file\";\n\treadonly scope: SourceScope;\n\treadonly sourcePath: string;\n\treadonly discoveredAt: SourceTiming;\n};\n\ntype SourceCandidate = InlineSource | FileSource;\n\nexport function loadHookConfigSources(options: HookConfigLoaderOptions): ParsedHookConfig {\n\tconst executableHandlers: ParsedHookConfig[\"executableHandlers\"][number][] = [];\n\tconst diagnostics: HookDiagnostic[] = [];\n\tlet displayOrder = 0;\n\n\tfor (const candidate of createSourceCandidates(options)) {\n\t\tconst source: HookSourceMetadata = {\n\t\t\tdiscoveredAt: candidate.discoveredAt,\n\t\t\tdisplayOrder,\n\t\t\tscope: candidate.scope,\n\t\t\tsourcePath: candidate.sourcePath,\n\t\t};\n\t\tconst loaded = loadCandidate(candidate, source, options.fileSystem);\n\t\tif (!loaded) {\n\t\t\tcontinue;\n\t\t}\n\t\tdisplayOrder += 1;\n\t\texecutableHandlers.push(...loaded.executableHandlers);\n\t\tdiagnostics.push(...loaded.diagnostics);\n\t\tif (source.discoveredAt === \"runtime\") {\n\t\t\tdiagnostics.push(...runtimeSessionStartDiagnostics(loaded.executableHandlers, source));\n\t\t}\n\t}\n\n\treturn { executableHandlers, diagnostics };\n}\n\nfunction createSourceCandidates(options: HookConfigLoaderOptions): SourceCandidate[] {\n\tconst candidates: SourceCandidate[] = [];\n\tif (options.globalSettingsHooks !== undefined) {\n\t\tcandidates.push({\n\t\t\tdiscoveredAt: \"pre-session\",\n\t\t\thooks: options.globalSettingsHooks,\n\t\t\tkind: \"inline\",\n\t\t\tscope: \"global\",\n\t\t\tsourcePath: \"<global-settings-hooks>\",\n\t\t});\n\t}\n\tcandidates.push(fileSource(\"global\", options.globalHooksPath ?? `${options.agentDir}/hooks.json`, \"pre-session\"));\n\tcandidates.push(...fileSources(\"global\", options.globalHookSourcePaths, \"pre-session\"));\n\tif (options.projectSettingsHooks !== undefined) {\n\t\tcandidates.push({\n\t\t\tdiscoveredAt: \"pre-session\",\n\t\t\thooks: options.projectSettingsHooks,\n\t\t\tkind: \"inline\",\n\t\t\tscope: \"project\",\n\t\t\tsourcePath: \"<project-settings-hooks>\",\n\t\t});\n\t}\n\tcandidates.push(\n\t\tfileSource(\"project\", options.projectHooksPath ?? `${options.cwd}/.senpi/hooks.json`, \"pre-session\"),\n\t);\n\tcandidates.push(...fileSources(\"project\", options.projectHookSourcePaths, \"pre-session\"));\n\tcandidates.push(...fileSources(\"plugin\", options.preSessionHookSourcePaths, \"pre-session\"));\n\tcandidates.push(...fileSources(\"runtime\", options.runtimeHookSourcePaths, \"runtime\"));\n\treturn candidates;\n}\n\nfunction fileSources(\n\tscope: SourceScope,\n\tpaths: readonly string[] | undefined,\n\tdiscoveredAt: SourceTiming,\n): SourceCandidate[] {\n\tif (!paths) {\n\t\treturn [];\n\t}\n\treturn paths.map((path) => fileSource(scope, path, discoveredAt));\n}\n\nfunction fileSource(scope: SourceScope, sourcePath: string, discoveredAt: SourceTiming): FileSource {\n\treturn { discoveredAt, kind: \"file\", scope, sourcePath };\n}\n\nfunction loadCandidate(\n\tcandidate: SourceCandidate,\n\tsource: HookSourceMetadata,\n\tfileSystem: HookConfigFileSystem,\n): ParsedHookConfig | undefined {\n\tif (candidate.kind === \"inline\") {\n\t\treturn parseHookConfig({ hooks: candidate.hooks }, source);\n\t}\n\n\tconst text = readSourceText(candidate.sourcePath, source, fileSystem);\n\tif (text === undefined) {\n\t\treturn undefined;\n\t}\n\tif (typeof text !== \"string\") {\n\t\treturn text;\n\t}\n\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(text);\n\t\treturn parseHookConfig(parsed, source);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown JSON parse failure.\";\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_root\",\n\t\t\t\t\t\tmessage: `Hook source JSON is malformed: ${message}`,\n\t\t\t\t\t\tpath: \"$\",\n\t\t\t\t\t},\n\t\t\t\t\tsource,\n\t\t\t\t),\n\t\t\t],\n\t\t\texecutableHandlers: [],\n\t\t};\n\t}\n}\n\nfunction readSourceText(\n\tsourcePath: string,\n\tsource: HookSourceMetadata,\n\tfileSystem: HookConfigFileSystem,\n): string | undefined | ParsedHookConfig {\n\ttry {\n\t\treturn fileSystem.readTextFile(sourcePath);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown file read failure.\";\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_root\",\n\t\t\t\t\t\tmessage: `Hook source could not be read: ${message}`,\n\t\t\t\t\t\tpath: \"$\",\n\t\t\t\t\t},\n\t\t\t\t\tsource,\n\t\t\t\t),\n\t\t\t],\n\t\t\texecutableHandlers: [],\n\t\t};\n\t}\n}\n\nfunction runtimeSessionStartDiagnostics(\n\thandlers: ParsedHookConfig[\"executableHandlers\"],\n\tsource: HookSourceMetadata,\n): HookDiagnostic[] {\n\tif (!handlers.some((handler) => handler.event === \"SessionStart\")) {\n\t\treturn [];\n\t}\n\treturn [\n\t\tdiagnostic(\n\t\t\t{\n\t\t\t\tcode: \"unsupported_event\",\n\t\t\t\tevent: \"SessionStart\",\n\t\t\t\tmessage: \"Runtime SessionStart hooks are loaded for reload or the next session only.\",\n\t\t\t\tpath: \"hooks.SessionStart\",\n\t\t\t\tseverity: \"warning\",\n\t\t\t},\n\t\t\tsource,\n\t\t),\n\t];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAyC9C,MAAM,UAAU,qBAAqB,CAAC,OAAgC;IACrE,MAAM,kBAAkB,GAAqD,EAAE,CAAC;IAChF,MAAM,WAAW,GAAqB,EAAE,CAAC;IACzC,IAAI,YAAY,GAAG,CAAC,CAAC;IAErB,KAAK,MAAM,SAAS,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,MAAM,MAAM,GAAuB;YAClC,YAAY,EAAE,SAAS,CAAC,YAAY;YACpC,YAAY;YACZ,KAAK,EAAE,SAAS,CAAC,KAAK;YACtB,UAAU,EAAE,SAAS,CAAC,UAAU;SAChC,CAAC;QACF,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,SAAS;QACV,CAAC;QACD,YAAY,IAAI,CAAC,CA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B,KAAK,EAAE,cAAc;YACrB,OAAO,EAAE,4EAA4E;YACrF,IAAI,EAAE,oBAAoB;YAC1B,QAAQ,EAAE,SAAS;SACnB,EACD,MAAM,CACN;KACD,CAAC;AACH,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { diagnostic } from \"./diagnostics.ts\";\nimport { parseHookConfig } from \"./schema.ts\";\nimport type { HookDiagnostic, HookSourceMetadata, ParsedHookConfig } from \"./types.ts\";\n\nexport type HookConfigFileSystem = {\n\treadonly readTextFile: (path: string) => string | undefined;\n};\n\nexport type HookConfigLoaderOptions = {\n\treadonly cwd: string;\n\treadonly agentDir: string;\n\treadonly fileSystem: HookConfigFileSystem;\n\treadonly globalSettingsHooks?: unknown;\n\treadonly projectSettingsHooks?: unknown;\n\treadonly globalHooksPath?: string;\n\treadonly projectHooksPath?: string;\n\treadonly globalHookSourcePaths?: readonly string[];\n\treadonly projectHookSourcePaths?: readonly string[];\n\treadonly preSessionHookSourcePaths?: readonly string[];\n\treadonly runtimeHookSourcePaths?: readonly string[];\n};\n\ntype SourceScope = HookSourceMetadata[\"scope\"];\ntype SourceTiming = HookSourceMetadata[\"discoveredAt\"];\n\ntype InlineSource = {\n\treadonly kind: \"inline\";\n\treadonly hooks: unknown;\n\treadonly scope: SourceScope;\n\treadonly sourcePath: string;\n\treadonly discoveredAt: SourceTiming;\n};\n\ntype FileSource = {\n\treadonly kind: \"file\";\n\treadonly scope: SourceScope;\n\treadonly sourcePath: string;\n\treadonly discoveredAt: SourceTiming;\n};\n\ntype SourceCandidate = InlineSource | FileSource;\n\nexport function loadHookConfigSources(options: HookConfigLoaderOptions): ParsedHookConfig {\n\tconst executableHandlers: ParsedHookConfig[\"executableHandlers\"][number][] = [];\n\tconst diagnostics: HookDiagnostic[] = [];\n\tlet displayOrder = 0;\n\n\tfor (const candidate of createSourceCandidates(options)) {\n\t\tconst source: HookSourceMetadata = {\n\t\t\tdiscoveredAt: candidate.discoveredAt,\n\t\t\tdisplayOrder,\n\t\t\tscope: candidate.scope,\n\t\t\tsourcePath: candidate.sourcePath,\n\t\t};\n\t\tconst loaded = loadCandidate(candidate, source, options.fileSystem);\n\t\tif (!loaded) {\n\t\t\tcontinue;\n\t\t}\n\t\tdisplayOrder += 1;\n\t\texecutableHandlers.push(...loaded.executableHandlers);\n\t\tdiagnostics.push(...loaded.diagnostics);\n\t\tif (source.discoveredAt === \"runtime\") {\n\t\t\tdiagnostics.push(...runtimeSessionStartDiagnostics(loaded.executableHandlers, source));\n\t\t}\n\t}\n\n\treturn { executableHandlers, diagnostics };\n}\n\n/** Read files asynchronously, retaining the synchronous parser's source order and diagnostics. */\nexport async function loadHookConfigSourcesAsync(\n\toptions: Omit<HookConfigLoaderOptions, \"fileSystem\">,\n): Promise<ParsedHookConfig> {\n\tconst files = new Map<string, { text?: string; error?: unknown }>();\n\tconst candidates = createSourceCandidates(options);\n\tawait Promise.all(\n\t\tcandidates.map(async (candidate) => {\n\t\t\tif (candidate.kind !== \"file\") return;\n\t\t\ttry {\n\t\t\t\tfiles.set(candidate.sourcePath, { text: await readFile(candidate.sourcePath, \"utf8\") });\n\t\t\t} catch (error) {\n\t\t\t\tfiles.set(candidate.sourcePath, (error as NodeJS.ErrnoException).code === \"ENOENT\" ? {} : { error });\n\t\t\t}\n\t\t}),\n\t);\n\treturn loadHookConfigSources({\n\t\t...options,\n\t\tfileSystem: {\n\t\t\treadTextFile(path) {\n\t\t\t\tconst file = files.get(path);\n\t\t\t\tif (file?.error !== undefined) throw file.error;\n\t\t\t\treturn file?.text;\n\t\t\t},\n\t\t},\n\t});\n}\n\nfunction createSourceCandidates(options: Omit<HookConfigLoaderOptions, \"fileSystem\">): SourceCandidate[] {\n\tconst candidates: SourceCandidate[] = [];\n\tif (options.globalSettingsHooks !== undefined) {\n\t\tcandidates.push({\n\t\t\tdiscoveredAt: \"pre-session\",\n\t\t\thooks: options.globalSettingsHooks,\n\t\t\tkind: \"inline\",\n\t\t\tscope: \"global\",\n\t\t\tsourcePath: \"<global-settings-hooks>\",\n\t\t});\n\t}\n\tcandidates.push(fileSource(\"global\", options.globalHooksPath ?? `${options.agentDir}/hooks.json`, \"pre-session\"));\n\tcandidates.push(...fileSources(\"global\", options.globalHookSourcePaths, \"pre-session\"));\n\tif (options.projectSettingsHooks !== undefined) {\n\t\tcandidates.push({\n\t\t\tdiscoveredAt: \"pre-session\",\n\t\t\thooks: options.projectSettingsHooks,\n\t\t\tkind: \"inline\",\n\t\t\tscope: \"project\",\n\t\t\tsourcePath: \"<project-settings-hooks>\",\n\t\t});\n\t}\n\tcandidates.push(\n\t\tfileSource(\"project\", options.projectHooksPath ?? `${options.cwd}/.senpi/hooks.json`, \"pre-session\"),\n\t);\n\tcandidates.push(...fileSources(\"project\", options.projectHookSourcePaths, \"pre-session\"));\n\tcandidates.push(...fileSources(\"plugin\", options.preSessionHookSourcePaths, \"pre-session\"));\n\tcandidates.push(...fileSources(\"runtime\", options.runtimeHookSourcePaths, \"runtime\"));\n\treturn candidates;\n}\n\nfunction fileSources(\n\tscope: SourceScope,\n\tpaths: readonly string[] | undefined,\n\tdiscoveredAt: SourceTiming,\n): SourceCandidate[] {\n\tif (!paths) {\n\t\treturn [];\n\t}\n\treturn paths.map((path) => fileSource(scope, path, discoveredAt));\n}\n\nfunction fileSource(scope: SourceScope, sourcePath: string, discoveredAt: SourceTiming): FileSource {\n\treturn { discoveredAt, kind: \"file\", scope, sourcePath };\n}\n\nfunction loadCandidate(\n\tcandidate: SourceCandidate,\n\tsource: HookSourceMetadata,\n\tfileSystem: HookConfigFileSystem,\n): ParsedHookConfig | undefined {\n\tif (candidate.kind === \"inline\") {\n\t\treturn parseHookConfig({ hooks: candidate.hooks }, source);\n\t}\n\n\tconst text = readSourceText(candidate.sourcePath, source, fileSystem);\n\tif (text === undefined) {\n\t\treturn undefined;\n\t}\n\tif (typeof text !== \"string\") {\n\t\treturn text;\n\t}\n\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(text);\n\t\treturn parseHookConfig(parsed, source);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown JSON parse failure.\";\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_root\",\n\t\t\t\t\t\tmessage: `Hook source JSON is malformed: ${message}`,\n\t\t\t\t\t\tpath: \"$\",\n\t\t\t\t\t},\n\t\t\t\t\tsource,\n\t\t\t\t),\n\t\t\t],\n\t\t\texecutableHandlers: [],\n\t\t};\n\t}\n}\n\nfunction readSourceText(\n\tsourcePath: string,\n\tsource: HookSourceMetadata,\n\tfileSystem: HookConfigFileSystem,\n): string | undefined | ParsedHookConfig {\n\ttry {\n\t\treturn fileSystem.readTextFile(sourcePath);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"Unknown file read failure.\";\n\t\treturn {\n\t\t\tdiagnostics: [\n\t\t\t\tdiagnostic(\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: \"invalid_root\",\n\t\t\t\t\t\tmessage: `Hook source could not be read: ${message}`,\n\t\t\t\t\t\tpath: \"$\",\n\t\t\t\t\t},\n\t\t\t\t\tsource,\n\t\t\t\t),\n\t\t\t],\n\t\t\texecutableHandlers: [],\n\t\t};\n\t}\n}\n\nfunction runtimeSessionStartDiagnostics(\n\thandlers: ParsedHookConfig[\"executableHandlers\"],\n\tsource: HookSourceMetadata,\n): HookDiagnostic[] {\n\tif (!handlers.some((handler) => handler.event === \"SessionStart\")) {\n\t\treturn [];\n\t}\n\treturn [\n\t\tdiagnostic(\n\t\t\t{\n\t\t\t\tcode: \"unsupported_event\",\n\t\t\t\tevent: \"SessionStart\",\n\t\t\t\tmessage: \"Runtime SessionStart hooks are loaded for reload or the next session only.\",\n\t\t\t\tpath: \"hooks.SessionStart\",\n\t\t\t\tseverity: \"warning\",\n\t\t\t},\n\t\t\tsource,\n\t\t),\n\t];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{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IAAI,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IACjG,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AACzB,CAAC;AAED,SAAS,mBAAmB,CAAC,OAA4B;IACxD,OAAO,OAAO,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,QAAQ,KAAK,MAAM,CAAC;AAClF,CAAC;AAED,SAAS,kBAAkB,CAC1B,IAAuB,EACvB,OAA4B,EAC5B,MAA0B,EAC1B,YAAsB;IAEtB,OAAO;QACN,IAAI;QACJ,GAAG,WAAW,CAAC,MAAM,CAAC;QACtB,MAAM,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM;QAC9B,aAAa,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO;QAC7C,GAAG,iBAAiB,CAAC,YAAY,CAAC;KAClC,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAAC,MAA0B;IAC9C,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QAC1B,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,CAAC;AACnB,CAAC;AAED,SAAS,iBAAiB,CAAC,YAAqB;IAC/C,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,EAAE,YAAY,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { stripAnsi } from \"../../../../utils/ansi.ts\";\nimport { type CommandHookRunOptions, type CommandHookRunResult, runCommandHook } from \"./command-runner.ts\";\nimport { matchingHookHandlers } from \"./matcher.ts\";\nimport { type ParsedHookOutput, parseHookOutput } from \"./output-parser.ts\";\nimport { type HookOutputPolicy, validateHookHandlerSafety } from \"./safety.ts\";\nimport { type HookTrustOptions, type HookTrustRecord, listHookTrustRecords } from \"./trust.ts\";\nimport type {\n\tExecutableHookHandler,\n\tHookDiagnostic,\n\tHookInputWire,\n\tHookSourceMetadata,\n\tHookTrustState,\n} from \"./types.ts\";\n\nexport type HookCommandRunner = (\n\thandler: ExecutableHookHandler,\n\tinput: HookInputWire,\n\toptions: CommandHookRunOptions,\n) => Promise<CommandHookRunResult>;\n\nexport type HookDispatchDecision =\n\t| { readonly kind: \"none\" }\n\t| {\n\t\t\treadonly kind: \"allow\" | \"block\";\n\t\t\treadonly reason?: string;\n\t\t\treadonly source: HookSourceMetadata;\n\t\t\treadonly sourceCommand: string;\n\t\t\treadonly updatedInput?: unknown;\n\t }\n\t| {\n\t\t\treadonly fallback: { readonly kind: \"block\"; readonly reason: string };\n\t\t\treadonly kind: \"ask\";\n\t\t\treadonly nativeRepresentable: false;\n\t\t\treadonly reason?: string;\n\t\t\treadonly source: HookSourceMetadata;\n\t\t\treadonly sourceCommand: string;\n\t };\n\nexport type HookDispatchSkipped = {\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly handler: ExecutableHookHandler;\n\treadonly reason: \"disabled\" | \"untrusted\" | \"unsafe\";\n\treadonly record: HookTrustRecord;\n};\n\nexport type HookDispatchSummary = {\n\treadonly completionIndex: number;\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly handler: ExecutableHookHandler;\n\treadonly output: ParsedHookOutput[\"output\"];\n\treadonly run: CommandHookRunResult;\n};\n\nexport type HookDispatchResult = {\n\treadonly decision: HookDispatchDecision;\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly executableHandlers: readonly ExecutableHookHandler[];\n\treadonly matchedHandlers: readonly ExecutableHookHandler[];\n\treadonly skipped: readonly HookDispatchSkipped[];\n\treadonly summaries: readonly HookDispatchSummary[];\n};\n\nexport type HookDispatchOptions = {\n\treadonly cwd: string;\n\treadonly envPassthrough?: readonly string[];\n\treadonly handlers: readonly ExecutableHookHandler[];\n\treadonly input: HookInputWire;\n\treadonly onRunningHandlersChange?: (running: readonly ExecutableHookHandler[]) => void;\n\treadonly outputPolicy?: HookOutputPolicy;\n\treadonly runCommand?: HookCommandRunner;\n\treadonly signal?: AbortSignal;\n\treadonly sourceEnv?: NodeJS.ProcessEnv;\n\treadonly trustOptions?: HookTrustOptions;\n\treadonly trustState: HookTrustState;\n};\n\ntype OrderedHandler = {\n\treadonly declarationIndex: number;\n\treadonly handler: ExecutableHookHandler;\n};\n\ntype RunnableHandler = OrderedHandler & {\n\treadonly record: HookTrustRecord;\n};\n\nexport async function dispatchHookEvent(options: HookDispatchOptions): Promise<HookDispatchResult> {\n\tconst match = matchingHookHandlers(options.input, options.handlers);\n\tconst ordered = declarationOrdered(match.handlers);\n\tconst selected = selectExecutableHandlers(ordered, options.trustState, options.trustOptions);\n\tlet nextCompletionIndex = 0;\n\tconst runner = options.runCommand ?? runCommandHook;\n\tconst notifyRunningChange = options.onRunningHandlersChange;\n\tconst runningHandlers: ExecutableHookHandler[] = [];\n\tconst completed = await Promise.all(\n\t\tselected.runnable.map(async ({ handler, declarationIndex }) => {\n\t\t\tif (notifyRunningChange !== undefined) {\n\t\t\t\trunningHandlers.push(handler);\n\t\t\t\tnotifyRunningChange([...runningHandlers]);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst run = await runner(handler, options.input, {\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\t...(options.envPassthrough === undefined ? {} : { envPassthrough: options.envPassthrough }),\n\t\t\t\t\t...(options.outputPolicy === undefined ? {} : { outputPolicy: options.outputPolicy }),\n\t\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t\t...(options.sourceEnv === undefined ? {} : { sourceEnv: options.sourceEnv }),\n\t\t\t\t});\n\t\t\t\tconst parsed = parseHookOutput({\n\t\t\t\t\tevent: options.input.event,\n\t\t\t\t\texitCode: run.exitCode ?? 1,\n\t\t\t\t\tsource: handler.source,\n\t\t\t\t\tstderr: run.stderr,\n\t\t\t\t\tstdout: run.stdout,\n\t\t\t\t});\n\t\t\t\tconst completionIndex = nextCompletionIndex;\n\t\t\t\tnextCompletionIndex += 1;\n\t\t\t\treturn { completionIndex, declarationIndex, handler, parsed, run };\n\t\t\t} finally {\n\t\t\t\tif (notifyRunningChange !== undefined) {\n\t\t\t\t\tconst runningIndex = runningHandlers.indexOf(handler);\n\t\t\t\t\tif (runningIndex !== -1) {\n\t\t\t\t\t\trunningHandlers.splice(runningIndex, 1);\n\t\t\t\t\t}\n\t\t\t\t\tnotifyRunningChange([...runningHandlers]);\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t);\n\tconst declarationSummaries = completed\n\t\t.toSorted((left, right) => left.declarationIndex - right.declarationIndex)\n\t\t.map((run) => ({\n\t\t\tcompletionIndex: run.completionIndex,\n\t\t\tdiagnostics: run.parsed.diagnostics,\n\t\t\thandler: run.handler,\n\t\t\toutput: run.parsed.output,\n\t\t\trun: run.run,\n\t\t}));\n\tconst diagnostics = [\n\t\t...match.diagnostics,\n\t\t...selected.skipped.flatMap((skip) => skip.diagnostics),\n\t\t...declarationSummaries.flatMap((summary) => summary.diagnostics),\n\t];\n\treturn {\n\t\tdecision: aggregateDecision(options.input.event, declarationSummaries),\n\t\tdiagnostics,\n\t\texecutableHandlers: selected.runnable.map((item) => item.handler),\n\t\tmatchedHandlers: ordered.map((item) => item.handler),\n\t\tskipped: selected.skipped,\n\t\tsummaries: declarationSummaries,\n\t};\n}\n\nexport function runningHookHandlersStatusLabel(\n\thandlers: readonly ExecutableHookHandler[],\n\tplatform: NodeJS.Platform = process.platform,\n): string {\n\tconst label = handlers.map((handler) => hookHandlerStatusLabel(handler, platform)).join(\" · \");\n\treturn label.length <= 79 ? label : `${label.slice(0, 76)}...`;\n}\n\nfunction hookHandlerStatusLabel(handler: ExecutableHookHandler, platform: NodeJS.Platform): string {\n\tconst raw =\n\t\thandler.config.statusMessage ??\n\t\t(platform === \"win32\" && handler.config.commandWindows !== undefined\n\t\t\t? handler.config.commandWindows\n\t\t\t: handler.config.command);\n\treturn stripAnsi(raw)\n\t\t.replace(/[\\r\\n\\t]+/g, \" \")\n\t\t.replace(/[\\u0000-\\u001f\\u007f]+/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction declarationOrdered(handlers: readonly ExecutableHookHandler[]): readonly OrderedHandler[] {\n\treturn handlers\n\t\t.map((handler, index) => ({ declarationIndex: index, handler }))\n\t\t.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tcompareHandlers(left.handler, right.handler) || left.declarationIndex - right.declarationIndex,\n\t\t);\n}\n\nfunction compareHandlers(left: ExecutableHookHandler, right: ExecutableHookHandler): number {\n\treturn (\n\t\tleft.source.displayOrder - right.source.displayOrder ||\n\t\tleft.groupIndex - right.groupIndex ||\n\t\tleft.handlerIndex - right.handlerIndex\n\t);\n}\n\nfunction selectExecutableHandlers(\n\thandlers: readonly OrderedHandler[],\n\ttrustState: HookTrustState,\n\ttrustOptions: HookTrustOptions | undefined,\n): { readonly runnable: readonly RunnableHandler[]; readonly skipped: readonly HookDispatchSkipped[] } {\n\tconst records = listHookTrustRecords(\n\t\thandlers.map((item) => item.handler),\n\t\ttrustState,\n\t\ttrustOptions,\n\t);\n\tconst runnable: RunnableHandler[] = [];\n\tconst skipped: HookDispatchSkipped[] = [];\n\tfor (const [index, item] of handlers.entries()) {\n\t\tconst record = records[index];\n\t\tif (record === undefined) continue;\n\t\tconst safetyDiagnostics = validateHookHandlerSafety(item.handler);\n\t\tconst unsafe = safetyDiagnostics.some((diagnostic) => diagnostic.severity === \"error\");\n\t\tif (unsafe) {\n\t\t\tskipped.push({ diagnostics: safetyDiagnostics, handler: item.handler, reason: \"unsafe\", record });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!record.enabled) {\n\t\t\tskipped.push({ diagnostics: [], handler: item.handler, reason: \"disabled\", record });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!record.trusted) {\n\t\t\tskipped.push({ diagnostics: [], handler: item.handler, reason: \"untrusted\", record });\n\t\t\tcontinue;\n\t\t}\n\t\trunnable.push({ ...item, record });\n\t}\n\treturn { runnable, skipped };\n}\n\nfunction aggregateDecision(\n\tevent: HookInputWire[\"event\"],\n\tsummaries: readonly HookDispatchSummary[],\n): HookDispatchDecision {\n\tswitch (event) {\n\t\tcase \"PreToolUse\":\n\t\t\treturn aggregatePreToolUseDecision(summaries);\n\t\tcase \"PostToolUse\":\n\t\tcase \"UserPromptSubmit\":\n\t\tcase \"SessionStart\":\n\t\tcase \"PreCompact\":\n\t\tcase \"PostCompact\":\n\t\tcase \"Stop\":\n\t\t\treturn aggregateBlockingDecision(summaries);\n\t}\n}\n\nfunction aggregatePreToolUseDecision(summaries: readonly HookDispatchSummary[]): HookDispatchDecision {\n\tconst blocker = summaries.find(hasBlockingDecision);\n\tif (blocker !== undefined) {\n\t\treturn decisionWithSource(\"block\", blocker, blocker.output.reason);\n\t}\n\tconst ask = summaries.find((summary) => summary.output.decision === \"ask\");\n\tif (ask !== undefined) {\n\t\tconst reason = ask.output.reason ?? \"Hook requested manual approval.\";\n\t\treturn {\n\t\t\tfallback: { kind: \"block\", reason },\n\t\t\tkind: \"ask\",\n\t\t\tnativeRepresentable: false,\n\t\t\t...reasonField(ask.output.reason),\n\t\t\tsource: ask.handler.source,\n\t\t\tsourceCommand: ask.handler.config.command,\n\t\t};\n\t}\n\tlet allowSummary: HookDispatchSummary | undefined;\n\tfor (const summary of summaries) {\n\t\tif (summary.output.decision === \"allow\" || summary.output.decision === \"approve\") allowSummary = summary;\n\t}\n\tif (allowSummary !== undefined) {\n\t\treturn decisionWithSource(\"allow\", allowSummary, undefined, allowSummary.output.updatedInput);\n\t}\n\treturn { kind: \"none\" };\n}\n\nfunction aggregateBlockingDecision(summaries: readonly HookDispatchSummary[]): HookDispatchDecision {\n\tconst blocker = summaries.find(hasBlockingDecision);\n\tif (blocker !== undefined) {\n\t\treturn decisionWithSource(\"block\", blocker, blocker.output.reason ?? blocker.output.stopReason);\n\t}\n\treturn { kind: \"none\" };\n}\n\nfunction hasBlockingDecision(summary: HookDispatchSummary): boolean {\n\treturn summary.output.decision === \"block\" || summary.output.decision === \"deny\";\n}\n\nfunction decisionWithSource(\n\tkind: \"allow\" | \"block\",\n\tsummary: HookDispatchSummary,\n\treason: string | undefined,\n\tupdatedInput?: unknown,\n): HookDispatchDecision {\n\treturn {\n\t\tkind,\n\t\t...reasonField(reason),\n\t\tsource: summary.handler.source,\n\t\tsourceCommand: summary.handler.config.command,\n\t\t...updatedInputField(updatedInput),\n\t};\n}\n\nfunction reasonField(reason: string | undefined): { readonly reason?: string } {\n\tif (reason === undefined) {\n\t\treturn {};\n\t}\n\treturn { reason };\n}\n\nfunction updatedInputField(updatedInput: unknown): { readonly updatedInput?: unknown } {\n\tif (updatedInput === undefined) {\n\t\treturn {};\n\t}\n\treturn { updatedInput };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dispatcher.js","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAyD,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAyB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAyB,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAC/E,OAAO,EAA+C,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAgF/F,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,OAA4B;IACnE,MAAM,KAAK,GAAG,oBAAoB,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpE,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACnD,MAAM,QAAQ,GAAG,wBAAwB,CAAC,OAAO,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;IAC7F,IAAI,mBAAmB,GAAG,CAAC,CAAC;IAC5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ED,SAAS,iBAAiB,CAAC,YAAqB;IAC/C,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,EAAE,YAAY,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { stripAnsi } from \"../../../../utils/ansi.ts\";\nimport { type CommandHookRunOptions, type CommandHookRunResult, runCommandHook } from \"./command-runner.ts\";\nimport { matchingHookHandlers } from \"./matcher.ts\";\nimport { type ParsedHookOutput, parseHookOutput } from \"./output-parser.ts\";\nimport { type HookOutputPolicy, validateHookHandlerSafety } from \"./safety.ts\";\nimport { type HookTrustOptions, type HookTrustRecord, listHookTrustRecords } from \"./trust.ts\";\nimport type {\n\tExecutableHookHandler,\n\tHookDiagnostic,\n\tHookInputWire,\n\tHookSourceMetadata,\n\tHookTrustState,\n} from \"./types.ts\";\n\nexport type HookCommandRunner = (\n\thandler: ExecutableHookHandler,\n\tinput: HookInputWire,\n\toptions: CommandHookRunOptions,\n) => Promise<CommandHookRunResult>;\n\nexport type HookDispatchDecision =\n\t| { readonly kind: \"none\" }\n\t| {\n\t\t\treadonly kind: \"allow\" | \"block\";\n\t\t\treadonly reason?: string;\n\t\t\treadonly source: HookSourceMetadata;\n\t\t\treadonly sourceCommand: string;\n\t\t\treadonly updatedInput?: unknown;\n\t }\n\t| {\n\t\t\treadonly fallback: { readonly kind: \"block\"; readonly reason: string };\n\t\t\treadonly kind: \"ask\";\n\t\t\treadonly nativeRepresentable: false;\n\t\t\treadonly reason?: string;\n\t\t\treadonly source: HookSourceMetadata;\n\t\t\treadonly sourceCommand: string;\n\t };\n\nexport type HookDispatchSkipped = {\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly handler: ExecutableHookHandler;\n\treadonly reason: \"disabled\" | \"untrusted\" | \"unsafe\";\n\treadonly record: HookTrustRecord;\n};\n\nexport type HookDispatchSummary = {\n\treadonly completionIndex: number;\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly handler: ExecutableHookHandler;\n\treadonly output: ParsedHookOutput[\"output\"];\n\treadonly run: CommandHookRunResult;\n};\n\nexport type HookDispatchResult = {\n\treadonly decision: HookDispatchDecision;\n\treadonly diagnostics: readonly HookDiagnostic[];\n\treadonly executableHandlers: readonly ExecutableHookHandler[];\n\treadonly matchedHandlers: readonly ExecutableHookHandler[];\n\treadonly skipped: readonly HookDispatchSkipped[];\n\treadonly summaries: readonly HookDispatchSummary[];\n};\n\nexport type HookDispatchOptions = {\n\treadonly cwd: string;\n\treadonly envPassthrough?: readonly string[];\n\treadonly handlers: readonly ExecutableHookHandler[];\n\treadonly input: HookInputWire;\n\treadonly onRunningHandlersChange?: (running: readonly ExecutableHookHandler[]) => void;\n\treadonly outputPolicy?: HookOutputPolicy;\n\treadonly runCommand?: HookCommandRunner;\n\treadonly signal?: AbortSignal;\n\treadonly sourceEnv?: NodeJS.ProcessEnv;\n\treadonly trustOptions?: HookTrustOptions;\n\treadonly trustState: HookTrustState;\n};\n\ntype OrderedHandler = {\n\treadonly declarationIndex: number;\n\treadonly handler: ExecutableHookHandler;\n};\n\ntype RunnableHandler = OrderedHandler & {\n\treadonly record: HookTrustRecord;\n};\n\nexport async function dispatchHookEvent(options: HookDispatchOptions): Promise<HookDispatchResult> {\n\tconst match = matchingHookHandlers(options.input, options.handlers);\n\tconst ordered = declarationOrdered(match.handlers);\n\tconst selected = selectExecutableHandlers(ordered, options.trustState, options.trustOptions);\n\tlet nextCompletionIndex = 0;\n\tconst runner = options.runCommand ?? runCommandHook;\n\tconst notifyRunningChange = options.onRunningHandlersChange;\n\tconst runningHandlers: ExecutableHookHandler[] = [];\n\tconst completed = await Promise.all(\n\t\tselected.runnable.map(async ({ handler, declarationIndex }) => {\n\t\t\tif (notifyRunningChange !== undefined) {\n\t\t\t\trunningHandlers.push(handler);\n\t\t\t\tnotifyRunningChange([...runningHandlers]);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst run = await runner(handler, options.input, {\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\t...(options.envPassthrough === undefined ? {} : { envPassthrough: options.envPassthrough }),\n\t\t\t\t\t...(options.outputPolicy === undefined ? {} : { outputPolicy: options.outputPolicy }),\n\t\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t\t...(options.sourceEnv === undefined ? {} : { sourceEnv: options.sourceEnv }),\n\t\t\t\t});\n\t\t\t\tconst parsed = parseHookOutput({\n\t\t\t\t\tevent: options.input.event,\n\t\t\t\t\texitCode: run.exitCode ?? 1,\n\t\t\t\t\tsource: handler.source,\n\t\t\t\t\tstderr: run.stderr,\n\t\t\t\t\tstdout: run.stdout,\n\t\t\t\t});\n\t\t\t\tconst completionIndex = nextCompletionIndex;\n\t\t\t\tnextCompletionIndex += 1;\n\t\t\t\treturn { completionIndex, declarationIndex, handler, parsed, run };\n\t\t\t} finally {\n\t\t\t\tif (notifyRunningChange !== undefined) {\n\t\t\t\t\tconst runningIndex = runningHandlers.indexOf(handler);\n\t\t\t\t\tif (runningIndex !== -1) {\n\t\t\t\t\t\trunningHandlers.splice(runningIndex, 1);\n\t\t\t\t\t}\n\t\t\t\t\tnotifyRunningChange([...runningHandlers]);\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t);\n\tconst declarationSummaries = completed\n\t\t.toSorted((left, right) => left.declarationIndex - right.declarationIndex)\n\t\t.map((run) => ({\n\t\t\tcompletionIndex: run.completionIndex,\n\t\t\tdiagnostics: run.parsed.diagnostics,\n\t\t\thandler: run.handler,\n\t\t\toutput: run.parsed.output,\n\t\t\trun: run.run,\n\t\t}));\n\tconst diagnostics = [\n\t\t...match.diagnostics,\n\t\t...selected.skipped.flatMap((skip) => skip.diagnostics),\n\t\t...declarationSummaries.flatMap((summary) => summary.diagnostics),\n\t];\n\treturn {\n\t\tdecision: aggregateDecision(options.input.event, declarationSummaries),\n\t\tdiagnostics,\n\t\texecutableHandlers: selected.runnable.map((item) => item.handler),\n\t\tmatchedHandlers: ordered.map((item) => item.handler),\n\t\tskipped: selected.skipped,\n\t\tsummaries: declarationSummaries,\n\t};\n}\n\nexport function runningHookHandlersStatusLabel(\n\thandlers: readonly ExecutableHookHandler[],\n\tplatform: NodeJS.Platform = process.platform,\n): string {\n\tconst label = handlers.map((handler) => hookHandlerStatusLabel(handler, platform)).join(\" · \");\n\treturn label.length <= 79 ? label : `${label.slice(0, 76)}...`;\n}\n\nfunction hookHandlerStatusLabel(handler: ExecutableHookHandler, platform: NodeJS.Platform): string {\n\tconst raw =\n\t\thandler.config.statusMessage ??\n\t\t(platform === \"win32\" && handler.config.commandWindows !== undefined\n\t\t\t? handler.config.commandWindows\n\t\t\t: handler.config.command);\n\treturn stripAnsi(raw)\n\t\t.replace(/[\\r\\n\\t]+/g, \" \")\n\t\t.replace(/[\\u0000-\\u001f\\u007f]+/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction declarationOrdered(handlers: readonly ExecutableHookHandler[]): readonly OrderedHandler[] {\n\treturn handlers\n\t\t.map((handler, index) => ({ declarationIndex: index, handler }))\n\t\t.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tcompareHandlers(left.handler, right.handler) || left.declarationIndex - right.declarationIndex,\n\t\t);\n}\n\nfunction compareHandlers(left: ExecutableHookHandler, right: ExecutableHookHandler): number {\n\treturn (\n\t\tleft.source.displayOrder - right.source.displayOrder ||\n\t\tleft.groupIndex - right.groupIndex ||\n\t\tleft.handlerIndex - right.handlerIndex\n\t);\n}\n\nfunction selectExecutableHandlers(\n\thandlers: readonly OrderedHandler[],\n\ttrustState: HookTrustState,\n\ttrustOptions: HookTrustOptions | undefined,\n): { readonly runnable: readonly RunnableHandler[]; readonly skipped: readonly HookDispatchSkipped[] } {\n\tconst records = listHookTrustRecords(\n\t\thandlers.map((item) => item.handler),\n\t\ttrustState,\n\t\ttrustOptions,\n\t);\n\tconst runnable: RunnableHandler[] = [];\n\tconst skipped: HookDispatchSkipped[] = [];\n\tfor (const [index, item] of handlers.entries()) {\n\t\tconst record = records[index];\n\t\tif (record === undefined) continue;\n\t\tconst safetyDiagnostics = validateHookHandlerSafety(item.handler);\n\t\tconst unsafe = safetyDiagnostics.some((diagnostic) => diagnostic.severity === \"error\");\n\t\tif (unsafe) {\n\t\t\tskipped.push({ diagnostics: safetyDiagnostics, handler: item.handler, reason: \"unsafe\", record });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!record.enabled) {\n\t\t\tskipped.push({ diagnostics: [], handler: item.handler, reason: \"disabled\", record });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!record.trusted) {\n\t\t\tskipped.push({ diagnostics: [], handler: item.handler, reason: \"untrusted\", record });\n\t\t\tcontinue;\n\t\t}\n\t\trunnable.push({ ...item, record });\n\t}\n\treturn { runnable, skipped };\n}\n\nfunction aggregateDecision(\n\tevent: HookInputWire[\"event\"],\n\tsummaries: readonly HookDispatchSummary[],\n): HookDispatchDecision {\n\tswitch (event) {\n\t\tcase \"PreToolUse\":\n\t\t\treturn aggregatePreToolUseDecision(summaries);\n\t\tcase \"PostToolUse\":\n\t\tcase \"UserPromptSubmit\":\n\t\tcase \"SessionStart\":\n\t\tcase \"PreCompact\":\n\t\tcase \"PostCompact\":\n\t\tcase \"Stop\":\n\t\tcase \"Notification\":\n\t\t\treturn aggregateBlockingDecision(summaries);\n\t}\n}\n\nfunction aggregatePreToolUseDecision(summaries: readonly HookDispatchSummary[]): HookDispatchDecision {\n\tconst blocker = summaries.find(hasBlockingDecision);\n\tif (blocker !== undefined) {\n\t\treturn decisionWithSource(\"block\", blocker, blocker.output.reason);\n\t}\n\tconst ask = summaries.find((summary) => summary.output.decision === \"ask\");\n\tif (ask !== undefined) {\n\t\tconst reason = ask.output.reason ?? \"Hook requested manual approval.\";\n\t\treturn {\n\t\t\tfallback: { kind: \"block\", reason },\n\t\t\tkind: \"ask\",\n\t\t\tnativeRepresentable: false,\n\t\t\t...reasonField(ask.output.reason),\n\t\t\tsource: ask.handler.source,\n\t\t\tsourceCommand: ask.handler.config.command,\n\t\t};\n\t}\n\tlet allowSummary: HookDispatchSummary | undefined;\n\tfor (const summary of summaries) {\n\t\tif (summary.output.decision === \"allow\" || summary.output.decision === \"approve\") allowSummary = summary;\n\t}\n\tif (allowSummary !== undefined) {\n\t\treturn decisionWithSource(\"allow\", allowSummary, undefined, allowSummary.output.updatedInput);\n\t}\n\treturn { kind: \"none\" };\n}\n\nfunction aggregateBlockingDecision(summaries: readonly HookDispatchSummary[]): HookDispatchDecision {\n\tconst blocker = summaries.find(hasBlockingDecision);\n\tif (blocker !== undefined) {\n\t\treturn decisionWithSource(\"block\", blocker, blocker.output.reason ?? blocker.output.stopReason);\n\t}\n\treturn { kind: \"none\" };\n}\n\nfunction hasBlockingDecision(summary: HookDispatchSummary): boolean {\n\treturn summary.output.decision === \"block\" || summary.output.decision === \"deny\";\n}\n\nfunction decisionWithSource(\n\tkind: \"allow\" | \"block\",\n\tsummary: HookDispatchSummary,\n\treason: string | undefined,\n\tupdatedInput?: unknown,\n): HookDispatchDecision {\n\treturn {\n\t\tkind,\n\t\t...reasonField(reason),\n\t\tsource: summary.handler.source,\n\t\tsourceCommand: summary.handler.config.command,\n\t\t...updatedInputField(updatedInput),\n\t};\n}\n\nfunction reasonField(reason: string | undefined): { readonly reason?: string } {\n\tif (reason === undefined) {\n\t\treturn {};\n\t}\n\treturn { reason };\n}\n\nfunction updatedInputField(updatedInput: unknown): { readonly updatedInput?: unknown } {\n\tif (updatedInput === undefined) {\n\t\treturn {};\n\t}\n\treturn { updatedInput };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAA+B,YAAY,EAAuC,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/core/extensions/builtin/hooks/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAA+B,YAAY,EAAuC,MAAM,gBAAgB,CAAC;AA+CrH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACX,iBAAiB,EACjB,qBAAqB,EACrB,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,yBAAyB,GACzB,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAqQ7D;AAmBD,OAAO,EACN,qBAAqB,EACrB,yBAAyB,EACzB,6BAA6B,GAC7B,MAAM,YAAY,CAAC"}
|