@denizokcu/haze 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -1
- package/README.md +66 -25
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/contextReport.js +2 -0
- package/dist/cli/chat/fileMentionSuggestions.js +3 -2
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -2
- package/dist/cli/chat/messages.js +216 -33
- package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
- package/dist/cli/chat/sessionLifecycle.js +64 -14
- package/dist/cli/chat/sessionRecorder.js +75 -7
- package/dist/cli/chat/startupInfo.d.ts +0 -1
- package/dist/cli/chat/startupInfo.js +11 -15
- package/dist/cli/chat/wizardDispatch.js +111 -12
- package/dist/cli/commands/chat.d.ts +5 -0
- package/dist/cli/commands/chat.js +203 -101
- package/dist/cli/commands/commands.d.ts +2 -0
- package/dist/cli/commands/commands.js +10 -5
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/formatters.js +2 -0
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +9 -2
- package/dist/cli/commands/providerWizard.js +37 -4
- package/dist/cli/commands/runCommand.d.ts +3 -0
- package/dist/cli/commands/runCommand.js +117 -11
- package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
- package/dist/cli/commands/streaming/turnOutcome.js +27 -11
- package/dist/cli/commands/streaming.d.ts +70 -3
- package/dist/cli/commands/streaming.js +491 -77
- package/dist/cli/commands/wizardActions.d.ts +1 -0
- package/dist/cli/commands/wizardActions.js +1 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.js +5 -3
- package/dist/cli/index.js +68 -22
- package/dist/cli/terminalTitle.js +1 -1
- package/dist/config/modelDiscovery.d.ts +51 -0
- package/dist/config/modelDiscovery.js +164 -1
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +39 -7
- package/dist/config/providerPresets.js +371 -100
- package/dist/config/providers.js +2 -0
- package/dist/config/settings.d.ts +36 -0
- package/dist/config/settings.js +9 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +92 -17
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +38 -0
- package/dist/core/agent/contextBudget.js +60 -7
- package/dist/core/agent/events.d.ts +74 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -0
- package/dist/core/agent/toolCapabilities.d.ts +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
- package/dist/core/agent/toolExecutionBudget.js +49 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +10 -10
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnBudget.d.ts +35 -0
- package/dist/core/agent/turnBudget.js +27 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +75 -0
- package/dist/core/agent/workState.js +120 -9
- package/dist/core/deadline.d.ts +33 -0
- package/dist/core/deadline.js +74 -0
- package/dist/core/goal/completionPolicy.d.ts +27 -0
- package/dist/core/goal/completionPolicy.js +37 -1
- package/dist/core/limits/byteBudgets.d.ts +2 -0
- package/dist/core/limits/byteBudgets.js +2 -0
- package/dist/core/limits/textBudgets.d.ts +2 -0
- package/dist/core/limits/textBudgets.js +2 -0
- package/dist/core/log/llmLog.js +7 -0
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.js +8 -7
- package/dist/core/process/runBoundedProcess.d.ts +8 -2
- package/dist/core/process/runBoundedProcess.js +15 -6
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/session/sessionStore.d.ts +37 -0
- package/dist/core/session/sessionStore.js +215 -51
- package/dist/core/subagent/contracts.d.ts +4 -0
- package/dist/core/subagent/contracts.js +1 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
- package/dist/core/subagent/subagentCoordinator.js +32 -2
- package/dist/core/subagent/subagentRunner.js +17 -37
- package/dist/llm/client.d.ts +17 -1
- package/dist/llm/client.js +82 -14
- package/dist/llm/hazeTools.d.ts +554 -80
- package/dist/llm/hazeTools.js +103 -24
- package/dist/llm/lsp.d.ts +24 -4
- package/dist/llm/lsp.js +72 -11
- package/dist/llm/lspTools.d.ts +2366 -0
- package/dist/llm/lspTools.js +87 -79
- package/dist/llm/openaiCodex.d.ts +3 -0
- package/dist/llm/openaiCodex.js +47 -0
- package/dist/llm/openaiCodexOAuth.d.ts +54 -0
- package/dist/llm/openaiCodexOAuth.js +214 -0
- package/dist/llm/requestContext.d.ts +3 -0
- package/dist/llm/requestContext.js +7 -4
- package/dist/llm/systemPrompt.d.ts +11 -0
- package/dist/llm/systemPrompt.js +12 -6
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +48 -16
- package/dist/llm/tools/bashTool.js +5 -0
- package/dist/llm/tools/editMatch.d.ts +14 -0
- package/dist/llm/tools/editMatch.js +72 -0
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +16 -0
- package/dist/llm/tools/fileToolShared.d.ts +4 -3
- package/dist/llm/tools/fileToolShared.js +16 -21
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/readRecovery.d.ts +10 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/toolContext.d.ts +1 -1
- package/dist/llm/tools/toolContext.js +61 -32
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +64 -97
- package/dist/ui/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +8 -1
- package/dist/ui/components/TextInput.js +6 -2
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +104 -0
- package/dist/utils/buildInfo.js +253 -0
- package/dist/utils/fs.d.ts +9 -0
- package/dist/utils/fs.js +87 -25
- package/dist/utils/openPath.d.ts +2 -2
- package/dist/utils/openPath.js +19 -6
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +5 -1
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +24 -19
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded, generic diagnostic for missing executables.
|
|
3
|
+
*
|
|
4
|
+
* When a shell command fails because an executable is not on PATH, this derives
|
|
5
|
+
* a precise, safe blocker: the executable name and a generic recovery order. It
|
|
6
|
+
* never returns raw stderr/command text and contains no dependency-specific
|
|
7
|
+
* branching (no special cases for Git, Python, Docker images, etc.).
|
|
8
|
+
*
|
|
9
|
+
* The recovery order is generic and safe:
|
|
10
|
+
* 1. an already-available alternative (versioned/similarly-named command);
|
|
11
|
+
* 2. the project's own manifest/package file + a project-local install;
|
|
12
|
+
* 3. a system install only with explicit user consent (deferred — see below).
|
|
13
|
+
*
|
|
14
|
+
* Product decision (deferred): a system-install permission model is not defined
|
|
15
|
+
* here. We never silently modify a user-managed toolchain. The diagnostic asks
|
|
16
|
+
* for consent and reports the blocker; it does not perform the install.
|
|
17
|
+
*/
|
|
18
|
+
const NOT_FOUND_PATTERNS = [
|
|
19
|
+
/:\s*command not found\b/i,
|
|
20
|
+
/\bcommand not found:\s*/i,
|
|
21
|
+
/\bnot found\s*$/i,
|
|
22
|
+
/No such file or directory\b/i,
|
|
23
|
+
];
|
|
24
|
+
/** Extract the executable name from a "not found" diagnostic line, generically. */
|
|
25
|
+
function executableFromMessage(line) {
|
|
26
|
+
// `zsh:1: command not found: NAME` / `command not found: NAME` (checked first
|
|
27
|
+
// so the line-number colon in the zsh form is not captured).
|
|
28
|
+
const m2 = line.match(/command not found:\s*([^\s]+)/i);
|
|
29
|
+
if (m2?.[1])
|
|
30
|
+
return m2[1];
|
|
31
|
+
// `bash: line 1: NAME: command not found` / `bash: NAME: command not found`
|
|
32
|
+
const m = line.match(/:\s*([^\s:]+):\s*command not found/i);
|
|
33
|
+
if (m?.[1] && !/^\d+$/.test(m[1]))
|
|
34
|
+
return m[1];
|
|
35
|
+
// `NAME: not found` / `NAME: command not found`
|
|
36
|
+
const m3 = line.match(/^\s*([^\s:]+):\s*(?:command )?not found\s*$/i);
|
|
37
|
+
if (m3?.[1])
|
|
38
|
+
return m3[1];
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
function firstCommandToken(command) {
|
|
42
|
+
const tokens = command.trim().split(/\s+/);
|
|
43
|
+
for (const raw of tokens) {
|
|
44
|
+
// Skip wrappers and environment-variable assignments (e.g. `env FOO=1 cmd`).
|
|
45
|
+
if (/^(env|sudo|command|nohup|exec|time)$/i.test(raw) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(raw))
|
|
46
|
+
continue;
|
|
47
|
+
const cleaned = raw.replace(/^.+\//, '').replace(/^['"]|['"]$/g, '');
|
|
48
|
+
return cleaned || undefined;
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Detect a missing-executable failure from a bounded command + reduced stderr +
|
|
54
|
+
* exit code. Returns undefined when the failure is not a missing-executable
|
|
55
|
+
* failure or no executable name can be derived.
|
|
56
|
+
*/
|
|
57
|
+
export function detectMissingExecutable(input) {
|
|
58
|
+
const looksMissing = input.code === 127 || NOT_FOUND_PATTERNS.some(pattern => pattern.test(input.stderr));
|
|
59
|
+
if (!looksMissing)
|
|
60
|
+
return undefined;
|
|
61
|
+
const byLine = input.stderr.split(/\r?\n/).map(executableFromMessage).find(Boolean);
|
|
62
|
+
const executable = byLine ?? firstCommandToken(input.command);
|
|
63
|
+
if (!executable)
|
|
64
|
+
return undefined;
|
|
65
|
+
return {
|
|
66
|
+
executable,
|
|
67
|
+
suggestedNextStep: `Command '${executable}' was not found. First check whether a versioned or similarly-named alternative is already installed, then add it to the project's manifest/package file and install project-locally, or ask for explicit consent before installing into the system environment. Report this as blocked if no safe option is available.`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Project the diagnostic into the bounded fields carried in safe tool output /
|
|
72
|
+
* events. Only the executable name and reasonCode are exposed — never stderr or
|
|
73
|
+
* the full command.
|
|
74
|
+
*/
|
|
75
|
+
export function missingExecutableFields(diagnostic) {
|
|
76
|
+
return { reasonCode: 'missing_executable', missingExecutable: diagnostic.executable };
|
|
77
|
+
}
|
|
@@ -7,6 +7,10 @@ export type SessionEntry = {
|
|
|
7
7
|
createdAt: string;
|
|
8
8
|
hazeVersion?: string;
|
|
9
9
|
forkedFrom?: string;
|
|
10
|
+
build?: {
|
|
11
|
+
commit?: string;
|
|
12
|
+
builtAt?: string;
|
|
13
|
+
};
|
|
10
14
|
} | {
|
|
11
15
|
type: 'ui_message';
|
|
12
16
|
at: string;
|
|
@@ -26,20 +30,46 @@ export type SessionEntry = {
|
|
|
26
30
|
name: string;
|
|
27
31
|
text?: string;
|
|
28
32
|
};
|
|
33
|
+
type SessionHeader = Extract<SessionEntry, {
|
|
34
|
+
type: 'header';
|
|
35
|
+
}>;
|
|
36
|
+
type DeferredSessionWrite = {
|
|
37
|
+
header: SessionHeader;
|
|
38
|
+
entries: SessionEntry[];
|
|
39
|
+
};
|
|
29
40
|
export interface HazeSession {
|
|
30
41
|
id: string;
|
|
31
42
|
file: string;
|
|
32
43
|
cwd: string;
|
|
44
|
+
/** New sessions stay memory-only until they contain a resumable message. */
|
|
45
|
+
deferredWrite?: DeferredSessionWrite;
|
|
33
46
|
}
|
|
34
47
|
export declare function createSession(options?: {
|
|
35
48
|
cwd?: string;
|
|
36
49
|
hazeVersion?: string;
|
|
37
50
|
sessionsDir?: string;
|
|
38
51
|
forkedFrom?: string;
|
|
52
|
+
build?: {
|
|
53
|
+
commit?: string;
|
|
54
|
+
builtAt?: string;
|
|
55
|
+
};
|
|
39
56
|
}): Promise<HazeSession>;
|
|
40
57
|
export declare function findSession(id: string, cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
|
|
41
58
|
export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
|
|
42
59
|
export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Session files rewrite their full conversation history per turn, so a long
|
|
62
|
+
* session grows quadratically: N tokens of final history cost O(turns ×
|
|
63
|
+
* history) bytes on disk (F-03). Once superseded snapshots dominate the file,
|
|
64
|
+
* rewrite it keeping only the newest conversation/work-state snapshot plus
|
|
65
|
+
* every non-snapshot entry (restore reads only the newest snapshot of each
|
|
66
|
+
* type, so dropping superseded ones is lossless for restore; summaries keep
|
|
67
|
+
* their ui_message/event history). Atomic replace, never partial.
|
|
68
|
+
*/
|
|
69
|
+
export declare const SESSION_VACUUM_THRESHOLD_BYTES: number;
|
|
70
|
+
/** Test-only override for the vacuum trigger; tests restore the original. */
|
|
71
|
+
export declare function setSessionVacuumThresholdForTests(bytes: number): void;
|
|
72
|
+
export declare function vacuumSessionFileIfLarge(session: HazeSession, thresholdBytes?: number): Promise<boolean>;
|
|
43
73
|
export interface ReadSessionEntriesResult {
|
|
44
74
|
entries: SessionEntry[];
|
|
45
75
|
/** Per-line parse failures, e.g. `Line 3: Unexpected token...`. Empty when every line parsed. */
|
|
@@ -86,6 +116,8 @@ export interface SessionSummary {
|
|
|
86
116
|
lastStatus?: string;
|
|
87
117
|
parseErrors: string[];
|
|
88
118
|
}
|
|
119
|
+
/** Test-only reset for the process-scoped session-summary cache. */
|
|
120
|
+
export declare function clearSessionSummaryCacheForTests(): void;
|
|
89
121
|
/** List this workspace's sessions newest-first while retaining only summary state per file. */
|
|
90
122
|
export declare function listSessions(cwd?: string, sessionsDir?: string): Promise<SessionSummary[]>;
|
|
91
123
|
export interface ForkSessionResult {
|
|
@@ -96,5 +128,10 @@ export interface ForkSessionResult {
|
|
|
96
128
|
export declare function forkSession(source: HazeSession, options?: {
|
|
97
129
|
hazeVersion?: string;
|
|
98
130
|
sessionsDir?: string;
|
|
131
|
+
build?: {
|
|
132
|
+
commit?: string;
|
|
133
|
+
builtAt?: string;
|
|
134
|
+
};
|
|
99
135
|
}): Promise<ForkSessionResult>;
|
|
100
136
|
export declare function formatSession(session: HazeSession): string;
|
|
137
|
+
export {};
|
|
@@ -3,7 +3,7 @@ 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';
|
|
6
|
+
import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
|
|
7
7
|
import { JSONL_LINE_BYTES } from '../limits/byteBudgets.js';
|
|
8
8
|
import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
|
|
9
9
|
const DEFAULT_SESSIONS_DIR = path.join(HAZE_DIR, 'sessions');
|
|
@@ -26,12 +26,22 @@ export async function createSession(options = {}) {
|
|
|
26
26
|
const id = newSessionId();
|
|
27
27
|
const file = sessionFile(id, cwd, options.sessionsDir);
|
|
28
28
|
await ensurePrivateDir(path.dirname(file));
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
return {
|
|
30
|
+
id,
|
|
31
|
+
file,
|
|
32
|
+
cwd,
|
|
33
|
+
deferredWrite: {
|
|
34
|
+
header: { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion, forkedFrom: options.forkedFrom, ...(options.build ? { build: options.build } : {}) },
|
|
35
|
+
entries: [],
|
|
36
|
+
},
|
|
37
|
+
};
|
|
31
38
|
}
|
|
32
39
|
export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
33
40
|
const normalizedId = id.trim();
|
|
34
|
-
|
|
41
|
+
// basename equality is the actual invariant: it rejects any id containing a
|
|
42
|
+
// path separator (POSIX or Windows), which is what prevents escaping the
|
|
43
|
+
// workspace's sessions/<hash>/ directory via `..` or absolute paths.
|
|
44
|
+
if (!normalizedId || path.basename(normalizedId) !== normalizedId)
|
|
35
45
|
return undefined;
|
|
36
46
|
const file = sessionFile(normalizedId, cwd, sessionsDir);
|
|
37
47
|
if (!await fs.pathExists(file))
|
|
@@ -39,25 +49,139 @@ export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT
|
|
|
39
49
|
return { id: normalizedId, file, cwd: path.resolve(cwd) };
|
|
40
50
|
}
|
|
41
51
|
export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
42
|
-
const
|
|
43
|
-
await ensurePrivateDir(dir);
|
|
44
|
-
const files = (await fs.readdir(dir).catch(() => []))
|
|
45
|
-
.filter(file => file.endsWith('.jsonl'))
|
|
46
|
-
.sort();
|
|
47
|
-
const latest = files.at(-1);
|
|
52
|
+
const latest = (await listSessions(cwd, sessionsDir))[0];
|
|
48
53
|
if (!latest)
|
|
49
54
|
return undefined;
|
|
50
|
-
|
|
51
|
-
|
|
55
|
+
return { id: latest.id, file: sessionFile(latest.id, cwd, sessionsDir), cwd: path.resolve(cwd) };
|
|
56
|
+
}
|
|
57
|
+
function entryMakesSessionResumable(entry) {
|
|
58
|
+
if (entry.type === 'ui_message')
|
|
59
|
+
return entry.text.trim().length > 0;
|
|
60
|
+
return entry.type === 'conversation_snapshot' && entry.messages.length > 0;
|
|
52
61
|
}
|
|
53
62
|
export async function appendSessionEntry(session, entry) {
|
|
54
63
|
const prepared = prepareSessionEntryForWrite(entry);
|
|
55
64
|
if (!prepared)
|
|
56
65
|
return;
|
|
66
|
+
const deferred = session.deferredWrite;
|
|
67
|
+
if (deferred) {
|
|
68
|
+
if (!entryMakesSessionResumable(prepared)) {
|
|
69
|
+
deferred.entries.push(prepared);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const entries = [deferred.header, ...deferred.entries, prepared];
|
|
73
|
+
await appendPrivateFile(session.file, entries.map(item => JSON.stringify(item)).join('\n') + '\n');
|
|
74
|
+
session.deferredWrite = undefined;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
57
77
|
await appendPrivateFile(session.file, `${JSON.stringify(prepared)}\n`);
|
|
78
|
+
// Snapshot deduplication runs inside the same serialized writer as the
|
|
79
|
+
// append, so ordering with subsequent entries is preserved (F-03).
|
|
80
|
+
await vacuumSessionFileIfLarge(session).catch(() => undefined);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Session files rewrite their full conversation history per turn, so a long
|
|
84
|
+
* session grows quadratically: N tokens of final history cost O(turns ×
|
|
85
|
+
* history) bytes on disk (F-03). Once superseded snapshots dominate the file,
|
|
86
|
+
* rewrite it keeping only the newest conversation/work-state snapshot plus
|
|
87
|
+
* every non-snapshot entry (restore reads only the newest snapshot of each
|
|
88
|
+
* type, so dropping superseded ones is lossless for restore; summaries keep
|
|
89
|
+
* their ui_message/event history). Atomic replace, never partial.
|
|
90
|
+
*/
|
|
91
|
+
export const SESSION_VACUUM_THRESHOLD_BYTES = 16 * 1024 * 1024;
|
|
92
|
+
let effectiveVacuumThresholdBytes = SESSION_VACUUM_THRESHOLD_BYTES;
|
|
93
|
+
/** Test-only override for the vacuum trigger; tests restore the original. */
|
|
94
|
+
export function setSessionVacuumThresholdForTests(bytes) {
|
|
95
|
+
effectiveVacuumThresholdBytes = bytes;
|
|
96
|
+
}
|
|
97
|
+
export async function vacuumSessionFileIfLarge(session, thresholdBytes = effectiveVacuumThresholdBytes) {
|
|
98
|
+
if (session.deferredWrite)
|
|
99
|
+
return false;
|
|
100
|
+
const stat = await fs.stat(session.file).catch(() => undefined);
|
|
101
|
+
if (!stat || stat.size < thresholdBytes)
|
|
102
|
+
return false;
|
|
103
|
+
const { entries } = await readSessionEntries(session);
|
|
104
|
+
let lastConversation = -1;
|
|
105
|
+
let lastWorkState = -1;
|
|
106
|
+
entries.forEach((entry, index) => {
|
|
107
|
+
if (entry.type === 'conversation_snapshot')
|
|
108
|
+
lastConversation = index;
|
|
109
|
+
if (entry.type === 'work_state_snapshot')
|
|
110
|
+
lastWorkState = index;
|
|
111
|
+
});
|
|
112
|
+
// Malformed lines are dropped by the rewrite: they were already unusable
|
|
113
|
+
// (and reported as parse errors on read) and keeping them would defeat the
|
|
114
|
+
// size bound the vacuum exists to enforce.
|
|
115
|
+
const kept = entries.filter((entry, index) => (entry.type !== 'conversation_snapshot' && entry.type !== 'work_state_snapshot')
|
|
116
|
+
|| index === lastConversation
|
|
117
|
+
|| index === lastWorkState);
|
|
118
|
+
const serialized = kept.map(entry => JSON.stringify(entry)).join('\n') + '\n';
|
|
119
|
+
// Only rewrite when it meaningfully shrinks the file; otherwise a single
|
|
120
|
+
// dominant snapshot would trigger a full rewrite on every append.
|
|
121
|
+
if (serialized.length > stat.size / 2)
|
|
122
|
+
return false;
|
|
123
|
+
await writePrivateFileAtomic(session.file, serialized);
|
|
124
|
+
return true;
|
|
58
125
|
}
|
|
59
126
|
const MAX_PARSE_ERRORS = 100;
|
|
127
|
+
const MODEL_MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool']);
|
|
128
|
+
function isRecord(value) {
|
|
129
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
130
|
+
}
|
|
131
|
+
function optionalString(value) {
|
|
132
|
+
return value === undefined || typeof value === 'string';
|
|
133
|
+
}
|
|
134
|
+
function optionalBuildProvenance(value) {
|
|
135
|
+
if (value === undefined)
|
|
136
|
+
return true;
|
|
137
|
+
if (!isRecord(value))
|
|
138
|
+
return false;
|
|
139
|
+
return optionalString(value.commit) && optionalString(value.builtAt);
|
|
140
|
+
}
|
|
141
|
+
function parseSessionEntry(value) {
|
|
142
|
+
const invalid = (detail) => {
|
|
143
|
+
throw new Error(`unexpected entry shape: ${detail}`);
|
|
144
|
+
};
|
|
145
|
+
if (!isRecord(value))
|
|
146
|
+
return invalid('expected an object with a string type');
|
|
147
|
+
const type = value.type;
|
|
148
|
+
if (typeof type !== 'string')
|
|
149
|
+
return invalid('expected an object with a string type');
|
|
150
|
+
switch (type) {
|
|
151
|
+
case 'header':
|
|
152
|
+
if (typeof value.id !== 'string' || typeof value.cwd !== 'string' || typeof value.createdAt !== 'string'
|
|
153
|
+
|| !optionalString(value.hazeVersion) || !optionalString(value.forkedFrom)
|
|
154
|
+
|| !optionalBuildProvenance(value.build))
|
|
155
|
+
return invalid('invalid header');
|
|
156
|
+
return value;
|
|
157
|
+
case 'ui_message':
|
|
158
|
+
if (typeof value.at !== 'string' || typeof value.text !== 'string'
|
|
159
|
+
|| !MODEL_MESSAGE_ROLES.has(typeof value.role === 'string' ? value.role : ''))
|
|
160
|
+
return invalid('invalid ui_message');
|
|
161
|
+
return value;
|
|
162
|
+
case 'conversation_snapshot':
|
|
163
|
+
if (typeof value.at !== 'string' || !Array.isArray(value.messages))
|
|
164
|
+
return invalid('conversation_snapshot messages must be an array');
|
|
165
|
+
if (!value.messages.every((message) => isRecord(message)
|
|
166
|
+
&& typeof message.role === 'string'
|
|
167
|
+
&& MODEL_MESSAGE_ROLES.has(message.role)))
|
|
168
|
+
return invalid('conversation_snapshot contains an invalid message role');
|
|
169
|
+
return value;
|
|
170
|
+
case 'work_state_snapshot':
|
|
171
|
+
if (typeof value.at !== 'string' || !isRecord(value.state))
|
|
172
|
+
return invalid('work_state_snapshot state must be an object');
|
|
173
|
+
return value;
|
|
174
|
+
case 'event':
|
|
175
|
+
if (typeof value.at !== 'string' || typeof value.name !== 'string' || !optionalString(value.text))
|
|
176
|
+
return invalid('invalid event');
|
|
177
|
+
return value;
|
|
178
|
+
default:
|
|
179
|
+
return invalid(`unknown entry type '${type}'`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
60
182
|
async function scanSessionEntries(session, onEntry) {
|
|
183
|
+
if (session.deferredWrite && !await fs.pathExists(session.file))
|
|
184
|
+
return [];
|
|
61
185
|
await tightenPrivateFile(session.file);
|
|
62
186
|
const parseErrors = [];
|
|
63
187
|
let omittedErrors = 0;
|
|
@@ -75,7 +199,7 @@ async function scanSessionEntries(session, onEntry) {
|
|
|
75
199
|
continue;
|
|
76
200
|
}
|
|
77
201
|
try {
|
|
78
|
-
onEntry(JSON.parse(line));
|
|
202
|
+
onEntry(parseSessionEntry(JSON.parse(line)));
|
|
79
203
|
}
|
|
80
204
|
catch (error) {
|
|
81
205
|
report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -124,64 +248,104 @@ export async function restoreWorkState(session) {
|
|
|
124
248
|
const SESSION_PREVIEW_CHARS = 120;
|
|
125
249
|
/** Acceptance budget for listing 50 ordinary workspace sessions. */
|
|
126
250
|
export const SESSION_LIST_LATENCY_BUDGET_MS = 2_000;
|
|
251
|
+
const SESSION_SUMMARY_CACHE_MAX = 500;
|
|
252
|
+
const sessionSummaryCache = new Map();
|
|
253
|
+
function cachedSessionSummary(file, stat) {
|
|
254
|
+
const cached = sessionSummaryCache.get(file);
|
|
255
|
+
if (!cached || cached.mtimeMs !== stat.mtimeMs || cached.size !== stat.size)
|
|
256
|
+
return undefined;
|
|
257
|
+
sessionSummaryCache.delete(file);
|
|
258
|
+
sessionSummaryCache.set(file, cached);
|
|
259
|
+
return cached.summary;
|
|
260
|
+
}
|
|
261
|
+
function cacheSessionSummary(file, stat, summary) {
|
|
262
|
+
sessionSummaryCache.delete(file);
|
|
263
|
+
sessionSummaryCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, summary });
|
|
264
|
+
while (sessionSummaryCache.size > SESSION_SUMMARY_CACHE_MAX) {
|
|
265
|
+
const oldest = sessionSummaryCache.keys().next().value;
|
|
266
|
+
if (oldest === undefined)
|
|
267
|
+
break;
|
|
268
|
+
sessionSummaryCache.delete(oldest);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** Test-only reset for the process-scoped session-summary cache. */
|
|
272
|
+
export function clearSessionSummaryCacheForTests() {
|
|
273
|
+
sessionSummaryCache.clear();
|
|
274
|
+
}
|
|
127
275
|
function previewText(text) {
|
|
128
276
|
const compact = text.replace(/\s+/g, ' ').trim();
|
|
129
277
|
return compact.length > SESSION_PREVIEW_CHARS ? `${compact.slice(0, SESSION_PREVIEW_CHARS - 1)}…` : compact;
|
|
130
278
|
}
|
|
279
|
+
async function summarizeSession(session, stat) {
|
|
280
|
+
let createdAt = stat.birthtime.toISOString();
|
|
281
|
+
let lastActivityAt = stat.mtime.toISOString();
|
|
282
|
+
let messageCount = 0;
|
|
283
|
+
let firstUserPreview = '';
|
|
284
|
+
let lastStatus;
|
|
285
|
+
const parseErrors = await scanSessionEntries(session, entry => {
|
|
286
|
+
if (entry.type === 'header')
|
|
287
|
+
createdAt = entry.createdAt || createdAt;
|
|
288
|
+
if ('at' in entry && entry.at)
|
|
289
|
+
lastActivityAt = entry.at;
|
|
290
|
+
if (entry.type === 'ui_message' && entry.text.trim().length > 0) {
|
|
291
|
+
messageCount++;
|
|
292
|
+
if (!firstUserPreview && entry.role === 'user')
|
|
293
|
+
firstUserPreview = previewText(entry.text);
|
|
294
|
+
}
|
|
295
|
+
if (entry.type === 'conversation_snapshot') {
|
|
296
|
+
if (messageCount === 0)
|
|
297
|
+
messageCount = entry.messages.length;
|
|
298
|
+
if (!firstUserPreview) {
|
|
299
|
+
const firstUser = entry.messages.find(message => message.role === 'user');
|
|
300
|
+
if (firstUser)
|
|
301
|
+
firstUserPreview = previewText(typeof firstUser.content === 'string' ? firstUser.content : JSON.stringify(firstUser.content));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (entry.type === 'event' && entry.name === 'turn_end' && entry.text) {
|
|
305
|
+
try {
|
|
306
|
+
const event = JSON.parse(entry.text);
|
|
307
|
+
if (typeof event.status === 'string')
|
|
308
|
+
lastStatus = event.status;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
// The outer entry remains valid; malformed optional event metadata is ignored.
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
return { id: session.id, createdAt, lastActivityAt, messageCount, firstUserPreview, sizeBytes: stat.size, lastStatus, parseErrors };
|
|
316
|
+
}
|
|
131
317
|
/** List this workspace's sessions newest-first while retaining only summary state per file. */
|
|
132
318
|
export async function listSessions(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
133
319
|
const dir = sessionDir(cwd, sessionsDir);
|
|
134
320
|
await ensurePrivateDir(dir);
|
|
135
321
|
const files = (await fs.readdir(dir).catch(() => [])).filter(file => file.endsWith('.jsonl'));
|
|
322
|
+
const present = new Set(files.map(file => path.join(dir, file)));
|
|
323
|
+
for (const cachedFile of sessionSummaryCache.keys()) {
|
|
324
|
+
if (path.dirname(cachedFile) === dir && !present.has(cachedFile))
|
|
325
|
+
sessionSummaryCache.delete(cachedFile);
|
|
326
|
+
}
|
|
136
327
|
const summaries = await Promise.all(files.map(async (fileName) => {
|
|
137
328
|
const id = path.basename(fileName, '.jsonl');
|
|
138
329
|
const session = { id, file: path.join(dir, fileName), cwd: path.resolve(cwd) };
|
|
330
|
+
await tightenPrivateFile(session.file);
|
|
139
331
|
const stat = await fs.stat(session.file);
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
if (entry.type === 'header')
|
|
147
|
-
createdAt = entry.createdAt || createdAt;
|
|
148
|
-
if ('at' in entry && entry.at)
|
|
149
|
-
lastActivityAt = entry.at;
|
|
150
|
-
if (entry.type === 'ui_message') {
|
|
151
|
-
messageCount++;
|
|
152
|
-
if (!firstUserPreview && entry.role === 'user')
|
|
153
|
-
firstUserPreview = previewText(entry.text);
|
|
154
|
-
}
|
|
155
|
-
if (entry.type === 'conversation_snapshot') {
|
|
156
|
-
if (messageCount === 0)
|
|
157
|
-
messageCount = entry.messages.length;
|
|
158
|
-
if (!firstUserPreview) {
|
|
159
|
-
const firstUser = entry.messages.find(message => message.role === 'user');
|
|
160
|
-
if (firstUser)
|
|
161
|
-
firstUserPreview = previewText(typeof firstUser.content === 'string' ? firstUser.content : JSON.stringify(firstUser.content));
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
if (entry.type === 'event' && entry.name === 'turn_end' && entry.text) {
|
|
165
|
-
try {
|
|
166
|
-
const event = JSON.parse(entry.text);
|
|
167
|
-
if (typeof event.status === 'string')
|
|
168
|
-
lastStatus = event.status;
|
|
169
|
-
}
|
|
170
|
-
catch {
|
|
171
|
-
// The outer entry remains valid; malformed optional event metadata is ignored.
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
});
|
|
175
|
-
return { id, createdAt, lastActivityAt, messageCount, firstUserPreview, sizeBytes: stat.size, lastStatus, parseErrors };
|
|
332
|
+
const cached = cachedSessionSummary(session.file, stat);
|
|
333
|
+
if (cached)
|
|
334
|
+
return cached;
|
|
335
|
+
const summary = await summarizeSession(session, stat);
|
|
336
|
+
cacheSessionSummary(session.file, stat, summary);
|
|
337
|
+
return summary;
|
|
176
338
|
}));
|
|
177
|
-
return summaries
|
|
339
|
+
return summaries
|
|
340
|
+
.filter(summary => summary.messageCount > 0)
|
|
341
|
+
.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
|
|
178
342
|
}
|
|
179
343
|
/** Create a new session from the source's latest durable snapshots without mutating it. */
|
|
180
344
|
export async function forkSession(source, options = {}) {
|
|
181
345
|
const restored = await restoreSessionState(source);
|
|
182
346
|
if (restored.messages.length === 0)
|
|
183
347
|
throw new Error(`Session ${source.id} has no conversation snapshot to fork.`);
|
|
184
|
-
const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id });
|
|
348
|
+
const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id, ...(options.build ? { build: options.build } : {}) });
|
|
185
349
|
const at = new Date().toISOString();
|
|
186
350
|
await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
|
|
187
351
|
if (restored.workState)
|
|
@@ -95,10 +95,14 @@ export interface ProviderCapabilities {
|
|
|
95
95
|
supportsStickySessionId: boolean;
|
|
96
96
|
supportsServerCompaction: boolean;
|
|
97
97
|
supportsTextVerbosity: boolean;
|
|
98
|
+
/** Protocol accepts an OpenAI-style reasoning-effort provider option. */
|
|
99
|
+
supportsReasoningEffort: boolean;
|
|
98
100
|
}
|
|
99
101
|
export interface ProviderRequestOptions {
|
|
100
102
|
providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
|
|
101
103
|
headers?: Record<string, string>;
|
|
104
|
+
/** Codex subscription requests let the provider manage the output limit. */
|
|
105
|
+
omitMaxOutputTokens?: boolean;
|
|
102
106
|
}
|
|
103
107
|
export interface WorkerRuntime {
|
|
104
108
|
model: LanguageModel;
|
|
@@ -21,6 +21,7 @@ export function fallbackProviderCapabilities() {
|
|
|
21
21
|
supportsStickySessionId: false,
|
|
22
22
|
supportsServerCompaction: false,
|
|
23
23
|
supportsTextVerbosity: false,
|
|
24
|
+
supportsReasoningEffort: false,
|
|
24
25
|
};
|
|
25
26
|
}
|
|
26
27
|
/** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
|
|
@@ -59,11 +59,15 @@ export declare class SubagentCoordinator {
|
|
|
59
59
|
private readonly queue;
|
|
60
60
|
private running;
|
|
61
61
|
private mutationRunning;
|
|
62
|
+
/** Read-only workers admitted behind a blocked mutation head (RH-010). */
|
|
63
|
+
private bypassRunning;
|
|
62
64
|
private nextId;
|
|
63
65
|
private nextSequence;
|
|
64
66
|
private submissionBatch;
|
|
65
67
|
private admissionScheduled;
|
|
66
68
|
peakConcurrency: number;
|
|
69
|
+
/** Peak read-only workers running concurrently behind a blocked mutation. */
|
|
70
|
+
peakBypass: number;
|
|
67
71
|
constructor(profile: SubagentExecutionProfile, onEvent?: ((event: CoordinatorEvent) => void) | undefined);
|
|
68
72
|
createId(): string;
|
|
69
73
|
submit<T>(input: Omit<Submission<T>, 'resolve' | 'submittedAt' | 'sequence' | 'batch' | 'abortListener'>): Promise<T>;
|
|
@@ -10,11 +10,15 @@ export class SubagentCoordinator {
|
|
|
10
10
|
queue = [];
|
|
11
11
|
running = 0;
|
|
12
12
|
mutationRunning = false;
|
|
13
|
+
/** Read-only workers admitted behind a blocked mutation head (RH-010). */
|
|
14
|
+
bypassRunning = 0;
|
|
13
15
|
nextId = 1;
|
|
14
16
|
nextSequence = 1;
|
|
15
17
|
submissionBatch = 1;
|
|
16
18
|
admissionScheduled = false;
|
|
17
19
|
peakConcurrency = 0;
|
|
20
|
+
/** Peak read-only workers running concurrently behind a blocked mutation. */
|
|
21
|
+
peakBypass = 0;
|
|
18
22
|
constructor(profile, onEvent) {
|
|
19
23
|
this.profile = profile;
|
|
20
24
|
this.onEvent = onEvent;
|
|
@@ -69,6 +73,9 @@ export class SubagentCoordinator {
|
|
|
69
73
|
});
|
|
70
74
|
}
|
|
71
75
|
admit() {
|
|
76
|
+
// FIFO admission from the queue head. A mutation at the head blocks behind
|
|
77
|
+
// another running mutation; everything else is admitted in order while
|
|
78
|
+
// slots remain free.
|
|
72
79
|
while (this.running < this.profile.maxConcurrency) {
|
|
73
80
|
const item = this.queue[0];
|
|
74
81
|
if (!item || (isMutationMode(item.mode) && this.mutationRunning))
|
|
@@ -76,12 +83,33 @@ export class SubagentCoordinator {
|
|
|
76
83
|
this.queue.shift();
|
|
77
84
|
if (item.signal && item.abortListener)
|
|
78
85
|
item.signal.removeEventListener('abort', item.abortListener);
|
|
79
|
-
this.start(item);
|
|
86
|
+
this.start(item, false);
|
|
87
|
+
}
|
|
88
|
+
// Bounded read-only bypass: while a mutation is blocked at the head, let
|
|
89
|
+
// read-only work waiting behind it consume otherwise-idle slots. The cap is
|
|
90
|
+
// maxConcurrency - 1 so a serialized mutation always retains a free slot
|
|
91
|
+
// the moment the running mutation settles, preventing starvation (RH-010).
|
|
92
|
+
const bypassCap = Math.max(0, this.profile.maxConcurrency - 1);
|
|
93
|
+
while (this.running < this.profile.maxConcurrency && this.bypassRunning < bypassCap) {
|
|
94
|
+
const head = this.queue[0];
|
|
95
|
+
if (!head || !(isMutationMode(head.mode) && this.mutationRunning))
|
|
96
|
+
break;
|
|
97
|
+
const index = this.queue.findIndex(item => !isMutationMode(item.mode));
|
|
98
|
+
if (index === -1)
|
|
99
|
+
break;
|
|
100
|
+
const [item] = this.queue.splice(index, 1);
|
|
101
|
+
if (item.signal && item.abortListener)
|
|
102
|
+
item.signal.removeEventListener('abort', item.abortListener);
|
|
103
|
+
this.start(item, true);
|
|
80
104
|
}
|
|
81
105
|
}
|
|
82
|
-
start(item) {
|
|
106
|
+
start(item, bypass) {
|
|
83
107
|
const mutation = isMutationMode(item.mode);
|
|
84
108
|
this.running++;
|
|
109
|
+
if (bypass) {
|
|
110
|
+
this.bypassRunning++;
|
|
111
|
+
this.peakBypass = Math.max(this.peakBypass, this.bypassRunning);
|
|
112
|
+
}
|
|
85
113
|
if (mutation)
|
|
86
114
|
this.mutationRunning = true;
|
|
87
115
|
this.peakConcurrency = Math.max(this.peakConcurrency, this.running);
|
|
@@ -123,6 +151,8 @@ export class SubagentCoordinator {
|
|
|
123
151
|
clearTimeout(timer);
|
|
124
152
|
item.signal?.removeEventListener('abort', parentAbort);
|
|
125
153
|
this.running--;
|
|
154
|
+
if (bypass)
|
|
155
|
+
this.bypassRunning--;
|
|
126
156
|
if (mutation)
|
|
127
157
|
this.mutationRunning = false;
|
|
128
158
|
if (deliveredTermination && abortSource) {
|