@denizokcu/haze 0.10.0 → 1.0.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 (294) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/README.md +77 -27
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +2 -2
  9. package/dist/cli/chat/chatMetrics.js +1 -1
  10. package/dist/cli/chat/contextReport.js +2 -0
  11. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  12. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  13. package/dist/cli/chat/inputSuggestions.js +9 -41
  14. package/dist/cli/chat/liveRegion.d.ts +25 -0
  15. package/dist/cli/chat/liveRegion.js +48 -0
  16. package/dist/cli/chat/messages.d.ts +33 -4
  17. package/dist/cli/chat/messages.js +218 -35
  18. package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
  19. package/dist/cli/chat/sessionLifecycle.js +64 -14
  20. package/dist/cli/chat/sessionRecorder.js +75 -7
  21. package/dist/cli/chat/startupInfo.d.ts +0 -1
  22. package/dist/cli/chat/startupInfo.js +11 -15
  23. package/dist/cli/chat/turnState.d.ts +1 -1
  24. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  25. package/dist/cli/chat/wizardDispatch.js +349 -133
  26. package/dist/cli/commands/chat.d.ts +5 -0
  27. package/dist/cli/commands/chat.js +216 -172
  28. package/dist/cli/commands/chatModes.d.ts +8 -1
  29. package/dist/cli/commands/chatModes.js +9 -44
  30. package/dist/cli/commands/commands.d.ts +2 -0
  31. package/dist/cli/commands/commands.js +10 -5
  32. package/dist/cli/commands/doctor.d.ts +19 -0
  33. package/dist/cli/commands/doctor.js +76 -0
  34. package/dist/cli/commands/formatters.d.ts +3 -3
  35. package/dist/cli/commands/formatters.js +8 -25
  36. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  37. package/dist/cli/commands/ndjsonSink.js +38 -0
  38. package/dist/cli/commands/providerWizard.d.ts +9 -2
  39. package/dist/cli/commands/providerWizard.js +39 -7
  40. package/dist/cli/commands/runCommand.d.ts +3 -0
  41. package/dist/cli/commands/runCommand.js +117 -11
  42. package/dist/cli/commands/serverWizard.d.ts +34 -0
  43. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  44. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  45. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  46. package/dist/cli/commands/streaming/abortCause.d.ts +25 -0
  47. package/dist/cli/commands/streaming/abortCause.js +16 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  50. package/dist/cli/commands/streaming/assistantText.js +9 -2
  51. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  62. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +16 -0
  66. package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
  68. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  69. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  70. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  71. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  73. package/dist/cli/commands/streaming.d.ts +65 -9
  74. package/dist/cli/commands/streaming.js +133 -430
  75. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  76. package/dist/cli/commands/wizardFlow.js +377 -0
  77. package/dist/cli/contextReport.js +3 -0
  78. package/dist/cli/index.js +68 -22
  79. package/dist/cli/terminalTitle.js +1 -1
  80. package/dist/config/contextFiles.js +9 -3
  81. package/dist/config/inputHistory.d.ts +0 -1
  82. package/dist/config/inputHistory.js +1 -1
  83. package/dist/config/modelDiscovery.d.ts +36 -0
  84. package/dist/config/modelDiscovery.js +164 -1
  85. package/dist/config/privateStorage.js +28 -2
  86. package/dist/config/providerAuth.d.ts +14 -0
  87. package/dist/config/providerAuth.js +49 -0
  88. package/dist/config/providerPresets.d.ts +39 -7
  89. package/dist/config/providerPresets.js +371 -100
  90. package/dist/config/providers.js +2 -0
  91. package/dist/config/settings.d.ts +43 -0
  92. package/dist/config/settings.js +12 -0
  93. package/dist/config/skillSettings.js +4 -4
  94. package/dist/config/updateCheck.d.ts +0 -1
  95. package/dist/config/updateCheck.js +1 -1
  96. package/dist/core/agent/budgets.d.ts +73 -1
  97. package/dist/core/agent/budgets.js +94 -1
  98. package/dist/core/agent/compaction.d.ts +38 -0
  99. package/dist/core/agent/compaction.js +92 -17
  100. package/dist/core/agent/completionController.d.ts +224 -0
  101. package/dist/core/agent/completionController.js +296 -0
  102. package/dist/core/agent/contextBudget.d.ts +36 -2
  103. package/dist/core/agent/contextBudget.js +62 -9
  104. package/dist/core/agent/errors.d.ts +0 -1
  105. package/dist/core/agent/errors.js +1 -1
  106. package/dist/core/agent/events.d.ts +78 -0
  107. package/dist/core/agent/goalPolicy.d.ts +47 -0
  108. package/dist/core/agent/goalPolicy.js +106 -0
  109. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  110. package/dist/core/agent/reasoningPolicy.js +27 -0
  111. package/dist/core/agent/requestAssembly.d.ts +2 -2
  112. package/dist/core/agent/requestAssembly.js +16 -4
  113. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  114. package/dist/core/agent/toolCapabilities.js +58 -0
  115. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  116. package/dist/core/agent/toolOutputStore.js +11 -11
  117. package/dist/core/agent/toolResults.d.ts +12 -0
  118. package/dist/core/agent/toolResults.js +38 -0
  119. package/dist/core/agent/turnPolicy.d.ts +11 -0
  120. package/dist/core/agent/turnPolicy.js +19 -0
  121. package/dist/core/agent/workState.d.ts +81 -3
  122. package/dist/core/agent/workState.js +176 -10
  123. package/dist/core/attachments/imageAttachments.js +90 -42
  124. package/dist/core/deadline.d.ts +27 -0
  125. package/dist/core/deadline.js +74 -0
  126. package/dist/core/io/boundedRead.js +1 -1
  127. package/dist/core/limits.d.ts +51 -0
  128. package/dist/core/limits.js +51 -0
  129. package/dist/core/log/llmLog.js +8 -1
  130. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  131. package/dist/core/persistence/orderedFileWriter.js +16 -2
  132. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  133. package/dist/core/process/backgroundRegistry.js +15 -10
  134. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  135. package/dist/core/process/runBoundedProcess.js +15 -6
  136. package/dist/core/process/userShell.d.ts +16 -0
  137. package/dist/core/process/userShell.js +59 -0
  138. package/dist/core/safety/missingExecutable.d.ts +42 -0
  139. package/dist/core/safety/missingExecutable.js +77 -0
  140. package/dist/core/safety/shellClassifier.d.ts +11 -0
  141. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  142. package/dist/core/safety/urlGuard.d.ts +1 -1
  143. package/dist/core/session/sessionSlimming.d.ts +0 -3
  144. package/dist/core/session/sessionSlimming.js +2 -3
  145. package/dist/core/session/sessionStore.d.ts +38 -0
  146. package/dist/core/session/sessionStore.js +242 -59
  147. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  148. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  149. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  150. package/dist/core/shellOutput/registry.d.ts +2 -0
  151. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  152. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  153. package/dist/core/subagent/contracts.d.ts +6 -14
  154. package/dist/core/subagent/contracts.js +4 -3
  155. package/dist/core/subagent/executionProfiles.js +2 -2
  156. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  157. package/dist/core/subagent/subagentCoordinator.js +32 -2
  158. package/dist/core/subagent/subagentRunner.js +19 -40
  159. package/dist/core/toolOutput/reduction.d.ts +0 -12
  160. package/dist/core/toolOutput/reduction.js +1 -1
  161. package/dist/core/validation/outputParser.d.ts +2 -2
  162. package/dist/llm/client.d.ts +17 -1
  163. package/dist/llm/client.js +86 -14
  164. package/dist/llm/hazeTools.d.ts +693 -204
  165. package/dist/llm/hazeTools.js +110 -28
  166. package/dist/llm/initPrompt.js +1 -1
  167. package/dist/llm/lsp/client.d.ts +45 -0
  168. package/dist/llm/lsp/client.js +195 -0
  169. package/dist/llm/lsp/pool.d.ts +23 -0
  170. package/dist/llm/lsp/pool.js +86 -0
  171. package/dist/llm/lsp/protocol.d.ts +64 -0
  172. package/dist/llm/lsp/protocol.js +128 -0
  173. package/dist/llm/lsp/requests.d.ts +94 -0
  174. package/dist/llm/lsp/requests.js +119 -0
  175. package/dist/llm/lspTools.d.ts +5653 -33
  176. package/dist/llm/lspTools.js +152 -80
  177. package/dist/llm/openaiCodex.d.ts +1 -0
  178. package/dist/llm/openaiCodex.js +43 -0
  179. package/dist/llm/openaiCodexOAuth.d.ts +51 -0
  180. package/dist/llm/openaiCodexOAuth.js +217 -0
  181. package/dist/llm/requestContext.d.ts +7 -0
  182. package/dist/llm/requestContext.js +30 -4
  183. package/dist/llm/systemPrompt.d.ts +12 -0
  184. package/dist/llm/systemPrompt.js +24 -11
  185. package/dist/llm/toolResultTypes.d.ts +7 -14
  186. package/dist/llm/toolResultTypes.js +1 -4
  187. package/dist/llm/tools/editMatch.d.ts +14 -9
  188. package/dist/llm/tools/editMatch.js +73 -1
  189. package/dist/llm/tools/failures.d.ts +2 -0
  190. package/dist/llm/tools/failures.js +1 -0
  191. package/dist/llm/tools/fetchTool.d.ts +16 -0
  192. package/dist/llm/tools/fetchTool.js +1 -1
  193. package/dist/llm/tools/fileToolShared.d.ts +8 -5
  194. package/dist/llm/tools/fileToolShared.js +22 -23
  195. package/dist/llm/tools/gitIgnore.d.ts +42 -0
  196. package/dist/llm/tools/gitIgnore.js +247 -0
  197. package/dist/llm/tools/grepParse.d.ts +2 -1
  198. package/dist/llm/tools/grepRunner.d.ts +1 -1
  199. package/dist/llm/tools/grepRunner.js +2 -2
  200. package/dist/llm/tools/outputCap.d.ts +2 -7
  201. package/dist/llm/tools/outputCap.js +3 -3
  202. package/dist/llm/tools/processTool.d.ts +16 -16
  203. package/dist/llm/tools/processTool.js +1 -1
  204. package/dist/llm/tools/readRecovery.d.ts +8 -0
  205. package/dist/llm/tools/readRecovery.js +135 -0
  206. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
  207. package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
  208. package/dist/llm/tools/toolContext.d.ts +1 -1
  209. package/dist/llm/tools/toolContext.js +66 -37
  210. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  211. package/dist/llm/tools/workspaceFile.js +1 -6
  212. package/dist/llm/webFetch.d.ts +18 -1
  213. package/dist/llm/webFetch.js +64 -97
  214. package/dist/skills/SkillLoader.d.ts +1 -11
  215. package/dist/skills/SkillLoader.js +1 -2
  216. package/dist/skills/types.d.ts +2 -1
  217. package/dist/ui/codeHighlight.d.ts +4 -0
  218. package/dist/ui/codeHighlight.js +31 -0
  219. package/dist/ui/components/Header.d.ts +1 -1
  220. package/dist/ui/components/MarkdownText.d.ts +16 -2
  221. package/dist/ui/components/MarkdownText.js +244 -34
  222. package/dist/ui/components/TextInput.d.ts +8 -1
  223. package/dist/ui/components/TextInput.js +6 -2
  224. package/dist/ui/theme.d.ts +4 -3
  225. package/dist/ui/theme.js +5 -4
  226. package/dist/utils/buildInfo.d.ts +97 -0
  227. package/dist/utils/buildInfo.js +244 -0
  228. package/dist/utils/fs.d.ts +11 -0
  229. package/dist/utils/fs.js +91 -26
  230. package/dist/utils/openPath.d.ts +2 -2
  231. package/dist/utils/openPath.js +19 -6
  232. package/dist/utils/path.d.ts +2 -1
  233. package/dist/utils/path.js +6 -2
  234. package/dist/utils/utf8.d.ts +22 -0
  235. package/dist/utils/utf8.js +54 -0
  236. package/dist/utils/version.d.ts +9 -3
  237. package/dist/utils/version.js +28 -2
  238. package/package.json +28 -21
  239. package/dist/cli/commands/lspWizard.d.ts +0 -14
  240. package/dist/cli/commands/lspWizard.js +0 -44
  241. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  242. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  243. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  244. package/dist/cli/commands/skillCreation.d.ts +0 -12
  245. package/dist/cli/commands/skillCreation.js +0 -14
  246. package/dist/cli/commands/skillWizard.d.ts +0 -17
  247. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  248. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  249. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -10
  250. package/dist/cli/commands/streaming/turnOutcome.js +0 -13
  251. package/dist/cli/commands/wizardActions.d.ts +0 -46
  252. package/dist/cli/commands/wizardActions.js +0 -46
  253. package/dist/cli/commands/wizardInput.d.ts +0 -4
  254. package/dist/cli/commands/wizardInput.js +0 -19
  255. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  256. package/dist/cli/commands/wizardPrompts.js +0 -52
  257. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  258. package/dist/cli/commands/wizardSuggestions.js +0 -188
  259. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  260. package/dist/cli/commands/wizardTransition.js +0 -43
  261. package/dist/core/bashOutput/ansi.d.ts +0 -1
  262. package/dist/core/bashOutput/ansi.js +0 -7
  263. package/dist/core/bashOutput/registry.d.ts +0 -4
  264. package/dist/core/goal/completionPolicy.d.ts +0 -2
  265. package/dist/core/goal/completionPolicy.js +0 -7
  266. package/dist/core/goal/requestClassifier.d.ts +0 -3
  267. package/dist/core/goal/requestClassifier.js +0 -18
  268. package/dist/core/goal/sessionGoal.d.ts +0 -8
  269. package/dist/core/goal/sessionGoal.js +0 -30
  270. package/dist/core/limits/byteBudgets.d.ts +0 -18
  271. package/dist/core/limits/byteBudgets.js +0 -18
  272. package/dist/core/limits/textBudgets.d.ts +0 -23
  273. package/dist/core/limits/textBudgets.js +0 -23
  274. package/dist/core/safety/bashClassifier.d.ts +0 -10
  275. package/dist/llm/lsp.d.ts +0 -129
  276. package/dist/llm/lsp.js +0 -307
  277. package/dist/ui/components/ErrorView.d.ts +0 -4
  278. package/dist/ui/components/ErrorView.js +0 -7
  279. package/dist/utils/yaml.d.ts +0 -2
  280. package/dist/utils/yaml.js +0 -8
  281. package/examples/skills/files/SKILL.md +0 -16
  282. package/examples/skills/files/examples/file-editing.md +0 -3
  283. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  284. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  285. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  286. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  287. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  288. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  289. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  290. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  291. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  292. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  293. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  294. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -4,7 +4,7 @@ function has(command, pattern) {
4
4
  function uniq(values) {
5
5
  return [...new Set(values)];
6
6
  }
7
- export function classifyBashCommand(command) {
7
+ export function classifyShellCommand(command) {
8
8
  const trimmed = command.trim();
9
9
  const traits = [];
10
10
  const lower = trimmed.toLowerCase();
@@ -63,11 +63,13 @@ export function classifyBashCommand(command) {
63
63
  traits.push('reads_files');
64
64
  return { riskLevel: 'unknown', traits: uniq(traits), confidence: 'low', reason: 'find -exec / xargs runs an embedded command' };
65
65
  }
66
- if (has(lower, /(^|[;&|]\s*)(npm\s+test|npm\s+run\s+(test|typecheck|lint|build)|pnpm\s+(test|run\s+(test|typecheck|lint|build))|yarn\s+(test|run\s+(test|typecheck|lint|build))|vitest\b|jest\b|tsc\b|eslint\b)/)) {
67
- if (has(lower, /test|vitest|jest/))
66
+ if (has(lower, /(^|[;&|]\s*)(npm\s+test|npm\s+run\s+(test|typecheck|lint|build)|pnpm\s+(test|run\s+(test|typecheck|lint|build))|yarn\s+(test|run\s+(test|typecheck|lint|build))|vitest\b|jest\b|tsc\b|eslint\b|pytest\b|(?:uv|poetry)\s+run\s+pytest\b|python3?\s+-m\s+(pytest|unittest|nose2?)\b|go\s+test\b|cargo\s+(test|nextest)\b|make\s+(test|check)\b|(?:mvn|\.\/mvnw)\s+(test|verify)\b|(?:gradle|gradlew|\.\/gradlew)\s+test\b|rspec\b|bundle\s+exec\s+rspec\b|dotnet\s+test\b|deno\s+(test|lint)\b|bun\s+(test|lint)\b|node\s+--test\b|phpunit\b|composer\s+test\b|mix\s+test\b|swift\s+test\b|ctest\b|xcodebuild\b[^;&|]*\btest\b)/)) {
67
+ if (has(lower, /test|vitest|jest|rspec|make\s+check|mvn\s+verify/))
68
68
  traits.push('runs_tests');
69
69
  if (has(lower, /build|tsc|typecheck|lint|eslint/))
70
70
  traits.push('runs_build');
71
+ if (traits.length === 0)
72
+ traits.push('runs_tests');
71
73
  return { riskLevel: 'read_only', traits: uniq(traits), confidence: complex ? 'medium' : 'high', reason: 'validation command' };
72
74
  }
73
75
  if (has(lower, /(^|[;&|]\s*)(git\s+(status|diff|log|show|branch)\b|rg\b|grep\b|find\b|ls\b|pwd\b|cat\b|head\b|tail\b|node\s+--version|npm\s+--version|which\b)/)) {
@@ -6,7 +6,7 @@
6
6
  * blocking + DNS-resolution check (defeats DNS rebinding to internal IPs).
7
7
  *
8
8
  * This module is pure safety logic under `core/safety/`, parallel to
9
- * `bashClassifier.ts`. It must not import anything from `ai`, `hazeTools`, or
9
+ * `shellClassifier.ts`. It must not import anything from `ai`, `hazeTools`, or
10
10
  * the UI — keep it auditable in one place.
11
11
  */
12
12
  export type UrlValidation = {
@@ -1,5 +1,2 @@
1
- import type { ModelMessage } from 'ai';
2
1
  import type { SessionEntry } from './sessionStore.js';
3
- export declare function slimConversationSnapshot(messages: ModelMessage[]): ModelMessage[];
4
2
  export declare function prepareSessionEntryForWrite(entry: SessionEntry): SessionEntry | undefined;
5
- export declare const SESSION_INLINE_VALUE_BYTES: number;
@@ -1,4 +1,4 @@
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';
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.js';
2
2
  import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
3
3
  import { formatBytes } from '../../utils/format.js';
4
4
  function jsonByteLength(value) {
@@ -65,7 +65,7 @@ function slimUnknown(value, seen = new WeakSet()) {
65
65
  next[key] = slimUnknown(child, seen);
66
66
  return next;
67
67
  }
68
- export function slimConversationSnapshot(messages) {
68
+ function slimConversationSnapshot(messages) {
69
69
  return slimUnknown(messages);
70
70
  }
71
71
  function slimToolStartInput(input) {
@@ -118,4 +118,3 @@ export function prepareSessionEntryForWrite(entry) {
118
118
  }
119
119
  return entry;
120
120
  }
121
- export const SESSION_INLINE_VALUE_BYTES = INLINE_VALUE_BYTES;
@@ -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,47 @@ 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
+ sessionsDir: string;
45
+ /** New sessions stay memory-only until they contain a resumable message. */
46
+ deferredWrite?: DeferredSessionWrite;
33
47
  }
34
48
  export declare function createSession(options?: {
35
49
  cwd?: string;
36
50
  hazeVersion?: string;
37
51
  sessionsDir?: string;
38
52
  forkedFrom?: string;
53
+ build?: {
54
+ commit?: string;
55
+ builtAt?: string;
56
+ };
39
57
  }): Promise<HazeSession>;
40
58
  export declare function findSession(id: string, cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
41
59
  export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
42
60
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
61
+ /**
62
+ * Session files rewrite their full conversation history per turn, so a long
63
+ * session grows quadratically: N tokens of final history cost O(turns ×
64
+ * history) bytes on disk (F-03). Once superseded snapshots dominate the file,
65
+ * rewrite it keeping only the newest conversation/work-state snapshot plus
66
+ * every non-snapshot entry (restore reads only the newest snapshot of each
67
+ * type, so dropping superseded ones is lossless for restore; summaries keep
68
+ * their ui_message/event history). Atomic replace, never partial.
69
+ */
70
+ export declare const SESSION_VACUUM_THRESHOLD_BYTES: number;
71
+ /** Test-only override for the vacuum trigger; tests restore the original. */
72
+ export declare function setSessionVacuumThresholdForTests(bytes: number): void;
73
+ export declare function vacuumSessionFileIfLarge(session: HazeSession, thresholdBytes?: number): Promise<boolean>;
43
74
  export interface ReadSessionEntriesResult {
44
75
  entries: SessionEntry[];
45
76
  /** Per-line parse failures, e.g. `Line 3: Unexpected token...`. Empty when every line parsed. */
@@ -86,6 +117,8 @@ export interface SessionSummary {
86
117
  lastStatus?: string;
87
118
  parseErrors: string[];
88
119
  }
120
+ /** Test-only reset for the process-scoped session-summary cache. */
121
+ export declare function clearSessionSummaryCacheForTests(): void;
89
122
  /** List this workspace's sessions newest-first while retaining only summary state per file. */
90
123
  export declare function listSessions(cwd?: string, sessionsDir?: string): Promise<SessionSummary[]>;
91
124
  export interface ForkSessionResult {
@@ -96,5 +129,10 @@ export interface ForkSessionResult {
96
129
  export declare function forkSession(source: HazeSession, options?: {
97
130
  hazeVersion?: string;
98
131
  sessionsDir?: string;
132
+ build?: {
133
+ commit?: string;
134
+ builtAt?: string;
135
+ };
99
136
  }): Promise<ForkSessionResult>;
100
137
  export declare function formatSession(session: HazeSession): string;
138
+ export {};
@@ -3,8 +3,8 @@ 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';
6
+ import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
7
+ import { JSONL_LINE_BYTES } from '../limits.js';
8
8
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
9
9
  const DEFAULT_SESSIONS_DIR = path.join(HAZE_DIR, 'sessions');
10
10
  function cwdHash(cwd = process.cwd()) {
@@ -16,6 +16,20 @@ function sessionDir(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
16
16
  function sessionFile(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
17
17
  return path.join(sessionDir(cwd, sessionsDir), `${id}.jsonl`);
18
18
  }
19
+ function validatedSessionFile(session) {
20
+ const id = session.id.trim();
21
+ if (!id || id !== session.id || id === '.' || id === '..' || id.includes('/') || id.includes('\\') || path.isAbsolute(id)) {
22
+ throw new Error(`Invalid session id: ${session.id}`);
23
+ }
24
+ const sessionsDir = path.resolve(session.sessionsDir);
25
+ const expected = path.resolve(sessionFile(id, session.cwd, sessionsDir));
26
+ const resolved = path.resolve(session.file);
27
+ const relative = path.relative(sessionsDir, resolved);
28
+ if (relative.startsWith('..') || path.isAbsolute(relative) || resolved !== expected) {
29
+ throw new Error(`Session file is outside its configured session directory: ${session.file}`);
30
+ }
31
+ return expected;
32
+ }
19
33
  function newSessionId(now = new Date()) {
20
34
  // Timestamp prefix keeps latestSession() lexicographic ordering; the random
21
35
  // suffix prevents same-millisecond collisions (CR-025).
@@ -24,41 +38,169 @@ function newSessionId(now = new Date()) {
24
38
  export async function createSession(options = {}) {
25
39
  const cwd = path.resolve(options.cwd ?? process.cwd());
26
40
  const id = newSessionId();
27
- const file = sessionFile(id, cwd, options.sessionsDir);
41
+ const sessionsDir = path.resolve(options.sessionsDir ?? DEFAULT_SESSIONS_DIR);
42
+ const file = sessionFile(id, cwd, sessionsDir);
28
43
  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 });
30
- return { id, file, cwd };
44
+ return {
45
+ id,
46
+ file,
47
+ cwd,
48
+ sessionsDir,
49
+ deferredWrite: {
50
+ header: { type: 'header', id, cwd, createdAt: new Date().toISOString(), hazeVersion: options.hazeVersion, forkedFrom: options.forkedFrom, ...(options.build ? { build: options.build } : {}) },
51
+ entries: [],
52
+ },
53
+ };
31
54
  }
32
55
  export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
33
56
  const normalizedId = id.trim();
34
- if (!normalizedId || path.basename(normalizedId) !== normalizedId || normalizedId.endsWith('.jsonl'))
57
+ // Reject both platform-native and foreign separators so session IDs remain
58
+ // single filenames if a session is moved between operating systems.
59
+ if (!normalizedId || normalizedId !== id || normalizedId === '.' || normalizedId === '..' || normalizedId.includes('/') || normalizedId.includes('\\') || path.isAbsolute(normalizedId))
35
60
  return undefined;
36
61
  const file = sessionFile(normalizedId, cwd, sessionsDir);
37
62
  if (!await fs.pathExists(file))
38
63
  return undefined;
39
- return { id: normalizedId, file, cwd: path.resolve(cwd) };
64
+ return { id: normalizedId, file, cwd: path.resolve(cwd), sessionsDir: path.resolve(sessionsDir) };
40
65
  }
41
66
  export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
42
- const dir = sessionDir(cwd, sessionsDir);
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);
67
+ const latest = (await listSessions(cwd, sessionsDir))[0];
48
68
  if (!latest)
49
69
  return undefined;
50
- const id = path.basename(latest, '.jsonl');
51
- return { id, file: path.join(dir, latest), cwd: path.resolve(cwd) };
70
+ return { id: latest.id, file: sessionFile(latest.id, cwd, sessionsDir), cwd: path.resolve(cwd), sessionsDir: path.resolve(sessionsDir) };
71
+ }
72
+ function entryMakesSessionResumable(entry) {
73
+ if (entry.type === 'ui_message')
74
+ return entry.text.trim().length > 0;
75
+ return entry.type === 'conversation_snapshot' && entry.messages.length > 0;
52
76
  }
53
77
  export async function appendSessionEntry(session, entry) {
78
+ const file = validatedSessionFile(session);
54
79
  const prepared = prepareSessionEntryForWrite(entry);
55
80
  if (!prepared)
56
81
  return;
57
- await appendPrivateFile(session.file, `${JSON.stringify(prepared)}\n`);
82
+ const deferred = session.deferredWrite;
83
+ if (deferred) {
84
+ if (!entryMakesSessionResumable(prepared)) {
85
+ deferred.entries.push(prepared);
86
+ return;
87
+ }
88
+ const entries = [deferred.header, ...deferred.entries, prepared];
89
+ await appendPrivateFile(file, entries.map(item => JSON.stringify(item)).join('\n') + '\n');
90
+ session.deferredWrite = undefined;
91
+ return;
92
+ }
93
+ await appendPrivateFile(file, `${JSON.stringify(prepared)}\n`);
94
+ // Snapshot deduplication runs inside the same serialized writer as the
95
+ // append, so ordering with subsequent entries is preserved (F-03).
96
+ await vacuumSessionFileIfLarge(session).catch(() => undefined);
97
+ }
98
+ /**
99
+ * Session files rewrite their full conversation history per turn, so a long
100
+ * session grows quadratically: N tokens of final history cost O(turns ×
101
+ * history) bytes on disk (F-03). Once superseded snapshots dominate the file,
102
+ * rewrite it keeping only the newest conversation/work-state snapshot plus
103
+ * every non-snapshot entry (restore reads only the newest snapshot of each
104
+ * type, so dropping superseded ones is lossless for restore; summaries keep
105
+ * their ui_message/event history). Atomic replace, never partial.
106
+ */
107
+ export const SESSION_VACUUM_THRESHOLD_BYTES = 16 * 1024 * 1024;
108
+ let effectiveVacuumThresholdBytes = SESSION_VACUUM_THRESHOLD_BYTES;
109
+ /** Test-only override for the vacuum trigger; tests restore the original. */
110
+ export function setSessionVacuumThresholdForTests(bytes) {
111
+ effectiveVacuumThresholdBytes = bytes;
112
+ }
113
+ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effectiveVacuumThresholdBytes) {
114
+ const file = validatedSessionFile(session);
115
+ if (session.deferredWrite)
116
+ return false;
117
+ const stat = await fs.stat(file).catch(() => undefined);
118
+ if (!stat || stat.size < thresholdBytes)
119
+ return false;
120
+ const { entries } = await readSessionEntries(session);
121
+ let lastConversation = -1;
122
+ let lastWorkState = -1;
123
+ entries.forEach((entry, index) => {
124
+ if (entry.type === 'conversation_snapshot')
125
+ lastConversation = index;
126
+ if (entry.type === 'work_state_snapshot')
127
+ lastWorkState = index;
128
+ });
129
+ // Malformed lines are dropped by the rewrite: they were already unusable
130
+ // (and reported as parse errors on read) and keeping them would defeat the
131
+ // size bound the vacuum exists to enforce.
132
+ const kept = entries.filter((entry, index) => (entry.type !== 'conversation_snapshot' && entry.type !== 'work_state_snapshot')
133
+ || index === lastConversation
134
+ || index === lastWorkState);
135
+ const serialized = kept.map(entry => JSON.stringify(entry)).join('\n') + '\n';
136
+ // Only rewrite when it meaningfully shrinks the file; otherwise a single
137
+ // dominant snapshot would trigger a full rewrite on every append.
138
+ if (serialized.length > stat.size / 2)
139
+ return false;
140
+ await writePrivateFileAtomic(file, serialized);
141
+ return true;
58
142
  }
59
143
  const MAX_PARSE_ERRORS = 100;
144
+ const MODEL_MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool']);
145
+ function isRecord(value) {
146
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
147
+ }
148
+ function optionalString(value) {
149
+ return value === undefined || typeof value === 'string';
150
+ }
151
+ function optionalBuildProvenance(value) {
152
+ if (value === undefined)
153
+ return true;
154
+ if (!isRecord(value))
155
+ return false;
156
+ return optionalString(value.commit) && optionalString(value.builtAt);
157
+ }
158
+ function parseSessionEntry(value) {
159
+ const invalid = (detail) => {
160
+ throw new Error(`unexpected entry shape: ${detail}`);
161
+ };
162
+ if (!isRecord(value))
163
+ return invalid('expected an object with a string type');
164
+ const type = value.type;
165
+ if (typeof type !== 'string')
166
+ return invalid('expected an object with a string type');
167
+ switch (type) {
168
+ case 'header':
169
+ if (typeof value.id !== 'string' || typeof value.cwd !== 'string' || typeof value.createdAt !== 'string'
170
+ || !optionalString(value.hazeVersion) || !optionalString(value.forkedFrom)
171
+ || !optionalBuildProvenance(value.build))
172
+ return invalid('invalid header');
173
+ return value;
174
+ case 'ui_message':
175
+ if (typeof value.at !== 'string' || typeof value.text !== 'string'
176
+ || !MODEL_MESSAGE_ROLES.has(typeof value.role === 'string' ? value.role : ''))
177
+ return invalid('invalid ui_message');
178
+ return value;
179
+ case 'conversation_snapshot':
180
+ if (typeof value.at !== 'string' || !Array.isArray(value.messages))
181
+ return invalid('conversation_snapshot messages must be an array');
182
+ if (!value.messages.every((message) => isRecord(message)
183
+ && typeof message.role === 'string'
184
+ && MODEL_MESSAGE_ROLES.has(message.role)))
185
+ return invalid('conversation_snapshot contains an invalid message role');
186
+ return value;
187
+ case 'work_state_snapshot':
188
+ if (typeof value.at !== 'string' || !isRecord(value.state))
189
+ return invalid('work_state_snapshot state must be an object');
190
+ return value;
191
+ case 'event':
192
+ if (typeof value.at !== 'string' || typeof value.name !== 'string' || !optionalString(value.text))
193
+ return invalid('invalid event');
194
+ return value;
195
+ default:
196
+ return invalid(`unknown entry type '${type}'`);
197
+ }
198
+ }
60
199
  async function scanSessionEntries(session, onEntry) {
61
- await tightenPrivateFile(session.file);
200
+ const file = validatedSessionFile(session);
201
+ if (session.deferredWrite && !await fs.pathExists(file))
202
+ return [];
203
+ await tightenPrivateFile(file);
62
204
  const parseErrors = [];
63
205
  let omittedErrors = 0;
64
206
  const report = (message) => {
@@ -67,7 +209,7 @@ async function scanSessionEntries(session, onEntry) {
67
209
  else
68
210
  omittedErrors++;
69
211
  };
70
- for await (const { line, lineNumber, oversized } of iterateBoundedUtf8Lines(session.file, JSONL_LINE_BYTES)) {
212
+ for await (const { line, lineNumber, oversized } of iterateBoundedUtf8Lines(file, JSONL_LINE_BYTES)) {
71
213
  if (!line && !oversized)
72
214
  continue;
73
215
  if (oversized) {
@@ -75,7 +217,7 @@ async function scanSessionEntries(session, onEntry) {
75
217
  continue;
76
218
  }
77
219
  try {
78
- onEntry(JSON.parse(line));
220
+ onEntry(parseSessionEntry(JSON.parse(line)));
79
221
  }
80
222
  catch (error) {
81
223
  report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
@@ -124,64 +266,105 @@ export async function restoreWorkState(session) {
124
266
  const SESSION_PREVIEW_CHARS = 120;
125
267
  /** Acceptance budget for listing 50 ordinary workspace sessions. */
126
268
  export const SESSION_LIST_LATENCY_BUDGET_MS = 2_000;
269
+ const SESSION_SUMMARY_CACHE_MAX = 500;
270
+ const sessionSummaryCache = new Map();
271
+ function cachedSessionSummary(file, stat) {
272
+ const cached = sessionSummaryCache.get(file);
273
+ if (!cached || cached.mtimeMs !== stat.mtimeMs || cached.size !== stat.size)
274
+ return undefined;
275
+ sessionSummaryCache.delete(file);
276
+ sessionSummaryCache.set(file, cached);
277
+ return cached.summary;
278
+ }
279
+ function cacheSessionSummary(file, stat, summary) {
280
+ sessionSummaryCache.delete(file);
281
+ sessionSummaryCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, summary });
282
+ while (sessionSummaryCache.size > SESSION_SUMMARY_CACHE_MAX) {
283
+ const oldest = sessionSummaryCache.keys().next().value;
284
+ if (oldest === undefined)
285
+ break;
286
+ sessionSummaryCache.delete(oldest);
287
+ }
288
+ }
289
+ /** Test-only reset for the process-scoped session-summary cache. */
290
+ export function clearSessionSummaryCacheForTests() {
291
+ sessionSummaryCache.clear();
292
+ }
127
293
  function previewText(text) {
128
294
  const compact = text.replace(/\s+/g, ' ').trim();
129
295
  return compact.length > SESSION_PREVIEW_CHARS ? `${compact.slice(0, SESSION_PREVIEW_CHARS - 1)}…` : compact;
130
296
  }
297
+ async function summarizeSession(session, stat) {
298
+ let createdAt = stat.birthtime.toISOString();
299
+ let lastActivityAt = stat.mtime.toISOString();
300
+ let messageCount = 0;
301
+ let firstUserPreview = '';
302
+ let lastStatus;
303
+ const parseErrors = await scanSessionEntries(session, entry => {
304
+ if (entry.type === 'header')
305
+ createdAt = entry.createdAt || createdAt;
306
+ if ('at' in entry && entry.at)
307
+ lastActivityAt = entry.at;
308
+ if (entry.type === 'ui_message' && entry.text.trim().length > 0) {
309
+ messageCount++;
310
+ if (!firstUserPreview && entry.role === 'user')
311
+ firstUserPreview = previewText(entry.text);
312
+ }
313
+ if (entry.type === 'conversation_snapshot') {
314
+ if (messageCount === 0)
315
+ messageCount = entry.messages.length;
316
+ if (!firstUserPreview) {
317
+ const firstUser = entry.messages.find(message => message.role === 'user');
318
+ if (firstUser)
319
+ firstUserPreview = previewText(typeof firstUser.content === 'string' ? firstUser.content : JSON.stringify(firstUser.content));
320
+ }
321
+ }
322
+ if (entry.type === 'event' && entry.name === 'turn_end' && entry.text) {
323
+ try {
324
+ const event = JSON.parse(entry.text);
325
+ if (typeof event.status === 'string')
326
+ lastStatus = event.status;
327
+ }
328
+ catch {
329
+ // The outer entry remains valid; malformed optional event metadata is ignored.
330
+ }
331
+ }
332
+ });
333
+ return { id: session.id, createdAt, lastActivityAt, messageCount, firstUserPreview, sizeBytes: stat.size, lastStatus, parseErrors };
334
+ }
131
335
  /** List this workspace's sessions newest-first while retaining only summary state per file. */
132
336
  export async function listSessions(cwd = process.cwd(), sessionsDir = DEFAULT_SESSIONS_DIR) {
133
337
  const dir = sessionDir(cwd, sessionsDir);
134
338
  await ensurePrivateDir(dir);
135
339
  const files = (await fs.readdir(dir).catch(() => [])).filter(file => file.endsWith('.jsonl'));
340
+ const present = new Set(files.map(file => path.join(dir, file)));
341
+ for (const cachedFile of sessionSummaryCache.keys()) {
342
+ if (path.dirname(cachedFile) === dir && !present.has(cachedFile))
343
+ sessionSummaryCache.delete(cachedFile);
344
+ }
136
345
  const summaries = await Promise.all(files.map(async (fileName) => {
137
346
  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 };
347
+ const session = { id, file: path.join(dir, fileName), cwd: path.resolve(cwd), sessionsDir: path.resolve(sessionsDir) };
348
+ const file = validatedSessionFile(session);
349
+ await tightenPrivateFile(file);
350
+ const stat = await fs.stat(file);
351
+ const cached = cachedSessionSummary(file, stat);
352
+ if (cached)
353
+ return cached;
354
+ const summary = await summarizeSession(session, stat);
355
+ cacheSessionSummary(file, stat, summary);
356
+ return summary;
176
357
  }));
177
- return summaries.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
358
+ return summaries
359
+ .filter(summary => summary.messageCount > 0)
360
+ .sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || b.id.localeCompare(a.id));
178
361
  }
179
362
  /** Create a new session from the source's latest durable snapshots without mutating it. */
180
363
  export async function forkSession(source, options = {}) {
181
364
  const restored = await restoreSessionState(source);
182
365
  if (restored.messages.length === 0)
183
366
  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 });
367
+ const session = await createSession({ cwd: source.cwd, sessionsDir: options.sessionsDir, hazeVersion: options.hazeVersion, forkedFrom: source.id, ...(options.build ? { build: options.build } : {}) });
185
368
  const at = new Date().toISOString();
186
369
  await appendSessionEntry(session, { type: 'conversation_snapshot', at, messages: restored.messages });
187
370
  if (restored.workState)
@@ -1,5 +1,11 @@
1
- import { stripAnsi as stripAnsiCodes } from './ansi.js';
2
1
  import { commandMatches } from './command.js';
2
+ /* eslint-disable no-control-regex */
3
+ /** Strip common CSI/OSC escape sequences emitted by CLIs (central ANSI handling for reducers/filters). */
4
+ function stripAnsi(text) {
5
+ return text
6
+ .replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g, '')
7
+ .replace(/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g, '');
8
+ }
3
9
  function matchesCommand(definition, command) {
4
10
  return commandMatches(command, definition.matchCommand);
5
11
  }
@@ -26,7 +32,7 @@ export function applyLineFilter(definition, command, text) {
26
32
  try {
27
33
  let next = text;
28
34
  if (definition.stripAnsi)
29
- next = stripAnsiCodes(next);
35
+ next = stripAnsi(next);
30
36
  for (const replacement of definition.replace ?? [])
31
37
  next = next.replace(replacement.pattern, replacement.replacement);
32
38
  const matched = definition.matchOutput?.test(next) ?? false;
@@ -3,5 +3,4 @@ export interface SearchReductionOptions {
3
3
  maxMatchesPerFile?: number;
4
4
  maxTotalMatches?: number;
5
5
  }
6
- export declare function isSearchCommand(command: string): boolean;
7
6
  export declare function reduceSearchOutput(command: string, stdout: string, stderr: string, options?: SearchReductionOptions): string | undefined;
@@ -3,7 +3,7 @@ const DEFAULT_OPTIONS = { maxFiles: 15, maxMatchesPerFile: 5, maxTotalMatches: 3
3
3
  const SEARCH_COMMAND = /^(?:rg|grep|git\s+grep|ag|ack)(?:\s|$)/;
4
4
  const SIGNAL_LINE = /\b(error|fail(?:ed|ure)?|warn(?:ing)?|exception|panic|fatal|todo|fixme)\b/i;
5
5
  const MATCH_LINE = /^(.+?)([:-])(\d+)\2(.*)$/;
6
- export function isSearchCommand(command) {
6
+ function isSearchCommand(command) {
7
7
  return commandMatches(command, SEARCH_COMMAND);
8
8
  }
9
9
  function parseSearchLine(line, index) {
@@ -0,0 +1,2 @@
1
+ import type { ShellOutputFilterInput, ShellOutputFilterResult } from './types.js';
2
+ export declare function filterShellOutput(input: ShellOutputFilterInput): ShellOutputFilterResult;
@@ -5,7 +5,7 @@ import { reduceGhOutput } from './reducers/gh.js';
5
5
  import { reduceSearchOutput } from './reducers/search.js';
6
6
  import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
7
7
  import { capOutputForProcessing, isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
8
- export const builtInLineFilters = [
8
+ const builtInLineFilters = [
9
9
  { name: 'markdownlint', matchCommand: /(^|[;&|]\s*)markdownlint\b/, stripAnsi: true, truncateLinesAt: 200, maxLines: 80, onEmpty: 'markdownlint: ok' },
10
10
  { name: 'shellcheck', matchCommand: /(^|[;&|]\s*)shellcheck\b/, stripAnsi: true, stripLinesMatching: [/^In .* line \d+:/], truncateLinesAt: 200, maxLines: 100, onEmpty: 'shellcheck: ok' },
11
11
  { name: 'docker-list', matchCommand: /(^|[;&|]\s*)docker\s+(?:ps|images)\b/, stripAnsi: true, truncateLinesAt: 180, maxLines: 40, onEmpty: 'docker: no rows' },
@@ -61,7 +61,7 @@ function passthroughReduction(raw, input) {
61
61
  ...reductionMetrics(raw, compacted.text),
62
62
  };
63
63
  }
64
- export function filterBashOutput(input) {
64
+ export function filterShellOutput(input) {
65
65
  try {
66
66
  let stdout;
67
67
  let stderr;
@@ -129,7 +129,7 @@ export function filterBashOutput(input) {
129
129
  const warning = error instanceof Error ? error.message : String(error);
130
130
  const stdout = passthroughReduction(input.stdout, input);
131
131
  const stderr = passthroughReduction(input.stderr, input);
132
- stdout.warning = `bash output filter failed: ${warning}`;
132
+ stdout.warning = `shell output filter failed: ${warning}`;
133
133
  stdout.parseTier = 'degraded';
134
134
  return { stdout, stderr, summary: input.validationSummary };
135
135
  }
@@ -1,14 +1,14 @@
1
- import type { BashClassification } from '../safety/bashClassifier.js';
1
+ import type { ShellClassification } from '../safety/shellClassifier.js';
2
2
  import type { ValidationSummary } from '../../llm/toolResultTypes.js';
3
3
  import type { ReductionContentKind, ReductionParseTier } from '../toolOutput/reduction.js';
4
- export type ParseTier = ReductionParseTier;
5
- export interface BashOutputFilterInput {
4
+ type ParseTier = ReductionParseTier;
5
+ export interface ShellOutputFilterInput {
6
6
  command: string;
7
7
  code: number | null;
8
8
  stdout: string;
9
9
  stderr: string;
10
10
  timedOut: boolean;
11
- classification?: BashClassification;
11
+ classification?: ShellClassification;
12
12
  validationSummary?: ValidationSummary;
13
13
  storeRawOutput?: (content: string) => string;
14
14
  fallbackCompact: (text: string, maxChars?: number) => {
@@ -39,8 +39,9 @@ export interface StreamReduction {
39
39
  estimatedSavedTokens?: number;
40
40
  savingsPct?: number;
41
41
  }
42
- export interface BashOutputFilterResult {
42
+ export interface ShellOutputFilterResult {
43
43
  stdout: StreamReduction;
44
44
  stderr: StreamReduction;
45
45
  summary?: ValidationSummary;
46
46
  }
47
+ export {};