@denizokcu/haze 0.3.0 → 0.5.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 +62 -0
- package/README.md +50 -36
- package/dist/cli/commands/chat.d.ts +1 -1
- package/dist/cli/commands/chat.js +244 -94
- package/dist/cli/commands/commands.js +119 -114
- package/dist/cli/commands/streaming.d.ts +37 -5
- package/dist/cli/commands/streaming.js +455 -192
- package/dist/cli/contextReport.d.ts +1 -0
- package/dist/cli/contextReport.js +47 -0
- package/dist/config/contextFiles.d.ts +31 -0
- package/dist/config/contextFiles.js +97 -13
- package/dist/config/providers.d.ts +2 -5
- package/dist/config/providers.js +16 -12
- package/dist/core/agent/compaction.d.ts +3 -0
- package/dist/core/agent/compaction.js +23 -3
- package/dist/core/agent/contextBudget.d.ts +33 -0
- package/dist/core/agent/contextBudget.js +88 -0
- package/dist/core/agent/requestAssembly.d.ts +22 -0
- package/dist/core/agent/requestAssembly.js +157 -0
- package/dist/core/agent/toolOutputStore.d.ts +16 -0
- package/dist/core/agent/toolOutputStore.js +65 -0
- package/dist/core/agent/workState.d.ts +38 -0
- package/dist/core/agent/workState.js +89 -0
- package/dist/core/bashOutput/ansi.d.ts +1 -0
- package/dist/core/bashOutput/ansi.js +7 -0
- package/dist/core/bashOutput/command.d.ts +2 -0
- package/dist/core/bashOutput/command.js +62 -0
- package/dist/core/bashOutput/lineFilter.d.ts +25 -0
- package/dist/core/bashOutput/lineFilter.js +62 -0
- package/dist/core/bashOutput/reducers/content.d.ts +3 -0
- package/dist/core/bashOutput/reducers/content.js +134 -0
- package/dist/core/bashOutput/reducers/git.d.ts +1 -0
- package/dist/core/bashOutput/reducers/git.js +147 -0
- package/dist/core/bashOutput/reducers/search.d.ts +7 -0
- package/dist/core/bashOutput/reducers/search.js +76 -0
- package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
- package/dist/core/bashOutput/reducers/validation.js +41 -0
- package/dist/core/bashOutput/registry.d.ts +4 -0
- package/dist/core/bashOutput/registry.js +126 -0
- package/dist/core/bashOutput/types.d.ts +46 -0
- package/dist/core/bashOutput/types.js +1 -0
- package/dist/core/goal/completionPolicy.d.ts +1 -0
- package/dist/core/goal/completionPolicy.js +5 -1
- package/dist/core/goal/sessionGoal.d.ts +2 -0
- package/dist/core/goal/sessionGoal.js +8 -1
- package/dist/core/log/llmLog.d.ts +68 -0
- package/dist/core/log/llmLog.js +55 -0
- package/dist/core/safety/urlGuard.d.ts +37 -0
- package/dist/core/safety/urlGuard.js +206 -0
- package/dist/core/session/sessionStore.d.ts +6 -0
- package/dist/core/session/sessionStore.js +5 -0
- package/dist/core/subagent/subagentRunner.d.ts +4 -1
- package/dist/core/subagent/subagentRunner.js +5 -15
- package/dist/core/toolOutput/reduction.d.ts +25 -0
- package/dist/core/toolOutput/reduction.js +23 -0
- package/dist/core/validation/outputParser.js +15 -2
- package/dist/llm/client.d.ts +40 -1
- package/dist/llm/client.js +51 -5
- package/dist/llm/hazeTools.d.ts +165 -23
- package/dist/llm/hazeTools.js +317 -65
- package/dist/llm/initPrompt.js +2 -1
- package/dist/llm/systemPrompt.d.ts +6 -1
- package/dist/llm/systemPrompt.js +44 -81
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/webFetch.d.ts +57 -0
- package/dist/llm/webFetch.js +270 -0
- package/dist/skills/builder/SkillBuilder.d.ts +16 -2
- package/dist/skills/builder/SkillBuilder.js +68 -65
- package/dist/skills/skillTools.d.ts +2 -19
- package/dist/skills/skillTools.js +28 -19
- package/dist/ui/components/MarkdownText.d.ts +2 -0
- package/dist/ui/components/MarkdownText.js +116 -3
- package/package.json +18 -10
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { stepCountIs, streamText } from 'ai';
|
|
2
|
-
import {
|
|
2
|
+
import { appendLogEntry as logAppend } from '../../core/log/llmLog.js';
|
|
3
|
+
import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
|
|
3
4
|
import { hazeTools } from '../../llm/hazeTools.js';
|
|
4
5
|
import { buildSystemPrompt } from '../../llm/systemPrompt.js';
|
|
5
6
|
import { loadSkillRegistry } from '../../skills/SkillRegistry.js';
|
|
6
7
|
import { buildSkillTools } from '../../skills/skillTools.js';
|
|
7
|
-
import { compact, toolCallSummary, toolResultSummary,
|
|
8
|
+
import { compact, toolCallSummary, toolResultSummary, formatElapsedTimeWhole, formatSeconds } from './formatters.js';
|
|
8
9
|
import { isActionRequest, isPlanImplementationRequest, isPlanOnlyRequest, isValidationRequest } from '../../core/goal/requestClassifier.js';
|
|
9
|
-
import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
10
|
+
import { completionDecision, looksIncomplete, noTextAfterToolPrompt, postContinuationPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
10
11
|
import { createSessionGoal, formatGoalStatus, observeGoalToolEvent } from '../../core/goal/sessionGoal.js';
|
|
11
12
|
import { agentEvent } from '../../core/agent/events.js';
|
|
12
13
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
13
14
|
import { createSubagentTool } from '../../core/subagent/subagentRunner.js';
|
|
15
|
+
import { contextBreakdown, cacheHitRatio, effectiveNonCachedInput, estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
16
|
+
import { compactToolHistory, stripSyntheticControls, toolRequestSettings, withSyntheticControl } from '../../core/agent/requestAssembly.js';
|
|
17
|
+
import { compactModelMessages } from '../../core/agent/compaction.js';
|
|
18
|
+
import { workStatePrompt } from '../../core/agent/workState.js';
|
|
14
19
|
function stableToolKey(toolCall) {
|
|
15
20
|
return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
|
|
16
21
|
}
|
|
@@ -45,8 +50,70 @@ function hideSyntheticToolCallMarkup(text) {
|
|
|
45
50
|
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*?<\/tool_call>\s*(?:```)?/gi, '$1')
|
|
46
51
|
.replace(/(^|\n)\s*(?:```(?:xml)?\s*)?(?:xml\s*)?<tool_call>[\s\S]*$/i, '$1');
|
|
47
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
|
+
}
|
|
48
78
|
function isNonSubstantiveAssistantText(text) {
|
|
49
|
-
return
|
|
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;
|
|
50
117
|
}
|
|
51
118
|
function assistantDisplayText(text) {
|
|
52
119
|
return hideSyntheticToolCallMarkup(text).trim();
|
|
@@ -82,33 +149,46 @@ async function abortableDelay(milliseconds, signal) {
|
|
|
82
149
|
}
|
|
83
150
|
const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
|
|
84
151
|
const IDLE_TIMEOUT_MS = 5 * 60_000;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
const
|
|
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;
|
|
92
165
|
function toolOutputOk(output, success) {
|
|
93
166
|
if (!success)
|
|
94
167
|
return false;
|
|
95
168
|
return !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
|
|
96
169
|
}
|
|
97
|
-
function
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
+
};
|
|
106
179
|
}
|
|
107
|
-
function
|
|
108
|
-
|
|
180
|
+
function logEntry(log, entry) {
|
|
181
|
+
if (log)
|
|
182
|
+
void logAppend(log, entry).catch(() => undefined);
|
|
109
183
|
}
|
|
110
|
-
function
|
|
111
|
-
|
|
184
|
+
function responseCompletionMetrics(text, generationStartedAt) {
|
|
185
|
+
const finishedAt = Date.now();
|
|
186
|
+
const elapsedSeconds = Math.max((finishedAt - generationStartedAt) / 1000, 0.001);
|
|
187
|
+
const outputTokens = estimateValueTokens(text);
|
|
188
|
+
return {
|
|
189
|
+
finishedAt,
|
|
190
|
+
tokensPerSecond: outputTokens > 0 ? outputTokens / elapsedSeconds : undefined,
|
|
191
|
+
};
|
|
112
192
|
}
|
|
113
193
|
function subagentTokenEstimate(output) {
|
|
114
194
|
if (typeof output !== 'object' || output == null || !('tokens' in output))
|
|
@@ -118,15 +198,21 @@ function subagentTokenEstimate(output) {
|
|
|
118
198
|
const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
|
|
119
199
|
return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
|
|
120
200
|
}
|
|
121
|
-
function
|
|
122
|
-
const
|
|
123
|
-
|
|
201
|
+
function extractUsage(event) {
|
|
202
|
+
const cacheReadTokens = event.usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
|
203
|
+
const reportedNoCache = 'noCacheTokens' in (event.usage?.inputTokenDetails ?? {})
|
|
204
|
+
? (event.usage?.inputTokenDetails).noCacheTokens
|
|
124
205
|
: undefined;
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
+
};
|
|
128
214
|
}
|
|
129
|
-
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false) {
|
|
215
|
+
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session) {
|
|
130
216
|
const displayVal = displayValue ?? value;
|
|
131
217
|
const userMessage = { role: 'user', text: displayVal };
|
|
132
218
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
@@ -136,36 +222,62 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
136
222
|
const abortController = new AbortController();
|
|
137
223
|
callbacks.setAbortController?.(abortController);
|
|
138
224
|
let turnStatus = 'failed';
|
|
225
|
+
let turnStopReason;
|
|
139
226
|
let idleTimer;
|
|
140
227
|
let stopActiveTimers = () => undefined;
|
|
228
|
+
let finalizeToolGroup = () => undefined;
|
|
141
229
|
const resetIdleTimer = () => {
|
|
142
230
|
if (idleTimer)
|
|
143
231
|
clearTimeout(idleTimer);
|
|
144
|
-
idleTimer = setTimeout(() =>
|
|
232
|
+
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
|
+
abortController.abort('Haze turn timed out after no model/tool activity.');
|
|
235
|
+
}, IDLE_TIMEOUT_MS);
|
|
145
236
|
};
|
|
146
237
|
try {
|
|
147
|
-
const
|
|
148
|
-
if (!
|
|
238
|
+
const runtime = await modelWithConfig(session ? { cwd: session.cwd } : undefined);
|
|
239
|
+
if (!runtime?.model) {
|
|
149
240
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. Haze cannot hallucinate without a model. Progress.' });
|
|
150
241
|
return;
|
|
151
242
|
}
|
|
152
|
-
const activeModel =
|
|
243
|
+
const activeModel = runtime.model;
|
|
244
|
+
const providerSettings = providerRequestSettings(runtime.config);
|
|
245
|
+
let activeContextFiles = [...contextFiles];
|
|
246
|
+
const rememberContextFiles = (files) => {
|
|
247
|
+
if (!Array.isArray(files))
|
|
248
|
+
return;
|
|
249
|
+
const seen = new Set(activeContextFiles.map(file => file.path));
|
|
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
|
+
};
|
|
153
260
|
const skillRegistry = await loadSkillRegistry();
|
|
154
|
-
const subagentTool = createSubagentTool({ model: activeModel, contextFiles });
|
|
261
|
+
const subagentTool = createSubagentTool({ model: activeModel, contextFiles: activeContextFiles, session });
|
|
155
262
|
const availableTools = { ...hazeTools, subagent: subagentTool, ...buildSkillTools(skillRegistry) };
|
|
156
263
|
const goal = createSessionGoal(value);
|
|
264
|
+
callbacks.setWorkState?.(goal.workState);
|
|
157
265
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
158
266
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
159
267
|
const likelyPlanImplementationRequest = isPlanImplementationRequest(value);
|
|
160
268
|
const likelyActionRequest = isActionRequest(value);
|
|
161
269
|
const likelyValidationRequest = isValidationRequest(value);
|
|
162
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.';
|
|
163
|
-
const
|
|
164
|
-
? callbacks.getConversation()
|
|
165
|
-
:
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
271
|
+
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
272
|
+
? stripSyntheticControls(callbacks.getConversation())
|
|
273
|
+
: [...stripSyntheticControls(callbacks.getConversation()), { role: 'user', content: value }]).messages;
|
|
274
|
+
let requestMessages = likelyPlanImplementationRequest
|
|
275
|
+
? withSyntheticControl(durableRequestMessages, planImplementationGuidance)
|
|
276
|
+
: durableRequestMessages;
|
|
277
|
+
if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
|
|
278
|
+
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal.workState }).messages;
|
|
279
|
+
}
|
|
280
|
+
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
169
281
|
resetIdleTimer();
|
|
170
282
|
let currentAssistantId = `assistant-${Date.now()}`;
|
|
171
283
|
let assistantStarted = false;
|
|
@@ -184,6 +296,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
184
296
|
let textAfterTool = false;
|
|
185
297
|
let completionContinuationCount = 0;
|
|
186
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 = [];
|
|
187
306
|
let editRecoveryPath;
|
|
188
307
|
let editRecoveryReasonCode;
|
|
189
308
|
let editRecoveryReadSatisfied = false;
|
|
@@ -207,12 +326,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
207
326
|
const normalized = normalizeAssistantText(text);
|
|
208
327
|
return normalized.length > 0 && [...visibleAssistantTexts].some(previous => previous.startsWith(normalized) && previous !== normalized);
|
|
209
328
|
};
|
|
210
|
-
const toolExecutionContext = { inFlightToolCalls: new Map() };
|
|
211
|
-
let toolGroupId = `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
329
|
+
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)) };
|
|
212
330
|
const INLINE_DIFF_LINE_LIMIT = 20;
|
|
213
|
-
const
|
|
214
|
-
let
|
|
215
|
-
let
|
|
331
|
+
const createToolDisplayGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false });
|
|
332
|
+
let activeToolGroup = createToolDisplayGroup();
|
|
333
|
+
let assistantSinceActiveToolGroup = false;
|
|
216
334
|
let toolTimer;
|
|
217
335
|
function stopToolTimer() {
|
|
218
336
|
if (!toolTimer)
|
|
@@ -224,45 +342,32 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
224
342
|
if (toolTimer)
|
|
225
343
|
return;
|
|
226
344
|
toolTimer = setInterval(() => {
|
|
227
|
-
if (
|
|
228
|
-
updateToolGroup(true);
|
|
345
|
+
if (activeToolGroup.items.some(item => item.status === 'running'))
|
|
346
|
+
updateToolGroup(activeToolGroup, true);
|
|
229
347
|
else
|
|
230
348
|
stopToolTimer();
|
|
231
349
|
}, 1000);
|
|
232
350
|
}
|
|
233
351
|
stopActiveTimers = stopToolTimer;
|
|
234
|
-
function renderToolGroup(
|
|
235
|
-
const
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
? [...new Map([...failures, ...changes].map(item => [item.id, item])).values()]
|
|
241
|
-
: visibleItems;
|
|
242
|
-
const grouped = new Map();
|
|
243
|
-
for (const item of compactItems) {
|
|
244
|
-
const key = `${item.status}:${item.summary}:${item.result ?? ''}`;
|
|
245
|
-
const current = grouped.get(key);
|
|
246
|
-
if (current)
|
|
247
|
-
current.count += 1;
|
|
248
|
-
else
|
|
249
|
-
grouped.set(key, { item, count: 1 });
|
|
250
|
-
}
|
|
251
|
-
const rows = [...grouped.values()];
|
|
252
|
-
const compactSuffix = !running && visibleItems.length > 12 ? ` · showing ${compactItems.length} important` : '';
|
|
253
|
-
const elapsedMs = visibleItems.length > 0
|
|
254
|
-
? (running ? Date.now() : Math.max(...visibleItems.map(item => item.finishedAt ?? item.startedAt))) - Math.min(...visibleItems.map(item => item.startedAt))
|
|
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))
|
|
255
358
|
: 0;
|
|
256
|
-
const elapsed =
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
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;
|
|
260
366
|
const lines = [];
|
|
261
|
-
for (const
|
|
367
|
+
for (const item of group.items) {
|
|
262
368
|
const icon = item.status === 'running' ? '…' : item.status === 'success' ? '✓' : '✗';
|
|
263
|
-
const countText = count > 1 ? ` ×${count}` : '';
|
|
264
369
|
const result = item.status === 'running' ? '' : ` — ${item.result ?? item.status}${item.durationMs == null ? '' : ` in ${formatSeconds(item.durationMs)}`}`;
|
|
265
|
-
lines.push(` ${icon} ${item.summary}${
|
|
370
|
+
lines.push(` ${icon} ${item.summary}${result}`);
|
|
266
371
|
if (item.diff && item.diff.length > 0 && (item.diffLineCount ?? item.diff.length) <= INLINE_DIFF_LINE_LIMIT) {
|
|
267
372
|
for (const diffLine of item.diff) {
|
|
268
373
|
const lineNumber = diffLine.type === 'add' ? diffLine.newLine : diffLine.oldLine;
|
|
@@ -282,45 +387,67 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
282
387
|
}
|
|
283
388
|
return [header, ...lines].join('\n');
|
|
284
389
|
}
|
|
285
|
-
function updateToolGroup(streaming = true) {
|
|
286
|
-
const text = renderToolGroup(streaming);
|
|
287
|
-
if (!
|
|
288
|
-
|
|
289
|
-
callbacks.addMessage({ id:
|
|
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 });
|
|
290
395
|
}
|
|
291
396
|
else {
|
|
292
|
-
callbacks.updateMessage(
|
|
397
|
+
callbacks.updateMessage(group.id, { text, streaming });
|
|
293
398
|
}
|
|
294
|
-
if (!streaming)
|
|
295
|
-
toolGroupFinalized = true;
|
|
296
399
|
}
|
|
297
|
-
|
|
298
|
-
if (
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
400
|
+
finalizeToolGroup = () => {
|
|
401
|
+
if (activeToolGroup.started)
|
|
402
|
+
updateToolGroup(activeToolGroup, false);
|
|
403
|
+
};
|
|
404
|
+
function closeToolGroupBeforeAssistantMessage() {
|
|
405
|
+
if (!activeToolGroup.started)
|
|
406
|
+
return undefined;
|
|
407
|
+
const relatedToolStartedAt = activeToolGroup.items.length > 0
|
|
408
|
+
? Math.min(...activeToolGroup.items.map(item => item.startedAt))
|
|
409
|
+
: undefined;
|
|
410
|
+
updateToolGroup(activeToolGroup, false);
|
|
411
|
+
assistantSinceActiveToolGroup = true;
|
|
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;
|
|
303
419
|
}
|
|
304
|
-
|
|
305
|
-
|
|
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);
|
|
306
429
|
startToolTimer();
|
|
307
|
-
updateToolGroup(true);
|
|
308
|
-
|
|
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;
|
|
309
437
|
if (runningSubagents > 0)
|
|
310
438
|
callbacks.setBusyLabel?.(`Running ${runningSubagents} subagent${runningSubagents === 1 ? '' : 's'}`);
|
|
311
439
|
}
|
|
312
440
|
function recordToolDisplayFinish(event) {
|
|
313
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 }));
|
|
314
|
-
const item =
|
|
315
|
-
|
|
316
|
-
return;
|
|
442
|
+
const item = ensureToolDisplayItem(event.toolCall);
|
|
443
|
+
item.startedAt = Math.min(item.startedAt, Date.now() - event.durationMs);
|
|
317
444
|
item.status = toolOutputOk(event.output, event.success) ? 'success' : 'error';
|
|
318
445
|
item.result = toolResultSummary(event);
|
|
319
446
|
item.durationMs = event.durationMs;
|
|
320
447
|
item.finishedAt = item.startedAt + event.durationMs;
|
|
321
|
-
item.hidden = isDuplicateSkippedOutput(event.output);
|
|
322
448
|
if (typeof event.output === 'object' && event.output != null) {
|
|
323
449
|
const output = event.output;
|
|
450
|
+
rememberContextFiles(output.applicableProjectInstructions);
|
|
324
451
|
if (typeof output.diffLineCount === 'number')
|
|
325
452
|
item.diffLineCount = output.diffLineCount;
|
|
326
453
|
if (Array.isArray(output.diff))
|
|
@@ -339,11 +466,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
339
466
|
if (event.toolCall.toolName === 'writeTasks' && event.success) {
|
|
340
467
|
callbacks.onTasksChanged?.();
|
|
341
468
|
}
|
|
342
|
-
const hasRunningTools =
|
|
343
|
-
updateToolGroup(
|
|
469
|
+
const hasRunningTools = activeToolGroup.items.some(candidate => candidate.status === 'running');
|
|
470
|
+
updateToolGroup(activeToolGroup, !assistantSinceActiveToolGroup);
|
|
344
471
|
if (!hasRunningTools)
|
|
345
472
|
stopToolTimer();
|
|
346
|
-
const runningSubagents =
|
|
473
|
+
const runningSubagents = activeToolGroup.items.filter(i => i.status === 'running' && i.summary.startsWith('subagent')).length;
|
|
347
474
|
if (runningSubagents === 0)
|
|
348
475
|
callbacks.setBusyLabel?.('Haze is thinking');
|
|
349
476
|
else
|
|
@@ -355,6 +482,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
355
482
|
const duplicateSkipped = isDuplicateSkippedOutput(event.output);
|
|
356
483
|
const ok = toolOutputOk(event.output, event.success);
|
|
357
484
|
observeGoalToolEvent(goal, { ...event.toolCall, success: ok, output: event.output, duplicateSkipped });
|
|
485
|
+
callbacks.setWorkState?.(goal.workState);
|
|
358
486
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
359
487
|
if (!ok && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolCall.toolName)) {
|
|
360
488
|
editFileFailed = true;
|
|
@@ -386,58 +514,57 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
386
514
|
async function streamAssistantResponse(messages, reason, prompt, allowTools = false) {
|
|
387
515
|
callbacks.debugLog(`requesting assistant ${allowTools ? 'continuation' : 'text'}: ${reason}`);
|
|
388
516
|
const responseId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
389
|
-
|
|
390
|
-
|
|
517
|
+
let responseStarted = false;
|
|
518
|
+
let responseStartedAt = Date.now();
|
|
391
519
|
let responseText = '';
|
|
392
520
|
let continuationToolCalls = 0;
|
|
393
521
|
let followUpStreamError;
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
{
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
const
|
|
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 });
|
|
400
531
|
const followUp = streamText({
|
|
401
532
|
model: activeModel,
|
|
402
533
|
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
403
534
|
system: followUpSystemPrompt,
|
|
404
535
|
messages: continuationMessages,
|
|
405
|
-
|
|
406
|
-
|
|
536
|
+
...toolRequestSettings(availableTools, allowTools),
|
|
537
|
+
...providerSettings,
|
|
407
538
|
stopWhen: stepCountIs(FOLLOW_UP_STEP_LIMIT),
|
|
408
539
|
abortSignal: abortController.signal,
|
|
409
540
|
experimental_context: toolExecutionContext,
|
|
410
541
|
prepareStep({ steps, messages }) {
|
|
411
|
-
|
|
542
|
+
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
543
|
+
continuationToolCalls = toolCalls.length;
|
|
544
|
+
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
412
545
|
if (continuationToolCalls >= FOLLOW_UP_TOOL_CALL_LIMIT || toolOnlyStepCount(steps) >= FOLLOW_UP_TOOL_ONLY_STEP_LIMIT) {
|
|
413
546
|
return {
|
|
414
547
|
toolChoice: 'none',
|
|
415
|
-
messages:
|
|
416
|
-
...messages,
|
|
417
|
-
{ role: 'user', content: toolLoopBudgetPrompt() },
|
|
418
|
-
],
|
|
548
|
+
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
419
549
|
};
|
|
420
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
|
+
}
|
|
421
558
|
if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
|
|
422
559
|
return {
|
|
423
560
|
toolChoice: 'none',
|
|
424
|
-
messages: [
|
|
425
|
-
...messages,
|
|
426
|
-
{ role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
|
|
427
|
-
],
|
|
428
561
|
};
|
|
429
562
|
}
|
|
430
563
|
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
431
564
|
return {
|
|
432
565
|
activeTools: ['readFile'],
|
|
433
|
-
messages: [
|
|
434
|
-
...messages,
|
|
435
|
-
{ role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
|
|
436
|
-
],
|
|
437
566
|
};
|
|
438
567
|
}
|
|
439
|
-
if (editFileFailed)
|
|
440
|
-
return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
|
|
441
568
|
return undefined;
|
|
442
569
|
},
|
|
443
570
|
onError({ error }) {
|
|
@@ -445,22 +572,48 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
445
572
|
callbacks.debugLog(`stream error: ${error instanceof Error ? error.message : String(error)}`);
|
|
446
573
|
},
|
|
447
574
|
onFinish(event) {
|
|
448
|
-
|
|
449
|
-
callbacks.
|
|
450
|
-
|
|
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`);
|
|
451
593
|
},
|
|
452
594
|
experimental_onToolCallStart({ toolCall }) {
|
|
453
595
|
sawToolCall = true;
|
|
454
596
|
recordToolStart(toolCall);
|
|
455
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 } });
|
|
456
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
|
+
}
|
|
457
609
|
},
|
|
458
610
|
experimental_onToolCallFinish(event) {
|
|
459
611
|
resetIdleTimer();
|
|
460
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 } });
|
|
461
614
|
const nestedTokens = subagentTokenEstimate(event.output);
|
|
462
615
|
if (nestedTokens)
|
|
463
|
-
callbacks.
|
|
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 });
|
|
464
617
|
const summary = toolResultSummary(event);
|
|
465
618
|
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
466
619
|
recordToolDisplayFinish(event);
|
|
@@ -471,17 +624,24 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
471
624
|
: `follow-up tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
472
625
|
},
|
|
473
626
|
});
|
|
474
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
|
|
475
|
-
callbacks.addMessage({ id: responseId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: responseStartedAt });
|
|
476
627
|
for await (const rawDelta of followUp.textStream) {
|
|
477
628
|
resetIdleTimer();
|
|
478
629
|
const delta = sanitizeAssistantText(rawDelta);
|
|
479
630
|
responseText += delta;
|
|
480
631
|
const displayText = assistantDisplayText(responseText);
|
|
481
|
-
if (!displayText
|
|
632
|
+
if ((!shouldStartAssistantStream(displayText, responseStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !responseStarted)
|
|
482
633
|
continue;
|
|
483
|
-
|
|
484
|
-
|
|
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
|
+
}
|
|
485
645
|
}
|
|
486
646
|
try {
|
|
487
647
|
await followUp.response;
|
|
@@ -491,25 +651,33 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
491
651
|
}
|
|
492
652
|
const finalText = assistantDisplayText(responseText);
|
|
493
653
|
const visibleFinalText = finalText;
|
|
494
|
-
const hidden =
|
|
654
|
+
const hidden = (responseStarted ? isHiddenAssistantFragment(visibleFinalText) : isHiddenUnstartedFinalText(visibleFinalText)) || isDuplicateVisibleAssistantText(visibleFinalText);
|
|
495
655
|
if (responseStarted) {
|
|
496
656
|
if (!hidden)
|
|
497
657
|
rememberVisibleAssistantText(visibleFinalText);
|
|
498
658
|
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden }));
|
|
499
|
-
callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden,
|
|
659
|
+
callbacks.updateMessage(responseId, { text: visibleFinalText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalText, responseStartedAt) });
|
|
660
|
+
}
|
|
661
|
+
else if (!hidden) {
|
|
662
|
+
rememberVisibleAssistantText(visibleFinalText);
|
|
663
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: responseId, role: 'assistant' }));
|
|
664
|
+
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: responseId, text: visibleFinalText, hidden: false }));
|
|
665
|
+
callbacks.addMessage({ id: responseId, role: 'assistant', text: visibleFinalText, streaming: false, startedAt: responseStartedAt, ...responseCompletionMetrics(visibleFinalText, responseStartedAt) });
|
|
500
666
|
}
|
|
501
667
|
return { text: finalText, id: responseId, started: responseStarted };
|
|
502
668
|
}
|
|
503
669
|
let streamError;
|
|
504
670
|
let lastFinishReason;
|
|
505
|
-
const mainSystemPrompt = buildSystemPrompt(
|
|
506
|
-
const
|
|
671
|
+
const mainSystemPrompt = buildSystemPrompt(activeContextFiles, session);
|
|
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 });
|
|
507
674
|
const result = streamText({
|
|
508
675
|
model: activeModel,
|
|
509
676
|
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
510
677
|
system: mainSystemPrompt,
|
|
511
678
|
messages: requestMessages,
|
|
512
679
|
tools: availableTools,
|
|
680
|
+
...providerSettings,
|
|
513
681
|
stopWhen: stepCountIs(MAIN_STEP_LIMIT),
|
|
514
682
|
abortSignal: abortController.signal,
|
|
515
683
|
experimental_context: toolExecutionContext,
|
|
@@ -525,78 +693,140 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
525
693
|
if (likelyPlanOnlyRequest && mutatingToolSucceeded) {
|
|
526
694
|
return {
|
|
527
695
|
toolChoice: 'none',
|
|
528
|
-
messages: [
|
|
529
|
-
...messages,
|
|
530
|
-
{ role: 'user', content: 'This was a planning request and the plan artifact has been created or updated. Stop using tools and summarize the plan file only; do not implement or validate it.' },
|
|
531
|
-
],
|
|
532
696
|
};
|
|
533
697
|
}
|
|
534
698
|
if (editRecoveryPath && !editRecoveryReadSatisfied) {
|
|
535
699
|
return {
|
|
536
700
|
activeTools: ['readFile'],
|
|
537
|
-
messages: [
|
|
538
|
-
...messages,
|
|
539
|
-
{ role: 'user', content: `A previous edit failed for ${editRecoveryPath}${editRecoveryReasonCode ? ` (${editRecoveryReasonCode})` : ''}. Before any further edit or bash inspection, call readFile on exactly ${editRecoveryPath}. Bash/cat does not satisfy this recovery step.` },
|
|
540
|
-
],
|
|
541
701
|
};
|
|
542
702
|
}
|
|
543
703
|
if (repeatedToolCall) {
|
|
544
704
|
const activeTools = Object.keys(availableTools).filter(name => !repeatedToolNames.includes(name));
|
|
545
705
|
callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
|
|
546
|
-
return
|
|
547
|
-
activeTools,
|
|
548
|
-
messages:
|
|
549
|
-
...messages,
|
|
550
|
-
{ role: 'user', content: `You already called ${repeatedToolNames.join(', ')} with the same input. Do not repeat that tool call. Use a different relevant tool. If this is an action request and no file change has been made yet, continue with edit/write tools rather than summarizing.` },
|
|
551
|
-
],
|
|
552
|
-
};
|
|
553
|
-
}
|
|
554
|
-
if (likelyActionRequest && !mutatingToolSucceeded && consecutiveToolOnlySteps >= 3 && toolCalls.length < MAIN_TOOL_CALL_LIMIT) {
|
|
555
|
-
callbacks.debugLog('nudging action request toward mutation after read-only steps');
|
|
556
|
-
return {
|
|
557
|
-
messages: [
|
|
558
|
-
...messages,
|
|
559
|
-
{ role: 'user', content: 'You have inspected enough for now. This is an action request; make the requested change with editFile, replaceLines, or writeFile instead of saying tools are unavailable or summarizing.' },
|
|
560
|
-
],
|
|
561
|
-
};
|
|
706
|
+
return activeTools.length > 0
|
|
707
|
+
? { activeTools, messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) }
|
|
708
|
+
: { toolChoice: 'none', messages: withSyntheticControl(messages, repeatedToolCallPrompt(repeatedToolNames)) };
|
|
562
709
|
}
|
|
563
710
|
if (toolCalls.length >= MAIN_TOOL_CALL_LIMIT || consecutiveToolOnlySteps >= MAIN_TOOL_ONLY_STEP_LIMIT) {
|
|
564
711
|
callbacks.debugLog('forcing text response to avoid tool loop');
|
|
712
|
+
turnStopReason = toolCalls.length >= MAIN_TOOL_CALL_LIMIT
|
|
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.` };
|
|
565
715
|
return {
|
|
566
716
|
toolChoice: 'none',
|
|
567
|
-
messages:
|
|
568
|
-
...messages,
|
|
569
|
-
{ role: 'user', content: toolLoopBudgetPrompt() },
|
|
570
|
-
],
|
|
717
|
+
messages: withSyntheticControl(messages, toolLoopBudgetPrompt()),
|
|
571
718
|
};
|
|
572
719
|
}
|
|
573
|
-
if (editFileFailed)
|
|
574
|
-
return { activeTools: ['listFiles', 'readFile', 'replaceLines', 'writeFile', 'bash'] };
|
|
575
720
|
return undefined;
|
|
576
721
|
},
|
|
577
|
-
onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason }) {
|
|
722
|
+
onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
723
|
+
for (const toolCall of toolCalls)
|
|
724
|
+
ensureToolDisplayItem(toolCall);
|
|
725
|
+
if (Array.isArray(response?.messages) && response.messages.length > 0) {
|
|
726
|
+
latestAccumulatedResponseMessages = response.messages;
|
|
727
|
+
}
|
|
728
|
+
if (!turnStopReason && stepNumber >= MAIN_STEP_LIMIT - 1) {
|
|
729
|
+
turnStopReason = { kind: 'step_limit', message: `Reached the per-turn step limit (${MAIN_STEP_LIMIT}). Type "continue" to resume — Haze will pick up where it left off.` };
|
|
730
|
+
}
|
|
578
731
|
lastFinishReason = finishReason;
|
|
579
|
-
|
|
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
|
+
}
|
|
580
776
|
},
|
|
581
777
|
onFinish(event) {
|
|
582
|
-
|
|
583
|
-
|
|
778
|
+
const providerUsage = extractUsage(event);
|
|
779
|
+
callbacks.recordTokenUsage?.({
|
|
780
|
+
inputTokens: providerUsage.inputTokens,
|
|
781
|
+
outputTokens: providerUsage.outputTokens,
|
|
782
|
+
systemPrompt: mainInputBreakdown.systemPrompt,
|
|
783
|
+
messages: mainInputBreakdown.messages,
|
|
784
|
+
toolSchemas: mainInputBreakdown.toolSchemas,
|
|
785
|
+
outputEstimate: estimateValueTokens(event.response.messages),
|
|
786
|
+
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
787
|
+
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
788
|
+
noCacheTokens: providerUsage.noCacheTokens,
|
|
789
|
+
reasoningTokens: providerUsage.reasoningTokens,
|
|
790
|
+
logicalInputEstimate: mainInputBreakdown.logicalInputEstimate,
|
|
791
|
+
effectiveNonCachedInput: effectiveNonCachedInput(providerUsage.inputTokens, providerUsage.cacheReadTokens),
|
|
792
|
+
});
|
|
793
|
+
const accumulated = [...stripSyntheticControls(requestMessages), ...event.response.messages];
|
|
794
|
+
const compacted = compactToolHistory(accumulated);
|
|
795
|
+
const nextConversation = compacted.messages;
|
|
584
796
|
callbacks.setConversation(nextConversation);
|
|
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
|
+
}
|
|
585
801
|
callbacks.debugLog(`conversation updated to ${nextConversation.length} messages`);
|
|
586
802
|
},
|
|
587
803
|
experimental_onToolCallStart({ toolCall }) {
|
|
588
804
|
sawToolCall = true;
|
|
589
805
|
recordToolStart(toolCall);
|
|
590
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 } });
|
|
591
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
|
+
}
|
|
592
821
|
},
|
|
593
822
|
experimental_onToolCallFinish(event) {
|
|
594
823
|
resetIdleTimer();
|
|
595
824
|
const summary = toolResultSummary(event);
|
|
596
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 } });
|
|
597
827
|
const nestedTokens = subagentTokenEstimate(event.output);
|
|
598
828
|
if (nestedTokens)
|
|
599
|
-
callbacks.
|
|
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 });
|
|
600
830
|
toolSummaries.push(`${event.toolCall.toolName}: ${summary}`);
|
|
601
831
|
recordToolDisplayFinish(event);
|
|
602
832
|
if (!isDuplicateSkippedOutput(event.output))
|
|
@@ -606,10 +836,6 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
606
836
|
: `tool error: ${event.toolCall.toolName} after ${event.durationMs}ms ${compact(event.error)}`);
|
|
607
837
|
}
|
|
608
838
|
});
|
|
609
|
-
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
610
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: 'Awaiting response…', streaming: true, startedAt: currentAssistantStartedAt });
|
|
611
|
-
assistantStarted = true;
|
|
612
|
-
currentAssistantStarted = true;
|
|
613
839
|
for await (const rawDelta of result.textStream) {
|
|
614
840
|
resetIdleTimer();
|
|
615
841
|
const delta = sanitizeAssistantText(rawDelta);
|
|
@@ -617,9 +843,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
617
843
|
textAfterTool = true;
|
|
618
844
|
if (currentAssistantStarted && currentAssistantText.length > 0 && toolEpoch > currentAssistantToolEpoch) {
|
|
619
845
|
const intermediateText = assistantDisplayText(currentAssistantText);
|
|
620
|
-
const hidden =
|
|
846
|
+
const hidden = isHiddenAssistantFragment(intermediateText) || isDuplicateVisibleAssistantText(intermediateText);
|
|
847
|
+
if (!hidden)
|
|
848
|
+
rememberVisibleAssistantText(intermediateText);
|
|
621
849
|
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: intermediateText, hidden }));
|
|
622
|
-
callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden,
|
|
850
|
+
callbacks.updateMessage(currentAssistantId, { text: intermediateText, streaming: false, hidden, ...responseCompletionMetrics(intermediateText, currentAssistantStartedAt) });
|
|
623
851
|
currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
624
852
|
currentAssistantStarted = false;
|
|
625
853
|
currentAssistantStartedAt = Date.now();
|
|
@@ -629,14 +857,15 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
629
857
|
assistantText += delta;
|
|
630
858
|
currentAssistantText += delta;
|
|
631
859
|
const displayText = assistantDisplayText(currentAssistantText);
|
|
632
|
-
if ((!displayText
|
|
860
|
+
if ((!shouldStartAssistantStream(displayText, currentAssistantStartedAt) || isPrefixOfVisibleAssistantText(displayText)) && !currentAssistantStarted)
|
|
633
861
|
continue;
|
|
634
862
|
if (!currentAssistantStarted) {
|
|
635
863
|
assistantStarted = true;
|
|
636
864
|
currentAssistantStarted = true;
|
|
637
865
|
callbacks.onEvent?.(agentEvent({ type: 'message_start', id: currentAssistantId, role: 'assistant' }));
|
|
638
866
|
currentAssistantStartedAt = Date.now();
|
|
639
|
-
|
|
867
|
+
const displayedStartedAt = closeToolGroupBeforeAssistantMessage() ?? currentAssistantStartedAt;
|
|
868
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: displayText, streaming: true, startedAt: displayedStartedAt });
|
|
640
869
|
}
|
|
641
870
|
else {
|
|
642
871
|
callbacks.onEvent?.(agentEvent({ type: 'message_update', id: currentAssistantId, text: displayText }));
|
|
@@ -646,10 +875,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
646
875
|
let completedConversation = callbacks.getConversation();
|
|
647
876
|
try {
|
|
648
877
|
const response = await result.response;
|
|
649
|
-
completedConversation = [...requestMessages, ...response.messages];
|
|
878
|
+
completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
|
|
650
879
|
callbacks.setConversation(completedConversation);
|
|
651
880
|
}
|
|
652
881
|
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
|
+
if (latestAccumulatedResponseMessages.length > 0) {
|
|
886
|
+
const accumulated = [...stripSyntheticControls(requestMessages), ...latestAccumulatedResponseMessages];
|
|
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
|
+
}
|
|
653
894
|
throw streamError ?? error;
|
|
654
895
|
}
|
|
655
896
|
callbacks.debugLog(`response stream finished; session has ${completedConversation.length} model messages`);
|
|
@@ -680,8 +921,10 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
680
921
|
async function runCompletionLoop(seedConversation, seedText) {
|
|
681
922
|
let loopConversation = seedConversation;
|
|
682
923
|
let latestText = seedText;
|
|
924
|
+
let noProgressSlices = 0;
|
|
683
925
|
while ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount < maxCompletionContinuations) {
|
|
684
926
|
completionContinuationCount += 1;
|
|
927
|
+
const revisionBefore = goal.workState.revision;
|
|
685
928
|
const prompt = decision.continuationPrompt
|
|
686
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.');
|
|
687
930
|
const continuation = await streamAssistantResponse(loopConversation, `completion gate ${completionContinuationCount}`, prompt, true);
|
|
@@ -689,6 +932,12 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
689
932
|
if (continuation.text)
|
|
690
933
|
latestText = continuation.text;
|
|
691
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.' });
|
|
692
941
|
}
|
|
693
942
|
if ((decision.needsActionContinuation || decision.needsValidationContinuation) && completionContinuationCount >= maxCompletionContinuations) {
|
|
694
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.' });
|
|
@@ -699,14 +948,23 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
699
948
|
callbacks.addMessage({ role: 'assistant', text: `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.` });
|
|
700
949
|
}
|
|
701
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
|
+
}
|
|
702
961
|
if (assistantStarted) {
|
|
703
|
-
const hidePreToolFragment = sawToolCall && !textAfterTool;
|
|
704
962
|
const visibleFinalAssistantText = assistantDisplayText(currentAssistantText);
|
|
705
|
-
const hidden =
|
|
963
|
+
const hidden = isHiddenAssistantFragment(visibleFinalAssistantText) || isDuplicateVisibleAssistantText(visibleFinalAssistantText);
|
|
706
964
|
if (!hidden)
|
|
707
965
|
rememberVisibleAssistantText(visibleFinalAssistantText);
|
|
708
966
|
callbacks.onEvent?.(agentEvent({ type: 'message_end', id: currentAssistantId, text: visibleFinalAssistantText, hidden }));
|
|
709
|
-
callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden,
|
|
967
|
+
callbacks.updateMessage(currentAssistantId, { text: visibleFinalAssistantText, streaming: false, hidden, ...responseCompletionMetrics(visibleFinalAssistantText, currentAssistantStartedAt) });
|
|
710
968
|
if (decision.needsActionContinuation || decision.needsValidationContinuation) {
|
|
711
969
|
await runCompletionLoop(completedConversation, combinedAssistantText);
|
|
712
970
|
}
|
|
@@ -728,22 +986,26 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
728
986
|
const fallback = toolSummaries.length > 0
|
|
729
987
|
? `Finished tool work but the model did not produce a final response. Last tool result: ${toolSummaries.at(-1)}.`
|
|
730
988
|
: 'Finished without a text response.';
|
|
731
|
-
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt,
|
|
989
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
|
|
732
990
|
}
|
|
733
991
|
}
|
|
734
992
|
else {
|
|
735
|
-
|
|
993
|
+
const fallback = 'Finished without a text response.';
|
|
994
|
+
callbacks.addMessage({ id: currentAssistantId, role: 'assistant', text: fallback, streaming: false, startedAt: currentAssistantStartedAt, ...responseCompletionMetrics(fallback, currentAssistantStartedAt) });
|
|
736
995
|
}
|
|
737
996
|
goal.phase = 'done';
|
|
738
997
|
goal.status = 'complete';
|
|
739
998
|
turnStatus = 'complete';
|
|
999
|
+
if (turnStopReason) {
|
|
1000
|
+
callbacks.addMessage({ role: 'system', text: turnStopReason.message });
|
|
1001
|
+
}
|
|
740
1002
|
callbacks.setGoalStatus?.(undefined);
|
|
741
1003
|
}
|
|
742
1004
|
catch (error) {
|
|
743
1005
|
if (abortController.signal.aborted) {
|
|
744
1006
|
turnStatus = 'aborted';
|
|
745
1007
|
callbacks.debugLog('request aborted');
|
|
746
|
-
callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
|
|
1008
|
+
callbacks.addMessage({ role: 'system', text: turnStopReason?.message ?? 'Thinking aborted. You can type again.' });
|
|
747
1009
|
}
|
|
748
1010
|
else {
|
|
749
1011
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -753,7 +1015,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
753
1015
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
754
1016
|
if (compacted) {
|
|
755
1017
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
756
|
-
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true);
|
|
1018
|
+
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt, true, true, session);
|
|
757
1019
|
return;
|
|
758
1020
|
}
|
|
759
1021
|
callbacks.addMessage({ role: 'system', text: 'Context overflow detected, but there was not enough conversation history to compact automatically.' });
|
|
@@ -766,7 +1028,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
766
1028
|
await abortableDelay(delay, abortController.signal);
|
|
767
1029
|
if (abortController.signal.aborted)
|
|
768
1030
|
return;
|
|
769
|
-
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered);
|
|
1031
|
+
await runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt + 1, true, contextOverflowRecovered, session);
|
|
770
1032
|
return;
|
|
771
1033
|
}
|
|
772
1034
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
@@ -775,6 +1037,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
775
1037
|
finally {
|
|
776
1038
|
if (idleTimer)
|
|
777
1039
|
clearTimeout(idleTimer);
|
|
1040
|
+
finalizeToolGroup();
|
|
778
1041
|
stopActiveTimers();
|
|
779
1042
|
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
|
|
780
1043
|
callbacks.setAbortController?.(null);
|