@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,11 +1,15 @@
1
1
  import { readContextFiles } from '../../config/contextFiles.js';
2
- import { runAgentTurn } from './streaming.js';
2
+ import { runAgentGoal } from './streaming/goalSupervisor.js';
3
3
  import { EMPTY_TOKEN_USAGE, accumulateTokenUsage } from '../chat/turnState.js';
4
4
  import { readSettings } from '../../config/settings.js';
5
5
  import { activeModel, modelSelector, resolveModelSelector } from '../../config/providers.js';
6
6
  import { createLog, endLog } from '../../core/log/llmLog.js';
7
7
  import { findSession, restoreSessionState } from '../../core/session/sessionStore.js';
8
+ import { compactModelMessages } from '../../core/agent/compaction.js';
9
+ import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
8
10
  import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
11
+ import { MAX_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
12
+ import { NdjsonSink } from './ndjsonSink.js';
9
13
  function pinnedUsage(usage) {
10
14
  // Normalize every field to a number: TokenUsage seeds most fields to 0 but
11
15
  // inputTokens/outputTokens may be undefined until the first report. A uniform ?? 0
@@ -18,35 +22,84 @@ function pinnedUsage(usage) {
18
22
  reasoningTokens: usage.reasoningTokens ?? 0,
19
23
  };
20
24
  }
25
+ /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
26
+ export function parseTurnTimeoutMs(raw) {
27
+ if (raw === undefined || raw.trim() === '')
28
+ return undefined;
29
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(raw.trim());
30
+ if (!match)
31
+ throw new Error(`Invalid --timeout '${raw}'. Use a number with optional ms/s/m/h units (e.g. 30s, 10m, 2h).`);
32
+ const value = Number(match[1]);
33
+ const unit = match[2] ?? 'ms';
34
+ const multiplier = unit === 'ms' ? 1 : unit === 's' ? 1000 : unit === 'm' ? 60_000 : 3_600_000;
35
+ const ms = Math.round(value * multiplier);
36
+ if (ms < 1000)
37
+ throw new Error(`--timeout must be at least 1 second (got ${ms}ms).`);
38
+ if (ms > MAX_TURN_DEADLINE_MS)
39
+ throw new Error(`--timeout must be at most 24 hours (got ${ms}ms).`);
40
+ return ms;
41
+ }
21
42
  function errorText(error) {
22
- return error instanceof Error ? error.message : String(error);
43
+ const value = error instanceof Error ? error.message : String(error);
44
+ const normalized = value.replace(/\p{Cc}+/gu, ' ').replace(/\s+/g, ' ').trim();
45
+ return normalized.length <= 500 ? normalized : `${normalized.slice(0, 499)}…`;
23
46
  }
24
47
  function toHeadlessStreamEvent(event) {
25
48
  switch (event.type) {
26
49
  case 'turn_start':
27
50
  return { type: 'turn_start', request: event.request, at: event.at };
28
51
  case 'turn_end':
29
- return { type: 'turn_end', request: event.request, status: event.status, at: event.at };
52
+ return { ...(event.evidence ? { evidence: event.evidence } : {}), type: 'turn_end', request: event.request, status: event.status, at: event.at };
53
+ case 'goal_start':
54
+ return { type: 'goal_start', goalId: event.goalId, request: event.request, at: event.at };
55
+ case 'goal_continue':
56
+ return { type: 'goal_continue', goalId: event.goalId, cycle: event.cycle, reason: event.reason, at: event.at };
57
+ case 'goal_end':
58
+ return { ...(event.stopReason ? { stopReason: event.stopReason } : {}), ...(event.evidence ? { evidence: event.evidence } : {}), type: 'goal_end', goalId: event.goalId, status: event.status, cycles: event.cycles, at: event.at };
59
+ case 'step_start':
60
+ return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
61
+ case 'step_end':
62
+ return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, ...(event.responseModel ? { responseModel: event.responseModel } : {}), at: event.at };
30
63
  case 'message_start':
31
64
  return { type: 'message_start', id: event.id, role: event.role, at: event.at };
32
65
  case 'message_update':
33
- return { type: 'message_update', id: event.id, text: event.text, at: event.at };
66
+ // Handled directly in emitStreamEvent with delta tracking; this case is
67
+ // unreachable but kept for type exhaustiveness.
68
+ return undefined;
34
69
  case 'message_end':
35
70
  return { ...(event.hidden === undefined ? {} : { hidden: event.hidden }), type: 'message_end', id: event.id, text: event.text, at: event.at };
36
71
  case 'tool_start':
37
72
  // Intentionally omit raw tool input: stdout is often persisted by harnesses/CI.
38
73
  return { type: 'tool_start', id: event.id, name: event.name, at: event.at };
39
74
  case 'tool_end':
40
- return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
75
+ return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.errorCode === undefined ? {} : { errorCode: event.errorCode }), ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
41
76
  case 'retry':
42
77
  return { type: 'retry', attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, error: event.error, at: event.at };
43
78
  case 'context_overflow':
44
79
  return { type: 'context_overflow', recovered: event.recovered, error: event.error, at: event.at };
80
+ case 'timeout':
81
+ return { type: 'timeout', phase: event.phase, timeoutMs: event.timeoutMs, at: event.at };
82
+ case 'reasoning_policy':
83
+ return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
84
+ case 'context_budget':
85
+ return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
45
86
  }
