@denizokcu/haze 0.4.0 → 0.5.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 +28 -0
- package/README.md +31 -29
- package/dist/cli/commands/chat.js +106 -48
- package/dist/cli/commands/commands.js +15 -1
- package/dist/cli/commands/streaming.d.ts +4 -0
- package/dist/cli/commands/streaming.js +242 -111
- package/dist/config/contextFiles.d.ts +6 -0
- package/dist/config/contextFiles.js +47 -16
- package/dist/config/providers.d.ts +2 -5
- package/dist/config/providers.js +16 -12
- package/dist/core/agent/requestAssembly.js +12 -1
- package/dist/core/agent/toolOutputStore.d.ts +6 -1
- package/dist/core/agent/toolOutputStore.js +33 -1
- package/dist/core/bashOutput/ansi.d.ts +1 -0
- package/dist/core/bashOutput/ansi.js +7 -0
- package/dist/core/bashOutput/command.d.ts +2 -0
- package/dist/core/bashOutput/command.js +62 -0
- package/dist/core/bashOutput/lineFilter.d.ts +25 -0
- package/dist/core/bashOutput/lineFilter.js +62 -0
- package/dist/core/bashOutput/reducers/content.d.ts +3 -0
- package/dist/core/bashOutput/reducers/content.js +134 -0
- package/dist/core/bashOutput/reducers/git.d.ts +1 -0
- package/dist/core/bashOutput/reducers/git.js +147 -0
- package/dist/core/bashOutput/reducers/search.d.ts +7 -0
- package/dist/core/bashOutput/reducers/search.js +76 -0
- package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
- package/dist/core/bashOutput/reducers/validation.js +41 -0
- package/dist/core/bashOutput/registry.d.ts +4 -0
- package/dist/core/bashOutput/registry.js +126 -0
- package/dist/core/bashOutput/types.d.ts +46 -0
- package/dist/core/bashOutput/types.js +1 -0
- package/dist/core/goal/completionPolicy.d.ts +1 -0
- package/dist/core/goal/completionPolicy.js +4 -0
- package/dist/core/safety/urlGuard.d.ts +37 -0
- package/dist/core/safety/urlGuard.js +206 -0
- package/dist/core/subagent/subagentRunner.d.ts +1 -1
- package/dist/core/subagent/subagentRunner.js +2 -2
- package/dist/core/toolOutput/reduction.d.ts +25 -0
- package/dist/core/toolOutput/reduction.js +23 -0
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +6 -4
- package/dist/llm/hazeTools.d.ts +133 -16
- package/dist/llm/hazeTools.js +205 -31
- package/dist/llm/initPrompt.js +2 -1
- package/dist/llm/systemPrompt.js +3 -1
- package/dist/llm/toolResultTypes.d.ts +1 -1
- package/dist/llm/webFetch.d.ts +57 -0
- package/dist/llm/webFetch.js +270 -0
- package/dist/ui/components/MarkdownText.d.ts +2 -0
- package/dist/ui/components/MarkdownText.js +116 -3
- package/package.json +17 -10
|
@@ -7,13 +7,11 @@ const DEFAULT_BUDGET_THRESHOLD = 0.15;
|
|
|
7
7
|
function resolveBudgetThreshold(explicit) {
|
|
8
8
|
if (typeof explicit === 'number' && Number.isFinite(explicit))
|
|
9
9
|
return Math.min(1, Math.max(0, explicit));
|
|
10
|
-
const envValue = Number.parseFloat(process.env.HAZE_CONTEXT_BUDGET_SHARE ?? '');
|
|
11
|
-
if (Number.isFinite(envValue))
|
|
12
|
-
return Math.min(1, Math.max(0, envValue));
|
|
13
10
|
return DEFAULT_BUDGET_THRESHOLD;
|
|
14
11
|
}
|
|
15
|
-
const CONTEXT_FILE_NAMES = ['
|
|
16
|
-
|
|
12
|
+
const CONTEXT_FILE_NAMES = ['CLAUDE.md', 'AGENTS.md'];
|
|
13
|
+
/** Maximum characters of a context file included in every request's system context. */
|
|
14
|
+
export const MAX_CONTEXT_FILE_CHARS = 20_000;
|
|
17
15
|
function uniqueExistingAncestors(fromDir) {
|
|
18
16
|
const dirs = [];
|
|
19
17
|
let current = path.resolve(fromDir);
|
|
@@ -35,17 +33,7 @@ function displayPath(filePath) {
|
|
|
35
33
|
return `~/${path.relative(home, filePath)}`;
|
|
36
34
|
return filePath;
|
|
37
35
|
}
|
|
38
|
-
|
|
39
|
-
const candidates = [];
|
|
40
|
-
for (const name of CONTEXT_FILE_NAMES) {
|
|
41
|
-
candidates.push(path.join(HAZE_DIR, name));
|
|
42
|
-
}
|
|
43
|
-
for (const dir of uniqueExistingAncestors(cwd)) {
|
|
44
|
-
for (const name of CONTEXT_FILE_NAMES) {
|
|
45
|
-
candidates.push(path.join(dir, name));
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
const seen = new Set();
|
|
36
|
+
async function readContextCandidates(candidates, seen = new Set()) {
|
|
49
37
|
const contextFiles = [];
|
|
50
38
|
for (const candidate of candidates) {
|
|
51
39
|
const absolute = path.resolve(candidate);
|
|
@@ -67,6 +55,49 @@ export async function readContextFiles(cwd = process.cwd()) {
|
|
|
67
55
|
}
|
|
68
56
|
return contextFiles;
|
|
69
57
|
}
|
|
58
|
+
async function scopedDirsForPath(targetPath, cwd) {
|
|
59
|
+
const root = path.resolve(cwd);
|
|
60
|
+
const absolute = path.resolve(root, targetPath);
|
|
61
|
+
const relative = path.relative(root, absolute);
|
|
62
|
+
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
63
|
+
return [];
|
|
64
|
+
const stat = await fs.stat(absolute).catch(() => null);
|
|
65
|
+
let current = stat?.isDirectory() ? absolute : path.dirname(absolute);
|
|
66
|
+
const dirs = [];
|
|
67
|
+
while (current.startsWith(root + path.sep) && current !== root) {
|
|
68
|
+
dirs.push(current);
|
|
69
|
+
current = path.dirname(current);
|
|
70
|
+
}
|
|
71
|
+
return dirs.reverse();
|
|
72
|
+
}
|
|
73
|
+
export async function readContextFiles(cwd = process.cwd()) {
|
|
74
|
+
const candidates = [
|
|
75
|
+
path.join(os.homedir(), '.claude', 'CLAUDE.md'),
|
|
76
|
+
path.join(HAZE_DIR, 'AGENTS.md'),
|
|
77
|
+
];
|
|
78
|
+
for (const dir of uniqueExistingAncestors(cwd)) {
|
|
79
|
+
for (const name of CONTEXT_FILE_NAMES)
|
|
80
|
+
candidates.push(path.join(dir, name));
|
|
81
|
+
}
|
|
82
|
+
return await readContextCandidates(candidates);
|
|
83
|
+
}
|
|
84
|
+
export async function readScopedContextFilesForPath(targetPath, options = {}) {
|
|
85
|
+
const cwd = options.cwd ?? process.cwd();
|
|
86
|
+
const loaded = new Set(options.alreadyLoadedPaths ?? []);
|
|
87
|
+
const candidates = [];
|
|
88
|
+
for (const dir of await scopedDirsForPath(targetPath, cwd)) {
|
|
89
|
+
for (const name of CONTEXT_FILE_NAMES)
|
|
90
|
+
candidates.push(path.join(dir, name));
|
|
91
|
+
}
|
|
92
|
+
const alreadySeen = new Set();
|
|
93
|
+
for (const loadedPath of loaded) {
|
|
94
|
+
if (loadedPath.startsWith('~/'))
|
|
95
|
+
alreadySeen.add(path.resolve(os.homedir(), loadedPath.slice(2)));
|
|
96
|
+
else
|
|
97
|
+
alreadySeen.add(path.resolve(cwd, loadedPath));
|
|
98
|
+
}
|
|
99
|
+
return await readContextCandidates(candidates, alreadySeen);
|
|
100
|
+
}
|
|
70
101
|
export function contextFileDiagnostics(files) {
|
|
71
102
|
return files.map(file => ({
|
|
72
103
|
path: file.path,
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import type { HazeSettings, HazeProviderSettings } from './settings.js';
|
|
2
|
-
export declare const DEFAULT_PROVIDER_NAME = "openrouter";
|
|
3
|
-
export declare const DEFAULT_PROVIDER_URL = "https://openrouter.ai/api/v1";
|
|
4
|
-
export declare const DEFAULT_MODEL = "x-ai/grok-build-0.1";
|
|
5
2
|
export type ModelResolution = {
|
|
6
3
|
status: 'found';
|
|
7
4
|
provider: HazeProviderSettings;
|
|
@@ -15,11 +12,11 @@ export type ModelResolution = {
|
|
|
15
12
|
};
|
|
16
13
|
export declare function configuredProviders(settings: HazeSettings): HazeProviderSettings[];
|
|
17
14
|
export declare function findProvider(settings: HazeSettings, name: string): HazeProviderSettings | undefined;
|
|
18
|
-
export declare function activeProvider(settings: HazeSettings): HazeProviderSettings;
|
|
15
|
+
export declare function activeProvider(settings: HazeSettings): HazeProviderSettings | undefined;
|
|
19
16
|
export declare function activeModel(settings: HazeSettings): {
|
|
20
17
|
provider: HazeProviderSettings;
|
|
21
18
|
model: string;
|
|
22
|
-
};
|
|
19
|
+
} | undefined;
|
|
23
20
|
export declare function resolveModelSelector(settings: HazeSettings, selector: string): ModelResolution;
|
|
24
21
|
export declare function modelSelector(provider: HazeProviderSettings, model: string): string;
|
|
25
22
|
export declare function upsertProvider(settings: HazeSettings, provider: HazeProviderSettings): HazeProviderSettings[];
|
package/dist/config/providers.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
// Used only to migrate legacy single-provider OpenRouter settings (apiKey/baseURL)
|
|
2
|
+
// into the providers array. There is no default provider or model anymore: users
|
|
3
|
+
// must configure a provider themselves via /provider.
|
|
4
|
+
const LEGACY_OPENROUTER_URL = 'https://openrouter.ai/api/v1';
|
|
4
5
|
function normalizeModels(models, fallbackModel) {
|
|
5
6
|
const values = Array.isArray(models) ? models : [];
|
|
6
7
|
const normalized = values
|
|
@@ -28,18 +29,17 @@ export function configuredProviders(settings) {
|
|
|
28
29
|
const providers = (settings.providers ?? [])
|
|
29
30
|
.map(provider => normalizeProvider(provider))
|
|
30
31
|
.filter((provider) => Boolean(provider));
|
|
31
|
-
|
|
32
|
-
|
|
32
|
+
// Legacy single-provider settings. Only migrate when the user actually supplied
|
|
33
|
+
// a base URL or API key — never invent a provider or model out of nothing.
|
|
34
|
+
const legacyUrl = settings.baseURL ?? (settings.apiKey ? LEGACY_OPENROUTER_URL : undefined);
|
|
35
|
+
if (legacyUrl && !providers.some(provider => provider.name === 'openrouter')) {
|
|
33
36
|
providers.unshift({
|
|
34
|
-
name:
|
|
37
|
+
name: 'openrouter',
|
|
35
38
|
url: legacyUrl,
|
|
36
39
|
...(settings.apiKey ? { key: settings.apiKey } : {}),
|
|
37
|
-
models: normalizeModels([], settings.model
|
|
40
|
+
models: normalizeModels([], settings.model),
|
|
38
41
|
});
|
|
39
42
|
}
|
|
40
|
-
if (providers.length === 0) {
|
|
41
|
-
return [{ name: DEFAULT_PROVIDER_NAME, url: DEFAULT_PROVIDER_URL, models: [settings.model ?? DEFAULT_MODEL] }];
|
|
42
|
-
}
|
|
43
43
|
return providers;
|
|
44
44
|
}
|
|
45
45
|
export function findProvider(settings, name) {
|
|
@@ -51,9 +51,13 @@ export function activeProvider(settings) {
|
|
|
51
51
|
}
|
|
52
52
|
export function activeModel(settings) {
|
|
53
53
|
const provider = activeProvider(settings);
|
|
54
|
+
if (!provider)
|
|
55
|
+
return undefined;
|
|
54
56
|
const model = settings.model && provider.models.includes(settings.model)
|
|
55
57
|
? settings.model
|
|
56
|
-
: settings.model ?? provider.models[0]
|
|
58
|
+
: settings.model ?? provider.models[0];
|
|
59
|
+
if (!model)
|
|
60
|
+
return undefined;
|
|
57
61
|
return { provider, model };
|
|
58
62
|
}
|
|
59
63
|
export function resolveModelSelector(settings, selector) {
|
|
@@ -84,5 +88,5 @@ export function upsertProvider(settings, provider) {
|
|
|
84
88
|
return [...providers, provider];
|
|
85
89
|
}
|
|
86
90
|
export function providerHasKey(settings, provider) {
|
|
87
|
-
return Boolean(provider.key ?? (provider.name ===
|
|
91
|
+
return Boolean(provider.key ?? (provider.name === 'openrouter' ? settings.apiKey : undefined));
|
|
88
92
|
}
|
|
@@ -40,7 +40,9 @@ function compactJsonValue(value, toolName) {
|
|
|
40
40
|
'ok', 'path', 'command', 'code', 'signal', 'timedOut', 'durationMs', 'reasonCode',
|
|
41
41
|
'bytes', 'created', 'replacements', 'totalMatches', 'returnedMatches',
|
|
42
42
|
'omittedMatches', 'truncated', 'nextOffset', 'totalLines', 'startLine', 'endLine',
|
|
43
|
-
'validationSummary', 'classification', 'summary', 'counts',
|
|
43
|
+
'validationSummary', 'classification', 'summary', 'counts', 'filterName', 'reducerName',
|
|
44
|
+
'contentKind', 'lossy', 'rawHandle', 'handle', 'rawChars', 'returnedChars',
|
|
45
|
+
'rawTokensEstimate', 'returnedTokensEstimate', 'estimatedSavedTokens', 'savingsPct',
|
|
44
46
|
];
|
|
45
47
|
const compacted = { compacted: true, toolName };
|
|
46
48
|
for (const key of keys)
|
|
@@ -53,8 +55,17 @@ function compactJsonValue(value, toolName) {
|
|
|
53
55
|
const details = candidate;
|
|
54
56
|
compacted[stream] = {
|
|
55
57
|
...(typeof details.handle === 'string' ? { handle: details.handle } : {}),
|
|
58
|
+
...(typeof details.rawHandle === 'string' ? { rawHandle: details.rawHandle } : {}),
|
|
59
|
+
...(typeof details.filterName === 'string' ? { filterName: details.filterName } : {}),
|
|
60
|
+
...(typeof details.reducerName === 'string' ? { reducerName: details.reducerName } : {}),
|
|
61
|
+
...(typeof details.contentKind === 'string' ? { contentKind: details.contentKind } : {}),
|
|
62
|
+
...(typeof details.lossy === 'boolean' ? { lossy: details.lossy } : {}),
|
|
56
63
|
...(typeof details.truncated === 'boolean' ? { truncated: details.truncated } : {}),
|
|
57
64
|
...(typeof details.omittedChars === 'number' ? { omittedChars: details.omittedChars } : {}),
|
|
65
|
+
...(typeof details.rawTokensEstimate === 'number' ? { rawTokensEstimate: details.rawTokensEstimate } : {}),
|
|
66
|
+
...(typeof details.returnedTokensEstimate === 'number' ? { returnedTokensEstimate: details.returnedTokensEstimate } : {}),
|
|
67
|
+
...(typeof details.estimatedSavedTokens === 'number' ? { estimatedSavedTokens: details.estimatedSavedTokens } : {}),
|
|
68
|
+
...(typeof details.savingsPct === 'number' ? { savingsPct: details.savingsPct } : {}),
|
|
58
69
|
};
|
|
59
70
|
}
|
|
60
71
|
return compacted;
|
|
@@ -5,7 +5,12 @@ export interface StoredToolOutputPage {
|
|
|
5
5
|
totalChars: number;
|
|
6
6
|
content: string;
|
|
7
7
|
truncated: boolean;
|
|
8
|
+
query?: string;
|
|
9
|
+
matches?: number;
|
|
8
10
|
}
|
|
9
11
|
export declare function storeToolOutput(content: string): string;
|
|
10
|
-
export declare function readToolOutput(handle: string, offset?: number, limit?: number
|
|
12
|
+
export declare function readToolOutput(handle: string, offset?: number, limit?: number, options?: {
|
|
13
|
+
query?: string;
|
|
14
|
+
contextLines?: number;
|
|
15
|
+
}): StoredToolOutputPage | undefined;
|
|
11
16
|
export declare function clearToolOutputs(): void;
|
|
@@ -12,10 +12,42 @@ export function storeToolOutput(content) {
|
|
|
12
12
|
}
|
|
13
13
|
return handle;
|
|
14
14
|
}
|
|
15
|
-
|
|
15
|
+
function escapeRegex(value) {
|
|
16
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
17
|
+
}
|
|
18
|
+
function searchOutput(output, query, limit, contextLines = 2) {
|
|
19
|
+
const pattern = new RegExp(escapeRegex(query), 'i');
|
|
20
|
+
const lines = output.split(/\r?\n/);
|
|
21
|
+
const ranges = [];
|
|
22
|
+
for (let index = 0; index < lines.length; index++) {
|
|
23
|
+
if (!pattern.test(lines[index] ?? ''))
|
|
24
|
+
continue;
|
|
25
|
+
const start = Math.max(0, index - contextLines);
|
|
26
|
+
const end = Math.min(lines.length - 1, index + contextLines);
|
|
27
|
+
const previous = ranges.at(-1);
|
|
28
|
+
if (previous && start <= previous.end + 1)
|
|
29
|
+
previous.end = Math.max(previous.end, end);
|
|
30
|
+
else
|
|
31
|
+
ranges.push({ start, end });
|
|
32
|
+
}
|
|
33
|
+
const chunks = [];
|
|
34
|
+
for (const range of ranges) {
|
|
35
|
+
if (chunks.length)
|
|
36
|
+
chunks.push('--');
|
|
37
|
+
for (let index = range.start; index <= range.end; index++)
|
|
38
|
+
chunks.push(`${index + 1}: ${lines[index] ?? ''}`);
|
|
39
|
+
}
|
|
40
|
+
const content = chunks.join('\n');
|
|
41
|
+
return { handle: '', offset: 0, totalChars: output.length, content: content.slice(0, limit), truncated: content.length > limit, query, matches: ranges.length };
|
|
42
|
+
}
|
|
43
|
+
export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
|
|
16
44
|
const output = outputs.get(handle);
|
|
17
45
|
if (output == null)
|
|
18
46
|
return undefined;
|
|
47
|
+
if (options?.query?.trim()) {
|
|
48
|
+
const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
|
|
49
|
+
return { ...result, handle };
|
|
50
|
+
}
|
|
19
51
|
const safeOffset = Math.min(Math.max(0, offset), output.length);
|
|
20
52
|
const content = output.slice(safeOffset, safeOffset + limit);
|
|
21
53
|
const nextOffset = safeOffset + content.length < output.length ? safeOffset + content.length : undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function stripAnsi(text: string): string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/* eslint-disable no-control-regex */
|
|
2
|
+
export function stripAnsi(text) {
|
|
3
|
+
// Covers common CSI/OSC escape sequences emitted by CLIs.
|
|
4
|
+
return text
|
|
5
|
+
.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, '')
|
|
6
|
+
.replace(/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g, '');
|
|
7
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const COMMAND_SEPARATORS = /\s*(?:&&|\|\||;|\|)\s*/;
|
|
2
|
+
const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=.*/;
|
|
3
|
+
const WRAPPER_COMMANDS = new Set(['sudo', 'command', 'env', 'time', 'nohup']);
|
|
4
|
+
function shellWords(segment) {
|
|
5
|
+
return segment.match(/(?:[^\s"']+|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+/g) ?? [];
|
|
6
|
+
}
|
|
7
|
+
function unquote(value) {
|
|
8
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))
|
|
9
|
+
return value.slice(1, -1);
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function stripWrapperWords(words) {
|
|
13
|
+
let index = 0;
|
|
14
|
+
while (index < words.length) {
|
|
15
|
+
const word = unquote(words[index] ?? '');
|
|
16
|
+
if (ASSIGNMENT.test(word)) {
|
|
17
|
+
index += 1;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (word === 'env') {
|
|
21
|
+
index += 1;
|
|
22
|
+
while (index < words.length) {
|
|
23
|
+
const envWord = unquote(words[index] ?? '');
|
|
24
|
+
if (envWord === '-u')
|
|
25
|
+
index += 2;
|
|
26
|
+
else if (envWord.startsWith('-'))
|
|
27
|
+
index += 1;
|
|
28
|
+
else if (ASSIGNMENT.test(envWord))
|
|
29
|
+
index += 1;
|
|
30
|
+
else
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (word === 'sudo') {
|
|
36
|
+
index += 1;
|
|
37
|
+
while (index < words.length && unquote(words[index] ?? '').startsWith('-'))
|
|
38
|
+
index += 1;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (WRAPPER_COMMANDS.has(word)) {
|
|
42
|
+
index += 1;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
return words.slice(index).join(' ');
|
|
48
|
+
}
|
|
49
|
+
export function commandCandidates(command) {
|
|
50
|
+
const rawSegments = command.split(COMMAND_SEPARATORS).map(segment => segment.trim()).filter(Boolean);
|
|
51
|
+
const candidates = new Set([command.trim()]);
|
|
52
|
+
for (const segment of rawSegments) {
|
|
53
|
+
candidates.add(segment);
|
|
54
|
+
const normalized = stripWrapperWords(shellWords(segment)).trim();
|
|
55
|
+
if (normalized)
|
|
56
|
+
candidates.add(normalized);
|
|
57
|
+
}
|
|
58
|
+
return [...candidates].filter(Boolean);
|
|
59
|
+
}
|
|
60
|
+
export function commandMatches(command, matcher) {
|
|
61
|
+
return commandCandidates(command).some(candidate => typeof matcher === 'function' ? matcher(candidate) : matcher.test(candidate));
|
|
62
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type LineFilterDefinition = {
|
|
2
|
+
name: string;
|
|
3
|
+
matchCommand: RegExp | ((command: string) => boolean);
|
|
4
|
+
stripAnsi?: boolean;
|
|
5
|
+
replace?: Array<{
|
|
6
|
+
pattern: RegExp;
|
|
7
|
+
replacement: string;
|
|
8
|
+
}>;
|
|
9
|
+
matchOutput?: RegExp;
|
|
10
|
+
unless?: RegExp;
|
|
11
|
+
stripLinesMatching?: RegExp[];
|
|
12
|
+
keepLinesMatching?: RegExp[];
|
|
13
|
+
truncateLinesAt?: number;
|
|
14
|
+
headLines?: number;
|
|
15
|
+
tailLines?: number;
|
|
16
|
+
maxLines?: number;
|
|
17
|
+
onEmpty?: string;
|
|
18
|
+
};
|
|
19
|
+
export type AppliedLineFilter = {
|
|
20
|
+
text: string;
|
|
21
|
+
filtered: boolean;
|
|
22
|
+
warning?: string;
|
|
23
|
+
};
|
|
24
|
+
export declare function applyLineFilter(definition: LineFilterDefinition, command: string, text: string): AppliedLineFilter | undefined;
|
|
25
|
+
export declare function findLineFilter(definitions: LineFilterDefinition[], command: string): LineFilterDefinition | undefined;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { stripAnsi as stripAnsiCodes } from './ansi.js';
|
|
2
|
+
import { commandMatches } from './command.js';
|
|
3
|
+
function matchesCommand(definition, command) {
|
|
4
|
+
return commandMatches(command, definition.matchCommand);
|
|
5
|
+
}
|
|
6
|
+
function capLines(lines, definition) {
|
|
7
|
+
if (definition.headLines != null && lines.length > definition.headLines) {
|
|
8
|
+
const omitted = lines.length - definition.headLines;
|
|
9
|
+
return [...lines.slice(0, definition.headLines), `[... ${omitted} lines omitted ...]`];
|
|
10
|
+
}
|
|
11
|
+
if (definition.tailLines != null && lines.length > definition.tailLines) {
|
|
12
|
+
const omitted = lines.length - definition.tailLines;
|
|
13
|
+
return [`[... ${omitted} lines omitted ...]`, ...lines.slice(-definition.tailLines)];
|
|
14
|
+
}
|
|
15
|
+
if (definition.maxLines != null && lines.length > definition.maxLines) {
|
|
16
|
+
const head = Math.ceil(definition.maxLines * 0.6);
|
|
17
|
+
const tail = Math.max(0, definition.maxLines - head);
|
|
18
|
+
const omitted = lines.length - definition.maxLines;
|
|
19
|
+
return [...lines.slice(0, head), `[... ${omitted} lines omitted ...]`, ...lines.slice(lines.length - tail)];
|
|
20
|
+
}
|
|
21
|
+
return lines;
|
|
22
|
+
}
|
|
23
|
+
export function applyLineFilter(definition, command, text) {
|
|
24
|
+
if (!matchesCommand(definition, command))
|
|
25
|
+
return undefined;
|
|
26
|
+
try {
|
|
27
|
+
let next = text;
|
|
28
|
+
if (definition.stripAnsi)
|
|
29
|
+
next = stripAnsiCodes(next);
|
|
30
|
+
for (const replacement of definition.replace ?? [])
|
|
31
|
+
next = next.replace(replacement.pattern, replacement.replacement);
|
|
32
|
+
const matched = definition.matchOutput?.test(next) ?? false;
|
|
33
|
+
const vetoed = definition.unless?.test(next) ?? false;
|
|
34
|
+
if (matched && !vetoed)
|
|
35
|
+
return { text: definition.onEmpty ?? next, filtered: true };
|
|
36
|
+
const hadTrailingNewline = /\r?\n$/.test(next);
|
|
37
|
+
let lines = next.split(/\r?\n/);
|
|
38
|
+
if (hadTrailingNewline)
|
|
39
|
+
lines.pop();
|
|
40
|
+
if (definition.stripLinesMatching?.length) {
|
|
41
|
+
lines = lines.filter(line => !definition.stripLinesMatching?.some(pattern => pattern.test(line)));
|
|
42
|
+
}
|
|
43
|
+
if (definition.keepLinesMatching?.length) {
|
|
44
|
+
lines = lines.filter(line => definition.keepLinesMatching?.some(pattern => pattern.test(line)));
|
|
45
|
+
}
|
|
46
|
+
if (definition.truncateLinesAt != null) {
|
|
47
|
+
lines = lines.map(line => line.length > definition.truncateLinesAt ? `${line.slice(0, definition.truncateLinesAt)}…` : line);
|
|
48
|
+
}
|
|
49
|
+
lines = capLines(lines, definition);
|
|
50
|
+
next = lines.join('\n');
|
|
51
|
+
if (!next.trim() && definition.onEmpty)
|
|
52
|
+
next = definition.onEmpty;
|
|
53
|
+
return { text: next, filtered: next !== text };
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
57
|
+
return { text, filtered: false, warning: `line filter ${definition.name} failed: ${message}` };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function findLineFilter(definitions, command) {
|
|
61
|
+
return definitions.find(definition => matchesCommand(definition, command));
|
|
62
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function reduceJsonOutput(stdout: string, stderr: string): string | undefined;
|
|
2
|
+
export declare function reduceUnifiedDiffOutput(stdout: string, stderr: string): string | undefined;
|
|
3
|
+
export declare function reduceGenericLogOutput(stdout: string, stderr: string): string | undefined;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
function clip(line, max = 220) {
|
|
2
|
+
return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
|
|
3
|
+
}
|
|
4
|
+
function tryParseJson(text) {
|
|
5
|
+
const trimmed = text.trim();
|
|
6
|
+
if (!trimmed || !/^(?:\[|\{)/.test(trimmed))
|
|
7
|
+
return undefined;
|
|
8
|
+
try {
|
|
9
|
+
return JSON.parse(trimmed);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function summarizeJsonValue(value, depth = 0) {
|
|
16
|
+
if (depth > 2)
|
|
17
|
+
return '[nested omitted]';
|
|
18
|
+
if (Array.isArray(value))
|
|
19
|
+
return { type: 'array', length: value.length, sample: value.slice(0, 3).map(item => summarizeJsonValue(item, depth + 1)) };
|
|
20
|
+
if (typeof value === 'object' && value != null) {
|
|
21
|
+
const source = value;
|
|
22
|
+
const keys = Object.keys(source);
|
|
23
|
+
const result = { keys };
|
|
24
|
+
for (const key of keys.slice(0, 20))
|
|
25
|
+
result[key] = summarizeJsonValue(source[key], depth + 1);
|
|
26
|
+
if (keys.length > 20)
|
|
27
|
+
result.omittedKeys = keys.length - 20;
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
export function reduceJsonOutput(stdout, stderr) {
|
|
33
|
+
const stream = stdout.trim() ? stdout : stderr;
|
|
34
|
+
const parsed = tryParseJson(stream);
|
|
35
|
+
if (parsed == null)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (Array.isArray(parsed)) {
|
|
38
|
+
if (parsed.length < 8 && stream.length < 4000)
|
|
39
|
+
return undefined;
|
|
40
|
+
const objectItems = parsed.filter(item => typeof item === 'object' && item != null && !Array.isArray(item));
|
|
41
|
+
const keyCounts = new Map();
|
|
42
|
+
for (const item of objectItems)
|
|
43
|
+
for (const key of Object.keys(item))
|
|
44
|
+
keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1);
|
|
45
|
+
const commonKeys = [...keyCounts.entries()].filter(([, count]) => count >= Math.max(2, objectItems.length * 0.7)).map(([key]) => key).slice(0, 30);
|
|
46
|
+
const anomalyIndexes = objectItems
|
|
47
|
+
.map((item, index) => ({ item, index, hasSignal: Object.values(item).some(value => typeof value === 'string' && /error|fail|warn|denied|invalid|missing/i.test(value)) }))
|
|
48
|
+
.filter(entry => entry.hasSignal)
|
|
49
|
+
.slice(0, 5);
|
|
50
|
+
const sampleIndexes = new Set([0, 1, 2, parsed.length - 2, parsed.length - 1, ...anomalyIndexes.map(entry => entry.index)].filter(index => index >= 0 && index < parsed.length));
|
|
51
|
+
const sample = [...sampleIndexes].sort((a, b) => a - b).map(index => ({ index, value: summarizeJsonValue(parsed[index]) }));
|
|
52
|
+
return JSON.stringify({ jsonSummary: { type: 'array', items: parsed.length, commonKeys, sample, omittedItems: Math.max(0, parsed.length - sample.length) } }, null, 2);
|
|
53
|
+
}
|
|
54
|
+
if (typeof parsed === 'object' && parsed != null && stream.length >= 4000) {
|
|
55
|
+
return JSON.stringify({ jsonSummary: summarizeJsonValue(parsed) }, null, 2);
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
export function reduceUnifiedDiffOutput(stdout, stderr) {
|
|
60
|
+
const text = stdout || stderr;
|
|
61
|
+
if (!/(^|\n)(diff --git |@@\s+-\d|---\s+\S+\n\+\+\+\s+\S+)/.test(text))
|
|
62
|
+
return undefined;
|
|
63
|
+
const lines = text.split(/\r?\n/);
|
|
64
|
+
if (lines.length < 80 && text.length < 8000)
|
|
65
|
+
return undefined;
|
|
66
|
+
const files = [];
|
|
67
|
+
let current;
|
|
68
|
+
for (const line of lines) {
|
|
69
|
+
const fileLine = line.match(/^diff --git a\/(.*?) b\//) ?? line.match(/^\+\+\+\s+b\/(.+)$/);
|
|
70
|
+
if (fileLine && (!current || line.startsWith('diff --git'))) {
|
|
71
|
+
current = { file: fileLine[1] ?? 'unknown', hunks: [], added: 0, removed: 0, body: [] };
|
|
72
|
+
files.push(current);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (!current)
|
|
76
|
+
continue;
|
|
77
|
+
if (line.startsWith('@@')) {
|
|
78
|
+
current.hunks.push(line);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
82
|
+
current.added += 1;
|
|
83
|
+
if (current.body.length < 8)
|
|
84
|
+
current.body.push(clip(line));
|
|
85
|
+
}
|
|
86
|
+
else if (line.startsWith('-') && !line.startsWith('---')) {
|
|
87
|
+
current.removed += 1;
|
|
88
|
+
if (current.body.length < 8)
|
|
89
|
+
current.body.push(clip(line));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (!files.length)
|
|
93
|
+
return undefined;
|
|
94
|
+
const totalAdded = files.reduce((sum, file) => sum + file.added, 0);
|
|
95
|
+
const totalRemoved = files.reduce((sum, file) => sum + file.removed, 0);
|
|
96
|
+
const output = [`diff: ${files.length} file${files.length === 1 ? '' : 's'} changed, +${totalAdded}/-${totalRemoved}`];
|
|
97
|
+
for (const file of files.slice(0, 30)) {
|
|
98
|
+
output.push(` ${file.file} +${file.added}/-${file.removed}${file.hunks.length ? ` (${file.hunks.length} hunks)` : ''}`);
|
|
99
|
+
for (const hunk of file.hunks.slice(0, 4))
|
|
100
|
+
output.push(` ${hunk}`);
|
|
101
|
+
for (const body of file.body.slice(0, 6))
|
|
102
|
+
output.push(` ${body}`);
|
|
103
|
+
}
|
|
104
|
+
if (files.length > 30)
|
|
105
|
+
output.push(` ... ${files.length - 30} more files`);
|
|
106
|
+
return output.join('\n');
|
|
107
|
+
}
|
|
108
|
+
export function reduceGenericLogOutput(stdout, stderr) {
|
|
109
|
+
const text = `${stdout}${stderr ? `\n${stderr}` : ''}`;
|
|
110
|
+
const lines = text.split(/\r?\n/).filter(Boolean);
|
|
111
|
+
if (lines.length < 120 && text.length < 12000)
|
|
112
|
+
return undefined;
|
|
113
|
+
const signalIndexes = new Set();
|
|
114
|
+
const signalPattern = /\b(error|failed|failure|fatal|exception|panic|traceback|assert|warning|warn|denied|timeout|timed out)\b/i;
|
|
115
|
+
lines.forEach((line, index) => {
|
|
116
|
+
if (!signalPattern.test(line))
|
|
117
|
+
return;
|
|
118
|
+
for (let i = Math.max(0, index - 2); i <= Math.min(lines.length - 1, index + 4); i++)
|
|
119
|
+
signalIndexes.add(i);
|
|
120
|
+
});
|
|
121
|
+
const summaryLines = lines.filter(line => /\b(\d+\s+(passed|failed|skipped|errors?)|tests?\s+run|build\s+(success|failed)|success|failed)\b/i.test(line)).slice(-10);
|
|
122
|
+
const selected = [...signalIndexes].sort((a, b) => a - b).slice(0, 120).map(index => clip(lines[index] ?? ''));
|
|
123
|
+
if (!selected.length && !summaryLines.length)
|
|
124
|
+
return undefined;
|
|
125
|
+
const output = [`log summary: ${lines.length} lines, ${signalIndexes.size} signal/context lines`];
|
|
126
|
+
if (summaryLines.length)
|
|
127
|
+
output.push('', 'summaries:', ...summaryLines.map(line => ` ${clip(line)}`));
|
|
128
|
+
if (selected.length)
|
|
129
|
+
output.push('', 'signal excerpts:', ...selected.map(line => ` ${line}`));
|
|
130
|
+
const omitted = lines.length - selected.length - summaryLines.length;
|
|
131
|
+
if (omitted > 0)
|
|
132
|
+
output.push('', `... ${omitted} non-signal lines omitted`);
|
|
133
|
+
return output.join('\n');
|
|
134
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function reduceGitOutput(command: string, stdout: string, stderr: string): string | undefined;
|