@denizokcu/haze 0.10.0 → 0.11.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 (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Maximum candidate paths submitted to a single `git check-ignore` invocation.
3
+ * Bounding the batch keeps stdin/stdout bounded while collapsing hundreds of
4
+ * entries into O(batches) subprocesses instead of one process per path
5
+ * (RH-001). 256 candidates comfortably fits a typical directory frontier.
6
+ */
7
+ export declare const GIT_IGNORE_BATCH = 256;
8
+ export interface IgnoreClassification {
9
+ /** Subset of the submitted paths Git reports as ignored. */
10
+ ignored: Set<string>;
11
+ /**
12
+ * False when a Git failure (e.g. git not installed) made the result partial.
13
+ * Reads treat that as "nothing ignored" (fail open); mutation guards treat
14
+ * it as un-verifiable and fail closed instead (F-05).
15
+ */
16
+ checked: boolean;
17
+ }
18
+ export interface IgnoreClassifier {
19
+ /**
20
+ * Classify workspace-relative candidate paths. Returns the subset that Git
21
+ * reports as ignored. Fails open: a non-repository, an operational Git
22
+ * failure, and the "no paths ignored" exit code (1) all resolve to "nothing
23
+ * here is ignored" so workspace reads are never blocked by ignore checks.
24
+ */
25
+ classify(relativePaths: readonly string[]): Promise<Set<string>>;
26
+ /** Like `classify`, but distinguishes "checked" from "could not check" (F-05). */
27
+ classifyChecked(relativePaths: readonly string[]): Promise<IgnoreClassification>;
28
+ /** Number of `git check-ignore` subprocesses started by this classifier. */
29
+ readonly invocationCount: number;
30
+ }
31
+ /**
32
+ * Create a bounded batch ignore classifier rooted at `root` (defaults to the
33
+ * workspace root). One classifier should own an entire listing operation so
34
+ * sibling/frontier candidates share subprocesses.
35
+ */
36
+ export declare function createIgnoreClassifier(root?: string): IgnoreClassifier;
37
+ /** Classify a set of workspace-relative paths in bounded batches. */
38
+ export declare function classifyGitIgnored(relativePaths: readonly string[], root?: string): Promise<Set<string>>;
39
+ /** Distinguish "checked and not ignored" from "could not check" (F-05). */
40
+ export type GitIgnoreStatus = 'ignored' | 'not-ignored' | 'unknown';
41
+ /**
42
+ * Single-path ignore classification (used by mutating-tool guards and other
43
+ * one-off checks). Built on the batch primitive so the fail-open read contract
44
+ * stays identical to batched traversal; `unknown` means Git could not be run
45
+ * at all, so callers that must not fail open (mutations) can fail closed.
46
+ */
47
+ export declare function isGitIgnored(absolutePath: string): Promise<boolean>;
48
+ /** Tri-state single-path check: mutation guards key off `unknown` (F-05). */
49
+ export declare function checkGitIgnored(absolutePath: string): Promise<GitIgnoreStatus>;
@@ -0,0 +1,129 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
3
+ /**
4
+ * Maximum candidate paths submitted to a single `git check-ignore` invocation.
5
+ * Bounding the batch keeps stdin/stdout bounded while collapsing hundreds of
6
+ * entries into O(batches) subprocesses instead of one process per path
7
+ * (RH-001). 256 candidates comfortably fits a typical directory frontier.
8
+ */
9
+ export const GIT_IGNORE_BATCH = 256;
10
+ /**
11
+ * Generous stdout ceiling for a single batch. check-ignore echoes at most the
12
+ * ignored paths it was given, so this is bounded by batch size in practice.
13
+ */
14
+ const CHECK_IGNORE_MAX_BYTES = 8 * 1024 * 1024;
15
+ /**
16
+ * Run one bounded `git check-ignore -z --stdin` invocation. Resolves with the
17
+ * raw NUL-delimited stdout (empty when no paths are ignored or the workspace is
18
+ * not a repository); rejects only on a spawn-level failure such as git missing.
19
+ */
20
+ function runCheckIgnore(root, input) {
21
+ return new Promise((resolve, reject) => {
22
+ const child = spawn('git', ['-C', root, 'check-ignore', '-z', '--stdin'], { windowsHide: true });
23
+ const chunks = [];
24
+ let totalBytes = 0;
25
+ let overflowed = false;
26
+ let settled = false;
27
+ const finish = (stdout) => {
28
+ if (settled)
29
+ return;
30
+ settled = true;
31
+ resolve(stdout);
32
+ };
33
+ const fail = (error) => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ reject(error);
38
+ };
39
+ child.stdout.on('data', (chunk) => {
40
+ if (overflowed)
41
+ return;
42
+ totalBytes += chunk.length;
43
+ if (totalBytes > CHECK_IGNORE_MAX_BYTES) {
44
+ overflowed = true;
45
+ chunks.length = 0;
46
+ return;
47
+ }
48
+ chunks.push(chunk);
49
+ });
50
+ child.stderr.on('data', () => undefined);
51
+ child.on('error', fail);
52
+ child.on('close', () => {
53
+ // Exit codes: 0 = some ignored, 1 = none ignored, 128 = not a repo. All
54
+ // are resolved with whatever stdout arrived (empty for 1/128); overflow
55
+ // yields empty output so the batch fails open (nothing reported ignored).
56
+ finish(overflowed ? '' : Buffer.concat(chunks).toString('utf8'));
57
+ });
58
+ child.stdin.on('error', () => undefined);
59
+ child.stdin.end(input, 'utf8');
60
+ });
61
+ }
62
+ /**
63
+ * Create a bounded batch ignore classifier rooted at `root` (defaults to the
64
+ * workspace root). One classifier should own an entire listing operation so
65
+ * sibling/frontier candidates share subprocesses.
66
+ */
67
+ export function createIgnoreClassifier(root = workspaceRoot()) {
68
+ let invocationCount = 0;
69
+ const classifyChecked = async (relativePaths) => {
70
+ // De-duplicate and drop meaningless inputs; preserve insertion uniqueness
71
+ // so the returned set keys match caller-supplied relative paths exactly.
72
+ const unique = Array.from(new Set(relativePaths.filter(candidate => candidate && candidate !== '.')));
73
+ if (unique.length === 0)
74
+ return { ignored: new Set(), checked: true };
75
+ const ignored = new Set();
76
+ let checked = true;
77
+ for (let offset = 0; offset < unique.length; offset += GIT_IGNORE_BATCH) {
78
+ const batch = unique.slice(offset, offset + GIT_IGNORE_BATCH);
79
+ const input = `${batch.join('\0')}\0`;
80
+ invocationCount++;
81
+ // check-ignore echoes each ignored path verbatim (NUL-delimited with
82
+ // -z). Matching by exact submitted string preserves spaces, embedded
83
+ // newlines, and unusual names; only ignored entries appear in stdout.
84
+ try {
85
+ const stdout = await runCheckIgnore(root, input);
86
+ for (const part of stdout.split('\0'))
87
+ if (part)
88
+ ignored.add(part);
89
+ }
90
+ catch {
91
+ // Spawn-level failure (e.g. git not installed): whatever was classified
92
+ // so far stands, but the batch could not be checked.
93
+ checked = false;
94
+ return { ignored, checked };
95
+ }
96
+ }
97
+ return { ignored, checked };
98
+ };
99
+ return {
100
+ classifyChecked,
101
+ classify: async (relativePaths) => (await classifyChecked(relativePaths)).ignored,
102
+ get invocationCount() {
103
+ return invocationCount;
104
+ },
105
+ };
106
+ }
107
+ /** Classify a set of workspace-relative paths in bounded batches. */
108
+ export async function classifyGitIgnored(relativePaths, root) {
109
+ return createIgnoreClassifier(root ?? workspaceRoot()).classify(relativePaths);
110
+ }
111
+ /**
112
+ * Single-path ignore classification (used by mutating-tool guards and other
113
+ * one-off checks). Built on the batch primitive so the fail-open read contract
114
+ * stays identical to batched traversal; `unknown` means Git could not be run
115
+ * at all, so callers that must not fail open (mutations) can fail closed.
116
+ */
117
+ export async function isGitIgnored(absolutePath) {
118
+ return (await checkGitIgnored(absolutePath)) === 'ignored';
119
+ }
120
+ /** Tri-state single-path check: mutation guards key off `unknown` (F-05). */
121
+ export async function checkGitIgnored(absolutePath) {
122
+ const relative = workspaceRelativePath(absolutePath);
123
+ if (relative === '.')
124
+ return 'not-ignored';
125
+ const { ignored, checked } = await createIgnoreClassifier(workspaceRoot()).classifyChecked([relative]);
126
+ if (!checked)
127
+ return 'unknown';
128
+ return ignored.has(relative) ? 'ignored' : 'not-ignored';
129
+ }
@@ -0,0 +1,10 @@
1
+ import type { ToolFailureReasonCode } from '../toolResultTypes.js';
2
+ export interface ReadFailureRecovery {
3
+ reasonCode?: ToolFailureReasonCode;
4
+ suggestedNextStep: string;
5
+ suggestedPaths?: string[];
6
+ }
7
+ /** Return a few close, non-ignored siblings without walking the workspace. */
8
+ export declare function nearbyReadablePaths(filePath: string): Promise<string[]>;
9
+ export declare function assertReadableTextFile(absolutePath: string, filePath: string): Promise<void>;
10
+ export declare function readFailureRecovery(filePath: string, error: unknown): Promise<ReadFailureRecovery>;
@@ -0,0 +1,135 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { resolveWorkspacePath, workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
4
+ import { isGitIgnored } from './fileToolShared.js';
5
+ import { HazeToolError } from './failures.js';
6
+ function errorCode(error) {
7
+ if (typeof error !== 'object' || error == null || !('code' in error))
8
+ return undefined;
9
+ const code = error.code;
10
+ return typeof code === 'string' ? code : undefined;
11
+ }
12
+ function editDistance(left, right) {
13
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
14
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
15
+ const current = [leftIndex];
16
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
17
+ const cost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1;
18
+ current[rightIndex] = Math.min(current[rightIndex - 1] + 1, previous[rightIndex] + 1, previous[rightIndex - 1] + cost);
19
+ }
20
+ previous.splice(0, previous.length, ...current);
21
+ }
22
+ return previous[right.length];
23
+ }
24
+ async function existingAncestor(candidate, root) {
25
+ let current = path.dirname(candidate);
26
+ while (current === root || current.startsWith(`${root}${path.sep}`)) {
27
+ try {
28
+ if ((await fs.stat(current)).isDirectory())
29
+ return current;
30
+ }
31
+ catch {
32
+ // Continue toward the workspace root.
33
+ }
34
+ if (current === root)
35
+ break;
36
+ current = path.dirname(current);
37
+ }
38
+ return undefined;
39
+ }
40
+ /** Return a few close, non-ignored siblings without walking the workspace. */
41
+ export async function nearbyReadablePaths(filePath) {
42
+ let candidate;
43
+ try {
44
+ candidate = resolveWorkspacePath(filePath);
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ const root = workspaceRoot();
50
+ const ancestor = await existingAncestor(candidate, root);
51
+ if (!ancestor)
52
+ return [];
53
+ const remainder = path.relative(ancestor, candidate).split(path.sep).filter(Boolean);
54
+ const wanted = remainder[0] ?? path.basename(candidate);
55
+ let entries;
56
+ try {
57
+ entries = await fs.readdir(ancestor, { withFileTypes: true });
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ const ranked = entries
63
+ .filter(entry => entry.name !== '.git' && entry.name !== 'node_modules')
64
+ .map(entry => ({ entry, distance: editDistance(wanted.toLowerCase(), entry.name.toLowerCase()) }))
65
+ .filter(({ entry, distance }) => distance <= Math.max(2, Math.ceil(wanted.length * 0.4)) || entry.name.toLowerCase().includes(wanted.toLowerCase()) || wanted.toLowerCase().includes(entry.name.toLowerCase()))
66
+ .sort((left, right) => left.distance - right.distance || left.entry.name.localeCompare(right.entry.name))
67
+ .slice(0, 10);
68
+ const suggestions = [];
69
+ for (const { entry } of ranked) {
70
+ const absolute = path.join(ancestor, entry.name);
71
+ if (await isGitIgnored(absolute))
72
+ continue;
73
+ const relative = workspaceRelativePath(absolute).replaceAll(path.sep, '/');
74
+ suggestions.push(entry.isDirectory() ? `${relative}/` : relative);
75
+ if (suggestions.length === 5)
76
+ break;
77
+ }
78
+ return suggestions;
79
+ }
80
+ export async function assertReadableTextFile(absolutePath, filePath) {
81
+ const stat = await fs.stat(absolutePath);
82
+ if (!stat.isFile()) {
83
+ throw new HazeToolError(`${filePath} is not a regular file.`, 'not_a_file', { recoveryTool: 'listFiles', recoveryInput: { path: filePath } });
84
+ }
85
+ const handle = await fs.open(absolutePath, 'r');
86
+ try {
87
+ const sample = Buffer.alloc(Math.min(8192, stat.size));
88
+ const { bytesRead } = await handle.read(sample, 0, sample.length, 0);
89
+ const bytes = sample.subarray(0, bytesRead);
90
+ if (bytes.includes(0))
91
+ throw new HazeToolError(`${filePath} appears to be binary, not UTF-8 text.`, 'binary_file');
92
+ try {
93
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes, { stream: bytesRead < stat.size });
94
+ }
95
+ catch {
96
+ throw new HazeToolError(`${filePath} is not valid UTF-8 text.`, 'binary_file');
97
+ }
98
+ }
99
+ finally {
100
+ await handle.close();
101
+ }
102
+ }
103
+ export async function readFailureRecovery(filePath, error) {
104
+ if (error instanceof HazeToolError) {
105
+ if (error.reasonCode === 'ignored_path')
106
+ return { reasonCode: error.reasonCode, suggestedNextStep: 'Set allowIgnored=true only when the user explicitly needs this ignored file.' };
107
+ if (error.reasonCode === 'binary_file')
108
+ return { reasonCode: error.reasonCode, suggestedNextStep: 'Use an appropriate binary or image inspection tool instead of retrying readFile.' };
109
+ if (error.reasonCode === 'not_a_file')
110
+ return { reasonCode: error.reasonCode, suggestedNextStep: 'Use listFiles for the directory, then read the intended regular file.' };
111
+ if (error.reasonCode === 'invalid_line_range')
112
+ return { reasonCode: error.reasonCode, suggestedNextStep: 'Retry with an offset within the reported total line count.' };
113
+ }
114
+ const message = error instanceof Error ? error.message : String(error);
115
+ if (message.includes('outside the workspace')) {
116
+ return { reasonCode: 'outside_workspace', suggestedNextStep: 'Use a path inside the workspace, or ask the user to mention the outside path explicitly for read-only access.' };
117
+ }
118
+ const code = errorCode(error);
119
+ if (code === 'ENOENT') {
120
+ const suggestedPaths = await nearbyReadablePaths(filePath);
121
+ const suffix = suggestedPaths.length > 0 ? ` Nearby paths: ${suggestedPaths.join(', ')}.` : '';
122
+ return {
123
+ reasonCode: 'path_not_found',
124
+ suggestedNextStep: `Correct the path using the nearby paths or listFiles; do not guess another path.${suffix}`,
125
+ ...(suggestedPaths.length > 0 ? { suggestedPaths } : {}),
126
+ };
127
+ }
128
+ if (code === 'EISDIR') {
129
+ return { reasonCode: 'not_a_file', suggestedNextStep: 'Use listFiles for this directory, then read the intended file.' };
130
+ }
131
+ if (code === 'EACCES' || code === 'EPERM') {
132
+ return { reasonCode: 'permission_denied', suggestedNextStep: 'Check file permissions or ask the user for access; do not retry unchanged.' };
133
+ }
134
+ return { suggestedNextStep: 'Check the path with listFiles, or set allowIgnored=true only if the user explicitly asked to inspect an ignored file.' };
135
+ }
@@ -69,7 +69,7 @@ export declare function scopedContextMutationStop(toolName: string, filePath: st
69
69
  /**
70
70
  * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
71
71
  * - skip concurrent mutations of the same path;
72
- * - force a re-read before retrying an edit that just failed on a path;
72
+ * - force a re-read when a stale-content failure explicitly requests one;
73
73
  * - skip identical completed read-only calls until a mutation occurs;
74
74
  * - skip identical in-flight calls;
75
75
  * - bump a mutation epoch on successful writes so read caches invalidate.
@@ -1,30 +1,58 @@
1
1
  import { z } from 'zod';
2
2
  import { readScopedContextFilesForPath } from '../../config/contextFiles.js';
3
- import { workspaceRoot } from '../../utils/path.js';
4
- import { isFailedToolOutput, toolInputField } from '../../core/agent/toolResults.js';
3
+ import { workspacePathKey, workspaceRoot } from '../../utils/path.js';
4
+ import { isFailedToolOutput, requiresReadFileRecovery, toolInputField } from '../../core/agent/toolResults.js';
5
5
  import { HazeToolError } from './failures.js';
6
- function stableJsonStringify(value) {
6
+ function stableJsonStringify(value, seen = new WeakSet()) {
7
7
  if (Array.isArray(value))
8
- return `[${value.map(stableJsonStringify).join(',')}]`;
8
+ return `[${value.map(item => stableJsonStringify(item, seen)).join(',')}]`;
9
9
  if (value && typeof value === 'object') {
10
+ if (seen.has(value))
11
+ throw new Error('Circular tool input');
12
+ seen.add(value);
10
13
  const entries = Object.entries(value)
11
14
  .filter(([, entryValue]) => entryValue !== undefined)
12
15
  .sort(([a], [b]) => a.localeCompare(b));
13
- return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`).join(',')}}`;
16
+ return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue, seen)}`).join(',')}}`;
14
17
  }
15
18
  return JSON.stringify(value) ?? 'undefined';
16
19
  }
17
20
  function toolCallKey(toolName, input) {
18
21
  return `${toolName}:${stableJsonStringify(input)}`;
19
22
  }
20
- export const hazeToolContextSchema = z.custom(value => typeof value === 'object' && value !== null);
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+ function isMutationPolicy(value) {
27
+ return isRecord(value) && typeof value.acquire === 'function' && typeof value.createOwner === 'function';
28
+ }
29
+ function isHazeToolContext(value) {
30
+ if (!isRecord(value))
31
+ return false;
32
+ const validOptional = (key, predicate) => value[key] === undefined || predicate(value[key]);
33
+ return validOptional('inFlightToolCalls', field => field instanceof Map)
34
+ && validOptional('completedToolCalls', field => field instanceof Map)
35
+ && validOptional('mutationEpoch', field => typeof field === 'number' && Number.isSafeInteger(field) && field >= 0)
36
+ && validOptional('failedMutationPaths', field => field instanceof Set)
37
+ && validOptional('failedMutationReasons', field => field instanceof Map)
38
+ && validOptional('pathsReadAfterFailedMutation', field => field instanceof Set)
39
+ && validOptional('inFlightMutationPaths', field => field instanceof Set)
40
+ && validOptional('loadedContextFilePaths', field => field instanceof Set)
41
+ && validOptional('loadedContextFileSignatures', field => field instanceof Map)
42
+ && validOptional('pendingContextFiles', field => Array.isArray(field))
43
+ && validOptional('scopedContextDiscovery', field => field instanceof Promise)
44
+ && validOptional('onContextFileRead', field => typeof field === 'function')
45
+ && validOptional('mutationPolicy', isMutationPolicy)
46
+ && validOptional('mutationOwner', field => typeof field === 'symbol')
47
+ && validOptional('isSubagent', field => typeof field === 'boolean')
48
+ && validOptional('blessedPaths', field => Array.isArray(field) && field.every(item => isRecord(item) && typeof item.realPath === 'string' && typeof item.isDirectory === 'boolean'));
49
+ }
50
+ export const hazeToolContextSchema = z.custom(isHazeToolContext, 'Invalid haze tool context');
21
51
  export function hazeContext(context) {
22
52
  const value = typeof context.context === 'object' && context.context != null
23
53
  ? context.context
24
54
  : context.experimental_context;
25
- return typeof value === 'object' && value != null
26
- ? value
27
- : undefined;
55
+ return isHazeToolContext(value) ? value : undefined;
28
56
  }
29
57
  export function toolsContextFor(tools, context) {
30
58
  const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'bash', 'process', 'fetch']);
@@ -102,7 +130,7 @@ function isDeduplicableReadOnlyTool(toolName) {
102
130
  /**
103
131
  * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
104
132
  * - skip concurrent mutations of the same path;
105
- * - force a re-read before retrying an edit that just failed on a path;
133
+ * - force a re-read when a stale-content failure explicitly requests one;
106
134
  * - skip identical completed read-only calls until a mutation occurs;
107
135
  * - skip identical in-flight calls;
108
136
  * - bump a mutation epoch on successful writes so read caches invalidate.
@@ -120,7 +148,8 @@ export async function runDedupedTool(toolName, input, context, execute) {
120
148
  ctx.mutationEpoch ??= 0;
121
149
  const key = toolCallKey(toolName, input);
122
150
  const pathForInput = toolInputField(input, 'path');
123
- if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
151
+ const mutationPathKey = pathForInput ? workspacePathKey(pathForInput) : undefined;
152
+ if (isMutatingTool(toolName) && mutationPathKey && ctx.inFlightMutationPaths.has(mutationPathKey)) {
124
153
  return {
125
154
  ok: true,
126
155
  duplicateSkipped: true,
@@ -128,12 +157,12 @@ export async function runDedupedTool(toolName, input, context, execute) {
128
157
  reason: `Skipped concurrent mutation for ${pathForInput}. Read the file again, then make one editFile call with all non-overlapping replacements or one replaceLines call based on the latest line numbers.`,
129
158
  };
130
159
  }
131
- if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
132
- const reason = ctx.failedMutationReasons.get(pathForInput);
160
+ if (isMutatingTool(toolName) && mutationPathKey && ctx.failedMutationPaths.has(mutationPathKey) && !ctx.pathsReadAfterFailedMutation.has(mutationPathKey)) {
161
+ const reason = ctx.failedMutationReasons.get(mutationPathKey);
133
162
  throw new HazeToolError(`Read ${pathForInput} before attempting another edit after the previous edit failure${reason ? ` (${reason})` : ''}.`, reason ?? 'io_error', { recoveryTool: 'readFile', recoveryInput: { path: pathForInput } });
134
163
  }
135
164
  const completedAt = ctx.completedToolCalls.get(key);
136
- const readAfterFailedMutation = toolName === 'readFile' && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput);
165
+ const readAfterFailedMutation = toolName === 'readFile' && mutationPathKey && ctx.failedMutationPaths.has(mutationPathKey) && !ctx.pathsReadAfterFailedMutation.has(mutationPathKey);
137
166
  if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
138
167
  return {
139
168
  ok: true,
@@ -152,8 +181,8 @@ export async function runDedupedTool(toolName, input, context, execute) {
152
181
  reason: 'Skipped duplicate in-flight tool call with identical input.',
153
182
  };
154
183
  }
155
- if (isMutatingTool(toolName) && pathForInput)
156
- ctx.inFlightMutationPaths.add(pathForInput);
184
+ if (isMutatingTool(toolName) && mutationPathKey)
185
+ ctx.inFlightMutationPaths.add(mutationPathKey);
157
186
  let releaseMutation;
158
187
  const promise = (async () => {
159
188
  if (isMutatingTool(toolName) && ctx.mutationPolicy) {
@@ -169,39 +198,39 @@ export async function runDedupedTool(toolName, input, context, execute) {
169
198
  try {
170
199
  const result = await promise;
171
200
  if (isFailedToolOutput(result)) {
172
- if (isMutatingTool(toolName) && pathForInput) {
173
- ctx.failedMutationPaths.add(pathForInput);
201
+ if (isMutatingTool(toolName) && mutationPathKey && requiresReadFileRecovery(result)) {
202
+ ctx.failedMutationPaths.add(mutationPathKey);
174
203
  const reasonCode = typeof result === 'object' && result != null && 'reasonCode' in result ? result.reasonCode : undefined;
175
- ctx.failedMutationReasons.set(pathForInput, reasonCode);
176
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
204
+ ctx.failedMutationReasons.set(mutationPathKey, reasonCode);
205
+ ctx.pathsReadAfterFailedMutation.delete(mutationPathKey);
177
206
  }
178
207
  return result;
179
208
  }
180
- if (toolName === 'readFile' && pathForInput)
181
- ctx.pathsReadAfterFailedMutation.add(pathForInput);
209
+ if (toolName === 'readFile' && mutationPathKey)
210
+ ctx.pathsReadAfterFailedMutation.add(mutationPathKey);
182
211
  if (isMutatingTool(toolName)) {
183
212
  ctx.mutationEpoch += 1;
184
- if (pathForInput) {
185
- ctx.failedMutationPaths.delete(pathForInput);
186
- ctx.failedMutationReasons.delete(pathForInput);
187
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
213
+ if (mutationPathKey) {
214
+ ctx.failedMutationPaths.delete(mutationPathKey);
215
+ ctx.failedMutationReasons.delete(mutationPathKey);
216
+ ctx.pathsReadAfterFailedMutation.delete(mutationPathKey);
188
217
  }
189
218
  }
190
219
  ctx.completedToolCalls.set(key, ctx.mutationEpoch);
191
220
  return result;
192
221
  }
193
222
  catch (error) {
194
- if (isMutatingTool(toolName) && pathForInput) {
195
- ctx.failedMutationPaths.add(pathForInput);
196
- ctx.failedMutationReasons.set(pathForInput, error instanceof HazeToolError ? error.reasonCode : undefined);
197
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
223
+ if (isMutatingTool(toolName) && mutationPathKey && requiresReadFileRecovery(error)) {
224
+ ctx.failedMutationPaths.add(mutationPathKey);
225
+ ctx.failedMutationReasons.set(mutationPathKey, error instanceof HazeToolError ? error.reasonCode : undefined);
226
+ ctx.pathsReadAfterFailedMutation.delete(mutationPathKey);
198
227
  }
199
228
  throw error;
200
229
  }
201
230
  finally {
202
231
  releaseMutation?.();
203
232
  ctx.inFlightToolCalls.delete(key);
204
- if (isMutatingTool(toolName) && pathForInput)
205
- ctx.inFlightMutationPaths?.delete(pathForInput);
233
+ if (isMutatingTool(toolName) && mutationPathKey)
234
+ ctx.inFlightMutationPaths?.delete(mutationPathKey);
206
235
  }
207
236
  }
@@ -58,6 +58,23 @@ export declare function extractContent(html: string, url: string): Promise<{
58
58
  content: string;
59
59
  title?: string;
60
60
  }>;
61
+ /**
62
+ * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
63
+ *
64
+ * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
65
+ * verified every address is public, but the global `fetch` would re-resolve the
66
+ * hostname at connect time — an attacker-controlled DNS server can return a
67
+ * public IP for the validation lookup and a private/internal IP for the connect
68
+ * lookup. By connecting directly to the already-validated IP (`hostname:
69
+ * pinnedIp`) while keeping the original `Host` header and TLS `servername`
70
+ * (`url.hostname`), the connection target is fixed to what we validated, with no
71
+ * second DNS lookup. TLS certificate verification still runs against the original
72
+ * hostname via `servername`, so pinning does not weaken identity checks.
73
+ *
74
+ * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
75
+ * they fall through to the global `fetch` — which also keeps the test mocks that
76
+ * stub `globalThis.fetch` working for that path.
77
+ */
61
78
  export declare function pinnedFetch(url: URL, pinnedIp: string | undefined, init: RequestInit): Promise<Response>;
62
79
  /**
63
80
  * Fetch a public http(s) URL and return readable content.