@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,453 +1,156 @@
1
- import { ToolLoopAgent, isStepCount } from 'ai';
2
- import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
3
- import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
4
- import { assembleRequestContext } from '../../llm/requestContext.js';
5
- import { projectContextSection } from '../../llm/systemPrompt.js';
6
- import { closeMcpClients } from '../../llm/mcp.js';
7
- import { readSettings } from '../../config/settings.js';
8
- import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
9
1
  import { agentEvent } from '../../core/agent/events.js';
10
- import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
11
- import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
12
- import { userTurnMessage } from '../../core/attachments/imageAttachments.js';
13
- import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
14
- import { estimateValueTokens } from '../../core/agent/contextBudget.js';
15
- import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
16
- import { isDuplicateSkippedOutput, toolInputField, toolOutputOk } from '../../core/agent/toolResults.js';
17
- import { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
18
- export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
19
- import { compactModelMessages } from '../../core/agent/compaction.js';
20
- import { ACTIVE_CONTEXT_TOKEN_BUDGET, DEFAULT_MAX_OUTPUT_TOKENS, IDLE_TIMEOUT_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, MAIN_TOOL_ONLY_STEP_LIMIT } from '../../core/agent/budgets.js';
21
- import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
22
- import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './streaming/assistantText.js';
23
- import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
24
- import { applyToolResultState, initialToolResultState, isMutatingToolName } from './streaming/toolResultState.js';
25
- import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
26
- import { toolsContextFor } from '../../llm/tools/toolContext.js';
2
+ import { createTurnExecutionState, recordGoalContinuation, toCompletionEvidence } from '../../core/agent/completionController.js';
3
+ import { createSessionGoal } from '../../core/agent/goalPolicy.js';
4
+ import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
5
+ import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
6
+ import { createAbsoluteDeadline } from '../../core/deadline.js';
27
7
  import { modelThinkingLabel } from '../../utils/modelName.js';
28
- import { terminalTurnStatus } from './streaming/turnOutcome.js';
29
- import { createIdleTimer } from './streaming/idleTimer.js';
30
- import { WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
31
- function logEntry(log, entry) {
32
- if (log)
33
- void logAppend(log, entry).catch(() => undefined);
34
- }
35
- function withScopedContextControl(messages, context) {
36
- const files = context.pendingContextFiles ?? [];
37
- if (files.length === 0)
38
- return messages;
39
- context.pendingContextFiles = [];
40
- return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
41
- }
42
- async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope) {
43
- let thinkingLabel = modelThinkingLabel(undefined);
44
- callbacks.setBusyLabel?.(thinkingLabel);
45
- let turnStatus = 'failed';
46
- let loadedMcp;
47
- // Tool calls currently executing. A concurrent subagent wave can run for many
48
- // minutes with no stream parts; that is activity, not a dead stream, so the
49
- // idle timer defers while any tool is in flight (see streaming/idleTimer.ts).
50
- const inFlightTools = new Set();
51
- const idleTimer = createIdleTimer({
52
- timeoutMs: IDLE_TIMEOUT_MS,
53
- isBusy: () => inFlightTools.size > 0,
54
- onTimeout: () => abortController.abort('haze turn timed out after no model/tool activity.'),
55
- });
56
- const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
57
- try {
58
- // Single choke point: one fresh settings read per turn, shared by model
59
- // resolution and request assembly (CR-024).
60
- const turnSettings = await readSettings();
61
- const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
62
- if (!runtime?.model) {
63
- callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
64
- turnStatus = 'failed';
65
- return { status: turnStatus };
66
- }
67
- thinkingLabel = modelThinkingLabel(runtime.config.modelName);
68
- callbacks.setBusyLabel?.(thinkingLabel);
69
- let activeContextFiles = contextFiles;
70
- const activeModel = runtime.model;
71
- const providerSettings = providerRequestSettings(runtime.config);
72
- const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, modelRuntime: runtime, subagentOverrides: turnOptions.subagentOverrides, abortSignal: abortController.signal, executionScope: turnScope.executionScope, settings: turnSettings, onSubagentEvent: event => callbacks.onEvent?.(agentEvent(event.type === 'queued'
73
- ? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
74
- : event.type === 'started'
75
- ? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
76
- : event.type === 'terminal'
77
- ? { type: 'subagent_state', id: event.id, state: 'terminal', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: event.execution, running: event.running }
78
- : { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
79
- turnScope.executionScope ??= assembled.executionScope;
80
- const availableTools = assembled.availableTools;
81
- loadedMcp = assembled.loadedMcp;
82
- if (loadedMcp?.errors.length)
83
- callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
84
- const goal = createSessionGoal(value);
85
- callbacks.setWorkState?.(goal);
86
- callbacks.setGoalStatus?.(formatGoalStatus(goal));
87
- const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
88
- const durableRequestMessages = compactToolHistory(retryingExistingRequest
89
- ? stripSyntheticControls(callbacks.getConversation())
90
- : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
91
- let requestMessages = durableRequestMessages;
92
- if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
93
- requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
94
- }
95
- requestMessages = withoutSystemMessages(requestMessages);
96
- callbacks.setConversation(stripSyntheticControls(requestMessages));
97
- if (turnOptions.ephemeralControl)
98
- requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
99
- const systemPrompt = assembled.systemPrompt;
100
- const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
101
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
102
- const previousAssistantText = normalizeAssistantText(callbacks.getLastAssistantText());
103
- const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
104
- const rememberVisibleAssistantText = (text) => {
105
- const normalized = normalizeAssistantText(text);
106
- if (!normalized)
107
- return;
108
- visibleAssistantTexts.add(normalized);
109
- callbacks.setLastAssistantText(text);
110
- };
111
- const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
112
- const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
113
- const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path), mutationPolicy, blessedPaths: turnOptions.blessedPaths };
114
- const startedTools = new Map();
115
- const latestToolCalls = new Map();
116
- let latestAccumulatedResponseMessages = [];
117
- let currentAssistantId = `assistant-${Date.now()}`;
118
- let assistantStarted = false;
119
- let assistantStartedAt = Date.now();
120
- let assistantText = '';
121
- let currentAssistantText = '';
122
- let streamError;
123
- let streamFinished = false;
124
- let finishReason;
125
- let lastToolOk;
126
- let completedSteps = 0;
127
- let completedToolCalls = 0;
128
- let completedToolOnlySteps = 0;
129
- let toolResultState = initialToolResultState();
130
- const resetAssistantSegment = () => {
131
- currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
132
- assistantStarted = false;
133
- assistantStartedAt = Date.now();
134
- currentAssistantText = '';
135
- };
136
- const finalizeAssistantSegment = (options = {}) => {
137
- const finalText = assistantDisplayText(currentAssistantText);
138
- const normalized = normalizeAssistantText(finalText);
139
- const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
140
- || (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
141
- || (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
142
- || (normalized.length > 0 && visibleAssistantTexts.has(normalized));
143
- if (assistantStarted) {
144
- if (!hidden)
145
- rememberVisibleAssistantText(finalText);
146
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden }));
147
- callbacks.updateMessage(currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, assistantStartedAt) });
148
- }
149
- else if (!hidden) {
150
- if (!hidden)
151
- rememberVisibleAssistantText(finalText);
152
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
153
- callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden: false }));
154
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(finalText, assistantStartedAt) });
155
- }
156
- resetAssistantSegment();
157
- return !hidden;
158
- };
159
- const agent = new ToolLoopAgent({
160
- id: 'haze-main',
161
- model: activeModel,
162
- instructions: systemPrompt,
163
- tools: availableTools,
164
- maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
165
- ...providerSettings,
166
- stopWhen: isStepCount(MAIN_STEP_LIMIT),
167
- runtimeContext: toolExecutionContext,
168
- toolsContext: toolsContextFor(availableTools, toolExecutionContext),
169
- prepareStep({ steps, messages }) {
170
- const toolCalls = steps.flatMap(step => step.toolCalls);
171
- const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
172
- const scopedMessages = withScopedContextControl(messages, toolExecutionContext);
173
- const messagesChanged = scopedMessages !== messages;
174
- if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
175
- return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
176
- if (toolResultState.editRecoveryPath && !toolResultState.editRecoveryReadSatisfied)
177
- return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
178
- if (repeatedToolNames.length > 0) {
179
- const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
180
- callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
181
- return activeTools.length > 0
182
- ? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
183
- : { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
184
- }
185
- if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= MAIN_TOOL_ONLY_STEP_LIMIT) {
186
- callbacks.debugLog('forcing text response to avoid tool loop');
187
- return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
188
- }
189
- return messagesChanged ? { messages: scopedMessages } : undefined;
190
- },
191
- onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
192
- completedSteps++;
193
- completedToolCalls += toolCalls.length;
194
- if (toolCalls.length > 0 && text.trim().length === 0)
195
- completedToolOnlySteps++;
196
- if (Array.isArray(response?.messages) && response.messages.length > 0)
197
- latestAccumulatedResponseMessages = response.messages;
198
- const stepUsage = stepCacheMetrics(usage);
199
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, text, finishReason, usage: { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens, cacheReadTokens: stepUsage.cacheReadTokens || undefined, cacheWriteTokens: stepUsage.cacheWriteTokens || undefined, noCacheTokens: stepUsage.noCacheTokens || undefined, reasoningTokens: stepUsage.reasoningTokens || undefined, cacheHitRatio: stepUsage.cacheHitRatio } });
200
- callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
201
- },
202
- onEnd(event) {
203
- const providerUsage = extractUsage({ usage: event.usage });
204
- callbacks.recordTokenUsage?.({
205
- inputTokens: providerUsage.inputTokens,
206
- outputTokens: providerUsage.outputTokens,
207
- systemPrompt: inputBreakdown.systemPrompt,
208
- messages: inputBreakdown.messages,
209
- toolSchemas: inputBreakdown.toolSchemas,
210
- outputEstimate: estimateValueTokens(event.responseMessages),
211
- cacheReadTokens: providerUsage.cacheReadTokens,
212
- cacheWriteTokens: providerUsage.cacheWriteTokens,
213
- noCacheTokens: providerUsage.noCacheTokens,
214
- reasoningTokens: providerUsage.reasoningTokens,
215
- logicalInputEstimate: inputBreakdown.logicalInputEstimate,
216
- effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
217
- });
218
- const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
219
- const compacted = compactToolHistory(accumulated);
220
- callbacks.setConversation(compacted.messages);
221
- callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
222
- },
223
- });
224
- idleTimer.reset();
225
- const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
226
- for await (const part of result.stream) {
227
- idleTimer.reset();
228
- switch (part.type) {
229
- case 'text-delta': {
230
- callbacks.setBusyLabel?.(thinkingLabel);
231
- toolDisplay.startFreshToolGroup();
232
- const delta = sanitizeAssistantText(part.text);
233
- assistantText += delta;
234
- currentAssistantText += delta;
235
- const displayText = assistantDisplayText(currentAssistantText);
236
- if (!assistantStarted && !shouldStartAssistantStream(displayText, assistantStartedAt))
237
- break;
238
- if (!assistantStarted) {
239
- assistantStarted = true;
240
- assistantStartedAt = Date.now();
241
- callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
242
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: assistantStartedAt });
243
- }
244
- else {
245
- callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
246
- callbacks.updateMessage(currentAssistantId, { text: displayText });
247
- }
248
- break;
249
- }
250
- case 'tool-input-start': {
251
- if (currentAssistantText.trim().length > 0 || assistantStarted) {
252
- const pending = assistantDisplayText(currentAssistantText);
253
- const shown = finalizeAssistantSegment({ beforeTool: true });
254
- if (!shown && pending)
255
- toolDisplay.setGroupCaption(pending);
256
- }
257
- const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
258
- latestToolCalls.set(part.id, toolCall);
259
- startedTools.set(part.id, Date.now());
260
- inFlightTools.add(part.id);
261
- callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
262
- toolDisplay.ensureToolItem(toolCall);
263
- break;
264
- }
265
- case 'tool-call': {
266
- if (currentAssistantText.trim().length > 0 || assistantStarted) {
267
- const pending = assistantDisplayText(currentAssistantText);
268
- const shown = finalizeAssistantSegment({ beforeTool: true });
269
- if (!shown && pending)
270
- toolDisplay.setGroupCaption(pending);
271
- }
272
- const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
273
- latestToolCalls.set(part.toolCallId, toolCall);
274
- if (!startedTools.has(part.toolCallId))
275
- startedTools.set(part.toolCallId, Date.now());
276
- callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
277
- toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
278
- toolDisplay.updateToolGroup(true);
279
- break;
280
- }
281
- case 'tool-result': {
282
- const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
283
- latestToolCalls.set(part.toolCallId, toolCall);
284
- inFlightTools.delete(part.toolCallId);
285
- const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
286
- const ok = toolOutputOk(part.output, true);
287
- lastToolOk = ok;
288
- const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
289
- const item = toolDisplay.ensureToolItem(toolCall);
290
- item.status = ok ? 'success' : 'error';
291
- item.result = toolResultSummary(finish);
292
- item.durationMs = finish.durationMs;
293
- item.finishedAt = startedAt + finish.durationMs;
294
- callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs }));
295
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs } });
296
- toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
297
- observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
298
- callbacks.setWorkState?.(goal);
299
- callbacks.setGoalStatus?.(formatGoalStatus(goal));
300
- activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
301
- if (toolCall.toolName === 'writeTasks')
302
- callbacks.onTasksChanged?.();
303
- const nestedTokens = subagentTokenEstimate(part.output);
304
- if (nestedTokens)
305
- callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
306
- toolDisplay.updateToolGroup(true);
307
- break;
308
- }
309
- case 'tool-error': {
310
- inFlightTools.delete(part.toolCallId);
311
- const existing = latestToolCalls.get(part.toolCallId);
312
- const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
313
- const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
314
- lastToolOk = false;
315
- const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
316
- const item = toolDisplay.ensureToolItem(toolCall);
317
- item.status = 'error';
318
- item.result = toolResultSummary(finish);
319
- item.durationMs = finish.durationMs;
320
- item.finishedAt = startedAt + finish.durationMs;
321
- callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs }));
322
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs } });
323
- if (isMutatingToolName(toolCall.toolName)) {
324
- toolResultState = { ...toolResultState, editRecoveryPath: toolInputField(toolCall.input, 'path'), editRecoveryReadSatisfied: false };
325
- }
326
- observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
327
- callbacks.setWorkState?.(goal);
328
- callbacks.setGoalStatus?.(formatGoalStatus(goal));
329
- toolDisplay.updateToolGroup(true);
330
- break;
331
- }
332
- case 'error':
333
- streamError = part.error;
334
- callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
335
- break;
336
- case 'finish':
337
- streamFinished = true;
338
- finishReason = part.finishReason;
339
- callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
340
- break;
341
- default:
342
- break;
343
- }
344
- }
345
- if (streamError && !streamFinished) {
346
- void Promise.resolve(result.responseMessages).catch(() => undefined);
347
- throw streamError;
348
- }
349
- try {
350
- const responseMessages = await result.responseMessages;
351
- const completedConversation = [...stripSyntheticControls(requestMessages), ...responseMessages];
352
- callbacks.setConversation(compactToolHistory(completedConversation).messages);
353
- }
354
- catch (error) {
355
- if (latestAccumulatedResponseMessages.length > 0) {
356
- callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
357
- }
358
- const text = error instanceof Error ? error.message : String(error);
359
- const benignTerminatedAfterStream = text === 'terminated' && (streamFinished || assistantText.trim().length > 0 || latestToolCalls.size > 0);
360
- if (!benignTerminatedAfterStream)
361
- throw streamError ?? error;
362
- callbacks.debugLog(`ignored post-stream response error: ${text}`);
363
- }
364
- if (currentAssistantText.trim().length > 0 || assistantStarted) {
365
- finalizeAssistantSegment();
366
- }
367
- else if (latestToolCalls.size > 0) {
368
- callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
369
- }
370
- const budgetReached = finishReason === 'length'
371
- || completedSteps >= MAIN_STEP_LIMIT
372
- || completedToolCalls >= MAIN_TOOL_CALL_LIMIT
373
- || completedToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT;
374
- turnStatus = terminalTurnStatus({ aborted: false, assistantText, sawToolCall: latestToolCalls.size > 0, lastToolOk, finishReason, budgetReached });
375
- goal.phase = 'done';
376
- goal.status = turnStatus === 'complete' ? 'complete' : 'blocked';
377
- callbacks.setWorkState?.(goal);
378
- callbacks.setGoalStatus?.(undefined);
379
- }
380
- catch (error) {
381
- if (abortController.signal.aborted) {
382
- turnStatus = 'aborted';
383
- callbacks.debugLog('request aborted');
384
- callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
385
- }
386
- else {
387
- const text = error instanceof Error ? error.message : String(error);
388
- callbacks.debugLog(`error: ${text}`);
389
- if (!contextOverflowRecovered && isContextOverflowError(error)) {
390
- const compacted = callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false;
391
- callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
392
- if (compacted) {
393
- callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
394
- return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
395
- }
396
- callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
397
- }
398
- const maxRetries = 2;
399
- if (retryAttempt < maxRetries && isRetryableModelError(error)) {
400
- const delay = retryDelayMs(retryAttempt);
401
- callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
402
- callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
403
- return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
404
- }
405
- callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
406
- }
407
- }
408
- finally {
409
- if (loadedMcp?.clients.length)
410
- await closeMcpClients(loadedMcp.clients);
411
- idleTimer.clear();
412
- toolDisplay.stopToolTimer();
413
- toolDisplay.finalizeToolGroup();
414
- }
415
- return { status: turnStatus };
416
- }
8
+ import { abortableDelay } from './streaming/turnRuntime.js';
9
+ import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
10
+ import { runAgentAttempt } from './streaming/agentAttempt.js';
11
+ import { projectGoalEvidence } from './streaming/attemptOutcome.js';
12
+ import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
13
+ import { formatIdleMinutes } from './streaming/stallRecovery.js';
417
14
  export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
