@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.
Files changed (48) hide show
  1. package/CHANGELOG.md +24 -8
  2. package/README.md +31 -31
  3. package/dist/cli/chat/inputSuggestions.js +2 -2
  4. package/dist/cli/commands/chat.js +46 -20
  5. package/dist/cli/commands/chatModes.js +1 -1
  6. package/dist/cli/commands/commandHelp.js +2 -2
  7. package/dist/cli/commands/formatters.d.ts +6 -0
  8. package/dist/cli/commands/formatters.js +38 -0
  9. package/dist/cli/commands/streaming.js +34 -23
  10. package/dist/cli/commands/wizardSuggestions.js +1 -1
  11. package/dist/config/providers.js +5 -9
  12. package/dist/config/settings.d.ts +1 -0
  13. package/dist/config/settings.js +54 -2
  14. package/dist/core/agent/compaction.js +2 -2
  15. package/dist/core/agent/errors.js +1 -1
  16. package/dist/core/agent/requestAssembly.d.ts +1 -0
  17. package/dist/core/agent/requestAssembly.js +13 -0
  18. package/dist/core/bashOutput/registry.js +11 -9
  19. package/dist/core/goal/completionPolicy.js +1 -1
  20. package/dist/core/subagent/subagentRunner.d.ts +252 -9
  21. package/dist/core/subagent/subagentRunner.js +13 -18
  22. package/dist/core/toolOutput/reduction.d.ts +2 -0
  23. package/dist/core/toolOutput/reduction.js +12 -0
  24. package/dist/core/validation/outputParser.js +5 -3
  25. package/dist/llm/client.d.ts +2 -2
  26. package/dist/llm/client.js +15 -2
  27. package/dist/llm/hazeTools.d.ts +7709 -364
  28. package/dist/llm/hazeTools.js +7 -1
  29. package/dist/llm/initPrompt.js +1 -1
  30. package/dist/llm/lsp.js +10 -1
  31. package/dist/llm/lspTools.d.ts +2310 -101
  32. package/dist/llm/systemPrompt.js +2 -2
  33. package/dist/llm/tools/bashTool.d.ts +251 -5
  34. package/dist/llm/tools/bashTool.js +4 -3
  35. package/dist/llm/tools/fetchTool.d.ts +1201 -65
  36. package/dist/llm/tools/fetchTool.js +2 -1
  37. package/dist/llm/tools/storedOutputTool.d.ts +351 -10
  38. package/dist/llm/tools/taskTool.d.ts +629 -28
  39. package/dist/llm/tools/toolContext.d.ts +7 -2
  40. package/dist/llm/tools/toolContext.js +11 -2
  41. package/dist/llm/webFetch.js +31 -21
  42. package/dist/skills/builder/SkillBuilder.js +7 -7
  43. package/dist/ui/components/TextInput.d.ts +7 -0
  44. package/dist/ui/components/TextInput.js +10 -0
  45. package/dist/utils/modelName.d.ts +2 -0
  46. package/dist/utils/modelName.js +15 -0
  47. package/examples/skills/files/SKILL.md +1 -1
  48. package/package.json +14 -14
@@ -1,16 +1,16 @@
1
- import { ToolLoopAgent, stepCountIs } from 'ai';
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 withScopedContextSystem(messages, context) {
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
- callbacks.setBusyLabel?.('Haze is thinking');
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('Haze turn timed out after no model/tool activity.');
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. Haze cannot hallucinate without a model. Progress.' });
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: stepCountIs(MAIN_STEP_LIMIT),
147
- experimental_context: toolExecutionContext,
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 = withScopedContextSystem(messages, toolExecutionContext);
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
- onStepFinish({ stepNumber, text, toolCalls, toolResults, finishReason, usage, response }) {
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
- onFinish(event) {
178
- const providerUsage = extractUsage({ usage: event.totalUsage ?? event.usage });
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.response.messages),
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.response.messages];
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.fullStream) {
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 response = await result.response;
313
- const completedConversation = [...stripSyntheticControls(requestMessages), ...response.messages];
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?.('Haze is thinking');
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 Haze to generate', kind: 'skill' },
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'}`,
@@ -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
- const providers = configuredProviders(settings);
51
- return providers.find(provider => provider.name === settings.provider) ?? providers[0];
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();
@@ -44,6 +44,7 @@ export interface HazeSettings {
44
44
  skills?: HazeSkillSetting[];
45
45
  apiKey?: string;
46
46
  baseURL?: string;
47
+ [key: string]: unknown;
47
48
  }
48
49
  export declare const SETTINGS_FILE: string;
49
50
  export declare function readSettings(): Promise<HazeSettings>;
@@ -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
- return fs.readJson(SETTINGS_FILE).catch(() => ({}));
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
- await fs.writeJson(SETTINGS_FILE, settings, { spaces: 2 });
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 Haze conversation. Treat this as continuity context, not a new user request.',
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: 'system', content: summary }, ...recent],
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 git = reduceGitOutput(input.command, input.stdout, input.stderr);
78
- const gh = git == null ? reduceGhOutput(input.command, input.stdout, input.stderr) : undefined;
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, input.stdout, input.stderr);
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(input.stdout, input.stderr);
100
- const json = diff == null ? reduceJsonOutput(input.stdout, input.stderr) : undefined;
101
- const log = diff == null && json == null ? reduceGenericLogOutput(input.stdout, input.stderr) : undefined;
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, input.stdout) : undefined;
114
- const err = input.stderr ? applyLineFilter(lineFilter, input.command, input.stderr) : undefined;
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 Haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
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(', ');