@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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@denizokcu/haze",
3
- "version": "1.7.10",
4
- "commit": "6be557482d6ce7892e87bd763326ba828c951f79",
5
- "builtAt": "2026-11-05T16:31:40.150Z"
3
+ "version": "1.7.12",
4
+ "commit": "6caef47334dd48adc89a9b58379eb1f0c1135a02",
5
+ "builtAt": "2026-11-20T17:35:30.238Z"
6
6
  }
@@ -1,7 +1,8 @@
1
1
  import React from 'react';
2
2
  /** Spinner ticks stay within this subtree, not the transcript orchestrator. */
3
- export declare function BusyBar({ label, elapsed, tip }: {
3
+ export declare function BusyBar({ label, elapsed, detail, tip }: {
4
4
  label: string;
5
5
  elapsed: string;
6
+ detail?: string;
6
7
  tip?: string;
7
8
  }): React.JSX.Element;
@@ -3,6 +3,6 @@ import { Box, Text } from 'ink';
3
3
  import { ActivitySpinner } from '../../ui/components/NativeIndicators.js';
4
4
  import { theme } from '../../ui/theme.js';
5
5
  /** Spinner ticks stay within this subtree, not the transcript orchestrator. */
6
- export function BusyBar({ label, elapsed, tip }) {
7
- return _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [_jsxs(Box, { overflow: "hidden", children: [_jsx(ActivitySpinner, {}), _jsx(Box, { flexShrink: 0, width: 1 }), _jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: theme.command, bold: true, children: [label, elapsed ? _jsxs(Text, { color: theme.muted, children: [" \u00B7 ", elapsed] }) : null] }), _jsx(Text, { color: theme.muted, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] })] }), tip && _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: [_jsx(Text, { bold: true, children: "Tip:" }), " ", tip] })] });
6
+ export function BusyBar({ label, elapsed, detail, tip }) {
7
+ return _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [_jsxs(Box, { overflow: "hidden", children: [_jsx(ActivitySpinner, {}), _jsx(Box, { flexShrink: 0, width: 1 }), _jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: theme.command, bold: true, children: [label, elapsed ? _jsxs(Text, { color: theme.muted, children: [" \u00B7 ", elapsed] }) : null] }), detail ? _jsxs(Text, { color: theme.muted, children: [" \u00B7 ", detail] }) : null, _jsx(Text, { color: theme.muted, children: " \u00B7 type to queue follow-up \u00B7 esc to interrupt" })] })] }), tip && _jsxs(Text, { color: theme.muted, wrap: "truncate-end", children: [_jsx(Text, { bold: true, children: "Tip:" }), " ", tip] })] });
8
8
  }
