@denizokcu/haze 0.11.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 (230) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +23 -14
  3. package/SECURITY.md +3 -3
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/chatMetrics.d.ts +2 -2
  6. package/dist/cli/chat/chatMetrics.js +1 -1
  7. package/dist/cli/chat/fileMentionSuggestions.js +1 -1
  8. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  9. package/dist/cli/chat/inputSuggestions.js +9 -41
  10. package/dist/cli/chat/messages.d.ts +0 -2
  11. package/dist/cli/chat/messages.js +2 -2
  12. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  13. package/dist/cli/chat/turnState.d.ts +1 -1
  14. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  15. package/dist/cli/chat/wizardDispatch.js +250 -133
  16. package/dist/cli/commands/chat.js +14 -72
  17. package/dist/cli/commands/chatModes.d.ts +8 -1
  18. package/dist/cli/commands/chatModes.js +9 -44
  19. package/dist/cli/commands/doctor.js +1 -1
  20. package/dist/cli/commands/formatters.d.ts +3 -3
  21. package/dist/cli/commands/formatters.js +6 -25
  22. package/dist/cli/commands/providerWizard.js +2 -3
  23. package/dist/cli/commands/runCommand.js +1 -1
  24. package/dist/cli/commands/serverWizard.d.ts +34 -0
  25. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  26. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  27. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  28. package/dist/cli/commands/streaming/abortCause.d.ts +2 -1
  29. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  30. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  31. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  32. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  33. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  34. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  35. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  36. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  38. package/dist/cli/commands/streaming/goalCheckpoint.js +2 -2
  39. package/dist/cli/commands/streaming/goalSupervisor.js +9 -6
  40. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  41. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  43. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  44. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +14 -0
  45. package/dist/cli/commands/streaming/toolCallRecovery.js +56 -0
  46. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -1
  47. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  48. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  49. package/dist/cli/commands/streaming.d.ts +14 -25
  50. package/dist/cli/commands/streaming.js +43 -754
  51. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  52. package/dist/cli/commands/wizardFlow.js +377 -0
  53. package/dist/cli/contextReport.js +3 -0
  54. package/dist/cli/index.js +1 -1
  55. package/dist/config/contextFiles.js +9 -3
  56. package/dist/config/inputHistory.d.ts +0 -1
  57. package/dist/config/inputHistory.js +1 -1
  58. package/dist/config/modelDiscovery.d.ts +0 -15
  59. package/dist/config/modelDiscovery.js +1 -1
  60. package/dist/config/settings.d.ts +7 -0
  61. package/dist/config/settings.js +3 -0
  62. package/dist/config/skillSettings.js +4 -4
  63. package/dist/config/updateCheck.d.ts +0 -1
  64. package/dist/config/updateCheck.js +1 -1
  65. package/dist/core/agent/budgets.d.ts +63 -1
  66. package/dist/core/agent/budgets.js +84 -1
  67. package/dist/core/agent/compaction.js +1 -1
  68. package/dist/core/agent/completionController.d.ts +7 -13
  69. package/dist/core/agent/completionController.js +17 -8
  70. package/dist/core/agent/contextBudget.d.ts +0 -4
  71. package/dist/core/agent/contextBudget.js +3 -3
  72. package/dist/core/agent/errors.d.ts +0 -1
  73. package/dist/core/agent/errors.js +1 -1
  74. package/dist/core/agent/events.d.ts +5 -1
  75. package/dist/core/{goal/completionPolicy.d.ts → agent/goalPolicy.d.ts} +18 -0
  76. package/dist/core/agent/goalPolicy.js +106 -0
  77. package/dist/core/agent/requestAssembly.d.ts +2 -2
  78. package/dist/core/agent/requestAssembly.js +16 -4
  79. package/dist/core/agent/toolCapabilities.d.ts +2 -2
  80. package/dist/core/agent/toolCapabilities.js +5 -5
  81. package/dist/core/agent/toolOutputStore.js +1 -1
  82. package/dist/core/agent/toolResults.js +1 -1
  83. package/dist/core/agent/workState.d.ts +6 -3
  84. package/dist/core/agent/workState.js +62 -7
  85. package/dist/core/attachments/imageAttachments.js +90 -42
  86. package/dist/core/deadline.d.ts +0 -6
  87. package/dist/core/deadline.js +1 -1
  88. package/dist/core/io/boundedRead.js +1 -1
  89. package/dist/core/limits.d.ts +51 -0
  90. package/dist/core/limits.js +51 -0
  91. package/dist/core/log/llmLog.js +1 -1
  92. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  93. package/dist/core/process/backgroundRegistry.js +10 -6
  94. package/dist/core/process/userShell.d.ts +16 -0
  95. package/dist/core/process/userShell.js +59 -0
  96. package/dist/core/safety/shellClassifier.d.ts +11 -0
  97. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  98. package/dist/core/safety/urlGuard.d.ts +1 -1
  99. package/dist/core/session/sessionSlimming.d.ts +0 -3
  100. package/dist/core/session/sessionSlimming.js +2 -3
  101. package/dist/core/session/sessionStore.d.ts +1 -0
  102. package/dist/core/session/sessionStore.js +39 -20
  103. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  104. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  105. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  106. package/dist/core/shellOutput/registry.d.ts +2 -0
  107. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  108. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  109. package/dist/core/subagent/contracts.d.ts +2 -14
  110. package/dist/core/subagent/contracts.js +3 -3
  111. package/dist/core/subagent/executionProfiles.js +2 -2
  112. package/dist/core/subagent/subagentRunner.js +3 -4
  113. package/dist/core/toolOutput/reduction.d.ts +0 -12
  114. package/dist/core/toolOutput/reduction.js +1 -1
  115. package/dist/core/validation/outputParser.d.ts +2 -2
  116. package/dist/llm/client.js +5 -1
  117. package/dist/llm/hazeTools.d.ts +139 -124
  118. package/dist/llm/hazeTools.js +14 -11
  119. package/dist/llm/initPrompt.js +1 -1
  120. package/dist/llm/lsp/client.d.ts +45 -0
  121. package/dist/llm/lsp/client.js +195 -0
  122. package/dist/llm/lsp/pool.d.ts +23 -0
  123. package/dist/llm/lsp/pool.js +86 -0
  124. package/dist/llm/lsp/protocol.d.ts +64 -0
  125. package/dist/llm/lsp/protocol.js +128 -0
  126. package/dist/llm/lsp/requests.d.ts +94 -0
  127. package/dist/llm/lsp/requests.js +119 -0
  128. package/dist/llm/lspTools.d.ts +3824 -570
  129. package/dist/llm/lspTools.js +65 -1
  130. package/dist/llm/openaiCodex.d.ts +0 -2
  131. package/dist/llm/openaiCodex.js +0 -4
  132. package/dist/llm/openaiCodexOAuth.d.ts +0 -3
  133. package/dist/llm/openaiCodexOAuth.js +6 -3
  134. package/dist/llm/requestContext.d.ts +5 -1
  135. package/dist/llm/requestContext.js +25 -2
  136. package/dist/llm/systemPrompt.d.ts +1 -0
  137. package/dist/llm/systemPrompt.js +13 -6
  138. package/dist/llm/toolResultTypes.d.ts +0 -14
  139. package/dist/llm/toolResultTypes.js +1 -4
  140. package/dist/llm/tools/editMatch.d.ts +0 -9
  141. package/dist/llm/tools/editMatch.js +1 -1
  142. package/dist/llm/tools/fetchTool.js +1 -1
  143. package/dist/llm/tools/fileToolShared.d.ts +4 -2
  144. package/dist/llm/tools/fileToolShared.js +9 -5
  145. package/dist/llm/tools/gitIgnore.d.ts +25 -32
  146. package/dist/llm/tools/gitIgnore.js +216 -98
  147. package/dist/llm/tools/grepParse.d.ts +2 -1
  148. package/dist/llm/tools/grepRunner.d.ts +1 -1
  149. package/dist/llm/tools/grepRunner.js +2 -2
  150. package/dist/llm/tools/outputCap.d.ts +2 -7
  151. package/dist/llm/tools/outputCap.js +3 -3
  152. package/dist/llm/tools/processTool.d.ts +16 -16
  153. package/dist/llm/tools/processTool.js +1 -1
  154. package/dist/llm/tools/readRecovery.d.ts +0 -2
  155. package/dist/llm/tools/readRecovery.js +2 -2
  156. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +123 -107
  157. package/dist/llm/tools/{bashTool.js → shellTool.js} +15 -14
  158. package/dist/llm/tools/toolContext.js +5 -5
  159. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  160. package/dist/llm/tools/workspaceFile.js +1 -6
  161. package/dist/llm/webFetch.d.ts +1 -1
  162. package/dist/skills/SkillLoader.d.ts +1 -11
  163. package/dist/skills/SkillLoader.js +1 -2
  164. package/dist/skills/types.d.ts +2 -1
  165. package/dist/utils/buildInfo.d.ts +6 -13
  166. package/dist/utils/buildInfo.js +6 -15
  167. package/dist/utils/fs.d.ts +7 -5
  168. package/dist/utils/fs.js +5 -2
  169. package/dist/utils/path.d.ts +0 -1
  170. package/dist/utils/path.js +1 -1
  171. package/package.json +6 -4
  172. package/dist/cli/commands/lspWizard.d.ts +0 -14
  173. package/dist/cli/commands/lspWizard.js +0 -44
  174. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  175. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  176. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  177. package/dist/cli/commands/skillCreation.d.ts +0 -12
  178. package/dist/cli/commands/skillCreation.js +0 -14
  179. package/dist/cli/commands/skillWizard.d.ts +0 -17
  180. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  181. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  182. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -27
  183. package/dist/cli/commands/streaming/turnOutcome.js +0 -29
  184. package/dist/cli/commands/wizardActions.d.ts +0 -47
  185. package/dist/cli/commands/wizardActions.js +0 -47
  186. package/dist/cli/commands/wizardInput.d.ts +0 -4
  187. package/dist/cli/commands/wizardInput.js +0 -19
  188. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  189. package/dist/cli/commands/wizardPrompts.js +0 -58
  190. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  191. package/dist/cli/commands/wizardSuggestions.js +0 -190
  192. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  193. package/dist/cli/commands/wizardTransition.js +0 -43
  194. package/dist/core/agent/toolExecutionBudget.d.ts +0 -35
  195. package/dist/core/agent/toolExecutionBudget.js +0 -49
  196. package/dist/core/agent/turnBudget.d.ts +0 -35
  197. package/dist/core/agent/turnBudget.js +0 -27
  198. package/dist/core/bashOutput/ansi.d.ts +0 -1
  199. package/dist/core/bashOutput/ansi.js +0 -7
  200. package/dist/core/bashOutput/registry.d.ts +0 -4
  201. package/dist/core/goal/completionPolicy.js +0 -43
  202. package/dist/core/goal/requestClassifier.d.ts +0 -3
  203. package/dist/core/goal/requestClassifier.js +0 -18
  204. package/dist/core/goal/sessionGoal.d.ts +0 -8
  205. package/dist/core/goal/sessionGoal.js +0 -30
  206. package/dist/core/limits/byteBudgets.d.ts +0 -20
  207. package/dist/core/limits/byteBudgets.js +0 -20
  208. package/dist/core/limits/textBudgets.d.ts +0 -25
  209. package/dist/core/limits/textBudgets.js +0 -25
  210. package/dist/core/safety/bashClassifier.d.ts +0 -10
  211. package/dist/llm/lsp.d.ts +0 -149
  212. package/dist/llm/lsp.js +0 -368
  213. package/dist/ui/components/ErrorView.d.ts +0 -4
  214. package/dist/ui/components/ErrorView.js +0 -7
  215. package/dist/utils/yaml.d.ts +0 -2
  216. package/dist/utils/yaml.js +0 -8
  217. package/examples/skills/files/SKILL.md +0 -16
  218. package/examples/skills/files/examples/file-editing.md +0 -3
  219. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  220. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  221. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  222. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  223. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  224. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  225. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  226. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  227. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  228. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  229. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  230. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -0,0 +1,167 @@
