@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.
Files changed (59) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +15 -12
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/sessionLifecycle.js +2 -0
  6. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  7. package/dist/cli/chat/sessionRecorder.js +6 -0
  8. package/dist/cli/commands/chat.js +24 -2
  9. package/dist/cli/commands/runCommand.js +6 -0
  10. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  11. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  12. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  13. package/dist/cli/commands/streaming/attemptOutcome.js +52 -9
  14. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  15. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  16. package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
  17. package/dist/cli/commands/streaming/goalSupervisor.js +9 -0
  18. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -1
  19. package/dist/cli/commands/streaming/prepareStep.js +35 -19
  20. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  21. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  22. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  23. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  24. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  25. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  26. package/dist/cli/commands/streaming.d.ts +8 -0
  27. package/dist/cli/commands/streaming.js +14 -4
  28. package/dist/cli/index.js +3 -2
  29. package/dist/config/modelCatalog.d.ts +32 -0
  30. package/dist/config/modelCatalog.js +84 -0
  31. package/dist/config/settings.d.ts +10 -2
  32. package/dist/config/settings.js +3 -0
  33. package/dist/core/agent/budgets.d.ts +10 -0
  34. package/dist/core/agent/budgets.js +10 -0
  35. package/dist/core/agent/compaction.d.ts +42 -3
  36. package/dist/core/agent/compaction.js +53 -5
  37. package/dist/core/agent/completionController.d.ts +3 -1
  38. package/dist/core/agent/completionController.js +1 -0
  39. package/dist/core/agent/contextBudget.d.ts +56 -0
  40. package/dist/core/agent/contextBudget.js +53 -0
  41. package/dist/core/agent/errors.js +2 -2
  42. package/dist/core/agent/events.d.ts +24 -1
  43. package/dist/core/agent/overflow.d.ts +45 -0
  44. package/dist/core/agent/overflow.js +91 -0
  45. package/dist/core/agent/requestAssembly.d.ts +7 -0
  46. package/dist/core/agent/requestAssembly.js +15 -7
  47. package/dist/core/agent/workState.js +13 -1
  48. package/dist/core/safety/shellClassifier.d.ts +16 -0
  49. package/dist/core/safety/shellClassifier.js +31 -0
  50. package/dist/core/session/sessionStore.d.ts +10 -0
  51. package/dist/core/session/sessionStore.js +6 -0
  52. package/dist/core/validation/outputParser.d.ts +1 -1
  53. package/dist/core/validation/outputParser.js +6 -1
  54. package/dist/llm/client.d.ts +2 -2
  55. package/dist/llm/client.js +14 -6
  56. package/dist/llm/tools/shellTool.js +27 -8
  57. package/dist/ui/components/TextInput.d.ts +18 -1
  58. package/dist/ui/components/TextInput.js +44 -6
  59. package/package.json +16 -15
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Curated model metadata catalog (Pillar 1.8 of the Pi learning roadmap).
3
+ *
4
+ * Keys are **model-name patterns** (not provider names) because haze reaches
5
+ * most models through user-configured OpenAI-compatible gateways where the
6
+ * provider name is arbitrary — the model id is the only stable identity.
7
+ *
8
+ * Precedence (enforced in `llm/client.ts`): per-model `modelLimits` settings →
9
+ * this catalog → user-set context-window fallback → built-in default fallback.
10
+ * Values are deliberately conservative (input-safe): when a family differs
11
+ * between variants, the smaller window wins — under-budgeting only compacts a
12
+ * little earlier, over-budgeting hard-fails the request. First match wins, so
13
+ * keep more specific patterns before broader family prefixes.
14
+ *
15
+ * Local inference servers (localhost URLs) never consult the catalog: their
16
+ * effective window is set by server configuration (often far below the model's
17
+ * nominal window) and silent truncation there is undetectable.
18
+ */
19
+ const MODEL_CATALOG = [
20
+ // ── OpenAI ────────────────────────────────────────────────────────────────
21
+ { match: 'gpt-5.1-codex', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
22
+ { match: 'gpt-5.1-codex-mini', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
23
+ { match: 'gpt-5', contextWindowTokens: 400_000, maxOutputTokens: 128_000 },
24
+ { match: 'gpt-4.1', contextWindowTokens: 1_047_576, maxOutputTokens: 32_768 },
25
+ { match: 'gpt-4o', contextWindowTokens: 128_000, maxOutputTokens: 16_384 },
26
+ { match: 'o4', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
27
+ { match: 'o3', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
28
+ { match: 'o1', contextWindowTokens: 200_000, maxOutputTokens: 100_000 },
29
+ // ── Anthropic ─────────────────────────────────────────────────────────────
30
+ { match: 'claude-opus-4', contextWindowTokens: 200_000, maxOutputTokens: 32_000 },
31
+ { match: 'claude-sonnet-4', contextWindowTokens: 200_000, maxOutputTokens: 64_000 },
32
+ { match: 'claude-haiku-4', contextWindowTokens: 200_000, maxOutputTokens: 32_000 },
33
+ { match: 'claude-3-7', contextWindowTokens: 200_000, maxOutputTokens: 64_000 },
34
+ { match: 'claude-3-5', contextWindowTokens: 200_000, maxOutputTokens: 8_192 },
35
+ // ── Google ────────────────────────────────────────────────────────────────
36
+ { match: 'gemini-3', contextWindowTokens: 1_048_576, maxOutputTokens: 65_536 },
37
+ { match: 'gemini-2.5', contextWindowTokens: 1_048_576, maxOutputTokens: 65_536 },
38
+ { match: 'gemini-2.0', contextWindowTokens: 1_048_576, maxOutputTokens: 8_192 },
39
+ // ── xAI ───────────────────────────────────────────────────────────────────
40
+ { match: 'grok-4', contextWindowTokens: 256_000, maxOutputTokens: 32_768 },
41
+ { match: 'grok-3', contextWindowTokens: 131_072, maxOutputTokens: 32_768 },
42
+ // ── DeepSeek ──────────────────────────────────────────────────────────────
43
+ { match: 'deepseek-reasoner', contextWindowTokens: 128_000, maxOutputTokens: 32_768, note: 'R1/reasoner family' },
44
+ { match: 'deepseek-r1', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
45
+ { match: 'deepseek', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
46
+ // ── Alibaba / Moonshot / Zhipu / MiniMax ─────────────────────────────────
47
+ { match: 'qwen3-coder', contextWindowTokens: 262_144, maxOutputTokens: 32_768 },
48
+ { match: 'qwen3', contextWindowTokens: 131_072, maxOutputTokens: 32_768, note: 'native window without YaRN extension' },
49
+ { match: 'qwen', contextWindowTokens: 131_072, maxOutputTokens: 8_192 },
50
+ { match: 'kimi-k2', contextWindowTokens: 131_072, maxOutputTokens: 32_768, note: 'input-safe half of the 256K total' },
51
+ { match: 'glm-4.6', contextWindowTokens: 200_000, maxOutputTokens: 32_768 },
52
+ { match: 'glm-4.5', contextWindowTokens: 131_072, maxOutputTokens: 32_768 },
53
+ { match: 'minimax-m2', contextWindowTokens: 204_800, maxOutputTokens: 1_048_576, note: 'output budget exceeds window in interleave mode' },
54
+ // ── Meta / Mistral ───────────────────────────────────────────────────────
55
+ { match: 'llama-4-maverick', contextWindowTokens: 1_048_576, maxOutputTokens: 32_768 },
56
+ { match: 'llama-4-scout', contextWindowTokens: 1_048_576, maxOutputTokens: 32_768, note: 'gateway-served window; self-host is server-configured' },
57
+ { match: 'llama-3.3', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
58
+ { match: 'llama-3.1', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
59
+ { match: 'mistral-large', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
60
+ { match: 'mistral-medium', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
61
+ { match: 'devstral', contextWindowTokens: 128_000, maxOutputTokens: 32_768 },
62
+ { match: 'codestral', contextWindowTokens: 256_000, maxOutputTokens: 32_768 },
63
+ { match: 'mistral', contextWindowTokens: 128_000, maxOutputTokens: 8_192 },
64
+ ];
65
+ /** Look up catalog limits for a model name (case-insensitive prefix families). Gateway-style `vendor/model` and `vendor:model` identifiers match on their final segment. */
66
+ export function catalogLimitsFor(modelName) {
67
+ const name = modelName.trim().toLowerCase();
68
+ if (!name)
69
+ return undefined;
70
+ for (const entry of MODEL_CATALOG) {
71
+ if (name.startsWith(entry.match) || lastSegment(name).startsWith(entry.match)) {
72
+ return { contextWindowTokens: entry.contextWindowTokens, ...(entry.maxOutputTokens !== undefined ? { maxOutputTokens: entry.maxOutputTokens } : {}) };
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+ function lastSegment(name) {
78
+ const slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf(':'));
79
+ return slash === -1 ? name : name.slice(slash + 1);
80
+ }
81
+ /** Catalog entries exposed for pinning tests (like the theme registry). */
82
+ export function getModelCatalog() {
83
+ return MODEL_CATALOG;
84
+ }
@@ -94,11 +94,19 @@ export interface HazeSettings {
94
94
  * OpenAI-compatible gateways); 0 disables automatic retries.
95
95
  */
96
96
  modelRetries?: number;
97
+ /**
98
+ * Base delay in milliseconds for the shared model-retry pool backoff
99
+ * (`base * 2^attempt`, capped at 4× the base). Unset means the built-in
100
+ * default of 1000ms. The pool resets whenever an attempt completes a
101
+ * successful step, so intermittent blips never exhaust it.
102
+ */
103
+ retryBaseDelayMs?: number;
97
104
  /**
98
105
  * Manual `/compact` mode (F-09): `llm-summary` (default) asks the active
99
106
  * model to summarize the older history; `heuristic` keeps the bounded
100
- * excerpt without a model call. Automatic mid-turn compaction is always
101
- * heuristic.
107
+ * excerpt without a model call. Mid-turn compaction prefers an LLM summary
108
+ * when the older history is large and falls back to the heuristic excerpt
109
+ * for small trims and on any summarization failure.
102
110
  */
103
111
  manualCompaction?: 'llm-summary' | 'heuristic';
104
112
  /** UI tweaks: rotating tips under the busy label, etc. Default enabled. */
@@ -46,6 +46,8 @@ const subagentSettingsSchema = z.object({
46
46
  const contextWindowFallbackSchema = z.number().int().min(1_000).max(10_000_000);
47
47
  /** Retry-pool size must be a small non-negative count (0 disables retries). */
48
48
  const modelRetriesSchema = z.number().int().min(0).max(10);
49
+ /** Retry backoff base must be a plausible delay (not fractions/junk). */
50
+ const retryBaseDelaySchema = z.number().int().min(250).max(60_000);
49
51
  const settingsSchema = z.object({
50
52
  provider: z.string().optional(),
51
53
  model: z.string().optional(),
@@ -58,6 +60,7 @@ const settingsSchema = z.object({
58
60
  contextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
59
61
  localContextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
60
62
  modelRetries: modelRetriesSchema.optional(),
63
+ retryBaseDelayMs: retryBaseDelaySchema.optional(),
61
64
  manualCompaction: z.enum(['llm-summary', 'heuristic']).optional(),
62
65
  tips: z.object({ enabled: z.boolean().optional() }).optional(),
63
66
  theme: z.string().optional(),
@@ -44,6 +44,16 @@ export declare const SUBAGENT_MAX_RETRIES = 5;
44
44
  export declare const DEFAULT_MODEL_RETRIES = 2;
45
45
  /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
46
46
  export declare const MAX_MODEL_RETRIES_SETTING = 10;
47
+ /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
48
+ export declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
49
+ /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
50
+ export declare const OVERFLOW_SHRINK_FACTOR = 0.6;
51
+ /** Bounded context-overflow retries per turn before the goal checkpoints instead of hard-failing (Pillar 1.4). */
52
+ export declare const MAX_OVERFLOW_RETRIES = 2;
53
+ /** Older-history estimate (tokens) at which mid-turn compaction prefers an LLM-written summary over the heuristic excerpt (Pillar 1.5). */
54
+ export declare const COMPACTION_LLM_MIN_OLDER_TOKENS = 6000;
55
+ /** Output cap for mid-turn LLM summarization calls; summaries never need the full response budget. */
56
+ export declare const COMPACTION_LLM_MAX_OUTPUT_TOKENS = 4096;
47
57
  export interface TurnBudget {
48
58
  /** Maximum completed model steps across the whole turn (incl. recovery). */
49
59
  stepLimit: number;
@@ -51,6 +51,16 @@ export const SUBAGENT_MAX_RETRIES = 5;
51
51
  export const DEFAULT_MODEL_RETRIES = 2;
52
52
  /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
53
53
  export const MAX_MODEL_RETRIES_SETTING = 10;
54
+ /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
55
+ export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000;
56
+ /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
57
+ export const OVERFLOW_SHRINK_FACTOR = 0.6;
58
+ /** Bounded context-overflow retries per turn before the goal checkpoints instead of hard-failing (Pillar 1.4). */
59
+ export const MAX_OVERFLOW_RETRIES = 2;
60
+ /** Older-history estimate (tokens) at which mid-turn compaction prefers an LLM-written summary over the heuristic excerpt (Pillar 1.5). */
61
+ export const COMPACTION_LLM_MIN_OLDER_TOKENS = 6_000;
62
+ /** Output cap for mid-turn LLM summarization calls; summaries never need the full response budget. */
63
+ export const COMPACTION_LLM_MAX_OUTPUT_TOKENS = 4_096;
54
64
  export function mainTurnBudget() {
55
65
  return { stepLimit: MAIN_STEP_LIMIT, toolCallLimit: MAIN_TOOL_CALL_LIMIT, toolOnlyStepLimit: MAIN_TOOL_ONLY_STEP_LIMIT };
56
66
  }
@@ -10,6 +10,13 @@ export interface CompactionResult {
10
10
  export interface CompactionSplit {
11
11
  older: ModelMessage[];
12
12
  recent: ModelMessage[];
13
+ /**
14
+ * The recent window lands mid-turn: the first kept message is not a user
15
+ * message, so the older half contains the early prefix of the current
16
+ * (unfinished) turn (Pillar 1.6). The LLM summarization path uses this to
17
+ * preserve the in-flight task's request, progress, and next action.
18
+ */
19
+ splitTurn: boolean;
13
20
  }
14
21
  /**
15
22
  * Decide which trailing messages survive compaction and which are folded into
@@ -29,16 +36,48 @@ export declare function compactModelMessages(messages: ModelMessage[], options?:
29
36
  instructions?: string;
30
37
  workState?: WorkState;
31
38
  }): CompactionResult;
39
+ /**
40
+ * Extract the summary text of an existing `<haze_compaction>` message so a
41
+ * later LLM summarization can update it in place instead of re-summarizing
42
+ * the whole history from scratch (Pillar 1.5, iterative summaries).
43
+ */
44
+ export declare function extractExistingCompactionSummary(messages: ModelMessage[]): string | undefined;
45
+ /** Which mid-turn compaction method an epoch boundary should use (Pillar 1.5). */
46
+ export type BoundaryCompactionMethod = 'none' | 'heuristic' | 'llm';
47
+ /**
48
+ * Choose the mid-turn compaction method: `none` while the conversation fits
49
+ * the budget; the deterministic heuristic excerpt for small older halves (fast,
50
+ * no extra model call); an LLM-written summary once the older history is large
51
+ * enough that an excerpt loses decisions and next steps. `totalTokens`
52
+ * overrides the chars/4 estimate for the over-budget check so a usage-anchored
53
+ * total (Pillar 1.1) can trigger compaction for token-dense history that the
54
+ * heuristic estimate undercounts.
55
+ */
56
+ export declare function chooseBoundaryCompactionMethod(input: {
57
+ messages: ModelMessage[];
58
+ messageTokenBudget: number;
59
+ olderTokenThreshold: number;
60
+ estimateTokens?: (messages: ModelMessage[]) => number;
61
+ totalTokens?: number;
62
+ }): {
63
+ method: BoundaryCompactionMethod;
64
+ split?: CompactionSplit;
65
+ };
32
66
  /**
33
67
  * Build the summarization request for the LLM-summarized compaction path
34
- * (F-09). The transcript is the older half, bounded to a character budget and
35
- * truncated from the front (the oldest context is the least valuable) so the
36
- * request itself can never overflow the model.
68
+ * (F-09; also the mid-turn path, Pillar 1.5). The transcript is the older
69
+ * half, bounded to a character budget and truncated from the front (the oldest
70
+ * context is the least valuable) so the request itself can never overflow the
71
+ * model. When a previous compaction summary exists it is included so the model
72
+ * updates it in place (iterative summaries); a split turn adds instructions to
73
+ * preserve the unfinished task's request, progress, and next action.
37
74
  */
38
75
  export declare function buildLlmCompactionPrompt(input: {
39
76
  older: ModelMessage[];
40
77
  instructions?: string;
41
78
  maxChars?: number;
79
+ previousSummary?: string;
80
+ splitTurn?: boolean;
42
81
  }): string;
43
82
  /**
44
83
  * Assemble the compacted history around a model-written summary (F-09). Same
@@ -1,4 +1,4 @@
1
- import { estimateModelMessageTokens } from './contextBudget.js';
1
+ import { estimateMessagesTokens, estimateModelMessageTokens } from './contextBudget.js';
2
2
  import { workStatePrompt } from './workState.js';
3
3
  import { COMPACTION_LLM_TRANSCRIPT_CHARS, COMPACTION_OLDER_CHARS } from '../limits.js';
4
4
  /**
@@ -29,7 +29,7 @@ export function splitForCompaction(messages, options = {}) {
29
29
  recentStart -= 1;
30
30
  if (recentStart === 0)
31
31
  return undefined;
32
- return { older: messages.slice(0, recentStart), recent: messages.slice(recentStart) };
32
+ return { older: messages.slice(0, recentStart), recent: messages.slice(recentStart), splitTurn: messages[recentStart]?.role !== 'user' };
33
33
  }
34
34
  export function modelMessageText(message) {
35
35
  const content = message.content;
@@ -79,11 +79,53 @@ export function compactModelMessages(messages, options = {}) {
79
79
  summary,
80
80
  };
81
81
  }
82
+ /**
83
+ * Extract the summary text of an existing `<haze_compaction>` message so a
84
+ * later LLM summarization can update it in place instead of re-summarizing
85
+ * the whole history from scratch (Pillar 1.5, iterative summaries).
86
+ */
87
+ export function extractExistingCompactionSummary(messages) {
88
+ for (const message of messages) {
89
+ if (message.role !== 'user' || typeof message.content !== 'string' || !message.content.startsWith('<haze_compaction>'))
90
+ continue;
91
+ const start = message.content.indexOf('\n');
92
+ const end = message.content.lastIndexOf('</haze_compaction>');
93
+ if (start === -1 || end === -1 || end <= start)
94
+ return undefined;
95
+ const summary = message.content.slice(start + 1, end).trim();
96
+ return summary || undefined;
97
+ }
98
+ return undefined;
99
+ }
100
+ /**
101
+ * Choose the mid-turn compaction method: `none` while the conversation fits
102
+ * the budget; the deterministic heuristic excerpt for small older halves (fast,
103
+ * no extra model call); an LLM-written summary once the older history is large
104
+ * enough that an excerpt loses decisions and next steps. `totalTokens`
105
+ * overrides the chars/4 estimate for the over-budget check so a usage-anchored
106
+ * total (Pillar 1.1) can trigger compaction for token-dense history that the
107
+ * heuristic estimate undercounts.
108
+ */
109
+ export function chooseBoundaryCompactionMethod(input) {
110
+ if (input.messages.length === 0)
111
+ return { method: 'none' };
112
+ const estimate = input.estimateTokens ?? estimateMessagesTokens;
113
+ const total = input.totalTokens ?? estimate(input.messages);
114
+ if (total <= input.messageTokenBudget)
115
+ return { method: 'none' };
116
+ const split = splitForCompaction(input.messages, { tokenBudget: input.messageTokenBudget });
117
+ if (!split)
118
+ return { method: 'none' };
119
+ return { method: estimate(split.older) >= input.olderTokenThreshold ? 'llm' : 'heuristic', split };
120
+ }
82
121
  /**
83
122
  * Build the summarization request for the LLM-summarized compaction path
84
- * (F-09). The transcript is the older half, bounded to a character budget and
85
- * truncated from the front (the oldest context is the least valuable) so the
86
- * request itself can never overflow the model.
123
+ * (F-09; also the mid-turn path, Pillar 1.5). The transcript is the older
124
+ * half, bounded to a character budget and truncated from the front (the oldest
125
+ * context is the least valuable) so the request itself can never overflow the
126
+ * model. When a previous compaction summary exists it is included so the model
127
+ * updates it in place (iterative summaries); a split turn adds instructions to
128
+ * preserve the unfinished task's request, progress, and next action.
87
129
  */
88
130
  export function buildLlmCompactionPrompt(input) {
89
131
  const maxChars = input.maxChars ?? COMPACTION_LLM_TRANSCRIPT_CHARS;
@@ -109,6 +151,12 @@ export function buildLlmCompactionPrompt(input) {
109
151
  'Summarize the following older conversation history for continuity. The summary replaces the history in a coding agent context.',
110
152
  'Preserve: current user goal and success condition; explicit user constraints, preferences, and decisions; files created/changed/read; validation commands and their pass/fail results; blockers or pending decisions; the exact next action if work was unfinished.',
111
153
  'Drop: restatements, exploration dead ends that led nowhere, raw tool output detail, and anything the recent messages supersede.',
154
+ input.splitTurn
155
+ ? 'The transcript below was cut in the MIDDLE of an unfinished task (split turn). Under Critical Context, additionally preserve: the original request of the current task, the concrete work already completed in the cut-off prefix, and the single exact next action to continue it.'
156
+ : undefined,
157
+ input.previousSummary
158
+ ? `A previous compaction summary exists. Update it with the new messages: PRESERVE everything still relevant, ADD new progress/decisions/context, DROP only what the recent tail supersedes.\n\n<previous-summary>\n${input.previousSummary}\n</previous-summary>`
159
+ : undefined,
112
160
  input.instructions ? `User compaction instructions: ${input.instructions}` : undefined,
113
161
  `Write a dense summary in at most 60 lines. ${omitted > 0 ? `(${omitted} oldest message(s) already omitted from this transcript.)` : ''}`.trim(),
114
162
  '',
@@ -93,7 +93,9 @@ export type TurnStatus = 'complete' | 'aborted' | 'failed';
93
93
  * mutation, validation, red→green, tool, and budget evidence is
94
94
  * authoritative).
95
95
  */
96
- export type CompletionReadiness = 'ready' | 'pending_tasks' | 'validation_failed' | 'validation_stale' | 'validation_absent_after_mutation' | 'red_check_not_green' | 'tool_failure' | 'unresolved_tool_input' | 'aborted';
96
+ export type CompletionReadiness = 'ready' | 'pending_tasks' | 'validation_failed' | 'validation_stale' | 'validation_absent_after_mutation' | 'red_check_not_green' | 'tool_failure' | 'unresolved_tool_input' | 'aborted'
97
+ /** Produced only by the context-overflow exhaustion path (Pillar 1.4): the window stayed full after bounded compact-and-retry attempts. */
98
+ | 'context_exhausted';
97
99
  /** Inputs `assessCompletionReadiness` needs; matches the TurnExecutionState projection. */
98
100
  export interface CompletionReadinessInput {
99
101
  aborted: boolean;
@@ -91,6 +91,7 @@ export function describeCompletionReadiness(readiness, taskProgress) {
91
91
  case 'tool_failure': return 'the last tool call failed';
92
92
  case 'unresolved_tool_input': return 'a tool call never executed because its input was invalid';
93
93
  case 'aborted': return 'the turn was aborted';
94
+ case 'context_exhausted': return 'the model context window was exhausted before the work could finish';
94
95
  case 'ready': return 'declared work is complete';
95
96
  }
96
97
  }
@@ -52,6 +52,62 @@ export declare function contextBreakdown(input: {
52
52
  }): ContextBreakdown;
53
53
  export declare function effectiveNonCachedInput(inputTokens: number | undefined, cacheReadTokens: number): number | undefined;
54
54
  export declare function cacheHitRatio(inputTokens: number | undefined, cacheReadTokens: number | undefined): number | undefined;
55
+ /** Marker prefix of a request-local synthetic control message (see requestAssembly.ts). */
56
+ export declare const SYNTHETIC_CONTROL_MARKER = "<haze_control>";
57
+ /**
58
+ * Anchor for usage-backed context estimation (Pillar 1.1): the provider's own
59
+ * token accounting for a completed step, plus the message count it covered.
60
+ * Trailing messages appended after that boundary are estimated with the usual
61
+ * chars/4 heuristic and added on top — mirroring how the estimate should behave
62
+ * once real usage exists.
63
+ */
64
+ export interface ContextUsageAnchor {
65
+ /** Message count (synthetic controls excluded) the usage covered. */
66
+ messageCount: number;
67
+ /** Provider-reported context tokens at that boundary (input+output+cache). */
68
+ contextTokens: number;
69
+ }
70
+ /**
71
+ * The input-like term of a provider usage record, robust to the two cache
72
+ * reporting conventions. OpenAI-style usage includes cached tokens inside
73
+ * `inputTokens` (the convention `effectiveNonCachedInput` assumes), so
74
+ * summing both would double the cached prefix — tripping silent-overflow
75
+ * detection and over-compaction on every cache-heavy turn. When cache-read
76
+ * exceeds input, the reporting must be exclusive-style (Anthropic-like), and
77
+ * the sum is exact. The remaining ambiguous case (exclusive-style with
78
+ * cache-read ≤ input) can only under-count — the safe direction: later
79
+ * compaction and late overflow detection, never false positives.
80
+ */
81
+ export declare function inputLikeTokens(usage: {
82
+ inputTokens?: number;
83
+ cacheReadTokens?: number;
84
+ }): number;
85
+ /**
86
+ * Total provider-reported context tokens from a usage record: the
87
+ * convention-robust input-like term (see `inputLikeTokens`) plus cache-write
88
+ * (never part of `inputTokens` on either convention) and output tokens.
89
+ */
90
+ export declare function contextTokensFromUsage(usage: {
91
+ inputTokens?: number;
92
+ outputTokens?: number;
93
+ cacheReadTokens?: number;
94
+ cacheWriteTokens?: number;
95
+ }): number | undefined;
96
+ export interface ContextTokenEstimate {
97
+ tokens: number;
98
+ /** Whether the number is provider-usage-backed or a pure chars/4 estimate. */
99
+ basis: 'usage' | 'estimate';
100
+ }
101
+ /**
102
+ * Estimate the message-history token count, preferring provider usage. When an
103
+ * anchor exists and still covers a prefix of the messages (nothing rewrote the
104
+ * history — e.g. compaction), the anchor's reported total minus the given
105
+ * non-message overhead (system prompt + tool schemas, which provider input
106
+ * tokens include) is used and only trailing messages are estimated. Synthetic
107
+ * controls are excluded on both sides so anchor indices stay aligned with the
108
+ * durable (control-free) conversation.
109
+ */
110
+ export declare function estimateConversationTokens(messages: readonly ModelMessage[], anchor: ContextUsageAnchor | undefined, overheadTokens?: number): ContextTokenEstimate;
55
111
  export interface RequestTokenBudget {
56
112
  contextWindowTokens: number;
57
113
  systemTokens: number;
@@ -153,6 +153,59 @@ export function cacheHitRatio(inputTokens, cacheReadTokens) {
153
153
  return undefined;
154
154
  return cacheReadTokens / inputTokens;
155
155
  }
156
+ // ── Usage-backed context estimation (Pillar 1.1) ─────────────────────────────
157
+ /** Marker prefix of a request-local synthetic control message (see requestAssembly.ts). */
158
+ export const SYNTHETIC_CONTROL_MARKER = '<haze_control>';
159
+ function isSyntheticControlMessage(message) {
160
+ return message.role === 'user' && typeof message.content === 'string' && message.content.startsWith(SYNTHETIC_CONTROL_MARKER);
161
+ }
162
+ /**
163
+ * The input-like term of a provider usage record, robust to the two cache
164
+ * reporting conventions. OpenAI-style usage includes cached tokens inside
165
+ * `inputTokens` (the convention `effectiveNonCachedInput` assumes), so
166
+ * summing both would double the cached prefix — tripping silent-overflow
167
+ * detection and over-compaction on every cache-heavy turn. When cache-read
168
+ * exceeds input, the reporting must be exclusive-style (Anthropic-like), and
169
+ * the sum is exact. The remaining ambiguous case (exclusive-style with
170
+ * cache-read ≤ input) can only under-count — the safe direction: later
171
+ * compaction and late overflow detection, never false positives.
172
+ */
173
+ export function inputLikeTokens(usage) {
174
+ const input = usage.inputTokens ?? 0;
175
+ const cacheRead = usage.cacheReadTokens ?? 0;
176
+ return cacheRead > input ? input + cacheRead : Math.max(input, cacheRead);
177
+ }
178
+ /**
179
+ * Total provider-reported context tokens from a usage record: the
180
+ * convention-robust input-like term (see `inputLikeTokens`) plus cache-write
181
+ * (never part of `inputTokens` on either convention) and output tokens.
182
+ */
183
+ export function contextTokensFromUsage(usage) {
184
+ const total = inputLikeTokens(usage) + (usage.cacheWriteTokens ?? 0) + (usage.outputTokens ?? 0);
185
+ return total > 0 ? total : undefined;
186
+ }
187
+ /**
188
+ * Estimate the message-history token count, preferring provider usage. When an
189
+ * anchor exists and still covers a prefix of the messages (nothing rewrote the
190
+ * history — e.g. compaction), the anchor's reported total minus the given
191
+ * non-message overhead (system prompt + tool schemas, which provider input
192
+ * tokens include) is used and only trailing messages are estimated. Synthetic
193
+ * controls are excluded on both sides so anchor indices stay aligned with the
194
+ * durable (control-free) conversation.
195
+ */
196
+ export function estimateConversationTokens(messages, anchor, overheadTokens = 0) {
197
+ if (!anchor)
198
+ return { tokens: estimateMessagesTokens(messages), basis: 'estimate' };
199
+ const withoutControls = messages.filter(message => !isSyntheticControlMessage(message));
200
+ if (withoutControls.length < anchor.messageCount) {
201
+ // History was rewritten (compaction, salvage) — the anchor is stale.
202
+ return { tokens: estimateMessagesTokens(withoutControls), basis: 'estimate' };
203
+ }
204
+ let trailing = 0;
205
+ for (let index = anchor.messageCount; index < withoutControls.length; index++)
206
+ trailing += estimateModelMessageTokens(withoutControls[index]);
207
+ return { tokens: Math.max(0, anchor.contextTokens - overheadTokens) + trailing, basis: 'usage' };
208
+ }
156
209
  /**
157
210
  * Compute the message-token allowance for a request from the full input
158
211
  * breakdown: context window minus system prompt, tool schemas, output reserve,
@@ -1,9 +1,9 @@
1
+ import { errorIndicatesContextOverflow } from './overflow.js';
1
2
  function errorText(error) {
2
3
  return (error instanceof Error ? `${error.name} ${error.message}` : String(error)).toLowerCase();
3
4
  }
4
5
  export function isContextOverflowError(error) {
5
- const text = errorText(error);
6
- return /context length|context window|context limit|maximum context|max context|token limit|too many tokens|input too long|prompt too long|context.*exceed|tokens.*exceed/.test(text);
6
+ return errorIndicatesContextOverflow(errorText(error));
7
7
  }
8
8
  export function isRetryableModelError(error) {
9
9
  const text = errorText(error);
@@ -62,6 +62,14 @@ export type AgentEvent = {
62
62
  usage: AgentStepUsage;
63
63
  responseModel?: string;
64
64
  at: string;
65
+ } | {
66
+ type: 'resource_rollover';
67
+ attempt: number;
68
+ completedSteps: number;
69
+ toolCalls: number;
70
+ prefixPreserved: boolean;
71
+ reason: 'sdk-step-boundary' | 'context-compaction' | 'request-policy-change';
72
+ at: string;
65
73
  } | {
66
74
  type: 'message_start';
67
75
  id: string;
@@ -110,13 +118,28 @@ export type AgentEvent = {
110
118
  } | {
111
119
  type: 'context_budget';
112
120
  contextWindowTokens: number;
113
- source: 'settings' | 'user-fallback' | 'default-fallback';
121
+ source: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback';
114
122
  at: string;
115
123
  } | {
116
124
  type: 'context_overflow';
117
125
  recovered: boolean;
118
126
  error: string;
119
127
  at: string;
128
+ } | {
129
+ type: 'compaction_start';
130
+ reason: 'threshold' | 'overflow' | 'manual';
131
+ method: 'heuristic' | 'llm';
132
+ at: string;
133
+ } | {
134
+ type: 'compaction_end';
135
+ reason: 'threshold' | 'overflow' | 'manual';
136
+ method: 'heuristic' | 'llm' | 'none';
137
+ compacted: boolean;
138
+ olderCount?: number;
139
+ keptCount?: number;
140
+ willRetry?: boolean;
141
+ error?: string;
142
+ at: string;
120
143
  } | {
121
144
  type: 'timeout';
122
145
  phase: 'turn' | 'tool' | 'model-stream';
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Provider context-overflow classification (Pillar 1.2 of the Pi learning
3
+ * roadmap). Three overflow modes exist and each routes to different recovery:
4
+ *
5
+ * 1. **Error overflow**: the provider rejects an oversized request with a
6
+ * provider-specific error message (`errorIndicatesContextOverflow`).
7
+ * 2. **Silent overflow**: some gateways (z.ai-style) accept the oversized
8
+ * request and answer normally; only the reported usage exceeds the window
9
+ * (`isSilentContextOverflow`).
10
+ * 3. **Length-stop overflow**: some local servers truncate the input to fill
11
+ * the window, leaving no room for output — a `length` finish with ~zero
12
+ * output and input filling the window (`isLengthStopOverflow`).
13
+ *
14
+ * Pattern families are battle-tested against the providers listed per regex;
15
+ * keep this file a pure data table so tests can pin it (like the theme
16
+ * registry). Additive changes only.
17
+ */
18
+ /** Does an error text indicate a provider context-window overflow? */
19
+ export declare function errorIndicatesContextOverflow(text: string): boolean;
20
+ export interface OverflowUsageInput {
21
+ inputTokens: number | undefined;
22
+ cacheReadTokens: number;
23
+ contextWindowTokens: number;
24
+ }
25
+ /**
26
+ * Silent overflow: the request succeeded but the reported input already
27
+ * exceeded the model's context window (some gateways accept and stream an
28
+ * answer anyway; the next request will fail or be truncated). The input-like
29
+ * term is convention-robust (see `inputLikeTokens`): subset-style cached
30
+ * tokens inside `inputTokens` are never double counted, so a cache-heavy
31
+ * successful finish cannot false-positive.
32
+ */
33
+ export declare function isSilentContextOverflow(input: OverflowUsageInput): boolean;
34
+ export interface LengthStopOverflowInput extends OverflowUsageInput {
35
+ finishReason: string | undefined;
36
+ outputTokens: number | undefined;
37
+ }
38
+ /**
39
+ * Length-stop overflow: the server truncated the oversized input to fit the
40
+ * window, leaving no room to generate — a `length` finish with zero output and
41
+ * input filling (≥99% of) the window.
42
+ */
43
+ export declare function isLengthStopOverflow(input: LengthStopOverflowInput): boolean;
44
+ /** Overflow patterns exposed for pinning tests. */
45
+ export declare function getOverflowPatterns(): readonly RegExp[];