@denizokcu/haze 1.7.10 → 1.7.12

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 (142) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +125 -99
  3. package/assets/graph-grammars/NOTICE.md +21 -0
  4. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  5. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  7. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  9. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  10. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  11. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  13. package/dist/buildInfo.json +3 -3
  14. package/dist/cli/chat/BusyBar.d.ts +2 -1
  15. package/dist/cli/chat/BusyBar.js +2 -2
  16. package/dist/cli/chat/chatMetrics.d.ts +25 -0
  17. package/dist/cli/chat/chatMetrics.js +36 -0
  18. package/dist/cli/chat/inputSuggestions.js +1 -0
  19. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  20. package/dist/cli/chat/sessionLifecycle.js +29 -19
  21. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  22. package/dist/cli/chat/sessionRecorder.js +29 -9
  23. package/dist/cli/chat/startupSequence.d.ts +2 -0
  24. package/dist/cli/chat/startupSequence.js +6 -0
  25. package/dist/cli/chat/transcriptPartition.js +10 -4
  26. package/dist/cli/chat/wizard/providerHandlers.js +57 -9
  27. package/dist/cli/chat/wizard/sessionThemeHandlers.js +5 -1
  28. package/dist/cli/commands/chat.js +44 -9
  29. package/dist/cli/commands/commandHelp.js +6 -3
  30. package/dist/cli/commands/commands.js +2 -0
  31. package/dist/cli/commands/formatters.js +28 -0
  32. package/dist/cli/commands/graphCommand.d.ts +2 -0
  33. package/dist/cli/commands/graphCommand.js +60 -0
  34. package/dist/cli/commands/initCommand.js +14 -0
  35. package/dist/cli/commands/providerWizard.js +9 -17
  36. package/dist/cli/commands/reasoningCommand.d.ts +1 -0
  37. package/dist/cli/commands/reasoningCommand.js +32 -4
  38. package/dist/cli/commands/runCommand.js +7 -1
  39. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  40. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  41. package/dist/cli/commands/streaming/attemptOutcome.js +6 -2
  42. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  43. package/dist/cli/commands/streaming/attemptSetup.js +13 -6
  44. package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
  45. package/dist/cli/commands/streaming/goalSupervisor.js +22 -1
  46. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  47. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  48. package/dist/cli/commands/streaming/streamLoop.js +14 -10
  49. package/dist/cli/commands/streaming/toolPartHandlers.js +7 -1
  50. package/dist/cli/commands/streaming.d.ts +2 -0
  51. package/dist/cli/commands/streaming.js +5 -0
  52. package/dist/cli/commands/wizardFlow.d.ts +1 -0
  53. package/dist/cli/commands/wizardFlow.js +10 -4
  54. package/dist/cli/index.js +5 -3
  55. package/dist/config/hazeBuild.d.ts +2 -2
  56. package/dist/config/hazeBuild.js +2 -2
  57. package/dist/config/modelDiscovery.d.ts +1 -1
  58. package/dist/config/modelDiscovery.js +8 -8
  59. package/dist/config/{modelCatalog.d.ts → providerModelFacts.d.ts} +13 -2
  60. package/dist/config/{modelCatalog.js → providerModelFacts.js} +145 -21
  61. package/dist/config/providerPresets.d.ts +8 -19
  62. package/dist/config/providerPresets.js +86 -555
  63. package/dist/config/providerReasoning.d.ts +16 -0
  64. package/dist/config/providerReasoning.js +56 -0
  65. package/dist/config/providers.d.ts +4 -0
  66. package/dist/config/providers.js +19 -2
  67. package/dist/config/settings.d.ts +14 -0
  68. package/dist/config/settings.js +5 -0
  69. package/dist/core/agent/compaction.d.ts +1 -0
  70. package/dist/core/agent/compaction.js +3 -0
  71. package/dist/core/agent/events.d.ts +1 -1
  72. package/dist/core/agent/providerTransition.d.ts +8 -0
  73. package/dist/core/agent/providerTransition.js +47 -0
  74. package/dist/core/agent/reasoningPolicy.d.ts +1 -1
  75. package/dist/core/agent/reasoningPolicy.js +4 -2
  76. package/dist/core/graph/analyze.d.ts +61 -0
  77. package/dist/core/graph/analyze.js +274 -0
  78. package/dist/core/graph/buildGraph.d.ts +44 -0
  79. package/dist/core/graph/buildGraph.js +290 -0
  80. package/dist/core/graph/digest.d.ts +2 -0
  81. package/dist/core/graph/digest.js +40 -0
  82. package/dist/core/graph/extract.d.ts +58 -0
  83. package/dist/core/graph/extract.js +394 -0
  84. package/dist/core/graph/model.d.ts +63 -0
  85. package/dist/core/graph/model.js +96 -0
  86. package/dist/core/graph/query.d.ts +69 -0
  87. package/dist/core/graph/query.js +391 -0
  88. package/dist/core/graph/store.d.ts +64 -0
  89. package/dist/core/graph/store.js +171 -0
  90. package/dist/core/limits.d.ts +0 -2
  91. package/dist/core/limits.js +0 -2
  92. package/dist/core/process/runBoundedProcess.js +12 -6
  93. package/dist/core/providerContracts.d.ts +9 -8
  94. package/dist/core/providerContracts.js +21 -1
  95. package/dist/core/safety/redaction.js +12 -2
  96. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  97. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  98. package/dist/core/session/sessionSlimming.js +5 -59
  99. package/dist/core/session/sessionStore.d.ts +4 -0
  100. package/dist/core/session/sessionStore.js +149 -9
  101. package/dist/core/session/snapshotCodec.d.ts +5 -0
  102. package/dist/core/session/snapshotCodec.js +47 -0
  103. package/dist/core/shellOutput/registry.js +2 -46
  104. package/dist/core/subagent/executionProfiles.js +8 -5
  105. package/dist/core/tasks/taskStorage.js +11 -1
  106. package/dist/core/toolOutput/reduction.d.ts +55 -2
  107. package/dist/core/toolOutput/reduction.js +77 -2
  108. package/dist/core/validation/outputParser.js +16 -8
  109. package/dist/llm/client.d.ts +4 -2
  110. package/dist/llm/client.js +104 -55
  111. package/dist/llm/hazeTools.d.ts +2 -12426
  112. package/dist/llm/hazeTools.js +2 -0
  113. package/dist/llm/lspTools.d.ts +3 -12622
  114. package/dist/llm/mistralReasoning.d.ts +2 -0
  115. package/dist/llm/mistralReasoning.js +17 -0
  116. package/dist/llm/mistralVibeAuth.d.ts +5 -0
  117. package/dist/llm/mistralVibeAuth.js +63 -0
  118. package/dist/llm/requestContext.d.ts +3 -0
  119. package/dist/llm/requestContext.js +21 -11
  120. package/dist/llm/subagentRunner.d.ts +2 -308
  121. package/dist/llm/subagentRunner.js +15 -7
  122. package/dist/llm/systemPrompt.js +7 -4
  123. package/dist/llm/toolResultTypes.d.ts +1 -1
  124. package/dist/llm/toolResultTypes.js +7 -1
  125. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  126. package/dist/llm/tools/fileTools.d.ts +2 -7768
  127. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  128. package/dist/llm/tools/graphAdvisory.js +68 -0
  129. package/dist/llm/tools/graphTools.d.ts +13 -0
  130. package/dist/llm/tools/graphTools.js +195 -0
  131. package/dist/llm/tools/outputCap.d.ts +2 -7
  132. package/dist/llm/tools/outputCap.js +3 -11
  133. package/dist/llm/tools/processTool.d.ts +2 -1081
  134. package/dist/llm/tools/replaceInFiles.js +5 -0
  135. package/dist/llm/tools/shellTool.d.ts +2 -1513
  136. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  137. package/dist/llm/tools/taskTool.d.ts +2 -489
  138. package/dist/llm/tools/toolContext.js +24 -9
  139. package/dist/llm/tools/toolContextState.d.ts +3 -0
  140. package/dist/llm/tools/toolContextState.js +2 -1
  141. package/dist/skills/skillTools.js +4 -1
  142. package/package.json +24 -15
