@denizokcu/haze 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +7 -1
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -4
  5. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  6. package/dist/cli/chat/sessionLifecycle.js +7 -0
  7. package/dist/cli/chat/wizard/providerHandlers.js +6 -2
  8. package/dist/cli/commands/chat.js +9 -0
  9. package/dist/cli/commands/formatters.d.ts +9 -0
  10. package/dist/cli/commands/formatters.js +19 -2
  11. package/dist/cli/commands/providerWizard.js +2 -0
  12. package/dist/cli/commands/streaming/attemptOutcome.js +2 -2
  13. package/dist/cli/commands/streaming/attemptSetup.js +5 -3
  14. package/dist/cli/commands/streaming/goalSupervisor.js +2 -1
  15. package/dist/cli/commands/streaming/prepareStep.d.ts +12 -1
  16. package/dist/cli/commands/streaming/prepareStep.js +34 -11
  17. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  18. package/dist/cli/commands/streaming/streamLoop.js +10 -3
  19. package/dist/cli/commands/streaming/toolGroupRenderer.js +5 -2
  20. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  21. package/dist/cli/commands/streaming/turnRuntime.js +8 -7
  22. package/dist/config/contextFiles.d.ts +26 -0
  23. package/dist/config/contextFiles.js +53 -5
  24. package/dist/config/hazeBuild.d.ts +43 -0
  25. package/dist/config/hazeBuild.js +92 -0
  26. package/dist/config/modelDiscovery.js +1 -1
  27. package/dist/config/providerPresets.d.ts +2 -0
  28. package/dist/config/providerPresets.js +5 -0
  29. package/dist/config/providers.js +1 -1
  30. package/dist/config/settings.d.ts +18 -1
  31. package/dist/config/settings.js +4 -1
  32. package/dist/core/agent/budgets.d.ts +11 -2
  33. package/dist/core/agent/budgets.js +13 -2
  34. package/dist/core/agent/compaction.d.ts +3 -1
  35. package/dist/core/agent/compaction.js +62 -8
  36. package/dist/core/agent/completionController.d.ts +7 -2
  37. package/dist/core/agent/completionController.js +10 -3
  38. package/dist/core/agent/contextBudget.d.ts +1 -2
  39. package/dist/core/agent/contextBudget.js +16 -3
  40. package/dist/core/agent/events.d.ts +1 -1
  41. package/dist/core/agent/toolOutputStore.d.ts +24 -1
  42. package/dist/core/agent/toolOutputStore.js +27 -6
  43. package/dist/core/agent/turnPolicy.d.ts +12 -2
  44. package/dist/core/agent/turnPolicy.js +27 -2
  45. package/dist/core/agent/workState.d.ts +6 -1
  46. package/dist/core/agent/workState.js +41 -5
  47. package/dist/core/attachments/imageAttachments.d.ts +4 -1
  48. package/dist/core/attachments/imageAttachments.js +7 -3
  49. package/dist/core/limits.d.ts +2 -0
  50. package/dist/core/limits.js +2 -0
  51. package/dist/core/log/llmLog.js +7 -2
  52. package/dist/core/process/backgroundRegistry.d.ts +9 -0
  53. package/dist/core/process/backgroundRegistry.js +12 -1
  54. package/dist/core/process/runBoundedProcess.d.ts +18 -0
  55. package/dist/core/process/runBoundedProcess.js +24 -1
  56. package/dist/core/providerContracts.d.ts +2 -0
  57. package/dist/core/safety/redaction.d.ts +18 -0
  58. package/dist/core/safety/redaction.js +50 -0
  59. package/dist/core/safety/secretPaths.js +54 -5
  60. package/dist/core/safety/untrustedEnvelopes.d.ts +22 -0
  61. package/dist/core/safety/untrustedEnvelopes.js +25 -0
  62. package/dist/core/safety/urlGuard.d.ts +5 -4
  63. package/dist/core/safety/urlGuard.js +12 -3
  64. package/dist/core/session/sessionSlimming.d.ts +3 -1
  65. package/dist/core/session/sessionSlimming.js +10 -1
  66. package/dist/core/session/sessionStore.d.ts +6 -0
  67. package/dist/core/session/sessionStore.js +1 -1
  68. package/dist/core/subagent/contracts.d.ts +3 -0
  69. package/dist/core/subagent/executionProfiles.js +1 -0
  70. package/dist/llm/client.d.ts +4 -1
  71. package/dist/llm/client.js +52 -16
  72. package/dist/llm/hazeBuild.d.ts +9 -0
  73. package/dist/llm/hazeBuild.js +35 -0
  74. package/dist/llm/hazeTools.d.ts +144 -128
  75. package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
  76. package/dist/llm/mcp.js +53 -1
  77. package/dist/llm/requestContext.js +18 -7
  78. package/dist/llm/subagentRunner.d.ts +9 -0
  79. package/dist/llm/subagentRunner.js +52 -15
  80. package/dist/llm/systemPrompt.d.ts +0 -2
  81. package/dist/llm/systemPrompt.js +10 -4
  82. package/dist/llm/toolResultTypes.d.ts +1 -1
  83. package/dist/llm/tools/fetchTool.js +7 -3
  84. package/dist/llm/tools/fileTools.d.ts +128 -128
  85. package/dist/llm/tools/fileTools.js +8 -1
  86. package/dist/llm/tools/gitIgnore.d.ts +7 -0
  87. package/dist/llm/tools/gitIgnore.js +21 -8
  88. package/dist/llm/tools/outputCap.d.ts +5 -2
  89. package/dist/llm/tools/outputCap.js +5 -3
  90. package/dist/llm/tools/readRecovery.js +4 -0
  91. package/dist/llm/tools/replaceInFiles.d.ts +1 -1
  92. package/dist/llm/tools/shellTool.d.ts +16 -0
  93. package/dist/llm/tools/shellTool.js +12 -3
  94. package/dist/llm/tools/toolContext.d.ts +2 -2
  95. package/dist/llm/tools/toolContext.js +4 -4
  96. package/dist/llm/tools/workspaceFile.d.ts +5 -4
  97. package/dist/llm/tools/workspaceFile.js +213 -4
  98. package/dist/skills/SkillRegistry.js +10 -1
  99. package/dist/skills/skillTools.js +19 -1
  100. package/dist/skills/types.d.ts +5 -0
  101. package/dist/ui/codeHighlight.js +6 -1
  102. package/dist/ui/components/MarkdownText.js +7 -1
  103. package/dist/ui/components/StreamingMarkdownText.js +6 -1
  104. package/dist/ui/terminalSanitize.d.ts +23 -0
  105. package/dist/ui/terminalSanitize.js +122 -0
  106. package/package.json +13 -15
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.7.0 - 2026-10-31
4
+
5
+ ### Security
6
+
7
+ - MCP tool results of every size now arrive inside the escaped `<mcp_result>` envelope — previously only oversized results were labeled, leaving short payloads (precisely what an attacker wants) indistinguishable from trusted tool output.
8
+ - One variant-tolerant closer escaper guards all five untrusted containers (`web_content`, `mcp_result`, `project_instructions`, `project_context`, `haze_compaction`), so case- or whitespace-variant closing tags can no longer end an envelope early; compaction summaries and context-path attributes are escaped too.
9
+ - Project instructions discovered mid-turn (main agent and subagents) ride ordinary user messages with the startup framing; the nonce'd control channel carries engine directives only.
10
+ - Terminal control sequences (including OSC 52 clipboard writes and 8-bit C1) are stripped from the Markdown transcript path, not just tool rows.
11
+ - The protected secret-file list extends to database and CLI credential stores (`.pgpass`, `.my.cnf`, `.msmtprc`, cloud configs, other agent stores), browser profile directories, and `~/.haze/settings.json`/`auth.json`; the shell-side prompt rule derives from the same category list, pinned by a drift canary test.
12
+
13
+ ### Fixed
14
+
15
+ - A failed validation whose command carried a trailing bare stderr redirect (e.g. `cd pkg && npm run typecheck 2>&1`) was recorded behind an opaque compound check identity that no later green rerun of the plain command could ever clear, so a fully validated goal could still end `failed` and pause as no-progress. Trailing `2>&1`/`2>/dev/null` are now treated as check-identity noise, and green `&&` chains record per-stage summaries instead of copying one stage's text onto every stage.
16
+ - Repeated identical tool calls are redirected with a one-step instruction appended to the next request instead of removing the tool from it: a model that retried the removed tool hit a step-fatal "unavailable tool" error and lost the provider prefix cache for that step. Identical reruns of recognized validation commands (re-running a test or typecheck after a fix) are never treated as repeats, and the instruction is bounded per attempt.
17
+ - The mid-implementation validation nudge now also fires when earlier validation evidence exists but new mutations have accumulated without a re-validation, so continuation turns with carried evidence no longer run many edits unvalidated.
18
+ - Goal continuation notices for failed validation name the open check kinds (e.g. `open checks: typecheck`), making carried validation debt visible instead of reading as an unexplained "latest validation failed".
19
+
20
+ ## 1.6.1 - 2026-10-24
21
+
22
+ ### Fixed
23
+
24
+ - OpenRouter attribution now sends `HTTP-Referer: https://github.com/DenizOkcu/haze` instead of the docs site, so OpenRouter's app lookup (`/apps/url/...`) resolves against the repository page. `X-Title: Haze` is unchanged; other OpenAI-compatible providers are unaffected.
25
+
3
26
  ## 1.6.0 - 2026-10-24
