@denizokcu/haze 0.8.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 (65) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +15 -13
  3. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  4. package/dist/cli/chat/sessionRecorder.js +23 -8
  5. package/dist/cli/commands/chat.js +90 -104
  6. package/dist/cli/commands/commands.d.ts +1 -1
  7. package/dist/cli/commands/commands.js +1 -1
  8. package/dist/cli/commands/formatters.js +3 -3
  9. package/dist/cli/commands/logsCommand.js +7 -21
  10. package/dist/cli/commands/mcpWizard.js +24 -2
  11. package/dist/cli/commands/providerWizard.js +18 -5
  12. package/dist/cli/commands/runCommand.js +7 -15
  13. package/dist/cli/commands/settingsSummary.js +3 -1
  14. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  15. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  16. package/dist/cli/commands/streaming.js +66 -29
  17. package/dist/cli/commands/wizardPrompts.js +1 -1
  18. package/dist/cli/commands/wizardSuggestions.js +2 -1
  19. package/dist/cli/commands/wizardTransition.d.ts +33 -0
  20. package/dist/cli/commands/wizardTransition.js +44 -0
  21. package/dist/config/contextFiles.js +6 -3
  22. package/dist/config/endpointSecurity.d.ts +2 -0
  23. package/dist/config/endpointSecurity.js +28 -0
  24. package/dist/config/inputHistory.js +4 -2
  25. package/dist/config/privateStorage.d.ts +6 -0
  26. package/dist/config/privateStorage.js +61 -0
  27. package/dist/config/settings.js +4 -4
  28. package/dist/config/updateCheck.js +4 -2
  29. package/dist/core/agent/toolOutputStore.d.ts +3 -0
  30. package/dist/core/agent/toolOutputStore.js +32 -11
  31. package/dist/core/goal/completionPolicy.d.ts +0 -28
  32. package/dist/core/goal/completionPolicy.js +0 -88
  33. package/dist/core/io/boundedRead.d.ts +15 -0
  34. package/dist/core/io/boundedRead.js +97 -0
  35. package/dist/core/limits/byteBudgets.d.ts +13 -0
  36. package/dist/core/limits/byteBudgets.js +13 -0
  37. package/dist/core/log/llmLog.d.ts +10 -0
  38. package/dist/core/log/llmLog.js +59 -13
  39. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  40. package/dist/core/persistence/orderedFileWriter.js +29 -0
  41. package/dist/core/process/runBoundedProcess.d.ts +27 -0
  42. package/dist/core/process/runBoundedProcess.js +80 -0
  43. package/dist/core/session/sessionStore.js +48 -25
  44. package/dist/core/subagent/subagentRunner.js +1 -1
  45. package/dist/llm/client.js +4 -1
  46. package/dist/llm/hazeTools.d.ts +410 -16
  47. package/dist/llm/hazeTools.js +36 -32
  48. package/dist/llm/lsp.d.ts +21 -3
  49. package/dist/llm/lsp.js +55 -13
  50. package/dist/llm/lspTools.d.ts +96 -48
  51. package/dist/llm/mcp.d.ts +1 -1
  52. package/dist/llm/mcp.js +65 -16
  53. package/dist/llm/requestContext.d.ts +1 -0
  54. package/dist/llm/requestContext.js +6 -3
  55. package/dist/llm/toolResultTypes.d.ts +1 -1
  56. package/dist/llm/tools/bashTool.d.ts +368 -16
  57. package/dist/llm/tools/bashTool.js +19 -57
  58. package/dist/llm/tools/grepRunner.d.ts +15 -0
  59. package/dist/llm/tools/grepRunner.js +85 -0
  60. package/dist/skills/SkillLoader.js +17 -5
  61. package/dist/skills/SkillRegistry.js +19 -6
  62. package/dist/skills/types.d.ts +5 -0
  63. package/dist/utils/path.d.ts +2 -0
  64. package/dist/utils/path.js +9 -4
  65. package/package.json +1 -1