@@ -24,3 +24,28 @@ export declare function statusBarMetrics(input: {
24
24
  statusDetailLabel: string;
25
25
  hasTokenBreakdown: boolean;
26
26
  };
27
+ export interface FleetStatus {
28
+ running: number;
29
+ queued: number;
30
+ }
31
+ /**
32
+ * Rolling fleet depth for the busy row, folded from coordinator events.
33
+ * `queued` events report the queue length after enqueue; each later `started`
34
+ * consumes one slot from it, terminal/settled events only move `running`.
35
+ */
36
+ export declare function nextFleetStatus(current: FleetStatus | undefined, event: {
37
+ type: string;
38
+ state?: string;
39
+ running?: number;
40
+ queued?: number;
41
+ }): FleetStatus | undefined;
42
+ /**
43
+ * Busy-row detail for long turns: live generation rate of the streaming
44
+ * message plus fleet depth, so a minutes-long turn shows it is progressing.
45
+ * Pure and cheap enough for the one-second busy heartbeat.
46
+ */
47
+ export declare function busyDetailLabel(input: {
48
+ messages: Message[];
49
+ fleet?: FleetStatus;
50
+ now?: number;
51
+ }): string | undefined;
@@ -1,5 +1,6 @@
1
1
  import os from 'node:os';
2
2
  import { modelMessageText } from '../../core/agent/compaction.js';
3
+ import { estimateValueTokens } from '../../core/agent/contextBudget.js';
3
4
  import { formatTokenCount } from '../../utils/format.js';
4
5
  export function toolCallCount(messages) {
5
6
  return messages.reduce((total, message) => {
@@ -59,3 +60,38 @@ export function statusBarMetrics(input) {
59
60
  const hasTokenBreakdown = tokenUsage.systemPrompt > 0 || tokenUsage.messages > 0 || tokenUsage.toolSchemas > 0 || effectiveInput > 0 || effectiveOutput > 0;
60
61
  return { assistantMessages, toolsUsed, effectiveInput, effectiveOutput, inputEstimated, outputEstimated, statusDetailLabel, hasTokenBreakdown };
61
62
  }
63
+ /**
64
+ * Rolling fleet depth for the busy row, folded from coordinator events.
65
+ * `queued` events report the queue length after enqueue; each later `started`
66
+ * consumes one slot from it, terminal/settled events only move `running`.
67
+ */
68
+ export function nextFleetStatus(current, event) {
69
+ if (event.type !== 'subagent_state')
70
+ return current;
71
+ const running = event.running ?? current?.running ?? 0;
72
+ const queued = event.state === 'queued'
73
+ ? event.queued ?? current?.queued ?? 0
74
+ : Math.max(0, (current?.queued ?? 0) - (event.state === 'started' ? 1 : 0));
75
+ return { running, queued };
76
+ }
77
+ /**
78
+ * Busy-row detail for long turns: live generation rate of the streaming
79
+ * message plus fleet depth, so a minutes-long turn shows it is progressing.
80
+ * Pure and cheap enough for the one-second busy heartbeat.
81
+ */
82
+ export function busyDetailLabel(input) {
83
+ const parts = [];
84
+ const streaming = [...input.messages].reverse()
85
+ .find(message => message.role === 'assistant' && message.streaming && message.startedAt != null && message.text);
86
+ if (streaming?.startedAt != null) {
87
+ const seconds = Math.max(1, ((input.now ?? Date.now()) - streaming.startedAt) / 1000);
88
+ const rate = Math.round(estimateValueTokens(streaming.text) / seconds);
89
+ if (rate > 0)
90
+ parts.push(`~${rate} tok/s`);
91
+ }
92
+ const fleet = input.fleet;
93
+ if (fleet && (fleet.running > 0 || fleet.queued > 0)) {
94
+ parts.push(`workers ${fleet.running} running${fleet.queued > 0 ? `, ${fleet.queued} queued` : ''}`);
95
+ }
96
+ return parts.length > 0 ? parts.join(' · ') : undefined;
97
+ }
@@ -20,6 +20,7 @@ const CHAT_COMMAND_SUGGESTIONS = [
20
20
  { value: '/session', description: 'Show current session path', kind: 'command' },
21
21
  { value: '/resume', description: 'Browse saved sessions for this workspace', kind: 'command' },
22
22
  { value: '/new', description: 'Start a new session', kind: 'command' },
23
+ { value: '/graph', description: 'Build or refresh the workspace code graph (deterministic, incremental) and show an orientation report', kind: 'command' },
23
24
  { value: '/logs', description: 'List recent LLM logs, or summarize one by id (--debug runs only)', kind: 'command' },
24
25
  { value: '/compact ', description: 'Summarize older context and keep recent messages', kind: 'command' },
25
26
  { value: '/clear', description: 'Clear conversation history', kind: 'command' },
@@ -1,4 +1,5 @@
1
1
  import type { ModelMessage } from 'ai';
2
+ import type { StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
2
3
  import type { ContextFile } from '../../config/contextFiles.js';
3
4
  import type { WorkState } from '../../core/agent/workState.js';
4
5
  import { type GoalLedgerFrontier, type HazeSession, type SessionModelSelection } from '../../core/session/sessionStore.js';
@@ -25,6 +26,7 @@ export interface SessionLifecycleDeps {
25
26
  debug: boolean;
26
27
  contextFiles: () => ContextFile[];
27
28
  modelSelection?: () => SessionModelSelection | undefined;
29
+ reasoningByModel?: () => Record<string, StoredReasoningSetting> | undefined;
28
30
  onModelSelection?: (selection: SessionModelSelection | undefined) => void;
29
31
  sessionRef: {
30
32
  current: HazeSession | undefined;
@@ -1,9 +1,12 @@
1
- import { generateText } from 'ai';
1
+ import { streamText } from 'ai';
2
+ import { transitionProviderConversation } from '../../core/agent/providerTransition.js';
2
3
  import { buildLlmCompactionPrompt, compactModelMessages, compactModelMessagesWithSummary, splitForCompaction } from '../../core/agent/compaction.js';
4
+ import { buildCodeGraphDigest } from '../../core/graph/digest.js';
3
5
  import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
4
6
  import { COMPACTION_LLM_MAX_OUTPUT_TOKENS } from '../../core/agent/budgets.js';
5
7
  import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
6
- import { modelWithConfig } from '../../llm/client.js';
8
+ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
9
+ import { auxiliaryRequestOptions } from '../../core/providerContracts.js';
7
10
  import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
8
11
  import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
9
12
  import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
@@ -56,21 +59,26 @@ export function createSessionLifecycle(deps) {
56
59
  applyRedactionSetting(session);
57
60
  deps.sessionRef.current = session;
58
61
  deps.onModelSelection?.(modelSelection);
59
- if (!modelSelection) {
62
+ const currentSelection = deps.modelSelection?.();
63
+ const endpointChanged = Boolean(currentSelection?.endpointFingerprint && (!modelSelection?.endpointFingerprint || modelSelection.endpointFingerprint !== currentSelection.endpointFingerprint));
64
+ const restoredConversation = endpointChanged ? transitionProviderConversation(conversation) : conversation;
65
+ if (!modelSelection && !endpointChanged) {
60
66
  const selection = deps.modelSelection?.();
61
67
  if (selection)
62
68
  deps.sessionRecorder()?.recordModelSelection(selection);
63
69
  }
64
- deps.conversationRef.current = conversation;
70
+ deps.conversationRef.current = restoredConversation;
71
+ if (endpointChanged && currentSelection)
72
+ deps.sessionRecorder()?.recordModelTransition(restoredConversation, currentSelection);
65
73
  deps.clearLiveMessages();
66
- const restoredMessages = displayMessagesFromConversation(conversation);
74
+ const restoredMessages = displayMessagesFromConversation(restoredConversation);
67
75
  deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
68
76
  deps.workStateRef.current = workState;
69
77
  for (const error of parseErrors) {
70
78
  deps.debugLog(`Session parse error: ${error}`);
71
79
  }
72
80
  deps.setMessages(messages => {
73
- const restored = [{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages];
81
+ const restored = [{ role: 'system', text: `Resumed session: ${formatSession(session)}${endpointChanged ? ' Provider endpoint changed or its previous identity was unknown; previous tool history was converted to text and provider reasoning state was cleared.' : ''}` }, ...restoredMessages];
74
82
  return replaceTranscript ? restored : [...messages, ...restored];
75
83
  });
76
84
  // P1 resume path: a durable, unterminated goal frontier surfaces in the
@@ -210,26 +218,26 @@ export function createSessionLifecycle(deps) {
210
218
  // A submission/session change while the summary was pending must not be
211
219
  // overwritten — the stale compaction is reported and discarded instead.
212
220
  const sessionAtStart = deps.sessionRef.current;
221
+ const isStale = () => deps.sessionRef.current !== sessionAtStart || deps.conversationRef.current !== messages;
222
+ const discardStale = () => {
223
+ deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the session or conversation changed while the summary was being written.' }]);
224
+ return false;
225
+ };
213
226
  try {
214
227
  const selection = deps.modelSelection?.();
215
- const runtime = await modelWithConfig(selection ? { modelSelector: `${selection.provider}:${selection.model}` } : undefined);
228
+ const runtime = await modelWithConfig({ ...(selection ? { modelSelector: `${selection.provider}:${selection.model}` } : {}), reasoningByModel: deps.reasoningByModel?.() });
216
229
  if (!runtime?.model)
217
230
  throw new Error('no model provider configured');
218
- const summarization = await generateText({
231
+ const providerSettings = auxiliaryRequestOptions(providerRequestSettings(runtime.config), runtime.config.capabilities, 'compaction', COMPACTION_LLM_MAX_OUTPUT_TOKENS);
232
+ const summarization = streamText({
219
233
  model: runtime.model,
220
- prompt: buildLlmCompactionPrompt({ older: split.older, instructions }),
221
- maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
234
+ ...providerSettings,
235
+ prompt: buildLlmCompactionPrompt({ older: split.older, instructions, codeGraphDigest: await buildCodeGraphDigest() }),
222
236
  abortSignal: AbortSignal.timeout(COMPACT_SUMMARY_TIMEOUT_MS),
223
237
  });
224
- if (deps.sessionRef.current !== sessionAtStart) {
225
- deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the session changed while the summary was being written.' }]);
226
- return false;
227
- }
228
- if (deps.conversationRef.current !== messages) {
229
- deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the conversation changed while the summary was being written. Run /compact again.' }]);
230
- return false;
231
- }
232
- const summaryText = summarization.text.trim();
238
+ const summaryText = (await summarization.text).trim();
239
+ if (isStale())
240
+ return discardStale();
233
241
  if (!summaryText)
234
242
  throw new Error('model returned an empty summary');
235
243
  const result = compactModelMessagesWithSummary(messages, { summaryText, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS, instructions, workState: deps.workStateRef.current });
@@ -243,6 +251,8 @@ export function createSessionLifecycle(deps) {
243
251
  return true;
244
252
  }
245
253
  catch (error) {
254
+ if (isStale())
255
+ return discardStale();
246
256
  deps.debugLog(`LLM compaction failed (${error instanceof Error ? error.message : String(error)}); falling back to the heuristic excerpt`);
247
257
  return compactConversationSync(instructions);
248
258
  }
@@ -5,7 +5,8 @@ import type { AgentEvent } from '../../core/agent/events.js';
5
5
  import type { WorkState } from '../../core/agent/workState.js';
6
6
  import type { Message } from '../commands/streaming.js';
7
7
  export declare function createSessionRecorder(getSession: () => HazeSession | undefined): {
8
- recordModelSelection(selection: SessionModelSelection): void;
8
+ recordModelSelection: (selection: SessionModelSelection) => void;
9
+ recordModelTransition(messages: ModelMessage[], selection: SessionModelSelection): void;
9
10
  recordUiMessage(message: Message): void;
10
11
  recordConversation(messages: ModelMessage[]): void;
11
12
  recordWorkState(state: WorkState): void;
@@ -8,7 +8,10 @@ export function createSessionRecorder(getSession) {
8
8
  const session = getSession();
9
9
  if (!session)
10
10
  return;
11
- void writer.append({ session, entry });
11
+ // Per-call rejections are captured as the writer's sticky first error and
12
+ // surfaced once by flush()/error(); an unhandled rejection here would kill
13
+ // the process on Node >=22 (the sibling paths below do the same).
14
+ void writer.append({ session, entry }).catch(() => undefined);
12
15
  };
13
16
  // Full-history snapshot coalescing (RH-008). conversation_snapshot and
14
17
  // work_state_snapshot entries are large and only the latest of each is ever
@@ -21,12 +24,10 @@ export function createSessionRecorder(getSession) {
21
24
  let conversationInFlight = false;
22
25
  let workStateInFlight = false;
23
26
  const writeConversation = (snapshot) => {
24
- const session = getSession();
25
- if (!session)
26
- return;
27
+ const { session, messages, at, selection } = snapshot;
27
28
  conversationInFlight = true;
28
29
  void writer
29
- .append({ session, entry: { type: 'conversation_snapshot', at: snapshot.at, messages: snapshot.messages } })
30
+ .append({ session, entry: { type: 'conversation_snapshot', at, messages, ...(selection ? { selection } : {}) } })
30
31
  .catch(() => undefined)
31
32
  .finally(() => {
32
33
  conversationInFlight = false;
@@ -61,19 +62,38 @@ export function createSessionRecorder(getSession) {
61
62
  writeWorkState(snapshot);
62
63
  };
63
64
  let lastModelSelection;
65
+ function recordModelSelection(selection) {
66
+ const session = getSession();
67
+ if (!session || (lastModelSelection?.session === session && lastModelSelection.provider === selection.provider && lastModelSelection.model === selection.model && lastModelSelection.endpointFingerprint === selection.endpointFingerprint))
68
+ return;
69
+ lastModelSelection = { session, ...selection };
70
+ appendEntry({ type: 'model_selection', at: new Date().toISOString(), selection });
71
+ }
64
72
  return {
65
- recordModelSelection(selection) {
73
+ recordModelSelection,
74
+ recordModelTransition(messages, selection) {
75
+ // Snapshot and selection must survive a crash together. Drop superseded
76
+ // queued snapshots before enqueuing the atomic transition record.
66
77
  const session = getSession();
67
- if (!session || (lastModelSelection?.session === session && lastModelSelection.provider === selection.provider && lastModelSelection.model === selection.model))
78
+ if (!session)
68
79
  return;
80
+ if (pendingConversation && pendingConversation.session !== session) {
81
+ const pending = pendingConversation;
82
+ void writer.append({ session: pending.session, entry: { type: 'conversation_snapshot', at: pending.at, messages: pending.messages, ...(pending.selection ? { selection: pending.selection } : {}) } }).catch(() => undefined);
83
+ }
84
+ pendingConversation = undefined;
85
+ appendEntry({ type: 'conversation_snapshot', at: new Date().toISOString(), messages, selection });
69
86
  lastModelSelection = { session, ...selection };
70
- appendEntry({ type: 'model_selection', at: new Date().toISOString(), selection });
71
87
  },
72
88
  recordUiMessage(message) {
73
89
  appendEntry({ type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
74
90
  },
75
91
  recordConversation(messages) {
76
- pendingConversation = { messages, at: new Date().toISOString() };
92
+ const session = getSession();
93
+ if (!session)
94
+ return;
95
+ const selection = lastModelSelection?.session === session ? { provider: lastModelSelection.provider, model: lastModelSelection.model, ...(lastModelSelection.endpointFingerprint ? { endpointFingerprint: lastModelSelection.endpointFingerprint } : {}) } : undefined;
96
+ pendingConversation = { session, messages, at: new Date().toISOString(), ...(selection ? { selection } : {}) };
77
97
  drainConversation();
78
98
  },
79
99
  recordWorkState(state) {
@@ -19,6 +19,8 @@ export interface StartupSequenceOptions {
19
19
  /** Reloads the skill registry (also reports project-skill and error signatures). */
20
20
  refreshSkills: () => Promise<unknown>;
21
21
  addSystemMessage: (text: string) => void;
22
+ /** Notified only when the background graph build actually starts/finishes. */
23
+ onGraphActivity?: (building: boolean) => void;
22
24
  }
23
25
  /**
24
26
  * The chat screen's startup sequence, extracted so ChatScreen stays rendering
@@ -4,6 +4,7 @@ import { readContextFiles } from '../../config/contextFiles.js';
4
4
  import { readSettings } from '../../config/settings.js';
5
5
  import { checkForUpdate } from '../../config/updateCheck.js';
6
6
  import { detectCheckoutMismatch, formatMismatchWarning, runtimeCapabilities } from '../../utils/buildInfo.js';
7
+ import { ensureGraphInBackground } from '../../core/graph/buildGraph.js';
7
8
  import { startupContextInfo, startupProviderInfo } from './startupInfo.js';
8
9
  const execFile = promisify(execFileCallback);
9
10
  /** Current git branch name for the workspace header, or undefined outside a repo/branch. */
@@ -56,4 +57,9 @@ export async function runStartupSequence(options) {
56
57
  else if (!runtimeCapabilities().goalSupervisorAvailable) {
57
58
  options.addSystemMessage('Warning: this haze build lacks the goal supervisor module; exhausting a turn step/tool budget may pause the goal instead of continuing automatically. Reinstall or relink haze (npm run dev:link in the checkout).');
58
59
  }
60
+ // Keep the workspace code graph warm without blocking startup: a single
61
+ // background build on every startup — creating the graph when none exists
62
+ // yet, incrementally refreshing it afterwards. Failures are silent here;
63
+ // the graph tools surface `graph_not_built` with a hint.
64
+ void ensureGraphInBackground({ onActivity: options.onGraphActivity });
59
65
  }
@@ -52,9 +52,15 @@ export function partitionDisplayMessages(messages) {
52
52
  }
53
53
  return;
54
54
  }
55
- // Marked may still reclassify the final root while the stream grows. Keep
56
- // only that root dynamic; every preceding root is now safe to append once.
57
- const staticChunkCount = message.streaming ? Math.max(0, chunks.length - 1) : chunks.length;
55
+ // A partial first line of the last root can still join the previous root:
56
+ // for example, a bare "2" after a list becomes its next item when ". "
57
+ // arrives. Wait for that line to finish before committing the prior root.
58
+ const lastChunk = chunks.at(-1) ?? '';
59
+ const newline = lastChunk.indexOf('\n');
60
+ // Marked can synthesize a trailing newline for an unfinished list marker.
61
+ const lastChunkHasCompleteLine = newline >= 0 && (newline < lastChunk.length - 1 || message.text.endsWith('\n'));
62
+ const pendingChunks = lastChunkHasCompleteLine ? 1 : 2;
63
+ const staticChunkCount = message.streaming ? Math.max(0, chunks.length - pendingChunks) : chunks.length;
58
64
  for (let chunkIndex = 0; chunkIndex < staticChunkCount; chunkIndex++) {
59
65
  staticItems.push({
60
66
  kind: 'assistant-markdown',
@@ -69,7 +75,7 @@ export function partitionDisplayMessages(messages) {
69
75
  reachedDynamicTail = true;
70
76
  streamingItems.push({
71
77
  key,
72
- message: { ...message, text: chunks.at(-1) ?? message.text },
78
+ message: { ...message, text: chunks.slice(staticChunkCount).join('') },
73
79
  showHeader: staticChunkCount === 0,
74
80
  });
75
81
  }
@@ -1,13 +1,14 @@
1
1
  import { setProviderAuth, removeProviderAuth } from '../../../config/providerAuth.js';
2
- import { findProvider, modelSelector, resolveModelSelector, upsertProvider } from '../../../config/providers.js';
2
+ import { findProvider, modelSelector, providerApiKey, resolveModelSelector, upsertProvider } from '../../../config/providers.js';
3
3
  import { discoverProviderModels, ollamaModelLimits } from '../../../config/modelDiscovery.js';
4
- import { findPreset, presetModelLimitsForModels, PROVIDER_PRESETS } from '../../../config/providerPresets.js';
5
- import { isLocalProviderUrl } from '../../../llm/client.js';
4
+ import { findPreset, PROVIDER_PRESETS } from '../../../config/providerPresets.js';
5
+ import { isLocalProvider } from '../../../llm/client.js';
6
6
  import { FALLBACK_LOCAL_CONTEXT_TOKENS } from '../../../core/agent/contextBudget.js';
7
7
  import { PROVIDER_ACTIONS, PROVIDER_CHOICES, MODEL_CHOICES, commaList, isYesConfirmation } from '../../commands/wizardFlow.js';
8
8
  import { chatgptCodexUrlWarning, providerActionResult, providerAppendModels, providerFinishAdd, providerRemove, providerRemoveModels, providerSetImageCapable, providerSetKey } from '../../commands/providerWizard.js';
9
9
  import { startupProviderInfo } from '../startupInfo.js';
10
10
  import { openBrowser, startChatGptBrowserLogin } from '../../../llm/openaiCodexOAuth.js';
11
+ import { startMistralVibeLogin } from '../../../llm/mistralVibeAuth.js';
11
12
  /**
12
13
  * Provider/model wizard handlers: provider picker and actions, preset-driven
13
14
  * add flow (including ChatGPT OAuth), model picker, model discovery, and the
@@ -61,7 +62,7 @@ export function createProviderWizardHandlers(deps, ctx) {
61
62
  setMode('chat');
62
63
  return;
63
64
  }
64
- const provider = { name: input.name, url: input.url, kind: 'chatgpt-codex', models: input.models, ...presetModelLimitsForModels({ name: input.name, url: input.url }, input.models) };
65
+ const provider = { name: input.name, url: input.url, kind: 'chatgpt-codex', models: input.models };
65
66
  await ctx.applySettings({ providers: upsertProvider(deps.settings, provider), provider: provider.name, model: undefined });
66
67
  setProviderDraft({});
67
68
  setSuggestedModels([]);
@@ -80,6 +81,46 @@ export function createProviderWizardHandlers(deps, ctx) {
80
81
  deps.setBusyLabel(deps.idleBusyLabel);
81
82
  }
82
83
  }
84
+ async function loginWithMistral(input) {
85
+ deps.setBusyLabel('Waiting for Mistral sign-in');
86
+ deps.setBusy(true);
87
+ try {
88
+ const login = await startMistralVibeLogin();
89
+ showMessage(`Complete Mistral Vibe sign-in in your browser.\nIf it does not open, visit:\n${login.url}`);
90
+ await openBrowser(login.url);
91
+ const key = await login.complete();
92
+ // Account-specific access may be narrower than the preset. Existing
93
+ // providers retain their explicitly configured models on re-sign-in.
94
+ const listing = input.existing ? undefined : await discoverProviderModels({ url: input.url, key });
95
+ const offered = listing?.status === 'ok' ? input.models.filter(model => listing.models.includes(model)) : [];
96
+ const models = input.existing ? input.models : offered.length ? offered : input.models.slice(0, 1);
97
+ const discovered = listing?.status === 'ok' ? Object.fromEntries(models.flatMap(model => listing.modelLimits?.[model] ? [[model, listing.modelLimits[model]]] : [])) : {};
98
+ const provider = { ...input.existing, name: input.name, url: input.url, key, models, ...(Object.keys(discovered).length ? { discoveredModelLimits: discovered } : {}) };
99
+ if (input.existing) {
100
+ await ctx.applySettings({ providers: upsertProvider(deps.settings, provider) });
101
+ setSelectedProviderName(undefined);
102
+ setMode('chat');
103
+ showMessage(`Mistral Vibe sign-in updated for ${provider.name}. Usage and billing depend on your Mistral plan.`);
104
+ return;
105
+ }
106
+ await ctx.applySettings({ providers: upsertProvider(deps.settings, provider), provider: provider.name, model: undefined });
107
+ setProviderDraft({});
108
+ setSuggestedModels([]);
109
+ setModelProviderFilter(provider.name);
110
+ setMode('model');
111
+ const discoveryNote = offered.length ? ' Suggested models were checked against the account model list.' : ' Model discovery did not confirm the suggested alias; available models depend on your account.';
112
+ showMessage(`Mistral Vibe connected as ${provider.name}. Choose a model explicitly.${discoveryNote} Usage and billing depend on your Mistral plan.`);
113
+ }
114
+ catch (error) {
115
+ showMessage(`Mistral sign-in failed: ${error instanceof Error ? error.message : String(error)}`);
116
+ setProviderDraft({});
117
+ setMode('chat');
118
+ }
119
+ finally {
120
+ deps.setBusy(false);
121
+ deps.setBusyLabel(deps.idleBusyLabel);
122
+ }
123
+ }
83
124
  async function discoverModelsFor(target, fallbackPrompt) {
84
125
  if (!target.name || !target.url) {
85
126
  showMessage('Provider name and URL are required to discover models.');
@@ -97,7 +138,7 @@ export function createProviderWizardHandlers(deps, ctx) {
97
138
  deps.setBusy(true);
98
139
  let result;
99
140
  try {
100
- result = await discoverProviderModels({ url: target.url, key: target.key });
141
+ result = await discoverProviderModels({ url: target.url, key: target.key ?? (existing?.url === target.url ? providerApiKey(deps.settings, existing) : undefined) });
101
142
  }
102
143
  finally {
103
144
  deps.setBusy(false);
@@ -144,6 +185,9 @@ export function createProviderWizardHandlers(deps, ctx) {
144
185
  else if (preset.auth === 'chatgpt-oauth') {
145
186
  await loginWithChatGpt({ name: existingName, url: preset.baseUrl, models: preset.suggestedModels ?? [] });
146
187
  }
188
+ else if (preset.auth === 'mistral-vibe') {
189
+ await loginWithMistral({ name: existingName, url: preset.baseUrl, models: preset.suggestedModels ?? [] });
190
+ }
147
191
  else if (preset.needsApiKey) {
148
192
  setMode('providerAddKey');
149
193
  const keyHint = preset.apiKeyHint ?? (preset.apiKeyEnvVar ? `commonly ${preset.apiKeyEnvVar}` : undefined);
@@ -208,6 +252,10 @@ export function createProviderWizardHandlers(deps, ctx) {
208
252
  await loginWithChatGpt({ name: provider.name, url: provider.url, models: provider.models, existing: provider });
209
253
  return;
210
254
  }
255
+ if (action === PROVIDER_ACTIONS.signInMistral && provider.url === 'https://api.mistral.ai/v1') {
256
+ await loginWithMistral({ name: provider.name, url: provider.url, models: provider.models, existing: provider });
257
+ return;
258
+ }
211
259
  const actionResult = providerActionResult(action, provider);
212
260
  if ('selectedName' in actionResult)
213
261
  setSelectedProviderName(actionResult.selectedName);
@@ -290,13 +338,13 @@ export function createProviderWizardHandlers(deps, ctx) {
290
338
  * Native Ollama enrichment at save time (the one place that knows the exact
291
339
  * model ids being added): /v1/models reports nothing for Ollama, but /api/ps
292
340
  * exposes the actually-loaded runtime context and /api/show the model's
293
- * declared maximum. Probed only for the user's loopback server; the cap for
341
+ * declared maximum. Probed only for the user's local server; the cap for
294
342
  * a declared maximum (which may exceed the VRAM-sized effective window) is
295
343
  * the user's own local fallback setting, defaulting to 32K. Failures are
296
344
  * ignored — providers that are not Ollama simply 404 the /api/* paths.
297
345
  */
298
- async function localNativeLimits(url, models) {
299
- if (!url || !isLocalProviderUrl(url) || models.length === 0)
346
+ async function localNativeLimits(url, models, location) {
347
+ if (!url || !isLocalProvider({ url, location }) || models.length === 0)
300
348
  return {};
301
349
  const conservativeCap = deps.settings.localContextWindowFallbackTokens ?? FALLBACK_LOCAL_CONTEXT_TOKENS;
302
350
  return await ollamaModelLimits({ baseUrl: url, models, conservativeCap }).catch(() => ({}));
@@ -304,7 +352,7 @@ export function createProviderWizardHandlers(deps, ctx) {
304
352
  async function appendModelsToProvider(modelsValue) {
305
353
  const provider = deps.wizard.selectedProviderName ? findProvider(deps.settings, deps.wizard.selectedProviderName) : undefined;
306
354
  if (provider) {
307
- const native = await localNativeLimits(provider.url, commaList(modelsValue));
355
+ const native = await localNativeLimits(provider.url, commaList(modelsValue), provider.location);
308
356
  if (Object.keys(native).length > 0)
309
357
  lastDiscoveredLimits = { ...lastDiscoveredLimits, ...native };
310
358
  }
@@ -1,5 +1,7 @@
1
1
  import { isStoredReasoning, resolveReasoningChoice } from '../../../core/agent/reasoningPolicy.js';
2
2
  import { resolveReasoningCommand } from '../../commands/reasoningCommand.js';
3
+ import { activeModel } from '../../../config/providers.js';
4
+ import { reasoningLevelsForProvider } from '../../../config/providerReasoning.js';
3
5
  import { selectThemeResult } from '../../commands/themesCommand.js';
4
6
  import { SESSION_ACTIONS } from '../../commands/sessionPicker.js';
5
7
  /** Session picker, theme picker, and reasoning picker handlers (tiny single-purpose flows). */
@@ -51,7 +53,9 @@ export function createSessionThemeHandlers(deps, ctx) {
51
53
  return;
52
54
  }
53
55
  const stored = isStoredReasoning(deps.settings.reasoning) ? deps.settings.reasoning : undefined;
54
- const result = resolveReasoningCommand(value, { current: resolveReasoningChoice(hook.get(modelSelector), stored), stored, modelSelector });
56
+ const active = activeModel(deps.settings);
57
+ const supportedLevels = active ? reasoningLevelsForProvider(active.provider, active.model) : [];
58
+ const result = resolveReasoningCommand(value, { current: resolveReasoningChoice(hook.get(modelSelector), stored), stored, modelSelector, supportedLevels });
55
59
  if (result.action === 'set')
56
60
  hook.set(modelSelector, result.setting);
57
61
  else if (result.action === 'reset')