4
27
 
5
28
  Class-aware idle-stream stall windows so patient local models are not mistaken for dead streams.
package/README.md CHANGED
@@ -2,7 +2,13 @@
2
2
 
3
3
  A minimal LLM harness for your terminal.
4
4
 
5
- ## What's new in 1.6.0
5
+ [![Known Vulnerabilities](https://snyk.io/test/github/DenizOkcu/haze/badge.svg)](https://snyk.io/test/github/DenizOkcu/haze)
6
+
7
+ ## What's new in 1.7.0
8
+
9
+ haze 1.7.0 hardens the untrusted-content boundary: MCP tool results of every size now arrive inside escaped untrusted envelopes, one variant-tolerant escaper guards all untrusted container closers (including compaction summaries), project instructions discovered mid-turn no longer ride the engine control channel, terminal control sequences (including OSC 52 clipboard writes) are stripped from the Markdown transcript path, and the protected secret-file list extends to database/CLI credential stores, browser profiles, and `~/.haze/settings.json`/`auth.json` — with the shell-side prompt rule derived from the same list. It also fixes validation-evidence edge cases around trailing stderr redirects and repeated tool-call redirects.
10
+
11
+ ### Highlights from 1.6.0
6
12
 
7
13
  haze 1.6.0 stops mistaking patient local models for dead streams:
8
14
 
package/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Supported |
6
6
  |---------|-----------|
7
- | Latest minor (`1.6.x`) | Yes — security fixes |
7
+ | Latest minor (`1.7.x`) | Yes — security fixes |
8
8
  | Older minors and pre-1.0 (`0.x`) | No — upgrade required |
9
9
 
10
10
  Security fixes are provided for the latest published minor release. Upgrade to the newest release before reporting an issue that may already have been fixed.
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "name": "@denizokcu/haze",
3
- "version": "1.6.0",
4
- "commit": "18eee57e33c3bf36f6d464a52949acade2562cea",
5
- "builtAt": "2026-10-24T13:09:16.106Z",
6
- "sourceRoot": "/Users/deniz.okcu/development/haze"
3
+ "version": "1.7.0",
4
+ "commit": "eafa483cf06553cbfc52e256f6255ade29b6dc28",
5
+ "builtAt": "2026-10-31T18:45:21.526Z"
7
6
  }
@@ -54,6 +54,8 @@ export interface SessionLifecycleDeps {
54
54
  setTokenUsage: (usage: TokenUsage) => void;
55
55
  /** Manual /compact mode: model-written summary (default) or heuristic excerpt. */
56
56
  manualCompaction?: () => 'llm-summary' | 'heuristic';
57
+ /** Opt-in session-write secret redaction (HZ-9 `redactSessionSecrets` setting). */
58
+ redactSessionSecrets?: () => boolean;
57
59
  /** Called when a resumed session carries an unterminated goal frontier (P1): the UI offers the one-key continue. */
58
60
  onGoalFrontier?: (frontier: GoalLedgerFrontier) => void;
59
61
  debugLog: (line: string) => void;
@@ -35,6 +35,7 @@ export function createSessionLifecycle(deps) {
35
35
  return;
36
36
  }
37
37
  const session = await createSession({ hazeVersion: deps.version, ...(deps.build ? { build: deps.build } : {}) });
38
+ applyRedactionSetting(session);
38
39
  deps.sessionRef.current = session;
39
40
  const selection = deps.modelSelection?.();
40
41
  if (selection)
@@ -52,6 +53,7 @@ export function createSessionLifecycle(deps) {
52
53
  }
53
54
  async function resumeSession(session, replaceTranscript) {
54
55
  const { messages: conversation, workState, parseErrors, goalFrontier, modelSelection } = await restoreSessionState(session);
56
+ applyRedactionSetting(session);
55
57
  deps.sessionRef.current = session;
56
58
  deps.onModelSelection?.(modelSelection);
57
59
  if (!modelSelection) {
@@ -77,6 +79,11 @@ export function createSessionLifecycle(deps) {
77
79
  if (goalFrontier)
78
80
  deps.onGoalFrontier?.(goalFrontier);
79
81
  }
82
+ /** Stamp the opt-in redaction setting onto every session this lifecycle owns (HZ-9). */
83
+ function applyRedactionSetting(session) {
84
+ if (deps.redactSessionSecrets?.())
85
+ session.redactSecrets = true;
86
+ }
80
87
  /** Heuristic-excerpt compaction shared by the sync path and the LLM fallback (F-09). */
81
88
  function compactConversationSync(instructions) {
82
89
  // Manual /compact and overflow recovery use the centralized fallback
@@ -135,9 +135,13 @@ export function createProviderWizardHandlers(deps, ctx) {
135
135
  setProviderDraft({});
136
136
  return;
137
137
  }
138
- setProviderDraft({ name: existingName, url: preset.baseUrl, ...(preset.auth === 'chatgpt-oauth' ? { kind: 'chatgpt-codex' } : {}) });
138
+ setProviderDraft({ name: existingName, url: preset.baseUrl, ...(preset.auth === 'chatgpt-oauth' ? { kind: 'chatgpt-codex' } : preset.kind ? { kind: preset.kind } : {}) });
139
139
  setSuggestedModels(preset.suggestedModels ?? []);
140
- if (preset.auth === 'chatgpt-oauth') {
140
+ if (preset.requiresEndpoint) {
141
+ setMode('providerAddUrl');
142
+ showMessage('haze.build API base URL? Use your deployed HTTPS endpoint ending in /v1 (or a loopback tunnel).');
143
+ }
144
+ else if (preset.auth === 'chatgpt-oauth') {
141
145
  await loginWithChatGpt({ name: existingName, url: preset.baseUrl, models: preset.suggestedModels ?? [] });
142
146
  }
143
147
  else if (preset.needsApiKey) {
@@ -126,6 +126,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
126
126
  const llmLogRef = useRef(undefined);
127
127
  const persistenceWarningShownRef = useRef(false);
128
128
  const skillErrorSignatureRef = useRef('');
129
+ const skillNoticeSignatureRef = useRef('');
129
130
  const projectSkillSignatureRef = useRef('');
130
131
  const contextFileSignaturesRef = useRef(new Map());
131
132
  const followUps = useFollowUpQueue(text => setMessages(m => [...m, { role: 'system', text }]));
@@ -264,6 +265,13 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
264
265
  setMessages(messages => [...messages, { role: 'system', text: `Invalid skills were isolated:\n${errorSignature}` }]);
265
266
  }
266
267
  skillErrorSignatureRef.current = errorSignature;
268
+ // Visible load-time shadow notices (HZA-6): a project skill silently
269
+ // overriding a same-named user skill is something the user should see.
270
+ const noticeSignature = (registry.notices ?? []).join('\n');
271
+ if (noticeSignature && noticeSignature !== skillNoticeSignatureRef.current) {
272
+ setMessages(messages => [...messages, { role: 'system', text: noticeSignature }]);
273
+ }
274
+ skillNoticeSignatureRef.current = noticeSignature;
267
275
  return nextSkills;
268
276
  }
269
277
  function skillInvocation(value) {
@@ -316,6 +324,7 @@ function ChatScreen({ debug = false, version, build, continueSession = false, re
316
324
  clearLiveMessages,
317
325
  setTokenUsage,
318
326
  manualCompaction: () => settings.manualCompaction ?? 'llm-summary',
327
+ redactSessionSecrets: () => settings.redactSessionSecrets === true,
319
328
  // P1 resume path: an unterminated goal frontier detected on resume becomes
320
329
  // the same one-key continue affordance the in-process pause uses — the
321
330
  // goal continues from the stored frontier without re-sending the request.
@@ -1,5 +1,14 @@
1
1
  export declare function compact(value: unknown, maxLength?: number): string;
2
+ /**
3
+ * One-line summary of a tool call for the transcript rows. Wraps the raw
4
+ * builder: paths, patterns, and commands are model/repo-derived, so terminal
5
+ * control sequences are stripped at this sink (HZA-3).
6
+ */
2
7
  export declare function toolCallSummary(toolName: string, input: unknown): string;
8
+ /**
9
+ * One-line summary of a tool result for the transcript rows; same terminal
10
+ * control-sequence sink discipline as `toolCallSummary` (HZA-3).
11
+ */
3
12
  export declare function toolResultSummary(event: {
4
13
  success: boolean;
5
14
  output?: unknown;
@@ -1,4 +1,5 @@
1
1
  import { formatBytes } from '../../utils/format.js';
2
+ import { stripTerminalControlSequences } from '../../ui/terminalSanitize.js';
2
3
  export function compact(value, maxLength = 180) {
3
4
  let text;
4
5
  if (value instanceof Error) {
@@ -16,7 +17,15 @@ export function compact(value, maxLength = 180) {
16
17
  return ''; // empty object: nothing useful to render; avoid "[object Object]"
17
18
  return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text;
18
19
  }
20
+ /**
21
+ * One-line summary of a tool call for the transcript rows. Wraps the raw
22
+ * builder: paths, patterns, and commands are model/repo-derived, so terminal
23
+ * control sequences are stripped at this sink (HZA-3).
24
+ */
19
25
  export function toolCallSummary(toolName, input) {
26
+ return stripTerminalControlSequences(toolCallSummaryText(toolName, input));
27
+ }
28
+ function toolCallSummaryText(toolName, input) {
20
29
  const data = input;
21
30
  if (toolName === 'shell' && typeof data?.command === 'string') {
22
31
  const mode = data.background === true ? ' (background)' : typeof data.timeoutSeconds === 'number' ? ` (timeout ${data.timeoutSeconds}s)` : '';
@@ -70,7 +79,14 @@ export function toolCallSummary(toolName, input) {
70
79
  return `${toolName} ${data.path}:${data.line}:${data.column}`;
71
80
  return `${toolName} ${compact(input)}`;
72
81
  }
82
+ /**
83
+ * One-line summary of a tool result for the transcript rows; same terminal
84
+ * control-sequence sink discipline as `toolCallSummary` (HZA-3).
85
+ */
73
86
  export function toolResultSummary(event) {
87
+ return stripTerminalControlSequences(toolResultSummaryText(event));
88
+ }
89
+ function toolResultSummaryText(event) {
74
90
  const output = event.output;
75
91
  if (!event.success)
76
92
  return `failed: ${compact(event.error ?? output?.error ?? event.output)}`;
@@ -137,11 +153,12 @@ export function toolResultSummary(event) {
137
153
  }
138
154
  return 'completed';
139
155
  }
140
- if (output.reasonCode === 'secret_file_protected') {
156
+ if (output.reasonCode === 'secret_file_protected' || output.reasonCode === 'git_internals_protected') {
141
157
  // Protection events are visible but distinct from ordinary failures so
142
158
  // the developer can audit them at a glance; never print file contents.
143
159
  const protectedPath = typeof output.path === 'string' && output.path ? ` (${compact(output.path, 80)})` : '';
144
- return `blocked: protected secret file${protectedPath}`;
160
+ const kind = output.reasonCode === 'secret_file_protected' ? 'protected secret file' : 'protected git internals';
161
+ return `blocked: ${kind}${protectedPath}`;
145
162
  }
146
163
  const reason = typeof output.reasonCode === 'string' ? ` (${output.reasonCode})` : '';
147
164
  return typeof output.error === 'string' ? `failed${reason}: ${compact(output.error)}` : `failed${reason}`;
@@ -126,6 +126,8 @@ export function providerSetImageCapable(settings, providerName, enabled) {
126
126
  const provider = providerName ? findProvider(settings, providerName) : undefined;
127
127
  if (!provider)
128
128
  return { message: 'No provider selected.' };
129
+ if (enabled && provider.kind === 'haze-build')
130
+ return { provider, message: 'haze.build haze0.1-coder-flash is text/tools only; images are not supported.' };
129
131
  const capabilities = { ...(provider.capabilities ?? {}), images: enabled };
130
132
  return {
131
133
  provider,
@@ -3,7 +3,7 @@ import { agentEvent } from '../../../core/agent/events.js';
3
3
  import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
4
4
  import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
6
- import { deriveValidationOutcome, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
6
+ import { checkKindsOfIds, deriveValidationOutcome, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
7
7
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
8
8
  import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
9
9
  import { formatSeconds } from '../../../utils/format.js';
@@ -148,7 +148,7 @@ export function finalizeAttemptOutcome(deps) {
148
148
  discardRejectedFinal();
149
149
  if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
150
150
  turnState.validationContinuationUsed = true;
151
- return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress), turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
151
+ return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress, checkKindsOfIds(unresolvedFailedCheckIds(goal))), taskCountsOf(turnState.taskProgress), turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
152
152
  }
153
153
  else if (rescueSlice && rescueSlice.steps > 0) {
154
154
  return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
@@ -1,5 +1,5 @@
1
1
  import { readSettings } from '../../../config/settings.js';
2
- import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, resolveStreamIdleTimeoutMs, withToolExecutionBudget } from '../../../core/agent/budgets.js';
2
+ import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, resolveStreamIdleTimeoutMs, usesPatientIdleWindow, withToolExecutionBudget } from '../../../core/agent/budgets.js';
3
3
  import { agentEvent } from '../../../core/agent/events.js';
4
4
  import { goalDirectionPrompt, isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
5
5
  import { projectPreflight } from '../../../core/agent/projectPreflight.js';
@@ -52,6 +52,8 @@ export async function prepareAttempt(deps) {
52
52
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
53
53
  return undefined;
54
54
  }
55
+ for (const warning of runtime.config.warnings ?? [])
56
+ callbacks.addMessage({ role: 'system', text: warning });
55
57
  const thinkingLabel = modelThinkingLabel(runtime.config.modelName);
56
58
  callbacks.setBusyLabel?.(thinkingLabel);
57
59
  // Observable requested-vs-effective reasoning policy (safe: level strings + reason only).
@@ -106,7 +108,7 @@ export async function prepareAttempt(deps) {
106
108
  // window minus system prompt, tool schemas, output reserve, and a safety
107
109
  // margin — not a fixed 40K constant. Small contexts get a safe budget; the
108
110
  // assembled request plus output reserve stays within configured capacity.
109
- const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
111
+ const requestedOutputTokens = Math.min(runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS, Math.max(1, runtime.config.contextWindowTokens - 1000));
110
112
  const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: systemPrompt, tools: availableTools });
111
113
  // A context-overflow retry progressively shrinks the target so it cannot loop
112
114
  // at an unchanged budget; further overflows get even smaller (RH-005, Pillar
@@ -193,7 +195,7 @@ export async function prepareAttempt(deps) {
193
195
  toolCategories,
194
196
  modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
195
197
  retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
196
- streamIdleTimeoutMs: resolveStreamIdleTimeoutMs(turnSettings.streamIdleTimeoutMs, isLocalProviderUrl(runtime.config.baseURL)),
198
+ streamIdleTimeoutMs: resolveStreamIdleTimeoutMs(turnSettings.streamIdleTimeoutMs, usesPatientIdleWindow(isLocalProviderUrl(runtime.config.baseURL), runtime.config.providerKind)),
197
199
  steeringProfile,
198
200
  };
199
201
  }
@@ -1,5 +1,6 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
3
+ import { checkKindsOfIds } from '../../../core/agent/workState.js';
3
4
  import { classifyRequestIntent, goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
4
5
  import { runAgentTurn } from '../streaming.js';
5
6
  import { goalCheckpointSignature, hashRequest } from './goalCheckpoint.js';
@@ -29,7 +30,7 @@ function countsToTaskProgress(counts) {
29
30
  /** Human-readable continuation reason for a checkpoint; stored-goal frontiers may predate a specific readiness. */
30
31
  function checkpointReason(checkpoint) {
31
32
  return checkpoint.readiness
32
- ? describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)
33
+ ? describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined, checkKindsOfIds(checkpoint.failedCheckIds ?? []))
33
34
  : 'the previous run ended before the goal was complete';
34
35
  }
35
36
  function carriedOf(checkpoint) {
@@ -1,5 +1,7 @@
1
+ import type { ModelMessage } from 'ai';
1
2
  import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
2
3
  import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
4
+ import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
3
5
  import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
4
6
  import type { AttemptSetup } from './attemptSetup.js';
5
7
  import type { AttemptLoopState } from './streamLoop.js';
@@ -8,7 +10,7 @@ import type { TurnExecutionState } from '../../../core/agent/completionControlle
8
10
  * The per-step request preparation decision tree (extracted from
9
11
  * streamLoop.ts): scoped context injection, mid-turn compaction, and the
10
12
  * ordered model-constraint guards (rescue synthesis, plan-only finals,
11
- * malformed-tool retries, edit recovery, repeated-tool suppression, budget
13
+ * malformed-tool retries, edit recovery, repeated-tool redirection, budget
12
14
  * exhaustion). Each guard returns the step's tool-choice/messages override or
13
15
  * falls through to the default request.
14
16
  */
@@ -16,6 +18,15 @@ type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLo
16
18
  type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
17
19
  type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
18
20
  type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
21
+ /**
22
+ * Late-discovered scoped AGENTS.md/CLAUDE.md content rides an ordinary user
23
+ * message with the standard `<project_instructions>` framing — never the
24
+ * nonce'd `<haze_control>` channel, which is engine-directives-only (R2-HZ-3).
25
+ * The message is durable conversation: it survives control stripping and must
26
+ * not rewrite the already-sent provider prefix, so it is appended like any
27
+ * other user turn message.
28
+ */
29
+ export declare function appendScopedContextUserMessage(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
19
30
  export declare function createRepairToolCall(deps: {
20
31
  callbacks: StreamCallbacks;
21
32
  loopState: AttemptLoopState;
@@ -3,17 +3,25 @@ import { earlyValidationPrompt, editRecoveryReadPrompt, malformedToolCallPrompt,
3
3
  import { estimateConversationTokens } from '../../../core/agent/contextBudget.js';
4
4
  import { compactModelMessages } from '../../../core/agent/compaction.js';
5
5
  import { appendSyntheticControl, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
6
+ import { scopedContextMessage } from '../../../config/contextFiles.js';
6
7
  import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
7
8
  import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
8
- import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
9
- import { projectContextSection } from '../../../llm/systemPrompt.js';
9
+ import { MAIN_TOOL_CALL_LIMIT, REPEATED_TOOL_NUDGE_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
10
10
  import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
11
- function withScopedContextControl(messages, context) {
11
+ /**
12
+ * Late-discovered scoped AGENTS.md/CLAUDE.md content rides an ordinary user
13
+ * message with the standard `<project_instructions>` framing — never the
14
+ * nonce'd `<haze_control>` channel, which is engine-directives-only (R2-HZ-3).
15
+ * The message is durable conversation: it survives control stripping and must
16
+ * not rewrite the already-sent provider prefix, so it is appended like any
17
+ * other user turn message.
18
+ */
19
+ export function appendScopedContextUserMessage(messages, context) {
12
20
  const files = context.pendingContextFiles ?? [];
13
21
  if (files.length === 0)
14
22
  return messages;
15
23
  context.pendingContextFiles = [];
16
- return appendSyntheticControl(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)}`);
24
+ return [...messages, scopedContextMessage('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.', files)];
17
25
  }
18
26
  export function createRepairToolCall(deps) {
19
27
  const { callbacks, loopState } = deps;
@@ -47,7 +55,7 @@ export function createPrepareStep(deps) {
47
55
  // therefore resets at each resource epoch; retain only bounded policy
48
56
  // metadata in loopState instead of holding prior StepResult graphs.
49
57
  const repeatedToolNames = steps.length > 0 ? latestRepeatedToolNames(steps) : loopState.latestRepeatedToolNames;
50
- let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
58
+ let scopedMessages = appendScopedContextUserMessage(messages, toolExecutionContext);
51
59
  let messagesChanged = scopedMessages !== messages;
52
60
  // Re-evaluate the accumulated request size before each provider call and
53
61
  // compact old tool history when it exceeds the model-aware budget, so a
@@ -106,13 +114,28 @@ export function createPrepareStep(deps) {
106
114
  return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, `The failed mutation of ${loopState.toolResultState.editRecoveryPath} requires a fresh read, but readFile is unavailable in this bounded recovery slice. Report the unfinished edit as blocked; do not claim it succeeded.`) };
107
115
  }
108
116
  if (repeatedToolNames.length > 0) {
109
- const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
110
- callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
111
- return activeTools.length > 0
112
- ? { activeTools, messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
113
- : { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
117
+ // Instruct, never restrict: narrowing the request's tool set downgrades
118
+ // a model's retry of the removed tool into a step-fatal
119
+ // AI_NoSuchToolError and rewrites the request prefix (observed
120
+ // 2026-10-30 session 30fd6f) — the lesson the edit-recovery path above
121
+ // already learned. The prompt redirects; genuine loops stay bounded by
122
+ // the tool-only and tool-call budget guards below.
123
+ loopState.repeatedToolNudges += 1;
124
+ if (loopState.repeatedToolNudges <= REPEATED_TOOL_NUDGE_LIMIT) {
125
+ callbacks.debugLog(`instructing against repeated tools: ${repeatedToolNames.join(', ')}`);
126
+ return { messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
127
+ }
128
+ callbacks.debugLog('repeated-tool instruction limit reached; budget guards take over');
114
129
  }
115
- if (!loopState.earlyValidationNudgeIssued && goal.mutationCount >= (setup.steeringProfile === 'compact' ? 4 : 8) && goal.validationSeq === 0 && 'shell' in sliceTools) {
130
+ const nudgeThreshold = setup.steeringProfile === 'compact' ? 4 : 8;
131
+ // Nudge both when nothing ever validated and when the latest validation
132
+ // went stale: carried evidence seeds validationSeq > 0, which once left
133
+ // 22 minutes of edits unvalidated across continuation turns (observed
134
+ // 2026-10-30 session 30fd6f).
135
+ const neverValidated = goal.validationSeq === 0 && goal.mutationCount >= nudgeThreshold;
136
+ const staleValidation = goal.validationSeq > 0 && goal.mutationSeq > goal.validationSeq
137
+ && goal.mutationCount - (goal.mutationCountAtLastValidation ?? 0) >= nudgeThreshold;
138
+ if (!loopState.earlyValidationNudgeIssued && (neverValidated || staleValidation) && 'shell' in sliceTools) {
116
139
  loopState.earlyValidationNudgeIssued = true;
117
140
  return { messages: appendSyntheticControl(scopedMessages, earlyValidationPrompt()) };
118
141
  }
@@ -47,6 +47,8 @@ export interface AttemptLoopState {
47
47
  generatedToolCalls: number;
48
48
  consecutiveToolOnlySteps: number;
49
49
  latestRepeatedToolNames: string[];
50
+ /** Bounded count of repeated-tool instructions this attempt; stops nagging past the limit. */
51
+ repeatedToolNudges: number;
50
52
  seenToolCallFingerprints: Set<string>;
51
53
  /** The current epoch rewrote history because the real context budget fired. */
52
54
  contextCompactedInEpoch: boolean;
@@ -5,7 +5,8 @@ import { contextTokensFromUsage, estimateConversationTokens, estimateValueTokens
5
5
  import { stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
6
6
  import { buildLlmCompactionPrompt, chooseBoundaryCompactionMethod, compactModelMessages, compactModelMessagesWithSummary, extractExistingCompactionSummary } from '../../../core/agent/compaction.js';
7
7
  import { isLengthStopOverflow, isSilentContextOverflow } from '../../../core/agent/overflow.js';
8
- import { COMPACTION_LLM_MAX_OUTPUT_TOKENS, COMPACTION_LLM_MIN_OLDER_TOKENS, DEFAULT_MAX_OUTPUT_TOKENS } from '../../../core/agent/budgets.js';
8
+ import { isValidationRerunToolCall } from '../../../core/agent/turnPolicy.js';
9
+ import { COMPACTION_LLM_MAX_OUTPUT_TOKENS, COMPACTION_LLM_MIN_OLDER_TOKENS } from '../../../core/agent/budgets.js';
9
10
  import { toolsContextFor } from '../../../llm/tools/toolContext.js';
10
11
  import { busyToolLabel, toolCallSummary } from '../formatters.js';
11
12
  import { sanitizeAssistantText, assistantDisplayText, normalizeAssistantText, shouldStartAssistantStream } from './assistantText.js';
@@ -49,6 +50,7 @@ export function createAttemptLoopState(previousAssistantText, contextFiles, call
49
50
  generatedToolCalls: 0,
50
51
  consecutiveToolOnlySteps: 0,
51
52
  latestRepeatedToolNames: [],
53
+ repeatedToolNudges: 0,
52
54
  seenToolCallFingerprints: new Set(),
53
55
  contextCompactedInEpoch: false,
54
56
  lastUsage: undefined,
@@ -71,6 +73,10 @@ function recordCompletedStep(loopState, input) {
71
73
  const keyed = toolCallFingerprint(toolCall);
72
74
  if (!keyed)
73
75
  continue;
76
+ // Validation reruns are legitimate red→green evidence; never track them
77
+ // for repetition (shared rule with turnPolicy's step-based detection).
78
+ if (isValidationRerunToolCall(toolCall))
79
+ continue;
74
80
  if (loopState.seenToolCallFingerprints.has(keyed.fingerprint))
75
81
  repeated.add(keyed.toolName);
76
82
  loopState.seenToolCallFingerprints.add(keyed.fingerprint);
@@ -210,7 +216,7 @@ async function runAgentEpoch(deps, requestMessages) {
210
216
  model: setup.runtime.model,
211
217
  instructions: systemPrompt,
212
218
  tools: sliceTools,
213
- ...(!omitMaxOutputTokens ? { maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS } : {}),
219
+ ...(!omitMaxOutputTokens ? { maxOutputTokens: setup.requestBudget.outputReserveTokens } : {}),
214
220
  ...providerSettings,
215
221
  // One provider request + its tool batch per SDK object graph. A normal
216
222
  // ToolLoopAgent would make the same next provider request internally.
@@ -362,7 +368,8 @@ async function compactAtEpochBoundary(deps, providerMessages) {
362
368
  const summarization = await generateText({
363
369
  model: setup.runtime.model,
364
370
  prompt,
365
- maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
371
+ ...(setup.runtime.config.providerKind === 'haze-build' ? { ...setup.providerSettings, reasoning: 'none' } : {}),
372
+ maxOutputTokens: Math.min(COMPACTION_LLM_MAX_OUTPUT_TOKENS, setup.runtime.config.maxOutputTokens ?? COMPACTION_LLM_MAX_OUTPUT_TOKENS),
366
373
  abortSignal: abortController.signal,
367
374
  });
368
375
  const summaryText = summarization.text.trim();
@@ -1,6 +1,7 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
3
3
  import { toolCallSummary, compact } from '../formatters.js';
4
+ import { stripTerminalControlSequences } from '../../../ui/terminalSanitize.js';
4
5
  import { formatElapsedTimeWhole, formatSeconds } from '../../../utils/format.js';
5
6
  function logEntry(log, entry) {
6
7
  if (log)
@@ -25,14 +26,16 @@ export function toolDiffFromResult(toolCall, output) {
25
26
  return [{ type: 'gap', omittedLines: line.omittedLines }];
26
27
  }
27
28
  if (line.type === 'meta' && typeof line.text === 'string')
28
- return [{ type: 'meta', text: line.text }];
29
+ return [{ type: 'meta', text: stripTerminalControlSequences(line.text) }];
29
30
  if ((line.type !== 'add' && line.type !== 'remove' && line.type !== 'context') || typeof line.text !== 'string')
30
31
  return [];
32
+ // File content is untrusted: strip terminal control sequences before the
33
+ // line reaches Ink/the terminal (OSC 52 clipboard writes, OSC 8 links, CSI).
31
34
  return [{
32
35
  type: line.type,
33
36
  ...(typeof line.oldLine === 'number' ? { oldLine: line.oldLine } : {}),
34
37
  ...(typeof line.newLine === 'number' ? { newLine: line.newLine } : {}),
35
- text: line.text,
38
+ text: stripTerminalControlSequences(line.text),
36
39
  }];
37
40
  });
38
41
  if (lines.length === 0)
@@ -1,5 +1,5 @@
1
1
  import type { ModelMessage } from 'ai';
2
- import type { ContextFile } from '../../../config/contextFiles.js';
2
+ import { type ContextFile } from '../../../config/contextFiles.js';
3
3
  import type { LlmLog } from '../../../core/log/llmLog.js';
4
4
  import { type LlmLogEntry } from '../../../core/log/llmLog.js';
5
5
  export interface TokenUsage {
@@ -1,3 +1,4 @@
1
+ import { parseProjectInstructionsBlocks } from '../../../config/contextFiles.js';
1
2
  import { appendLogEntry as logAppend } from '../../../core/log/llmLog.js';
2
3
  import { cacheHitRatio, contextBreakdown, effectiveNonCachedInput, estimateValueTokens } from '../../../core/agent/contextBudget.js';
3
4
  import { DEFAULT_RETRY_BASE_DELAY_MS } from '../../../core/agent/budgets.js';
@@ -78,16 +79,16 @@ export function rememberContextFilesFromToolOutput(activeContextFiles, output) {
78
79
  const files = output.applicableProjectInstructions;
79
80
  if (!Array.isArray(files))
80
81
  return activeContextFiles;
82
+ // Tool results carry framed `<project_instructions>` blocks (untrusted
83
+ // framing, escaped content), never raw ContextFile objects (HZA-1).
84
+ const discovered = parseProjectInstructionsBlocks(files);
81
85
  const seen = new Set(activeContextFiles.map(file => file.path));
82
86
  const next = [...activeContextFiles];
83
- for (const file of files) {
84
- if (typeof file !== 'object' || file == null)
87
+ for (const file of discovered) {
88
+ if (seen.has(file.path))
85
89
  continue;
86
- const candidate = file;
87
- if (typeof candidate.path !== 'string' || typeof candidate.content !== 'string' || seen.has(candidate.path))
88
- continue;
89
- next.push({ path: candidate.path, content: candidate.content });
90
- seen.add(candidate.path);
90
+ next.push(file);
91
+ seen.add(file.path);
91
92
  }
92
93
  return next;
93
94
  }
@@ -1,3 +1,4 @@
1
+ import type { ModelMessage } from 'ai';
1
2
  export interface ContextFile {
2
3
  path: string;
3
4
  content: string;
@@ -38,6 +39,23 @@ export declare function readScopedContextFilesForPath(targetPath: string, option
38
39
  alreadyLoadedSignatures?: ReadonlyMap<string, string>;
39
40
  onContextFileRead?: (path: string) => void;
40
41
  }): Promise<ContextFile[]>;
42
+ /**
43
+ * Render context files as framed/escaped `<project_instructions>` blocks.
44
+ * Used both by `projectContextSection` (trusted prompt framing, shared intro)
45
+ * and by tool-result surfaces that surface scoped files outside the prompt
46
+ * section; each block carries the untrusted intro so the framing never
47
+ * depends on prompt position (HZA-1).
48
+ */
49
+ export declare function projectInstructionsBlocks(contextFiles: ContextFile[], options?: {
50
+ intro?: boolean;
51
+ }): string[];
52
+ /**
53
+ * Parse framed `<project_instructions>` blocks (as produced by
54
+ * `projectInstructionsBlocks`) back into `ContextFile`s, undoing the closing
55
+ * tag escape. Unknown shapes are skipped; used by the turn accumulator that
56
+ * re-surfaces scoped files from tool results.
57
+ */
58
+ export declare function parseProjectInstructionsBlocks(blocks: readonly string[]): ContextFile[];
41
59
  /**
42
60
  * Render loaded context files as the trusted-framing `<project_context>` block
43
61
  * embedded in prompts. Lives here (next to the ContextFile type) so both the
@@ -45,6 +63,14 @@ export declare function readScopedContextFilesForPath(targetPath: string, option
45
63
  * `core` importing `llm`.
46
64
  */
47
65
  export declare function projectContextSection(contextFiles: ContextFile[]): string;
66
+ /**
67
+ * Ordinary user-role message delivering late-discovered scoped context files
68
+ * (R2-HZ-3). Reuses `projectContextSection` so the framing is byte-identical
69
+ * to the startup path, but rides the durable user channel — never the nonce'd
70
+ * `<haze_control>` engine-directive channel, so repo-controlled guidance
71
+ * cannot execute with directive authority.
72
+ */
73
+ export declare function scopedContextMessage(lead: string, contextFiles: ContextFile[]): ModelMessage;
48
74
  export declare function contextFileDiagnostics(files: ContextFile[]): ContextFileDiagnostic[];
49
75
  export declare function summarizeContextDiagnostics(files: ContextFile[], options?: {
50
76
  windowSize?: number;