@denizokcu/haze 0.9.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 +133 -17
- package/README.md +164 -68
- 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/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +46 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +92 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- 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 +67 -0
- package/dist/cli/chat/sessionLifecycle.js +205 -0
- package/dist/cli/chat/sessionRecorder.js +80 -14
- package/dist/cli/chat/startupInfo.js +11 -4
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +744 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +373 -790
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +5 -2
- package/dist/cli/commands/commands.js +22 -18
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +35 -6
- package/dist/cli/commands/logsCommand.js +1 -7
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +10 -2
- package/dist/cli/commands/providerWizard.js +50 -4
- package/dist/cli/commands/runCommand.d.ts +4 -0
- package/dist/cli/commands/runCommand.js +142 -16
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +6 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- 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/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -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 +31 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
- 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/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +82 -3
- package/dist/cli/commands/streaming.js +528 -91
- package/dist/cli/commands/wizardActions.d.ts +7 -0
- package/dist/cli/commands/wizardActions.js +7 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +64 -14
- package/dist/cli/commands/wizardTransition.d.ts +4 -0
- package/dist/cli/commands/wizardTransition.js +1 -2
- package/dist/cli/index.js +82 -22
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +12 -18
- package/dist/config/modelDiscovery.d.ts +71 -0
- package/dist/config/modelDiscovery.js +214 -0
- 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 +49 -5
- package/dist/config/providerPresets.js +573 -73
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +9 -0
- package/dist/config/settings.d.ts +58 -0
- package/dist/config/settings.js +38 -1
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/core/agent/budgets.d.ts +36 -0
- package/dist/core/agent/budgets.js +44 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +108 -19
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +46 -0
- package/dist/core/agent/contextBudget.js +89 -7
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +86 -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 +13 -0
- package/dist/core/agent/toolOutputStore.js +27 -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 +76 -1
- package/dist/core/agent/workState.js +120 -13
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- 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/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.js +76 -29
- package/dist/core/limits/byteBudgets.d.ts +7 -0
- package/dist/core/limits/byteBudgets.js +7 -0
- package/dist/core/limits/textBudgets.d.ts +25 -0
- package/dist/core/limits/textBudgets.js +25 -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.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +195 -0
- package/dist/core/process/runBoundedProcess.d.ts +9 -0
- package/dist/core/process/runBoundedProcess.js +74 -29
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +74 -0
- package/dist/core/session/sessionStore.js +268 -18
- package/dist/core/subagent/contracts.d.ts +120 -0
- package/dist/core/subagent/contracts.js +55 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
- package/dist/core/subagent/subagentCoordinator.js +164 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +208 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +36 -29
- package/dist/llm/client.js +102 -33
- package/dist/llm/hazeTools.d.ts +2559 -150
- package/dist/llm/hazeTools.js +119 -31
- package/dist/llm/lsp.d.ts +26 -4
- package/dist/llm/lsp.js +90 -14
- 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 +25 -1
- package/dist/llm/requestContext.js +51 -8
- package/dist/llm/systemPrompt.d.ts +15 -1
- package/dist/llm/systemPrompt.js +24 -8
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +906 -32
- package/dist/llm/tools/bashTool.js +30 -4
- 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 +42 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +6 -4
- package/dist/llm/tools/fileToolShared.js +18 -23
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/grepRunner.d.ts +5 -0
- package/dist/llm/tools/grepRunner.js +52 -71
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -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 +9 -1
- package/dist/llm/tools/toolContext.js +83 -43
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +66 -86
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +43 -13
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +6 -1
- 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 +12 -2
- package/dist/ui/components/TextInput.js +80 -8
- 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/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +9 -1
- package/dist/utils/fs.js +87 -29
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +22 -0
- 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
|
@@ -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');
|
|
@@ -17,36 +17,171 @@ function sessionFile(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR
|
|
|
17
17
|
return path.join(sessionDir(cwd, sessionsDir), `${id}.jsonl`);
|
|
18
18
|
}
|
|
19
19
|
function newSessionId(now = new Date()) {
|
|
20
|
-
|
|
20
|
+
// Timestamp prefix keeps latestSession() lexicographic ordering; the random
|
|
21
|
+
// suffix prevents same-millisecond collisions (CR-025).
|
|
22
|
+
return `${now.toISOString().replace(/[:.]/g, '-')}-${crypto.randomBytes(3).toString('hex')}`;
|
|
21
23
|
}
|
|
22
24
|
export async function createSession(options = {}) {
|
|
23
25
|
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
24
26
|
const id = newSessionId();
|
|
25
27
|
const file = sessionFile(id, cwd, options.sessionsDir);
|
|
26
28
|
await ensurePrivateDir(path.dirname(file));
|
|
27
|
-
|
|
28
|
-
|
|
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
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
40
|
+
const normalizedId = id.trim();
|
|
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)
|
|
45
|
+
return undefined;
|
|
46
|
+
const file = sessionFile(normalizedId, cwd, sessionsDir);
|
|
47
|
+
if (!await fs.pathExists(file))
|
|
48
|
+
return undefined;
|
|
49
|
+
return { id: normalizedId, file, cwd: path.resolve(cwd) };
|
|
29
50
|
}
|
|
30
51
|
export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
31
|
-
const
|
|
32
|
-
await ensurePrivateDir(dir);
|
|
33
|
-
const files = (await fs.readdir(dir).catch(() => []))
|
|
34
|
-
.filter(file => file.endsWith('.jsonl'))
|
|
35
|
-
.sort();
|
|
36
|
-
const latest = files.at(-1);
|
|
52
|
+
const latest = (await listSessions(cwd, sessionsDir))[0];
|
|
37
53
|
if (!latest)
|
|
38
54
|
return undefined;
|
|
39
|
-
|
|
40
|
-
|
|
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;
|
|
41
61
|
}
|
|
42
62
|
export async function appendSessionEntry(session, entry) {
|
|
43
63
|
const prepared = prepareSessionEntryForWrite(entry);
|
|
44
64
|
if (!prepared)
|
|
45
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
|
+
}
|
|
46
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;
|
|
47
125
|
}
|
|
48
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
|
+
}
|
|
49
182
|
async function scanSessionEntries(session, onEntry) {
|
|
183
|
+
if (session.deferredWrite && !await fs.pathExists(session.file))
|
|
184
|
+
return [];
|
|
50
185
|
await tightenPrivateFile(session.file);
|
|
51
186
|
const parseErrors = [];
|
|
52
187
|
let omittedErrors = 0;
|
|
@@ -64,7 +199,7 @@ async function scanSessionEntries(session, onEntry) {
|
|
|
64
199
|
continue;
|
|
65
200
|
}
|
|
66
201
|
try {
|
|
67
|
-
onEntry(JSON.parse(line));
|
|
202
|
+
onEntry(parseSessionEntry(JSON.parse(line)));
|
|
68
203
|
}
|
|
69
204
|
catch (error) {
|
|
70
205
|
report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -86,21 +221,136 @@ export async function readSessionEntries(session) {
|
|
|
86
221
|
const parseErrors = await scanSessionEntries(session, entry => entries.push(entry));
|
|
87
222
|
return { entries, parseErrors };
|
|
88
223
|
}
|
|
89
|
-
|
|
224
|
+
/**
|
|
225
|
+
* Restore conversation and work state in one file scan (CR-013). Session
|
|
226
|
+
* files grow to megabytes in long workspaces; resuming should not parse the
|
|
227
|
+
* JSONL twice.
|
|
228
|
+
*/
|
|
229
|
+
export async function restoreSessionState(session) {
|
|
90
230
|
let messages = [];
|
|
231
|
+
let workState;
|
|
91
232
|
const parseErrors = await scanSessionEntries(session, entry => {
|
|
92
233
|
if (entry.type === 'conversation_snapshot')
|
|
93
234
|
messages = entry.messages;
|
|
235
|
+
if (entry.type === 'work_state_snapshot')
|
|
236
|
+
workState = entry.state;
|
|
94
237
|
});
|
|
238
|
+
return { messages, workState, parseErrors };
|
|
239
|
+
}
|
|
240
|
+
export async function restoreConversation(session) {
|
|
241
|
+
const { messages, parseErrors } = await restoreSessionState(session);
|
|
95
242
|
return { messages, parseErrors };
|
|
96
243
|
}
|
|
97
244
|
export async function restoreWorkState(session) {
|
|
98
|
-
|
|
245
|
+
const { workState, parseErrors } = await restoreSessionState(session);
|
|
246
|
+
return { state: workState, parseErrors };
|
|
247
|
+
}
|
|
248
|
+
const SESSION_PREVIEW_CHARS = 120;
|
|
249
|
+
/** Acceptance budget for listing 50 ordinary workspace sessions. */
|
|
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
|
+
}
|
|
275
|
+
function previewText(text) {
|
|
276
|
+
const compact = text.replace(/\s+/g, ' ').trim();
|
|
277
|
+
return compact.length > SESSION_PREVIEW_CHARS ? `${compact.slice(0, SESSION_PREVIEW_CHARS - 1)}…` : compact;
|
|
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;
|
|
99
285
|
const parseErrors = await scanSessionEntries(session, entry => {
|
|
100
|
-
if (entry.type === '
|
|
101
|
-
|
|
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
|
+
}
|
|
102
314
|
});
|
|
103
|
-
return {
|
|
315
|
+
return { id: session.id, createdAt, lastActivityAt, messageCount, firstUserPreview, sizeBytes: stat.size, lastStatus, parseErrors };
|
|
316
|
+
}
|
|
317
|
+
/** List this workspace's sessions newest-first while retaining only summary state per file. */
|
|
318
|
+
export async function listSessions(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
|
|
319
|
+
const dir = sessionDir(cwd, sessionsDir);
|
|
320
|
+
await ensurePrivateDir(dir);
|
|
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
|
+
}
|
|
327
|
+
const summaries = await Promise.all(files.map(async (fileName) => {
|
|
328
|
+
const id = path.basename(fileName, '.jsonl');
|
|
329
|
+
const session = { id, file: path.join(dir, fileName), cwd: path.resolve(cwd) };
|
|
330
|
+
await tightenPrivateFile(session.file);
|
|
331
|
+
const stat = await fs.stat(session.file);
|
|
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;
|
|
338
|
+
}));
|
|
339
|
+
return summaries
|
|
340
|
+
.filter(summary => summary.messageCount > 0)
|
|
341
|
+
.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
|
|
342
|
+
}
|
|
343
|
+
/** Create a new session from the source's latest durable snapshots without mutating it. */
|
|
344
|
+
export async function forkSession(source, options = {}) {
|
|
345
|
+
const restored = await restoreSessionState(source);
|
|
346
|
+
if (restored.messages.length === 0)
|
|
347
|
+
throw new Error(`Session ${source.id} has no conversation snapshot to fork.`);
|
|
348
|
+
const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id, ...(options.build ? { build: options.build } : {}) });
|
|
349
|
+
const at = new Date().toISOString();
|
|
350
|
+
await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
|
|
351
|
+
if (restored.workState)
|
|
352
|
+
await appendSessionEntry(session, { type: 'work_state_snapshot', at, state: restored.workState });
|
|
353
|
+
return { session, parseErrors: restored.parseErrors };
|
|
104
354
|
}
|
|
105
355
|
export function formatSession(session) {
|
|
106
356
|
return `${session.id} · ${session.file}`;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { JSONValue, LanguageModel } from 'ai';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
export declare const workerModes: readonly ["inspect", "research", "implement", "validate"];
|
|
4
|
+
export type WorkerMode = typeof workerModes[number];
|
|
5
|
+
export declare const subagentTaskInputV2Schema: z.ZodObject<{
|
|
6
|
+
objective: z.ZodString;
|
|
7
|
+
deliverable: z.ZodString;
|
|
8
|
+
mode: z.ZodEnum<{
|
|
9
|
+
inspect: "inspect";
|
|
10
|
+
research: "research";
|
|
11
|
+
implement: "implement";
|
|
12
|
+
validate: "validate";
|
|
13
|
+
}>;
|
|
14
|
+
scope: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
15
|
+
acceptanceCriteria: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
16
|
+
}, z.core.$strip>;
|
|
17
|
+
export declare const subagentInputSchema: z.ZodObject<{
|
|
18
|
+
objective: z.ZodString;
|
|
19
|
+
deliverable: z.ZodString;
|
|
20
|
+
mode: z.ZodEnum<{
|
|
21
|
+
inspect: "inspect";
|
|
22
|
+
research: "research";
|
|
23
|
+
implement: "implement";
|
|
24
|
+
validate: "validate";
|
|
25
|
+
}>;
|
|
26
|
+
scope: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
27
|
+
acceptanceCriteria: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
28
|
+
}, z.core.$strip>;
|
|
29
|
+
export type SubagentToolInput = z.infer<typeof subagentInputSchema>;
|
|
30
|
+
export interface SubagentTaskCapsule {
|
|
31
|
+
id: string;
|
|
32
|
+
objective: string;
|
|
33
|
+
deliverable: string;
|
|
34
|
+
mode: WorkerMode;
|
|
35
|
+
scope: string[];
|
|
36
|
+
acceptanceCriteria: string[];
|
|
37
|
+
legacyMaxSteps?: number;
|
|
38
|
+
}
|
|
39
|
+
export type WorkerTermination = 'completed' | 'no_output' | 'step_limit' | 'tool_limit' | 'deadline_exceeded' | 'cancelled' | 'provider_error' | 'policy_blocked';
|
|
40
|
+
export interface SubagentResultCapsule {
|
|
41
|
+
id: string;
|
|
42
|
+
termination: WorkerTermination;
|
|
43
|
+
usable: boolean;
|
|
44
|
+
deliverable: string;
|
|
45
|
+
changedPaths: string[];
|
|
46
|
+
validation: Array<{
|
|
47
|
+
command: string;
|
|
48
|
+
ok: boolean;
|
|
49
|
+
}>;
|
|
50
|
+
coverageGaps: string[];
|
|
51
|
+
truncated: boolean;
|
|
52
|
+
resultHandle?: string;
|
|
53
|
+
}
|
|
54
|
+
export interface SubagentTelemetry {
|
|
55
|
+
modelSelector: string;
|
|
56
|
+
profile: string;
|
|
57
|
+
durationMs: number;
|
|
58
|
+
queueMs: number;
|
|
59
|
+
toolCallCount: number;
|
|
60
|
+
toolCalls: Array<{
|
|
61
|
+
name: string;
|
|
62
|
+
summary: string;
|
|
63
|
+
durationMs: number;
|
|
64
|
+
}>;
|
|
65
|
+
usage: {
|
|
66
|
+
inputTokens?: number;
|
|
67
|
+
outputTokens?: number;
|
|
68
|
+
};
|
|
69
|
+
estimates: {
|
|
70
|
+
taskCapsuleTokens: number;
|
|
71
|
+
initialInputTokens: number;
|
|
72
|
+
privateContextTokens: number;
|
|
73
|
+
resultCapsuleTokens: number;
|
|
74
|
+
mainContextTokensAvoided: number;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export interface SubagentExecutionResult {
|
|
78
|
+
capsule: SubagentResultCapsule;
|
|
79
|
+
telemetry: SubagentTelemetry;
|
|
80
|
+
status: 'ok' | 'error' | 'timeout' | 'cancelled';
|
|
81
|
+
summary: string;
|
|
82
|
+
toolCalls: SubagentTelemetry['toolCalls'];
|
|
83
|
+
toolCallCount: number;
|
|
84
|
+
tokens: {
|
|
85
|
+
in?: number;
|
|
86
|
+
out?: number;
|
|
87
|
+
};
|
|
88
|
+
durationMs: number;
|
|
89
|
+
error?: string;
|
|
90
|
+
}
|
|
91
|
+
export interface ProviderCapabilities {
|
|
92
|
+
reportsCacheUsage: boolean;
|
|
93
|
+
supportsPromptCacheKey: boolean;
|
|
94
|
+
supportsExtendedCacheRetention: boolean;
|
|
95
|
+
supportsStickySessionId: boolean;
|
|
96
|
+
supportsServerCompaction: boolean;
|
|
97
|
+
supportsTextVerbosity: boolean;
|
|
98
|
+
/** Protocol accepts an OpenAI-style reasoning-effort provider option. */
|
|
99
|
+
supportsReasoningEffort: boolean;
|
|
100
|
+
}
|
|
101
|
+
export interface ProviderRequestOptions {
|
|
102
|
+
providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
|
|
103
|
+
headers?: Record<string, string>;
|
|
104
|
+
/** Codex subscription requests let the provider manage the output limit. */
|
|
105
|
+
omitMaxOutputTokens?: boolean;
|
|
106
|
+
}
|
|
107
|
+
export interface WorkerRuntime {
|
|
108
|
+
model: LanguageModel;
|
|
109
|
+
selector: string;
|
|
110
|
+
providerName: string;
|
|
111
|
+
capabilities: ProviderCapabilities;
|
|
112
|
+
requestOptions: ProviderRequestOptions;
|
|
113
|
+
}
|
|
114
|
+
/** All-false capabilities + empty request options, used when no real provider runtime is known (CR-018). */
|
|
115
|
+
export declare function fallbackProviderCapabilities(): ProviderCapabilities;
|
|
116
|
+
/** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
|
|
117
|
+
export declare function fallbackWorkerRuntime(model: WorkerRuntime['model'], selector?: string, providerName?: string): WorkerRuntime;
|
|
118
|
+
export declare function normalizeSubagentInput(input: SubagentToolInput, id: string): SubagentTaskCapsule;
|
|
119
|
+
export declare function legacyStatus(termination: WorkerTermination): SubagentExecutionResult['status'];
|
|
120
|
+
export declare function withLegacyProjection(capsule: SubagentResultCapsule, telemetry: SubagentTelemetry, error?: string): SubagentExecutionResult;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { SUBAGENT_ACCEPTANCE_CHARS, SUBAGENT_ACCEPTANCE_ITEMS, SUBAGENT_DELIVERABLE_CHARS, SUBAGENT_OBJECTIVE_CHARS, SUBAGENT_SCOPE_CHARS, SUBAGENT_SCOPE_ITEMS, } from '../agent/budgets.js';
|
|
3
|
+
export const workerModes = ['inspect', 'research', 'implement', 'validate'];
|
|
4
|
+
export const subagentTaskInputV2Schema = z.object({
|
|
5
|
+
objective: z.string().trim().min(1).max(SUBAGENT_OBJECTIVE_CHARS).describe('Self-contained outcome for the worker. Keep it under 1000 characters; do not paste conversation history or file contents.'),
|
|
6
|
+
deliverable: z.string().trim().min(1).max(SUBAGENT_DELIVERABLE_CHARS).describe('Exact compact result the worker must return to the main agent.'),
|
|
7
|
+
mode: z.enum(workerModes).describe('inspect/research are read-only; implement may edit; validate may run commands.'),
|
|
8
|
+
scope: z.array(z.string().trim().min(1).max(SUBAGENT_SCOPE_CHARS)).max(SUBAGENT_SCOPE_ITEMS).optional().describe('Optional workspace-relative paths that bound the task. Prefer at most 12 concise directory/file hints.'),
|
|
9
|
+
acceptanceCriteria: z.array(z.string().trim().min(1).max(SUBAGENT_ACCEPTANCE_CHARS)).max(SUBAGENT_ACCEPTANCE_ITEMS).optional().describe('Optional concise conditions the deliverable must satisfy.'),
|
|
10
|
+
}).describe('A single self-contained task capsule for a disposable subagent.');
|
|
11
|
+
// Keep the model-facing schema flat and unambiguous. In particular, do not
|
|
12
|
+
// union it with the pre-capsule {task, tools, maxSteps} shape: several local
|
|
13
|
+
// OpenAI-compatible models respond to union tool schemas with an empty object.
|
|
14
|
+
export const subagentInputSchema = subagentTaskInputV2Schema;
|
|
15
|
+
/** All-false capabilities + empty request options, used when no real provider runtime is known (CR-018). */
|
|
16
|
+
export function fallbackProviderCapabilities() {
|
|
17
|
+
return {
|
|
18
|
+
reportsCacheUsage: false,
|
|
19
|
+
supportsPromptCacheKey: false,
|
|
20
|
+
supportsExtendedCacheRetention: false,
|
|
21
|
+
supportsStickySessionId: false,
|
|
22
|
+
supportsServerCompaction: false,
|
|
23
|
+
supportsTextVerbosity: false,
|
|
24
|
+
supportsReasoningEffort: false,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
|
|
28
|
+
export function fallbackWorkerRuntime(model, selector = 'active-model', providerName = 'active') {
|
|
29
|
+
return { model, selector, providerName, capabilities: fallbackProviderCapabilities(), requestOptions: {} };
|
|
30
|
+
}
|
|
31
|
+
export function normalizeSubagentInput(input, id) {
|
|
32
|
+
return { id, objective: input.objective, deliverable: input.deliverable, mode: input.mode, scope: input.scope ?? [], acceptanceCriteria: input.acceptanceCriteria ?? [] };
|
|
33
|
+
}
|
|
34
|
+
export function legacyStatus(termination) {
|
|
35
|
+
if (termination === 'completed' || termination === 'no_output')
|
|
36
|
+
return 'ok';
|
|
37
|
+
if (termination === 'cancelled')
|
|
38
|
+
return 'cancelled';
|
|
39
|
+
if (termination === 'step_limit' || termination === 'tool_limit' || termination === 'deadline_exceeded')
|
|
40
|
+
return 'timeout';
|
|
41
|
+
return 'error';
|
|
42
|
+
}
|
|
43
|
+
export function withLegacyProjection(capsule, telemetry, error) {
|
|
44
|
+
return {
|
|
45
|
+
capsule,
|
|
46
|
+
telemetry,
|
|
47
|
+
status: legacyStatus(capsule.termination),
|
|
48
|
+
summary: capsule.deliverable,
|
|
49
|
+
toolCalls: telemetry.toolCalls,
|
|
50
|
+
toolCallCount: telemetry.toolCallCount,
|
|
51
|
+
tokens: { in: telemetry.usage.inputTokens, out: telemetry.usage.outputTokens },
|
|
52
|
+
durationMs: telemetry.durationMs,
|
|
53
|
+
...(error ? { error } : {}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { WorkerMode } from './contracts.js';
|
|
3
|
+
export interface SubagentExecutionProfile {
|
|
4
|
+
name: string;
|
|
5
|
+
maxConcurrency: number;
|
|
6
|
+
maxSteps: number;
|
|
7
|
+
maxToolCalls: number;
|
|
8
|
+
maxOutputTokens: number;
|
|
9
|
+
maxSummaryChars: number;
|
|
10
|
+
maxInputTokens: number;
|
|
11
|
+
deadlineMs: number;
|
|
12
|
+
maxRetries: number;
|
|
13
|
+
}
|
|
14
|
+
export declare const customProfileSchema: z.ZodObject<{
|
|
15
|
+
maxConcurrency: z.ZodOptional<z.ZodNumber>;
|
|
16
|
+
maxSteps: z.ZodOptional<z.ZodNumber>;
|
|
17
|
+
maxToolCalls: z.ZodOptional<z.ZodNumber>;
|
|
18
|
+
maxOutputTokens: z.ZodOptional<z.ZodNumber>;
|
|
19
|
+
maxSummaryChars: z.ZodOptional<z.ZodNumber>;
|
|
20
|
+
maxInputTokens: z.ZodOptional<z.ZodNumber>;
|
|
21
|
+
deadlineMs: z.ZodOptional<z.ZodNumber>;
|
|
22
|
+
maxRetries: z.ZodOptional<z.ZodNumber>;
|
|
23
|
+
}, z.core.$loose>;
|
|
24
|
+
export declare const COMPATIBILITY_PROFILE: SubagentExecutionProfile;
|
|
25
|
+
export declare const BUILT_IN_SUBAGENT_PROFILES: Readonly<Record<string, SubagentExecutionProfile>>;
|
|
26
|
+
export declare const MODE_TOOL_NAMES: Readonly<Record<WorkerMode, readonly string[]>>;
|
|
27
|
+
export declare function isMutationMode(mode: WorkerMode): mode is "implement" | "validate";
|
|
28
|
+
export declare function resolveExecutionProfile(name: string | undefined, custom: Record<string, unknown> | undefined, concurrency?: number): SubagentExecutionProfile | undefined;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { SUBAGENT_DEFAULT_DEADLINE_MS, SUBAGENT_DEFAULT_INPUT_TOKENS, SUBAGENT_DEFAULT_OUTPUT_TOKENS, SUBAGENT_DEFAULT_STEPS, SUBAGENT_DEFAULT_SUMMARY_CHARS, SUBAGENT_DEFAULT_TOOL_CALLS, SUBAGENT_MAX_CONCURRENCY, SUBAGENT_MAX_DEADLINE_MS, SUBAGENT_MAX_INPUT_TOKENS, SUBAGENT_MAX_OUTPUT_TOKENS, SUBAGENT_MAX_RETRIES, SUBAGENT_MAX_STEPS, SUBAGENT_MAX_SUMMARY_CHARS, SUBAGENT_MAX_TOOL_CALLS, SUBAGENT_MIN_DEADLINE_MS, SUBAGENT_MIN_STEPS, } from '../agent/budgets.js';
|
|
3
|
+
export const customProfileSchema = z.object({
|
|
4
|
+
maxConcurrency: z.number().int().min(1).max(SUBAGENT_MAX_CONCURRENCY).optional(),
|
|
5
|
+
maxSteps: z.number().int().min(SUBAGENT_MIN_STEPS).max(SUBAGENT_MAX_STEPS).optional(),
|
|
6
|
+
maxToolCalls: z.number().int().min(1).max(SUBAGENT_MAX_TOOL_CALLS).optional(),
|
|
7
|
+
maxOutputTokens: z.number().int().min(256).max(SUBAGENT_MAX_OUTPUT_TOKENS).optional(),
|
|
8
|
+
maxSummaryChars: z.number().int().min(500).max(SUBAGENT_MAX_SUMMARY_CHARS).optional(),
|
|
9
|
+
maxInputTokens: z.number().int().min(1_000).max(SUBAGENT_MAX_INPUT_TOKENS).optional(),
|
|
10
|
+
deadlineMs: z.number().int().min(SUBAGENT_MIN_DEADLINE_MS).max(SUBAGENT_MAX_DEADLINE_MS).optional(),
|
|
11
|
+
maxRetries: z.number().int().min(0).max(SUBAGENT_MAX_RETRIES).optional(),
|
|
12
|
+
}).passthrough();
|
|
13
|
+
export const COMPATIBILITY_PROFILE = {
|
|
14
|
+
name: 'compatibility', maxConcurrency: 5, maxSteps: SUBAGENT_DEFAULT_STEPS,
|
|
15
|
+
maxToolCalls: SUBAGENT_DEFAULT_TOOL_CALLS, maxOutputTokens: SUBAGENT_DEFAULT_OUTPUT_TOKENS,
|
|
16
|
+
maxSummaryChars: SUBAGENT_DEFAULT_SUMMARY_CHARS, maxInputTokens: SUBAGENT_DEFAULT_INPUT_TOKENS,
|
|
17
|
+
deadlineMs: SUBAGENT_DEFAULT_DEADLINE_MS, maxRetries: 2,
|
|
18
|
+
};
|
|
19
|
+
export const BUILT_IN_SUBAGENT_PROFILES = {
|
|
20
|
+
'local-safe': { ...COMPATIBILITY_PROFILE, name: 'local-safe', maxConcurrency: 1, maxSteps: 16, maxToolCalls: 12, maxOutputTokens: 2_048, maxInputTokens: 20_000, maxRetries: 0 },
|
|
21
|
+
'local-throughput': { ...COMPATIBILITY_PROFILE, name: 'local-throughput', maxConcurrency: 2, maxSteps: 20, maxToolCalls: 16, maxOutputTokens: 3_072, maxInputTokens: 24_000, maxRetries: 0 },
|
|
22
|
+
'cloud-balanced': { ...COMPATIBILITY_PROFILE, name: 'cloud-balanced', maxConcurrency: 3, deadlineMs: 180_000 },
|
|
23
|
+
'cloud-fast': { ...COMPATIBILITY_PROFILE, name: 'cloud-fast', maxConcurrency: 5, deadlineMs: 120_000, maxRetries: 1 },
|
|
24
|
+
};
|
|
25
|
+
export const MODE_TOOL_NAMES = {
|
|
26
|
+
inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput'],
|
|
27
|
+
research: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'fetch'],
|
|
28
|
+
implement: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'bash'],
|
|
29
|
+
validate: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'bash'],
|
|
30
|
+
};
|
|
31
|
+
export function isMutationMode(mode) {
|
|
32
|
+
return mode === 'implement' || mode === 'validate';
|
|
33
|
+
}
|
|
34
|
+
export function resolveExecutionProfile(name, custom, concurrency) {
|
|
35
|
+
const selected = name ? BUILT_IN_SUBAGENT_PROFILES[name] : COMPATIBILITY_PROFILE;
|
|
36
|
+
const customValue = name ? custom?.[name] : undefined;
|
|
37
|
+
if (!selected && customValue == null)
|
|
38
|
+
return undefined;
|
|
39
|
+
const parsed = customValue == null ? {} : customProfileSchema.parse(customValue);
|
|
40
|
+
const base = selected ?? { ...COMPATIBILITY_PROFILE, name: name };
|
|
41
|
+
const merged = { ...base, ...parsed, name: name ?? base.name };
|
|
42
|
+
if (concurrency != null)
|
|
43
|
+
return { ...merged, maxConcurrency: z.number().int().min(1).max(SUBAGENT_MAX_CONCURRENCY).parse(concurrency) };
|
|
44
|
+
return merged;
|
|
45
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { WorkerMode, WorkerTermination } from './contracts.js';
|
|
2
|
+
import { type SubagentExecutionProfile } from './executionProfiles.js';
|
|
3
|
+
export type CoordinatorEvent = {
|
|
4
|
+
type: 'queued';
|
|
5
|
+
id: string;
|
|
6
|
+
mode: WorkerMode;
|
|
7
|
+
queued: number;
|
|
8
|
+
running: number;
|
|
9
|
+
} | {
|
|
10
|
+
type: 'started';
|
|
11
|
+
id: string;
|
|
12
|
+
mode: WorkerMode;
|
|
13
|
+
queueMs: number;
|
|
14
|
+
running: number;
|
|
15
|
+
} | {
|
|
16
|
+
type: 'terminal';
|
|
17
|
+
id: string;
|
|
18
|
+
mode: WorkerMode;
|
|
19
|
+
termination: WorkerTermination;
|
|
20
|
+
execution: 'settled' | 'quarantined';
|
|
21
|
+
queueMs: number;
|
|
22
|
+
durationMs: number;
|
|
23
|
+
running: number;
|
|
24
|
+
} | {
|
|
25
|
+
type: 'settled';
|
|
26
|
+
id: string;
|
|
27
|
+
mode: WorkerMode;
|
|
28
|
+
termination: WorkerTermination;
|
|
29
|
+
queueMs: number;
|
|
30
|
+
durationMs: number;
|
|
31
|
+
running: number;
|
|
32
|
+
};
|
|
33
|
+
interface Submission<T> {
|
|
34
|
+
id: string;
|
|
35
|
+
mode: WorkerMode;
|
|
36
|
+
sequence: number;
|
|
37
|
+
batch: number;
|
|
38
|
+
submittedAt: number;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
run: (context: {
|
|
41
|
+
id: string;
|
|
42
|
+
signal: AbortSignal;
|
|
43
|
+
queueMs: number;
|
|
44
|
+
deadlineExpired: () => boolean;
|
|
45
|
+
}) => Promise<T>;
|
|
46
|
+
terminal: (termination: WorkerTermination, queueMs: number) => T;
|
|
47
|
+
terminationOf: (value: T) => WorkerTermination;
|
|
48
|
+
resolve: (value: T) => void;
|
|
49
|
+
abortListener?: () => void;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Turn-scoped worker admission. A deadline returns logical control immediately,
|
|
53
|
+
* but an uncooperative underlying execution remains quarantined and continues
|
|
54
|
+
* to consume its real concurrency/mutation slot until it physically settles.
|
|
55
|
+
*/
|
|
56
|
+
export declare class SubagentCoordinator {
|
|
57
|
+
private readonly profile;
|
|
58
|
+
private readonly onEvent?;
|
|
59
|
+
private readonly queue;
|
|
60
|
+
private running;
|
|
61
|
+
private mutationRunning;
|
|
62
|
+
/** Read-only workers admitted behind a blocked mutation head (RH-010). */
|
|
63
|
+
private bypassRunning;
|
|
64
|
+
private nextId;
|
|
65
|
+
private nextSequence;
|
|
66
|
+
private submissionBatch;
|
|
67
|
+
private admissionScheduled;
|
|
68
|
+
peakConcurrency: number;
|
|
69
|
+
/** Peak read-only workers running concurrently behind a blocked mutation. */
|
|
70
|
+
peakBypass: number;
|
|
71
|
+
constructor(profile: SubagentExecutionProfile, onEvent?: ((event: CoordinatorEvent) => void) | undefined);
|
|
72
|
+
createId(): string;
|
|
73
|
+
submit<T>(input: Omit<Submission<T>, 'resolve' | 'submittedAt' | 'sequence' | 'batch' | 'abortListener'>): Promise<T>;
|
|
74
|
+
private scheduleAdmission;
|
|
75
|
+
private admit;
|
|
76
|
+
private start;
|
|
77
|
+
}
|
|
78
|
+
export {};
|