@denizokcu/haze 0.3.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +50 -36
  3. package/dist/cli/commands/chat.d.ts +1 -1
  4. package/dist/cli/commands/chat.js +244 -94
  5. package/dist/cli/commands/commands.js +119 -114
  6. package/dist/cli/commands/streaming.d.ts +37 -5
  7. package/dist/cli/commands/streaming.js +455 -192
  8. package/dist/cli/contextReport.d.ts +1 -0
  9. package/dist/cli/contextReport.js +47 -0
  10. package/dist/config/contextFiles.d.ts +31 -0
  11. package/dist/config/contextFiles.js +97 -13
  12. package/dist/config/providers.d.ts +2 -5
  13. package/dist/config/providers.js +16 -12
  14. package/dist/core/agent/compaction.d.ts +3 -0
  15. package/dist/core/agent/compaction.js +23 -3
  16. package/dist/core/agent/contextBudget.d.ts +33 -0
  17. package/dist/core/agent/contextBudget.js +88 -0
  18. package/dist/core/agent/requestAssembly.d.ts +22 -0
  19. package/dist/core/agent/requestAssembly.js +157 -0
  20. package/dist/core/agent/toolOutputStore.d.ts +16 -0
  21. package/dist/core/agent/toolOutputStore.js +65 -0
  22. package/dist/core/agent/workState.d.ts +38 -0
  23. package/dist/core/agent/workState.js +89 -0
  24. package/dist/core/bashOutput/ansi.d.ts +1 -0
  25. package/dist/core/bashOutput/ansi.js +7 -0
  26. package/dist/core/bashOutput/command.d.ts +2 -0
  27. package/dist/core/bashOutput/command.js +62 -0
  28. package/dist/core/bashOutput/lineFilter.d.ts +25 -0
  29. package/dist/core/bashOutput/lineFilter.js +62 -0
  30. package/dist/core/bashOutput/reducers/content.d.ts +3 -0
  31. package/dist/core/bashOutput/reducers/content.js +134 -0
  32. package/dist/core/bashOutput/reducers/git.d.ts +1 -0
  33. package/dist/core/bashOutput/reducers/git.js +147 -0
  34. package/dist/core/bashOutput/reducers/search.d.ts +7 -0
  35. package/dist/core/bashOutput/reducers/search.js +76 -0
  36. package/dist/core/bashOutput/reducers/validation.d.ts +2 -0
  37. package/dist/core/bashOutput/reducers/validation.js +41 -0
  38. package/dist/core/bashOutput/registry.d.ts +4 -0
  39. package/dist/core/bashOutput/registry.js +126 -0
  40. package/dist/core/bashOutput/types.d.ts +46 -0
  41. package/dist/core/bashOutput/types.js +1 -0
  42. package/dist/core/goal/completionPolicy.d.ts +1 -0
  43. package/dist/core/goal/completionPolicy.js +5 -1
  44. package/dist/core/goal/sessionGoal.d.ts +2 -0
  45. package/dist/core/goal/sessionGoal.js +8 -1
  46. package/dist/core/log/llmLog.d.ts +68 -0
  47. package/dist/core/log/llmLog.js +55 -0
  48. package/dist/core/safety/urlGuard.d.ts +37 -0
  49. package/dist/core/safety/urlGuard.js +206 -0
  50. package/dist/core/session/sessionStore.d.ts +6 -0
  51. package/dist/core/session/sessionStore.js +5 -0
  52. package/dist/core/subagent/subagentRunner.d.ts +4 -1
  53. package/dist/core/subagent/subagentRunner.js +5 -15
  54. package/dist/core/toolOutput/reduction.d.ts +25 -0
  55. package/dist/core/toolOutput/reduction.js +23 -0
  56. package/dist/core/validation/outputParser.js +15 -2
  57. package/dist/llm/client.d.ts +40 -1
  58. package/dist/llm/client.js +51 -5
  59. package/dist/llm/hazeTools.d.ts +165 -23
  60. package/dist/llm/hazeTools.js +317 -65
  61. package/dist/llm/initPrompt.js +2 -1
  62. package/dist/llm/systemPrompt.d.ts +6 -1
  63. package/dist/llm/systemPrompt.js +44 -81
  64. package/dist/llm/toolResultTypes.d.ts +1 -1
  65. package/dist/llm/webFetch.d.ts +57 -0
  66. package/dist/llm/webFetch.js +270 -0
  67. package/dist/skills/builder/SkillBuilder.d.ts +16 -2
  68. package/dist/skills/builder/SkillBuilder.js +68 -65
  69. package/dist/skills/skillTools.d.ts +2 -19
  70. package/dist/skills/skillTools.js +28 -19
  71. package/dist/ui/components/MarkdownText.d.ts +2 -0
  72. package/dist/ui/components/MarkdownText.js +116 -3
  73. package/package.json +18 -10
