@denizokcu/haze 0.10.0 → 1.0.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 (294) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/README.md +77 -27
  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 +2 -2
  9. package/dist/cli/chat/chatMetrics.js +1 -1
  10. package/dist/cli/chat/contextReport.js +2 -0
  11. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  12. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  13. package/dist/cli/chat/inputSuggestions.js +9 -41
  14. package/dist/cli/chat/liveRegion.d.ts +25 -0
  15. package/dist/cli/chat/liveRegion.js +48 -0
  16. package/dist/cli/chat/messages.d.ts +33 -4
  17. package/dist/cli/chat/messages.js +218 -35
  18. package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
  19. package/dist/cli/chat/sessionLifecycle.js +64 -14
  20. package/dist/cli/chat/sessionRecorder.js +75 -7
  21. package/dist/cli/chat/startupInfo.d.ts +0 -1
  22. package/dist/cli/chat/startupInfo.js +11 -15
  23. package/dist/cli/chat/turnState.d.ts +1 -1
  24. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  25. package/dist/cli/chat/wizardDispatch.js +349 -133
  26. package/dist/cli/commands/chat.d.ts +5 -0
  27. package/dist/cli/commands/chat.js +216 -172
  28. package/dist/cli/commands/chatModes.d.ts +8 -1
  29. package/dist/cli/commands/chatModes.js +9 -44
  30. package/dist/cli/commands/commands.d.ts +2 -0
  31. package/dist/cli/commands/commands.js +10 -5
  32. package/dist/cli/commands/doctor.d.ts +19 -0
  33. package/dist/cli/commands/doctor.js +76 -0
  34. package/dist/cli/commands/formatters.d.ts +3 -3
  35. package/dist/cli/commands/formatters.js +8 -25
  36. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  37. package/dist/cli/commands/ndjsonSink.js +38 -0
  38. package/dist/cli/commands/providerWizard.d.ts +9 -2
  39. package/dist/cli/commands/providerWizard.js +39 -7
  40. package/dist/cli/commands/runCommand.d.ts +3 -0
  41. package/dist/cli/commands/runCommand.js +117 -11
  42. package/dist/cli/commands/serverWizard.d.ts +34 -0
  43. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  44. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  45. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  46. package/dist/cli/commands/streaming/abortCause.d.ts +25 -0
  47. package/dist/cli/commands/streaming/abortCause.js +16 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  50. package/dist/cli/commands/streaming/assistantText.js +9 -2
  51. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  62. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +16 -0
  66. package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
  68. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  69. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  70. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  71. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  73. package/dist/cli/commands/streaming.d.ts +65 -9
  74. package/dist/cli/commands/streaming.js +133 -430
  75. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  76. package/dist/cli/commands/wizardFlow.js +377 -0
  77. package/dist/cli/contextReport.js +3 -0
  78. package/dist/cli/index.js +68 -22
  79. package/dist/cli/terminalTitle.js +1 -1
  80. package/dist/config/contextFiles.js +9 -3
  81. package/dist/config/inputHistory.d.ts +0 -1
  82. package/dist/config/inputHistory.js +1 -1
  83. package/dist/config/modelDiscovery.d.ts +36 -0
  84. package/dist/config/modelDiscovery.js +164 -1
  85. package/dist/config/privateStorage.js +28 -2
  86. package/dist/config/providerAuth.d.ts +14 -0
  87. package/dist/config/providerAuth.js +49 -0
  88. package/dist/config/providerPresets.d.ts +39 -7
  89. package/dist/config/providerPresets.js +371 -100
  90. package/dist/config/providers.js +2 -0
  91. package/dist/config/settings.d.ts +43 -0
  92. package/dist/config/settings.js +12 -0
  93. package/dist/config/skillSettings.js +4 -4
  94. package/dist/config/updateCheck.d.ts +0 -1
  95. package/dist/config/updateCheck.js +1 -1
  96. package/dist/core/agent/budgets.d.ts +73 -1
  97. package/dist/core/agent/budgets.js +94 -1
  98. package/dist/core/agent/compaction.d.ts +38 -0
  99. package/dist/core/agent/compaction.js +92 -17
  100. package/dist/core/agent/completionController.d.ts +224 -0
  101. package/dist/core/agent/completionController.js +296 -0
  102. package/dist/core/agent/contextBudget.d.ts +36 -2
  103. package/dist/core/agent/contextBudget.js +62 -9
  104. package/dist/core/agent/errors.d.ts +0 -1
  105. package/dist/core/agent/errors.js +1 -1
  106. package/dist/core/agent/events.d.ts +78 -0
  107. package/dist/core/agent/goalPolicy.d.ts +47 -0
  108. package/dist/core/agent/goalPolicy.js +106 -0
  109. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  110. package/dist/core/agent/reasoningPolicy.js +27 -0
  111. package/dist/core/agent/requestAssembly.d.ts +2 -2
  112. package/dist/core/agent/requestAssembly.js +16 -4
  113. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  114. package/dist/core/agent/toolCapabilities.js +58 -0
  115. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  116. package/dist/core/agent/toolOutputStore.js +11 -11
  117. package/dist/core/agent/toolResults.d.ts +12 -0
  118. package/dist/core/agent/toolResults.js +38 -0
  119. package/dist/core/agent/turnPolicy.d.ts +11 -0
  120. package/dist/core/agent/turnPolicy.js +19 -0
  121. package/dist/core/agent/workState.d.ts +81 -3
  122. package/dist/core/agent/workState.js +176 -10
  123. package/dist/core/attachments/imageAttachments.js +90 -42
  124. package/dist/core/deadline.d.ts +27 -0
  125. package/dist/core/deadline.js +74 -0
  126. package/dist/core/io/boundedRead.js +1 -1
  127. package/dist/core/limits.d.ts +51 -0
  128. package/dist/core/limits.js +51 -0
  129. package/dist/core/log/llmLog.js +8 -1
  130. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  131. package/dist/core/persistence/orderedFileWriter.js +16 -2
  132. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  133. package/dist/core/process/backgroundRegistry.js +15 -10
  134. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  135. package/dist/core/process/runBoundedProcess.js +15 -6
  136. package/dist/core/process/userShell.d.ts +16 -0
  137. package/dist/core/process/userShell.js +59 -0
  138. package/dist/core/safety/missingExecutable.d.ts +42 -0
  139. package/dist/core/safety/missingExecutable.js +77 -0
  140. package/dist/core/safety/shellClassifier.d.ts +11 -0
  141. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  142. package/dist/core/safety/urlGuard.d.ts +1 -1
  143. package/dist/core/session/sessionSlimming.d.ts +0 -3
  144. package/dist/core/session/sessionSlimming.js +2 -3
  145. package/dist/core/session/sessionStore.d.ts +38 -0
  146. package/dist/core/session/sessionStore.js +242 -59
  147. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  148. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  149. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  150. package/dist/core/shellOutput/registry.d.ts +2 -0
  151. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  152. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  153. package/dist/core/subagent/contracts.d.ts +6 -14
  154. package/dist/core/subagent/contracts.js +4 -3
  155. package/dist/core/subagent/executionProfiles.js +2 -2
  156. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  157. package/dist/core/subagent/subagentCoordinator.js +32 -2
  158. package/dist/core/subagent/subagentRunner.js +19 -40
  159. package/dist/core/toolOutput/reduction.d.ts +0 -12
  160. package/dist/core/toolOutput/reduction.js +1 -1
  161. package/dist/core/validation/outputParser.d.ts +2 -2
  162. package/dist/llm/client.d.ts +17 -1
  163. package/dist/llm/client.js +86 -14
  164. package/dist/llm/hazeTools.d.ts +693 -204
  165. package/dist/llm/hazeTools.js +110 -28
  166. package/dist/llm/initPrompt.js +1 -1
  167. package/dist/llm/lsp/client.d.ts +45 -0
  168. package/dist/llm/lsp/client.js +195 -0
  169. package/dist/llm/lsp/pool.d.ts +23 -0
  170. package/dist/llm/lsp/pool.js +86 -0
  171. package/dist/llm/lsp/protocol.d.ts +64 -0
  172. package/dist/llm/lsp/protocol.js +128 -0
  173. package/dist/llm/lsp/requests.d.ts +94 -0
  174. package/dist/llm/lsp/requests.js +119 -0
  175. package/dist/llm/lspTools.d.ts +5653 -33
  176. package/dist/llm/lspTools.js +152 -80
  177. package/dist/llm/openaiCodex.d.ts +1 -0
  178. package/dist/llm/openaiCodex.js +43 -0
  179. package/dist/llm/openaiCodexOAuth.d.ts +51 -0
  180. package/dist/llm/openaiCodexOAuth.js +217 -0
  181. package/dist/llm/requestContext.d.ts +7 -0
  182. package/dist/llm/requestContext.js +30 -4
  183. package/dist/llm/systemPrompt.d.ts +12 -0
  184. package/dist/llm/systemPrompt.js +24 -11
  185. package/dist/llm/toolResultTypes.d.ts +7 -14
  186. package/dist/llm/toolResultTypes.js +1 -4
  187. package/dist/llm/tools/editMatch.d.ts +14 -9
  188. package/dist/llm/tools/editMatch.js +73 -1
  189. package/dist/llm/tools/failures.d.ts +2 -0
  190. package/dist/llm/tools/failures.js +1 -0
  191. package/dist/llm/tools/fetchTool.d.ts +16 -0
  192. package/dist/llm/tools/fetchTool.js +1 -1
  193. package/dist/llm/tools/fileToolShared.d.ts +8 -5
  194. package/dist/llm/tools/fileToolShared.js +22 -23
  195. package/dist/llm/tools/gitIgnore.d.ts +42 -0
  196. package/dist/llm/tools/gitIgnore.js +247 -0
  197. package/dist/llm/tools/grepParse.d.ts +2 -1
  198. package/dist/llm/tools/grepRunner.d.ts +1 -1
  199. package/dist/llm/tools/grepRunner.js +2 -2
  200. package/dist/llm/tools/outputCap.d.ts +2 -7
  201. package/dist/llm/tools/outputCap.js +3 -3
  202. package/dist/llm/tools/processTool.d.ts +16 -16
  203. package/dist/llm/tools/processTool.js +1 -1
  204. package/dist/llm/tools/readRecovery.d.ts +8 -0
  205. package/dist/llm/tools/readRecovery.js +135 -0
  206. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
  207. package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
  208. package/dist/llm/tools/toolContext.d.ts +1 -1
  209. package/dist/llm/tools/toolContext.js +66 -37
  210. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  211. package/dist/llm/tools/workspaceFile.js +1 -6
  212. package/dist/llm/webFetch.d.ts +18 -1
  213. package/dist/llm/webFetch.js +64 -97
  214. package/dist/skills/SkillLoader.d.ts +1 -11
  215. package/dist/skills/SkillLoader.js +1 -2
  216. package/dist/skills/types.d.ts +2 -1
  217. package/dist/ui/codeHighlight.d.ts +4 -0
  218. package/dist/ui/codeHighlight.js +31 -0
  219. package/dist/ui/components/Header.d.ts +1 -1
  220. package/dist/ui/components/MarkdownText.d.ts +16 -2
  221. package/dist/ui/components/MarkdownText.js +244 -34
  222. package/dist/ui/components/TextInput.d.ts +8 -1
  223. package/dist/ui/components/TextInput.js +6 -2
  224. package/dist/ui/theme.d.ts +4 -3
  225. package/dist/ui/theme.js +5 -4
  226. package/dist/utils/buildInfo.d.ts +97 -0
  227. package/dist/utils/buildInfo.js +244 -0
  228. package/dist/utils/fs.d.ts +11 -0
  229. package/dist/utils/fs.js +91 -26
  230. package/dist/utils/openPath.d.ts +2 -2
  231. package/dist/utils/openPath.js +19 -6
  232. package/dist/utils/path.d.ts +2 -1
  233. package/dist/utils/path.js +6 -2
  234. package/dist/utils/utf8.d.ts +22 -0
  235. package/dist/utils/utf8.js +54 -0
  236. package/dist/utils/version.d.ts +9 -3
  237. package/dist/utils/version.js +28 -2
  238. package/package.json +28 -21
  239. package/dist/cli/commands/lspWizard.d.ts +0 -14
  240. package/dist/cli/commands/lspWizard.js +0 -44
  241. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  242. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  243. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  244. package/dist/cli/commands/skillCreation.d.ts +0 -12
  245. package/dist/cli/commands/skillCreation.js +0 -14
  246. package/dist/cli/commands/skillWizard.d.ts +0 -17
  247. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  248. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  249. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -10
  250. package/dist/cli/commands/streaming/turnOutcome.js +0 -13
  251. package/dist/cli/commands/wizardActions.d.ts +0 -46
  252. package/dist/cli/commands/wizardActions.js +0 -46
  253. package/dist/cli/commands/wizardInput.d.ts +0 -4
  254. package/dist/cli/commands/wizardInput.js +0 -19
  255. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  256. package/dist/cli/commands/wizardPrompts.js +0 -52
  257. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  258. package/dist/cli/commands/wizardSuggestions.js +0 -188
  259. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  260. package/dist/cli/commands/wizardTransition.js +0 -43
  261. package/dist/core/bashOutput/ansi.d.ts +0 -1
  262. package/dist/core/bashOutput/ansi.js +0 -7
  263. package/dist/core/bashOutput/registry.d.ts +0 -4
  264. package/dist/core/goal/completionPolicy.d.ts +0 -2
  265. package/dist/core/goal/completionPolicy.js +0 -7
  266. package/dist/core/goal/requestClassifier.d.ts +0 -3
  267. package/dist/core/goal/requestClassifier.js +0 -18
  268. package/dist/core/goal/sessionGoal.d.ts +0 -8
  269. package/dist/core/goal/sessionGoal.js +0 -30
  270. package/dist/core/limits/byteBudgets.d.ts +0 -18
  271. package/dist/core/limits/byteBudgets.js +0 -18
  272. package/dist/core/limits/textBudgets.d.ts +0 -23
  273. package/dist/core/limits/textBudgets.js +0 -23
  274. package/dist/core/safety/bashClassifier.d.ts +0 -10
  275. package/dist/llm/lsp.d.ts +0 -129
  276. package/dist/llm/lsp.js +0 -307
  277. package/dist/ui/components/ErrorView.d.ts +0 -4
  278. package/dist/ui/components/ErrorView.js +0 -7
  279. package/dist/utils/yaml.d.ts +0 -2
  280. package/dist/utils/yaml.js +0 -8
  281. package/examples/skills/files/SKILL.md +0 -16
  282. package/examples/skills/files/examples/file-editing.md +0 -3
  283. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  284. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  285. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  286. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  287. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  288. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  289. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  290. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  291. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  292. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  293. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  294. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -1,6 +1,20 @@