418
- const abortController = new AbortController();
15
+ // The controller is replaced when an idle-stall retry needs a live signal
16
+ // after aborting a hung stream, so both it and the cause are mutable.
17
+ let abortController = new AbortController();
18
+ let abortCause = createUserAbortCause();
419
19
  let status = 'failed';
20
+ let abortReason;
21
+ let resume;
22
+ const turnState = createTurnExecutionState();
420
23
  callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
421
24
  callbacks.setBusy(true);
422
25
  callbacks.setAbortController?.(abortController);
423
26
  if (!retryingExistingRequest)
424
27
  callbacks.addMessage({ role: 'user', text: displayValue ?? value });
28
+ let turnDeadline;
29
+ const turnStartedAt = Date.now();
30
+ const turnDeadlineMs = turnOptions.turnDeadlineMs ?? DEFAULT_TURN_DEADLINE_MS;
425
31
  try {
426
32
  // Retries are one logical turn and therefore share coordinator admission and
427
- // the workspace mutation lease, including quarantined lingering work.
428
- const turnScope = {};
33
+ // the workspace mutation lease, including quarantined lingering work. A
34
+ // goal supervisor may pass one shared scope so every physical turn of the
35
+ // logical goal shares the same lease.
36
+ const turnScope = turnOptions.sharedTurnScope ?? {};
37
+ const turnBudget = mainTurnBudget();
38
+ // Turn-wide execution budget (RH-003): one authoritative counter of
39
+ // underlying tool executions, shared across retries and recovery slices so
40
+ // the global limit cannot be reset or exceeded. The slice budget caps the
41
+ // current slice (main phase or one recovery slice): it is shared by every
42
+ // attempt in that slice and reset only when a new slice is admitted, so a
43
+ // provider retry inside a rescue can never re-arm the slice cap (C2).
44
+ const globalBudget = createToolExecutionBudget();
45
+ const sliceBudget = createToolExecutionBudget();
46
+ // Turn-wide work state: persists across provider retries and recovery
47
+ // slices so mutation/validation evidence accumulates correctly. When the
48
+ // goal supervisor continues a logical goal, cumulative evidence (tasks,
49
+ // mutations, carried validation) is hydrated so a fresh physical turn
50
+ // cannot complete while carried work remains.
51
+ const goal = createSessionGoal(value);
52
+ if (turnOptions.goalContext)
53
+ seedCarriedGoalEvidence(goal, turnOptions.goalContext.carried);
54
+ // Completion policy is intent-sensitive (implement/fix/test expect
55
+ // post-mutation validation); the turn-wide state carries the classified intent.
56
+ turnState.intent = goal.intent;
57
+ let activeOptions = turnOptions;
429
58
  let attempt = retryAttempt;
430
59
  let overflowRecovered = contextOverflowRecovered;
431
60
  let retrying = retryingExistingRequest;
61
+ // The attempt machinery runs against quarantinable callbacks so an
62
+ // abort-ignoring stream that outlives forced settlement cannot mutate the
63
+ // finished turn's UI, conversation, or session state.
64
+ const { callbacks: attemptCallbacks, quarantine } = createQuarantinableCallbacks(callbacks);
432
65
  while (true) {
433
- const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController, turnOptions, turnScope);
66
+ // Absolute main-turn deadline (RH-004): distinct from the idle timer, it
67
+ // bounds total turn elapsed time so a stream of busy tools cannot defer
68
+ // it. Recreated per attempt with the remaining wall-clock budget and bound
69
+ // to the current attempt's controller — an idle-stall retry replaces the
70
+ // controller and must not trip this deadline early via the old signal.
71
+ turnDeadline = createAbsoluteDeadline({
72
+ timeoutMs: Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)),
73
+ signal: abortController.signal,
74
+ onTimeout: () => {
75
+ if (abortController.signal.aborted)
76
+ return;
77
+ callbacks.onEvent?.(agentEvent({ type: 'timeout', phase: 'turn', timeoutMs: turnDeadlineMs }));
78
+ abortForTurn(abortCause, { kind: 'turn-deadline', timeoutMs: turnDeadlineMs }, abortController, `haze turn exceeded the ${turnDeadlineMs}ms absolute deadline.`);
79
+ },
80
+ });
81
+ const cleanup = createAttemptCleanupRegistry();
82
+ const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, contextOverflowRecovered: overflowRecovered, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)) }), {
83
+ abortController,
84
+ cleanup,
85
+ quarantine,
86
+ onForced: tornDown => {
87
+ // The attempt ignored cancellation past the grace window: settle the
88
+ // turn ourselves, truthfully reporting whether teardown completed.
89
+ turnState.aborted = true;
90
+ callbacks.debugLog(`attempt ignored cancellation; forced settlement after grace (teardown ${tornDown ? 'completed' : 'still settling'})`);
91
+ callbacks.addMessage({ role: 'system', text: abortCause.kind === 'turn-deadline'
92
+ ? `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? turnDeadlineMs)} turn budget elapsed before the model finished.${tornDown ? '' : ' Some background teardown is still settling.'} Completed steps are preserved in the conversation; send a follow-up to continue.`
93
+ : 'Thinking aborted. You can type again.' });
94
+ return { status: 'aborted', abortReason: abortCause.kind === 'turn-deadline' ? 'turn-deadline' : 'user' };
95
+ },
96
+ });
97
+ turnDeadline.clear();
98
+ turnDeadline = undefined;
434
99
  status = result.status;
