@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,27 @@
1
+ /** True when a tool result is the structured "deadline exceeded" placeholder. */
2
+ export declare function isToolDeadlineExceeded(output: unknown): boolean;
3
+ /**
4
+ * Run an underlying tool `execute` under a deadline. The wrapper resolves
5
+ * promptly when the deadline (or an optional parent abort signal) fires, even
6
+ * if the underlying work ignores cancellation. The still-pending work is
7
+ * quarantined so its eventual settlement cannot produce an unhandled rejection
8
+ * or mutate caller state (RH-004).
9
+ *
10
+ * - Normal completion → resolves with the underlying value.
11
+ * - Underlying rejection → rejects with that error (let the SDK classify it).
12
+ * - Deadline / parent abort → resolves with a structured bounded failure.
13
+ */
14
+ export declare function withToolDeadline(execute: () => Promise<unknown>, timeoutMs: number, signal?: AbortSignal): Promise<unknown>;
15
+ /**
16
+ * Create a clearable absolute deadline that fires `onTimeout` once after
17
+ * `timeoutMs`, unless `clear()` is called first. An already-aborted parent
18
+ * signal fires immediately. Used for the absolute main-turn bound (RH-004).
19
+ */
20
+ export interface AbsoluteDeadline {
21
+ clear: () => void;
22
+ }
23
+ export declare function createAbsoluteDeadline(input: {
24
+ timeoutMs: number;
25
+ signal?: AbortSignal;
26
+ onTimeout: () => void;
27
+ }): AbsoluteDeadline;
@@ -0,0 +1,74 @@
1
+ const TOOL_DEADLINE_EXCEEDED = '__hazeToolDeadlineExceeded';
2
+ /** True when a tool result is the structured "deadline exceeded" placeholder. */
3
+ export function isToolDeadlineExceeded(output) {
4
+ return typeof output === 'object' && output !== null && TOOL_DEADLINE_EXCEEDED in output;
5
+ }
6
+ /**
7
+ * Run an underlying tool `execute` under a deadline. The wrapper resolves
8
+ * promptly when the deadline (or an optional parent abort signal) fires, even
9
+ * if the underlying work ignores cancellation. The still-pending work is
10
+ * quarantined so its eventual settlement cannot produce an unhandled rejection
11
+ * or mutate caller state (RH-004).
12
+ *
13
+ * - Normal completion → resolves with the underlying value.
14
+ * - Underlying rejection → rejects with that error (let the SDK classify it).
15
+ * - Deadline / parent abort → resolves with a structured bounded failure.
16
+ */
17
+ export function withToolDeadline(execute, timeoutMs, signal) {
18
+ return new Promise((resolve, reject) => {
19
+ let settled = false;
20
+ const handle = { timer: undefined };
21
+ const settle = (action) => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ if (handle.timer)
26
+ clearTimeout(handle.timer);
27
+ action();
28
+ };
29
+ const quarantineLate = () => {
30
+ // Swallow the eventual resolution/rejection of an abort-ignoring tool so
31
+ // it cannot surface as an unhandled rejection after the wrapper returned.
32
+ work.catch(() => undefined);
33
+ };
34
+ const fire = (message) => settle(() => {
35
+ quarantineLate();
36
+ resolve({ ok: false, [TOOL_DEADLINE_EXCEEDED]: true, error: message });
37
+ });
38
+ const work = execute();
39
+ handle.timer = setTimeout(() => fire(`Tool execution exceeded the ${timeoutMs}ms deadline.`), timeoutMs);
40
+ if (signal) {
41
+ if (signal.aborted)
42
+ return fire('Tool execution was aborted.');
43
+ signal.addEventListener('abort', () => fire('Tool execution was aborted.'), { once: true });
44
+ }
45
+ work.then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
46
+ });
47
+ }
48
+ export function createAbsoluteDeadline(input) {
49
+ const { timeoutMs, signal, onTimeout } = input;
50
+ let fired = false;
51
+ let timer;
52
+ const fire = () => {
53
+ if (fired)
54
+ return;
55
+ fired = true;
56
+ if (timer)
57
+ clearTimeout(timer);
58
+ onTimeout();
59
+ };
60
+ timer = setTimeout(fire, timeoutMs);
61
+ if (signal) {
62
+ if (signal.aborted)
63
+ fire();
64
+ else
65
+ signal.addEventListener('abort', fire, { once: true });
66
+ }
67
+ return {
68
+ clear: () => {
69
+ if (timer)
70
+ clearTimeout(timer);
71
+ timer = undefined;
72
+ },
73
+ };
74
+ }
@@ -1,7 +1,7 @@
1
1
  import { createReadStream } from 'node:fs';
