@denizokcu/haze 0.7.0 → 0.9.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 (96) hide show
  1. package/CHANGELOG.md +35 -9
  2. package/README.md +37 -35
  3. package/dist/cli/chat/inputSuggestions.js +2 -2
  4. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  5. package/dist/cli/chat/sessionRecorder.js +23 -8
  6. package/dist/cli/commands/chat.js +136 -124
  7. package/dist/cli/commands/chatModes.js +1 -1
  8. package/dist/cli/commands/commandHelp.js +2 -2
  9. package/dist/cli/commands/commands.d.ts +1 -1
  10. package/dist/cli/commands/commands.js +1 -1
  11. package/dist/cli/commands/formatters.d.ts +6 -0
  12. package/dist/cli/commands/formatters.js +41 -3
  13. package/dist/cli/commands/logsCommand.js +7 -21
  14. package/dist/cli/commands/mcpWizard.js +24 -2
  15. package/dist/cli/commands/providerWizard.js +18 -5
  16. package/dist/cli/commands/runCommand.js +7 -15
  17. package/dist/cli/commands/settingsSummary.js +3 -1
  18. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  19. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  20. package/dist/cli/commands/streaming.js +99 -51
  21. package/dist/cli/commands/wizardPrompts.js +1 -1
  22. package/dist/cli/commands/wizardSuggestions.js +3 -2
  23. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  24. package/dist/cli/commands/wizardTransition.js +44 -0
  25. package/dist/config/contextFiles.js +6 -3
  26. package/dist/config/endpointSecurity.d.ts +2 -0
  27. package/dist/config/endpointSecurity.js +28 -0
  28. package/dist/config/inputHistory.js +4 -2
  29. package/dist/config/privateStorage.d.ts +6 -0
  30. package/dist/config/privateStorage.js +61 -0
  31. package/dist/config/providers.js +5 -9
  32. package/dist/config/settings.d.ts +1 -0
  33. package/dist/config/settings.js +55 -3
  34. package/dist/config/updateCheck.js +4 -2
  35. package/dist/core/agent/compaction.js +2 -2
  36. package/dist/core/agent/errors.js +1 -1
  37. package/dist/core/agent/requestAssembly.d.ts +1 -0
  38. package/dist/core/agent/requestAssembly.js +13 -0
  39. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  40. package/dist/core/agent/toolOutputStore.js +32 -11
  41. package/dist/core/bashOutput/registry.js +11 -9
  42. package/dist/core/goal/completionPolicy.d.ts +0 -28
  43. package/dist/core/goal/completionPolicy.js +1 -89
  44. package/dist/core/io/boundedRead.d.ts +15 -0
  45. package/dist/core/io/boundedRead.js +97 -0
  46. package/dist/core/limits/byteBudgets.d.ts +13 -0
  47. package/dist/core/limits/byteBudgets.js +13 -0
  48. package/dist/core/log/llmLog.d.ts +10 -0
  49. package/dist/core/log/llmLog.js +59 -13
  50. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  51. package/dist/core/persistence/orderedFileWriter.js +29 -0
  52. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  53. package/dist/core/process/runBoundedProcess.js +80 -0
  54. package/dist/core/session/sessionStore.js +48 -25
  55. package/dist/core/subagent/subagentRunner.d.ts +252 -9
  56. package/dist/core/subagent/subagentRunner.js +14 -19
  57. package/dist/core/toolOutput/reduction.d.ts +2 -0
  58. package/dist/core/toolOutput/reduction.js +12 -0
  59. package/dist/core/validation/outputParser.js +5 -3
  60. package/dist/llm/client.d.ts +2 -2
  61. package/dist/llm/client.js +19 -3
  62. package/dist/llm/hazeTools.d.ts +8103 -364
  63. package/dist/llm/hazeTools.js +43 -33
  64. package/dist/llm/initPrompt.js +1 -1
  65. package/dist/llm/lsp.d.ts +21 -3
  66. package/dist/llm/lsp.js +65 -14
  67. package/dist/llm/lspTools.d.ts +2358 -101
  68. package/dist/llm/mcp.d.ts +1 -1
  69. package/dist/llm/mcp.js +65 -16
  70. package/dist/llm/requestContext.d.ts +1 -0
  71. package/dist/llm/requestContext.js +6 -3
  72. package/dist/llm/systemPrompt.js +2 -2
  73. package/dist/llm/toolResultTypes.d.ts +1 -1
  74. package/dist/llm/tools/bashTool.d.ts +603 -5
  75. package/dist/llm/tools/bashTool.js +23 -60
  76. package/dist/llm/tools/fetchTool.d.ts +1201 -65
  77. package/dist/llm/tools/fetchTool.js +2 -1
  78. package/dist/llm/tools/grepRunner.d.ts +15 -0
  79. package/dist/llm/tools/grepRunner.js +85 -0
  80. package/dist/llm/tools/storedOutputTool.d.ts +351 -10
  81. package/dist/llm/tools/taskTool.d.ts +629 -28
  82. package/dist/llm/tools/toolContext.d.ts +7 -2
  83. package/dist/llm/tools/toolContext.js +11 -2
  84. package/dist/llm/webFetch.js +31 -21
  85. package/dist/skills/SkillLoader.js +17 -5
  86. package/dist/skills/SkillRegistry.js +19 -6
  87. package/dist/skills/builder/SkillBuilder.js +7 -7
  88. package/dist/skills/types.d.ts +5 -0
  89. package/dist/ui/components/TextInput.d.ts +7 -0
  90. package/dist/ui/components/TextInput.js +10 -0
  91. package/dist/utils/modelName.d.ts +2 -0
  92. package/dist/utils/modelName.js +15 -0
  93. package/dist/utils/path.d.ts +2 -0
  94. package/dist/utils/path.js +9 -4
  95. package/examples/skills/files/SKILL.md +1 -1
  96. package/package.json +14 -14
