@denizokcu/haze 1.1.1 → 1.4.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 (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. package/package.json +20 -19
@@ -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;
@@ -139,6 +141,14 @@ export declare function hasRemainingRecoveryBudget(state: Pick<TurnExecutionStat
139
141
  * failure (length-continuation lands in Increment 2 and only flips on when a
140
142
  * recovery credit is both available and warranted).
141
143
  */
144
+ /**
145
+ * Explicit, persisted cause for a failed turn (RT-05): the live session's
146
+ * second goal failed in 20s with zero assistant output and no timeout/retry
147
+ * events, and with `--debug` off the ledger held nothing diagnosable. Pure and
148
+ * bounded; safe metadata only. Undefined when the finish explains itself
149
+ * (normal failed readiness with a substantive answer).
150
+ */
151
+ export declare function describeTurnFailure(state: Pick<TurnExecutionState, 'finishCause' | 'aborted' | 'budgetBoundary'>, lastAssistantText: string): string | undefined;
142
152
  export declare function decideTerminalStatus(state: TurnExecutionState, evidence: CompletionEvidence, budgetExhausted: boolean): TurnStatus;
143
153
  type RecoveryAction = 'continue' | 'stop';
144
154
  interface RecoverySlice {
@@ -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
  }
@@ -125,9 +126,41 @@ export function hasRemainingRecoveryBudget(state, budget) {
125
126
  * failure (length-continuation lands in Increment 2 and only flips on when a
126
127
  * recovery credit is both available and warranted).
127
128
  */
129
+ /**
130
+ * Explicit, persisted cause for a failed turn (RT-05): the live session's
131
+ * second goal failed in 20s with zero assistant output and no timeout/retry
132
+ * events, and with `--debug` off the ledger held nothing diagnosable. Pure and
133
+ * bounded; safe metadata only. Undefined when the finish explains itself
134
+ * (normal failed readiness with a substantive answer).
135
+ */
136
+ export function describeTurnFailure(state, lastAssistantText) {
137
+ if (!state.aborted && state.finishCause === 'stop' && lastAssistantText.trim().length === 0)
138
+ return 'model-returned-no-output';
139
+ if (state.finishCause === 'length')
140
+ return 'output-length-truncation';
141
+ if (state.finishCause === 'error')
142
+ return 'model-error';
143
+ if (state.finishCause === 'content-filter')
144
+ return 'content-filter';
145
+ if (state.finishCause === 'tool-calls' && state.budgetBoundary)
146
+ return 'tool-budget-boundary';
147
+ if (state.finishCause === 'unknown')
148
+ return 'unknown-finish';
149
+ return undefined;
150
+ }
128
151
  export function decideTerminalStatus(state, evidence, budgetExhausted) {
129
152
  if (state.aborted)
130
153
  return 'aborted';
154
+ // A voluntary `stop` final whose structured completion evidence is ready is
155
+ // complete even at a budget boundary: a turn that finished its declared work
156
+ // and answered substantively must not be reported failed merely because it
157
+ // also used its whole budget (RT-02 — the review session's goal 1 ended
158
+ // failed/blocked with finishCause 'stop', 5/5 tasks, and a delivered report).
159
+ // `classifyTerminalOutcome` already treats this exact shape as goal-complete;
160
+ // keep the two authorities aligned. Non-stop finishes (length/error) and
161
+ // non-ready evidence still fail as before.
162
+ if (state.finishCause === 'stop' && evidence.assistantText.trim().length > 0 && assessCompletionReadiness(state, evidence) === 'ready')
163
+ return 'complete';
131
164
  if (budgetExhausted || state.finishCause === 'length' || state.finishCause === 'error')
132
165
  return 'failed';
133
166
  if (assessCompletionReadiness(state, evidence) !== 'ready')
@@ -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);
@@ -16,7 +16,8 @@ export type AgentEvent = {
16
16
  request: string;
17
17
  at: string;
18
18
  status: 'complete' | 'aborted' | 'failed';
19
- evidence?: TurnCompletionEvidence;
19
+ evidence?: TurnCompletionEvidence; /** Explicit cause when the outcome is otherwise unexplained (RT-05): persisted without --debug so silent failures are diagnosable from the ledger. */
20
+ reason?: string;
20
21
  } | {
21
22
  type: 'goal_start';
22
23
  goalId: string;
@@ -62,6 +63,14 @@ export type AgentEvent = {
62
63
  usage: AgentStepUsage;
63
64
  responseModel?: string;
64
65
  at: string;
66
+ } | {
67
+ type: 'resource_rollover';
68
+ attempt: number;
69
+ completedSteps: number;
70
+ toolCalls: number;
71
+ prefixPreserved: boolean;
72
+ reason: 'sdk-step-boundary' | 'context-compaction' | 'request-policy-change';
73
+ at: string;
65
74
  } | {
66
75
  type: 'message_start';
67
76
  id: string;
@@ -110,13 +119,28 @@ export type AgentEvent = {
110
119
  } | {
111
120
  type: 'context_budget';
112
121
  contextWindowTokens: number;
113
- source: 'settings' | 'user-fallback' | 'default-fallback';
122
+ source: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback';
114
123
  at: string;
115
124
  } | {
116
125
  type: 'context_overflow';
117
126
  recovered: boolean;
118
127
  error: string;
119
128
  at: string;
129
+ } | {
130
+ type: 'compaction_start';
131
+ reason: 'threshold' | 'overflow' | 'manual';
132
+ method: 'heuristic' | 'llm';
133
+ at: string;
134
+ } | {
135
+ type: 'compaction_end';
136
+ reason: 'threshold' | 'overflow' | 'manual';
137
+ method: 'heuristic' | 'llm' | 'none';
138
+ compacted: boolean;
139
+ olderCount?: number;
140
+ keptCount?: number;
141
+ willRetry?: boolean;
142
+ error?: string;
143
+ at: string;
120
144
  } | {
121
145
  type: 'timeout';
122
146
  phase: 'turn' | 'tool' | 'model-stream';
@@ -32,6 +32,13 @@ export declare function lengthContinuationPrompt(): string;
32
32
  */
33
33
  export declare function completionRescuePrompt(): string;
34
34
  export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
35
+ /**
36
+ * Ephemeral control for read-only edit recovery: a failed file mutation
37
+ * requested a fresh read before any further mutation. Names the exact path
38
+ * so the model re-reads it instead of retrying the stale edit. The tool set
39
+ * stays intact; the execution-time gate in toolContext is the enforcer.
40
+ */
41
+ export declare function editRecoveryReadPrompt(path: string): string;
35
42
  /**
36
43
  * Ephemeral control for a goal-continuation slice or a fresh continuation
37
44
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -88,6 +88,15 @@ export function malformedToolCallPrompt(toolName, chunkBytes) {
88
88
  : '';
89
89
  return `The ${toolName} call had invalid, malformed, or truncated JSON input and did not execute. Retry it now with valid smaller arguments; do not merely announce that you will retry.${chunkGuidance}`;
90
90
  }
91
+ /**
92
+ * Ephemeral control for read-only edit recovery: a failed file mutation
93
+ * requested a fresh read before any further mutation. Names the exact path
94
+ * so the model re-reads it instead of retrying the stale edit. The tool set
95
+ * stays intact; the execution-time gate in toolContext is the enforcer.
96
+ */
97
+ export function editRecoveryReadPrompt(path) {
98
+ return `A file mutation on ${path} failed and its content may be stale. Read ${path} with readFile now to get fresh content and current line numbers; the edit tools will reject any retry on ${path} until that read completes. Then retry the mutation once with corrected, fresh content. Do not retry the failed edit first and do not announce tool calls.`;
99
+ }
91
100
  /**
92
101
  * Ephemeral control for a goal-continuation slice or a fresh continuation
93
102
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -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[];
@@ -0,0 +1,91 @@
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
+ import { inputLikeTokens } from './contextBudget.js';
19
+ /** Provider error shapes that indicate the request exceeded the context window. */
20
+ const OVERFLOW_PATTERNS = [
21
+ /prompt is too long/i, // Anthropic: "prompt is too long: 213462 tokens > 200000 maximum"
22
+ /request_too_large/i, // Anthropic HTTP 413 request_too_large
23
+ /input is too long for requested model/i, // Amazon Bedrock
24
+ /exceeds the context window/i, // OpenAI (Completions & Responses)
25
+ /exceeds (?:the )?(?:model'?s )?maximum context length/i, // OpenAI/LiteLLM
26
+ /input token count.*exceeds the maximum/i, // Google Gemini
27
+ /maximum prompt length is \d+/i, // xAI Grok
28
+ /reduce the length of the messages/i, // Groq
29
+ /maximum context length is \d+ tokens/i, // OpenRouter (most backends)
30
+ /exceeds (?:the )?maximum allowed input length/i, // OpenRouter/Poolside
31
+ /input \(\d+ tokens\) is longer than the model'?s context length/i, // Together AI
32
+ /exceeds the limit of \d+/i, // GitHub Copilot
33
+ /exceeds the available context size/i, // llama.cpp server
34
+ /greater than the context length/i, // LM Studio
35
+ /context window exceeds limit/i, // MiniMax
36
+ /exceeded model token limit/i, // Kimi
37
+ /too large for model with \d+ maximum context length/i, // Mistral
38
+ /prompt has [\d,]+ tokens?, but the configured context size is/i, // DS4
39
+ /model_context_window_exceeded/i, // z.ai finish_reason surfaced as error text
40
+ /prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow
41
+ /range of input length should be/i, // DashScope / Qwen
42
+ /context[_ ]length[_ ]exceeded/i, // Generic fallback
43
+ /too many tokens/i, // Generic fallback
44
+ /token limit exceeded/i, // Generic fallback
45
+ /^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 400/413 with no body
46
+ ];
47
+ /**
48
+ * Error shapes that look like overflow but are not (rate limiting and other
49
+ * transient throttles). Checked before the overflow patterns so a throttling
50
+ * message containing "too many tokens" cannot trigger compaction.
51
+ */
52
+ const NON_OVERFLOW_PATTERNS = [
53
+ /^(?:throttling|service unavailable)/i, // AWS Bedrock throttling/unavailable prefixes (raw ThrottlingException and formatted variants)
54
+ /rate limit/i,
55
+ /too many requests/i,
56
+ ];
57
+ /** Does an error text indicate a provider context-window overflow? */
58
+ export function errorIndicatesContextOverflow(text) {
59
+ if (NON_OVERFLOW_PATTERNS.some(pattern => pattern.test(text)))
60
+ return false;
61
+ return OVERFLOW_PATTERNS.some(pattern => pattern.test(text));
62
+ }
63
+ /**
64
+ * Silent overflow: the request succeeded but the reported input already
65
+ * exceeded the model's context window (some gateways accept and stream an
66
+ * answer anyway; the next request will fail or be truncated). The input-like
67
+ * term is convention-robust (see `inputLikeTokens`): subset-style cached
68
+ * tokens inside `inputTokens` are never double counted, so a cache-heavy
69
+ * successful finish cannot false-positive.
70
+ */
71
+ export function isSilentContextOverflow(input) {
72
+ if (input.contextWindowTokens <= 0)
73
+ return false;
74
+ return inputLikeTokens(input) > input.contextWindowTokens;
75
+ }
76
+ /**
77
+ * Length-stop overflow: the server truncated the oversized input to fit the
78
+ * window, leaving no room to generate — a `length` finish with zero output and
79
+ * input filling (≥99% of) the window.
80
+ */
81
+ export function isLengthStopOverflow(input) {
82
+ if (input.finishReason !== 'length' || (input.outputTokens ?? 0) > 0)
83
+ return false;
84
+ if (input.contextWindowTokens <= 0)
85
+ return false;
86
+ return inputLikeTokens(input) >= input.contextWindowTokens * 0.99;
87
+ }
88
+ /** Overflow patterns exposed for pinning tests. */
89
+ export function getOverflowPatterns() {
90
+ return OVERFLOW_PATTERNS;
91
+ }
@@ -1,9 +1,28 @@
1
1
  import type { ProviderCapabilities } from '../subagent/contracts.js';
2
2
  /**
3
- * Provider-neutral reasoning-depth setting. Unset by default; explicitly user
4
- * controlled. Mapped to a supported provider protocol (not a model name).
3
+ * Provider-neutral reasoning-depth levels (the AI SDK `reasoning` enum minus
4
+ * `provider-default`). `'none'` is an explicit request to disable reasoning;
5
+ * the stored `provider-default` sentinel means "send no parameter at all".
5
6
  */
6
- export type ReasoningLevel = 'low' | 'medium' | 'high';
7
+ export type ReasoningLevel = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
8
+ export declare const REASONING_LEVELS: readonly ReasoningLevel[];
9
+ /**
10
+ * Level applied when settings carry no `reasoning` key. Users opt out with an
11
+ * explicit `none` (reasoning off) or the stored `provider-default` sentinel
12
+ * (written by `/reasoning unset`); key-absent means this default.
13
+ */
14
+ export declare const DEFAULT_REASONING_LEVEL: ReasoningLevel;
15
+ /** Value the settings file may store: a level or the `provider-default` sentinel. */
16
+ export type StoredReasoningSetting = ReasoningLevel | 'provider-default';
17
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
18
+ export declare const REASONING_PROVIDER_DEFAULT: "provider-default";
19
+ export declare function isStoredReasoning(value: unknown): value is StoredReasoningSetting;
20
+ /**
21
+ * The level a session actually requests: the stored setting when present, the
22
+ * default when the key is absent. The `provider-default` sentinel maps to
23
+ * undefined — no parameter is sent.
24
+ */
25
+ export declare function effectiveRequestedReasoning(setting: StoredReasoningSetting | undefined): ReasoningLevel | undefined;
7
26
  export type EffectiveReasoning = ReasoningLevel | 'disabled';
8
27
  export interface ResolvedReasoningPolicy {
9
28
  /** What the user requested, if anything. */
@@ -15,17 +34,34 @@ export interface ResolvedReasoningPolicy {
15
34
  }
16
35
  /**
17
36
  * Resolve a requested reasoning level against provider capabilities. Pure and
18
- * capability based: only protocols that accept the OpenAI `reasoningEffort`
19
- * provider option receive a level; everything else is disabled (never silently
20
- * passed in a shape the protocol does not define). No model-name branching.
37
+ * capability based: only protocols that accept the reasoning parameter receive
38
+ * a level; everything else is disabled (the parameter is omitted entirely,
39
+ * never sent in a shape the protocol does not define). No model-name branching.
21
40
  */
22
41
  export declare function resolveReasoningPolicy(input: {
23
42
  requested: ReasoningLevel | undefined;
24
43
  capabilities: ProviderCapabilities;
25
44
  }): ResolvedReasoningPolicy;
26
45
  /**
27
- * The provider-option fragment to merge into request settings for a resolved
28
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
46
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
47
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
48
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
49
+ * stays in the return type for forward compatibility.
29
50
  */
30
- export declare function reasoningProviderOptions(policy: ResolvedReasoningPolicy): Record<string, unknown> | undefined;
51
+ export declare function reasoningCallSetting(policy: ResolvedReasoningPolicy): ReasoningLevel | 'provider-default' | undefined;
31
52
  export declare function isReasoningLevel(value: unknown): value is ReasoningLevel;
53
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
54
+ export declare function isReasoningUnsetAlias(value: string): boolean;
55
+ export type ParsedReasoningOverride = {
56
+ ok: true;
57
+ setting: StoredReasoningSetting;
58
+ } | {
59
+ ok: false;
60
+ error: string;
61
+ };
62
+ /**
63
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
64
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
65
+ * the commander flag surface and the headless option validation.
66
+ */
67
+ export declare function parseReasoningOverride(raw: string): ParsedReasoningOverride;