@denizokcu/haze 1.7.12 → 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 (178) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +30 -6
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +47 -19
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/BusyBar.d.ts +1 -2
  7. package/dist/cli/chat/ChatHeader.d.ts +6 -0
  8. package/dist/cli/chat/ChatHeader.js +11 -0
  9. package/dist/cli/chat/ChatScreen.d.ts +16 -0
  10. package/dist/cli/chat/ChatScreen.js +399 -0
  11. package/dist/cli/chat/ChatScreenView.d.ts +68 -0
  12. package/dist/cli/chat/ChatScreenView.js +47 -0
  13. package/dist/cli/chat/LiveTail.d.ts +11 -0
  14. package/dist/cli/chat/LiveTail.js +26 -0
  15. package/dist/cli/chat/TaskBar.d.ts +3 -2
  16. package/dist/cli/chat/TaskBar.js +4 -0
  17. package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
  18. package/dist/cli/chat/agentTurnRunner.js +177 -0
  19. package/dist/cli/chat/busyIndicator.js +9 -5
  20. package/dist/cli/chat/chatMetrics.d.ts +7 -0
  21. package/dist/cli/chat/chatMetrics.js +15 -1
  22. package/dist/cli/chat/chatViewModel.d.ts +85 -0
  23. package/dist/cli/chat/chatViewModel.js +66 -0
  24. package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
  25. package/dist/cli/chat/fileMentionSuggestions.js +4 -21
  26. package/dist/cli/chat/liveTheme.d.ts +11 -0
  27. package/dist/cli/chat/liveTheme.js +26 -0
  28. package/dist/cli/chat/messageFinalize.d.ts +4 -0
  29. package/dist/cli/chat/messageFinalize.js +8 -0
  30. package/dist/cli/chat/messages.js +1 -1
  31. package/dist/cli/chat/pickerOpeners.d.ts +23 -0
  32. package/dist/cli/chat/pickerOpeners.js +36 -0
  33. package/dist/cli/chat/promptSessionState.d.ts +11 -0
  34. package/dist/cli/chat/promptSessionState.js +39 -0
  35. package/dist/cli/chat/renderMetrics.d.ts +8 -0
  36. package/dist/cli/chat/renderMetrics.js +14 -0
  37. package/dist/cli/chat/resizeGuard.d.ts +11 -0
  38. package/dist/cli/chat/resizeGuard.js +25 -0
  39. package/dist/cli/chat/screenDeps.d.ts +116 -0
  40. package/dist/cli/chat/screenDeps.js +1 -0
  41. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  42. package/dist/cli/chat/sessionLifecycle.js +4 -1
  43. package/dist/cli/chat/settingsSelection.d.ts +33 -0
  44. package/dist/cli/chat/settingsSelection.js +46 -0
  45. package/dist/cli/chat/skillNotices.d.ts +18 -0
  46. package/dist/cli/chat/skillNotices.js +26 -0
  47. package/dist/cli/chat/startupInfo.js +1 -1
  48. package/dist/cli/chat/submitPipeline.d.ts +8 -0
  49. package/dist/cli/chat/submitPipeline.js +141 -0
  50. package/dist/cli/chat/terminalControl.js +1 -1
  51. package/dist/cli/chat/toolSummaries.d.ts +29 -0
  52. package/dist/cli/chat/toolSummaries.js +268 -0
  53. package/dist/cli/chat/turnState.d.ts +8 -0
  54. package/dist/cli/chat/turnState.js +1 -0
  55. package/dist/cli/chat/userCommandFlow.d.ts +21 -0
  56. package/dist/cli/chat/userCommandFlow.js +66 -0
  57. package/dist/cli/chat/userCommandRunner.d.ts +14 -0
  58. package/dist/cli/chat/userCommandRunner.js +56 -0
  59. package/dist/cli/chat/wizard/providerHandlers.js +19 -2
  60. package/dist/cli/chat/wizardTrail.d.ts +22 -0
  61. package/dist/cli/chat/wizardTrail.js +55 -0
  62. package/dist/cli/commands/chat.d.ts +1 -13
  63. package/dist/cli/commands/chat.js +10 -798
  64. package/dist/cli/commands/commandHelp.js +7 -5
  65. package/dist/cli/commands/commandSuggest.d.ts +2 -0
  66. package/dist/cli/commands/commandSuggest.js +35 -0
  67. package/dist/cli/commands/commands.js +10 -3
  68. package/dist/cli/commands/formatters.d.ts +1 -23
  69. package/dist/cli/commands/formatters.js +3 -252
  70. package/dist/cli/commands/modelCommand.js +11 -7
  71. package/dist/cli/commands/reasoningCommand.js +3 -3
  72. package/dist/cli/commands/runCommand.js +6 -2
  73. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  74. package/dist/cli/commands/streaming/attemptOutcome.js +7 -2
  75. package/dist/cli/commands/streaming/attemptSetup.d.ts +1 -0
  76. package/dist/cli/commands/streaming/attemptSetup.js +26 -2
  77. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
  78. package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
  79. package/dist/cli/commands/streaming/stepProjection.js +54 -0
  80. package/dist/cli/commands/streaming/streamLoop.js +31 -23
  81. package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
  82. package/dist/cli/commands/streaming/toolPartHandlers.js +1 -1
  83. package/dist/cli/commands/streaming.d.ts +3 -1
  84. package/dist/cli/commands/wizardFlow.d.ts +2 -0
  85. package/dist/cli/commands/wizardFlow.js +3 -0
  86. package/dist/cli/index.js +8 -4
  87. package/dist/cli/terminalTitle.js +9 -3
  88. package/dist/config/contextFiles.d.ts +2 -5
  89. package/dist/config/contextFiles.js +1 -1
  90. package/dist/config/inputHistory.js +2 -2
  91. package/dist/config/providerAuth.js +2 -2
  92. package/dist/config/providerModelFacts.js +5 -0
  93. package/dist/config/providerPresets.js +1 -1
  94. package/dist/config/settings.d.ts +7 -0
  95. package/dist/config/settings.js +9 -2
  96. package/dist/config/updateCheck.js +2 -2
  97. package/dist/core/agent/completionController.d.ts +1 -1
  98. package/dist/core/agent/contextBudget.d.ts +1 -1
  99. package/dist/core/agent/goalPolicy.js +8 -2
  100. package/dist/core/agent/overflow.js +5 -0
  101. package/dist/core/agent/toolCapabilities.js +14 -0
  102. package/dist/core/agent/userCommands.d.ts +53 -0
  103. package/dist/core/agent/userCommands.js +116 -0
  104. package/dist/core/agent/workState.d.ts +3 -1
  105. package/dist/core/agent/workState.js +57 -26
  106. package/dist/core/contextFileTypes.d.ts +12 -0
  107. package/dist/core/contextFileTypes.js +1 -0
  108. package/dist/core/graph/buildGraph.js +1 -1
  109. package/dist/core/graph/store.js +1 -1
  110. package/dist/core/limits.d.ts +2 -0
  111. package/dist/core/limits.js +2 -0
  112. package/dist/core/log/llmLog.js +2 -2
  113. package/dist/{config → core/persistence}/privateStorage.js +1 -1
  114. package/dist/core/process/runBoundedProcess.d.ts +7 -4
  115. package/dist/core/process/runBoundedProcess.js +10 -5
  116. package/dist/core/safety/redaction.d.ts +2 -0
  117. package/dist/core/safety/redaction.js +26 -5
  118. package/dist/core/safety/secretPaths.js +12 -3
  119. package/dist/core/safety/urlGuard.js +2 -0
  120. package/dist/core/session/sessionStore.d.ts +8 -1
  121. package/dist/core/session/sessionStore.js +15 -4
  122. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  123. package/dist/core/shellOutput/types.d.ts +1 -1
  124. package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
  125. package/dist/core/validation/outputParser.d.ts +1 -1
  126. package/dist/llm/hazeTools.js +2 -0
  127. package/dist/llm/lsp/pool.js +1 -1
  128. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  129. package/dist/llm/requestContext.d.ts +3 -0
  130. package/dist/llm/requestContext.js +20 -8
  131. package/dist/llm/systemPrompt.js +10 -3
  132. package/dist/llm/toolGroups.d.ts +534 -0
  133. package/dist/llm/toolGroups.js +57 -0
  134. package/dist/llm/tools/editMatch.d.ts +1 -1
  135. package/dist/llm/tools/failures.d.ts +1 -1
  136. package/dist/llm/tools/fileToolShared.d.ts +1 -1
  137. package/dist/llm/tools/fileToolShared.js +1 -1
  138. package/dist/llm/tools/fileTools.js +1 -1
  139. package/dist/llm/tools/gitTools.d.ts +12 -0
  140. package/dist/llm/tools/gitTools.js +527 -0
  141. package/dist/llm/tools/readRecovery.d.ts +1 -1
  142. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  143. package/dist/llm/tools/replaceInFiles.js +1 -1
  144. package/dist/llm/tools/taskTool.js +4 -1
  145. package/dist/llm/tools/toolContext.js +5 -2
  146. package/dist/llm/tools/toolContextState.d.ts +1 -1
  147. package/dist/llm/tools/workspaceFile.d.ts +2 -2
  148. package/dist/llm/tools/workspaceFile.js +10 -5
  149. package/dist/skills/SkillRegistry.js +1 -1
  150. package/dist/skills/builder/SkillBuilder.js +1 -1
  151. package/dist/skills/plugins/installer.js +1 -1
  152. package/dist/skills/plugins/runtime.js +1 -1
  153. package/dist/ui/components/MarkdownText.d.ts +14 -0
  154. package/dist/ui/components/MarkdownText.js +77 -12
  155. package/dist/ui/components/NativeIndicators.js +5 -1
  156. package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
  157. package/dist/ui/components/StreamingMarkdownText.js +39 -11
  158. package/dist/ui/components/TextInput.d.ts +1 -2
  159. package/dist/ui/components/TextInput.js +79 -9
  160. package/dist/ui/components/WizardChoices.d.ts +1 -2
  161. package/dist/ui/components/useInputSuggestions.d.ts +1 -1
  162. package/dist/ui/components/useInputSuggestions.js +1 -1
  163. package/dist/ui/mentionDetection.d.ts +20 -0
  164. package/dist/ui/mentionDetection.js +24 -0
  165. package/dist/ui/terminalColors.d.ts +4 -4
  166. package/dist/ui/terminalColors.js +23 -6
  167. package/dist/ui/terminalSanitize.js +8 -3
  168. package/dist/ui/textGeometry.d.ts +2 -0
  169. package/dist/ui/textGeometry.js +6 -0
  170. package/dist/ui/themes/registry.js +33 -33
  171. package/dist/utils/openPath.js +7 -0
  172. package/package.json +13 -13
  173. /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
  174. /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
  175. /package/dist/{config → core}/paths.d.ts +0 -0
  176. /package/dist/{config → core}/paths.js +0 -0
  177. /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
  178. /package/dist/{llm → core}/toolResultTypes.js +0 -0
