@denizokcu/haze 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -7
- package/README.md +81 -34
- 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 +331 -906
- 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 +1 -1
- package/dist/cli/commands/commands.js +41 -267
- package/dist/cli/commands/formatters.d.ts +6 -0
- package/dist/cli/commands/formatters.js +50 -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 +9 -25
- package/dist/cli/commands/streaming.js +109 -363
- 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.js +3 -6
- package/dist/config/mcpSettings.js +5 -5
- package/dist/config/providers.js +8 -12
- package/dist/config/settings.d.ts +1 -0
- package/dist/config/settings.js +54 -2
- package/dist/config/skillSettings.js +4 -3
- package/dist/core/agent/budgets.d.ts +6 -0
- package/dist/core/agent/budgets.js +6 -0
- package/dist/core/agent/compaction.js +3 -3
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +1 -7
- package/dist/core/agent/requestAssembly.js +40 -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 +18 -8
- package/dist/core/goal/completionPolicy.js +1 -1
- 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 +258 -5
- package/dist/core/subagent/subagentRunner.js +14 -18
- package/dist/core/toolOutput/reduction.d.ts +2 -0
- package/dist/core/toolOutput/reduction.js +12 -0
- package/dist/core/validation/outputParser.js +5 -3
- package/dist/llm/capabilities.d.ts +12 -0
- package/dist/llm/capabilities.js +10 -0
- package/dist/llm/client.d.ts +3 -2
- package/dist/llm/client.js +26 -4
- package/dist/llm/hazeTools.d.ts +7710 -366
- package/dist/llm/hazeTools.js +46 -567
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp.d.ts +46 -1
- package/dist/llm/lsp.js +19 -10
- package/dist/llm/lspTools.d.ts +2310 -119
- package/dist/llm/mcp.js +9 -0
- package/dist/llm/requestContext.js +7 -22
- package/dist/llm/systemPrompt.d.ts +1 -0
- package/dist/llm/systemPrompt.js +3 -3
- package/dist/llm/tools/bashTool.d.ts +251 -0
- package/dist/llm/tools/bashTool.js +82 -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 +1201 -0
- package/dist/llm/tools/fetchTool.js +46 -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 +351 -0
- package/dist/llm/tools/storedOutputTool.js +17 -0
- package/dist/llm/tools/taskTool.d.ts +629 -0
- package/dist/llm/tools/taskTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +74 -0
- package/dist/llm/tools/toolContext.js +196 -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 +122 -28
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +8 -8
- package/dist/ui/components/TextInput.d.ts +7 -0
- package/dist/ui/components/TextInput.js +10 -98
- 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/modelName.d.ts +2 -0
- package/dist/utils/modelName.js +15 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +40 -0
- package/examples/skills/files/SKILL.md +1 -1
- package/package.json +14 -15
|
@@ -1,229 +1,45 @@
|
|
|
1
|
-
import { ToolLoopAgent,
|
|
1
|
+
import { ToolLoopAgent, isStepCount } from 'ai';
|
|
2
2
|
import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
|
|
3
3
|
import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
|
|
4
4
|
import { assembleRequestContext } from '../../llm/requestContext.js';
|
|
5
|
+
import { projectContextSection } from '../../llm/systemPrompt.js';
|
|
5
6
|
import { closeMcpClients } from '../../llm/mcp.js';
|
|
6
|
-
import {
|
|
7
|
+
import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
|
|
7
8
|
import { agentEvent } from '../../core/agent/events.js';
|
|
8
9
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
9
10
|
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
10
11
|
import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
11
|
-
import {
|
|
12
|
-
import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
|
|
12
|
+
import { estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
13
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } 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';
|
|
13
17
|
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
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';
|
|
14
19
|
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
for (const toolCall of toolCalls) {
|
|
22
|
-
const key = stableToolKey(toolCall);
|
|
23
|
-
if (seen.has(key))
|
|
24
|
-
repeated.add(toolCall.toolName);
|
|
25
|
-
seen.add(key);
|
|
26
|
-
}
|
|
27
|
-
return [...repeated];
|
|
28
|
-
}
|
|
29
|
-
export function toolOnlyStepCount(steps) {
|
|
30
|
-
let count = 0;
|
|
31
|
-
for (const step of [...steps].reverse()) {
|
|
32
|
-
if (step.toolCalls.length === 0 || step.text.trim().length > 0)
|
|
33
|
-
break;
|
|
34
|
-
count += 1;
|
|
35
|
-
}
|
|
36
|
-
return count;
|
|
37
|
-
}
|
|
38
|
-
function sanitizeAssistantText(text) {
|
|
39
|
-
return [...text].filter(char => {
|
|
40
|
-
const code = char.charCodeAt(0);
|
|
41
|
-
return !(code <= 8 || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127 || code === 155);
|
|
42
|
-
}).join('');
|
|
43
|
-
}
|
|
44
|
-
function hideSyntheticToolCallMarkup(text) {
|
|
45
|
-
return text
|
|
46
|
-
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
|
|
47
|
-
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
|
|
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
|
-
}
|
|
74
|
-
function isNonSubstantiveAssistantText(text) {
|
|
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;
|
|
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
|
-
const MAIN_STEP_LIMIT = 64;
|
|
153
|
-
const MAIN_TOOL_CALL_LIMIT = 120;
|
|
154
|
-
const MAIN_TOOL_ONLY_STEP_LIMIT = 24;
|
|
155
|
-
const ACTIVE_CONTEXT_TOKEN_BUDGET = 40_000;
|
|
156
|
-
function toolOutputOk(output, success) {
|
|
157
|
-
if (!success)
|
|
158
|
-
return false;
|
|
159
|
-
return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
|
|
160
|
-
}
|
|
161
|
-
function estimateInputBreakdown(input) {
|
|
162
|
-
const breakdown = contextBreakdown(input);
|
|
163
|
-
return {
|
|
164
|
-
breakdown,
|
|
165
|
-
systemPrompt: breakdown.system,
|
|
166
|
-
messages: Object.values(breakdown.messagesByRole).reduce((sum, value) => sum + value, 0),
|
|
167
|
-
toolSchemas: breakdown.toolSchemas.reduce((sum, value) => sum + value.tokens, 0),
|
|
168
|
-
logicalInputEstimate: breakdown.logicalInputEstimate,
|
|
169
|
-
};
|
|
170
|
-
}
|
|
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';
|
|
24
|
+
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
25
|
+
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
171
26
|
function logEntry(log, entry) {
|
|
172
27
|
if (log)
|
|
173
28
|
void logAppend(log, entry).catch(() => undefined);
|
|
174
29
|
}
|
|
175
|
-
function
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
function extractUsage(event) {
|
|
185
|
-
const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
186
|
-
return {
|
|
187
|
-
inputTokens: event.usage?.inputTokens,
|
|
188
|
-
outputTokens: event.usage?.outputTokens,
|
|
189
|
-
cacheReadTokens,
|
|
190
|
-
cacheWriteTokens: event.usage?.inputTokenDetails?.cacheWriteTokens ?? 0,
|
|
191
|
-
noCacheTokens: event.usage?.inputTokenDetails?.noCacheTokens ?? effectiveNonCachedInput(event.usage?.inputTokens, cacheReadTokens) ?? 0,
|
|
192
|
-
reasoningTokens: event.usage?.outputTokenDetails?.reasoningTokens ?? 0,
|
|
193
|
-
};
|
|
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;
|
|
30
|
+
function withScopedContextControl(messages, context) {
|
|
31
|
+
const files = context.pendingContextFiles ?? [];
|
|
32
|
+
if (files.length === 0)
|
|
33
|
+
return messages;
|
|
34
|
+
context.pendingContextFiles = [];
|
|
35
|
+
return withSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
|
|
202
36
|
}
|
|
203
|
-
function
|
|
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
|
-
}
|
|
222
|
-
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
|
|
37
|
+
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
|
|
223
38
|
const displayVal = displayValue ?? value;
|
|
224
39
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
225
40
|
callbacks.setBusy(true);
|
|
226
|
-
|
|
41
|
+
let thinkingLabel = modelThinkingLabel(undefined);
|
|
42
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
227
43
|
if (!retryingExistingRequest)
|
|
228
44
|
callbacks.addMessage({ role: 'user', text: displayVal });
|
|
229
45
|
const abortController = new AbortController();
|
|
@@ -235,90 +51,19 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
235
51
|
if (idleTimer)
|
|
236
52
|
clearTimeout(idleTimer);
|
|
237
53
|
idleTimer = setTimeout(() => {
|
|
238
|
-
abortController.abort('
|
|
54
|
+
abortController.abort('haze turn timed out after no model/tool activity.');
|
|
239
55
|
}, IDLE_TIMEOUT_MS);
|
|
240
56
|
};
|
|
241
|
-
const
|
|
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
|
-
};
|
|
57
|
+
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
315
58
|
try {
|
|
316
|
-
const runtime = await modelWithConfig(
|
|
59
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
|
|
317
60
|
if (!runtime?.model) {
|
|
318
|
-
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider.
|
|
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.' });
|
|
319
62
|
turnStatus = 'complete';
|
|
320
|
-
return;
|
|
63
|
+
return { status: turnStatus };
|
|
321
64
|
}
|
|
65
|
+
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
66
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
322
67
|
let activeContextFiles = contextFiles;
|
|
323
68
|
const activeModel = runtime.model;
|
|
324
69
|
const providerSettings = providerRequestSettings(runtime.config);
|
|
@@ -328,7 +73,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
328
73
|
if (loadedMcp?.errors.length)
|
|
329
74
|
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
330
75
|
const goal = createSessionGoal(value);
|
|
331
|
-
callbacks.setWorkState?.(goal
|
|
76
|
+
callbacks.setWorkState?.(goal);
|
|
332
77
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
333
78
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
334
79
|
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
@@ -336,8 +81,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
336
81
|
: [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
|
|
337
82
|
let requestMessages = durableRequestMessages;
|
|
338
83
|
if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
|
|
339
|
-
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal
|
|
84
|
+
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
|
|
340
85
|
}
|
|
86
|
+
requestMessages = withoutSystemMessages(requestMessages);
|
|
341
87
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
342
88
|
const systemPrompt = assembled.systemPrompt;
|
|
343
89
|
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
@@ -351,7 +97,8 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
351
97
|
visibleAssistantTexts.add(normalized);
|
|
352
98
|
callbacks.setLastAssistantText(text);
|
|
353
99
|
};
|
|
354
|
-
const
|
|
100
|
+
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
101
|
+
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead: path => toolDisplay.addContextFileRead(path) };
|
|
355
102
|
const startedTools = new Map();
|
|
356
103
|
const latestToolCalls = new Map();
|
|
357
104
|
let latestAccumulatedResponseMessages = [];
|
|
@@ -362,9 +109,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
362
109
|
let currentAssistantText = '';
|
|
363
110
|
let streamError;
|
|
364
111
|
let streamFinished = false;
|
|
365
|
-
let
|
|
366
|
-
let editRecoveryPath;
|
|
367
|
-
let editRecoveryReadSatisfied = false;
|
|
112
|
+
let toolResultState = initialToolResultState();
|
|
368
113
|
const resetAssistantSegment = () => {
|
|
369
114
|
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
370
115
|
assistantStarted = false;
|
|
@@ -374,7 +119,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
374
119
|
const finalizeAssistantSegment = (options = {}) => {
|
|
375
120
|
const finalText = assistantDisplayText(currentAssistantText);
|
|
376
121
|
const normalized = normalizeAssistantText(finalText);
|
|
377
|
-
const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
122
|
+
const hidden = (assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
|
|
123
|
+
|| (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
|
|
124
|
+
|| (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
|
|
125
|
+
|| (normalized.length > 0 && visibleAssistantTexts.has(normalized));
|
|
378
126
|
if (assistantStarted) {
|
|
379
127
|
if (!hidden)
|
|
380
128
|
rememberVisibleAssistantText(finalText);
|
|
@@ -398,58 +146,55 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
398
146
|
tools: availableTools,
|
|
399
147
|
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
400
148
|
...providerSettings,
|
|
401
|
-
stopWhen:
|
|
402
|
-
|
|
149
|
+
stopWhen: isStepCount(MAIN_STEP_LIMIT),
|
|
150
|
+
runtimeContext: toolExecutionContext,
|
|
151
|
+
toolsContext: toolsContextFor(availableTools, toolExecutionContext),
|
|
403
152
|
prepareStep({ steps, messages }) {
|
|
404
153
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
405
154
|
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
if (
|
|
409
|
-
return {
|
|
155
|
+
const scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
156
|
+
const messagesChanged = scopedMessages !== messages;
|
|
157
|
+
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
158
|
+
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
159
|
+
if (toolResultState.editRecoveryPath && !toolResultState.editRecoveryReadSatisfied)
|
|
160
|
+
return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
|
|
410
161
|
if (repeatedToolNames.length > 0) {
|
|
411
162
|
const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
|
|
412
163
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
413
164
|
return activeTools.length > 0
|
|
414
|
-
? { activeTools, messages: withSyntheticControl(
|
|
415
|
-
: { toolChoice: 'none', messages: withSyntheticControl(
|
|
165
|
+
? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
166
|
+
: { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
416
167
|
}
|
|
417
168
|
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= MAIN_TOOL_ONLY_STEP_LIMIT) {
|
|
418
169
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
419
|
-
return { toolChoice: 'none', messages: withSyntheticControl(
|
|
170
|
+
return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
|
|
420
171
|
}
|
|
421
|
-
return undefined;
|
|
172
|
+
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
422
173
|
},
|
|
423
|
-
|
|
174
|
+
onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
424
175
|
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
425
176
|
latestAccumulatedResponseMessages = response.messages;
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
const stepCacheRead = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
429
|
-
const stepCacheWrite = usage?.inputTokenDetails?.cacheWriteTokens ?? 0;
|
|
430
|
-
const stepReasoning = usage?.outputTokenDetails?.reasoningTokens ?? 0;
|
|
431
|
-
const stepNoCache = effectiveNonCachedInput(stepInputTokens, stepCacheRead) ?? 0;
|
|
432
|
-
const stepCacheHitRatio = cacheHitRatio(stepInputTokens, stepCacheRead || undefined);
|
|
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 } });
|
|
177
|
+
const stepUsage = stepCacheMetrics(usage);
|
|
178
|
+
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 } });
|
|
434
179
|
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
435
180
|
},
|
|
436
|
-
|
|
437
|
-
const providerUsage = extractUsage({ usage: event.
|
|
181
|
+
onEnd(event) {
|
|
182
|
+
const providerUsage = extractUsage({ usage: event.usage });
|
|
438
183
|
callbacks.recordTokenUsage?.({
|
|
439
184
|
inputTokens: providerUsage.inputTokens,
|
|
440
185
|
outputTokens: providerUsage.outputTokens,
|
|
441
186
|
systemPrompt: inputBreakdown.systemPrompt,
|
|
442
187
|
messages: inputBreakdown.messages,
|
|
443
188
|
toolSchemas: inputBreakdown.toolSchemas,
|
|
444
|
-
outputEstimate: estimateValueTokens(event.
|
|
189
|
+
outputEstimate: estimateValueTokens(event.responseMessages),
|
|
445
190
|
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
446
191
|
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
447
192
|
noCacheTokens: providerUsage.noCacheTokens,
|
|
448
193
|
reasoningTokens: providerUsage.reasoningTokens,
|
|
449
194
|
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
450
|
-
effectiveNonCachedInput:
|
|
195
|
+
effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
|
|
451
196
|
});
|
|
452
|
-
const accumulated = [...stripSyntheticControls(requestMessages), ...event.
|
|
197
|
+
const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
|
|
453
198
|
const compacted = compactToolHistory(accumulated);
|
|
454
199
|
callbacks.setConversation(compacted.messages);
|
|
455
200
|
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
@@ -457,11 +202,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
457
202
|
});
|
|
458
203
|
resetIdleTimer();
|
|
459
204
|
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
460
|
-
for await (const part of result.
|
|
205
|
+
for await (const part of result.stream) {
|
|
461
206
|
resetIdleTimer();
|
|
462
207
|
switch (part.type) {
|
|
463
208
|
case 'text-delta': {
|
|
464
|
-
|
|
209
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
210
|
+
toolDisplay.startFreshToolGroup();
|
|
465
211
|
const delta = sanitizeAssistantText(part.text);
|
|
466
212
|
assistantText += delta;
|
|
467
213
|
currentAssistantText += delta;
|
|
@@ -481,23 +227,33 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
481
227
|
break;
|
|
482
228
|
}
|
|
483
229
|
case 'tool-input-start': {
|
|
484
|
-
if (currentAssistantText.trim().length > 0 || assistantStarted)
|
|
485
|
-
|
|
230
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
231
|
+
const pending = assistantDisplayText(currentAssistantText);
|
|
232
|
+
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
233
|
+
if (!shown && pending)
|
|
234
|
+
toolDisplay.setGroupCaption(pending);
|
|
235
|
+
}
|
|
486
236
|
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
487
237
|
latestToolCalls.set(part.id, toolCall);
|
|
488
238
|
startedTools.set(part.id, Date.now());
|
|
489
|
-
|
|
239
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
240
|
+
toolDisplay.ensureToolItem(toolCall);
|
|
490
241
|
break;
|
|
491
242
|
}
|
|
492
243
|
case 'tool-call': {
|
|
493
|
-
if (currentAssistantText.trim().length > 0 || assistantStarted)
|
|
494
|
-
|
|
244
|
+
if (currentAssistantText.trim().length > 0 || assistantStarted) {
|
|
245
|
+
const pending = assistantDisplayText(currentAssistantText);
|
|
246
|
+
const shown = finalizeAssistantSegment({ beforeTool: true });
|
|
247
|
+
if (!shown && pending)
|
|
248
|
+
toolDisplay.setGroupCaption(pending);
|
|
249
|
+
}
|
|
495
250
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input };
|
|
496
251
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
497
252
|
if (!startedTools.has(part.toolCallId))
|
|
498
253
|
startedTools.set(part.toolCallId, Date.now());
|
|
499
|
-
|
|
500
|
-
|
|
254
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
255
|
+
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
256
|
+
toolDisplay.updateToolGroup(true);
|
|
501
257
|
break;
|
|
502
258
|
}
|
|
503
259
|
case 'tool-result': {
|
|
@@ -505,7 +261,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
505
261
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
506
262
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
507
263
|
const finish = { toolCall, success: true, output: part.output, durationMs: Date.now() - startedAt };
|
|
508
|
-
const item = ensureToolItem(toolCall);
|
|
264
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
509
265
|
item.status = toolOutputOk(part.output, true) ? 'success' : 'error';
|
|
510
266
|
item.result = toolResultSummary(finish);
|
|
511
267
|
item.durationMs = finish.durationMs;
|
|
@@ -513,23 +269,9 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
513
269
|
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs }));
|
|
514
270
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'tool_result', stream: 'main', toolResult: { id: toolCall.toolCallId, name: toolCall.toolName, success: true, output: part.output, durationMs: finish.durationMs } });
|
|
515
271
|
const ok = toolOutputOk(part.output, true);
|
|
516
|
-
|
|
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
|
-
}
|
|
272
|
+
toolResultState = applyToolResultState(toolResultState, { toolName: toolCall.toolName, input: toolCall.input, output: part.output, ok });
|
|
531
273
|
observeGoalToolEvent(goal, { ...toolCall, success: ok, output: part.output, duplicateSkipped: isDuplicateSkippedOutput(part.output) });
|
|
532
|
-
callbacks.setWorkState?.(goal
|
|
274
|
+
callbacks.setWorkState?.(goal);
|
|
533
275
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
534
276
|
activeContextFiles = rememberContextFilesFromToolOutput(activeContextFiles, part.output);
|
|
535
277
|
if (toolCall.toolName === 'writeTasks')
|
|
@@ -537,7 +279,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
537
279
|
const nestedTokens = subagentTokenEstimate(part.output);
|
|
538
280
|
if (nestedTokens)
|
|
539
281
|
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);
|
|
282
|
+
toolDisplay.updateToolGroup(true);
|
|
541
283
|
break;
|
|
542
284
|
}
|
|
543
285
|
case 'tool-error': {
|
|
@@ -545,21 +287,20 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
545
287
|
const toolCall = { toolCallId: part.toolCallId, toolName: part.toolName, input: part.input ?? existing?.input };
|
|
546
288
|
const startedAt = startedTools.get(part.toolCallId) ?? Date.now();
|
|
547
289
|
const finish = { toolCall, success: false, error: part.error, durationMs: Date.now() - startedAt };
|
|
548
|
-
const item = ensureToolItem(toolCall);
|
|
290
|
+
const item = toolDisplay.ensureToolItem(toolCall);
|
|
549
291
|
item.status = 'error';
|
|
550
292
|
item.result = toolResultSummary(finish);
|
|
551
293
|
item.durationMs = finish.durationMs;
|
|
552
294
|
item.finishedAt = startedAt + finish.durationMs;
|
|
553
295
|
callbacks.onEvent?.(agentEvent({ type: 'tool_end', id: toolCall.toolCallId, name: toolCall.toolName, success: false, error: part.error, durationMs: finish.durationMs }));
|
|
554
296
|
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 (
|
|
556
|
-
|
|
557
|
-
editRecoveryReadSatisfied = false;
|
|
297
|
+
if (isMutatingToolName(toolCall.toolName)) {
|
|
298
|
+
toolResultState = { ...toolResultState, editRecoveryPath: toolInputField(toolCall.input, 'path'), editRecoveryReadSatisfied: false };
|
|
558
299
|
}
|
|
559
|
-
observeGoalToolEvent(goal, { ...toolCall, success: false,
|
|
560
|
-
callbacks.setWorkState?.(goal
|
|
300
|
+
observeGoalToolEvent(goal, { ...toolCall, success: false, output: part.error });
|
|
301
|
+
callbacks.setWorkState?.(goal);
|
|
561
302
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
562
|
-
updateToolGroup(true);
|
|
303
|
+
toolDisplay.updateToolGroup(true);
|
|
563
304
|
break;
|
|
564
305
|
}
|
|
565
306
|
case 'error':
|
|
@@ -574,9 +315,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
574
315
|
break;
|
|
575
316
|
}
|
|
576
317
|
}
|
|
318
|
+
if (streamError && !streamFinished) {
|
|
319
|
+
void Promise.resolve(result.responseMessages).catch(() => undefined);
|
|
320
|
+
throw streamError;
|
|
321
|
+
}
|
|
577
322
|
try {
|
|
578
|
-
const
|
|
579
|
-
const completedConversation = [...stripSyntheticControls(requestMessages), ...
|
|
323
|
+
const responseMessages = await result.responseMessages;
|
|
324
|
+
const completedConversation = [...stripSyntheticControls(requestMessages), ...responseMessages];
|
|
580
325
|
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
581
326
|
}
|
|
582
327
|
catch (error) {
|
|
@@ -593,7 +338,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
593
338
|
finalizeAssistantSegment();
|
|
594
339
|
}
|
|
595
340
|
else if (latestToolCalls.size > 0) {
|
|
596
|
-
const fallback =
|
|
341
|
+
const fallback = 'Finished tool work.';
|
|
597
342
|
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: assistantStartedAt, ...responseCompletionMetrics(fallback, assistantStartedAt) });
|
|
598
343
|
}
|
|
599
344
|
goal.phase = 'done';
|
|
@@ -615,8 +360,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
615
360
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
616
361
|
if (compacted) {
|
|
617
362
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
618
|
-
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session);
|
|
619
|
-
return;
|
|
363
|
+
return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session, modelOverride);
|
|
620
364
|
}
|
|
621
365
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
|
|
622
366
|
}
|
|
@@ -626,10 +370,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
626
370
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
627
371
|
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
628
372
|
await abortableDelay(delay, abortController.signal);
|
|
629
|
-
if (abortController.signal.aborted)
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
373
|
+
if (abortController.signal.aborted) {
|
|
374
|
+
turnStatus = 'aborted';
|
|
375
|
+
return { status: turnStatus };
|
|
376
|
+
}
|
|
377
|
+
return await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session, modelOverride);
|
|
633
378
|
}
|
|
634
379
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
635
380
|
}
|
|
@@ -639,11 +384,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
639
384
|
await closeMcpClients(loadedMcp.clients);
|
|
640
385
|
if (idleTimer)
|
|
641
386
|
clearTimeout(idleTimer);
|
|
642
|
-
stopToolTimer();
|
|
643
|
-
finalizeToolGroup();
|
|
387
|
+
toolDisplay.stopToolTimer();
|
|
388
|
+
toolDisplay.finalizeToolGroup();
|
|
644
389
|
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
|
|
645
390
|
callbacks.setAbortController?.(null);
|
|
646
|
-
callbacks.setBusyLabel?.(
|
|
391
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
647
392
|
callbacks.setBusy(false);
|
|
648
393
|
}
|
|
394
|
+
return { status: turnStatus };
|
|
649
395
|
}
|