@denizokcu/haze 0.7.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 +24 -8
- package/README.md +31 -31
- package/dist/cli/chat/inputSuggestions.js +2 -2
- package/dist/cli/commands/chat.js +46 -20
- package/dist/cli/commands/chatModes.js +1 -1
- package/dist/cli/commands/commandHelp.js +2 -2
- package/dist/cli/commands/formatters.d.ts +6 -0
- package/dist/cli/commands/formatters.js +38 -0
- package/dist/cli/commands/streaming.js +34 -23
- package/dist/cli/commands/wizardSuggestions.js +1 -1
- package/dist/config/providers.js +5 -9
- package/dist/config/settings.d.ts +1 -0
- package/dist/config/settings.js +54 -2
- package/dist/core/agent/compaction.js +2 -2
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/requestAssembly.d.ts +1 -0
- package/dist/core/agent/requestAssembly.js +13 -0
- package/dist/core/bashOutput/registry.js +11 -9
- package/dist/core/goal/completionPolicy.js +1 -1
- package/dist/core/subagent/subagentRunner.d.ts +252 -9
- package/dist/core/subagent/subagentRunner.js +13 -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/client.d.ts +2 -2
- package/dist/llm/client.js +15 -2
- package/dist/llm/hazeTools.d.ts +7709 -364
- package/dist/llm/hazeTools.js +7 -1
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp.js +10 -1
- package/dist/llm/lspTools.d.ts +2310 -101
- package/dist/llm/systemPrompt.js +2 -2
- package/dist/llm/tools/bashTool.d.ts +251 -5
- package/dist/llm/tools/bashTool.js +4 -3
- package/dist/llm/tools/fetchTool.d.ts +1201 -65
- package/dist/llm/tools/fetchTool.js +2 -1
- package/dist/llm/tools/storedOutputTool.d.ts +351 -10
- package/dist/llm/tools/taskTool.d.ts +629 -28
- package/dist/llm/tools/toolContext.d.ts +7 -2
- package/dist/llm/tools/toolContext.js +11 -2
- package/dist/llm/webFetch.js +31 -21
- package/dist/skills/builder/SkillBuilder.js +7 -7
- package/dist/ui/components/TextInput.d.ts +7 -0
- package/dist/ui/components/TextInput.js +10 -0
- package/dist/utils/modelName.d.ts +2 -0
- package/dist/utils/modelName.js +15 -0
- package/examples/skills/files/SKILL.md +1 -1
- package/package.json +14 -14
|
@@ -1,16 +1,16 @@
|
|
|
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
5
|
import { projectContextSection } from '../../llm/systemPrompt.js';
|
|
6
6
|
import { closeMcpClients } from '../../llm/mcp.js';
|
|
7
|
-
import { toolCallSummary, toolResultSummary, formatSeconds } from './formatters.js';
|
|
7
|
+
import { toolCallSummary, toolResultSummary, busyToolLabel, formatSeconds } from './formatters.js';
|
|
8
8
|
import { agentEvent } from '../../core/agent/events.js';
|
|
9
9
|
import { isContextOverflowError, isRetryableModelError } from '../../core/agent/errors.js';
|
|
10
10
|
import { isPlanOnlyRequest } from '../../core/goal/requestClassifier.js';
|
|
11
11
|
import { repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../core/goal/completionPolicy.js';
|
|
12
12
|
import { estimateValueTokens } from '../../core/agent/contextBudget.js';
|
|
13
|
-
import { compactToolHistory, stripSyntheticControls, withSyntheticControl } from '../../core/agent/requestAssembly.js';
|
|
13
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../core/agent/requestAssembly.js';
|
|
14
14
|
import { isDuplicateSkippedOutput, toolInputField, toolOutputOk } from '../../core/agent/toolResults.js';
|
|
15
15
|
import { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
16
16
|
export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
|
|
@@ -21,25 +21,25 @@ import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, sh
|
|
|
21
21
|
import { createToolGroupRenderer } from './streaming/toolGroupRenderer.js';
|
|
22
22
|
import { applyToolResultState, initialToolResultState, isMutatingToolName } from './streaming/toolResultState.js';
|
|
23
23
|
import { abortableDelay, estimateInputBreakdown, extractUsage, rememberContextFilesFromToolOutput, responseCompletionMetrics, retryDelayMs, stepCacheMetrics, subagentTokenEstimate } from './streaming/turnRuntime.js';
|
|
24
|
+
import { toolsContextFor } from '../../llm/tools/toolContext.js';
|
|
25
|
+
import { modelThinkingLabel } from '../../utils/modelName.js';
|
|
24
26
|
function logEntry(log, entry) {
|
|
25
27
|
if (log)
|
|
26
28
|
void logAppend(log, entry).catch(() => undefined);
|
|
27
29
|
}
|
|
28
|
-
function
|
|
30
|
+
function withScopedContextControl(messages, context) {
|
|
29
31
|
const files = context.pendingContextFiles ?? [];
|
|
30
32
|
if (files.length === 0)
|
|
31
33
|
return messages;
|
|
32
34
|
context.pendingContextFiles = [];
|
|
33
|
-
return
|
|
34
|
-
...messages,
|
|
35
|
-
{ role: 'system', content: `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}` },
|
|
36
|
-
];
|
|
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)}`);
|
|
37
36
|
}
|
|
38
37
|
export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride) {
|
|
39
38
|
const displayVal = displayValue ?? value;
|
|
40
39
|
callbacks.onEvent?.(agentEvent({ type: 'turn_start', request: value }));
|
|
41
40
|
callbacks.setBusy(true);
|
|
42
|
-
|
|
41
|
+
let thinkingLabel = modelThinkingLabel(undefined);
|
|
42
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
43
43
|
if (!retryingExistingRequest)
|
|
44
44
|
callbacks.addMessage({ role: 'user', text: displayVal });
|
|
45
45
|
const abortController = new AbortController();
|
|
@@ -51,17 +51,19 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
51
51
|
if (idleTimer)
|
|
52
52
|
clearTimeout(idleTimer);
|
|
53
53
|
idleTimer = setTimeout(() => {
|
|
54
|
-
abortController.abort('
|
|
54
|
+
abortController.abort('haze turn timed out after no model/tool activity.');
|
|
55
55
|
}, IDLE_TIMEOUT_MS);
|
|
56
56
|
};
|
|
57
57
|
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
58
58
|
try {
|
|
59
59
|
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride });
|
|
60
60
|
if (!runtime?.model) {
|
|
61
|
-
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.' });
|
|
62
62
|
turnStatus = 'complete';
|
|
63
63
|
return { status: turnStatus };
|
|
64
64
|
}
|
|
65
|
+
thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
66
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
65
67
|
let activeContextFiles = contextFiles;
|
|
66
68
|
const activeModel = runtime.model;
|
|
67
69
|
const providerSettings = providerRequestSettings(runtime.config);
|
|
@@ -81,6 +83,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
81
83
|
if (estimateValueTokens(requestMessages) > ACTIVE_CONTEXT_TOKEN_BUDGET) {
|
|
82
84
|
requestMessages = compactModelMessages(requestMessages, { tokenBudget: ACTIVE_CONTEXT_TOKEN_BUDGET, workState: goal }).messages;
|
|
83
85
|
}
|
|
86
|
+
requestMessages = withoutSystemMessages(requestMessages);
|
|
84
87
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
85
88
|
const systemPrompt = assembled.systemPrompt;
|
|
86
89
|
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
@@ -143,12 +146,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
143
146
|
tools: availableTools,
|
|
144
147
|
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
|
|
145
148
|
...providerSettings,
|
|
146
|
-
stopWhen:
|
|
147
|
-
|
|
149
|
+
stopWhen: isStepCount(MAIN_STEP_LIMIT),
|
|
150
|
+
runtimeContext: toolExecutionContext,
|
|
151
|
+
toolsContext: toolsContextFor(availableTools, toolExecutionContext),
|
|
148
152
|
prepareStep({ steps, messages }) {
|
|
149
153
|
const toolCalls = steps.flatMap(step => step.toolCalls);
|
|
150
154
|
const repeatedToolNames = uniqueRepeatedToolNames(toolCalls);
|
|
151
|
-
const scopedMessages =
|
|
155
|
+
const scopedMessages = withScopedContextControl(messages, toolExecutionContext);
|
|
152
156
|
const messagesChanged = scopedMessages !== messages;
|
|
153
157
|
if (likelyPlanOnlyRequest && toolResultState.mutatingToolSucceeded)
|
|
154
158
|
return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
|
|
@@ -167,22 +171,22 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
167
171
|
}
|
|
168
172
|
return messagesChanged ? { messages: scopedMessages } : undefined;
|
|
169
173
|
},
|
|
170
|
-
|
|
174
|
+
onStepEnd({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
|
|
171
175
|
if (Array.isArray(response?.messages) && response.messages.length > 0)
|
|
172
176
|
latestAccumulatedResponseMessages = response.messages;
|
|
173
177
|
const stepUsage = stepCacheMetrics(usage);
|
|
174
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 } });
|
|
175
179
|
callbacks.debugLog(`step ${stepNumber} finished: ${finishReason}; text=${text.length}; toolCalls=${toolCalls.length}; toolResults=${toolResults.length}`);
|
|
176
180
|
},
|
|
177
|
-
|
|
178
|
-
const providerUsage = extractUsage({ usage: event.
|
|
181
|
+
onEnd(event) {
|
|
182
|
+
const providerUsage = extractUsage({ usage: event.usage });
|
|
179
183
|
callbacks.recordTokenUsage?.({
|
|
180
184
|
inputTokens: providerUsage.inputTokens,
|
|
181
185
|
outputTokens: providerUsage.outputTokens,
|
|
182
186
|
systemPrompt: inputBreakdown.systemPrompt,
|
|
183
187
|
messages: inputBreakdown.messages,
|
|
184
188
|
toolSchemas: inputBreakdown.toolSchemas,
|
|
185
|
-
outputEstimate: estimateValueTokens(event.
|
|
189
|
+
outputEstimate: estimateValueTokens(event.responseMessages),
|
|
186
190
|
cacheReadTokens: providerUsage.cacheReadTokens,
|
|
187
191
|
cacheWriteTokens: providerUsage.cacheWriteTokens,
|
|
188
192
|
noCacheTokens: providerUsage.noCacheTokens,
|
|
@@ -190,7 +194,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
190
194
|
logicalInputEstimate: inputBreakdown.logicalInputEstimate,
|
|
191
195
|
effectiveNonCachedInput: providerUsage.effectiveNonCachedInput,
|
|
192
196
|
});
|
|
193
|
-
const accumulated = [...stripSyntheticControls(requestMessages), ...event.
|
|
197
|
+
const accumulated = [...stripSyntheticControls(requestMessages), ...event.responseMessages];
|
|
194
198
|
const compacted = compactToolHistory(accumulated);
|
|
195
199
|
callbacks.setConversation(compacted.messages);
|
|
196
200
|
callbacks.debugLog(`conversation updated to ${compacted.messages.length} messages by ToolLoopAgent`);
|
|
@@ -198,10 +202,11 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
198
202
|
});
|
|
199
203
|
resetIdleTimer();
|
|
200
204
|
const result = await agent.stream({ messages: requestMessages, abortSignal: abortController.signal });
|
|
201
|
-
for await (const part of result.
|
|
205
|
+
for await (const part of result.stream) {
|
|
202
206
|
resetIdleTimer();
|
|
203
207
|
switch (part.type) {
|
|
204
208
|
case 'text-delta': {
|
|
209
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
205
210
|
toolDisplay.startFreshToolGroup();
|
|
206
211
|
const delta = sanitizeAssistantText(part.text);
|
|
207
212
|
assistantText += delta;
|
|
@@ -231,6 +236,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
231
236
|
const toolCall = { toolCallId: part.id, toolName: part.toolName, input: {} };
|
|
232
237
|
latestToolCalls.set(part.id, toolCall);
|
|
233
238
|
startedTools.set(part.id, Date.now());
|
|
239
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, {}));
|
|
234
240
|
toolDisplay.ensureToolItem(toolCall);
|
|
235
241
|
break;
|
|
236
242
|
}
|
|
@@ -245,6 +251,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
245
251
|
latestToolCalls.set(part.toolCallId, toolCall);
|
|
246
252
|
if (!startedTools.has(part.toolCallId))
|
|
247
253
|
startedTools.set(part.toolCallId, Date.now());
|
|
254
|
+
callbacks.setBusyLabel?.(busyToolLabel(part.toolName, part.input));
|
|
248
255
|
toolDisplay.ensureToolItem(toolCall).summary = toolCallSummary(part.toolName, part.input);
|
|
249
256
|
toolDisplay.updateToolGroup(true);
|
|
250
257
|
break;
|
|
@@ -308,9 +315,13 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
308
315
|
break;
|
|
309
316
|
}
|
|
310
317
|
}
|
|
318
|
+
if (streamError && !streamFinished) {
|
|
319
|
+
void Promise.resolve(result.responseMessages).catch(() => undefined);
|
|
320
|
+
throw streamError;
|
|
321
|
+
}
|
|
311
322
|
try {
|
|
312
|
-
const
|
|
313
|
-
const completedConversation = [...stripSyntheticControls(requestMessages), ...
|
|
323
|
+
const responseMessages = await result.responseMessages;
|
|
324
|
+
const completedConversation = [...stripSyntheticControls(requestMessages), ...responseMessages];
|
|
314
325
|
callbacks.setConversation(compactToolHistory(completedConversation).messages);
|
|
315
326
|
}
|
|
316
327
|
catch (error) {
|
|
@@ -377,7 +388,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
|
|
|
377
388
|
toolDisplay.finalizeToolGroup();
|
|
378
389
|
callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status: turnStatus }));
|
|
379
390
|
callbacks.setAbortController?.(null);
|
|
380
|
-
callbacks.setBusyLabel?.(
|
|
391
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
381
392
|
callbacks.setBusy(false);
|
|
382
393
|
}
|
|
383
394
|
return { status: turnStatus };
|
|
@@ -118,7 +118,7 @@ export function mcpTransportSuggestions() {
|
|
|
118
118
|
];
|
|
119
119
|
}
|
|
120
120
|
export function skillsSuggestions(settings, skills) {
|
|
121
|
-
return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for
|
|
121
|
+
return [{ value: SKILL_CHOICES.addSkill, description: 'describe a new skill for haze to generate', kind: 'skill' },
|
|
122
122
|
...skills.map(skill => ({
|
|
123
123
|
value: skill.name,
|
|
124
124
|
description: `${skill.description}${isSkillEnabled(settings, skill.name) ? '' : ' · disabled'}`,
|
package/dist/config/providers.js
CHANGED
|
@@ -47,19 +47,15 @@ export function findProvider(settings, name) {
|
|
|
47
47
|
return findByName(configuredProviders(settings), name);
|
|
48
48
|
}
|
|
49
49
|
export function activeProvider(settings) {
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
if (!settings.provider)
|
|
51
|
+
return undefined;
|
|
52
|
+
return configuredProviders(settings).find(provider => provider.name === settings.provider);
|
|
52
53
|
}
|
|
53
54
|
export function activeModel(settings) {
|
|
54
55
|
const provider = activeProvider(settings);
|
|
55
|
-
if (!provider)
|
|
56
|
-
return undefined;
|
|
57
|
-
const model = settings.model && provider.models.includes(settings.model)
|
|
58
|
-
? settings.model
|
|
59
|
-
: provider.models[0];
|
|
60
|
-
if (!model)
|
|
56
|
+
if (!provider || !settings.model || !provider.models.includes(settings.model))
|
|
61
57
|
return undefined;
|
|
62
|
-
return { provider, model };
|
|
58
|
+
return { provider, model: settings.model };
|
|
63
59
|
}
|
|
64
60
|
export function resolveModelSelector(settings, selector) {
|
|
65
61
|
const trimmed = selector.trim();
|
package/dist/config/settings.js
CHANGED
|
@@ -1,13 +1,65 @@
|
|
|
1
1
|
import fs from 'fs-extra';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
3
4
|
import { HAZE_DIR } from './paths.js';
|
|
4
5
|
export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
|
|
6
|
+
const providerSchema = z.object({
|
|
7
|
+
name: z.string(),
|
|
8
|
+
url: z.string(),
|
|
9
|
+
key: z.string().optional(),
|
|
10
|
+
models: z.array(z.string()),
|
|
11
|
+
}).passthrough();
|
|
12
|
+
const lspServerSchema = z.object({
|
|
13
|
+
name: z.string(),
|
|
14
|
+
command: z.string(),
|
|
15
|
+
args: z.array(z.string()).optional(),
|
|
16
|
+
extensions: z.array(z.string()).optional(),
|
|
17
|
+
rootPatterns: z.array(z.string()).optional(),
|
|
18
|
+
enabled: z.boolean().optional(),
|
|
19
|
+
}).passthrough();
|
|
20
|
+
const mcpHeaderSchema = z.object({ name: z.string(), value: z.string() }).passthrough();
|
|
21
|
+
const mcpServerSchema = z.object({
|
|
22
|
+
name: z.string(),
|
|
23
|
+
transport: z.enum(['http', 'sse', 'stdio']),
|
|
24
|
+
url: z.string().optional(),
|
|
25
|
+
command: z.string().optional(),
|
|
26
|
+
args: z.array(z.string()).optional(),
|
|
27
|
+
headers: z.array(mcpHeaderSchema).optional(),
|
|
28
|
+
enabled: z.boolean().optional(),
|
|
29
|
+
}).passthrough();
|
|
30
|
+
const skillSettingSchema = z.object({ name: z.string(), enabled: z.boolean().optional() }).passthrough();
|
|
31
|
+
const settingsSchema = z.object({
|
|
32
|
+
provider: z.string().optional(),
|
|
33
|
+
model: z.string().optional(),
|
|
34
|
+
providers: z.array(providerSchema).optional(),
|
|
35
|
+
lspServers: z.array(lspServerSchema).optional(),
|
|
36
|
+
mcpServers: z.array(mcpServerSchema).optional(),
|
|
37
|
+
skills: z.array(skillSettingSchema).optional(),
|
|
38
|
+
apiKey: z.string().optional(),
|
|
39
|
+
baseURL: z.string().optional(),
|
|
40
|
+
}).passthrough();
|
|
41
|
+
function settingsReadError(error) {
|
|
42
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
43
|
+
return new Error(`Failed to read Haze settings at ${SETTINGS_FILE}: ${message}. Fix or remove the settings file, then retry.`);
|
|
44
|
+
}
|
|
5
45
|
export async function readSettings() {
|
|
6
|
-
|
|
46
|
+
try {
|
|
47
|
+
const raw = await fs.readJson(SETTINGS_FILE);
|
|
48
|
+
return settingsSchema.parse(raw);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
|
|
52
|
+
if (code === 'ENOENT')
|
|
53
|
+
return {};
|
|
54
|
+
throw settingsReadError(error);
|
|
55
|
+
}
|
|
7
56
|
}
|
|
8
57
|
export async function writeSettings(settings) {
|
|
9
58
|
await fs.ensureDir(HAZE_DIR);
|
|
10
|
-
|
|
59
|
+
const parsed = settingsSchema.parse(settings);
|
|
60
|
+
const tempFile = `${SETTINGS_FILE}.${process.pid}.${Date.now()}.tmp`;
|
|
61
|
+
await fs.writeJson(tempFile, parsed, { spaces: 2 });
|
|
62
|
+
await fs.move(tempFile, SETTINGS_FILE, { overwrite: true });
|
|
11
63
|
}
|
|
12
64
|
export async function updateSettings(patch) {
|
|
13
65
|
const next = { ...await readSettings(), ...patch };
|
|
@@ -37,7 +37,7 @@ export function compactModelMessages(messages, options = {}) {
|
|
|
37
37
|
return text ? `- ${message.role}: ${text}` : '';
|
|
38
38
|
}).filter(Boolean).join('\n');
|
|
39
39
|
const summary = [
|
|
40
|
-
'Compacted prior
|
|
40
|
+
'Compacted prior haze conversation. Treat this as continuity context, not a new user request.',
|
|
41
41
|
'Preserve especially: current user goal and success condition; explicit user constraints/preferences/decisions; files created/changed/read; validation commands and pass/fail results; blockers or pending product decisions; exact next action if work was unfinished.',
|
|
42
42
|
'Do not treat older tool outputs as current unless the recent conversation confirms they still apply.',
|
|
43
43
|
options.instructions ? `User compaction instructions: ${options.instructions}` : undefined,
|
|
@@ -48,7 +48,7 @@ export function compactModelMessages(messages, options = {}) {
|
|
|
48
48
|
].filter((line) => line !== undefined).join('\n');
|
|
49
49
|
return {
|
|
50
50
|
compacted: true,
|
|
51
|
-
messages: [{ role: '
|
|
51
|
+
messages: [{ role: 'user', content: `<haze_compaction>\n${summary}\n</haze_compaction>` }, ...recent],
|
|
52
52
|
olderCount: older.length,
|
|
53
53
|
keptCount: recent.length,
|
|
54
54
|
summary,
|
|
@@ -9,5 +9,5 @@ export function isRetryableModelError(error) {
|
|
|
9
9
|
const text = errorText(error);
|
|
10
10
|
if (isContextOverflowError(error) || /quota|billing|balance|auth|api key|invalid request|permission|forbidden|401|403|400/.test(text))
|
|
11
11
|
return false;
|
|
12
|
-
return /overload|rate limit|429|500|502|503|504|network|connection|stream|timeout|timed? out|econnreset|etimedout|fetch failed/.test(text);
|
|
12
|
+
return /overload|rate limit|429|500|502|503|504|network|connection|stream|timeout|timed? out|terminated|econnreset|etimedout|fetch failed/.test(text);
|
|
13
13
|
}
|
|
@@ -2,6 +2,7 @@ import type { ModelMessage } from 'ai';
|
|
|
2
2
|
export declare const SYNTHETIC_CONTROL_OPEN = "<haze_control>";
|
|
3
3
|
export declare function isSyntheticControlMessage(message: ModelMessage): boolean;
|
|
4
4
|
export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
|
|
5
|
+
export declare function withoutSystemMessages(messages: ModelMessage[]): ModelMessage[];
|
|
5
6
|
export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
|
|
6
7
|
export declare function compactToolHistory(messages: ModelMessage[], options?: {
|
|
7
8
|
keepRecentResults?: number;
|
|
@@ -9,6 +9,19 @@ export function isSyntheticControlMessage(message) {
|
|
|
9
9
|
export function stripSyntheticControls(messages) {
|
|
10
10
|
return messages.filter(message => !isSyntheticControlMessage(message));
|
|
11
11
|
}
|
|
12
|
+
export function withoutSystemMessages(messages) {
|
|
13
|
+
return messages.map(message => message.role === 'system'
|
|
14
|
+
? { ...message, role: 'user', content: `<haze_system_context>\n${modelMessageTextForContext(message)}\n</haze_system_context>` }
|
|
15
|
+
: message);
|
|
16
|
+
}
|
|
17
|
+
function modelMessageTextForContext(message) {
|
|
18
|
+
const content = message.content;
|
|
19
|
+
if (typeof content === 'string')
|
|
20
|
+
return content;
|
|
21
|
+
if (!Array.isArray(content))
|
|
22
|
+
return JSON.stringify(content);
|
|
23
|
+
return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : JSON.stringify(part)).join('\n');
|
|
24
|
+
}
|
|
12
25
|
export function withSyntheticControl(messages, control) {
|
|
13
26
|
return [
|
|
14
27
|
...stripSyntheticControls(messages),
|
|
@@ -4,7 +4,7 @@ import { reduceGitOutput } from './reducers/git.js';
|
|
|
4
4
|
import { reduceGhOutput } from './reducers/gh.js';
|
|
5
5
|
import { reduceSearchOutput } from './reducers/search.js';
|
|
6
6
|
import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
|
|
7
|
-
import { isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
|
|
7
|
+
import { capOutputForProcessing, isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
|
|
8
8
|
export const builtInLineFilters = [
|
|
9
9
|
{ name: 'markdownlint', matchCommand: /(^|[;&|]\s*)markdownlint\b/, stripAnsi: true, truncateLinesAt: 200, maxLines: 80, onEmpty: 'markdownlint: ok' },
|
|
10
10
|
{ name: 'shellcheck', matchCommand: /(^|[;&|]\s*)shellcheck\b/, stripAnsi: true, stripLinesMatching: [/^In .* line \d+:/], truncateLinesAt: 200, maxLines: 100, onEmpty: 'shellcheck: ok' },
|
|
@@ -74,8 +74,10 @@ export function filterBashOutput(input) {
|
|
|
74
74
|
stderr = makeReduction(input.stderr, '', input.stderr.length > 0, filterName, input, undefined, 'validation');
|
|
75
75
|
}
|
|
76
76
|
else {
|
|
77
|
-
const
|
|
78
|
-
const
|
|
77
|
+
const stdoutIn = capOutputForProcessing(input.stdout);
|
|
78
|
+
const stderrIn = capOutputForProcessing(input.stderr);
|
|
79
|
+
const git = reduceGitOutput(input.command, stdoutIn, stderrIn);
|
|
80
|
+
const gh = git == null ? reduceGhOutput(input.command, stdoutIn, stderrIn) : undefined;
|
|
79
81
|
if (git != null) {
|
|
80
82
|
filterName = 'git';
|
|
81
83
|
const kind = /^git (?:diff|show):/.test(git) ? 'diff' : 'generic';
|
|
@@ -89,16 +91,16 @@ export function filterBashOutput(input) {
|
|
|
89
91
|
stderr = makeReduction(input.stderr, input.stdout ? '' : gh, true, filterName, input, undefined, kind);
|
|
90
92
|
}
|
|
91
93
|
else {
|
|
92
|
-
const search = reduceSearchOutput(input.command,
|
|
94
|
+
const search = reduceSearchOutput(input.command, stdoutIn, stderrIn);
|
|
93
95
|
if (search != null) {
|
|
94
96
|
filterName = 'search';
|
|
95
97
|
stdout = makeReduction(input.stdout, input.stdout ? search : '', true, filterName, input, undefined, 'search');
|
|
96
98
|
stderr = makeReduction(input.stderr, input.stdout ? '' : search, true, filterName, input, undefined, 'search');
|
|
97
99
|
}
|
|
98
100
|
else {
|
|
99
|
-
const diff = reduceUnifiedDiffOutput(
|
|
100
|
-
const json = diff == null ? reduceJsonOutput(
|
|
101
|
-
const log = diff == null && json == null ? reduceGenericLogOutput(
|
|
101
|
+
const diff = reduceUnifiedDiffOutput(stdoutIn, stderrIn);
|
|
102
|
+
const json = diff == null ? reduceJsonOutput(stdoutIn, stderrIn) : undefined;
|
|
103
|
+
const log = diff == null && json == null ? reduceGenericLogOutput(stdoutIn, stderrIn) : undefined;
|
|
102
104
|
const content = diff ?? json ?? log;
|
|
103
105
|
if (content != null) {
|
|
104
106
|
filterName = diff != null ? 'diff' : json != null ? 'json' : 'log';
|
|
@@ -110,8 +112,8 @@ export function filterBashOutput(input) {
|
|
|
110
112
|
const lineFilter = findLineFilter(builtInLineFilters, input.command);
|
|
111
113
|
if (lineFilter) {
|
|
112
114
|
filterName = lineFilter.name;
|
|
113
|
-
const out = input.stdout ? applyLineFilter(lineFilter, input.command,
|
|
114
|
-
const err = input.stderr ? applyLineFilter(lineFilter, input.command,
|
|
115
|
+
const out = input.stdout ? applyLineFilter(lineFilter, input.command, stdoutIn) : undefined;
|
|
116
|
+
const err = input.stderr ? applyLineFilter(lineFilter, input.command, stderrIn) : undefined;
|
|
115
117
|
stdout = makeReduction(input.stdout, out?.text ?? input.stdout, out?.filtered ?? false, lineFilter.name, input, out?.warning, 'log');
|
|
116
118
|
stderr = makeReduction(input.stderr, err?.text ?? input.stderr, err?.filtered ?? false, lineFilter.name, input, err?.warning, 'log');
|
|
117
119
|
}
|
|
@@ -79,7 +79,7 @@ export function completionDecision(input) {
|
|
|
79
79
|
};
|
|
80
80
|
}
|
|
81
81
|
export function toolLoopBudgetPrompt() {
|
|
82
|
-
return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so
|
|
82
|
+
return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
|
|
83
83
|
}
|
|
84
84
|
export function repeatedToolCallPrompt(toolNames) {
|
|
85
85
|
const names = [...new Set(toolNames)].join(', ');
|