@denizokcu/haze 0.7.0 → 0.9.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 (96) hide show
  1. package/CHANGELOG.md +35 -9
  2. package/README.md +37 -35
  3. package/dist/cli/chat/inputSuggestions.js +2 -2
  4. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  5. package/dist/cli/chat/sessionRecorder.js +23 -8
  6. package/dist/cli/commands/chat.js +136 -124
  7. package/dist/cli/commands/chatModes.js +1 -1
  8. package/dist/cli/commands/commandHelp.js +2 -2
  9. package/dist/cli/commands/commands.d.ts +1 -1
  10. package/dist/cli/commands/commands.js +1 -1
  11. package/dist/cli/commands/formatters.d.ts +6 -0
  12. package/dist/cli/commands/formatters.js +41 -3
  13. package/dist/cli/commands/logsCommand.js +7 -21
  14. package/dist/cli/commands/mcpWizard.js +24 -2
  15. package/dist/cli/commands/providerWizard.js +18 -5
  16. package/dist/cli/commands/runCommand.js +7 -15
  17. package/dist/cli/commands/settingsSummary.js +3 -1
  18. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  19. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  20. package/dist/cli/commands/streaming.js +99 -51
  21. package/dist/cli/commands/wizardPrompts.js +1 -1
  22. package/dist/cli/commands/wizardSuggestions.js +3 -2
  23. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  24. package/dist/cli/commands/wizardTransition.js +44 -0
  25. package/dist/config/contextFiles.js +6 -3
  26. package/dist/config/endpointSecurity.d.ts +2 -0
  27. package/dist/config/endpointSecurity.js +28 -0
  28. package/dist/config/inputHistory.js +4 -2
  29. package/dist/config/privateStorage.d.ts +6 -0
  30. package/dist/config/privateStorage.js +61 -0
  31. package/dist/config/providers.js +5 -9
  32. package/dist/config/settings.d.ts +1 -0
  33. package/dist/config/settings.js +55 -3
  34. package/dist/config/updateCheck.js +4 -2
  35. package/dist/core/agent/compaction.js +2 -2
  36. package/dist/core/agent/errors.js +1 -1
  37. package/dist/core/agent/requestAssembly.d.ts +1 -0
  38. package/dist/core/agent/requestAssembly.js +13 -0
  39. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  40. package/dist/core/agent/toolOutputStore.js +32 -11
  41. package/dist/core/bashOutput/registry.js +11 -9
  42. package/dist/core/goal/completionPolicy.d.ts +0 -28
  43. package/dist/core/goal/completionPolicy.js +1 -89
  44. package/dist/core/io/boundedRead.d.ts +15 -0
  45. package/dist/core/io/boundedRead.js +97 -0
  46. package/dist/core/limits/byteBudgets.d.ts +13 -0
  47. package/dist/core/limits/byteBudgets.js +13 -0
  48. package/dist/core/log/llmLog.d.ts +10 -0
  49. package/dist/core/log/llmLog.js +59 -13
  50. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  51. package/dist/core/persistence/orderedFileWriter.js +29 -0
  52. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  53. package/dist/core/process/runBoundedProcess.js +80 -0
  54. package/dist/core/session/sessionStore.js +48 -25
  55. package/dist/core/subagent/subagentRunner.d.ts +252 -9
  56. package/dist/core/subagent/subagentRunner.js +14 -19
  57. package/dist/core/toolOutput/reduction.d.ts +2 -0
  58. package/dist/core/toolOutput/reduction.js +12 -0
  59. package/dist/core/validation/outputParser.js +5 -3
  60. package/dist/llm/client.d.ts +2 -2
  61. package/dist/llm/client.js +19 -3
  62. package/dist/llm/hazeTools.d.ts +8103 -364
  63. package/dist/llm/hazeTools.js +43 -33
  64. package/dist/llm/initPrompt.js +1 -1
  65. package/dist/llm/lsp.d.ts +21 -3
  66. package/dist/llm/lsp.js +65 -14
  67. package/dist/llm/lspTools.d.ts +2358 -101
  68. package/dist/llm/mcp.d.ts +1 -1
  69. package/dist/llm/mcp.js +65 -16
  70. package/dist/llm/requestContext.d.ts +1 -0
  71. package/dist/llm/requestContext.js +6 -3
  72. package/dist/llm/systemPrompt.js +2 -2
  73. package/dist/llm/toolResultTypes.d.ts +1 -1
  74. package/dist/llm/tools/bashTool.d.ts +603 -5
  75. package/dist/llm/tools/bashTool.js +23 -60
  76. package/dist/llm/tools/fetchTool.d.ts +1201 -65
  77. package/dist/llm/tools/fetchTool.js +2 -1
  78. package/dist/llm/tools/grepRunner.d.ts +15 -0
  79. package/dist/llm/tools/grepRunner.js +85 -0
  80. package/dist/llm/tools/storedOutputTool.d.ts +351 -10
  81. package/dist/llm/tools/taskTool.d.ts +629 -28
  82. package/dist/llm/tools/toolContext.d.ts +7 -2
  83. package/dist/llm/tools/toolContext.js +11 -2
  84. package/dist/llm/webFetch.js +31 -21
  85. package/dist/skills/SkillLoader.js +17 -5
  86. package/dist/skills/SkillRegistry.js +19 -6
  87. package/dist/skills/builder/SkillBuilder.js +7 -7
  88. package/dist/skills/types.d.ts +5 -0
  89. package/dist/ui/components/TextInput.d.ts +7 -0
  90. package/dist/ui/components/TextInput.js +10 -0
  91. package/dist/utils/modelName.d.ts +2 -0
  92. package/dist/utils/modelName.js +15 -0
  93. package/dist/utils/path.d.ts +2 -0
  94. package/dist/utils/path.js +9 -4
  95. package/examples/skills/files/SKILL.md +1 -1
  96. package/package.json +14 -14
