@denizokcu/haze 0.8.0 → 0.10.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 (182) hide show
  1. package/CHANGELOG.md +67 -17
  2. package/README.md +121 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  14. package/dist/cli/chat/sessionRecorder.js +21 -8
  15. package/dist/cli/chat/startupInfo.d.ts +1 -0
  16. package/dist/cli/chat/startupInfo.js +11 -0
  17. package/dist/cli/chat/tips.d.ts +21 -0
  18. package/dist/cli/chat/tips.js +43 -0
  19. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  20. package/dist/cli/chat/wizardDispatch.js +645 -0
  21. package/dist/cli/commands/chat.d.ts +1 -0
  22. package/dist/cli/commands/chat.js +246 -779
  23. package/dist/cli/commands/chatModes.d.ts +1 -1
  24. package/dist/cli/commands/chatModes.js +7 -2
  25. package/dist/cli/commands/commandHelp.js +5 -3
  26. package/dist/cli/commands/commands.d.ts +4 -3
  27. package/dist/cli/commands/commands.js +12 -13
  28. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  29. package/dist/cli/commands/fleetCommand.js +46 -0
  30. package/dist/cli/commands/formatters.d.ts +5 -0
  31. package/dist/cli/commands/formatters.js +36 -9
  32. package/dist/cli/commands/logsCommand.js +8 -28
  33. package/dist/cli/commands/mcpWizard.js +24 -2
  34. package/dist/cli/commands/modelCommand.js +1 -1
  35. package/dist/cli/commands/providerWizard.d.ts +1 -0
  36. package/dist/cli/commands/providerWizard.js +31 -5
  37. package/dist/cli/commands/runCommand.d.ts +1 -0
  38. package/dist/cli/commands/runCommand.js +32 -20
  39. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  40. package/dist/cli/commands/sessionPicker.js +29 -0
  41. package/dist/cli/commands/settingsSummary.js +8 -4
  42. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  43. package/dist/cli/commands/skillWizard.d.ts +2 -0
  44. package/dist/cli/commands/skillWizard.js +16 -6
  45. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  46. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  47. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  48. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  49. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  50. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  51. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  52. package/dist/cli/commands/streaming.d.ts +13 -1
  53. package/dist/cli/commands/streaming.js +104 -44
  54. package/dist/cli/commands/wizardActions.d.ts +6 -0
  55. package/dist/cli/commands/wizardActions.js +6 -0
  56. package/dist/cli/commands/wizardPrompts.js +1 -1
  57. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  58. package/dist/cli/commands/wizardSuggestions.js +62 -13
  59. package/dist/cli/commands/wizardTransition.d.ts +37 -0
  60. package/dist/cli/commands/wizardTransition.js +43 -0
  61. package/dist/cli/index.js +17 -3
  62. package/dist/cli/terminalTitle.d.ts +6 -0
  63. package/dist/cli/terminalTitle.js +36 -0
  64. package/dist/config/contextFiles.js +6 -3
  65. package/dist/config/endpointSecurity.d.ts +2 -0
  66. package/dist/config/endpointSecurity.js +28 -0
  67. package/dist/config/inputHistory.d.ts +3 -3
  68. package/dist/config/inputHistory.js +13 -17
  69. package/dist/config/modelDiscovery.d.ts +20 -0
  70. package/dist/config/modelDiscovery.js +51 -0
  71. package/dist/config/privateStorage.d.ts +6 -0
  72. package/dist/config/privateStorage.js +61 -0
  73. package/dist/config/providerPresets.d.ts +16 -4
  74. package/dist/config/providerPresets.js +263 -34
  75. package/dist/config/providers.d.ts +2 -0
  76. package/dist/config/providers.js +7 -0
  77. package/dist/config/settings.d.ts +22 -0
  78. package/dist/config/settings.js +33 -5
  79. package/dist/config/skillSettings.d.ts +6 -13
  80. package/dist/config/skillSettings.js +20 -19
  81. package/dist/config/updateCheck.js +4 -2
  82. package/dist/core/agent/budgets.d.ts +26 -0
  83. package/dist/core/agent/budgets.js +34 -0
  84. package/dist/core/agent/compaction.js +17 -3
  85. package/dist/core/agent/contextBudget.d.ts +8 -0
  86. package/dist/core/agent/contextBudget.js +29 -0
  87. package/dist/core/agent/errors.js +6 -2
  88. package/dist/core/agent/events.d.ts +12 -0
  89. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  90. package/dist/core/agent/toolOutputStore.js +49 -11
  91. package/dist/core/agent/workState.d.ts +1 -1
  92. package/dist/core/agent/workState.js +0 -4
  93. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  94. package/dist/core/attachments/imageAttachments.js +245 -0
  95. package/dist/core/attachments/readBlessings.d.ts +37 -0
  96. package/dist/core/attachments/readBlessings.js +79 -0
  97. package/dist/core/goal/completionPolicy.d.ts +0 -28
  98. package/dist/core/goal/completionPolicy.js +0 -88
  99. package/dist/core/goal/requestClassifier.d.ts +0 -3
  100. package/dist/core/goal/requestClassifier.js +0 -13
  101. package/dist/core/io/boundedRead.d.ts +15 -0
  102. package/dist/core/io/boundedRead.js +144 -0
  103. package/dist/core/limits/byteBudgets.d.ts +18 -0
  104. package/dist/core/limits/byteBudgets.js +18 -0
  105. package/dist/core/limits/textBudgets.d.ts +23 -0
  106. package/dist/core/limits/textBudgets.js +23 -0
  107. package/dist/core/log/llmLog.d.ts +10 -0
  108. package/dist/core/log/llmLog.js +59 -13
  109. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  110. package/dist/core/persistence/orderedFileWriter.js +29 -0
  111. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  112. package/dist/core/process/backgroundRegistry.js +194 -0
  113. package/dist/core/process/runBoundedProcess.d.ts +30 -0
  114. package/dist/core/process/runBoundedProcess.js +116 -0
  115. package/dist/core/safety/urlGuard.d.ts +2 -1
  116. package/dist/core/safety/urlGuard.js +3 -2
  117. package/dist/core/session/sessionSlimming.js +47 -4
  118. package/dist/core/session/sessionStore.d.ts +37 -0
  119. package/dist/core/session/sessionStore.js +136 -27
  120. package/dist/core/subagent/contracts.d.ts +116 -0
  121. package/dist/core/subagent/contracts.js +54 -0
  122. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  123. package/dist/core/subagent/executionProfiles.js +45 -0
  124. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  125. package/dist/core/subagent/subagentCoordinator.js +134 -0
  126. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  127. package/dist/core/subagent/subagentRunner.js +228 -98
  128. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  129. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  130. package/dist/core/tasks/taskStorage.js +12 -1
  131. package/dist/llm/client.d.ts +20 -29
  132. package/dist/llm/client.js +33 -29
  133. package/dist/llm/hazeTools.d.ts +2396 -67
  134. package/dist/llm/hazeTools.js +50 -37
  135. package/dist/llm/lsp.d.ts +23 -3
  136. package/dist/llm/lsp.js +73 -16
  137. package/dist/llm/lspTools.d.ts +96 -48
  138. package/dist/llm/mcp.d.ts +1 -1
  139. package/dist/llm/mcp.js +65 -16
  140. package/dist/llm/requestContext.d.ts +23 -1
  141. package/dist/llm/requestContext.js +50 -7
  142. package/dist/llm/systemPrompt.d.ts +4 -1
  143. package/dist/llm/systemPrompt.js +14 -4
  144. package/dist/llm/toolResultTypes.d.ts +1 -1
  145. package/dist/llm/tools/bashTool.d.ts +1210 -16
  146. package/dist/llm/tools/bashTool.js +43 -60
  147. package/dist/llm/tools/fetchTool.d.ts +26 -26
  148. package/dist/llm/tools/fetchTool.js +1 -1
  149. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  150. package/dist/llm/tools/fileToolShared.js +5 -5
  151. package/dist/llm/tools/grepRunner.d.ts +20 -0
  152. package/dist/llm/tools/grepRunner.js +66 -0
  153. package/dist/llm/tools/outputCap.d.ts +2 -6
  154. package/dist/llm/tools/outputCap.js +2 -6
  155. package/dist/llm/tools/processTool.d.ts +1077 -0
  156. package/dist/llm/tools/processTool.js +41 -0
  157. package/dist/llm/tools/toolContext.d.ts +8 -0
  158. package/dist/llm/tools/toolContext.js +22 -11
  159. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  160. package/dist/llm/tools/workspaceFile.js +33 -4
  161. package/dist/llm/webFetch.js +24 -11
  162. package/dist/llm/workerContext.d.ts +18 -0
  163. package/dist/llm/workerContext.js +55 -0
  164. package/dist/skills/SkillLoader.d.ts +2 -2
  165. package/dist/skills/SkillLoader.js +17 -5
  166. package/dist/skills/SkillRegistry.d.ts +3 -2
  167. package/dist/skills/SkillRegistry.js +53 -10
  168. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  169. package/dist/skills/builder/SkillBuilder.js +23 -5
  170. package/dist/skills/skillTools.js +11 -4
  171. package/dist/skills/types.d.ts +11 -1
  172. package/dist/ui/components/TextInput.d.ts +5 -2
  173. package/dist/ui/components/TextInput.js +76 -8
  174. package/dist/utils/format.d.ts +2 -0
  175. package/dist/utils/format.js +8 -0
  176. package/dist/utils/fs.d.ts +0 -1
  177. package/dist/utils/fs.js +0 -4
  178. package/dist/utils/openPath.d.ts +2 -0
  179. package/dist/utils/openPath.js +9 -0
  180. package/dist/utils/path.d.ts +2 -0
  181. package/dist/utils/path.js +9 -4
  182. package/package.json +1 -1