@@ -1,4 +1,4 @@
1
- import { listLogs, readLogEntries } from '../../core/log/llmLog.js';
1
+ import { listLogs, summarizeLog } from '../../core/log/llmLog.js';
2
2
  function formatBytes(bytes) {
3
3
  if (bytes < 1024)
4
4
  return `${bytes} B`;
@@ -21,39 +21,25 @@ export async function handleLogsCommand(args, ctx) {
21
21
  ctx.addSystemMessage(['Recent logs:', ' ID Size Modified', ...lines].join('\n'));
22
22
  return 'handled';
23
23
  }
24
- const entries = await readLogEntries(id);
25
- if (entries.length === 0) {
24
+ const summary = await summarizeLog(id);
25
+ if (!summary) {
26
26
  ctx.addSystemMessage(`No log found with id ${id}.`);
27
27
  return 'handled';
28
28
  }
29
- const typeCounts = {};
30
- let totalInput = 0;
31
- let totalOutput = 0;
32
- const toolCallCounts = {};
33
- for (const entry of entries) {
34
- typeCounts[entry.type] = (typeCounts[entry.type] ?? 0) + 1;
35
- if (entry.usage) {
36
- totalInput += entry.usage.inputTokens ?? 0;
37
- totalOutput += entry.usage.outputTokens ?? 0;
38
- }
39
- if (entry.type === 'tool_call' && entry.toolCall) {
40
- toolCallCounts[entry.toolCall.name] = (toolCallCounts[entry.toolCall.name] ?? 0) + 1;
41
- }
42
- }
43
- const typeLines = Object.entries(typeCounts)
29
+ const typeLines = Object.entries(summary.typeCounts)
44
30
  .sort(([a], [b]) => a.localeCompare(b))
45
31
  .map(([type, count]) => ` ${type}: ${count}`);
46
- const toolLines = Object.entries(toolCallCounts)
32
+ const toolLines = Object.entries(summary.toolCallCounts)
47
33
  .sort(([, a], [, b]) => b - a)
48
34
  .map(([name, count]) => ` ${name}: ${count}`);
49
35
  const parts = [
50
36
  `Log: ${id}`,
51
- `Entries: ${entries.length}`,
37
+ `Entries: ${summary.entries}`,
52
38
  '',
53
39
  'Entry counts by type:',
54
40
  ...typeLines,
55
41
  '',
56
- `Total token usage: in=${totalInput} out=${totalOutput}`,
42
+ `Total token usage: in=${summary.totalInput} out=${summary.totalOutput}`,
57
43
  ];
58
44
  if (toolLines.length > 0) {
59
45
  parts.push('', 'Tool call counts:', ...toolLines);
@@ -1,5 +1,6 @@
1
1
  import { findMcpPreset, findMcpServer, toggleMcpServer, upsertMcpServer } from '../../config/mcpSettings.js';
2
2
  import { COMMON_ACTIONS, MCP_ACTIONS, MCP_TRANSPORTS, SERVER_CHOICES } from './wizardActions.js';
3
+ import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
3
4
  export function selectMcpServerResult(settings, serverName) {
4
5
  if (serverName === SERVER_CHOICES.addServer)
5
6
  return { mode: 'mcpAddName', clearDraft: true, message: 'Choose an MCP preset, or select "custom" to enter details manually.' };
@@ -32,8 +33,11 @@ export function selectMcpActionResult(settings, selectedName, action) {
32
33
  const enabled = action === COMMON_ACTIONS.enable;
33
34
  return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: toggleMcpServer(settings, selectedName, enabled) ?? [] }, message: `MCP server ${selectedName} ${enabled ? 'enabled' : 'disabled'}.` };
34
35
  }
35
- if (action === MCP_ACTIONS.setApiKey)
36
+ if (action === MCP_ACTIONS.setApiKey) {
37
+ if (server.transport === 'stdio')
38
+ return { mode: 'chat', selectedName: undefined, message: 'Stdio MCP authentication must be handled by its command or wrapper; HTTP headers do not apply.' };
36
39
  return { mode: 'mcpSetKey', message: `New API key for ${selectedName}? (current: ${server.headers?.length ? 'saved' : 'not set'}) Sent as Authorization: Bearer <value>.` };
40
+ }
37
41
  if (action === MCP_ACTIONS.removeServer)
38
42
  return { mode: 'mcpConfirmRemove', message: `Remove MCP server ${selectedName}? Type "yes" to confirm. Esc to cancel.` };
39
43
  return { message: `Unknown MCP action: ${action}` };
@@ -45,12 +49,20 @@ export function finishMcpCustomResult(settings, draft, keyValue) {
45
49
  return { mode: 'chat', clearDraft: true, message: 'MCP server name and transport are required.' };
46
50
  const headers = keyValue?.trim() ? [{ name: 'Authorization', value: `Bearer ${keyValue.trim()}` }] : undefined;
47
51
  const server = transport === MCP_TRANSPORTS.stdio
48
- ? { name, transport, command: draft.command, args: draft.args, ...(headers ? { headers } : {}), enabled: true }
52
+ ? { name, transport, command: draft.command, args: draft.args, enabled: true }
49
53
  : { name, transport, url: draft.url, ...(headers ? { headers } : {}), enabled: true };
50
54
  if (transport === MCP_TRANSPORTS.stdio && !server.command)
51
55
  return { mode: 'chat', clearDraft: true, message: 'Command is required for stdio transport.' };
52
56
  if (transport !== MCP_TRANSPORTS.stdio && !server.url)
53
57
  return { mode: 'chat', clearDraft: true, message: `URL is required for ${transport} transport.` };
58
+ if (server.url) {
59
+ try {
60
+ assertCredentialedEndpointSecure(server.url, server.headers);
61
+ }
62
+ catch (error) {
63
+ return { mode: 'chat', clearDraft: true, message: error instanceof Error ? error.message : String(error) };
64
+ }
65
+ }
54
66
  const location = transport === MCP_TRANSPORTS.stdio ? `${server.command}${(server.args ?? []).length ? ` ${(server.args ?? []).join(' ')}` : ''}` : server.url;
55
67
  return { mode: 'chat', clearDraft: true, server, settingsPatch: { mcpServers: upsertMcpServer(settings, server) }, message: `Added MCP server ${name} (${transport}, ${location}). Tools load on the next turn.` };
56
68
  }
@@ -60,10 +72,20 @@ export function setMcpServerKeyResult(settings, selectedName, keyValue) {
60
72
  const server = findMcpServer(settings, selectedName);
61
73
  if (!server)
62
74
  return { mode: 'chat', selectedName: undefined, message: `MCP server ${selectedName} not found.` };
75
+ if (server.transport === 'stdio')
76
+ return { mode: 'chat', selectedName: undefined, message: 'Stdio MCP authentication must be handled by its command or wrapper.' };
63
77
  const key = keyValue.trim();
64
78
  if (!key)
65
79
  return { message: 'API key cannot be empty. Esc to cancel.' };
66
80
  const headers = (server.headers ?? []).filter(header => header.name !== 'Authorization');
67
81
  headers.push({ name: 'Authorization', value: `Bearer ${key}` });
82
+ if (server.url) {
83
+ try {
84
+ assertCredentialedEndpointSecure(server.url, headers);
85
+ }
86
+ catch (error) {
87
+ return { mode: 'chat', selectedName: undefined, message: error instanceof Error ? error.message : String(error) };
88
+ }
89
+ }
68
90
  return { mode: 'chat', selectedName: undefined, settingsPatch: { mcpServers: upsertMcpServer(settings, { ...server, headers }) }, message: `API key updated for ${server.name}.` };
69
91
  }
@@ -1,6 +1,7 @@
1
1
  import { configuredProviders, findProvider, upsertProvider } from '../../config/providers.js';
2
2
  import { PROVIDER_ACTIONS } from './wizardActions.js';
3
3
  import { commaList } from './wizardInput.js';
4
+ import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
4
5
  export function providerAppendModels(settings, providerName, modelsValue) {
5
6
  const provider = providerName ? findProvider(settings, providerName) : undefined;
6
7
  const models = commaList(modelsValue);
@@ -21,6 +22,12 @@ export function providerFinishAdd(settings, draft, modelsValue) {
21
22
  if (!draft.name || !draft.url || models.length === 0) {
22
23
  return { models, message: 'Provider name, URL, and at least one model are required.' };
23
24
  }
25
+ try {
26
+ assertCredentialedEndpointSecure(draft.url, draft.key);
27
+ }
28
+ catch (error) {
29
+ return { models, message: error instanceof Error ? error.message : String(error) };
30
+ }
24
31
  const provider = {
25
32
  name: draft.name,
26
33
  url: draft.url,
@@ -52,7 +59,7 @@ export function providerRemoveModels(settings, providerName, modelsValue) {
52
59
  if (notFound.length)
53
60
  parts.push(`Not found: ${notFound.join(', ')}.`);
54
61
  if (wasActive)
55
- parts.push(`Active model updated to ${remaining[0]}.`);
62
+ parts.push('Active model selection cleared. Choose a model explicitly.');
56
63
  return {
57
64
  provider,
58
65
  remaining,
@@ -61,7 +68,7 @@ export function providerRemoveModels(settings, providerName, modelsValue) {
61
68
  wasActive,
62
69
  settingsPatch: {
63
70
  providers: upsertProvider(settings, updated),
64
- ...(wasActive ? { model: remaining[0] } : {}),
71
+ ...(wasActive ? { model: undefined } : {}),
65
72
  },
66
73
  message: parts.join(' '),
67
74
  };
@@ -71,16 +78,16 @@ export function providerRemove(settings, providerName) {
71
78
  if (!provider)
72
79
  return { message: 'No provider selected.' };
73
80
  const providers = configuredProviders(settings).filter(candidate => candidate.name !== providerName);
74
- const wasActiveProvider = settings.provider === providerName || (!settings.provider && configuredProviders(settings)[0]?.name === providerName);
81
+ const wasActiveProvider = settings.provider === providerName;
75
82
  return {
76
83
  provider,
77
84
  providers,
78
85
  wasActiveProvider,
79
86
  settingsPatch: {
80
87
  providers,
81
- ...(wasActiveProvider ? { provider: providers[0]?.name, model: providers[0]?.models[0] } : {}),
88
+ ...(wasActiveProvider ? { provider: undefined, model: undefined } : {}),
82
89
  },
83
- message: `Removed provider ${provider.name}.${wasActiveProvider ? ` Switched to ${providers[0]?.name ?? 'no provider'}.` : ''}`,
90
+ message: `Removed provider ${provider.name}.${wasActiveProvider ? ' Active provider and model selection cleared.' : ''}`,
84
91
  };
85
92
  }
86
93
  export function providerSetKey(settings, providerName, value) {
@@ -90,6 +97,12 @@ export function providerSetKey(settings, providerName, value) {
90
97
  const key = value.trim();
91
98
  if (!key)
92
99
  return { provider, message: 'API key cannot be empty. Esc to cancel.' };
100
+ try {
101
+ assertCredentialedEndpointSecure(provider.url, key);
102
+ }
103
+ catch (error) {
104
+ return { provider, message: error instanceof Error ? error.message : String(error) };
105
+ }
93
106
  return {
94
107
  provider,
95
108
  key,
@@ -90,19 +90,8 @@ export async function runHeadless(options) {
90
90
  let log;
91
91
  if (options.debug)
92
92
  log = await createLog();
93
- let emittedTurnStart = false;
94
93
  const emitStreamEvent = options.output === 'stream-json'
95
94
  ? (event) => {
96
- // runAgentTurn emits nested turn_start/turn_end pairs for retries; expose one clean
97
- // headless turn and emit the authoritative turn_end after the run settles.
98
- if (event.type === 'turn_start') {
99
- if (emittedTurnStart)
100
- return;
101
- emittedTurnStart = true;
102
- }
103
- else if (event.type === 'turn_end') {
104
- return;
105
- }
106
95
  const headlessEvent = toHeadlessStreamEvent(event);
107
96
  if (headlessEvent)
108
97
  writeNdjson(headlessEvent);
@@ -141,6 +130,7 @@ export async function runHeadless(options) {
141
130
  };
142
131
  let status;
143
132
  let result;
133
+ let persistenceError;
144
134
  try {
145
135
  ({ status } = await runAgentTurn(options.prompt, options.prompt, contextFiles, callbacks, 0, false, false, session, options.modelOverride));
146
136
  result = segments.filter((s) => !s.hidden && s.text).map((s) => s.text).join('\n');
@@ -151,12 +141,14 @@ export async function runHeadless(options) {
151
141
  }
152
142
  finally {
153
143
  if (log)
154
- await endLog(log).catch(() => undefined);
144
+ await endLog(log).catch(error => {
145
+ persistenceError = error instanceof Error ? error.message : String(error);
146
+ });
155
147
  }
148
+ if (persistenceError)
149
+ process.stderr.write(`haze persistence warning: ${persistenceError}\n`);
156
150
  if (options.output === 'json' || options.output === 'stream-json') {
157
- if (options.output === 'stream-json')
158
- writeNdjson({ type: 'turn_end', request: options.prompt, status, at: new Date().toISOString() });
159
- // For stream-json the agent events have already streamed above; this is the terminal line.
151
+ // For stream-json the authoritative agent events have already streamed above; this is the terminal line.
160
152
  // It is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
161
153
  writeNdjson({ type: 'result', status, result, usage: pinnedUsage(usage) });
162
154
  }
@@ -21,7 +21,8 @@ export async function formatSettingsSummary(settings, contextFiles) {
21
21
  notes.push(`${summary.duplicateGroups.length} duplicate group${summary.duplicateGroups.length === 1 ? '' : 's'} (${duplicateTotal} file${duplicateTotal === 1 ? '' : 's'} with identical content)`);
22
22
  }
23
23
  const lspServers = configuredLspServers(settings);
24
- const installedSkills = [...(await loadSkillRegistry()).skills.values()];
24
+ const skillRegistry = await loadSkillRegistry();
25
+ const installedSkills = [...skillRegistry.skills.values()];
25
26
  const skillNames = installedSkills.map(skill => `${skill.name}${isSkillEnabled(settings, skill.name) ? '' : ' (disabled)'}`).join(', ');
26
27
  const lines = [
27
28
  `Provider: ${activeProvider?.name ?? 'not configured'}`,
@@ -32,6 +33,7 @@ export async function formatSettingsSummary(settings, contextFiles) {
32
33
  `LSP servers: ${lspServers.map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
33
34
  `MCP servers: ${configuredMcpServers(settings).map(server => `${server.name}${server.enabled === false ? ' (disabled)' : ''}`).join(', ') || 'none'}`,
34
35
  `Skills: ${skillNames || 'none'}`,
36
+ ...(skillRegistry.errors.length ? [`Skill load errors: ${skillRegistry.errors.map(error => `${error.directory}: ${error.message}`).join('; ')}`] : []),
35
37
  `Context files: ${contextFiles.length ? `${contextFiles.map(file => file.path).join(', ')} (~${contextTokens} tokens)` : 'none'}`,
36
38
  ];
37
39
  if (notes.length > 0)
@@ -0,0 +1,10 @@
1
+ import type { TurnStatus } from '../streaming.js';
2
+ export declare function terminalTurnStatus(input: {
3
+ aborted: boolean;
4
+ error?: unknown;
5
+ assistantText: string;
6
+ sawToolCall: boolean;
7
+ lastToolOk?: boolean;
8
+ finishReason?: string;
9
+ budgetReached?: boolean;
10
+ }): TurnStatus;
@@ -0,0 +1,13 @@
1
+ export function terminalTurnStatus(input) {
2
+ if (input.aborted)
3
+ return 'aborted';
4
+ if (input.error)
5
+ return 'failed';
6
+ if (input.lastToolOk === false)
7
+ return 'failed';
8
+ if (input.budgetReached || input.finishReason === 'length' || input.finishReason === 'error')
9
+ return 'failed';
10
+ if (input.sawToolCall && input.assistantText.trim().length === 0)
11
+ return 'failed';
12
+ return input.assistantText.trim().length > 0 ? 'complete' : 'failed';
13
+ }
@@ -1,16 +1,16 @@
1
- import { ToolLoopAgent, stepCountIs } from 'ai';
1
+ import { ToolLoopAgent, isStepCount } from 'ai';
2
2
  import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
3
3
  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 { toolCallSummary, toolResultSummary, formatSeconds } from './formatters.js';
7
+ import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
8
8
  import { agentEvent } from '../../core/agent/events.js';
9
9
  import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
10
10
  import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
11
11
  import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
12
12
  import { estimateValueTokens } from '../../core/agent/contextBudget.js';
13
- import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
13
+ import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
14
14
  import { isDuplicateSkippedOutput, toolInputField, toolOutputOk } from '../../core/agent/toolResults.js';
15
15
  import { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
16
16
  export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
@@ -21,29 +21,23 @@ import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, sh
21
21
  import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
22
22
  import { applyToolResultState, initialToolResultState, isMutatingToolName } from './streaming/toolResultState.js';
23
23
  import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
24
+ import { toolsContextFor } from '../../llm/tools/toolContext.js';
25
+ import { modelThinkingLabel } from '../../utils/modelName.js';
26
+ import { terminalTurnStatus } from './streaming/turnOutcome.js';
24
27
  function logEntry(log, entry) {
25
28
  if (log)
26
29
  void logAppend(log, entry).catch(() => undefined);
27
30
  }
28
- function withScopedContextSystem(messages, context) {
31
+ function withScopedContextControl(messages, context) {
29
32
  const files = context.pendingContextFiles ?? [];
30
33
  if (files.length === 0)
31
34
  return messages;
32
35
  context.pendingContextFiles = [];
33
- return [
34
- ...messages,
35
- { role: 'system', content: `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
- ];
36
+ 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)}`);
37
37
  }
38
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
39
- const displayVal = displayValue ?? value;
40
- callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
41
- callbacks.setBusy(true);
42
- callbacks.setBusyLabel?.('Haze is thinking');
43
- if (!retryingExistingRequest)
44
- callbacks.addMessage({ role: 'user', text: displayVal });
45
- const abortController = new AbortController();
46
- callbacks.setAbortController?.(abortController);
38
+ async function runAgentAttempt(value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController) {
39
+ let thinkingLabel = modelThinkingLabel(undefined);
40
+ callbacks.setBusyLabel?.(thinkingLabel);
47
41
  let turnStatus = 'failed';
48
42
  let idleTimer;
49
43
  let loadedMcp;
@@ -51,21 +45,23 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
51
45
  if (idleTimer)
52
46
  clearTimeout(idleTimer);
53
47
  idleTimer = setTimeout(() => {
54
- abortController.abort('Haze turn timed out after no model/tool activity.');
48
+ abortController.abort('haze turn timed out after no model/tool activity.');
55
49
  }, IDLE_TIMEOUT_MS);
56
50
  };
57
51
  const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
58
52
  try {
59
53
  const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
60
54
  if (!runtime?.model) {
61
- 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';
55
+ callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
56
+ turnStatus = 'failed';
63
57
  return { status: turnStatus };
64
58
  }
59
+ thinkingLabel = modelThinkingLabel(runtime.config.modelName);
60
+ callbacks.setBusyLabel?.(thinkingLabel);
65
61
  let activeContextFiles = contextFiles;
66
62
  const activeModel = runtime.model;
67
63
  const providerSettings = providerRequestSettings(runtime.config);
68
- const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
64
+ const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel, abortSignal: abortController.signal });
69
65
  const availableTools = assembled.availableTools;
70
66
  loadedMcp = assembled.loadedMcp;
71
67
  if (loadedMcp?.errors.length)
@@ -81,6 +77,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
81
77
  if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
82
78
  requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
83
79
  }
80
+ requestMessages = withoutSystemMessages(requestMessages);
84
81
  callbacks.setConversation(stripSyntheticControls(requestMessages));
85
82
  const systemPrompt = assembled.systemPrompt;
86
83
  const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
@@ -106,6 +103,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
106
103
  let currentAssistantText = '';
107
104
  let streamError;
108
105
  let streamFinished = false;
106
+ let finishReason;
107
+ let lastToolOk;
108
+ let completedSteps = 0;
109
+ let completedToolCalls = 0;
110
+ let completedToolOnlySteps = 0;
109
111
  let toolResultState = initialToolResultState();
110
112
  const resetAssistantSegment = () => {
111
113
  currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
@@ -143,12 +145,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
143
145
  tools: availableTools,
144
146
  maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
145
147
  ...providerSettings,
146
- stopWhen: stepCountIs(MAIN_STEP_LIMIT),
147
- experimental_context: toolExecutionContext,
148
+ stopWhen: isStepCount(MAIN_STEP_LIMIT),
149
+ runtimeContext: toolExecutionContext,
150
+ toolsContext: toolsContextFor(availableTools, toolExecutionContext),
148
151
  prepareStep({ steps, messages }) {
149
152
  const toolCalls = steps.flatMap(step => step.toolCalls);
150
153
  const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
151
- const scopedMessages = withScopedContextSystem(messages, toolExecutionContext);
154
+ const scopedMessages = withScopedContextControl(messages, toolExecutionContext);
152
155
  const messagesChanged = scopedMessages !== messages;
153
156
  if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
154
157
  return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
@@ -167,22 +170,26 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
167
170
  }
168
171
  return messagesChanged ? { messages: scopedMessages } : undefined;
169
172
  },
170
- onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
173
+ onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
174
+ completedSteps++;
175
+ completedToolCalls += toolCalls.length;
176
+ if (toolCalls.length > 0 && text.trim().length === 0)
177
+ completedToolOnlySteps++;
171
178
  if (Array.isArray(response?.messages) && response.messages.length > 0)
172
179
  latestAccumulatedResponseMessages = response.messages;
173
180
  const stepUsage = stepCacheMetrics(usage);
174
181
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, 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 } });
175
182
  callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
176
183
  },
177
- onFinish(event) {
178
- const providerUsage = extractUsage({ usage: event.totalUsage ?? event.usage });
184
+ onEnd(event) {
185
+ const providerUsage = extractUsage({ usage: event.usage });
179
186
  callbacks.recordTokenUsage?.({
180
187
  inputTokens: providerUsage.inputTokens,
181
188
  outputTokens: providerUsage.outputTokens,
182
189
  systemPrompt: inputBreakdown.systemPrompt,
183
190
  messages: inputBreakdown.messages,
184
191
  toolSchemas: inputBreakdown.toolSchemas,
185
- outputEstimate: estimateValueTokens(event.response.messages),
192
+ outputEstimate: estimateValueTokens(event.responseMessages),
186
193
  cacheReadTokens: providerUsage.cacheReadTokens,
187
194
  cacheWriteTokens: providerUsage.cacheWriteTokens,
188
195
  noCacheTokens: providerUsage.noCacheTokens,
@@ -190,7 +197,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
190
197
  logicalInputEstimate: inputBreakdown.logicalInputEstimate,
191
198
  effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
192
199
  });
193
- const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
200
+ const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
194
201
  const compacted = compactToolHistory(accumulated);
195
202
  callbacks.setConversation(compacted.messages);
196
203
  callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
@@ -198,10 +205,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
198
205
  });
199
206
  resetIdleTimer();
200
207
  const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
201
- for await (const part of result.fullStream) {
208
+ for await (const part of result.stream) {
202
209
  resetIdleTimer();
203
210
  switch (part.type) {
204
211
  case 'text-delta': {
212
+ callbacks.setBusyLabel?.(thinkingLabel);
205
213
  toolDisplay.startFreshToolGroup();
206
214
  const delta = sanitizeAssistantText(part.text);
207
215
  assistantText += delta;
@@ -231,6 +239,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
231
239
  const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
232
240
  latestToolCalls.set(part.id, toolCall);
233
241
  startedTools.set(part.id, Date.now());
242
+ callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
234
243
  toolDisplay.ensureToolItem(toolCall);
235
244
  break;
236
245
  }
@@ -245,6 +254,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
245
254
  latestToolCalls.set(part.toolCallId, toolCall);
246
255
  if (!startedTools.has(part.toolCallId))
247
256
  startedTools.set(part.toolCallId, Date.now());
257
+ callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
248
258
  toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
249
259
  toolDisplay.updateToolGroup(true);
250
260
  break;
@@ -253,15 +263,16 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
253
263
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
254
264
  latestToolCalls.set(part.toolCallId, toolCall);
255
265
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
256
- const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
266
+ const ok = toolOutputOk(part.output, true);
267
+ lastToolOk = ok;
268
+ const finish = { toolCall, success: ok, output: part.output, durationMs: Date.now() - startedAt };
257
269
  const item = toolDisplay.ensureToolItem(toolCall);
258
- item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
270
+ item.status = ok ? 'success' : 'error';
259
271
  item.result = toolResultSummary(finish);
260
272
  item.durationMs = finish.durationMs;
261
273
  item.finishedAt = startedAt + finish.durationMs;
262
- callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs }));
263
- 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 } });
264
- const ok = toolOutputOk(part.output, true);
274
+ callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: ok, output: part.output, durationMs: finish.durationMs }));
275
+ 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 } });
265
276
  toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
266
277
  observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
267
278
  callbacks.setWorkState?.(goal);
@@ -279,6 +290,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
279
290
  const existing = latestToolCalls.get(part.toolCallId);
280
291
  const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
281
292
  const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
293
+ lastToolOk = false;
282
294
  const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
283
295
  const item = toolDisplay.ensureToolItem(toolCall);
284
296
  item.status = 'error';
@@ -302,15 +314,20 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
302
314
  break;
303
315
  case 'finish':
304
316
  streamFinished = true;
317
+ finishReason = part.finishReason;
305
318
  callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
306
319
  break;
307
320
  default:
308
321
  break;
309
322
  }
310
323
  }
324
+ if (streamError && !streamFinished) {
325
+ void Promise.resolve(result.responseMessages).catch(() => undefined);
326
+ throw streamError;
327
+ }
311
328
  try {
312
- const response = await result.response;
313
- const completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
329
+ const responseMessages = await result.responseMessages;
330
+ const completedConversation = [...stripSyntheticControls(requestMessages), ...responseMessages];
314
331
  callbacks.setConversation(compactToolHistory(completedConversation).messages);
315
332
  }
316
333
  catch (error) {
@@ -327,13 +344,17 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
327
344
  finalizeAssistantSegment();
328
345
  }
329
346
  else if (latestToolCalls.size > 0) {
330
- const fallback = 'Finished tool work.';
331
- callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
347
+ callbacks.addMessage({ role: 'system', text: 'Tool work ended without a substantive final answer.' });
332
348
  }
349
+ const budgetReached = finishReason === 'length'
350
+ || completedSteps >= MAIN_STEP_LIMIT
351
+ || completedToolCalls >= MAIN_TOOL_CALL_LIMIT
352
+ || completedToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT;
353
+ turnStatus = terminalTurnStatus({ aborted: false, assistantText, sawToolCall: latestToolCalls.size > 0, lastToolOk, finishReason, budgetReached });
333
354
  goal.phase = 'done';
334
- goal.status = 'complete';
355
+ goal.status = turnStatus === 'complete' ? 'complete' : 'blocked';
356
+ callbacks.setWorkState?.(goal);
335
357
  callbacks.setGoalStatus?.(undefined);
336
- turnStatus = 'complete';
337
358
  }
338
359
  catch (error) {
339
360
  if (abortController.signal.aborted) {
@@ -349,7 +370,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
349
370
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
350
371
  if (compacted) {
351
372
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
352
- return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session, modelOverride);
373
+ return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
353
374
  }
354
375
  callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
355
376
  }
@@ -358,12 +379,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
358
379
  const delay = retryDelayMs(retryAttempt);
359
380
  callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
360
381
  callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
361
- await abortableDelay(delay, abortController.signal);
362
- if (abortController.signal.aborted) {
363
- turnStatus = 'aborted';
364
- return { status: turnStatus };
365
- }
366
- return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session, modelOverride);
382
+ return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
367
383
  }
368
384
  callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
369
385
  }
@@ -375,10 +391,42 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
375
391
  clearTimeout(idleTimer);
376
392
  toolDisplay.stopToolTimer();
377
393
  toolDisplay.finalizeToolGroup();
378
- callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
394
+ }
395
+ return { status: turnStatus };
396
+ }
397
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
398
+ const abortController = new AbortController();
399
+ let status = 'failed';
400
+ callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
401
+ callbacks.setBusy(true);
402
+ callbacks.setAbortController?.(abortController);
403
+ if (!retryingExistingRequest)
404
+ callbacks.addMessage({ role: 'user', text: displayValue ?? value });
405
+ try {
406
+ let attempt = retryAttempt;
407
+ let overflowRecovered = contextOverflowRecovered;
408
+ let retrying = retryingExistingRequest;
409
+ while (true) {
410
+ const result = await runAgentAttempt(value, contextFiles, callbacks, attempt, retrying, overflowRecovered, session, modelOverride, abortController);
411
+ status = result.status;
412
+ if (!result.retry)
413
+ break;
414
+ attempt = result.retry.attempt;
415
+ overflowRecovered = result.retry.contextOverflowRecovered;
416
+ retrying = true;
417
+ if (result.retry.delayMs > 0)
418
+ await abortableDelay(result.retry.delayMs, abortController.signal);
419
+ if (abortController.signal.aborted) {
420
+ status = 'aborted';
421
+ break;
422
+ }
423
+ }
424
+ return { status };
425
+ }
426
+ finally {
427
+ callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status }));
379
428
  callbacks.setAbortController?.(null);
380
- callbacks.setBusyLabel?.('Haze is thinking');
429
+ callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
381
430
  callbacks.setBusy(false);
382
431
  }
383
- return { status: turnStatus };
384
432
  }
@@ -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
  }
@@ -96,7 +96,8 @@ export function mcpActionSuggestions(settings, selectedMcpName) {
96
96
  const result = [];
97
97
  if (server) {
98
98
  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' });
99
+ if (server.transport !== 'stdio')
100
+ result.push({ value: MCP_ACTIONS.setApiKey, description: server.headers?.length ? 'update the saved API key' : 'add an API key', kind: 'mcp' });
100
101
  }
101
102
  result.push({ value: MCP_ACTIONS.removeServer, description: 'remove this server', kind: 'mcp' });
102
103
  return result;
@@ -118,7 +119,7 @@ export function mcpTransportSuggestions() {
118
119
  ];
119
120
  }
120
121
  export function skillsSuggestions(settings, skills) {
121
- return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for Haze to generate', kind: 'skill' },
122
+ return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for haze to generate', kind: 'skill' },
122
123
  ...skills.map(skill => ({
123
124
  value: skill.name,
124
125
  description: `${skill.description}${isSkillEnabled(settings, skill.name) ? '' : ' · disabled'}`,