@denizokcu/haze 1.6.1 → 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 +17 -0
  2. package/README.md +2 -2
  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 +51 -15
  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
@@ -11,6 +11,29 @@ export interface StoredToolOutputPage {
11
11
  query?: string;
12
12
  matches?: number;
13
13
  }
14
+ /**
15
+ * Origin metadata for stored content whose pages must stay inside their
16
+ * untrusted envelope on every `readToolOutput` read (HZA-2): without it, an
17
+ * oversized fetch/MCP result invites the model to page through raw, unlabeled
18
+ * attacker-controlled text via the retrieval handle.
19
+ */
20
+ export type StoredOutputOrigin = {
21
+ kind: 'web';
22
+ url: string;
23
+ } | {
24
+ kind: 'mcp';
25
+ server: string;
26
+ toolName: string;
27
+ };
28
+ /**
29
+ * Wrap untrusted-origin content in its labeled envelope. Occurrences of the
30
+ * closing tag inside the content are escaped (variant-tolerantly — see
31
+ * `escapeEnvelopeClosers`) so the payload cannot forge the envelope boundary
32
+ * and smuggle instructions outside it. Shared by the fetch/MCP tools (inline
33
+ * results) and `readToolOutput` page re-wraps so both views use identical
34
+ * framing.
35
+ */
36
+ export declare function wrapUntrustedOutput(origin: StoredOutputOrigin, content: string): string;
14
37
  export declare function registerDynamicToolOutput(read: () => {
15
38
  content: string;
16
39
  totalBytes: number;
@@ -24,7 +47,7 @@ export declare function unregisterDynamicToolOutput(handle: string): void;
24
47
  * budget is evicted on the next `storeToolOutput` call, so callers should not
25
48
  * assume a freshly-stored handle survives beyond the next store.
26
49
  */
27
- export declare function storeToolOutput(content: string): string;
50
+ export declare function storeToolOutput(content: string, origin?: StoredOutputOrigin): string;
28
51
  export declare function readToolOutput(handle: string, offset?: number, limit?: number, options?: {
29
52
  query?: string;
30
53
  contextLines?: number;
@@ -1,6 +1,25 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits.js';
3
3
  import { truncateUtf8AtBytes } from '../../utils/utf8.js';
4
+ import { escapeEnvelopeClosers } from '../safety/untrustedEnvelopes.js';
5
+ function escapeAttribute(value) {
6
+ return value.replaceAll('"', '%22');
7
+ }
8
+ /**
9
+ * Wrap untrusted-origin content in its labeled envelope. Occurrences of the
10
+ * closing tag inside the content are escaped (variant-tolerantly — see
11
+ * `escapeEnvelopeClosers`) so the payload cannot forge the envelope boundary
12
+ * and smuggle instructions outside it. Shared by the fetch/MCP tools (inline
13
+ * results) and `readToolOutput` page re-wraps so both views use identical
14
+ * framing.
15
+ */
16
+ export function wrapUntrustedOutput(origin, content) {
17
+ const escaped = escapeEnvelopeClosers(content);
18
+ if (origin.kind === 'web') {
19
+ return `<web_content url="${escapeAttribute(origin.url)}" untrusted="data">\n${escaped}\n</web_content>`;
20
+ }
21
+ return `<mcp_result server="${escapeAttribute(origin.server)}" untrusted="data">\n${escaped}\n</mcp_result>`;
22
+ }
4
23
  const outputs = new Map();
5
24
  const dynamicOutputs = new Map();
6
25
  const MAX_STORED_OUTPUTS = 100;
@@ -21,12 +40,12 @@ export function unregisterDynamicToolOutput(handle) {
21
40
  * budget is evicted on the next `storeToolOutput` call, so callers should not
22
41
  * assume a freshly-stored handle survives beyond the next store.
23
42
  */
24
- export function storeToolOutput(content) {
43
+ export function storeToolOutput(content, origin) {
25
44
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
26
45
  const originalBytes = Buffer.byteLength(content, 'utf8');
27
46
  const retained = truncateUtf8AtBytes(content, TOOL_OUTPUT_ENTRY_BYTES).text;
28
47
  const bytes = Buffer.byteLength(retained, 'utf8');
29
- outputs.set(handle, { content: retained, bytes, originalBytes });
48
+ outputs.set(handle, { content: retained, bytes, originalBytes, ...(origin ? { origin } : {}) });
30
49
  storedBytes += bytes;
31
50
  while (outputs.size > MAX_STORED_OUTPUTS || storedBytes > TOOL_OUTPUT_TOTAL_BYTES) {
32
51
  const oldest = outputs.keys().next().value;
@@ -77,15 +96,17 @@ export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
77
96
  outputs.delete(handle);
78
97
  outputs.set(handle, stored);
79
98
  }
99
+ const origin = 'origin' in stored ? stored.origin : undefined;
80
100
  const output = stored.content;
81
101
  if (options?.query?.trim()) {
82
102
  const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
83
103
  const omittedBytes = stored.originalBytes - stored.bytes;
84
- return { ...result, handle, truncated: result.truncated || omittedBytes > 0, totalBytes: stored.originalBytes, retainedBytes: stored.bytes, omittedBytes };
104
+ return { ...result, handle, truncated: result.truncated || omittedBytes > 0, totalBytes: stored.originalBytes, retainedBytes: stored.bytes, omittedBytes,
105
+ ...(origin ? { content: wrapUntrustedOutput(origin, result.content) } : {}) };
85
106
  }
86
107
  const safeOffset = Math.min(Math.max(0, offset), output.length);
87
- const content = output.slice(safeOffset, safeOffset + limit);
88
- const nextOffset = safeOffset + content.length < output.length ? safeOffset + content.length : undefined;
108
+ const page = output.slice(safeOffset, safeOffset + limit);
109
+ const nextOffset = safeOffset + page.length < output.length ? safeOffset + page.length : undefined;
89
110
  return {
90
111
  handle,
91
112
  offset: safeOffset,
@@ -94,7 +115,7 @@ export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
94
115
  totalBytes: stored.originalBytes,
95
116
  retainedBytes: stored.bytes,
96
117
  omittedBytes: stored.originalBytes - stored.bytes,
97
- content,
118
+ content: origin ? wrapUntrustedOutput(origin, page) : page,
98
119
  truncated: nextOffset != null || stored.originalBytes > stored.bytes,
99
120
  };
100
121
  }
@@ -1,11 +1,21 @@
1
+ /**
2
+ * Identical validation reruns are evidence, not loops: re-running the same
3
+ * recognized check after a fix is the desired red→green flow (observed
4
+ * 2026-10-30 session 30fd6f: a legitimate re-typecheck after an edit was
5
+ * flagged as a repeat, the next request dropped `shell`, and the model's
6
+ * retry of the removed tool failed the whole step). Only shell calls whose
7
+ * unquoted command shape infers a real validation kind are exempt.
8
+ */
9
+ export declare function isValidationRerunToolCall(value: unknown): boolean;
1
10
  export declare function uniqueRepeatedToolNames(toolCalls: Array<{
2
11
  toolName: string;
3
12
  input: unknown;
4
13
  }>): string[];
5
14
  /**
6
15
  * Return tool names whose latest-step calls repeat an earlier identical call.
7
- * Restricting only the immediately following step prevents one duplicate from
8
- * disabling an entire tool category for the rest of the turn.
16
+ * The next request redirects them with a one-step instruction — tools are
17
+ * never removed from the request (removal once let a model retry a dropped
18
+ * tool and fail the step). Validation reruns are never flagged.
9
19
  */
10
20
  export declare function latestRepeatedToolNames(steps: Array<{
11
21
  toolCalls: Array<{
@@ -1,10 +1,32 @@
1
+ import { inferValidationKind } from '../validation/outputParser.js';
1
2
  function stableToolKey(toolCall) {
2
3
  return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
3
4
  }
5
+ /**
6
+ * Identical validation reruns are evidence, not loops: re-running the same
7
+ * recognized check after a fix is the desired red→green flow (observed
8
+ * 2026-10-30 session 30fd6f: a legitimate re-typecheck after an edit was
9
+ * flagged as a repeat, the next request dropped `shell`, and the model's
10
+ * retry of the removed tool failed the whole step). Only shell calls whose
11
+ * unquoted command shape infers a real validation kind are exempt.
12
+ */
13
+ export function isValidationRerunToolCall(value) {
14
+ if (typeof value !== 'object' || value === null)
15
+ return false;
16
+ const call = value;
17
+ if (call.toolName !== 'shell')
18
+ return false;
19
+ if (typeof call.input !== 'object' || call.input === null)
20
+ return false;
21
+ const command = call.input.command;
22
+ return typeof command === 'string' && inferValidationKind(command) !== 'generic';
23
+ }
4
24
  export function uniqueRepeatedToolNames(toolCalls) {
5
25
  const seen = new Set();
6
26
  const repeated = new Set();
7
27
  for (const toolCall of toolCalls) {
28
+ if (isValidationRerunToolCall(toolCall))
29
+ continue;
8
30
  const key = stableToolKey(toolCall);
9
31
  if (seen.has(key))
10
32
  repeated.add(toolCall.toolName);
@@ -14,8 +36,9 @@ export function uniqueRepeatedToolNames(toolCalls) {
14
36
  }
15
37
  /**
16
38
  * Return tool names whose latest-step calls repeat an earlier identical call.
17
- * Restricting only the immediately following step prevents one duplicate from
18
- * disabling an entire tool category for the rest of the turn.
39
+ * The next request redirects them with a one-step instruction — tools are
40
+ * never removed from the request (removal once let a model retry a dropped
41
+ * tool and fail the step). Validation reruns are never flagged.
19
42
  */
20
43
  export function latestRepeatedToolNames(steps) {
21
44
  const latest = steps.at(-1);
@@ -24,6 +47,8 @@ export function latestRepeatedToolNames(steps) {
24
47
  const seen = new Set(steps.slice(0, -1).flatMap(step => step.toolCalls).map(stableToolKey));
25
48
  const repeated = new Set();
26
49
  for (const toolCall of latest.toolCalls) {
50
+ if (isValidationRerunToolCall(toolCall))
51
+ continue;
27
52
  const key = stableToolKey(toolCall);
28
53
  if (seen.has(key))
29
54
  repeated.add(toolCall.toolName);
@@ -19,7 +19,8 @@ export declare function intentExpectsValidation(intent: RequestIntent): boolean;
19
19
  * Normalize a validation command into a matching key so a green run can be
20
20
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
21
21
  * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
22
- * a lone line-continuation backslash, and a trailing `--` separator are noise.
22
+ * a lone line-continuation backslash, a trailing `--` separator, and trailing
23
+ * bare stderr redirects (`2>&1`, `2>/dev/null`) are noise.
23
24
  */
24
25
  export declare function validationCommandKey(command: string): string;
25
26
  /**
@@ -66,6 +67,8 @@ export interface WorkState {
66
67
  mutationSeq: number;
67
68
  /** Monotonic sequence number of the latest validation (0 = none). */
68
69
  validationSeq: number;
70
+ /** mutationCount when the latest validation ran — the delta since it drives the stale-validation nudge. */
71
+ mutationCountAtLastValidation?: number;
69
72
  /**
70
73
  * Current-turn task-list evidence, recorded only from a successful `writeTasks`
71
74
  * result. Counts only — never task titles or raw output — so malformed tool
@@ -143,5 +146,7 @@ export declare function taskProgressFromOutput(output: unknown, revision: number
143
146
  */
144
147
  export declare function deriveValidationOutcome(state: WorkState): ValidationOutcome;
145
148
  export declare function unresolvedFailedCheckIds(state: WorkState): string[];
149
+ /** Distinct confirmed check kinds behind open ids, for bounded human-readable notices. */
150
+ export declare function checkKindsOfIds(ids: string[]): string[];
146
151
  export declare function workStatePrompt(state: WorkState): string;
147
152
  export {};
@@ -9,11 +9,14 @@ import { changedPathsFromTool } from './toolCapabilities.js';
9
9
  export function intentExpectsValidation(intent) {
10
10
  return intent === 'implement' || intent === 'fix' || intent === 'test';
11
11
  }
12
+ /** Bare fd merges/discards with no filename — pure output plumbing. */
13
+ const TRAILING_REDIRECT_NOISE = /^(?:\d*>&\d+|\d*>\/dev\/null)$/;
12
14
  /**
13
15
  * Normalize a validation command into a matching key so a green run can be
14
16
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
15
17
  * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
16
- * a lone line-continuation backslash, and a trailing `--` separator are noise.
18
+ * a lone line-continuation backslash, a trailing `--` separator, and trailing
19
+ * bare stderr redirects (`2>&1`, `2>/dev/null`) are noise.
17
20
  */
18
21
  export function validationCommandKey(command) {
19
22
  const words = command.replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
@@ -32,6 +35,14 @@ export function validationCommandKey(command) {
32
35
  }
33
36
  while (words.length > 1 && words.at(-1) === '--')
34
37
  words.pop();
38
+ // A trailing bare stderr redirect cannot change a check's identity, but it
39
+ // defeats the single-invocation gate below (observed 2026-10-30, session
40
+ // 30fd6f): a red `cd pkg && npm run typecheck 2>&1` kept its whole-compound
41
+ // identity, so its opaque `compound@` scope could never pair with the plain
42
+ // green rerun and the goal stayed `failed` with typecheck and tests green.
43
+ // Trailing tokens only; redirects with a filename stay part of the key.
44
+ while (words.length > 1 && TRAILING_REDIRECT_NOISE.test(words.at(-1)))
45
+ words.pop();
35
46
  const normalized = words.join(' ');
36
47
  // npm's --prefix form and a simple `cd` wrapper address the same package.
37
48
  // Keep this deliberately narrow: parsing arbitrary shell syntax would risk
@@ -96,7 +107,7 @@ function failedCheckScope(command) {
96
107
  const scoped = /^npm@(\S+) /.exec(normalized);
97
108
  if (scoped)
98
109
  return `npm@${scoped[1]}`;
99
- // `// `&&` compounds are recorded per stage (see andStages)// `&&` compounds are recorded per stage (see andStages)` compounds are recorded per stage (see validationStages), so a stage reaching
110
+ // `&&` compounds are recorded per stage (see validationStages), so a stage reaching
100
111
  // this function is a single invocation; `;`/`||` chains are a different
101
112
  // check than their stages: a red `npm test; npm run lint` must not be cleared
102
113
  // by a green bare `npm test`. The compound gets its own hashed (non-reversible)
@@ -153,6 +164,10 @@ export function seedCarriedGoalEvidence(state, carried) {
153
164
  }
154
165
  if (carried.validationOutcome === 'passed' || carried.validationOutcome === 'failed') {
155
166
  state.validationSeq = 1;
167
+ // Conservative baseline: treat all carried mutations as predating the
168
+ // carried validation, so the stale-validation nudge only fires once new
169
+ // unvalidated mutations accrue (the checkpoint carries no finer ordering).
170
+ state.mutationCountAtLastValidation = carried.mutationCount;
156
171
  state.carriedValidation = carried.validationOutcome === 'passed'
157
172
  ? { status: 'passed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) }
158
173
  : { status: 'failed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) };
@@ -360,9 +375,19 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
360
375
  // stages are treated as unresolved — individually clearable by a green rerun).
361
376
  const stages = validationStages(command);
362
377
  if (stages) {
363
- for (const stage of stages) {
364
- upsertValidation(state, stage, status, summaryText, inferValidationKind(stage), seq);
365
- }
378
+ // Attribute the chain's parsed summary to the stage whose kind it
379
+ // describes — never copy one stage's text onto another (observed
380
+ // 2026-10-30 session 30fd6f: a green `typecheck && test` chain
381
+ // recorded the test stage with summary "typecheck passed"). No kind
382
+ // match defaults to the first stage.
383
+ const attributed = stages.findIndex(stage => inferValidationKind(stage) === summary?.kind);
384
+ const summaryStage = attributed >= 0 ? attributed : 0;
385
+ stages.forEach((stage, index) => {
386
+ const stageSummary = index === summaryStage
387
+ ? summaryText
388
+ : `stage ${index + 1}/${stages.length} of && chain: ${status}`;
389
+ upsertValidation(state, stage, status, stageSummary, inferValidationKind(stage), seq);
390
+ });
366
391
  }
367
392
  else {
368
393
  upsertValidation(state, command, status, summaryText, summary?.kind ?? 'generic', seq);
@@ -380,6 +405,7 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
380
405
  state.carriedFailedCheckIds = remaining.length ? remaining : undefined;
381
406
  }
382
407
  state.validationSeq = seq;
408
+ state.mutationCountAtLastValidation = state.mutationCount;
383
409
  state.phase = 'validating';
384
410
  state.lastProgressAt = now;
385
411
  if (status === 'failed') {
@@ -478,6 +504,16 @@ export function unresolvedFailedCheckIds(state) {
478
504
  // Bound only the model-facing preview, not the authoritative check set.
479
505
  return [...new Set([...(state.carriedFailedCheckIds ?? []), ...local])];
480
506
  }
507
+ /** Distinct confirmed check kinds behind open ids, for bounded human-readable notices. */
508
+ export function checkKindsOfIds(ids) {
509
+ const kinds = new Set();
510
+ for (const id of ids) {
511
+ const kind = kindOfCheckId(id);
512
+ if (kind && kind !== 'generic')
513
+ kinds.add(kind);
514
+ }
515
+ return [...kinds];
516
+ }
481
517
  export function workStatePrompt(state) {
482
518
  // Compaction needs a continuity capsule, not a second copy of every file
483
519
  // read and validation ever observed. Keep the exact request and open-check
@@ -69,6 +69,7 @@ export declare const IMAGE_ONLY_PROMPT_TEXT = "See the attached image.";
69
69
  /** Minimal provider shape the capability gate needs (no settings I/O). */
70
70
  export interface ImageCapableProviderLike {
71
71
  name: string;
72
+ kind?: string;
72
73
  capabilities?: {
73
74
  images?: boolean;
74
75
  };
@@ -76,7 +77,9 @@ export interface ImageCapableProviderLike {
76
77
  /**
77
78
  * Loud capability gate (constitution VII): images only go to providers the
78
79
  * user explicitly marked image-capable. Returns undefined when the provider
79
- * may receive image parts, otherwise an actionable error message.
80
+ * may receive image parts, otherwise an actionable error message. The native
81
+ * haze.build kind is text/tools only regardless of any stored capability
82
+ * flag, so a hand-edited settings file cannot admit images to it.
80
83
  */
81
84
  export declare function imageCapabilityError(provider: ImageCapableProviderLike | undefined): string | undefined;
82
85
  /** Guard for AI SDK `file` parts carrying images, in any message role. */
@@ -263,13 +263,17 @@ export const IMAGE_ONLY_PROMPT_TEXT = 'See the attached image.';
263
263
  /**
264
264
  * Loud capability gate (constitution VII): images only go to providers the
265
265
  * user explicitly marked image-capable. Returns undefined when the provider
266
- * may receive image parts, otherwise an actionable error message.
266
+ * may receive image parts, otherwise an actionable error message. The native
267
+ * haze.build kind is text/tools only regardless of any stored capability
268
+ * flag, so a hand-edited settings file cannot admit images to it.
267
269
  */
268
270
  export function imageCapabilityError(provider) {
269
- if (provider?.capabilities?.images === true)
270
- return undefined;
271
271
  if (!provider)
272
272
  return 'No provider is configured. Run /provider to add one, then attach the image again.';
273
+ if (provider.kind === 'haze-build')
274
+ return 'haze.build haze0.1-coder-flash is text/tools only; images are not supported.';
275
+ if (provider.capabilities?.images === true)
276
+ return undefined;
273
277
  return `Provider '${provider.name}' is not marked image-capable. Enable image input for it via /provider, or switch models.`;
274
278
  }
275
279
  /** Guard for AI SDK `file` parts carrying images, in any message role. */
@@ -37,6 +37,8 @@ export declare const COMPACT_COMMAND_CHARS = 12000;
37
37
  export declare const SHORT_VALIDATION_CHARS = 2000;
38
38
  /** Total rendered size cap for grep match output. */
39
39
  export declare const GREP_MAX_OUTPUT_CHARS = 30000;
40
+ /** Model-visible cap for one MCP tool result; larger results move behind a readToolOutput handle. */
41
+ export declare const MAX_MCP_OUTPUT_CHARS = 100000;
40
42
  /** Per-line cap for rendered grep matches. */
41
43
  export declare const GREP_MAX_LINE_CHARS = 500;
42
44
  /** Bounded excerpt of older messages kept by /compact-style compaction. */
@@ -37,6 +37,8 @@ export const COMPACT_COMMAND_CHARS = 12_000;
37
37
  export const SHORT_VALIDATION_CHARS = 2_000;
38
38
  /** Total rendered size cap for grep match output. */
39
39
  export const GREP_MAX_OUTPUT_CHARS = 30_000;
40
+ /** Model-visible cap for one MCP tool result; larger results move behind a readToolOutput handle. */
41
+ export const MAX_MCP_OUTPUT_CHARS = 100_000;
40
42
  /** Per-line cap for rendered grep matches. */
41
43
  export const GREP_MAX_LINE_CHARS = 500;
42
44
  /** Bounded excerpt of older messages kept by /compact-style compaction. */
@@ -5,6 +5,7 @@ import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateF
5
5
  import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
6
6
  import { JSONL_LINE_BYTES } from '../limits.js';
7
7
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
8
+ import { redactUnknown } from '../safety/redaction.js';
8
9
  const LOGS_DIR = path.join(HAZE_DIR, 'logs');
9
10
  function logFileId(now = new Date()) {
10
11
  return now.toISOString().replace(/[:.]/g, '-');
@@ -25,11 +26,15 @@ export async function createLog() {
25
26
  return log;
26
27
  }
27
28
  export async function appendLogEntry(log, entry) {
29
+ // LLM logs record full prompts/tool IO in plaintext; secret-shaped tokens
30
+ // are masked on every write (default ON — logs exist only under --debug,
31
+ // and a printed credential must not persist in cleartext) (HZA-7).
32
+ const redacted = redactUnknown(entry);
28
33
  if (log.writer) {
29
- await log.writer.append(entry);
34
+ await log.writer.append(redacted);
30
35
  return;
31
36
  }
32
- await appendPrivateFile(log.file, `${JSON.stringify(entry)}\n`);
37
+ await appendPrivateFile(log.file, `${JSON.stringify(redacted)}\n`);
33
38
  }
34
39
  export async function endLog(log) {
35
40
  const entry = {
@@ -1,3 +1,4 @@
1
+ import { type SanitizeEnvOptions } from './runBoundedProcess.js';
1
2
  type BackgroundProcessStatus = 'running' | 'exited' | 'failed' | 'killed';
2
3
  export interface BackgroundProcessSummary {
3
4
  backgroundId: string;
@@ -14,6 +15,13 @@ export interface BackgroundProcessSummary {
14
15
  retainedBytes: number;
15
16
  omittedBytes: number;
16
17
  };
18
+ /**
19
+ * Advisory only (HZ-11): set when teardown could not fully reap the process
20
+ * group — e.g. a descendant created its own session (setsid/daemonize) and
21
+ * survived the tree kill. Informational; it never changes kill behavior or
22
+ * the status above.
23
+ */
24
+ teardownNote?: string;
17
25
  error?: string;
18
26
  }
19
27
  export declare function backgroundProcessCount(): number;
@@ -23,6 +31,7 @@ export declare function getBackgroundProcess(backgroundId: string): BackgroundPr
23
31
  export declare function startBackgroundProcess(input: {
24
32
  command: string;
25
33
  cwd: string;
34
+ sanitizeEnv?: SanitizeEnvOptions;
26
35
  }): BackgroundProcessSummary;
27
36
  export declare function killBackgroundProcess(backgroundId: string, killGraceMs?: number): Promise<BackgroundProcessSummary | undefined>;
28
37
  /** Terminate every owned tree and clear the session-local registry and handles. */
@@ -3,7 +3,7 @@ import { StringDecoder } from 'node:string_decoder';
3
3
  import { BACKGROUND_PROCESS_HISTORY_LIMIT, BACKGROUND_PROCESS_MAX_CONCURRENCY } from '../agent/budgets.js';
4
4
  import { registerDynamicToolOutput, unregisterDynamicToolOutput } from '../agent/toolOutputStore.js';
5
5
  import { BACKGROUND_PROCESS_OUTPUT_BYTES } from '../limits.js';
6
- import { signalProcessTree } from './runBoundedProcess.js';
6
+ import { signalProcessTree, sanitizeChildEnv } from './runBoundedProcess.js';
7
7
  import { shellInvocation } from './userShell.js';
8
8
  import { truncateUtf8TailBufferAtBytes } from '../../utils/utf8.js';
9
9
  class OutputRing {
@@ -79,10 +79,13 @@ export function startBackgroundProcess(input) {
79
79
  installExitHook();
80
80
  const backgroundId = `background-${nextId++}`;
81
81
  const invocation = shellInvocation(input.command);
82
+ // Absent `sanitizeEnv` (default) means the child inherits process.env
83
+ // exactly — no `env` option at all (HZ-10 opt-in).
82
84
  const child = spawn(invocation.command, invocation.args, {
83
85
  cwd: input.cwd,
84
86
  detached: process.platform !== 'win32',
85
87
  stdio: ['ignore', 'pipe', 'pipe'],
88
+ ...(input.sanitizeEnv ? { env: sanitizeChildEnv(process.env, input.sanitizeEnv) } : {}),
86
89
  });
87
90
  const ring = new OutputRing();
88
91
  const outputHandle = registerDynamicToolOutput(() => ring.snapshot());
@@ -148,6 +151,14 @@ export async function killBackgroundProcess(backgroundId, killGraceMs = 500) {
148
151
  if (!closed) {
149
152
  signalProcessTree(record.child, 'SIGKILL');
150
153
  closed = await waitForClose(record, 100);
154
+ if (!closed) {
155
+ // Advisory only (HZ-11): SIGKILL went to the process group, but no close
156
+ // event arrived — typically a descendant that created its own session
157
+ // (setsid/daemonize) still holds stdio and survives the group kill.
158
+ // Record it so the report never implies a fully reaped tree; the kill
159
+ // behavior itself is unchanged.
160
+ record.summary.teardownNote = 'Process group may not be fully reaped: no close event after SIGKILL escalation; a descendant in its own session (e.g. setsid/daemonized) may outlive haze teardown.';
161
+ }
151
162
  record.child.stdout?.destroy();
152
163
  record.child.stderr?.destroy();
153
164
  }
@@ -22,6 +22,23 @@ export interface ProcessTreeSignalOptions {
22
22
  /** @internal testing seam. */
23
23
  spawnProcess?: typeof spawn;
24
24
  }
25
+ /** Options for the opt-in child-environment sanitizer (HZ-10). */
26
+ export interface SanitizeEnvOptions {
27
+ /**
28
+ * Additional case-insensitive substrings: any environment key containing one
29
+ * is omitted as well. Matched as plain substrings, never regex, so values
30
+ * coming from settings cannot widen matching beyond literal names.
31
+ */
32
+ extra?: readonly string[];
33
+ }
34
+ /**
35
+ * Build a child environment that omits secret-shaped keys: anything matching
36
+ * TOKEN/KEY/SECRET/PASSWORD/CREDENTIAL (case-insensitive) plus the caller's
37
+ * extra substrings. Everything else — PATH, HOME, LANG, TERM, TZ, etc. — is
38
+ * passed through untouched. Opt-in only; callers that do not ask for this keep
39
+ * the child inheriting the full environment exactly as before.
40
+ */
41
+ export declare function sanitizeChildEnv(env: NodeJS.ProcessEnv, options?: SanitizeEnvOptions): NodeJS.ProcessEnv;
25
42
  export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals, options?: ProcessTreeSignalOptions): void;
26
43
  export declare function runBoundedProcess(input: {
27
44
  command: string;
@@ -33,4 +50,5 @@ export declare function runBoundedProcess(input: {
33
50
  maxStderrBytes: number;
34
51
  killGraceMs?: number;
35
52
  onStdoutChunk?: (chunk: Buffer) => boolean | void;
53
+ sanitizeEnv?: SanitizeEnvOptions;
36
54
  }): Promise<BoundedProcessResult>;
@@ -1,5 +1,26 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
+ /** Environment keys carrying these case-insensitive markers are treated as secret-shaped (HZ-10). */
4
+ const SECRET_ENV_KEY_PATTERN = /TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL/i;
5
+ /**
6
+ * Build a child environment that omits secret-shaped keys: anything matching
7
+ * TOKEN/KEY/SECRET/PASSWORD/CREDENTIAL (case-insensitive) plus the caller's
8
+ * extra substrings. Everything else — PATH, HOME, LANG, TERM, TZ, etc. — is
9
+ * passed through untouched. Opt-in only; callers that do not ask for this keep
10
+ * the child inheriting the full environment exactly as before.
11
+ */
12
+ export function sanitizeChildEnv(env, options = {}) {
13
+ const extra = (options.extra ?? []).map(marker => marker.trim().toLowerCase()).filter(marker => marker.length > 0);
14
+ const child = {};
15
+ for (const [key, value] of Object.entries(env)) {
16
+ if (SECRET_ENV_KEY_PATTERN.test(key))
17
+ continue;
18
+ if (extra.some(marker => key.toLowerCase().includes(marker)))
19
+ continue;
20
+ child[key] = value;
21
+ }
22
+ return child;
23
+ }
3
24
  export function signalProcessTree(child, signal, options = {}) {
4
25
  // When pid is null, child.kill is a no-op against a real Node child (returns
5
26
  // false). Tests still rely on the call going through so they can observe
@@ -51,7 +72,9 @@ export async function runBoundedProcess(input) {
51
72
  return { code: null, signal: null, stdout: stdout.result(), stderr: stderr.result(), timedOut: false, aborted: true, forced: false, durationMs: 0 };
52
73
  }
53
74
  const detached = process.platform !== 'win32';
54
- const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'] });
75
+ // Absent `sanitizeEnv` means the child inherits process.env exactly (no
76
+ // `env` option at all) — the pre-sanitizer behavior.
77
+ const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'], ...(input.sanitizeEnv ? { env: sanitizeChildEnv(process.env, input.sanitizeEnv) } : {}) });
55
78
  let timedOut = false;
56
79
  let aborted = false;
57
80
  let forced = false;
@@ -21,6 +21,8 @@ export interface ProviderCapabilities {
21
21
  * `on`, silently inverting the request. `false` omits the parameter entirely.
22
22
  */
23
23
  supportsReasoningEffort: boolean;
24
+ /** Native template switch, independently of OpenAI effort pass-through. */
25
+ supportsBinaryThinking?: boolean;
24
26
  }
25
27
  export interface ProviderRequestOptions {
26
28
  providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Secret-shape redaction for data-at-rest writes (HZA-7 / HZ-9).
3
+ *
4
+ * Sessions and --debug LLM logs persist conversation content in plaintext
5
+ * (permissions are 0600/0700, but injected instructions can make the shell
6
+ * tool print non-protected credentials, which then live on disk indefinitely).
7
+ * These helpers mask common token shapes before persistence: --debug LLM logs
8
+ * always redact; session files redact only when the `redactSessionSecrets`
9
+ * setting opts in (default off, to keep sessions debuggable).
10
+ */
11
+ /** Replace common secret token shapes in a string with `[redacted:<kind>]`. */
12
+ export declare function redactSecrets(text: string): string;
13
+ /**
14
+ * Deep redaction for JSON-serializable values: every nested string is passed
15
+ * through `redactSecrets`. Cycles collapse to a marker (same convention as
16
+ * session slimming); non-string leaves pass through untouched.
17
+ */
18
+ export declare function redactUnknown(value: unknown, seen?: WeakSet<object>): unknown;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Secret-shape redaction for data-at-rest writes (HZA-7 / HZ-9).
3
+ *
4
+ * Sessions and --debug LLM logs persist conversation content in plaintext
5
+ * (permissions are 0600/0700, but injected instructions can make the shell
6
+ * tool print non-protected credentials, which then live on disk indefinitely).
7
+ * These helpers mask common token shapes before persistence: --debug LLM logs
8
+ * always redact; session files redact only when the `redactSessionSecrets`
9
+ * setting opts in (default off, to keep sessions debuggable).
10
+ */
11
+ const SECRET_PATTERNS = [
12
+ // OpenAI-style API keys (and the many gateways that copy the sk- shape).
13
+ { kind: 'api-key', pattern: /sk-[A-Za-z0-9_-]{16,}/g },
14
+ // GitHub personal access / OAuth tokens.
15
+ { kind: 'github-token', pattern: /gh[po]_[A-Za-z0-9]{20,}/g },
16
+ // AWS access key IDs.
17
+ { kind: 'aws-key', pattern: /AKIA[0-9A-Z]{16}/g },
18
+ // Slack tokens (bot, app, refresh, user tokens).
19
+ { kind: 'slack-token', pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/g },
20
+ // JWTs (three base64url segments starting with a JSON header).
21
+ { kind: 'jwt', pattern: /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g },
22
+ ];
23
+ /** Replace common secret token shapes in a string with `[redacted:<kind>]`. */
24
+ export function redactSecrets(text) {
25
+ let result = text;
26
+ for (const { kind, pattern } of SECRET_PATTERNS) {
27
+ result = result.replace(pattern, `[redacted:${kind}]`);
28
+ }
29
+ return result;
30
+ }
31
+ /**
32
+ * Deep redaction for JSON-serializable values: every nested string is passed
33
+ * through `redactSecrets`. Cycles collapse to a marker (same convention as
34
+ * session slimming); non-string leaves pass through untouched.
35
+ */
36
+ export function redactUnknown(value, seen = new WeakSet()) {
37
+ if (typeof value === 'string')
38
+ return redactSecrets(value);
39
+ if (value == null || typeof value !== 'object')
40
+ return value;
41
+ if (seen.has(value))
42
+ return '[Circular]';
43
+ seen.add(value);
44
+ if (Array.isArray(value))
45
+ return value.map(item => redactUnknown(item, seen));
46
+ const next = {};
47
+ for (const [key, child] of Object.entries(value))
48
+ next[key] = redactUnknown(child, seen);
49
+ return next;
50
+ }