@denizokcu/haze 0.8.0 → 0.10.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 (182) hide show
  1. package/CHANGELOG.md +67 -17
  2. package/README.md +121 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  14. package/dist/cli/chat/sessionRecorder.js +21 -8
  15. package/dist/cli/chat/startupInfo.d.ts +1 -0
  16. package/dist/cli/chat/startupInfo.js +11 -0
  17. package/dist/cli/chat/tips.d.ts +21 -0
  18. package/dist/cli/chat/tips.js +43 -0
  19. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  20. package/dist/cli/chat/wizardDispatch.js +645 -0
  21. package/dist/cli/commands/chat.d.ts +1 -0
  22. package/dist/cli/commands/chat.js +246 -779
  23. package/dist/cli/commands/chatModes.d.ts +1 -1
  24. package/dist/cli/commands/chatModes.js +7 -2
  25. package/dist/cli/commands/commandHelp.js +5 -3
  26. package/dist/cli/commands/commands.d.ts +4 -3
  27. package/dist/cli/commands/commands.js +12 -13
  28. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  29. package/dist/cli/commands/fleetCommand.js +46 -0
  30. package/dist/cli/commands/formatters.d.ts +5 -0
  31. package/dist/cli/commands/formatters.js +36 -9
  32. package/dist/cli/commands/logsCommand.js +8 -28
  33. package/dist/cli/commands/mcpWizard.js +24 -2
  34. package/dist/cli/commands/modelCommand.js +1 -1
  35. package/dist/cli/commands/providerWizard.d.ts +1 -0
  36. package/dist/cli/commands/providerWizard.js +31 -5
  37. package/dist/cli/commands/runCommand.d.ts +1 -0
  38. package/dist/cli/commands/runCommand.js +32 -20
  39. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  40. package/dist/cli/commands/sessionPicker.js +29 -0
  41. package/dist/cli/commands/settingsSummary.js +8 -4
  42. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  43. package/dist/cli/commands/skillWizard.d.ts +2 -0
  44. package/dist/cli/commands/skillWizard.js +16 -6
  45. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  46. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  47. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  48. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  49. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  50. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  51. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  52. package/dist/cli/commands/streaming.d.ts +13 -1
  53. package/dist/cli/commands/streaming.js +104 -44
  54. package/dist/cli/commands/wizardActions.d.ts +6 -0
  55. package/dist/cli/commands/wizardActions.js +6 -0
  56. package/dist/cli/commands/wizardPrompts.js +1 -1
  57. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  58. package/dist/cli/commands/wizardSuggestions.js +62 -13
  59. package/dist/cli/commands/wizardTransition.d.ts +37 -0
  60. package/dist/cli/commands/wizardTransition.js +43 -0
  61. package/dist/cli/index.js +17 -3
  62. package/dist/cli/terminalTitle.d.ts +6 -0
  63. package/dist/cli/terminalTitle.js +36 -0
  64. package/dist/config/contextFiles.js +6 -3
  65. package/dist/config/endpointSecurity.d.ts +2 -0
  66. package/dist/config/endpointSecurity.js +28 -0
  67. package/dist/config/inputHistory.d.ts +3 -3
  68. package/dist/config/inputHistory.js +13 -17
  69. package/dist/config/modelDiscovery.d.ts +20 -0
  70. package/dist/config/modelDiscovery.js +51 -0
  71. package/dist/config/privateStorage.d.ts +6 -0
  72. package/dist/config/privateStorage.js +61 -0
  73. package/dist/config/providerPresets.d.ts +16 -4
  74. package/dist/config/providerPresets.js +263 -34
  75. package/dist/config/providers.d.ts +2 -0
  76. package/dist/config/providers.js +7 -0
  77. package/dist/config/settings.d.ts +22 -0
  78. package/dist/config/settings.js +33 -5
  79. package/dist/config/skillSettings.d.ts +6 -13
  80. package/dist/config/skillSettings.js +20 -19
  81. package/dist/config/updateCheck.js +4 -2
  82. package/dist/core/agent/budgets.d.ts +26 -0
  83. package/dist/core/agent/budgets.js +34 -0
  84. package/dist/core/agent/compaction.js +17 -3
  85. package/dist/core/agent/contextBudget.d.ts +8 -0
  86. package/dist/core/agent/contextBudget.js +29 -0
  87. package/dist/core/agent/errors.js +6 -2
  88. package/dist/core/agent/events.d.ts +12 -0
  89. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  90. package/dist/core/agent/toolOutputStore.js +49 -11
  91. package/dist/core/agent/workState.d.ts +1 -1
  92. package/dist/core/agent/workState.js +0 -4
  93. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  94. package/dist/core/attachments/imageAttachments.js +245 -0
  95. package/dist/core/attachments/readBlessings.d.ts +37 -0
  96. package/dist/core/attachments/readBlessings.js +79 -0
  97. package/dist/core/goal/completionPolicy.d.ts +0 -28
  98. package/dist/core/goal/completionPolicy.js +0 -88
  99. package/dist/core/goal/requestClassifier.d.ts +0 -3
  100. package/dist/core/goal/requestClassifier.js +0 -13
  101. package/dist/core/io/boundedRead.d.ts +15 -0
  102. package/dist/core/io/boundedRead.js +144 -0
  103. package/dist/core/limits/byteBudgets.d.ts +18 -0
  104. package/dist/core/limits/byteBudgets.js +18 -0
  105. package/dist/core/limits/textBudgets.d.ts +23 -0
  106. package/dist/core/limits/textBudgets.js +23 -0
  107. package/dist/core/log/llmLog.d.ts +10 -0
  108. package/dist/core/log/llmLog.js +59 -13
  109. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  110. package/dist/core/persistence/orderedFileWriter.js +29 -0
  111. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  112. package/dist/core/process/backgroundRegistry.js +194 -0
  113. package/dist/core/process/runBoundedProcess.d.ts +30 -0
  114. package/dist/core/process/runBoundedProcess.js +116 -0
  115. package/dist/core/safety/urlGuard.d.ts +2 -1
  116. package/dist/core/safety/urlGuard.js +3 -2
  117. package/dist/core/session/sessionSlimming.js +47 -4
  118. package/dist/core/session/sessionStore.d.ts +37 -0
  119. package/dist/core/session/sessionStore.js +136 -27
  120. package/dist/core/subagent/contracts.d.ts +116 -0
  121. package/dist/core/subagent/contracts.js +54 -0
  122. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  123. package/dist/core/subagent/executionProfiles.js +45 -0
  124. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  125. package/dist/core/subagent/subagentCoordinator.js +134 -0
  126. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  127. package/dist/core/subagent/subagentRunner.js +228 -98
  128. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  129. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  130. package/dist/core/tasks/taskStorage.js +12 -1
  131. package/dist/llm/client.d.ts +20 -29
  132. package/dist/llm/client.js +33 -29
  133. package/dist/llm/hazeTools.d.ts +2396 -67
  134. package/dist/llm/hazeTools.js +50 -37
  135. package/dist/llm/lsp.d.ts +23 -3
  136. package/dist/llm/lsp.js +73 -16
  137. package/dist/llm/lspTools.d.ts +96 -48
  138. package/dist/llm/mcp.d.ts +1 -1
  139. package/dist/llm/mcp.js +65 -16
  140. package/dist/llm/requestContext.d.ts +23 -1
  141. package/dist/llm/requestContext.js +50 -7
  142. package/dist/llm/systemPrompt.d.ts +4 -1
  143. package/dist/llm/systemPrompt.js +14 -4
  144. package/dist/llm/toolResultTypes.d.ts +1 -1
  145. package/dist/llm/tools/bashTool.d.ts +1210 -16
  146. package/dist/llm/tools/bashTool.js +43 -60
  147. package/dist/llm/tools/fetchTool.d.ts +26 -26
  148. package/dist/llm/tools/fetchTool.js +1 -1
  149. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  150. package/dist/llm/tools/fileToolShared.js +5 -5
  151. package/dist/llm/tools/grepRunner.d.ts +20 -0
  152. package/dist/llm/tools/grepRunner.js +66 -0
  153. package/dist/llm/tools/outputCap.d.ts +2 -6
  154. package/dist/llm/tools/outputCap.js +2 -6
  155. package/dist/llm/tools/processTool.d.ts +1077 -0
  156. package/dist/llm/tools/processTool.js +41 -0
  157. package/dist/llm/tools/toolContext.d.ts +8 -0
  158. package/dist/llm/tools/toolContext.js +22 -11
  159. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  160. package/dist/llm/tools/workspaceFile.js +33 -4
  161. package/dist/llm/webFetch.js +24 -11
  162. package/dist/llm/workerContext.d.ts +18 -0
  163. package/dist/llm/workerContext.js +55 -0
  164. package/dist/skills/SkillLoader.d.ts +2 -2
  165. package/dist/skills/SkillLoader.js +17 -5
  166. package/dist/skills/SkillRegistry.d.ts +3 -2
  167. package/dist/skills/SkillRegistry.js +53 -10
  168. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  169. package/dist/skills/builder/SkillBuilder.js +23 -5
  170. package/dist/skills/skillTools.js +11 -4
  171. package/dist/skills/types.d.ts +11 -1
  172. package/dist/ui/components/TextInput.d.ts +5 -2
  173. package/dist/ui/components/TextInput.js +76 -8
  174. package/dist/utils/format.d.ts +2 -0
  175. package/dist/utils/format.js +8 -0
  176. package/dist/utils/fs.d.ts +0 -1
  177. package/dist/utils/fs.js +0 -4
  178. package/dist/utils/openPath.d.ts +2 -0
  179. package/dist/utils/openPath.js +9 -0
  180. package/dist/utils/path.d.ts +2 -0
  181. package/dist/utils/path.js +9 -4
  182. package/package.json +1 -1