@@ -12,15 +12,12 @@ export interface ProviderCapabilities {
12
12
  supportsStickySessionId: boolean;
13
13
  supportsServerCompaction: boolean;
14
14
  supportsTextVerbosity: boolean;
15
- /**
16
- * Protocol accepts a reasoning-effort request. Explicit-first: a provider
17
- * `capabilities.reasoningEffort` override in settings wins. The default is
18
- * the SDK pass-through (`true`) for hosted OpenAI-compatible endpoints and
19
- * `false` for loopback/local inference servers, whose own reasoning switches
20
- * (e.g. LM Studio's `on`/`off`) coerce unsupported levels — even `none` — to
21
- * `on`, silently inverting the request. `false` omits the parameter entirely.
22
- */
15
+ /** The resolved model profile has at least one supported reasoning choice. */
23
16
  supportsReasoningEffort: boolean;
17
+ /** Lowest supported worker effort when the model does not accept none. */
18
+ workerReasoningEffort?: ReasoningLevel;
19
+ /** OpenRouter accepts effort inside its provider-specific reasoning object. */
20
+ reasoningTransport?: 'openrouter';
24
21
  /** Native template switch, independently of OpenAI effort pass-through. */
25
22
  supportsBinaryThinking?: boolean;
26
23
  }
@@ -32,3 +29,7 @@ export interface ProviderRequestOptions {
32
29
  /** Codex subscription requests let the provider manage the output limit. */
33
30
  omitMaxOutputTokens?: boolean;
34
31
  }
