@denizokcu/haze 0.4.0 → 0.6.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.
- package/CHANGELOG.md +45 -1
- package/README.md +68 -36
- package/dist/cli/commands/chat.d.ts +1 -1
- package/dist/cli/commands/chat.js +789 -106
- package/dist/cli/commands/commands.d.ts +2 -1
- package/dist/cli/commands/commands.js +77 -102
- package/dist/cli/commands/formatters.d.ts +27 -0
- package/dist/cli/commands/formatters.js +137 -0
- package/dist/cli/commands/streaming.d.ts +14 -13
- package/dist/cli/commands/streaming.js +399 -665
- package/dist/config/contextFiles.d.ts +6 -0
- package/dist/config/contextFiles.js +47 -16
- package/dist/config/lspSettings.d.ts +16 -0
- package/dist/config/lspSettings.js +98 -0
- package/dist/config/mcpSettings.d.ts +24 -0
- package/dist/config/mcpSettings.js +100 -0
- package/dist/config/providers.d.ts +2 -5
- package/dist/config/providers.js +16 -12
- package/dist/config/settings.d.ts +34 -0
- package/dist/config/skillSettings.d.ts +15 -0
- package/dist/config/skillSettings.js +31 -0
- package/dist/config/updateCheck.d.ts +44 -0
- package/dist/config/updateCheck.js +83 -0
- package/dist/core/agent/requestAssembly.js +12 -1
- package/dist/core/agent/toolOutputStore.d.ts +6 -1
- package/dist/core/agent/toolOutputStore.js +33 -1
- package/dist/core/bashOutput/ansi.d.ts +1 -0
- package/dist/core/bashOutput/ansi.js +7 -0
- package/dist/core/bashOutput/command.d.ts +2 -0
- package/dist/core/bashOutput/command.js +62 -0
- package/dist/core/bashOutput/lineFilter.d.ts +25 -0
- package/dist/core/bashOutput/lineFilter.js +62 -0
- package/dist/core/bashOutput/reducers/content.d.ts +3 -0
- package/dist/core/bashOutput/reducers/content.js +134 -0
- package/dist/core/bashOutput/reducers/git.d.ts +1 -0
- package/dist/core/bashOutput/reducers/git.js +147 -0
- package/dist/core/bashOutput/reducers/search.d.ts +7 -0
- package/dist/core/bashOutput/reducers/search.js +76 -0
- package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
- package/dist/core/bashOutput/reducers/validation.js +41 -0
- package/dist/core/bashOutput/registry.d.ts +4 -0
- package/dist/core/bashOutput/registry.js +126 -0
- package/dist/core/bashOutput/types.d.ts +46 -0
- package/dist/core/bashOutput/types.js +1 -0
- package/dist/core/goal/completionPolicy.d.ts +1 -0
- package/dist/core/goal/completionPolicy.js +4 -0
- package/dist/core/safety/urlGuard.d.ts +37 -0
- package/dist/core/safety/urlGuard.js +206 -0
- package/dist/core/subagent/subagentRunner.d.ts +1 -1
- package/dist/core/subagent/subagentRunner.js +2 -2
- package/dist/core/toolOutput/reduction.d.ts +25 -0
- package/dist/core/toolOutput/reduction.js +23 -0
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +6 -4
- package/dist/llm/hazeTools.d.ts +133 -16
- package/dist/llm/hazeTools.js +205 -31
- package/dist/llm/initPrompt.js +2 -1
- package/dist/llm/lsp.d.ts +64 -0
- package/dist/llm/lsp.js +241 -0
- package/dist/llm/lspTools.d.ts +122 -0
- package/dist/llm/lspTools.js +115 -0
- package/dist/llm/mcp.d.ts +19 -0
- package/dist/llm/mcp.js +64 -0
- package/dist/llm/requestContext.d.ts +28 -0
- package/dist/llm/requestContext.js +56 -0
- package/dist/llm/systemPrompt.d.ts +4 -1
- package/dist/llm/systemPrompt.js +11 -3
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/webFetch.d.ts +57 -0
- package/dist/llm/webFetch.js +270 -0
- package/dist/skills/builder/SkillBuilder.js +23 -44
- package/dist/ui/components/MarkdownText.d.ts +2 -0
- package/dist/ui/components/MarkdownText.js +116 -3
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/utils/version.d.ts +20 -0
- package/dist/utils/version.js +72 -0
- package/package.json +18 -10
- package/dist/cli/commands/skills.d.ts +0 -4
- package/dist/cli/commands/skills.js +0 -38
|
@@ -1,25 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ToolLoopAgent, stepCountIs } from 'ai';
|
|
2
2
|
import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
|
|
3
3
|
import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { buildSkillTools } from '../../skills/skillTools.js';
|
|
8
|
-
import { compact, toolCallSummary, toolResultSummary, formatElapsedTime, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
|
|
9
|
-
import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
|
|
10
|
-
import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
11
|
-
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
4
|
+
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
5
|
+
import { closeMcpClients } from '../../llm/mcp.js';
|
|
6
|
+
import { compact, toolCallSummary, toolResultSummary, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
|
|
12
7
|
import { agentEvent } from '../../core/agent/events.js';
|
|
13
8
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
14
|
-
import {
|
|
9
|
+
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
10
|
+
import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
15
11
|
import { contextBreakdown, cacheHitRatio, effectiveNonCachedInput, estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
16
|
-
import { compactToolHistory, stripSyntheticControls,
|
|
12
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
|
|
17
13
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
18
|
-
import {
|
|
14
|
+
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
19
15
|
function stableToolKey(toolCall) {
|
|
20
16
|
return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
|
|
21
17
|
}
|
|
22
|
-
function uniqueRepeatedToolNames(toolCalls) {
|
|
18
|
+
export function uniqueRepeatedToolNames(toolCalls) {
|
|
23
19
|
const seen = new Set();
|
|
24
20
|
const repeated = new Set();
|
|
25
21
|
for (const toolCall of toolCalls) {
|
|
@@ -30,7 +26,7 @@ function uniqueRepeatedToolNames(toolCalls) {
|
|
|
30
26
|
}
|
|
31
27
|
return [...repeated];
|
|
32
28
|
}
|
|
33
|
-
function toolOnlyStepCount(steps) {
|
|
29
|
+
export function toolOnlyStepCount(steps) {
|
|
34
30
|
let count = 0;
|
|
35
31
|
for (const step of [...steps].reverse()) {
|
|
36
32
|
if (step.toolCalls.length === 0 || step.text.trim().length > 0)
|
|
@@ -50,8 +46,74 @@ function hideSyntheticToolCallMarkup(text) {
|
|
|
50
46
|
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
|
|
51
47
|
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
|
|
52
48
|
}
|
|
49
|
+
function isWordChar(char) {
|
|
50
|
+
return char.toLowerCase() !== char.toUpperCase() || (char >= '0' && char <= '9');
|
|
51
|
+
}
|
|
52
|
+
function wordCount(text) {
|
|
53
|
+
let count = 0;
|
|
54
|
+
let inWord = false;
|
|
55
|
+
for (const char of text) {
|
|
56
|
+
if (isWordChar(char)) {
|
|
57
|
+
if (!inWord)
|
|
58
|
+
count += 1;
|
|
59
|
+
inWord = true;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
inWord = false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return count;
|
|
66
|
+
}
|
|
67
|
+
function endsWithSentenceBoundary(text) {
|
|
68
|
+
const trimmed = text.trim();
|
|
69
|
+
if (!trimmed || wordCount(trimmed) === 0)
|
|
70
|
+
return false;
|
|
71
|
+
const last = trimmed.at(-1) ?? '';
|
|
72
|
+
return last === '.' || last === '!' || last === '?' || last === ':' || last === ';' || last === ')';
|
|
73
|
+
}
|
|
53
74
|
function isNonSubstantiveAssistantText(text) {
|
|
54
|
-
return
|
|
75
|
+
return wordCount(text) === 0;
|
|
76
|
+
}
|
|
77
|
+
function isSubstantiveAssistantText(text) {
|
|
78
|
+
const trimmed = text.trim();
|
|
79
|
+
const words = wordCount(trimmed);
|
|
80
|
+
if (words === 0)
|
|
81
|
+
return false;
|
|
82
|
+
if (trimmed.length >= 24)
|
|
83
|
+
return true;
|
|
84
|
+
if (endsWithSentenceBoundary(trimmed))
|
|
85
|
+
return true;
|
|
86
|
+
return words >= 4;
|
|
87
|
+
}
|
|
88
|
+
function isIncompleteAssistantFragment(text) {
|
|
89
|
+
const trimmed = text.trim();
|
|
90
|
+
return !isSubstantiveAssistantText(trimmed) && wordCount(trimmed) <= 2 && !endsWithSentenceBoundary(trimmed);
|
|
91
|
+
}
|
|
92
|
+
function isLikelyUnfinishedMarkdownFragment(text) {
|
|
93
|
+
const trimmed = text.trim();
|
|
94
|
+
if (!trimmed.includes('\n'))
|
|
95
|
+
return false;
|
|
96
|
+
const last = trimmed.at(-1) ?? '';
|
|
97
|
+
return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
|
|
98
|
+
}
|
|
99
|
+
export function isShortUnfinishedBridgeBeforeTool(text) {
|
|
100
|
+
const trimmed = text.trim();
|
|
101
|
+
return trimmed.length > 0 && wordCount(trimmed) <= 12 && !endsWithSentenceBoundary(trimmed) && !isLikelyUnfinishedMarkdownFragment(trimmed);
|
|
102
|
+
}
|
|
103
|
+
function isHiddenAssistantText(text) {
|
|
104
|
+
return text.length === 0 || isNonSubstantiveAssistantText(text);
|
|
105
|
+
}
|
|
106
|
+
function isHiddenAssistantFragment(text) {
|
|
107
|
+
return isHiddenAssistantText(text) || isIncompleteAssistantFragment(text) || isLikelyUnfinishedMarkdownFragment(text);
|
|
108
|
+
}
|
|
109
|
+
export function isHiddenUnstartedFinalText(text) {
|
|
110
|
+
return isHiddenAssistantText(text) || isLikelyUnfinishedMarkdownFragment(text);
|
|
111
|
+
}
|
|
112
|
+
const ASSISTANT_STREAM_DEBOUNCE_MS = 200;
|
|
113
|
+
export function shouldStartAssistantStream(text, startedAt) {
|
|
114
|
+
if (isHiddenAssistantFragment(text))
|
|
115
|
+
return false;
|
|
116
|
+
return isSubstantiveAssistantText(text) || Date.now() - startedAt >= ASSISTANT_STREAM_DEBOUNCE_MS;
|
|
55
117
|
}
|
|
56
118
|
function assistantDisplayText(text) {
|
|
57
119
|
return hideSyntheticToolCallMarkup(text).trim();
|
|
@@ -88,12 +150,8 @@ async function abortableDelay(milliseconds, signal) {
|
|
|
88
150
|
const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
89
151
|
const IDLE_TIMEOUT_MS = 5 * 60_000;
|
|
90
152
|
const MAIN_STEP_LIMIT = 64;
|
|
91
|
-
const MAIN_TOOL_CALL_LIMIT =
|
|
153
|
+
const MAIN_TOOL_CALL_LIMIT = 120;
|
|
92
154
|
const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
|
|
93
|
-
const FOLLOW_UP_STEP_LIMIT = 64;
|
|
94
|
-
const FOLLOW_UP_TOOL_CALL_LIMIT = 40;
|
|
95
|
-
const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
|
|
96
|
-
const COMPLETION_CONTINUATION_LIMIT = 12;
|
|
97
155
|
const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
|
|
98
156
|
function toolOutputOk(output, success) {
|
|
99
157
|
if (!success)
|
|
@@ -114,110 +172,178 @@ function logEntry(log, entry) {
|
|
|
114
172
|
if (log)
|
|
115
173
|
void logAppend(log, entry).catch(() => undefined);
|
|
116
174
|
}
|
|
117
|
-
function
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
175
|
+
function responseCompletionMetrics(text, generationStartedAt) {
|
|
176
|
+
const finishedAt = Date.now();
|
|
177
|
+
const elapsedSeconds = Math.max((finishedAt - generationStartedAt) / 1000, 0.001);
|
|
178
|
+
const outputTokens = estimateValueTokens(text);
|
|
179
|
+
return {
|
|
180
|
+
finishedAt,
|
|
181
|
+
tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
|
|
182
|
+
};
|
|
124
183
|
}
|
|
125
184
|
function extractUsage(event) {
|
|
126
185
|
const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
127
|
-
const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
|
|
128
|
-
? (event.usage?.inputTokenDetails).noCacheTokens
|
|
129
|
-
: undefined;
|
|
130
186
|
return {
|
|
131
187
|
inputTokens: event.usage?.inputTokens,
|
|
132
188
|
outputTokens: event.usage?.outputTokens,
|
|
133
189
|
cacheReadTokens,
|
|
134
190
|
cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
|
|
135
|
-
noCacheTokens:
|
|
191
|
+
noCacheTokens: event.usage?.inputTokenDetails?.noCacheTokens ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
|
|
136
192
|
reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
|
|
137
193
|
};
|
|
138
194
|
}
|
|
195
|
+
function subagentTokenEstimate(output) {
|
|
196
|
+
if (typeof output !== 'object' || output == null || !('tokens' in output))
|
|
197
|
+
return undefined;
|
|
198
|
+
const tokens = output.tokens;
|
|
199
|
+
const input = typeof tokens?.in === 'number' ? tokens.in : 0;
|
|
200
|
+
const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
|
|
201
|
+
return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
|
|
202
|
+
}
|
|
203
|
+
function rememberContextFilesFromToolOutput(activeContextFiles, output) {
|
|
204
|
+
if (typeof output !== 'object' || output == null)
|
|
205
|
+
return activeContextFiles;
|
|
206
|
+
const files = output.applicableProjectInstructions;
|
|
207
|
+
if (!Array.isArray(files))
|
|
208
|
+
return activeContextFiles;
|
|
209
|
+
const seen = new Set(activeContextFiles.map(file => file.path));
|
|
210
|
+
const next = [...activeContextFiles];
|
|
211
|
+
for (const file of files) {
|
|
212
|
+
if (typeof file !== 'object' || file == null)
|
|
213
|
+
continue;
|
|
214
|
+
const candidate = file;
|
|
215
|
+
if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
|
|
216
|
+
continue;
|
|
217
|
+
next.push({ path: candidate.path, content: candidate.content });
|
|
218
|
+
seen.add(candidate.path);
|
|
219
|
+
}
|
|
220
|
+
return next;
|
|
221
|
+
}
|
|
139
222
|
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
|
|
140
223
|
const displayVal = displayValue ?? value;
|
|
141
|
-
const userMessage = { role: 'user', text: displayVal };
|
|
142
224
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
143
225
|
callbacks.setBusy(true);
|
|
226
|
+
callbacks.setBusyLabel?.('Haze is thinking');
|
|
144
227
|
if (!retryingExistingRequest)
|
|
145
|
-
callbacks.addMessage(
|
|
228
|
+
callbacks.addMessage({ role: 'user', text: displayVal });
|
|
146
229
|
const abortController = new AbortController();
|
|
147
230
|
callbacks.setAbortController?.(abortController);
|
|
148
231
|
let turnStatus = 'failed';
|
|
149
|
-
let turnStopReason;
|
|
150
232
|
let idleTimer;
|
|
151
|
-
let
|
|
233
|
+
let loadedMcp;
|
|
152
234
|
const resetIdleTimer = () => {
|
|
153
235
|
if (idleTimer)
|
|
154
236
|
clearTimeout(idleTimer);
|
|
155
237
|
idleTimer = setTimeout(() => {
|
|
156
|
-
turnStopReason = { kind: 'idle_timeout', message: `Stopped after ${Math.round(IDLE_TIMEOUT_MS / 60_000)} minutes of no activity. Type "continue" to resume — Haze will pick up where it left off.` };
|
|
157
238
|
abortController.abort('Haze turn timed out after no model/tool activity.');
|
|
158
239
|
}, IDLE_TIMEOUT_MS);
|
|
159
240
|
};
|
|
241
|
+
const createToolGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false, finalized: false });
|
|
242
|
+
let toolGroup = createToolGroup();
|
|
243
|
+
let toolTimer;
|
|
244
|
+
const renderToolGroup = (group = toolGroup) => {
|
|
245
|
+
const running = group.items.some(item => item.status === 'running');
|
|
246
|
+
const failures = group.items.filter(item => item.status === 'error').length;
|
|
247
|
+
const changes = group.items.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary)).length;
|
|
248
|
+
const elapsedMs = group.items.length > 0
|
|
249
|
+
? (running ? Date.now() : Math.max(...group.items.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...group.items.map(item => item.startedAt))
|
|
250
|
+
: 0;
|
|
251
|
+
const summaryParts = [`${group.items.length} calls`, `${changes} changes`];
|
|
252
|
+
if (failures > 0)
|
|
253
|
+
summaryParts.push(`${failures} failed`);
|
|
254
|
+
summaryParts.push(formatElapsedTimeWhole(elapsedMs));
|
|
255
|
+
return [summaryParts.join(' · '), ...group.items.map(item => {
|
|
256
|
+
const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
|
|
257
|
+
const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
|
|
258
|
+
return ` ${icon} ${item.summary}${result}`;
|
|
259
|
+
})].join('\n');
|
|
260
|
+
};
|
|
261
|
+
const updateToolGroup = (streaming = true, group = toolGroup) => {
|
|
262
|
+
const text = renderToolGroup(group);
|
|
263
|
+
if (!group.started) {
|
|
264
|
+
group.started = true;
|
|
265
|
+
group.finalized = !streaming;
|
|
266
|
+
callbacks.addMessage({ id: group.id, role: 'tool', text, streaming });
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
group.finalized = !streaming;
|
|
270
|
+
callbacks.updateMessage(group.id, { text, streaming });
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const finalizeToolGroup = (group = toolGroup) => {
|
|
274
|
+
if (!group.started || group.finalized)
|
|
275
|
+
return;
|
|
276
|
+
updateToolGroup(false, group);
|
|
277
|
+
};
|
|
278
|
+
const startFreshToolGroup = () => {
|
|
279
|
+
if (!toolGroup.started || toolGroup.items.some(item => item.status === 'running'))
|
|
280
|
+
return;
|
|
281
|
+
finalizeToolGroup(toolGroup);
|
|
282
|
+
toolGroup = createToolGroup();
|
|
283
|
+
};
|
|
284
|
+
const stopToolTimer = () => {
|
|
285
|
+
if (!toolTimer)
|
|
286
|
+
return;
|
|
287
|
+
clearInterval(toolTimer);
|
|
288
|
+
toolTimer = undefined;
|
|
289
|
+
};
|
|
290
|
+
const startToolTimer = () => {
|
|
291
|
+
if (toolTimer)
|
|
292
|
+
return;
|
|
293
|
+
toolTimer = setInterval(() => {
|
|
294
|
+
if (toolGroup.items.some(item => item.status === 'running'))
|
|
295
|
+
updateToolGroup(true);
|
|
296
|
+
else
|
|
297
|
+
stopToolTimer();
|
|
298
|
+
}, 1000);
|
|
299
|
+
};
|
|
300
|
+
const ensureToolItem = (toolCall) => {
|
|
301
|
+
if (toolGroup.finalized)
|
|
302
|
+
toolGroup = createToolGroup();
|
|
303
|
+
let item = toolGroup.items.find(candidate => candidate.id === toolCall.toolCallId);
|
|
304
|
+
if (!item) {
|
|
305
|
+
item = { id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() };
|
|
306
|
+
toolGroup.items.push(item);
|
|
307
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
|
|
308
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
309
|
+
callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
310
|
+
startToolTimer();
|
|
311
|
+
updateToolGroup(true);
|
|
312
|
+
}
|
|
313
|
+
return item;
|
|
314
|
+
};
|
|
160
315
|
try {
|
|
161
316
|
const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
|
|
162
|
-
if (!runtime
|
|
317
|
+
if (!runtime?.model) {
|
|
163
318
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
|
|
319
|
+
turnStatus = 'complete';
|
|
164
320
|
return;
|
|
165
321
|
}
|
|
322
|
+
let activeContextFiles = contextFiles;
|
|
166
323
|
const activeModel = runtime.model;
|
|
167
324
|
const providerSettings = providerRequestSettings(runtime.config);
|
|
168
|
-
const
|
|
169
|
-
const
|
|
170
|
-
|
|
325
|
+
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
|
|
326
|
+
const availableTools = assembled.availableTools;
|
|
327
|
+
loadedMcp = assembled.loadedMcp;
|
|
328
|
+
if (loadedMcp?.errors.length)
|
|
329
|
+
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
171
330
|
const goal = createSessionGoal(value);
|
|
172
331
|
callbacks.setWorkState?.(goal.workState);
|
|
173
332
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
174
333
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
175
|
-
const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
|
|
176
|
-
const likelyActionRequest = isActionRequest(value);
|
|
177
|
-
const likelyValidationRequest = isValidationRequest(value);
|
|
178
|
-
const planImplementationGuidance = 'Haze internal guidance for implementing plan files. The original user request remains authoritative. First identify the concrete required checklist items and compare them with the current files. Do not edit source or tests when the required behavior is already present. Implement the smallest clearly required phase or required items, skip optional/design-question items unless explicitly requested, add tests rather than exploratory one-off scripts where possible, prefer file tools for source changes, run validation once after code/test edits, then update plan status with file tools if requested. Do not call unresolved optional scope a blocker.';
|
|
179
334
|
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
180
335
|
? stripSyntheticControls(callbacks.getConversation())
|
|
181
336
|
: [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
|
|
182
|
-
let requestMessages =
|
|
183
|
-
? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
|
|
184
|
-
: durableRequestMessages;
|
|
337
|
+
let requestMessages = durableRequestMessages;
|
|
185
338
|
if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
|
|
186
339
|
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages;
|
|
187
340
|
}
|
|
188
341
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
let currentAssistantStarted = false;
|
|
193
|
-
let currentAssistantStartedAt = Date.now();
|
|
194
|
-
let currentAssistantText = '';
|
|
195
|
-
let assistantText = '';
|
|
196
|
-
let toolEpoch = 0;
|
|
197
|
-
let currentAssistantToolEpoch = 0;
|
|
198
|
-
let editFileFailed = false;
|
|
199
|
-
let mutatingToolSucceeded = false;
|
|
200
|
-
let validationToolSucceeded = false;
|
|
201
|
-
let validationToolFailed = false;
|
|
202
|
-
let sawReadOnlyTool = false;
|
|
203
|
-
let sawToolCall = false;
|
|
204
|
-
let textAfterTool = false;
|
|
205
|
-
let completionContinuationCount = 0;
|
|
206
|
-
const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
|
|
207
|
-
const recentStepTextSignatures = [];
|
|
208
|
-
let consecutiveTextOnlySteps = 0;
|
|
209
|
-
let repetitionAbortFired = false;
|
|
210
|
-
const toolCallSignatureCounts = new Map();
|
|
211
|
-
const TOOL_REPETITION_THRESHOLD = 3;
|
|
212
|
-
let latestAccumulatedResponseMessages = [];
|
|
213
|
-
let editRecoveryPath;
|
|
214
|
-
let editRecoveryReasonCode;
|
|
215
|
-
let editRecoveryReadSatisfied = false;
|
|
216
|
-
const toolSummaries = [];
|
|
217
|
-
const visibleAssistantTexts = new Set();
|
|
342
|
+
const systemPrompt = assembled.systemPrompt;
|
|
343
|
+
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
344
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
218
345
|
const previousAssistantText = normalizeAssistantText(callbacks.getLastAssistantText());
|
|
219
|
-
|
|
220
|
-
visibleAssistantTexts.add(previousAssistantText);
|
|
346
|
+
const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
|
|
221
347
|
const rememberVisibleAssistantText = (text) => {
|
|
222
348
|
const normalized = normalizeAssistantText(text);
|
|
223
349
|
if (!normalized)
|
|
@@ -225,387 +351,78 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
225
351
|
visibleAssistantTexts.add(normalized);
|
|
226
352
|
callbacks.setLastAssistantText(text);
|
|
227
353
|
};
|
|
228
|
-
const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
354
|
+
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)) };
|
|
355
|
+
const startedTools = new Map();
|
|
356
|
+
const latestToolCalls = new Map();
|
|
357
|
+
let latestAccumulatedResponseMessages = [];
|
|
358
|
+
let currentAssistantId = `assistant-${Date.now()}`;
|
|
359
|
+
let assistantStarted = false;
|
|
360
|
+
let assistantStartedAt = Date.now();
|
|
361
|
+
let assistantText = '';
|
|
362
|
+
let currentAssistantText = '';
|
|
363
|
+
let streamError;
|
|
364
|
+
let streamFinished = false;
|
|
365
|
+
let mutatingToolSucceeded = false;
|
|
366
|
+
let editRecoveryPath;
|
|
367
|
+
let editRecoveryReadSatisfied = false;
|
|
368
|
+
const resetAssistantSegment = () => {
|
|
369
|
+
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
370
|
+
assistantStarted = false;
|
|
371
|
+
assistantStartedAt = Date.now();
|
|
372
|
+
currentAssistantText = '';
|
|
235
373
|
};
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
return;
|
|
246
|
-
clearInterval(toolTimer);
|
|
247
|
-
toolTimer = undefined;
|
|
248
|
-
}
|
|
249
|
-
function startToolTimer() {
|
|
250
|
-
if (toolTimer)
|
|
251
|
-
return;
|
|
252
|
-
toolTimer = setInterval(() => {
|
|
253
|
-
if (toolDisplayItems.some(item => item.status === 'running'))
|
|
254
|
-
updateToolGroup(true);
|
|
255
|
-
else
|
|
256
|
-
stopToolTimer();
|
|
257
|
-
}, 1000);
|
|
258
|
-
}
|
|
259
|
-
stopActiveTimers = stopToolTimer;
|
|
260
|
-
function renderToolGroup(streaming) {
|
|
261
|
-
const visibleItems = toolDisplayItems.filter(item => !item.hidden);
|
|
262
|
-
const running = visibleItems.some(item => item.status === 'running');
|
|
263
|
-
const failures = visibleItems.filter(item => item.status === 'error');
|
|
264
|
-
const changes = visibleItems.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary));
|
|
265
|
-
const compactItems = !running && visibleItems.length > 12
|
|
266
|
-
? [...new Map([...failures, ...changes].map(item => [item.id, item])).values()]
|
|
267
|
-
: visibleItems;
|
|
268
|
-
const grouped = new Map();
|
|
269
|
-
for (const item of compactItems) {
|
|
270
|
-
const key = `${item.status}:${item.summary}:${item.result ?? ''}`;
|
|
271
|
-
const current = grouped.get(key);
|
|
272
|
-
if (current)
|
|
273
|
-
current.count += 1;
|
|
274
|
-
else
|
|
275
|
-
grouped.set(key, { item, count: 1 });
|
|
276
|
-
}
|
|
277
|
-
const rows = [...grouped.values()];
|
|
278
|
-
const compactSuffix = !running && visibleItems.length > 12 ? ` · showing ${compactItems.length} important` : '';
|
|
279
|
-
const elapsedMs = visibleItems.length > 0
|
|
280
|
-
? (running ? Date.now() : Math.max(...visibleItems.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...visibleItems.map(item => item.startedAt))
|
|
281
|
-
: 0;
|
|
282
|
-
const elapsed = running || streaming ? formatElapsedTimeWhole(elapsedMs) : formatElapsedTime(elapsedMs);
|
|
283
|
-
const header = running || streaming
|
|
284
|
-
? `Running tools · ${elapsed}`
|
|
285
|
-
: `${visibleItems.length} call${visibleItems.length === 1 ? '' : 's'} · ${changes.length} change${changes.length === 1 ? '' : 's'} · ${failures.length} failed · ${elapsed}${compactSuffix}`;
|
|
286
|
-
const lines = [];
|
|
287
|
-
for (const { item, count } of rows) {
|
|
288
|
-
const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
|
|
289
|
-
const countText = count > 1 ? ` ×${count}` : '';
|
|
290
|
-
const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
|
|
291
|
-
lines.push(` ${icon} ${item.summary}${countText}${result}`);
|
|
292
|
-
if (item.diff && item.diff.length > 0 && (item.diffLineCount ?? item.diff.length) <= INLINE_DIFF_LINE_LIMIT) {
|
|
293
|
-
for (const diffLine of item.diff) {
|
|
294
|
-
const lineNumber = diffLine.type === 'add' ? diffLine.newLine : diffLine.oldLine;
|
|
295
|
-
const marker = diffLine.type === 'add' ? '+' : diffLine.type === 'remove' ? '-' : ' ';
|
|
296
|
-
lines.push(` ${String(lineNumber ?? '').padStart(5)} ${marker} ${diffLine.text}`);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
else if ((item.diffLineCount ?? 0) > INLINE_DIFF_LINE_LIMIT) {
|
|
300
|
-
lines.push(` diff hidden (${item.diffLineCount} changed lines; run git diff to inspect)`);
|
|
301
|
-
}
|
|
302
|
-
if (item.subItems && item.subItems.length > 0) {
|
|
303
|
-
for (const sub of item.subItems) {
|
|
304
|
-
const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
|
|
305
|
-
lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
return [header, ...lines].join('\n');
|
|
310
|
-
}
|
|
311
|
-
function updateToolGroup(streaming = true) {
|
|
312
|
-
const text = renderToolGroup(streaming);
|
|
313
|
-
if (!toolGroupStarted) {
|
|
314
|
-
toolGroupStarted = true;
|
|
315
|
-
callbacks.addMessage({ id: toolGroupId, role: 'tool', text, streaming });
|
|
316
|
-
}
|
|
317
|
-
else {
|
|
318
|
-
callbacks.updateMessage(toolGroupId, { text, streaming });
|
|
319
|
-
}
|
|
320
|
-
if (!streaming)
|
|
321
|
-
toolGroupFinalized = true;
|
|
322
|
-
}
|
|
323
|
-
function recordToolStart(toolCall) {
|
|
324
|
-
if (toolGroupFinalized) {
|
|
325
|
-
toolDisplayItems.length = 0;
|
|
326
|
-
toolGroupId = `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
327
|
-
toolGroupFinalized = false;
|
|
328
|
-
toolGroupStarted = false;
|
|
329
|
-
}
|
|
330
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
|
|
331
|
-
toolDisplayItems.push({ id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() });
|
|
332
|
-
startToolTimer();
|
|
333
|
-
updateToolGroup(true);
|
|
334
|
-
const runningSubagents = toolDisplayItems.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
|
|
335
|
-
if (runningSubagents > 0)
|
|
336
|
-
callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
|
|
337
|
-
}
|
|
338
|
-
function recordToolDisplayFinish(event) {
|
|
339
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs }));
|
|
340
|
-
const item = toolDisplayItems.find(candidate => candidate.id === event.toolCall.toolCallId);
|
|
341
|
-
if (!item)
|
|
342
|
-
return;
|
|
343
|
-
item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
|
|
344
|
-
item.result = toolResultSummary(event);
|
|
345
|
-
item.durationMs = event.durationMs;
|
|
346
|
-
item.finishedAt = item.startedAt + event.durationMs;
|
|
347
|
-
item.hidden = isDuplicateSkippedOutput(event.output);
|
|
348
|
-
if (typeof event.output === 'object' && event.output != null) {
|
|
349
|
-
const output = event.output;
|
|
350
|
-
if (typeof output.diffLineCount === 'number')
|
|
351
|
-
item.diffLineCount = output.diffLineCount;
|
|
352
|
-
if (Array.isArray(output.diff))
|
|
353
|
-
item.diff = output.diff;
|
|
354
|
-
}
|
|
355
|
-
if (event.toolCall.toolName === 'subagent' && typeof event.output === 'object' && event.output != null) {
|
|
356
|
-
const out = event.output;
|
|
357
|
-
if (Array.isArray(out.toolCalls)) {
|
|
358
|
-
item.subItems = out.toolCalls.map(tc => ({
|
|
359
|
-
name: tc.name,
|
|
360
|
-
summary: tc.summary,
|
|
361
|
-
durationMs: tc.durationMs,
|
|
362
|
-
}));
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
if (event.toolCall.toolName === 'writeTasks' && event.success) {
|
|
366
|
-
callbacks.onTasksChanged?.();
|
|
367
|
-
}
|
|
368
|
-
const hasRunningTools = toolDisplayItems.some(candidate => candidate.status === 'running');
|
|
369
|
-
updateToolGroup(hasRunningTools);
|
|
370
|
-
if (!hasRunningTools)
|
|
371
|
-
stopToolTimer();
|
|
372
|
-
const runningSubagents = toolDisplayItems.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
|
|
373
|
-
if (runningSubagents === 0)
|
|
374
|
-
callbacks.setBusyLabel?.('Haze is thinking');
|
|
375
|
-
else
|
|
376
|
-
callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
|
|
377
|
-
}
|
|
378
|
-
callbacks.debugLog(`request started with ${requestMessages.length} conversation messages; intent=${goal.normalizedIntent}; action=${likelyActionRequest}`);
|
|
379
|
-
function recordToolFinish(event) {
|
|
380
|
-
const path = toolInputPath(event.toolCall.input);
|
|
381
|
-
const duplicateSkipped = isDuplicateSkippedOutput(event.output);
|
|
382
|
-
const ok = toolOutputOk(event.output, event.success);
|
|
383
|
-
observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
|
|
384
|
-
callbacks.setWorkState?.(goal.workState);
|
|
385
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
386
|
-
if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
|
|
387
|
-
editFileFailed = true;
|
|
388
|
-
editRecoveryPath = path;
|
|
389
|
-
editRecoveryReasonCode = typeof event.output === 'object' && event.output != null && 'reasonCode' in event.output && typeof event.output.reasonCode === 'string' ? event.output.reasonCode : undefined;
|
|
390
|
-
editRecoveryReadSatisfied = false;
|
|
391
|
-
}
|
|
392
|
-
if (ok && ['listFiles', 'readFile'].includes(event.toolCall.toolName))
|
|
393
|
-
sawReadOnlyTool = true;
|
|
394
|
-
if (ok && event.toolCall.toolName === 'readFile' && path && path === editRecoveryPath && !duplicateSkipped) {
|
|
395
|
-
editRecoveryReadSatisfied = true;
|
|
396
|
-
}
|
|
397
|
-
if (ok && !duplicateSkipped && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
|
|
398
|
-
mutatingToolSucceeded = true;
|
|
399
|
-
if (!path || path === editRecoveryPath) {
|
|
400
|
-
editRecoveryPath = undefined;
|
|
401
|
-
editRecoveryReasonCode = undefined;
|
|
402
|
-
editRecoveryReadSatisfied = false;
|
|
403
|
-
editFileFailed = false;
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
if (event.success && event.toolCall.toolName === 'bash') {
|
|
407
|
-
if (ok)
|
|
408
|
-
validationToolSucceeded = true;
|
|
409
|
-
else
|
|
410
|
-
validationToolFailed = true;
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
|
|
414
|
-
callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
|
|
415
|
-
const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
416
|
-
const responseStarted = true;
|
|
417
|
-
const responseStartedAt = Date.now();
|
|
418
|
-
let responseText = '';
|
|
419
|
-
let continuationToolCalls = 0;
|
|
420
|
-
let followUpStreamError;
|
|
421
|
-
const prunedMessages = compactToolHistory(stripSyntheticControls(messages)).messages;
|
|
422
|
-
const compactedMessages = estimateValueTokens(prunedMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET
|
|
423
|
-
? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
|
|
424
|
-
: prunedMessages;
|
|
425
|
-
const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
|
|
426
|
-
const followUpSystemPrompt = buildSystemPrompt(contextFiles, session);
|
|
427
|
-
const followUpTools = allowTools ? availableTools : undefined;
|
|
428
|
-
const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles, messages: continuationMessages, tools: followUpTools });
|
|
429
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: `continuation:${reason}`, system: followUpSystemPrompt, messages: continuationMessages, tools: followUpTools ? Object.keys(followUpTools) : [], context: followUpInputBreakdown.breakdown });
|
|
430
|
-
const followUp = streamText({
|
|
431
|
-
model: activeModel,
|
|
432
|
-
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
433
|
-
system: followUpSystemPrompt,
|
|
434
|
-
messages: continuationMessages,
|
|
435
|
-
...toolRequestSettings(availableTools, allowTools),
|
|
436
|
-
...providerSettings,
|
|
437
|
-
stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
|
|
438
|
-
abortSignal: abortController.signal,
|
|
439
|
-
experimental_context: toolExecutionContext,
|
|
440
|
-
prepareStep({ steps, messages }) {
|
|
441
|
-
continuationToolCalls = steps.flatMap(step => step.toolCalls).length;
|
|
442
|
-
if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
|
|
443
|
-
return {
|
|
444
|
-
toolChoice: 'none',
|
|
445
|
-
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
446
|
-
};
|
|
447
|
-
}
|
|
448
|
-
if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
|
|
449
|
-
return {
|
|
450
|
-
toolChoice: 'none',
|
|
451
|
-
};
|
|
452
|
-
}
|
|
453
|
-
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
454
|
-
return {
|
|
455
|
-
activeTools: ['readFile'],
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
return undefined;
|
|
459
|
-
},
|
|
460
|
-
onError({ error }) {
|
|
461
|
-
followUpStreamError = error;
|
|
462
|
-
callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
463
|
-
},
|
|
464
|
-
onFinish(event) {
|
|
465
|
-
const providerUsage = extractUsage(event);
|
|
466
|
-
callbacks.recordTokenUsage?.({
|
|
467
|
-
inputTokens: providerUsage.inputTokens,
|
|
468
|
-
outputTokens: providerUsage.outputTokens,
|
|
469
|
-
systemPrompt: followUpInputBreakdown.systemPrompt,
|
|
470
|
-
messages: followUpInputBreakdown.messages,
|
|
471
|
-
toolSchemas: followUpInputBreakdown.toolSchemas,
|
|
472
|
-
outputEstimate: estimateValueTokens(event.response.messages),
|
|
473
|
-
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
474
|
-
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
475
|
-
noCacheTokens: providerUsage.noCacheTokens,
|
|
476
|
-
reasoningTokens: providerUsage.reasoningTokens,
|
|
477
|
-
logicalInputEstimate: followUpInputBreakdown.logicalInputEstimate,
|
|
478
|
-
effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
|
|
479
|
-
});
|
|
480
|
-
const nextConversation = [...stripSyntheticControls(compactedMessages), ...event.response.messages];
|
|
481
|
-
callbacks.setConversation(nextConversation);
|
|
482
|
-
callbacks.debugLog(`conversation updated to ${nextConversation.length} messages after follow-up`);
|
|
483
|
-
},
|
|
484
|
-
experimental_onToolCallStart({ toolCall }) {
|
|
485
|
-
sawToolCall = true;
|
|
486
|
-
recordToolStart(toolCall);
|
|
487
|
-
resetIdleTimer();
|
|
488
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: `continuation:${reason}`, toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
489
|
-
callbacks.debugLog(`follow-up tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
490
|
-
const sig = stableToolKey(toolCall);
|
|
491
|
-
const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
|
|
492
|
-
toolCallSignatureCounts.set(sig, count);
|
|
493
|
-
if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
|
|
494
|
-
repetitionAbortFired = true;
|
|
495
|
-
turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
|
|
496
|
-
const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
|
|
497
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: `continuation:${reason}`, text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
|
|
498
|
-
callbacks.debugLog(`tool repetition guard abort (continuation): ${toolCall.toolName} count=${count}`);
|
|
499
|
-
abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
|
|
500
|
-
}
|
|
501
|
-
},
|
|
502
|
-
experimental_onToolCallFinish(event) {
|
|
503
|
-
resetIdleTimer();
|
|
504
|
-
recordToolFinish(event);
|
|
505
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: `continuation:${reason}`, toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
|
|
506
|
-
const nestedTokens = subagentTokenEstimate(event.output);
|
|
507
|
-
if (nestedTokens)
|
|
508
|
-
callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
|
|
509
|
-
const summary = toolResultSummary(event);
|
|
510
|
-
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
511
|
-
recordToolDisplayFinish(event);
|
|
512
|
-
if (!isDuplicateSkippedOutput(event.output))
|
|
513
|
-
toolEpoch += 1;
|
|
514
|
-
callbacks.debugLog(event.success
|
|
515
|
-
? `follow-up tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
|
|
516
|
-
: `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
517
|
-
},
|
|
518
|
-
});
|
|
519
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
|
|
520
|
-
callbacks.addMessage({ id: responseId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: responseStartedAt });
|
|
521
|
-
for await (const rawDelta of followUp.textStream) {
|
|
522
|
-
resetIdleTimer();
|
|
523
|
-
const delta = sanitizeAssistantText(rawDelta);
|
|
524
|
-
responseText += delta;
|
|
525
|
-
const displayText = assistantDisplayText(responseText);
|
|
526
|
-
if (!displayText || isNonSubstantiveAssistantText(displayText) || isPrefixOfVisibleAssistantText(displayText))
|
|
527
|
-
continue;
|
|
528
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
|
|
529
|
-
callbacks.updateMessage(responseId, { text: displayText });
|
|
530
|
-
}
|
|
531
|
-
try {
|
|
532
|
-
await followUp.response;
|
|
533
|
-
}
|
|
534
|
-
catch (error) {
|
|
535
|
-
throw followUpStreamError ?? error;
|
|
374
|
+
const finalizeAssistantSegment = (options = {}) => {
|
|
375
|
+
const finalText = assistantDisplayText(currentAssistantText);
|
|
376
|
+
const normalized = normalizeAssistantText(finalText);
|
|
377
|
+
const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText)) || (options.beforeTool === true && isShortUnfinishedBridgeBeforeTool(finalText)) || (normalized.length > 0 && visibleAssistantTexts.has(normalized));
|
|
378
|
+
if (assistantStarted) {
|
|
379
|
+
if (!hidden)
|
|
380
|
+
rememberVisibleAssistantText(finalText);
|
|
381
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden }));
|
|
382
|
+
callbacks.updateMessage(currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
536
383
|
}
|
|
537
|
-
|
|
538
|
-
const visibleFinalText = finalText;
|
|
539
|
-
const hidden = visibleFinalText.length === 0 || isNonSubstantiveAssistantText(visibleFinalText) || isDuplicateVisibleAssistantText(visibleFinalText);
|
|
540
|
-
if (responseStarted) {
|
|
384
|
+
else if (!hidden) {
|
|
541
385
|
if (!hidden)
|
|
542
|
-
rememberVisibleAssistantText(
|
|
543
|
-
callbacks.onEvent?.(agentEvent({ type: '
|
|
544
|
-
callbacks.
|
|
386
|
+
rememberVisibleAssistantText(finalText);
|
|
387
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
388
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden: false }));
|
|
389
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
545
390
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles, messages: requestMessages, tools: availableTools });
|
|
552
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
|
|
553
|
-
const result = streamText({
|
|
391
|
+
resetAssistantSegment();
|
|
392
|
+
return !hidden;
|
|
393
|
+
};
|
|
394
|
+
const agent = new ToolLoopAgent({
|
|
395
|
+
id: 'haze-main',
|
|
554
396
|
model: activeModel,
|
|
555
|
-
|
|
556
|
-
system: mainSystemPrompt,
|
|
557
|
-
messages: requestMessages,
|
|
397
|
+
instructions: systemPrompt,
|
|
558
398
|
tools: availableTools,
|
|
399
|
+
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
559
400
|
...providerSettings,
|
|
560
401
|
stopWhen: stepCountIs(MAIN_STEP_LIMIT),
|
|
561
|
-
abortSignal: abortController.signal,
|
|
562
402
|
experimental_context: toolExecutionContext,
|
|
563
|
-
onError({ error }) {
|
|
564
|
-
streamError = error;
|
|
565
|
-
callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
566
|
-
},
|
|
567
403
|
prepareStep({ steps, messages }) {
|
|
568
404
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
569
405
|
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
if (
|
|
573
|
-
return {
|
|
574
|
-
|
|
575
|
-
};
|
|
576
|
-
}
|
|
577
|
-
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
578
|
-
return {
|
|
579
|
-
activeTools: ['readFile'],
|
|
580
|
-
};
|
|
581
|
-
}
|
|
582
|
-
if (repeatedToolCall) {
|
|
406
|
+
if (likelyPlanOnlyRequest && mutatingToolSucceeded)
|
|
407
|
+
return { toolChoice: 'none' };
|
|
408
|
+
if (editRecoveryPath && !editRecoveryReadSatisfied)
|
|
409
|
+
return { activeTools: ['readFile'] };
|
|
410
|
+
if (repeatedToolNames.length > 0) {
|
|
583
411
|
const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
|
|
584
412
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
585
|
-
return
|
|
586
|
-
activeTools,
|
|
587
|
-
|
|
413
|
+
return activeTools.length > 0
|
|
414
|
+
? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
415
|
+
: { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
588
416
|
}
|
|
589
|
-
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT ||
|
|
417
|
+
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= MAIN_TOOL_ONLY_STEP_LIMIT) {
|
|
590
418
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
591
|
-
|
|
592
|
-
? { kind: 'tool_budget', message: `Reached the per-turn tool-call limit (${MAIN_TOOL_CALL_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` }
|
|
593
|
-
: { kind: 'tool_only_limit', message: `Made ${MAIN_TOOL_ONLY_STEP_LIMIT} consecutive inspection-only steps without making changes. Type "continue" to resume.` };
|
|
594
|
-
return {
|
|
595
|
-
toolChoice: 'none',
|
|
596
|
-
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
597
|
-
};
|
|
419
|
+
return { toolChoice: 'none', messages: withSyntheticControl(messages, toolLoopBudgetPrompt()) };
|
|
598
420
|
}
|
|
599
421
|
return undefined;
|
|
600
422
|
},
|
|
601
423
|
onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
602
|
-
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
424
|
+
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
603
425
|
latestAccumulatedResponseMessages = response.messages;
|
|
604
|
-
}
|
|
605
|
-
if (!turnStopReason && stepNumber >= MAIN_STEP_LIMIT - 1) {
|
|
606
|
-
turnStopReason = { kind: 'step_limit', message: `Reached the per-turn step limit (${MAIN_STEP_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` };
|
|
607
|
-
}
|
|
608
|
-
lastFinishReason = finishReason;
|
|
609
426
|
const stepInputTokens = usage?.inputTokens;
|
|
610
427
|
const stepOutputTokens = usage?.outputTokens;
|
|
611
428
|
const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
@@ -614,268 +431,181 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
614
431
|
const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
|
|
615
432
|
const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
|
|
616
433
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'step', stream: 'main', step: stepNumber, text, finishReason, usage: { inputTokens: stepInputTokens, outputTokens: stepOutputTokens, cacheReadTokens: stepCacheRead || undefined, cacheWriteTokens: stepCacheWrite || undefined, noCacheTokens: stepNoCache || undefined, reasoningTokens: stepReasoning || undefined, cacheHitRatio: stepCacheHitRatio } });
|
|
617
|
-
|
|
618
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `low cache hit: ${(stepCacheHitRatio * 100).toFixed(1)}% (${stepCacheRead}/${stepInputTokens}), ${stepNoCache} no-cache tokens. Likely prompt prefix changed mid-turn.` });
|
|
619
|
-
}
|
|
620
|
-
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}; usage=${stepInputTokens != null ? `in=${stepInputTokens} out=${stepOutputTokens}` : 'not reported'}${stepCacheRead ? ` cached=${stepCacheRead}` : ''}${stepCacheWrite ? ` cache_write=${stepCacheWrite}` : ''}${stepReasoning ? ` reasoning=${stepReasoning}` : ''}${stepCacheHitRatio !== undefined ? ` cache_hit=${(stepCacheHitRatio * 100).toFixed(0)}%` : ''}`);
|
|
621
|
-
// Repetition guard: when a constrained (no-tools) step emits short text
|
|
622
|
-
// that matches the prior two short-text steps, the model is stuck in a
|
|
623
|
-
// "Let me X" loop. Abort the whole turn so we don't burn maxOutputTokens
|
|
624
|
-
// on every remaining step in the limit. The secondary consecutive-text-only
|
|
625
|
-
// check catches varied-phrasing loops (e.g. "Let me install" → "I'll install
|
|
626
|
-
// dependencies now" → "Now let me run npm install") that the exact-signature
|
|
627
|
-
// check would miss.
|
|
628
|
-
if (finishReason === 'stop' && toolCalls.length === 0) {
|
|
629
|
-
consecutiveTextOnlySteps += 1;
|
|
630
|
-
const signature = text.trim().toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').slice(0, 120);
|
|
631
|
-
if (signature.length >= 8) {
|
|
632
|
-
recentStepTextSignatures.push(signature);
|
|
633
|
-
const last3 = recentStepTextSignatures.slice(-3);
|
|
634
|
-
if (last3.length === 3 && last3[0] === last3[1] && last3[1] === last3[2] && !repetitionAbortFired) {
|
|
635
|
-
repetitionAbortFired = true;
|
|
636
|
-
turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted the same response 3 times in a row (text loop). Type "continue" to try again — the next turn starts fresh.' };
|
|
637
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: 3 consecutive identical text-only steps. Aborting turn to avoid loop. Last signature: "${signature.slice(0, 60)}"` });
|
|
638
|
-
callbacks.debugLog(`repetition guard abort at step ${stepNumber}; signature="${signature.slice(0, 60)}"`);
|
|
639
|
-
abortController.abort('Haze repetition guard: 3 consecutive identical text-only steps.');
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
if (consecutiveTextOnlySteps >= 4 && !repetitionAbortFired) {
|
|
643
|
-
repetitionAbortFired = true;
|
|
644
|
-
turnStopReason = { kind: 'text_repetition', message: 'Stopped: the model emitted several text responses in a row without making progress (likely a varied-phrasing loop). Type "continue" to try again — the next turn starts fresh.' };
|
|
645
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', step: stepNumber, text: `repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps with no tool calls. Aborting turn to avoid varied-phrasing loop.` });
|
|
646
|
-
callbacks.debugLog(`repetition guard abort at step ${stepNumber}; consecutiveTextOnlySteps=${consecutiveTextOnlySteps}`);
|
|
647
|
-
abortController.abort(`Haze repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps without progress.`);
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
else {
|
|
651
|
-
consecutiveTextOnlySteps = 0;
|
|
652
|
-
}
|
|
434
|
+
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
653
435
|
},
|
|
654
436
|
onFinish(event) {
|
|
655
|
-
const providerUsage = extractUsage(event);
|
|
437
|
+
const providerUsage = extractUsage({ usage: event.totalUsage ?? event.usage });
|
|
656
438
|
callbacks.recordTokenUsage?.({
|
|
657
439
|
inputTokens: providerUsage.inputTokens,
|
|
658
440
|
outputTokens: providerUsage.outputTokens,
|
|
659
|
-
systemPrompt:
|
|
660
|
-
messages:
|
|
661
|
-
toolSchemas:
|
|
441
|
+
systemPrompt: inputBreakdown.systemPrompt,
|
|
442
|
+
messages: inputBreakdown.messages,
|
|
443
|
+
toolSchemas: inputBreakdown.toolSchemas,
|
|
662
444
|
outputEstimate: estimateValueTokens(event.response.messages),
|
|
663
445
|
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
664
446
|
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
665
447
|
noCacheTokens: providerUsage.noCacheTokens,
|
|
666
448
|
reasoningTokens: providerUsage.reasoningTokens,
|
|
667
|
-
logicalInputEstimate:
|
|
449
|
+
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
668
450
|
effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
|
|
669
451
|
});
|
|
670
452
|
const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
|
|
671
453
|
const compacted = compactToolHistory(accumulated);
|
|
672
|
-
|
|
673
|
-
callbacks.
|
|
674
|
-
if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
|
|
675
|
-
callbacks.debugLog(`end-of-turn compaction: ${compacted.compactedResults} results, ${compacted.compactedCalls} tool-call inputs compacted`);
|
|
676
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `end-of-turn compaction: ${compacted.compactedResults} old results, ${compacted.compactedCalls} old tool-call inputs compacted before next turn.` });
|
|
677
|
-
}
|
|
678
|
-
callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
|
|
679
|
-
},
|
|
680
|
-
experimental_onToolCallStart({ toolCall }) {
|
|
681
|
-
sawToolCall = true;
|
|
682
|
-
recordToolStart(toolCall);
|
|
683
|
-
resetIdleTimer();
|
|
684
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
685
|
-
callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
686
|
-
// Tool-repetition guard: if the same (toolName, input) has been called
|
|
687
|
-
// TOOL_REPETITION_THRESHOLD times this turn, the model is stuck in a
|
|
688
|
-
// tool-only loop. Abort the turn rather than letting it burn more calls.
|
|
689
|
-
const sig = stableToolKey(toolCall);
|
|
690
|
-
const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
|
|
691
|
-
toolCallSignatureCounts.set(sig, count);
|
|
692
|
-
if (count >= TOOL_REPETITION_THRESHOLD && !repetitionAbortFired) {
|
|
693
|
-
repetitionAbortFired = true;
|
|
694
|
-
turnStopReason = { kind: 'tool_repetition', message: `Stopped: called ${toolCall.toolName} ${count} times with identical input (tool loop). Type "continue" to try again — the next turn starts fresh.` };
|
|
695
|
-
const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
|
|
696
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Aborting to avoid tool-only loop.` });
|
|
697
|
-
callbacks.debugLog(`tool repetition guard abort: ${toolCall.toolName} count=${count} sig=${preview}`);
|
|
698
|
-
abortController.abort(`Haze tool repetition guard: ${toolCall.toolName} called ${count} times with identical input.`);
|
|
699
|
-
}
|
|
454
|
+
callbacks.setConversation(compacted.messages);
|
|
455
|
+
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
700
456
|
},
|
|
701
|
-
experimental_onToolCallFinish(event) {
|
|
702
|
-
resetIdleTimer();
|
|
703
|
-
const summary = toolResultSummary(event);
|
|
704
|
-
recordToolFinish(event);
|
|
705
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: event.toolCall.toolCallId, name: event.toolCall.toolName, success: event.success, output: event.output, error: event.error, durationMs: event.durationMs } });
|
|
706
|
-
const nestedTokens = subagentTokenEstimate(event.output);
|
|
707
|
-
if (nestedTokens)
|
|
708
|
-
callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
|
|
709
|
-
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
710
|
-
recordToolDisplayFinish(event);
|
|
711
|
-
if (!isDuplicateSkippedOutput(event.output))
|
|
712
|
-
toolEpoch += 1;
|
|
713
|
-
callbacks.debugLog(event.success
|
|
714
|
-
? `tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
|
|
715
|
-
: `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
716
|
-
}
|
|
717
457
|
});
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
currentAssistantStarted = true;
|
|
722
|
-
for await (const rawDelta of result.textStream) {
|
|
458
|
+
resetIdleTimer();
|
|
459
|
+
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
460
|
+
for await (const part of result.fullStream) {
|
|
723
461
|
resetIdleTimer();
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
462
|
+
switch (part.type) {
|
|
463
|
+
case 'text-delta': {
|
|
464
|
+
startFreshToolGroup();
|
|
465
|
+
const delta = sanitizeAssistantText(part.text);
|
|
466
|
+
assistantText += delta;
|
|
467
|
+
currentAssistantText += delta;
|
|
468
|
+
const displayText = assistantDisplayText(currentAssistantText);
|
|
469
|
+
if (!assistantStarted && !shouldStartAssistantStream(displayText, assistantStartedAt))
|
|
470
|
+
break;
|
|
471
|
+
if (!assistantStarted) {
|
|
472
|
+
assistantStarted = true;
|
|
473
|
+
assistantStartedAt = Date.now();
|
|
474
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
475
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: assistantStartedAt });
|
|
476
|
+
}
|
|
477
|
+
else {
|
|
478
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
|
|
479
|
+
callbacks.updateMessage(currentAssistantId, { text: displayText });
|
|
480
|
+
}
|
|
481
|
+
break;
|
|
482
|
+
}
|
|
483
|
+
case 'tool-input-start': {
|
|
484
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted)
|
|
485
|
+
finalizeAssistantSegment({ beforeTool: true });
|
|
486
|
+
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
487
|
+
latestToolCalls.set(part.id, toolCall);
|
|
488
|
+
startedTools.set(part.id, Date.now());
|
|
489
|
+
ensureToolItem(toolCall);
|
|
490
|
+
break;
|
|
491
|
+
}
|
|
492
|
+
case 'tool-call': {
|
|
493
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted)
|
|
494
|
+
finalizeAssistantSegment({ beforeTool: true });
|
|
495
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
496
|
+
latestToolCalls.set(part.toolCallId, toolCall);
|
|
497
|
+
if (!startedTools.has(part.toolCallId))
|
|
498
|
+
startedTools.set(part.toolCallId, Date.now());
|
|
499
|
+
ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
500
|
+
updateToolGroup(true);
|
|
501
|
+
break;
|
|
502
|
+
}
|
|
503
|
+
case 'tool-result': {
|
|
504
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
505
|
+
latestToolCalls.set(part.toolCallId, toolCall);
|
|
506
|
+
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
507
|
+
const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
|
|
508
|
+
const item = ensureToolItem(toolCall);
|
|
509
|
+
item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
|
|
510
|
+
item.result = toolResultSummary(finish);
|
|
511
|
+
item.durationMs = finish.durationMs;
|
|
512
|
+
item.finishedAt = startedAt + finish.durationMs;
|
|
513
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs }));
|
|
514
|
+
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 } });
|
|
515
|
+
const ok = toolOutputOk(part.output, true);
|
|
516
|
+
const path = toolInputPath(toolCall.input);
|
|
517
|
+
if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
|
|
518
|
+
editRecoveryPath = path;
|
|
519
|
+
editRecoveryReadSatisfied = false;
|
|
520
|
+
}
|
|
521
|
+
if (ok && toolCall.toolName === 'readFile' && path && path === editRecoveryPath && !isDuplicateSkippedOutput(part.output)) {
|
|
522
|
+
editRecoveryReadSatisfied = true;
|
|
523
|
+
}
|
|
524
|
+
if (ok && !isDuplicateSkippedOutput(part.output) && ['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
|
|
525
|
+
mutatingToolSucceeded = true;
|
|
526
|
+
if (!path || path === editRecoveryPath) {
|
|
527
|
+
editRecoveryPath = undefined;
|
|
528
|
+
editRecoveryReadSatisfied = false;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
532
|
+
callbacks.setWorkState?.(goal.workState);
|
|
533
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
534
|
+
activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
|
|
535
|
+
if (toolCall.toolName === 'writeTasks')
|
|
536
|
+
callbacks.onTasksChanged?.();
|
|
537
|
+
const nestedTokens = subagentTokenEstimate(part.output);
|
|
538
|
+
if (nestedTokens)
|
|
539
|
+
callbacks.recordTokenUsage?.({ inputTokens: nestedTokens.input, outputTokens: nestedTokens.output, systemPrompt: 0, messages: 0, toolSchemas: 0, outputEstimate: 0, cacheReadTokens: 0, cacheWriteTokens: 0, noCacheTokens: nestedTokens.input, reasoningTokens: 0, logicalInputEstimate: nestedTokens.input, effectiveNonCachedInput: nestedTokens.input });
|
|
540
|
+
updateToolGroup(true);
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
case 'tool-error': {
|
|
544
|
+
const existing = latestToolCalls.get(part.toolCallId);
|
|
545
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
546
|
+
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
547
|
+
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
548
|
+
const item = ensureToolItem(toolCall);
|
|
549
|
+
item.status = 'error';
|
|
550
|
+
item.result = toolResultSummary(finish);
|
|
551
|
+
item.durationMs = finish.durationMs;
|
|
552
|
+
item.finishedAt = startedAt + finish.durationMs;
|
|
553
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs }));
|
|
554
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs } });
|
|
555
|
+
if (['editFile', 'replaceLines', 'writeFile'].includes(toolCall.toolName)) {
|
|
556
|
+
editRecoveryPath = toolInputPath(toolCall.input);
|
|
557
|
+
editRecoveryReadSatisfied = false;
|
|
558
|
+
}
|
|
559
|
+
observeGoalToolEvent(goal, { ...toolCall, success: false, error: part.error });
|
|
560
|
+
callbacks.setWorkState?.(goal.workState);
|
|
561
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
562
|
+
updateToolGroup(true);
|
|
563
|
+
break;
|
|
564
|
+
}
|
|
565
|
+
case 'error':
|
|
566
|
+
streamError = part.error;
|
|
567
|
+
callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
|
|
568
|
+
break;
|
|
569
|
+
case 'finish':
|
|
570
|
+
streamFinished = true;
|
|
571
|
+
callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
|
|
572
|
+
break;
|
|
573
|
+
default:
|
|
574
|
+
break;
|
|
753
575
|
}
|
|
754
576
|
}
|
|
755
|
-
let completedConversation = callbacks.getConversation();
|
|
756
577
|
try {
|
|
757
578
|
const response = await result.response;
|
|
758
|
-
completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
|
|
759
|
-
callbacks.setConversation(completedConversation);
|
|
579
|
+
const completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
|
|
580
|
+
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
760
581
|
}
|
|
761
582
|
catch (error) {
|
|
762
|
-
// The turn was aborted or errored mid-stream. If we have any accumulated
|
|
763
|
-
// response messages from completed steps (tracked in onStepFinish), persist
|
|
764
|
-
// them so the next turn inherits the partial work instead of losing it.
|
|
765
583
|
if (latestAccumulatedResponseMessages.length > 0) {
|
|
766
|
-
|
|
767
|
-
const compacted = compactToolHistory(accumulated);
|
|
768
|
-
callbacks.setConversation(compacted.messages);
|
|
769
|
-
if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
|
|
770
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages, compacted ${compacted.compactedResults} results and ${compacted.compactedCalls} tool-call inputs.` });
|
|
771
|
-
}
|
|
772
|
-
callbacks.debugLog(`abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages before re-throwing`);
|
|
773
|
-
}
|
|
774
|
-
throw streamError ?? error;
|
|
775
|
-
}
|
|
776
|
-
callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
|
|
777
|
-
if (lastFinishReason === 'length' && !sawToolCall && completionContinuationCount < maxCompletionContinuations) {
|
|
778
|
-
completionContinuationCount += 1;
|
|
779
|
-
callbacks.debugLog('output token limit reached, auto-continuing');
|
|
780
|
-
const continuation = await streamAssistantResponse(completedConversation, 'output token limit reached', 'Your response was cut off because you hit the output token limit. Continue from where you left off — do not repeat what you already said, just pick up exactly where you stopped.', true);
|
|
781
|
-
completedConversation = callbacks.getConversation();
|
|
782
|
-
if (continuation.text) {
|
|
783
|
-
assistantText += '\n' + continuation.text;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
const combinedAssistantText = assistantDisplayText(assistantText);
|
|
787
|
-
const decideCompletion = (text) => completionDecision({
|
|
788
|
-
request: value,
|
|
789
|
-
goal,
|
|
790
|
-
assistantText: text,
|
|
791
|
-
sawReadOnlyTool,
|
|
792
|
-
sawToolCall,
|
|
793
|
-
mutatingToolSucceeded,
|
|
794
|
-
validationToolSucceeded,
|
|
795
|
-
validationToolFailed,
|
|
796
|
-
editFileFailed,
|
|
797
|
-
editRecoveryPath,
|
|
798
|
-
editRecoveryReasonCode,
|
|
799
|
-
});
|
|
800
|
-
let decision = decideCompletion(combinedAssistantText);
|
|
801
|
-
async function runCompletionLoop(seedConversation, seedText) {
|
|
802
|
-
let loopConversation = seedConversation;
|
|
803
|
-
let latestText = seedText;
|
|
804
|
-
let noProgressSlices = 0;
|
|
805
|
-
while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
|
|
806
|
-
completionContinuationCount += 1;
|
|
807
|
-
const revisionBefore = goal.workState.revision;
|
|
808
|
-
const prompt = decision.continuationPrompt
|
|
809
|
-
?? (looksIncomplete(latestText) ? postContinuationPrompt() : 'Continue the same user goal until it is complete, blocked by a concrete issue, or needs a user decision. Focus on the concrete blocker, not a generic plan.');
|
|
810
|
-
const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
|
|
811
|
-
loopConversation = callbacks.getConversation();
|
|
812
|
-
if (continuation.text)
|
|
813
|
-
latestText = continuation.text;
|
|
814
|
-
decision = decideCompletion(latestText);
|
|
815
|
-
noProgressSlices = goal.workState.revision === revisionBefore ? noProgressSlices + 1 : 0;
|
|
816
|
-
if (noProgressSlices >= 2)
|
|
817
|
-
break;
|
|
818
|
-
}
|
|
819
|
-
if ((decision.needsActionContinuation || decision.needsValidationContinuation) && noProgressSlices >= 2) {
|
|
820
|
-
callbacks.addMessage({ role: 'assistant', text: 'Status: partial. Two continuation slices made no tool progress; the latest work state and blocker evidence were preserved.' });
|
|
821
|
-
}
|
|
822
|
-
if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
|
|
823
|
-
callbacks.addMessage({ role: 'assistant', text: 'Stopped after the autonomous safety limit. The current goal may still need work; ask me to continue and I will resume from the latest tool results.' });
|
|
824
|
-
}
|
|
825
|
-
if (!latestText && toolSummaries.length > 0) {
|
|
826
|
-
const followUp = await streamAssistantResponse(loopConversation, 'completion loop ended without text', noTextAfterToolPrompt(false), false);
|
|
827
|
-
if (!followUp.text)
|
|
828
|
-
callbacks.addMessage({ role: 'assistant', text: `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.` });
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
if (assistantStarted) {
|
|
832
|
-
const hidePreToolFragment = sawToolCall && !textAfterTool;
|
|
833
|
-
const visibleFinalAssistantText = assistantDisplayText(currentAssistantText);
|
|
834
|
-
const hidden = visibleFinalAssistantText.length === 0 || isNonSubstantiveAssistantText(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText) || hidePreToolFragment;
|
|
835
|
-
if (!hidden)
|
|
836
|
-
rememberVisibleAssistantText(visibleFinalAssistantText);
|
|
837
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
|
|
838
|
-
callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, finishedAt: Date.now() });
|
|
839
|
-
if (decision.needsActionContinuation || decision.needsValidationContinuation) {
|
|
840
|
-
await runCompletionLoop(completedConversation, combinedAssistantText);
|
|
841
|
-
}
|
|
842
|
-
else if (sawToolCall && !textAfterTool) {
|
|
843
|
-
const followUp = await streamAssistantResponse(completedConversation, 'tool use completed without follow-up text', noTextAfterToolPrompt(false), false);
|
|
844
|
-
if (!followUp.text) {
|
|
845
|
-
callbacks.addMessage({ role: 'assistant', text: 'Stopped after tool use without a follow-up response. You can ask me to continue if the task is not complete.' });
|
|
846
|
-
}
|
|
584
|
+
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
|
|
847
585
|
}
|
|
586
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
587
|
+
const benignTerminatedAfterStream = text === 'terminated' && (streamFinished || assistantText.trim().length > 0 || latestToolCalls.size > 0);
|
|
588
|
+
if (!benignTerminatedAfterStream)
|
|
589
|
+
throw streamError ?? error;
|
|
590
|
+
callbacks.debugLog(`ignored post-stream response error: ${text}`);
|
|
848
591
|
}
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
const prompt = noTextAfterToolPrompt(allowTools);
|
|
852
|
-
const followUp = await streamAssistantResponse(completedConversation, 'tool-only turn completed without text', prompt, allowTools);
|
|
853
|
-
decision = decideCompletion(followUp.text);
|
|
854
|
-
if (allowTools)
|
|
855
|
-
await runCompletionLoop(callbacks.getConversation(), followUp.text);
|
|
856
|
-
if (!followUp.text && completionContinuationCount === 0) {
|
|
857
|
-
const fallback = toolSummaries.length > 0
|
|
858
|
-
? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
|
|
859
|
-
: 'Finished without a text response.';
|
|
860
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, finishedAt: Date.now() });
|
|
861
|
-
}
|
|
592
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
593
|
+
finalizeAssistantSegment();
|
|
862
594
|
}
|
|
863
|
-
else {
|
|
864
|
-
|
|
595
|
+
else if (latestToolCalls.size > 0) {
|
|
596
|
+
const fallback = `Finished tool work.${toolInputPath([...latestToolCalls.values()].at(-1)?.input) ? '' : ''}`;
|
|
597
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
|
|
865
598
|
}
|
|
866
599
|
goal.phase = 'done';
|
|
867
600
|
goal.status = 'complete';
|
|
868
|
-
turnStatus = 'complete';
|
|
869
|
-
if (turnStopReason) {
|
|
870
|
-
callbacks.addMessage({ role: 'system', text: turnStopReason.message });
|
|
871
|
-
}
|
|
872
601
|
callbacks.setGoalStatus?.(undefined);
|
|
602
|
+
turnStatus = 'complete';
|
|
873
603
|
}
|
|
874
604
|
catch (error) {
|
|
875
605
|
if (abortController.signal.aborted) {
|
|
876
606
|
turnStatus = 'aborted';
|
|
877
607
|
callbacks.debugLog('request aborted');
|
|
878
|
-
callbacks.addMessage({ role: 'system', text:
|
|
608
|
+
callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
|
|
879
609
|
}
|
|
880
610
|
else {
|
|
881
611
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -905,11 +635,15 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
905
635
|
}
|
|
906
636
|
}
|
|
907
637
|
finally {
|
|
638
|
+
if (loadedMcp?.clients.length)
|
|
639
|
+
await closeMcpClients(loadedMcp.clients);
|
|
908
640
|
if (idleTimer)
|
|
909
641
|
clearTimeout(idleTimer);
|
|
910
|
-
|
|
642
|
+
stopToolTimer();
|
|
643
|
+
finalizeToolGroup();
|
|
911
644
|
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
|
|
912
645
|
callbacks.setAbortController?.(null);
|
|
646
|
+
callbacks.setBusyLabel?.('Haze is thinking');
|
|
913
647
|
callbacks.setBusy(false);
|
|
914
648
|
}
|
|
915
649
|
}
|