@denizokcu/haze 0.8.0 → 0.10.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 (182) hide show
  1. package/CHANGELOG.md +67 -17
  2. package/README.md +121 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.d.ts +3 -0
  14. package/dist/cli/chat/sessionRecorder.js +21 -8
  15. package/dist/cli/chat/startupInfo.d.ts +1 -0
  16. package/dist/cli/chat/startupInfo.js +11 -0
  17. package/dist/cli/chat/tips.d.ts +21 -0
  18. package/dist/cli/chat/tips.js +43 -0
  19. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  20. package/dist/cli/chat/wizardDispatch.js +645 -0
  21. package/dist/cli/commands/chat.d.ts +1 -0
  22. package/dist/cli/commands/chat.js +246 -779
  23. package/dist/cli/commands/chatModes.d.ts +1 -1
  24. package/dist/cli/commands/chatModes.js +7 -2
  25. package/dist/cli/commands/commandHelp.js +5 -3
  26. package/dist/cli/commands/commands.d.ts +4 -3
  27. package/dist/cli/commands/commands.js +12 -13
  28. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  29. package/dist/cli/commands/fleetCommand.js +46 -0
  30. package/dist/cli/commands/formatters.d.ts +5 -0
  31. package/dist/cli/commands/formatters.js +36 -9
  32. package/dist/cli/commands/logsCommand.js +8 -28
  33. package/dist/cli/commands/mcpWizard.js +24 -2
  34. package/dist/cli/commands/modelCommand.js +1 -1
  35. package/dist/cli/commands/providerWizard.d.ts +1 -0
  36. package/dist/cli/commands/providerWizard.js +31 -5
  37. package/dist/cli/commands/runCommand.d.ts +1 -0
  38. package/dist/cli/commands/runCommand.js +32 -20
  39. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  40. package/dist/cli/commands/sessionPicker.js +29 -0
  41. package/dist/cli/commands/settingsSummary.js +8 -4
  42. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  43. package/dist/cli/commands/skillWizard.d.ts +2 -0
  44. package/dist/cli/commands/skillWizard.js +16 -6
  45. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  46. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  47. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  48. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  49. package/dist/cli/commands/streaming/turnOutcome.d.ts +10 -0
  50. package/dist/cli/commands/streaming/turnOutcome.js +13 -0
  51. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  52. package/dist/cli/commands/streaming.d.ts +13 -1
  53. package/dist/cli/commands/streaming.js +104 -44
  54. package/dist/cli/commands/wizardActions.d.ts +6 -0
  55. package/dist/cli/commands/wizardActions.js +6 -0
  56. package/dist/cli/commands/wizardPrompts.js +1 -1
  57. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  58. package/dist/cli/commands/wizardSuggestions.js +62 -13
  59. package/dist/cli/commands/wizardTransition.d.ts +37 -0
  60. package/dist/cli/commands/wizardTransition.js +43 -0
  61. package/dist/cli/index.js +17 -3
  62. package/dist/cli/terminalTitle.d.ts +6 -0
  63. package/dist/cli/terminalTitle.js +36 -0
  64. package/dist/config/contextFiles.js +6 -3
  65. package/dist/config/endpointSecurity.d.ts +2 -0
  66. package/dist/config/endpointSecurity.js +28 -0
  67. package/dist/config/inputHistory.d.ts +3 -3
  68. package/dist/config/inputHistory.js +13 -17
  69. package/dist/config/modelDiscovery.d.ts +20 -0
  70. package/dist/config/modelDiscovery.js +51 -0
  71. package/dist/config/privateStorage.d.ts +6 -0
  72. package/dist/config/privateStorage.js +61 -0
  73. package/dist/config/providerPresets.d.ts +16 -4
  74. package/dist/config/providerPresets.js +263 -34
  75. package/dist/config/providers.d.ts +2 -0
  76. package/dist/config/providers.js +7 -0
  77. package/dist/config/settings.d.ts +22 -0
  78. package/dist/config/settings.js +33 -5
  79. package/dist/config/skillSettings.d.ts +6 -13
  80. package/dist/config/skillSettings.js +20 -19
  81. package/dist/config/updateCheck.js +4 -2
  82. package/dist/core/agent/budgets.d.ts +26 -0
  83. package/dist/core/agent/budgets.js +34 -0
  84. package/dist/core/agent/compaction.js +17 -3
  85. package/dist/core/agent/contextBudget.d.ts +8 -0
  86. package/dist/core/agent/contextBudget.js +29 -0
  87. package/dist/core/agent/errors.js +6 -2
  88. package/dist/core/agent/events.d.ts +12 -0
  89. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  90. package/dist/core/agent/toolOutputStore.js +49 -11
  91. package/dist/core/agent/workState.d.ts +1 -1
  92. package/dist/core/agent/workState.js +0 -4
  93. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  94. package/dist/core/attachments/imageAttachments.js +245 -0
  95. package/dist/core/attachments/readBlessings.d.ts +37 -0
  96. package/dist/core/attachments/readBlessings.js +79 -0
  97. package/dist/core/goal/completionPolicy.d.ts +0 -28
  98. package/dist/core/goal/completionPolicy.js +0 -88
  99. package/dist/core/goal/requestClassifier.d.ts +0 -3
  100. package/dist/core/goal/requestClassifier.js +0 -13
  101. package/dist/core/io/boundedRead.d.ts +15 -0
  102. package/dist/core/io/boundedRead.js +144 -0
  103. package/dist/core/limits/byteBudgets.d.ts +18 -0
  104. package/dist/core/limits/byteBudgets.js +18 -0
  105. package/dist/core/limits/textBudgets.d.ts +23 -0
  106. package/dist/core/limits/textBudgets.js +23 -0
  107. package/dist/core/log/llmLog.d.ts +10 -0
  108. package/dist/core/log/llmLog.js +59 -13
  109. package/dist/core/persistence/orderedFileWriter.d.ts +11 -0
  110. package/dist/core/persistence/orderedFileWriter.js +29 -0
  111. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  112. package/dist/core/process/backgroundRegistry.js +194 -0
  113. package/dist/core/process/runBoundedProcess.d.ts +30 -0
  114. package/dist/core/process/runBoundedProcess.js +116 -0
  115. package/dist/core/safety/urlGuard.d.ts +2 -1
  116. package/dist/core/safety/urlGuard.js +3 -2
  117. package/dist/core/session/sessionSlimming.js +47 -4
  118. package/dist/core/session/sessionStore.d.ts +37 -0
  119. package/dist/core/session/sessionStore.js +136 -27
  120. package/dist/core/subagent/contracts.d.ts +116 -0
  121. package/dist/core/subagent/contracts.js +54 -0
  122. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  123. package/dist/core/subagent/executionProfiles.js +45 -0
  124. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  125. package/dist/core/subagent/subagentCoordinator.js +134 -0
  126. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  127. package/dist/core/subagent/subagentRunner.js +228 -98
  128. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  129. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  130. package/dist/core/tasks/taskStorage.js +12 -1
  131. package/dist/llm/client.d.ts +20 -29
  132. package/dist/llm/client.js +33 -29
  133. package/dist/llm/hazeTools.d.ts +2396 -67
  134. package/dist/llm/hazeTools.js +50 -37
  135. package/dist/llm/lsp.d.ts +23 -3
  136. package/dist/llm/lsp.js +73 -16
  137. package/dist/llm/lspTools.d.ts +96 -48
  138. package/dist/llm/mcp.d.ts +1 -1
  139. package/dist/llm/mcp.js +65 -16
  140. package/dist/llm/requestContext.d.ts +23 -1
  141. package/dist/llm/requestContext.js +50 -7
  142. package/dist/llm/systemPrompt.d.ts +4 -1
  143. package/dist/llm/systemPrompt.js +14 -4
  144. package/dist/llm/toolResultTypes.d.ts +1 -1
  145. package/dist/llm/tools/bashTool.d.ts +1210 -16
  146. package/dist/llm/tools/bashTool.js +43 -60
  147. package/dist/llm/tools/fetchTool.d.ts +26 -26
  148. package/dist/llm/tools/fetchTool.js +1 -1
  149. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  150. package/dist/llm/tools/fileToolShared.js +5 -5
  151. package/dist/llm/tools/grepRunner.d.ts +20 -0
  152. package/dist/llm/tools/grepRunner.js +66 -0
  153. package/dist/llm/tools/outputCap.d.ts +2 -6
  154. package/dist/llm/tools/outputCap.js +2 -6
  155. package/dist/llm/tools/processTool.d.ts +1077 -0
  156. package/dist/llm/tools/processTool.js +41 -0
  157. package/dist/llm/tools/toolContext.d.ts +8 -0
  158. package/dist/llm/tools/toolContext.js +22 -11
  159. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  160. package/dist/llm/tools/workspaceFile.js +33 -4
  161. package/dist/llm/webFetch.js +24 -11
  162. package/dist/llm/workerContext.d.ts +18 -0
  163. package/dist/llm/workerContext.js +55 -0
  164. package/dist/skills/SkillLoader.d.ts +2 -2
  165. package/dist/skills/SkillLoader.js +17 -5
  166. package/dist/skills/SkillRegistry.d.ts +3 -2
  167. package/dist/skills/SkillRegistry.js +53 -10
  168. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  169. package/dist/skills/builder/SkillBuilder.js +23 -5
  170. package/dist/skills/skillTools.js +11 -4
  171. package/dist/skills/types.d.ts +11 -1
  172. package/dist/ui/components/TextInput.d.ts +5 -2
  173. package/dist/ui/components/TextInput.js +76 -8
  174. package/dist/utils/format.d.ts +2 -0
  175. package/dist/utils/format.js +8 -0
  176. package/dist/utils/fs.d.ts +0 -1
  177. package/dist/utils/fs.js +0 -4
  178. package/dist/utils/openPath.d.ts +2 -0
  179. package/dist/utils/openPath.js +9 -0
  180. package/dist/utils/path.d.ts +2 -0
  181. package/dist/utils/path.js +9 -4
  182. package/package.json +1 -1
