@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
@@ -1,5 +1,25 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
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.
7
+ if (child.pid == null) {
8
+ child.kill(signal);
9
+ return;
10
+ }
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();
14
+ return;
15
+ }
16
+ try {
17
+ process.kill(-child.pid, signal);
18
+ }
19
+ catch {
20
+ child.kill(signal);
21
+ }
22
+ }
3
23
  function collector(limit) {
4
24
  const chunks = [];
5
25
  let totalBytes = 0;
@@ -8,6 +28,8 @@ function collector(limit) {
8
28
  add(chunk) {
9
29
  totalBytes += chunk.length;
10
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.
11
33
  if (remaining > 0) {
12
34
  const kept = chunk.subarray(0, remaining);
13
35
  chunks.push(kept);
@@ -34,34 +56,10 @@ export async function runBoundedProcess(input) {
34
56
  let aborted = false;
35
57
  let forced = false;
36
58
  let killTimer;
37
- const killTree = (signal) => {
38
- if (child.pid == null)
39
- return;
40
- if (process.platform === 'win32') {
41
- if (signal === 'SIGKILL')
42
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
43
- else
44
- child.kill('SIGTERM');
45
- }
46
- else {
47
- try {
48
- process.kill(-child.pid, signal);
49
- }
50
- catch {
51
- child.kill(signal);
52
- }
53
- }
54
- };
55
- const terminate = () => {
56
- killTree('SIGTERM');
57
- killTimer ??= setTimeout(() => { forced = true; killTree('SIGKILL'); }, input.killGraceMs ?? 500);
58
- killTimer.unref?.();
59
- };
60
- const timeout = setTimeout(() => { timedOut = true; terminate(); }, input.timeoutMs);
61
- const onAbort = () => { aborted = true; terminate(); };
62
- input.signal?.addEventListener('abort', onAbort, { once: true });
63
- child.stdout.on('data', (chunk) => stdout.add(chunk));
64
- child.stderr.on('data', (chunk) => stderr.add(chunk));
59
+ let closeTimer;
60
+ let terminating = false;
61
+ let exitCode = null;
62
+ let exitSignal = null;
65
63
  return await new Promise(resolve => {
66
64
  let settled = false;
67
65
  const settle = (code, signal, error) => {
@@ -71,10 +69,57 @@ export async function runBoundedProcess(input) {
71
69
  clearTimeout(timeout);
72
70
  if (killTimer)
73
71
  clearTimeout(killTimer);
72
+ if (closeTimer)
73
+ clearTimeout(closeTimer);
74
74
  input.signal?.removeEventListener('abort', onAbort);
75
- resolve({ code, signal, stdout: stdout.result(), stderr: stderr.result(), timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
75
+ child.stdout.off('data', stdoutData);
76
+ child.stderr.off('data', stderrData);
77
+ const stdoutResult = stdout.result();
78
+ const stderrResult = stderr.result();
79
+ child.stdout.destroy();
80
+ child.stderr.destroy();
81
+ resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
82
+ };
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.
90
+ closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
91
+ closeTimer.unref?.();
92
+ };
93
+ const terminate = () => {
94
+ if (terminating || settled)
95
+ return;
96
+ terminating = true;
97
+ killTree('SIGTERM');
98
+ killTimer = setTimeout(() => {
99
+ forced = true;
100
+ killTree('SIGKILL');
101
+ scheduleCloseFallback();
102
+ }, input.killGraceMs ?? 500);
103
+ killTimer.unref?.();
104
+ };
105
+ const timeout = setTimeout(() => { timedOut = true; terminate(); }, input.timeoutMs);
106
+ const onAbort = () => { aborted = true; terminate(); };
107
+ input.signal?.addEventListener('abort', onAbort, { once: true });
108
+ const killTree = (signal) => signalProcessTree(child, signal);
109
+ const stdoutData = (chunk) => {
110
+ stdout.add(chunk);
111
+ // Streaming interceptors (e.g. grep's early-stop) may request termination.
112
+ if (!terminating && input.onStdoutChunk?.(chunk))
113
+ terminate();
76
114
  };
115
+ const stderrData = (chunk) => stderr.add(chunk);
116
+ child.stdout.on('data', stdoutData);
117
+ child.stderr.on('data', stderrData);
77
118
  child.once('error', error => settle(null, null, error.message));
119
+ child.once('exit', (code, signal) => {
120
+ exitCode = code;
121
+ exitSignal = signal;
122
+ });
78
123
  child.once('close', (code, signal) => settle(code, signal));
79
124
  });
80
125
  }
@@ -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
+ }
@@ -21,7 +21,8 @@ export type UrlValidation = {
21
21
  export type DnsLookupFn = (hostname: string) => Promise<string[]>;
22
22
  /**
23
23
  * Check whether a literal IP address (v4 or v6) is in a blocked range.
24
- * Returns false for non-IP strings (hostnames are resolved separately).
24
+ * Returns false for ordinary non-IP strings. Colon-shaped malformed IPv6 is
25
+ * blocked fail-closed because callers treat such hosts as literal addresses.
25
26
  */
26
27
  export declare function isBlockedIp(ip: string): boolean;
27
28
  /**
@@ -116,7 +116,7 @@ function ipv6InBlockedRange(ip) {
116
116
  num = ipv6ToBigInt(ip);
117
117
  }
118
118
  catch {
119
- return false;
119
+ return true;
120
120
  }
121
121
  for (const range of BLOCKED_IPV6_CIDRS) {
122
122
  if ((num & range.mask) === range.start)
@@ -126,7 +126,8 @@ function ipv6InBlockedRange(ip) {
126
126
  }
127
127
  /**
128
128
  * Check whether a literal IP address (v4 or v6) is in a blocked range.
129
- * Returns false for non-IP strings (hostnames are resolved separately).
129
+ * Returns false for ordinary non-IP strings. Colon-shaped malformed IPv6 is
130
+ * blocked fail-closed because callers treat such hosts as literal addresses.
130
131
  */
131
132
  export function isBlockedIp(ip) {
132
133
  // Strip IPv6 bracket form for literal checks.
@@ -1,6 +1,6 @@
1
- const INLINE_VALUE_BYTES = 32 * 1024;
2
- const PREVIEW_CHARS = 4 * 1024;
3
- const LARGE_STRING_CHARS = 8 * 1024;
1
+ import { SESSION_INLINE_VALUE_BYTES as INLINE_VALUE_BYTES, SESSION_LARGE_STRING_CHARS as LARGE_STRING_CHARS, SESSION_PREVIEW_CHARS as PREVIEW_CHARS } from '../limits/textBudgets.js';
2
+ import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
3
+ import { formatBytes } from '../../utils/format.js';
4
4
  function jsonByteLength(value) {
5
5
  try {
6
6
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
@@ -24,6 +24,19 @@ function slimLargeValue(value) {
24
24
  preview: previewText(value),
25
25
  };
26
26
  }
27
+ /**
28
+ * Image file parts become text placeholders (F03): resumed sessions must not
29
+ * replay megabytes of base64, and the placeholder stays a protocol-safe
30
+ * ModelMessage part for any provider. The model re-asks if it needs the image.
31
+ */
32
+ function slimImageFilePart(part) {
33
+ const bytes = imageFilePartBytes(part.data);
34
+ const name = typeof part.filename === 'string' && part.filename ? ` ${part.filename}` : '';
35
+ return {
36
+ type: 'text',
37
+ text: `[image omitted from session:${name} ${part.mediaType}, ${formatBytes(bytes)} — ask the user to re-attach it if needed]`,
38
+ };
39
+ }
27
40
  function slimUnknown(value, seen = new WeakSet()) {
28
41
  if (typeof value === 'string') {
29
42
  if (value.length <= LARGE_STRING_CHARS)
@@ -38,6 +51,8 @@ function slimUnknown(value, seen = new WeakSet()) {
38
51
  if (Array.isArray(value))
39
52
  return value.map(item => slimUnknown(item, seen));
40
53
  const record = value;
54
+ if (isImageFilePart(record))
55
+ return slimImageFilePart(record);
41
56
  if (record.type === 'tool-result') {
42
57
  return {
43
58
  ...record,
@@ -53,14 +68,42 @@ function slimUnknown(value, seen = new WeakSet()) {
53
68
  export function slimConversationSnapshot(messages) {
54
69
  return slimUnknown(messages);
55
70
  }
71
+ function slimToolStartInput(input) {
72
+ // Full tool inputs (writeFile/editFile payloads can be tens of KB) are replaced
73
+ // with byte counts; raw inputs stay only in opt-in --debug LLM logs (CR-031).
74
+ const slimmed = { inputBytes: jsonByteLength(input) };
75
+ if (typeof input === 'object' && input != null && typeof input.path === 'string') {
76
+ slimmed.path = input.path;
77
+ }
78
+ return slimmed;
79
+ }
56
80
  export function prepareSessionEntryForWrite(entry) {
57
81
  if (entry.type === 'event') {
58
82
  if (entry.name === 'message_update')
59
83
  return undefined;
84
+ if (entry.name === 'tool_start' && entry.text) {
85
+ try {
86
+ const event = JSON.parse(entry.text);
87
+ event.input = slimToolStartInput(event.input);
88
+ return { ...entry, text: JSON.stringify(event) };
89
+ }
90
+ catch {
91
+ return entry;
92
+ }
93
+ }
60
94
  if (entry.name === 'tool_end' && entry.text) {
61
95
  try {
62
96
  const event = JSON.parse(entry.text);
63
- event.output = slimLargeValue(event.output);
97
+ if (event.name === 'subagent' && typeof event.output === 'object' && event.output != null) {
98
+ const output = event.output;
99
+ const telemetry = typeof output.telemetry === 'object' && output.telemetry != null ? output.telemetry : undefined;
100
+ event.output = {
101
+ capsule: output.capsule,
102
+ coordinator: telemetry ? { modelSelector: telemetry.modelSelector, profile: telemetry.profile, durationMs: telemetry.durationMs, queueMs: telemetry.queueMs, toolCallCount: telemetry.toolCallCount } : undefined,
103
+ };
104
+ }
105
+ else
106
+ event.output = slimLargeValue(event.output);
64
107
  event.error = slimLargeValue(event.error);
65
108
  return { ...entry, text: JSON.stringify(event) };
66
109
  }
@@ -6,6 +6,11 @@ export type SessionEntry = {
6
6
  cwd: string;
7
7
  createdAt: string;
8
8
  hazeVersion?: string;
9
+ forkedFrom?: string;
10
+ build?: {
11
+ commit?: string;
12
+ builtAt?: string;
13
+ };
9
14
  } | {
10
15
  type: 'ui_message';
11
16
  at: string;
@@ -25,18 +30,46 @@ export type SessionEntry = {
25
30
  name: string;
26
31
  text?: string;
27
32
  };
33
+ type SessionHeader = Extract<SessionEntry, {
34
+ type: 'header';
35
+ }>;
36
+ type DeferredSessionWrite = {
37
+ header: SessionHeader;
38
+ entries: SessionEntry[];
39
+ };
28
40
  export interface HazeSession {
29
41
  id: string;
30
42
  file: string;
31
43
  cwd: string;
44
+ /** New sessions stay memory-only until they contain a resumable message. */
45
+ deferredWrite?: DeferredSessionWrite;
32
46
  }
33
47
  export declare function createSession(options?: {
34
48
  cwd?: string;
35
49
  hazeVersion?: string;
36
50
  sessionsDir?: string;
51
+ forkedFrom?: string;
52
+ build?: {
53
+ commit?: string;
54
+ builtAt?: string;
55
+ };
37
56
  }): Promise<HazeSession>;
57
+ export declare function findSession(id: string, cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
38
58
  export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
39
59
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
60
+ /**
61
+ * Session files rewrite their full conversation history per turn, so a long
62
+ * session grows quadratically: N tokens of final history cost O(turns ×
63
+ * history) bytes on disk (F-03). Once superseded snapshots dominate the file,
64
+ * rewrite it keeping only the newest conversation/work-state snapshot plus
65
+ * every non-snapshot entry (restore reads only the newest snapshot of each
66
+ * type, so dropping superseded ones is lossless for restore; summaries keep
67
+ * their ui_message/event history). Atomic replace, never partial.
68
+ */
69
+ export declare const SESSION_VACUUM_THRESHOLD_BYTES: number;
70
+ /** Test-only override for the vacuum trigger; tests restore the original. */
71
+ export declare function setSessionVacuumThresholdForTests(bytes: number): void;
72
+ export declare function vacuumSessionFileIfLarge(session: HazeSession, thresholdBytes?: number): Promise<boolean>;
40
73
  export interface ReadSessionEntriesResult {
41
74
  entries: SessionEntry[];
42
75
  /** Per-line parse failures, e.g. `Line 3: Unexpected token...`. Empty when every line parsed. */
@@ -54,10 +87,51 @@ export interface RestoreConversationResult {
54
87
  messages: ModelMessage[];
55
88
  parseErrors: string[];
56
89
  }
90
+ export interface RestoreSessionStateResult {
91
+ messages: ModelMessage[];
92
+ workState: WorkState | undefined;
93
+ parseErrors: string[];
94
+ }
95
+ /**
96
+ * Restore conversation and work state in one file scan (CR-013). Session
97
+ * files grow to megabytes in long workspaces; resuming should not parse the
98
+ * JSONL twice.
99
+ */
100
+ export declare function restoreSessionState(session: HazeSession): Promise<RestoreSessionStateResult>;
57
101
  export declare function restoreConversation(session: HazeSession): Promise<RestoreConversationResult>;
58
102
  export interface RestoreWorkStateResult {
59
103
  state: WorkState | undefined;
60
104
  parseErrors: string[];
61
105
  }
62
106
  export declare function restoreWorkState(session: HazeSession): Promise<RestoreWorkStateResult>;
107
+ /** Acceptance budget for listing 50 ordinary workspace sessions. */
108
+ export declare const SESSION_LIST_LATENCY_BUDGET_MS = 2000;
109
+ export interface SessionSummary {
110
+ id: string;
111
+ createdAt: string;
112
+ lastActivityAt: string;
113
+ messageCount: number;
114
+ firstUserPreview: string;
115
+ sizeBytes: number;
116
+ lastStatus?: string;
117
+ parseErrors: string[];
118
+ }
119
+ /** Test-only reset for the process-scoped session-summary cache. */
120
+ export declare function clearSessionSummaryCacheForTests(): void;
121
+ /** List this workspace's sessions newest-first while retaining only summary state per file. */
122
+ export declare function listSessions(cwd?: string, sessionsDir?: string): Promise<SessionSummary[]>;
123
+ export interface ForkSessionResult {
124
+ session: HazeSession;
125
+ parseErrors: string[];
126
+ }
127
+ /** Create a new session from the source's latest durable snapshots without mutating it. */
128
+ export declare function forkSession(source: HazeSession, options?: {
129
+ hazeVersion?: string;
130
+ sessionsDir?: string;
131
+ build?: {
132
+ commit?: string;
133
+ builtAt?: string;
134
+ };
135
+ }): Promise<ForkSessionResult>;
63
136
  export declare function formatSession(session: HazeSession): string;
137
+ export {};