32
+ /** Apply the same output-limit and purpose-specific reasoning rules to auxiliary calls. */
33
+ export declare function auxiliaryRequestOptions(options: ProviderRequestOptions, capabilities: ProviderCapabilities, purpose: 'worker' | 'compaction', maxOutputTokens: number): Omit<ProviderRequestOptions, 'omitMaxOutputTokens'> & {
34
+ maxOutputTokens?: number;
35
+ };
@@ -1 +1,21 @@
1
- export {};
1
+ /** Apply the same output-limit and purpose-specific reasoning rules to auxiliary calls. */
2
+ export function auxiliaryRequestOptions(options, capabilities, purpose, maxOutputTokens) {
3
+ const { omitMaxOutputTokens, ...result } = options;
4
+ if (purpose === 'worker') {
5
+ const effort = capabilities.workerReasoningEffort;
6
+ if (capabilities.reasoningTransport === 'openrouter') {
7
+ const openrouter = { ...result.providerOptions?.openrouter };
8
+ if (effort)
9
+ openrouter.reasoning = { effort };
10
+ else
11
+ delete openrouter.reasoning;
12
+ result.providerOptions = { ...result.providerOptions, openrouter };
13
+ delete result.reasoning;
14
+ }
15
+ else if (effort)
16
+ result.reasoning = effort;
17
+ else
18
+ delete result.reasoning;
19
+ }
20
+ return { ...result, ...(!omitMaxOutputTokens ? { maxOutputTokens } : {}) };
21
+ }
@@ -17,8 +17,18 @@ const SECRET_PATTERNS = [
17
17
  { kind: 'aws-key', pattern: /AKIA[0-9A-Z]{16}/g },
18
18
  // Slack tokens (bot, app, refresh, user tokens).
19
19
  { kind: 'slack-token', pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/g },
20
- // JWTs (three base64url segments starting with a JSON header).
21
- { kind: 'jwt', pattern: /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g },
20
+ // JWTs (three base64url segments starting with a JSON header). Per-segment
21
+ // minimums cut false positives on short token-shaped strings while still
22
+ // matching real JWTs, whose segments are far longer than this.
23
+ { kind: 'jwt', pattern: /eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
24
+ // GitHub fine-grained / long-lived personal access tokens (github_pat_ prefix).
25
+ { kind: 'github-token', pattern: /github_pat_[A-Za-z0-9_]{20,}/g },
26
+ // GCP API keys (AIza prefix).
27
+ { kind: 'gcp-api-key', pattern: /AIza[0-9A-Za-z_-]{30,}/g },
28
+ // Google OAuth client secrets (GOCSPX prefix).
29
+ { kind: 'oauth-client-secret', pattern: /GOCSPX-[A-Za-z0-9_-]{20,}/g },
30
+ // Stripe restricted keys (rk_live_ / rk_test_ prefix).
31
+ { kind: 'stripe-key', pattern: /rk_(live|test)_[A-Za-z0-9]{20,}/g },
22
32
  ];
23
33
  /** Replace common secret token shapes in a string with `[redacted:<kind>]`. */
24
34
  export function redactSecrets(text) {
@@ -20,3 +20,9 @@
20
20
  * the exact form keep working because the producer's own closer is intact.
21
21
  */
22
22
  export declare function escapeEnvelopeClosers(content: string): string;
23
+ /**
24
+ * Escape every closing-tag variant of one additional labeled container (e.g.
25
+ * `project_skill`) with the same variant tolerance as the five built-in
26
+ * kinds, so ad-hoc per-site `replaceAll` escapes cannot reappear.
27
+ */
28
+ export declare function escapeTagCloserVariants(content: string, tag: string): string;
@@ -13,7 +13,12 @@
13
13
  *
14
14
  * One helper for all envelope producers: no ad-hoc per-site escapes.
15
15
  */
16
- const ENVELOPE_CLOSER = /<\/\s*(web_content|mcp_result|project_instructions|project_context|haze_compaction)\s*>/gi;
16
+ const ENVELOPE_TAGS = ['web_content', 'mcp_result', 'project_instructions', 'project_context', 'haze_compaction'];
17
+ const ENVELOPE_CLOSER = new RegExp(`<\\/\\s*(?:${ENVELOPE_TAGS.join('|')})\\s*>`, 'gi');
18
+ /** Neutralize one matched closer by breaking the tag open (`<\/`). */
19
+ function escapeCloserMatch(closer) {
20
+ return closer.replace('</', '<\\/');
21
+ }
17
22
  /**
18
23
  * Escape every envelope-closing-tag variant in `content` so the payload
19
24
  * cannot forge an envelope boundary. The escape breaks the tag open (`<\/`)
@@ -21,5 +26,15 @@ const ENVELOPE_CLOSER = /<\/\s*(web_content|mcp_result|project_instructions|proj
21
26
  * the exact form keep working because the producer's own closer is intact.
22
27
  */
23
28
  export function escapeEnvelopeClosers(content) {
24
- return content.replace(ENVELOPE_CLOSER, closer => closer.replace('</', '<\\/'));
29
+ return content.replace(ENVELOPE_CLOSER, escapeCloserMatch);
30
+ }
31
+ /**
32
+ * Escape every closing-tag variant of one additional labeled container (e.g.
33
+ * `project_skill`) with the same variant tolerance as the five built-in
34
+ * kinds, so ad-hoc per-site `replaceAll` escapes cannot reappear.
35
+ */
36
+ export function escapeTagCloserVariants(content, tag) {
37
+ if (!/^[a-z0-9_]+$/i.test(tag))
38
+ throw new Error(`Invalid envelope tag: ${tag}`);
39
+ return content.replace(new RegExp(`<\\/\\s*${tag}\\s*>`, 'gi'), escapeCloserMatch);
25
40
  }
@@ -1,7 +1,6 @@
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
- import { imageFilePartBytes, isImageFilePart } from '../attachments/imageAttachments.js';
1
+ import { SESSION_INLINE_VALUE_BYTES as INLINE_VALUE_BYTES, SESSION_PREVIEW_CHARS as PREVIEW_CHARS } from '../limits.js';
2
+ import { encodeSnapshotMessages } from './snapshotCodec.js';
3
3
  import { redactUnknown } from '../safety/redaction.js';
4
- import { formatBytes } from '../../utils/format.js';
5
4
  function jsonByteLength(value) {
6
5
  try {
7
6
  return Buffer.byteLength(JSON.stringify(value), 'utf8');
@@ -25,62 +24,9 @@ function slimLargeValue(value) {
25
24
  preview: previewText(value),
26
25
  };
27
26
  }
28
- /**
29
- * Image file parts become text placeholders (F03): resumed sessions must not
30
- * replay megabytes of base64, and the placeholder stays a protocol-safe
31
- * ModelMessage part for any provider. The model re-asks if it needs the image.
32
- */
33
- function slimImageFilePart(part) {
34
- const bytes = imageFilePartBytes(part.data);
35
- const name = typeof part.filename === 'string' && part.filename ? ` ${part.filename}` : '';
36
- return {
37
- type: 'text',
38
- text: `[image omitted from session:${name} ${part.mediaType}, ${formatBytes(bytes)} — ask the user to re-attach it if needed]`,
39
- };
40
- }
41
27
  function isRecord(value) {
42
28
  return typeof value === 'object' && value != null && !Array.isArray(value);
43
29
  }
44
- /**
45
- * Slim a tool-result output while preserving the AI SDK output envelope.
46
- * Restored snapshots are re-sent to providers, and `modelMessageSchema` requires
47
- * a tool-result output to be `{type: 'json'|'text'|... , value}`; a bare slim
48
- * marker as the output made every resumed session fail with
49
- * AI_InvalidPromptError (F-09 regression).
50
- */
51
- function slimToolResultOutput(output) {
52
- if (!isRecord(output) || typeof output.type !== 'string' || !('value' in output))
53
- return slimLargeValue(output);
54
- return { ...output, value: slimLargeValue(output.value) };
55
- }
56
- function slimUnknown(value, seen = new WeakSet()) {
57
- if (typeof value === 'string') {
58
- if (value.length <= LARGE_STRING_CHARS)
59
- return value;
60
- return `${value.slice(0, PREVIEW_CHARS)}\n\n[Session value truncated: ${value.length - PREVIEW_CHARS} characters omitted]`;
61
- }
62
- if (value == null || typeof value !== 'object')
63
- return value;
64
- if (seen.has(value))
65
- return '[Circular]';
66
- seen.add(value);
67
- if (Array.isArray(value))
68
- return value.map(item => slimUnknown(item, seen));
69
- const record = value;
70
- if (isImageFilePart(record))
71
- return slimImageFilePart(record);
72
- if (record.type === 'tool-result') {
73
- return {
74
- ...record,
75
- output: slimToolResultOutput(record.output),
76
- result: slimLargeValue(record.result),
77
- };
78
- }
79
- const next = {};
80
- for (const [key, child] of Object.entries(record))
81
- next[key] = slimUnknown(child, seen);
82
- return next;
83
- }
84
30
  /**
85
31
  * Restore-side repair (F-09): sessions written before the envelope fix store
86
32
  * bare `{omitted, reason, originalBytes, preview}` slim markers as tool-result
@@ -115,8 +61,8 @@ function isLegacySlimMarker(value) {
115
61
  export function repairRestoredConversation(messages) {
116
62
  return repairLegacySlimmedMessages(messages);
117
63
  }
118
- function slimConversationSnapshot(messages) {
119
- return slimUnknown(messages);
64
+ function prepareConversationSnapshot(messages) {
65
+ return encodeSnapshotMessages(messages);
120
66
  }
121
67
  function slimToolStartInput(input) {
122
68
  // Full tool inputs (writeFile/editFile payloads can be tens of KB) are replaced
@@ -180,7 +126,7 @@ function slimSessionEntry(entry) {
180
126
  return entry;
181
127
  }
182
128
  if (entry.type === 'conversation_snapshot') {
183
- return { ...entry, messages: slimConversationSnapshot(entry.messages) };
129
+ return { ...entry, messages: prepareConversationSnapshot(entry.messages) };
184
130
  }
185
131
  // Goal-ledger entries are small bounded metadata; only the request text is
186
132
  // capped (a pathological 256 KiB piped prompt must not bloat every boundary
@@ -4,6 +4,7 @@ import type { ValidationKind } from '../../llm/toolResultTypes.js';
4
4
  export interface SessionModelSelection {
5
5
  provider: string;
6
6
  model: string;
7
+ endpointFingerprint?: string;
7
8
  }
8
9
  export type SessionEntry = {
9
10
  type: 'header';
@@ -25,6 +26,7 @@ export type SessionEntry = {
25
26
  type: 'conversation_snapshot';
26
27
  at: string;
27
28
  messages: ModelMessage[];
29
+ selection?: SessionModelSelection;
28
30
  } | {
29
31
  type: 'work_state_snapshot';
30
32
  at: string;
@@ -119,6 +121,8 @@ export interface HazeSession {
119
121
  * resumed; default (absent/false) persists entries verbatim.
120
122
  */
121
123
  redactSecrets?: boolean;
124
+ /** Internal: the existing JSONL tail has been checked before appending. */
125
+ tailChecked?: boolean;
122
126
  }
123
127
  export declare function createSession(options?: {
124
128
  cwd?: string;
@@ -4,6 +4,7 @@ import fs from 'node:fs/promises';
4
4
  import { pathExists } from '../../utils/fs.js';
5
5
  import { HAZE_DIR } from '../../config/paths.js';
6
6
  import { prepareSessionEntryForWrite, repairRestoredConversation } from './sessionSlimming.js';
7
+ import { decodeSnapshotMessages, encodeSnapshotMessages } from './snapshotCodec.js';
7
8
  import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
8
9
  import { JSONL_LINE_BYTES } from '../limits.js';
9
10
  import { iterateBoundedUtf8Lines } from '../io/boundedRead.js';
@@ -84,6 +85,51 @@ function entryMakesSessionResumable(entry) {
84
85
  return entry.text.trim().length > 0;
85
86
  return entry.type === 'conversation_snapshot' && entry.messages.length > 0;
86
87
  }
88
+ // A snapshot is one logical record, but large opaque provider data must not
89
+ // exceed the line reader's bound. The commit line makes incomplete writes
90
+ // invisible; the digest prevents a damaged snapshot from being replayed.
91
+ const SNAPSHOT_CHUNK_BYTES = 256 * 1024;
92
+ const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
93
+ function serializeSessionEntry(entry) {
94
+ const serializable = entry.type === 'conversation_snapshot' ? { ...entry, messages: encodeSnapshotMessages(entry.messages) } : entry;
95
+ const json = JSON.stringify(serializable);
96
+ const bytes = Buffer.from(json, 'utf8');
97
+ if (bytes.length <= JSONL_LINE_BYTES - 1)
98
+ return `${json}\n`;
99
+ if (entry.type !== 'conversation_snapshot')
100
+ throw new Error(`Session ${entry.type} exceeds the ${JSONL_LINE_BYTES} byte line limit`);
101
+ if (bytes.length > MAX_SNAPSHOT_BYTES)
102
+ throw new Error(`Session snapshot exceeds the ${MAX_SNAPSHOT_BYTES} byte limit`);
103
+ const id = crypto.randomUUID();
104
+ const count = Math.ceil(bytes.length / SNAPSHOT_CHUNK_BYTES);
105
+ const digest = crypto.createHash('sha256').update(bytes).digest('hex');
106
+ const lines = [];
107
+ for (let index = 0; index < count; index++) {
108
+ lines.push(JSON.stringify({ type: 'snapshot_chunk', id, index, count, data: bytes.subarray(index * SNAPSHOT_CHUNK_BYTES, (index + 1) * SNAPSHOT_CHUNK_BYTES).toString('base64') }));
109
+ }
110
+ lines.push(JSON.stringify({ type: 'snapshot_commit', id, count, bytes: bytes.length, digest }));
111
+ return `${lines.join('\n')}\n`;
112
+ }
113
+ async function hasUnterminatedTail(file) {
114
+ const handle = await fs.open(file, 'r').catch(error => {
115
+ if (error.code === 'ENOENT')
116
+ return undefined;
117
+ throw error;
118
+ });
119
+ if (!handle)
120
+ return false;
121
+ try {
122
+ const { size } = await handle.stat();
123
+ if (!size)
124
+ return false;
125
+ const last = Buffer.alloc(1);
126
+ await handle.read(last, 0, 1, size - 1);
127
+ return last[0] !== 10;
128
+ }
129
+ finally {
130
+ await handle.close();
131
+ }
132
+ }
87
133
  export async function appendSessionEntry(session, entry) {
88
134
  const file = validatedSessionFile(session);
89
135
  const prepared = prepareSessionEntryForWrite(entry, { redactSecrets: session.redactSecrets === true });
@@ -96,11 +142,21 @@ export async function appendSessionEntry(session, entry) {
96
142
  return;
97
143
  }
98
144
  const entries = [deferred.header, ...deferred.entries, prepared];
99
- await appendPrivateFile(file, entries.map(item => JSON.stringify(item)).join('\n') + '\n');
145
+ await appendPrivateFile(file, entries.map(serializeSessionEntry).join(''));
100
146
  session.deferredWrite = undefined;
147
+ session.tailChecked = true;
101
148
  return;
102
149
  }
103
- await appendPrivateFile(file, `${JSON.stringify(prepared)}\n`);
150
+ const separator = !session.tailChecked && await hasUnterminatedTail(file) ? '\n' : '';
151
+ try {
152
+ await appendPrivateFile(file, separator + serializeSessionEntry(prepared));
153
+ }
154
+ catch (error) {
155
+ // A failed append can leave a partial JSONL line even in this process.
156
+ session.tailChecked = false;
157
+ throw error;
158
+ }
159
+ session.tailChecked = true;
104
160
  // Snapshot deduplication runs inside the same serialized writer as the
105
161
  // append, so ordering with subsequent entries is preserved (F-03).
106
162
  await vacuumSessionFileIfLarge(session).catch(() => undefined);
@@ -168,7 +224,7 @@ export async function vacuumSessionFileIfLarge(session, thresholdBytes = effecti
168
224
  const droppedGoalBytes = entries
169
225
  .filter((entry, index) => entry.type === 'goal' && !keepGoal.has(index))
170
226
  .reduce((sum, entry) => sum + Buffer.byteLength(JSON.stringify(entry), 'utf8'), 0);
171
- const serialized = kept.map(entry => JSON.stringify(entry)).join('\n') + '\n';
227
+ const serialized = kept.map(serializeSessionEntry).join('');
172
228
  // Only rewrite when it meaningfully shrinks the file (otherwise a single
173
229
  // dominant snapshot would trigger a full rewrite on every append), or when
174
230
  // the goal-ledger trim alone has accumulated enough to amortize the rewrite.
@@ -250,15 +306,18 @@ function parseSessionEntry(value) {
250
306
  case 'conversation_snapshot':
251
307
  if (typeof value.at !== 'string' || !Array.isArray(value.messages))
252
308
  return invalid('conversation_snapshot messages must be an array');
309
+ if (value.selection !== undefined && (!isRecord(value.selection) || typeof value.selection.provider !== 'string' || !value.selection.provider.trim() || typeof value.selection.model !== 'string' || !value.selection.model.trim() || (value.selection.endpointFingerprint !== undefined && (typeof value.selection.endpointFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(value.selection.endpointFingerprint)))))
310
+ return invalid('invalid conversation_snapshot selection');
253
311
  if (!value.messages.every((message) => isRecord(message)
254
312
  && typeof message.role === 'string'
255
313
  && MODEL_MESSAGE_ROLES.has(message.role)))
256
314
  return invalid('conversation_snapshot contains an invalid message role');
257
- return value;
315
+ return { ...value, messages: decodeSnapshotMessages(value.messages) };
258
316
  case 'model_selection':
259
317
  if (typeof value.at !== 'string' || !isRecord(value.selection)
260
318
  || typeof value.selection.provider !== 'string' || !value.selection.provider.trim()
261
- || typeof value.selection.model !== 'string' || !value.selection.model.trim())
319
+ || typeof value.selection.model !== 'string' || !value.selection.model.trim()
320
+ || (value.selection.endpointFingerprint !== undefined && (typeof value.selection.endpointFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(value.selection.endpointFingerprint))))
262
321
  return invalid('invalid model_selection');
263
322
  return value;
264
323
  case 'work_state_snapshot':
@@ -305,20 +364,95 @@ async function scanSessionEntries(session, onEntry) {
305
364
  else
306
365
  omittedErrors++;
307
366
  };
367
+ let pending;
368
+ let legacyReader;
369
+ const recoverLegacySnapshot = async (lineNumber) => {
370
+ legacyReader ??= iterateBoundedUtf8Lines(file, MAX_SNAPSHOT_BYTES);
371
+ for (;;) {
372
+ const next = await legacyReader.next();
373
+ if (next.done || next.value.lineNumber > lineNumber)
374
+ return undefined;
375
+ if (next.value.lineNumber < lineNumber)
376
+ continue;
377
+ if (next.value.oversized)
378
+ return undefined;
379
+ try {
380
+ const value = JSON.parse(next.value.line);
381
+ if (!isRecord(value) || value.type !== 'conversation_snapshot')
382
+ return undefined;
383
+ return parseSessionEntry(value);
384
+ }
385
+ catch {
386
+ return undefined;
387
+ }
388
+ }
389
+ };
308
390
  for await (const { line, lineNumber, oversized } of iterateBoundedUtf8Lines(file, JSONL_LINE_BYTES)) {
309
391
  if (!line && !oversized)
310
392
  continue;
311
393
  if (oversized) {
394
+ if (pending) {
395
+ report(`Line ${pending.line}: incomplete snapshot`);
396
+ pending = undefined;
397
+ }
398
+ const legacy = await recoverLegacySnapshot(lineNumber);
399
+ if (legacy) {
400
+ onEntry(legacy);
401
+ continue;
402
+ }
312
403
  report(`Line ${lineNumber}: exceeds ${JSONL_LINE_BYTES} byte limit`);
313
404
  continue;
314
405
  }
315
406
  try {
316
- onEntry(parseSessionEntry(JSON.parse(line)));
407
+ const value = JSON.parse(line);
408
+ if (isRecord(value) && value.type === 'snapshot_chunk') {
409
+ if (typeof value.id !== 'string' || !Number.isInteger(value.index) || !Number.isInteger(value.count) || typeof value.data !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(value.data))
410
+ throw new Error('invalid snapshot chunk');
411
+ const index = value.index;
412
+ const count = value.count;
413
+ if (count < 1 || count > Math.ceil(MAX_SNAPSHOT_BYTES / SNAPSHOT_CHUNK_BYTES) || index < 0 || index >= count || value.data.length > Math.ceil(SNAPSHOT_CHUNK_BYTES / 3) * 4)
414
+ throw new Error('snapshot chunk out of bounds');
415
+ if (index === 0) {
416
+ if (pending)
417
+ report(`Line ${pending.line}: incomplete snapshot`);
418
+ pending = { id: value.id, count, chunks: [], bytes: 0, line: lineNumber };
419
+ }
420
+ if (!pending || pending.id !== value.id || pending.count !== count || pending.chunks.length !== index)
421
+ throw new Error('snapshot chunks out of order');
422
+ const chunk = Buffer.from(value.data, 'base64');
423
+ pending.bytes += chunk.length;
424
+ if (chunk.length > SNAPSHOT_CHUNK_BYTES || pending.bytes > MAX_SNAPSHOT_BYTES)
425
+ throw new Error('snapshot exceeds size limit');
426
+ pending.chunks.push(chunk);
427
+ continue;
428
+ }
429
+ if (isRecord(value) && value.type === 'snapshot_commit') {
430
+ if (!pending || value.id !== pending.id || value.count !== pending.count || pending.chunks.length !== pending.count || value.bytes !== pending.bytes || typeof value.digest !== 'string')
431
+ throw new Error('invalid snapshot commit');
432
+ const bytes = Buffer.concat(pending.chunks, pending.bytes);
433
+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== value.digest)
434
+ throw new Error('snapshot checksum mismatch');
435
+ const entry = parseSessionEntry(JSON.parse(bytes.toString('utf8')));
436
+ if (entry.type !== 'conversation_snapshot')
437
+ throw new Error('chunked entry is not a conversation snapshot');
438
+ pending = undefined;
439
+ onEntry(entry);
440
+ continue;
441
+ }
442
+ if (pending) {
443
+ report(`Line ${pending.line}: incomplete snapshot`);
444
+ pending = undefined;
445
+ }
446
+ onEntry(parseSessionEntry(value));
317
447
  }
318
448
  catch (error) {
449
+ pending = undefined;
319
450
  report(`Line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
320
451
  }
321
452
  }
453
+ await legacyReader?.return(undefined);
454
+ if (pending)
455
+ report(`Line ${pending.line}: incomplete snapshot`);
322
456
  if (omittedErrors > 0)
323
457
  parseErrors.push(`${omittedErrors} additional parse errors omitted.`);
324
458
  return parseErrors;
@@ -390,8 +524,11 @@ export async function restoreSessionState(session) {
390
524
  // Legacy slim markers (pre-envelope-fix) are re-wrapped so the restored
391
525
  // conversation is a protocol-safe ModelMessage[] for the next provider
392
526
  // request (F-09).
393
- if (entry.type === 'conversation_snapshot')
527
+ if (entry.type === 'conversation_snapshot') {
394
528
  messages = repairRestoredConversation(entry.messages);
529
+ if (entry.selection)
530
+ modelSelection = entry.selection;
531
+ }
395
532
  // SU-02: a durable clear marker means "no conversation after this line";
396
533
  // later snapshots (if any) re-materialize it, otherwise restore yields [].
397
534
  if (entry.type === 'event' && entry.name === 'clear') {
@@ -466,8 +603,11 @@ async function summarizeSession(session, stat) {
466
603
  messageCount = entry.messages.length;
467
604
  if (!firstUserPreview) {
468
605
  const firstUser = entry.messages.find(message => message.role === 'user');
469
- if (firstUser)
470
- firstUserPreview = previewText(typeof firstUser.content === 'string' ? firstUser.content : JSON.stringify(firstUser.content));
606
+ if (firstUser) {
607
+ const content = firstUser.content;
608
+ const text = typeof content === 'string' ? content : content.flatMap(part => part.type === 'text' ? [part.text] : []).join(' ');
609
+ firstUserPreview = previewText(text || '[attachment]');
610
+ }
471
611
  }
472
612
  }
473
613
  if (entry.type === 'event' && entry.name === 'turn_end' && entry.text) {
@@ -0,0 +1,5 @@
1
+ import type { ModelMessage } from 'ai';
2
+ /** Convert binary and URL file data into an unambiguous JSON representation. */
3
+ export declare function encodeSnapshotMessages(messages: ModelMessage[]): ModelMessage[];
4
+ /** Reconstruct file data before passing restored messages back to the SDK. */
5
+ export declare function decodeSnapshotMessages(messages: ModelMessage[]): ModelMessage[];
@@ -0,0 +1,47 @@
1
+ const FILE_DATA_TAG = '__haze_file_data_v1';
2
+ /** Convert binary and URL file data into an unambiguous JSON representation. */
3
+ export function encodeSnapshotMessages(messages) {
4
+ return mapFileData(messages, data => {
5
+ if (data instanceof Uint8Array)
6
+ return { [FILE_DATA_TAG]: 'bytes', value: Buffer.from(data).toString('base64') };
7
+ if (data instanceof ArrayBuffer)
8
+ return { [FILE_DATA_TAG]: 'array-buffer', value: Buffer.from(data).toString('base64') };
9
+ if (data instanceof URL)
10
+ return { [FILE_DATA_TAG]: 'url', value: data.href };
11
+ return data;
12
+ });
13
+ }
14
+ /** Reconstruct file data before passing restored messages back to the SDK. */
15
+ export function decodeSnapshotMessages(messages) {
16
+ return mapFileData(messages, data => {
17
+ if (typeof data !== 'object' || data === null || !(FILE_DATA_TAG in data))
18
+ return data;
19
+ const marker = data;
20
+ if (typeof marker.value !== 'string')
21
+ throw new Error('invalid snapshot file data');
22
+ if (marker[FILE_DATA_TAG] === 'url')
23
+ return new URL(marker.value);
24
+ if ((marker[FILE_DATA_TAG] !== 'bytes' && marker[FILE_DATA_TAG] !== 'array-buffer') || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(marker.value))
25
+ throw new Error('invalid snapshot file data');
26
+ const bytes = Uint8Array.from(Buffer.from(marker.value, 'base64'));
27
+ return marker[FILE_DATA_TAG] === 'array-buffer' ? bytes.buffer : bytes;
28
+ });
29
+ }
30
+ function mapFileData(messages, map) {
31
+ const mapValue = (value) => {
32
+ const mapped = map(value);
33
+ if (mapped !== value || typeof value !== 'object' || value === null)
34
+ return mapped;
35
+ const record = value;
36
+ if (record.type === 'data' && 'data' in record)
37
+ return { ...record, data: map(record.data) };
38
+ if (record.type === 'url' && 'url' in record)
39
+ return { ...record, url: map(record.url) };
40
+ return value;
41
+ };
42
+ return messages.map(message => {
43
+ if (!Array.isArray(message.content))
44
+ return message;
45
+ return { ...message, content: message.content.map(part => part.type === 'file' ? { ...part, data: mapValue(part.data) } : part.type === 'image' ? { ...part, image: mapValue(part.image) } : part) };
46
+ });
47
+ }
@@ -5,7 +5,7 @@ import { reduceGitOutput } from './reducers/git.js';
5
5
  import { reduceGhOutput } from './reducers/gh.js';
6
6
  import { reduceSearchOutput } from './reducers/search.js';
7
7
  import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
8
- import { capOutputForProcessing, isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
8
+ import { capOutputForProcessing, makeStreamReduction, passthroughReduction } from '../toolOutput/reduction.js';
9
9
  const builtInLineFilters = [
10
10
  { name: 'markdownlint', matchCommand: /(^|[;&|]\s*)markdownlint\b/, stripAnsi: true, truncateLinesAt: 200, maxLines: 80, onEmpty: 'markdownlint: ok' },
11
11
  { name: 'shellcheck', matchCommand: /(^|[;&|]\s*)shellcheck\b/, stripAnsi: true, stripLinesMatching: [/^In .* line \d+:/], truncateLinesAt: 200, maxLines: 100, onEmpty: 'shellcheck: ok' },
@@ -16,51 +16,7 @@ const builtInLineFilters = [
16
16
  { name: 'system-list', matchCommand: /(^|[;&|]\s*)(?:du|df|ps)\b/, stripAnsi: true, truncateLinesAt: 180, maxLines: 50 },
17
17
  ];
18
18
  function makeReduction(raw, text, filtered, filterName, input, warning, contentKind = 'generic') {
19
- let finalText = text;
20
- let handle;
21
- let truncated = false;
22
- if (finalText.length > input.compactMaxChars) {
23
- const compacted = input.fallbackCompact(finalText, input.compactMaxChars);
24
- finalText = compacted.text;
25
- handle = compacted.handle;
26
- truncated = compacted.truncated;
27
- }
28
- const lossy = filtered && finalText !== raw;
29
- const rawHandle = lossy && input.storeRawOutput ? input.storeRawOutput(raw) : handle;
30
- if (filtered && contentKind !== 'validation' && raw.length > 2000 && isInflating(raw, finalText))
31
- return passthroughReduction(raw, input);
32
- if (lossy && rawHandle && !finalText.includes(rawHandle))
33
- finalText = `${finalText}\n\n[${retrievalHint(rawHandle)}]`;
34
- const metrics = reductionMetrics(raw, finalText);
35
- return {
36
- text: finalText,
37
- truncated,
38
- filtered,
39
- ...(filterName ? { filterName, reducerName: filterName } : {}),
40
- contentKind,
41
- lossy,
42
- parseTier: warning ? 'degraded' : filtered ? 'full' : 'passthrough',
43
- ...(warning ? { warning } : {}),
44
- ...(handle ?? rawHandle ? { handle: handle ?? rawHandle } : {}),
45
- ...(rawHandle ? { rawHandle } : {}),
46
- omittedChars: Math.max(0, raw.length - finalText.length),
47
- ...metrics,
48
- };
49
- }
50
- function passthroughReduction(raw, input) {
51
- const compacted = input.fallbackCompact(raw, input.compactMaxChars);
52
- return {
53
- text: compacted.text,
54
- truncated: compacted.truncated,
55
- filtered: false,
56
- reducerName: 'generic-cap',
57
- contentKind: 'generic',
58
- lossy: compacted.truncated,
59
- parseTier: 'passthrough',
60
- ...(compacted.handle ? { handle: compacted.handle, rawHandle: compacted.handle } : {}),
61
- omittedChars: compacted.omittedChars ?? Math.max(0, raw.length - compacted.text.length),
62
- ...reductionMetrics(raw, compacted.text),
63
- };
19
+ return makeStreamReduction(raw, text, filtered, filterName, input, warning, contentKind);
64
20
  }
65
21
  export function filterShellOutput(input) {
66
22
  try {
@@ -17,17 +17,20 @@ export const COMPATIBILITY_PROFILE = {
17
17
  deadlineMs: SUBAGENT_DEFAULT_DEADLINE_MS, maxRetries: 2,
18
18
  };
19
19
  export const BUILT_IN_SUBAGENT_PROFILES = {
20
- 'haze-build': { ...COMPATIBILITY_PROFILE, name: 'haze-build', maxConcurrency: 2, maxInputTokens: 48_000, maxOutputTokens: 6_144, maxRetries: 0 },
20
+ // Ceiling only: the effective cap is the deployment manifest's native-worker
21
+ // allowance (requestContext clamps to it), so a 3-sequence server raises the
22
+ // fleet to 3 and a future multi-tenant server lowers it without a release.
23
+ 'haze-build': { ...COMPATIBILITY_PROFILE, name: 'haze-build', maxConcurrency: 5, maxInputTokens: 48_000, maxOutputTokens: 6_144, maxRetries: 0 },
21
24
  'local-safe': { ...COMPATIBILITY_PROFILE, name: 'local-safe', maxConcurrency: 1, maxSteps: 32, maxToolCalls: 24, maxOutputTokens: 4_096, maxInputTokens: 40_000, maxRetries: 0 },
22
25
  'local-throughput': { ...COMPATIBILITY_PROFILE, name: 'local-throughput', maxConcurrency: 2, maxSteps: 40, maxToolCalls: 32, maxOutputTokens: 6_144, maxInputTokens: 48_000, maxRetries: 0 },
23
26
  'cloud-balanced': { ...COMPATIBILITY_PROFILE, name: 'cloud-balanced', maxConcurrency: 3, deadlineMs: 360_000 },
24
27
  'cloud-fast': { ...COMPATIBILITY_PROFILE, name: 'cloud-fast', maxConcurrency: 5, deadlineMs: 240_000, maxRetries: 1 },
25
28
  };
26
29
  export const MODE_TOOL_NAMES = {
27
- inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput'],
28
- research: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'fetch'],
29
- implement: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'shell'],
30
- validate: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'shell'],
30
+ inspect: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'graphQuery', 'graphExplain', 'graphPath'],
31
+ research: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'fetch', 'graphQuery', 'graphExplain', 'graphPath'],
32
+ implement: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'shell', 'graphQuery', 'graphAffected'],
33
+ validate: ['listFiles', 'readFile', 'grep', 'readToolOutput', 'shell', 'graphAffected'],
31
34
  };
32
35
  export function isMutationMode(mode) {
33
36
  return mode === 'implement' || mode === 'validate';
@@ -40,7 +40,17 @@ export async function saveTasks(tasks) {
40
40
  // Mutation guards fail closed: an escaped real path throws instead of writing.
41
41
  await assertWritablePathInsideWorkspace(filePath, filePath);
42
42
  await fs.mkdir(path.dirname(filePath), { recursive: true });
43
- await fs.writeFile(filePath, JSON.stringify(tasks, null, 2), 'utf-8');
43
+ // Atomic temp-file-plus-rename (same directory) so a crash mid-write cannot
44
+ // leave truncated JSON that loadTasks would silently reset to an empty list.
45
+ const tempPath = `${filePath}.tmp-${randomUUID()}`;
46
+ await fs.writeFile(tempPath, JSON.stringify(tasks, null, 2), 'utf-8');
47
+ try {
48
+ await fs.rename(tempPath, filePath);
49
+ }
50
+ catch (error) {
51
+ await fs.rm(tempPath, { force: true }).catch(() => undefined);
52
+ throw error;
53
+ }
44
54
  }
45
55
  export async function clearTasks() {
46
56
  await saveTasks([]);