@denizokcu/haze 1.1.0 → 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 (149) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/README.md +17 -10
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  6. package/dist/cli/chat/busyIndicator.js +34 -0
  7. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  8. package/dist/cli/chat/chatMetrics.js +1 -7
  9. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  10. package/dist/cli/chat/followUpQueue.js +38 -0
  11. package/dist/cli/chat/messages.d.ts +0 -22
  12. package/dist/cli/chat/messages.js +40 -85
  13. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  14. package/dist/cli/chat/sessionLifecycle.js +8 -1
  15. package/dist/cli/chat/sessionRecorder.d.ts +9 -0
  16. package/dist/cli/chat/sessionRecorder.js +12 -0
  17. package/dist/cli/chat/startupSequence.d.ts +29 -0
  18. package/dist/cli/chat/startupSequence.js +59 -0
  19. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  20. package/dist/cli/chat/transcriptPartition.js +78 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  22. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  23. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  24. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  26. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  27. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  28. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  33. package/dist/cli/chat/wizard/types.d.ts +63 -0
  34. package/dist/cli/chat/wizard/types.js +24 -0
  35. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  36. package/dist/cli/chat/wizard/uiState.js +15 -0
  37. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  38. package/dist/cli/chat/wizardDispatch.js +41 -815
  39. package/dist/cli/commands/chat.js +69 -110
  40. package/dist/cli/commands/formatters.d.ts +0 -3
  41. package/dist/cli/commands/formatters.js +0 -29
  42. package/dist/cli/commands/runCommand.d.ts +2 -0
  43. package/dist/cli/commands/runCommand.js +73 -4
  44. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  45. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  46. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  47. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  48. package/dist/cli/commands/streaming/attemptOutcome.d.ts +25 -5
  49. package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
  50. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  51. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  52. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  53. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  54. package/dist/cli/commands/streaming/goalSupervisor.d.ts +18 -3
  55. package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
  56. package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
  57. package/dist/cli/commands/streaming/prepareStep.js +116 -0
  58. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  59. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  60. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  61. package/dist/cli/commands/streaming/stallRecovery.js +2 -6
  62. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +283 -268
  64. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  65. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  66. package/dist/cli/commands/streaming/toolPartHandlers.js +108 -0
  67. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  68. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  69. package/dist/cli/commands/streaming.d.ts +12 -1
  70. package/dist/cli/commands/streaming.js +20 -25
  71. package/dist/cli/index.js +6 -3
  72. package/dist/config/modelCatalog.d.ts +32 -0
  73. package/dist/config/modelCatalog.js +84 -0
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +10 -2
  77. package/dist/config/settings.js +3 -0
  78. package/dist/core/agent/budgets.d.ts +10 -0
  79. package/dist/core/agent/budgets.js +10 -0
  80. package/dist/core/agent/compaction.d.ts +42 -3
  81. package/dist/core/agent/compaction.js +53 -5
  82. package/dist/core/agent/completionController.d.ts +16 -7
  83. package/dist/core/agent/completionController.js +13 -6
  84. package/dist/core/agent/contextBudget.d.ts +56 -0
  85. package/dist/core/agent/contextBudget.js +53 -0
  86. package/dist/core/agent/errors.js +2 -2
  87. package/dist/core/agent/events.d.ts +36 -1
  88. package/dist/core/agent/goalPolicy.d.ts +4 -3
  89. package/dist/core/agent/goalPolicy.js +9 -4
  90. package/dist/core/agent/overflow.d.ts +45 -0
  91. package/dist/core/agent/overflow.js +91 -0
  92. package/dist/core/agent/requestAssembly.d.ts +7 -0
  93. package/dist/core/agent/requestAssembly.js +15 -7
  94. package/dist/core/agent/workState.d.ts +25 -15
  95. package/dist/core/agent/workState.js +84 -44
  96. package/dist/core/safety/shellClassifier.d.ts +16 -0
  97. package/dist/core/safety/shellClassifier.js +31 -0
  98. package/dist/core/session/sessionSlimming.js +8 -0
  99. package/dist/core/session/sessionStore.d.ts +71 -1
  100. package/dist/core/session/sessionStore.js +121 -6
  101. package/dist/core/validation/outputParser.d.ts +1 -1
  102. package/dist/core/validation/outputParser.js +6 -1
  103. package/dist/llm/client.d.ts +2 -2
  104. package/dist/llm/client.js +14 -6
  105. package/dist/llm/hazeTools.d.ts +64 -208
  106. package/dist/llm/tools/shellTool.js +27 -8
  107. package/dist/llm/tools/taskTool.d.ts +64 -208
  108. package/dist/llm/tools/taskTool.js +22 -10
  109. package/dist/ui/components/TextInput.d.ts +18 -1
  110. package/dist/ui/components/TextInput.js +50 -73
  111. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  112. package/dist/ui/components/useInputSuggestions.js +98 -0
  113. package/dist/ui/theme.d.ts +8 -8
  114. package/dist/ui/theme.js +11 -12
  115. package/dist/ui/themes/registry.d.ts +5 -0
  116. package/dist/ui/themes/registry.js +436 -0
  117. package/dist/utils/format.d.ts +10 -0
  118. package/dist/utils/format.js +45 -0
  119. package/package.json +16 -15
  120. package/dist/ui/themes/af-magic.d.ts +0 -7
  121. package/dist/ui/themes/af-magic.js +0 -25
  122. package/dist/ui/themes/agnoster.d.ts +0 -10
  123. package/dist/ui/themes/agnoster.js +0 -40
  124. package/dist/ui/themes/bira.d.ts +0 -10
  125. package/dist/ui/themes/bira.js +0 -28
  126. package/dist/ui/themes/bureau.d.ts +0 -10
  127. package/dist/ui/themes/bureau.js +0 -28
  128. package/dist/ui/themes/clean.d.ts +0 -9
  129. package/dist/ui/themes/clean.js +0 -27
  130. package/dist/ui/themes/cloud.d.ts +0 -6
  131. package/dist/ui/themes/cloud.js +0 -24
  132. package/dist/ui/themes/dst.d.ts +0 -10
  133. package/dist/ui/themes/dst.js +0 -28
  134. package/dist/ui/themes/fishy.d.ts +0 -7
  135. package/dist/ui/themes/fishy.js +0 -25
  136. package/dist/ui/themes/index.d.ts +0 -8
  137. package/dist/ui/themes/index.js +0 -36
  138. package/dist/ui/themes/light.d.ts +0 -3
  139. package/dist/ui/themes/light.js +0 -21
  140. package/dist/ui/themes/purple.d.ts +0 -7
  141. package/dist/ui/themes/purple.js +0 -26
  142. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  143. package/dist/ui/themes/robbyrussell.js +0 -26
  144. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  145. package/dist/ui/themes/solarized-dark.js +0 -44
  146. package/dist/ui/themes/solarized-light.d.ts +0 -12
  147. package/dist/ui/themes/solarized-light.js +0 -40
  148. package/dist/ui/themes/steeef.d.ts +0 -11
  149. package/dist/ui/themes/steeef.js +0 -29