@@ -4,10 +4,12 @@ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
4
4
  import { assembleRequestContext } from '../../llm/requestContext.js';
5
5
  import { projectContextSection } from '../../llm/systemPrompt.js';
6
6
  import { closeMcpClients } from '../../llm/mcp.js';
7
+ import { readSettings } from '../../config/settings.js';
7
8
  import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
8
9
  import { agentEvent } from '../../core/agent/events.js';
9
10
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
10
11
  import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
12
+ import { userTurnMessage } from '../../core/attachments/imageAttachments.js';
11
13
  import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
12
14
  import { estimateValueTokens } from '../../core/agent/contextBudget.js';
13
15
  import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
@@ -23,6 +25,9 @@ import { applyToolResultState, initialToolResultState, isMutatingToolName } from
23
25
  import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
24
26
  import { toolsContextFor } from '../../llm/tools/toolContext.js';
25
27
  import { modelThinkingLabel } from '../../utils/modelName.js';
28
+ import { terminalTurnStatus } from './streaming/turnOutcome.js';
29
+ import { createIdleTimer } from './streaming/idleTimer.js';
30
+ import { WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
26
31
  function logEntry(log, entry) {
27
32
  if (log)
28
33
  void logAppend(log, entry).catch(() => undefined);
@@ -34,32 +39,29 @@ function withScopedContextControl(messages, context) {
34
39
  context.pendingContextFiles = [];
35
40
  return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
36
41
  }
37
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
38
- const displayVal = displayValue ?? value;
39
- callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
40
- callbacks.setBusy(true);
42
+ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope) {
41
43
  let thinkingLabel = modelThinkingLabel(undefined);
42
44
  callbacks.setBusyLabel?.(thinkingLabel);
43
- if (!retryingExistingRequest)
44
- callbacks.addMessage({ role: 'user', text: displayVal });
45
- const abortController = new AbortController();
46
- callbacks.setAbortController?.(abortController);
47
45
  let turnStatus = 'failed';
48
- let idleTimer;
49
46
  let loadedMcp;
50
- const resetIdleTimer = () => {
51
- if (idleTimer)
52
- clearTimeout(idleTimer);
53
- idleTimer = setTimeout(() => {
54
- abortController.abort('haze turn timed out after no model/tool activity.');
55
- }, IDLE_TIMEOUT_MS);
56
- };
47
+ // Tool calls currently executing. A concurrent subagent wave can run for many
48
+ // minutes with no stream parts; that is activity, not a dead stream, so the
49
+ // idle timer defers while any tool is in flight (see streaming/idleTimer.ts).
50
+ const inFlightTools = new Set();
51
+ const idleTimer = createIdleTimer({
52
+ timeoutMs: IDLE_TIMEOUT_MS,
53
+ isBusy: () => inFlightTools.size > 0,
54
+ onTimeout: () => abortController.abort('haze turn timed out after no model/tool activity.'),
55
+ });
57
56
  const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
58
57
  try {
59
- const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
58
+ // Single choke point: one fresh settings read per turn, shared by model
59
+ // resolution and request assembly (CR-024).
60
+ const turnSettings = await readSettings();
61
+ const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
60
62
  if (!runtime?.model) {
61
63
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
62
- turnStatus = 'complete';
64
+ turnStatus = 'failed';
63
65
  return { status: turnStatus };
64
66
  }
65
67
  thinkingLabel = modelThinkingLabel(runtime.config.modelName);
@@ -67,7 +69,14 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
67
69
  let activeContextFiles = contextFiles;
68
70
  const activeModel = runtime.model;
69
71
  const providerSettings = providerRequestSettings(runtime.config);
70
- const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
72
+ const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, modelRuntime: runtime, subagentOverrides: turnOptions.subagentOverrides, abortSignal: abortController.signal, executionScope: turnScope.executionScope, settings: turnSettings, onSubagentEvent: event => callbacks.onEvent?.(agentEvent(event.type === 'queued'
73
+ ? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
74
+ : event.type === 'started'
75
+ ? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
76
+ : event.type === 'terminal'
77
+ ? { type: 'subagent_state', id: event.id, state: 'terminal', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: event.execution, running: event.running }
78
+ : { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
79
+ turnScope.executionScope ??= assembled.executionScope;
71
80
  const availableTools = assembled.availableTools;
72
81
  loadedMcp = assembled.loadedMcp;
73
82
  if (loadedMcp?.errors.length)
@@ -78,13 +87,15 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
78
87
  const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
79
88
  const durableRequestMessages = compactToolHistory(retryingExistingRequest
80
89
  ? stripSyntheticControls(callbacks.getConversation())
81
- : [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
90
+ : [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
82
91
  let requestMessages = durableRequestMessages;
83
92
  if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
84
93
  requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
85
94
  }
86
95
  requestMessages = withoutSystemMessages(requestMessages);
87
96
  callbacks.setConversation(stripSyntheticControls(requestMessages));
97
+ if (turnOptions.ephemeralControl)
98
+ requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
88
99
  const systemPrompt = assembled.systemPrompt;
89
100
  const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
90
101
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
@@ -98,7 +109,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
98
109
  callbacks.setLastAssistantText(text);
99
110
  };
100
111
  const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
101
- const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path) };
112
+ const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
113
+ const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path), mutationPolicy, blessedPaths: turnOptions.blessedPaths };
102
114
  const startedTools = new Map();
103
115
  const latestToolCalls = new Map();
104
116
  let latestAccumulatedResponseMessages = [];
@@ -109,6 +121,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
109
121
  let currentAssistantText = '';
110
122
  let streamError;
111
123
  let streamFinished = false;
124
+ let finishReason;
125
+ let lastToolOk;
126
+ let completedSteps = 0;
127
+ let completedToolCalls = 0;
128
+ let completedToolOnlySteps = 0;
112
129
  let toolResultState = initialToolResultState();
113
130
  const resetAssistantSegment = () => {
114
131
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
@@ -172,6 +189,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
172
189
  return messagesChanged ? { messages: scopedMessages } : undefined;
173
190
  },
174
191
  onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
192
+ completedSteps++;
193
+ completedToolCalls += toolCalls.length;
194
+ if (toolCalls.length > 0 && text.trim().length === 0)
195
+ completedToolOnlySteps++;
175
196
  if (Array.isArray(response?.messages) && response.messages.length > 0)
176
197
  latestAccumulatedResponseMessages = response.messages;
177
198
  const stepUsage = stepCacheMetrics(usage);
@@ -200,10 +221,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
200
221
  callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
201
222
  },
202
223
  });