435
- if (!result.retry)
436
- break;
437
- attempt = result.retry.attempt;
438
- overflowRecovered = result.retry.contextOverflowRecovered;
439
- retrying = true;
440
- if (result.retry.delayMs > 0)
441
- await abortableDelay(result.retry.delayMs, abortController.signal);
442
- if (abortController.signal.aborted) {
443
- status = 'aborted';
444
- break;
100
+ abortReason = result.abortReason;
101
+ resume = result.resume;
102
+ if (result.retry) {
103
+ attempt = result.retry.attempt;
104
+ overflowRecovered = result.retry.contextOverflowRecovered;
105
+ retrying = true;
106
+ if (result.retry.freshController) {
107
+ // The idle stall aborted the previous controller to kill the hung
108
+ // stream; the retry needs a live one (and a fresh 'user' cause).
109
+ abortController = new AbortController();
110
+ abortCause = createUserAbortCause();
111
+ callbacks.setAbortController?.(abortController);
112
+ }
113
+ if (result.retry.delayMs > 0)
114
+ await abortableDelay(result.retry.delayMs, abortController.signal);
115
+ if (abortController.signal.aborted) {
116
+ status = 'aborted';
117
+ break;
118
+ }
119
+ continue;
120
+ }
121
+ // Bounded recovery slice (length-continuation, rescue, or goal
122
+ // continuation). Length/rescue credits are single-use, so a slice cannot
123
+ // trigger another of the same kind; goal continuation is repeatable but
124
+ // progress-guarded and counts against the shared turn budget. Abort is
125
+ // re-checked before and within the slice.
126
+ if (result.recovery && !abortController.signal.aborted) {
127
+ const rec = result.recovery;
128
+ if (rec.kind === 'length') {
129
+ turnState.lengthCreditUsed = true;
130
+ turnState.lengthRecoveriesAttempted += 1;
131
+ }
132
+ else if (rec.kind === 'rescue')
133
+ turnState.rescueUsed = true;
134
+ else
135
+ recordGoalContinuation(turnState);
136
+ // A new slice gets a fresh execution allowance, clamped once here; the
137
+ // slice budget persists across provider retries within the slice (C2).
138
+ sliceBudget.started = 0;
139
+ sliceBudget.exceeded = false;
140
+ activeOptions = { ...activeOptions, ephemeralControl: rec.control, recoverySlice: { kind: rec.kind, maxSteps: rec.slice.maxSteps, maxToolCalls: rec.slice.maxToolCalls } };
141
+ retrying = true;
142
+ callbacks.debugLog(`starting ${rec.kind} recovery slice: ${rec.slice.maxSteps} steps / ${rec.slice.maxToolCalls} tool calls`);
143
+ continue;
445
144
  }
145
+ break;
446
146
  }
447
- return { status };
147
+ projectGoalEvidence(turnState, goal);
148
+ const evidence = toCompletionEvidence(turnState);
149
+ return { status, evidence, ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
448
150
  }
449
151
  finally {
450
- callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status }));
152
+ turnDeadline?.clear();
153
+ callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState) }));
451
154
  callbacks.setAbortController?.(null);
452
155
  callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
453
156
  callbacks.setBusy(false);