@@ -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
  '',
@@ -43,6 +43,8 @@ export interface TurnExecutionState {
43
43
  goalContinuationProgress: string | undefined;
44
44
  /** Whether the single allowed no-progress corrective nudge has been consumed. */
45
45
  goalContinuationCorrectiveUsed: boolean;
46
+ /** Opportunistic red→green state for fix intents. */
47
+ redPair: 'not-required' | 'missing' | 'satisfied' | undefined;
46
48
  budgetBoundary: boolean;
47
49
  aborted: boolean;
48
50
  }
@@ -64,6 +66,8 @@ export interface TurnCompletionEvidence {
64
66
  inProgress: number;
65
67
  completed: number;
66
68
  };
69
+ /** Opportunistic red→green state for fix intents. */
70
+ redPair?: 'not-required' | 'missing' | 'satisfied';
67
71
  finishCause: FinishCause | undefined;
68
72
  recoveryUsed: {
69
73
  length: boolean;
@@ -86,9 +90,12 @@ export type TurnStatus = 'complete' | 'aborted' | 'failed';
86
90
  * Reasoned completion readiness from structured current-turn evidence. A
87
91
  * voluntary final is acceptable only when the declared work is actually done;
88
92
  * prose alone is never evidence of completion (no semantic judge — task,
89
- * mutation, validation, tool, and budget evidence is authoritative).
93
+ * mutation, validation, red→green, tool, and budget evidence is
94
+ * authoritative).
90
95
  */
91
- export type CompletionReadiness = 'ready' | 'pending_tasks' | 'validation_failed' | 'validation_stale' | 'validation_absent_after_mutation' | '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';
92
99
  /** Inputs `assessCompletionReadiness` needs; matches the TurnExecutionState projection. */
