@bastani/atomic 0.9.12 → 0.9.13-alpha.1
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 +20 -0
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/README.md +5 -12
- package/dist/builtin/intercom/broker/client.ts +11 -2
- package/dist/builtin/intercom/contact-supervisor-tool.ts +13 -3
- package/dist/builtin/intercom/index-heavy.ts +13 -3
- package/dist/builtin/intercom/index.ts +43 -19
- package/dist/builtin/intercom/intercom-utils.ts +15 -29
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/source-ownership.ts +9 -12
- package/dist/builtin/mcp/CHANGELOG.md +6 -0
- package/dist/builtin/mcp/README.md +3 -1
- package/dist/builtin/mcp/index.ts +10 -16
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/startup-warmup.ts +20 -8
- package/dist/builtin/subagents/CHANGELOG.md +30 -0
- package/dist/builtin/subagents/README.md +22 -30
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/doctor.ts +1 -1
- package/dist/builtin/subagents/src/extension/fanout-child.ts +76 -56
- package/dist/builtin/subagents/src/extension/index.ts +23 -32
- package/dist/builtin/subagents/src/extension/startup-maintenance.ts +25 -44
- package/dist/builtin/subagents/src/intercom/result-intercom.ts +7 -7
- package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +166 -434
- package/dist/builtin/subagents/src/runs/background/notify.ts +29 -8
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-dynamic-step.ts +2 -2
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-runner.ts +4 -4
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-parallel-step.ts +2 -2
- package/dist/builtin/subagents/src/runs/foreground/chain-execution-sequential-step.ts +2 -2
- package/dist/builtin/subagents/src/runs/foreground/execution-run-sync.ts +1 -281
- package/dist/builtin/subagents/src/runs/foreground/execution-structured-retries.ts +11 -75
- package/dist/builtin/subagents/src/runs/foreground/inprocess-run-sync.ts +457 -0
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-async.ts +119 -246
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-chain.ts +1 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-context.ts +18 -9
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel-task.ts +1 -1
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-parallel.ts +4 -4
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-resume.ts +1 -646
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-runtime.ts +2 -7
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-single.ts +5 -5
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-status.ts +7 -8
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor-types.ts +14 -5
- package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +158 -93
- package/dist/builtin/subagents/src/runs/inprocess/background-single.ts +179 -0
- package/dist/builtin/subagents/src/runs/inprocess/background.ts +89 -0
- package/dist/builtin/subagents/src/runs/inprocess/child-policy.ts +27 -0
- package/dist/builtin/subagents/src/runs/inprocess/control-registry.ts +55 -0
- package/dist/builtin/subagents/src/runs/inprocess/control-status.ts +106 -0
- package/dist/builtin/subagents/src/runs/inprocess/index.ts +50 -0
- package/dist/builtin/subagents/src/runs/inprocess/nested-routing.ts +218 -0
- package/dist/builtin/subagents/src/runs/{shared/subagent-prompt-runtime.ts → inprocess/prompt-behavior.ts} +37 -75
- package/dist/builtin/subagents/src/runs/inprocess/runner.ts +1138 -0
- package/dist/builtin/subagents/src/runs/{shared/nested-events.ts → inprocess/runtime-support/nested-api.ts} +13 -7
- package/dist/builtin/subagents/src/runs/{shared/nested-events-control.ts → inprocess/runtime-support/nested-control.ts} +18 -17
- package/dist/builtin/subagents/src/runs/{shared/nested-events-core.ts → inprocess/runtime-support/nested-core.ts} +14 -61
- package/dist/builtin/subagents/src/runs/{shared/nested-events-projection.ts → inprocess/runtime-support/nested-projection.ts} +4 -10
- package/dist/builtin/subagents/src/runs/{shared/nested-events-registry.ts → inprocess/runtime-support/nested-registry.ts} +19 -4
- package/dist/builtin/subagents/src/runs/{shared/nested-render.ts → inprocess/runtime-support/nested-rendering.ts} +3 -3
- package/dist/builtin/subagents/src/runs/{shared/nested-events-sanitize.ts → inprocess/runtime-support/nested-sanitize.ts} +3 -3
- package/dist/builtin/subagents/src/runs/inprocess.ts +1 -0
- package/dist/builtin/subagents/src/runs/shared/dynamic-fanout.ts +10 -4
- package/dist/builtin/subagents/src/runs/shared/model-candidate-filter.ts +0 -1
- package/dist/builtin/subagents/src/runs/shared/model-fallback.ts +15 -492
- package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +13 -11
- package/dist/builtin/subagents/src/runs/shared/run-history.ts +3 -5
- package/dist/builtin/subagents/src/runs/shared/single-output.ts +4 -4
- package/dist/builtin/subagents/src/runs/shared/workflow-graph.ts +5 -5
- package/dist/builtin/subagents/src/shared/types-async.ts +0 -1
- package/dist/builtin/subagents/src/shared/types-config.ts +18 -0
- package/dist/builtin/subagents/src/shared/types-results.ts +9 -2
- package/dist/builtin/subagents/src/slash/prompt-template-bridge.ts +2 -3
- package/dist/builtin/subagents/src/slash/slash-live-state.ts +2 -2
- package/dist/builtin/subagents/src/tui/render-chain-graph.ts +10 -4
- package/dist/builtin/subagents/src/tui/render-event-formatting.ts +12 -11
- package/dist/builtin/subagents/src/tui/render-result-compact.ts +49 -12
- package/dist/builtin/subagents/src/tui/render-result.ts +46 -17
- package/dist/builtin/subagents/src/tui/render-stable-output.ts +1 -1
- package/dist/builtin/subagents/src/tui/render-status-progress.ts +8 -5
- package/dist/builtin/subagents/src/tui/render-widget-graph.ts +0 -8
- package/dist/builtin/subagents/src/tui/render-widget.ts +0 -24
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +25 -0
- package/dist/builtin/workflows/README.md +13 -3
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/durable/backend.ts +7 -0
- package/dist/builtin/workflows/src/durable/dbos-metadata.ts +11 -1
- package/dist/builtin/workflows/src/durable/resume-runtime.ts +1 -0
- package/dist/builtin/workflows/src/durable/tool-primitive.ts +4 -28
- package/dist/builtin/workflows/src/durable/types.ts +5 -0
- package/dist/builtin/workflows/src/engine/run.ts +17 -1
- package/dist/builtin/workflows/src/extension/atomic-stage-session.ts +12 -39
- package/dist/builtin/workflows/src/extension/config-file-loader.ts +10 -1
- package/dist/builtin/workflows/src/extension/config-loader.ts +1 -1
- package/dist/builtin/workflows/src/extension/dispatcher.ts +4 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +1151 -737
- package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +303 -38
- package/dist/builtin/workflows/src/extension/render-result.ts +4 -0
- package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +6 -3
- package/dist/builtin/workflows/src/extension/runtime.ts +7 -1
- package/dist/builtin/workflows/src/extension/wiring.ts +53 -11
- package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +12 -3
- package/dist/builtin/workflows/src/extension/workflow-durable-resume-command.ts +5 -2
- package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +9 -7
- package/dist/builtin/workflows/src/extension/workflow-status-summary.ts +11 -0
- package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +18 -1
- package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +10 -8
- package/dist/builtin/workflows/src/extension/workflow-tool.ts +9 -4
- package/dist/builtin/workflows/src/runs/background/quit.ts +28 -4
- package/dist/builtin/workflows/src/runs/background/resume-acknowledgements.ts +2 -1
- package/dist/builtin/workflows/src/runs/background/status.ts +55 -8
- package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +4 -0
- package/dist/builtin/workflows/src/runs/foreground/executor-prompt-nodes.ts +3 -1
- package/dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +1 -1
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +688 -38
- package/dist/builtin/workflows/src/runs/foreground/stage-runner-types.ts +3 -1
- package/dist/builtin/workflows/src/runs/shared/model-fallback-failures.ts +19 -514
- package/dist/builtin/workflows/src/runs/shared/retry.ts +44 -0
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +5 -0
- package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +6 -0
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +5 -1
- package/dist/builtin/workflows/src/shared/authoring-contract-ui.ts +5 -0
- package/dist/builtin/workflows/src/shared/persistence-restore-helpers.ts +5 -0
- package/dist/builtin/workflows/src/shared/persistence-restore.ts +3 -0
- package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +4 -0
- package/dist/builtin/workflows/src/shared/run-indicator-status.ts +75 -0
- package/dist/builtin/workflows/src/shared/store-public-types.ts +43 -7
- package/dist/builtin/workflows/src/shared/store-run-methods.ts +42 -8
- package/dist/builtin/workflows/src/shared/store-stage-methods.ts +31 -8
- package/dist/builtin/workflows/src/shared/store-types.ts +34 -0
- package/dist/builtin/workflows/src/shared/timing.ts +10 -0
- package/dist/builtin/workflows/src/tui/chat-surface-message.ts +22 -2
- package/dist/builtin/workflows/src/tui/session-list.ts +1 -1
- package/dist/builtin/workflows/src/tui/session-overlays.ts +14 -10
- package/dist/builtin/workflows/src/tui/session-picker.ts +20 -4
- package/dist/builtin/workflows/src/tui/status-list.ts +31 -47
- package/dist/builtin/workflows/src/tui/store-widget-installer.ts +9 -1
- package/dist/builtin/workflows/src/tui/widget.ts +16 -46
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +54 -11
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +49 -14
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +13 -0
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js +12 -1
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +4 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts +21 -4
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +232 -106
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js +2 -1
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
- package/dist/core/agent-session-tool-hooks.js +12 -0
- package/dist/core/agent-session-tool-hooks.js.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.js +1 -1
- package/dist/core/agent-session-tool-registry.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +3 -1
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/context-types.d.ts +25 -0
- package/dist/core/extensions/context-types.d.ts.map +1 -1
- package/dist/core/extensions/context-types.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/runner-context.d.ts +2 -1
- package/dist/core/extensions/runner-context.d.ts.map +1 -1
- package/dist/core/extensions/runner-context.js +4 -0
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +3 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/model-fallback-failures.d.ts +30 -0
- package/dist/core/model-fallback-failures.d.ts.map +1 -0
- package/dist/core/model-fallback-failures.js +610 -0
- package/dist/core/model-fallback-failures.js.map +1 -0
- package/dist/core/retry-policy.d.ts +30 -0
- package/dist/core/retry-policy.d.ts.map +1 -0
- package/dist/core/retry-policy.js +25 -0
- package/dist/core/retry-policy.js.map +1 -0
- package/dist/core/sdk-types.d.ts +8 -2
- package/dist/core/sdk-types.d.ts.map +1 -1
- package/dist/core/sdk-types.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +6 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-core.d.ts +2 -0
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +7 -0
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/docs/intercom.md +5 -10
- package/docs/settings.md +7 -1
- package/docs/subagents.md +19 -19
- package/docs/workflows.md +21 -5
- package/examples/extensions/gondolin/package-lock.json +3 -3
- package/npm-shrinkwrap.json +29 -29
- package/package.json +2 -2
- package/dist/builtin/subagents/src/runs/background/async-event-journal.ts +0 -112
- package/dist/builtin/subagents/src/runs/background/async-execution-chain.ts +0 -543
- package/dist/builtin/subagents/src/runs/background/async-execution-common.ts +0 -140
- package/dist/builtin/subagents/src/runs/background/async-execution-single.ts +0 -279
- package/dist/builtin/subagents/src/runs/background/async-execution-types.ts +0 -99
- package/dist/builtin/subagents/src/runs/background/async-execution.ts +0 -17
- package/dist/builtin/subagents/src/runs/background/async-resume.ts +0 -402
- package/dist/builtin/subagents/src/runs/background/async-status.ts +0 -411
- package/dist/builtin/subagents/src/runs/background/completion-claims.ts +0 -196
- package/dist/builtin/subagents/src/runs/background/completion-dedupe.ts +0 -102
- package/dist/builtin/subagents/src/runs/background/parallel-groups.ts +0 -59
- package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +0 -300
- package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +0 -166
- package/dist/builtin/subagents/src/runs/background/result-quarantine.ts +0 -77
- package/dist/builtin/subagents/src/runs/background/result-retry-scheduler.ts +0 -48
- package/dist/builtin/subagents/src/runs/background/result-status.ts +0 -87
- package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +0 -72
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +0 -320
- package/dist/builtin/subagents/src/runs/background/run-id-resolver.ts +0 -105
- package/dist/builtin/subagents/src/runs/background/run-status.ts +0 -358
- package/dist/builtin/subagents/src/runs/background/stale-run-reconciler.ts +0 -457
- package/dist/builtin/subagents/src/runs/background/subagent-runner-dynamic.ts +0 -376
- package/dist/builtin/subagents/src/runs/background/subagent-runner-finalize.ts +0 -150
- package/dist/builtin/subagents/src/runs/background/subagent-runner-output.ts +0 -109
- package/dist/builtin/subagents/src/runs/background/subagent-runner-parallel-helpers.ts +0 -128
- package/dist/builtin/subagents/src/runs/background/subagent-runner-parallel.ts +0 -309
- package/dist/builtin/subagents/src/runs/background/subagent-runner-sequential.ts +0 -173
- package/dist/builtin/subagents/src/runs/background/subagent-runner-state.ts +0 -578
- package/dist/builtin/subagents/src/runs/background/subagent-runner-step.ts +0 -330
- package/dist/builtin/subagents/src/runs/background/subagent-runner-streaming.ts +0 -330
- package/dist/builtin/subagents/src/runs/background/subagent-runner-types.ts +0 -210
- package/dist/builtin/subagents/src/runs/background/subagent-runner-utils.ts +0 -69
- package/dist/builtin/subagents/src/runs/background/subagent-runner.ts +0 -90
- package/dist/builtin/subagents/src/runs/background/top-level-async.ts +0 -12
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt-control.ts +0 -140
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt-finalize.ts +0 -108
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt-types.ts +0 -17
- package/dist/builtin/subagents/src/runs/foreground/execution-attempt.ts +0 -558
- package/dist/builtin/subagents/src/runs/shared/attempt-watchdog.ts +0 -126
- package/dist/builtin/subagents/src/runs/shared/final-drain.ts +0 -39
- package/dist/builtin/subagents/src/runs/shared/pi-args.ts +0 -339
- package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +0 -165
- package/dist/builtin/subagents/src/runs/shared/spawn-env.ts +0 -21
- package/dist/builtin/subagents/src/shared/post-exit-stdio-guard.ts +0 -86
- /package/dist/builtin/subagents/src/runs/{shared/nested-path.ts → inprocess/runtime-support/nested-paths.ts} +0 -0
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
|
|
21
21
|
import { keyText } from "@bastani/atomic";
|
|
22
22
|
import { isWorkflowRunResumable, type WorkflowRunResumeCandidate } from "../durable/resume-eligibility.js";
|
|
23
|
+
import { runIndicatorStatus } from "../shared/run-indicator-status.js";
|
|
23
24
|
import { isTopLevelWorkflowRun } from "../shared/run-visibility.js";
|
|
24
25
|
import type { RunSnapshot, StoreSnapshot } from "../shared/store-types.js";
|
|
25
26
|
import { elapsedRunMs } from "../shared/timing.js";
|
|
@@ -31,6 +32,10 @@ import { fmtDuration, statusColor, statusIcon } from "./status-helpers.js";
|
|
|
31
32
|
import { Key, matchesKey, truncateToWidth, visibleWidth } from "./text-helpers.js";
|
|
32
33
|
|
|
33
34
|
const ESCAPE_CODE = 0x1b;
|
|
35
|
+
|
|
36
|
+
function isQuitRun(run: RunSnapshot): boolean {
|
|
37
|
+
return run.endedAt === undefined && run.status === "paused" && run.exitReason === "quit";
|
|
38
|
+
}
|
|
34
39
|
const DOUBLE_ESCAPE_SEQUENCE = String.fromCharCode(ESCAPE_CODE, ESCAPE_CODE);
|
|
35
40
|
|
|
36
41
|
// ---------------------------------------------------------------------------
|
|
@@ -146,6 +151,8 @@ export interface SessionPickerRenderOpts {
|
|
|
146
151
|
state: SessionPickerState;
|
|
147
152
|
/** Optional: now override for deterministic tests. */
|
|
148
153
|
now?: number;
|
|
154
|
+
/** Point-in-time/live run collection used to attribute hidden child prompts. */
|
|
155
|
+
allRuns?: readonly RunSnapshot[];
|
|
149
156
|
}
|
|
150
157
|
|
|
151
158
|
/** Pad a visible string (any embedded ANSI is OK; we measure visibly). */
|
|
@@ -257,12 +264,20 @@ function stageProgress(run: RunSnapshot): string {
|
|
|
257
264
|
return `${done}/${total} stages`;
|
|
258
265
|
}
|
|
259
266
|
|
|
260
|
-
function renderRunRow(
|
|
267
|
+
function renderRunRow(
|
|
268
|
+
row: PickerRow,
|
|
269
|
+
isSelected: boolean,
|
|
270
|
+
inner: number,
|
|
271
|
+
theme: GraphTheme,
|
|
272
|
+
now: number,
|
|
273
|
+
allRuns: readonly RunSnapshot[],
|
|
274
|
+
): string[] {
|
|
261
275
|
const border = hexToAnsi(theme.border);
|
|
262
276
|
const panelBg = hexBg(theme.bg);
|
|
263
277
|
const run = row.run;
|
|
264
|
-
const
|
|
265
|
-
const
|
|
278
|
+
const indicatorStatus = isQuitRun(run) ? run.status : runIndicatorStatus(run, allRuns);
|
|
279
|
+
const icon = statusIcon(indicatorStatus);
|
|
280
|
+
const iconColor = hexToAnsi(statusColor(indicatorStatus, theme));
|
|
266
281
|
const dim = hexToAnsi(theme.dim);
|
|
267
282
|
const text = hexToAnsi(theme.text);
|
|
268
283
|
const muted = hexToAnsi(theme.textMuted);
|
|
@@ -349,6 +364,7 @@ export function renderSessionPicker(opts: SessionPickerRenderOpts): string[] {
|
|
|
349
364
|
const visible = rows.slice(Math.max(0, start), Math.max(0, start) + VIEWPORT);
|
|
350
365
|
|
|
351
366
|
let prevBucket: PickerRow["bucket"] | null = null;
|
|
367
|
+
const allRuns = opts.allRuns ?? rows.map(({ run }) => run);
|
|
352
368
|
for (let i = 0; i < visible.length; i++) {
|
|
353
369
|
const row = visible[i]!;
|
|
354
370
|
if (row.bucket !== prevBucket) {
|
|
@@ -356,7 +372,7 @@ export function renderSessionPicker(opts: SessionPickerRenderOpts): string[] {
|
|
|
356
372
|
prevBucket = row.bucket;
|
|
357
373
|
}
|
|
358
374
|
const absIndex = Math.max(0, start) + i;
|
|
359
|
-
lines.push(...renderRunRow(row, absIndex === sel, inner, theme, now));
|
|
375
|
+
lines.push(...renderRunRow(row, absIndex === sel, inner, theme, now, allRuns));
|
|
360
376
|
}
|
|
361
377
|
lines.push(renderBlankRow(inner, theme));
|
|
362
378
|
lines.push(renderBottomBorder(width, theme));
|
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
24
|
import { effectiveRunStatus } from "../shared/returned-run-status.js";
|
|
25
|
+
import type { RunIndicatorStatus } from "../shared/run-indicator-status.js";
|
|
26
|
+
import { runIndicatorStatus } from "../shared/run-indicator-status.js";
|
|
25
27
|
import type { RunSnapshot, StageSnapshot, StageStatus } from "../shared/store-types.js";
|
|
26
28
|
import { elapsedRunMs, elapsedStageMs } from "../shared/timing.js";
|
|
27
29
|
import type { FlatBandBadge } from "./chat-surface.js";
|
|
@@ -29,7 +31,7 @@ import { chatWidth, ELLIPSIS, progressStrip, renderRoundedBox } from "./chat-sur
|
|
|
29
31
|
import { BOLD, hexToAnsi, RESET } from "./color-utils.js";
|
|
30
32
|
import type { GraphTheme } from "./graph-theme.js";
|
|
31
33
|
import { wrapIdentifierLines } from "./run-identity-rows.js";
|
|
32
|
-
import { fmtDuration } from "./status-helpers.js";
|
|
34
|
+
import { fmtDuration, statusColor, statusIcon } from "./status-helpers.js";
|
|
33
35
|
import { truncateToWidth, visibleWidth } from "./text-helpers.js";
|
|
34
36
|
|
|
35
37
|
const STAGE_LABEL_BUDGET = 24;
|
|
@@ -43,6 +45,15 @@ export interface RenderStatusListOpts {
|
|
|
43
45
|
showDetailHint?: boolean;
|
|
44
46
|
/** Render width (cells). Defaults to `process.stdout.columns`. */
|
|
45
47
|
width?: number;
|
|
48
|
+
/** Point-in-time run collection used to attribute hidden child prompts. */
|
|
49
|
+
allRuns?: readonly RunSnapshot[];
|
|
50
|
+
/**
|
|
51
|
+
* Emit-time indicator status per run id, taking precedence over deriving
|
|
52
|
+
* from `allRuns`. Lets persisted payloads (e.g. the `/workflow status`
|
|
53
|
+
* chat entry) keep hidden-descendant prompt attribution after a session
|
|
54
|
+
* restore, when the full run collection is no longer available.
|
|
55
|
+
*/
|
|
56
|
+
indicatorStatuses?: Readonly<Record<string, RunIndicatorStatus>>;
|
|
46
57
|
}
|
|
47
58
|
|
|
48
59
|
function isQuitRun(run: RunSnapshot): boolean {
|
|
@@ -74,7 +85,9 @@ export function renderStatusList(runs: readonly RunSnapshot[], opts: RenderStatu
|
|
|
74
85
|
} else {
|
|
75
86
|
for (let i = 0; i < sorted.length; i++) {
|
|
76
87
|
if (i > 0) body.push("");
|
|
77
|
-
body.push(
|
|
88
|
+
body.push(
|
|
89
|
+
...renderRunEntry(sorted[i]!, now, cardWidth, opts.theme, opts.allRuns ?? runs, opts.indicatorStatuses),
|
|
90
|
+
);
|
|
78
91
|
}
|
|
79
92
|
}
|
|
80
93
|
if (opts.showDetailHint !== false && sorted.length > 0) {
|
|
@@ -94,11 +107,19 @@ export function renderStatusList(runs: readonly RunSnapshot[], opts: RenderStatu
|
|
|
94
107
|
// Run card
|
|
95
108
|
// ---------------------------------------------------------------------------
|
|
96
109
|
|
|
97
|
-
function renderRunEntry(
|
|
110
|
+
function renderRunEntry(
|
|
111
|
+
run: RunSnapshot,
|
|
112
|
+
now: number,
|
|
113
|
+
width: number,
|
|
114
|
+
theme: GraphTheme | undefined,
|
|
115
|
+
allRuns: readonly RunSnapshot[],
|
|
116
|
+
indicatorStatuses?: Readonly<Record<string, RunIndicatorStatus>>,
|
|
117
|
+
): string[] {
|
|
98
118
|
const bodyWidth = effectiveWidth(width);
|
|
99
119
|
const interior = Math.max(8, bodyWidth - 4);
|
|
100
|
-
const
|
|
101
|
-
const
|
|
120
|
+
const indicatorStatus = indicatorStatuses?.[run.id] ?? runIndicatorStatus(run, allRuns);
|
|
121
|
+
const glyph = statusIconForRun(run, indicatorStatus);
|
|
122
|
+
const glyphFg = theme ? hexToAnsi(runAccent(run, theme, indicatorStatus)) : "";
|
|
102
123
|
const accent = theme ? hexToAnsi(theme.accent) : "";
|
|
103
124
|
const text = theme ? hexToAnsi(theme.text) : "";
|
|
104
125
|
const muted = theme ? hexToAnsi(theme.textMuted) : "";
|
|
@@ -141,29 +162,10 @@ function renderRunEntry(run: RunSnapshot, now: number, width: number, theme?: Gr
|
|
|
141
162
|
return [...identityRows, identity, metaLine];
|
|
142
163
|
}
|
|
143
164
|
|
|
144
|
-
function runAccent(run: RunSnapshot, theme
|
|
165
|
+
function runAccent(run: RunSnapshot, theme: GraphTheme | undefined, indicatorStatus: RunIndicatorStatus): string {
|
|
145
166
|
if (!theme) return "#000000";
|
|
146
167
|
if (isQuitRun(run)) return theme.warning;
|
|
147
|
-
|
|
148
|
-
case "completed":
|
|
149
|
-
return theme.success;
|
|
150
|
-
case "running":
|
|
151
|
-
return theme.warning;
|
|
152
|
-
case "paused":
|
|
153
|
-
return theme.warning;
|
|
154
|
-
case "skipped":
|
|
155
|
-
return theme.dim;
|
|
156
|
-
case "cancelled":
|
|
157
|
-
return theme.dim;
|
|
158
|
-
case "blocked":
|
|
159
|
-
return theme.dim;
|
|
160
|
-
case "failed":
|
|
161
|
-
return theme.error;
|
|
162
|
-
case "killed":
|
|
163
|
-
return theme.error;
|
|
164
|
-
default:
|
|
165
|
-
return theme.dim;
|
|
166
|
-
}
|
|
168
|
+
return statusColor(indicatorStatus, theme);
|
|
167
169
|
}
|
|
168
170
|
|
|
169
171
|
function runTrailing(run: RunSnapshot, theme?: GraphTheme): { text: string; fg?: string } | undefined {
|
|
@@ -436,27 +438,9 @@ function emptyStateLine(theme?: GraphTheme): string {
|
|
|
436
438
|
return ` ${hexToAnsi(theme.dim)}no workflow runs in current session${RESET}`;
|
|
437
439
|
}
|
|
438
440
|
|
|
439
|
-
function statusIconForRun(run: RunSnapshot): string {
|
|
440
|
-
if (isQuitRun(run)) return "
|
|
441
|
-
|
|
442
|
-
case "completed":
|
|
443
|
-
return "✓";
|
|
444
|
-
case "skipped":
|
|
445
|
-
case "cancelled":
|
|
446
|
-
return "⊘";
|
|
447
|
-
case "blocked":
|
|
448
|
-
return "↑";
|
|
449
|
-
case "running":
|
|
450
|
-
return "●";
|
|
451
|
-
case "paused":
|
|
452
|
-
return "❚❚";
|
|
453
|
-
case "failed":
|
|
454
|
-
return "✗";
|
|
455
|
-
case "killed":
|
|
456
|
-
return "⊘";
|
|
457
|
-
default:
|
|
458
|
-
return "○";
|
|
459
|
-
}
|
|
441
|
+
function statusIconForRun(run: RunSnapshot, indicatorStatus: RunIndicatorStatus): string {
|
|
442
|
+
if (isQuitRun(run)) return statusIcon("pending");
|
|
443
|
+
return statusIcon(indicatorStatus);
|
|
460
444
|
}
|
|
461
445
|
|
|
462
446
|
// Re-export for callers that need to inspect width budgeting.
|
|
@@ -86,6 +86,14 @@ function isStale(err: unknown): boolean {
|
|
|
86
86
|
return err instanceof Error && err.message.includes(STALE_CONTEXT);
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
function liveWidgetSnapshot(storeInstance: Store): StoreSnapshot {
|
|
90
|
+
return {
|
|
91
|
+
runs: storeInstance.runs(),
|
|
92
|
+
notices: storeInstance.notices(),
|
|
93
|
+
version: 0,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
89
97
|
export function decideWidgetAction(prev: WidgetRenderState, nextLines: readonly string[]): WidgetAction {
|
|
90
98
|
return decideReactiveWidgetAction(prev, nextLines);
|
|
91
99
|
}
|
|
@@ -107,7 +115,7 @@ export function installStoreWidget(
|
|
|
107
115
|
key: WIDGET_KEY,
|
|
108
116
|
placement: "belowEditor",
|
|
109
117
|
timers,
|
|
110
|
-
getSnapshot: () =>
|
|
118
|
+
getSnapshot: () => liveWidgetSnapshot(storeInstance),
|
|
111
119
|
subscribe: (listener) => subscribeStoreInvalidation(storeInstance, listener),
|
|
112
120
|
getPreviewLines: (snap, now) => buildThemedWidgetLines(snap, undefined, 120, now),
|
|
113
121
|
render: (snap, { theme, width, now }) => buildThemedWidgetLines(snap, theme as PiTheme | undefined, width, now),
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
24
|
import { effectiveRunStatus } from "../shared/returned-run-status.js";
|
|
25
|
+
import { runIndicatorStatus } from "../shared/run-indicator-status.js";
|
|
25
26
|
import { topLevelWorkflowRuns } from "../shared/run-visibility.js";
|
|
26
27
|
import type { RunSnapshot, StoreSnapshot } from "../shared/store-types.js";
|
|
27
28
|
import { elapsedRunMs } from "../shared/timing.js";
|
|
@@ -31,7 +32,7 @@ import { hexToAnsi, RESET } from "./color-utils.js";
|
|
|
31
32
|
import type { GraphTheme } from "./graph-theme.js";
|
|
32
33
|
import { deriveGraphTheme } from "./graph-theme.js";
|
|
33
34
|
import { renderRunIdentityRows } from "./run-identity-rows.js";
|
|
34
|
-
import { statusIcon } from "./status-helpers.js";
|
|
35
|
+
import { statusColor, statusIcon } from "./status-helpers.js";
|
|
35
36
|
import type { PiTheme } from "./store-widget-installer.js";
|
|
36
37
|
|
|
37
38
|
// ---------------------------------------------------------------------------
|
|
@@ -96,23 +97,8 @@ interface RunCounts {
|
|
|
96
97
|
awaiting: number;
|
|
97
98
|
}
|
|
98
99
|
|
|
99
|
-
function runAwaitsInput(run: RunSnapshot): boolean {
|
|
100
|
-
return (
|
|
101
|
-
run.endedAt === undefined &&
|
|
102
|
-
(run.pendingPrompt !== undefined || run.stages.some((s) => s.status === "awaiting_input"))
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/**
|
|
107
|
-
* A top-level run "needs attention" when it OR any of its nested
|
|
108
|
-
* `ctx.workflow()` descendants is awaiting human input. Nested child runs are
|
|
109
|
-
* hidden from the widget, but each carries `rootRunId` pointing at the ultimate
|
|
110
|
-
* top-level run, so a hidden child's awaiting (HiL) state surfaces on the
|
|
111
|
-
* visible ancestor instead of vanishing with it.
|
|
112
|
-
*/
|
|
113
100
|
function subtreeAwaitsInput(root: RunSnapshot, allRuns: readonly RunSnapshot[]): boolean {
|
|
114
|
-
|
|
115
|
-
return allRuns.some((run) => run.rootRunId === root.id && runAwaitsInput(run));
|
|
101
|
+
return runIndicatorStatus(root, allRuns) === "awaiting_input";
|
|
116
102
|
}
|
|
117
103
|
|
|
118
104
|
function countRuns(runs: readonly RunSnapshot[], allRuns: readonly RunSnapshot[] = runs): RunCounts {
|
|
@@ -125,7 +111,7 @@ function countRuns(runs: readonly RunSnapshot[], allRuns: readonly RunSnapshot[]
|
|
|
125
111
|
else if (r.endedAt === undefined) counts.active++;
|
|
126
112
|
else if (status === "completed" || status === "skipped" || status === "cancelled") counts.done++;
|
|
127
113
|
else if (status === "failed" || status === "killed") counts.failed++;
|
|
128
|
-
if (r.endedAt === undefined && subtreeAwaitsInput(r, allRuns)) counts.awaiting++;
|
|
114
|
+
if (r.endedAt === undefined && !isQuitRun(r) && subtreeAwaitsInput(r, allRuns)) counts.awaiting++;
|
|
129
115
|
}
|
|
130
116
|
return counts;
|
|
131
117
|
}
|
|
@@ -175,31 +161,15 @@ function selectDisplayRuns(snap: StoreSnapshot, now: number): RunSnapshot[] {
|
|
|
175
161
|
// Per-run derived strings
|
|
176
162
|
// ---------------------------------------------------------------------------
|
|
177
163
|
|
|
178
|
-
function statusGlyph(run: RunSnapshot): string {
|
|
179
|
-
if (isQuitRun(run)) return "
|
|
180
|
-
|
|
181
|
-
case "running":
|
|
182
|
-
return "●";
|
|
183
|
-
case "paused":
|
|
184
|
-
return "❚❚";
|
|
185
|
-
case "completed":
|
|
186
|
-
return "✓";
|
|
187
|
-
case "skipped":
|
|
188
|
-
case "cancelled":
|
|
189
|
-
return "⊘";
|
|
190
|
-
case "blocked":
|
|
191
|
-
return "↑";
|
|
192
|
-
case "failed":
|
|
193
|
-
return "✗";
|
|
194
|
-
case "killed":
|
|
195
|
-
return "⊘";
|
|
196
|
-
default:
|
|
197
|
-
return "○";
|
|
198
|
-
}
|
|
164
|
+
function statusGlyph(run: RunSnapshot, allRuns: readonly RunSnapshot[]): string {
|
|
165
|
+
if (isQuitRun(run)) return statusIcon("pending");
|
|
166
|
+
return statusIcon(runIndicatorStatus(run, allRuns));
|
|
199
167
|
}
|
|
200
168
|
|
|
201
|
-
function statusFg(run: RunSnapshot, theme: GraphTheme): string {
|
|
169
|
+
function statusFg(run: RunSnapshot, theme: GraphTheme, allRuns: readonly RunSnapshot[]): string {
|
|
202
170
|
if (isQuitRun(run)) return theme.warning;
|
|
171
|
+
const indicatorStatus = runIndicatorStatus(run, allRuns);
|
|
172
|
+
if (indicatorStatus === "awaiting_input") return statusColor(indicatorStatus, theme);
|
|
203
173
|
switch (effectiveRunStatus(run)) {
|
|
204
174
|
case "running":
|
|
205
175
|
case "paused":
|
|
@@ -307,7 +277,7 @@ function formatTitleBadges(badges: readonly FlatBandBadge[], theme: GraphTheme,
|
|
|
307
277
|
// Themed rendering (ANSI + Catppuccin)
|
|
308
278
|
// ---------------------------------------------------------------------------
|
|
309
279
|
|
|
310
|
-
function themedRunLines(run: RunSnapshot, now: number, theme: GraphTheme): string[] {
|
|
280
|
+
function themedRunLines(run: RunSnapshot, now: number, theme: GraphTheme, allRuns: readonly RunSnapshot[]): string[] {
|
|
311
281
|
const meta = metaLine(run, now);
|
|
312
282
|
// Render the meta line in muted while running so the elapsed-time
|
|
313
283
|
// gradient stays readable; dim it once the run has terminated.
|
|
@@ -316,19 +286,19 @@ function themedRunLines(run: RunSnapshot, now: number, theme: GraphTheme): strin
|
|
|
316
286
|
runId: run.id,
|
|
317
287
|
name: run.name,
|
|
318
288
|
meta,
|
|
319
|
-
glyph: statusGlyph(run),
|
|
320
|
-
glyphColor: statusFg(run, theme),
|
|
289
|
+
glyph: statusGlyph(run, allRuns),
|
|
290
|
+
glyphColor: statusFg(run, theme, allRuns),
|
|
321
291
|
metaColor,
|
|
322
292
|
theme,
|
|
323
293
|
});
|
|
324
294
|
}
|
|
325
295
|
|
|
326
|
-
function plainRunLines(run: RunSnapshot, now: number): string[] {
|
|
296
|
+
function plainRunLines(run: RunSnapshot, now: number, allRuns: readonly RunSnapshot[]): string[] {
|
|
327
297
|
return renderRunIdentityRows({
|
|
328
298
|
runId: run.id,
|
|
329
299
|
name: run.name,
|
|
330
300
|
meta: metaLine(run, now),
|
|
331
|
-
glyph: statusGlyph(run),
|
|
301
|
+
glyph: statusGlyph(run, allRuns),
|
|
332
302
|
});
|
|
333
303
|
}
|
|
334
304
|
|
|
@@ -415,7 +385,7 @@ export function buildThemedWidgetLines(
|
|
|
415
385
|
|
|
416
386
|
for (let i = 0; i < display.length; i++) {
|
|
417
387
|
const run = display[i]!;
|
|
418
|
-
const runLines = themed ? themedRunLines(run, now, graphTheme) : plainRunLines(run, now);
|
|
388
|
+
const runLines = themed ? themedRunLines(run, now, graphTheme, snap.runs) : plainRunLines(run, now, snap.runs);
|
|
419
389
|
body.push(...runLines);
|
|
420
390
|
if (i < display.length - 1) body.push("");
|
|
421
391
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAK9F;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAc/D,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAK9F;;;;;;GAMG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAc/D,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,CA6If;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAqDD,wBAAgB,8BAA8B,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ1F;AAED,wBAAgB,mCAAmC,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAE/F;AAED;;GAEG;AAEH,wBAAgB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQ3F;AAED;;;;;GAKG;AAEH,wBAAgB,4CAA4C,CAC3D,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,UAAU,GAAG,WAAW,EACjC,SAAS,EAAE,OAAO,GAChB,IAAI,CA0DN;AAED,wBAAsB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAI/F;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAED;;;;;;GAMG;AAEH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAgBD,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,OAAO,CAAC,IAAI,CAAC,CAwFf;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC"}
|
|
@@ -36,17 +36,22 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
|
|
|
36
36
|
// response — before a fresh user prompt we must not resume the old turn.
|
|
37
37
|
const isLiveTurnCompletion = skipAbortedCheck;
|
|
38
38
|
const settings = this.settingsManager.getCompactionSettings();
|
|
39
|
-
if (!settings.enabled)
|
|
40
|
-
return;
|
|
41
|
-
// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
|
|
42
|
-
if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
|
|
43
|
-
return;
|
|
44
39
|
const contextWindow = this.model?.contextWindow ?? 0;
|
|
45
|
-
// Skip overflow
|
|
40
|
+
// Skip overflow handling if the message came from a different model.
|
|
46
41
|
// This handles the case where user switched from a smaller-context model (e.g. opus)
|
|
47
42
|
// to a larger-context model (e.g. codex) - the overflow error from the old model
|
|
48
43
|
// shouldn't trigger compaction for the new model.
|
|
49
44
|
const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
|
|
45
|
+
if (!settings.enabled) {
|
|
46
|
+
// Compaction cannot recover this turn, so a configured fallback chain may
|
|
47
|
+
// advance to a larger-context candidate instead of dead-ending.
|
|
48
|
+
if (sameModel && isContextOverflow(assistantMessage, contextWindow))
|
|
49
|
+
this._contextOverflowUnresolved = true;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
|
|
53
|
+
if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
|
|
54
|
+
return;
|
|
50
55
|
// Skip compaction checks if this assistant message is older than the latest
|
|
51
56
|
// compaction boundary. This prevents a stale pre-compaction usage/error
|
|
52
57
|
// from retriggering compaction on the first prompt after compaction.
|
|
@@ -64,6 +69,9 @@ export async function _checkCompaction(assistantMessage, skipAbortedCheck = true
|
|
|
64
69
|
return;
|
|
65
70
|
}
|
|
66
71
|
if (this._overflowRecoveryAttempted) {
|
|
72
|
+
// One compact-and-retry has already been spent on this turn; a configured
|
|
73
|
+
// fallback chain may now advance to a larger-context candidate.
|
|
74
|
+
this._contextOverflowUnresolved = true;
|
|
67
75
|
this._emit({
|
|
68
76
|
type: "compaction_end",
|
|
69
77
|
reason: "overflow",
|
|
@@ -221,10 +229,24 @@ export function _dropTrailingAutoCompactionRetryAssistantIfPresent() {
|
|
|
221
229
|
export function _schedulePostAutoCompactionContinuationProbe(_reason, willRetry) {
|
|
222
230
|
const token = this._postCompactionContinuationToken + 1;
|
|
223
231
|
this._postCompactionContinuationToken = token;
|
|
232
|
+
const fallbackScopeGeneration = this._fallbackOriginGeneration;
|
|
224
233
|
let pending;
|
|
225
234
|
pending = new Promise((resolve) => {
|
|
226
235
|
setTimeout(() => {
|
|
227
236
|
void (async () => {
|
|
237
|
+
const restoreIfOwned = async () => {
|
|
238
|
+
if (fallbackScopeGeneration === undefined ||
|
|
239
|
+
this._fallbackOriginGeneration !== fallbackScopeGeneration ||
|
|
240
|
+
typeof this._restoreFallbackModel !== "function")
|
|
241
|
+
return;
|
|
242
|
+
try {
|
|
243
|
+
await this._restoreFallbackModel();
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
// A listener must not strand the continuation waiter. The model
|
|
247
|
+
// state was already restored before lifecycle notifications ran.
|
|
248
|
+
}
|
|
249
|
+
};
|
|
228
250
|
try {
|
|
229
251
|
if (willRetry) {
|
|
230
252
|
if (this._postCompactionContinuationToken !== token)
|
|
@@ -238,10 +260,24 @@ export function _schedulePostAutoCompactionContinuationProbe(_reason, willRetry)
|
|
|
238
260
|
return;
|
|
239
261
|
if (this.isCompacting || this.isStreaming)
|
|
240
262
|
return;
|
|
241
|
-
if (!this.agent.hasQueuedMessages())
|
|
263
|
+
if (!this.agent.hasQueuedMessages()) {
|
|
264
|
+
await restoreIfOwned();
|
|
242
265
|
return;
|
|
266
|
+
}
|
|
267
|
+
// A queued message starts the next user turn. Restore before
|
|
268
|
+
// Agent snapshots the next request's model.
|
|
269
|
+
await restoreIfOwned();
|
|
243
270
|
}
|
|
271
|
+
if (this._pendingPostCompactionContinuation !== pending)
|
|
272
|
+
return;
|
|
273
|
+
// Clear this probe before entering the next run. Its promise is
|
|
274
|
+
// still awaited by _awaitPendingPostCompactionContinuation, but
|
|
275
|
+
// the nested agent_end must be free to schedule a new probe.
|
|
276
|
+
this._pendingPostCompactionContinuation = undefined;
|
|
244
277
|
await this._resumeAfterAutoCompaction();
|
|
278
|
+
if (willRetry && this._pendingPostCompactionContinuation === undefined) {
|
|
279
|
+
await restoreIfOwned();
|
|
280
|
+
}
|
|
245
281
|
}
|
|
246
282
|
finally {
|
|
247
283
|
if (this._pendingPostCompactionContinuation === pending) {
|
|
@@ -293,8 +329,15 @@ export function _resumeAfterLengthTruncation() {
|
|
|
293
329
|
this._dropTrailingAutoCompactionRetryAssistantIfPresent();
|
|
294
330
|
this._schedulePostAutoCompactionContinuationProbe("threshold", true);
|
|
295
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* Whether an overflow turn is now unrecoverable by compaction, recording it on
|
|
334
|
+
* the session so a configured fallback chain may advance to another candidate.
|
|
335
|
+
*/
|
|
296
336
|
function overflowUnresolved(reason, aborted = false) {
|
|
297
|
-
|
|
337
|
+
if (reason !== "overflow" || aborted)
|
|
338
|
+
return undefined;
|
|
339
|
+
this._contextOverflowUnresolved = true;
|
|
340
|
+
return true;
|
|
298
341
|
}
|
|
299
342
|
export async function _runAutoCompaction(reason, willRetry) {
|
|
300
343
|
// Publish automatic ownership before notifying listeners. `_emit()` invokes
|
|
@@ -322,7 +365,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
322
365
|
result: undefined,
|
|
323
366
|
aborted: false,
|
|
324
367
|
willRetry: false,
|
|
325
|
-
unresolvedOverflow: overflowUnresolved(reason),
|
|
368
|
+
unresolvedOverflow: overflowUnresolved.call(this, reason),
|
|
326
369
|
});
|
|
327
370
|
return;
|
|
328
371
|
}
|
|
@@ -352,7 +395,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
352
395
|
result: undefined,
|
|
353
396
|
aborted: false,
|
|
354
397
|
willRetry: false,
|
|
355
|
-
unresolvedOverflow: overflowUnresolved(reason),
|
|
398
|
+
unresolvedOverflow: overflowUnresolved.call(this, reason),
|
|
356
399
|
});
|
|
357
400
|
return;
|
|
358
401
|
}
|
|
@@ -371,7 +414,7 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
371
414
|
result: undefined,
|
|
372
415
|
aborted,
|
|
373
416
|
willRetry: false,
|
|
374
|
-
unresolvedOverflow: overflowUnresolved(reason, aborted),
|
|
417
|
+
unresolvedOverflow: overflowUnresolved.call(this, reason, aborted),
|
|
375
418
|
errorMessage: aborted
|
|
376
419
|
? undefined
|
|
377
420
|
: reason === "overflow"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+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K,YAAY,CAAC,CAAC;QACpG,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM;YACN,MAAM,EAAE,SAAS;YACjB,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,kBAAkB,EAAE,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC;YACvD,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACrD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QAChD,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;IAC3E,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) return;\n\t\t\t\t\t}\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\nfunction overflowUnresolved(reason: \"overflow\" | \"threshold\", aborted = false): boolean | undefined {\n\treturn reason === \"overflow\" && !aborted ? true : undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): Promise<void> {\n\t// Publish automatic ownership before notifying listeners. `_emit()` invokes\n\t// public listeners synchronously, so a `compaction_start` listener that calls\n\t// `compact()` must already observe this controller and be rejected rather than\n\t// racing the run that was just announced.\n\tthis._autoCompactionAbortController = new AbortController();\n\tthis._compactionReason = reason;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\t// Overflow recovery is load-bearing: the turn cannot continue without it.\n\t\t\t// A threshold crossing has already passed its turn boundary, so failing is safe.\n\t\t\turgency: reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n\t\t\t// A real provider overflow already proved the context does not fit, so a\n\t\t\t// sub-minimum region may reach the fresh rung.\n\t\t\t...(reason === \"overflow\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved(reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved(reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAErC,gBAAkC,EAClC,gBAAgB,GAAG,IAAI;IAEvB,IAAI,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,+BAA+B,CAAC;QACxD,IAAI,CAAC,+BAA+B,GAAG,SAAS,CAAC;QACjD,IAAI,CAAC,K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AAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QAChD,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;IAC3E,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on consecutive automatic continuations of a response that was\n * truncated at the output-token cap (\"length\") while the context is still\n * below the compaction budget. Each continuation regenerates the cut-off turn,\n * so a model that insists on emitting more than its per-turn output cap can\n * still terminate instead of looping forever.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Overflow - LLM returned context overflow error\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._overflowRecoveryAttempted) {\n\t\t\t// One compact-and-retry has already been spent on this turn; a configured\n\t\t\t// fallback chain may now advance to a larger-context candidate.\n\t\t\tthis._contextOverflowUnresolved = true;\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: true,\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\",\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A response truncated at the output-token cap (\"length\") with the context\n\t// still below the compaction budget is genuine work cut off mid-flight, not a\n\t// context overflow. Compaction would not free any room, so continue the\n\t// generation directly instead of dead-ending on the truncation and leaving\n\t// the task half-finished.\n\tif (isLiveTurnCompletion && isRetryWorthyLengthStop(assistantMessage)) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(assistantMessage: AssistantMessage): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) || isRetryWorthyOutputBudgetError(assistantMessage);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role !== \"assistant\") return;\n\tconst stopReason = (lastMsg as AssistantMessage).stopReason;\n\tif (stopReason === \"error\" || stopReason === \"length\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst restoreIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._restoreFallbackModel !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._restoreFallbackModel();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The model\n\t\t\t\t\t\t// state was already restored before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Restore before\n\t\t\t\t\t\t// Agent snapshots the next request's model.\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait restoreIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\tconst pending = this._pendingPostCompactionContinuation;\n\tif (pending === undefined) return;\n\tawait pending;\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that was truncated at the output-token cap\n * (\"length\") when the context does not warrant compaction. The generation is\n * continued directly so the model finishes the work it was cut off from, rather\n * than dead-ending on the truncation. Bounded by MAX_LENGTH_CONTINUATION_ATTEMPTS\n * so a turn that keeps exceeding the per-turn output cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\taborted = false,\n): boolean | undefined {\n\tif (reason !== \"overflow\" || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): Promise<void> {\n\t// Publish automatic ownership before notifying listeners. `_emit()` invokes\n\t// public listeners synchronously, so a `compaction_start` listener that calls\n\t// `compact()` must already observe this controller and be rejected rather than\n\t// racing the run that was just announced.\n\tthis._autoCompactionAbortController = new AbortController();\n\tthis._compactionReason = reason;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tif (!this.model) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\t// Overflow recovery is load-bearing: the turn cannot continue without it.\n\t\t\t// A threshold crossing has already passed its turn boundary, so failing is safe.\n\t\t\turgency: reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n\t\t\t// A real provider overflow already proved the context does not fit, so a\n\t\t\t// sub-minimum region may reach the fresh rung.\n\t\t\t...(reason === \"overflow\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, reason),\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted =\n\t\t\terrorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, reason, aborted),\n\t\t\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|