@denizokcu/haze 0.9.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  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/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -1,11 +1,54 @@
1
1
  import { z } from 'zod';
2
+ import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
2
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;
18
+ /**
19
+ * Rough vision estimate for attached images: providers bill images by
20
+ * resolution, not by serialized bytes. ~750 bytes per token matches common
21
+ * screenshot encodings closely enough for budget/display estimates. Labeled
22
+ * as an estimate wherever it surfaces.
23
+ */
24
+ export const IMAGE_BYTES_PER_TOKEN_ESTIMATE = 750;
3
25
  export function estimateTextTokens(text) {
4
26
  return Math.ceil(text.length / DEFAULT_CHARS_PER_TOKEN);
5
27
  }
28
+ export function estimateImagePartTokens(part) {
29
+ if (!isImageFilePart(part))
30
+ return 0;
31
+ const bytes = imageFilePartBytes(part.data);
32
+ return bytes > 0 ? Math.max(1, Math.ceil(bytes / IMAGE_BYTES_PER_TOKEN_ESTIMATE)) : 1;
33
+ }
6
34
  export function estimateValueTokens(value) {
7
35
  if (typeof value === 'string')
8
36
  return estimateTextTokens(value);
37
+ // Image parts are estimated from their byte size; serializing megabytes of
38
+ // image data as JSON would blow up both memory and the token estimate.
39
+ if (isImageFilePart(value))
40
+ return estimateImagePartTokens(value);
41
+ if (Array.isArray(value))
42
+ return value.reduce((sum, item) => sum + estimateValueTokens(item), 0);
43
+ if (typeof value === 'object' && value != null && Array.isArray(value.content)) {
44
+ const message = value;
45
+ const envelope = {};
46
+ for (const [key, item] of Object.entries(message))
47
+ if (key !== 'content')
48
+ envelope[key] = item;
49
+ return estimateTextTokens(JSON.stringify(envelope))
50
+ + message.content.reduce((sum, part) => sum + estimateValueTokens(part), 0);
51
+ }
9
52
  try {
10
53
  return estimateTextTokens(JSON.stringify(value));
11
54
  }
@@ -13,6 +56,36 @@ export function estimateValueTokens(value) {
13
56
  return estimateTextTokens(String(value));
14
57
  }
15
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
+ }
16
89
  function toolSchemaText(toolValue) {
17
90
  if (typeof toolValue !== 'object' || toolValue == null)
18
91
  return '';
@@ -29,12 +102,6 @@ function toolSchemaText(toolValue) {
29
102
  inputSchema: schema,
30
103
  });
31
104
  }
32
- export function estimateToolSchemas(tools = {}) {
33
- return Object.entries(tools).map(([name, value]) => ({
34
- name,
35
- tokens: estimateTextTokens(toolSchemaText(value)),
36
- }));
37
- }
38
105
  function contentParts(message) {
39
106
  return Array.isArray(message.content) ? message.content : [];
40
107
  }