1
+ import { readSettings } from '../../../config/settings.js';
2
+ import { DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
3
+ import { agentEvent } from '../../../core/agent/events.js';
4
+ import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
5
+ import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
6
+ import { calculateRequestTokenBudget, estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
7
+ import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
8
+ import { compactModelMessages } from '../../../core/agent/compaction.js';
9
+ import { DEFAULT_MAX_OUTPUT_TOKENS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, withToolExecutionBudget } from '../../../core/agent/budgets.js';
10
+ import { withToolDeadline } from '../../../core/deadline.js';
11
+ import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
12
+ import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
13
+ import { WorkspaceMutationPolicy } from '../../../core/subagent/workspaceMutationPolicy.js';
14
+ import { modelWithConfig, providerRequestSettings } from '../../../llm/client.js';
15
+ import { assembleRequestContext } from '../../../llm/requestContext.js';
16
+ import { modelThinkingLabel } from '../../../utils/modelName.js';
17
+ import { estimateInputBreakdown, logEntry } from './turnRuntime.js';
18
+ /**
19
+ * Restrict a tool set to the capabilities permitted in a completion-rescue
20
+ * slice: mutation (edit/write/replace) and validation-capable (shell) built-in
21
+ * tools only. Discovery, read, coordinate, and all third-party (MCP) tools are
22
+ * dropped so the rescue cannot reopen exploration. May return an empty set
23
+ * when no built-in mutation/validation tools exist (only possible if builtins
24
+ * were removed); the caller then forces a tool-free synthesis slice instead
25
+ * of silently keeping the unfiltered tool set (F-08).
26
+ */
27
+ export function restrictToRescueTools(tools) {
28
+ const restricted = {};
29
+ for (const [name, tool] of Object.entries(tools)) {
30
+ if (isMutatingCapability(name) || isValidationCapable(name))
31
+ restricted[name] = tool;
32
+ }
33
+ return restricted;
34
+ }
35
+ /**
36
+ * Assemble one attempt: resolve the model (single fresh settings read, CR-024),
37
+ * build the request context, clamp the request to the model-aware token budget,
38
+ * and wrap the slice's tools with the execution-boundary budget (RH-003) and
39
+ * per-tool deadlines (RH-004). Returns `undefined` when no provider is
40
+ * configured (the caller-reported failure path).
41
+ */
42
+ export async function prepareAttempt(deps) {
43
+ const { value, contextFiles, callbacks, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead } = deps;
44
+ // Single choke point: one fresh settings read per turn, shared by model
45
+ // resolution and request assembly (CR-024).
46
+ const turnSettings = await readSettings();
47
+ const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
48
+ if (!runtime?.model) {
49
+ callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
50
+ return undefined;
51
+ }
52
+ const thinkingLabel = modelThinkingLabel(runtime.config.modelName);
53
+ callbacks.setBusyLabel?.(thinkingLabel);
54
+ // Observable requested-vs-effective reasoning policy (safe: level strings + reason only).
55
+ const reasoningPolicy = runtime.config.reasoningPolicy;
56
+ if (reasoningPolicy)
57
+ callbacks.onEvent?.(agentEvent({ type: 'reasoning_policy', requested: reasoningPolicy.requested, effective: reasoningPolicy.effective, reason: reasoningPolicy.reason }));
58
+ // Make the context-budget guess observable: a stream event every turn
59
+ // (headless consumers can gate on it), and — interactively — a system
60
+ // message only when the built-in default was used for a model this session
61
+ // has not warned about yet (a user-set fallback setting is an intentional
62
+ // choice and is not warned about). The warned key is `provider:model`, so
63
+ // the message appears at the start of a session and once after a model
64
+ // switch, never on every turn.
65
+ callbacks.onEvent?.(agentEvent({ type: 'context_budget', contextWindowTokens: runtime.config.contextWindowTokens, source: runtime.config.contextWindowSource }));
66
+ const fallbackModelKey = `${runtime.config.providerName}:${runtime.config.modelName}`;
67
+ if (runtime.config.contextWindowSource === 'default-fallback' && session && session.contextFallbackWarned !== fallbackModelKey) {
68
+ session.contextFallbackWarned = fallbackModelKey;
69
+ callbacks.addMessage({ role: 'system', text: `No context-window data for ${runtime.config.providerName}:${runtime.config.modelName}; budgeting conservatively at ${runtime.config.contextWindowTokens.toLocaleString('en-US')} tokens. Set modelLimits for this model via /provider, or contextWindowFallbackTokens in settings, to use its real window.` });
70
+ }
71
+ const activeContextFiles = contextFiles;
72
+ const activeModel = runtime.model;
73
+ const { omitMaxOutputTokens, ...providerSettings } = providerRequestSettings(runtime.config);
74
+ const assembled = await assembleRequestContext({ request: value, 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'
75
+ ? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
76
+ : event.type === 'started'
77
+ ? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
78
+ : event.type === 'terminal'
79
+ ? { 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 }
80
+ : { 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 })) });
81
+ turnScope.executionScope ??= assembled.executionScope;
82
+ const availableTools = assembled.availableTools;
83
+ const toolCategories = assembled.toolCategories;
84
+ const loadedMcp = assembled.loadedMcp;
85
+ const lspPool = assembled.lspPool;
86
+ if (loadedMcp?.errors.length)
87
+ callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
88
+ callbacks.setWorkState?.(goal);
89
+ callbacks.setGoalStatus?.(formatGoalStatus(goal));
90
+ const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
91
+ const durableRequestMessages = compactToolHistory(retryingExistingRequest
92
+ ? stripSyntheticControls(callbacks.getConversation())
93
+ : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
94
+ // Model-aware request budget (RH-005): message allowance is the context
95
+ // window minus system prompt, tool schemas, output reserve, and a safety
96
+ // margin — not a fixed 40K constant. Small contexts get a safe budget; the
97
+ // assembled request plus output reserve stays within configured capacity.
98
+ const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
99
+ const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
100
+ // A context-overflow retry progressively shrinks the target so it cannot loop
101
+ // at an unchanged budget; further overflows get even smaller (RH-005).
102
+ const overflowTargetTokens = contextOverflowRecovered ? Math.floor(requestBudget.messageTokens * 0.6) : requestBudget.messageTokens;
103
+ let requestMessages = durableRequestMessages;
104
+ if (estimateMessagesTokens(requestMessages) > overflowTargetTokens) {
105
+ requestMessages = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal }).messages;
106
+ }
107
+ requestMessages = withoutSystemMessages(requestMessages);
108
+ callbacks.setConversation(stripSyntheticControls(requestMessages));
109
+ if (turnOptions.ephemeralControl)
110
+ requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
111
+ const systemPrompt = assembled.systemPrompt;
112
+ const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
113
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
114
+ const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
115
+ const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
116
+ const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead, mutationPolicy, blessedPaths: turnOptions.blessedPaths };
117
+ const recoverySlice = turnOptions.recoverySlice;
118
+ const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
119
+ // Rescue exposes only mutation + validation-capable built-in tools so
120
+ // discovery cannot be reopened near the boundary. Length-continuation keeps
121
+ // the full tool set. When no built-in mutation/validation tool qualifies,
122
+ // the rescue slice runs tool-free (forced synthesis) rather than keeping
123
+ // the unfiltered set — the "discovery must not be reopened" invariant (F-08).
124
+ const rescueTools = recoverySlice?.kind === 'rescue' ? restrictToRescueTools(availableTools) : availableTools;
125
+ const rescueWithoutTools = recoverySlice?.kind === 'rescue' && Object.keys(rescueTools).length === 0;
126
+ const sliceTools = rescueWithoutTools ? {} : rescueTools;
127
+ // Execution-boundary budgets (RH-003). The global budget is turn-wide
128
+ // (shared across retries and recovery slices); the slice budget belongs to
129
+ // the current slice (main phase or one recovery slice) and is provided by
130
+ // the turn loop so provider retries within the slice cannot re-arm its cap
131
+ // (round-1 C2): the slice envelope is clamped once at slice admission. Both
132
+ // are checked atomically at the actual execute boundary so one oversized
133
+ // parallel batch cannot overshoot.
134
+ const sliceToolCallCap = turnOptions.recoverySlice?.maxToolCalls ?? MAIN_TOOL_CALL_LIMIT;
135
+ const budgetedTools = withToolExecutionBudget(sliceTools, { state: globalBudget, limit: turnBudget.toolCallLimit }, { state: sliceBudget, limit: sliceToolCallCap });
136
+ // Layer a per-tool execution deadline on top of the budget (RH-004). The
137
+ // budget is checked first (cheap); a permitted call then runs under a
138
+ // deadline so an uncooperative tool cannot defer the turn indefinitely.
139
+ // Subagents legitimately run long, so their wrapper gets a larger bound.
140
+ const deadlineWrappedTools = Object.fromEntries(Object.entries(budgetedTools).map(([name, definition]) => {
141
+ if (typeof definition.execute !== 'function')
142
+ return [name, definition];
143
+ const execute = definition.execute;
144
+ const deadlineMs = name === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS;
145
+ return [name, { ...definition, execute: (...args) => withToolDeadline(() => execute(...args), deadlineMs, abortController.signal) }];
146
+ }));
147
+ return {
148
+ runtime,
149
+ thinkingLabel,
150
+ systemPrompt,
151
+ requestMessages,
152
+ requestBudget,
153
+ inputBreakdown,
154
+ providerSettings,
155
+ omitMaxOutputTokens,
156
+ sliceTools: deadlineWrappedTools,
157
+ stepCap,
158
+ rescueWithoutTools,
159
+ toolExecutionContext,
160
+ likelyPlanOnlyRequest,
161
+ loadedMcp,
162
+ lspPool,
163
+ contextFiles: activeContextFiles,
164
+ toolCategories,
165
+ modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
166
+ };
167
+ }
@@ -45,7 +45,7 @@ export interface GoalCheckpoint {
45
45
  /** Consecutive physical turns without measurable progress. */
46
46
  noProgressCount: number;
47
47
  }