1
1
  import { z } from 'zod';
2
2
  import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
3
- export const DEFAULT_CHARS_PER_TOKEN = 4;
3
+ 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
+ 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
@@ -11,7 +25,7 @@ export const IMAGE_BYTES_PER_TOKEN_ESTIMATE = 750;
11
25
  export function estimateTextTokens(text) {
12
26
  return Math.ceil(text.length / DEFAULT_CHARS_PER_TOKEN);
13
27
  }
14
- export function estimateImagePartTokens(part) {
28
+ function estimateImagePartTokens(part) {
15
29
  if (!isImageFilePart(part))
16
30
  return 0;
17
31
  const bytes = imageFilePartBytes(part.data);
@@ -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,2 @@
1
- export declare function errorText(error: unknown): string;
2
1
  export declare function isContextOverflowError(error: unknown): boolean;
3
2
  export declare function isRetryableModelError(error: unknown): boolean;
@@ -1,4 +1,4 @@
1
- export function errorText(error) {
1
+ function errorText(error) {
2
2
  return (error instanceof Error ? `${error.name} ${error.message}` : String(error)).toLowerCase();
3
3
  }
4
4
  export function isContextOverflowError(error) {
@@ -1,3 +1,12 @@
1
+ import type { TurnCompletionEvidence } from './completionController.js';
2
+ import type { EffectiveReasoning, ReasoningLevel } from './reasoningPolicy.js';
3
+ 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,40 @@ 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
+ responseModel?: string;
52
+ at: string;
10
53
  } | {
11
54
  type: 'message_start';
12
55
  id: string;
@@ -35,6 +78,7 @@ export type AgentEvent = {
35
78
  name: string;
36
79
  success: boolean;
37
80
  output?: unknown;
81
+ errorCode?: string;
38
82
  error?: unknown;
39
83
  durationMs: number;
40
84
  at: string;
@@ -45,11 +89,44 @@ export type AgentEvent = {
45
89
  delayMs: number;
46
90
  error: string;
47
91
  at: string;
92
+ } | {
93
+ type: 'reasoning_policy';
94
+ requested?: ReasoningLevel;
95
+ effective: EffectiveReasoning;
96
+ reason: string;
97
+ at: string;
98
+ } | {
99
+ type: 'context_budget';
100
+ contextWindowTokens: number;
101
+ source: 'settings' | 'user-fallback' | 'default-fallback';
102
+ at: string;
48
103
  } | {
49
104
  type: 'context_overflow';
50
105
  recovered: boolean;
51
106
  error: string;
52
107
  at: string;
108
+ } | {
109
+ type: 'timeout';
110
+ phase: 'turn' | 'tool' | 'model-stream';
111
+ timeoutMs: number;
112
+ /**
113
+ * Model-stream stall diagnostics (phase 'model-stream' only). Safe metadata
114
+ * only — provider/model names, timestamps, enums, work phase — never prompt
115
+ * content or credentials.
116
+ */
117
+ provider?: string;
118
+ model?: string;
119
+ lastStreamEventAt?: string;
120
+ lastStreamEventType?: string;
121
+ /** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
122
+ stallEmission?: 'none' | 'text' | 'tool';
123
+ /** Active work-state phase when the stall was detected. */
124
+ workPhase?: string;
125
+ /** Whether the stall rides the bounded model-retry pool. */
126
+ retryEligible?: boolean;
127
+ /** Size of the bounded model-retry pool in effect (`modelRetries` setting). */
128
+ maxRetries?: number;
129
+ at: string;
53
130
  } | {
54
131
  type: 'subagent_state';
55
132
  id: string;
@@ -68,3 +145,4 @@ export type AgentEventInput = AgentEvent extends infer Event ? Event extends {
68
145
  at: string;
69
146
  } ? Omit<Event, 'at'> : never : never;
70
147
  export declare function agentEvent(event: AgentEventInput): AgentEvent;
148
+ export {};
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Goal policy: request-intent classification, session-goal state, and the
3
+ * model-facing completion/continuation control prompts (CR-006 home for the
4
+ * former `core/goal/` directory).
5
+ *
6
+ * Classifiers are hints, not hard authorization. Avoid preventing legitimate
7
+ * work solely because of a heuristic. Plan-only requests should not lead to
8
+ * source mutations unless the user asks for implementation.
9
+ */
10
+ import { observeWorkToolEvent, type WorkState } from './workState.js';
11
+ export type RequestIntent = 'implement' | 'fix' | 'test' | 'review' | 'plan' | 'answer' | 'unknown';
12
+ export declare function isPlanOnlyRequest(value: string): boolean;
13
+ export declare function classifyRequestIntent(value: string): RequestIntent;
14
+ export type SessionGoal = WorkState;
15
+ export type GoalToolEvent = Parameters<typeof observeWorkToolEvent>[1];
16
+ export declare function createSessionGoal(request: string, now?: number): SessionGoal;
17
+ export declare function observeGoalToolEvent(goal: SessionGoal, event: GoalToolEvent, now?: number): WorkState;
18
+ export declare function formatGoalStatus(goal: SessionGoal): string;
19
+ export declare function toolLoopBudgetPrompt(): string;
20
+ export declare function repeatedToolCallPrompt(toolNames: string[]): string;
21
+ /**
22
+ * Ephemeral control appended to continue a response truncated by an
23
+ * output-length finish. Asks the model to resume from where it stopped and
24
+ * complete the requested artifact/answer. One-request nudge only.
25
+ */
26
+ export declare function lengthContinuationPrompt(): string;
27
+ /**
28
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
29
+ * validation tools are available; discovery must not be reopened. The model gets
30
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
31
+ * deliverable you already discovered, then one final tool-free synthesis.
32
+ */
33
+ export declare function completionRescuePrompt(): string;
34
+ export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
35
+ /**
36
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
37
+ * turn. The model's stop was rejected (or its physical turn hit a budget
38
+ * boundary) while structured evidence — declared task counts, post-edit
39
+ * validation — shows unfinished work; this nudge requires resuming concrete
40
+ * work rather than summarizing again. One-request nudge only.
41
+ */
42
+ export declare function goalContinuationPrompt(reason: string, taskCounts?: {
43
+ total: number;
44
+ pending: number;
45
+ inProgress: number;
46
+ completed: number;
47
+ }): string;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Goal policy: request-intent classification, session-goal state, and the
3
+ * model-facing completion/continuation control prompts (CR-006 home for the
4
+ * former `core/goal/` directory).
5
+ *
6
+ * Classifiers are hints, not hard authorization. Avoid preventing legitimate
7
+ * work solely because of a heuristic. Plan-only requests should not lead to
8
+ * source mutations unless the user asks for implementation.
9
+ */
10
+ import { createWorkState, observeWorkToolEvent } from './workState.js';
11
+ export function isPlanOnlyRequest(value) {
12
+ return /\b(create|make|write|draft|outline)\s+(?:a\s+)?plan\b|\bplan\s+(?:for|to)\b/i.test(value) && !/\bimplement|execute|do\b/i.test(value);
13
+ }
14
+ export function classifyRequestIntent(value) {
15
+ if (isPlanOnlyRequest(value))
16
+ return 'plan';
17
+ if (/\b(review|audit|inspect|analy[sz]e|compare)\b/i.test(value))
18
+ return 'review';
19
+ if (/\b(fix|repair|resolve|debug)\b/i.test(value))
20
+ return 'fix';
21
+ if (/\b(run|verify|check|validate)\b/i.test(value) || /\btests?\b/i.test(value) && !/\b(add|create|write)\b/i.test(value))
22
+ return 'test';
23
+ if (/\b(add|create|write|implement|update|change|support|wire|document|docs|documentation)\b/i.test(value))
24
+ return 'implement';
25
+ if (/\b(what|why|how|explain|tell me)\b/i.test(value))
26
+ return 'answer';
27
+ return 'unknown';
28
+ }
29
+ function shortRequest(value) {
30
+ return value.replace(/\s+/g, ' ').trim().slice(0, 160) || 'current request';
31
+ }
32
+ export function createSessionGoal(request, now = Date.now()) {
33
+ const intent = classifyRequestIntent(request);
34
+ const successCriteria = intent === 'plan'
35
+ ? ['Create or update the requested plan artifact/answer', 'Do not implement source changes unless asked']
36
+ : intent === 'test'
37
+ ? ['Run the requested validation or closest relevant check', 'Report pass/fail accurately']
38
+ : intent === 'review'
39
+ ? ['Inspect the relevant current project state', 'Return evidence-based findings with file paths']
40
+ : intent === 'answer'
41
+ ? ['Answer the user using current project context when needed']
42
+ : ['Inspect the relevant files', 'Make the requested change when needed', 'Validate the change when practical', 'Summarize only current-task changes and validation'];
43
+ return createWorkState(request, intent, successCriteria, now);
44
+ }
45
+ export function observeGoalToolEvent(goal, event, now = Date.now()) {
46
+ return observeWorkToolEvent(goal, event, now);
47
+ }
48
+ export function formatGoalStatus(goal) {
49
+ const action = goal.phase === 'starting' ? 'starting'
50
+ : goal.phase === 'inspecting' ? 'inspecting'
51
+ : goal.phase === 'editing' ? `${goal.touchedFiles.length} file${goal.touchedFiles.length === 1 ? '' : 's'} changed`
52
+ : goal.phase === 'validating' ? `validation ${goal.validationCommands.at(-1)?.status ?? 'running'}`
53
+ : goal.phase === 'summarizing' ? 'summarizing'
54
+ : 'done';
55
+ return `Goal: ${shortRequest(goal.originalUserRequest)} · ${action}`;
56
+ }
57
+ // ── Completion/continuation control prompts ─────────────────────────────────
58
+ // Keep these small and reusable; prefer one shared helper over embedding
59
+ // near-identical model-facing control text in multiple loops. They are
60
+ // one-request nudges, never durable conversation history.
61
+ export function toolLoopBudgetPrompt() {
62
+ return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once with a bounded progress checkpoint: what is done so far (changes + validation evidence) and, if work remains, the single next concrete unfinished action. haze continues the active goal automatically from that line — do not manufacture a completion summary and do not treat this as the end of the task. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
63
+ }
64
+ export function repeatedToolCallPrompt(toolNames) {
65
+ const names = [...new Set(toolNames)].join(', ');
66
+ return `You already called ${names || 'a tool'} with identical input in this turn. Do not call the same tool again with the same arguments. Use the existing tool result already in the conversation, choose a different concrete tool/input if genuinely needed, or give the final/blocked status now.`;
67
+ }
68
+ /**
69
+ * Ephemeral control appended to continue a response truncated by an
70
+ * output-length finish. Asks the model to resume from where it stopped and
71
+ * complete the requested artifact/answer. One-request nudge only.
72
+ */
73
+ export function lengthContinuationPrompt() {
74
+ return 'Your previous response was truncated by the output-token limit before it finished. Continue exactly from where you stopped and complete the requested artifact or answer. Do not repeat what you already produced; finish the in-progress work and then stop.';
75
+ }
76
+ /**
77
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
78
+ * validation tools are available; discovery must not be reopened. The model gets
79
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
80
+ * deliverable you already discovered, then one final tool-free synthesis.
81
+ */
82
+ export function completionRescuePrompt() {
83
+ return 'You reached the tool-boundary without a substantive final answer. Only edit/write and validation tools are available now. Use at most two tool calls to apply the single most important remaining concrete deliverable you already discovered (do not explore or read new files), then give the final status: current-task changes plus validation evidence, or a single short line stating the next unfinished action. Do not loop.';
84
+ }
85
+ export function malformedToolCallPrompt(toolName, chunkBytes) {
86
+ const chunkGuidance = toolName === 'writeFile'
87
+ ? ` Keep content below ${chunkBytes} UTF-8 bytes per call: write the first chunk normally, then continue the same file with append=true.`
88
+ : '';
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
+ }
91
+ /**
92
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
93
+ * turn. The model's stop was rejected (or its physical turn hit a budget
94
+ * boundary) while structured evidence — declared task counts, post-edit
95
+ * validation — shows unfinished work; this nudge requires resuming concrete
96
+ * work rather than summarizing again. One-request nudge only.
97
+ */
98
+ export function goalContinuationPrompt(reason, taskCounts) {
99
+ const taskLine = taskCounts
100
+ ? ` The task list currently shows ${taskCounts.pending + taskCounts.inProgress} open item${taskCounts.pending + taskCounts.inProgress === 1 ? '' : 's'} of ${taskCounts.total}; update writeTasks as you complete them.`
101
+ : '';
102
+ const validationLine = reason.includes('validation')
103
+ ? ' No recognized post-edit validation was recorded. Run one standard test/build command, directly execute the changed artifact as one unchained command, or call shell with purpose=validation for a custom assertion check.'
104
+ : '';
105
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine} Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
106
+ }
@@ -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
+ }
@@ -1,9 +1,9 @@
1
1
  import type { ModelMessage } from 'ai';
2
- export declare const SYNTHETIC_CONTROL_OPEN = "<haze_control>";
3
- export declare function isSyntheticControlMessage(message: ModelMessage): boolean;
4
2
  export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
5
3
  export declare function withoutSystemMessages(messages: ModelMessage[]): ModelMessage[];
6
4
  export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
5
+ /** Drop only a trailing text-only assistant final that completion policy rejected. */
6
+ export declare function withoutRejectedAssistantFinal(messages: ModelMessage[]): ModelMessage[];
7
7
  export declare function compactToolHistory(messages: ModelMessage[], options?: {
8
8
  keepRecentResults?: number;
9
9
  minResultTokens?: number;
@@ -1,7 +1,7 @@
1
1
  import { estimateValueTokens } from './contextBudget.js';
2
2
  import { isFailedToolOutput } from './toolResults.js';
3
- export const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
4
- export function isSyntheticControlMessage(message) {
3
+ const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
4
+ function isSyntheticControlMessage(message) {
5
5
  return message.role === 'user'
6
6
  && typeof message.content === 'string'
7
7
  && message.content.startsWith(SYNTHETIC_CONTROL_OPEN);
@@ -28,6 +28,18 @@ export function withSyntheticControl(messages, control) {
28
28
  { role: 'user', content: `${SYNTHETIC_CONTROL_OPEN}\n${control}\n</haze_control>` },
29
29
  ];
30
30
  }
31
+ /** Drop only a trailing text-only assistant final that completion policy rejected. */
32
+ export function withoutRejectedAssistantFinal(messages) {
33
+ const last = messages.at(-1);
34
+ if (!last || last.role !== 'assistant')
35
+ return messages;
36
+ if (typeof last.content === 'string')
37
+ return messages.slice(0, -1);
38
+ if (!Array.isArray(last.content))
39
+ return messages;
40
+ const hasToolCall = last.content.some(part => typeof part === 'object' && part != null && part.type === 'tool-call');
41
+ return hasToolCall ? messages : messages.slice(0, -1);
42
+ }
31
43
  function resultValue(output) {
32
44
  return typeof output === 'object' && output != null && 'value' in output
33
45
  ? output.value
@@ -91,7 +103,7 @@ function compactResultOutput(output, toolName) {
91
103
  return { ...typed, value: `[Older successful ${toolName} result omitted from active context.]` };
92
104
  return output;
93
105
  }
94
- const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'editFile', 'replaceLines', 'bash']);
106
+ const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'editFile', 'replaceLines', 'shell']);
95
107
  const BASH_COMMAND_TRUNCATE_THRESHOLD = 200;
96
108
  const BASH_COMMAND_KEEP_CHARS = 150;
97
109
  function compactToolCallInput(input, toolName) {
@@ -130,7 +142,7 @@ function compactToolCallInput(input, toolName) {
130
142
  content: `[Compacted: original ${bytes} bytes. Use readFile on "${path}" to inspect.]`,
131
143
  };
132
144
  }
133
- if (toolName === 'bash' && typeof source.command === 'string' && source.command.length > BASH_COMMAND_TRUNCATE_THRESHOLD) {
145
+ if (toolName === 'shell' && typeof source.command === 'string' && source.command.length > BASH_COMMAND_TRUNCATE_THRESHOLD) {
134
146
  const total = source.command.length;
135
147
  const truncated = source.command.slice(0, BASH_COMMAND_KEEP_CHARS).replace(/\s+/g, ' ').trim();
136
148
  return {
@@ -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
+ * shell-classifier contract): the actual effect of a call is still determined at
8
+ * runtime (e.g. a `shell` 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
+ * shell-classifier contract): the actual effect of a call is still determined at
8
+ * runtime (e.g. a `shell` 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 shell 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
+ shell: ['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 === 'shell';
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
+ }
@@ -16,6 +16,14 @@ export declare function registerDynamicToolOutput(read: () => {
16
16
  totalBytes: number;
17
17
  }): string;
18
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
+ */
19
27
  export declare function storeToolOutput(content: string): string;
20
28
  export declare function readToolOutput(handle: string, offset?: number, limit?: number, options?: {
21
29
  query?: string;
@@ -1,18 +1,10 @@
1
1
  import crypto from 'node:crypto';
2
- import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits/byteBudgets.js';
2
+ import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits.js';
3
+ import { truncateUtf8AtBytes } from '../../utils/utf8.js';
3
4
  const outputs = new Map();
4
5
  const dynamicOutputs = new Map();
5
6
  const MAX_STORED_OUTPUTS = 100;
6
7
  let storedBytes = 0;
7
- function utf8Prefix(content, maxBytes) {
8
- const bytes = Buffer.from(content, 'utf8');
9
- if (bytes.length <= maxBytes)
10
- return content;
11
- let end = maxBytes;
12
- while (end > 0 && (bytes[end] & 0xc0) === 0x80)
13
- end--;
14
- return bytes.subarray(0, end).toString('utf8');
15
- }
16
8
  export function registerDynamicToolOutput(read) {
17
9
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
18
10
  dynamicOutputs.set(handle, read);
@@ -21,10 +13,18 @@ export function registerDynamicToolOutput(read) {
21
13
  export function unregisterDynamicToolOutput(handle) {
22
14
  dynamicOutputs.delete(handle);
23
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
+ */
24
24
  export function storeToolOutput(content) {
25
25
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
26
26
  const originalBytes = Buffer.byteLength(content, 'utf8');
27
- const retained = utf8Prefix(content, TOOL_OUTPUT_ENTRY_BYTES);
27
+ const retained = truncateUtf8AtBytes(content, TOOL_OUTPUT_ENTRY_BYTES).text;
28
28
  const bytes = Buffer.byteLength(retained, 'utf8');
29
29
  outputs.set(handle, { content: retained, bytes, originalBytes });
30
30
  storedBytes += bytes;