@@ -58,7 +125,7 @@ export function contextBreakdown(input) {
58
125
  const toolResults = {};
59
126
  let syntheticControl = 0;
60
127
  for (const message of input.messages) {
61
- const tokens = estimateValueTokens(message);
128
+ const tokens = estimateModelMessageTokens(message);
62
129
  messagesByRole[message.role] = (messagesByRole[message.role] ?? 0) + tokens;
63
130
  if (message.role === 'user' && typeof message.content === 'string' && message.content.startsWith('<haze_control>')) {
64
131
  syntheticControl += tokens;
@@ -86,3 +153,18 @@ export function cacheHitRatio(inputTokens, cacheReadTokens) {
86
153
  return undefined;
87
154
  return cacheReadTokens / inputTokens;
88
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
+ }
@@ -7,7 +7,11 @@ export function isContextOverflowError(error) {
7
7
  }
8
8
  export function isRetryableModelError(error) {
9
9
  const text = errorText(error);
10
- if (isContextOverflowError(error) || /quota|billing|balance|auth|api key|invalid request|permission|forbidden|401|403|400/.test(text))
10
+ if (isContextOverflowError(error))
11
11
  return false;
12
- return /overload|rate limit|429|500|502|503|504|network|connection|stream|timeout|timed? out|terminated|econnreset|etimedout|fetch failed/.test(text);
12
+ // Status codes are matched as whole words so "15000 tokens" or "processed
13
+ // 5000 files" are not misclassified (CR-020).
14
+ if (/\b(?:400|401|403)\b/.test(text) || /quota|billing|balance|auth|api key|invalid request|permission|forbidden/.test(text))
15
+ return false;
16
+ return /\b(?:429|500|502|503|504)\b/.test(text) || /overload|rate limit|network|connection|timeout|timed? out|terminated|econnreset|etimedout|fetch failed|stream disconnected|stream closed|stream aborted|stream error/.test(text);
13
17
  }
@@ -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,54 @@ 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;
127
+ } | {
128
+ type: 'subagent_state';
129
+ id: string;
130
+ state: 'queued' | 'started' | 'terminal' | 'settled';
131
+ mode: string;
132
+ queued?: number;
133
+ running: number;
134
+ queueMs?: number;
135
+ durationMs?: number;
136
+ termination?: string;
137
+ execution?: 'settled' | 'quarantined';
138
+ at: string;
53
139
  };
54
140
  export type AgentEventSink = (event: AgentEvent) => void;
55
141
  export type AgentEventInput = AgentEvent extends infer Event ? Event extends {
@@ -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;
@@ -0,0 +1,58 @@
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
+ const CAPABILITY_MAP = {
15
+ // File discovery / inspection.
16
+ listFiles: ['discovery'],
17
+ grep: ['discovery'],
18
+ readFile: ['read'],
19
+ readToolOutput: ['read'],
20
+ fetch: ['read'],
21
+ // File mutation.
22
+ writeFile: ['mutate'],
23
+ editFile: ['mutate'],
24
+ replaceLines: ['mutate'],
25
+ // Process execution. A bash call becomes validation only when its command is
26
+ // a classifier-confirmed validation command (see work state); that runtime
27
+ // fact is tracked separately as a validation event, not as a static trait.
28
+ bash: ['process'],
29
+ process: ['process'],
30
+ // Coordination / durable state.
31
+ writeTasks: ['coordinate'],
32
+ subagent: ['coordinate'],
33
+ // LSP diagnostic reads.
34
+ };
35
+ /**
36
+ * Capability set for a built-in tool name. Unknown/third-party tool names
37
+ * (MCP) return an empty set: their effects are not statically knowable, so
38
+ * policy code treats them conservatively.
39
+ */
40
+ export function toolCapability(name) {
41
+ return CAPABILITY_MAP[name] ?? [];
42
+ }
43
+ export function hasCapability(name, capability) {
44
+ return toolCapability(name).includes(capability);
45
+ }
46
+ /** Tools whose successful call introduces a workspace mutation. */
47
+ export function isMutatingCapability(name) {
48
+ return hasCapability(name, 'mutate');
49
+ }
50
+ /** Tools that can act as a validation step (runtime-classifier dependent). */
51
+ export function isValidationCapable(name) {
52
+ return hasCapability(name, 'validate') || name === 'bash';
53
+ }
54
+ /** Read/discovery-only built-in tools (no mutation side effects). */
55
+ export function isReadOrDiscoveryCapability(name) {
56
+ const caps = toolCapability(name);
57
+ return caps.length > 0 && caps.every(capability => capability === 'read' || capability === 'discovery');
58
+ }
@@ -0,0 +1,35 @@
1
+ import type { ToolSet } from 'ai';
2
+ /**
3
+ * Marker placed on a structured tool result when the execution-boundary budget
4
+ * blocked the call. The underlying implementation never ran, so callers (goal
5
+ * observers, telemetry) must not treat it as a real tool failure with side
6
+ * effects (RH-003).
7
+ */
8
+ export declare const TOOL_BUDGET_BLOCKED = "__hazeToolBudgetBlocked";
9
+ export interface ToolExecutionBudgetState {
10
+ /** Number of underlying executions that have actually started. */
11
+ started: number;
12
+ /** Set once a call was blocked so callers can force synthesis. */
13
+ exceeded: boolean;
14
+ }
15
+ export declare function createToolExecutionBudget(): ToolExecutionBudgetState;
16
+ /** True when a tool result is the structured "budget blocked" placeholder. */
17
+ export declare function isToolBudgetBlocked(output: unknown): boolean;
18
+ export interface BudgetLimit {
19
+ state: ToolExecutionBudgetState;
20
+ limit: number;
21
+ }
22
+ /**
23
+ * Wrap a tool set so each underlying `execute` checks-and-increments one or more
24
+ * shared budgets synchronously at the actual execution boundary. A model-emitted
25
+ * parallel batch enters `execute` sequentially on the JS event loop, so no more
26
+ * than the remaining budget can reach an underlying implementation even within
27
+ * one batch (RH-003). Revisit if the AI SDK ever yields between queueing a batch
28
+ * and invoking execute.
29
+ *
30
+ * When any supplied limit is exhausted the call is blocked: every limit is
31
+ * marked exceeded, no underlying call runs, and a structured bounded failure is
32
+ * returned so the SDK completes the step and the next prepareStep forces
33
+ * text-only synthesis.
34
+ */
35
+ export declare function withToolExecutionBudget(tools: ToolSet, ...limits: BudgetLimit[]): ToolSet;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Marker placed on a structured tool result when the execution-boundary budget
3
+ * blocked the call. The underlying implementation never ran, so callers (goal
4
+ * observers, telemetry) must not treat it as a real tool failure with side
5
+ * effects (RH-003).
6
+ */
7
+ export const TOOL_BUDGET_BLOCKED = '__hazeToolBudgetBlocked';
8
+ export function createToolExecutionBudget() {
9
+ return { started: 0, exceeded: false };
10
+ }
11
+ /** True when a tool result is the structured "budget blocked" placeholder. */
12
+ export function isToolBudgetBlocked(output) {
13
+ return typeof output === 'object' && output !== null && TOOL_BUDGET_BLOCKED in output;
14
+ }
15
+ /**
16
+ * Wrap a tool set so each underlying `execute` checks-and-increments one or more
17
+ * shared budgets synchronously at the actual execution boundary. A model-emitted
18
+ * parallel batch enters `execute` sequentially on the JS event loop, so no more
19
+ * than the remaining budget can reach an underlying implementation even within
20
+ * one batch (RH-003). Revisit if the AI SDK ever yields between queueing a batch
21
+ * and invoking execute.
22
+ *
23
+ * When any supplied limit is exhausted the call is blocked: every limit is
24
+ * marked exceeded, no underlying call runs, and a structured bounded failure is
25
+ * returned so the SDK completes the step and the next prepareStep forces
26
+ * text-only synthesis.
27
+ */
28
+ export function withToolExecutionBudget(tools, ...limits) {
29
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => {
30
+ if (typeof definition.execute !== 'function')
31
+ return [name, definition];
32
+ const execute = definition.execute;
33
+ return [name, {
34
+ ...definition,
35
+ execute: (...args) => {
36
+ for (const { state, limit } of limits) {
37
+ if (state.started >= limit) {
38
+ for (const entry of limits)
39
+ entry.state.exceeded = true;
40
+ return { ok: false, [TOOL_BUDGET_BLOCKED]: true, error: 'Tool-call budget exhausted; execution was blocked before the underlying tool ran.' };
41
+ }
42
+ }
43
+ for (const { state } of limits)
44
+ state.started++;
45
+ return execute(...args);
46
+ },
47
+ }];
48
+ }));
49
+ }
@@ -11,6 +11,19 @@ export interface StoredToolOutputPage {
11
11
  query?: string;
12
12
  matches?: number;
13
13
  }
14
+ export declare function registerDynamicToolOutput(read: () => {
15
+ content: string;
16
+ totalBytes: number;
17
+ }): string;
18
+ export declare function unregisterDynamicToolOutput(handle: string): void;
19
+ /**
20
+ * Store a tool output and return a handle for later retrieval.
21
+ *
22
+ * Two eviction pressures apply: count (`MAX_STORED_OUTPUTS`) and total bytes
23
+ * (`TOOL_OUTPUT_TOTAL_BYTES`). A single entry that alone exceeds the byte
24
+ * budget is evicted on the next `storeToolOutput` call, so callers should not
25
+ * assume a freshly-stored handle survives beyond the next store.
26
+ */
14
27
  export declare function storeToolOutput(content: string): string;
15
28
  export declare function readToolOutput(handle: string, offset?: number, limit?: number, options?: {
16
29
  query?: string;
@@ -1,21 +1,30 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits/byteBudgets.js';
3
+ import { truncateUtf8AtBytes } from '../../utils/utf8.js';
3
4
  const outputs = new Map();
5
+ const dynamicOutputs = new Map();
4
6
  const MAX_STORED_OUTPUTS = 100;
5
7
  let storedBytes = 0;
6
- function utf8Prefix(content, maxBytes) {
7
- const bytes = Buffer.from(content, 'utf8');
8
- if (bytes.length <= maxBytes)
9
- return content;
10
- let end = maxBytes;
11
- while (end > 0 && (bytes[end] & 0xc0) === 0x80)
12
- end--;
13
- return bytes.subarray(0, end).toString('utf8');
8
+ export function registerDynamicToolOutput(read) {
9
+ const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
10
+ dynamicOutputs.set(handle, read);
11
+ return handle;
14
12
  }
13
+ export function unregisterDynamicToolOutput(handle) {
14
+ dynamicOutputs.delete(handle);
15
+ }
16
+ /**
17
+ * Store a tool output and return a handle for later retrieval.
18
+ *
19
+ * Two eviction pressures apply: count (`MAX_STORED_OUTPUTS`) and total bytes
20
+ * (`TOOL_OUTPUT_TOTAL_BYTES`). A single entry that alone exceeds the byte
21
+ * budget is evicted on the next `storeToolOutput` call, so callers should not
22
+ * assume a freshly-stored handle survives beyond the next store.
23
+ */
15
24
  export function storeToolOutput(content) {
16
25
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
17
26
  const originalBytes = Buffer.byteLength(content, 'utf8');
18
- const retained = utf8Prefix(content, TOOL_OUTPUT_ENTRY_BYTES);
27
+ const retained = truncateUtf8AtBytes(content, TOOL_OUTPUT_ENTRY_BYTES).text;
19
28
  const bytes = Buffer.byteLength(retained, 'utf8');
20
29
  outputs.set(handle, { content: retained, bytes, originalBytes });
21
30
  storedBytes += bytes;
@@ -57,9 +66,17 @@ function searchOutput(output, query, limit, contextLines = 2) {
57
66
  return { offset: 0, totalChars: output.length, content: content.slice(0, limit), truncated: content.length > limit, query, matches: ranges.length };
58
67
  }
59
68
  export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
60
- const stored = outputs.get(handle);
69
+ const dynamic = dynamicOutputs.get(handle)?.();
70
+ const stored = dynamic
71
+ ? { content: dynamic.content, bytes: Buffer.byteLength(dynamic.content, 'utf8'), originalBytes: dynamic.totalBytes }
72
+ : outputs.get(handle);
61
73
  if (stored == null)
62
74
  return undefined;
75
+ // Refresh recency so reads protect entries from LRU eviction (CR-019).
76
+ if (!dynamic) {
77
+ outputs.delete(handle);
78
+ outputs.set(handle, stored);
79
+ }
63
80
  const output = stored.content;
64
81
  if (options?.query?.trim()) {
65
82
  const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
@@ -19,11 +19,23 @@ export declare function isFailedToolOutput(output: unknown): boolean;
19
19
  * counts as OK only when the call succeeded AND did not report `{ok: false}`.
20
20
  */
21
21
  export declare function toolOutputOk(output: unknown, success: boolean): boolean;
22
+ export interface SafeToolFailureDetails {
23
+ errorCode?: string;
24
+ error?: string;
25
+ }
26
+ /**
27
+ * Extract a bounded diagnostic from Haze's structured failure shape. Generic
28
+ * third-party tool outputs are intentionally ignored because their error fields
29
+ * may contain arbitrary remote content or secrets.
30
+ */
31
+ export declare function safeToolFailureDetails(output: unknown): SafeToolFailureDetails;
22
32
  /**
23
33
  * Read a string field from an `unknown` tool input object. Returns undefined
24
34
  * for non-objects, missing keys, or non-string values.
25
35
  */
26
36
  export declare function toolInputField(input: unknown, key: string): string | undefined;
37
+ /** A mutation failure needs a fresh file read only when it explicitly says so. */
38
+ export declare function requiresReadFileRecovery(value: unknown): boolean;
27
39
  /**
28
40
  * Deduplicated read-only tool calls return a `{duplicateSkipped: true}` marker
29
41
  * instead of re-running. Lets observers treat them as no-ops.
@@ -23,6 +23,39 @@ export function isFailedToolOutput(output) {
23
23
  export function toolOutputOk(output, success) {
24
24
  return success && !isFailedToolOutput(output);
25
25
  }
26
+ const MAX_PUBLIC_TOOL_ERROR_CHARS = 500;
27
+ const SAFE_ERROR_CODE = /^[a-z0-9_-]{1,80}$/i;
28
+ function boundedSingleLine(value) {
29
+ const normalized = value.replace(/\p{Cc}+/gu, ' ').replace(/\s+/g, ' ').trim();
30
+ if (normalized.length <= MAX_PUBLIC_TOOL_ERROR_CHARS)
31
+ return normalized;
32
+ return `${normalized.slice(0, MAX_PUBLIC_TOOL_ERROR_CHARS - 1)}…`;
33
+ }
34
+ /**
35
+ * Extract a bounded diagnostic from Haze's structured failure shape. Generic
36
+ * third-party tool outputs are intentionally ignored because their error fields
37
+ * may contain arbitrary remote content or secrets.
38
+ */
39
+ export function safeToolFailureDetails(output) {
40
+ if (typeof output !== 'object' || output == null)
41
+ return {};
42
+ const value = output;
43
+ if (value.ok !== false)
44
+ return {};
45
+ const structuredHazeFailure = typeof value.toolName === 'string' && typeof value.recoverable === 'boolean';
46
+ const reasonCode = typeof value.reasonCode === 'string' && SAFE_ERROR_CODE.test(value.reasonCode) ? value.reasonCode : undefined;
47
+ const missingExecutable = typeof value.missingExecutable === 'string' && value.missingExecutable.trim() ? boundedSingleLine(value.missingExecutable) : undefined;
48
+ const errorCode = reasonCode
49
+ ?? (missingExecutable ? 'missing_executable'
50
+ : value.timedOut === true ? 'command_timed_out'
51
+ : typeof value.exitCode === 'number' && value.exitCode !== 0 ? 'nonzero_exit'
52
+ : typeof value.signal === 'string' ? 'process_signal'
53
+ : undefined);
54
+ // Only the dedicated Haze failure shape guarantees that `error` is a bounded
55
+ // local diagnostic. Bash stderr and third-party fields may contain secrets.
56
+ const error = structuredHazeFailure && typeof value.error === 'string' ? boundedSingleLine(value.error) : undefined;
57
+ return { ...(errorCode ? { errorCode } : {}), ...(error ? { error } : {}), ...(missingExecutable ? { missingExecutable } : {}) };
58
+ }
26
59
  /**
27
60
  * Read a string field from an `unknown` tool input object. Returns undefined
28
61
  * for non-objects, missing keys, or non-string values.
@@ -33,6 +66,11 @@ export function toolInputField(input, key) {
33
66
  const value = input[key];
34
67
  return typeof value === 'string' ? value : undefined;
35
68
  }
69
+ /** A mutation failure needs a fresh file read only when it explicitly says so. */
70
+ export function requiresReadFileRecovery(value) {
71
+ return typeof value === 'object' && value != null && 'recoveryTool' in value
72
+ && value.recoveryTool === 'readFile';
73
+ }
36
74
  /**
37
75
  * Deduplicated read-only tool calls return a `{duplicateSkipped: true}` marker
38
76
  * instead of re-running. Lets observers treat them as no-ops.