@denizokcu/haze 0.9.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 (158) hide show
  1. package/CHANGELOG.md +57 -17
  2. package/README.md +119 -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.js +7 -9
  14. package/dist/cli/chat/startupInfo.d.ts +1 -0
  15. package/dist/cli/chat/startupInfo.js +11 -0
  16. package/dist/cli/chat/tips.d.ts +21 -0
  17. package/dist/cli/chat/tips.js +43 -0
  18. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  19. package/dist/cli/chat/wizardDispatch.js +645 -0
  20. package/dist/cli/commands/chat.d.ts +1 -0
  21. package/dist/cli/commands/chat.js +181 -700
  22. package/dist/cli/commands/chatModes.d.ts +1 -1
  23. package/dist/cli/commands/chatModes.js +7 -2
  24. package/dist/cli/commands/commandHelp.js +5 -3
  25. package/dist/cli/commands/commands.d.ts +3 -2
  26. package/dist/cli/commands/commands.js +12 -13
  27. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  28. package/dist/cli/commands/fleetCommand.js +46 -0
  29. package/dist/cli/commands/formatters.d.ts +5 -0
  30. package/dist/cli/commands/formatters.js +33 -6
  31. package/dist/cli/commands/logsCommand.js +1 -7
  32. package/dist/cli/commands/modelCommand.js +1 -1
  33. package/dist/cli/commands/providerWizard.d.ts +1 -0
  34. package/dist/cli/commands/providerWizard.js +13 -0
  35. package/dist/cli/commands/runCommand.d.ts +1 -0
  36. package/dist/cli/commands/runCommand.js +25 -5
  37. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  38. package/dist/cli/commands/sessionPicker.js +29 -0
  39. package/dist/cli/commands/settingsSummary.js +6 -4
  40. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  41. package/dist/cli/commands/skillWizard.d.ts +2 -0
  42. package/dist/cli/commands/skillWizard.js +16 -6
  43. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  44. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  45. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  46. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  47. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  48. package/dist/cli/commands/streaming.d.ts +13 -1
  49. package/dist/cli/commands/streaming.js +42 -19
  50. package/dist/cli/commands/wizardActions.d.ts +6 -0
  51. package/dist/cli/commands/wizardActions.js +6 -0
  52. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  53. package/dist/cli/commands/wizardSuggestions.js +60 -12
  54. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  55. package/dist/cli/commands/wizardTransition.js +1 -2
  56. package/dist/cli/index.js +17 -3
  57. package/dist/cli/terminalTitle.d.ts +6 -0
  58. package/dist/cli/terminalTitle.js +36 -0
  59. package/dist/config/inputHistory.d.ts +3 -3
  60. package/dist/config/inputHistory.js +12 -18
  61. package/dist/config/modelDiscovery.d.ts +20 -0
  62. package/dist/config/modelDiscovery.js +51 -0
  63. package/dist/config/providerPresets.d.ts +16 -4
  64. package/dist/config/providerPresets.js +263 -34
  65. package/dist/config/providers.d.ts +2 -0
  66. package/dist/config/providers.js +7 -0
  67. package/dist/config/settings.d.ts +22 -0
  68. package/dist/config/settings.js +29 -1
  69. package/dist/config/skillSettings.d.ts +6 -13
  70. package/dist/config/skillSettings.js +20 -19
  71. package/dist/core/agent/budgets.d.ts +26 -0
  72. package/dist/core/agent/budgets.js +34 -0
  73. package/dist/core/agent/compaction.js +17 -3
  74. package/dist/core/agent/contextBudget.d.ts +8 -0
  75. package/dist/core/agent/contextBudget.js +29 -0
  76. package/dist/core/agent/errors.js +6 -2
  77. package/dist/core/agent/events.d.ts +12 -0
  78. package/dist/core/agent/toolOutputStore.d.ts +5 -0
  79. package/dist/core/agent/toolOutputStore.js +18 -1
  80. package/dist/core/agent/workState.d.ts +1 -1
  81. package/dist/core/agent/workState.js +0 -4
  82. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  83. package/dist/core/attachments/imageAttachments.js +245 -0
  84. package/dist/core/attachments/readBlessings.d.ts +37 -0
  85. package/dist/core/attachments/readBlessings.js +79 -0
  86. package/dist/core/goal/requestClassifier.d.ts +0 -3
  87. package/dist/core/goal/requestClassifier.js +0 -13
  88. package/dist/core/io/boundedRead.js +76 -29
  89. package/dist/core/limits/byteBudgets.d.ts +5 -0
  90. package/dist/core/limits/byteBudgets.js +5 -0
  91. package/dist/core/limits/textBudgets.d.ts +23 -0
  92. package/dist/core/limits/textBudgets.js +23 -0
  93. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  94. package/dist/core/process/backgroundRegistry.js +194 -0
  95. package/dist/core/process/runBoundedProcess.d.ts +3 -0
  96. package/dist/core/process/runBoundedProcess.js +65 -29
  97. package/dist/core/safety/urlGuard.d.ts +2 -1
  98. package/dist/core/safety/urlGuard.js +3 -2
  99. package/dist/core/session/sessionSlimming.js +47 -4
  100. package/dist/core/session/sessionStore.d.ts +37 -0
  101. package/dist/core/session/sessionStore.js +95 -9
  102. package/dist/core/subagent/contracts.d.ts +116 -0
  103. package/dist/core/subagent/contracts.js +54 -0
  104. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  105. package/dist/core/subagent/executionProfiles.js +45 -0
  106. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  107. package/dist/core/subagent/subagentCoordinator.js +134 -0
  108. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  109. package/dist/core/subagent/subagentRunner.js +228 -98
  110. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  111. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  112. package/dist/core/tasks/taskStorage.js +12 -1
  113. package/dist/llm/client.d.ts +20 -29
  114. package/dist/llm/client.js +29 -28
  115. package/dist/llm/hazeTools.d.ts +2013 -78
  116. package/dist/llm/hazeTools.js +16 -7
  117. package/dist/llm/lsp.d.ts +2 -0
  118. package/dist/llm/lsp.js +18 -3
  119. package/dist/llm/requestContext.d.ts +22 -1
  120. package/dist/llm/requestContext.js +45 -5
  121. package/dist/llm/systemPrompt.d.ts +4 -1
  122. package/dist/llm/systemPrompt.js +14 -4
  123. package/dist/llm/toolResultTypes.d.ts +1 -1
  124. package/dist/llm/tools/bashTool.d.ts +874 -32
  125. package/dist/llm/tools/bashTool.js +25 -4
  126. package/dist/llm/tools/fetchTool.d.ts +26 -26
  127. package/dist/llm/tools/fetchTool.js +1 -1
  128. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  129. package/dist/llm/tools/fileToolShared.js +5 -5
  130. package/dist/llm/tools/grepRunner.d.ts +5 -0
  131. package/dist/llm/tools/grepRunner.js +52 -71
  132. package/dist/llm/tools/outputCap.d.ts +2 -6
  133. package/dist/llm/tools/outputCap.js +2 -6
  134. package/dist/llm/tools/processTool.d.ts +1077 -0
  135. package/dist/llm/tools/processTool.js +41 -0
  136. package/dist/llm/tools/toolContext.d.ts +8 -0
  137. package/dist/llm/tools/toolContext.js +22 -11
  138. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  139. package/dist/llm/tools/workspaceFile.js +33 -4
  140. package/dist/llm/webFetch.js +24 -11
  141. package/dist/llm/workerContext.d.ts +18 -0
  142. package/dist/llm/workerContext.js +55 -0
  143. package/dist/skills/SkillLoader.d.ts +2 -2
  144. package/dist/skills/SkillRegistry.d.ts +3 -2
  145. package/dist/skills/SkillRegistry.js +43 -13
  146. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  147. package/dist/skills/builder/SkillBuilder.js +23 -5
  148. package/dist/skills/skillTools.js +11 -4
  149. package/dist/skills/types.d.ts +6 -1
  150. package/dist/ui/components/TextInput.d.ts +5 -2
  151. package/dist/ui/components/TextInput.js +76 -8
  152. package/dist/utils/format.d.ts +2 -0
  153. package/dist/utils/format.js +8 -0
  154. package/dist/utils/fs.d.ts +0 -1
  155. package/dist/utils/fs.js +0 -4
  156. package/dist/utils/openPath.d.ts +2 -0
  157. package/dist/utils/openPath.js +9 -0
  158. package/package.json +1 -1
