@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.
- package/CHANGELOG.md +67 -17
- package/README.md +121 -64
- package/dist/cli/chat/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +44 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +91 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
- package/dist/cli/chat/sessionLifecycle.js +155 -0
- package/dist/cli/chat/sessionRecorder.d.ts +3 -0
- package/dist/cli/chat/sessionRecorder.js +21 -8
- package/dist/cli/chat/startupInfo.d.ts +1 -0
- package/dist/cli/chat/startupInfo.js +11 -0
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +645 -0
- package/dist/cli/commands/chat.d.ts +1 -0
- package/dist/cli/commands/chat.js +246 -779
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +4 -3
- package/dist/cli/commands/commands.js +12 -13
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +36 -9
- package/dist/cli/commands/logsCommand.js +8 -28
- package/dist/cli/commands/mcpWizard.js +24 -2
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/providerWizard.d.ts +1 -0
- package/dist/cli/commands/providerWizard.js +31 -5
- package/dist/cli/commands/runCommand.d.ts +1 -0
- package/dist/cli/commands/runCommand.js +32 -20
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +8 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
- package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
- package/dist/cli/commands/streaming/turnOutcome.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +13 -1
- package/dist/cli/commands/streaming.js +104 -44
- package/dist/cli/commands/wizardActions.d.ts +6 -0
- package/dist/cli/commands/wizardActions.js +6 -0
- package/dist/cli/commands/wizardPrompts.js +1 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +62 -13
- package/dist/cli/commands/wizardTransition.d.ts +37 -0
- package/dist/cli/commands/wizardTransition.js +43 -0
- package/dist/cli/index.js +17 -3
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/contextFiles.js +6 -3
- package/dist/config/endpointSecurity.d.ts +2 -0
- package/dist/config/endpointSecurity.js +28 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +13 -17
- package/dist/config/modelDiscovery.d.ts +20 -0
- package/dist/config/modelDiscovery.js +51 -0
- package/dist/config/privateStorage.d.ts +6 -0
- package/dist/config/privateStorage.js +61 -0
- package/dist/config/providerPresets.d.ts +16 -4
- package/dist/config/providerPresets.js +263 -34
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +7 -0
- package/dist/config/settings.d.ts +22 -0
- package/dist/config/settings.js +33 -5
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/config/updateCheck.js +4 -2
- package/dist/core/agent/budgets.d.ts +26 -0
- package/dist/core/agent/budgets.js +34 -0
- package/dist/core/agent/compaction.js +17 -3
- package/dist/core/agent/contextBudget.d.ts +8 -0
- package/dist/core/agent/contextBudget.js +29 -0
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +12 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +49 -11
- package/dist/core/agent/workState.d.ts +1 -1
- package/dist/core/agent/workState.js +0 -4
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- package/dist/core/goal/completionPolicy.d.ts +0 -28
- package/dist/core/goal/completionPolicy.js +0 -88
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.d.ts +15 -0
- package/dist/core/io/boundedRead.js +144 -0
- package/dist/core/limits/byteBudgets.d.ts +18 -0
- package/dist/core/limits/byteBudgets.js +18 -0
- package/dist/core/limits/textBudgets.d.ts +23 -0
- package/dist/core/limits/textBudgets.js +23 -0
- package/dist/core/log/llmLog.d.ts +10 -0
- package/dist/core/log/llmLog.js +59 -13
- package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
- package/dist/core/persistence/orderedFileWriter.js +29 -0
- package/dist/core/process/backgroundRegistry.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +194 -0
- package/dist/core/process/runBoundedProcess.d.ts +30 -0
- package/dist/core/process/runBoundedProcess.js +116 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +37 -0
- package/dist/core/session/sessionStore.js +136 -27
- package/dist/core/subagent/contracts.d.ts +116 -0
- package/dist/core/subagent/contracts.js +54 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
- package/dist/core/subagent/subagentCoordinator.js +134 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +228 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +20 -29
- package/dist/llm/client.js +33 -29
- package/dist/llm/hazeTools.d.ts +2396 -67
- package/dist/llm/hazeTools.js +50 -37
- package/dist/llm/lsp.d.ts +23 -3
- package/dist/llm/lsp.js +73 -16
- package/dist/llm/lspTools.d.ts +96 -48
- package/dist/llm/mcp.d.ts +1 -1
- package/dist/llm/mcp.js +65 -16
- package/dist/llm/requestContext.d.ts +23 -1
- package/dist/llm/requestContext.js +50 -7
- package/dist/llm/systemPrompt.d.ts +4 -1
- package/dist/llm/systemPrompt.js +14 -4
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/tools/bashTool.d.ts +1210 -16
- package/dist/llm/tools/bashTool.js +43 -60
- package/dist/llm/tools/fetchTool.d.ts +26 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +2 -1
- package/dist/llm/tools/fileToolShared.js +5 -5
- package/dist/llm/tools/grepRunner.d.ts +20 -0
- package/dist/llm/tools/grepRunner.js +66 -0
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -0
- package/dist/llm/tools/toolContext.d.ts +8 -0
- package/dist/llm/tools/toolContext.js +22 -11
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.js +24 -11
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillLoader.js +17 -5
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +53 -10
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +11 -1
- package/dist/ui/components/TextInput.d.ts +5 -2
- package/dist/ui/components/TextInput.js +76 -8
- package/dist/utils/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +0 -1
- package/dist/utils/fs.js +0 -4
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +9 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +9 -4
- package/package.json +1 -1
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
|
+
import { TEXT_LINE_BYTES } from '../limits/byteBudgets.js';
|
|
5
|
+
async function* iterateBoundedUtf8LinesFrom(file, maxLineBytes, startByte, previousLineNumber) {
|
|
6
|
+
const input = createReadStream(file, startByte > 0 ? { start: startByte } : undefined);
|
|
7
|
+
let lineNumber = previousLineNumber;
|
|
8
|
+
let retained = [];
|
|
9
|
+
let retainedBytes = 0;
|
|
10
|
+
let lineBytes = 0;
|
|
11
|
+
const append = (segment) => {
|
|
12
|
+
lineBytes += segment.length;
|
|
13
|
+
const remaining = maxLineBytes - retainedBytes;
|
|
14
|
+
if (remaining <= 0)
|
|
15
|
+
return;
|
|
16
|
+
const kept = segment.subarray(0, remaining);
|
|
17
|
+
if (kept.length > 0) {
|
|
18
|
+
retained.push(kept);
|
|
19
|
+
retainedBytes += kept.length;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const finish = () => {
|
|
23
|
+
lineNumber++;
|
|
24
|
+
let bytes = Buffer.concat(retained, retainedBytes);
|
|
25
|
+
if (bytes.at(-1) === 13)
|
|
26
|
+
bytes = bytes.subarray(0, -1);
|
|
27
|
+
const oversized = lineBytes > maxLineBytes;
|
|
28
|
+
const decoder = new StringDecoder('utf8');
|
|
29
|
+
const line = oversized ? decoder.write(bytes) : bytes.toString('utf8');
|
|
30
|
+
const result = { line, lineNumber, oversized };
|
|
31
|
+
retained = [];
|
|
32
|
+
retainedBytes = 0;
|
|
33
|
+
lineBytes = 0;
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
for await (const value of input) {
|
|
37
|
+
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
38
|
+
let start = 0;
|
|
39
|
+
while (start < chunk.length) {
|
|
40
|
+
const newline = chunk.indexOf(10, start);
|
|
41
|
+
if (newline === -1) {
|
|
42
|
+
append(chunk.subarray(start));
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
append(chunk.subarray(start, newline));
|
|
46
|
+
yield finish();
|
|
47
|
+
start = newline + 1;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (lineBytes > 0 || retainedBytes > 0)
|
|
51
|
+
yield finish();
|
|
52
|
+
}
|
|
53
|
+
export async function* iterateBoundedUtf8Lines(file, maxLineBytes) {
|
|
54
|
+
yield* iterateBoundedUtf8LinesFrom(file, maxLineBytes, 0, 0);
|
|
55
|
+
}
|
|
56
|
+
const MAX_LINE_INDEX_FILES = 8;
|
|
57
|
+
const MAX_LINE_CHECKPOINTS = 8_192;
|
|
58
|
+
const lineIndexCache = new Map();
|
|
59
|
+
function sameFileSignature(index, stat) {
|
|
60
|
+
return index.size === stat.size && index.mtimeMs === stat.mtimeMs && index.ctimeMs === stat.ctimeMs;
|
|
61
|
+
}
|
|
62
|
+
async function buildLineIndex(file, stat) {
|
|
63
|
+
let totalLines = 1;
|
|
64
|
+
let byteOffset = 0;
|
|
65
|
+
let stride = 256;
|
|
66
|
+
let trailingNewline = false;
|
|
67
|
+
let checkpoints = [{ lineNumber: 1, byteOffset: 0 }];
|
|
68
|
+
for await (const value of createReadStream(file)) {
|
|
69
|
+
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
70
|
+
let cursor = 0;
|
|
71
|
+
while (cursor < chunk.length) {
|
|
72
|
+
const newline = chunk.indexOf(10, cursor);
|
|
73
|
+
if (newline === -1)
|
|
74
|
+
break;
|
|
75
|
+
totalLines++;
|
|
76
|
+
const lineStart = byteOffset + newline + 1;
|
|
77
|
+
if ((totalLines - 1) % stride === 0)
|
|
78
|
+
checkpoints.push({ lineNumber: totalLines, byteOffset: lineStart });
|
|
79
|
+
if (checkpoints.length > MAX_LINE_CHECKPOINTS) {
|
|
80
|
+
stride *= 2;
|
|
81
|
+
checkpoints = checkpoints.filter(point => (point.lineNumber - 1) % stride === 0);
|
|
82
|
+
}
|
|
83
|
+
cursor = newline + 1;
|
|
84
|
+
}
|
|
85
|
+
trailingNewline = chunk.length > 0 ? chunk[chunk.length - 1] === 10 : trailingNewline;
|
|
86
|
+
byteOffset += chunk.length;
|
|
87
|
+
}
|
|
88
|
+
return { size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, totalLines, trailingNewline, checkpoints };
|
|
89
|
+
}
|
|
90
|
+
async function lineIndex(file) {
|
|
91
|
+
const stat = await fs.stat(file);
|
|
92
|
+
const cached = lineIndexCache.get(file);
|
|
93
|
+
if (cached && sameFileSignature(cached, stat)) {
|
|
94
|
+
lineIndexCache.delete(file);
|
|
95
|
+
lineIndexCache.set(file, cached);
|
|
96
|
+
return cached;
|
|
97
|
+
}
|
|
98
|
+
const index = await buildLineIndex(file, stat);
|
|
99
|
+
lineIndexCache.delete(file);
|
|
100
|
+
lineIndexCache.set(file, index);
|
|
101
|
+
while (lineIndexCache.size > MAX_LINE_INDEX_FILES) {
|
|
102
|
+
const oldest = lineIndexCache.keys().next().value;
|
|
103
|
+
if (oldest == null)
|
|
104
|
+
break;
|
|
105
|
+
lineIndexCache.delete(oldest);
|
|
106
|
+
}
|
|
107
|
+
return index;
|
|
108
|
+
}
|
|
109
|
+
export async function readUtf8LinesPage(file, offset, limit) {
|
|
110
|
+
const index = await lineIndex(file);
|
|
111
|
+
const lines = [];
|
|
112
|
+
if (limit <= 0 || offset > index.totalLines)
|
|
113
|
+
return { lines, totalLines: index.totalLines };
|
|
114
|
+
let checkpoint = index.checkpoints[0];
|
|
115
|
+
for (const candidate of index.checkpoints) {
|
|
116
|
+
if (candidate.lineNumber > offset)
|
|
117
|
+
break;
|
|
118
|
+
checkpoint = candidate;
|
|
119
|
+
}
|
|
120
|
+
for await (const entry of iterateBoundedUtf8LinesFrom(file, TEXT_LINE_BYTES, checkpoint.byteOffset, checkpoint.lineNumber - 1)) {
|
|
121
|
+
if (entry.lineNumber < offset)
|
|
122
|
+
continue;
|
|
123
|
+
lines.push(entry.oversized ? `${entry.line}\n[Line truncated at ${TEXT_LINE_BYTES} bytes]` : entry.line);
|
|
124
|
+
if (lines.length >= limit)
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
const includesSyntheticLastLine = index.size === 0 || index.trailingNewline;
|
|
128
|
+
if (includesSyntheticLastLine && offset <= index.totalLines && index.totalLines < offset + limit && lines.length < limit)
|
|
129
|
+
lines.push('');
|
|
130
|
+
return { lines, totalLines: index.totalLines };
|
|
131
|
+
}
|
|
132
|
+
export async function readUtf8Prefix(file, maxBytes) {
|
|
133
|
+
const stat = await fs.stat(file);
|
|
134
|
+
if (maxBytes <= 0)
|
|
135
|
+
return { content: '', truncated: stat.size > 0, totalBytes: stat.size };
|
|
136
|
+
const input = createReadStream(file, { start: 0, end: maxBytes - 1 });
|
|
137
|
+
const chunks = [];
|
|
138
|
+
for await (const chunk of input)
|
|
139
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
140
|
+
const buffer = Buffer.concat(chunks);
|
|
141
|
+
const decoder = new StringDecoder('utf8');
|
|
142
|
+
const content = decoder.write(buffer) + (stat.size <= maxBytes ? decoder.end() : '');
|
|
143
|
+
return { content, truncated: stat.size > maxBytes, totalBytes: stat.size };
|
|
144
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const BASH_STREAM_BYTES: number;
|
|
2
|
+
export declare const BACKGROUND_PROCESS_OUTPUT_BYTES: number;
|
|
3
|
+
export declare const GREP_STREAM_BYTES: number;
|
|
4
|
+
export declare const PROCESS_STDERR_BYTES: number;
|
|
5
|
+
export declare const TOOL_OUTPUT_ENTRY_BYTES: number;
|
|
6
|
+
export declare const TOOL_OUTPUT_TOTAL_BYTES: number;
|
|
7
|
+
export declare const LSP_DOCUMENT_BYTES: number;
|
|
8
|
+
export declare const LSP_HEADER_BYTES: number;
|
|
9
|
+
export declare const LSP_FRAME_BYTES: number;
|
|
10
|
+
export declare const LSP_BUFFER_BYTES: number;
|
|
11
|
+
export declare const SKILL_MARKDOWN_BYTES: number;
|
|
12
|
+
export declare const EXACT_MUTATION_BYTES: number;
|
|
13
|
+
export declare const JSONL_LINE_BYTES: number;
|
|
14
|
+
export declare const TEXT_LINE_BYTES: number;
|
|
15
|
+
/** Maximum size of one user-attached image (checked before the read). */
|
|
16
|
+
export declare const IMAGE_ATTACHMENT_BYTES: number;
|
|
17
|
+
/** Maximum number of image attachments in a single user message. */
|
|
18
|
+
export declare const IMAGE_ATTACHMENTS_PER_MESSAGE = 4;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const BASH_STREAM_BYTES = 2 * 1024 * 1024;
|
|
2
|
+
export const BACKGROUND_PROCESS_OUTPUT_BYTES = 256 * 1024;
|
|
3
|
+
export const GREP_STREAM_BYTES = 8 * 1024 * 1024;
|
|
4
|
+
export const PROCESS_STDERR_BYTES = 64 * 1024;
|
|
5
|
+
export const TOOL_OUTPUT_ENTRY_BYTES = 2 * 1024 * 1024;
|
|
6
|
+
export const TOOL_OUTPUT_TOTAL_BYTES = 16 * 1024 * 1024;
|
|
7
|
+
export const LSP_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
export const LSP_HEADER_BYTES = 16 * 1024;
|
|
9
|
+
export const LSP_FRAME_BYTES = 8 * 1024 * 1024;
|
|
10
|
+
export const LSP_BUFFER_BYTES = LSP_FRAME_BYTES + LSP_HEADER_BYTES;
|
|
11
|
+
export const SKILL_MARKDOWN_BYTES = 256 * 1024;
|
|
12
|
+
export const EXACT_MUTATION_BYTES = 8 * 1024 * 1024;
|
|
13
|
+
export const JSONL_LINE_BYTES = 4 * 1024 * 1024;
|
|
14
|
+
export const TEXT_LINE_BYTES = 1024 * 1024;
|
|
15
|
+
/** Maximum size of one user-attached image (checked before the read). */
|
|
16
|
+
export const IMAGE_ATTACHMENT_BYTES = 5 * 1024 * 1024;
|
|
17
|
+
/** Maximum number of image attachments in a single user message. */
|
|
18
|
+
export const IMAGE_ATTACHMENTS_PER_MESSAGE = 4;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing text caps (characters). Byte budgets live in `byteBudgets.ts`;
|
|
3
|
+
* these bound the text returned to the model or persisted in previews so
|
|
4
|
+
* callers cite a named constant instead of a magic number (CR-014).
|
|
5
|
+
*/
|
|
6
|
+
/** Per-page cap for numbered file content returned by readFile/listFiles-style tools. */
|
|
7
|
+
export declare const MAX_OUTPUT_CHARS = 50000;
|
|
8
|
+
/** Default compact cap for stored bash output shown to the model. */
|
|
9
|
+
export declare const COMPACT_COMMAND_CHARS = 12000;
|
|
10
|
+
/** Compact cap for passing-validation summaries. */
|
|
11
|
+
export declare const SHORT_VALIDATION_CHARS = 2000;
|
|
12
|
+
/** Total rendered size cap for grep match output. */
|
|
13
|
+
export declare const GREP_MAX_OUTPUT_CHARS = 30000;
|
|
14
|
+
/** Per-line cap for rendered grep matches. */
|
|
15
|
+
export declare const GREP_MAX_LINE_CHARS = 500;
|
|
16
|
+
/** Bounded excerpt of older messages kept by /compact-style compaction. */
|
|
17
|
+
export declare const COMPACTION_OLDER_CHARS = 8000;
|
|
18
|
+
/** Session JSONL values up to this size stay inline; larger ones become previews. */
|
|
19
|
+
export declare const SESSION_INLINE_VALUE_BYTES: number;
|
|
20
|
+
/** Preview length for slimmed session values. */
|
|
21
|
+
export declare const SESSION_PREVIEW_CHARS: number;
|
|
22
|
+
/** Strings longer than this are truncated in session snapshots. */
|
|
23
|
+
export declare const SESSION_LARGE_STRING_CHARS: number;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing text caps (characters). Byte budgets live in `byteBudgets.ts`;
|
|
3
|
+
* these bound the text returned to the model or persisted in previews so
|
|
4
|
+
* callers cite a named constant instead of a magic number (CR-014).
|
|
5
|
+
*/
|
|
6
|
+
/** Per-page cap for numbered file content returned by readFile/listFiles-style tools. */
|
|
7
|
+
export const MAX_OUTPUT_CHARS = 50_000;
|
|
8
|
+
/** Default compact cap for stored bash output shown to the model. */
|
|
9
|
+
export const COMPACT_COMMAND_CHARS = 12_000;
|
|
10
|
+
/** Compact cap for passing-validation summaries. */
|
|
11
|
+
export const SHORT_VALIDATION_CHARS = 2_000;
|
|
12
|
+
/** Total rendered size cap for grep match output. */
|
|
13
|
+
export const GREP_MAX_OUTPUT_CHARS = 30_000;
|
|
14
|
+
/** Per-line cap for rendered grep matches. */
|
|
15
|
+
export const GREP_MAX_LINE_CHARS = 500;
|
|
16
|
+
/** Bounded excerpt of older messages kept by /compact-style compaction. */
|
|
17
|
+
export const COMPACTION_OLDER_CHARS = 8_000;
|
|
18
|
+
/** Session JSONL values up to this size stay inline; larger ones become previews. */
|
|
19
|
+
export const SESSION_INLINE_VALUE_BYTES = 32 * 1024;
|
|
20
|
+
/** Preview length for slimmed session values. */
|
|
21
|
+
export const SESSION_PREVIEW_CHARS = 4 * 1024;
|
|
22
|
+
/** Strings longer than this are truncated in session snapshots. */
|
|
23
|
+
export const SESSION_LARGE_STRING_CHARS = 8 * 1024;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
2
|
import type { ContextBreakdown } from '../agent/contextBudget.js';
|
|
3
|
+
import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
|
|
3
4
|
export interface LlmLogEntry {
|
|
4
5
|
/** ISO timestamp. */
|
|
5
6
|
at: string;
|
|
@@ -55,6 +56,7 @@ export interface LlmLogEntry {
|
|
|
55
56
|
export interface LlmLog {
|
|
56
57
|
id: string;
|
|
57
58
|
file: string;
|
|
59
|
+
writer?: OrderedFileWriter<LlmLogEntry>;
|
|
58
60
|
}
|
|
59
61
|
export declare function createLog(): Promise<LlmLog>;
|
|
60
62
|
export declare function appendLogEntry(log: LlmLog, entry: LlmLogEntry): Promise<void>;
|
|
@@ -66,3 +68,11 @@ export declare function listLogs(): Promise<Array<{
|
|
|
66
68
|
modified: string;
|
|
67
69
|
}>>;
|
|
68
70
|
export declare function readLogEntries(id: string): Promise<LlmLogEntry[]>;
|
|
71
|
+
export interface LlmLogSummary {
|
|
72
|
+
entries: number;
|
|
73
|
+
typeCounts: Record<string, number>;
|
|
74
|
+
totalInput: number;
|
|
75
|
+
totalOutput: number;
|
|
76
|
+
toolCallCounts: Record<string, number>;
|
|
77
|
+
}
|
|
78
|
+
export declare function summarizeLog(id: string): Promise<LlmLogSummary | undefined>;
|
package/dist/core/log/llmLog.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import fs from 'fs-extra';
|
|
3
3
|
import { HAZE_DIR } from '../../config/paths.js';
|
|
4
|
+
import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
|
|
5
|
+
import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
|
|
6
|
+
import { JSONL_LINE_BYTES } from '../limits/byteBudgets.js';
|
|
7
|
+
import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
|
|
4
8
|
const LOGS_DIR = path.join(HAZE_DIR, 'logs');
|
|
5
9
|
function logFileId(now = new Date()) {
|
|
6
10
|
return now.toISOString().replace(/[:.]/g, '-');
|
|
@@ -9,15 +13,20 @@ function logFilePath(id) {
|
|
|
9
13
|
return path.join(LOGS_DIR, `${id}.jsonl`);
|
|
10
14
|
}
|
|
11
15
|
export async function createLog() {
|
|
12
|
-
await
|
|
16
|
+
await ensurePrivateDir(LOGS_DIR);
|
|
13
17
|
const id = logFileId();
|
|
14
18
|
const file = logFilePath(id);
|
|
15
|
-
await
|
|
16
|
-
|
|
19
|
+
await ensurePrivateFile(file);
|
|
20
|
+
const log = { id, file };
|
|
21
|
+
log.writer = new OrderedFileWriter(entry => appendPrivateFile(file, `${JSON.stringify(entry)}\n`));
|
|
22
|
+
return log;
|
|
17
23
|
}
|
|
18
24
|
export async function appendLogEntry(log, entry) {
|
|
19
|
-
|
|
20
|
-
|
|
25
|
+
if (log.writer) {
|
|
26
|
+
await log.writer.append(entry);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
await appendPrivateFile(log.file, `${JSON.stringify(entry)}\n`);
|
|
21
30
|
}
|
|
22
31
|
export async function endLog(log) {
|
|
23
32
|
const entry = {
|
|
@@ -27,9 +36,10 @@ export async function endLog(log) {
|
|
|
27
36
|
finishReason: 'log-ended',
|
|
28
37
|
};
|
|
29
38
|
await appendLogEntry(log, entry);
|
|
39
|
+
await log.writer?.close();
|
|
30
40
|
}
|
|
31
41
|
export async function listLogs() {
|
|
32
|
-
await
|
|
42
|
+
await ensurePrivateDir(LOGS_DIR);
|
|
33
43
|
const files = await fs.readdir(LOGS_DIR);
|
|
34
44
|
const logs = [];
|
|
35
45
|
for (const name of files) {
|
|
@@ -43,13 +53,49 @@ export async function listLogs() {
|
|
|
43
53
|
}
|
|
44
54
|
export async function readLogEntries(id) {
|
|
45
55
|
const file = logFilePath(id);
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
56
|
+
const entries = [];
|
|
57
|
+
try {
|
|
58
|
+
await tightenPrivateFile(file);
|
|
59
|
+
for await (const { line, oversized } of iterateBoundedUtf8Lines(file, JSONL_LINE_BYTES)) {
|
|
60
|
+
if (!line || oversized)
|
|
61
|
+
continue;
|
|
62
|
+
try {
|
|
63
|
+
entries.push(JSON.parse(line));
|
|
64
|
+
}
|
|
65
|
+
catch { /* isolate malformed lines */ }
|
|
50
66
|
}
|
|
51
|
-
|
|
52
|
-
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
return entries;
|
|
72
|
+
}
|
|
73
|
+
export async function summarizeLog(id) {
|
|
74
|
+
const file = logFilePath(id);
|
|
75
|
+
const summary = { entries: 0, typeCounts: {}, totalInput: 0, totalOutput: 0, toolCallCounts: {} };
|
|
76
|
+
try {
|
|
77
|
+
await tightenPrivateFile(file);
|
|
78
|
+
for await (const { line, oversized } of iterateBoundedUtf8Lines(file, JSONL_LINE_BYTES)) {
|
|
79
|
+
if (!line || oversized)
|
|
80
|
+
continue;
|
|
81
|
+
let entry;
|
|
82
|
+
try {
|
|
83
|
+
entry = JSON.parse(line);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
summary.entries++;
|
|
89
|
+
summary.typeCounts[entry.type] = (summary.typeCounts[entry.type] ?? 0) + 1;
|
|
90
|
+
summary.totalInput += entry.usage?.inputTokens ?? 0;
|
|
91
|
+
summary.totalOutput += entry.usage?.outputTokens ?? 0;
|
|
92
|
+
if (entry.type === 'tool_call' && entry.toolCall) {
|
|
93
|
+
summary.toolCallCounts[entry.toolCall.name] = (summary.toolCallCounts[entry.toolCall.name] ?? 0) + 1;
|
|
94
|
+
}
|
|
53
95
|
}
|
|
54
|
-
}
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
return summary.entries > 0 ? summary : undefined;
|
|
55
101
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class OrderedFileWriter<T> {
|
|
2
|
+
private readonly write;
|
|
3
|
+
private tail;
|
|
4
|
+
private firstError;
|
|
5
|
+
private closed;
|
|
6
|
+
constructor(write: (value: T) => Promise<void>);
|
|
7
|
+
append(value: T): Promise<void>;
|
|
8
|
+
flush(): Promise<void>;
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
error(): Error | undefined;
|
|
11
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export class OrderedFileWriter {
|
|
2
|
+
write;
|
|
3
|
+
tail = Promise.resolve();
|
|
4
|
+
firstError;
|
|
5
|
+
closed = false;
|
|
6
|
+
constructor(write) {
|
|
7
|
+
this.write = write;
|
|
8
|
+
}
|
|
9
|
+
append(value) {
|
|
10
|
+
if (this.closed)
|
|
11
|
+
return Promise.reject(new Error('Writer is closed.'));
|
|
12
|
+
this.tail = this.tail.then(() => this.write(value)).catch(error => {
|
|
13
|
+
this.firstError ??= error instanceof Error ? error : new Error(String(error));
|
|
14
|
+
});
|
|
15
|
+
return this.tail;
|
|
16
|
+
}
|
|
17
|
+
async flush() {
|
|
18
|
+
await this.tail;
|
|
19
|
+
if (this.firstError)
|
|
20
|
+
throw this.firstError;
|
|
21
|
+
}
|
|
22
|
+
async close() {
|
|
23
|
+
this.closed = true;
|
|
24
|
+
await this.flush();
|
|
25
|
+
}
|
|
26
|
+
error() {
|
|
27
|
+
return this.firstError;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type BackgroundProcessStatus = 'running' | 'exited' | 'failed' | 'killed';
|
|
2
|
+
export interface BackgroundProcessSummary {
|
|
3
|
+
backgroundId: string;
|
|
4
|
+
pid?: number;
|
|
5
|
+
command: string;
|
|
6
|
+
cwd: string;
|
|
7
|
+
startedAt: string;
|
|
8
|
+
status: BackgroundProcessStatus;
|
|
9
|
+
code?: number | null;
|
|
10
|
+
signal?: NodeJS.Signals | null;
|
|
11
|
+
outputHandle: string;
|
|
12
|
+
outputBytes: {
|
|
13
|
+
totalBytes: number;
|
|
14
|
+
retainedBytes: number;
|
|
15
|
+
omittedBytes: number;
|
|
16
|
+
};
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function backgroundProcessCount(): number;
|
|
20
|
+
export declare function subscribeBackgroundProcesses(listener: () => void): () => void;
|
|
21
|
+
export declare function listBackgroundProcesses(): BackgroundProcessSummary[];
|
|
22
|
+
export declare function getBackgroundProcess(backgroundId: string): BackgroundProcessSummary | undefined;
|
|
23
|
+
export declare function startBackgroundProcess(input: {
|
|
24
|
+
command: string;
|
|
25
|
+
cwd: string;
|
|
26
|
+
}): BackgroundProcessSummary;
|
|
27
|
+
export declare function killBackgroundProcess(backgroundId: string, killGraceMs?: number): Promise<BackgroundProcessSummary | undefined>;
|
|
28
|
+
/** Terminate every owned tree and clear the session-local registry and handles. */
|
|
29
|
+
export declare function teardownBackgroundProcesses(killGraceMs?: number): Promise<BackgroundProcessSummary[]>;
|
|
30
|
+
/** Install CLI-level abnormal-exit teardown for SIGINT and SIGTERM. */
|
|
31
|
+
export declare function installBackgroundProcessSignalHandlers(): void;
|
|
32
|
+
/** Best-effort synchronous safety net for process.exit and otherwise unawaitable exits. */
|
|
33
|
+
export declare function terminateBackgroundProcessesSync(): void;
|
|
34
|
+
/** Test-only reset; callers should normally use teardownBackgroundProcesses. */
|
|
35
|
+
export declare function resetBackgroundProcessesForTests(): Promise<void>;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
2
|
+
export interface BoundedStream {
|
|
3
|
+
text: string;
|
|
4
|
+
totalBytes: number;
|
|
5
|
+
retainedBytes: number;
|
|
6
|
+
omittedBytes: number;
|
|
7
|
+
}
|
|
8
|
+
export interface BoundedProcessResult {
|
|
9
|
+
code: number | null;
|
|
10
|
+
signal: NodeJS.Signals | null;
|
|
11
|
+
stdout: BoundedStream;
|
|
12
|
+
stderr: BoundedStream;
|
|
13
|
+
timedOut: boolean;
|
|
14
|
+
aborted: boolean;
|
|
15
|
+
forced: boolean;
|
|
16
|
+
durationMs: number;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function signalProcessTree(child: Pick<ChildProcess, 'pid' | 'kill'>, signal: NodeJS.Signals): void;
|
|
20
|
+
export declare function runBoundedProcess(input: {
|
|
21
|
+
command: string;
|
|
22
|
+
args: string[];
|
|
23
|
+
cwd: string;
|
|
24
|
+
timeoutMs: number;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
maxStdoutBytes: number;
|
|
27
|
+
maxStderrBytes: number;
|
|
28
|
+
killGraceMs?: number;
|
|
29
|
+
onStdoutChunk?: (chunk: Buffer) => boolean | void;
|
|
30
|
+
}): Promise<BoundedProcessResult>;
|