48
- /** Cumulative progress signature: mutations, validation outcome, task counts. */
48
+ /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
49
49
  export declare function goalCheckpointSignature(input: {
50
50
  mutationCount: number;
51
51
  validationOutcome: ValidationOutcome;
@@ -1,6 +1,6 @@
1
- /** Cumulative progress signature: mutations, validation outcome, task counts. */
1
+ /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
2
2
  export function goalCheckpointSignature(input) {
3
- return JSON.stringify([input.mutationCount, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
3
+ return JSON.stringify([input.mutationCount > 0, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
4
4
  }
5
5
  /**
6
6
  * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
@@ -1,11 +1,11 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
3
3
  import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
4
- import { goalContinuationPrompt } from '../../../core/goal/completionPolicy.js';
4
+ import { goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { runAgentTurn } from '../streaming.js';
6
6
  import { goalCheckpointSignature } from './goalCheckpoint.js';
7
- /** Pause after this many consecutive physical turns without measurable progress (one corrective cycle allowed). */
8
- const GOAL_NO_PROGRESS_LIMIT = 2;
7
+ /** Pause after one corrective physical turn without measurable outcome progress. */
8
+ const GOAL_NO_PROGRESS_LIMIT = 1;
9
9
  function checkpointFromResume(resume, noProgressCount) {
10
10
  const validationOutcome = resume.validationOutcome ?? 'not_applicable';
11
11
  return {
@@ -94,15 +94,18 @@ export async function runAgentGoal(options) {
94
94
  lastEvidence = result.evidence;
95
95
  if (result.status === 'complete')
96
96
  return finish('complete', 'completed');
97
- if (result.status === 'aborted')
98
- return finish('aborted', 'user-aborted');
97
+ if (result.status === 'aborted') {
98
+ return result.abortReason === 'turn-deadline'
99
+ ? finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined)
100
+ : finish('aborted', 'user-aborted');
101
+ }
99
102
  if (result.resume?.kind === 'incomplete-goal') {
100
103
  const next = checkpointFromResume(result.resume, 0);
101
104
  noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
102
105
  prevSignature = next.progressSignature;
103
106
  checkpoint = { ...next, noProgressCount };
104
107
  if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
105
- callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} cycles without measurable progress (${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
108
+ callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} without measurable progress (${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
106
109
  return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
107
110
  }
108
111
  const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
@@ -0,0 +1,94 @@
1
+ import type { LlmLog } from '../../../core/log/llmLog.js';
2
+ import { type AgentEventSink } from '../../../core/agent/events.js';
3
+ import type { ModelMessage } from 'ai';
4
+ import { type TurnAbortCause } from './abortCause.js';
5
+ /** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
6
+ type StallEmission = 'none' | 'text' | 'tool';
7
+ export declare function formatIdleMinutes(milliseconds: number): string;
8
+ /**
9
+ * An idle timer for the main agent turn.
10
+ *
11
+ * The turn is considered "idle" (and aborted) after `timeoutMs` with no stream
12
+ * activity — UNLESS a tool call is currently executing (`isBusy()` returns
13
+ * true). Concurrent subagents can run for many minutes while emitting no stream
14
+ * parts; that is legitimate work, not a dead stream, so the timer defers (rearms)
15
+ * while any tool is in flight. This prevents a long subagent wave from being
16
+ * mistaken for a hung turn.
17
+ *
18
+ * `clear()` is a permanent quiescence barrier: once cleared, `reset()` can never
19
+ * rearm it, so a late stream part from an abort-ignoring stream cannot keep the
20
+ * timer (and whatever its timeout would trigger) alive after teardown.
21
+ *
22
+ * Note: there is intentionally no upper bound on how long a single tool may run
23
+ * while in flight — a genuinely hung tool would defer indefinitely. A per-tool
24
+ * hard timeout is a separate concern; the idle timer only guards against a turn
25
+ * that is producing no model output AND doing no tool work.
26
+ */
27
+ export interface IdleTimer {
28
+ /** Clear any pending deadline and rearm it for a fresh idle window. No-op after `clear()`. */
29
+ reset: () => void;
30
+ /** Cancel the pending deadline permanently; later `reset()` calls are ignored. */
31
+ clear: () => void;
32
+ }
33
+ export declare function createIdleTimer(input: {
34
+ timeoutMs: number;
35
+ isBusy: () => boolean;
36
+ onTimeout: () => void;
37
+ }): IdleTimer;
38
+ /**
39
+ * Idle-stall guard for one attempt: the idle timer plus the hoisted stall
40
+ * state the attempt catch needs (last stream event, emission classification,
41
+ * retry eligibility). `onTimeout` classifies the stall from live stream state
42
+ * (via `classifyEmission`), reports it through the timeout event protocol, and
43
+ * aborts the shared controller with the `model-stream-idle` cause. Diagnostics
44
+ * carry safe metadata only (names, timestamps, enums, phases) — never prompt
45
+ * content or credentials.
46
+ */
47
+ export interface StreamStallGuard {
48
+ /** Record a consumed stream part (type + timestamp) and rearm the idle window. */
49
+ noteStreamEvent: (type: string) => void;
50
+ /** Rearm the idle window without recording an event (before the first request). */
51
+ rearm: () => void;
52
+ /** Cancel the pending deadline. */
53
+ clear: () => void;
54
+ /** Emission classified by the last timeout; only meaningful after a stall fired. */
55
+ readonly stallEmission: StallEmission;
56
+ /** Whether the last stall rides the bounded model-retry pool. */
57
+ readonly retryEligible: boolean;
58
+ }
59
+ export interface StreamStallGuardDeps {
60
+ controller: AbortController;
61
+ abortCause: TurnAbortCause;
62
+ retryAttempt: number;
63
+ /** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
64
+ maxRetries?: number;
65
+ /** Classify what the stalled step emitted so far: partial text, in-flight tool, or nothing. */
66
+ classifyEmission: () => StallEmission;
67
+ isToolInFlight: () => boolean;
68
+ provider: () => string | undefined;
69
+ model: () => string | undefined;
70
+ workPhase: () => string;
71
+ stepsUsed: () => number;
72
+ onEvent?: AgentEventSink;
73
+ log?: LlmLog;
74
+ debugLog: (line: string) => void;
75
+ }
76
+ export declare function createStreamStallGuard(deps: StreamStallGuardDeps): StreamStallGuard;
77
+ /**
78
+ * Salvage state shared by the attempt phases: the request messages this
79
+ * attempt sent, and the latest fully completed step's accumulated response
80
+ * messages (captured in `onStepEnd`) that an idle-stall retry resumes from.
81
+ */
82
+ export interface AttemptSalvage {
83
+ requestMessages: ModelMessage[];
84
+ accumulated: ModelMessage[];
85
+ }
86
+ /**
87
+ * Salvage the conversation to the last fully completed step after a stalled or
88
+ * failed stream: completed — possibly mutating — tool work is preserved so an
89
+ * idle retry (or a user resume) continues from there instead of re-running it.
90
+ */
91
+ export declare function salvageConversationToLastStep(callbacks: {
92
+ setConversation: (messages: ModelMessage[]) => void;
93
+ }, salvage: AttemptSalvage): void;
94
+ export {};
@@ -0,0 +1,105 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
3
+ import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
4
+ import { abortForTurn } from './abortCause.js';
5
+ import { logEntry } from './turnRuntime.js';
6
+ export function formatIdleMinutes(milliseconds) {
7
+ const minutes = Math.round(milliseconds / 60_000);
8
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
9
+ }
10
+ /** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
11
+ function idleStallAutoRetryEligible(retryAttempt, stallEmission, maxRetries) {
12
+ return stallEmission === 'none' && retryAttempt < maxRetries;
13
+ }
14
+ export function createIdleTimer(input) {
15
+ const { timeoutMs, isBusy, onTimeout } = input;
16
+ let timer;
17
+ let stopped = false;
18
+ const fire = () => {
19
+ if (stopped)
20
+ return;
21
+ if (isBusy()) {
22
+ // Tools are executing — that is activity. Defer by rearming.
23
+ timer = setTimeout(fire, timeoutMs);
24
+ return;
25
+ }
26
+ onTimeout();
27
+ };
28
+ return {
29
+ reset: () => {
30
+ if (stopped)
31
+ return;
32
+ if (timer)
33
+ clearTimeout(timer);
34
+ timer = setTimeout(fire, timeoutMs);
35
+ },
36
+ clear: () => {
37
+ stopped = true;
38
+ if (timer)
39
+ clearTimeout(timer);
40
+ timer = undefined;
41
+ },
42
+ };
43
+ }
44
+ export function createStreamStallGuard(deps) {
45
+ const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
46
+ let stallEmission = 'none';
47
+ let retryEligible = false;
48
+ let lastStreamEventAt;
49
+ let lastStreamEventType;
50
+ const timer = createIdleTimer({
51
+ timeoutMs: IDLE_TIMEOUT_MS,
52
+ isBusy: () => deps.isToolInFlight(),
53
+ onTimeout: () => {
54
+ if (deps.controller.signal.aborted)
55
+ return;
56
+ // What the stalled step had emitted when the stream went quiet. Retrying
57
+ // after partial output could duplicate or mangle it, so only 'none' is
58
+ // automatically retryable.
59
+ stallEmission = deps.classifyEmission();
60
+ retryEligible = idleStallAutoRetryEligible(deps.retryAttempt, stallEmission, maxRetries);
61
+ const lastEventAtIso = lastStreamEventAt != null ? new Date(lastStreamEventAt).toISOString() : undefined;
62
+ deps.onEvent?.(agentEvent({
63
+ type: 'timeout',
64
+ phase: 'model-stream',
65
+ timeoutMs: IDLE_TIMEOUT_MS,
66
+ provider: deps.provider(),
67
+ model: deps.model(),
68
+ lastStreamEventAt: lastEventAtIso,
69
+ lastStreamEventType: lastStreamEventType,
70
+ stallEmission: stallEmission,
71
+ workPhase: deps.workPhase(),
72
+ retryEligible: retryEligible,
73
+ maxRetries: maxRetries,
74
+ }));
75
+ logEntry(deps.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', error: `model-stream idle ${IDLE_TIMEOUT_MS}ms: provider=${deps.provider() ?? 'unknown'} model=${deps.model() ?? 'unknown'} lastEvent=${lastStreamEventType ?? 'none'}@${lastEventAtIso ?? 'never'} stallEmission=${stallEmission} workPhase=${deps.workPhase()} retryEligible=${retryEligible} maxRetries=${maxRetries} stepsUsed=${deps.stepsUsed()}` });
76
+ deps.debugLog(`model stream idle for ${IDLE_TIMEOUT_MS}ms (last event: ${lastStreamEventType ?? 'none'}); ${retryEligible ? `retryable stall (${deps.retryAttempt}/${maxRetries} used)` : 'stall not retryable'}`);
77
+ abortForTurn(deps.abortCause, { kind: 'model-stream-idle', timeoutMs: IDLE_TIMEOUT_MS }, deps.controller, 'haze model stream was idle for the configured timeout.');
78
+ },
79
+ });
80
+ return {
81
+ noteStreamEvent: (type) => {
82
+ lastStreamEventAt = Date.now();
83
+ lastStreamEventType = type;
84
+ timer.reset();
85
+ },
86
+ rearm: () => timer.reset(),
87
+ clear: () => timer.clear(),
88
+ get stallEmission() {
89
+ return stallEmission;
90
+ },
91
+ get retryEligible() {
92
+ return retryEligible;
93
+ },
94
+ };
95
+ }
96
+ /**
97
+ * Salvage the conversation to the last fully completed step after a stalled or
98
+ * failed stream: completed — possibly mutating — tool work is preserved so an
99
+ * idle retry (or a user resume) continues from there instead of re-running it.
100
+ */
101
+ export function salvageConversationToLastStep(callbacks, salvage) {
102
+ if (salvage.accumulated.length > 0) {
103
+ callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
104
+ }
105
+ }
@@ -0,0 +1,72 @@
1
+ import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
2
+ import { type TurnExecutionState } from '../../../core/agent/completionController.js';
3
+ import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
4
+ import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
5
+ import { type NativeToolCall, type ToolGroupRenderer } from './toolGroupRenderer.js';
6
+ import { type ToolResultState } from './toolResultState.js';
7
+ import type { AttemptSalvage, StreamStallGuard } from './stallRecovery.js';
8
+ import type { AttemptSetup } from './attemptSetup.js';
9
+ import type { ContextFile } from '../../../config/contextFiles.js';
10
+ /**
11
+ * Mutable per-attempt loop state. Created before the stall guard so its
12
+ * `classifyEmission` can read what the stalled step emitted, and consumed by
13
+ * the stream part handlers, `prepareStep`, and the attempt outcome.
14
+ */
15
+ export interface AttemptLoopState {
16
+ /** Cumulative assistant text across all segments of this attempt. */
17
+ assistantText: string;
18
+ currentAssistantText: string;
19
+ assistantStarted: boolean;
20
+ currentAssistantId: string;
21
+ assistantStartedAt: number;
22
+ streamError: unknown;
23
+ streamFinished: boolean;
24
+ finishReason: string | undefined;
25
+ lastToolOk: boolean | undefined;
26
+ pendingMalformedToolName: string | undefined;
27
+ unresolvedMalformedToolName: string | undefined;
28
+ /** Per-attempt (not per-turn) recovery counter: a transient retry gets a fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT. */
29
+ malformedRecoveryAttempts: Map<string, number>;
30
+ toolResultState: ToolResultState;
31
+ /** Tool calls currently executing; a busy tool wave defers the idle timer. */
32
+ inFlightTools: Set<string>;
33
+ startedTools: Map<string, number>;
34
+ latestToolCalls: Map<string, NativeToolCall>;
35
+ /** Normalized assistant texts already shown this session (duplicate suppression). */
36
+ visibleAssistantTexts: Set<string>;
37
+ rememberVisibleAssistantText: (text: string) => void;
38
+ /** Context files active for this attempt; grows when tool outputs surface scoped instructions. */
39
+ contextFiles: ContextFile[];
40
+ }
41
+ export declare function createAttemptLoopState(previousAssistantText: string, contextFiles: ContextFile[], callbacks: Pick<StreamCallbacks, 'setLastAssistantText'>): AttemptLoopState;
42
+ /** What the completed stream tells the attempt outcome (classification evidence). */
43
+ export interface AttemptStreamOutcome {
44
+ finishReason: string | undefined;
45
+ lastToolOk: boolean | undefined;
46
+ assistantText: string;
47
+ sawToolCall: boolean;
48
+ unresolvedMalformedToolName: string | undefined;
49
+ unresolvedToolInputError: boolean;
50
+ }
51
+ export interface AttemptStreamDeps {
52
+ setup: AttemptSetup;
53
+ callbacks: StreamCallbacks;
54
+ abortController: AbortController;
55
+ retryAttempt: number;
56
+ recoverySlice: TurnExecutionOptions['recoverySlice'];
57
+ turnState: TurnExecutionState;
58
+ turnBudget: TurnBudget;
59
+ globalBudget: ToolExecutionBudgetState;
60
+ goal: SessionGoal;
61
+ stallGuard: StreamStallGuard;
62
+ loopState: AttemptLoopState;
63
+ toolDisplay: ToolGroupRenderer;
64
+ salvage: AttemptSalvage;
65
+ }
66
+ /**
67
+ * Drive one attempt's `ToolLoopAgent` stream: construct the agent (repair,
68
+ * prepareStep, step observers), consume every stream part, and commit the
69
+ * completed conversation. Throws the stream error so the attempt orchestrator
70
+ * classifies failures (abort cause, retry pool, recovery) in one place.
71
+ */
72
+ export declare function runAttemptStream(deps: AttemptStreamDeps): Promise<AttemptStreamOutcome>;