@@ -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
+ }
@@ -1,30 +1,2 @@
1
- import type { SessionGoal } from './sessionGoal.js';
2
- export declare function looksIncomplete(text: string): boolean;
3
- export declare function looksTruncated(text: string): boolean;
4
- export declare function looksBlocked(text: string): boolean;
5
- export interface CompletionPolicyInput {
6
- request: string;
7
- goal: SessionGoal;
8
- assistantText: string;
9
- sawReadOnlyTool: boolean;
10
- sawToolCall: boolean;
11
- mutatingToolSucceeded: boolean;
12
- validationToolSucceeded: boolean;
13
- validationToolFailed: boolean;
14
- editFileFailed: boolean;
15
- editRecoveryPath?: string;
16
- editRecoveryReasonCode?: string;
17
- }
18
- export interface CompletionDecision {
19
- needsActionContinuation: boolean;
20
- needsValidationContinuation: boolean;
21
- requestCompletedByTools: boolean;
22
- assistantAdmitsIncomplete: boolean;
23
- assistantReportsBlocker: boolean;
24
- continuationPrompt?: string;
25
- }
26
- export declare function completionDecision(input: CompletionPolicyInput): CompletionDecision;
27
1
  export declare function toolLoopBudgetPrompt(): string;
28
2
  export declare function repeatedToolCallPrompt(toolNames: string[]): string;
