@denizokcu/haze 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -0,0 +1,245 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { IMAGE_ATTACHMENT_BYTES, IMAGE_ATTACHMENTS_PER_MESSAGE } from '../limits/byteBudgets.js';
5
+ import { workspaceRoot } from '../../utils/path.js';
6
+ import { formatBytes } from '../../utils/format.js';
7
+ /**
8
+ * User-attached images for one prompt (F03).
9
+ *
10
+ * Attachments are resolved from `@path` mentions typed by the user in the
11
+ * interactive chat: host-path allowed (workspace-relative, absolute, or `~/`),
12
+ * real-path deduped, extension-allowlisted, byte-bounded. The module is UI-
13
+ * and provider-agnostic (constitution VI): the capability gate takes the
14
+ * provider shape explicitly, never settings I/O.
15
+ */
16
+ /** Extension allowlist → media type. Only these image kinds can be attached. */
17
+ export const IMAGE_MEDIA_TYPES = {
18
+ '.png': 'image/png',
19
+ '.jpg': 'image/jpeg',
20
+ '.jpeg': 'image/jpeg',
21
+ '.gif': 'image/gif',
22
+ '.webp': 'image/webp',
23
+ };
24
+ export const IMAGE_EXTENSIONS = Object.keys(IMAGE_MEDIA_TYPES);
25
+ /**
26
+ * `@token` candidates. The lookbehind keeps emails/handles intact
27
+ * (`user@example.com` never matches at `@example.com`). Backslash escapes
28
+ * (`\ `, `\(`, …) are part of the token so paths containing spaces — the
29
+ * default macOS screenshot filename is `Bildschirmfoto YYYY-MM-DD um HH.MM.SS.png` —
30
+ * survive intact. The escape is removed during resolution, never silently.
31
+ */
32
+ const MENTION_PATTERN = /(?<![\w@])@((?:[\w./~-]|\\.)+)/g;
33
+ /**
34
+ * Bare path candidates (no `@`). The lookahead requires a `/` somewhere in
35
+ * the token so ordinary prose ("I named it cat.png") is never scanned; the
36
+ * lookbehind stops mid-word matches and skips anything right after `@`
37
+ * (handled by `MENTION_PATTERN`), `.`, or `/`. Backslash escapes are part
38
+ * of the token. Routing (image attachment vs read-blessing) happens during
39
+ * resolution based on extension and stat result.
40
+ */
41
+ const BARE_PATH_PATTERN = /(?<![\w.@/])(?=[\w.~/-]*\/)((?:[\w./~-]|\\.)+)(?![\w.-])/gi;
42
+ /**
43
+ * Extract path-like attachment candidates from prompt text. Two forms are
44
+ * recognised:
45
+ *
46
+ * - Explicit `@token` mentions: any path-like token after `@`. A candidate
47
+ * must contain a `.` or `/` so bare handles (`@here`) are skipped.
48
+ * - Bare paths: a token that ends in an allowlisted image extension AND
49
+ * contains `/`. The separator keeps prose like "I named it cat.png" out;
50
+ * the existence check during resolution is the final gate.
51
+ *
52
+ * Whether a candidate is really an attachment is decided during resolution.
53
+ */
54
+ export function extractPathMentions(text) {
55
+ const mentions = [];
56
+ const seen = new Set();
57
+ for (const match of text.matchAll(MENTION_PATTERN)) {
58
+ const token = match[1];
59
+ if (!token || (!token.includes('.') && !token.includes('/')))
60
+ continue;
61
+ if (seen.has(match[0]))
62
+ continue;
63
+ seen.add(match[0]);
64
+ mentions.push({ mention: match[0], token });
65
+ }
66
+ for (const match of text.matchAll(BARE_PATH_PATTERN)) {
67
+ const token = match[1];
68
+ if (!token || !token.includes('/'))
69
+ continue;
70
+ if (seen.has(match[0]))
71
+ continue;
72
+ seen.add(match[0]);
73
+ mentions.push({ mention: match[0], token });
74
+ }
75
+ return mentions;
76
+ }
77
+ /**
78
+ * Resolve an `@token` mention to a host path. Relative tokens resolve against
79
+ * the workspace root but may escape it (`../shot.png`); `~/` expands to the
80
+ * home directory; absolute tokens stay absolute. Attachments are explicit
81
+ * user-typed references, so host paths outside the workspace are allowed.
82
+ */
83
+ function resolveAttachmentPath(token) {
84
+ if (token === '~' || token.startsWith('~/'))
85
+ return path.join(os.homedir(), token.slice(1));
86
+ return path.resolve(workspaceRoot(), token);
87
+ }
88
+ /** Workspace-relative for files inside the project, `~/…` under the home directory, absolute otherwise. */
89
+ function displayPathFor(realPath) {
90
+ const relativeTo = (root) => {
91
+ const relative = path.relative(root, realPath);
92
+ return relative.startsWith('..') || path.isAbsolute(relative) ? undefined : relative || '.';
93
+ };
94
+ const inWorkspace = relativeTo(workspaceRoot());
95
+ if (inWorkspace !== undefined)
96
+ return inWorkspace;
97
+ const inHome = relativeTo(os.homedir());
98
+ return inHome !== undefined ? path.join('~', inHome) : realPath;
99
+ }
100
+ function notAnImageError(token) {
101
+ return new Error(`Not an image: @${token}. Only ${IMAGE_EXTENSIONS.join(', ')} files can be attached.`);
102
+ }
103
+ async function statFile(absolutePath) {
104
+ try {
105
+ return await fs.stat(absolutePath);
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ /**
112
+ * Resolve `@path` mentions into image attachments.
113
+ *
114
+ * - Mentions that do not resolve to an existing file stay literal
115
+ * prompt text (emails, handles, typos) — no error.
116
+ * - Existing paths with a non-image extension stay literal text too; the
117
+ * read-blessing resolver picks them up so the model can `readFile` them.
118
+ * - Existing image-extension paths that are not regular files (e.g. a
119
+ * directory named `foo.png`) fail loudly — that is a genuine attach-intent
120
+ * mismatch, not silent drop.
121
+ * - An `@` mention is an explicit user-typed reference, so any host path
122
+ * works: workspace-relative (including `../`), absolute, or `~/`. The real
123
+ * path dedupes aliases (symlinks, `..` segments) instead of confining
124
+ * reads; `.gitignore` is not enforced here (documented in AGENTS.md).
125
+ * - Size and per-message count are bounded by named limits; errors name them.
126
+ * - The same file mentioned twice is attached once; both mentions are stripped.
127
+ */
128
+ export async function resolveImageAttachments(text) {
129
+ const mentions = extractPathMentions(text);
130
+ if (mentions.length === 0)
131
+ return { text, attachments: [] };
132
+ const attachments = [];
133
+ const seenRealPaths = new Set();
134
+ const strippedTokens = new Set();
135
+ for (const { token } of mentions) {
136
+ // Backslash escapes (`\ `, `\(`, …) are removed for filesystem resolution
137
+ // but kept in `token` so the mention can be stripped from the prompt
138
+ // exactly as the user typed it. macOS screenshot paths and other host
139
+ // paths commonly contain spaces; without unescape the file would never
140
+ // resolve and the mention would silently become plain text.
141
+ const resolveToken = token.replace(/\\(.)/g, '$1');
142
+ // A sentence-ending period ("@shot.png.") is not part of the filename, so
143
+ // fall back to the trailing-dot-stripped form when the verbatim path does
144
+ // not exist; the image is then attached instead of being silently left as
145
+ // text.
146
+ let fileToken = resolveToken;
147
+ let absolutePath = resolveAttachmentPath(resolveToken);
148
+ let stats = await statFile(absolutePath);
149
+ if (!stats) {
150
+ const trimmed = resolveToken.replace(/\.+$/, '');
151
+ if (trimmed && trimmed !== resolveToken) {
152
+ const trimmedPath = resolveAttachmentPath(trimmed);
153
+ const trimmedStats = await statFile(trimmedPath);
154
+ if (trimmedStats) {
155
+ fileToken = trimmed;
156
+ absolutePath = trimmedPath;
157
+ stats = trimmedStats;
158
+ }
159
+ }
160
+ }
161
+ if (!stats)
162
+ continue; // Not an existing path: leave the mention as literal text.
163
+ const mediaType = IMAGE_MEDIA_TYPES[path.extname(fileToken).toLowerCase()];
164
+ if (!mediaType)
165
+ continue; // Non-image extension: leave as text; resolveReadBlessings blesses it.
166
+ if (!stats.isFile())
167
+ throw notAnImageError(fileToken); // Image extension but directory: genuine mismatch.
168
+ const realPath = await fs.realpath(absolutePath);
169
+ if (seenRealPaths.has(realPath)) {
170
+ strippedTokens.add(token); // Same file already attached; still strip the repeat.
171
+ continue;
172
+ }
173
+ if (stats.size > IMAGE_ATTACHMENT_BYTES) {
174
+ throw new Error(`Image too large: @${fileToken} is ${formatBytes(stats.size)}; the attachment limit is ${formatBytes(IMAGE_ATTACHMENT_BYTES)} per image.`);
175
+ }
176
+ if (attachments.length >= IMAGE_ATTACHMENTS_PER_MESSAGE) {
177
+ throw new Error(`Too many image attachments: at most ${IMAGE_ATTACHMENTS_PER_MESSAGE} per message.`);
178
+ }
179
+ const data = new Uint8Array(await fs.readFile(realPath));
180
+ seenRealPaths.add(realPath);
181
+ strippedTokens.add(token);
182
+ attachments.push({
183
+ displayPath: displayPathFor(realPath),
184
+ absolutePath: realPath,
185
+ fileName: path.basename(realPath),
186
+ mediaType,
187
+ bytes: data.byteLength,
188
+ data,
189
+ });
190
+ }
191
+ if (strippedTokens.size === 0)
192
+ return { text, attachments };
193
+ // Strip attached mentions (explicit `@` and bare), then tidy the double
194
+ // space a mid-line removal can leave behind. The lookbehind keeps line-
195
+ // leading indentation intact.
196
+ const cleaned = text
197
+ .replace(MENTION_PATTERN, (mention, token) => strippedTokens.has(token) ? '' : mention)
198
+ .replace(BARE_PATH_PATTERN, (match, token) => strippedTokens.has(token) ? '' : match)
199
+ .replace(/(?<=[^\n])[ \t]{2,}/g, ' ')
200
+ .trim();
201
+ return { text: cleaned, attachments };
202
+ }
203
+ /** Build the turn's user message: plain string without attachments, multipart with. */
204
+ export function userTurnMessage(text, attachments) {
205
+ if (attachments.length === 0)
206
+ return { role: 'user', content: text };
207
+ const parts = [
208
+ ...(text.trim() ? [{ type: 'text', text }] : []),
209
+ ...attachments.map(attachment => ({ type: 'file', mediaType: attachment.mediaType, data: attachment.data, filename: attachment.fileName })),
210
+ ];
211
+ return { role: 'user', content: parts };
212
+ }
213
+ /** Minimal prompt text used when a message contains only images. */
214
+ export const IMAGE_ONLY_PROMPT_TEXT = 'See the attached image.';
215
+ /**
216
+ * Loud capability gate (constitution VII): images only go to providers the
217
+ * user explicitly marked image-capable. Returns undefined when the provider
218
+ * may receive image parts, otherwise an actionable error message.
219
+ */
220
+ export function imageCapabilityError(provider) {
221
+ if (provider?.capabilities?.images === true)
222
+ return undefined;
223
+ if (!provider)
224
+ return 'No provider is configured. Run /provider to add one, then attach the image again.';
225
+ return `Provider '${provider.name}' is not marked image-capable. Enable image input for it via /provider, or switch models.`;
226
+ }
227
+ /** Guard for AI SDK `file` parts carrying images, in any message role. */
228
+ export function isImageFilePart(value) {
229
+ if (typeof value !== 'object' || value == null)
230
+ return false;
231
+ const part = value;
232
+ return part.type === 'file' && typeof part.mediaType === 'string' && part.mediaType.startsWith('image/');
233
+ }
234
+ /** Byte size of a file part's data without serializing it. */
235
+ export function imageFilePartBytes(data) {
236
+ let candidate = data;
237
+ if (typeof candidate === 'object' && candidate != null && candidate.type === 'data') {
238
+ candidate = candidate.data;
239
+ }
240
+ if (candidate instanceof Uint8Array || candidate instanceof ArrayBuffer)
241
+ return candidate.byteLength;
242
+ if (typeof candidate === 'string')
243
+ return Math.floor(candidate.length * 3 / 4); // base64 payload
244
+ return 0;
245
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Read-blessings for paths the user mentioned in the prompt (F03 follow-on).
3
+ *
4
+ * When the user types `@path` or a bare path containing `/`, the model is
5
+ * allowed to `readFile` / `grep` it even outside `process.cwd()`. This module
6
+ * resolves those mentions into a deduped list of blessed real paths. The
7
+ * read-tooling layer consults `isPathBlessed` to skip workspace confinement
8
+ * for them. Mutating tools never consult this set.
9
+ *
10
+ * Like image attachments: an `@` mention is an explicit user-typed reference,
11
+ * so host paths are allowed. Unlike image attachments: text paths stay in the
12
+ * prompt text (the model needs the cue to know what to read).
13
+ */
14
+ export interface BlessedPath {
15
+ /** Canonical real path (post-symlink-resolution). */
16
+ realPath: string;
17
+ /** Whether the blessed path is a directory; directories bless the whole tree. */
18
+ isDirectory: boolean;
19
+ }
20
+ export interface ResolvedReadBlessings {
21
+ blessedPaths: BlessedPath[];
22
+ }
23
+ /**
24
+ * Resolve `@path` and bare-path mentions into read-blessings.
25
+ *
26
+ * - Image-extension paths are skipped — `resolveImageAttachments` owns them.
27
+ * - Mentions that do not resolve to an existing file or directory are skipped.
28
+ * - The real path dedupes aliases (symlinks, `..` segments).
29
+ * - Mentions are NOT stripped from the prompt text: the model needs them as a
30
+ * cue to know what to read.
31
+ */
32
+ export declare function resolveReadBlessings(text: string): Promise<ResolvedReadBlessings>;
33
+ /**
34
+ * Whether a requested real path may be read outside workspace confinement.
35
+ * True if the path is itself blessed, or falls inside a blessed directory.
36
+ */
37
+ export declare function isPathBlessed(requestedRealPath: string, blessed: readonly BlessedPath[]): boolean;
@@ -0,0 +1,79 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { extractPathMentions, IMAGE_MEDIA_TYPES } from './imageAttachments.js';
5
+ import { workspaceRoot } from '../../utils/path.js';
6
+ function resolveAttachmentPath(token) {
7
+ if (token === '~' || token.startsWith('~/'))
8
+ return path.join(os.homedir(), token.slice(1));
9
+ return path.resolve(workspaceRoot(), token);
10
+ }
11
+ async function statFile(absolutePath) {
12
+ try {
13
+ return await fs.stat(absolutePath);
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ /**
20
+ * Resolve `@path` and bare-path mentions into read-blessings.
21
+ *
22
+ * - Image-extension paths are skipped — `resolveImageAttachments` owns them.
23
+ * - Mentions that do not resolve to an existing file or directory are skipped.
24
+ * - The real path dedupes aliases (symlinks, `..` segments).
25
+ * - Mentions are NOT stripped from the prompt text: the model needs them as a
26
+ * cue to know what to read.
27
+ */
28
+ export async function resolveReadBlessings(text) {
29
+ const mentions = extractPathMentions(text);
30
+ if (mentions.length === 0)
31
+ return { blessedPaths: [] };
32
+ const blessedPaths = [];
33
+ const seenRealPaths = new Set();
34
+ for (const { token } of mentions) {
35
+ // Backslash escapes are removed for filesystem resolution (same rule as
36
+ // image attachments). See imageAttachments.ts for the rationale.
37
+ const resolveToken = token.replace(/\\(.)/g, '$1');
38
+ // Image-extension paths are owned by the image attachment system; skip
39
+ // them here so an attached image is not also blessed for read.
40
+ if (IMAGE_MEDIA_TYPES[path.extname(resolveToken).toLowerCase()])
41
+ continue;
42
+ // Sentence-ending period is not part of the filename — same fallback as
43
+ // for image attachments.
44
+ let absolutePath = resolveAttachmentPath(resolveToken);
45
+ let stats = await statFile(absolutePath);
46
+ if (!stats) {
47
+ const trimmed = resolveToken.replace(/\.+$/, '');
48
+ if (trimmed && trimmed !== resolveToken) {
49
+ const trimmedPath = resolveAttachmentPath(trimmed);
50
+ const trimmedStats = await statFile(trimmedPath);
51
+ if (trimmedStats) {
52
+ absolutePath = trimmedPath;
53
+ stats = trimmedStats;
54
+ }
55
+ }
56
+ }
57
+ if (!stats)
58
+ continue;
59
+ const realPath = await fs.realpath(absolutePath);
60
+ if (seenRealPaths.has(realPath))
61
+ continue;
62
+ seenRealPaths.add(realPath);
63
+ blessedPaths.push({ realPath, isDirectory: stats.isDirectory() });
64
+ }
65
+ return { blessedPaths };
66
+ }
67
+ /**
68
+ * Whether a requested real path may be read outside workspace confinement.
69
+ * True if the path is itself blessed, or falls inside a blessed directory.
70
+ */
71
+ export function isPathBlessed(requestedRealPath, blessed) {
72
+ for (const entry of blessed) {
73
+ if (entry.realPath === requestedRealPath)
74
+ return true;
75
+ if (entry.isDirectory && requestedRealPath.startsWith(`${entry.realPath}${path.sep}`))
76
+ return true;
77
+ }
78
+ return false;
79
+ }
@@ -0,0 +1,33 @@
1
+ export declare const TOOL_DEADLINE_EXCEEDED = "__hazeToolDeadlineExceeded";
2
+ export interface ToolDeadlineResult {
3
+ ok: false;
4
+ [TOOL_DEADLINE_EXCEEDED]: true;
5
+ error: string;
6
+ }
7
+ /** True when a tool result is the structured "deadline exceeded" placeholder. */
8
+ export declare function isToolDeadlineExceeded(output: unknown): boolean;
9
+ /**
10
+ * Run an underlying tool `execute` under a deadline. The wrapper resolves
11
+ * promptly when the deadline (or an optional parent abort signal) fires, even
12
+ * if the underlying work ignores cancellation. The still-pending work is
13
+ * quarantined so its eventual settlement cannot produce an unhandled rejection
14
+ * or mutate caller state (RH-004).
15
+ *
16
+ * - Normal completion → resolves with the underlying value.
17
+ * - Underlying rejection → rejects with that error (let the SDK classify it).
18
+ * - Deadline / parent abort → resolves with a structured bounded failure.
19
+ */
20
+ export declare function withToolDeadline(execute: () => Promise<unknown>, timeoutMs: number, signal?: AbortSignal): Promise<unknown>;
21
+ /**
22
+ * Create a clearable absolute deadline that fires `onTimeout` once after
23
+ * `timeoutMs`, unless `clear()` is called first. An already-aborted parent
24
+ * signal fires immediately. Used for the absolute main-turn bound (RH-004).
25
+ */
26
+ export interface AbsoluteDeadline {
27
+ clear: () => void;
28
+ }
29
+ export declare function createAbsoluteDeadline(input: {
30
+ timeoutMs: number;
31
+ signal?: AbortSignal;
32
+ onTimeout: () => void;
33
+ }): AbsoluteDeadline;
@@ -0,0 +1,74 @@
1
+ export 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,2 +1,29 @@
1
1
  export declare function toolLoopBudgetPrompt(): string;
2
2
  export declare function repeatedToolCallPrompt(toolNames: string[]): string;
3
+ /**
4
+ * Ephemeral control appended to continue a response truncated by an
5
+ * output-length finish. Asks the model to resume from where it stopped and
6
+ * complete the requested artifact/answer. One-request nudge only.
7
+ */
8
+ export declare function lengthContinuationPrompt(): string;
9
+ /**
10
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
11
+ * validation tools are available; discovery must not be reopened. The model gets
12
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
13
+ * deliverable you already discovered, then one final tool-free synthesis.
14
+ */
15
+ export declare function completionRescuePrompt(): string;
16
+ export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
17
+ /**
18
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
19
+ * turn. The model's stop was rejected (or its physical turn hit a budget
20
+ * boundary) while structured evidence — declared task counts, post-edit
21
+ * validation — shows unfinished work; this nudge requires resuming concrete
22
+ * work rather than summarizing again. One-request nudge only.
23
+ */
24
+ export declare function goalContinuationPrompt(reason: string, taskCounts?: {
25
+ total: number;
26
+ pending: number;
27
+ inProgress: number;
28
+ completed: number;
29
+ }): string;
@@ -1,7 +1,43 @@
1
1
  export function toolLoopBudgetPrompt() {
2
- return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
2
+ return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once with a bounded progress checkpoint: what is done so far (changes + validation evidence) and, if work remains, the single next concrete unfinished action. haze continues the active goal automatically from that line — do not manufacture a completion summary and do not treat this as the end of the task. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
3
3
  }
4
4
  export function repeatedToolCallPrompt(toolNames) {
5
5
  const names = [...new Set(toolNames)].join(', ');
6
6
  return `You already called ${names || 'a tool'} with identical input in this turn. Do not call the same tool again with the same arguments. Use the existing tool result already in the conversation, choose a different concrete tool/input if genuinely needed, or give the final/blocked status now.`;
7
7
  }
8
+ /**
9
+ * Ephemeral control appended to continue a response truncated by an
10
+ * output-length finish. Asks the model to resume from where it stopped and
11
+ * complete the requested artifact/answer. One-request nudge only.
12
+ */
13
+ export function lengthContinuationPrompt() {
14
+ return 'Your previous response was truncated by the output-token limit before it finished. Continue exactly from where you stopped and complete the requested artifact or answer. Do not repeat what you already produced; finish the in-progress work and then stop.';
15
+ }
16
+ /**
17
+ * Ephemeral control for the single completion-rescue slice. Only mutation and
18
+ * validation tools are available; discovery must not be reopened. The model gets
19
+ * one tool-bearing step (at most two tool calls) to apply a concrete remaining
20
+ * deliverable you already discovered, then one final tool-free synthesis.
21
+ */
22
+ export function completionRescuePrompt() {
23
+ return 'You reached the tool-boundary without a substantive final answer. Only edit/write and validation tools are available now. Use at most two tool calls to apply the single most important remaining concrete deliverable you already discovered (do not explore or read new files), then give the final status: current-task changes plus validation evidence, or a single short line stating the next unfinished action. Do not loop.';
24
+ }
25
+ export function malformedToolCallPrompt(toolName, chunkBytes) {
26
+ const chunkGuidance = toolName === 'writeFile'
27
+ ? ` Keep content below ${chunkBytes} UTF-8 bytes per call: write the first chunk normally, then continue the same file with append=true.`
28
+ : '';
29
+ return `The ${toolName} call had invalid, malformed, or truncated JSON input and did not execute. Retry it now with valid smaller arguments; do not merely announce that you will retry.${chunkGuidance}`;
30
+ }
31
+ /**
32
+ * Ephemeral control for a goal-continuation slice or a fresh continuation
33
+ * turn. The model's stop was rejected (or its physical turn hit a budget
34
+ * boundary) while structured evidence — declared task counts, post-edit
35
+ * validation — shows unfinished work; this nudge requires resuming concrete
36
+ * work rather than summarizing again. One-request nudge only.
37
+ */
38
+ export function goalContinuationPrompt(reason, taskCounts) {
39
+ const taskLine = taskCounts
40
+ ? ` The task list currently shows ${taskCounts.pending + taskCounts.inProgress} open item${taskCounts.pending + taskCounts.inProgress === 1 ? '' : 's'} of ${taskCounts.total}; update writeTasks as you complete them.`
41
+ : '';
42
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}). Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
43
+ }
@@ -1,6 +1,3 @@
1
1
  export type RequestIntent = 'implement' | 'fix' | 'test' | 'review' | 'plan' | 'answer' | 'unknown';
2
2
  export declare function isPlanOnlyRequest(value: string): boolean;
3
- export declare function isPlanImplementationRequest(value: string): boolean;
4
- export declare function isValidationRequest(value: string): boolean;
5
- export declare function isActionRequest(value: string): boolean;
6
3
  export declare function classifyRequestIntent(value: string): RequestIntent;
@@ -1,19 +1,6 @@
1
1
  export function isPlanOnlyRequest(value) {
2
2
  return /\b(create|make|write|draft|outline)\s+(?:a\s+)?plan\b|\bplan\s+(?:for|to)\b/i.test(value) && !/\bimplement|execute|do\b/i.test(value);
3
3
  }
4
- export function isPlanImplementationRequest(value) {
5
- return /\b(implement|execute|do)\b.*\bplan\b|\bplan\.md\b|\btest_plan\.md\b/i.test(value);
6
- }
7
- export function isValidationRequest(value) {
8
- if (isPlanOnlyRequest(value))
9
- return false;
10
- return /\b(run|verify|test|tests|check|validate)\b/i.test(value);
11
- }
12
- export function isActionRequest(value) {
13
- if (isPlanOnlyRequest(value))
14
- return false;
15
- return /\b(add|create|write|implement|update|fix|change|support|wire|test|tests|document|docs|documentation|run|verify)\b/i.test(value);
16
- }
17
4
  export function classifyRequestIntent(value) {
18
5
  if (isPlanOnlyRequest(value))
19
6
  return 'plan';