93
100
  export interface CompletionReadinessInput {
94
101
  aborted: boolean;
@@ -96,13 +103,16 @@ export interface CompletionReadinessInput {
96
103
  mutationCount: number;
97
104
  validationOutcome: ValidationOutcome;
98
105
  taskProgress: WorkTaskProgress | undefined;
106
+ /** Red→green pair state; absent/not-required disables the gate. */
107
+ redPair?: 'not-required' | 'missing' | 'satisfied';
99
108
  }
100
109
  /**
101
110
  * Pure completion-readiness assessment. Priority: abort, unresolved tool
102
- * input, failed tool, declared task progress, then intent-sensitive validation
103
- * policy (implement/fix/test turns with successful mutations require fresh
104
- * passing validation; plan/review/answer turns never do). A task list is
105
- * enforced only when this turn declared one via a successful writeTasks call.
111
+ * input, failed tool, declared task progress, then intent-sensitive
112
+ * validation policy (implement/fix/test turns with successful mutations
113
+ * require fresh passing validation; plan/review/answer turns never do), then
114
+ * the fix-intent red→green pair. A task list is enforced only when this turn
115
+ * declared one via a successful writeTasks call.
106
116
  */
107
117
  export declare function assessCompletionReadiness(state: CompletionReadinessInput, evidence: Pick<CompletionEvidence, 'lastToolOk' | 'unresolvedToolInputError'>): CompletionReadiness;
108
118
  /** Human-readable, safe (no commands/content) description of a readiness result. */
@@ -180,7 +190,6 @@ export interface GoalContinuationDecision {
180
190
  slice: RecoverySlice;
181
191
  }
182
192
  /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
183
- /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
184
193
  export declare function goalContinuationRecoverable(readiness: CompletionReadiness): boolean;
185
194
  /**
186
195
  * Terminal classification of a finished attempt against the logical goal.
@@ -29,6 +29,7 @@ export function createTurnExecutionState() {
29
29
  validationContinuationUsed: false,
30
30
  goalContinuationProgress: undefined,
31
31
  goalContinuationCorrectiveUsed: false,
32
+ redPair: undefined,
32
33
  budgetBoundary: false,
33
34
  aborted: false,
34
35
  };
@@ -41,6 +42,7 @@ export function toCompletionEvidence(state) {
41
42
  validationAfterMutation: state.validationAfterMutation,
42
43
  mutationCount: state.mutationCount,
43
44
  ...(state.taskProgress ? { taskProgress: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
45
+ ...(state.redPair && state.redPair !== 'not-required' ? { redPair: state.redPair } : {}),
44
46
  finishCause: state.finishCause,
45
47
  recoveryUsed: { length: state.lengthCreditUsed, rescue: state.rescueUsed, goal: state.goalContinuationsUsed },
46
48
  budgetBoundary: state.budgetBoundary,
@@ -48,10 +50,11 @@ export function toCompletionEvidence(state) {
48
50
  }
49
51
  /**
50
52
  * Pure completion-readiness assessment. Priority: abort, unresolved tool
51
- * input, failed tool, declared task progress, then intent-sensitive validation
52
- * policy (implement/fix/test turns with successful mutations require fresh
53
- * passing validation; plan/review/answer turns never do). A task list is
54
- * enforced only when this turn declared one via a successful writeTasks call.
53
+ * input, failed tool, declared task progress, then intent-sensitive
54
+ * validation policy (implement/fix/test turns with successful mutations
55
+ * require fresh passing validation; plan/review/answer turns never do), then
56
+ * the fix-intent red→green pair. A task list is enforced only when this turn
57
+ * declared one via a successful writeTasks call.
55
58
  */
56
59
  export function assessCompletionReadiness(state, evidence) {
57
60
  if (state.aborted)
@@ -70,6 +73,8 @@ export function assessCompletionReadiness(state, evidence) {
70
73
  if (state.validationOutcome === 'absent' && state.mutationCount > 0)
71
74
  return 'validation_absent_after_mutation';
72
75
  }
76
+ if (state.intent === 'fix' && state.redPair === 'missing')
77
+ return 'red_check_not_green';
73
78
  return 'ready';
74
79
  }
75
80
  /** Human-readable, safe (no commands/content) description of a readiness result. */
@@ -82,9 +87,11 @@ export function describeCompletionReadiness(readiness, taskProgress) {
82
87
  case 'validation_failed': return 'the latest validation failed and remains unresolved';
83
88
  case 'validation_stale': return 'edits landed after the latest validation';
84
89
  case 'validation_absent_after_mutation': return 'edits landed without any relevant validation';
90
+ case 'red_check_not_green': return 'the captured pre-edit failing check has not passed after the fix';
85
91
  case 'tool_failure': return 'the last tool call failed';
86
92
  case 'unresolved_tool_input': return 'a tool call never executed because its input was invalid';
87
93
  case 'aborted': return 'the turn was aborted';
94
+ case 'context_exhausted': return 'the model context window was exhausted before the work could finish';
88
95
  case 'ready': return 'declared work is complete';
89
96
  }
90
97
  }