203
- resetIdleTimer();
224
+ idleTimer.reset();
204
225
  const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
205
226
  for await (const part of result.stream) {
206
- resetIdleTimer();
227
+ idleTimer.reset();
207
228
  switch (part.type) {
208
229
  case 'text-delta': {
209
230
  callbacks.setBusyLabel?.(thinkingLabel);
@@ -236,6 +257,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
236
257
  const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
237
258
  latestToolCalls.set(part.id, toolCall);
238
259
  startedTools.set(part.id, Date.now());
260
+ inFlightTools.add(part.id);
239
261
  callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
240
262
  toolDisplay.ensureToolItem(toolCall);
241
263
  break;
@@ -259,16 +281,18 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
259
281
  case 'tool-result': {
260
282
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
261
283
  latestToolCalls.set(part.toolCallId, toolCall);
284
+ inFlightTools.delete(part.toolCallId);
262
285
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
263
- const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
286
+ const ok = toolOutputOk(part.output, true);
287
+ lastToolOk = ok;
288
+ const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
264
289
  const item = toolDisplay.ensureToolItem(toolCall);
265
- item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
290
+ item.status = ok ? 'success' : 'error';
266
291
  item.result = toolResultSummary(finish);
267
292
  item.durationMs = finish.durationMs;
268
293
  item.finishedAt = startedAt + finish.durationMs;
269
- callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs }));
270
- logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs } });
271
- const ok = toolOutputOk(part.output, true);
294
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs }));
295
+ logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs } });
272
296
  toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