@@ -1,95 +1,7 @@
1
- import { isActionRequest, isPlanOnlyRequest, isValidationRequest } from './requestClassifier.js';
2
- export function looksIncomplete(text) {
3
- return /\b(incomplete|what remains|remains:|remaining:|next:|unfinished|not implemented|not created|no tests exist|created no docs|has not been|have not been|not yet|never executed|not executed|not run|cannot retry|cannot write|cannot validate|tool budget reached|tool slice reached)/i.test(text);
4
- }
5
- export function looksTruncated(text) {
6
- const trimmed = text.trimEnd();
7
- if (!trimmed)
8
- return false;
9
- const lines = trimmed.split('\n');
10
- const lastLine = lines[lines.length - 1].trim();
11
- if (/^#{1,6}\s+\S/.test(lastLine))
12
- return true;
13
- if (/^(-{3,}|\*{3,}|_{3,})$/.test(lastLine))
14
- return true;
15
- if (trimmed.endsWith(':'))
16
- return true;
17
- const fences = (trimmed.match(/```/g) ?? []).length;
18
- if (fences % 2 !== 0)
19
- return true;
20
- return false;
21
- }
22
- export function looksBlocked(text) {
23
- return /\b(blocked|blocker|needs user|need user|missing permission|permission denied|missing dependency|no practical validation|unable to validate|can't validate|cannot validate)\b/i.test(text);
24
- }
25
- export function completionDecision(input) {
26
- const likelyPlanOnlyRequest = isPlanOnlyRequest(input.request);
27
- const likelyActionRequest = isActionRequest(input.request);
28
- const likelyValidationRequest = isValidationRequest(input.request);
29
- const assistantAdmitsIncomplete = looksIncomplete(input.assistantText) || looksTruncated(input.assistantText);
30
- const assistantReportsBlocker = looksBlocked(input.assistantText);
31
- const requestCompletedByTools = input.mutatingToolSucceeded && input.validationToolSucceeded && !input.editRecoveryPath;
32
- const changedActionNeedsValidation = likelyActionRequest
33
- && !likelyPlanOnlyRequest
34
- && input.mutatingToolSucceeded
35
- && !input.validationToolSucceeded
36
- && !input.validationToolFailed
37
- && !input.editRecoveryPath
38
- && !assistantReportsBlocker;
39
- const needsActionContinuation = likelyActionRequest
40
- && !likelyPlanOnlyRequest
41
- && !requestCompletedByTools
42
- && ((input.sawReadOnlyTool && !input.mutatingToolSucceeded) || input.validationToolFailed || input.editFileFailed || assistantAdmitsIncomplete);
43
- const needsValidationContinuation = (likelyValidationRequest || changedActionNeedsValidation)
44
- && !requestCompletedByTools
45
- && !input.validationToolSucceeded
46
- && !assistantReportsBlocker;
47
- const stateLines = [
48
- `User goal: ${input.request}`,
49
- input.editRecoveryPath ? `Edit recovery path: ${input.editRecoveryPath}` : undefined,
50
- input.editRecoveryReasonCode ? `Edit failure reason: ${input.editRecoveryReasonCode}` : undefined,
51
- input.mutatingToolSucceeded ? 'Files changed in this turn: yes' : 'Files changed in this turn: no',
52
- input.validationToolSucceeded ? 'Validation status: passed' : input.validationToolFailed ? 'Validation status: failed' : 'Validation status: not run',
53
- ].filter((line) => line !== undefined).join('\n');
54
- let continuationPrompt;
55
- if (input.editFileFailed) {
56
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: call readFile on the exact edit recovery path first. Then use the latest line-numbered output with replaceLines, or a corrected editFile call, to complete the requested change. Continue with relevant validation if practical. Do not stop with a summary while tools are available.`;
57
- }
58
- else if (input.validationToolFailed && input.mutatingToolSucceeded) {
59
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: Validation failed after files changed in this task. Use the validation summary/output to inspect the first relevant failure, make one focused fix if it is plausibly caused by this change, then rerun the same relevant validation once. If it is an environment/dependency/unrelated failure, finish with Status: blocked or Status: partial and concrete evidence.`;
60
- }
61
- else if (needsValidationContinuation) {
62
- continuationPrompt = changedActionNeedsValidation
63
- ? `State:\n${stateLines}\n\nRequired next action: files changed for this request, but no validation has run. Run the smallest relevant test/typecheck/build command you can identify. If no practical validation exists, finish with the final status template and say why validation was not run.`
64
- : `State:\n${stateLines}\n\nRequired next action: run the requested validation now. Summarize only after the command finishes.`;
65
- }
66
- else if (input.mutatingToolSucceeded && assistantAdmitsIncomplete) {
67
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: your previous response described unfinished work. Continue with the remaining in-scope edits and validation for this same request. Do not summarize a plan unless concretely blocked.`;
68
- }
69
- else if (needsActionContinuation) {
70
- continuationPrompt = `State:\n${stateLines}\n\nRequired next action: you inspected files but have not made the requested change yet. Edit or write the necessary files now. Do not summarize a plan unless concretely blocked.`;
71
- }
72
- return {
73
- needsActionContinuation,
74
- needsValidationContinuation,
75
- requestCompletedByTools,
76
- assistantAdmitsIncomplete,
77
- assistantReportsBlocker,
78
- continuationPrompt,
79
- };
80
- }
81
1
  export function toolLoopBudgetPrompt() {
82
- return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so Haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
2
+ return 'Tool slice reached for this model step — tools are no longer callable in this turn. Stop attempting to describe or announce tool calls (e.g. "Let me install", "Now I\'ll run", "Let me X"); those phrases imply tool use you cannot perform. Answer once: either the final status template (current-turn changes + validation evidence) or, if incomplete, a single short line stating the next concrete unfinished action so haze can continue in a fresh tool slice. Do not repeat yourself, do not loop, do not emit XML/JSON tool-call syntax.';
83
3
  }
84
4
  export function repeatedToolCallPrompt(toolNames) {
85
5
  const names = [...new Set(toolNames)].join(', ');
86
6
  return `You already called ${names || 'a tool'} with identical input in this turn. Do not call the same tool again with the same arguments. Use the existing tool result already in the conversation, choose a different concrete tool/input if genuinely needed, or give the final/blocked status now.`;
87
7
  }
88
- export function postContinuationPrompt() {
89
- return 'Your previous response still described unfinished work, missing validation, or a tool-budget issue. If tools are available, complete the remaining edit or run the final validation now. Only call something blocked for a concrete tool failure, missing dependency/permission, or unavoidable ambiguity.';
90
- }
91
- export function noTextAfterToolPrompt(allowTools) {
92
- return allowTools
93
- ? 'Continue the original request now. If it asks for a change, edit or write the necessary files. If it asks to run or verify tests, run the command. Do not provide only a retrospective summary unless blocked or needing a user decision.'
94
- : 'Continue from the tool result and answer my original request. Do not call tools. Use the final status template for implementation-like requests; summarize only current-turn changes and validation; do not recap unrelated earlier tasks.';
95
- }
@@ -0,0 +1,15 @@
1
+ export interface BoundedUtf8Line {
2
+ line: string;
3
+ lineNumber: number;
4
+ oversized: boolean;
5
+ }
6
+ export declare function iterateBoundedUtf8Lines(file: string, maxLineBytes: number): AsyncGenerator<BoundedUtf8Line>;
7
+ export declare function readUtf8LinesPage(file: string, offset: number, limit: number): Promise<{
8
+ lines: string[];
9
+ totalLines: number;
10
+ }>;
11
+ export declare function readUtf8Prefix(file: string, maxBytes: number): Promise<{
12
+ content: string;
13
+ truncated: boolean;
14
+ totalBytes: number;
15
+ }>;
@@ -0,0 +1,97 @@
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
+ export async function* iterateBoundedUtf8Lines(file, maxLineBytes) {
6
+ const input = createReadStream(file);
7
+ let lineNumber = 0;
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 readUtf8LinesPage(file, offset, limit) {
54
+ const lines = [];
55
+ let totalLines = 0;
56
+ for await (const entry of iterateBoundedUtf8Lines(file, TEXT_LINE_BYTES)) {
57
+ totalLines = entry.lineNumber;
58
+ if (totalLines >= offset && lines.length < limit) {
59
+ lines.push(entry.oversized ? `${entry.line}\n[Line truncated at ${TEXT_LINE_BYTES} bytes]` : entry.line);
60
+ }
61
+ }
62
+ const stat = await fs.stat(file);
63
+ if (stat.size === 0) {
64
+ totalLines = 1;
65
+ if (offset <= 1 && limit > 0)
66
+ lines.push('');
67
+ }
68
+ else {
69
+ const handle = await fs.open(file, 'r');
70
+ try {
71
+ const last = Buffer.alloc(1);
72
+ await handle.read(last, 0, 1, stat.size - 1);
73
+ if (last[0] === 10) {
74
+ totalLines++;
75
+ if (totalLines >= offset && lines.length < limit)
76
+ lines.push('');
77
+ }
78
+ }
79
+ finally {
80
+ await handle.close();
81
+ }
82
+ }
83
+ return { lines, totalLines };
84
+ }
85
+ export async function readUtf8Prefix(file, maxBytes) {
86
+ const stat = await fs.stat(file);
87
+ if (maxBytes <= 0)
88
+ return { content: '', truncated: stat.size > 0, totalBytes: stat.size };
89
+ const input = createReadStream(file, { start: 0, end: maxBytes - 1 });
90
+ const chunks = [];
91
+ for await (const chunk of input)
92
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
93
+ const buffer = Buffer.concat(chunks);
94
+ const decoder = new StringDecoder('utf8');
95
+ const content = decoder.write(buffer) + (stat.size <= maxBytes ? decoder.end() : '');
96
+ return { content, truncated: stat.size > maxBytes, totalBytes: stat.size };
97
+ }
@@ -0,0 +1,13 @@
1
+ export declare const BASH_STREAM_BYTES: number;
2
+ export declare const GREP_STREAM_BYTES: number;
3
+ export declare const PROCESS_STDERR_BYTES: number;
4
+ export declare const TOOL_OUTPUT_ENTRY_BYTES: number;
5
+ export declare const TOOL_OUTPUT_TOTAL_BYTES: number;
6
+ export declare const LSP_DOCUMENT_BYTES: number;
7
+ export declare const LSP_HEADER_BYTES: number;
8
+ export declare const LSP_FRAME_BYTES: number;
9
+ export declare const LSP_BUFFER_BYTES: number;
10
+ export declare const SKILL_MARKDOWN_BYTES: number;
11
+ export declare const EXACT_MUTATION_BYTES: number;
12
+ export declare const JSONL_LINE_BYTES: number;
13
+ export declare const TEXT_LINE_BYTES: number;
@@ -0,0 +1,13 @@
1
+ export const BASH_STREAM_BYTES = 2 * 1024 * 1024;
2
+ export const GREP_STREAM_BYTES = 8 * 1024 * 1024;
3
+ export const PROCESS_STDERR_BYTES = 64 * 1024;
4
+ export const TOOL_OUTPUT_ENTRY_BYTES = 2 * 1024 * 1024;
5
+ export const TOOL_OUTPUT_TOTAL_BYTES = 16 * 1024 * 1024;
6
+ export const LSP_DOCUMENT_BYTES = 2 * 1024 * 1024;
7
+ export const LSP_HEADER_BYTES = 16 * 1024;
8
+ export const LSP_FRAME_BYTES = 8 * 1024 * 1024;
9
+ export const LSP_BUFFER_BYTES = LSP_FRAME_BYTES + LSP_HEADER_BYTES;
10
+ export const SKILL_MARKDOWN_BYTES = 256 * 1024;
11
+ export const EXACT_MUTATION_BYTES = 8 * 1024 * 1024;
12
+ export const JSONL_LINE_BYTES = 4 * 1024 * 1024;
13
+ export const TEXT_LINE_BYTES = 1024 * 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>;
@@ -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 fs.ensureDir(LOGS_DIR);
16
+ await ensurePrivateDir(LOGS_DIR);
13
17
  const id = logFileId();
14
18
  const file = logFilePath(id);
15
- await fs.writeFile(file, '');
16
- return { id, file };
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
- const line = JSON.stringify(entry) + '\n';
20
- await fs.appendFile(log.file, line);
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 fs.ensureDir(LOGS_DIR);
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 raw = await fs.readFile(file, 'utf8').catch(() => '');
47
- return raw.split('\n').filter(Boolean).flatMap(line => {
48
- try {
49
- return [JSON.parse(line)];
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
- catch {
52
- return [];
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,27 @@
1
+ export interface BoundedStream {
2
+ text: string;
3
+ totalBytes: number;
4
+ retainedBytes: number;
5
+ omittedBytes: number;
6
+ }
7
+ export interface BoundedProcessResult {
8
+ code: number | null;
9
+ signal: NodeJS.Signals | null;
10
+ stdout: BoundedStream;
11
+ stderr: BoundedStream;
12
+ timedOut: boolean;
13
+ aborted: boolean;
14
+ forced: boolean;
15
+ durationMs: number;
16
+ error?: string;
17
+ }
18
+ export declare function runBoundedProcess(input: {
19
+ command: string;
20
+ args: string[];
21
+ cwd: string;
22
+ timeoutMs: number;
23
+ signal?: AbortSignal;
24
+ maxStdoutBytes: number;
25
+ maxStderrBytes: number;
26
+ killGraceMs?: number;
27
+ }): Promise<BoundedProcessResult>;
@@ -0,0 +1,80 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ function collector(limit) {
4
+ const chunks = [];
5
+ let totalBytes = 0;
6
+ let retainedBytes = 0;
7
+ return {
8
+ add(chunk) {
9
+ totalBytes += chunk.length;
10
+ const remaining = limit - retainedBytes;
11
+ if (remaining > 0) {
12
+ const kept = chunk.subarray(0, remaining);
13
+ chunks.push(kept);
14
+ retainedBytes += kept.length;
15
+ }
16
+ },
17
+ result() {
18
+ const decoder = new StringDecoder('utf8');
19
+ const text = chunks.map(chunk => decoder.write(chunk)).join('') + (totalBytes === retainedBytes ? decoder.end() : '');
20
+ return { text, totalBytes, retainedBytes, omittedBytes: totalBytes - retainedBytes };
21
+ },
22
+ };
23
+ }
24
+ export async function runBoundedProcess(input) {
25
+ const startedAt = Date.now();
26
+ const stdout = collector(input.maxStdoutBytes);
27
+ const stderr = collector(input.maxStderrBytes);
28
+ if (input.signal?.aborted) {
29
+ return { code: null, signal: null, stdout: stdout.result(), stderr: stderr.result(), timedOut: false, aborted: true, forced: false, durationMs: 0 };
30
+ }
31
+ const detached = process.platform !== 'win32';
32
+ const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'] });
33
+ let timedOut = false;
34
+ let aborted = false;
35
+ let forced = false;
36
+ let killTimer;
37
+ const killTree = (signal) => {
38
+ if (child.pid == null)
39
+ return;
40
+ if (process.platform === 'win32') {
41
+ if (signal === 'SIGKILL')
42
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
43
+ else
44
+ child.kill('SIGTERM');
45
+ }
46
+ else {
47
+ try {
48
+ process.kill(-child.pid, signal);
49
+ }
50
+ catch {
51
+ child.kill(signal);
52
+ }
53
+ }
54
+ };
55
+ const terminate = () => {
56
+ killTree('SIGTERM');
57
+ killTimer ??= setTimeout(() => { forced = true; killTree('SIGKILL'); }, input.killGraceMs ?? 500);
58
+ killTimer.unref?.();
59
+ };
60
+ const timeout = setTimeout(() => { timedOut = true; terminate(); }, input.timeoutMs);
61
+ const onAbort = () => { aborted = true; terminate(); };
62
+ input.signal?.addEventListener('abort', onAbort, { once: true });
63
+ child.stdout.on('data', (chunk) => stdout.add(chunk));
64
+ child.stderr.on('data', (chunk) => stderr.add(chunk));
65
+ return await new Promise(resolve => {
66
+ let settled = false;
67
+ const settle = (code, signal, error) => {
68
+ if (settled)
69
+ return;
70
+ settled = true;
71
+ clearTimeout(timeout);
72
+ if (killTimer)
73
+ clearTimeout(killTimer);
74
+ input.signal?.removeEventListener('abort', onAbort);
75
+ resolve({ code, signal, stdout: stdout.result(), stderr: stderr.result(), timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
76
+ };
77
+ child.once('error', error => settle(null, null, error.message));
78
+ child.once('close', (code, signal) => settle(code, signal));
79
+ });
80
+ }
@@ -3,6 +3,9 @@ import path from 'node:path';
3
3
  import fs from 'fs-extra';
4
4
  import { HAZE_DIR } from '../../config/paths.js';
5
5
  import { prepareSessionEntryForWrite } from './sessionSlimming.js';
6
+ import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
7
+ import { JSONL_LINE_BYTES } from '../limits/byteBudgets.js';
8
+ import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
6
9
  const DEFAULT_SESSIONS_DIR = path.join(HAZE_DIR, 'sessions');
7
10
  function cwdHash(cwd = process.cwd()) {
8
11
  return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
@@ -20,12 +23,13 @@ export async function createSession(options = {}) {
20
23
  const cwd = path.resolve(options.cwd ?? process.cwd());
21
24
  const id = newSessionId();
22
25
  const file = sessionFile(id, cwd, options.sessionsDir);
23
- await fs.ensureDir(path.dirname(file));
26
+ await ensurePrivateDir(path.dirname(file));
24
27
  await appendSessionEntry({ id, file, cwd }, { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion });
25
28
  return { id, file, cwd };
26
29
  }
27
30
  export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
28
31
  const dir = sessionDir(cwd, sessionsDir);
32
+ await ensurePrivateDir(dir);
29
33
  const files = (await fs.readdir(dir).catch(() => []))
30
34
  .filter(file => file.endsWith('.jsonl'))
31
35
  .sort();
@@ -39,8 +43,36 @@ export async function appendSessionEntry(session, entry) {
39
43
  const prepared = prepareSessionEntryForWrite(entry);
40
44
  if (!prepared)
41
45
  return;
42
- await fs.ensureDir(path.dirname(session.file));
43
- await fs.appendFile(session.file, `${JSON.stringify(prepared)}\n`, 'utf8');
46
+ await appendPrivateFile(session.file, `${JSON.stringify(prepared)}\n`);
47
+ }
48
+ const MAX_PARSE_ERRORS = 100;
49
+ async function scanSessionEntries(session, onEntry) {
50
+ await tightenPrivateFile(session.file);
51
+ const parseErrors = [];
52
+ let omittedErrors = 0;
53
+ const report = (message) => {
54
+ if (parseErrors.length < MAX_PARSE_ERRORS)
55
+ parseErrors.push(message);
56
+ else
57
+ omittedErrors++;
58
+ };
59
+ for await (const { line, lineNumber, oversized } of iterateBoundedUtf8Lines(session.file, JSONL_LINE_BYTES)) {
60
+ if (!line && !oversized)
61
+ continue;
62
+ if (oversized) {
63
+ report(`Line ${lineNumber}: exceeds ${JSONL_LINE_BYTES} byte limit`);
64
+ continue;
65
+ }
66
+ try {
67
+ onEntry(JSON.parse(line));
68
+ }
69
+ catch (error) {
70
+ report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
71
+ }
72
+ }
73
+ if (omittedErrors > 0)
74
+ parseErrors.push(`${omittedErrors} additional parse errors omitted.`);
75
+ return parseErrors;
44
76
  }
45
77
  /**
46
78
  * Read a session file and parse each non-empty line as a JSONL entry.
@@ -50,34 +82,25 @@ export async function appendSessionEntry(session, entry) {
50
82
  * loss in debug mode instead of silently dropping messages.
51
83
  */
52
84
  export async function readSessionEntries(session) {
53
- const raw = await fs.readFile(session.file, 'utf8');
54
85
  const entries = [];
55
- const parseErrors = [];
56
- // Number by true file position: a stray blank line (e.g. from corruption) must not shift
57
- // the reported line number away from where the malformed line actually sits.
58
- const lines = raw.split('\n');
59
- for (let i = 0; i < lines.length; i++) {
60
- const line = lines[i];
61
- if (!line)
62
- continue; // skip blank lines (e.g. the trailing newline)
63
- try {
64
- entries.push(JSON.parse(line));
65
- }
66
- catch (error) {
67
- parseErrors.push(`Line ${i + 1}: ${error instanceof Error ? error.message : String(error)}`);
68
- }
69
- }
86
+ const parseErrors = await scanSessionEntries(session, entry => entries.push(entry));
70
87
  return { entries, parseErrors };
71
88
  }
72
89
  export async function restoreConversation(session) {
73
- const { entries, parseErrors } = await readSessionEntries(session);
74
- const snapshots = entries.filter((entry) => entry.type === 'conversation_snapshot');
75
- return { messages: snapshots.at(-1)?.messages ?? [], parseErrors };
90
+ let messages = [];
91
+ const parseErrors = await scanSessionEntries(session, entry => {
92
+ if (entry.type === 'conversation_snapshot')
93
+ messages = entry.messages;
94
+ });
95
+ return { messages, parseErrors };
76
96
  }
77
97
  export async function restoreWorkState(session) {
78
- const { entries, parseErrors } = await readSessionEntries(session);
79
- const snapshots = entries.filter((entry) => entry.type === 'work_state_snapshot');
80
- return { state: snapshots.at(-1)?.state, parseErrors };
98
+ let state;
99
+ const parseErrors = await scanSessionEntries(session, entry => {
100
+ if (entry.type === 'work_state_snapshot')
101
+ state = entry.state;
102
+ });
103
+ return { state, parseErrors };
81
104
  }
82
105
  export function formatSession(session) {
83
106
  return `${session.id} · ${session.file}`;