@@ -0,0 +1,16 @@
1
+ export interface StoredToolOutputPage {
2
+ handle: string;
3
+ offset: number;
4
+ nextOffset?: number;
5
+ totalChars: number;
6
+ content: string;
7
+ truncated: boolean;
8
+ query?: string;
9
+ matches?: number;
10
+ }
11
+ export declare function storeToolOutput(content: string): string;
12
+ export declare function readToolOutput(handle: string, offset?: number, limit?: number, options?: {
13
+ query?: string;
14
+ contextLines?: number;
15
+ }): StoredToolOutputPage | undefined;
16
+ export declare function clearToolOutputs(): void;
@@ -0,0 +1,65 @@
1
+ import crypto from 'node:crypto';
2
+ const outputs = new Map();
3
+ const MAX_STORED_OUTPUTS = 100;
4
+ export function storeToolOutput(content) {
5
+ const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
6
+ outputs.set(handle, content);
7
+ while (outputs.size > MAX_STORED_OUTPUTS) {
8
+ const oldest = outputs.keys().next().value;
9
+ if (!oldest)
10
+ break;
11
+ outputs.delete(oldest);
12
+ }
13
+ return handle;
14
+ }
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) {
44
+ const output = outputs.get(handle);
45
+ if (output == null)
46
+ return undefined;
47
+ if (options?.query?.trim()) {
48
+ const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
49
+ return { ...result, handle };
50
+ }
51
+ const safeOffset = Math.min(Math.max(0, offset), output.length);
52
+ const content = output.slice(safeOffset, safeOffset + limit);
53
+ const nextOffset = safeOffset + content.length < output.length ? safeOffset + content.length : undefined;
54
+ return {
55
+ handle,
56
+ offset: safeOffset,
57
+ ...(nextOffset == null ? {} : { nextOffset }),
58
+ totalChars: output.length,
59
+ content,
60
+ truncated: nextOffset != null,
61
+ };
62
+ }
63
+ export function clearToolOutputs() {
64
+ outputs.clear();
65
+ }
@@ -0,0 +1,38 @@
1
+ import type { RequestIntent } from '../goal/requestClassifier.js';
2
+ export type WorkFileAction = 'read' | 'created' | 'modified';
3
+ export type WorkValidationStatus = 'passed' | 'failed';
4
+ export interface WorkState {
5
+ goal: string;
6
+ intent: RequestIntent;
7
+ successCriteria: string[];
8
+ constraints: string[];
9
+ decisions: Array<{
10
+ decision: string;
11
+ reason?: string;
12
+ }>;
13
+ files: Array<{
14
+ path: string;
15
+ action: WorkFileAction;
16
+ note?: string;
17
+ }>;
18
+ validations: Array<{
19
+ command: string;
20
+ status: WorkValidationStatus;
21
+ summary: string;
22
+ }>;
23
+ blockers: string[];
24
+ pending: string[];
25
+ nextAction?: string;
26
+ phase: string;
27
+ revision: number;
28
+ }
29
+ export interface WorkToolEvent {
30
+ toolName: string;
31
+ input?: unknown;
32
+ success: boolean;
33
+ output?: unknown;
34
+ duplicateSkipped?: boolean;
35
+ }
36
+ export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[]): WorkState;
37
+ export declare function observeWorkToolEvent(state: WorkState, event: WorkToolEvent): WorkState;
38
+ export declare function workStatePrompt(state: WorkState): string;
@@ -0,0 +1,89 @@
1
+ function inputString(input, key) {
2
+ return typeof input === 'object' && input != null && key in input && typeof input[key] === 'string'
3
+ ? input[key]
4
+ : undefined;
5
+ }
6
+ function upsertFile(state, path, action, note) {
7
+ const existing = state.files.find(file => file.path === path);
8
+ if (existing) {
9
+ if (action !== 'read')
10
+ existing.action = action;
11
+ if (note)
12
+ existing.note = note;
13
+ }
14
+ else {
15
+ state.files.push({ path, action, ...(note ? { note } : {}) });
16
+ }
17
+ }
18
+ function outputOk(output, success) {
19
+ return success && !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
20
+ }
21
+ function outputSummary(output) {
22
+ if (typeof output !== 'object' || output == null)
23
+ return '';
24
+ if ('validationSummary' in output && typeof output.validationSummary === 'object' && output.validationSummary != null && 'summaryText' in output.validationSummary) {
25
+ return String(output.validationSummary.summaryText);
26
+ }
27
+ if ('error' in output && typeof output.error === 'string')
28
+ return output.error;
29
+ if ('code' in output)
30
+ return `exit ${String(output.code)}`;
31
+ return '';
32
+ }
33
+ export function createWorkState(goal, intent, successCriteria) {
34
+ return {
35
+ goal,
36
+ intent,
37
+ successCriteria: [...successCriteria],
38
+ constraints: [],
39
+ decisions: [],
40
+ files: [],
41
+ validations: [],
42
+ blockers: [],
43
+ pending: [],
44
+ phase: 'starting',
45
+ revision: 0,
46
+ };
47
+ }
48
+ export function observeWorkToolEvent(state, event) {
49
+ if (event.duplicateSkipped)
50
+ return state;
51
+ const ok = outputOk(event.output, event.success);
52
+ const path = inputString(event.input, 'path');
53
+ if (ok && path && ['listFiles', 'readFile', 'grep'].includes(event.toolName)) {
54
+ if (event.toolName === 'readFile')
55
+ upsertFile(state, path, 'read');
56
+ state.phase = 'inspecting';
57
+ }
58
+ if (path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
59
+ if (ok) {
60
+ upsertFile(state, path, event.toolName === 'writeFile' ? 'created' : 'modified');
61
+ state.phase = 'editing';
62
+ state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
63
+ }
64
+ else {
65
+ state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
66
+ state.nextAction = `Read ${path}, then retry the edit with current content.`;
67
+ }
68
+ }
69
+ if (event.toolName === 'bash') {
70
+ const command = inputString(event.input, 'command');
71
+ if (command) {
72
+ const status = ok ? 'passed' : 'failed';
73
+ const existing = state.validations.find(validation => validation.command === command);
74
+ const summary = outputSummary(event.output);
75
+ if (existing)
76
+ Object.assign(existing, { status, summary });
77
+ else
78
+ state.validations.push({ command, status, summary });
79
+ state.phase = 'validating';
80
+ if (!ok)
81
+ state.blockers = [...new Set([...state.blockers, `Validation failed: ${command}`])];
82
+ }
83
+ }
84
+ state.revision += 1;
85
+ return state;
86
+ }
87
+ export function workStatePrompt(state) {
88
+ return `<work_state>\n${JSON.stringify(state)}\n</work_state>`;
89
+ }
@@ -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,2 @@
1
+ export declare function commandCandidates(command: string): string[];
2
+ export declare function commandMatches(command: string, matcher: RegExp | ((command: string) => boolean)): boolean;
@@ -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;
@@ -0,0 +1,147 @@
1
+ import { commandCandidates } from '../command.js';
2
+ function gitSubcommand(command) {
3
+ for (const candidate of commandCandidates(command)) {
4
+ const words = candidate.toLowerCase().split(/\s+/).filter(Boolean);
5
+ const gitIndex = words.indexOf('git');
6
+ if (gitIndex === -1)
7
+ continue;
8
+ for (let index = gitIndex + 1; index < words.length; index++) {
9
+ const word = words[index] ?? '';
10
+ if (word === '-c' || word === '--git-dir' || word === '--work-tree') {
11
+ index += 1;
12
+ continue;
13
+ }
14
+ if (word.startsWith('-'))
15
+ continue;
16
+ return word;
17
+ }
18
+ }
19
+ return undefined;
20
+ }
21
+ export function reduceGitOutput(command, stdout, stderr) {
22
+ const text = stdout || stderr;
23
+ const subcommand = gitSubcommand(command);
24
+ if (subcommand === 'status')
25
+ return reduceGitStatus(text);
26
+ if (subcommand === 'log')
27
+ return reduceGitLog(text);
28
+ if (subcommand === 'diff' || subcommand === 'show')
29
+ return reduceGitDiff(text, subcommand);
30
+ return undefined;
31
+ }
32
+ function cleanStatusItem(line) {
33
+ return line.trim().replace(/^\t/, '').replace(/^\s*(modified:|deleted:|new file:|renamed:)\s+/, match => `${match.trim()} `);
34
+ }
35
+ function reduceGitStatus(text) {
36
+ const lines = text.split(/\r?\n/).filter(Boolean);
37
+ if (lines.length === 0)
38
+ return 'git status: clean';
39
+ const porcelain = lines.filter(line => /^(?:##|\?\?|[ MADRCU?!]{2})\s+/.test(line));
40
+ if (porcelain.length) {
41
+ const branchLine = porcelain.find(line => line.startsWith('## '));
42
+ const branch = branchLine?.replace(/^##\s+/, '').split('...')[0];
43
+ const items = porcelain.filter(line => !line.startsWith('## '));
44
+ const untracked = items.filter(line => line.startsWith('??')).length;
45
+ const changed = items.length - untracked;
46
+ const shown = items.slice(0, 30);
47
+ return [`git status: ${branch ? `branch ${branch}, ` : ''}${changed} changed, ${untracked} untracked`, ...shown.map(line => ` ${line}`), ...(items.length > shown.length ? [` ... ${items.length - shown.length} more`] : [])].join('\n');
48
+ }
49
+ const branch = lines.find(line => line.startsWith('On branch '))?.replace('On branch ', '');
50
+ if (lines.some(line => /nothing to commit|working tree clean/i.test(line)))
51
+ return `git status: ${branch ? `branch ${branch}, ` : ''}clean`;
52
+ const items = [];
53
+ let inUntracked = false;
54
+ for (const line of lines) {
55
+ if (/^Untracked files:/.test(line)) {
56
+ inUntracked = true;
57
+ continue;
58
+ }
59
+ if (/^Changes/.test(line)) {
60
+ inUntracked = false;
61
+ continue;
62
+ }
63
+ if (/^\s*(modified:|deleted:|new file:|renamed:)/.test(line) || (inUntracked && /^\s+\S/.test(line) && !/\(use /.test(line))) {
64
+ const item = cleanStatusItem(line);
65
+ if (item && !/^\(use /.test(item))
66
+ items.push(inUntracked && !/^\w+:/.test(item) ? `?? ${item}` : item);
67
+ }
68
+ }
69
+ const untracked = items.filter(line => line.startsWith('?? ')).length;
70
+ const changed = items.length - untracked;
71
+ const shown = items.slice(0, 30);
72
+ return [`git status: ${branch ? `branch ${branch}, ` : ''}${changed} changed, ${untracked} untracked`, ...shown.map(line => ` ${line}`), ...(items.length > shown.length ? [` ... ${items.length - shown.length} more`] : [])].join('\n');
73
+ }
74
+ function reduceGitLog(text) {
75
+ const lines = text.split(/\r?\n/).filter(Boolean);
76
+ if (lines.length === 0)
77
+ return 'git log: no commits shown';
78
+ const commits = [];
79
+ let currentHash;
80
+ for (const line of lines) {
81
+ const commit = line.match(/^commit\s+([a-f0-9]{7,40})/i);
82
+ if (commit) {
83
+ currentHash = commit[1]?.slice(0, 12);
84
+ continue;
85
+ }
86
+ if (currentHash && /^\s{4}\S/.test(line)) {
87
+ commits.push(`${currentHash} ${line.trim()}`);
88
+ currentHash = undefined;
89
+ continue;
90
+ }
91
+ if (/^[a-f0-9]{7,40}\s+\S/.test(line))
92
+ commits.push(line.length > 180 ? `${line.slice(0, 180)}…` : line);
93
+ }
94
+ const rows = (commits.length ? commits : lines).slice(0, 30);
95
+ return [`git log: ${rows.length} commit${rows.length === 1 ? '' : 's'} shown`, ...rows.map(line => ` ${line.length > 180 ? `${line.slice(0, 180)}…` : line}`), ...(lines.length > rows.length && commits.length === 0 ? [` ... ${lines.length - rows.length} more lines`] : [])].join('\n');
96
+ }
97
+ function reduceGitDiff(text, label = 'diff') {
98
+ const lines = text.split(/\r?\n/);
99
+ const statLines = lines.filter(line => /\|\s+\d+\s+[-+]+/.test(line) || /files? changed/.test(line)).slice(0, 40);
100
+ const files = [];
101
+ let current;
102
+ for (const line of lines) {
103
+ if (line.startsWith('diff --git ')) {
104
+ const file = line.replace(/^diff --git a\//, '').replace(/ b\/.*/, '');
105
+ current = { file, hunks: [], body: [], added: 0, removed: 0 };
106
+ files.push(current);
107
+ continue;
108
+ }
109
+ if (!current)
110
+ continue;
111
+ if (line.startsWith('@@')) {
112
+ current.hunks.push(line);
113
+ current.body.push(line);
114
+ continue;
115
+ }
116
+ if (/^(?:---|\+\+\+|index |new file mode|deleted file mode|similarity index|rename from|rename to)/.test(line))
117
+ continue;
118
+ if (line.startsWith('+') && !line.startsWith('+++'))
119
+ current.added += 1;
120
+ if (line.startsWith('-') && !line.startsWith('---'))
121
+ current.removed += 1;
122
+ if ((line.startsWith('+') || line.startsWith('-')) && current.body.length < 12)
123
+ current.body.push(line.length > 180 ? `${line.slice(0, 180)}…` : line);
124
+ }
125
+ if (files.length === 0) {
126
+ const compact = statLines.length ? statLines : lines.filter(Boolean).slice(0, 60);
127
+ return [`git ${label}: ${compact.length ? 'summary' : 'no changes'}`, ...compact].join('\n');
128
+ }
129
+ const totalAdded = files.reduce((sum, file) => sum + file.added, 0);
130
+ const totalRemoved = files.reduce((sum, file) => sum + file.removed, 0);
131
+ const shownFiles = files.slice(0, 30);
132
+ const output = [`git ${label}: ${files.length} file${files.length === 1 ? '' : 's'} changed, +${totalAdded}/-${totalRemoved}`];
133
+ for (const file of shownFiles) {
134
+ output.push(` ${file.file} +${file.added}/-${file.removed}${file.hunks.length ? ` (${file.hunks.length} hunk${file.hunks.length === 1 ? '' : 's'})` : ''}`);
135
+ for (const hunk of file.hunks.slice(0, 4))
136
+ output.push(` ${hunk}`);
137
+ for (const bodyLine of file.body.filter(line => !line.startsWith('@@')).slice(0, 6))
138
+ output.push(` ${bodyLine}`);
139
+ if (file.body.length > file.hunks.length + 6)
140
+ output.push(` ... ${file.body.length - file.hunks.length - 6} diff lines omitted for this file`);
141
+ }
142
+ if (files.length > shownFiles.length)
143
+ output.push(` ... ${files.length - shownFiles.length} more files`);
144
+ if (statLines.length)
145
+ output.push('', ...statLines);
146
+ return output.join('\n');
147
+ }