@@ -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
+ }
@@ -10,13 +10,14 @@ import { isLengthStopOverflow, isSilentContextOverflow } from '../../../core/age
10
10
  import { isValidationRerunToolCall } from '../../../core/agent/turnPolicy.js';
11
11
  import { COMPACTION_LLM_MAX_OUTPUT_TOKENS, COMPACTION_LLM_MIN_OLDER_TOKENS } from '../../../core/agent/budgets.js';
12
12
  import { toolsContextFor } from '../../../llm/tools/toolContext.js';
13
- import { busyToolLabel, toolCallSummary } from '../formatters.js';
13
+ import { busyToolLabel, toolCallSummary } from '../../chat/toolSummaries.js';
14
14
  import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
15
15
  import { finalizeAssistantSegment, finalizePendingAssistantBeforeTool } from './assistantSegments.js';
16
16
  import { handleToolErrorPart, handleToolResultPart } from './toolPartHandlers.js';
17
17
  import { createPrepareStep, createRepairToolCall } from './prepareStep.js';
18
18
  import { applyStepToolResultState, initialToolResultState } from './toolResultState.js';
19
- import { extractUsage, logEntry, stepCacheMetrics } from './turnRuntime.js';
19
+ import { extractUsage, logEntry } from './turnRuntime.js';
20
+ import { projectStepEnd } from './stepProjection.js';
20
21
  export function createAttemptLoopState(previousAssistantText, contextFiles, callbacks) {
21
22
  const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
22
23
  return {
@@ -204,6 +205,7 @@ async function commitStreamResult(deps, result) {
204
205
  */
205
206
  async function runAgentEpoch(deps, requestMessages) {
206
207
  const { setup, callbacks, loopState, turnState, globalBudget, stallGuard, salvage, retryAttempt, abortController } = deps;
208
+ const toolsActivated = setup.activateToolGroups?.() ?? false;
207
209
  const { sliceTools, systemPrompt, inputBreakdown, providerSettings, omitMaxOutputTokens, toolExecutionContext } = setup;
208
210
  const prepare = createPrepareStep(deps);
209
211
  const completedBefore = loopState.completedSteps;
@@ -239,7 +241,7 @@ async function runAgentEpoch(deps, requestMessages) {
239
241
  if (completedBefore > 0) {
240
242
  const messagesPreserved = requestMessages.length <= preparedMessages.length
241
243
  && requestMessages.every((message, index) => preparedMessages[index] === message);
242
- const requestPolicyStable = prepared?.activeTools == null
244
+ const requestPolicyStable = !toolsActivated && prepared?.activeTools == null
243
245
  && prepared?.toolChoice == null
244
246
  && prepared?.model == null
245
247
  && prepared?.providerOptions == null;
@@ -263,35 +265,41 @@ async function runAgentEpoch(deps, requestMessages) {
263
265
  // Tool-loop control must advance from this internally ordered callback.
264
266
  loopState.toolResultState = applyStepToolResultState(loopState.toolResultState, content);
265
267
  recordCompletedStep(loopState, { text, toolCalls });
266
- // Remember the last valid per-step usage for usage-overflow detection
267
- // (Pillar 1.2); empty usage objects (some gateways/tests) keep the
268
- // previous value or stay unset.
269
- const stepUsage = stepCacheMetrics(usage);
270
- if (stepUsage.inputTokens != null || usage?.outputTokens != null || stepUsage.cacheReadTokens > 0 || stepUsage.cacheWriteTokens > 0) {
271
- loopState.lastUsage = { inputTokens: stepUsage.inputTokens, outputTokens: usage?.outputTokens ?? 0, cacheReadTokens: stepUsage.cacheReadTokens, cacheWriteTokens: stepUsage.cacheWriteTokens };
272
- }
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;
273
285
  // Turn-wide counters remain shared across bounded SDK epochs, retries,
274
286
  // and recovery slices. Executions are authoritative for tool-call usage.
275
- turnState.stepsUsed += 1;
276
- turnState.toolCallsUsed = globalBudget.started;
277
- if (toolCalls.length > 0 && text.trim().length === 0)
287
+ turnState.stepsUsed = projection.stepsUsed;
288
+ turnState.toolCallsUsed = projection.toolCallsUsed;
289
+ if (projection.toolOnlyStep)
278
290
  turnState.toolOnlyStepsUsed += 1;
279
291
  if (Array.isArray(response?.messages) && response.messages.length > 0)
280
292
  salvage.accumulated = response.messages;
281
- const publicUsage = {
282
- inputTokens: stepUsage.inputTokens ?? 0,
283
- outputTokens: usage?.outputTokens ?? 0,
284
- cacheReadTokens: stepUsage.cacheReadTokens,
285
- cacheWriteTokens: stepUsage.cacheWriteTokens,
286
- reasoningTokens: stepUsage.reasoningTokens,
287
- };
288
- callbacks.onEvent?.(agentEvent({ type: 'step_end', attempt: retryAttempt + 1, step: loopState.completedSteps, finishReason, toolCallCount: toolCalls.length, usage: publicUsage, ...(response?.modelId ? { responseModel: response.modelId } : {}) }));
289
- 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 } });
290
- 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);
291
296
  },
292
297
  onEnd(event) {
293
298
  const providerUsage = extractUsage({ usage: event.usage });
294
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);
295
303
  callbacks.recordTokenUsage?.({
296
304
  inputTokens: providerUsage.inputTokens,
297
305
  outputTokens: providerUsage.outputTokens,
@@ -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';
@@ -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;
@@ -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
  }
@@ -1,9 +1,6 @@
1
1
  import type { ModelMessage } from 'ai';
2
- export interface ContextFile {
3
- path: string;
4
- content: string;
5
- signature?: string;
6
- }
2
+ import type { ContextFile } from '../core/contextFileTypes.js';
3
+ export type { ContextFile };
7
4
  export interface ReadContextFileOptions {
8
5
  onContextFileRead?: (path: string) => void;
9
6
  alreadyLoadedSignatures?: ReadonlyMap<string, string>;
@@ -3,7 +3,7 @@ import { pathExists } from '../utils/fs.js';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import crypto from 'node:crypto';
6
- import { HAZE_DIR } from './paths.js';
6
+ import { HAZE_DIR } from '../core/paths.js';
7
7
  import { readUtf8Prefix } from '../core/io/boundedRead.js';
8
8
  import { assertRealPathInsideRoot } from '../utils/path.js';
9
9
  import { escapeEnvelopeClosers } from '../core/safety/untrustedEnvelopes.js';
@@ -1,7 +1,7 @@
1
1
  import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
- import { HAZE_DIR } from './paths.js';
4
- import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
3
+ import { HAZE_DIR } from '../core/paths.js';
4
+ import { tightenPrivateFile, writePrivateJsonAtomic } from '../core/persistence/privateStorage.js';
5
5
  const HISTORY_DIR = path.join(HAZE_DIR, 'history');
6
6
  const INPUT_HISTORY_FILE = path.join(HISTORY_DIR, 'input-history.json');
7
7
  const MAX_HISTORY_ITEMS = 500;
@@ -1,8 +1,8 @@
1
1
  import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
- import { HAZE_DIR } from './paths.js';
5
- import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
4
+ import { HAZE_DIR } from '../core/paths.js';
5
+ import { tightenPrivateFile, writePrivateJsonAtomic } from '../core/persistence/privateStorage.js';
6
6
  export const PROVIDER_AUTH_FILE = path.join(HAZE_DIR, 'auth.json');
7
7
  const oauthProviderAuthSchema = z.object({
8
8
  type: z.literal('oauth'),
@@ -47,6 +47,7 @@ const ENDPOINT_MODEL_LIMITS = {
47
47
  'glm-5.3-flash': [1_000_000, 131_072],
48
48
  },
49
49
  'https://api.z.ai/api/coding/paas/v4': {
50
+ 'glm-5.4': [1_000_000, 131_072],
50
51
  'glm-5.3': [1_000_000, 131_072],
51
52
  'glm-5.2-highspeed': [1_000_000, 131_072],
52
53
  },
@@ -126,6 +127,9 @@ function documentedReasoningLevels(url, model) {
126
127
  }
127
128
  if ((host === 'api.x.ai' || host.endsWith('.api.x.ai')) && /^grok-4\.[67]$/i.test(model))
128
129
  return ['low', 'medium', 'high', 'xhigh'];
130
+ // GLM-5.4 always thinks (disabled maps to low) and defaults to max when the parameter is omitted.
131
+ if (host === 'api.z.ai' && /^glm-5\.4$/i.test(model))
132
+ return ['low', 'high', 'max'];
129
133
  // The coding subscription and direct API have always-thinking K3 variants;
130
134
  // use the shared subset instead of sending unsupported none to workers.
131
135
  if ((host === 'api.moonshot.ai' && /^kimi-k3(?:\.1-pro)?$/i.test(model))
@@ -196,6 +200,7 @@ const MODEL_CATALOG = [
196
200
  { match: 'qwen', contextWindowTokens: 131_072, maxOutputTokens: 8_192 },
197
201
  { match: 'kimi-k3', contextWindowTokens: 1_048_576, maxOutputTokens: 131_072, note: 'smaller gateway output cap' },
198
202
  { match: 'kimi-k2', contextWindowTokens: 131_072, maxOutputTokens: 32_768, note: 'input-safe half of the 256K total' },
203
+ { match: 'glm-5.4', contextWindowTokens: 1_000_000, maxOutputTokens: 131_072 },
199
204
  { match: 'glm-5.3', contextWindowTokens: 1_000_000, maxOutputTokens: 131_072 },
200
205
  { match: 'glm-5.2', contextWindowTokens: 262_144, maxOutputTokens: 131_072, note: 'smaller Hugging Face window' },
201
206
  { match: 'glm-5.1', contextWindowTokens: 200_000, maxOutputTokens: 131_072 },
@@ -34,7 +34,7 @@ const PRESET_DEFINITIONS = [
34
34
  'glm-5.3', 'glm-5.3-flash',
35
35
  ] },
36
36
  { id: 'z-ai-coding', name: 'Z.ai (Coding Plan)', baseUrl: 'https://api.z.ai/api/coding/paas/v4/', apiKeyEnvVar: 'ZAI_API_KEY', category: 'cloud', models: [
37
- 'glm-5.3', 'glm-5.2-highspeed',
37
+ 'glm-5.4', 'glm-5.3', 'glm-5.2-highspeed',
38
38
  ] },
39
39
  { id: 'moonshot', name: 'Moonshot AI (Kimi API)', baseUrl: 'https://api.moonshot.ai/v1', apiKeyEnvVar: 'MOONSHOT_API_KEY', category: 'cloud', models: [
40
40
  'kimi-k3.1-pro', 'kimi-k3',
@@ -180,6 +180,13 @@ export interface HazeSettings {
180
180
  export declare const SETTINGS_FILE: string;
181
181
  export declare function readSettings(): Promise<HazeSettings>;
182
182
  export declare function writeSettings(settings: HazeSettings): Promise<void>;
183
+ /**
184
+ * Shallow merge: a patch key replaces the whole stored value (BE-07) — a
185
+ * patch containing `providers` replaces the entire array. To change one
186
+ * provider, use `upsertProvider(settings, provider)` from `providers.ts`
187
+ * (which the `/provider` wizard already does) instead of passing a
188
+ * reconstructed array.
189
+ */
183
190
  export declare function updateSettings(patch: HazeSettings): Promise<HazeSettings>;
184
191
  /** Patch subagent settings without dropping unknown nested/profile fields. */
185
192
  export declare function updateSubagentSettings(patch: HazeSubagentSettings): Promise<HazeSettings>;
@@ -1,8 +1,8 @@
1
1
  import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
- import { HAZE_DIR } from './paths.js';
5
- import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
4
+ import { HAZE_DIR } from '../core/paths.js';
5
+ import { tightenPrivateFile, writePrivateJsonAtomic } from '../core/persistence/privateStorage.js';
6
6
  import { customProfileSchema } from '../core/subagent/executionProfiles.js';
7
7
  import { REASONING_LEVELS, REASONING_PROVIDER_DEFAULT } from '../core/agent/reasoningPolicy.js';
8
8
  /**
@@ -117,6 +117,13 @@ export async function writeSettings(settings) {
117
117
  const parsed = settingsSchema.parse(settings);
118
118
  await writePrivateJsonAtomic(SETTINGS_FILE, parsed);
119
119
  }
120
+ /**
121
+ * Shallow merge: a patch key replaces the whole stored value (BE-07) — a
122
+ * patch containing `providers` replaces the entire array. To change one
123
+ * provider, use `upsertProvider(settings, provider)` from `providers.ts`
124
+ * (which the `/provider` wizard already does) instead of passing a
125
+ * reconstructed array.
126
+ */
120
127
  export async function updateSettings(patch) {
121
128
  const next = { ...await readSettings(), ...patch };
122
129
  await writeSettings(next);
@@ -2,9 +2,9 @@ import { execFile as execFileCallback } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import { pathExists, readJson } from '../utils/fs.js';
4
4
  import path from 'node:path';
5
- import { HAZE_DIR } from './paths.js';
5
+ import { HAZE_DIR } from '../core/paths.js';
6
6
  import { isNewer } from '../utils/version.js';
7
- import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
7
+ import { tightenPrivateFile, writePrivateJsonAtomic } from '../core/persistence/privateStorage.js';
8
8
  const execFile = promisify(execFileCallback);
9
9
  const UPDATE_CHECK_FILE = path.join(HAZE_DIR, 'updateCheck.json');
10
10
  const DEFAULT_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24h
@@ -1,4 +1,4 @@
1
- import type { ValidationKind } from '../../llm/toolResultTypes.js';
1
+ import type { ValidationKind } from '../../core/toolResultTypes.js';
2
2
  import { type TurnBudget } from './budgets.js';
3
3
  import { type ValidationOutcome, type WorkTaskProgress } from './workState.js';
4
4
  import type { RequestIntent } from './goalPolicy.js';
@@ -1,5 +1,5 @@
1
1
  import type { ModelMessage } from 'ai';
2
- import type { ContextFile } from '../../config/contextFiles.js';
2
+ import type { ContextFile } from '../contextFileTypes.js';
3
3
  /**
4
4
  * Conservative fallback context window for a hosted model with no metadata
5
5
  * (RH-005). 128K is the floor for current capable hosted models (GPT-4o class,
@@ -147,9 +147,15 @@ export function goalContinuationPrompt(reason, taskCounts, detail) {
147
147
  const taskLine = taskCounts
148
148
  ? ` The task list currently shows ${taskCounts.pending + taskCounts.inProgress} open item${taskCounts.pending + taskCounts.inProgress === 1 ? '' : 's'} of ${taskCounts.total}; update writeTasks as you complete them.`
149
149
  : '';
150
- const validationLine = reason.includes('validation')
150
+ const unresolved = reason.includes('failed and remains unresolved');
151
+ const validationLine = reason.includes('validation') && !unresolved
151
152
  ? ' No recognized post-edit validation was recorded. Run one standard test/build command, directly execute the changed artifact as one unchained command, or call shell with purpose=validation for a custom assertion check.'
152
153
  : '';
154
+ // Observed 2026-11: a bare "validation failed" notice let models re-answer
155
+ // with prose (or rerun other kinds) while the actual red check stayed open.
156
+ const unresolvedLine = unresolved
157
+ ? ` Checks did run and one still fails: rerun the failed check${detail ? 's named below' : ' from this goal\'s earlier run (its command is in the conversation above)'} until it exits green; a passing check of another kind does not close it.`
158
+ : '';
153
159
  const ledgerLine = reason.includes('outcome list')
154
160
  ? ' First call writeTasks with the concrete user-visible outcomes and their checks; keep the list until each outcome is complete.'
155
161
  : '';
@@ -157,5 +163,5 @@ export function goalContinuationPrompt(reason, taskCounts, detail) {
157
163
  ? ' Rerun the same validation command that failed before the edit and resolve it; a different check does not close the captured red evidence.'
158
164
  : '';
159
165
  const detailLine = detail ? ` ${detail}` : '';
160
- return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine}${ledgerLine}${redLine}${detailLine} The user's original request defines the scope in any language. A task list cannot authorize work beyond that request; revise out-of-scope tasks rather than carrying them out. Resume the next authorized unfinished task.${taskLine} Update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
166
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine}${unresolvedLine}${ledgerLine}${redLine}${detailLine} The user's original request defines the scope in any language. A task list cannot authorize work beyond that request; revise out-of-scope tasks rather than carrying them out. Resume the next authorized unfinished task.${taskLine} Update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
161
167
  }
@@ -53,6 +53,11 @@ const NON_OVERFLOW_PATTERNS = [
53
53
  /^(?:throttling|service unavailable)/i, // AWS Bedrock throttling/unavailable prefixes (raw ThrottlingException and formatted variants)
54
54
  /rate limit/i,
55
55
  /too many requests/i,
56
+ // Output-cap errors look like "too many tokens"/"token limit exceeded" but
57
+ // are NOT context overflow — compacting would not help (BE-05).
58
+ /max[_ ]?(?:output|completion)[_ ]?tokens?/i,
59
+ /max_tokens/i,
60
+ /maximum (?:output|completion) tokens?/i,
56
61
  ];
57
62
  /** Does an error text indicate a provider context-window overflow? */
58
63
  export function errorIndicatesContextOverflow(text) {
@@ -25,6 +25,20 @@ const CAPABILITY_MAP = {
25
25
  replaceInFiles: ['mutate'],
26
26
  lspRenameSymbol: ['mutate'],
27
27
  lspSafeDeleteSymbol: ['mutate'],
28
+ // Git mutation tools.
29
+ gitFetch: ['mutate'],
30
+ gitPull: ['mutate'],
31
+ gitClone: ['mutate'],
32
+ gitStage: ['mutate'],
33
+ gitCommit: ['mutate'],
34
+ gitBranchManage: ['mutate'],
35
+ gitRebase: ['mutate'],
36
+ gitReset: ['mutate'],
37
+ // Git read-only queries.
38
+ gitStatus: ['read'],
39
+ gitLog: ['read'],
40
+ gitDiff: ['read'],
41
+ gitBranch: ['read'],
28
42
  // Process execution. A shell call becomes validation only when its command is
29
43
  // a classifier-confirmed validation command (see work state); that runtime
30
44
  // fact is tracked separately as a validation event, not as a static trait.
@@ -0,0 +1,53 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import type { BoundedProcessResult } from '../process/runBoundedProcess.js';
3
+ import type { StreamReduction } from '../shellOutput/types.js';
4
+ /**
5
+ * User-run (`! <command>`) commands: a line starting with `!` runs directly,
6
+ * without a model request. Pure helpers only — parsing, status, the
7
+ * model-facing record, the request-time fold, and the transcript row. Effects
8
+ * live in `cli/chat/userCommandRunner.ts`.
9
+ */
10
+ export type ParsedInputLine = {
11
+ kind: 'command';
12
+ command: string;
13
+ } | {
14
+ kind: 'escaped';
15
+ value: string;
16
+ } | {
17
+ kind: 'none';
18
+ };
19
+ export type UserCommandStatus = 'completed' | 'failed' | 'timed_out' | 'cancelled' | 'error';
20
+ export interface UserCommandRun {
21
+ command: string;
22
+ status: UserCommandStatus;
23
+ exitCode: number | null;
24
+ durationMs: number;
25
+ stdout: StreamReduction;
26
+ stderr: StreamReduction;
27
+ error?: string;
28
+ }
29
+ /** Classify one submitted line: `! cmd` → command, `\\! text` → escaped message, else none. */
30
+ export declare function parseUserInputLine(value: string): ParsedInputLine;
31
+ /**
32
+ * One run status from runtime facts, first match wins: spawn error, abort,
33
+ * timeout, zero exit, anything else.
34
+ */
35
+ export declare function userCommandStatus(result: Pick<BoundedProcessResult, 'code' | 'timedOut' | 'aborted' | 'error'>): UserCommandStatus;
36
+ /**
37
+ * The model-facing record: one labelled envelope holding command, status and
38
+ * reduced output, with forged closers neutralized.
39
+ */
40
+ export declare function formatUserCommandRecord(run: UserCommandRun): string;
41
+ /** The turn that follows a user command: its record is folded into this request. */
42
+ export declare const USER_COMMAND_RESPONSE_REQUEST = "I just ran the command above in my terminal. React to its output.";
43
+ /**
44
+ * Fold the run of user-command records that immediately precede a new user
45
+ * turn into that turn's message, so the provider sees one user message. The
46
+ * input array is never mutated; without trailing records the result is just
47
+ * `[...messages, turn]`.
48
+ */
49
+ export declare function foldUserCommandRecords(messages: ModelMessage[], turn: ModelMessage): ModelMessage[];
50
+ /** Transcript row text: the command, its output, then one status line. */
51
+ export declare function userCommandTranscriptText(run: UserCommandRun): string;
52
+ /** First line of a command, bounded, for the busy label. */
53
+ export declare function userCommandHead(command: string): string;