@denizokcu/haze 0.10.0 → 1.0.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 (294) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/README.md +77 -27
  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 +2 -2
  9. package/dist/cli/chat/chatMetrics.js +1 -1
  10. package/dist/cli/chat/contextReport.js +2 -0
  11. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  12. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  13. package/dist/cli/chat/inputSuggestions.js +9 -41
  14. package/dist/cli/chat/liveRegion.d.ts +25 -0
  15. package/dist/cli/chat/liveRegion.js +48 -0
  16. package/dist/cli/chat/messages.d.ts +33 -4
  17. package/dist/cli/chat/messages.js +218 -35
  18. package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
  19. package/dist/cli/chat/sessionLifecycle.js +64 -14
  20. package/dist/cli/chat/sessionRecorder.js +75 -7
  21. package/dist/cli/chat/startupInfo.d.ts +0 -1
  22. package/dist/cli/chat/startupInfo.js +11 -15
  23. package/dist/cli/chat/turnState.d.ts +1 -1
  24. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  25. package/dist/cli/chat/wizardDispatch.js +349 -133
  26. package/dist/cli/commands/chat.d.ts +5 -0
  27. package/dist/cli/commands/chat.js +216 -172
  28. package/dist/cli/commands/chatModes.d.ts +8 -1
  29. package/dist/cli/commands/chatModes.js +9 -44
  30. package/dist/cli/commands/commands.d.ts +2 -0
  31. package/dist/cli/commands/commands.js +10 -5
  32. package/dist/cli/commands/doctor.d.ts +19 -0
  33. package/dist/cli/commands/doctor.js +76 -0
  34. package/dist/cli/commands/formatters.d.ts +3 -3
  35. package/dist/cli/commands/formatters.js +8 -25
  36. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  37. package/dist/cli/commands/ndjsonSink.js +38 -0
  38. package/dist/cli/commands/providerWizard.d.ts +9 -2
  39. package/dist/cli/commands/providerWizard.js +39 -7
  40. package/dist/cli/commands/runCommand.d.ts +3 -0
  41. package/dist/cli/commands/runCommand.js +117 -11
  42. package/dist/cli/commands/serverWizard.d.ts +34 -0
  43. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  44. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  45. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  46. package/dist/cli/commands/streaming/abortCause.d.ts +25 -0
  47. package/dist/cli/commands/streaming/abortCause.js +16 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  50. package/dist/cli/commands/streaming/assistantText.js +9 -2
  51. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  62. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +16 -0
  66. package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
  68. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  69. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  70. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  71. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  73. package/dist/cli/commands/streaming.d.ts +65 -9
  74. package/dist/cli/commands/streaming.js +133 -430
  75. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  76. package/dist/cli/commands/wizardFlow.js +377 -0
  77. package/dist/cli/contextReport.js +3 -0
  78. package/dist/cli/index.js +68 -22
  79. package/dist/cli/terminalTitle.js +1 -1
  80. package/dist/config/contextFiles.js +9 -3
  81. package/dist/config/inputHistory.d.ts +0 -1
  82. package/dist/config/inputHistory.js +1 -1
  83. package/dist/config/modelDiscovery.d.ts +36 -0
  84. package/dist/config/modelDiscovery.js +164 -1
  85. package/dist/config/privateStorage.js +28 -2
  86. package/dist/config/providerAuth.d.ts +14 -0
  87. package/dist/config/providerAuth.js +49 -0
  88. package/dist/config/providerPresets.d.ts +39 -7
  89. package/dist/config/providerPresets.js +371 -100
  90. package/dist/config/providers.js +2 -0
  91. package/dist/config/settings.d.ts +43 -0
  92. package/dist/config/settings.js +12 -0
  93. package/dist/config/skillSettings.js +4 -4
  94. package/dist/config/updateCheck.d.ts +0 -1
  95. package/dist/config/updateCheck.js +1 -1
  96. package/dist/core/agent/budgets.d.ts +73 -1
  97. package/dist/core/agent/budgets.js +94 -1
  98. package/dist/core/agent/compaction.d.ts +38 -0
  99. package/dist/core/agent/compaction.js +92 -17
  100. package/dist/core/agent/completionController.d.ts +224 -0
  101. package/dist/core/agent/completionController.js +296 -0
  102. package/dist/core/agent/contextBudget.d.ts +36 -2
  103. package/dist/core/agent/contextBudget.js +62 -9
  104. package/dist/core/agent/errors.d.ts +0 -1
  105. package/dist/core/agent/errors.js +1 -1
  106. package/dist/core/agent/events.d.ts +78 -0
  107. package/dist/core/agent/goalPolicy.d.ts +47 -0
  108. package/dist/core/agent/goalPolicy.js +106 -0
  109. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  110. package/dist/core/agent/reasoningPolicy.js +27 -0
  111. package/dist/core/agent/requestAssembly.d.ts +2 -2
  112. package/dist/core/agent/requestAssembly.js +16 -4
  113. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  114. package/dist/core/agent/toolCapabilities.js +58 -0
  115. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  116. package/dist/core/agent/toolOutputStore.js +11 -11
  117. package/dist/core/agent/toolResults.d.ts +12 -0
  118. package/dist/core/agent/toolResults.js +38 -0
  119. package/dist/core/agent/turnPolicy.d.ts +11 -0
  120. package/dist/core/agent/turnPolicy.js +19 -0
  121. package/dist/core/agent/workState.d.ts +81 -3
  122. package/dist/core/agent/workState.js +176 -10
  123. package/dist/core/attachments/imageAttachments.js +90 -42
  124. package/dist/core/deadline.d.ts +27 -0
  125. package/dist/core/deadline.js +74 -0
  126. package/dist/core/io/boundedRead.js +1 -1
  127. package/dist/core/limits.d.ts +51 -0
  128. package/dist/core/limits.js +51 -0
  129. package/dist/core/log/llmLog.js +8 -1
  130. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  131. package/dist/core/persistence/orderedFileWriter.js +16 -2
  132. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  133. package/dist/core/process/backgroundRegistry.js +15 -10
  134. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  135. package/dist/core/process/runBoundedProcess.js +15 -6
  136. package/dist/core/process/userShell.d.ts +16 -0
  137. package/dist/core/process/userShell.js +59 -0
  138. package/dist/core/safety/missingExecutable.d.ts +42 -0
  139. package/dist/core/safety/missingExecutable.js +77 -0
  140. package/dist/core/safety/shellClassifier.d.ts +11 -0
  141. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  142. package/dist/core/safety/urlGuard.d.ts +1 -1
  143. package/dist/core/session/sessionSlimming.d.ts +0 -3
  144. package/dist/core/session/sessionSlimming.js +2 -3
  145. package/dist/core/session/sessionStore.d.ts +38 -0
  146. package/dist/core/session/sessionStore.js +242 -59
  147. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  148. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  149. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  150. package/dist/core/shellOutput/registry.d.ts +2 -0
  151. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  152. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  153. package/dist/core/subagent/contracts.d.ts +6 -14
  154. package/dist/core/subagent/contracts.js +4 -3
  155. package/dist/core/subagent/executionProfiles.js +2 -2
  156. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  157. package/dist/core/subagent/subagentCoordinator.js +32 -2
  158. package/dist/core/subagent/subagentRunner.js +19 -40
  159. package/dist/core/toolOutput/reduction.d.ts +0 -12
  160. package/dist/core/toolOutput/reduction.js +1 -1
  161. package/dist/core/validation/outputParser.d.ts +2 -2
  162. package/dist/llm/client.d.ts +17 -1
  163. package/dist/llm/client.js +86 -14
  164. package/dist/llm/hazeTools.d.ts +693 -204
  165. package/dist/llm/hazeTools.js +110 -28
  166. package/dist/llm/initPrompt.js +1 -1
  167. package/dist/llm/lsp/client.d.ts +45 -0
  168. package/dist/llm/lsp/client.js +195 -0
  169. package/dist/llm/lsp/pool.d.ts +23 -0
  170. package/dist/llm/lsp/pool.js +86 -0
  171. package/dist/llm/lsp/protocol.d.ts +64 -0
  172. package/dist/llm/lsp/protocol.js +128 -0
  173. package/dist/llm/lsp/requests.d.ts +94 -0
  174. package/dist/llm/lsp/requests.js +119 -0
  175. package/dist/llm/lspTools.d.ts +5653 -33
  176. package/dist/llm/lspTools.js +152 -80
  177. package/dist/llm/openaiCodex.d.ts +1 -0
  178. package/dist/llm/openaiCodex.js +43 -0
  179. package/dist/llm/openaiCodexOAuth.d.ts +51 -0
  180. package/dist/llm/openaiCodexOAuth.js +217 -0
  181. package/dist/llm/requestContext.d.ts +7 -0
  182. package/dist/llm/requestContext.js +30 -4
  183. package/dist/llm/systemPrompt.d.ts +12 -0
  184. package/dist/llm/systemPrompt.js +24 -11
  185. package/dist/llm/toolResultTypes.d.ts +7 -14
  186. package/dist/llm/toolResultTypes.js +1 -4
  187. package/dist/llm/tools/editMatch.d.ts +14 -9
  188. package/dist/llm/tools/editMatch.js +73 -1
  189. package/dist/llm/tools/failures.d.ts +2 -0
  190. package/dist/llm/tools/failures.js +1 -0
  191. package/dist/llm/tools/fetchTool.d.ts +16 -0
  192. package/dist/llm/tools/fetchTool.js +1 -1
  193. package/dist/llm/tools/fileToolShared.d.ts +8 -5
  194. package/dist/llm/tools/fileToolShared.js +22 -23
  195. package/dist/llm/tools/gitIgnore.d.ts +42 -0
  196. package/dist/llm/tools/gitIgnore.js +247 -0
  197. package/dist/llm/tools/grepParse.d.ts +2 -1
  198. package/dist/llm/tools/grepRunner.d.ts +1 -1
  199. package/dist/llm/tools/grepRunner.js +2 -2
  200. package/dist/llm/tools/outputCap.d.ts +2 -7
  201. package/dist/llm/tools/outputCap.js +3 -3
  202. package/dist/llm/tools/processTool.d.ts +16 -16
  203. package/dist/llm/tools/processTool.js +1 -1
  204. package/dist/llm/tools/readRecovery.d.ts +8 -0
  205. package/dist/llm/tools/readRecovery.js +135 -0
  206. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
  207. package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
  208. package/dist/llm/tools/toolContext.d.ts +1 -1
  209. package/dist/llm/tools/toolContext.js +66 -37
  210. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  211. package/dist/llm/tools/workspaceFile.js +1 -6
  212. package/dist/llm/webFetch.d.ts +18 -1
  213. package/dist/llm/webFetch.js +64 -97
  214. package/dist/skills/SkillLoader.d.ts +1 -11
  215. package/dist/skills/SkillLoader.js +1 -2
  216. package/dist/skills/types.d.ts +2 -1
  217. package/dist/ui/codeHighlight.d.ts +4 -0
  218. package/dist/ui/codeHighlight.js +31 -0
  219. package/dist/ui/components/Header.d.ts +1 -1
  220. package/dist/ui/components/MarkdownText.d.ts +16 -2
  221. package/dist/ui/components/MarkdownText.js +244 -34
  222. package/dist/ui/components/TextInput.d.ts +8 -1
  223. package/dist/ui/components/TextInput.js +6 -2
  224. package/dist/ui/theme.d.ts +4 -3
  225. package/dist/ui/theme.js +5 -4
  226. package/dist/utils/buildInfo.d.ts +97 -0
  227. package/dist/utils/buildInfo.js +244 -0
  228. package/dist/utils/fs.d.ts +11 -0
  229. package/dist/utils/fs.js +91 -26
  230. package/dist/utils/openPath.d.ts +2 -2
  231. package/dist/utils/openPath.js +19 -6
  232. package/dist/utils/path.d.ts +2 -1
  233. package/dist/utils/path.js +6 -2
  234. package/dist/utils/utf8.d.ts +22 -0
  235. package/dist/utils/utf8.js +54 -0
  236. package/dist/utils/version.d.ts +9 -3
  237. package/dist/utils/version.js +28 -2
  238. package/package.json +28 -21
  239. package/dist/cli/commands/lspWizard.d.ts +0 -14
  240. package/dist/cli/commands/lspWizard.js +0 -44
  241. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  242. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  243. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  244. package/dist/cli/commands/skillCreation.d.ts +0 -12
  245. package/dist/cli/commands/skillCreation.js +0 -14
  246. package/dist/cli/commands/skillWizard.d.ts +0 -17
  247. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  248. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  249. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -10
  250. package/dist/cli/commands/streaming/turnOutcome.js +0 -13
  251. package/dist/cli/commands/wizardActions.d.ts +0 -46
  252. package/dist/cli/commands/wizardActions.js +0 -46
  253. package/dist/cli/commands/wizardInput.d.ts +0 -4
  254. package/dist/cli/commands/wizardInput.js +0 -19
  255. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  256. package/dist/cli/commands/wizardPrompts.js +0 -52
  257. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  258. package/dist/cli/commands/wizardSuggestions.js +0 -188
  259. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  260. package/dist/cli/commands/wizardTransition.js +0 -43
  261. package/dist/core/bashOutput/ansi.d.ts +0 -1
  262. package/dist/core/bashOutput/ansi.js +0 -7
  263. package/dist/core/bashOutput/registry.d.ts +0 -4
  264. package/dist/core/goal/completionPolicy.d.ts +0 -2
  265. package/dist/core/goal/completionPolicy.js +0 -7
  266. package/dist/core/goal/requestClassifier.d.ts +0 -3
  267. package/dist/core/goal/requestClassifier.js +0 -18
  268. package/dist/core/goal/sessionGoal.d.ts +0 -8
  269. package/dist/core/goal/sessionGoal.js +0 -30
  270. package/dist/core/limits/byteBudgets.d.ts +0 -18
  271. package/dist/core/limits/byteBudgets.js +0 -18
  272. package/dist/core/limits/textBudgets.d.ts +0 -23
  273. package/dist/core/limits/textBudgets.js +0 -23
  274. package/dist/core/safety/bashClassifier.d.ts +0 -10
  275. package/dist/llm/lsp.d.ts +0 -129
  276. package/dist/llm/lsp.js +0 -307
  277. package/dist/ui/components/ErrorView.d.ts +0 -4
  278. package/dist/ui/components/ErrorView.js +0 -7
  279. package/dist/utils/yaml.d.ts +0 -2
  280. package/dist/utils/yaml.js +0 -8
  281. package/examples/skills/files/SKILL.md +0 -16
  282. package/examples/skills/files/examples/file-editing.md +0 -3
  283. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  284. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  285. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  286. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  287. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  288. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  289. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  290. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  291. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  292. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  293. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  294. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -0,0 +1,247 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import ignoreFactory from 'ignore';
