@denizokcu/haze 1.7.11 → 1.8.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 (234) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +142 -102
  3. package/SECURITY.md +1 -1
  4. package/assets/graph-grammars/NOTICE.md +21 -0
  5. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  7. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  9. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  10. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  11. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  13. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  14. package/bin/haze.js +47 -19
  15. package/dist/buildInfo.json +3 -3
  16. package/dist/cli/chat/BusyBar.d.ts +1 -2
  17. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  18. package/dist/cli/chat/ChatHeader.js +11 -0
  19. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  20. package/dist/cli/chat/ChatScreen.js +399 -0
  21. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  22. package/dist/cli/chat/ChatScreenView.js +47 -0
  23. package/dist/cli/chat/LiveTail.d.ts +11 -0
  24. package/dist/cli/chat/LiveTail.js +26 -0
  25. package/dist/cli/chat/TaskBar.d.ts +3 -2
  26. package/dist/cli/chat/TaskBar.js +4 -0
  27. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  28. package/dist/cli/chat/agentTurnRunner.js +177 -0
  29. package/dist/cli/chat/busyIndicator.js +9 -5
  30. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  31. package/dist/cli/chat/chatMetrics.js +15 -1
  32. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  33. package/dist/cli/chat/chatViewModel.js +66 -0
  34. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  35. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  36. package/dist/cli/chat/inputSuggestions.js +1 -0
  37. package/dist/cli/chat/liveTheme.d.ts +11 -0
  38. package/dist/cli/chat/liveTheme.js +26 -0
  39. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  40. package/dist/cli/chat/messageFinalize.js +8 -0
  41. package/dist/cli/chat/messages.js +1 -1
  42. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  43. package/dist/cli/chat/pickerOpeners.js +36 -0
  44. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  45. package/dist/cli/chat/promptSessionState.js +39 -0
  46. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  47. package/dist/cli/chat/renderMetrics.js +14 -0
  48. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  49. package/dist/cli/chat/resizeGuard.js +25 -0
  50. package/dist/cli/chat/screenDeps.d.ts +116 -0
  51. package/dist/cli/chat/screenDeps.js +1 -0
  52. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  53. package/dist/cli/chat/sessionLifecycle.js +6 -2
  54. package/dist/cli/chat/sessionRecorder.js +4 -1
  55. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  56. package/dist/cli/chat/settingsSelection.js +46 -0
  57. package/dist/cli/chat/skillNotices.d.ts +18 -0
  58. package/dist/cli/chat/skillNotices.js +26 -0
  59. package/dist/cli/chat/startupInfo.js +1 -1
  60. package/dist/cli/chat/startupSequence.d.ts +2 -0
  61. package/dist/cli/chat/startupSequence.js +6 -0
  62. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  63. package/dist/cli/chat/submitPipeline.js +141 -0
  64. package/dist/cli/chat/terminalControl.js +1 -1
  65. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  66. package/dist/cli/chat/toolSummaries.js +268 -0
  67. package/dist/cli/chat/turnState.d.ts +8 -0
  68. package/dist/cli/chat/turnState.js +1 -0
  69. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  70. package/dist/cli/chat/userCommandFlow.js +66 -0
  71. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  72. package/dist/cli/chat/userCommandRunner.js +56 -0
  73. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  74. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  75. package/dist/cli/chat/wizardTrail.js +55 -0
  76. package/dist/cli/commands/chat.d.ts +1 -13
  77. package/dist/cli/commands/chat.js +10 -795
  78. package/dist/cli/commands/commandHelp.js +11 -6
  79. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  80. package/dist/cli/commands/commandSuggest.js +35 -0
  81. package/dist/cli/commands/commands.js +12 -3
  82. package/dist/cli/commands/formatters.d.ts +1 -23
  83. package/dist/cli/commands/formatters.js +3 -224
  84. package/dist/cli/commands/graphCommand.d.ts +2 -0
  85. package/dist/cli/commands/graphCommand.js +60 -0
  86. package/dist/cli/commands/initCommand.js +14 -0
  87. package/dist/cli/commands/modelCommand.js +11 -7
  88. package/dist/cli/commands/reasoningCommand.js +3 -3
  89. package/dist/cli/commands/runCommand.js +6 -2
  90. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  91. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  92. package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
  93. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  94. package/dist/cli/commands/streaming/attemptSetup.js +34 -5
  95. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  96. package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
  97. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  98. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  99. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  100. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  101. package/dist/cli/commands/streaming/streamLoop.js +34 -23
  102. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  103. package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
  104. package/dist/cli/commands/streaming.d.ts +3 -1
  105. package/dist/cli/commands/streaming.js +5 -0
  106. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  107. package/dist/cli/commands/wizardFlow.js +3 -0
  108. package/dist/cli/index.js +8 -4
  109. package/dist/cli/terminalTitle.js +9 -3
  110. package/dist/config/contextFiles.d.ts +2 -5
  111. package/dist/config/contextFiles.js +1 -1
  112. package/dist/config/inputHistory.js +2 -2
  113. package/dist/config/providerAuth.js +2 -2
  114. package/dist/config/providerModelFacts.js +5 -0
  115. package/dist/config/providerPresets.js +1 -1
  116. package/dist/config/settings.d.ts +7 -0
  117. package/dist/config/settings.js +9 -2
  118. package/dist/config/updateCheck.js +2 -2
  119. package/dist/core/agent/compaction.d.ts +1 -0
  120. package/dist/core/agent/compaction.js +3 -0
  121. package/dist/core/agent/completionController.d.ts +1 -1
  122. package/dist/core/agent/contextBudget.d.ts +1 -1
  123. package/dist/core/agent/goalPolicy.js +8 -2
  124. package/dist/core/agent/overflow.js +5 -0
  125. package/dist/core/agent/toolCapabilities.js +14 -0
  126. package/dist/core/agent/userCommands.d.ts +53 -0
  127. package/dist/core/agent/userCommands.js +116 -0
  128. package/dist/core/agent/workState.d.ts +3 -1
  129. package/dist/core/agent/workState.js +57 -26
  130. package/dist/core/contextFileTypes.d.ts +12 -0
  131. package/dist/core/contextFileTypes.js +1 -0
  132. package/dist/core/graph/analyze.d.ts +61 -0
  133. package/dist/core/graph/analyze.js +274 -0
  134. package/dist/core/graph/buildGraph.d.ts +44 -0
  135. package/dist/core/graph/buildGraph.js +290 -0
  136. package/dist/core/graph/digest.d.ts +2 -0
  137. package/dist/core/graph/digest.js +40 -0
  138. package/dist/core/graph/extract.d.ts +58 -0
  139. package/dist/core/graph/extract.js +394 -0
  140. package/dist/core/graph/model.d.ts +63 -0
  141. package/dist/core/graph/model.js +96 -0
  142. package/dist/core/graph/query.d.ts +69 -0
  143. package/dist/core/graph/query.js +391 -0
  144. package/dist/core/graph/store.d.ts +64 -0
  145. package/dist/core/graph/store.js +171 -0
  146. package/dist/core/limits.d.ts +2 -0
  147. package/dist/core/limits.js +2 -0
  148. package/dist/core/log/llmLog.js +2 -2
  149. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  150. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  151. package/dist/core/process/runBoundedProcess.js +22 -11
  152. package/dist/core/safety/redaction.d.ts +2 -0
  153. package/dist/core/safety/redaction.js +26 -5
  154. package/dist/core/safety/secretPaths.js +12 -3
  155. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  156. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  157. package/dist/core/safety/urlGuard.js +2 -0
  158. package/dist/core/session/sessionStore.d.ts +8 -1
  159. package/dist/core/session/sessionStore.js +15 -4
  160. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  161. package/dist/core/shellOutput/types.d.ts +1 -1
  162. package/dist/core/subagent/executionProfiles.js +4 -4
  163. package/dist/core/tasks/taskStorage.js +11 -1
  164. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  165. package/dist/core/validation/outputParser.d.ts +1 -1
  166. package/dist/core/validation/outputParser.js +16 -8
  167. package/dist/llm/hazeTools.d.ts +2 -12426
  168. package/dist/llm/hazeTools.js +4 -0
  169. package/dist/llm/lsp/pool.js +1 -1
  170. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  171. package/dist/llm/lspTools.d.ts +3 -12622
  172. package/dist/llm/requestContext.d.ts +6 -0
  173. package/dist/llm/requestContext.js +28 -7
  174. package/dist/llm/subagentRunner.d.ts +2 -308
  175. package/dist/llm/systemPrompt.js +17 -7
  176. package/dist/llm/toolGroups.d.ts +534 -0
  177. package/dist/llm/toolGroups.js +57 -0
  178. package/dist/llm/tools/editMatch.d.ts +1 -1
  179. package/dist/llm/tools/failures.d.ts +1 -1
  180. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  181. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  182. package/dist/llm/tools/fileToolShared.js +1 -1
  183. package/dist/llm/tools/fileTools.d.ts +2 -7768
  184. package/dist/llm/tools/fileTools.js +1 -1
  185. package/dist/llm/tools/gitTools.d.ts +12 -0
  186. package/dist/llm/tools/gitTools.js +527 -0
  187. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  188. package/dist/llm/tools/graphAdvisory.js +68 -0
  189. package/dist/llm/tools/graphTools.d.ts +13 -0
  190. package/dist/llm/tools/graphTools.js +195 -0
  191. package/dist/llm/tools/processTool.d.ts +2 -1081
  192. package/dist/llm/tools/readRecovery.d.ts +1 -1
  193. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  194. package/dist/llm/tools/replaceInFiles.js +1 -1
  195. package/dist/llm/tools/shellTool.d.ts +2 -1513
  196. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  197. package/dist/llm/tools/taskTool.d.ts +2 -489
  198. package/dist/llm/tools/taskTool.js +4 -1
  199. package/dist/llm/tools/toolContext.js +29 -11
  200. package/dist/llm/tools/toolContextState.d.ts +4 -1
  201. package/dist/llm/tools/toolContextState.js +2 -1
  202. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  203. package/dist/llm/tools/workspaceFile.js +10 -5
  204. package/dist/skills/SkillRegistry.js +1 -1
  205. package/dist/skills/builder/SkillBuilder.js +1 -1
  206. package/dist/skills/plugins/installer.js +1 -1
  207. package/dist/skills/plugins/runtime.js +1 -1
  208. package/dist/skills/skillTools.js +4 -1
  209. package/dist/ui/components/MarkdownText.d.ts +14 -0
  210. package/dist/ui/components/MarkdownText.js +77 -12
  211. package/dist/ui/components/NativeIndicators.js +5 -1
  212. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  213. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  214. package/dist/ui/components/TextInput.d.ts +1 -2
  215. package/dist/ui/components/TextInput.js +79 -9
  216. package/dist/ui/components/WizardChoices.d.ts +1 -2
  217. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  218. package/dist/ui/components/useInputSuggestions.js +1 -1
  219. package/dist/ui/mentionDetection.d.ts +20 -0
  220. package/dist/ui/mentionDetection.js +24 -0
  221. package/dist/ui/terminalColors.d.ts +4 -4
  222. package/dist/ui/terminalColors.js +23 -6
  223. package/dist/ui/terminalSanitize.js +8 -3
  224. package/dist/ui/textGeometry.d.ts +2 -0
  225. package/dist/ui/textGeometry.js +6 -0
  226. package/dist/ui/themes/registry.js +33 -33
  227. package/dist/utils/openPath.js +7 -0
  228. package/package.json +22 -19
  229. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  230. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  231. /package/dist/{config → core}/paths.d.ts +0 -0
  232. /package/dist/{config → core}/paths.js +0 -0
  233. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  234. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -3,7 +3,7 @@ import { agentEvent } from '../../../core/agent/events.js';
