@denizokcu/haze 1.1.1 → 1.2.0
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 +25 -0
- package/README.md +15 -12
- package/SECURITY.md +1 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/sessionLifecycle.js +2 -0
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/commands/chat.js +24 -2
- package/dist/cli/commands/runCommand.js +6 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +52 -9
- package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
- package/dist/cli/commands/streaming/attemptSetup.js +30 -13
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +9 -0
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -1
- package/dist/cli/commands/streaming/prepareStep.js +35 -19
- package/dist/cli/commands/streaming/stallRecovery.js +2 -2
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +280 -44
- package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +8 -0
- package/dist/cli/commands/streaming.js +14 -4
- package/dist/cli/index.js +3 -2
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/settings.d.ts +10 -2
- package/dist/config/settings.js +3 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +3 -1
- package/dist/core/agent/completionController.js +1 -0
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +24 -1
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/workState.js +13 -1
- package/dist/core/safety/shellClassifier.d.ts +16 -0
- package/dist/core/safety/shellClassifier.js +31 -0
- package/dist/core/session/sessionStore.d.ts +10 -0
- package/dist/core/session/sessionStore.js +6 -0
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +6 -1
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +14 -6
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/package.json +16 -15
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 1.2.0 - 2026-08-31
|
|
6
|
+
|
|
7
|
+
Context truthfulness and never-stop-for-recoverable-reasons. A model-backed eval harness drove the changes: the completion gate's trust in real process results had four independent ways to be fed false positives, and the recovery paths still hard-failed on recoverable context conditions.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- Model-backed eval harness: `npm run eval` runs the real turn stack (goal supervisor, tools, budgets, compaction) against the configured provider in throwaway workspaces and asserts on the structured goal envelope plus deterministic ground truth (fixture test commands, file hashes) — never on response text. Five canonical scenarios including an honesty invariant (an unsatisfiable, tamper-protected task can never be reported `complete`). Evals skip under plain `npm test`, serialize process-wide, and write transcripts under gitignored `.eval/`.
|
|
12
|
+
- Curated model catalog: known model families carry real context-window and output-cap metadata keyed by model-name pattern (gateway-style `vendor/model` ids match on the final segment), slotted between per-model `modelLimits` and the user fallback. Values are input-safe (the smaller window wins when variants differ); local inference servers never consult the catalog because their effective window is server-configured.
|
|
13
|
+
- Compaction observability: `compaction_start` / `compaction_end` stream events (reason, method, counts, `willRetry`) and durable `compact` session entries (method, older/kept counts, summary) make every compaction — manual, threshold, or overflow-recovery — observable and auditable.
|
|
14
|
+
- `retryBaseDelayMs` setting (integer 250–60000, default 1000): base delay for the shared model-retry pool's exponential backoff, capped at 4× the base.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Context estimation prefers the provider's own accounting: each completed step re-anchors the estimate on reported usage (convention-robust across OpenAI-style and Anthropic-style cache reporting, so cache-heavy finishes are never double-counted), with chars/4 estimates only for trailing messages. Silent overflows (usage over the window on a successful finish) and length-stop overflows (truncated input filling the window) are detected from usage and route through the same compact-and-retry recovery as thrown overflow errors, alongside a 25-family provider error-pattern table with rate-limit exclusions.
|
|
19
|
+
- Context-overflow recovery no longer hard-fails: retries shrink the message budget progressively (60%, then 36%); once the bounded retries are exhausted the goal checkpoints (`context_exhausted`) and the supervisor pauses with a one-key resume instead of relaunching the same oversized request.
|
|
20
|
+
- Mid-turn compaction runs at epoch boundaries and prefers an LLM-written summary for large older halves — chained from any previous compaction summary and split-turn aware (a recent window landing mid-turn preserves the unfinished task's request, progress, and next action) — with the deterministic heuristic excerpt for small trims and as the fallback on any summarization failure.
|
|
21
|
+
- The shared model-retry pool resets whenever a failed attempt completed steps since the previous retry, so a long turn with intermittent provider blips never exhausts it; consecutive failures still chain backoff.
|
|
22
|
+
- Settings are re-read per attempt, so a provider or model switch made mid-goal applies from the next attempt.
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- Validation exit codes are truthful evidence (found by adversarial model-backed evals): validation-classified commands run under `pipefail` so a pipeline like `npm test | tail` can no longer report the final stage's success while the suite failed; a passing validation whose unquoted command can mask a failing stage (`;`, `||`, or single `&` list operators — redirections like `2>&1` are not) is demoted to unconfirmed; validation-kind inference matches only the unquoted command shape, so a quoted payload mentioning "test" cannot claim tool authority; and a passing self-declared custom check can no longer clear a failed classifier-confirmed validation, including one carried from a goal checkpoint.
|
|
27
|
+
|
|
3
28
|
## 1.1.1 - 2026-08-26
|
|
4
29
|
|
|
5
30
|
Durable goal resume and a smaller autonomy core. This patch keeps the concrete headless/recovery gains developed after 1.1.0 while removing unproven completion ceremony before publication.
|
package/README.md
CHANGED
|
@@ -2,17 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
A minimal LLM harness for your terminal.
|
|
4
4
|
|
|
5
|
-
## What's new in 1.
|
|
5
|
+
## What's new in 1.2.0
|
|
6
6
|
|
|
7
|
-
haze 1.
|
|
7
|
+
haze 1.2.0 makes long-running work more truthful under context pressure and provider instability.
|
|
8
8
|
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
9
|
+
- Provider-aware context accounting: completed steps re-anchor estimates on provider usage, a curated model catalog supplies known context/output limits, and live or user-configured model metadata still takes precedence.
|
|
10
|
+
- Recoverable overflow handling: thrown, silent, and length-stop context overflows compact and retry with progressively smaller budgets. Exhausted recovery checkpoints the goal as `context_exhausted` instead of hard-failing or looping on the same request.
|
|
11
|
+
- Better continuity: large mid-turn compactions use model-written, split-turn-aware summaries; every compaction emits stream events and a durable session entry for auditability.
|
|
12
|
+
- Truthful validation: validation pipelines run with `pipefail`; masking command lists and quoted lookalikes cannot claim validation authority; and a generic custom pass cannot erase a real classified failure.
|
|
13
|
+
- Resilient retries: `retryBaseDelayMs` configures exponential backoff, the retry pool resets after measurable step progress, and provider/model settings are re-read for each attempt.
|
|
13
14
|
|
|
14
15
|
Previous releases:
|
|
15
16
|
|
|
17
|
+
- `1.1.1`: durable goal ledgers and crash-resume frontiers; headless `--until-done` relaunches with bounded notices and a no-progress guard; proportional task/validation completion gates; and smaller orchestration internals.
|
|
16
18
|
- `1.1.0`: terminal theming with 14 built-in palettes and live `/themes` switching; hard secret-file protection across every file tool, including symlink, read-blessing, ignore-override, and grep-traversal defenses.
|
|
17
19
|
- `1.0.0`: first stable release — the CLI flags, settings schema, `stream-json` event contract, session format, skill layout, and structured tool-result shape under the 1.x compatibility promise; a configurable model-retry pool; and four benchmark-driven reliability fixes (validated with the Harbor differential benchmark: 17/17 verifier tests, fewest input tokens of the reporting harnesses, zero stalls).
|
|
18
20
|
- `0.11.0`: goal-level autonomy across physical-turn budgets (logical-goal supervisor, evidence-gated completion, `goal_*` stream events, cumulative goal envelope), runtime provenance and `haze doctor` (embedded build info, stale-build refusal, session build headers), model-aware context budgeting (per-preset limits, live discovery, 128K fallback, self-healing context overflow), headless `--timeout` with per-tool deadlines and abort-cause typing, performance work (batched ignore checks, LSP reuse, coalesced/vacuumed sessions, memoized estimates, incremental streaming, viewport-clamped live region), and model-written `/compact` summaries with a heuristic fallback.
|
|
@@ -252,7 +254,7 @@ echo "what does this project do?" | haze
|
|
|
252
254
|
|
|
253
255
|
`-p` and `--prompt` run one agentic turn with the full tool set and print the final assistant text. `--model` accepts a bare model name or `provider:name` and overrides the active model for that run without changing `~/.haze/settings.json`. The model must already be registered under a provider's `models`; add it once with `/provider`. Unknown or ambiguous selectors print a specific error to stderr and exit nonzero.
|
|
254
256
|
|
|
255
|
-
If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts are limited to 256 KiB; for larger input, pass a file path and ask haze to read it. One-shot runs do not create or update durable sessions, and they ignore `--continue`; `--resume <id>` can load an exact saved context for the turn without changing the original session. On a provider context overflow they compact the loaded conversation
|
|
257
|
+
If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts are limited to 256 KiB; for larger input, pass a file path and ask haze to read it. One-shot runs do not create or update durable sessions, and they ignore `--continue`; `--resume <id>` can load an exact saved context for the turn without changing the original session. On a provider context overflow they compact the loaded conversation and retry at a progressively smaller message budget (up to twice), like the interactive path; if the window stays full the run ends failed with a resumable `context_exhausted` checkpoint, and when compaction is unavailable the error says so explicitly. Add `--debug` to write a detailed JSONL log under `~/.haze/logs/`.
|
|
256
258
|
|
|
257
259
|
`--output` controls the result format: `text` is the default, `json` prints one final envelope, and `stream-json` writes live NDJSON events followed by the same envelope.
|
|
258
260
|
|
|
@@ -273,7 +275,7 @@ If you pipe stdin without `-p`, haze reads the prompt from stdin. Piped prompts
|
|
|
273
275
|
}
|
|
274
276
|
```
|
|
275
277
|
|
|
276
|
-
The `status` field is authoritative (driven by the agent's terminal state, not by parsing `result`), and the exit code mirrors it: `0` only for `complete`. A run that ends without a substantive final answer, after an unresolved final tool failure, or with declared tasks or required validation still unfinished is `failed` even if the provider returned normally; the evidence envelope carries the task counts and validation outcome that gated it. For fixes, red→green evidence is opportunistic: haze does not require a pre-edit failing repro, but if a recognized validation fails before the first mutation, that same command must pass after the fix. Per-turn step/tool budgets are safety boundaries, not completion: haze automatically continues the logical goal in fresh turns while measurable progress remains, so a budget boundary alone never fails a run. `--timeout` bounds the entire logical goal (not each internal turn), and `--until-done` additionally relaunches the goal after transient provider failures (exponential backoff, `goal_resume` events, a three-strike no-progress guard) until it structurally completes or the deadline hits — without granting any extra authority. The result envelope additionally carries a `goal` object (physical turns used, stop reason, total mutations, final validation outcome and task counts) when goal-level continuation was involved, and a bounded `notices` array with the gate decisions the run made (such as pause reasons) so scripts can see why a goal continued or stopped — the same decisions stream live as `goal_notice` events in `--output stream-json`.
|
|
278
|
+
The `status` field is authoritative (driven by the agent's terminal state, not by parsing `result`), and the exit code mirrors it: `0` only for `complete`. A run that ends without a substantive final answer, after an unresolved final tool failure, or with declared tasks or required validation still unfinished is `failed` even if the provider returned normally; the evidence envelope carries the task counts and validation outcome that gated it. For fixes, red→green evidence is opportunistic: haze does not require a pre-edit failing repro, but if a recognized validation fails before the first mutation, that same command must pass after the fix. Long tool loops use one bounded Vercel AI SDK step at a time, releasing request-local SDK state while appending the exact provider message prefix for prompt-cache reuse. Per-turn step/tool budgets are safety boundaries, not completion: haze automatically continues the logical goal in fresh turns while measurable progress remains, so a budget boundary alone never fails a run. `--timeout` bounds the entire logical goal (not each internal turn), and `--until-done` additionally relaunches the goal after transient provider failures (exponential backoff, `goal_resume` events, a three-strike no-progress guard) until it structurally completes or the deadline hits — without granting any extra authority. The result envelope additionally carries a `goal` object (physical turns used, stop reason, total mutations, final validation outcome and task counts) when goal-level continuation was involved, and a bounded `notices` array with the gate decisions the run made (such as pause reasons) so scripts can see why a goal continued or stopped — the same decisions stream live as `goal_notice` events in `--output stream-json`.
|
|
277
279
|
|
|
278
280
|
`--output stream-json` writes progress as the run happens. Each public event is one newline-delimited JSON object on stdout. The last line uses the same `{ type: "result", status, result, usage }` envelope as `--output json`, so consumers can display progress and parse the final result in the same way:
|
|
279
281
|
|
|
@@ -288,7 +290,7 @@ The `status` field is authoritative (driven by the agent's terminal state, not b
|
|
|
288
290
|
{"type":"result","status":"complete","result":"Here are the findings…","usage":{"inputTokens":0,"outputTokens":0,"cacheReadTokens":0,"cacheWriteTokens":0,"reasoningTokens":0}}
|
|
289
291
|
```
|
|
290
292
|
|
|
291
|
-
Each line is valid JSON and can be piped through `jq -c .`. Event types include `turn_start`, `message_start` / `message_update` / `message_end`, `tool_start` / `tool_end`, `retry`, `context_overflow`, and `turn_end`. Every event has an ISO-8601 `at` timestamp. Tool events omit raw inputs and outputs because CI and harness logs often capture stdout; use `--debug` for detailed local JSONL logs.
|
|
293
|
+
Each line is valid JSON and can be piped through `jq -c .`. Event types include `turn_start`, `message_start` / `message_update` / `message_end`, `tool_start` / `tool_end`, `resource_rollover`, `retry`, `context_overflow`, `compaction_start` / `compaction_end`, and `turn_end`. `resource_rollover` reports bounded SDK-step transitions and whether the provider prefix was preserved, without exposing prompts or tool output. Every event has an ISO-8601 `at` timestamp. Tool events omit raw inputs and outputs because CI and harness logs often capture stdout; use `--debug` for detailed local JSONL logs.
|
|
292
294
|
|
|
293
295
|
This mode is intended for harnesses that run haze without a person at the terminal. A supervisor can watch stdout for progress, stalls, or loops. The final `result` envelope contains the authoritative status, text, and usage. The `text` and `json` formats are unchanged.
|
|
294
296
|
|
|
@@ -364,7 +366,7 @@ Keep trivial, conversation-coupled, sequential, user-interactive, or uncertain s
|
|
|
364
366
|
|
|
365
367
|
## Context files
|
|
366
368
|
|
|
367
|
-
haze saves durable workspace sessions in `~/.haze/sessions`. It writes a session after the first resumable message, so empty sessions do not create files or appear under `/resume`. Settings, history, sessions, and debug logs use private POSIX directory/file permissions (`0700`/`0600`) and ordered, flushable writes. Use `/session` to see the current file, `/new` to start fresh, and `/resume` to browse workspace sessions, resume one, or fork its latest snapshot into a new session. `/resume <id>` and `haze --resume <id>` select an exact session. Use `/compact` to condense older model context: by default the active model writes a continuity summary of the older history (set `manualCompaction: "heuristic"` in settings to keep the model-free bounded excerpt instead); automatic mid-turn compaction
|
|
369
|
+
haze saves durable workspace sessions in `~/.haze/sessions`. It writes a session after the first resumable message, so empty sessions do not create files or appear under `/resume`. Settings, history, sessions, and debug logs use private POSIX directory/file permissions (`0700`/`0600`) and ordered, flushable writes. Use `/session` to see the current file, `/new` to start fresh, and `/resume` to browse workspace sessions, resume one, or fork its latest snapshot into a new session. `/resume <id>` and `haze --resume <id>` select an exact session. Use `/compact` to condense older model context: by default the active model writes a continuity summary of the older history (set `manualCompaction: "heuristic"` in settings to keep the model-free bounded excerpt instead); automatic mid-turn compaction also prefers a model-written summary once the older history is large, keeping the bounded excerpt for small trims and as the fallback when summarization fails. Sessions also persist compact structured work state: the active goal, touched files, validation evidence, blockers, and next action.
|
|
368
370
|
|
|
369
371
|
Snapshots are written at turn boundaries, not per tool call. If haze crashes or is killed mid-turn, the session resumes from the last completed turn: work already on disk (file edits, command side effects) is not reflected in the session record, so after a crash verify the working tree (`git status`, `git diff`) before continuing. To keep long sessions from growing quadratically — every turn appends the full history again — session files are automatically compacted once superseded snapshots dominate the file: only the newest conversation and work-state snapshots are kept and the file is rewritten atomically.
|
|
370
372
|
|
|
@@ -387,7 +389,8 @@ Use `AGENTS.md` for project conventions, commands, architecture notes, and anyth
|
|
|
387
389
|
Most haze behaviour needs no configuration; a few optional keys in `~/.haze/settings.json` tune reliability and context handling. All are validated loudly — malformed values fail with a clear settings error instead of being silently ignored.
|
|
388
390
|
|
|
389
391
|
- `modelRetries` (integer 0–10, default 2): size of the shared bounded retry pool for transient model errors and idle-stream stalls. Raise it for providers that terminate long streams aggressively; `0` disables automatic retries (a stalled stream pauses with the goal preserved for a one-key resume). The effective value is reported in `timeout` and `retry` stream events as `maxRetries`.
|
|
390
|
-
- `
|
|
392
|
+
- `retryBaseDelayMs` (integer 250–60000, default 1000): base delay for the shared retry pool's exponential backoff (`base × 2^attempt`, capped at 4× the base). The pool resets whenever a failed attempt completed steps since the previous retry, so intermittent blips on a long turn never exhaust it.
|
|
393
|
+
- `contextWindowFallbackTokens` / `localContextWindowFallbackTokens` (default 128K hosted / 32K local): context-window guess for models without limits metadata or a curated catalog entry. Every turn emits a `context_budget` event naming the window and its source, and the interactive warning fires once per model per session when the built-in default was used.
|
|
391
394
|
- `manualCompaction` (`"llm-summary"` default, or `"heuristic"`): whether manual `/compact` asks the active model for a continuity summary or keeps the model-free bounded excerpt.
|
|
392
395
|
- `theme` (string, default `purple`): name of a built-in palette (`/themes` lists and sets them, with `light` and oh-my-zsh ports like `robbyrussell` included). Unknown names fail loudly at startup with the valid names listed.
|
|
393
396
|
|
|
@@ -452,7 +455,7 @@ Package check:
|
|
|
452
455
|
npm pack --dry-run
|
|
453
456
|
```
|
|
454
457
|
|
|
455
|
-
The npm package ships `bin`, `dist`, README,
|
|
458
|
+
The npm package ships `bin`, `dist`, README, SECURITY.md, license, and changelog.
|
|
456
459
|
|
|
457
460
|
## Release
|
|
458
461
|
|
package/SECURITY.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
| Version | Supported |
|
|
6
6
|
|---------|-----------|
|
|
7
|
-
| Latest minor (`1.
|
|
7
|
+
| Latest minor (`1.2.x`) | Yes — security fixes |
|
|
8
8
|
| Older minors and pre-1.0 (`0.x`) | No — upgrade required |
|
|
9
9
|
|
|
10
10
|
Security fixes are provided for the latest published minor release. Upgrade to the newest release before reporting an issue that may already have been fixed.
|
package/dist/buildInfo.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@denizokcu/haze",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"commit": "
|
|
5
|
-
"builtAt": "2026-08-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"commit": "667c1c325d41e1f9811d9de0d19361e95a969d0e",
|
|
5
|
+
"builtAt": "2026-08-31T22:00:27.789Z",
|
|
6
6
|
"sourceRoot": "/Users/deniz.okcu/development/haze"
|
|
7
7
|
}
|
|
@@ -75,6 +75,7 @@ export function createSessionLifecycle(deps) {
|
|
|
75
75
|
}
|
|
76
76
|
deps.conversationRef.current = result.messages;
|
|
77
77
|
deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages; kept ${result.keptCount}.`);
|
|
78
|
+
deps.sessionRecorder()?.recordCompactEntry({ method: 'heuristic', olderCount: result.olderCount, keptCount: result.keptCount, ...(instructions ? { instructions } : {}), summary: result.summary ?? '' });
|
|
78
79
|
deps.sessionRecorder()?.recordConversation(result.messages);
|
|
79
80
|
deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: condensed ${result.olderCount} older model messages into a bounded excerpt and kept the last ${result.keptCount}.` }]);
|
|
80
81
|
return true;
|
|
@@ -197,6 +198,7 @@ export function createSessionLifecycle(deps) {
|
|
|
197
198
|
throw new Error('nothing older to compact');
|
|
198
199
|
deps.conversationRef.current = result.messages;
|
|
199
200
|
deps.sessionRecorder()?.recordNamedEvent('compact', `Compacted ${result.olderCount} messages with a model-written summary; kept ${result.keptCount}.`);
|
|
201
|
+
deps.sessionRecorder()?.recordCompactEntry({ method: 'llm', olderCount: result.olderCount, keptCount: result.keptCount, ...(instructions ? { instructions } : {}), summary: result.summary ?? '' });
|
|
200
202
|
deps.sessionRecorder()?.recordConversation(result.messages);
|
|
201
203
|
deps.setMessages(m => [...m, { role: 'system', text: `Compacted context: replaced ${result.olderCount} older model messages with a model-written summary and kept the last ${result.keptCount}.` }]);
|
|
202
204
|
return true;
|
|
@@ -11,6 +11,13 @@ export declare function createSessionRecorder(getSession: () => HazeSession | un
|
|
|
11
11
|
recordEvent(event: AgentEvent): void;
|
|
12
12
|
recordGoalEntry(entry: GoalLedgerAppend): void;
|
|
13
13
|
recordNamedEvent(name: string, text: string): void;
|
|
14
|
+
recordCompactEntry(entry: {
|
|
15
|
+
method: "heuristic" | "llm";
|
|
16
|
+
olderCount: number;
|
|
17
|
+
keptCount: number;
|
|
18
|
+
instructions?: string;
|
|
19
|
+
summary: string;
|
|
20
|
+
}): void;
|
|
14
21
|
flush(): Promise<void>;
|
|
15
22
|
error(): Error | undefined;
|
|
16
23
|
};
|
|
@@ -89,6 +89,12 @@ export function createSessionRecorder(getSession) {
|
|
|
89
89
|
recordNamedEvent(name, text) {
|
|
90
90
|
appendEntry({ type: 'event', at: new Date().toISOString(), name, text });
|
|
91
91
|
},
|
|
92
|
+
// First-class compaction audit entry (Pillar 1.7): what was compacted,
|
|
93
|
+
// when, how, and the summary that replaced it. Snapshots stay the restore
|
|
94
|
+
// source of truth; this entry is the durable narrative.
|
|
95
|
+
recordCompactEntry(entry) {
|
|
96
|
+
appendEntry({ type: 'compact', at: new Date().toISOString(), method: entry.method, olderCount: entry.olderCount, keptCount: entry.keptCount, ...(entry.instructions ? { instructions: entry.instructions } : {}), summary: entry.summary });
|
|
97
|
+
},
|
|
92
98
|
async flush() {
|
|
93
99
|
// Fold coalesced snapshots into the writer queue, then wait for the queue
|
|
94
100
|
// to drain. Loop because a write completing mid-flush may have queued a
|
|
@@ -548,6 +548,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
548
548
|
sessionRecorder.recordWorkState(state);
|
|
549
549
|
},
|
|
550
550
|
compactConversation,
|
|
551
|
+
recordCompaction: entry => sessionRecorder.recordCompactEntry(entry),
|
|
551
552
|
recordTokenUsage: usage => {
|
|
552
553
|
setTokenUsage(current => accumulateTokenUsage(current, usage));
|
|
553
554
|
},
|
|
@@ -630,7 +631,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
|
|
|
630
631
|
setTaskBarPadding(Math.max(0, expandedRows - collapsedRows));
|
|
631
632
|
setTasksExpanded(false);
|
|
632
633
|
}
|
|
633
|
-
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onEscape: () => {
|
|
634
|
+
}, onCancel: cancelThinking, onResumeKey: pausedResume != null && !busy ? resumePausedTask : undefined, onInterrupt: () => exit(), onEscape: () => {
|
|
634
635
|
if (busy)
|
|
635
636
|
cancelThinking();
|
|
636
637
|
else
|
|
@@ -660,7 +661,28 @@ export async function chatCommand(options = {}) {
|
|
|
660
661
|
// Incremental rendering rewrites only changed lines of the live frame, removing
|
|
661
662
|
// the full-frame erase/rewrite flicker while streaming. The fps cap aligns with
|
|
662
663
|
// the ~80ms spinner cadence; faster renders would only repaint unchanged lines.
|
|
663
|
-
|
|
664
|
+
//
|
|
665
|
+
// Kitty keyboard protocol (auto-detected): without opting in, terminals send a
|
|
666
|
+
// bare \r for Shift+Enter — indistinguishable from Enter — so Shift+Enter would
|
|
667
|
+
// submit the prompt instead of inserting a newline. With the disambiguate flag,
|
|
668
|
+
// compliant terminals (kitty, WezTerm, Ghostty, iTerm2 >=3.5, foot, recent
|
|
669
|
+
// Windows Terminal, tmux passthrough) report modified Enter as CSI 13;<mod>u,
|
|
670
|
+
// which TextInput maps to a newline. Ink queries support first (CSI ? u) with a
|
|
671
|
+
// 200ms timeout, pushes/pops the terminal's flag stack across lifecycle, and
|
|
672
|
+
// leaves unsupporting terminals (e.g. macOS Terminal.app) untouched; Enter,
|
|
673
|
+
// Tab, and Backspace without modifiers keep their legacy bytes.
|
|
674
|
+
//
|
|
675
|
+
// The protocol also re-encodes Ctrl+C as CSI 99;5u, which Ink 7.1.1's
|
|
676
|
+
// exit-on-CtrlC (raw \x03 check) does not recognize — its useInput layer
|
|
677
|
+
// would swallow the parsed c+ctrl without exiting. haze therefore owns the
|
|
678
|
+
// interrupt: render with exitOnCtrlC disabled and let ChatScreen's TextInput
|
|
679
|
+
// onInterrupt (useApp exit) terminate for both encodings.
|
|
680
|
+
const app = render(_jsx(ChatScreen, { debug: options.debug, version: options.version, build: options.build, continueSession: options.continueSession, resumeSessionId: options.resumeSessionId, noSession: options.noSession }), {
|
|
681
|
+
incrementalRendering: true,
|
|
682
|
+
maxFps: 15,
|
|
683
|
+
kittyKeyboard: { mode: 'auto', flags: ['disambiguateEscapeCodes'] },
|
|
684
|
+
exitOnCtrlC: false,
|
|
685
|
+
});
|
|
664
686
|
try {
|
|
665
687
|
await app.waitUntilExit();
|
|
666
688
|
await teardownBackgroundProcesses().catch(() => undefined);
|
|
@@ -65,6 +65,8 @@ function toHeadlessStreamEvent(event) {
|
|
|
65
65
|
return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
|
|
66
66
|
case 'step_end':
|
|
67
67
|
return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, ...(event.responseModel ? { responseModel: event.responseModel } : {}), at: event.at };
|
|
68
|
+
case 'resource_rollover':
|
|
69
|
+
return { type: 'resource_rollover', attempt: event.attempt, completedSteps: event.completedSteps, toolCalls: event.toolCalls, prefixPreserved: event.prefixPreserved, reason: event.reason, at: event.at };
|
|
68
70
|
case 'message_start':
|
|
69
71
|
return { type: 'message_start', id: event.id, role: event.role, at: event.at };
|
|
70
72
|
case 'message_update':
|
|
@@ -88,6 +90,10 @@ function toHeadlessStreamEvent(event) {
|
|
|
88
90
|
return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
|
|
89
91
|
case 'context_budget':
|
|
90
92
|
return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
|
|
93
|
+
case 'compaction_start':
|
|
94
|
+
return { type: 'compaction_start', reason: event.reason, method: event.method, at: event.at };
|
|
95
|
+
case 'compaction_end':
|
|
96
|
+
return { ...(event.olderCount === undefined ? {} : { olderCount: event.olderCount }), ...(event.keptCount === undefined ? {} : { keptCount: event.keptCount }), ...(event.willRetry === undefined ? {} : { willRetry: event.willRetry }), ...(event.error === undefined ? {} : { error: event.error }), type: 'compaction_end', reason: event.reason, method: event.method, compacted: event.compacted, at: event.at };
|
|
91
97
|
}
|
|
92
98
|
}
|
|
93
99
|
function writeNdjson(value) {
|
|
@@ -2,6 +2,7 @@ import type { ContextFile } from '../../../config/contextFiles.js';
|
|
|
2
2
|
import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
3
3
|
import type { TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
4
4
|
import type { ToolExecutionBudgetState, TurnBudget } from '../../../core/agent/budgets.js';
|
|
5
|
+
import type { ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
5
6
|
import type { TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
6
7
|
import type { SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
7
8
|
import { type AgentAttemptResult } from './attemptOutcome.js';
|
|
@@ -14,7 +15,12 @@ export interface AgentAttemptInput {
|
|
|
14
15
|
callbacks: StreamCallbacks;
|
|
15
16
|
retryAttempt: number;
|
|
16
17
|
retryingExistingRequest: boolean;
|
|
17
|
-
|
|
18
|
+
/** Multiplier for the message-token budget after context-overflow retries (1 = none; Pillar 1.4). */
|
|
19
|
+
overflowShrinkFactor: number;
|
|
20
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
21
|
+
overflowRetries: number;
|
|
22
|
+
/** Whether this attempt runs after progress since the previous retry (Pillar 1.3 pool reset). */
|
|
23
|
+
progressSinceLastRetry: boolean;
|
|
18
24
|
session: PromptSession | undefined;
|
|
19
25
|
modelOverride: string | undefined;
|
|
20
26
|
abortController: AbortController;
|
|
@@ -32,6 +38,10 @@ export interface AgentAttemptInput {
|
|
|
32
38
|
/** Exactly-once teardown registry; shared with the turn's forced-settlement path. */
|
|
33
39
|
cleanup: AttemptCleanupRegistry;
|
|
34
40
|
remainingTurnDeadlineMs: () => number;
|
|
41
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
42
|
+
usageAnchor: {
|
|
43
|
+
current: ContextUsageAnchor | undefined;
|
|
44
|
+
};
|
|
35
45
|
}
|
|
36
46
|
/**
|
|
37
47
|
* Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
|
|
@@ -15,7 +15,11 @@ import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
|
|
|
15
15
|
* display are always torn down.
|
|
16
16
|
*/
|
|
17
17
|
export async function runAgentAttempt(input) {
|
|
18
|
-
const { value, contextFiles, callbacks,
|
|
18
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
|
|
19
|
+
// Pillar 1.3: progress since the previous retry resets the shared retry pool
|
|
20
|
+
// (mirrors a per-burst budget), applied to both the stall guard's retry
|
|
21
|
+
// eligibility and the failure classification below.
|
|
22
|
+
const retryAttempt = input.progressSinceLastRetry && input.retryAttempt > 0 ? 0 : input.retryAttempt;
|
|
19
23
|
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
20
24
|
let loadedMcp;
|
|
21
25
|
let lspPool;
|
|
@@ -43,7 +47,7 @@ export async function runAgentAttempt(input) {
|
|
|
43
47
|
let stallGuard;
|
|
44
48
|
let setup;
|
|
45
49
|
try {
|
|
46
|
-
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest,
|
|
50
|
+
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
|
|
47
51
|
if (!setup)
|
|
48
52
|
return { status: 'failed' };
|
|
49
53
|
const attemptSetupResult = setup;
|
|
@@ -66,11 +70,11 @@ export async function runAgentAttempt(input) {
|
|
|
66
70
|
log: callbacks.log,
|
|
67
71
|
debugLog: callbacks.debugLog,
|
|
68
72
|
});
|
|
69
|
-
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage });
|
|
70
|
-
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream });
|
|
73
|
+
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage, usageAnchor });
|
|
74
|
+
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream, retryAttempt, overflowRetries: input.overflowRetries });
|
|
71
75
|
}
|
|
72
76
|
catch (error) {
|
|
73
|
-
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt,
|
|
77
|
+
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt, progressSinceLastRetry: input.progressSinceLastRetry, overflowRetries: input.overflowRetries, abortCause, stallGuard, salvage, error, maxRetries: setup?.modelRetries, retryBaseDelayMs: setup?.retryBaseDelayMs, goal, turnOptions });
|
|
74
78
|
}
|
|
75
79
|
finally {
|
|
76
80
|
await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
|
|
@@ -45,9 +45,9 @@ export type AttemptRecovery = {
|
|
|
45
45
|
export type AgentAttemptResult = TurnResult & {
|
|
46
46
|
retry?: {
|
|
47
47
|
attempt: number;
|
|
48
|
-
contextOverflowRecovered: boolean;
|
|
49
48
|
delayMs: number; /** The retry aborts the previous controller (idle stall); hand the loop a fresh one. */
|
|
50
|
-
freshController?: boolean;
|
|
49
|
+
freshController?: boolean; /** Message-budget multiplier for the next attempt after an overflow retry (Pillar 1.4). */
|
|
50
|
+
overflowShrinkFactor?: number;
|
|
51
51
|
};
|
|
52
52
|
/** When set, run one bounded recovery slice next (length-continuation, rescue, or goal continuation). */
|
|
53
53
|
recovery?: AttemptRecovery;
|
|
@@ -64,6 +64,10 @@ export interface AttemptOutcomeDeps {
|
|
|
64
64
|
goal: SessionGoal;
|
|
65
65
|
remainingTurnDeadlineMs: () => number;
|
|
66
66
|
stream: AttemptStreamOutcome;
|
|
67
|
+
/** Current attempt number (for overflow retry bookkeeping). */
|
|
68
|
+
retryAttempt: number;
|
|
69
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
70
|
+
overflowRetries: number;
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
69
73
|
* Classify the finished attempt: project work evidence onto the turn state,
|
|
@@ -79,18 +83,34 @@ export interface AttemptFailureDeps {
|
|
|
79
83
|
abortController: AbortController;
|
|
80
84
|
turnState: TurnExecutionState;
|
|
81
85
|
retryAttempt: number;
|
|
82
|
-
|
|
86
|
+
/** Whether the failed attempt completed at least one step since the previous retry (Pillar 1.3: progress refills the shared pool). */
|
|
87
|
+
progressSinceLastRetry?: boolean;
|
|
88
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
89
|
+
overflowRetries?: number;
|
|
83
90
|
abortCause: TurnAbortCause;
|
|
84
91
|
stallGuard: StreamStallGuard | undefined;
|
|
85
92
|
salvage: AttemptSalvage;
|
|
86
93
|
error: unknown;
|
|
87
94
|
/** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
|
|
88
95
|
maxRetries?: number;
|
|
96
|
+
/** Backoff base for the shared model-retry pool (`retryBaseDelayMs` setting); defaults to DEFAULT_RETRY_BASE_DELAY_MS. */
|
|
97
|
+
retryBaseDelayMs?: number;
|
|
98
|
+
goal: SessionGoal;
|
|
99
|
+
turnOptions: TurnExecutionOptions;
|
|
89
100
|
}
|
|
90
101
|
/**
|
|
91
102
|
* Classify a failed attempt from the recorded abort cause and the error:
|
|
92
103
|
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
93
104
|
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
94
105
|
* hard model-call failure. Completed-step progress is always preserved.
|
|
106
|
+
*
|
|
107
|
+
* Pillar 1.3: the shared retry pool resets whenever the failed attempt made
|
|
108
|
+
* progress (completed at least one step) since the previous retry — a long
|
|
109
|
+
* turn with intermittent blips never exhausts the pool. Pillar 1.4: each
|
|
110
|
+
* context-overflow retry shrinks the message budget (0.6 → 0.36); once the
|
|
111
|
+
* bounded overflow retries are exhausted the goal checkpoints
|
|
112
|
+
* (`context_exhausted`) instead of hard-failing, so the supervisor or the
|
|
113
|
+
* R-resume can continue after the user compacts, clears context, or switches
|
|
114
|
+
* models — never a false hard block.
|
|
95
115
|
*/
|
|
96
116
|
export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
|
|
@@ -3,7 +3,7 @@ import { agentEvent } from '../../../core/agent/events.js';
|
|
|
3
3
|
import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
|
|
4
4
|
import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, rescueEligibleRequest } from '../../../core/agent/completionController.js';
|
|
6
|
-
import { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS
|
|
6
|
+
import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
|
|
7
7
|
import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
|
|
8
8
|
import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
|
|
9
9
|
import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
|
|
@@ -72,6 +72,24 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
72
72
|
if (stream.unresolvedMalformedToolName)
|
|
73
73
|
callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
74
74
|
goal.phase = 'done';
|
|
75
|
+
// Non-error overflow recovery (Pillar 1.2/1.4): a silent overflow completed
|
|
76
|
+
// its response, so compact only — the next physical turn (or the supervisor)
|
|
77
|
+
// continues from the smaller history; a length-stop overflow dropped the
|
|
78
|
+
// truncated final and retries the same request once per shrink step.
|
|
79
|
+
if (stream.usageOverflow && !abortController.signal.aborted) {
|
|
80
|
+
const compacted = callbacks.compactConversation?.('Automatic recovery after a context-window overflow detected from provider usage. Preserve the active user request and concrete next steps.') ?? false;
|
|
81
|
+
const willRetry = compacted && stream.usageOverflow === 'length-stop' && deps.overflowRetries < MAX_OVERFLOW_RETRIES;
|
|
82
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: `silent usage overflow (window exceeded on a successful finish)` }));
|
|
83
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
|
|
84
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry }));
|
|
85
|
+
if (willRetry) {
|
|
86
|
+
callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
87
|
+
callbacks.addMessage({ role: 'system', text: 'Context window filled by truncated input; compacted older context and retrying the same request at a smaller budget.' });
|
|
88
|
+
return { status: 'failed', retry: { attempt: deps.retryAttempt, delayMs: 0, overflowShrinkFactor: OVERFLOW_SHRINK_FACTOR ** (deps.overflowRetries + 1) } };
|
|
89
|
+
}
|
|
90
|
+
if (compacted)
|
|
91
|
+
callbacks.addMessage({ role: 'system', text: 'Context overflow detected from provider usage; compacted older context. Completed work is preserved.' });
|
|
92
|
+
}
|
|
75
93
|
// Goal status reflects completion readiness, not the shallow text status:
|
|
76
94
|
// unfinished-but-recoverable work is waiting on continuation (supervisor or
|
|
77
95
|
// the user), while tool/input failures are concrete blockers. Prose alone
|
|
@@ -146,10 +164,24 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
146
164
|
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
147
165
|
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
148
166
|
* hard model-call failure. Completed-step progress is always preserved.
|
|
167
|
+
*
|
|
168
|
+
* Pillar 1.3: the shared retry pool resets whenever the failed attempt made
|
|
169
|
+
* progress (completed at least one step) since the previous retry — a long
|
|
170
|
+
* turn with intermittent blips never exhausts the pool. Pillar 1.4: each
|
|
171
|
+
* context-overflow retry shrinks the message budget (0.6 → 0.36); once the
|
|
172
|
+
* bounded overflow retries are exhausted the goal checkpoints
|
|
173
|
+
* (`context_exhausted`) instead of hard-failing, so the supervisor or the
|
|
174
|
+
* R-resume can continue after the user compacts, clears context, or switches
|
|
175
|
+
* models — never a false hard block.
|
|
149
176
|
*/
|
|
150
177
|
export function handleAttemptFailure(deps) {
|
|
151
|
-
const { value, callbacks, abortController, turnState,
|
|
178
|
+
const { value, callbacks, abortController, turnState, abortCause, stallGuard, salvage, error, goal, turnOptions } = deps;
|
|
152
179
|
const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
|
|
180
|
+
const retryBaseDelayMs = deps.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
|
|
181
|
+
const overflowRetries = deps.overflowRetries ?? 0;
|
|
182
|
+
// Progress refills the shared pool: consecutive failures chain backoff, but
|
|
183
|
+
// a failed attempt that completed steps since the last retry starts fresh.
|
|
184
|
+
const retryAttempt = deps.progressSinceLastRetry && deps.retryAttempt > 0 ? 0 : deps.retryAttempt;
|
|
153
185
|
if (abortController.signal.aborted) {
|
|
154
186
|
if (abortCause.kind === 'model-stream-idle') {
|
|
155
187
|
// Transport stall, not a user cancel. Preserve completed work first: the
|
|
@@ -158,12 +190,12 @@ export function handleAttemptFailure(deps) {
|
|
|
158
190
|
// instead of re-running — possibly mutating — tool work.
|
|
159
191
|
salvageConversationToLastStep(callbacks, salvage);
|
|
160
192
|
if (stallGuard?.retryEligible) {
|
|
161
|
-
const delay = retryDelayMs(retryAttempt);
|
|
193
|
+
const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
|
|
162
194
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: `model stream idle for ${formatSeconds(IDLE_TIMEOUT_MS)}` }));
|
|
163
195
|
callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}. Completed steps are preserved.` });
|
|
164
196
|
// freshController: this stall aborted the controller to kill the hung
|
|
165
197
|
// stream; the retry needs a live signal.
|
|
166
|
-
return { status: 'failed', retry: { attempt: retryAttempt + 1,
|
|
198
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay, freshController: true } };
|
|
167
199
|
}
|
|
168
200
|
// Bounded retries exhausted, or the stalled step emitted partial output.
|
|
169
201
|
// Pause with the active goal preserved (work state is untouched by this
|
|
@@ -189,15 +221,26 @@ export function handleAttemptFailure(deps) {
|
|
|
189
221
|
}
|
|
190
222
|
const text = error instanceof Error ? error.message : String(error);
|
|
191
223
|
callbacks.debugLog(`error: ${text}`);
|
|
192
|
-
|
|
224
|
+
// Bounded overflow retries with progressive shrink (Pillar 1.4): each retry
|
|
225
|
+
// compacts and multiplies the message budget by 0.6; once MAX_OVERFLOW_RETRIES
|
|
226
|
+
// are consumed the goal checkpoints instead of hard-failing.
|
|
227
|
+
if (overflowRetries >= MAX_OVERFLOW_RETRIES && isContextOverflowError(error)) {
|
|
228
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: false, error: text }));
|
|
229
|
+
callbacks.addMessage({ role: 'system', text: 'Context overflow persisted after bounded compaction retries; pausing the goal with a checkpoint. Completed work is preserved in the conversation. Press R to resume after compacting or clearing context, or switch to a larger-context model.' });
|
|
230
|
+
return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', {}) };
|
|
231
|
+
}
|
|
232
|
+
if (isContextOverflowError(error)) {
|
|
193
233
|
const canCompact = typeof callbacks.compactConversation === 'function';
|
|
194
234
|
const compacted = canCompact
|
|
195
235
|
? callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false
|
|
196
236
|
: false;
|
|
197
237
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
238
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
|
|
239
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry: compacted }));
|
|
198
240
|
if (compacted) {
|
|
199
|
-
|
|
200
|
-
|
|
241
|
+
const shrink = OVERFLOW_SHRINK_FACTOR ** (overflowRetries + 1);
|
|
242
|
+
callbacks.addMessage({ role: 'system', text: `Context overflow detected; compacted older context and retrying the same request at ${Math.round(shrink * 100)}% of the message budget.` });
|
|
243
|
+
return { status: 'failed', retry: { attempt: retryAttempt, delayMs: 0, overflowShrinkFactor: shrink } };
|
|
201
244
|
}
|
|
202
245
|
callbacks.addMessage({ role: 'system', text: canCompact
|
|
203
246
|
? 'Context overflow detected, but there was not enough conversation history to compact automatically.'
|
|
@@ -206,10 +249,10 @@ export function handleAttemptFailure(deps) {
|
|
|
206
249
|
// Transient model errors share the bounded retry pool with idle-stream
|
|
207
250
|
// stalls, so a turn can never retry more than its configured total.
|
|
208
251
|
if (retryAttempt < maxRetries && isRetryableModelError(error)) {
|
|
209
|
-
const delay = retryDelayMs(retryAttempt);
|
|
252
|
+
const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
|
|
210
253
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
211
254
|
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
212
|
-
return { status: 'failed', retry: { attempt: retryAttempt + 1,
|
|
255
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay } };
|
|
213
256
|
}
|
|
214
257
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
215
258
|
return { status: 'failed' };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { ModelMessage, ToolSet } from 'ai';
|
|
2
2
|
import type { ContextFile } from '../../../config/contextFiles.js';
|
|
3
|
-
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
4
|
-
import { calculateRequestTokenBudget } from '../../../core/agent/contextBudget.js';
|
|
5
3
|
import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
|
|
4
|
+
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
5
|
+
import { calculateRequestTokenBudget, type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
6
6
|
import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
|
|
7
7
|
import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
8
8
|
import type { LoadedMcpTools } from '../../../llm/mcp.js';
|
|
@@ -47,13 +47,16 @@ export interface AttemptSetup {
|
|
|
47
47
|
toolCategories: Map<string, ToolCategory>;
|
|
48
48
|
/** Retry-pool size for this attempt's turn, from the `modelRetries` setting (default 2). */
|
|
49
49
|
modelRetries: number;
|
|
50
|
+
/** Backoff base for the shared model-retry pool, from the `retryBaseDelayMs` setting (default 1000ms). */
|
|
51
|
+
retryBaseDelayMs: number;
|
|
50
52
|
}
|
|
51
53
|
export interface AttemptSetupDeps {
|
|
52
54
|
value: string;
|
|
53
55
|
contextFiles: ContextFile[];
|
|
54
56
|
callbacks: StreamCallbacks;
|
|
55
57
|
retryingExistingRequest: boolean;
|
|
56
|
-
|
|
58
|
+
/** Multiplier for the message-token budget after context-overflow retries (1 = none, 0.6/0.36 after each; Pillar 1.4). */
|
|
59
|
+
overflowShrinkFactor: number;
|
|
57
60
|
session: PromptSession | undefined;
|
|
58
61
|
modelOverride: string | undefined;
|
|
59
62
|
abortController: AbortController;
|
|
@@ -67,6 +70,10 @@ export interface AttemptSetupDeps {
|
|
|
67
70
|
sliceBudget: ToolExecutionBudgetState;
|
|
68
71
|
goal: SessionGoal;
|
|
69
72
|
onContextFileRead: (path: string) => void;
|
|
73
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
74
|
+
usageAnchor: {
|
|
75
|
+
current: ContextUsageAnchor | undefined;
|
|
76
|
+
};
|
|
70
77
|
}
|
|
71
78
|
/**
|
|
72
79
|
* Assemble one attempt: resolve the model (single fresh settings read, CR-024),
|