273
297
  observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
274
298
  callbacks.setWorkState?.(goal);
@@ -283,9 +307,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
283
307
  break;
284
308
  }
285
309
  case 'tool-error': {
310
+ inFlightTools.delete(part.toolCallId);
286
311
  const existing = latestToolCalls.get(part.toolCallId);
287
312
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
288
313
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
314
+ lastToolOk = false;
289
315
  const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
290
316
  const item = toolDisplay.ensureToolItem(toolCall);
291
317
  item.status = 'error';
@@ -309,6 +335,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
309
335
  break;
310
336
  case 'finish':
311
337
  streamFinished = true;
338
+ finishReason = part.finishReason;
312
339
  callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
313
340
  break;
314
341
  default:
@@ -338,13 +365,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
338
365
  finalizeAssistantSegment();
339
366
  }
340
367
  else if (latestToolCalls.size > 0) {
341
- const fallback = 'Finished tool work.';
342
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
368
+ callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
343
369
  }
370
+ const budgetReached = finishReason === 'length'
371
+ || completedSteps >= MAIN_STEP_LIMIT
372
+ || completedToolCalls >= MAIN_TOOL_CALL_LIMIT
373
+ || completedToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT;
374
+ turnStatus = terminalTurnStatus({ aborted: false, assistantText, sawToolCall: latestToolCalls.size > 0, lastToolOk, finishReason, budgetReached });
344
375
  goal.phase = 'done';
345
- goal.status = 'complete';
376
+ goal.status = turnStatus === 'complete' ? 'complete' : 'blocked';
377
+ callbacks.setWorkState?.(goal);
346
378
  callbacks.setGoalStatus?.(undefined);
347
- turnStatus = 'complete';
348
379
  }
349
380
  catch (error) {
350
381
  if (abortController.signal.aborted) {
@@ -360,7 +391,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
360
391
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
361
392
  if (compacted) {
362
393
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
363
- return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session, modelOverride);
394
+ return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
364
395
  }
365
396
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
366
397
  }
@@ -369,12 +400,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
369
400
  const delay = retryDelayMs(retryAttempt);
370
401
  callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
371
402
  callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
372
- await abortableDelay(delay, abortController.signal);
373
- if (abortController.signal.aborted) {
374
- turnStatus = 'aborted';
375
- return { status: turnStatus };
376
- }
377
- return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session, modelOverride);
403
+ return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
378
404
  }
379
405
  callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
380
406
  }
@@ -382,14 +408,48 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
382
408
  finally {
383
409
  if (loadedMcp?.clients.length)
384
410
  await closeMcpClients(loadedMcp.clients);
385
- if (idleTimer)
386
- clearTimeout(idleTimer);
411
+ idleTimer.clear();
387
412
  toolDisplay.stopToolTimer();
388
413
  toolDisplay.finalizeToolGroup();
389
- callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
414
+ }
415
+ return { status: turnStatus };
416
+ }
417
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
418
+ const abortController = new AbortController();
419
+ let status = 'failed';
420
+ callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
421
+ callbacks.setBusy(true);
422
+ callbacks.setAbortController?.(abortController);
423
+ if (!retryingExistingRequest)
424
+ callbacks.addMessage({ role: 'user', text: displayValue ?? value });
425
+ try {
426
+ // Retries are one logical turn and therefore share coordinator admission and
427
+ // the workspace mutation lease, including quarantined lingering work.
428
+ const turnScope = {};
429
+ let attempt = retryAttempt;
430
+ let overflowRecovered = contextOverflowRecovered;
431
+ let retrying = retryingExistingRequest;
432
+ while (true) {
433
+ const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController, turnOptions, turnScope);
434
+ status = result.status;
435
+ if (!result.retry)
436
+ break;
437
+ attempt = result.retry.attempt;
438
+ overflowRecovered = result.retry.contextOverflowRecovered;
439
+ retrying = true;
440
+ if (result.retry.delayMs > 0)
441
+ await abortableDelay(result.retry.delayMs, abortController.signal);
442
+ if (abortController.signal.aborted) {
443
+ status = 'aborted';
444
+ break;
445
+ }
446
+ }
447
+ return { status };
448
+ }
449
+ finally {
450
+ callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status }));
390
451
  callbacks.setAbortController?.(null);
