@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
@@ -1,32 +1,34 @@
1
1
  import { tool } from 'ai';
2
2
  import { z } from 'zod';
3
- import { classifyBashCommand, isValidationClassification } from '../../core/safety/bashClassifier.js';
3
+ import { classifyShellCommand, isValidationClassification } from '../../core/safety/shellClassifier.js';
4
+ import { detectMissingExecutable, missingExecutableFields } from '../../core/safety/missingExecutable.js';
4
5
  import { parseValidationOutput } from '../../core/validation/outputParser.js';
5
- import { filterBashOutput } from '../../core/bashOutput/registry.js';
6
+ import { filterShellOutput } from '../../core/shellOutput/registry.js';
6
7
  import { storeToolOutput } from '../../core/agent/toolOutputStore.js';
7
8
  import { workspaceRoot } from '../../utils/path.js';
8
9
  import { compactStoredOutput, COMPACT_COMMAND_CHARS } from './outputCap.js';
9
10
  import { hazeContext, hazeToolContextSchema, runDedupedTool } from './toolContext.js';
10
11
  import { runBoundedProcess } from '../../core/process/runBoundedProcess.js';
11
- import { BASH_STREAM_BYTES } from '../../core/limits/byteBudgets.js';
12
- import { SHORT_VALIDATION_CHARS } from '../../core/limits/textBudgets.js';
12
+ import { SHELL_STREAM_BYTES, SHORT_VALIDATION_CHARS } from '../../core/limits.js';
13
13
  import { startBackgroundProcess } from '../../core/process/backgroundRegistry.js';
14
+ import { resolveUserShell, shellInvocation, shellSyntaxGuidance } from '../../core/process/userShell.js';
14
15
  /** Byte-stat metadata only — the raw stream text must never reach the model context (see code-review CR-001). */
15
16
  function streamByteStats(stream) {
16
17
  return { totalBytes: stream.totalBytes, retainedBytes: stream.retainedBytes, omittedBytes: stream.omittedBytes };
17
18
  }
