@denizokcu/haze 0.9.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  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/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -0,0 +1,41 @@
1
+ import { tool } from 'ai';
2
+ import { z } from 'zod';
3
+ import { getBackgroundProcess, killBackgroundProcess, listBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
4
+ import { readToolOutput } from '../../core/agent/toolOutputStore.js';
5
+ import { hazeContext, hazeToolContextSchema } from './toolContext.js';
6
+ export const processTool = tool({
7
+ description: 'List, read output from, or kill background processes started by bash background=true. Kill servers and watchers when finished.',
8
+ contextSchema: hazeToolContextSchema,
9
+ inputSchema: z.object({
10
+ action: z.enum(['list', 'output', 'kill']),
11
+ backgroundId: z.string().optional().describe('Required for output and kill, e.g. background-1'),
12
+ offset: z.number().int().nonnegative().default(0).describe('Character offset for output'),
13
+ limit: z.number().int().positive().max(20_000).default(12_000).describe('Maximum output characters'),
14
+ }),
15
+ execute: async ({ action, backgroundId, offset, limit }, context) => {
16
+ if (hazeContext(context)?.isSubagent) {
17
+ return { ok: false, reasonCode: 'background_not_allowed', recoverable: false, error: 'Background processes are unavailable in fleet workers.', suggestedNextStep: 'Manage background processes from the main conversation.' };
18
+ }
19
+ if (action === 'list') {
20
+ return { ok: true, processes: listBackgroundProcesses() };
21
+ }
22
+ if (!backgroundId) {
23
+ return { ok: false, reasonCode: 'process_id_required', recoverable: true, error: `backgroundId is required for process action=${action}.`, suggestedNextStep: 'Call process action=list and retry with an existing backgroundId.' };
24
+ }
25
+ const existing = getBackgroundProcess(backgroundId);
26
+ if (!existing) {
27
+ return { ok: false, reasonCode: 'process_not_found', recoverable: true, error: `No background process named ${backgroundId}.`, suggestedNextStep: 'Call process action=list to get current ids.' };
28
+ }
29
+ if (action === 'output') {
30
+ const page = readToolOutput(existing.outputHandle, offset, limit);
31
+ return page ? { ok: true, backgroundId, status: existing.status, outputHandle: existing.outputHandle, ...page } : { ok: false, reasonCode: 'output_expired', recoverable: false, error: `Output handle for ${backgroundId} has expired.`, suggestedNextStep: 'Restart the background process if its output is still needed.' };
32
+ }
33
+ if (existing.status !== 'running') {
34
+ return { ok: false, reasonCode: 'process_already_exited', recoverable: false, error: `${backgroundId} is already ${existing.status}.`, suggestedNextStep: 'Call process action=list to inspect remaining processes.' };
35
+ }
36
+ const killed = await killBackgroundProcess(backgroundId);
37
+ return killed?.status === 'killed'
38
+ ? { ok: true, action: 'kill', process: killed }
39
+ : { ok: false, reasonCode: 'process_kill_failed', recoverable: false, error: killed?.error ?? `Failed to kill ${backgroundId}.`, suggestedNextStep: 'Stop haze to trigger final process-tree teardown, then inspect the host process list.' };
40
+ },
41
+ });
@@ -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
+ }
@@ -1,6 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import type { ToolFailureReasonCode } from '../toolResultTypes.js';
3
3
  import { type ContextFile } from '../../config/contextFiles.js';
4
+ import type { BlessedPath } from '../../core/attachments/readBlessings.js';
5
+ import type { WorkspaceMutationOwner, WorkspaceMutationPolicy } from '../../core/subagent/workspaceMutationPolicy.js';
4
6
  /**
5
7
  * Turn-scoped tool-call orchestration shared by every built-in tool: in-flight
6
8
  * and completed-call deduplication, a mutation epoch that invalidates read
@@ -29,6 +31,12 @@ export type HazeToolContext = {
29
31
  pendingContextFiles?: ContextFile[];
30
32
  scopedContextDiscovery?: Promise<void>;
31
33
  onContextFileRead?: (path: string) => void;
34
+ mutationPolicy?: WorkspaceMutationPolicy;
35
+ mutationOwner?: WorkspaceMutationOwner;
36
+ /** True in disposable worker contexts; background processes are main-turn-only. */
37
+ isSubagent?: boolean;
38
+ /** Real paths the user mentioned this turn; read tools may escape workspace for them. */
39
+ blessedPaths?: readonly BlessedPath[];
32
40
  };