3
3
  import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
4
4
  import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
6
- import { checkKindsOfIds, deriveValidationOutcome, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
6
+ import { checkKindsOfIds, deriveValidationOutcome, openFailedCheckCommands, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
7
7
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
8
8
  import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
9
9
  import { formatSeconds } from '../../../utils/format.js';
@@ -70,7 +70,7 @@ export function finalizeAttemptOutcome(deps) {
70
70
  const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, unresolvedToolInputError: stream.unresolvedToolInputError };
71
71
  const readiness = assessCompletionReadiness(turnState, completionEvidence);
72
72
  const classification = classifyTerminalOutcome(turnState, completionEvidence);
73
- const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, requiresTaskLedger: turnState.requiresTaskLedger, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
73
+ const turnStatus = terminalTurnStatus({ aborted: abortController.signal.aborted, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, requiresTaskLedger: turnState.requiresTaskLedger, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
74
74
  if (stream.unresolvedMalformedToolName)
75
75
  callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated${stream.unresolvedMalformedToolProblem ? ` — ${stream.unresolvedMalformedToolProblem}` : ''}. The requested work is incomplete.` });
76
76
  // Non-error overflow recovery (Pillar 1.2/1.4): a silent overflow completed
@@ -147,7 +147,12 @@ export function finalizeAttemptOutcome(deps) {
147
147
  discardRejectedFinal();
148
148
  if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
149
149
  turnState.validationContinuationUsed = true;
150
- return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress, checkKindsOfIds(unresolvedFailedCheckIds(goal))), taskCountsOf(turnState.taskProgress), turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
150
+ const openChecks = openFailedCheckCommands(goal);
151
+ const openCheckDetail = readiness === 'validation_failed' && openChecks.length
152
+ ? `Failed checks still open: ${openChecks.map(command => `\`${command}\``).join('; ')}.`
153
+ : undefined;
154
+ const validationDetail = [openCheckDetail, turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined].filter(Boolean).join(' ') || undefined;
155
+ return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress, checkKindsOfIds(unresolvedFailedCheckIds(goal))), taskCountsOf(turnState.taskProgress), validationDetail), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
151
156
  }
152
157
  else if (rescueSlice && rescueSlice.steps > 0) {
153
158
  return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
@@ -3,6 +3,7 @@ import type { ContextFile } from '../../../config/contextFiles.js';
3
3
  import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
4
4
  import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
5
5
  import { calculateRequestTokenBudget, type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
6
+ import type { TurnExecutionState } from '../../../core/agent/completionController.js';
6
7
  import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
7
8
  import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
8
9
  import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
@@ -36,6 +37,7 @@ export interface AttemptSetup {
36
37
  omitMaxOutputTokens: boolean | undefined;
37
38
  /** Tools visible to this attempt: rescue-restricted, budget-clamped, and deadline-wrapped. */
38
39
  sliceTools: ToolSet;
40
+ activateToolGroups?: () => boolean;
39
41
  stepCap: number;
40
42
  /** A rescue slice with no qualifying tools must synthesize, never reopen discovery (F-08). */
41
43
  rescueWithoutTools: boolean;
@@ -71,6 +73,8 @@ export interface AttemptSetupDeps {
71
73
  executionScope?: TurnExecutionScope;
72
74
  };
73
75
  turnBudget: TurnBudget;
76
+ /** Turn-wide execution state; the attempt's step cap is clamped against its cumulative usage. */
77
+ turnState: TurnExecutionState;
74
78
  globalBudget: ToolExecutionBudgetState;
75
79
  /** Shared slice execution state (see AgentAttemptInput.sliceBudget). */
76
80
  sliceBudget: ToolExecutionBudgetState;
@@ -1,11 +1,12 @@
1
1
  import { readSettings } from '../../../config/settings.js';
2
- import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, resolveStreamIdleTimeoutMs, usesPatientIdleWindow, withToolExecutionBudget } from '../../../core/agent/budgets.js';
2
+ import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, resolveStreamIdleTimeoutMs, remainingSteps, usesPatientIdleWindow, withToolExecutionBudget } from '../../../core/agent/budgets.js';
3
3
  import { agentEvent } from '../../../core/agent/events.js';
4
4
  import { goalDirectionPrompt, isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
5
5
  import { projectPreflight } from '../../../core/agent/projectPreflight.js';
6
6
  import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
7
7
  import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
8
8
  import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
9
+ import { foldUserCommandRecords } from '../../../core/agent/userCommands.js';
9
10
  import { compactModelMessages } from '../../../core/agent/compaction.js';
10
11
  import { withToolDeadline } from '../../../core/deadline.js';
11
12
  import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
@@ -13,6 +14,7 @@ import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
13
14
  import { WorkspaceMutationPolicy } from '../../../core/subagent/workspaceMutationPolicy.js';
14
15
  import { modelWithConfig, providerRequestSettings, isLocalProviderUrl } from '../../../llm/client.js';
15
16
  import { assembleRequestContext } from '../../../llm/requestContext.js';
17
+ import { toolsInLoadedGroups } from '../../../llm/toolGroups.js';
16
18
  import { modelThinkingLabel } from '../../../utils/modelName.js';
17
19
  import { estimateInputBreakdown, logEntry } from './turnRuntime.js';
18
20
  /**
@@ -40,7 +42,7 @@ export function restrictToRescueTools(tools) {
40
42
  * configured (the caller-reported failure path).
41
43
  */
42
44
  export async function prepareAttempt(deps) {
43
- const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
45
+ const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnState, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
44
46
  // Single choke point: one fresh settings read per attempt, shared by model
45
47
  // resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
46
48
  // provider/model switch mid-goal applies from the next attempt — the first
@@ -102,10 +104,12 @@ export async function prepareAttempt(deps) {
102
104
  // to rewrite older successful calls/results here, invalidating provider
103
105
  // prompt-cache prefixes before the context budget required compaction.
104
106
  // Durable session snapshots preserve this history; only model-aware
105
- // compaction or an explicit provider transition may rewrite it.
107
+ // compaction or an explicit provider transition may rewrite it. Records of
108
+ // commands the user ran with `!` fold into the new user turn (one user
109
+ // message per turn for providers that require alternation).
106
110
  const durableRequestMessages = retryingExistingRequest
107
111
  ? stripSyntheticControls(callbacks.getConversation())
108
- : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])];
112
+ : foldUserCommandRecords(stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? []));
109
113
  // Model-aware request budget (RH-005): message allowance is the context
110
114
  // window minus system prompt, tool schemas, output reserve, and a safety
111
115
  // margin — not a fixed 40K constant. Small contexts get a safe budget; the
@@ -146,9 +150,14 @@ export async function prepareAttempt(deps) {
146
150
  mutationPolicy,
147
151
  blessedPaths: turnOptions.blessedPaths,
148
152
  postMutationDiagnostics: assembled.postMutationDiagnostics,
153
+ postMutationGraph: assembled.postMutationGraph,
149
154
  };
150
155
  const recoverySlice = turnOptions.recoverySlice;
151
- const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
156
+ // The turn-wide step budget never resets (matching the tool-call execution
157
+ // boundary): a provider retry must not re-arm the main step cap, so clamp
158
+ // this attempt's cap to what the turn has left. Recovery slices were
159
+ // already clamped at admission; Math.min keeps them unchanged.
160
+ const stepCap = Math.min(recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT, remainingSteps(turnState.stepsUsed, turnBudget));
152
161
  // Rescue exposes only mutation + validation-capable built-in tools so
153
162
  // discovery cannot be reopened near the boundary. Length-continuation keeps
154
163
  // the full tool set. When no built-in mutation/validation tool qualifies,
@@ -177,6 +186,25 @@ export async function prepareAttempt(deps) {
177
186
  const deadlineMs = name === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS;
178
187
  return [name, { ...definition, execute: (...args) => withToolDeadline(() => execute(...args), deadlineMs, abortController.signal) }];
179
188
  }));
189
+ const activateToolGroups = () => {
190
+ if (recoverySlice?.kind === 'rescue' || !assembled.deferredTools)
191
+ return false;
192
+ const candidates = toolsInLoadedGroups(assembled.deferredTools, assembled.executionScope.loadedToolGroups ?? new Set());
193
+ const added = Object.fromEntries(Object.entries(candidates).filter(([name]) => !(name in deadlineWrappedTools)));
194
+ if (Object.keys(added).length === 0)
195
+ return false;
196
+ const budgeted = withToolExecutionBudget(added, { state: globalBudget, limit: turnBudget.toolCallLimit }, { state: sliceBudget, limit: sliceToolCallCap });
197
+ for (const [name, definition] of Object.entries(budgeted)) {
198
+ const execute = definition.execute;
199
+ deadlineWrappedTools[name] = typeof definition.execute !== 'function' ? definition : { ...definition, execute: (...args) => withToolDeadline(() => execute(...args), DEFAULT_TOOL_DEADLINE_MS, abortController.signal) };
200
+ toolCategories.set(name, name.startsWith('lsp') ? 'lsp' : 'builtin');
201
+ }
202
+ Object.assign(requestBudget, calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: systemPrompt, tools: deadlineWrappedTools }));
203
+ Object.assign(inputBreakdown, estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: deadlineWrappedTools }));
204
+ usageAnchor.current = undefined;
205
+ callbacks.debugLog(`Loaded tool groups: ${Object.keys(added).join(', ')}`);
206
+ return true;
207
+ };
180
208
  return {
181
209
  runtime,
182
210
  thinkingLabel,
@@ -187,6 +215,7 @@ export async function prepareAttempt(deps) {
187
215
  providerSettings,
188
216
  omitMaxOutputTokens,
189
217
  sliceTools: deadlineWrappedTools,
218
+ activateToolGroups,
190
219
  stepCap,
191
220
  rescueWithoutTools,
192
221
  toolExecutionContext,
@@ -1,7 +1,7 @@
1
1
  import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
2
  import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
3
3
  import type { RedEvidence, ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
4
- import type { ValidationKind } from '../../../llm/toolResultTypes.js';
4
+ import type { ValidationKind } from '../../../core/toolResultTypes.js';
5
5
  import type { GoalLedgerFrontier } from '../../../core/session/sessionStore.js';
6
6
  /**
7
7
  * Bounded continuation checkpoint for a logical goal whose work is recoverably
@@ -191,14 +191,16 @@ export async function runAgentGoal(options) {
191
191
  const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, activeModelOverride, turnOptions, options.reasoningOverride);
192
192
  initialRetryAttempt = 0;
193
193
  cycle += 1;
194
- if (cycle >= GOAL_MAX_CYCLES) {
195
- return finish('failed', 'cycle-limit', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
196
- }
197
194
  lastEvidence = result.evidence;
198
195
  if (result.checkpoint)
199
196
  checkpoint = result.checkpoint;
197
+ // Structured completion wins over the cycle bound: a goal that finishes
198
+ // on the limit cycle is a success, never a cycle-limit failure.
200
199
  if (result.status === 'complete')
201
200
  return finish('complete', 'completed');
201
+ if (cycle >= GOAL_MAX_CYCLES) {
202
+ return finish('failed', 'cycle-limit', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
203
+ }
202
204
  if (result.status === 'aborted') {
203
205
  return result.abortReason === 'turn-deadline'
204
206
  ? finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined)
@@ -40,6 +40,7 @@ export function createRepairToolCall(deps) {
40
40
  loopState.pendingMalformedToolProblem = problem;
41
41
  loopState.unresolvedMalformedToolName = toolCall.toolName;
42
42
  loopState.unresolvedMalformedToolProblem = problem;
43
+ loopState.unresolvedMalformedAtStep = loopState.completedSteps;
43
44
  }
44
45
  // Truncated generated file content cannot be reconstructed safely here;
45
46
  // let the next agent step retry under the bounded tool-choice constraint.
@@ -0,0 +1,59 @@
1
+ import { type AgentEvent } from '../../../core/agent/events.js';
2
+ import { stepCacheMetrics } from './turnRuntime.js';
3
+ /** Provider usage shape accepted by `stepCacheMetrics`, plus output tokens. */
4
+ export type StepUsage = Parameters<typeof stepCacheMetrics>[0] & {
5
+ outputTokens?: number;
6
+ };
7
+ /**
8
+ * Pure "what happened this epoch" projection (ARCH-06), extracted from
9
+ * `streamLoop.ts`'s `onStepEnd` so the counter/usage/event math is unit-testable
10
+ * outside the SDK. The caller owns the side effects (loop/turn state, callbacks,
11
+ * logs); this function only computes values.
12
+ */
13
+ export interface StepEndInput {
14
+ /** Completed-step count AFTER this step is recorded. */
15
+ completedSteps: number;
16
+ /** 1-based retry attempt number. */
17
+ attempt: number;
18
+ text: string;
19
+ toolCallCount: number;
20
+ toolResultCount: number;
21
+ finishReason: string;
22
+ /** Raw provider usage object for this step (may be an empty shape). */
23
+ usage: StepUsage | undefined;
24
+ responseModel: string | undefined;
25
+ /** Last valid per-step usage before this step (usage-overflow detection). */
26
+ previousLastUsage: LastStepUsage | undefined;
27
+ /** Turn-wide counters before this step. */
28
+ stepsUsed: number;
29
+ toolCallsUsed: number;
30
+ }
31
+ export interface LastStepUsage {
32
+ inputTokens: number | undefined;
33
+ outputTokens: number;
34
+ cacheReadTokens: number;
35
+ cacheWriteTokens: number;
36
+ }
37
+ export interface StepEndProjection {
38
+ /** step_end agent event payload. */
39
+ event: AgentEvent;
40
+ /** --debug LLM log entry payload (without the log sink). */
41
+ log: {
42
+ at: string;
43
+ type: 'step';
44
+ stream: 'main';
45
+ step: number;
46
+ text: string;
47
+ finishReason: string | undefined;
48
+ usage: Record<string, number | undefined>;
49
+ };
50
+ /** Usage to remember for usage-overflow detection (unchanged when this step reported nothing). */
51
+ lastUsage: LastStepUsage | undefined;
52
+ /** Turn-wide counters after this step. */
53
+ stepsUsed: number;
54
+ toolCallsUsed: number;
55
+ /** Whether this step was tool-only (tool calls with no text). */
56
+ toolOnlyStep: boolean;
57
+ debugLine: string;
58
+ }
59
+ export declare function projectStepEnd(input: StepEndInput, now?: () => Date): StepEndProjection;
@@ -0,0 +1,54 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { stepCacheMetrics } from './turnRuntime.js';
3
+ export function projectStepEnd(input, now = () => new Date()) {
4
+ const stepUsage = stepCacheMetrics(input.usage);
5
+ const outputTokens = input.usage?.outputTokens;
6
+ const hasUsage = stepUsage.inputTokens != null || outputTokens != null
7
+ || stepUsage.cacheReadTokens > 0 || stepUsage.cacheWriteTokens > 0;
8
+ const lastUsage = hasUsage
9
+ ? { inputTokens: stepUsage.inputTokens, outputTokens: outputTokens ?? 0, cacheReadTokens: stepUsage.cacheReadTokens, cacheWriteTokens: stepUsage.cacheWriteTokens }
10
+ : input.previousLastUsage;
11
+ const toolOnlyStep = input.toolCallCount > 0 && input.text.trim().length === 0;
12
+ const publicUsage = {
13
+ inputTokens: stepUsage.inputTokens ?? 0,
14
+ outputTokens: outputTokens ?? 0,
15
+ cacheReadTokens: stepUsage.cacheReadTokens,
16
+ cacheWriteTokens: stepUsage.cacheWriteTokens,
17
+ reasoningTokens: stepUsage.reasoningTokens,
18
+ };
19
+ const event = agentEvent({
20
+ type: 'step_end',
21
+ attempt: input.attempt,
22
+ step: input.completedSteps,
23
+ finishReason: input.finishReason,
24
+ toolCallCount: input.toolCallCount,
25
+ usage: publicUsage,
26
+ ...(input.responseModel ? { responseModel: input.responseModel } : {}),
27
+ });
28
+ const log = {
29
+ at: now().toISOString(),
30
+ type: 'step',
31
+ stream: 'main',
32
+ step: input.completedSteps - 1,
33
+ text: input.text,
34
+ finishReason: input.finishReason,
35
+ usage: {
36
+ inputTokens: stepUsage.inputTokens,
37
+ outputTokens,
38
+ cacheReadTokens: stepUsage.cacheReadTokens || undefined,
39
+ cacheWriteTokens: stepUsage.cacheWriteTokens || undefined,
40
+ noCacheTokens: stepUsage.noCacheTokens || undefined,
41
+ reasoningTokens: stepUsage.reasoningTokens || undefined,
42
+ cacheHitRatio: stepUsage.cacheHitRatio,
43
+ },
44
+ };
45
+ return {
46
+ event,
47
+ log,
48
+ lastUsage,
49
+ stepsUsed: input.stepsUsed + 1,
50
+ toolCallsUsed: input.toolCallsUsed,
51
+ toolOnlyStep,
52
+ debugLine: `step ${input.completedSteps - 1} finished: ${String(input.finishReason)}; text=${input.text.length}; toolCalls=${input.toolCallCount}; toolResults=${input.toolResultCount}`,
53
+ };
54
+ }
@@ -34,6 +34,8 @@ export interface AttemptLoopState {
34
34
  unresolvedMalformedToolName: string | undefined;
35
35
  /** Last known diagnosis for the unresolved malformed tool; rides the turn-end system note so later turns see the exact defect. */
36
36
  unresolvedMalformedToolProblem: string | undefined;
37
+ /** Attempt-local completed-step count when the unresolved malformed call was recorded; a same-name success clears the flag only from a later step. */
38
+ unresolvedMalformedAtStep: number | undefined;
37
39
  /** Per-attempt (not per-turn) recovery counter: a transient retry gets a fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT. */
38
40
  malformedRecoveryAttempts: Map<string, number>;
39
41
  toolResultState: ToolResultState;
@@ -5,17 +5,19 @@ import { auxiliaryRequestOptions } from '../../../core/providerContracts.js';
5
5
  import { contextTokensFromUsage, estimateConversationTokens, estimateValueTokens } from '../../../core/agent/contextBudget.js';
6
6
  import { stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
7
7
  import { buildLlmCompactionPrompt, chooseBoundaryCompactionMethod, compactModelMessages, compactModelMessagesWithSummary, extractExistingCompactionSummary } from '../../../core/agent/compaction.js';
8
+ import { buildCodeGraphDigest } from '../../../core/graph/digest.js';
8
9
  import { isLengthStopOverflow, isSilentContextOverflow } from '../../../core/agent/overflow.js';
9
10
  import { isValidationRerunToolCall } from '../../../core/agent/turnPolicy.js';
10
11
  import { COMPACTION_LLM_MAX_OUTPUT_TOKENS, COMPACTION_LLM_MIN_OLDER_TOKENS } from '../../../core/agent/budgets.js';
11
12
  import { toolsContextFor } from '../../../llm/tools/toolContext.js';
12
- import { busyToolLabel, toolCallSummary } from '../formatters.js';
13
+ import { busyToolLabel, toolCallSummary } from '../../chat/toolSummaries.js';
13
14
  import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
14
15
  import { finalizeAssistantSegment, finalizePendingAssistantBeforeTool } from './assistantSegments.js';
15
16
  import { handleToolErrorPart, handleToolResultPart } from './toolPartHandlers.js';
16
17
  import { createPrepareStep, createRepairToolCall } from './prepareStep.js';
17
18
  import { applyStepToolResultState, initialToolResultState } from './toolResultState.js';
18
- import { extractUsage, logEntry, stepCacheMetrics } from './turnRuntime.js';
19
+ import { extractUsage, logEntry } from './turnRuntime.js';
20
+ import { projectStepEnd } from './stepProjection.js';
19
21
  export function createAttemptLoopState(previousAssistantText, contextFiles, callbacks) {
20
22
  const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
21
23
  return {
@@ -35,6 +37,7 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
35
37
  pendingMalformedToolProblem: undefined,
36
38
  unresolvedMalformedToolName: undefined,
37
39
  unresolvedMalformedToolProblem: undefined,
40
+ unresolvedMalformedAtStep: undefined,
38
41
  malformedRecoveryAttempts: new Map(),
39
42
  toolResultState: initialToolResultState(),
40
43
  inFlightTools: new Set(),
@@ -202,6 +205,7 @@ async function commitStreamResult(deps, result) {
202
205
  */
203
206
  async function runAgentEpoch(deps, requestMessages) {
204
207
  const { setup, callbacks, loopState, turnState, globalBudget, stallGuard, salvage, retryAttempt, abortController } = deps;
208
+ const toolsActivated = setup.activateToolGroups?.() ?? false;
205
209
  const { sliceTools, systemPrompt, inputBreakdown, providerSettings, omitMaxOutputTokens, toolExecutionContext } = setup;
206
210
  const prepare = createPrepareStep(deps);
207
211
  const completedBefore = loopState.completedSteps;
@@ -237,7 +241,7 @@ async function runAgentEpoch(deps, requestMessages) {
237
241
  if (completedBefore > 0) {
238
242
  const messagesPreserved = requestMessages.length <= preparedMessages.length
239
243
  && requestMessages.every((message, index) => preparedMessages[index] === message);
240
- const requestPolicyStable = prepared?.activeTools == null
244
+ const requestPolicyStable = !toolsActivated && prepared?.activeTools == null
241
245
  && prepared?.toolChoice == null
242
246
  && prepared?.model == null
243
247
  && prepared?.providerOptions == null;
@@ -261,35 +265,41 @@ async function runAgentEpoch(deps, requestMessages) {
261
265
  // Tool-loop control must advance from this internally ordered callback.
262
266
  loopState.toolResultState = applyStepToolResultState(loopState.toolResultState, content);
263
267
  recordCompletedStep(loopState, { text, toolCalls });
264
- // Remember the last valid per-step usage for usage-overflow detection
265
- // (Pillar 1.2); empty usage objects (some gateways/tests) keep the
266
- // previous value or stay unset.
267
- const stepUsage = stepCacheMetrics(usage);
268
- if (stepUsage.inputTokens != null || usage?.outputTokens != null || stepUsage.cacheReadTokens > 0 || stepUsage.cacheWriteTokens > 0) {
269
- loopState.lastUsage = { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens ?? 0, cacheReadTokens: stepUsage.cacheReadTokens, cacheWriteTokens: stepUsage.cacheWriteTokens };
270
- }
268
+ // The "what happened this epoch" projection (counters, usage fallback,
269
+ // step_end event, log entry) is pure and unit-tested in stepProjection.ts.
270
+ const projection = projectStepEnd({
271
+ completedSteps: loopState.completedSteps,
272
+ attempt: retryAttempt + 1,
273
+ text,
274
+ toolCallCount: toolCalls.length,
275
+ toolResultCount: toolResults.length,
276
+ finishReason,
277
+ usage,
278
+ responseModel: response?.modelId,
279
+ previousLastUsage: loopState.lastUsage,
280
+ stepsUsed: turnState.stepsUsed,
281
+ toolCallsUsed: globalBudget.started,
282
+ });
283
+ if (projection.lastUsage)
284
+ loopState.lastUsage = projection.lastUsage;
271
285
  // Turn-wide counters remain shared across bounded SDK epochs, retries,
272
286
  // and recovery slices. Executions are authoritative for tool-call usage.
273
- turnState.stepsUsed += 1;
274
- turnState.toolCallsUsed = globalBudget.started;
275
- if (toolCalls.length > 0 && text.trim().length === 0)
287
+ turnState.stepsUsed = projection.stepsUsed;
288
+ turnState.toolCallsUsed = projection.toolCallsUsed;
289
+ if (projection.toolOnlyStep)
276
290
  turnState.toolOnlyStepsUsed += 1;
277
291
  if (Array.isArray(response?.messages) && response.messages.length > 0)
278
292
  salvage.accumulated = response.messages;
279
- const publicUsage = {
280
- inputTokens: stepUsage.inputTokens ?? 0,
281
- outputTokens: usage?.outputTokens ?? 0,
282
- cacheReadTokens: stepUsage.cacheReadTokens,
283
- cacheWriteTokens: stepUsage.cacheWriteTokens,
284
- reasoningTokens: stepUsage.reasoningTokens,
285
- };
286
- callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: loopState.completedSteps, finishReason, toolCallCount: toolCalls.length, usage: publicUsage, ...(response?.modelId ? { responseModel: response.modelId } : {}) }));
287
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: loopState.completedSteps - 1, text, finishReason, usage: { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens, cacheReadTokens: stepUsage.cacheReadTokens || undefined, cacheWriteTokens: stepUsage.cacheWriteTokens || undefined, noCacheTokens: stepUsage.noCacheTokens || undefined, reasoningTokens: stepUsage.reasoningTokens || undefined, cacheHitRatio: stepUsage.cacheHitRatio } });
288
- callbacks.debugLog(`step ${loopState.completedSteps - 1} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
293
+ callbacks.onEvent?.(projection.event);
294
+ logEntry(callbacks.log, projection.log);
295
+ callbacks.debugLog(projection.debugLine);
289
296
  },
290
297
  onEnd(event) {
291
298
  const providerUsage = extractUsage({ usage: event.usage });
292
299
  epochUsage = { inputTokens: providerUsage.inputTokens, outputTokens: providerUsage.outputTokens, cacheReadTokens: providerUsage.cacheReadTokens, cacheWriteTokens: providerUsage.cacheWriteTokens };
300
+ const contextTokens = contextTokensFromUsage(epochUsage ?? {});
301
+ if (contextTokens !== undefined)
302
+ callbacks.recordContextUsage?.(contextTokens);
293
303
  callbacks.recordTokenUsage?.({
294
304
  inputTokens: providerUsage.inputTokens,
295
305
  outputTokens: providerUsage.outputTokens,
@@ -367,6 +377,7 @@ async function compactAtEpochBoundary(deps, providerMessages) {
367
377
  older: split.older,
368
378
  previousSummary: extractExistingCompactionSummary(providerMessages),
369
379
  splitTurn: split.splitTurn,
380
+ codeGraphDigest: await buildCodeGraphDigest(),
370
381
  });
371
382
  const summarization = streamText({
372
383
  model: setup.runtime.model,
@@ -1,6 +1,6 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
3
- import { toolCallSummary, compact } from '../formatters.js';
3
+ import { toolCallSummary, compact } from '../../chat/toolSummaries.js';
4
4
  import { stripTerminalControlSequences } from '../../../ui/terminalSanitize.js';
5
5
  import { formatElapsedTimeWhole, formatSeconds } from '../../../utils/format.js';
6
6
  function logEntry(log, entry) {
@@ -4,7 +4,7 @@ import { DEFAULT_TOOL_DEADLINE_MS, SUBAGENT_TOOL_DEADLINE_MS, isToolBudgetBlocke
4
4
  import { isToolDeadlineExceeded } from '../../../core/deadline.js';
5
5
  import { isDuplicateSkippedOutput, safeToolFailureDetails, toolOutputOk } from '../../../core/agent/toolResults.js';
6
6
  import { validationSummaryFromOutput } from '../../../core/agent/workState.js';
7
- import { toolResultSummary } from '../formatters.js';
7
+ import { toolResultSummary } from '../../chat/toolSummaries.js';
8
8
  import { toolDiffFromResult } from './toolGroupRenderer.js';
9
9
  import { isMalformedToolInputError, toolInputProblemFromError } from './toolCallRecovery.js';
10
10
  import { logEntry, rememberContextFilesFromToolOutput, subagentTokenEstimate } from './turnRuntime.js';
@@ -58,9 +58,15 @@ export function handleToolResultPart(deps, part) {
58
58
  // the completion gates; a failed edit/write stays a hard tool failure even
59
59
  // when an earlier check also failed.
60
60
  loopState.lastFailedToolWasValidation = !ok && toolName === 'shell' && validationSummaryFromOutput(part.output) != null;
61
- if (ok && part.toolName === loopState.unresolvedMalformedToolName) {
61
+ // A successful same-name call clears the unresolved flag only when it ran
62
+ // in a *later* step: a successful sibling within the same parallel batch
63
+ // (same completed-step count) must not mask the malformed call's failure.
64
+ if (ok && part.toolName === loopState.unresolvedMalformedToolName
65
+ && loopState.unresolvedMalformedAtStep != null
66
+ && loopState.completedSteps > loopState.unresolvedMalformedAtStep) {
62
67
  loopState.unresolvedMalformedToolName = undefined;
63
68
  loopState.unresolvedMalformedToolProblem = undefined;
69
+ loopState.unresolvedMalformedAtStep = undefined;
64
70
  }
65
71
  const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
66
72
  const item = toolDisplay.ensureToolItem(toolCall);
@@ -5,7 +5,7 @@ import type { ImageAttachment } from '../../core/attachments/imageAttachments.js
5
5
  import { type BlessedPath } from '../../core/attachments/readBlessings.js';
6
6
  import type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
7
7
  import type { RedEvidence, ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
8
- import type { ValidationKind } from '../../llm/toolResultTypes.js';
8
+ import type { ValidationKind } from '../../core/toolResultTypes.js';
9
9
  import type { SubagentOverrides, TurnExecutionScope } from '../../llm/requestContext.js';
10
10
  import type { PromptSession } from '../../llm/systemPrompt.js';
11
11
  import type { StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
@@ -123,6 +123,8 @@ export interface StreamCallbacks {
123
123
  summary: string;
124
124
  }) => void;
125
125
  recordTokenUsage?: (usage: TokenUsage) => void;
126
+ /** Provider-measured size (input + output) of the last completed model step, i.e. the next request's context. */
127
+ recordContextUsage?: (tokens: number) => void;
126
128
  setWorkState?: (state: WorkState) => void;
127
129
  onTasksChanged?: () => void;
128
130
  log?: LlmLog;
@@ -131,6 +131,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
131
131
  await abortableDelay(result.retry.delayMs, abortController.signal);
132
132
  if (abortController.signal.aborted) {
133
133
  status = 'aborted';
134
+ // The abort landed during retry backoff, after the attempt result
135
+ // was classified: recover the cause from the shared holder so a
136
+ // turn-deadline abort reaches the supervisor as `turn-deadline`
137
+ // (goal-deadline checkpoint) instead of a plain user cancel.
138
+ abortReason = abortCause.kind === 'turn-deadline' ? 'turn-deadline' : 'user';
134
139
  break;
135
140
  }
136
141
  continue;
@@ -18,6 +18,8 @@ import type { TextInputSuggestion } from '../../ui/components/TextInput.js';
18
18
  export declare const PROVIDER_CHOICES: {
19
19
  readonly addProvider: "add provider";
20
20
  readonly custom: "custom";
21
+ /** Skip provider setup and start chatting (UX-06). */
22
+ readonly later: "later";
21
23
  };
22
24
  export declare const PROVIDER_ACTIONS: {
23
25
  readonly useProvider: "use provider";
@@ -24,6 +24,8 @@ import { sessionActionSuggestions, sessionSuggestions } from './sessionPicker.js
24
24
  export const PROVIDER_CHOICES = {
25
25
  addProvider: 'add provider',
26
26
  custom: 'custom',
27
+ /** Skip provider setup and start chatting (UX-06). */
28
+ later: 'later',
27
29
  };
28
30
  export const PROVIDER_ACTIONS = {
29
31
  useProvider: 'use provider',
@@ -173,6 +175,7 @@ export function providerSuggestions(settings) {
173
175
  kind: 'provider',
174
176
  })),
175
177
  { value: PROVIDER_CHOICES.addProvider, description: 'Add a new provider (presets available)', kind: 'provider' },
178
+ { value: PROVIDER_CHOICES.later, description: 'Skip for now and start chatting; run /provider any time', kind: 'provider' },
176
179
  ];
177
180
  }
178
181
  export function providerActionSuggestions(settings, selectedProviderName) {
package/dist/cli/index.js CHANGED
@@ -22,8 +22,9 @@ program
22
22
  .addOption(new Option('--resume <id>', 'resume an exact saved session id for this workspace').conflicts(['continue', 'session']))
23
23
  .option('--no-session', 'run without saving or resuming a durable session')
24
24
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
25
+ .option('--print <text>', 'alias of --prompt: run one non-interactive turn and print the result')
25
26
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
26
- .addOption(new Option('--reasoning <level>', 'print-mode reasoning effort for this run only — none, minimal, low, medium, high, xhigh, max, or unset (no parameter sent; provider default)').choices(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'unset', 'off']))
27
+ .addOption(new Option('--reasoning <level>', 'print-mode reasoning effort for this run only — none, minimal, low, medium, high, xhigh, max, or unset (off = none; unset sends no parameter, provider default)').choices(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'unset', 'off']))
27
28
  .addOption(new Option('--output <format>', 'print-mode output: plain text, a single JSON result envelope, or a stream-json NDJSON event stream').choices(['text', 'json', 'stream-json']).default('text'))
28
29
  .option('--timeout <duration>', 'print-mode absolute turn deadline (e.g. 30s, 10m, 2h); bounds total elapsed time so a busy tool cannot run indefinitely')
29
30
  .option('--until-done', 'print mode: relaunch the goal after transient model failures (with backoff) until it structurally completes, the --timeout deadline hits, or repeated relaunches make no progress');
@@ -43,7 +44,7 @@ Examples:
43
44
  Print mode (-p):
44
45
  Runs a single agentic turn with the full toolset and guardrails, prints the final assistant
45
46
  text, then exits (0 = complete; non-zero = aborted/failed, so CI can gate on the exit code).
46
- The prompt comes from -p, otherwise from piped stdin. Piped prompts over 256 KiB are rejected;
47
+ The prompt comes from -p/--prompt (--print is an alias), otherwise from piped stdin. Piped prompts over 256 KiB are rejected;
47
48
  pass a file path and ask haze to read it instead. With --output json the reply is wrapped in a
48
49
  single-line { type, status, result, usage } envelope. With --output stream-json haze streams
49
50
  one NDJSON agent event per line (turn_start, step_*, message_*, tool_*, retry, turn_end) as the
@@ -52,7 +53,7 @@ Print mode (-p):
52
53
  detection without raw tool inputs or outputs. --model overrides the model for this
53
54
  run only (no settings change) and must already be registered under a provider (add it once via
54
55
  the /provider picker). --reasoning overrides the reasoning effort for this run only (levels
55
- none–max; unset sends no reasoning parameter, provider default). Print-mode runs are non-durable: --continue is ignored and no session is
56
+ none–max, off = none; unset sends no reasoning parameter, provider default). Print-mode runs are non-durable: --continue is ignored and no session is
56
57
  saved. --resume <id> loads saved context for the turn without changing that session. On a
57
58
  provider context overflow, haze compacts the conversation and retries at a progressively smaller
58
59
  message budget (up to twice); exhausted retries pause with a context_exhausted checkpoint, and
@@ -141,12 +142,15 @@ program.action(async () => {
141
142
  // Name the terminal tab for the run; no-op unless stdout is a real TTY.
142
143
  installTerminalTitle(terminalTitleLabel(process.cwd()));
143
144
  // -p takes precedence; otherwise fall back to piped stdin. An empty stdin yields no prompt.
144
- const prompt = opts.prompt?.trim() ? opts.prompt : await readStdinPrompt();
145
+ const promptOption = opts.prompt ?? opts.print;
146
+ const prompt = promptOption?.trim() ? promptOption : await readStdinPrompt();
145
147
  if (opts.resume && !await findSession(opts.resume)) {
146
148
  throw new Error(`No session named ${opts.resume} exists for this workspace.`);
147
149
  }
148
150
  if (prompt) {
149
151
  // One-shot runs are always fresh and non-durable; --continue is ignored in this mode.
152
+ if (opts.continue)
153
+ process.stderr.write('haze: --continue is ignored in print mode (one-shot runs are non-durable).\n');
150
154
  const { runHeadless } = await import('./commands/runCommand.js');
151
155
  const code = await runHeadless({
152
156
  prompt,
@@ -7,7 +7,8 @@ import { basename } from 'node:path';
7
7
  * naming instead of showing a stale haze title.
8
8
  */
9
9
  function titleEscape(label) {
10
- return `\u001B]0;${label}\u0007`;
10
+ // Emit both BEL- and ST-terminated forms: some terminals only honor one (FE-12).
11
+ return `\u001B]0;${label}\u0007\u001B]0;${label}\u001B\\`;
11
12
  }
12
13
  export function terminalTitleLabel(cwd) {
13
14
  // eslint-disable-next-line no-control-regex -- stripping control characters is the point here.
@@ -22,7 +23,7 @@ export function installTerminalTitle(label) {
22
23
  if (!process.stdout.isTTY)
23
24
  return;
24
25
  process.stdout.write(titleEscape(label));
25
- process.once('exit', () => {
26
+ const restore = () => {
26
27
  // Re-check at exit time: the terminal may no longer be attached.
27
28
  if (!process.stdout.isTTY)
28
29
  return;
@@ -32,5 +33,10 @@ export function installTerminalTitle(label) {
32
33
  catch {
33
34
  // Best effort only: title restoration must never break shutdown.
34
35
  }
35
- });
36
+ };
37
+ process.once('exit', restore);
38
+ // FE-12: 'exit' alone misses fatal paths that keep the loop alive or bail
39
+ // before the normal handler chain; restore on the monitor hooks too.
40
+ process.on('uncaughtExceptionMonitor', restore);
41
+ process.on('unhandledRejection', restore);
36
42
  }