@@ -0,0 +1,194 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ import { BACKGROUND_PROCESS_HISTORY_LIMIT, BACKGROUND_PROCESS_MAX_CONCURRENCY } from '../agent/budgets.js';
4
+ import { registerDynamicToolOutput, unregisterDynamicToolOutput } from '../agent/toolOutputStore.js';
5
+ import { BACKGROUND_PROCESS_OUTPUT_BYTES } from '../limits/byteBudgets.js';
6
+ import { signalProcessTree } from './runBoundedProcess.js';
7
+ class OutputRing {
8
+ decoder = new StringDecoder('utf8');
9
+ retained = Buffer.alloc(0);
10
+ totalBytes = 0;
11
+ appendText(completeText) {
12
+ if (!completeText)
13
+ return;
14
+ const bytes = Buffer.from(completeText, 'utf8');
15
+ this.retained = this.retained.length === 0 ? bytes : Buffer.concat([this.retained, bytes]);
16
+ if (this.retained.length > BACKGROUND_PROCESS_OUTPUT_BYTES) {
17
+ let start = this.retained.length - BACKGROUND_PROCESS_OUTPUT_BYTES;
18
+ while (start < this.retained.length && (this.retained[start] & 0xc0) === 0x80)
19
+ start++;
20
+ this.retained = this.retained.subarray(start);
21
+ }
22
+ }
23
+ add(chunk) {
24
+ this.totalBytes += chunk.length;
25
+ this.appendText(this.decoder.write(chunk));
26
+ }
27
+ end() {
28
+ this.appendText(this.decoder.end());
29
+ }
30
+ snapshot() {
31
+ return { content: this.retained.toString('utf8'), totalBytes: this.totalBytes };
32
+ }
33
+ stats() {
34
+ return { totalBytes: this.totalBytes, retainedBytes: this.retained.length, omittedBytes: Math.max(0, this.totalBytes - this.retained.length) };
35
+ }
36
+ }
37
+ const records = new Map();
38
+ const listeners = new Set();
39
+ let nextId = 1;
40
+ let exitHookInstalled = false;
41
+ function notify() {
42
+ for (const listener of listeners)
43
+ listener();
44
+ }
45
+ function installExitHook() {
46
+ if (exitHookInstalled)
47
+ return;
48
+ exitHookInstalled = true;
49
+ process.once('exit', terminateBackgroundProcessesSync);
50
+ }
51
+ function activeRecords() {
52
+ return [...records.values()].filter(record => record.summary.status === 'running');
53
+ }
54
+ function pruneCompletedRecords() {
55
+ const completed = [...records.values()].filter(record => record.summary.status !== 'running');
56
+ for (const record of completed.slice(0, Math.max(0, completed.length - BACKGROUND_PROCESS_HISTORY_LIMIT))) {
57
+ records.delete(record.summary.backgroundId);
58
+ unregisterDynamicToolOutput(record.summary.outputHandle);
59
+ }
60
+ }
61
+ function publicSummary(record) {
62
+ return { ...record.summary, outputBytes: record.ring.stats() };
63
+ }
64
+ export function backgroundProcessCount() {
65
+ return activeRecords().length;
66
+ }
67
+ export function subscribeBackgroundProcesses(listener) {
68
+ listeners.add(listener);
69
+ return () => { listeners.delete(listener); };
70
+ }
71
+ export function listBackgroundProcesses() {
72
+ return [...records.values()].map(publicSummary);
73
+ }
74
+ export function getBackgroundProcess(backgroundId) {
75
+ const record = records.get(backgroundId);
76
+ return record ? publicSummary(record) : undefined;
77
+ }
78
+ export function startBackgroundProcess(input) {
79
+ if (activeRecords().length >= BACKGROUND_PROCESS_MAX_CONCURRENCY) {
80
+ throw new Error(`Background process limit reached (${BACKGROUND_PROCESS_MAX_CONCURRENCY}). Kill an existing process with process action=kill, then retry.`);
81
+ }
82
+ installExitHook();
83
+ const backgroundId = `background-${nextId++}`;
84
+ const child = spawn('bash', ['-lc', input.command], {
85
+ cwd: input.cwd,
86
+ detached: process.platform !== 'win32',
87
+ stdio: ['ignore', 'pipe', 'pipe'],
88
+ });
89
+ const ring = new OutputRing();
90
+ const outputHandle = registerDynamicToolOutput(() => ring.snapshot());
91
+ const summary = {
92
+ backgroundId,
93
+ ...(child.pid == null ? {} : { pid: child.pid }),
94
+ command: input.command,
95
+ cwd: input.cwd,
96
+ startedAt: new Date().toISOString(),
97
+ status: 'running',
98
+ outputHandle,
99
+ };
100
+ const record = { child, ring, closed: false, summary };
101
+ records.set(backgroundId, record);
102
+ child.stdout?.on('data', (chunk) => ring.add(chunk));
103
+ child.stderr?.on('data', (chunk) => ring.add(chunk));
104
+ child.once('error', error => {
105
+ summary.status = 'failed';
106
+ summary.error = error.message;
107
+ notify();
108
+ });
109
+ child.once('close', (code, signal) => {
110
+ record.closed = true;
111
+ ring.end();
112
+ summary.code = code;
113
+ summary.signal = signal;
114
+ if (summary.status === 'running')
115
+ summary.status = 'exited';
116
+ child.stdout?.destroy();
117
+ child.stderr?.destroy();
118
+ pruneCompletedRecords();
119
+ notify();
120
+ });
121
+ notify();
122
+ return publicSummary(record);
123
+ }
124
+ function waitForClose(record, timeoutMs) {
125
+ if (record.closed)
126
+ return Promise.resolve(true);
127
+ return new Promise(resolve => {
128
+ const timeout = setTimeout(() => { cleanup(); resolve(false); }, timeoutMs);
129
+ timeout.unref?.();
130
+ const onClose = () => { cleanup(); resolve(true); };
131
+ const cleanup = () => { clearTimeout(timeout); record.child.off('close', onClose); };
132
+ record.child.once('close', onClose);
133
+ });
134
+ }
135
+ export async function killBackgroundProcess(backgroundId, killGraceMs = 500) {
136
+ const record = records.get(backgroundId);
137
+ if (!record)
138
+ return undefined;
139
+ if (record.summary.status !== 'running')
140
+ return publicSummary(record);
141
+ signalProcessTree(record.child, 'SIGTERM');
142
+ let closed = await waitForClose(record, killGraceMs);
143
+ if (!closed) {
144
+ signalProcessTree(record.child, 'SIGKILL');
145
+ closed = await waitForClose(record, 100);
146
+ record.child.stdout?.destroy();
147
+ record.child.stderr?.destroy();
148
+ }
149
+ const terminated = closed || record.child.exitCode != null || record.child.signalCode != null;
150
+ if (terminated)
151
+ record.summary.status = 'killed';
152
+ else
153
+ record.summary.error = `Failed to terminate process tree for ${backgroundId}.`;
154
+ notify();
155
+ return publicSummary(record);
156
+ }
157
+ /** Terminate every owned tree and clear the session-local registry and handles. */
158
+ export async function teardownBackgroundProcesses(killGraceMs = 500) {
159
+ const active = activeRecords();
160
+ const results = await Promise.all(active.map(record => killBackgroundProcess(record.summary.backgroundId, killGraceMs)));
161
+ const tornDown = results.filter((result) => result != null);
162
+ const failures = tornDown.filter(result => result.status !== 'killed');
163
+ if (failures.length > 0)
164
+ throw new Error(`Failed to terminate background processes: ${failures.map(result => result.backgroundId).join(', ')}.`);
165
+ for (const record of records.values())
166
+ unregisterDynamicToolOutput(record.summary.outputHandle);
167
+ records.clear();
168
+ notify();
169
+ return tornDown;
170
+ }
171
+ let signalHandlersInstalled = false;
172
+ /** Install CLI-level abnormal-exit teardown for SIGINT and SIGTERM. */
173
+ export function installBackgroundProcessSignalHandlers() {
174
+ if (signalHandlersInstalled)
175
+ return;
176
+ signalHandlersInstalled = true;
177
+ const handle = (signal, exitCode) => {
178
+ process.once(signal, () => {
179
+ void teardownBackgroundProcesses(200).finally(() => process.exit(exitCode));
180
+ });
181
+ };
182
+ handle('SIGINT', 130);
183
+ handle('SIGTERM', 143);
184
+ }
185
+ /** Best-effort synchronous safety net for process.exit and otherwise unawaitable exits. */
186
+ export function terminateBackgroundProcessesSync() {
187
+ for (const record of activeRecords())
188
+ signalProcessTree(record.child, 'SIGTERM');
189
+ }
190
+ /** Test-only reset; callers should normally use teardownBackgroundProcesses. */
191
+ export async function resetBackgroundProcessesForTests() {
192
+ await teardownBackgroundProcesses(25);
193
+ nextId = 1;
194
+ }
@@ -1,3 +1,4 @@
1
+ import { type ChildProcess } from 'node:child_process';
1
2
  export interface BoundedStream {
2
3
  text: string;
3
4
  totalBytes: number;
@@ -15,6 +16,7 @@ export interface BoundedProcessResult {
15
16
  durationMs: number;
16
17
  error?: string;
17
18
  }
19
+ export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals): void;
18
20
  export declare function runBoundedProcess(input: {
19
21
  command: string;
20
22
  args: string[];
@@ -24,4 +26,5 @@ export declare function runBoundedProcess(input: {
24
26
  maxStdoutBytes: number;
25
27
  maxStderrBytes: number;
26
28
  killGraceMs?: number;
29
+ onStdoutChunk?: (chunk: Buffer) => boolean | void;
27
30
  }): Promise<BoundedProcessResult>;
@@ -1,5 +1,24 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
+ export function signalProcessTree(child, signal) {
4
+ if (child.pid == null) {
5
+ child.kill(signal);
6
+ return;
7
+ }
8
+ if (process.platform === 'win32') {
9
+ if (signal === 'SIGKILL')
10
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
11
+ else
12
+ child.kill('SIGTERM');
13
+ return;
14
+ }
15
+ try {
16
+ process.kill(-child.pid, signal);
17
+ }
18
+ catch {
19
+ child.kill(signal);
20
+ }
21
+ }
3
22
  function collector(limit) {
4
23
  const chunks = [];
5
24
  let totalBytes = 0;
@@ -34,34 +53,10 @@ export async function runBoundedProcess(input) {
34
53
  let aborted = false;
35
54
  let forced = false;
36
55
  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));
56
+ let closeTimer;
57
+ let terminating = false;
58
+ let exitCode = null;
59
+ let exitSignal = null;
65
60
  return await new Promise(resolve => {
66
61
  let settled = false;
67
62
  const settle = (code, signal, error) => {
@@ -71,10 +66,51 @@ export async function runBoundedProcess(input) {
71
66
  clearTimeout(timeout);
72
67
  if (killTimer)
73
68
  clearTimeout(killTimer);
69
+ if (closeTimer)
70
+ clearTimeout(closeTimer);
74
71
  input.signal?.removeEventListener('abort', onAbort);
75
- resolve({ code, signal, stdout: stdout.result(), stderr: stderr.result(), timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
72
+ child.stdout.off('data', stdoutData);
73
+ child.stderr.off('data', stderrData);
74
+ const stdoutResult = stdout.result();
75
+ const stderrResult = stderr.result();
76
+ child.stdout.destroy();
77
+ child.stderr.destroy();
78
+ resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
79
+ };
80
+ const scheduleCloseFallback = () => {
81
+ closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
82
+ closeTimer.unref?.();
83
+ };
84
+ const terminate = () => {
85
+ if (terminating || settled)
86
+ return;
87
+ terminating = true;
88
+ killTree('SIGTERM');
89
+ killTimer = setTimeout(() => {
90
+ forced = true;
91
+ killTree('SIGKILL');
92
+ scheduleCloseFallback();
93
+ }, input.killGraceMs ?? 500);
94
+ killTimer.unref?.();
95
+ };
96
+ const timeout = setTimeout(() => { timedOut = true; terminate(); }, input.timeoutMs);
97
+ const onAbort = () => { aborted = true; terminate(); };
98
+ input.signal?.addEventListener('abort', onAbort, { once: true });
99
+ const killTree = (signal) => signalProcessTree(child, signal);
100
+ const stdoutData = (chunk) => {
101
+ stdout.add(chunk);
102
+ // Streaming interceptors (e.g. grep's early-stop) may request termination.
103
+ if (!terminating && input.onStdoutChunk?.(chunk))
104
+ terminate();
76
105
  };
106
+ const stderrData = (chunk) => stderr.add(chunk);
107
+ child.stdout.on('data', stdoutData);
108
+ child.stderr.on('data', stderrData);
77
109
  child.once('error', error => settle(null, null, error.message));
110
+ child.once('exit', (code, signal) => {
111
+ exitCode = code;
112
+ exitSignal = signal;
113
+ });
78
114
  child.once('close', (code, signal) => settle(code, signal));
79
115
  });
80
116
  }
@@ -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,7 @@ export type SessionEntry = {
6
6
  cwd: string;
7
7
  createdAt: string;
8
8
  hazeVersion?: string;
9
+ forkedFrom?: string;
9
10
  } | {
10
11
  type: 'ui_message';
11
12
  at: string;
@@ -34,7 +35,9 @@ export declare function createSession(options?: {
34
35
  cwd?: string;
35
36
  hazeVersion?: string;
36
37
  sessionsDir?: string;
38
+ forkedFrom?: string;
37
39
  }): Promise<HazeSession>;
40
+ export declare function findSession(id: string, cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
38
41
  export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
39
42
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
40
43
  export interface ReadSessionEntriesResult {
@@ -54,10 +57,44 @@ export interface RestoreConversationResult {
54
57
  messages: ModelMessage[];
55
58
  parseErrors: string[];
56
59
  }
60
+ export interface RestoreSessionStateResult {
61
+ messages: ModelMessage[];
62
+ workState: WorkState | undefined;
63
+ parseErrors: string[];
64
+ }
65
+ /**
66
+ * Restore conversation and work state in one file scan (CR-013). Session
67
+ * files grow to megabytes in long workspaces; resuming should not parse the
68
+ * JSONL twice.
69
+ */
70
+ export declare function restoreSessionState(session: HazeSession): Promise<RestoreSessionStateResult>;
57
71
  export declare function restoreConversation(session: HazeSession): Promise<RestoreConversationResult>;
58
72
  export interface RestoreWorkStateResult {
59
73
  state: WorkState | undefined;
60
74
  parseErrors: string[];
61
75
  }
62
76
  export declare function restoreWorkState(session: HazeSession): Promise<RestoreWorkStateResult>;
77
+ /** Acceptance budget for listing 50 ordinary workspace sessions. */
78
+ export declare const SESSION_LIST_LATENCY_BUDGET_MS = 2000;
79
+ export interface SessionSummary {
80
+ id: string;
81
+ createdAt: string;
82
+ lastActivityAt: string;
83
+ messageCount: number;
84
+ firstUserPreview: string;
85
+ sizeBytes: number;
86
+ lastStatus?: string;
87
+ parseErrors: string[];
88
+ }
89
+ /** List this workspace's sessions newest-first while retaining only summary state per file. */
90
+ export declare function listSessions(cwd?: string, sessionsDir?: string): Promise<SessionSummary[]>;
91
+ export interface ForkSessionResult {
92
+ session: HazeSession;
93
+ parseErrors: string[];
94
+ }
95
+ /** Create a new session from the source's latest durable snapshots without mutating it. */
96
+ export declare function forkSession(source: HazeSession, options?: {
97
+ hazeVersion?: string;
98
+ sessionsDir?: string;
99
+ }): Promise<ForkSessionResult>;
63
100
  export declare function formatSession(session: HazeSession): string;
@@ -17,16 +17,27 @@ function sessionFile(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR
17
17
  return path.join(sessionDir(cwd, sessionsDir), `${id}.jsonl`);
18
18
  }
19
19
  function newSessionId(now = new Date()) {
20
- return now.toISOString().replace(/[:.]/g, '-');
20
+ // Timestamp prefix keeps latestSession() lexicographic ordering; the random
21
+ // suffix prevents same-millisecond collisions (CR-025).
22
+ return `${now.toISOString().replace(/[:.]/g, '-')}-${crypto.randomBytes(3).toString('hex')}`;
21
23
  }
22
24
  export async function createSession(options = {}) {
23
25
  const cwd = path.resolve(options.cwd ?? process.cwd());
24
26
  const id = newSessionId();
25
27
  const file = sessionFile(id, cwd, options.sessionsDir);
26
28
  await ensurePrivateDir(path.dirname(file));
27
- await appendSessionEntry({ id, file, cwd }, { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion });
29
+ await appendSessionEntry({ id, file, cwd }, { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion, forkedFrom: options.forkedFrom });
28
30
  return { id, file, cwd };
29
31
  }
32
+ export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
33
+ const normalizedId = id.trim();
34
+ if (!normalizedId || path.basename(normalizedId) !== normalizedId || normalizedId.endsWith('.jsonl'))
35
+ return undefined;
36
+ const file = sessionFile(normalizedId, cwd, sessionsDir);
37
+ if (!await fs.pathExists(file))
38
+ return undefined;
39
+ return { id: normalizedId, file, cwd: path.resolve(cwd) };
40
+ }
30
41
  export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
31
42
  const dir = sessionDir(cwd, sessionsDir);
32
43
  await ensurePrivateDir(dir);
@@ -86,21 +97,96 @@ export async function readSessionEntries(session) {
86
97
  const parseErrors = await scanSessionEntries(session, entry => entries.push(entry));
87
98
  return { entries, parseErrors };
88
99
  }
89
- export async function restoreConversation(session) {
100
+ /**
101
+ * Restore conversation and work state in one file scan (CR-013). Session
102
+ * files grow to megabytes in long workspaces; resuming should not parse the
103
+ * JSONL twice.
104
+ */
105
+ export async function restoreSessionState(session) {
90
106
  let messages = [];
107
+ let workState;
91
108
  const parseErrors = await scanSessionEntries(session, entry => {
92
109
  if (entry.type === 'conversation_snapshot')
93
110
  messages = entry.messages;
111
+ if (entry.type === 'work_state_snapshot')
112
+ workState = entry.state;
94
113
  });
114
+ return { messages, workState, parseErrors };
115
+ }
116
+ export async function restoreConversation(session) {
117
+ const { messages, parseErrors } = await restoreSessionState(session);
95
118
  return { messages, parseErrors };
96
119
  }
97
120
  export async function restoreWorkState(session) {
98
- let state;
99
- const parseErrors = await scanSessionEntries(session, entry => {
100
- if (entry.type === 'work_state_snapshot')
101
- state = entry.state;
102
- });
103
- return { state, parseErrors };
121
+ const { workState, parseErrors } = await restoreSessionState(session);
122
+ return { state: workState, parseErrors };
123
+ }
124
+ const SESSION_PREVIEW_CHARS = 120;
125
+ /** Acceptance budget for listing 50 ordinary workspace sessions. */
126
+ export const SESSION_LIST_LATENCY_BUDGET_MS = 2_000;
127
+ function previewText(text) {
128
+ const compact = text.replace(/\s+/g, ' ').trim();
129
+ return compact.length > SESSION_PREVIEW_CHARS ? `${compact.slice(0, SESSION_PREVIEW_CHARS - 1)}…` : compact;
130
+ }
131
+ /** List this workspace's sessions newest-first while retaining only summary state per file. */
132
+ export async function listSessions(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
133
+ const dir = sessionDir(cwd, sessionsDir);
134
+ await ensurePrivateDir(dir);
135
+ const files = (await fs.readdir(dir).catch(() => [])).filter(file => file.endsWith('.jsonl'));
136
+ const summaries = await Promise.all(files.map(async (fileName) => {
137
+ const id = path.basename(fileName, '.jsonl');
138
+ const session = { id, file: path.join(dir, fileName), cwd: path.resolve(cwd) };
139
+ const stat = await fs.stat(session.file);
140
+ let createdAt = stat.birthtime.toISOString();
141
+ let lastActivityAt = stat.mtime.toISOString();
142
+ let messageCount = 0;
143
+ let firstUserPreview = '';
144
+ let lastStatus;
145
+ const parseErrors = await scanSessionEntries(session, entry => {
146
+ if (entry.type === 'header')
147
+ createdAt = entry.createdAt || createdAt;
148
+ if ('at' in entry && entry.at)
149
+ lastActivityAt = entry.at;
150
+ if (entry.type === 'ui_message') {
151
+ messageCount++;
152
+ if (!firstUserPreview && entry.role === 'user')
153
+ firstUserPreview = previewText(entry.text);
154
+ }
155
+ if (entry.type === 'conversation_snapshot') {
156
+ if (messageCount === 0)
157
+ messageCount = entry.messages.length;
158
+ if (!firstUserPreview) {
159
+ const firstUser = entry.messages.find(message => message.role === 'user');
160
+ if (firstUser)
161
+ firstUserPreview = previewText(typeof firstUser.content === 'string' ? firstUser.content : JSON.stringify(firstUser.content));
162
+ }
163
+ }
164
+ if (entry.type === 'event' && entry.name === 'turn_end' && entry.text) {
165
+ try {
166
+ const event = JSON.parse(entry.text);
167
+ if (typeof event.status === 'string')
168
+ lastStatus = event.status;
169
+ }
170
+ catch {
171
+ // The outer entry remains valid; malformed optional event metadata is ignored.
172
+ }
173
+ }
174
+ });
175
+ return { id, createdAt, lastActivityAt, messageCount, firstUserPreview, sizeBytes: stat.size, lastStatus, parseErrors };
176
+ }));
177
+ return summaries.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
178
+ }
179
+ /** Create a new session from the source's latest durable snapshots without mutating it. */
180
+ export async function forkSession(source, options = {}) {
181
+ const restored = await restoreSessionState(source);
182
+ if (restored.messages.length === 0)
183
+ throw new Error(`Session ${source.id} has no conversation snapshot to fork.`);
184
+ const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id });
185
+ const at = new Date().toISOString();
186
+ await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
187
+ if (restored.workState)
188
+ await appendSessionEntry(session, { type: 'work_state_snapshot', at, state: restored.workState });
189
+ return { session, parseErrors: restored.parseErrors };
104
190
  }
105
191
  export function formatSession(session) {
106
192
  return `${session.id} · ${session.file}`;