@denizokcu/haze 0.10.0 → 0.11.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 (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -0,0 +1,287 @@
1
+ import { MAIN_TOOL_ONLY_STEP_LIMIT } from './budgets.js';
2
+ import { intentExpectsValidation } from './workState.js';
3
+ export function normalizeFinishReason(finishReason) {
4
+ switch (finishReason) {
5
+ case 'stop': return 'stop';
6
+ case 'length': return 'length';
7
+ case 'tool-calls': return 'tool-calls';
8
+ case 'error': return 'error';
9
+ case 'content-filter': return 'content-filter';
10
+ default: return 'unknown';
11
+ }
12
+ }
13
+ export function createTurnExecutionState() {
14
+ return {
15
+ stepsUsed: 0,
16
+ toolCallsUsed: 0,
17
+ toolOnlyStepsUsed: 0,
18
+ finishCause: undefined,
19
+ lengthCreditUsed: false,
20
+ lengthRecoveriesAttempted: 0,
21
+ rescueUsed: false,
22
+ mutationCount: 0,
23
+ validationOutcome: 'absent',
24
+ validationKind: undefined,
25
+ validationAfterMutation: false,
26
+ intent: 'unknown',
27
+ taskProgress: undefined,
28
+ goalContinuationsUsed: 0,
29
+ goalContinuationProgress: undefined,
30
+ goalContinuationCorrectiveUsed: false,
31
+ budgetBoundary: false,
32
+ aborted: false,
33
+ };
34
+ }
35
+ /** Project the turn-wide state into the safe evidence shape. */
36
+ export function toCompletionEvidence(state) {
37
+ return {
38
+ validationOutcome: state.validationOutcome,
39
+ ...(state.validationKind ? { validationKind: state.validationKind } : {}),
40
+ validationAfterMutation: state.validationAfterMutation,
41
+ mutationCount: state.mutationCount,
42
+ ...(state.taskProgress ? { taskProgress: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
43
+ finishCause: state.finishCause,
44
+ recoveryUsed: { length: state.lengthCreditUsed, rescue: state.rescueUsed, goal: state.goalContinuationsUsed },
45
+ budgetBoundary: state.budgetBoundary,
46
+ };
47
+ }
48
+ /**
49
+ * Pure completion-readiness assessment. Priority: abort, unresolved tool
50
+ * input, failed tool, declared task progress, then intent-sensitive validation
51
+ * policy (implement/fix/test turns with successful mutations require fresh
52
+ * passing validation; plan/review/answer turns never do). A task list is
53
+ * enforced only when this turn declared one via a successful writeTasks call.
54
+ */
55
+ export function assessCompletionReadiness(state, evidence) {
56
+ if (state.aborted)
57
+ return 'aborted';
58
+ if (evidence.unresolvedToolInputError)
59
+ return 'unresolved_tool_input';
60
+ if (evidence.lastToolOk === false)
61
+ return 'tool_failure';
62
+ if (state.taskProgress && (state.taskProgress.pending > 0 || state.taskProgress.inProgress > 0))
63
+ return 'pending_tasks';
64
+ if (intentExpectsValidation(state.intent)) {
65
+ if (state.validationOutcome === 'failed')
66
+ return 'validation_failed';
67
+ if (state.validationOutcome === 'stale')
68
+ return 'validation_stale';
69
+ if (state.validationOutcome === 'absent' && state.mutationCount > 0)
70
+ return 'validation_absent_after_mutation';
71
+ }
72
+ return 'ready';
73
+ }
74
+ /** Human-readable, safe (no commands/content) description of a readiness result. */
75
+ export function describeCompletionReadiness(readiness, taskProgress) {
76
+ switch (readiness) {
77
+ case 'pending_tasks': {
78
+ const open = taskProgress ? taskProgress.pending + taskProgress.inProgress : 0;
79
+ return `${open} declared task${open === 1 ? '' : 's'} still pending or in progress`;
80
+ }
81
+ case 'validation_failed': return 'the latest validation failed and remains unresolved';
82
+ case 'validation_stale': return 'edits landed after the latest validation';
83
+ case 'validation_absent_after_mutation': return 'edits landed without any relevant validation';
84
+ case 'tool_failure': return 'the last tool call failed';
85
+ case 'unresolved_tool_input': return 'a tool call never executed because its input was invalid';
86
+ case 'aborted': return 'the turn was aborted';
87
+ case 'ready': return 'declared work is complete';
88
+ }
89
+ }
90
+ /**
91
+ * True when the turn-wide budget is exhausted. Expressed against turn-wide
92
+ * counters so a retry or recovery slice observes prior usage and the global
93
+ * budget cannot be reset or exceeded. A `length` finish counts as exhausted
94
+ * for the *terminal* status (the output was truncated); recovery uses
95
+ * `hasRemainingRecoveryBudget` instead, because a length finish often leaves
96
+ * plenty of step/tool budget.
97
+ */
98
+ export function isBudgetExhausted(state, budget) {
99
+ return state.finishCause === 'length'
100
+ || state.stepsUsed >= budget.stepLimit
101
+ || state.toolCallsUsed >= budget.toolCallLimit
102
+ || state.toolOnlyStepsUsed >= budget.toolOnlyStepLimit;
103
+ }
104
+ /** Whether step/tool-call resources remain for a recovery slice (length finish excluded). */
105
+ export function hasRemainingRecoveryBudget(state, budget) {
106
+ return state.stepsUsed < budget.stepLimit && state.toolCallsUsed < budget.toolCallLimit;
107
+ }
108
+ /**
109
+ * Authoritative terminal turn status. This is the pure, unit-testable core of
110
+ * the old inline `terminalTurnStatus` in the CLI layer; the CLI wrapper still
111
+ * owns the single call site.
112
+ *
113
+ * `budgetExhausted` is supplied by the caller (typically via `isBudgetExhausted`)
114
+ * so this function stays free of budget-wiring details and a turn-wide caller
115
+ * and a per-slice caller can share one decision.
116
+ *
117
+ * Increment 1 reproduces historical behavior exactly: a `length` finish is a
118
+ * failure (length-continuation lands in Increment 2 and only flips on when a
119
+ * recovery credit is both available and warranted).
120
+ */
121
+ export function decideTerminalStatus(state, evidence, budgetExhausted) {
122
+ if (state.aborted)
123
+ return 'aborted';
124
+ if (budgetExhausted || state.finishCause === 'length' || state.finishCause === 'error')
125
+ return 'failed';
126
+ if (assessCompletionReadiness(state, evidence) !== 'ready')
127
+ return 'failed';
128
+ if (evidence.sawToolCall && evidence.assistantText.trim().length === 0)
129
+ return 'failed';
130
+ return evidence.assistantText.trim().length > 0 ? 'complete' : 'failed';
131
+ }
132
+ /** Length-continuation slice cap: four model steps / four tool calls (global). */
133
+ export const LENGTH_RECOVERY_SLICE = { steps: 4, toolCalls: 4 };
134
+ /** Completion-rescue slice: one tool-bearing step (≤2 calls) + one synthesis step. */
135
+ export const RESCUE_SLICE = { steps: 2, toolCalls: 2 };
136
+ /** Number of trailing tool-only slots reserved for the rescue slice. */
137
+ export const RESCUE_RESERVE = 1;
138
+ /** Tool-only boundary at which rescue becomes eligible (normal exploration stops here). */
139
+ export const RESCUE_BOUNDARY = MAIN_TOOL_ONLY_STEP_LIMIT - RESCUE_RESERVE;
140
+ /**
141
+ * Length-continuation decision. Fires once per turn when an output-length finish
142
+ * truncates the response, the turn is not aborted, the credit is unused, the
143
+ * global budget still has room, and the work is not already satisfactorily
144
+ * validated (a fresh passing validation means the artifact landed). A repeated
145
+ * length finish terminates cleanly because the credit is single-use.
146
+ */
147
+ export function decideLengthRecovery(state, budget) {
148
+ const stop = (reason) => ({ action: 'stop', reason, slice: LENGTH_RECOVERY_SLICE });
149
+ if (state.aborted)
150
+ return stop('turn aborted');
151
+ if (state.finishCause !== 'length')
152
+ return stop('finish is not a length truncation');
153
+ if (state.lengthCreditUsed)
154
+ return stop('length-continuation credit already used');
155
+ if (!hasRemainingRecoveryBudget(state, budget))
156
+ return stop('global budget exhausted');
157
+ if (state.validationOutcome === 'passed')
158
+ return stop('fresh passing validation already observed');
159
+ return { action: 'continue', reason: 'output-length finish with budget remaining', slice: LENGTH_RECOVERY_SLICE };
160
+ }
161
+ /**
162
+ * Whether a request intent has a deliverable the rescue slice could apply or
163
+ * validate. Deliberately matches `intentExpectsValidation` so a test-orchestration
164
+ * turn (F-04) gets the same bounded rescue as implement/fix: a `test` finish is
165
+ * driven by tool runs exactly like the intents `decideRescue` already serves.
166
+ */
167
+ export function rescueEligibleRequest(intent) {
168
+ return intentExpectsValidation(intent);
169
+ }
170
+ /**
171
+ * Completion-rescue decision near the tool-only boundary. Fires once when normal
172
+ * exploration exhausted the (reserved) tool-only slots without producing a
173
+ * substantive answer, the turn is not aborted, the rescue credit is unused, and
174
+ * the global budget still has room. Rescue never reopens discovery and never
175
+ * extends the global budget.
176
+ */
177
+ export function decideRescue(state, evidence, budget, isMutatingRequest) {
178
+ const stop = (reason) => ({ action: 'stop', reason, slice: RESCUE_SLICE });
179
+ if (state.aborted)
180
+ return stop('turn aborted');
181
+ if (state.rescueUsed)
182
+ return stop('rescue credit already used');
183
+ if (state.finishCause !== 'stop' && state.finishCause !== 'tool-calls' && state.finishCause !== 'length')
184
+ return stop('finish is not a normal/tool boundary stop');
185
+ if (!isMutatingRequest)
186
+ return stop('request has no deliverable to apply');
187
+ if (state.toolOnlyStepsUsed < RESCUE_BOUNDARY)
188
+ return stop('not near the tool-only boundary');
189
+ if (hasSatisfactoryTerminalOutcome(state, evidence))
190
+ return stop('substantive terminal outcome already present');
191
+ if (!hasRemainingRecoveryBudget(state, budget))
192
+ return stop('global budget exhausted');
193
+ return { action: 'continue', reason: 'near tool-only boundary with no substantive answer', slice: RESCUE_SLICE };
194
+ }
195
+ /** Goal-continuation slice: real per-cycle work headroom, clamped to remaining global budget. */
196
+ export const GOAL_CONTINUATION_SLICE = { steps: 6, toolCalls: 12 };
197
+ /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
198
+ /** Readiness reasons a bounded continuation can plausibly resolve with more work. */
199
+ export function goalContinuationRecoverable(readiness) {
200
+ return readiness === 'pending_tasks'
201
+ || readiness === 'validation_failed'
202
+ || readiness === 'validation_stale'
203
+ || readiness === 'validation_absent_after_mutation';
204
+ }
205
+ /**
206
+ * Normal provider finishes that can still represent recoverable unfinished
207
+ * work. `stop` is a voluntary final; `tool-calls` is a step/slice budget
208
+ * boundary (often with a runtime-forced progress line); `length` is output
209
+ * truncation; `unknown` is an unmapped but non-erroneous finish. `error` and
210
+ * `content-filter` stay hard: they are provider failures, not work states.
211
+ */
212
+ const RECOVERABLE_FINISH_CAUSES = new Set(['stop', 'tool-calls', 'length', 'unknown']);
213
+ export function isRecoverableFinishCause(finishCause) {
214
+ return finishCause != null && RECOVERABLE_FINISH_CAUSES.has(finishCause);
215
+ }
216
+ export function classifyTerminalOutcome(state, evidence) {
217
+ if (state.aborted)
218
+ return 'user-aborted';
219
+ const readiness = assessCompletionReadiness(state, evidence);
220
+ if (readiness === 'ready') {
221
+ return evidence.assistantText.trim().length > 0 && state.finishCause === 'stop' ? 'goal-complete' : 'hard-blocked';
222
+ }
223
+ if (!goalContinuationRecoverable(readiness))
224
+ return 'hard-blocked';
225
+ return isRecoverableFinishCause(state.finishCause) ? 'recoverable-incomplete' : 'hard-blocked';
226
+ }
227
+ /** Compact signature of measurable work: mutations, validation outcome/kind, task counts. */
228
+ export function goalProgressSignature(state) {
229
+ const tasks = state.taskProgress;
230
+ return JSON.stringify([state.mutationCount, state.validationOutcome, state.validationKind ?? '', tasks ? [tasks.revision, tasks.pending, tasks.inProgress, tasks.completed] : null]);
231
+ }
232
+ /**
233
+ * Record that a goal-continuation slice was issued. Progress since the previous
234
+ * continuation (work/task signature comparison) decides whether this issuance
235
+ * is the single allowed corrective nudge; a second no-progress stop then
236
+ * terminates as failed (see `decideGoalContinuation`). Never resets counters.
237
+ */
238
+ export function recordGoalContinuation(state) {
239
+ const signature = goalProgressSignature(state);
240
+ state.goalContinuationCorrectiveUsed = state.goalContinuationProgress != null && signature === state.goalContinuationProgress;
241
+ state.goalContinuationProgress = signature;
242
+ state.goalContinuationsUsed += 1;
243
+ }
244
+ /**
245
+ * Goal-continuation decision for a `recoverable-incomplete` attempt with a
246
+ * substantive answer to reject: continue in-turn with a slice when the global
247
+ * budget and progress guard allow it. Any other outcome is the caller's signal
248
+ * to end the physical turn — the goal-level invariant (failed + recoverable +
249
+ * no same-turn recovery → `incomplete-goal` checkpoint) is enforced by the
250
+ * caller via `classifyTerminalOutcome`, not here. Never resets budgets.
251
+ */
252
+ export function decideGoalContinuation(state, evidence, budget) {
253
+ const stop = (reason) => ({ action: 'stop', reason, slice: GOAL_CONTINUATION_SLICE });
254
+ if (state.aborted)
255
+ return stop('turn aborted');
256
+ if (!isRecoverableFinishCause(state.finishCause))
257
+ return stop('finish shape is not recoverable');
258
+ if (evidence.assistantText.trim().length === 0)
259
+ return stop('no substantive final to reject');
260
+ if (evidence.lastToolOk === false || evidence.unresolvedToolInputError)
261
+ return stop('unresolved tool failure');
262
+ const readiness = assessCompletionReadiness(state, evidence);
263
+ if (readiness === 'ready')
264
+ return stop('completion readiness satisfied');
265
+ if (!goalContinuationRecoverable(readiness))
266
+ return stop(`readiness '${readiness}' is not autonomously recoverable`);
267
+ if (!hasRemainingRecoveryBudget(state, budget))
268
+ return stop('global budget exhausted');
269
+ if (state.goalContinuationProgress != null && goalProgressSignature(state) === state.goalContinuationProgress && state.goalContinuationCorrectiveUsed) {
270
+ return stop('no measurable progress after the corrective nudge');
271
+ }
272
+ return { action: 'continue', reason: `premature final rejected: ${readiness}`, slice: GOAL_CONTINUATION_SLICE };
273
+ }
274
+ /**
275
+ * Does the turn have a satisfactory terminal outcome that should stop recovery?
276
+ * A substantive assistant answer is satisfactory only when the structured
277
+ * completion evidence agrees: declared tasks finished, no unresolved tool
278
+ * failure, and (for validation-bearing intents) fresh validation after edits.
279
+ * Used by recovery guards so a normal successful turn makes no extra model call.
280
+ */
281
+ export function hasSatisfactoryTerminalOutcome(state, evidence) {
282
+ if (state.aborted)
283
+ return true;
284
+ if (evidence.assistantText.trim().length === 0)
285
+ return false;
286
+ return assessCompletionReadiness(state, evidence) === 'ready';
287
+ }
@@ -1,6 +1,20 @@
1
1
  import type { ModelMessage } from 'ai';
2
2
  import type { ContextFile } from '../../config/contextFiles.js';
3
3
  export declare const DEFAULT_CHARS_PER_TOKEN = 4;
4
+ /**
5
+ * Conservative fallback context window for a hosted model with no metadata
6
+ * (RH-005). 128K is the floor for current capable hosted models (GPT-4o class,
7
+ * older Claude, fine-tunes); assuming more risks hard request failures on
8
+ * exactly-128K models, while assuming less only compacts earlier. Local
9
+ * servers use a smaller fallback (see FALLBACK_LOCAL_CONTEXT_TOKENS) because
10
+ * their effective window is set by server configuration (often 4–32K), not the
11
+ * model, and silent truncation there is undetectable.
12
+ */
13
+ export declare const FALLBACK_CONTEXT_WINDOW_TOKENS = 128000;
14
+ /** Fallback window for unknown models on local (localhost) inference servers. */
15
+ export declare const FALLBACK_LOCAL_CONTEXT_TOKENS = 32768;
16
+ /** Safety margin reserved below the computed budget to absorb estimate drift. */
17
+ export declare const CONTEXT_SAFETY_MARGIN_TOKENS = 1000;
4
18
  /**
5
19
  * Rough vision estimate for attached images: providers bill images by
6
20
  * resolution, not by serialized bytes. ~750 bytes per token matches common
@@ -27,6 +41,9 @@ export interface ContextBreakdown {
27
41
  export declare function estimateTextTokens(text: string): number;
28
42
  export declare function estimateImagePartTokens(part: unknown): number;
29
43
  export declare function estimateValueTokens(value: unknown): number;
44
+ export declare function estimateModelMessageTokens(message: ModelMessage): number;
45
+ /** Sum of per-message estimates for a history array, memoized per message object. */
46
+ export declare function estimateMessagesTokens(messages: readonly ModelMessage[]): number;
30
47
  export declare function estimateToolSchemas(tools?: Record<string, unknown>): {
31
48
  name: string;
32
49
  tokens: number;
@@ -39,3 +56,24 @@ export declare function contextBreakdown(input: {
39
56
  }): ContextBreakdown;
40
57
  export declare function effectiveNonCachedInput(inputTokens: number | undefined, cacheReadTokens: number): number | undefined;
41
58
  export declare function cacheHitRatio(inputTokens: number | undefined, cacheReadTokens: number | undefined): number | undefined;
59
+ export interface RequestTokenBudget {
60
+ contextWindowTokens: number;
61
+ systemTokens: number;
62
+ toolSchemaTokens: number;
63
+ outputReserveTokens: number;
64
+ safetyMarginTokens: number;
65
+ /** Tokens available for the message history. */
66
+ messageTokens: number;
67
+ }
68
+ /**
69
+ * Compute the message-token allowance for a request from the full input
70
+ * breakdown: context window minus system prompt, tool schemas, output reserve,
71
+ * and a safety margin (RH-005). Falls back to a conservative window when a
72
+ * model declares no capacity metadata.
73
+ */
74
+ export declare function calculateRequestTokenBudget(input: {
75
+ contextWindowTokens?: number;
76
+ requestedOutputTokens: number;
77
+ system: string;
78
+ tools: Record<string, unknown>;
79
+ }): RequestTokenBudget;
@@ -1,6 +1,20 @@
1
1
  import { z } from 'zod';
2
2
  import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
3
3
  export const DEFAULT_CHARS_PER_TOKEN = 4;
4
+ /**
5
+ * Conservative fallback context window for a hosted model with no metadata
6
+ * (RH-005). 128K is the floor for current capable hosted models (GPT-4o class,
7
+ * older Claude, fine-tunes); assuming more risks hard request failures on
8
+ * exactly-128K models, while assuming less only compacts earlier. Local
9
+ * servers use a smaller fallback (see FALLBACK_LOCAL_CONTEXT_TOKENS) because
10
+ * their effective window is set by server configuration (often 4–32K), not the
11
+ * model, and silent truncation there is undetectable.
12
+ */
13
+ export const FALLBACK_CONTEXT_WINDOW_TOKENS = 128_000;
14
+ /** Fallback window for unknown models on local (localhost) inference servers. */
15
+ export const FALLBACK_LOCAL_CONTEXT_TOKENS = 32_768;
16
+ /** Safety margin reserved below the computed budget to absorb estimate drift. */
17
+ export const CONTEXT_SAFETY_MARGIN_TOKENS = 1_000;
4
18
  /**
5
19
  * Rough vision estimate for attached images: providers bill images by
6
20
  * resolution, not by serialized bytes. ~750 bytes per token matches common
@@ -42,6 +56,36 @@ export function estimateValueTokens(value) {
42
56
  return estimateTextTokens(String(value));
43
57
  }
44
58
  }
59
+ /**
60
+ * Per-message token estimates memoized by object identity (F-07). History
61
+ * messages are treated as immutable everywhere in haze (compaction and
62
+ * synthetic-control wrapping produce new objects; response messages arrive
63
+ * fresh from the SDK), so a `prepareStep` that re-estimates the full history
64
+ * every provider call re-uses cached per-message values instead of
65
+ * re-stringifying the whole array each step.
66
+ */
67
+ const messageTokenEstimates = new WeakMap();
68
+ export function estimateModelMessageTokens(message) {
69
+ const cached = messageTokenEstimates.get(message);
70
+ if (cached !== undefined)
71
+ return cached;
72
+ const tokens = estimateValueTokens(message);
73
+ messageTokenEstimates.set(message, tokens);
74
+ return tokens;
75
+ }
76
+ /** Sum of per-message estimates for a history array, memoized per message object. */
77
+ export function estimateMessagesTokens(messages) {
78
+ let total = 0;
79
+ for (const message of messages)
80
+ total += estimateModelMessageTokens(message);
81
+ return total;
82
+ }
83
+ export function estimateToolSchemas(tools = {}) {
84
+ return Object.entries(tools).map(([name, value]) => ({
85
+ name,
86
+ tokens: estimateTextTokens(toolSchemaText(value)),
87
+ }));
88
+ }
45
89
  function toolSchemaText(toolValue) {
46
90
  if (typeof toolValue !== 'object' || toolValue == null)
47
91
  return '';
@@ -58,12 +102,6 @@ function toolSchemaText(toolValue) {
58
102
  inputSchema: schema,
59
103
  });
60
104
  }
61
- export function estimateToolSchemas(tools = {}) {
62
- return Object.entries(tools).map(([name, value]) => ({
63
- name,
64
- tokens: estimateTextTokens(toolSchemaText(value)),
65
- }));
66
- }
67
105
  function contentParts(message) {
68
106
  return Array.isArray(message.content) ? message.content : [];
69
107
  }
@@ -87,7 +125,7 @@ export function contextBreakdown(input) {
87
125
  const toolResults = {};
88
126
  let syntheticControl = 0;
89
127
  for (const message of input.messages) {
90
- const tokens = estimateValueTokens(message);
128
+ const tokens = estimateModelMessageTokens(message);
91
129
  messagesByRole[message.role] = (messagesByRole[message.role] ?? 0) + tokens;
92
130
  if (message.role === 'user' && typeof message.content === 'string' && message.content.startsWith('<haze_control>')) {
93
131
  syntheticControl += tokens;
@@ -115,3 +153,18 @@ export function cacheHitRatio(inputTokens, cacheReadTokens) {
115
153
  return undefined;
116
154
  return cacheReadTokens / inputTokens;
117
155
  }
156
+ /**
157
+ * Compute the message-token allowance for a request from the full input
158
+ * breakdown: context window minus system prompt, tool schemas, output reserve,
159
+ * and a safety margin (RH-005). Falls back to a conservative window when a
160
+ * model declares no capacity metadata.
161
+ */
162
+ export function calculateRequestTokenBudget(input) {
163
+ const contextWindowTokens = input.contextWindowTokens ?? FALLBACK_CONTEXT_WINDOW_TOKENS;
164
+ const systemTokens = estimateTextTokens(input.system);
165
+ const toolSchemaTokens = estimateToolSchemas(input.tools).reduce((sum, tool) => sum + tool.tokens, 0);
166
+ const outputReserveTokens = input.requestedOutputTokens;
167
+ const safetyMarginTokens = CONTEXT_SAFETY_MARGIN_TOKENS;
168
+ const messageTokens = Math.max(0, contextWindowTokens - systemTokens - toolSchemaTokens - outputReserveTokens - safetyMarginTokens);
169
+ return { contextWindowTokens, systemTokens, toolSchemaTokens, outputReserveTokens, safetyMarginTokens, messageTokens };
170
+ }
@@ -1,3 +1,12 @@
1
+ import type { TurnCompletionEvidence } from './completionController.js';
2
+ import type { EffectiveReasoning, ReasoningLevel } from './reasoningPolicy.js';
3
+ export interface AgentStepUsage {
4
+ inputTokens: number;
5
+ outputTokens: number;
6
+ cacheReadTokens: number;
7
+ cacheWriteTokens: number;
8
+ reasoningTokens: number;
9
+ }
1
10
  export type AgentEvent = {
2
11
  type: 'turn_start';
3
12
  request: string;
@@ -7,6 +16,39 @@ export type AgentEvent = {
7
16
  request: string;
8
17
  at: string;
9
18
  status: 'complete' | 'aborted' | 'failed';
19
+ evidence?: TurnCompletionEvidence;
20
+ } | {
21
+ type: 'goal_start';
22
+ goalId: string;
23
+ request: string;
24
+ at: string;
25
+ } | {
26
+ type: 'goal_continue';
27
+ goalId: string;
28
+ cycle: number;
29
+ reason: string;
30
+ at: string;
31
+ } | {
32
+ type: 'goal_end';
33
+ goalId: string;
34
+ at: string;
35
+ status: 'complete' | 'failed' | 'aborted';
36
+ cycles: number;
37
+ stopReason?: string;
38
+ evidence?: TurnCompletionEvidence;
39
+ } | {
40
+ type: 'step_start';
41
+ attempt: number;
42
+ step: number;
43
+ at: string;
44
+ } | {
45
+ type: 'step_end';
46
+ attempt: number;
47
+ step: number;
48
+ finishReason: string;
49
+ toolCallCount: number;
50
+ usage: AgentStepUsage;
51
+ at: string;
10
52
  } | {
11
53
  type: 'message_start';
12
54
  id: string;
@@ -35,6 +77,7 @@ export type AgentEvent = {
35
77
  name: string;
36
78
  success: boolean;
37
79
  output?: unknown;
80
+ errorCode?: string;
38
81
  error?: unknown;
39
82
  durationMs: number;
40
83
  at: string;
@@ -45,11 +88,42 @@ export type AgentEvent = {
45
88
  delayMs: number;
46
89
  error: string;
47
90
  at: string;
91
+ } | {
92
+ type: 'reasoning_policy';
93
+ requested?: ReasoningLevel;
94
+ effective: EffectiveReasoning;
95
+ reason: string;
96
+ at: string;
97
+ } | {
98
+ type: 'context_budget';
99
+ contextWindowTokens: number;
100
+ source: 'settings' | 'user-fallback' | 'default-fallback';
101
+ at: string;
48
102
  } | {
49
103
  type: 'context_overflow';
50
104
  recovered: boolean;
51
105
  error: string;
52
106
  at: string;
107
+ } | {
108
+ type: 'timeout';
109
+ phase: 'turn' | 'tool' | 'model-stream';
110
+ timeoutMs: number;
111
+ /**
112
+ * Model-stream stall diagnostics (phase 'model-stream' only). Safe metadata
113
+ * only — provider/model names, timestamps, enums, work phase — never prompt
114
+ * content or credentials.
115
+ */
116
+ provider?: string;
117
+ model?: string;
118
+ lastStreamEventAt?: string;
119
+ lastStreamEventType?: string;
120
+ /** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
121
+ stallEmission?: 'none' | 'text' | 'tool';
122
+ /** Active work-state phase when the stall was detected. */
123
+ workPhase?: string;
124
+ /** Whether the stall rides the bounded model-retry pool. */
125
+ retryEligible?: boolean;
126
+ at: string;
53
127
  } | {
54
128
  type: 'subagent_state';
55
129
  id: string;
@@ -0,0 +1,31 @@
1
+ import type { ProviderCapabilities } from '../subagent/contracts.js';
2
+ /**
3
+ * Provider-neutral reasoning-depth setting. Unset by default; explicitly user
4
+ * controlled. Mapped to a supported provider protocol (not a model name).
5
+ */
6
+ export type ReasoningLevel = 'low' | 'medium' | 'high';
7
+ export type EffectiveReasoning = ReasoningLevel | 'disabled';
8
+ export interface ResolvedReasoningPolicy {
9
+ /** What the user requested, if anything. */
10
+ requested: ReasoningLevel | undefined;
11
+ /** What will actually be applied (a level, or 'disabled' when unsupported). */
12
+ effective: EffectiveReasoning;
13
+ /** Why effective differs from requested, when it does. */
14
+ reason: string;
15
+ }
16
+ /**
17
+ * 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.
21
+ */
22
+ export declare function resolveReasoningPolicy(input: {
23
+ requested: ReasoningLevel | undefined;
24
+ capabilities: ProviderCapabilities;
25
+ }): ResolvedReasoningPolicy;
26
+ /**
27
+ * The provider-option fragment to merge into request settings for a resolved
28
+ * policy. Returns undefined when disabled so unsupported protocols send nothing.
29
+ */
30
+ export declare function reasoningProviderOptions(policy: ResolvedReasoningPolicy): Record<string, unknown> | undefined;
31
+ export declare function isReasoningLevel(value: unknown): value is ReasoningLevel;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Resolve a requested reasoning level against provider capabilities. Pure and
3
+ * capability based: only protocols that accept the OpenAI `reasoningEffort`
4
+ * provider option receive a level; everything else is disabled (never silently
5
+ * passed in a shape the protocol does not define). No model-name branching.
6
+ */
7
+ export function resolveReasoningPolicy(input) {
8
+ const { requested, capabilities } = input;
9
+ if (!requested)
10
+ return { requested: undefined, effective: 'disabled', reason: 'no reasoning depth requested' };
11
+ if (!capabilities.supportsReasoningEffort)
12
+ return { requested, effective: 'disabled', reason: 'provider protocol does not support a reasoning-effort option' };
13
+ return { requested, effective: requested, reason: 'applied via supported provider protocol' };
14
+ }
15
+ /**
16
+ * The provider-option fragment to merge into request settings for a resolved
17
+ * policy. Returns undefined when disabled so unsupported protocols send nothing.
18
+ */
19
+ export function reasoningProviderOptions(policy) {
20
+ if (policy.effective === 'disabled')
21
+ return undefined;
22
+ return { openai: { reasoningEffort: policy.effective } };
23
+ }
24
+ const LEVELS = ['low', 'medium', 'high'];
25
+ export function isReasoningLevel(value) {
26
+ return typeof value === 'string' && LEVELS.includes(value);
27
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Static capability metadata for built-in tools.
3
+ *
4
+ * Capabilities describe what a tool *can do* so turn-policy code can reason
5
+ * about a turn without hard-coding tool names in every decision site. They are
6
+ * metadata for policy/observability, never an execution gate (mirroring the
7
+ * bash-classifier contract): the actual effect of a call is still determined at
8
+ * runtime (e.g. a `bash` call is only validation when its command is a
9
+ * classifier-confirmed validation command).
10
+ *
11
+ * Kept provider/UI-agnostic (no `ai`/Ink imports) so it is unit-testable in
12
+ * `tests/core/**` and reusable by the subagent flow.
13
+ */
14
+ export type ToolCapability = 'discovery' | 'read' | 'mutate' | 'validate' | 'process' | 'coordinate';
15
+ /**
16
+ * Capability set for a built-in tool name. Unknown/third-party tool names
17
+ * (MCP) return an empty set: their effects are not statically knowable, so
18
+ * policy code treats them conservatively.
19
+ */
20
+ export declare function toolCapability(name: string): readonly ToolCapability[];
21
+ export declare function hasCapability(name: string, capability: ToolCapability): boolean;
22
+ /** Tools whose successful call introduces a workspace mutation. */
23
+ export declare function isMutatingCapability(name: string): boolean;
24
+ /** Tools that can act as a validation step (runtime-classifier dependent). */
25
+ export declare function isValidationCapable(name: string): boolean;
26
+ /** Read/discovery-only built-in tools (no mutation side effects). */
27
+ export declare function isReadOrDiscoveryCapability(name: string): boolean;