@@ -0,0 +1,61 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { HAZE_DIR } from './paths.js';
4
+ const DIRECTORY_MODE = 0o700;
5
+ const FILE_MODE = 0o600;
6
+ export async function ensurePrivateDir(dir) {
7
+ const absolute = path.resolve(dir);
8
+ await fs.mkdir(absolute, { recursive: true, mode: DIRECTORY_MODE });
9
+ if (process.platform === 'win32')
10
+ return;
11
+ const hazeRoot = path.resolve(HAZE_DIR);
12
+ const relative = path.relative(hazeRoot, absolute);
13
+ if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
14
+ await fs.chmod(hazeRoot, DIRECTORY_MODE);
15
+ let current = hazeRoot;
16
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
17
+ current = path.join(current, segment);
18
+ await fs.chmod(current, DIRECTORY_MODE);
19
+ }
20
+ return;
21
+ }
22
+ await fs.chmod(absolute, DIRECTORY_MODE);
23
+ }
24
+ export async function ensurePrivateFile(file) {
25
+ await ensurePrivateDir(path.dirname(file));
26
+ const handle = await fs.open(file, 'a', FILE_MODE);
27
+ await handle.close();
28
+ if (process.platform !== 'win32')
29
+ await fs.chmod(file, FILE_MODE);
30
+ }
31
+ export async function tightenPrivateFile(file) {
32
+ await ensurePrivateDir(path.dirname(file));
33
+ if (process.platform !== 'win32')
34
+ await fs.chmod(file, FILE_MODE);
35
+ }
36
+ export async function appendPrivateFile(file, content) {
37
+ await ensurePrivateFile(file);
38
+ await fs.appendFile(file, content, { encoding: 'utf8', mode: FILE_MODE });
39
+ }
40
+ export async function writePrivateFileAtomic(file, content) {
41
+ await ensurePrivateDir(path.dirname(file));
42
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
43
+ let handle;
44
+ try {
45
+ handle = await fs.open(temp, 'wx', FILE_MODE);
46
+ await handle.writeFile(content, 'utf8');
47
+ await handle.sync();
48
+ await handle.close();
49
+ handle = undefined;
50
+ await fs.rename(temp, file);
51
+ if (process.platform !== 'win32')
52
+ await fs.chmod(file, FILE_MODE);
53
+ }
54
+ finally {
55
+ await handle?.close().catch(() => undefined);
56
+ await fs.rm(temp, { force: true }).catch(() => undefined);
57
+ }
58
+ }
59
+ export async function writePrivateJsonAtomic(file, value) {
60
+ await writePrivateFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
61
+ }
@@ -2,6 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { HAZE_DIR } from './paths.js';
5
+ import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
5
6
  export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