4
+ import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
5
+ /**
6
+ * In-process `.gitignore` evaluation. No Git binary is required or used: rules
7
+ * come from `.gitignore` files between the repository/worktree boundary and
8
+ * each candidate (deepest file wins, last matching line within a file wins),
9
+ * plus the resolved Git common directory's `info/exclude` at lowest precedence.
10
+ * Global user excludes are intentionally omitted for deterministic workspaces. The
11
+ * evaluation is pure filesystem work — stat/read/regex — so it is fast enough
12
+ * to call per walked entry and deterministic across environments.
13
+ */
14
+ const GITIGNORE_FILE = '.gitignore';
15
+ const GIT_POINTER_MAX_BYTES = 8 * 1024;
16
+ /** Convert native separators only; a backslash is a valid POSIX filename byte. */
17
+ function gitPath(relPath) {
18
+ return path.sep === '\\' ? relPath.replaceAll('\\', '/') : relPath;
19
+ }
20
+ function probePath(relPath, isDirectory) {
21
+ const normalized = gitPath(relPath).replace(/^\.\//, '').replace(/\/$/, '');
22
+ return isDirectory ? `${normalized}/` : normalized;
23
+ }
24
+ function isOutsideRoot(relativePath) {
25
+ return relativePath === '..' || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath);
26
+ }
27
+ async function lstatIsDirectory(absolutePath) {
28
+ try {
29
+ return (await fs.lstat(absolutePath)).isDirectory();
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ async function readSmallPointer(filePath) {
36
+ const stat = await fs.stat(filePath);
37
+ if (stat.size > GIT_POINTER_MAX_BYTES)
38
+ throw new Error(`Git pointer file exceeds ${GIT_POINTER_MAX_BYTES} bytes.`);
39
+ return fs.readFile(filePath, 'utf8');
40
+ }
41
+ async function resolveExcludeFile(repositoryRoot, gitMarker) {
42
+ try {
43
+ const markerStat = await fs.lstat(gitMarker);
44
+ let gitDir = gitMarker;
45
+ if (!markerStat.isDirectory()) {
46
+ const pointer = /^gitdir:\s*(.+)\s*$/im.exec(await readSmallPointer(gitMarker))?.[1];
47
+ if (!pointer)
48
+ return { checked: false };
49
+ gitDir = path.resolve(repositoryRoot, pointer);
50
+ }
51
+ const commonDirFile = path.join(gitDir, 'commondir');
52
+ try {
53
+ const commonDir = (await readSmallPointer(commonDirFile)).trim();
54
+ if (commonDir)
55
+ gitDir = path.resolve(gitDir, commonDir);
56
+ }
57
+ catch (error) {
58
+ if (error.code !== 'ENOENT')
59
+ return { checked: false };
60
+ }
61
+ return { path: path.join(gitDir, 'info', 'exclude'), checked: true };
62
+ }
63
+ catch {
64
+ return { checked: false };
65
+ }
66
+ }
67
+ /** Find the repository boundary without requiring Git, including linked worktrees. */
68
+ async function discoverIgnoreRoot(workspace) {
69
+ let current = path.resolve(workspace);
70
+ while (true) {
71
+ const marker = path.join(current, '.git');
72
+ try {
73
+ await fs.lstat(marker);
74
+ const exclude = await resolveExcludeFile(current, marker);
75
+ const workspaceRelative = path.relative(current, workspace);
76
+ return {
77
+ ignoreRoot: current,
78
+ workspacePrefix: workspaceRelative === '' ? '' : gitPath(workspaceRelative),
79
+ ...(exclude.path ? { excludeFile: exclude.path } : {}),
80
+ checked: exclude.checked,
81
+ };
82
+ }
83
+ catch (error) {
84
+ if (error.code !== 'ENOENT') {
85
+ return { ignoreRoot: workspace, workspacePrefix: '', checked: false };
86
+ }
87
+ }
88
+ const parent = path.dirname(current);
89
+ if (parent === current)
90
+ return { ignoreRoot: workspace, workspacePrefix: '', checked: true };
91
+ current = parent;
92
+ }
93
+ }
94
+ /**
95
+ * Create an ignore classifier rooted at `root` (defaults to the workspace
96
+ * root). One classifier should own an entire listing operation: it memoizes
97
+ * compiled rule files by mtime, so a walk stats each `.gitignore` once per
98
+ * mtime change instead of re-reading it per entry. Nothing is cached across
99
+ * classifier instances, so external edits are always picked up.
100
+ */
101
+ export function createIgnoreClassifier(root = workspaceRoot()) {
102
+ const workspace = path.resolve(root);
103
+ const rootContext = discoverIgnoreRoot(workspace);
104
+ const ruleFiles = new Map();
105
+ async function loadAbsoluteRuleFile(absolute) {
106
+ let stat;
107
+ try {
108
+ stat = await fs.stat(absolute);
109
+ }
110
+ catch (error) {
111
+ if (error.code === 'ENOENT') {
112
+ const absent = { mtimeMs: -1, size: -1, rules: null };
113
+ ruleFiles.set(absolute, absent);
114
+ return absent;
115
+ }
116
+ // Exists (or unknowable) but cannot be stat-read: not cached, retried next call.
117
+ return { unreadable: true };
118
+ }
119
+ const cached = ruleFiles.get(absolute);
120
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
121
+ return cached;
122
+ try {
123
+ const rules = ignoreFactory().add(await fs.readFile(absolute, 'utf8'));
124
+ const state = { mtimeMs: stat.mtimeMs, size: stat.size, rules };
125
+ ruleFiles.set(absolute, state);
126
+ return state;
127
+ }
128
+ catch {
129
+ return { unreadable: true };
130
+ }
131
+ }
132
+ async function loadRuleFile(relDir) {
133
+ const context = await rootContext;
134
+ return loadAbsoluteRuleFile(path.join(context.ignoreRoot, relDir, GITIGNORE_FILE));
135
+ }
136
+ /**
137
+ * Verdict for one path from its applicable rule files: `.gitignore` files in
138
+ * the parent chain, deepest first (deeper overrides shallower), then the
139
+ * root exclude file (lowest precedence). `unknown` is true when any file in
140
+ * the chain could not be read.
141
+ */
142
+ async function verdictFor(relPath, isDirectory) {
143
+ const context = await rootContext;
144
+ const probe = probePath(relPath, isDirectory);
145
+ const parentSegments = probe.split('/').filter(segment => segment.length > 0).slice(0, -1);
146
+ let unknown = !context.checked;
147
+ for (let index = parentSegments.length; index >= 0; index--) {
148
+ const relDir = parentSegments.slice(0, index).join('/');
149
+ const state = await loadRuleFile(relDir);
150
+ if ('unreadable' in state) {
151
+ unknown = true;
152
+ continue;
153
+ }
154
+ if (!state.rules)
155
+ continue;
156
+ // Paths probed against a nested rule file are relative to its directory.
157
+ const relToDir = index === 0 ? probe : probe.slice(relDir.length + 1);
158
+ const result = state.rules.test(relToDir);
159
+ if (result.ignored || result.unignored)
160
+ return { ignored: result.ignored, unknown };
161
+ }
162
+ if (context.excludeFile) {
163
+ const exclude = await loadAbsoluteRuleFile(context.excludeFile);
164
+ if ('unreadable' in exclude)
165
+ return { ignored: false, unknown: true };
166
+ if (exclude.rules) {
167
+ const result = exclude.rules.test(probe);
168
+ if (result.ignored || result.unignored)
169
+ return { ignored: result.ignored, unknown };
170
+ }
171
+ }
172
+ return { ignored: false, unknown };
173
+ }
174
+ /**
175
+ * Tri-state status for one root-relative path. Any ignored ancestor makes
176
+ * the path ignored (Git cannot re-include below an excluded directory);
177
+ * otherwise the deepest matching rule decides the leaf itself.
178
+ */
179
+ async function statusOf(relPath, isDirectory) {
180
+ const segments = probePath(relPath, isDirectory).replace(/\/$/, '').split('/');
181
+ let unknown = false;
182
+ for (let depth = 1; depth <= segments.length; depth++) {
183
+ const rel = segments.slice(0, depth).join('/');
184
+ const isDir = depth < segments.length || isDirectory;
185
+ const verdict = await verdictFor(rel, isDir);
186
+ if (verdict.unknown)
187
+ unknown = true;
188
+ // An ignored prefix is decisive: everything below it is ignored too.
189
+ if (verdict.ignored)
190
+ return { status: 'ignored', checked: !unknown };
191
+ }
192
+ return { status: 'not-ignored', checked: !unknown };
193
+ }
194
+ const classifyChecked = async (candidates) => {
195
+ // De-duplicate while preserving the first occurrence's directory hint.
196
+ const unique = new Map();
197
+ for (const candidate of candidates) {
198
+ const entry = typeof candidate === 'string' ? { path: candidate } : candidate;
199
+ if (!entry.path || entry.path === '.')
200
+ continue;
201
+ if (!unique.has(entry.path))
202
+ unique.set(entry.path, entry);
203
+ }
204
+ const ignored = new Set();
205
+ let checked = true;
206
+ const context = await rootContext;
207
+ for (const [relPath, entry] of unique) {
208
+ const workspaceRelative = entry.absolutePath ? path.relative(workspace, entry.absolutePath) : relPath;
209
+ if (isOutsideRoot(workspaceRelative))
210
+ continue;
211
+ const absolutePath = entry.absolutePath ?? path.join(workspace, workspaceRelative);
212
+ const isDirectory = entry.isDirectory ?? (await lstatIsDirectory(absolutePath));
213
+ const workspaceProbe = gitPath(workspaceRelative);
214
+ const ignoreRelative = context.workspacePrefix ? `${context.workspacePrefix}/${workspaceProbe}` : workspaceProbe;
215
+ const { status, checked: entryChecked } = await statusOf(ignoreRelative, isDirectory);
216
+ if (!entryChecked)
217
+ checked = false;
218
+ // Reads fail open: an uncertain verdict is never returned as ignored.
219
+ if (status === 'ignored' && entryChecked)
220
+ ignored.add(relPath);
221
+ }
222
+ return { ignored, checked };
223
+ };
224
+ return {
225
+ classifyChecked,
226
+ classify: async (candidates) => (await classifyChecked(candidates)).ignored,
227
+ };
228
+ }
229
+ /** Classify a set of root-relative paths. */
230
+ export async function classifyGitIgnored(relativePaths, root) {
231
+ return createIgnoreClassifier(root ?? workspaceRoot()).classify(relativePaths);
232
+ }
233
+ export async function isGitIgnored(absolutePath) {
234
+ return (await checkGitIgnored(absolutePath)) === 'ignored';
235
+ }
236
+ /** Tri-state single-path check: mutation guards key off `unknown` (F-05). */
237
+ export async function checkGitIgnored(absolutePath) {
238
+ const root = workspaceRoot();
239
+ const relative = workspaceRelativePath(absolutePath);
240
+ if (relative === '.' || relative.startsWith('..'))
241
+ return 'not-ignored'; // root, or outside the workspace: no rules apply
242
+ const isDirectory = await lstatIsDirectory(absolutePath);
243
+ const { ignored, checked } = await createIgnoreClassifier(root).classifyChecked([{ path: relative, isDirectory }]);
244
+ if (!checked)
245
+ return 'unknown';
246
+ return ignored.has(relative) ? 'ignored' : 'not-ignored';
247
+ }
@@ -1,4 +1,4 @@
1
- export type GrepMatchItem = {
1
+ type GrepMatchItem = {
2
2
  file: string;
3
3
  line: number;
4
4
  content: string;
@@ -11,3 +11,4 @@ export type ParsedGrepOutput = {
11
11
  omittedMatches: number;
12
12
  };
13
13
  export declare function parseRipgrepJsonStream(stdout: string, maxMatches: number, contextLines: number, toRelativePath?: (absolute: string) => string): ParsedGrepOutput;
14
+ export {};
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Line-oriented bounded ripgrep runner built on the shared bounded-process
3
3
  * primitive, so spawn/timeout/abort/process-group teardown behavior is
4
- * identical to bash (CR-004). Match counting and early-stop stay here.
4
+ * identical to shell execution (CR-004). Match counting and early-stop stay here.
5
5
  */
6
6
  export declare function runRipgrepBounded(input: {
7
7
  executable: string;
@@ -1,10 +1,10 @@
1
1
  import { StringDecoder } from 'node:string_decoder';
2
2
  import { runBoundedProcess } from '../../core/process/runBoundedProcess.js';
3
- import { GREP_STREAM_BYTES, PROCESS_STDERR_BYTES, TEXT_LINE_BYTES } from '../../core/limits/byteBudgets.js';
3
+ import { GREP_STREAM_BYTES, PROCESS_STDERR_BYTES, TEXT_LINE_BYTES } from '../../core/limits.js';
4
4
  /**
5
5
  * Line-oriented bounded ripgrep runner built on the shared bounded-process
6
6
  * primitive, so spawn/timeout/abort/process-group teardown behavior is
7
- * identical to bash (CR-004). Match counting and early-stop stay here.
7
+ * identical to shell execution (CR-004). Match counting and early-stop stay here.
8
8
  */
9
9
  export async function runRipgrepBounded(input) {
10
10
  const decoder = new StringDecoder('utf8');
@@ -1,5 +1,5 @@
1
- import { COMPACT_COMMAND_CHARS, GREP_MAX_LINE_CHARS, GREP_MAX_OUTPUT_CHARS } from '../../core/limits/textBudgets.js';
2
- export { COMPACT_COMMAND_CHARS, GREP_MAX_OUTPUT_CHARS, GREP_MAX_LINE_CHARS };
1
+ import { COMPACT_COMMAND_CHARS } from '../../core/limits.js';
2
+ export { COMPACT_COMMAND_CHARS };
3
3
  /**
4
4
  * Cap a string to `maxChars` characters, keeping a head + tail and storing the
5
5
  * full text behind a `readToolOutput` handle so nothing is lost.
@@ -15,11 +15,6 @@ export declare function compactStoredOutput(text: string, maxChars?: number): {
15
15
  omittedChars: number;
16
16
  handle: string;
17
17
  };
18
- /** Truncate a single over-long line in place. */
19
- export declare function compactLine(text: string, maxChars?: number): {
20
- text: string;
21
- truncated: boolean;
22
- };
23
18
  /** Render structured grep matches as `file:line:content` lines (context flagged with `-`). */
24
19
  export declare function renderGrepMatches(matches: Array<{
25
20
  file: string;
@@ -1,6 +1,6 @@
1
1
  import { storeToolOutput } from '../../core/agent/toolOutputStore.js';
2
- import { COMPACT_COMMAND_CHARS, GREP_MAX_LINE_CHARS, GREP_MAX_OUTPUT_CHARS } from '../../core/limits/textBudgets.js';
3
- export { COMPACT_COMMAND_CHARS, GREP_MAX_OUTPUT_CHARS, GREP_MAX_LINE_CHARS };
2
+ import { COMPACT_COMMAND_CHARS, GREP_MAX_LINE_CHARS, GREP_MAX_OUTPUT_CHARS } from '../../core/limits.js';
3
+ export { COMPACT_COMMAND_CHARS };
4
4
  /**
5
5
  * Cap a string to `maxChars` characters, keeping a head + tail and storing the
6
6
  * full text behind a `readToolOutput` handle so nothing is lost.
@@ -19,7 +19,7 @@ export function compactStoredOutput(text, maxChars = COMPACT_COMMAND_CHARS) {
19
19
  };
20
20
  }
21
21
  /** Truncate a single over-long line in place. */
22
- export function compactLine(text, maxChars = GREP_MAX_LINE_CHARS) {
22
+ function compactLine(text, maxChars = GREP_MAX_LINE_CHARS) {
23
23
  if (text.length <= maxChars)
24
24
  return { text, truncated: false };
25
25
  return { text: `${text.slice(0, Math.max(0, maxChars - 22))}[line truncated]`, truncated: true };
@@ -67,7 +67,7 @@ export declare const processTool: ({
67
67
  matches?: number;
68
68
  ok: boolean;
69
69
  backgroundId: string;
70
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
70
+ status: "failed" | "killed" | "running" | "exited";
71
71
  outputHandle: string;
72
72
  reasonCode?: undefined;
73
73
  recoverable?: undefined;
@@ -120,7 +120,7 @@ export declare const processTool: ({
120
120
  matches?: number;
121
121
  ok: boolean;
122
122
  backgroundId: string;
123
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
123
+ status: "failed" | "killed" | "running" | "exited";
124
124
  outputHandle: string;
125
125
  reasonCode?: undefined;
126
126
  recoverable?: undefined;
@@ -176,7 +176,7 @@ export declare const processTool: ({
176
176
  matches?: number;
177
177
  ok: boolean;
178
178
  backgroundId: string;
179
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
179
+ status: "failed" | "killed" | "running" | "exited";
180
180
  outputHandle: string;
181
181
  reasonCode?: undefined;
182
182
  recoverable?: undefined;
@@ -253,7 +253,7 @@ export declare const processTool: ({
253
253
  matches?: number;
254
254
  ok: boolean;
255
255
  backgroundId: string;
256
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
256
+ status: "failed" | "killed" | "running" | "exited";
257
257
  outputHandle: string;
258
258
  reasonCode?: undefined;
259
259
  recoverable?: undefined;
@@ -341,7 +341,7 @@ export declare const processTool: ({
341
341
  matches?: number;
342
342
  ok: boolean;
343
343
  backgroundId: string;
344
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
344
+ status: "failed" | "killed" | "running" | "exited";
345
345
  outputHandle: string;
346
346
  reasonCode?: undefined;
347
347
  recoverable?: undefined;
@@ -394,7 +394,7 @@ export declare const processTool: ({
394
394
  matches?: number;
395
395
  ok: boolean;
396
396
  backgroundId: string;
397
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
397
+ status: "failed" | "killed" | "running" | "exited";
398
398
  outputHandle: string;
399
399
  reasonCode?: undefined;
400
400
  recoverable?: undefined;
@@ -450,7 +450,7 @@ export declare const processTool: ({
450
450
  matches?: number;
451
451
  ok: boolean;
452
452
  backgroundId: string;
453
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
453
+ status: "failed" | "killed" | "running" | "exited";
454
454
  outputHandle: string;
455
455
  reasonCode?: undefined;
456
456
  recoverable?: undefined;
@@ -527,7 +527,7 @@ export declare const processTool: ({
527
527
  matches?: number;
528
528
  ok: boolean;
529
529
  backgroundId: string;
530
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
530
+ status: "failed" | "killed" | "running" | "exited";
531
531
  outputHandle: string;
532
532
  reasonCode?: undefined;
533
533
  recoverable?: undefined;
@@ -615,7 +615,7 @@ export declare const processTool: ({
615
615
  matches?: number;
616
616
  ok: boolean;
617
617
  backgroundId: string;
618
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
618
+ status: "failed" | "killed" | "running" | "exited";
619
619
  outputHandle: string;
620
620
  reasonCode?: undefined;
621
621
  recoverable?: undefined;
@@ -668,7 +668,7 @@ export declare const processTool: ({
668
668
  matches?: number;
669
669
  ok: boolean;
670
670
  backgroundId: string;
671
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
671
+ status: "failed" | "killed" | "running" | "exited";
672
672
  outputHandle: string;
673
673
  reasonCode?: undefined;
674
674
  recoverable?: undefined;
@@ -724,7 +724,7 @@ export declare const processTool: ({
724
724
  matches?: number;
725
725
  ok: boolean;
726
726
  backgroundId: string;
727
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
727
+ status: "failed" | "killed" | "running" | "exited";
728
728
  outputHandle: string;
729
729
  reasonCode?: undefined;
730
730
  recoverable?: undefined;
@@ -791,7 +791,7 @@ export declare const processTool: ({
791
791
  matches?: number;
792
792
  ok: boolean;
793
793
  backgroundId: string;
794
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
794
+ status: "failed" | "killed" | "running" | "exited";
795
795
  outputHandle: string;
796
796
  reasonCode?: undefined;
797
797
  recoverable?: undefined;
@@ -879,7 +879,7 @@ export declare const processTool: ({
879
879
  matches?: number;
880
880
  ok: boolean;
881
881
  backgroundId: string;
882
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
882
+ status: "failed" | "killed" | "running" | "exited";
883
883
  outputHandle: string;
884
884
  reasonCode?: undefined;
885
885
  recoverable?: undefined;
@@ -932,7 +932,7 @@ export declare const processTool: ({
932
932
  matches?: number;
933
933
  ok: boolean;
934
934
  backgroundId: string;
935
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
935
+ status: "failed" | "killed" | "running" | "exited";
936
936
  outputHandle: string;
937
937
  reasonCode?: undefined;
938
938
  recoverable?: undefined;
@@ -988,7 +988,7 @@ export declare const processTool: ({
988
988
  matches?: number;
989
989
  ok: boolean;
990
990
  backgroundId: string;
991
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
991
+ status: "failed" | "killed" | "running" | "exited";
992
992
  outputHandle: string;
993
993
  reasonCode?: undefined;
994
994
  recoverable?: undefined;
@@ -1055,7 +1055,7 @@ export declare const processTool: ({
1055
1055
  matches?: number;
1056
1056
  ok: boolean;
1057
1057
  backgroundId: string;
1058
- status: import("../../core/process/backgroundRegistry.js").BackgroundProcessStatus;
1058
+ status: "failed" | "killed" | "running" | "exited";
1059
1059
  outputHandle: string;
1060
1060
  reasonCode?: undefined;
1061
1061
  recoverable?: undefined;
@@ -4,7 +4,7 @@ import { getBackgroundProcess, killBackgroundProcess, listBackgroundProcesses }
4
4
  import { readToolOutput } from '../../core/agent/toolOutputStore.js';
5
5
  import { hazeContext, hazeToolContextSchema } from './toolContext.js';
6
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.',
7
+ description: 'List, read output from, or kill background processes started by shell background=true. Kill servers and watchers when finished.',
8
8
  contextSchema: hazeToolContextSchema,
9
9
  inputSchema: z.object({
10
10
  action: z.enum(['list', 'output', 'kill']),
@@ -0,0 +1,8 @@
1
+ import type { ToolFailureReasonCode } from '../toolResultTypes.js';
2
+ export interface ReadFailureRecovery {
3
+ reasonCode?: ToolFailureReasonCode;
4
+ suggestedNextStep: string;
5
+ suggestedPaths?: string[];
6
+ }
7
+ export declare function assertReadableTextFile(absolutePath: string, filePath: string): Promise<void>;
8
+ 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
+ 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')
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
+ }