391
- callbacks.setBusyLabel?.(thinkingLabel);
452
+ callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
392
453
  callbacks.setBusy(false);
393
454
  }
394
- return { status: turnStatus };
395
455
  }
@@ -6,9 +6,15 @@ export declare const PROVIDER_ACTIONS: {
6
6
  readonly useProvider: "use provider";
7
7
  readonly addModels: "add models";
8
8
  readonly setApiKey: "set API key";
9
+ readonly markImageCapable: "mark image-capable";
10
+ readonly clearImageCapable: "clear image-capable";
9
11
  readonly removeModels: "remove models";
10
12
  readonly removeProvider: "remove provider";
11
13
  };
14
+ export declare const MODEL_CHOICES: {
15
+ readonly addModels: "add models";
16
+ readonly enterModelNames: "enter model names";
17
+ };
12
18
  export declare const SERVER_CHOICES: {
13
19
  readonly addServer: "add server";
14
20
  readonly custom: "custom";
@@ -6,9 +6,15 @@ export const PROVIDER_ACTIONS = {
6
6
  useProvider: 'use provider',
7
7
  addModels: 'add models',
8
8
  setApiKey: 'set API key',
9
+ markImageCapable: 'mark image-capable',
10
+ clearImageCapable: 'clear image-capable',
9
11
  removeModels: 'remove models',
10
12
  removeProvider: 'remove provider',
11
13
  };
14
+ export const MODEL_CHOICES = {
15
+ addModels: 'add models',
16
+ enterModelNames: 'enter model names',
17
+ };
12
18
  export const SERVER_CHOICES = {
13
19
  addServer: 'add server',
14
20
  custom: 'custom',
@@ -48,5 +48,5 @@ export function captureMcpCommand(value) {
48
48
  const parts = commandParts(value);
49
49
  if (parts.length === 0)
50
50
  return { message: 'Command is required.' };
51
- return { draft: { command: parts[0], args: parts.slice(1) }, nextMode: 'mcpAddKey', systemMessage: 'Optional API key or auth header value? (Leave blank to skip — Enter works.) Sent as Authorization: Bearer <value>.' };
51
+ return { draft: { command: parts[0], args: parts.slice(1) }, nextMode: 'chat', systemMessage: 'Stdio MCP authentication must be handled by the command or wrapper; HTTP headers do not apply.' };
52
52
  }
@@ -12,6 +12,13 @@ export declare function providerSuggestions(settings: HazeSettings): TextInputSu
12
12
  export declare function providerActionSuggestions(settings: HazeSettings, selectedProviderName: string | undefined): TextInputSuggestion[];
13
13
  export declare function presetSuggestions(): TextInputSuggestion[];
14
14
  export declare function modelSuggestions(settings: HazeSettings, modelProviderFilter: string | undefined): TextInputSuggestion[];
15
+ export declare function modelAddProviderSuggestions(settings: HazeSettings): TextInputSuggestion[];
16
+ /**
17
+ * Model picker fed by live /models discovery. Curated `suggestedModels`
18
+ * (from provider presets) are pinned atop the discovered list when the
19
+ * endpoint actually serves them — stale curation entries simply don't pin.
20
+ */
21
+ export declare function modelPickSuggestions(settings: HazeSettings, providerName: string | undefined, discoveredModels: string[], suggestedModels?: string[]): TextInputSuggestion[];
15
22
  export declare function lspSuggestions(settings: HazeSettings): TextInputSuggestion[];
16
23
  export declare function lspActionSuggestions(settings: HazeSettings, selectedLspName: string | undefined): TextInputSuggestion[];
17
24
  export declare function lspPresetSuggestions(): TextInputSuggestion[];
@@ -20,4 +27,5 @@ export declare function mcpActionSuggestions(settings: HazeSettings, selectedMcp
20
27
  export declare function mcpPresetSuggestions(): TextInputSuggestion[];
21
28
  export declare function mcpTransportSuggestions(): TextInputSuggestion[];
22
29
  export declare function skillsSuggestions(settings: HazeSettings, skills: LoadedSkill[]): TextInputSuggestion[];
30
+ export declare function skillScopeSuggestions(): TextInputSuggestion[];
23
31
  export declare function skillsActionSuggestions(settings: HazeSettings, skills: LoadedSkill[], selectedSkillName: string | undefined): TextInputSuggestion[];
@@ -1,9 +1,10 @@
1
- import { configuredProviders, findProvider, modelSelector } from '../../config/providers.js';
1
+ import { configuredProviders, findProvider, modelSelector, providerImageCapable } from '../../config/providers.js';
2
2
  import { configuredLspServers, LSP_PRESETS } from '../../config/lspSettings.js';
3
3
  import { configuredMcpServers, findMcpServer, findMcpPreset, presetIds } from '../../config/mcpSettings.js';
4
4
  import { isSkillEnabled } from '../../config/skillSettings.js';
5
5
  import { PROVIDER_PRESETS } from '../../config/providerPresets.js';
6
- import { COMMON_ACTIONS, LSP_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, PROVIDER_ACTIONS, PROVIDER_CHOICES, SERVER_CHOICES, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
6
+ import { COMMON_ACTIONS, LSP_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, MODEL_CHOICES, PROVIDER_ACTIONS, PROVIDER_CHOICES, SERVER_CHOICES, SKILL_ACTIONS, SKILL_CHOICES } from './wizardActions.js';
7
+ import { findSelectedSkill, skillPickerValue } from './skillWizard.js';
7
8
  /**
8
9
  * Pure suggestion builders for the chat wizard pickers (provider / model / LSP /
9
10
  * MCP / skills). Extracted from the React component so they are unit-testable
@@ -25,8 +26,13 @@ export function providerActionSuggestions(settings, selectedProviderName) {
25
26
  const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
26
27
  return [
27
28
  { value: PROVIDER_ACTIONS.useProvider, description: 'Set this provider and choose a model', kind: 'provider' },
28
- { value: PROVIDER_ACTIONS.addModels, description: 'Append comma-separated model names', kind: 'provider' },
29
+ { value: PROVIDER_ACTIONS.addModels, description: 'Fetch the provider model list and add models', kind: 'provider' },
29
30
  { value: PROVIDER_ACTIONS.setApiKey, description: provider?.key ? 'Update the saved API key' : 'Add an API key', kind: 'provider' },
31
+ provider
32
+ ? (providerImageCapable(provider)
33
+ ? { value: PROVIDER_ACTIONS.clearImageCapable, description: 'Stop sending attached images to this provider', kind: 'provider' }
34
+ : { value: PROVIDER_ACTIONS.markImageCapable, description: 'Allow attached images to be sent to this provider', kind: 'provider' })
35
+ : { value: PROVIDER_ACTIONS.markImageCapable, description: 'Allow attached images to be sent to this provider', kind: 'provider' },
30
36
  ...(provider?.models?.length ? [{ value: PROVIDER_ACTIONS.removeModels, description: 'Remove models from this provider', kind: 'provider' }] : []),
31
37
  { value: PROVIDER_ACTIONS.removeProvider, description: 'Delete this provider from settings', kind: 'provider' },
32
38
  ];
@@ -50,11 +56,47 @@ export function presetSuggestions() {
50
56
  }
51
57
  export function modelSuggestions(settings, modelProviderFilter) {
52
58
  const providers = configuredProviders(settings).filter(provider => !modelProviderFilter || provider.name === modelProviderFilter);
53
- return providers.flatMap(provider => provider.models.map(model => ({
54
- value: modelProviderFilter ? model : modelSelector(provider, model),
55
- description: provider.name,
56
- kind: 'model',
57
- })));
59
+ return [
60
+ ...providers.flatMap(provider => provider.models.map(model => ({
61
+ value: modelProviderFilter ? model : modelSelector(provider, model),
62
+ description: provider.name,
63
+ kind: 'model',
64
+ }))),
65
+ { value: MODEL_CHOICES.addModels, description: modelProviderFilter ? `Add models to ${modelProviderFilter} (fetched from its models endpoint)` : 'Add models to a provider (fetched from its models endpoint)', kind: 'model' },
66
+ ];
67
+ }
68
+ export function modelAddProviderSuggestions(settings) {
69
+ return configuredProviders(settings).map(provider => ({
70
+ value: provider.name,
71
+ description: `${provider.models.length} model${provider.models.length === 1 ? '' : 's'} configured`,
72
+ kind: 'provider',
73
+ }));
74
+ }
75
+ /**
76
+ * Model picker fed by live /models discovery. Curated `suggestedModels`
77
+ * (from provider presets) are pinned atop the discovered list when the
78
+ * endpoint actually serves them — stale curation entries simply don't pin.
79
+ */
80
+ export function modelPickSuggestions(settings, providerName, discoveredModels, suggestedModels = []) {
81
+ const provider = providerName ? findProvider(settings, providerName) : undefined;
82
+ const configured = new Set(provider?.models ?? []);
83
+ const available = discoveredModels.filter(model => !configured.has(model));
84
+ const availableSet = new Set(available);
85
+ const pinned = suggestedModels.filter(model => availableSet.has(model));
86
+ const pinnedSet = new Set(pinned);
87
+ return [
88
+ ...pinned.map(model => ({
89
+ value: model,
90
+ description: 'suggested',
91
+ kind: 'model',
92
+ })),
93
+ ...available.filter(model => !pinnedSet.has(model)).map(model => ({
94
+ value: model,
95
+ description: providerName,
96
+ kind: 'model',
97
+ })),
98
+ { value: MODEL_CHOICES.enterModelNames, description: 'Type comma-separated model names instead', kind: 'model' },
99
+ ];
58
100
  }
59
101
  export function lspSuggestions(settings) {
60
102
  const servers = configuredLspServers(settings);
@@ -96,7 +138,8 @@ export function mcpActionSuggestions(settings, selectedMcpName) {
96
138
  const result = [];
97
139
  if (server) {
98
140
  result.push({ value: server.enabled === false ? COMMON_ACTIONS.enable : COMMON_ACTIONS.disable, description: `${server.enabled === false ? COMMON_ACTIONS.enable : COMMON_ACTIONS.disable} this server`, kind: 'mcp' });
99
- result.push({ value: MCP_ACTIONS.setApiKey, description: server.headers?.length ? 'update the saved API key' : 'add an API key', kind: 'mcp' });
141
+ if (server.transport !== 'stdio')
142
+ result.push({ value: MCP_ACTIONS.setApiKey, description: server.headers?.length ? 'update the saved API key' : 'add an API key', kind: 'mcp' });
100
143
  }
101
144
  result.push({ value: MCP_ACTIONS.removeServer, description: 'remove this server', kind: 'mcp' });
102
145
  return result;
@@ -120,16 +163,22 @@ export function mcpTransportSuggestions() {
120
163
  export function skillsSuggestions(settings, skills) {
121
164
  return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for haze to generate', kind: 'skill' },
122
165
  ...skills.map(skill => ({
123
- value: skill.name,
124
- description: `${skill.description}${isSkillEnabled(settings, skill.name) ? '' : ' · disabled'}`,
166
+ value: skills.some(candidate => candidate !== skill && candidate.name === skill.name) ? skillPickerValue(skill) : skill.name,
167
+ description: `${skill.description} · ${skill.source}${isSkillEnabled(settings, skill.name, skill.source) ? '' : ' · disabled'}`,
125
168
  kind: 'skill',
126
169
  }))];
127
170
  }
171
+ export function skillScopeSuggestions() {
172
+ return [
173
+ { value: 'this project', description: 'create .haze/skills/<name>/SKILL.md for this repository', kind: 'skill' },
174
+ { value: 'global', description: 'create ~/.haze/skills/<name>/SKILL.md for your user', kind: 'skill' },
175
+ ];
176
+ }
128
177
  export function skillsActionSuggestions(settings, skills, selectedSkillName) {
129
- const skill = selectedSkillName ? skills.find(candidate => candidate.name === selectedSkillName) : undefined;
178
+ const skill = findSelectedSkill(skills, selectedSkillName);
130
179
  const result = [];
131
180
  if (skill) {
132
- const enabled = isSkillEnabled(settings, skill.name);
181
+ const enabled = isSkillEnabled(settings, skill.name, skill.source);
133
182
  result.push({ value: enabled ? COMMON_ACTIONS.disable : COMMON_ACTIONS.enable, description: `${enabled ? COMMON_ACTIONS.disable : COMMON_ACTIONS.enable} this skill`, kind: 'skill' });
134
183
  result.push({ value: SKILL_ACTIONS.showInfo, description: 'show description, references, and path', kind: 'skill' });
135
184
  result.push({ value: SKILL_ACTIONS.validate, description: 're-load and validate SKILL.md', kind: 'skill' });
@@ -0,0 +1,37 @@
1
+ import type { HazeSettings, HazeMcpServer, HazeProviderSettings } from '../../config/settings.js';
2
+ import type { Mode } from './chatModes.js';
3
+ type SharedWizardEffect = {
4
+ type: 'message';
5
+ text?: string;
6
+ } | {
7
+ type: 'mode';
8
+ mode: Mode;
9
+ };
10
+ export type ProviderWizardEffect = SharedWizardEffect | {
11
+ type: 'provider-draft';
12
+ patch: Partial<HazeProviderSettings>;
13
+ replace?: boolean;
14
+ } | {
15
+ type: 'discover-provider-models';
16
+ draft: Partial<HazeProviderSettings>;
17
+ };
18
+ export type McpWizardEffect = SharedWizardEffect | {
19
+ type: 'mcp-draft';
20
+ patch: Partial<HazeMcpServer>;
21
+ } | {
22
+ type: 'finish-mcp-stdio';
23
+ draft: Partial<HazeMcpServer>;
24
+ };
25
+ export declare function transitionProviderField(input: {
26
+ mode: Mode;
27
+ value: string;
28
+ settings: HazeSettings;
29
+ draft: Partial<HazeProviderSettings>;
30
+ }): ProviderWizardEffect[] | undefined;
31
+ export declare function transitionMcpField(input: {
32
+ mode: Mode;
33
+ value: string;
34
+ settings: HazeSettings;
35
+ draft: Partial<HazeMcpServer>;
36
+ }): McpWizardEffect[] | undefined;
37
+ export {};
@@ -0,0 +1,43 @@
1
+ import { captureMcpCommand, captureMcpName, captureMcpTransport, captureMcpUrl, captureProviderName, captureProviderUrl } from './wizardPrompts.js';
2
+ export function transitionProviderField(input) {
3
+ if (input.mode === 'providerAddKey') {
4
+ const key = input.value.trim();
5
+ return [
6
+ { type: 'provider-draft', patch: key ? { key } : {} },
7
+ { type: 'discover-provider-models', draft: { ...input.draft, ...(key ? { key } : {}) } },
8
+ ];
9
+ }
10
+ const result = input.mode === 'providerAddName' ? captureProviderName(input.settings, input.value)
11
+ : input.mode === 'providerAddUrl' ? captureProviderUrl(input.value)
12
+ : undefined;
13
+ if (!result)
14
+ return undefined;
15
+ if (result.message)
16
+ return [{ type: 'message', text: result.message }];
17
+ const patch = result.draft ?? {};
18
+ return [
19
+ ...(Object.keys(patch).length ? [{ type: 'provider-draft', patch, replace: input.mode === 'providerAddName' }] : []),
20
+ ...(result.nextMode ? [{ type: 'mode', mode: result.nextMode }] : []),
21
+ { type: 'message', text: result.systemMessage },
22
+ ];
23
+ }
24
+ export function transitionMcpField(input) {
25
+ const result = input.mode === 'mcpAddName' ? captureMcpName(input.settings, input.value)
26
+ : input.mode === 'mcpAddTransport' ? captureMcpTransport(input.value)
27
+ : input.mode === 'mcpAddUrl' ? captureMcpUrl(input.value)
28
+ : input.mode === 'mcpAddCommand' ? captureMcpCommand(input.value)
29
+ : undefined;
30
+ if (!result)
31
+ return undefined;
32
+ if (result.message)
33
+ return [{ type: 'message', text: result.message }];
34
+ const patch = result.draft ?? {};
35
+ const nextDraft = { ...input.draft, ...patch };
36
+ if (result.nextMode === 'chat' && input.mode === 'mcpAddCommand')
37
+ return [{ type: 'finish-mcp-stdio', draft: nextDraft }];
38
+ return [
39
+ ...(Object.keys(patch).length ? [{ type: 'mcp-draft', patch }] : []),
40
+ ...(result.nextMode ? [{ type: 'mode', mode: result.nextMode }] : []),
41
+ { type: 'message', text: result.systemMessage },
42
+ ];
43
+ }
package/dist/cli/index.js CHANGED
@@ -5,7 +5,11 @@ import { dirname, join } from 'node:path';
5
5
  import { Command, Option } from 'commander';
6
6
  import { chatCommand } from './commands/chat.js';
7
7
  import { runHeadless } from './commands/runCommand.js';
8
+ import { installTerminalTitle, terminalTitleLabel } from './terminalTitle.js';
9
+ import { findSession } from '../core/session/sessionStore.js';
10
+ import { installBackgroundProcessSignalHandlers, teardownBackgroundProcesses } from '../core/process/backgroundRegistry.js';
8
11
  const __dirname = dirname(fileURLToPath(import.meta.url));
12
+ installBackgroundProcessSignalHandlers();
9
13
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
10
14
  const program = new Command();
11
15
  program
@@ -14,6 +18,7 @@ program
14
18
  .version(pkg.version)
15
19
  .option('--debug', 'show model/tool debug logs and write a detailed JSONL log to ~/.haze/logs/')
16
20
  .option('-c, --continue', 'resume the latest saved session for this workspace')
21
+ .addOption(new Option('--resume <id>', 'resume an exact saved session id for this workspace').conflicts(['continue', 'session']))
17
22
  .option('--no-session', 'run without saving or resuming a durable session')
18
23
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
19
24
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
@@ -26,6 +31,7 @@ Examples:
26
31
  $ haze -p "list the top 3 bugs" --output json emit a JSON envelope { type, status, result, usage }
27
32
  $ haze -p "audit src/" --output stream-json stream NDJSON events live, then the final result envelope
28
33
  $ haze -p "summarize" --model openai:gpt-4o-mini override the model for this run only
34
+ $ haze --resume <id> -p "continue the review" load a saved context for one print-mode turn
29
35
  $ haze -p "audit auth.ts" --debug also write a detailed JSONL log to ~/.haze/logs/
30
36
 
31
37
  Print mode (-p):
@@ -38,7 +44,8 @@ Print mode (-p):
38
44
  harnesses live progress and stagnation detection. --model overrides the model for this
39
45
  run only (no settings change) and must already be registered under a provider (add it once via
40
46
  the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
41
- saved, and there is no automatic context-overflow recovery.
47
+ saved. --resume <id> loads saved context for the turn without changing that session. There is no
48
+ automatic context-overflow recovery.
42
49
  `);
43
50
  async function readStdinPrompt() {
44
51
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
@@ -57,13 +64,19 @@ async function readStdinPrompt() {
57
64
  }
58
65
  program.action(async () => {
59
66
  const opts = program.opts();
67
+ // Name the terminal tab for the run; no-op unless stdout is a real TTY.
68
+ installTerminalTitle(terminalTitleLabel(process.cwd()));
60
69
  // -p takes precedence; otherwise fall back to piped stdin. An empty stdin yields no prompt.
61
70
  const prompt = opts.prompt?.trim() ? opts.prompt : await readStdinPrompt();
71
+ if (opts.resume && !await findSession(opts.resume)) {
72
+ throw new Error(`No session named ${opts.resume} exists for this workspace.`);
73
+ }
62
74
  if (prompt) {
63
75
  // One-shot runs are always fresh and non-durable; --continue is ignored in this mode.
64
76
  const code = await runHeadless({
65
77
  prompt,
66
78
  modelOverride: opts.model,
79
+ resumeSessionId: opts.resume,
67
80
  // commander validates --output against the choices above, so opts.output is one of
68
81
  // 'text' | 'json' | 'stream-json'; default to text for piped/stdin runs without the flag.
69
82
  output: opts.output === 'json' || opts.output === 'stream-json' ? opts.output : 'text',
@@ -74,9 +87,10 @@ program.action(async () => {
74
87
  process.exitCode = code;
75
88
  return;
76
89
  }
77
- await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), noSession: opts.session === false, version: pkg.version });
90
+ await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), resumeSessionId: opts.resume, noSession: opts.session === false, version: pkg.version });
78
91
  });
79
- program.parseAsync().catch((error) => {
92
+ program.parseAsync().catch(async (error) => {
80
93
  console.error(error instanceof Error ? error.message : error);
94
+ await teardownBackgroundProcesses().catch(() => undefined);
81
95
  process.exit(1);
82
96
  });