6
7
  const providerSchema = z.object({
7
8
  name: z.string(),
@@ -44,6 +45,8 @@ function settingsReadError(error) {
44
45
  }
45
46
  export async function readSettings() {
46
47
  try {
48
+ if (await fs.pathExists(SETTINGS_FILE))
49
+ await tightenPrivateFile(SETTINGS_FILE);
47
50
  const raw = await fs.readJson(SETTINGS_FILE);
48
51
  return settingsSchema.parse(raw);
49
52
  }
@@ -55,11 +58,8 @@ export async function readSettings() {
55
58
  }
56
59
  }
57
60
  export async function writeSettings(settings) {
58
- await fs.ensureDir(HAZE_DIR);
59
61
  const parsed = settingsSchema.parse(settings);
60
- const tempFile = `${SETTINGS_FILE}.${process.pid}.${Date.now()}.tmp`;
61
- await fs.writeJson(tempFile, parsed, { spaces: 2 });
62
- await fs.move(tempFile, SETTINGS_FILE, { overwrite: true });
62
+ await writePrivateJsonAtomic(SETTINGS_FILE, parsed);
63
63
  }
64
64
  export async function updateSettings(patch) {
65
65
  const next = { ...await readSettings(), ...patch };
@@ -4,6 +4,7 @@ import fs from 'fs-extra';
4
4
  import path from 'node:path';
5
5
  import { HAZE_DIR } from './paths.js';
6
6
  import { isNewer } from '../utils/version.js';
7
+ import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
7
8
  const execFile = promisify(execFileCallback);
8
9
  export const UPDATE_CHECK_FILE = path.join(HAZE_DIR, 'updateCheck.json');
9
10
  const DEFAULT_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24h
@@ -13,11 +14,12 @@ async function defaultExecVersion(packageName, options) {
13
14
  return stdout;
14
15
  }
15
16
  async function defaultReadStore(file) {
17
+ if (await fs.pathExists(file))
18
+ await tightenPrivateFile(file);
16
19
  return fs.readJson(file).catch(() => ({}));
17
20
  }
18
21
  async function defaultWriteStore(file, store) {
19
- await fs.ensureDir(path.dirname(file));
20
- await fs.writeJson(file, store, { spaces: 2 });
22
+ await writePrivateJsonAtomic(file, store);
21
23
  }
22
24
  /**
23
25
  * Non-blockingly check whether a newer version of `packageName` is published.
@@ -3,6 +3,9 @@ export interface StoredToolOutputPage {
3
3
  offset: number;
4
4
  nextOffset?: number;
5
5
  totalChars: number;
6
+ totalBytes: number;
7
+ retainedBytes: number;
8
+ omittedBytes: number;
6
9
  content: string;
7
10
  truncated: boolean;
8
11
  query?: string;
@@ -1,15 +1,30 @@
1
1
  import crypto from 'node:crypto';
2
+ import { TOOL_OUTPUT_ENTRY_BYTES, TOOL_OUTPUT_TOTAL_BYTES } from '../limits/byteBudgets.js';
2
3
  const outputs = new Map();
3
4
  const MAX_STORED_OUTPUTS = 100;
5
+ let storedBytes = 0;
6
+ function utf8Prefix(content, maxBytes) {
7
+ const bytes = Buffer.from(content, 'utf8');
8
+ if (bytes.length <= maxBytes)
9
+ return content;
10
+ let end = maxBytes;
11
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
12
+ end--;
13
+ return bytes.subarray(0, end).toString('utf8');
14
+ }
4
15
  export function storeToolOutput(content) {
5
16
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
6
- outputs.set(handle, content);
7
- // Synchronous, so the check+delete is atomic across async callers — no race.
8
- // Each call inserts exactly one entry, so a single eviction restores the cap.
9
- if (outputs.size > MAX_STORED_OUTPUTS) {
17
+ const originalBytes = Buffer.byteLength(content, 'utf8');
18
+ const retained = utf8Prefix(content, TOOL_OUTPUT_ENTRY_BYTES);
19
+ const bytes = Buffer.byteLength(retained, 'utf8');
20
+ outputs.set(handle, { content: retained, bytes, originalBytes });
21
+ storedBytes += bytes;
22
+ while (outputs.size > MAX_STORED_OUTPUTS || storedBytes > TOOL_OUTPUT_TOTAL_BYTES) {
10
23
  const oldest = outputs.keys().next().value;
11
- if (oldest)
12
- outputs.delete(oldest);
24
+ if (!oldest)
25
+ break;
26
+ storedBytes -= outputs.get(oldest)?.bytes ?? 0;
27
+ outputs.delete(oldest);
13
28
  }
14
29
  return handle;
15
30
  }
@@ -39,15 +54,17 @@ function searchOutput(output, query, limit, contextLines = 2) {
39
54
  chunks.push(`${index + 1}: ${lines[index] ?? ''}`);
40
55
  }
41
56
  const content = chunks.join('\n');
42
- return { handle: '', offset: 0, totalChars: output.length, content: content.slice(0, limit), truncated: content.length > limit, query, matches: ranges.length };
57
+ return { offset: 0, totalChars: output.length, content: content.slice(0, limit), truncated: content.length > limit, query, matches: ranges.length };
43
58
  }
44
59
  export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
45
- const output = outputs.get(handle);
46
- if (output == null)
60
+ const stored = outputs.get(handle);
61
+ if (stored == null)
47
62
  return undefined;
63
+ const output = stored.content;
48
64
  if (options?.query?.trim()) {
49
65
  const result = searchOutput(output, options.query.trim(), limit, options.contextLines);
50
- return { ...result, handle };
66
+ const omittedBytes = stored.originalBytes - stored.bytes;
67
+ return { ...result, handle, truncated: result.truncated || omittedBytes > 0, totalBytes: stored.originalBytes, retainedBytes: stored.bytes, omittedBytes };
51
68
  }
52
69
  const safeOffset = Math.min(Math.max(0, offset), output.length);
53
70
  const content = output.slice(safeOffset, safeOffset + limit);
@@ -57,10 +74,14 @@ export function readToolOutput(handle, offset = 0, limit = 12_000, options) {
57
74
  offset: safeOffset,
58
75
  ...(nextOffset == null ? {} : { nextOffset }),
59
76
  totalChars: output.length,
77
+ totalBytes: stored.originalBytes,
78
+ retainedBytes: stored.bytes,
79
+ omittedBytes: stored.originalBytes - stored.bytes,
60
80
  content,
61
- truncated: nextOffset != null,
81
+ truncated: nextOffset != null || stored.originalBytes > stored.bytes,
62
82
  };
63
83
  }
64
84
  export function clearToolOutputs() {
65
85
  outputs.clear();
86
+ storedBytes = 0;
66
87
  }
@@ -1,30 +1,2 @@
1
- import type { SessionGoal } from './sessionGoal.js';
2
- export declare function looksIncomplete(text: string): boolean;
3
- export declare function looksTruncated(text: string): boolean;
4
- export declare function looksBlocked(text: string): boolean;
5
- export interface CompletionPolicyInput {
6
- request: string;
7
- goal: SessionGoal;
8
- assistantText: string;
9
- sawReadOnlyTool: boolean;
10
- sawToolCall: boolean;
11
- mutatingToolSucceeded: boolean;
12
- validationToolSucceeded: boolean;
13
- validationToolFailed: boolean;
14
- editFileFailed: boolean;
15
- editRecoveryPath?: string;
16
- editRecoveryReasonCode?: string;
17
- }
18
- export interface CompletionDecision {
19
- needsActionContinuation: boolean;
20
- needsValidationContinuation: boolean;
21
- requestCompletedByTools: boolean;
22
- assistantAdmitsIncomplete: boolean;
23
- assistantReportsBlocker: boolean;
24
- continuationPrompt?: string;
25
- }
26
- export declare function completionDecision(input: CompletionPolicyInput): CompletionDecision;
27
1
  export declare function toolLoopBudgetPrompt(): string;
28
2
  export declare function repeatedToolCallPrompt(toolNames: string[]): string;
29
- export declare function postContinuationPrompt(): string;
30
- export declare function noTextAfterToolPrompt(allowTools: boolean): "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." | "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.";
@@ -1,83 +1,3 @@
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
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
  }
@@ -85,11 +5,3 @@ 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
+ }