46
87
  }
47
88
  function writeNdjson(value) {
48
89
  process.stdout.write(`${JSON.stringify(value)}\n`);
49
90
  }
91
+ /** Apply a cumulative-text message_update as a delta against the last emitted text for the segment. */
92
+ function messageUpdateDelta(event, emitted) {
93
+ const prev = emitted.get(event.id) ?? '';
94
+ // Delta from the last emitted text. If display sanitization reset the suffix,
95
+ // re-emit from offset 0 so consumers can reconstruct the exact final text.
96
+ const delta = event.text.startsWith(prev) ? event.text.slice(prev.length) : event.text;
97
+ const offset = event.text.startsWith(prev) ? prev.length : 0;
98
+ emitted.set(event.id, event.text);
99
+ if (delta.length === 0)
100
+ return undefined;
101
+ return { type: 'message_update', id: event.id, delta, offset, at: event.at };
102
+ }
50
103
  /**
51
104
  * Resolve the model the run will use *before* invoking the agent, so a bad `--model`
52
105
  * selector or a missing provider produces a precise error (not the generic no-provider
@@ -71,6 +124,14 @@ async function resolveModelOrError(modelOverride) {
71
124
  return undefined;
72
125
  }
73
126
  export async function runHeadless(options) {
127
+ let turnDeadlineMs;
128
+ try {
129
+ turnDeadlineMs = parseTurnTimeoutMs(options.timeout);
130
+ }
131
+ catch (error) {
132
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
133
+ return 2;
134
+ }
74
135
  const resumed = options.resumeSessionId ? await findSession(options.resumeSessionId) : undefined;
75
136
  if (options.resumeSessionId && !resumed) {
76
137
  process.stderr.write(`No session named ${options.resumeSessionId} exists for this workspace.\n`);
@@ -104,11 +165,23 @@ export async function runHeadless(options) {
104
165
  let log;
105
166
  if (options.debug)
106
167
  log = await createLog();
107
- const emitStreamEvent = options.output === 'stream-json'
168
+ const streamSink = options.output === 'stream-json' ? new NdjsonSink(process.stdout) : undefined;
169
+ // Last cumulative text emitted per segment, used to derive deltas (RH-006) so
170
+ // the total stream-json update payload is linear in the final text size.
171
+ const emittedSegmentText = new Map();
172
+ const emitStreamEvent = options.output === 'stream-json' && streamSink
108
173
  ? (event) => {
174
+ if (event.type === 'message_update') {
175
+ const delta = messageUpdateDelta(event, emittedSegmentText);
176
+ if (delta)
177
+ void streamSink.write(delta);
178
+ return;
179
+ }
180
+ if (event.type === 'message_end')
181
+ emittedSegmentText.delete(event.id);
109
182
  const headlessEvent = toHeadlessStreamEvent(event);
110
183
  if (headlessEvent)
111
- writeNdjson(headlessEvent);
184
+ void streamSink.write(headlessEvent);
112
185
  }
113
186
  : undefined;
114
187
  const callbacks = {
@@ -139,15 +212,39 @@ export async function runHeadless(options) {
139
212
  recordTokenUsage: (u) => {
140
213
  usage = accumulateTokenUsage(usage, u);
141
214
  },
215
+ compactConversation: (instructions) => {
216
+ // Headless context-overflow recovery (F-10): compact the in-scope
217
+ // conversation exactly like the interactive fallback path so a long CI
218
+ // run self-heals instead of dying on the first provider overflow.
219
+ const result = compactModelMessages(conversation, { instructions, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS });
220
+ if (!result.compacted)
221
+ return false;
222
+ conversation = result.messages;
223
+ return true;
224
+ },
142
225
  onEvent: emitStreamEvent,
143
226
  log,
144
227
  };
145
228
  let status;
146
229
  let result;
230
+ let evidence;
231
+ let goal;
147
232
  let persistenceError;
148
233
  let backgroundTeardownError;
149
234
  try {
150
- ({ status } = await runAgentTurn(options.prompt, options.prompt, contextFiles, callbacks, 0, false, false, session, options.modelOverride));
235
+ // The logical-goal supervisor owns the whole request: `--timeout` bounds
236
+ // the entire goal, and per-turn budgets merely end physical turns that
237
+ // continue automatically while recoverable work and progress remain.
238
+ const goalResult = await runAgentGoal({ request: options.prompt, displayValue: options.prompt, contextFiles, callbacks, session, modelOverride: options.modelOverride, ...(turnDeadlineMs != null ? { goalDeadlineMs: turnDeadlineMs } : {}) });
239
+ status = goalResult.status;
240
+ evidence = goalResult.evidence;
241
+ goal = {
242
+ cycles: goalResult.cycles,
243
+ stopReason: goalResult.stopReason,
244
+ mutations: goalResult.evidence?.mutationCount ?? 0,
245
+ ...(goalResult.evidence && goalResult.evidence.validationOutcome !== 'not_applicable' ? { validationOutcome: goalResult.evidence.validationOutcome } : {}),
246
+ ...(goalResult.evidence?.taskProgress ? { taskProgress: goalResult.evidence.taskProgress } : {}),
247
+ };
151
248
  result = segments.filter((s) => !s.hidden && s.text).map((s) => s.text).join('\n');
152
249
  }
153
250
  catch (error) {
@@ -168,9 +265,18 @@ export async function runHeadless(options) {
168
265
  if (persistenceError)
169
266
  process.stderr.write(`haze persistence warning: ${persistenceError}\n`);
170
267
  if (options.output === 'json' || options.output === 'stream-json') {
171
- // For stream-json the authoritative agent events have already streamed above; this is the terminal line.
172
- // It is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
173
- writeNdjson({ type: 'result', status, result, usage: pinnedUsage(usage) });
268
+ // For stream-json the authoritative agent events have already streamed; flush
269
+ // them before the terminal result so ordering is preserved under backpressure.
270
+ if (streamSink)
271
+ await streamSink.flush().catch(() => undefined);
272
+ // This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
273
+ const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}) };
274
+ if (streamSink)
275
+ await streamSink.write(resultLine).catch(() => undefined);
276
+ else
277
+ writeNdjson(resultLine);
278
+ if (streamSink)
279
+ await streamSink.flush().catch(() => undefined);
174
280
  }
175
281
  else if (status === 'complete') {
176
282
  process.stdout.write(result + (result.endsWith('\n') ? '' : '\n'));
@@ -0,0 +1,34 @@
1
+ import { type HazeLspServer } from '../../config/lspSettings.js';
2
+ import type { HazeMcpServer, HazeSettings } from '../../config/settings.js';
3
+ /**
4
+ * Pure result functions for the LSP and MCP server wizard flows. The
5
+ * corresponding steps (placeholders, kinds, suggestions) live in
6
+ * `wizardFlow.ts`; the submit orchestration lives in
7
+ * `chat/wizardDispatch.ts`.
8
+ */
9
+ export type LspWizardResult = {
10
+ message?: string;
11
+ mode?: 'chat' | 'lsp' | 'lspAction' | 'lspAddName' | 'lspConfirmRemove';
12
+ selectedName?: string;
13
+ settingsPatch?: Partial<HazeSettings>;
14
+ server?: HazeLspServer;
15
+ clearDraft?: boolean;
16
+ };
17
+ export declare function selectLspServerResult(settings: HazeSettings, serverName: string): LspWizardResult;
18
+ export declare function selectLspPresetResult(settings: HazeSettings, presetId: string): LspWizardResult;
19
+ export declare function selectLspActionResult(settings: HazeSettings, selectedName: string | undefined, action: string): LspWizardResult;
20
+ export declare function finishLspCustomResult(settings: HazeSettings, draftName: string | undefined, commandLine: string): LspWizardResult;
21
+ export type McpWizardResult = {
22
+ message?: string;
23
+ mode?: 'chat' | 'mcp' | 'mcpAction' | 'mcpAddName' | 'mcpAddKey' | 'mcpSetKey' | 'mcpConfirmRemove';
24
+ selectedName?: string;
25
+ draft?: Partial<HazeMcpServer>;
26
+ settingsPatch?: Partial<HazeSettings>;
27
+ server?: HazeMcpServer;
28
+ clearDraft?: boolean;
29
+ };
30
+ export declare function selectMcpServerResult(settings: HazeSettings, serverName: string): McpWizardResult;
31
+ export declare function selectMcpPresetResult(settings: HazeSettings, presetId: string): McpWizardResult;
32
+ export declare function selectMcpActionResult(settings: HazeSettings, selectedName: string | undefined, action: string): McpWizardResult;
33
+ export declare function finishMcpCustomResult(settings: HazeSettings, draft: Partial<HazeMcpServer>, keyValue?: string): McpWizardResult;
34
+ export declare function setMcpServerKeyResult(settings: HazeSettings, selectedName: string | undefined, keyValue: string): McpWizardResult;
@@ -1,6 +1,48 @@
1
+ import { configuredLspServers, lspPreset, upsertLspServer, setLspServerEnabled } from '../../config/lspSettings.js';
1
2
  import { findMcpPreset, findMcpServer, toggleMcpServer, upsertMcpServer } from '../../config/mcpSettings.js';