@@ -0,0 +1,116 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ export function signalProcessTree(child, signal) {
4
+ if (child.pid == null) {
5
+ child.kill(signal);
6
+ return;
7
+ }
8
+ if (process.platform === 'win32') {
9
+ if (signal === 'SIGKILL')
10
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' }).unref();
11
+ else
12
+ child.kill('SIGTERM');
13
+ return;
14
+ }
15
+ try {
16
+ process.kill(-child.pid, signal);
17
+ }
18
+ catch {
19
+ child.kill(signal);
20
+ }
21
+ }
22
+ function collector(limit) {
23
+ const chunks = [];
24
+ let totalBytes = 0;
25
+ let retainedBytes = 0;
26
+ return {
27
+ add(chunk) {
28
+ totalBytes += chunk.length;
29
+ const remaining = limit - retainedBytes;
30
+ if (remaining > 0) {
31
+ const kept = chunk.subarray(0, remaining);
32
+ chunks.push(kept);
33
+ retainedBytes += kept.length;
34
+ }
35
+ },
36
+ result() {
37
+ const decoder = new StringDecoder('utf8');
38
+ const text = chunks.map(chunk => decoder.write(chunk)).join('') + (totalBytes === retainedBytes ? decoder.end() : '');
39
+ return { text, totalBytes, retainedBytes, omittedBytes: totalBytes - retainedBytes };
40
+ },
41
+ };
42
+ }
43
+ export async function runBoundedProcess(input) {
44
+ const startedAt = Date.now();
45
+ const stdout = collector(input.maxStdoutBytes);
46
+ const stderr = collector(input.maxStderrBytes);
47
+ if (input.signal?.aborted) {
48
+ return { code: null, signal: null, stdout: stdout.result(), stderr: stderr.result(), timedOut: false, aborted: true, forced: false, durationMs: 0 };
49
+ }
50
+ const detached = process.platform !== 'win32';
51
+ const child = spawn(input.command, input.args, { cwd: input.cwd, detached, stdio: ['ignore', 'pipe', 'pipe'] });
52
+ let timedOut = false;
53
+ let aborted = false;
54
+ let forced = false;
55
+ let killTimer;
56
+ let closeTimer;
57
+ let terminating = false;
58
+ let exitCode = null;
59
+ let exitSignal = null;
60
+ return await new Promise(resolve => {
61
+ let settled = false;
62
+ const settle = (code, signal, error) => {
63
+ if (settled)
64
+ return;
65
+ settled = true;
66
+ clearTimeout(timeout);
67
+ if (killTimer)
68
+ clearTimeout(killTimer);
69
+ if (closeTimer)
70
+ clearTimeout(closeTimer);
71
+ input.signal?.removeEventListener('abort', onAbort);
72
+ child.stdout.off('data', stdoutData);
73
+ child.stderr.off('data', stderrData);
74
+ const stdoutResult = stdout.result();
75
+ const stderrResult = stderr.result();
76
+ child.stdout.destroy();
77
+ child.stderr.destroy();
78
+ resolve({ code, signal, stdout: stdoutResult, stderr: stderrResult, timedOut, aborted, forced, durationMs: Date.now() - startedAt, ...(error ? { error } : {}) });
79
+ };
80
+ const scheduleCloseFallback = () => {
81
+ closeTimer ??= setTimeout(() => settle(exitCode, exitSignal), 50);
82
+ closeTimer.unref?.();
83
+ };
84
+ const terminate = () => {
85
+ if (terminating || settled)
86
+ return;
87
+ terminating = true;
88
+ killTree('SIGTERM');
89
+ killTimer = setTimeout(() => {
90
+ forced = true;
91
+ killTree('SIGKILL');
92
+ scheduleCloseFallback();
93
+ }, input.killGraceMs ?? 500);
94
+ killTimer.unref?.();
95
+ };
96
+ const timeout = setTimeout(() => { timedOut = true; terminate(); }, input.timeoutMs);
97
+ const onAbort = () => { aborted = true; terminate(); };
98
+ input.signal?.addEventListener('abort', onAbort, { once: true });
99
+ const killTree = (signal) => signalProcessTree(child, signal);
100
+ const stdoutData = (chunk) => {
101
+ stdout.add(chunk);
102
+ // Streaming interceptors (e.g. grep's early-stop) may request termination.
103
+ if (!terminating && input.onStdoutChunk?.(chunk))
104
+ terminate();
105
+ };
106
+ const stderrData = (chunk) => stderr.add(chunk);
107
+ child.stdout.on('data', stdoutData);
108
+ child.stderr.on('data', stderrData);
109
+ child.once('error', error => settle(null, null, error.message));
110
+ child.once('exit', (code, signal) => {
111
+ exitCode = code;
112
+ exitSignal = signal;
113
+ });
114
+ child.once('close', (code, signal) => settle(code, signal));
115
+ });
116
+ }
@@ -21,7 +21,8 @@ export type UrlValidation = {
21
21
  export type DnsLookupFn = (hostname: string) => Promise<string[]>;
22
22
  /**
23
23
  * Check whether a literal IP address (v4 or v6) is in a blocked range.
24
- * Returns false for non-IP strings (hostnames are resolved separately).
24
+ * Returns false for ordinary non-IP strings. Colon-shaped malformed IPv6 is
25
+ * blocked fail-closed because callers treat such hosts as literal addresses.
25
26
  */
26
27
  export declare function isBlockedIp(ip: string): boolean;
27
28
  /**
@@ -116,7 +116,7 @@ function ipv6InBlockedRange(ip) {
116
116
  num = ipv6ToBigInt(ip);
117
117
  }
118
118
  catch {
119
- return false;
119
+ return true;
120
120
  }
121
121
  for (const range of BLOCKED_IPV6_CIDRS) {
122
122
  if ((num & range.mask) === range.start)
@@ -126,7 +126,8 @@ function ipv6InBlockedRange(ip) {
126
126
  }
127
127
  /**
128
128
  * Check whether a literal IP address (v4 or v6) is in a blocked range.
129
- * Returns false for non-IP strings (hostnames are resolved separately).
129
+ * Returns false for ordinary non-IP strings. Colon-shaped malformed IPv6 is
130
+ * blocked fail-closed because callers treat such hosts as literal addresses.
130
131
  */
131
132
  export function isBlockedIp(ip) {
132
133
  // Strip IPv6 bracket form for literal checks.
@@ -1,6 +1,6 @@
1
- const INLINE_VALUE_BYTES = 32 * 1024;
2
- const PREVIEW_CHARS = 4 * 1024;
3
- const LARGE_STRING_CHARS = 8 * 1024;
1
+ import { SESSION_INLINE_VALUE_BYTES as INLINE_VALUE_BYTES, SESSION_LARGE_STRING_CHARS as LARGE_STRING_CHARS, SESSION_PREVIEW_CHARS as PREVIEW_CHARS } from '../limits/textBudgets.js';
2
+ import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
3
+ import { formatBytes } from '../../utils/format.js';
4
4
  function jsonByteLength(value) {
5
5
  try {
6
6
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
@@ -24,6 +24,19 @@ function slimLargeValue(value) {
24
24
  preview: previewText(value),
25
25
  };
26
26
  }
27
+ /**
28
+ * Image file parts become text placeholders (F03): resumed sessions must not
29
+ * replay megabytes of base64, and the placeholder stays a protocol-safe
30
+ * ModelMessage part for any provider. The model re-asks if it needs the image.
31
+ */
32
+ function slimImageFilePart(part) {
33
+ const bytes = imageFilePartBytes(part.data);
34
+ const name = typeof part.filename === 'string' && part.filename ? ` ${part.filename}` : '';
35
+ return {
36
+ type: 'text',
37
+ text: `[image omitted from session:${name} ${part.mediaType}, ${formatBytes(bytes)} — ask the user to re-attach it if needed]`,
38
+ };
39
+ }
27
40
  function slimUnknown(value, seen = new WeakSet()) {
28
41
  if (typeof value === 'string') {
29
42
  if (value.length <= LARGE_STRING_CHARS)
@@ -38,6 +51,8 @@ function slimUnknown(value, seen = new WeakSet()) {
38
51
  if (Array.isArray(value))
39
52
  return value.map(item => slimUnknown(item, seen));
40
53
  const record = value;
54
+ if (isImageFilePart(record))
55
+ return slimImageFilePart(record);
41
56
  if (record.type === 'tool-result') {
42
57
  return {
43
58
  ...record,
@@ -53,14 +68,42 @@ function slimUnknown(value, seen = new WeakSet()) {
53
68
  export function slimConversationSnapshot(messages) {
54
69
  return slimUnknown(messages);
55
70
  }
71
+ function slimToolStartInput(input) {
72
+ // Full tool inputs (writeFile/editFile payloads can be tens of KB) are replaced
73
+ // with byte counts; raw inputs stay only in opt-in --debug LLM logs (CR-031).
74
+ const slimmed = { inputBytes: jsonByteLength(input) };
75
+ if (typeof input === 'object' && input != null && typeof input.path === 'string') {
76
+ slimmed.path = input.path;
77
+ }
78
+ return slimmed;
79
+ }
56
80
  export function prepareSessionEntryForWrite(entry) {
57
81
  if (entry.type === 'event') {
58
82
  if (entry.name === 'message_update')
59
83
  return undefined;
84
+ if (entry.name === 'tool_start' && entry.text) {
85
+ try {
86
+ const event = JSON.parse(entry.text);
87
+ event.input = slimToolStartInput(event.input);
88
+ return { ...entry, text: JSON.stringify(event) };
89
+ }
90
+ catch {
91
+ return entry;
92
+ }
93
+ }
60
94
  if (entry.name === 'tool_end' && entry.text) {
61
95
  try {
62
96
  const event = JSON.parse(entry.text);
63
- event.output = slimLargeValue(event.output);
97
+ if (event.name === 'subagent' && typeof event.output === 'object' && event.output != null) {
98
+ const output = event.output;
99
+ const telemetry = typeof output.telemetry === 'object' && output.telemetry != null ? output.telemetry : undefined;
100
+ event.output = {
101
+ capsule: output.capsule,
102
+ coordinator: telemetry ? { modelSelector: telemetry.modelSelector, profile: telemetry.profile, durationMs: telemetry.durationMs, queueMs: telemetry.queueMs, toolCallCount: telemetry.toolCallCount } : undefined,
103
+ };
104
+ }
105
+ else
106
+ event.output = slimLargeValue(event.output);
64
107
  event.error = slimLargeValue(event.error);
65
108
  return { ...entry, text: JSON.stringify(event) };
66
109
  }
@@ -6,6 +6,7 @@ export type SessionEntry = {
6
6
  cwd: string;
7
7
  createdAt: string;
8
8
  hazeVersion?: string;
9
+ forkedFrom?: string;
9
10
  } | {
10
11
  type: 'ui_message';
11
12
  at: string;
@@ -34,7 +35,9 @@ export declare function createSession(options?: {
34
35
  cwd?: string;
35
36
  hazeVersion?: string;
36
37
  sessionsDir?: string;
38
+ forkedFrom?: string;
37
39
  }): Promise<HazeSession>;
40
+ export declare function findSession(id: string, cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
38
41
  export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
39
42
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
40
43
  export interface ReadSessionEntriesResult {
@@ -54,10 +57,44 @@ export interface RestoreConversationResult {
54
57
  messages: ModelMessage[];
55
58
  parseErrors: string[];
56
59
  }
60
+ export interface RestoreSessionStateResult {
61
+ messages: ModelMessage[];
62
+ workState: WorkState | undefined;
63
+ parseErrors: string[];
64
+ }
65
+ /**
66
+ * Restore conversation and work state in one file scan (CR-013). Session
67
+ * files grow to megabytes in long workspaces; resuming should not parse the
68
+ * JSONL twice.
69
+ */
70
+ export declare function restoreSessionState(session: HazeSession): Promise<RestoreSessionStateResult>;
57
71
  export declare function restoreConversation(session: HazeSession): Promise<RestoreConversationResult>;
58
72
  export interface RestoreWorkStateResult {
59
73
  state: WorkState | undefined;
60
74
  parseErrors: string[];
61
75
  }
62
76
  export declare function restoreWorkState(session: HazeSession): Promise<RestoreWorkStateResult>;
77
+ /** Acceptance budget for listing 50 ordinary workspace sessions. */
78
+ export declare const SESSION_LIST_LATENCY_BUDGET_MS = 2000;
79
+ export interface SessionSummary {
80
+ id: string;
81
+ createdAt: string;
82
+ lastActivityAt: string;
83
+ messageCount: number;
84
+ firstUserPreview: string;
85
+ sizeBytes: number;
86
+ lastStatus?: string;
87
+ parseErrors: string[];
88
+ }
89
+ /** List this workspace's sessions newest-first while retaining only summary state per file. */
90
+ export declare function listSessions(cwd?: string, sessionsDir?: string): Promise<SessionSummary[]>;
91
+ export interface ForkSessionResult {
92
+ session: HazeSession;
93
+ parseErrors: string[];
94
+ }
95
+ /** Create a new session from the source's latest durable snapshots without mutating it. */
96
+ export declare function forkSession(source: HazeSession, options?: {
97
+ hazeVersion?: string;
98
+ sessionsDir?: string;
99
+ }): Promise<ForkSessionResult>;
63
100
  export declare function formatSession(session: HazeSession): string;
@@ -3,6 +3,9 @@ import path from 'node:path';
3
3
  import fs from 'fs-extra';
4
4
  import { HAZE_DIR } from '../../config/paths.js';
5
5
  import { prepareSessionEntryForWrite } from './sessionSlimming.js';
6
+ import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
7
+ import { JSONL_LINE_BYTES } from '../limits/byteBudgets.js';
8
+ import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
6
9
  const DEFAULT_SESSIONS_DIR = path.join(HAZE_DIR, 'sessions');
7
10
  function cwdHash(cwd = process.cwd()) {
8
11
  return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
@@ -14,18 +17,30 @@ function sessionFile(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR
14
17
  return path.join(sessionDir(cwd, sessionsDir), `${id}.jsonl`);
15
18
  }
16
19
  function newSessionId(now = new Date()) {
17
- return now.toISOString().replace(/[:.]/g, '-');
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')}`;
18
23
  }
19
24
  export async function createSession(options = {}) {
20
25
  const cwd = path.resolve(options.cwd ?? process.cwd());
21
26
  const id = newSessionId();
22
27
  const file = sessionFile(id, cwd, options.sessionsDir);
23
- await fs.ensureDir(path.dirname(file));
24
- await appendSessionEntry({ id, file, cwd }, { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion });
28
+ await ensurePrivateDir(path.dirname(file));
29
+ await appendSessionEntry({ id, file, cwd }, { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion, forkedFrom: options.forkedFrom });
25
30
  return { id, file, cwd };
26
31
  }
32
+ export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
33
+ const normalizedId = id.trim();
34
+ if (!normalizedId || path.basename(normalizedId) !== normalizedId || normalizedId.endsWith('.jsonl'))
35
+ return undefined;
36
+ const file = sessionFile(normalizedId, cwd, sessionsDir);
37
+ if (!await fs.pathExists(file))
38
+ return undefined;
39
+ return { id: normalizedId, file, cwd: path.resolve(cwd) };
40
+ }
27
41
  export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
28
42
  const dir = sessionDir(cwd, sessionsDir);
43
+ await ensurePrivateDir(dir);
29
44
  const files = (await fs.readdir(dir).catch(() => []))
30
45
  .filter(file => file.endsWith('.jsonl'))
31
46
  .sort();
@@ -39,8 +54,36 @@ export async function appendSessionEntry(session, entry) {
39
54
  const prepared = prepareSessionEntryForWrite(entry);
40
55
  if (!prepared)
41
56
  return;
42
- await fs.ensureDir(path.dirname(session.file));
43
- await fs.appendFile(session.file, `${JSON.stringify(prepared)}\n`, 'utf8');
57
+ await appendPrivateFile(session.file, `${JSON.stringify(prepared)}\n`);
58
+ }
59
+ const MAX_PARSE_ERRORS = 100;
60
+ async function scanSessionEntries(session, onEntry) {
61
+ await tightenPrivateFile(session.file);
62
+ const parseErrors = [];
63
+ let omittedErrors = 0;
64
+ const report = (message) => {
65
+ if (parseErrors.length < MAX_PARSE_ERRORS)
66
+ parseErrors.push(message);
67
+ else
68
+ omittedErrors++;
69
+ };
70
+ for await (const { line, lineNumber, oversized } of iterateBoundedUtf8Lines(session.file, JSONL_LINE_BYTES)) {
71
+ if (!line && !oversized)
72
+ continue;
73
+ if (oversized) {
74
+ report(`Line ${lineNumber}: exceeds ${JSONL_LINE_BYTES} byte limit`);
75
+ continue;
76
+ }
77
+ try {
78
+ onEntry(JSON.parse(line));
79
+ }
80
+ catch (error) {
81
+ report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
82
+ }
83
+ }
84
+ if (omittedErrors > 0)
85
+ parseErrors.push(`${omittedErrors} additional parse errors omitted.`);
86
+ return parseErrors;
44
87
  }
45
88
  /**
46
89
  * Read a session file and parse each non-empty line as a JSONL entry.
@@ -50,34 +93,100 @@ export async function appendSessionEntry(session, entry) {
50
93
  * loss in debug mode instead of silently dropping messages.
51
94
  */
52
95
  export async function readSessionEntries(session) {
53
- const raw = await fs.readFile(session.file, 'utf8');
54
96
  const entries = [];
55
- const parseErrors = [];
56
- // Number by true file position: a stray blank line (e.g. from corruption) must not shift
57
- // the reported line number away from where the malformed line actually sits.
58
- const lines = raw.split('\n');
59
- for (let i = 0; i < lines.length; i++) {
60
- const line = lines[i];
61
- if (!line)
62
- continue; // skip blank lines (e.g. the trailing newline)
63
- try {
64
- entries.push(JSON.parse(line));
65
- }
66
- catch (error) {
67
- parseErrors.push(`Line ${i + 1}: ${error instanceof Error ? error.message : String(error)}`);
68
- }
69
- }
97
+ const parseErrors = await scanSessionEntries(session, entry => entries.push(entry));
70
98
  return { entries, parseErrors };
71
99
  }
100
+ /**
101
+ * Restore conversation and work state in one file scan (CR-013). Session
102
+ * files grow to megabytes in long workspaces; resuming should not parse the
103
+ * JSONL twice.
104
+ */
105
+ export async function restoreSessionState(session) {
106
+ let messages = [];
107
+ let workState;
108
+ const parseErrors = await scanSessionEntries(session, entry => {
109
+ if (entry.type === 'conversation_snapshot')
110
+ messages = entry.messages;
111
+ if (entry.type === 'work_state_snapshot')
112
+ workState = entry.state;
113
+ });
114
+ return { messages, workState, parseErrors };
115
+ }
72
116
  export async function restoreConversation(session) {
73
- const { entries, parseErrors } = await readSessionEntries(session);
74
- const snapshots = entries.filter((entry) => entry.type === 'conversation_snapshot');
75
- return { messages: snapshots.at(-1)?.messages ?? [], parseErrors };
117
+ const { messages, parseErrors } = await restoreSessionState(session);
118
+ return { messages, parseErrors };
76
119
  }
77
120
  export async function restoreWorkState(session) {
78
- const { entries, parseErrors } = await readSessionEntries(session);
79
- const snapshots = entries.filter((entry) => entry.type === 'work_state_snapshot');
80
- return { state: snapshots.at(-1)?.state, parseErrors };
121
+ const { workState, parseErrors } = await restoreSessionState(session);
122
+ return { state: workState, parseErrors };
123
+ }
124
+ const SESSION_PREVIEW_CHARS = 120;
125
+ /** Acceptance budget for listing 50 ordinary workspace sessions. */
126
+ export const SESSION_LIST_LATENCY_BUDGET_MS = 2_000;
127
+ function previewText(text) {
128
+ const compact = text.replace(/\s+/g, ' ').trim();
129
+ return compact.length > SESSION_PREVIEW_CHARS ? `${compact.slice(0, SESSION_PREVIEW_CHARS - 1)}…` : compact;
130
+ }
131
+ /** List this workspace's sessions newest-first while retaining only summary state per file. */
132
+ export async function listSessions(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
133
+ const dir = sessionDir(cwd, sessionsDir);
134
+ await ensurePrivateDir(dir);
135
+ const files = (await fs.readdir(dir).catch(() => [])).filter(file => file.endsWith('.jsonl'));
136
+ const summaries = await Promise.all(files.map(async (fileName) => {
137
+ const id = path.basename(fileName, '.jsonl');
138
+ const session = { id, file: path.join(dir, fileName), cwd: path.resolve(cwd) };
139
+ const stat = await fs.stat(session.file);
140
+ let createdAt = stat.birthtime.toISOString();
141
+ let lastActivityAt = stat.mtime.toISOString();
142
+ let messageCount = 0;
143
+ let firstUserPreview = '';
144
+ let lastStatus;
145
+ const parseErrors = await scanSessionEntries(session, entry => {
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 };
176
+ }));
177
+ return summaries.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
178
+ }
179
+ /** Create a new session from the source's latest durable snapshots without mutating it. */
180
+ export async function forkSession(source, options = {}) {
181
+ const restored = await restoreSessionState(source);
182
+ if (restored.messages.length === 0)
183
+ 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 });
185
+ const at = new Date().toISOString();
186
+ await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
187
+ if (restored.workState)
188
+ await appendSessionEntry(session, { type: 'work_state_snapshot', at, state: restored.workState });
189
+ return { session, parseErrors: restored.parseErrors };
81
190
  }
82
191
  export function formatSession(session) {
83
192
  return `${session.id} · ${session.file}`;
@@ -0,0 +1,116 @@
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
+ }
99
+ export interface ProviderRequestOptions {
100
+ providerOptions?: Record<string, Record<string, JSONValue | undefined>>;
101
+ headers?: Record<string, string>;
102
+ }
103
+ export interface WorkerRuntime {
104
+ model: LanguageModel;
105
+ selector: string;
106
+ providerName: string;
107
+ capabilities: ProviderCapabilities;
108
+ requestOptions: ProviderRequestOptions;
109
+ }
110
+ /** All-false capabilities + empty request options, used when no real provider runtime is known (CR-018). */
111
+ export declare function fallbackProviderCapabilities(): ProviderCapabilities;
112
+ /** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
113
+ export declare function fallbackWorkerRuntime(model: WorkerRuntime['model'], selector?: string, providerName?: string): WorkerRuntime;
114
+ export declare function normalizeSubagentInput(input: SubagentToolInput, id: string): SubagentTaskCapsule;
115
+ export declare function legacyStatus(termination: WorkerTermination): SubagentExecutionResult['status'];
116
+ export declare function withLegacyProjection(capsule: SubagentResultCapsule, telemetry: SubagentTelemetry, error?: string): SubagentExecutionResult;
@@ -0,0 +1,54 @@
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
+ };
25
+ }
26
+ /** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
27
+ export function fallbackWorkerRuntime(model, selector = 'active-model', providerName = 'active') {
28
+ return { model, selector, providerName, capabilities: fallbackProviderCapabilities(), requestOptions: {} };
29
+ }
30
+ export function normalizeSubagentInput(input, id) {
31
+ return { id, objective: input.objective, deliverable: input.deliverable, mode: input.mode, scope: input.scope ?? [], acceptanceCriteria: input.acceptanceCriteria ?? [] };
32
+ }
33
+ export function legacyStatus(termination) {
34
+ if (termination === 'completed' || termination === 'no_output')
35
+ return 'ok';
36
+ if (termination === 'cancelled')
37
+ return 'cancelled';
38
+ if (termination === 'step_limit' || termination === 'tool_limit' || termination === 'deadline_exceeded')
39
+ return 'timeout';
40
+ return 'error';
41
+ }
42
+ export function withLegacyProjection(capsule, telemetry, error) {
43
+ return {
44
+ capsule,
45
+ telemetry,
46
+ status: legacyStatus(capsule.termination),
47
+ summary: capsule.deliverable,
48
+ toolCalls: telemetry.toolCalls,
49
+ toolCallCount: telemetry.toolCallCount,
50
+ tokens: { in: telemetry.usage.inputTokens, out: telemetry.usage.outputTokens },
51
+ durationMs: telemetry.durationMs,
52
+ ...(error ? { error } : {}),
53
+ };
54
+ }