2
2
  import fs from 'node:fs/promises';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
- import { TEXT_LINE_BYTES } from '../limits/byteBudgets.js';
4
+ import { TEXT_LINE_BYTES } from '../limits.js';
5
5
  async function* iterateBoundedUtf8LinesFrom(file, maxLineBytes, startByte, previousLineNumber) {
6
6
  const input = createReadStream(file, startByte > 0 ? { start: startByte } : undefined);
7
7
  let lineNumber = previousLineNumber;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Centralized output/resource limits.
3
+ *
4
+ * Byte budgets below bound work performed (process output, file reads, JSONL
5
+ * lines, LSP frames/headers/buffers, stored tool-output handles, skill files,
6
+ * exact-mutation size); the model-facing character caps bound returned/persisted
7
+ * text so callers cite a named constant instead of a magic number (CR-014).
8
+ *
9
+ * Changing a value changes availability/memory behavior; mention user-visible
10
+ * changes in `CHANGELOG.md` and docs.
11
+ */
12
+ export declare const SHELL_STREAM_BYTES: number;
13
+ export declare const BACKGROUND_PROCESS_OUTPUT_BYTES: number;
14
+ export declare const GREP_STREAM_BYTES: number;
15
+ export declare const PROCESS_STDERR_BYTES: number;
16
+ export declare const TOOL_OUTPUT_ENTRY_BYTES: number;
17
+ export declare const TOOL_OUTPUT_TOTAL_BYTES: number;
18
+ export declare const LSP_DOCUMENT_BYTES: number;
19
+ export declare const LSP_HEADER_BYTES: number;
20
+ export declare const LSP_FRAME_BYTES: number;
21
+ export declare const LSP_BUFFER_BYTES: number;
22
+ export declare const SKILL_MARKDOWN_BYTES: number;
23
+ export declare const EXACT_MUTATION_BYTES: number;
24
+ export declare const JSONL_LINE_BYTES: number;
25
+ export declare const TEXT_LINE_BYTES: number;
26
+ /** Maximum byte size of a prompt read from piped stdin. */
27
+ export declare const STDIN_PROMPT_BYTES: number;
28
+ /** Maximum size of one user-attached image (checked before the read). */
29
+ export declare const IMAGE_ATTACHMENT_BYTES: number;
30
+ /** Maximum number of image attachments in a single user message. */
31
+ export declare const IMAGE_ATTACHMENTS_PER_MESSAGE = 4;
32
+ /** Per-page cap for numbered file content returned by readFile/listFiles-style tools. */
33
+ export declare const MAX_OUTPUT_CHARS = 50000;
34
+ /** Default compact cap for stored shell output shown to the model. */
35
+ export declare const COMPACT_COMMAND_CHARS = 12000;
36
+ /** Compact cap for passing-validation summaries. */
37
+ export declare const SHORT_VALIDATION_CHARS = 2000;
38
+ /** Total rendered size cap for grep match output. */
39
+ export declare const GREP_MAX_OUTPUT_CHARS = 30000;
40
+ /** Per-line cap for rendered grep matches. */
41
+ export declare const GREP_MAX_LINE_CHARS = 500;
42
+ /** Bounded excerpt of older messages kept by /compact-style compaction. */
43
+ export declare const COMPACTION_OLDER_CHARS = 8000;
44
+ /** Bounded older-transcript budget sent to the model for LLM-summarized /compact (F-09). */
45
+ export declare const COMPACTION_LLM_TRANSCRIPT_CHARS = 60000;
46
+ /** Session JSONL values up to this size stay inline; larger ones become previews. */
47
+ export declare const SESSION_INLINE_VALUE_BYTES: number;
48
+ /** Preview length for slimmed session values. */
49
+ export declare const SESSION_PREVIEW_CHARS: number;
50
+ /** Strings longer than this are truncated in session snapshots. */
51
+ export declare const SESSION_LARGE_STRING_CHARS: number;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Centralized output/resource limits.
3
+ *
4
+ * Byte budgets below bound work performed (process output, file reads, JSONL
5
+ * lines, LSP frames/headers/buffers, stored tool-output handles, skill files,
6
+ * exact-mutation size); the model-facing character caps bound returned/persisted
7
+ * text so callers cite a named constant instead of a magic number (CR-014).
8
+ *
9
+ * Changing a value changes availability/memory behavior; mention user-visible
10
+ * changes in `CHANGELOG.md` and docs.
11
+ */
12
+ export const SHELL_STREAM_BYTES = 2 * 1024 * 1024;
13
+ export const BACKGROUND_PROCESS_OUTPUT_BYTES = 256 * 1024;
14
+ export const GREP_STREAM_BYTES = 8 * 1024 * 1024;
15
+ export const PROCESS_STDERR_BYTES = 64 * 1024;
16
+ export const TOOL_OUTPUT_ENTRY_BYTES = 2 * 1024 * 1024;
17
+ export const TOOL_OUTPUT_TOTAL_BYTES = 16 * 1024 * 1024;
18
+ export const LSP_DOCUMENT_BYTES = 2 * 1024 * 1024;
19
+ export const LSP_HEADER_BYTES = 16 * 1024;
20
+ export const LSP_FRAME_BYTES = 8 * 1024 * 1024;
21
+ export const LSP_BUFFER_BYTES = LSP_FRAME_BYTES + LSP_HEADER_BYTES;
22
+ export const SKILL_MARKDOWN_BYTES = 256 * 1024;
23
+ export const EXACT_MUTATION_BYTES = 8 * 1024 * 1024;
24
+ export const JSONL_LINE_BYTES = 4 * 1024 * 1024;
25
+ export const TEXT_LINE_BYTES = 1024 * 1024;
26
+ /** Maximum byte size of a prompt read from piped stdin. */
27
+ export const STDIN_PROMPT_BYTES = 256 * 1024;
28
+ /** Maximum size of one user-attached image (checked before the read). */
29
+ export const IMAGE_ATTACHMENT_BYTES = 5 * 1024 * 1024;
30
+ /** Maximum number of image attachments in a single user message. */
31
+ export const IMAGE_ATTACHMENTS_PER_MESSAGE = 4;
32
+ /** Per-page cap for numbered file content returned by readFile/listFiles-style tools. */
33
+ export const MAX_OUTPUT_CHARS = 50_000;
34
+ /** Default compact cap for stored shell output shown to the model. */
35
+ export const COMPACT_COMMAND_CHARS = 12_000;
36
+ /** Compact cap for passing-validation summaries. */
37
+ export const SHORT_VALIDATION_CHARS = 2_000;
38
+ /** Total rendered size cap for grep match output. */
39
+ export const GREP_MAX_OUTPUT_CHARS = 30_000;
40
+ /** Per-line cap for rendered grep matches. */
41
+ export const GREP_MAX_LINE_CHARS = 500;
42
+ /** Bounded excerpt of older messages kept by /compact-style compaction. */
43
+ export const COMPACTION_OLDER_CHARS = 8_000;
44
+ /** Bounded older-transcript budget sent to the model for LLM-summarized /compact (F-09). */
45
+ export const COMPACTION_LLM_TRANSCRIPT_CHARS = 60_000;
46
+ /** Session JSONL values up to this size stay inline; larger ones become previews. */
47
+ export const SESSION_INLINE_VALUE_BYTES = 32 * 1024;
48
+ /** Preview length for slimmed session values. */
49
+ export const SESSION_PREVIEW_CHARS = 4 * 1024;
50
+ /** Strings longer than this are truncated in session snapshots. */
51
+ export const SESSION_LARGE_STRING_CHARS = 8 * 1024;
@@ -3,12 +3,15 @@ import fs from 'fs-extra';
3
3
  import { HAZE_DIR } from '../../config/paths.js';
4
4
  import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
5
5
  import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
6
- import { JSONL_LINE_BYTES } from '../limits/byteBudgets.js';
6
+ import { JSONL_LINE_BYTES } from '../limits.js';
7
7
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
8
8
  const LOGS_DIR = path.join(HAZE_DIR, 'logs');
9
9
  function logFileId(now = new Date()) {
10
10
  return now.toISOString().replace(/[:.]/g, '-');
11
11
  }
12
+ function isSafeLogId(id) {
13
+ return id.length > 0 && path.basename(id) === id && path.win32.basename(id) === id;
14
+ }
12
15
  function logFilePath(id) {
13
16
  return path.join(LOGS_DIR, `${id}.jsonl`);
14
17
  }
@@ -52,6 +55,8 @@ export async function listLogs() {
52
55
  return logs.sort((a, b) => b.modified.localeCompare(a.modified));
53
56
  }
54
57
  export async function readLogEntries(id) {
58
+ if (!isSafeLogId(id))
59
+ return [];
55
60
  const file = logFilePath(id);
56
61
  const entries = [];
57
62
  try {
@@ -71,6 +76,8 @@ export async function readLogEntries(id) {
71
76
  return entries;
72
77
  }
73
78
  export async function summarizeLog(id) {
79
+ if (!isSafeLogId(id))
80
+ return undefined;
74
81
  const file = logFilePath(id);
75
82
  const summary = { entries: 0, typeCounts: {}, totalInput: 0, totalOutput: 0, toolCallCounts: {} };
76
83
  try {
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Serializes async writes so appends land in arrival order, even when an earlier
3
+ * write rejects. Two contract points worth knowing:
4
+ * - The per-`append` promise rejects with the specific error of that write,
5
+ * so awaiting callers see their own failure. Subsequent appends still
6
+ * chain (the queue keeps draining) so a single bad write does not wedge
7
+ * the writer or reject unrelated callers.
8
+ * - `error()` and `flush()` surface the *first* captured error and never
9
+ * clear it; later successful writes do not reset the sticky state.
10
+ */
1
11
  export declare class OrderedFileWriter<T> {
2
12
  private readonly write;
3
13
  private tail;
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Serializes async writes so appends land in arrival order, even when an earlier
3
+ * write rejects. Two contract points worth knowing:
4
+ * - The per-`append` promise rejects with the specific error of that write,
5
+ * so awaiting callers see their own failure. Subsequent appends still
6
+ * chain (the queue keeps draining) so a single bad write does not wedge
7
+ * the writer or reject unrelated callers.
8
+ * - `error()` and `flush()` surface the *first* captured error and never
9
+ * clear it; later successful writes do not reset the sticky state.
10
+ */
1
11
  export class OrderedFileWriter {
2
12
  write;
3
13
  tail = Promise.resolve();
@@ -9,10 +19,14 @@ export class OrderedFileWriter {
9
19
  append(value) {
10
20
  if (this.closed)
11
21
  return Promise.reject(new Error('Writer is closed.'));
12
- this.tail = this.tail.then(() => this.write(value)).catch(error => {
22
+ // per-call result: rejects only with this append's own write error
23
+ const result = this.tail.then(() => this.write(value)).catch(error => {
13
24
  this.firstError ??= error instanceof Error ? error : new Error(String(error));
25
+ throw error;
14
26
  });
15
- return this.tail;
27
+ // Chain continues regardless so later appends are not blocked by this one's failure.
28
+ this.tail = result.catch(() => undefined);
29
+ return result;
16
30
  }
17
31
  async flush() {
18
32
  await this.tail;
@@ -1,4 +1,4 @@
1
- export type BackgroundProcessStatus = 'running' | 'exited' | 'failed' | 'killed';
1
+ type BackgroundProcessStatus = 'running' | 'exited' | 'failed' | 'killed';
2
2
  export interface BackgroundProcessSummary {
3
3
  backgroundId: string;
4
4
  pid?: number;
@@ -29,7 +29,6 @@ export declare function killBackgroundProcess(backgroundId: string, killGraceMs?
29
29
  export declare function teardownBackgroundProcesses(killGraceMs?: number): Promise<BackgroundProcessSummary[]>;
30
30
  /** Install CLI-level abnormal-exit teardown for SIGINT and SIGTERM. */
31
31
  export declare function installBackgroundProcessSignalHandlers(): void;
32
- /** Best-effort synchronous safety net for process.exit and otherwise unawaitable exits. */
33
- export declare function terminateBackgroundProcessesSync(): void;
34
32
  /** Test-only reset; callers should normally use teardownBackgroundProcesses. */
35
33
  export declare function resetBackgroundProcessesForTests(): Promise<void>;
34
+ export {};
@@ -2,8 +2,10 @@ import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
3
  import { BACKGROUND_PROCESS_HISTORY_LIMIT, BACKGROUND_PROCESS_MAX_CONCURRENCY } from '../agent/budgets.js';
4
4
  import { registerDynamicToolOutput, unregisterDynamicToolOutput } from '../agent/toolOutputStore.js';
5
- import { BACKGROUND_PROCESS_OUTPUT_BYTES } from '../limits/byteBudgets.js';
5
+ import { BACKGROUND_PROCESS_OUTPUT_BYTES } from '../limits.js';
6
6
  import { signalProcessTree } from './runBoundedProcess.js';
7
+ import { shellInvocation } from './userShell.js';
8
+ import { truncateUtf8TailBufferAtBytes } from '../../utils/utf8.js';
7
9
  class OutputRing {
8
10
  decoder = new StringDecoder('utf8');
9
11
  retained = Buffer.alloc(0);
@@ -13,12 +15,7 @@ class OutputRing {
13
15
  return;
14
16
  const bytes = Buffer.from(completeText, 'utf8');
15
17
  this.retained = this.retained.length === 0 ? bytes : Buffer.concat([this.retained, bytes]);
16
- if (this.retained.length > BACKGROUND_PROCESS_OUTPUT_BYTES) {
17
- let start = this.retained.length - BACKGROUND_PROCESS_OUTPUT_BYTES;
18
- while (start < this.retained.length && (this.retained[start] & 0xc0) === 0x80)
19
- start++;
20
- this.retained = this.retained.subarray(start);
21
- }
18
+ this.retained = truncateUtf8TailBufferAtBytes(this.retained, BACKGROUND_PROCESS_OUTPUT_BYTES).buffer;
22
19
  }
23
20
  add(chunk) {
24
21
  this.totalBytes += chunk.length;
@@ -81,7 +78,8 @@ export function startBackgroundProcess(input) {
81
78
  }
82
79
  installExitHook();
83
80
  const backgroundId = `background-${nextId++}`;
84
- const child = spawn('bash', ['-lc', input.command], {
81
+ const invocation = shellInvocation(input.command);
82
+ const child = spawn(invocation.command, invocation.args, {
85
83
  cwd: input.cwd,
86
84
  detached: process.platform !== 'win32',
87
85
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -103,7 +101,14 @@ export function startBackgroundProcess(input) {
103
101
  child.stderr?.on('data', (chunk) => ring.add(chunk));
104
102
  child.once('error', error => {
105
103
  summary.status = 'failed';
106
- summary.error = error.message;
104
+ const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
105
+ // Without the user's shell on PATH, spawn fails with ENOENT; surface a
106
+ // clearer message than the raw syscall error. The default Windows shell is
107
+ // bash (via WSL or Git Bash), so that case keeps the install hint.
108
+ const shellName = invocation.command;
109
+ summary.error = code === 'ENOENT' && process.platform === 'win32'
110
+ ? `${shellName} was not found on PATH.${shellName === 'bash' ? ' Install WSL or Git Bash, or run haze on a POSIX shell.' : ''} Underlying error: ${error.message}`
111
+ : error.message;
107
112
  notify();
108
113
  });
109
114
  child.once('close', (code, signal) => {
@@ -183,7 +188,7 @@ export function installBackgroundProcessSignalHandlers() {
183
188
  handle('SIGTERM', 143);
184
189
  }
185
190
  /** Best-effort synchronous safety net for process.exit and otherwise unawaitable exits. */
186
- export function terminateBackgroundProcessesSync() {
191
+ function terminateBackgroundProcessesSync() {
187
192
  for (const record of activeRecords())
188
193
  signalProcessTree(record.child, 'SIGTERM');
189
194
  }
@@ -1,4 +1,4 @@
1
- import { type ChildProcess } from 'node:child_process';
1
+ import { spawn, type ChildProcess } from 'node:child_process';
2
2
  export interface BoundedStream {
3
3
  text: string;
4
4
  totalBytes: number;
@@ -16,7 +16,13 @@ export interface BoundedProcessResult {
16
16
  durationMs: number;
17
17
  error?: string;
18
18
  }
19
- export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals): void;
19
+ export interface ProcessTreeSignalOptions {
20
+ /** @internal testing seam. */
21
+ platform?: NodeJS.Platform;
22
+ /** @internal testing seam. */
23
+ spawnProcess?: typeof spawn;
24
+ }
25
+ export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals, options?: ProcessTreeSignalOptions): void;
20
26
  export declare function runBoundedProcess(input: {
21
27
  command: string;
22
28
  args: string[];
@@ -1,15 +1,16 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
- export function signalProcessTree(child, signal) {
3
+ export function signalProcessTree(child, signal, options = {}) {
4
+ // When pid is null, child.kill is a no-op against a real Node child (returns
5
+ // false). Tests still rely on the call going through so they can observe
6
+ // which signal was used via their fake child's kill implementation.
4
7
  if (child.pid == null) {
5
8
  child.kill(signal);
6
9
  return;
7
10
  }
8
- if (process.platform === 'win32') {
9
- if (signal === 'SIGKILL')
10
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
11
- else
12
- child.kill('SIGTERM');
11
+ if ((options.platform ?? process.platform) === 'win32') {
12
+ const args = ['/pid', String(child.pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])];
13
+ (options.spawnProcess ?? spawn)('taskkill', args, { stdio: 'ignore' }).unref();
13
14
  return;
14
15
  }
15
16
  try {
@@ -27,6 +28,8 @@ function collector(limit) {
27
28
  add(chunk) {
28
29
  totalBytes += chunk.length;
29
30
  const remaining = limit - retainedBytes;
31
+ // Keep consuming data after the retention cap so the child does not
32
+ // block on a full pipe; only allocation and retained output are capped.
30
33
  if (remaining > 0) {
31
34
  const kept = chunk.subarray(0, remaining);
32
35
  chunks.push(kept);
@@ -78,6 +81,12 @@ export async function runBoundedProcess(input) {
78
81
  resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
79
82
  };
80
83
  const scheduleCloseFallback = () => {
84
+ // Only call after SIGKILL — running this after SIGTERM would resolve the
85
+ // promise before the forced-kill escalation, leaking processes that ignore
86
+ // SIGTERM. 50ms is enough for the kernel to deliver the signal and for an
87
+ // 'exit' event to fire; if 'close' still doesn't fire, the descendant is
88
+ // holding stdio (escaped grandchild) and we settle with whatever exit
89
+ // info we already captured.
81
90
  closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
82
91
  closeTimer.unref?.();
83
92
  };
@@ -0,0 +1,16 @@
1
+ export type ShellDialect = 'posix' | 'fish' | 'csh' | 'powershell' | 'cmd' | 'unknown';
2
+ export declare function shellDialect(shellPath?: string): ShellDialect;
3
+ /** Model-facing syntax guidance for the selected shell. */
4
+ export declare function shellSyntaxGuidance(shellPath?: string): "Use POSIX-compatible shell syntax." | "Use fish syntax; do not use POSIX variable-assignment syntax." | "Use csh/tcsh syntax; do not use POSIX variable-assignment syntax." | "Use PowerShell syntax, cmdlets, quoting, and environment-variable notation." | "Use Windows cmd.exe syntax and environment-variable notation." | "Use syntax supported by this shell; avoid shell-specific constructs when uncertain.";
5
+ /**
6
+ * The shell commands run in: an explicit HAZE_SHELL override, otherwise the
7
+ * user's login shell from the environment, with a bash fallback. On Windows the fallback stays `bash` (via WSL or Git Bash)
8
+ * because commands are written in POSIX syntax; Git Bash terminals export
9
+ * `SHELL` anyway, so the fallback only covers the no-`SHELL` case.
10
+ */
11
+ export declare function resolveUserShell(): string;
12
+ /** Spawn target for running `command` under `shellPath` (default: user's shell). */
13
+ export declare function shellInvocation(command: string, shellPath?: string): {
14
+ command: string;
15
+ args: string[];
16
+ };
@@ -0,0 +1,59 @@
1
+ // Shells that accept `-l` (login shell) alongside `-c`. Flags are passed
2
+ // separately (`-l -c`, not `-lc`) because that form is accepted by every
3
+ // login-capable shell including fish.
4
+ const LOGIN_CAPABLE = new Set(['bash', 'zsh', 'ksh', 'ksh93', 'mksh', 'yash', 'fish']);
5
+ function shellName(shellPath) {
6
+ const base = shellPath.split(/[\\/]/).pop() ?? shellPath;
7
+ return base.replace(/\.exe$/i, '').toLowerCase();
8
+ }
9
+ export function shellDialect(shellPath = resolveUserShell()) {
10
+ const name = shellName(shellPath);
11
+ if (['bash', 'zsh', 'sh', 'dash', 'ksh', 'ksh93', 'mksh', 'yash'].includes(name))
12
+ return 'posix';
13
+ if (name === 'fish')
14
+ return 'fish';
15
+ if (name === 'csh' || name === 'tcsh')
16
+ return 'csh';
17
+ if (name === 'pwsh' || name === 'powershell')
18
+ return 'powershell';
19
+ if (name === 'cmd')
20
+ return 'cmd';
21
+ return 'unknown';
22
+ }
23
+ /** Model-facing syntax guidance for the selected shell. */
24
+ export function shellSyntaxGuidance(shellPath = resolveUserShell()) {
25
+ const dialect = shellDialect(shellPath);
26
+ if (dialect === 'posix')
27
+ return 'Use POSIX-compatible shell syntax.';
28
+ if (dialect === 'fish')
29
+ return 'Use fish syntax; do not use POSIX variable-assignment syntax.';
30
+ if (dialect === 'csh')
31
+ return 'Use csh/tcsh syntax; do not use POSIX variable-assignment syntax.';
32
+ if (dialect === 'powershell')
33
+ return 'Use PowerShell syntax, cmdlets, quoting, and environment-variable notation.';
34
+ if (dialect === 'cmd')
35
+ return 'Use Windows cmd.exe syntax and environment-variable notation.';
36
+ return 'Use syntax supported by this shell; avoid shell-specific constructs when uncertain.';
37
+ }
38
+ /**
39
+ * The shell commands run in: an explicit HAZE_SHELL override, otherwise the
40
+ * user's login shell from the environment, with a bash fallback. On Windows the fallback stays `bash` (via WSL or Git Bash)
41
+ * because commands are written in POSIX syntax; Git Bash terminals export
42
+ * `SHELL` anyway, so the fallback only covers the no-`SHELL` case.
43
+ */
44
+ export function resolveUserShell() {
45
+ const fromEnv = process.env.HAZE_SHELL || process.env.SHELL;
46
+ if (fromEnv)
47
+ return fromEnv;
48
+ return process.platform === 'win32' ? 'bash' : '/bin/bash';
49
+ }
50
+ /** Spawn target for running `command` under `shellPath` (default: user's shell). */
51
+ export function shellInvocation(command, shellPath = resolveUserShell()) {
52
+ const name = shellName(shellPath);
53
+ if (name === 'pwsh' || name === 'powershell')
54
+ return { command: shellPath, args: ['-Command', command] };
55
+ if (name === 'cmd')
56
+ return { command: shellPath, args: ['/c', command] };
57
+ const login = LOGIN_CAPABLE.has(name) ? ['-l'] : [];
58
+ return { command: shellPath, args: [...login, '-c', command] };
59
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Bounded, generic diagnostic for missing executables.
3
+ *
4
+ * When a shell command fails because an executable is not on PATH, this derives
5
+ * a precise, safe blocker: the executable name and a generic recovery order. It
6
+ * never returns raw stderr/command text and contains no dependency-specific
7
+ * branching (no special cases for Git, Python, Docker images, etc.).
8
+ *
9
+ * The recovery order is generic and safe:
10
+ * 1. an already-available alternative (versioned/similarly-named command);
11
+ * 2. the project's own manifest/package file + a project-local install;
12
+ * 3. a system install only with explicit user consent (deferred — see below).
13
+ *
14
+ * Product decision (deferred): a system-install permission model is not defined
15
+ * here. We never silently modify a user-managed toolchain. The diagnostic asks
16
+ * for consent and reports the blocker; it does not perform the install.
17
+ */
18
+ export interface MissingExecutableDiagnostic {
19
+ /** Best-effort name of the executable that was not found. */
20
+ executable: string;
21
+ /** Generic, dependency-agnostic next step (bounded, no raw command/stderr). */
22
+ suggestedNextStep: string;
23
+ }
24
+ /**
25
+ * Detect a missing-executable failure from a bounded command + reduced stderr +
26
+ * exit code. Returns undefined when the failure is not a missing-executable
27
+ * failure or no executable name can be derived.
28
+ */
29
+ export declare function detectMissingExecutable(input: {
30
+ command: string;
31
+ code: number | null;
32
+ stderr: string;
33
+ }): MissingExecutableDiagnostic | undefined;
34
+ /**
35
+ * Project the diagnostic into the bounded fields carried in safe tool output /
36
+ * events. Only the executable name and reasonCode are exposed — never stderr or
37
+ * the full command.
38
+ */
39
+ export declare function missingExecutableFields(diagnostic: MissingExecutableDiagnostic): {
40
+ reasonCode: 'missing_executable';
41
+ missingExecutable: string;
42
+ };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Bounded, generic diagnostic for missing executables.
3
+ *
4
+ * When a shell command fails because an executable is not on PATH, this derives
5
+ * a precise, safe blocker: the executable name and a generic recovery order. It
6
+ * never returns raw stderr/command text and contains no dependency-specific
7
+ * branching (no special cases for Git, Python, Docker images, etc.).
8
+ *
9
+ * The recovery order is generic and safe:
10
+ * 1. an already-available alternative (versioned/similarly-named command);
11
+ * 2. the project's own manifest/package file + a project-local install;
12
+ * 3. a system install only with explicit user consent (deferred — see below).
13
+ *
14
+ * Product decision (deferred): a system-install permission model is not defined
15
+ * here. We never silently modify a user-managed toolchain. The diagnostic asks
16
+ * for consent and reports the blocker; it does not perform the install.
17
+ */
18
+ const NOT_FOUND_PATTERNS = [
19
+ /:\s*command not found\b/i,
20
+ /\bcommand not found:\s*/i,
21
+ /\bnot found\s*$/i,
22
+ /No such file or directory\b/i,
23
+ ];
24
+ /** Extract the executable name from a "not found" diagnostic line, generically. */
25
+ function executableFromMessage(line) {
26
+ // `zsh:1: command not found: NAME` / `command not found: NAME` (checked first
27
+ // so the line-number colon in the zsh form is not captured).
28
+ const m2 = line.match(/command not found:\s*([^\s]+)/i);
29
+ if (m2?.[1])
30
+ return m2[1];
31
+ // `bash: line 1: NAME: command not found` / `bash: NAME: command not found`
32
+ const m = line.match(/:\s*([^\s:]+):\s*command not found/i);
33
+ if (m?.[1] && !/^\d+$/.test(m[1]))
34
+ return m[1];
35
+ // `NAME: not found` / `NAME: command not found`
36
+ const m3 = line.match(/^\s*([^\s:]+):\s*(?:command )?not found\s*$/i);
37
+ if (m3?.[1])
38
+ return m3[1];
39
+ return undefined;
40
+ }
41
+ function firstCommandToken(command) {
42
+ const tokens = command.trim().split(/\s+/);
43
+ for (const raw of tokens) {
44
+ // Skip wrappers and environment-variable assignments (e.g. `env FOO=1 cmd`).
45
+ if (/^(env|sudo|command|nohup|exec|time)$/i.test(raw) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(raw))
46
+ continue;
47
+ const cleaned = raw.replace(/^.+\//, '').replace(/^['"]|['"]$/g, '');
48
+ return cleaned || undefined;
49
+ }
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Detect a missing-executable failure from a bounded command + reduced stderr +
54
+ * exit code. Returns undefined when the failure is not a missing-executable
55
+ * failure or no executable name can be derived.
56
+ */
57
+ export function detectMissingExecutable(input) {
58
+ const looksMissing = input.code === 127 || NOT_FOUND_PATTERNS.some(pattern => pattern.test(input.stderr));
59
+ if (!looksMissing)
60
+ return undefined;
61
+ const byLine = input.stderr.split(/\r?\n/).map(executableFromMessage).find(Boolean);
62
+ const executable = byLine ?? firstCommandToken(input.command);
63
+ if (!executable)
64
+ return undefined;
65
+ return {
66
+ executable,
67
+ suggestedNextStep: `Command '${executable}' was not found. First check whether a versioned or similarly-named alternative is already installed, then add it to the project's manifest/package file and install project-locally, or ask for explicit consent before installing into the system environment. Report this as blocked if no safe option is available.`,
68
+ };
69
+ }
70
+ /**
71
+ * Project the diagnostic into the bounded fields carried in safe tool output /
72
+ * events. Only the executable name and reasonCode are exposed — never stderr or
73
+ * the full command.
74
+ */
75
+ export function missingExecutableFields(diagnostic) {
76
+ return { reasonCode: 'missing_executable', missingExecutable: diagnostic.executable };
77
+ }
@@ -0,0 +1,11 @@
1
+ type ShellRiskLevel = 'read_only' | 'mutating' | 'destructive' | 'network' | 'unknown';
2
+ type ShellTrait = 'reads_files' | 'writes_files' | 'deletes_files' | 'installs_dependencies' | 'runs_tests' | 'runs_build' | 'uses_network' | 'changes_git_state' | 'changes_permissions';
3
+ export type ShellClassification = {
4
+ riskLevel: ShellRiskLevel;
5
+ traits: ShellTrait[];
6
+ confidence: 'high' | 'medium' | 'low';
7
+ reason: string;
8
+ };
9
+ export declare function classifyShellCommand(command: string): ShellClassification;
10
+ export declare function isValidationClassification(classification: ShellClassification): boolean;
11
+ export {};