2
- import { COMMON_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, SERVER_CHOICES } from './wizardActions.js';
3
3
  import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
4
+ import { COMMON_ACTIONS, LSP_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, SERVER_CHOICES, commandParts } from './wizardFlow.js';
5
+ export function selectLspServerResult(settings, serverName) {
6
+ if (serverName === SERVER_CHOICES.addServer)
7
+ return { mode: 'lspAddName', clearDraft: true, message: 'Choose an LSP preset, or select "custom" to enter a name and command manually.' };
8
+ const server = configuredLspServers(settings).find(candidate => candidate.name === serverName);
9
+ if (!server)
10
+ return { mode: 'chat', message: `No LSP server named ${serverName}. Use /lsp and choose add server.` };
11
+ return { mode: 'lspAction', selectedName: server.name, message: `${server.name}: choose an action.` };
12
+ }
13
+ export function selectLspPresetResult(settings, presetId) {
14
+ if (presetId === SERVER_CHOICES.custom)
15
+ return { mode: 'lspAddName', clearDraft: true, message: 'LSP server name? Example: typescript, rust, my-lsp.' };
16
+ const preset = lspPreset(presetId);
17
+ if (!preset)
18
+ return { message: `Unknown preset: ${presetId}.` };
19
+ if (configuredLspServers(settings).some(server => server.name === preset.name))
20
+ return { mode: 'chat', message: `LSP server ${preset.name} already exists. Use /lsp to manage existing servers.` };
21
+ return { mode: 'chat', server: preset, settingsPatch: { lspServers: upsertLspServer(settings, preset) }, message: `Added LSP preset ${preset.name}. Ensure ${preset.command} is installed and on PATH; tools appear once it is.` };
22
+ }
23
+ export function selectLspActionResult(settings, selectedName, action) {
24
+ if (!selectedName)
25
+ return { mode: 'lsp' };
26
+ const server = configuredLspServers(settings).find(candidate => candidate.name === selectedName);
27
+ if (!server)
28
+ return { mode: 'chat', selectedName: undefined, message: `LSP server ${selectedName} not found.` };
29
+ if (action === COMMON_ACTIONS.enable || action === COMMON_ACTIONS.disable) {
30
+ const enabled = action === COMMON_ACTIONS.enable;
31
+ return { mode: 'chat', selectedName: undefined, settingsPatch: { lspServers: setLspServerEnabled(settings, selectedName, enabled) }, message: `LSP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
32
+ }
33
+ if (action === LSP_ACTIONS.removeServer)
34
+ return { mode: 'lspConfirmRemove', message: `Remove LSP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
35
+ return { message: `Unknown LSP action: ${action}` };
36
+ }
37
+ export function finishLspCustomResult(settings, draftName, commandLine) {
38
+ const name = draftName?.trim();
39
+ const parts = commandParts(commandLine);
40
+ const command = parts[0];
41
+ if (!name || !command)
42
+ return { mode: 'chat', clearDraft: true, message: 'LSP server name and command are required.' };
43
+ const server = { name, command, args: parts.slice(1), extensions: [], rootPatterns: ['.git'], enabled: true };
44
+ return { mode: 'chat', clearDraft: true, server, settingsPatch: { lspServers: upsertLspServer(settings, server) }, message: `Added LSP server ${name} (${command}${parts.length > 1 ? ` ${parts.slice(1).join(' ')}` : ''}). Add extensions in ~/.haze/settings.json so tools can auto-select it.` };
45
+ }
4
46
  export function selectMcpServerResult(settings, serverName) {
5
47
  if (serverName === SERVER_CHOICES.addServer)
6
48
  return { mode: 'mcpAddName', clearDraft: true, message: 'Choose an MCP preset, or select "custom" to enter details manually.' };
@@ -33,7 +75,7 @@ export function selectMcpActionResult(settings, selectedName, action) {
33
75
  const enabled = action === COMMON_ACTIONS.enable;
34
76
  return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: toggleMcpServer(settings, selectedName, enabled) ?? [] }, message: `MCP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
35
77
  }
36
- if (action === MCP_ACTIONS.setApiKey) {
78
+ if (action === MCP_ACTIONS.manageAccess) {
37
79
  if (server.transport === 'stdio')
38
80
  return { mode: 'chat', selectedName: undefined, message: 'Stdio MCP authentication must be handled by its command or wrapper; HTTP headers do not apply.' };
39
81
  return { mode: 'mcpSetKey', message: `New API key for ${selectedName}? (current: ${server.headers?.length ? 'saved' : 'not set'}) Sent as Authorization: Bearer <value>.` };
@@ -0,0 +1,41 @@
1
+ import type { HazeSettings } from '../../config/settings.js';
2
+ import type { LoadedSkill } from '../../skills/types.js';
3
+ /**
4
+ * Pure result functions for the skills wizard flow: selection, actions,
5
+ * creation-from-description, and confirm-remove. Steps live in
6
+ * `wizardFlow.ts`; submit orchestration in `chat/wizardDispatch.ts`.
7
+ */
8
+ export type SkillWizardResult = {
9
+ message?: string;
10
+ mode?: 'chat' | 'skills' | 'skillsAction' | 'skillsAddName' | 'skillsConfirmRemove';
11
+ selectedName?: string;
12
+ settingsPatch?: Partial<HazeSettings>;
13
+ clearDraft?: boolean;
14
+ };
15
+ export declare function selectSkillResult(skills: LoadedSkill[], name: string): SkillWizardResult;
16
+ export declare function skillInfoMessage(settings: HazeSettings, skill: LoadedSkill): string;
17
+ export declare function selectSkillActionResult(settings: HazeSettings, skills: LoadedSkill[], selectedName: string | undefined, action: string): SkillWizardResult & {
18
+ skill?: LoadedSkill;
19
+ validate?: boolean;
20
+ };
21
+ export type SkillCreationResult = {
22
+ busy?: boolean;
23
+ busyLabel?: string;
24
+ message?: string;
25
+ description?: string;
26
+ draftName?: string;
27
+ mode?: 'chat';
28
+ clearDraft?: boolean;
29
+ };
30
+ export declare function captureSkillDescription(value: string, draftName: string | undefined): SkillCreationResult;
31
+ export declare function skillCreationMessage(name: string, file: string): string;
32
+ export declare function skillCreationFailure(error: unknown): string;
33
+ export type SkillConfirmRemoveResult = {
34
+ message?: string;
35
+ mode?: 'chat';
36
+ settingsPatch?: Partial<HazeSettings>;
37
+ removedDir?: string;
38
+ selectedName?: string;
39
+ skill?: LoadedSkill;
40
+ };
41
+ export declare function skillConfirmRemoveResult(settings: HazeSettings, skills: LoadedSkill[], selectedName: string | undefined, value: string): SkillConfirmRemoveResult;
@@ -1,14 +1,5 @@
1
- import { isSkillEnabled, setSkillEnabled } from '../../config/skillSettings.js';
2
- import { COMMON_ACTIONS, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
3
- export function skillPickerValue(skill) {
4
- return `${skill.name} · ${skill.source}`;
5
- }
6
- export function findSelectedSkill(skills, selection) {
7
- if (!selection)
8
- return undefined;
9
- return skills.find(skill => skillPickerValue(skill) === selection)
10
- ?? skills.find(skill => skill.name === selection);
11
- }
1
+ import { isSkillEnabled, removeSkillSetting, setSkillEnabled } from '../../config/skillSettings.js';
2
+ import { COMMON_ACTIONS, SKILL_ACTIONS, SKILL_CHOICES, findSelectedSkill, isYesConfirmation, skillPickerValue } from './wizardFlow.js';
12
3
  export function selectSkillResult(skills, name) {
13
4
  if (name === SKILL_CHOICES.addSkill)
14
5
  return { mode: 'skillsAddName', clearDraft: true, message: 'Name the skill (kebab-case, e.g. security-review). ESC cancels.' };
@@ -46,3 +37,34 @@ export function selectSkillActionResult(settings, skills, selectedName, action)
46
37
  return { mode: 'skillsConfirmRemove', message: `Remove ${skill.source} skill ${skill.name}? This deletes ${skill.dir}. Type "yes" to confirm. Esc to cancel.`, skill };
47
38
  return { message: `Unknown skill action: ${action}`, skill };
48
39
  }
40
+ export function captureSkillDescription(value, draftName) {
41
+ const description = value.trim();
42
+ if (!description)
43
+ return { message: 'Description is required. Try again, or press ESC to cancel.' };
44
+ if (!draftName)
45
+ return { mode: 'chat', clearDraft: true, message: 'Skill wizard lost the name. Start over with /skills.' };
46
+ return { description, draftName, busy: true, busyLabel: 'Creating skill' };
47
+ }
48
+ export function skillCreationMessage(name, file) {
49
+ return `Created skill ${name} at ${file}. Invoke it with /${name}. Edit SKILL.md to refine its workflow.`;
50
+ }
51
+ export function skillCreationFailure(error) {
52
+ return `Skill creation failed: ${error instanceof Error ? error.message : String(error)}`;
53
+ }
54
+ export function skillConfirmRemoveResult(settings, skills, selectedName, value) {
55
+ if (!selectedName)
56
+ return { mode: 'chat' };
57
+ if (!isYesConfirmation(value))
58
+ return { mode: 'chat', selectedName: undefined, message: 'Cancelled. Skill not removed.' };
59
+ const skill = findSelectedSkill(skills, selectedName);
60
+ if (!skill)
61
+ return { mode: 'chat', selectedName: undefined, message: `Skill ${selectedName} not found.` };
62
+ return {
63
+ mode: 'chat',
64
+ selectedName: undefined,
65
+ skill,
66
+ removedDir: skill.dir,
67
+ settingsPatch: { skills: removeSkillSetting(settings, skill.name, skill.source) },
68
+ message: skill.source === 'global' ? `Removed skill ${skill.name}.` : `Removed project skill ${skill.name}.`,
69
+ };
70
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Why a turn's AbortController fired.
3
+ *
4
+ * One controller is shared by three abort sites: the model-stream idle timer,
5
+ * the absolute turn deadline (both in this subtree), and the user's cancel
6
+ * action (chat.tsx aborts the controller it holds). All three land in the same
7
+ * catch block in `runAgentAttempt`, so the *cause* is tracked in a per-turn
8
+ * mutable holder set by whichever internal site aborts first. A user abort
9
+ * never sets it and therefore stays `'user'` (the default).
10
+ */
11
+ type TurnAbortCauseKind = 'user' | 'turn-deadline' | 'model-stream-idle';
12
+ export interface TurnAbortCause {
13
+ kind: TurnAbortCauseKind;
14
+ /** Window of the timer that fired (idle window or turn deadline), for messages and diagnostics. */
15
+ timeoutMs?: number;
16
+ }
17
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
18
+ export declare function createUserAbortCause(): TurnAbortCause;
19
+ /**
20
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
21
+ * a no-op once the controller already aborted, so a user Esc raced against an
22
+ * idle timeout keeps whichever cause actually fired first.
23
+ */
24
+ export declare function abortForTurn(cause: TurnAbortCause, next: TurnAbortCause, controller: AbortController, reason: string): void;
25
+ export {};
@@ -0,0 +1,16 @@
1
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
2
+ export function createUserAbortCause() {
3
+ return { kind: 'user' };
4
+ }
5
+ /**
6
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
7
+ * a no-op once the controller already aborted, so a user Esc raced against an
8
+ * idle timeout keeps whichever cause actually fired first.
9
+ */
10
+ export function abortForTurn(cause, next, controller, reason) {
11
+ if (controller.signal.aborted)
12
+ return;
13
+ cause.kind = next.kind;
14
+ cause.timeoutMs = next.timeoutMs;
15
+ controller.abort(reason);
16
+ }
@@ -0,0 +1,43 @@
1
+ import type { ContextFile } from '../../../config/contextFiles.js';
2
+ import type { PromptSession } from '../../../llm/systemPrompt.js';
3
+ import type { TurnExecutionScope } from '../../../llm/requestContext.js';
4
+ import type { ToolExecutionBudgetState, TurnBudget } from '../../../core/agent/budgets.js';
5
+ import type { TurnExecutionState } from '../../../core/agent/completionController.js';
6
+ import type { SessionGoal } from '../../../core/agent/goalPolicy.js';
7
+ import { type AgentAttemptResult } from './attemptOutcome.js';
8
+ import type { AttemptCleanupRegistry } from './attemptLifecycle.js';
9
+ import type { TurnAbortCause } from './abortCause.js';
10
+ import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
11
+ export interface AgentAttemptInput {
12
+ value: string;
13
+ contextFiles: ContextFile[];
14
+ callbacks: StreamCallbacks;
15
+ retryAttempt: number;
16
+ retryingExistingRequest: boolean;
17
+ contextOverflowRecovered: boolean;
18
+ session: PromptSession | undefined;
19
+ modelOverride: string | undefined;
20
+ abortController: AbortController;
21
+ turnOptions: TurnExecutionOptions;
22
+ turnScope: {
23
+ executionScope?: TurnExecutionScope;
24
+ };
25
+ turnState: TurnExecutionState;
26
+ turnBudget: TurnBudget;
27
+ globalBudget: ToolExecutionBudgetState;
28
+ /** Slice execution budget shared by every attempt in the current slice (main phase or one recovery slice); reset when a new slice is admitted. */
29
+ sliceBudget: ToolExecutionBudgetState;
30
+ goal: SessionGoal;
31
+ abortCause: TurnAbortCause;
32
+ /** Exactly-once teardown registry; shared with the turn's forced-settlement path. */
33
+ cleanup: AttemptCleanupRegistry;
34
+ remainingTurnDeadlineMs: () => number;
35
+ }
36
+ /**
37
+ * Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
38
+ * (`streamLoop`), then terminal classification and recovery decisions
39
+ * (`attemptOutcome`). Failures are classified from the abort cause and error
40
+ * in one catch; MCP clients, the LSP pool, the stall guard, and the tool
41
+ * display are always torn down.
42
+ */
43
+ export declare function runAgentAttempt(input: AgentAttemptInput): Promise<AgentAttemptResult>;
@@ -0,0 +1,79 @@
1
+ import { closeMcpClients } from '../../../llm/mcp.js';
2
+ import { modelThinkingLabel } from '../../../utils/modelName.js';
3
+ import { normalizeAssistantText } from './assistantText.js';
4
+ import { createToolGroupRenderer } from './toolGroupRenderer.js';
5
+ import { prepareAttempt } from './attemptSetup.js';
6
+ import { createAttemptLoopState, runAttemptStream } from './streamLoop.js';
7
+ import { createStreamStallGuard } from './stallRecovery.js';
8
+ import { finalizeAttemptOutcome, handleAttemptFailure } from './attemptOutcome.js';
9
+ import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
10
+ /**
11
+ * Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
12
+ * (`streamLoop`), then terminal classification and recovery decisions
13
+ * (`attemptOutcome`). Failures are classified from the abort cause and error
14
+ * in one catch; MCP clients, the LSP pool, the stall guard, and the tool
15
+ * display are always torn down.
16
+ */
17
+ export async function runAgentAttempt(input) {
18
+ const { value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs } = input;
19
+ callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
20
+ let loadedMcp;
21
+ let lspPool;
22
+ let mcpClosed = false;
23
+ let lspClosed = false;
24
+ const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
25
+ // Teardown is registered, not inline: whichever runs first — this attempt's
26
+ // own finally or the turn-level forced settlement after an abort-ignoring
27
+ // stream — performs it exactly once (bounded), the other becomes a no-op.
28
+ cleanup.register(async () => {
29
+ const closes = [];
30
+ if (loadedMcp?.clients.length && !mcpClosed) {
31
+ mcpClosed = true;
32
+ closes.push(closeMcpClients(loadedMcp.clients));
33
+ }
34
+ if (lspPool && !lspClosed) {
35
+ lspClosed = true;
36
+ closes.push(lspPool.close());
37
+ }
38
+ stallGuard?.clear();
39
+ toolDisplay.stopToolTimer();
40
+ await Promise.allSettled(closes);
41
+ });
42
+ const salvage = { requestMessages: [], accumulated: [] };
43
+ let stallGuard;
44
+ let setup;
45
+ try {
46
+ setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path) });
47
+ if (!setup)
48
+ return { status: 'failed' };
49
+ const attemptSetupResult = setup;
50
+ loadedMcp = setup.loadedMcp;
51
+ lspPool = setup.lspPool;
52
+ salvage.requestMessages = setup.requestMessages;
53
+ const loopState = createAttemptLoopState(normalizeAssistantText(callbacks.getLastAssistantText()), setup.contextFiles, callbacks);
54
+ stallGuard = createStreamStallGuard({
55
+ controller: abortController,
56
+ abortCause,
57
+ retryAttempt,
58
+ maxRetries: attemptSetupResult.modelRetries,
59
+ classifyEmission: () => loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted ? 'text' : loopState.inFlightTools.size > 0 ? 'tool' : 'none',
60
+ isToolInFlight: () => loopState.inFlightTools.size > 0,
61
+ provider: () => attemptSetupResult.runtime.config.providerName,
62
+ model: () => attemptSetupResult.runtime.config.modelName,
63
+ workPhase: () => goal.phase,
64
+ stepsUsed: () => turnState.stepsUsed,
65
+ onEvent: callbacks.onEvent,
66
+ log: callbacks.log,
67
+ debugLog: callbacks.debugLog,
68
+ });
69
+ const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage });
70
+ return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream });
71
+ }
72
+ catch (error) {
73
+ return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt, contextOverflowRecovered, abortCause, stallGuard, salvage, error, maxRetries: setup?.modelRetries });
74
+ }
75
+ finally {
76
+ await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
77
+ toolDisplay.finalizeToolGroup();
78
+ }
79
+ }
@@ -64,8 +64,15 @@ function isLikelyUnfinishedMarkdownFragment(text) {
64
64
  const trimmed = text.trim();
65
65
  if (!trimmed.includes('\n'))
66
66
  return false;
67
- const last = trimmed.at(-1) ?? '';
68
- return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
67
+ // A dangling structural marker alone on the last line ("- ", "#", ">") means
68
+ // the model just opened a list/heading/blockquote and is about to continue.
69
+ const lastLine = trimmed.split('\n').pop()?.trim() ?? '';
70
+ if (lastLine.length === 1 && '-*#>'.includes(lastLine))
71
+ return true;
72
+ // An odd number of fence-open lines means a code block was opened but never
73
+ // closed. An even count (including a trailing closing fence) is balanced.
74
+ const fenceCount = (trimmed.match(/^`{3,}/gm) ?? []).length;
75
+ return fenceCount % 2 === 1;
69
76
  }