18
- export const bashTool = tool({
19
- description: 'Run workspace tests, builds, validation, or inspection. Risk classification is informational; use file tools for edits.',
19
+ const userShell = resolveUserShell();
20
+ export const shellTool = tool({
21
+ description: 'Run workspace inspection or validation. Set purpose=validation for custom checks that should count as completion evidence; risk classification is informational.',
20
22
  contextSchema: hazeToolContextSchema,
21
23
  inputSchema: z.object({
22
- command: z.string().min(1).describe('Command to execute with bash -lc'),
24
+ command: z.string().min(1).describe(`Command to execute with ${userShell} ${shellInvocation('', userShell).args.join(' ')}. ${shellSyntaxGuidance(userShell)}`.trim()),
25
+ purpose: z.enum(['auto', 'validation']).default('auto').describe('Use validation for an intentional test/check command, including custom assertion scripts; pass/fail still comes from the real process result.'),
23
26
  timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
24
- allowMutation: z.boolean().default(false).describe('Deprecated compatibility flag. Commands run without confirmation; retained for compatibility.'),
25
27
  background: z.boolean().default(false).describe('Start a registered long-running process and return immediately. Use process to list, inspect output, or kill it.'),
26
28
  }),
27
- execute: async ({ command, timeoutSeconds, background }, context) => runDedupedTool('bash', { command, timeoutSeconds, background }, context, async () => {
29
+ execute: async ({ command, purpose, timeoutSeconds, background }, context) => runDedupedTool('shell', { command, purpose, timeoutSeconds, background }, context, async () => {
28
30
  const cwd = workspaceRoot();
29
- const classification = classifyBashCommand(command);
31
+ const classification = classifyShellCommand(command);
30
32
  if (background) {
31
33
  if (hazeContext(context)?.isSubagent) {
32
34
  return { ok: false, command, reasonCode: 'background_not_allowed', recoverable: false, error: 'Background processes are available only to the main haze turn, not fleet workers.', suggestedNextStep: 'Run the server from the main conversation.' };
@@ -44,21 +46,25 @@ export const bashTool = tool({
44
46
  }
45
47
  const timeoutMs = (timeoutSeconds ?? 60) * 1000;
46
48
  const startedAt = Date.now();
47
- const processResult = await runBoundedProcess({ command: 'bash', args: ['-lc', command], cwd, timeoutMs, signal: context.abortSignal, maxStdoutBytes: BASH_STREAM_BYTES, maxStderrBytes: BASH_STREAM_BYTES });
49
+ const processResult = await runBoundedProcess({ ...shellInvocation(command), cwd, timeoutMs, signal: context.abortSignal, maxStdoutBytes: SHELL_STREAM_BYTES, maxStderrBytes: SHELL_STREAM_BYTES });
48
50
  const { code, timedOut } = processResult;
49
51
  const stdout = processResult.stdout.text;
50
52
  const stderr = processResult.stderr.text;
51
- const validationSummary = isValidationClassification(classification)
53
+ const validationSummary = purpose === 'validation' || isValidationClassification(classification)
52
54
  ? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: processResult.stdout.omittedBytes > 0, stderrTruncated: processResult.stderr.omittedBytes > 0, classification })
53
55
  : undefined;
54
56
  const validationPassed = validationSummary?.status === 'passed';
55
- const output = filterBashOutput({ command, code, stdout, stderr, timedOut, classification, validationSummary, storeRawOutput: storeToolOutput, fallbackCompact: compactStoredOutput, compactMaxChars: validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS });
57
+ const output = filterShellOutput({ command, code, stdout, stderr, timedOut, classification, validationSummary, storeRawOutput: storeToolOutput, fallbackCompact: compactStoredOutput, compactMaxChars: validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS });
58
+ // Generic, dependency-agnostic diagnostic for a missing executable. Only the
59
+ // executable name and a generic next step are exposed (never raw stderr).
60
+ const missing = code !== 0 && !processResult.aborted ? detectMissingExecutable({ command, code, stderr }) : undefined;
56
61
  return {
57
62
  ok: code === 0 && !timedOut && !processResult.aborted && !processResult.error,
58
- code, command, cwd, classification, durationMs: Date.now() - startedAt, timedOut,
63
+ code, command, purpose, cwd, classification, durationMs: Date.now() - startedAt, timedOut,
59
64
  aborted: processResult.aborted, signal: processResult.signal, forcedTermination: processResult.forced,
60
65
  stdout: output.stdout, stderr: output.stderr, validationSummary,
61
66
  stdoutBytes: streamByteStats(processResult.stdout), stderrBytes: streamByteStats(processResult.stderr),
67
+ ...(missing ? { ...missingExecutableFields(missing), missingExecutableStep: missing.suggestedNextStep } : {}),
62
68
  ...(processResult.error ? { error: processResult.error } : {}),
63
69
  };
64
70
  }),
@@ -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,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', 'process', 'fetch']);
58
+ const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'shell', 'process', 'fetch']);
31
59
  return Object.fromEntries(Object.keys(tools).filter(name => hazeToolNames.has(name)).map(name => [name, context]));
32
60
  }
33
61
  /**
@@ -86,15 +114,15 @@ export function scopedContextMutationStop(toolName, filePath, files) {
86
114
  };
87
115
  }
88
116
  function isMutatingTool(toolName) {
89
- // Bash is conservatively workspace-mutation-capable. Classification remains
117
+ // Shell execution is conservatively workspace-mutation-capable. Classification remains
90
118
  // informational and is not a sandbox boundary.
91
- return ['editFile', 'replaceLines', 'writeFile', 'bash'].includes(toolName);
119
+ return ['editFile', 'replaceLines', 'writeFile', 'shell'].includes(toolName);
92
120
  }
93
121
  function isReadOnlyFileTool(toolName) {
94
122
  return ['listFiles', 'readFile', 'grep'].includes(toolName);
95
123
  }
96
124
  // Read-only tools that participate in completed-call deduplication within a
97
- // turn (no side effects). Bash is deliberately excluded: commands can observe
125
+ // turn (no side effects). Shell is deliberately excluded: commands can observe
98
126
  // external state changes between identical calls (CR-007).
99
127
  function isDeduplicableReadOnlyTool(toolName) {
100
128
  return isReadOnlyFileTool(toolName) || toolName === '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,14 +181,14 @@ 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) {
160
189
  // A worker supplies its whole-run owner so nested tool calls are
161
190
  // reentrant. Main-turn calls intentionally receive a fresh owner per
162
- // mutation, serializing concurrent edit/bash calls.
191
+ // mutation, serializing concurrent edit/shell calls.
163
192
  const owner = ctx.mutationOwner ?? ctx.mutationPolicy.createOwner();
164
193
  releaseMutation = await ctx.mutationPolicy.acquire(owner, context.abortSignal);
165
194
  }
@@ -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
  }
@@ -1,5 +1,4 @@
1
1
  import { type ToolExecutionContext } from './toolContext.js';
2
- export declare function prepareWorkspaceExisting(filePath: string): Promise<string>;
3
2
  /**
4
3
  * Resolve a read path and confine it to the workspace — unless the user
5
4
  * explicitly mentioned it (or a parent directory) in the prompt this turn.
@@ -4,11 +4,6 @@ import { assertRealPathInsideWorkspace, assertWritablePathInsideWorkspace, resol
4
4
  import { isPathBlessed } from '../../core/attachments/readBlessings.js';
5
5
  import { assertNotIgnored } from './fileToolShared.js';
6
6
  import { discoverScopedContext, hazeContext, scopedContextMutationStop } from './toolContext.js';
7
- export async function prepareWorkspaceExisting(filePath) {
8
- const absolutePath = resolveWorkspacePath(filePath);
9
- await assertRealPathInsideWorkspace(absolutePath, filePath);
10
- return absolutePath;
11
- }
12
7
  /**
13
8
  * Resolve a read path and confine it to the workspace — unless the user
14
9
  * explicitly mentioned it (or a parent directory) in the prompt this turn.
@@ -26,7 +21,7 @@ export async function prepareWorkspaceRead(filePath, allowIgnored, context) {
26
21
  return absolutePath;
27
22
  }
28
23
  const absolutePath = resolveWorkspacePath(filePath);
29
- await assertNotIgnored(absolutePath, filePath, allowIgnored);
24
+ await assertNotIgnored(absolutePath, filePath, allowIgnored, { operation: 'read' });
30
25
  await assertRealPathInsideWorkspace(absolutePath, filePath);
31
26
  return absolutePath;
32
27
  }
@@ -30,7 +30,7 @@ export interface FetchOptions {
30
30
  * caller). When `pinnedIp` is undefined (literal-IP URL), the transport falls
31
31
  * back to the global fetch — no DNS-rebinding surface exists for a literal IP.
32
32
  */
33
- export type PinnedFetcher = (url: URL, pinnedIp: string | undefined, init: RequestInit) => Promise<Response>;
33
+ type PinnedFetcher = (url: URL, pinnedIp: string | undefined, init: RequestInit) => Promise<Response>;
34
34
  export interface FetchResult {
35
35
  url: string;
36
36
  status: number;
@@ -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.
@@ -1,31 +1,17 @@
1
1
  import http from 'node:http';
2
2
  import https from 'node:https';
3
3
  import { Readable } from 'node:stream';
4
- import { readFileSync } from 'node:fs';
5
- import { fileURLToPath } from 'node:url';
6
- import { dirname, join } from 'node:path';
7
4
  import { validateUrl } from '../core/safety/urlGuard.js';
5
+ import { truncateUtf8AtBytes } from '../utils/utf8.js';
6
+ import { readPackageVersion } from '../utils/version.js';
8
7
  const DEFAULT_TIMEOUT_MS = 30_000;
9
8
  const DEFAULT_MAX_BYTES = 2_000_000;
10
9
  const DEFAULT_MAX_REDIRECTS = 5;
11
- // Derive the version from package.json (as cli/index.ts does) so the user
12
- // agent never goes stale; fall back to an unversioned agent if the read fails
13
- // (CR-017).
14
- let cachedUserAgent;
10
+ // Derive the version from package.json so the user agent never goes stale;
11
+ // fall back to an unversioned agent if package metadata is unavailable.
15
12
  function userAgent() {
16
- if (cachedUserAgent)
17
- return cachedUserAgent;
18
- let version;
19
- try {
20
- const here = dirname(fileURLToPath(import.meta.url));
21
- const pkg = JSON.parse(readFileSync(join(here, '..', '..', 'package.json'), 'utf8'));
22
- version = pkg.version;
23
- }
24
- catch {
25
- version = undefined;
26
- }
27
- cachedUserAgent = version ? `haze/${version} (+https://github.com/DenizOkcu/haze)` : 'haze (+https://github.com/DenizOkcu/haze)';
28
- return cachedUserAgent;
13
+ const version = readPackageVersion();
14
+ return version ? `haze/${version} (+https://github.com/DenizOkcu/haze)` : 'haze (+https://github.com/DenizOkcu/haze)';
29
15
  }
30
16
  /** Error thrown when a URL is rejected by the SSRF guard. */
31
17
  export class BlockedUrlError extends Error {
@@ -92,28 +78,12 @@ function classifyContentType(contentType) {
92
78
  return 'html';
93
79
  return 'text';
94
80
  }
95
- function decodeValidUtf8Prefix(buffer) {
96
- for (let end = buffer.byteLength; end >= 0; end--) {
97
- try {
98
- return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, end));
99
- }
100
- catch {
101
- // Back up until we land on a UTF-8 character boundary.
102
- }
103
- }
104
- return '';
105
- }
106
- function truncateUtf8Bytes(text, maxBytes) {
107
- const buffer = Buffer.from(text, 'utf8');
108
- if (buffer.byteLength <= maxBytes)
109
- return { text, bytes: buffer.byteLength, truncated: false };
110
- return { text: decodeValidUtf8Prefix(buffer.subarray(0, maxBytes)), bytes: maxBytes, truncated: true };
111
- }
112
81
  async function readBodyCapped(response, maxBytes, abortController) {
113
82
  const body = response.body;
114
- if (body == null || typeof body.getReader !== 'function') {
115
- // No streamable body; read as text once and cap.
116
- return truncateUtf8Bytes(await response.text(), maxBytes);
83
+ if (body == null)
84
+ return { text: '', bytes: 0, truncated: false };
85
+ if (typeof body.getReader !== 'function') {
86
+ throw new Error('Response body is not streamable; refusing unbounded read');
117
87
  }
118
88
  const reader = body.getReader();
119
89
  const chunks = [];
@@ -153,25 +123,8 @@ async function readBodyCapped(response, maxBytes, abortController) {
153
123
  if (truncated && !abortController.signal.aborted)
154
124
  abortController.abort();
155
125
  }
156
- return { text: decodeValidUtf8Prefix(Buffer.concat(chunks)), bytes: Math.min(received, maxBytes), truncated };
126
+ return { text: truncateUtf8AtBytes(Buffer.concat(chunks), maxBytes).text, bytes: Math.min(received, maxBytes), truncated };
157
127
  }
158
- /**
159
- * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
160
- *
161
- * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
162
- * verified every address is public, but the global `fetch` would re-resolve the
163
- * hostname at connect time — an attacker-controlled DNS server can return a
164
- * public IP for the validation lookup and a private/internal IP for the connect
165
- * lookup. By connecting directly to the already-validated IP (`hostname:
166
- * pinnedIp`) while keeping the original `Host` header and TLS `servername`
167
- * (`url.hostname`), the connection target is fixed to what we validated, with no
168
- * second DNS lookup. TLS certificate verification still runs against the original
169
- * hostname via `servername`, so pinning does not weaken identity checks.
170
- *
171
- * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
172
- * they fall through to the global `fetch` — which also keeps the test mocks that
173
- * stub `globalThis.fetch` working for that path.
174
- */
175
128
  /**
176
129
  * Coerce a RequestInit headers value into a plain string record. Keeps the
177
130
  * transport defensive against `Headers`/tuple/array inputs instead of blindly
@@ -197,9 +150,45 @@ function normalizeHeaders(input) {
197
150
  }
198
151
  return { ...input };
199
152
  }
153
+ function normalizeResponseHeaders(input) {
154
+ const headers = {};
155
+ for (const [key, value] of Object.entries(input)) {
156
+ if (value === undefined)
157
+ continue;
158
+ // Cookie fidelity is out of scope for this read-only transport; all array
159
+ // headers are represented deterministically as comma-separated values.
160
+ headers[key] = Array.isArray(value) ? value.join(', ') : value;
161
+ }
162
+ return headers;
163
+ }
164
+ /**
165
+ * Perform an HTTP(S) request with the TCP connection pinned to `pinnedIp`.
166
+ *
167
+ * This closes the DNS-rebinding TOCTOU: `validateUrl` resolved the hostname and
168
+ * verified every address is public, but the global `fetch` would re-resolve the
169
+ * hostname at connect time — an attacker-controlled DNS server can return a
170
+ * public IP for the validation lookup and a private/internal IP for the connect
171
+ * lookup. By connecting directly to the already-validated IP (`hostname:
172
+ * pinnedIp`) while keeping the original `Host` header and TLS `servername`
173
+ * (`url.hostname`), the connection target is fixed to what we validated, with no
174
+ * second DNS lookup. TLS certificate verification still runs against the original
175
+ * hostname via `servername`, so pinning does not weaken identity checks.
176
+ *
177
+ * Literal-IP URLs carry no DNS-rebinding surface (`pinnedIp` is undefined), so
178
+ * they fall through to the global `fetch` — which also keeps the test mocks that
179
+ * stub `globalThis.fetch` working for that path.
180
+ */
200
181
  export async function pinnedFetch(url, pinnedIp, init) {
182
+ const method = (init.method ?? 'GET').toUpperCase();
183
+ if (method !== 'GET' && method !== 'HEAD') {
184
+ throw new Error('Pinned fetch supports only GET and HEAD requests');
185
+ }
186
+ if (init.body != null)
187
+ throw new Error('Pinned fetch does not support request bodies');
188
+ if (url.username || url.password)
189
+ throw new Error('Pinned fetch does not support URL credentials');
201
190
  if (!pinnedIp)
202
- return globalThis.fetch(url, init);
191
+ return globalThis.fetch(url, { ...init, method });
203
192
  const isTls = url.protocol === 'https:';
204
193
  const port = url.port ? Number(url.port) : (isTls ? 443 : 80);
205
194
  const path = url.pathname + url.search;
@@ -210,7 +199,7 @@ export async function pinnedFetch(url, pinnedIp, init) {
210
199
  const lib = isTls ? https : http;
211
200
  return new Promise((resolve, reject) => {
212
201
  const req = lib.request({
213
- method: init.method ?? 'GET',
202
+ method,
214
203
  hostname: pinnedIp,
215
204
  port,
216
205
  path,
@@ -222,7 +211,7 @@ export async function pinnedFetch(url, pinnedIp, init) {
222
211
  resolve(new Response(body, {
223
212
  status: res.statusCode ?? 200,
224
213
  statusText: res.statusMessage ?? '',
225
- headers: res.headers,
214
+ headers: normalizeResponseHeaders(res.headers),
226
215
  }));
227
216
  });
228
217
  req.on('error', reject);
@@ -251,30 +240,22 @@ export async function fetchUrlContent(input, opts) {
251
240
  // lookup in between (that gap was the rebinding window).
252
241
  let currentPinnedIp = initial.resolvedAddresses?.[0];
253
242
  let response;
243
+ let responseAbortController;
254
244
  const visited = [];
245
+ const totalTimeoutSignal = AbortSignal.timeout(timeoutMs * 2);
255
246
  for (let hop = 0; hop <= maxRedirects; hop++) {
256
247
  const timeoutSignal = AbortSignal.timeout(timeoutMs);
257
248
  const abortController = new AbortController();
258
- const onAbort = () => abortController.abort();
259
- if (opts?.signal) {
260
- if (opts.signal.aborted)
261
- abortController.abort();
262
- else
263
- opts.signal.addEventListener('abort', onAbort, { once: true });
264
- }
265
- const combined = AbortSignal.any([timeoutSignal, abortController.signal]);
266
- try {
267
- response = await fetcher(currentUrl, currentPinnedIp, {
268
- redirect: 'manual',
269
- signal: combined,
270
- headers: { accept: 'text/html,application/xhtml+xml,application/json,text/plain;q=0.5,*/*;q=0.1', 'user-agent': userAgent() },
271
- });
272
- }
273
- finally {
274
- // Listener cleanup only; fetch errors propagate unchanged (CR-017).
275
- if (opts?.signal)
276
- opts.signal.removeEventListener('abort', onAbort);
277
- }
249
+ const signals = [totalTimeoutSignal, timeoutSignal, abortController.signal];
250
+ if (opts?.signal)
251
+ signals.push(opts.signal);
252
+ const combined = AbortSignal.any(signals);
253
+ response = await fetcher(currentUrl, currentPinnedIp, {
254
+ redirect: 'manual',
255
+ signal: combined,
256
+ headers: { accept: 'text/html,application/xhtml+xml,application/json,text/plain;q=0.5,*/*;q=0.1', 'user-agent': userAgent() },
257
+ });
258
+ responseAbortController = abortController;
278
259
  // Follow redirects ourselves, re-validating each Location (closes the
279
260
  // redirect-to-internal-IP hole).
280
261
  const status = response.status;
@@ -282,6 +263,7 @@ export async function fetchUrlContent(input, opts) {
282
263
  const location = response.headers.get('location');
283
264
  if (!location)
284
265
  break;
266
+ await response.body?.cancel().catch(() => undefined);
285
267
  if (hop >= maxRedirects) {
286
268
  throw new Error(`Too many redirects (>${maxRedirects}) fetching ${input}`);
287
269
  }
@@ -314,22 +296,7 @@ export async function fetchUrlContent(input, opts) {
314
296
  // validated and connection-pinned at fetch time. Re-resolving the final URL
315
297
  // here would only reopen a rebinding race against a connection that already
316
298
  // used a safe, pinned IP.
317
- const abortController = new AbortController();
318
- const onAbort = () => abortController.abort();
319
- if (opts?.signal) {
320
- if (opts.signal.aborted)
321
- abortController.abort();
322
- else
323
- opts.signal.addEventListener('abort', onAbort, { once: true });
324
- }
325
- let bodyResult;
326
- try {
327
- bodyResult = await readBodyCapped(response, maxBytes, abortController);
328
- }
329
- finally {
330
- if (opts?.signal)
331
- opts.signal.removeEventListener('abort', onAbort);
332
- }
299
+ const bodyResult = await readBodyCapped(response, maxBytes, responseAbortController ?? new AbortController());
333
300
  const contentType = response.headers.get('content-type') ?? 'application/octet-stream';
334
301
  const kind = classifyContentType(contentType);
335
302
  let content = bodyResult.text;
@@ -1,12 +1,2 @@
1
- import type { LoadedSkill, SkillFrontmatter, SkillSource } from './types.js';
2
- declare function parseSkillMarkdown(content: string): {
3
- frontmatter: SkillFrontmatter;
4
- body: string;
5
- };
6
- declare function referencedPaths(body: string): string[];
1
+ import type { LoadedSkill, SkillSource } from './types.js';
7
2
  export declare function loadSkill(dir: string, source?: SkillSource): Promise<LoadedSkill | null>;
8
- export declare const internals: {
9
- parseSkillMarkdown: typeof parseSkillMarkdown;
10
- referencedPaths: typeof referencedPaths;
11
- };
12
- export {};
@@ -2,7 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import YAML from 'yaml';
4
4
  import { assertRealPathInsideRoot } from '../utils/path.js';
5
- import { SKILL_MARKDOWN_BYTES } from '../core/limits/byteBudgets.js';
5
+ import { SKILL_MARKDOWN_BYTES } from '../core/limits.js';
6
6
  import { readUtf8Prefix } from '../core/io/boundedRead.js';
7
7
  const MAX_REFERENCE_BYTES = 50_000;
8
8
  const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
@@ -77,4 +77,3 @@ export async function loadSkill(dir, source = 'global') {
77
77
  const references = await Promise.all(referencedPaths(body).map(ref => loadReference(dir, ref)));
78
78
  return { dir, path: realSkillPath, name: frontmatter.name, description: frontmatter.description, body, references, source };
79
79
  }
80
- export const internals = { parseSkillMarkdown, referencedPaths };
@@ -17,7 +17,7 @@ export interface LoadedSkill {
17
17
  references: LoadedSkillReference[];
18
18
  source: SkillSource;
19
19
  }
20
- export interface SkillRegistryError {
20
+ interface SkillRegistryError {
21
21
  directory: string;
22
22
  message: string;
23
23
  source?: SkillSource;
@@ -29,3 +29,4 @@ export interface SkillRegistry {
29
29
  candidates?: LoadedSkill[];
30
30
  errors: SkillRegistryError[];
31
31
  }
32
+ export {};
@@ -0,0 +1,4 @@
1
+ /** Map a source path to a cli-highlight language when its extension is known. */
2
+ export declare function languageForPath(filePath: string): string | undefined;
3
+ /** Highlight, clip, and pad one source line to an exact terminal width. */
4
+ export declare function highlightedCodeLine(code: string, width: number, language?: string): string;