29
- export declare function postContinuationPrompt(): string;
30
- export declare function noTextAfterToolPrompt(allowTools: boolean): "Continue the original request now. If it asks for a change, edit or write the necessary files. If it asks to run or verify tests, run the command. Do not provide only a retrospective summary unless blocked or needing a user decision." | "Continue from the tool result and answer my original request. Do not call tools. Use the final status template for implementation-like requests; summarize only current-turn changes and validation; do not recap unrelated earlier tasks.";
@@ -1,83 +1,3 @@
1
- import { isActionRequest, isPlanOnlyRequest, isValidationRequest } from './requestClassifier.js';
2
- export function looksIncomplete(text) {
3
- return /\b(incomplete|what remains|remains:|remaining:|next:|unfinished|not implemented|not created|no tests exist|created no docs|has not been|have not been|not yet|never executed|not executed|not run|cannot retry|cannot write|cannot validate|tool budget reached|tool slice reached)/i.test(text);
4
- }
5
- export function looksTruncated(text) {
6
- const trimmed = text.trimEnd();
7
- if (!trimmed)
8
- return false;
9
- const lines = trimmed.split('\n');
10
- const lastLine = lines[lines.length - 1].trim();
11
- if (/^#{1,6}\s+\S/.test(lastLine))
12
- return true;
13
- if (/^(-{3,}|\*{3,}|_{3,})$/.test(lastLine))
14
- return true;
15
- if (trimmed.endsWith(':'))
16
- return true;
17
- const fences = (trimmed.match(/```/g) ?? []).length;
18
- if (fences % 2 !== 0)
19
- return true;
20
- return false;
21
- }
22
- export function looksBlocked(text) {
23
- return /\b(blocked|blocker|needs user|need user|missing permission|permission denied|missing dependency|no practical validation|unable to validate|can't validate|cannot validate)\b/i.test(text);
24
- }
25
- export function completionDecision(input) {
26
- const likelyPlanOnlyRequest = isPlanOnlyRequest(input.request);
27
- const likelyActionRequest = isActionRequest(input.request);
28
- const likelyValidationRequest = isValidationRequest(input.request);
29
- const assistantAdmitsIncomplete = looksIncomplete(input.assistantText) || looksTruncated(input.assistantText);
30
- const assistantReportsBlocker = looksBlocked(input.assistantText);
31
- const requestCompletedByTools = input.mutatingToolSucceeded && input.validationToolSucceeded && !input.editRecoveryPath;
32
- const changedActionNeedsValidation = likelyActionRequest
33
- && !likelyPlanOnlyRequest
34
- && input.mutatingToolSucceeded
35
- && !input.validationToolSucceeded
36
- && !input.validationToolFailed
37
- && !input.editRecoveryPath
38
- && !assistantReportsBlocker;
39
- const needsActionContinuation = likelyActionRequest
40
- && !likelyPlanOnlyRequest
41
- && !requestCompletedByTools
42
- && ((input.sawReadOnlyTool && !input.mutatingToolSucceeded) || input.validationToolFailed || input.editFileFailed || assistantAdmitsIncomplete);
43
- const needsValidationContinuation = (likelyValidationRequest || changedActionNeedsValidation)
44
- && !requestCompletedByTools
45
- && !input.validationToolSucceeded
46
- && !assistantReportsBlocker;
47
- const stateLines = [
48
- `User goal: ${input.request}`,
49
- input.editRecoveryPath ? `Edit recovery path: ${input.editRecoveryPath}` : undefined,
50
- input.editRecoveryReasonCode ? `Edit failure reason: ${input.editRecoveryReasonCode}` : undefined,
51
- input.mutatingToolSucceeded ? 'Files changed in this turn: yes' : 'Files changed in this turn: no',
52
- input.validationToolSucceeded ? 'Validation status: passed' : input.validationToolFailed ? 'Validation status: failed' : 'Validation status: not run',
53
- ].filter((line) => line !== undefined).join('\n');
54
- let continuationPrompt;
55
- if (input.editFileFailed) {
56
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: call readFile on the exact edit recovery path first. Then use the latest line-numbered output with replaceLines, or a corrected editFile call, to complete the requested change. Continue with relevant validation if practical. Do not stop with a summary while tools are available.`;
57
- }
58
- else if (input.validationToolFailed && input.mutatingToolSucceeded) {
59
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: Validation failed after files changed in this task. Use the validation summary/output to inspect the first relevant failure, make one focused fix if it is plausibly caused by this change, then rerun the same relevant validation once. If it is an environment/dependency/unrelated failure, finish with Status: blocked or Status: partial and concrete evidence.`;
60
- }
61
- else if (needsValidationContinuation) {
62
- continuationPrompt = changedActionNeedsValidation
63
- ? `State:\n${stateLines}\n\nRequired next action: files changed for this request, but no validation has run. Run the smallest relevant test/typecheck/build command you can identify. If no practical validation exists, finish with the final status template and say why validation was not run.`
64
- : `State:\n${stateLines}\n\nRequired next action: run the requested validation now. Summarize only after the command finishes.`;
65
- }
66
- else if (input.mutatingToolSucceeded && assistantAdmitsIncomplete) {
67
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: your previous response described unfinished work. Continue with the remaining in-scope edits and validation for this same request. Do not summarize a plan unless concretely blocked.`;
68
- }
69
- else if (needsActionContinuation) {
70
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: you inspected files but have not made the requested change yet. Edit or write the necessary files now. Do not summarize a plan unless concretely blocked.`;
71
- }
72
- return {
73
- needsActionContinuation,
74
- needsValidationContinuation,
75
- requestCompletedByTools,
76
- assistantAdmitsIncomplete,
77
- assistantReportsBlocker,
78
- continuationPrompt,
79
- };
80
- }
81
1
  export function toolLoopBudgetPrompt() {
82
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.';
83
3
  }
@@ -85,11 +5,3 @@ export function repeatedToolCallPrompt(toolNames) {
85
5
  const names = [...new Set(toolNames)].join(', ');
86
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.`;
87
7
  }
88
- export function postContinuationPrompt() {
89
- return 'Your previous response still described unfinished work, missing validation, or a tool-budget issue. If tools are available, complete the remaining edit or run the final validation now. Only call something blocked for a concrete tool failure, missing dependency/permission, or unavoidable ambiguity.';
90
- }
91
- export function noTextAfterToolPrompt(allowTools) {
92
- return allowTools
93
- ? 'Continue the original request now. If it asks for a change, edit or write the necessary files. If it asks to run or verify tests, run the command. Do not provide only a retrospective summary unless blocked or needing a user decision.'
94
- : 'Continue from the tool result and answer my original request. Do not call tools. Use the final status template for implementation-like requests; summarize only current-turn changes and validation; do not recap unrelated earlier tasks.';
95
- }
@@ -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';
@@ -0,0 +1,15 @@
1
+ export interface BoundedUtf8Line {
2
+ line: string;
3
+ lineNumber: number;
4
+ oversized: boolean;
5
+ }
6
+ export declare function iterateBoundedUtf8Lines(file: string, maxLineBytes: number): AsyncGenerator<BoundedUtf8Line>;
7
+ export declare function readUtf8LinesPage(file: string, offset: number, limit: number): Promise<{
8
+ lines: string[];
9
+ totalLines: number;
10
+ }>;
11
+ export declare function readUtf8Prefix(file: string, maxBytes: number): Promise<{
12
+ content: string;
13
+ truncated: boolean;
14
+ totalBytes: number;
15
+ }>;