70
77
  // Procedural pre-tool lead-ins (e.g. "Confirmed:", "Files written.", "Now let me",
71
78
  // "I checked the tests.") are short preambles the model emits before calling a tool; they
@@ -0,0 +1,56 @@
1
+ import type { StreamCallbacks } from '../streaming.js';
2
+ import type { AgentAttemptResult } from './attemptOutcome.js';
3
+ /** Upper bound for one forced teardown pass; the underlying closes continue even if it expires. */
4
+ export declare const ATTEMPT_TEARDOWN_BOUND_MS = 5000;
5
+ /**
6
+ * Exactly-once cleanup registry for one agent attempt. The attempt registers
7
+ * its resource cleanups (MCP clients, LSP pool, stall guard, tool display) as
8
+ * it acquires them; whichever of the attempt's own `finally` or the turn's
9
+ * forced settlement runs first performs the teardown, and the other becomes a
10
+ * no-op. `closeOnce` is bounded and reports truthfully whether every cleanup
11
+ * completed within `timeoutMs` (closes keep settling in the background).
12
+ */
13
+ export interface AttemptCleanupRegistry {
14
+ /** Register a cleanup to run once at teardown. Ignored after teardown started. */
15
+ register: (cleanup: () => void | Promise<void>) => void;
16
+ /** Run all registered cleanups exactly once; resolves false when the bound expired. */
17
+ closeOnce: (timeoutMs: number) => Promise<boolean>;
18
+ /** True once teardown has started. */
19
+ readonly closed: boolean;
20
+ }
21
+ export declare function createAttemptCleanupRegistry(): AttemptCleanupRegistry;
22
+ /**
23
+ * Per-turn callback guard for the attempt machinery. After `quarantine()` —
24
+ * run at forced settlement — every state-mutating callback (messages,
25
+ * conversation, busy/goal/work state, events, token usage, logs) becomes a
26
+ * permanent no-op, so a still-running abort-ignoring stream cannot mutate the
27
+ * finished turn's UI, conversation, or session state if it ever wakes up.
28
+ * Diagnostics (`debugLog`) and read-only accessors stay live.
29
+ */
30
+ export interface QuarantinableCallbacks {
31
+ callbacks: StreamCallbacks;
32
+ /** Permanently no-op all state-mutating callbacks. */
33
+ quarantine: () => void;
34
+ }
35
+ export declare function createQuarantinableCallbacks(callbacks: StreamCallbacks): QuarantinableCallbacks;
36
+ export interface ForcedSettlementDeps {
37
+ abortController: AbortController;
38
+ cleanup: AttemptCleanupRegistry;
39
+ quarantine: () => void;
40
+ /**
41
+ * Build the synthetic attempt result after forced teardown. Runs with the
42
+ * turn's live (unguarded) callbacks before the abandoned attempt's result
43
+ * (if it ever settles) is discarded.
44
+ */
45
+ onForced: (tornDownCleanly: boolean) => AgentAttemptResult;
46
+ }
47
+ /**
48
+ * Await one agent attempt, but never let an abort-ignoring attempt defer the
49
+ * turn forever: once the shared controller aborts (user cancel or absolute
50
+ * deadline), the attempt gets a grace window to settle normally; if the grace
51
+ * expires, owned resources are torn down (bounded, exactly once), the attempt's
52
+ * callbacks are quarantined, and the turn resolves with `onForced`'s result.
53
+ * The abandoned attempt keeps running detached; its eventual settlement is
54
+ * discarded and its teardown is a no-op.
55
+ */
56
+ export declare function awaitAttemptWithForcedSettlement(attempt: Promise<AgentAttemptResult>, deps: ForcedSettlementDeps): Promise<AgentAttemptResult>;