33
41
  export declare const hazeToolContextSchema: z.ZodCustom<HazeToolContext, HazeToolContext>;
34
42
  export declare function hazeContext(context: ToolExecutionContext): HazeToolContext | undefined;
@@ -61,7 +69,7 @@ export declare function scopedContextMutationStop(toolName: string, filePath: st
61
69
  /**
62
70
  * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
63
71
  * - skip concurrent mutations of the same path;
64
- * - 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;
65
73
  * - skip identical completed read-only calls until a mutation occurs;
66
74
  * - skip identical in-flight calls;
67
75
  * - bump a mutation epoch on successful writes so read caches invalidate.
@@ -1,33 +1,61 @@
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
- const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'bash', 'fetch']);
58
+ const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'bash', 'process', 'fetch']);
31
59
  return Object.fromEntries(Object.keys(tools).filter(name => hazeToolNames.has(name)).map(name => [name, context]));
32
60
  }
33
61
  /**
@@ -86,21 +114,23 @@ export function scopedContextMutationStop(toolName, filePath, files) {
86
114
  };
87
115
  }
88
116
  function isMutatingTool(toolName) {
89
- return ['editFile', 'replaceLines', 'writeFile'].includes(toolName);
117
+ // Bash is conservatively workspace-mutation-capable. Classification remains
118
+ // informational and is not a sandbox boundary.
119
+ return ['editFile', 'replaceLines', 'writeFile', 'bash'].includes(toolName);
90
120
  }
91
121
  function isReadOnlyFileTool(toolName) {
92
122
  return ['listFiles', 'readFile', 'grep'].includes(toolName);
93
123
  }
94
124
  // Read-only tools that participate in completed-call deduplication within a
95
- // turn (no side effects). File tools + bash + fetch; fetch has no path and is
96
- // network-side-effect-free for the agent's purposes.
125
+ // turn (no side effects). Bash is deliberately excluded: commands can observe
126
+ // external state changes between identical calls (CR-007).
97
127
  function isDeduplicableReadOnlyTool(toolName) {
98
- return isReadOnlyFileTool(toolName) || toolName === 'bash' || toolName === 'fetch';
128
+ return isReadOnlyFileTool(toolName) || toolName === 'fetch';
99
129
  }
100
130
  /**
101
131
  * Wrap a tool's execution with turn-scoped deduplication and edit-recovery:
102
132
  * - skip concurrent mutations of the same path;
103
- * - 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;
104
134
  * - skip identical completed read-only calls until a mutation occurs;
105
135
  * - skip identical in-flight calls;
106
136
  * - bump a mutation epoch on successful writes so read caches invalidate.
@@ -118,7 +148,8 @@ export async function runDedupedTool(toolName, input, context, execute) {
118
148
  ctx.mutationEpoch ??= 0;
119
149
  const key = toolCallKey(toolName, input);
120
150
  const pathForInput = toolInputField(input, 'path');
121
- if (isMutatingTool(toolName) && pathForInput && ctx.inFlightMutationPaths.has(pathForInput)) {
151
+ const mutationPathKey = pathForInput ? workspacePathKey(pathForInput) : undefined;
152
+ if (isMutatingTool(toolName) && mutationPathKey && ctx.inFlightMutationPaths.has(mutationPathKey)) {
122
153
  return {
123
154
  ok: true,
124
155
  duplicateSkipped: true,
@@ -126,22 +157,20 @@ export async function runDedupedTool(toolName, input, context, execute) {
126
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.`,
127
158
  };
128
159
  }
129
- if (isMutatingTool(toolName) && pathForInput && ctx.failedMutationPaths.has(pathForInput) && !ctx.pathsReadAfterFailedMutation.has(pathForInput)) {
130
- 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);
131
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 } });
132
163
  }
133
164
  const completedAt = ctx.completedToolCalls.get(key);
134
- 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);
135
166
  if ((isDeduplicableReadOnlyTool(toolName)) && completedAt === ctx.mutationEpoch && !readAfterFailedMutation) {
136
167
  return {
137
168
  ok: true,
138
169
  duplicateSkipped: true,
139
170
  toolName,
140
- reason: toolName === 'bash'
141
- ? 'Skipped duplicate bash command; no files changed since the previous run.'
142
- : toolName === 'fetch'
143
- ? 'Skipped duplicate fetch with identical URL; no files changed since the previous call.'
144
- : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
171
+ reason: toolName === 'fetch'
172
+ ? 'Skipped duplicate fetch with identical URL; no files changed since the previous call.'
173
+ : 'Skipped duplicate read-only tool call with identical input; no files changed since the previous call.',
145
174
  };
146
175
  }
147
176
  if (ctx.inFlightToolCalls.has(key)) {
@@ -152,45 +181,56 @@ 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);
157
- const promise = execute();
184
+ if (isMutatingTool(toolName) && mutationPathKey)
185
+ ctx.inFlightMutationPaths.add(mutationPathKey);
186
+ let releaseMutation;
187
+ const promise = (async () => {
188
+ if (isMutatingTool(toolName) && ctx.mutationPolicy) {
189
+ // A worker supplies its whole-run owner so nested tool calls are
190
+ // reentrant. Main-turn calls intentionally receive a fresh owner per
191
+ // mutation, serializing concurrent edit/bash calls.
192
+ const owner = ctx.mutationOwner ?? ctx.mutationPolicy.createOwner();
193
+ releaseMutation = await ctx.mutationPolicy.acquire(owner, context.abortSignal);
194
+ }
195
+ return await execute();
196
+ })();
158
197
  ctx.inFlightToolCalls.set(key, promise);
159
198
  try {
160
199
  const result = await promise;
161
200
  if (isFailedToolOutput(result)) {
162
- if (isMutatingTool(toolName) && pathForInput) {
163
- ctx.failedMutationPaths.add(pathForInput);
201
+ if (isMutatingTool(toolName) && mutationPathKey && requiresReadFileRecovery(result)) {
202
+ ctx.failedMutationPaths.add(mutationPathKey);
164
203
  const reasonCode = typeof result === 'object' && result != null && 'reasonCode' in result ? result.reasonCode : undefined;
165
- ctx.failedMutationReasons.set(pathForInput, reasonCode);
166
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
204
+ ctx.failedMutationReasons.set(mutationPathKey, reasonCode);
205
+ ctx.pathsReadAfterFailedMutation.delete(mutationPathKey);
167
206
  }
168
207
  return result;
169
208
  }
170
- if (toolName === 'readFile' && pathForInput)
171
- ctx.pathsReadAfterFailedMutation.add(pathForInput);
209
+ if (toolName === 'readFile' && mutationPathKey)
210
+ ctx.pathsReadAfterFailedMutation.add(mutationPathKey);
172
211
  if (isMutatingTool(toolName)) {
173
212
  ctx.mutationEpoch += 1;
174
- if (pathForInput) {
175
- ctx.failedMutationPaths.delete(pathForInput);
176
- ctx.failedMutationReasons.delete(pathForInput);
177
- ctx.pathsReadAfterFailedMutation.delete(pathForInput);
213
+ if (mutationPathKey) {
214
+ ctx.failedMutationPaths.delete(mutationPathKey);
215
+ ctx.failedMutationReasons.delete(mutationPathKey);
216
+ ctx.pathsReadAfterFailedMutation.delete(mutationPathKey);
178
217
  }
179
218
  }
180
219
  ctx.completedToolCalls.set(key, ctx.mutationEpoch);
181
220
  return result;
182
221
  }
183
222
  catch (error) {
184
- if (isMutatingTool(toolName) && pathForInput) {
185
- ctx.failedMutationPaths.add(pathForInput);
186
- ctx.failedMutationReasons.set(pathForInput, error instanceof HazeToolError ? error.reasonCode : undefined);
187
- 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);
188
227
  }
189
228
  throw error;
190
229
  }
191
230
  finally {
231
+ releaseMutation?.();
192
232
  ctx.inFlightToolCalls.delete(key);
193
- if (isMutatingTool(toolName) && pathForInput)
194
- ctx.inFlightMutationPaths?.delete(pathForInput);
233
+ if (isMutatingTool(toolName) && mutationPathKey)
234
+ ctx.inFlightMutationPaths?.delete(mutationPathKey);
195
235
  }
196
236
  }
@@ -1,6 +1,14 @@
1
1
  import { type ToolExecutionContext } from './toolContext.js';
2
2
  export declare function prepareWorkspaceExisting(filePath: string): Promise<string>;
3
- export declare function prepareWorkspaceRead(filePath: string, allowIgnored: boolean | undefined): Promise<string>;
3
+ /**
4
+ * Resolve a read path and confine it to the workspace — unless the user
5
+ * explicitly mentioned it (or a parent directory) in the prompt this turn.
6
+ * Blessed paths skip both `.gitignore` enforcement and the workspace boundary
7
+ * so the model can read host files the user pointed at. Mutating tools use
8
+ * `prepareWorkspaceMutation` / `prepareWorkspaceWritePath` instead, which
9
+ * never consult the bless set.
10
+ */
11
+ export declare function prepareWorkspaceRead(filePath: string, allowIgnored: boolean | undefined, context?: ToolExecutionContext): Promise<string>;
4
12
  export declare function prepareWorkspaceMutation(toolName: string, filePath: string, allowIgnored: boolean | undefined, context: ToolExecutionContext): Promise<{
5
13
  absolutePath: string;
6
14
  scopedContext: import("../../config/contextFiles.js").ContextFile[];
@@ -1,19 +1,48 @@
1
- import { assertRealPathInsideWorkspace, assertWritablePathInsideWorkspace, resolveWorkspacePath } from '../../utils/path.js';
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { assertRealPathInsideWorkspace, assertWritablePathInsideWorkspace, resolveWorkspacePath, workspaceRoot } from '../../utils/path.js';
4
+ import { isPathBlessed } from '../../core/attachments/readBlessings.js';
2
5
  import { assertNotIgnored } from './fileToolShared.js';
3
- import { discoverScopedContext, scopedContextMutationStop } from './toolContext.js';
6
+ import { discoverScopedContext, hazeContext, scopedContextMutationStop } from './toolContext.js';
4
7
  export async function prepareWorkspaceExisting(filePath) {
5
8
  const absolutePath = resolveWorkspacePath(filePath);
6
9
  await assertRealPathInsideWorkspace(absolutePath, filePath);
7
10
  return absolutePath;
8
11
  }
9
- export async function prepareWorkspaceRead(filePath, allowIgnored) {
12
+ /**
13
+ * Resolve a read path and confine it to the workspace — unless the user
14
+ * explicitly mentioned it (or a parent directory) in the prompt this turn.
15
+ * Blessed paths skip both `.gitignore` enforcement and the workspace boundary
16
+ * so the model can read host files the user pointed at. Mutating tools use
17
+ * `prepareWorkspaceMutation` / `prepareWorkspaceWritePath` instead, which
18
+ * never consult the bless set.
19
+ */
20
+ export async function prepareWorkspaceRead(filePath, allowIgnored, context) {
21
+ const blessed = context ? hazeContext(context)?.blessedPaths : undefined;
22
+ if (blessed && blessed.length > 0) {
23
+ const absolutePath = path.resolve(workspaceRoot(), filePath);
24
+ const realRequested = await requestedRealPath(absolutePath);
25
+ if (isPathBlessed(realRequested, blessed))
26
+ return absolutePath;
27
+ }
10
28
  const absolutePath = resolveWorkspacePath(filePath);
11
29
  await assertNotIgnored(absolutePath, filePath, allowIgnored);
12
30
  await assertRealPathInsideWorkspace(absolutePath, filePath);
13
31
  return absolutePath;
14
32
  }
33
+ /** Best-effort realpath for bless comparison; falls back to the verbatim path if the file is gone. */
34
+ async function requestedRealPath(absolutePath) {
35
+ try {
36
+ return await fs.realpath(absolutePath);
37
+ }
38
+ catch {
39
+ return absolutePath;
40
+ }
41
+ }
15
42
  export async function prepareWorkspaceMutation(toolName, filePath, allowIgnored, context) {
16
- const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
43
+ const absolutePath = resolveWorkspacePath(filePath);
44
+ await assertNotIgnored(absolutePath, filePath, allowIgnored);
45
+ await assertRealPathInsideWorkspace(absolutePath, filePath);
17
46
  const scopedContext = await discoverScopedContext(filePath, context);
18
47
  const scopedStop = scopedContextMutationStop(toolName, filePath, scopedContext);
19
48
  return { absolutePath, scopedContext, scopedStop };
@@ -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.