@denizokcu/haze 0.5.0 → 0.7.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 +36 -1
- package/README.md +101 -24
- package/dist/cli/chat/TaskBar.d.ts +9 -0
- package/dist/cli/chat/TaskBar.js +40 -0
- package/dist/cli/chat/chatMetrics.d.ts +11 -0
- package/dist/cli/chat/chatMetrics.js +50 -0
- package/dist/cli/chat/inputSuggestions.d.ts +16 -0
- package/dist/cli/chat/inputSuggestions.js +55 -0
- package/dist/cli/chat/messages.d.ts +9 -0
- package/dist/cli/chat/messages.js +76 -0
- package/dist/cli/chat/sessionRecorder.d.ts +12 -0
- package/dist/cli/chat/sessionRecorder.js +21 -0
- package/dist/cli/chat/startupInfo.d.ts +4 -0
- package/dist/cli/chat/startupInfo.js +53 -0
- package/dist/cli/chat/turnState.d.ts +5 -0
- package/dist/cli/chat/turnState.js +20 -0
- package/dist/cli/commands/chat.d.ts +0 -1
- package/dist/cli/commands/chat.js +519 -495
- package/dist/cli/commands/chatModes.d.ts +8 -0
- package/dist/cli/commands/chatModes.js +44 -0
- package/dist/cli/commands/commandHelp.d.ts +6 -0
- package/dist/cli/commands/commandHelp.js +25 -0
- package/dist/cli/commands/commands.d.ts +3 -2
- package/dist/cli/commands/commands.js +55 -320
- package/dist/cli/commands/formatters.d.ts +27 -0
- package/dist/cli/commands/formatters.js +149 -4
- package/dist/cli/commands/initCommand.d.ts +2 -0
- package/dist/cli/commands/initCommand.js +19 -0
- package/dist/cli/commands/logsCommand.d.ts +2 -0
- package/dist/cli/commands/logsCommand.js +63 -0
- package/dist/cli/commands/lspWizard.d.ts +14 -0
- package/dist/cli/commands/lspWizard.js +44 -0
- package/dist/cli/commands/mcpWizard.d.ts +15 -0
- package/dist/cli/commands/mcpWizard.js +69 -0
- package/dist/cli/commands/modelCommand.d.ts +2 -0
- package/dist/cli/commands/modelCommand.js +36 -0
- package/dist/cli/commands/providerWizard.d.ts +30 -0
- package/dist/cli/commands/providerWizard.js +114 -0
- package/dist/cli/commands/runCommand.d.ts +16 -0
- package/dist/cli/commands/runCommand.js +170 -0
- package/dist/cli/commands/settingsSummary.d.ts +3 -0
- package/dist/cli/commands/settingsSummary.js +40 -0
- package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
- package/dist/cli/commands/skillConfirmRemove.js +19 -0
- package/dist/cli/commands/skillCreation.d.ts +12 -0
- package/dist/cli/commands/skillCreation.js +14 -0
- package/dist/cli/commands/skillWizard.d.ts +15 -0
- package/dist/cli/commands/skillWizard.js +38 -0
- package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
- package/dist/cli/commands/streaming/assistantText.js +115 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
- package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
- package/dist/cli/commands/streaming/toolResultState.js +25 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
- package/dist/cli/commands/streaming/turnRuntime.js +86 -0
- package/dist/cli/commands/streaming.d.ts +10 -29
- package/dist/cli/commands/streaming.js +249 -911
- package/dist/cli/commands/wizardActions.d.ts +40 -0
- package/dist/cli/commands/wizardActions.js +40 -0
- package/dist/cli/commands/wizardInput.d.ts +4 -0
- package/dist/cli/commands/wizardInput.js +19 -0
- package/dist/cli/commands/wizardPrompts.d.ts +22 -0
- package/dist/cli/commands/wizardPrompts.js +52 -0
- package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
- package/dist/cli/commands/wizardSuggestions.js +139 -0
- package/dist/cli/index.js +62 -4
- package/dist/config/contextFiles.d.ts +8 -1
- package/dist/config/contextFiles.js +25 -12
- package/dist/config/lspSettings.d.ts +16 -0
- package/dist/config/lspSettings.js +95 -0
- package/dist/config/mcpSettings.d.ts +24 -0
- package/dist/config/mcpSettings.js +100 -0
- package/dist/config/providers.js +4 -4
- package/dist/config/settings.d.ts +34 -0
- package/dist/config/skillSettings.d.ts +15 -0
- package/dist/config/skillSettings.js +32 -0
- package/dist/config/updateCheck.d.ts +44 -0
- package/dist/config/updateCheck.js +83 -0
- package/dist/core/agent/budgets.d.ts +6 -0
- package/dist/core/agent/budgets.js +6 -0
- package/dist/core/agent/compaction.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +0 -7
- package/dist/core/agent/requestAssembly.js +27 -5
- package/dist/core/agent/toolOutputStore.js +5 -4
- package/dist/core/agent/toolResults.d.ts +31 -0
- package/dist/core/agent/toolResults.js +42 -0
- package/dist/core/agent/turnPolicy.d.ts +8 -0
- package/dist/core/agent/turnPolicy.js +23 -0
- package/dist/core/agent/workState.d.ts +18 -5
- package/dist/core/agent/workState.js +39 -20
- package/dist/core/bashOutput/reducers/content.d.ts +1 -0
- package/dist/core/bashOutput/reducers/content.js +1 -1
- package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
- package/dist/core/bashOutput/reducers/gh.js +77 -0
- package/dist/core/bashOutput/registry.js +8 -0
- package/dist/core/goal/sessionGoal.d.ts +6 -30
- package/dist/core/goal/sessionGoal.js +3 -68
- package/dist/core/safety/bashClassifier.js +30 -0
- package/dist/core/safety/urlGuard.d.ts +1 -0
- package/dist/core/safety/urlGuard.js +6 -1
- package/dist/core/session/sessionSlimming.d.ts +5 -0
- package/dist/core/session/sessionSlimming.js +78 -0
- package/dist/core/session/sessionStore.d.ts +23 -3
- package/dist/core/session/sessionStore.js +30 -10
- package/dist/core/subagent/subagentRunner.d.ts +11 -1
- package/dist/core/subagent/subagentRunner.js +1 -0
- package/dist/llm/capabilities.d.ts +12 -0
- package/dist/llm/capabilities.js +10 -0
- package/dist/llm/client.d.ts +1 -0
- package/dist/llm/client.js +11 -2
- package/dist/llm/hazeTools.d.ts +31 -32
- package/dist/llm/hazeTools.js +40 -567
- package/dist/llm/lsp.d.ts +109 -0
- package/dist/llm/lsp.js +241 -0
- package/dist/llm/lspTools.d.ts +104 -0
- package/dist/llm/lspTools.js +115 -0
- package/dist/llm/mcp.d.ts +19 -0
- package/dist/llm/mcp.js +73 -0
- package/dist/llm/requestContext.d.ts +28 -0
- package/dist/llm/requestContext.js +41 -0
- package/dist/llm/systemPrompt.d.ts +5 -1
- package/dist/llm/systemPrompt.js +9 -3
- package/dist/llm/tools/bashTool.d.ts +5 -0
- package/dist/llm/tools/bashTool.js +81 -0
- package/dist/llm/tools/editMatch.d.ts +55 -0
- package/dist/llm/tools/editMatch.js +99 -0
- package/dist/llm/tools/failures.d.ts +36 -0
- package/dist/llm/tools/failures.js +38 -0
- package/dist/llm/tools/fetchTool.d.ts +65 -0
- package/dist/llm/tools/fetchTool.js +45 -0
- package/dist/llm/tools/fileToolShared.d.ts +10 -0
- package/dist/llm/tools/fileToolShared.js +43 -0
- package/dist/llm/tools/grepParse.d.ts +13 -0
- package/dist/llm/tools/grepParse.js +67 -0
- package/dist/llm/tools/outputCap.d.ts +53 -0
- package/dist/llm/tools/outputCap.js +67 -0
- package/dist/llm/tools/storedOutputTool.d.ts +10 -0
- package/dist/llm/tools/storedOutputTool.js +17 -0
- package/dist/llm/tools/taskTool.d.ts +28 -0
- package/dist/llm/tools/taskTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +69 -0
- package/dist/llm/tools/toolContext.js +187 -0
- package/dist/llm/tools/workspaceFile.d.ts +33 -0
- package/dist/llm/tools/workspaceFile.js +27 -0
- package/dist/llm/webFetch.d.ts +13 -1
- package/dist/llm/webFetch.js +91 -7
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +24 -45
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/ui/components/TextInput.js +1 -99
- package/dist/ui/inputBuffer.d.ts +28 -0
- package/dist/ui/inputBuffer.js +99 -0
- package/dist/utils/collections.d.ts +6 -0
- package/dist/utils/collections.js +9 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +40 -0
- package/dist/utils/version.d.ts +20 -0
- package/dist/utils/version.js +72 -0
- package/package.json +2 -2
- package/dist/cli/commands/skills.d.ts +0 -4
- package/dist/cli/commands/skills.js +0 -38
|
@@ -1,316 +1,92 @@
|
|
|
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 {
|
|
8
|
-
import { compact, toolCallSummary, toolResultSummary, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
|
|
9
|
-
import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
|
|
10
|
-
import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, repeatedToolCallPrompt, 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 { projectContextSection } from '../../llm/systemPrompt.js';
|
|
6
|
+
import { closeMcpClients } from '../../llm/mcp.js';
|
|
7
|
+
import { toolCallSummary, toolResultSummary, formatSeconds } from './formatters.js';
|
|
12
8
|
import { agentEvent } from '../../core/agent/events.js';
|
|
13
9
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
10
|
+
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
11
|
+
import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
12
|
+
import { estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
13
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
|
|
14
|
+
import { isDuplicateSkippedOutput, toolInputField, toolOutputOk } from '../../core/agent/toolResults.js';
|
|
15
|
+
import { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
16
|
+
export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
17
17
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const repeated = new Set();
|
|
25
|
-
for (const toolCall of toolCalls) {
|
|
26
|
-
const key = stableToolKey(toolCall);
|
|
27
|
-
if (seen.has(key))
|
|
28
|
-
repeated.add(toolCall.toolName);
|
|
29
|
-
seen.add(key);
|
|
30
|
-
}
|
|
31
|
-
return [...repeated];
|
|
32
|
-
}
|
|
33
|
-
function toolOnlyStepCount(steps) {
|
|
34
|
-
let count = 0;
|
|
35
|
-
for (const step of [...steps].reverse()) {
|
|
36
|
-
if (step.toolCalls.length === 0 || step.text.trim().length > 0)
|
|
37
|
-
break;
|
|
38
|
-
count += 1;
|
|
39
|
-
}
|
|
40
|
-
return count;
|
|
41
|
-
}
|
|
42
|
-
function sanitizeAssistantText(text) {
|
|
43
|
-
return [...text].filter(char => {
|
|
44
|
-
const code = char.charCodeAt(0);
|
|
45
|
-
return !(code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127 || code === 155);
|
|
46
|
-
}).join('');
|
|
47
|
-
}
|
|
48
|
-
function hideSyntheticToolCallMarkup(text) {
|
|
49
|
-
return text
|
|
50
|
-
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
|
|
51
|
-
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
|
|
52
|
-
}
|
|
53
|
-
function isWordChar(char) {
|
|
54
|
-
return char.toLowerCase() !== char.toUpperCase() || (char >= '0' && char <= '9');
|
|
55
|
-
}
|
|
56
|
-
function wordCount(text) {
|
|
57
|
-
let count = 0;
|
|
58
|
-
let inWord = false;
|
|
59
|
-
for (const char of text) {
|
|
60
|
-
if (isWordChar(char)) {
|
|
61
|
-
if (!inWord)
|
|
62
|
-
count += 1;
|
|
63
|
-
inWord = true;
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
inWord = false;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return count;
|
|
70
|
-
}
|
|
71
|
-
function endsWithSentenceBoundary(text) {
|
|
72
|
-
const trimmed = text.trim();
|
|
73
|
-
if (!trimmed || wordCount(trimmed) === 0)
|
|
74
|
-
return false;
|
|
75
|
-
const last = trimmed.at(-1) ?? '';
|
|
76
|
-
return last === '.' || last === '!' || last === '?' || last === ':' || last === ';' || last === ')';
|
|
77
|
-
}
|
|
78
|
-
function isNonSubstantiveAssistantText(text) {
|
|
79
|
-
return wordCount(text) === 0;
|
|
80
|
-
}
|
|
81
|
-
function isSubstantiveAssistantText(text) {
|
|
82
|
-
const trimmed = text.trim();
|
|
83
|
-
const words = wordCount(trimmed);
|
|
84
|
-
if (words === 0)
|
|
85
|
-
return false;
|
|
86
|
-
if (trimmed.length >= 24)
|
|
87
|
-
return true;
|
|
88
|
-
if (endsWithSentenceBoundary(trimmed))
|
|
89
|
-
return true;
|
|
90
|
-
return words >= 4;
|
|
91
|
-
}
|
|
92
|
-
function isIncompleteAssistantFragment(text) {
|
|
93
|
-
const trimmed = text.trim();
|
|
94
|
-
return !isSubstantiveAssistantText(trimmed) && wordCount(trimmed) <= 2 && !endsWithSentenceBoundary(trimmed);
|
|
95
|
-
}
|
|
96
|
-
function isLikelyUnfinishedMarkdownFragment(text) {
|
|
97
|
-
const trimmed = text.trim();
|
|
98
|
-
if (!trimmed.includes('\n'))
|
|
99
|
-
return false;
|
|
100
|
-
const last = trimmed.at(-1) ?? '';
|
|
101
|
-
return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
|
|
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;
|
|
117
|
-
}
|
|
118
|
-
function assistantDisplayText(text) {
|
|
119
|
-
return hideSyntheticToolCallMarkup(text).trim();
|
|
120
|
-
}
|
|
121
|
-
function normalizeAssistantText(text) {
|
|
122
|
-
return assistantDisplayText(text)
|
|
123
|
-
.replace(/[`*_~#>\-–—:;,.!?()[\]{}"']/g, '')
|
|
124
|
-
.replace(/\s+/g, ' ')
|
|
125
|
-
.trim()
|
|
126
|
-
.toLowerCase();
|
|
127
|
-
}
|
|
128
|
-
function toolInputPath(input) {
|
|
129
|
-
return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
|
|
130
|
-
? input.path
|
|
131
|
-
: undefined;
|
|
132
|
-
}
|
|
133
|
-
function isDuplicateSkippedOutput(output) {
|
|
134
|
-
return typeof output === 'object' && output != null && 'duplicateSkipped' in output && output.duplicateSkipped === true;
|
|
135
|
-
}
|
|
136
|
-
function retryDelayMs(attempt) {
|
|
137
|
-
return Math.min(4000, 1000 * 2 ** attempt);
|
|
138
|
-
}
|
|
139
|
-
async function abortableDelay(milliseconds, signal) {
|
|
140
|
-
if (signal.aborted)
|
|
141
|
-
return;
|
|
142
|
-
await new Promise(resolve => {
|
|
143
|
-
const timer = setTimeout(resolve, milliseconds);
|
|
144
|
-
signal.addEventListener('abort', () => {
|
|
145
|
-
clearTimeout(timer);
|
|
146
|
-
resolve();
|
|
147
|
-
}, { once: true });
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
151
|
-
const IDLE_TIMEOUT_MS = 5 * 60_000;
|
|
152
|
-
// The step limit is the primary per-turn cost ceiling. The tool-call limits sit
|
|
153
|
-
// above it so healthy autonomous runs (read -> edit -> validate per todo item)
|
|
154
|
-
// complete in one turn instead of being interrupted by a blunt count ceiling.
|
|
155
|
-
// True tool loops are steered by duplicate-call nudges and the tool-only-step
|
|
156
|
-
// guard below, not by these count limits.
|
|
157
|
-
const MAIN_STEP_LIMIT = 64;
|
|
158
|
-
const MAIN_TOOL_CALL_LIMIT = 120;
|
|
159
|
-
const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
|
|
160
|
-
const FOLLOW_UP_STEP_LIMIT = 64;
|
|
161
|
-
const FOLLOW_UP_TOOL_CALL_LIMIT = 120;
|
|
162
|
-
const FOLLOW_UP_TOOL_ONLY_STEP_LIMIT = 24;
|
|
163
|
-
const COMPLETION_CONTINUATION_LIMIT = 12;
|
|
164
|
-
const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
|
|
165
|
-
function toolOutputOk(output, success) {
|
|
166
|
-
if (!success)
|
|
167
|
-
return false;
|
|
168
|
-
return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
|
|
169
|
-
}
|
|
170
|
-
function estimateInputBreakdown(input) {
|
|
171
|
-
const breakdown = contextBreakdown(input);
|
|
172
|
-
return {
|
|
173
|
-
breakdown,
|
|
174
|
-
systemPrompt: breakdown.system,
|
|
175
|
-
messages: Object.values(breakdown.messagesByRole).reduce((sum, value) => sum + value, 0),
|
|
176
|
-
toolSchemas: breakdown.toolSchemas.reduce((sum, value) => sum + value.tokens, 0),
|
|
177
|
-
logicalInputEstimate: breakdown.logicalInputEstimate,
|
|
178
|
-
};
|
|
179
|
-
}
|
|
18
|
+
import { ACTIVE_CONTEXT_TOKEN_BUDGET, DEFAULT_MAX_OUTPUT_TOKENS, IDLE_TIMEOUT_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, MAIN_TOOL_ONLY_STEP_LIMIT } from '../../core/agent/budgets.js';
|
|
19
|
+
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
20
|
+
import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './streaming/assistantText.js';
|
|
21
|
+
import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
|
|
22
|
+
import { applyToolResultState, initialToolResultState, isMutatingToolName } from './streaming/toolResultState.js';
|
|
23
|
+
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
180
24
|
function logEntry(log, entry) {
|
|
181
25
|
if (log)
|
|
182
26
|
void logAppend(log, entry).catch(() => undefined);
|
|
183
27
|
}
|
|
184
|
-
function
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
function subagentTokenEstimate(output) {
|
|
194
|
-
if (typeof output !== 'object' || output == null || !('tokens' in output))
|
|
195
|
-
return undefined;
|
|
196
|
-
const tokens = output.tokens;
|
|
197
|
-
const input = typeof tokens?.in === 'number' ? tokens.in : 0;
|
|
198
|
-
const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
|
|
199
|
-
return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
|
|
28
|
+
function withScopedContextSystem(messages, context) {
|
|
29
|
+
const files = context.pendingContextFiles ?? [];
|
|
30
|
+
if (files.length === 0)
|
|
31
|
+
return messages;
|
|
32
|
+
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
|
+
];
|
|
200
37
|
}
|
|
201
|
-
function
|
|
202
|
-
const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
203
|
-
const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
|
|
204
|
-
? (event.usage?.inputTokenDetails).noCacheTokens
|
|
205
|
-
: undefined;
|
|
206
|
-
return {
|
|
207
|
-
inputTokens: event.usage?.inputTokens,
|
|
208
|
-
outputTokens: event.usage?.outputTokens,
|
|
209
|
-
cacheReadTokens,
|
|
210
|
-
cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
|
|
211
|
-
noCacheTokens: reportedNoCache ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
|
|
212
|
-
reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
|
|
38
|
+
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
|
|
216
39
|
const displayVal = displayValue ?? value;
|
|
217
|
-
const userMessage = { role: 'user', text: displayVal };
|
|
218
40
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
219
41
|
callbacks.setBusy(true);
|
|
42
|
+
callbacks.setBusyLabel?.('Haze is thinking');
|
|
220
43
|
if (!retryingExistingRequest)
|
|
221
|
-
callbacks.addMessage(
|
|
44
|
+
callbacks.addMessage({ role: 'user', text: displayVal });
|
|
222
45
|
const abortController = new AbortController();
|
|
223
46
|
callbacks.setAbortController?.(abortController);
|
|
224
47
|
let turnStatus = 'failed';
|
|
225
|
-
let turnStopReason;
|
|
226
48
|
let idleTimer;
|
|
227
|
-
let
|
|
228
|
-
let finalizeToolGroup = () => undefined;
|
|
49
|
+
let loadedMcp;
|
|
229
50
|
const resetIdleTimer = () => {
|
|
230
51
|
if (idleTimer)
|
|
231
52
|
clearTimeout(idleTimer);
|
|
232
53
|
idleTimer = setTimeout(() => {
|
|
233
|
-
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.` };
|
|
234
54
|
abortController.abort('Haze turn timed out after no model/tool activity.');
|
|
235
55
|
}, IDLE_TIMEOUT_MS);
|
|
236
56
|
};
|
|
57
|
+
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
237
58
|
try {
|
|
238
|
-
const runtime = await modelWithConfig(
|
|
59
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
|
|
239
60
|
if (!runtime?.model) {
|
|
240
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.' });
|
|
241
|
-
|
|
62
|
+
turnStatus = 'complete';
|
|
63
|
+
return { status: turnStatus };
|
|
242
64
|
}
|
|
65
|
+
let activeContextFiles = contextFiles;
|
|
243
66
|
const activeModel = runtime.model;
|
|
244
67
|
const providerSettings = providerRequestSettings(runtime.config);
|
|
245
|
-
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
for (const file of files) {
|
|
251
|
-
if (typeof file !== 'object' || file == null)
|
|
252
|
-
continue;
|
|
253
|
-
const candidate = file;
|
|
254
|
-
if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
|
|
255
|
-
continue;
|
|
256
|
-
activeContextFiles = [...activeContextFiles, { path: candidate.path, content: candidate.content }];
|
|
257
|
-
seen.add(candidate.path);
|
|
258
|
-
}
|
|
259
|
-
};
|
|
260
|
-
const skillRegistry = await loadSkillRegistry();
|
|
261
|
-
const subagentTool = createSubagentTool({ model: activeModel, contextFiles: activeContextFiles, session });
|
|
262
|
-
const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
|
|
68
|
+
const assembled = await assembleRequestContext({ contextFiles: activeContextFiles, session, model: activeModel });
|
|
69
|
+
const availableTools = assembled.availableTools;
|
|
70
|
+
loadedMcp = assembled.loadedMcp;
|
|
71
|
+
if (loadedMcp?.errors.length)
|
|
72
|
+
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
263
73
|
const goal = createSessionGoal(value);
|
|
264
|
-
callbacks.setWorkState?.(goal
|
|
74
|
+
callbacks.setWorkState?.(goal);
|
|
265
75
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
266
76
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
267
|
-
const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
|
|
268
|
-
const likelyActionRequest = isActionRequest(value);
|
|
269
|
-
const likelyValidationRequest = isValidationRequest(value);
|
|
270
|
-
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.';
|
|
271
77
|
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
272
78
|
? stripSyntheticControls(callbacks.getConversation())
|
|
273
79
|
: [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
|
|
274
|
-
let requestMessages =
|
|
275
|
-
? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
|
|
276
|
-
: durableRequestMessages;
|
|
80
|
+
let requestMessages = durableRequestMessages;
|
|
277
81
|
if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
|
|
278
|
-
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal
|
|
82
|
+
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
|
|
279
83
|
}
|
|
280
84
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
let currentAssistantStarted = false;
|
|
285
|
-
let currentAssistantStartedAt = Date.now();
|
|
286
|
-
let currentAssistantText = '';
|
|
287
|
-
let assistantText = '';
|
|
288
|
-
let toolEpoch = 0;
|
|
289
|
-
let currentAssistantToolEpoch = 0;
|
|
290
|
-
let editFileFailed = false;
|
|
291
|
-
let mutatingToolSucceeded = false;
|
|
292
|
-
let validationToolSucceeded = false;
|
|
293
|
-
let validationToolFailed = false;
|
|
294
|
-
let sawReadOnlyTool = false;
|
|
295
|
-
let sawToolCall = false;
|
|
296
|
-
let textAfterTool = false;
|
|
297
|
-
let completionContinuationCount = 0;
|
|
298
|
-
const maxCompletionContinuations = COMPLETION_CONTINUATION_LIMIT;
|
|
299
|
-
const recentStepTextSignatures = [];
|
|
300
|
-
let consecutiveTextOnlySteps = 0;
|
|
301
|
-
let repetitionAbortFired = false;
|
|
302
|
-
const warnedRepeatedToolSignatures = new Set();
|
|
303
|
-
const toolCallSignatureCounts = new Map();
|
|
304
|
-
const TOOL_REPETITION_THRESHOLD = 3;
|
|
305
|
-
let latestAccumulatedResponseMessages = [];
|
|
306
|
-
let editRecoveryPath;
|
|
307
|
-
let editRecoveryReasonCode;
|
|
308
|
-
let editRecoveryReadSatisfied = false;
|
|
309
|
-
const toolSummaries = [];
|
|
310
|
-
const visibleAssistantTexts = new Set();
|
|
85
|
+
const systemPrompt = assembled.systemPrompt;
|
|
86
|
+
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
87
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
311
88
|
const previousAssistantText = normalizeAssistantText(callbacks.getLastAssistantText());
|
|
312
|
-
|
|
313
|
-
visibleAssistantTexts.add(previousAssistantText);
|
|
89
|
+
const visibleAssistantTexts = new Set(previousAssistantText ? [previousAssistantText] : []);
|
|
314
90
|
const rememberVisibleAssistantText = (text) => {
|
|
315
91
|
const normalized = normalizeAssistantText(text);
|
|
316
92
|
if (!normalized)
|
|
@@ -318,694 +94,252 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
318
94
|
visibleAssistantTexts.add(normalized);
|
|
319
95
|
callbacks.setLastAssistantText(text);
|
|
320
96
|
};
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
let
|
|
333
|
-
let
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
toolTimer = undefined;
|
|
340
|
-
}
|
|
341
|
-
function startToolTimer() {
|
|
342
|
-
if (toolTimer)
|
|
343
|
-
return;
|
|
344
|
-
toolTimer = setInterval(() => {
|
|
345
|
-
if (activeToolGroup.items.some(item => item.status === 'running'))
|
|
346
|
-
updateToolGroup(activeToolGroup, true);
|
|
347
|
-
else
|
|
348
|
-
stopToolTimer();
|
|
349
|
-
}, 1000);
|
|
350
|
-
}
|
|
351
|
-
stopActiveTimers = stopToolTimer;
|
|
352
|
-
function renderToolGroup(group, _streaming) {
|
|
353
|
-
const running = group.items.some(item => item.status === 'running');
|
|
354
|
-
const failures = group.items.filter(item => item.status === 'error');
|
|
355
|
-
const changes = group.items.filter(item => /^(editFile|replaceLines|writeFile)\b/.test(item.summary));
|
|
356
|
-
const elapsedMs = group.items.length > 0
|
|
357
|
-
? (running ? Date.now() : Math.max(...group.items.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...group.items.map(item => item.startedAt))
|
|
358
|
-
: 0;
|
|
359
|
-
const elapsed = formatElapsedTimeWhole(elapsedMs);
|
|
360
|
-
const summaryParts = [`${group.items.length} calls`, `${changes.length} changes`];
|
|
361
|
-
if (failures.length > 0)
|
|
362
|
-
summaryParts.push(`${failures.length} failed`);
|
|
363
|
-
summaryParts.push(elapsed);
|
|
364
|
-
const summary = summaryParts.join(' · ');
|
|
365
|
-
const header = summary;
|
|
366
|
-
const lines = [];
|
|
367
|
-
for (const item of group.items) {
|
|
368
|
-
const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
|
|
369
|
-
const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
|
|
370
|
-
lines.push(` ${icon} ${item.summary}${result}`);
|
|
371
|
-
if (item.diff && item.diff.length > 0 && (item.diffLineCount ?? item.diff.length) <= INLINE_DIFF_LINE_LIMIT) {
|
|
372
|
-
for (const diffLine of item.diff) {
|
|
373
|
-
const lineNumber = diffLine.type === 'add' ? diffLine.newLine : diffLine.oldLine;
|
|
374
|
-
const marker = diffLine.type === 'add' ? '+' : diffLine.type === 'remove' ? '-' : ' ';
|
|
375
|
-
lines.push(` ${String(lineNumber ?? '').padStart(5)} ${marker} ${diffLine.text}`);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
else if ((item.diffLineCount ?? 0) > INLINE_DIFF_LINE_LIMIT) {
|
|
379
|
-
lines.push(` diff hidden (${item.diffLineCount} changed lines; run git diff to inspect)`);
|
|
380
|
-
}
|
|
381
|
-
if (item.subItems && item.subItems.length > 0) {
|
|
382
|
-
for (const sub of item.subItems) {
|
|
383
|
-
const subDuration = sub.durationMs > 1000 ? ` · ${formatSeconds(sub.durationMs)}` : '';
|
|
384
|
-
lines.push(` · ${sub.name} — ${sub.summary}${subDuration}`);
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
return [header, ...lines].join('\n');
|
|
389
|
-
}
|
|
390
|
-
function updateToolGroup(group = activeToolGroup, streaming = true) {
|
|
391
|
-
const text = renderToolGroup(group, streaming);
|
|
392
|
-
if (!group.started) {
|
|
393
|
-
group.started = true;
|
|
394
|
-
callbacks.addMessage({ id: group.id, role: 'tool', text, streaming });
|
|
395
|
-
}
|
|
396
|
-
else {
|
|
397
|
-
callbacks.updateMessage(group.id, { text, streaming });
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
finalizeToolGroup = () => {
|
|
401
|
-
if (activeToolGroup.started)
|
|
402
|
-
updateToolGroup(activeToolGroup, false);
|
|
97
|
+
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
98
|
+
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path) };
|
|
99
|
+
const startedTools = new Map();
|
|
100
|
+
const latestToolCalls = new Map();
|
|
101
|
+
let latestAccumulatedResponseMessages = [];
|
|
102
|
+
let currentAssistantId = `assistant-${Date.now()}`;
|
|
103
|
+
let assistantStarted = false;
|
|
104
|
+
let assistantStartedAt = Date.now();
|
|
105
|
+
let assistantText = '';
|
|
106
|
+
let currentAssistantText = '';
|
|
107
|
+
let streamError;
|
|
108
|
+
let streamFinished = false;
|
|
109
|
+
let toolResultState = initialToolResultState();
|
|
110
|
+
const resetAssistantSegment = () => {
|
|
111
|
+
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
112
|
+
assistantStarted = false;
|
|
113
|
+
assistantStartedAt = Date.now();
|
|
114
|
+
currentAssistantText = '';
|
|
403
115
|
};
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
return relatedToolStartedAt;
|
|
413
|
-
}
|
|
414
|
-
function toolGroupForNextCall() {
|
|
415
|
-
const hasRunningTools = activeToolGroup.items.some(item => item.status === 'running');
|
|
416
|
-
if (assistantSinceActiveToolGroup && activeToolGroup.started && !hasRunningTools) {
|
|
417
|
-
activeToolGroup = createToolDisplayGroup();
|
|
418
|
-
assistantSinceActiveToolGroup = false;
|
|
419
|
-
}
|
|
420
|
-
return activeToolGroup;
|
|
421
|
-
}
|
|
422
|
-
function ensureToolDisplayItem(toolCall) {
|
|
423
|
-
let item = activeToolGroup.items.find(candidate => candidate.id === toolCall.toolCallId);
|
|
424
|
-
if (item)
|
|
425
|
-
return item;
|
|
426
|
-
const group = toolGroupForNextCall();
|
|
427
|
-
item = { id: toolCall.toolCallId, summary: toolCallSummary(toolCall.toolName, toolCall.input), status: 'running', startedAt: Date.now() };
|
|
428
|
-
group.items.push(item);
|
|
429
|
-
startToolTimer();
|
|
430
|
-
updateToolGroup(group, true);
|
|
431
|
-
return item;
|
|
432
|
-
}
|
|
433
|
-
function recordToolStart(toolCall) {
|
|
434
|
-
callbacks.onEvent?.(agentEvent({ type: 'tool_start', id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input }));
|
|
435
|
-
ensureToolDisplayItem(toolCall);
|
|
436
|
-
const runningSubagents = activeToolGroup.items.filter(item => item.status === 'running' && item.summary.startsWith('subagent')).length;
|
|
437
|
-
if (runningSubagents > 0)
|
|
438
|
-
callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
|
|
439
|
-
}
|
|
440
|
-
function recordToolDisplayFinish(event) {
|
|
441
|
-
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 }));
|
|
442
|
-
const item = ensureToolDisplayItem(event.toolCall);
|
|
443
|
-
item.startedAt = Math.min(item.startedAt, Date.now() - event.durationMs);
|
|
444
|
-
item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
|
|
445
|
-
item.result = toolResultSummary(event);
|
|
446
|
-
item.durationMs = event.durationMs;
|
|
447
|
-
item.finishedAt = item.startedAt + event.durationMs;
|
|
448
|
-
if (typeof event.output === 'object' && event.output != null) {
|
|
449
|
-
const output = event.output;
|
|
450
|
-
rememberContextFiles(output.applicableProjectInstructions);
|
|
451
|
-
if (typeof output.diffLineCount === 'number')
|
|
452
|
-
item.diffLineCount = output.diffLineCount;
|
|
453
|
-
if (Array.isArray(output.diff))
|
|
454
|
-
item.diff = output.diff;
|
|
455
|
-
}
|
|
456
|
-
if (event.toolCall.toolName === 'subagent' && typeof event.output === 'object' && event.output != null) {
|
|
457
|
-
const out = event.output;
|
|
458
|
-
if (Array.isArray(out.toolCalls)) {
|
|
459
|
-
item.subItems = out.toolCalls.map(tc => ({
|
|
460
|
-
name: tc.name,
|
|
461
|
-
summary: tc.summary,
|
|
462
|
-
durationMs: tc.durationMs,
|
|
463
|
-
}));
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
if (event.toolCall.toolName === 'writeTasks' && event.success) {
|
|
467
|
-
callbacks.onTasksChanged?.();
|
|
468
|
-
}
|
|
469
|
-
const hasRunningTools = activeToolGroup.items.some(candidate => candidate.status === 'running');
|
|
470
|
-
updateToolGroup(activeToolGroup, !assistantSinceActiveToolGroup);
|
|
471
|
-
if (!hasRunningTools)
|
|
472
|
-
stopToolTimer();
|
|
473
|
-
const runningSubagents = activeToolGroup.items.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
|
|
474
|
-
if (runningSubagents === 0)
|
|
475
|
-
callbacks.setBusyLabel?.('Haze is thinking');
|
|
476
|
-
else
|
|
477
|
-
callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
|
|
478
|
-
}
|
|
479
|
-
callbacks.debugLog(`request started with ${requestMessages.length} conversation messages; intent=${goal.normalizedIntent}; action=${likelyActionRequest}`);
|
|
480
|
-
function recordToolFinish(event) {
|
|
481
|
-
const path = toolInputPath(event.toolCall.input);
|
|
482
|
-
const duplicateSkipped = isDuplicateSkippedOutput(event.output);
|
|
483
|
-
const ok = toolOutputOk(event.output, event.success);
|
|
484
|
-
observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
|
|
485
|
-
callbacks.setWorkState?.(goal.workState);
|
|
486
|
-
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
487
|
-
if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
|
|
488
|
-
editFileFailed = true;
|
|
489
|
-
editRecoveryPath = path;
|
|
490
|
-
editRecoveryReasonCode = typeof event.output === 'object' && event.output != null && 'reasonCode' in event.output && typeof event.output.reasonCode === 'string' ? event.output.reasonCode : undefined;
|
|
491
|
-
editRecoveryReadSatisfied = false;
|
|
492
|
-
}
|
|
493
|
-
if (ok && ['listFiles', 'readFile'].includes(event.toolCall.toolName))
|
|
494
|
-
sawReadOnlyTool = true;
|
|
495
|
-
if (ok && event.toolCall.toolName === 'readFile' && path && path === editRecoveryPath && !duplicateSkipped) {
|
|
496
|
-
editRecoveryReadSatisfied = true;
|
|
497
|
-
}
|
|
498
|
-
if (ok && !duplicateSkipped && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
|
|
499
|
-
mutatingToolSucceeded = true;
|
|
500
|
-
if (!path || path === editRecoveryPath) {
|
|
501
|
-
editRecoveryPath = undefined;
|
|
502
|
-
editRecoveryReasonCode = undefined;
|
|
503
|
-
editRecoveryReadSatisfied = false;
|
|
504
|
-
editFileFailed = false;
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
if (event.success && event.toolCall.toolName === 'bash') {
|
|
508
|
-
if (ok)
|
|
509
|
-
validationToolSucceeded = true;
|
|
510
|
-
else
|
|
511
|
-
validationToolFailed = true;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
|
|
515
|
-
callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
|
|
516
|
-
const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
517
|
-
let responseStarted = false;
|
|
518
|
-
let responseStartedAt = Date.now();
|
|
519
|
-
let responseText = '';
|
|
520
|
-
let continuationToolCalls = 0;
|
|
521
|
-
let followUpStreamError;
|
|
522
|
-
const prunedMessages = compactToolHistory(stripSyntheticControls(messages)).messages;
|
|
523
|
-
const compactedMessages = estimateValueTokens(prunedMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET
|
|
524
|
-
? compactModelMessages(prunedMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages
|
|
525
|
-
: prunedMessages;
|
|
526
|
-
const continuationMessages = withSyntheticControl(compactedMessages, `${prompt}\n\n${workStatePrompt(goal.workState)}`);
|
|
527
|
-
const followUpSystemPrompt = buildSystemPrompt(activeContextFiles, session);
|
|
528
|
-
const followUpTools = allowTools ? availableTools : undefined;
|
|
529
|
-
const followUpInputBreakdown = estimateInputBreakdown({ system: followUpSystemPrompt, contextFiles: activeContextFiles, messages: continuationMessages, tools: followUpTools });
|
|
530
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: `continuation:${reason}`, system: followUpSystemPrompt, messages: continuationMessages, tools: followUpTools ? Object.keys(followUpTools) : [], context: followUpInputBreakdown.breakdown });
|
|
531
|
-
const followUp = streamText({
|
|
532
|
-
model: activeModel,
|
|
533
|
-
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
534
|
-
system: followUpSystemPrompt,
|
|
535
|
-
messages: continuationMessages,
|
|
536
|
-
...toolRequestSettings(availableTools, allowTools),
|
|
537
|
-
...providerSettings,
|
|
538
|
-
stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
|
|
539
|
-
abortSignal: abortController.signal,
|
|
540
|
-
experimental_context: toolExecutionContext,
|
|
541
|
-
prepareStep({ steps, messages }) {
|
|
542
|
-
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
543
|
-
continuationToolCalls = toolCalls.length;
|
|
544
|
-
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
545
|
-
if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
|
|
546
|
-
return {
|
|
547
|
-
toolChoice: 'none',
|
|
548
|
-
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
if (repeatedToolNames.length > 0) {
|
|
552
|
-
const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
|
|
553
|
-
callbacks.debugLog(`disabling repeated tools for follow-up step: ${repeatedToolNames.join(', ')}`);
|
|
554
|
-
return activeTools.length > 0
|
|
555
|
-
? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
556
|
-
: { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
557
|
-
}
|
|
558
|
-
if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
|
|
559
|
-
return {
|
|
560
|
-
toolChoice: 'none',
|
|
561
|
-
};
|
|
562
|
-
}
|
|
563
|
-
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
564
|
-
return {
|
|
565
|
-
activeTools: ['readFile'],
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
return undefined;
|
|
569
|
-
},
|
|
570
|
-
onError({ error }) {
|
|
571
|
-
followUpStreamError = error;
|
|
572
|
-
callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
573
|
-
},
|
|
574
|
-
onFinish(event) {
|
|
575
|
-
const providerUsage = extractUsage(event);
|
|
576
|
-
callbacks.recordTokenUsage?.({
|
|
577
|
-
inputTokens: providerUsage.inputTokens,
|
|
578
|
-
outputTokens: providerUsage.outputTokens,
|
|
579
|
-
systemPrompt: followUpInputBreakdown.systemPrompt,
|
|
580
|
-
messages: followUpInputBreakdown.messages,
|
|
581
|
-
toolSchemas: followUpInputBreakdown.toolSchemas,
|
|
582
|
-
outputEstimate: estimateValueTokens(event.response.messages),
|
|
583
|
-
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
584
|
-
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
585
|
-
noCacheTokens: providerUsage.noCacheTokens,
|
|
586
|
-
reasoningTokens: providerUsage.reasoningTokens,
|
|
587
|
-
logicalInputEstimate: followUpInputBreakdown.logicalInputEstimate,
|
|
588
|
-
effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
|
|
589
|
-
});
|
|
590
|
-
const nextConversation = [...stripSyntheticControls(compactedMessages), ...event.response.messages];
|
|
591
|
-
callbacks.setConversation(nextConversation);
|
|
592
|
-
callbacks.debugLog(`conversation updated to ${nextConversation.length} messages after follow-up`);
|
|
593
|
-
},
|
|
594
|
-
experimental_onToolCallStart({ toolCall }) {
|
|
595
|
-
sawToolCall = true;
|
|
596
|
-
recordToolStart(toolCall);
|
|
597
|
-
resetIdleTimer();
|
|
598
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: `continuation:${reason}`, toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
599
|
-
callbacks.debugLog(`follow-up tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
600
|
-
const sig = stableToolKey(toolCall);
|
|
601
|
-
const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
|
|
602
|
-
toolCallSignatureCounts.set(sig, count);
|
|
603
|
-
if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
|
|
604
|
-
warnedRepeatedToolSignatures.add(sig);
|
|
605
|
-
const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
|
|
606
|
-
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. Steering the model away from this repeated call.` });
|
|
607
|
-
callbacks.debugLog(`tool repetition guard steering (continuation): ${toolCall.toolName} count=${count}`);
|
|
608
|
-
}
|
|
609
|
-
},
|
|
610
|
-
experimental_onToolCallFinish(event) {
|
|
611
|
-
resetIdleTimer();
|
|
612
|
-
recordToolFinish(event);
|
|
613
|
-
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 } });
|
|
614
|
-
const nestedTokens = subagentTokenEstimate(event.output);
|
|
615
|
-
if (nestedTokens)
|
|
616
|
-
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 });
|
|
617
|
-
const summary = toolResultSummary(event);
|
|
618
|
-
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
619
|
-
recordToolDisplayFinish(event);
|
|
620
|
-
if (!isDuplicateSkippedOutput(event.output))
|
|
621
|
-
toolEpoch += 1;
|
|
622
|
-
callbacks.debugLog(event.success
|
|
623
|
-
? `follow-up tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
|
|
624
|
-
: `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
625
|
-
},
|
|
626
|
-
});
|
|
627
|
-
for await (const rawDelta of followUp.textStream) {
|
|
628
|
-
resetIdleTimer();
|
|
629
|
-
const delta = sanitizeAssistantText(rawDelta);
|
|
630
|
-
responseText += delta;
|
|
631
|
-
const displayText = assistantDisplayText(responseText);
|
|
632
|
-
if ((!shouldStartAssistantStream(displayText, responseStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
|
|
633
|
-
continue;
|
|
634
|
-
if (!responseStarted) {
|
|
635
|
-
responseStarted = true;
|
|
636
|
-
responseStartedAt = Date.now();
|
|
637
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
|
|
638
|
-
const displayedStartedAt = closeToolGroupBeforeAssistantMessage() ?? responseStartedAt;
|
|
639
|
-
callbacks.addMessage({ id: responseId, role: 'assistant', text: displayText, streaming: true, startedAt: displayedStartedAt });
|
|
640
|
-
}
|
|
641
|
-
else {
|
|
642
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: responseId, text: displayText }));
|
|
643
|
-
callbacks.updateMessage(responseId, { text: displayText });
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
try {
|
|
647
|
-
await followUp.response;
|
|
648
|
-
}
|
|
649
|
-
catch (error) {
|
|
650
|
-
throw followUpStreamError ?? error;
|
|
651
|
-
}
|
|
652
|
-
const finalText = assistantDisplayText(responseText);
|
|
653
|
-
const visibleFinalText = finalText;
|
|
654
|
-
const hidden = (responseStarted ? isHiddenAssistantFragment(visibleFinalText) : isHiddenUnstartedFinalText(visibleFinalText)) || isDuplicateVisibleAssistantText(visibleFinalText);
|
|
655
|
-
if (responseStarted) {
|
|
116
|
+
const finalizeAssistantSegment = (options = {}) => {
|
|
117
|
+
const finalText = assistantDisplayText(currentAssistantText);
|
|
118
|
+
const normalized = normalizeAssistantText(finalText);
|
|
119
|
+
const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
120
|
+
|| (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
|
|
121
|
+
|| (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
|
|
122
|
+
|| (normalized.length > 0 && visibleAssistantTexts.has(normalized));
|
|
123
|
+
if (assistantStarted) {
|
|
656
124
|
if (!hidden)
|
|
657
|
-
rememberVisibleAssistantText(
|
|
658
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id:
|
|
659
|
-
callbacks.updateMessage(
|
|
125
|
+
rememberVisibleAssistantText(finalText);
|
|
126
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden }));
|
|
127
|
+
callbacks.updateMessage(currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
660
128
|
}
|
|
661
129
|
else if (!hidden) {
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
callbacks.onEvent?.(agentEvent({ type: '
|
|
665
|
-
callbacks.
|
|
130
|
+
if (!hidden)
|
|
131
|
+
rememberVisibleAssistantText(finalText);
|
|
132
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
133
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: finalText, hidden: false }));
|
|
134
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(finalText, assistantStartedAt) });
|
|
666
135
|
}
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
const mainInputBreakdown = estimateInputBreakdown({ system: mainSystemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
673
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: mainSystemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: mainInputBreakdown.breakdown });
|
|
674
|
-
const result = streamText({
|
|
136
|
+
resetAssistantSegment();
|
|
137
|
+
return !hidden;
|
|
138
|
+
};
|
|
139
|
+
const agent = new ToolLoopAgent({
|
|
140
|
+
id: 'haze-main',
|
|
675
141
|
model: activeModel,
|
|
676
|
-
|
|
677
|
-
system: mainSystemPrompt,
|
|
678
|
-
messages: requestMessages,
|
|
142
|
+
instructions: systemPrompt,
|
|
679
143
|
tools: availableTools,
|
|
144
|
+
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
680
145
|
...providerSettings,
|
|
681
146
|
stopWhen: stepCountIs(MAIN_STEP_LIMIT),
|
|
682
|
-
abortSignal: abortController.signal,
|
|
683
147
|
experimental_context: toolExecutionContext,
|
|
684
|
-
onError({ error }) {
|
|
685
|
-
streamError = error;
|
|
686
|
-
callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
687
|
-
},
|
|
688
148
|
prepareStep({ steps, messages }) {
|
|
689
149
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
690
150
|
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
691
|
-
const
|
|
692
|
-
const
|
|
693
|
-
if (likelyPlanOnlyRequest && mutatingToolSucceeded)
|
|
694
|
-
return {
|
|
695
|
-
|
|
696
|
-
};
|
|
697
|
-
|
|
698
|
-
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
699
|
-
return {
|
|
700
|
-
activeTools: ['readFile'],
|
|
701
|
-
};
|
|
702
|
-
}
|
|
703
|
-
if (repeatedToolCall) {
|
|
151
|
+
const scopedMessages = withScopedContextSystem(messages, toolExecutionContext);
|
|
152
|
+
const messagesChanged = scopedMessages !== messages;
|
|
153
|
+
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
154
|
+
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
155
|
+
if (toolResultState.editRecoveryPath && !toolResultState.editRecoveryReadSatisfied)
|
|
156
|
+
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
157
|
+
if (repeatedToolNames.length > 0) {
|
|
704
158
|
const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
|
|
705
159
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
706
160
|
return activeTools.length > 0
|
|
707
|
-
? { activeTools, messages: withSyntheticControl(
|
|
708
|
-
: { toolChoice: 'none', messages: withSyntheticControl(
|
|
161
|
+
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
162
|
+
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
709
163
|
}
|
|
710
|
-
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT ||
|
|
164
|
+
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= MAIN_TOOL_ONLY_STEP_LIMIT) {
|
|
711
165
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
712
|
-
|
|
713
|
-
? { 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.` }
|
|
714
|
-
: { kind: 'tool_only_limit', message: `Made ${MAIN_TOOL_ONLY_STEP_LIMIT} consecutive inspection-only steps without making changes. Type "continue" to resume.` };
|
|
715
|
-
return {
|
|
716
|
-
toolChoice: 'none',
|
|
717
|
-
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
718
|
-
};
|
|
166
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
719
167
|
}
|
|
720
|
-
return undefined;
|
|
168
|
+
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
721
169
|
},
|
|
722
170
|
onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
723
|
-
|
|
724
|
-
ensureToolDisplayItem(toolCall);
|
|
725
|
-
if (Array.isArray(response?.messages) && response.messages.length > 0) {
|
|
171
|
+
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
726
172
|
latestAccumulatedResponseMessages = response.messages;
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
}
|
|
731
|
-
lastFinishReason = finishReason;
|
|
732
|
-
const stepInputTokens = usage?.inputTokens;
|
|
733
|
-
const stepOutputTokens = usage?.outputTokens;
|
|
734
|
-
const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
735
|
-
const stepCacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;
|
|
736
|
-
const stepReasoning = usage?.outputTokenDetails?.reasoningTokens ?? 0;
|
|
737
|
-
const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
|
|
738
|
-
const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
|
|
739
|
-
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 } });
|
|
740
|
-
if (stepCacheHitRatio !== undefined && stepCacheHitRatio < 0.5 && stepNoCache > 2000) {
|
|
741
|
-
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.` });
|
|
742
|
-
}
|
|
743
|
-
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)}%` : ''}`);
|
|
744
|
-
// Repetition guard: when a constrained (no-tools) step emits short text
|
|
745
|
-
// that matches the prior two short-text steps, the model is stuck in a
|
|
746
|
-
// "Let me X" loop. Abort the whole turn so we don't burn maxOutputTokens
|
|
747
|
-
// on every remaining step in the limit. The secondary consecutive-text-only
|
|
748
|
-
// check catches varied-phrasing loops (e.g. "Let me install" → "I'll install
|
|
749
|
-
// dependencies now" → "Now let me run npm install") that the exact-signature
|
|
750
|
-
// check would miss.
|
|
751
|
-
if (finishReason === 'stop' && toolCalls.length === 0) {
|
|
752
|
-
consecutiveTextOnlySteps += 1;
|
|
753
|
-
const signature = text.trim().toLowerCase().replace(/[^a-z0-9 ]/g, '').replace(/\s+/g, ' ').slice(0, 120);
|
|
754
|
-
if (signature.length >= 8) {
|
|
755
|
-
recentStepTextSignatures.push(signature);
|
|
756
|
-
const last3 = recentStepTextSignatures.slice(-3);
|
|
757
|
-
if (last3.length === 3 && last3[0] === last3[1] && last3[1] === last3[2] && !repetitionAbortFired) {
|
|
758
|
-
repetitionAbortFired = true;
|
|
759
|
-
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.' };
|
|
760
|
-
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)}"` });
|
|
761
|
-
callbacks.debugLog(`repetition guard abort at step ${stepNumber}; signature="${signature.slice(0, 60)}"`);
|
|
762
|
-
abortController.abort('Haze repetition guard: 3 consecutive identical text-only steps.');
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
if (consecutiveTextOnlySteps >= 4 && !repetitionAbortFired) {
|
|
766
|
-
repetitionAbortFired = true;
|
|
767
|
-
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.' };
|
|
768
|
-
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.` });
|
|
769
|
-
callbacks.debugLog(`repetition guard abort at step ${stepNumber}; consecutiveTextOnlySteps=${consecutiveTextOnlySteps}`);
|
|
770
|
-
abortController.abort(`Haze repetition guard: ${consecutiveTextOnlySteps} consecutive text-only steps without progress.`);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
else {
|
|
774
|
-
consecutiveTextOnlySteps = 0;
|
|
775
|
-
}
|
|
173
|
+
const stepUsage = stepCacheMetrics(usage);
|
|
174
|
+
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
|
+
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
776
176
|
},
|
|
777
177
|
onFinish(event) {
|
|
778
|
-
const providerUsage = extractUsage(event);
|
|
178
|
+
const providerUsage = extractUsage({ usage: event.totalUsage ?? event.usage });
|
|
779
179
|
callbacks.recordTokenUsage?.({
|
|
780
180
|
inputTokens: providerUsage.inputTokens,
|
|
781
181
|
outputTokens: providerUsage.outputTokens,
|
|
782
|
-
systemPrompt:
|
|
783
|
-
messages:
|
|
784
|
-
toolSchemas:
|
|
182
|
+
systemPrompt: inputBreakdown.systemPrompt,
|
|
183
|
+
messages: inputBreakdown.messages,
|
|
184
|
+
toolSchemas: inputBreakdown.toolSchemas,
|
|
785
185
|
outputEstimate: estimateValueTokens(event.response.messages),
|
|
786
186
|
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
787
187
|
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
788
188
|
noCacheTokens: providerUsage.noCacheTokens,
|
|
789
189
|
reasoningTokens: providerUsage.reasoningTokens,
|
|
790
|
-
logicalInputEstimate:
|
|
791
|
-
effectiveNonCachedInput:
|
|
190
|
+
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
191
|
+
effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
|
|
792
192
|
});
|
|
793
193
|
const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
|
|
794
194
|
const compacted = compactToolHistory(accumulated);
|
|
795
|
-
|
|
796
|
-
callbacks.
|
|
797
|
-
if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
|
|
798
|
-
callbacks.debugLog(`end-of-turn compaction: ${compacted.compactedResults} results, ${compacted.compactedCalls} tool-call inputs compacted`);
|
|
799
|
-
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.` });
|
|
800
|
-
}
|
|
801
|
-
callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
|
|
802
|
-
},
|
|
803
|
-
experimental_onToolCallStart({ toolCall }) {
|
|
804
|
-
sawToolCall = true;
|
|
805
|
-
recordToolStart(toolCall);
|
|
806
|
-
resetIdleTimer();
|
|
807
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_call', stream: 'main', toolCall: { id: toolCall.toolCallId, name: toolCall.toolName, input: toolCall.input } });
|
|
808
|
-
callbacks.debugLog(`tool start: ${toolCall.toolName} ${compact(toolCall.input)}`);
|
|
809
|
-
// Tool-repetition guard: if the same (toolName, input) has been called
|
|
810
|
-
// TOOL_REPETITION_THRESHOLD times this turn, log once. prepareStep then
|
|
811
|
-
// disables that repeated tool and injects a model-facing correction.
|
|
812
|
-
const sig = stableToolKey(toolCall);
|
|
813
|
-
const count = (toolCallSignatureCounts.get(sig) ?? 0) + 1;
|
|
814
|
-
toolCallSignatureCounts.set(sig, count);
|
|
815
|
-
if (count >= TOOL_REPETITION_THRESHOLD && !warnedRepeatedToolSignatures.has(sig)) {
|
|
816
|
-
warnedRepeatedToolSignatures.add(sig);
|
|
817
|
-
const preview = sig.length > 100 ? `${sig.slice(0, 100)}…` : sig;
|
|
818
|
-
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', text: `tool repetition guard: "${preview}" called ${count} times with identical input this turn. Steering the model away from this repeated call.` });
|
|
819
|
-
callbacks.debugLog(`tool repetition guard steering: ${toolCall.toolName} count=${count} sig=${preview}`);
|
|
820
|
-
}
|
|
195
|
+
callbacks.setConversation(compacted.messages);
|
|
196
|
+
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
821
197
|
},
|
|
822
|
-
experimental_onToolCallFinish(event) {
|
|
823
|
-
resetIdleTimer();
|
|
824
|
-
const summary = toolResultSummary(event);
|
|
825
|
-
recordToolFinish(event);
|
|
826
|
-
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 } });
|
|
827
|
-
const nestedTokens = subagentTokenEstimate(event.output);
|
|
828
|
-
if (nestedTokens)
|
|
829
|
-
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 });
|
|
830
|
-
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
831
|
-
recordToolDisplayFinish(event);
|
|
832
|
-
if (!isDuplicateSkippedOutput(event.output))
|
|
833
|
-
toolEpoch += 1;
|
|
834
|
-
callbacks.debugLog(event.success
|
|
835
|
-
? `tool done: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.output)}`
|
|
836
|
-
: `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
837
|
-
}
|
|
838
198
|
});
|
|
839
|
-
|
|
199
|
+
resetIdleTimer();
|
|
200
|
+
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
201
|
+
for await (const part of result.fullStream) {
|
|
840
202
|
resetIdleTimer();
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
203
|
+
switch (part.type) {
|
|
204
|
+
case 'text-delta': {
|
|
205
|
+
toolDisplay.startFreshToolGroup();
|
|
206
|
+
const delta = sanitizeAssistantText(part.text);
|
|
207
|
+
assistantText += delta;
|
|
208
|
+
currentAssistantText += delta;
|
|
209
|
+
const displayText = assistantDisplayText(currentAssistantText);
|
|
210
|
+
if (!assistantStarted && !shouldStartAssistantStream(displayText, assistantStartedAt))
|
|
211
|
+
break;
|
|
212
|
+
if (!assistantStarted) {
|
|
213
|
+
assistantStarted = true;
|
|
214
|
+
assistantStartedAt = Date.now();
|
|
215
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
216
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: assistantStartedAt });
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
|
|
220
|
+
callbacks.updateMessage(currentAssistantId, { text: displayText });
|
|
221
|
+
}
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
case 'tool-input-start': {
|
|
225
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
226
|
+
const pending = assistantDisplayText(currentAssistantText);
|
|
227
|
+
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
228
|
+
if (!shown && pending)
|
|
229
|
+
toolDisplay.setGroupCaption(pending);
|
|
230
|
+
}
|
|
231
|
+
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
232
|
+
latestToolCalls.set(part.id, toolCall);
|
|
233
|
+
startedTools.set(part.id, Date.now());
|
|
234
|
+
toolDisplay.ensureToolItem(toolCall);
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
case 'tool-call': {
|
|
238
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
239
|
+
const pending = assistantDisplayText(currentAssistantText);
|
|
240
|
+
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
241
|
+
if (!shown && pending)
|
|
242
|
+
toolDisplay.setGroupCaption(pending);
|
|
243
|
+
}
|
|
244
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
245
|
+
latestToolCalls.set(part.toolCallId, toolCall);
|
|
246
|
+
if (!startedTools.has(part.toolCallId))
|
|
247
|
+
startedTools.set(part.toolCallId, Date.now());
|
|
248
|
+
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
249
|
+
toolDisplay.updateToolGroup(true);
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
case 'tool-result': {
|
|
253
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
254
|
+
latestToolCalls.set(part.toolCallId, toolCall);
|
|
255
|
+
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
256
|
+
const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
|
|
257
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
258
|
+
item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
|
|
259
|
+
item.result = toolResultSummary(finish);
|
|
260
|
+
item.durationMs = finish.durationMs;
|
|
261
|
+
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);
|
|
265
|
+
toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
|
|
266
|
+
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
267
|
+
callbacks.setWorkState?.(goal);
|
|
268
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
269
|
+
activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
|
|
270
|
+
if (toolCall.toolName === 'writeTasks')
|
|
271
|
+
callbacks.onTasksChanged?.();
|
|
272
|
+
const nestedTokens = subagentTokenEstimate(part.output);
|
|
273
|
+
if (nestedTokens)
|
|
274
|
+
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 });
|
|
275
|
+
toolDisplay.updateToolGroup(true);
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
case 'tool-error': {
|
|
279
|
+
const existing = latestToolCalls.get(part.toolCallId);
|
|
280
|
+
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
281
|
+
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
282
|
+
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
283
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
284
|
+
item.status = 'error';
|
|
285
|
+
item.result = toolResultSummary(finish);
|
|
286
|
+
item.durationMs = finish.durationMs;
|
|
287
|
+
item.finishedAt = startedAt + finish.durationMs;
|
|
288
|
+
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs }));
|
|
289
|
+
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 } });
|
|
290
|
+
if (isMutatingToolName(toolCall.toolName)) {
|
|
291
|
+
toolResultState = { ...toolResultState, editRecoveryPath: toolInputField(toolCall.input, 'path'), editRecoveryReadSatisfied: false };
|
|
292
|
+
}
|
|
293
|
+
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
294
|
+
callbacks.setWorkState?.(goal);
|
|
295
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
296
|
+
toolDisplay.updateToolGroup(true);
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
case 'error':
|
|
300
|
+
streamError = part.error;
|
|
301
|
+
callbacks.debugLog(`stream error: ${part.error instanceof Error ? part.error.message : String(part.error)}`);
|
|
302
|
+
break;
|
|
303
|
+
case 'finish':
|
|
304
|
+
streamFinished = true;
|
|
305
|
+
callbacks.debugLog(`ToolLoopAgent finished: ${part.finishReason}`);
|
|
306
|
+
break;
|
|
307
|
+
default:
|
|
308
|
+
break;
|
|
873
309
|
}
|
|
874
310
|
}
|
|
875
|
-
let completedConversation = callbacks.getConversation();
|
|
876
311
|
try {
|
|
877
312
|
const response = await result.response;
|
|
878
|
-
completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
|
|
879
|
-
callbacks.setConversation(completedConversation);
|
|
313
|
+
const completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
|
|
314
|
+
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
880
315
|
}
|
|
881
316
|
catch (error) {
|
|
882
|
-
// The turn was aborted or errored mid-stream. If we have any accumulated
|
|
883
|
-
// response messages from completed steps (tracked in onStepFinish), persist
|
|
884
|
-
// them so the next turn inherits the partial work instead of losing it.
|
|
885
317
|
if (latestAccumulatedResponseMessages.length > 0) {
|
|
886
|
-
|
|
887
|
-
const compacted = compactToolHistory(accumulated);
|
|
888
|
-
callbacks.setConversation(compacted.messages);
|
|
889
|
-
if (compacted.compactedResults > 0 || compacted.compactedCalls > 0) {
|
|
890
|
-
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.` });
|
|
891
|
-
}
|
|
892
|
-
callbacks.debugLog(`abort recovery: persisted ${latestAccumulatedResponseMessages.length} response messages before re-throwing`);
|
|
893
|
-
}
|
|
894
|
-
throw streamError ?? error;
|
|
895
|
-
}
|
|
896
|
-
callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
|
|
897
|
-
if (lastFinishReason === 'length' && !sawToolCall && completionContinuationCount < maxCompletionContinuations) {
|
|
898
|
-
completionContinuationCount += 1;
|
|
899
|
-
callbacks.debugLog('output token limit reached, auto-continuing');
|
|
900
|
-
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);
|
|
901
|
-
completedConversation = callbacks.getConversation();
|
|
902
|
-
if (continuation.text) {
|
|
903
|
-
assistantText += '\n' + continuation.text;
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
const combinedAssistantText = assistantDisplayText(assistantText);
|
|
907
|
-
const decideCompletion = (text) => completionDecision({
|
|
908
|
-
request: value,
|
|
909
|
-
goal,
|
|
910
|
-
assistantText: text,
|
|
911
|
-
sawReadOnlyTool,
|
|
912
|
-
sawToolCall,
|
|
913
|
-
mutatingToolSucceeded,
|
|
914
|
-
validationToolSucceeded,
|
|
915
|
-
validationToolFailed,
|
|
916
|
-
editFileFailed,
|
|
917
|
-
editRecoveryPath,
|
|
918
|
-
editRecoveryReasonCode,
|
|
919
|
-
});
|
|
920
|
-
let decision = decideCompletion(combinedAssistantText);
|
|
921
|
-
async function runCompletionLoop(seedConversation, seedText) {
|
|
922
|
-
let loopConversation = seedConversation;
|
|
923
|
-
let latestText = seedText;
|
|
924
|
-
let noProgressSlices = 0;
|
|
925
|
-
while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
|
|
926
|
-
completionContinuationCount += 1;
|
|
927
|
-
const revisionBefore = goal.workState.revision;
|
|
928
|
-
const prompt = decision.continuationPrompt
|
|
929
|
-
?? (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.');
|
|
930
|
-
const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
|
|
931
|
-
loopConversation = callbacks.getConversation();
|
|
932
|
-
if (continuation.text)
|
|
933
|
-
latestText = continuation.text;
|
|
934
|
-
decision = decideCompletion(latestText);
|
|
935
|
-
noProgressSlices = goal.workState.revision === revisionBefore ? noProgressSlices + 1 : 0;
|
|
936
|
-
if (noProgressSlices >= 2)
|
|
937
|
-
break;
|
|
938
|
-
}
|
|
939
|
-
if ((decision.needsActionContinuation || decision.needsValidationContinuation) && noProgressSlices >= 2) {
|
|
940
|
-
callbacks.addMessage({ role: 'assistant', text: 'Status: partial. Two continuation slices made no tool progress; the latest work state and blocker evidence were preserved.' });
|
|
941
|
-
}
|
|
942
|
-
if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
|
|
943
|
-
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.' });
|
|
944
|
-
}
|
|
945
|
-
if (!latestText && toolSummaries.length > 0) {
|
|
946
|
-
const followUp = await streamAssistantResponse(loopConversation, 'completion loop ended without text', noTextAfterToolPrompt(false), false);
|
|
947
|
-
if (!followUp.text)
|
|
948
|
-
callbacks.addMessage({ role: 'assistant', text: `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.` });
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
if (!assistantStarted) {
|
|
952
|
-
const hidden = isHiddenUnstartedFinalText(combinedAssistantText) || isDuplicateVisibleAssistantText(combinedAssistantText);
|
|
953
|
-
if (!hidden) {
|
|
954
|
-
assistantStarted = true;
|
|
955
|
-
currentAssistantStarted = true;
|
|
956
|
-
currentAssistantText = combinedAssistantText;
|
|
957
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
958
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: combinedAssistantText, streaming: true, startedAt: currentAssistantStartedAt });
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
if (assistantStarted) {
|
|
962
|
-
const visibleFinalAssistantText = assistantDisplayText(currentAssistantText);
|
|
963
|
-
const hidden = isHiddenAssistantFragment(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText);
|
|
964
|
-
if (!hidden)
|
|
965
|
-
rememberVisibleAssistantText(visibleFinalAssistantText);
|
|
966
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
|
|
967
|
-
callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalAssistantText, currentAssistantStartedAt) });
|
|
968
|
-
if (decision.needsActionContinuation || decision.needsValidationContinuation) {
|
|
969
|
-
await runCompletionLoop(completedConversation, combinedAssistantText);
|
|
970
|
-
}
|
|
971
|
-
else if (sawToolCall && !textAfterTool) {
|
|
972
|
-
const followUp = await streamAssistantResponse(completedConversation, 'tool use completed without follow-up text', noTextAfterToolPrompt(false), false);
|
|
973
|
-
if (!followUp.text) {
|
|
974
|
-
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.' });
|
|
975
|
-
}
|
|
318
|
+
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages]).messages);
|
|
976
319
|
}
|
|
320
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
321
|
+
const benignTerminatedAfterStream = text === 'terminated' && (streamFinished || assistantText.trim().length > 0 || latestToolCalls.size > 0);
|
|
322
|
+
if (!benignTerminatedAfterStream)
|
|
323
|
+
throw streamError ?? error;
|
|
324
|
+
callbacks.debugLog(`ignored post-stream response error: ${text}`);
|
|
977
325
|
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
const prompt = noTextAfterToolPrompt(allowTools);
|
|
981
|
-
const followUp = await streamAssistantResponse(completedConversation, 'tool-only turn completed without text', prompt, allowTools);
|
|
982
|
-
decision = decideCompletion(followUp.text);
|
|
983
|
-
if (allowTools)
|
|
984
|
-
await runCompletionLoop(callbacks.getConversation(), followUp.text);
|
|
985
|
-
if (!followUp.text && completionContinuationCount === 0) {
|
|
986
|
-
const fallback = toolSummaries.length > 0
|
|
987
|
-
? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
|
|
988
|
-
: 'Finished without a text response.';
|
|
989
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
|
|
990
|
-
}
|
|
326
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
327
|
+
finalizeAssistantSegment();
|
|
991
328
|
}
|
|
992
|
-
else {
|
|
993
|
-
const fallback = 'Finished
|
|
994
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt:
|
|
329
|
+
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) });
|
|
995
332
|
}
|
|
996
333
|
goal.phase = 'done';
|
|
997
334
|
goal.status = 'complete';
|
|
998
|
-
turnStatus = 'complete';
|
|
999
|
-
if (turnStopReason) {
|
|
1000
|
-
callbacks.addMessage({ role: 'system', text: turnStopReason.message });
|
|
1001
|
-
}
|
|
1002
335
|
callbacks.setGoalStatus?.(undefined);
|
|
336
|
+
turnStatus = 'complete';
|
|
1003
337
|
}
|
|
1004
338
|
catch (error) {
|
|
1005
339
|
if (abortController.signal.aborted) {
|
|
1006
340
|
turnStatus = 'aborted';
|
|
1007
341
|
callbacks.debugLog('request aborted');
|
|
1008
|
-
callbacks.addMessage({ role: 'system', text:
|
|
342
|
+
callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
|
|
1009
343
|
}
|
|
1010
344
|
else {
|
|
1011
345
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -1015,8 +349,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
1015
349
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
1016
350
|
if (compacted) {
|
|
1017
351
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
1018
|
-
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session);
|
|
1019
|
-
return;
|
|
352
|
+
return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session, modelOverride);
|
|
1020
353
|
}
|
|
1021
354
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
|
|
1022
355
|
}
|
|
@@ -1026,21 +359,26 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
1026
359
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
1027
360
|
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
1028
361
|
await abortableDelay(delay, abortController.signal);
|
|
1029
|
-
if (abortController.signal.aborted)
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
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);
|
|
1033
367
|
}
|
|
1034
368
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
1035
369
|
}
|
|
1036
370
|
}
|
|
1037
371
|
finally {
|
|
372
|
+
if (loadedMcp?.clients.length)
|
|
373
|
+
await closeMcpClients(loadedMcp.clients);
|
|
1038
374
|
if (idleTimer)
|
|
1039
375
|
clearTimeout(idleTimer);
|
|
1040
|
-
|
|
1041
|
-
|
|
376
|
+
toolDisplay.stopToolTimer();
|
|
377
|
+
toolDisplay.finalizeToolGroup();
|
|
1042
378
|
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
|
|
1043
379
|
callbacks.setAbortController?.(null);
|
|
380
|
+
callbacks.setBusyLabel?.('Haze is thinking');
|
|
1044
381
|
callbacks.setBusy(false);
|
|
1045
382
|
}
|
|
383
|
+
return { status: turnStatus };
|
|
1046
384
|
}
|