@@ -197,12 +204,12 @@ export function decideRescue(state, evidence, budget, isMutatingRequest) {
197
204
  const GOAL_CONTINUATION_SLICE = { steps: 6, toolCalls: 12 };
198
205
  const VALIDATION_CONTINUATION_SLICE = { steps: 3, toolCalls: 3 };
199
206
  /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
200
- /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
201
207
  export function goalContinuationRecoverable(readiness) {
202
208
  return readiness === 'pending_tasks'
203
209
  || readiness === 'validation_failed'
204
210
  || readiness === 'validation_stale'
205
- || readiness === 'validation_absent_after_mutation';
211
+ || readiness === 'validation_absent_after_mutation'
212
+ || readiness === 'red_check_not_green';
206
213
  }
207
214
  /**
208
215
  * Normal provider finishes that can still represent recoverable unfinished
@@ -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);
@@ -27,6 +27,11 @@ export type AgentEvent = {
27
27
  goalId: string;
28
28
  cycle: number;
29
29
  reason: string;
30
+ text?: string;
31
+ at: string;
32
+ } | {
33
+ type: 'goal_notice';
34
+ text: string;
30
35
  at: string;
31
36
  } | {
32
37
  type: 'goal_end';
@@ -36,6 +41,13 @@ export type AgentEvent = {
36
41
  cycles: number;
37
42
  stopReason?: string;
38
43
  evidence?: TurnCompletionEvidence;
44
+ } | {
45
+ type: 'goal_resume';
46
+ goalId: string;
47
+ at: string;
48
+ relaunch: number;
49
+ stopReason: string;
50
+ reason: string;
39
51
  } | {
40
52
  type: 'step_start';
41
53
  attempt: number;
@@ -50,6 +62,14 @@ export type AgentEvent = {
50
62
  usage: AgentStepUsage;
51
63
  responseModel?: string;
52
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;
53
73
  } | {
54
74
  type: 'message_start';
55
75
  id: string;
@@ -98,13 +118,28 @@ export type AgentEvent = {
98
118
  } | {
99
119
  type: 'context_budget';
100
120
  contextWindowTokens: number;
101
- source: 'settings' | 'user-fallback' | 'default-fallback';
121
+ source: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback';
102
122
  at: string;
103
123
  } | {
104
124
  type: 'context_overflow';
105
125
  recovered: boolean;
106
126
  error: string;
107
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;
108
143
  } | {
109
144
  type: 'timeout';
110
145
  phase: 'turn' | 'tool' | 'model-stream';
@@ -36,12 +36,13 @@ export declare function malformedToolCallPrompt(toolName: string, chunkBytes: nu
36
36
  * Ephemeral control for a goal-continuation slice or a fresh continuation
37
37
  * turn. The model's stop was rejected (or its physical turn hit a budget
38
38
  * boundary) while structured evidence — declared task counts, post-edit
39
- * validation — shows unfinished work; this nudge requires resuming concrete
40
- * work rather than summarizing again. One-request nudge only.
39
+ * validation, or red→green pairs — shows unfinished work; this nudge requires
40
+ * resuming concrete work rather than summarizing
41
+ * again. One-request nudge only.
41
42
  */
42
43
  export declare function goalContinuationPrompt(reason: string, taskCounts?: {
43
44
  total: number;
44
45
  pending: number;
45
46
  inProgress: number;
46
47
  completed: number;
47
- }): string;
48
+ }, detail?: string): string;
@@ -92,15 +92,20 @@ export function malformedToolCallPrompt(toolName, chunkBytes) {
92
92
  * Ephemeral control for a goal-continuation slice or a fresh continuation
93
93
  * turn. The model's stop was rejected (or its physical turn hit a budget
94
94
  * boundary) while structured evidence — declared task counts, post-edit
95
- * validation — shows unfinished work; this nudge requires resuming concrete
96
- * work rather than summarizing again. One-request nudge only.
95
+ * validation, or red→green pairs — shows unfinished work; this nudge requires
96
+ * resuming concrete work rather than summarizing
97
+ * again. One-request nudge only.
97
98
  */
98
- export function goalContinuationPrompt(reason, taskCounts) {
99
+ export function goalContinuationPrompt(reason, taskCounts, detail) {
99
100
  const taskLine = taskCounts
100
101
  ? ` The task list currently shows ${taskCounts.pending + taskCounts.inProgress} open item${taskCounts.pending + taskCounts.inProgress === 1 ? '' : 's'} of ${taskCounts.total}; update writeTasks as you complete them.`
101
102
  : '';
102
103
  const validationLine = reason.includes('validation')
103
104
  ? ' No recognized post-edit validation was recorded. Run one standard test/build command, directly execute the changed artifact as one unchained command, or call shell with purpose=validation for a custom assertion check.'
104
105
  : '';
105
- return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine} Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
106
+ const redLine = reason.includes('failing check')
107
+ ? ' Rerun the same validation command that failed before the edit and resolve it; a different check does not close the captured red evidence.'
108
+ : '';
109
+ const detailLine = detail ? ` ${detail}` : '';
110
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine}${redLine}${detailLine} Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
106
111
  }