@denizokcu/haze 1.7.10 → 1.7.11

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 (78) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +18 -8
  3. package/dist/buildInfo.json +3 -3
  4. package/dist/cli/chat/BusyBar.d.ts +2 -1
  5. package/dist/cli/chat/BusyBar.js +2 -2
  6. package/dist/cli/chat/chatMetrics.d.ts +25 -0
  7. package/dist/cli/chat/chatMetrics.js +36 -0
  8. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  9. package/dist/cli/chat/sessionLifecycle.js +27 -18
  10. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  11. package/dist/cli/chat/sessionRecorder.js +25 -8
  12. package/dist/cli/chat/transcriptPartition.js +10 -4
  13. package/dist/cli/chat/wizard/providerHandlers.js +57 -9
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +5 -1
  15. package/dist/cli/commands/chat.js +39 -7
  16. package/dist/cli/commands/commandHelp.js +2 -2
  17. package/dist/cli/commands/providerWizard.js +9 -17
  18. package/dist/cli/commands/reasoningCommand.d.ts +1 -0
  19. package/dist/cli/commands/reasoningCommand.js +32 -4
  20. package/dist/cli/commands/runCommand.js +7 -1
  21. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  22. package/dist/cli/commands/streaming/attemptOutcome.js +5 -1
  23. package/dist/cli/commands/streaming/attemptSetup.js +5 -3
  24. package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
  25. package/dist/cli/commands/streaming/goalSupervisor.js +20 -1
  26. package/dist/cli/commands/streaming/streamLoop.js +11 -10
  27. package/dist/cli/commands/streaming.d.ts +2 -0
  28. package/dist/cli/commands/wizardFlow.d.ts +1 -0
  29. package/dist/cli/commands/wizardFlow.js +10 -4
  30. package/dist/cli/index.js +5 -3
  31. package/dist/config/hazeBuild.d.ts +2 -2
  32. package/dist/config/hazeBuild.js +2 -2
  33. package/dist/config/modelDiscovery.d.ts +1 -1
  34. package/dist/config/modelDiscovery.js +8 -8
  35. package/dist/config/{modelCatalog.d.ts → providerModelFacts.d.ts} +13 -2
  36. package/dist/config/{modelCatalog.js → providerModelFacts.js} +145 -21
  37. package/dist/config/providerPresets.d.ts +8 -19
  38. package/dist/config/providerPresets.js +86 -555
  39. package/dist/config/providerReasoning.d.ts +16 -0
  40. package/dist/config/providerReasoning.js +56 -0
  41. package/dist/config/providers.d.ts +4 -0
  42. package/dist/config/providers.js +19 -2
  43. package/dist/config/settings.d.ts +14 -0
  44. package/dist/config/settings.js +5 -0
  45. package/dist/core/agent/events.d.ts +1 -1
  46. package/dist/core/agent/providerTransition.d.ts +8 -0
  47. package/dist/core/agent/providerTransition.js +47 -0
  48. package/dist/core/agent/reasoningPolicy.d.ts +1 -1
  49. package/dist/core/agent/reasoningPolicy.js +4 -2
  50. package/dist/core/limits.d.ts +0 -2
  51. package/dist/core/limits.js +0 -2
  52. package/dist/core/providerContracts.d.ts +9 -8
  53. package/dist/core/providerContracts.js +21 -1
  54. package/dist/core/safety/redaction.js +12 -2
  55. package/dist/core/session/sessionSlimming.js +5 -59
  56. package/dist/core/session/sessionStore.d.ts +4 -0
  57. package/dist/core/session/sessionStore.js +149 -9
  58. package/dist/core/session/snapshotCodec.d.ts +5 -0
  59. package/dist/core/session/snapshotCodec.js +47 -0
  60. package/dist/core/shellOutput/registry.js +2 -46
  61. package/dist/core/subagent/executionProfiles.js +4 -1
  62. package/dist/core/toolOutput/reduction.d.ts +55 -2
  63. package/dist/core/toolOutput/reduction.js +77 -2
  64. package/dist/llm/client.d.ts +4 -2
  65. package/dist/llm/client.js +104 -55
  66. package/dist/llm/hazeTools.d.ts +16 -16
  67. package/dist/llm/mistralReasoning.d.ts +2 -0
  68. package/dist/llm/mistralReasoning.js +17 -0
  69. package/dist/llm/mistralVibeAuth.d.ts +5 -0
  70. package/dist/llm/mistralVibeAuth.js +63 -0
  71. package/dist/llm/requestContext.js +8 -7
  72. package/dist/llm/subagentRunner.js +15 -7
  73. package/dist/llm/toolResultTypes.js +7 -1
  74. package/dist/llm/tools/fetchTool.d.ts +16 -16
  75. package/dist/llm/tools/outputCap.d.ts +2 -7
  76. package/dist/llm/tools/outputCap.js +3 -11
  77. package/dist/llm/tools/replaceInFiles.js +5 -0
  78. package/package.json +14 -8
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.7.11 - 2026-11-06
4
+
5
+ ### Changed
6
+
7
+ - Native fleet size follows the deployment manifest's worker allowance instead of a hardcoded two; deployments that advertise nothing stay conservative at two workers.
8
+ - The busy bar shows live progress for long turns: estimated generation tok/s and fleet workers running or queued.
9
+
3
10
  ## 1.7.10 - 2026-11-05
4
11
 
5
12
  ### Fixed
package/README.md CHANGED
@@ -4,7 +4,11 @@ A minimal LLM harness for your terminal.
4
4
 
5
5
  [![Known Vulnerabilities](https://snyk.io/test/github/DenizOkcu/haze/badge.svg)](https://snyk.io/test/github/DenizOkcu/haze)
6
6
 
7
- ## What's new in 1.7.10
7
+ ## What's new in 1.7.11
8
+
9
+ Fleet size now follows the deployment manifest's worker allowance, and long turns show live generation speed and fleet depth in the busy bar.
10
+
11
+ ### Changes in 1.7.10
8
12
 
9
13
  This patch rebuilds the npm package with matching version and build metadata.
10
14
 
@@ -44,7 +48,7 @@ haze 1.6.0 stops mistaking patient local models for dead streams:
44
48
  haze 1.5.1 improves terminal resizing and reasoning-effort compatibility:
45
49
 
46
50
  - On terminal width changes, haze replays the full settled transcript, including formatted Markdown, at the new width. The input draft and active turn stay mounted. Terminal scrollback is preserved, so older transcript copies can remain there after a replay.
47
- - Local inference endpoints omit reasoning effort by default; providers can explicitly enable or disable it with `capabilities.reasoningEffort`. Hosted OpenAI-compatible endpoints retain pass-through behavior.
51
+ - Unknown local and hosted endpoints omit reasoning effort by default. Providers can configure their supported reasoning levels explicitly.
48
52
  - Unsupported `none`/`minimal` choices for GPT-6+ model names are omitted rather than promoted to a different effort; the provider default applies.
49
53
 
50
54
  ### Highlights from 1.5.0
@@ -125,6 +129,10 @@ On first run, create or choose a provider, then choose your first model:
125
129
 
126
130
  `/provider` sets up any OpenAI-compatible endpoint, such as OpenRouter, OpenAI, LM Studio, Ollama, or a proxy. haze asks for a provider name, base URL, optional API key, and model names. The **OpenAI API Key** preset uses platform API billing. The **OpenAI Subscription** preset instead opens a ChatGPT browser login and uses the Codex Responses endpoint; no pasted session token is required. Its sign-in callback listens on a fixed localhost port (1455) required by the registered client, so a lingering process holding that port blocks sign-in until it exits; retry after freeing the port.
127
131
 
132
+ Cloud presets include a small set of current models; account discovery can expose more. The Ollama, LM Studio, llama.cpp, MLX Server, and vLLM presets do not suggest model names: use the models discovered from your own server, or enter them manually. Custom providers remain available. Preset changes do not modify previously saved providers or their models.
133
+
134
+ The **Mistral Vibe Subscription** preset opens Mistral's browser sign-in and stores the issued API key in Haze's private settings. It uses the regular Mistral API with Vibe's model alias; available models, quota, and any pay-as-you-go charges depend on the selected Mistral account and plan. Existing direct Mistral providers can use **sign in with Mistral Vibe** from their `/provider` actions to replace their key.
135
+
128
136
  `/model` selects the model haze should use. The picker also offers `add models`, which fetches a provider's model list from its OpenAI-compatible `/models` endpoint so you can pick instead of typing; if the endpoint is unavailable you can still type model names. You can also set one directly:
129
137
 
130
138
  ```txt
@@ -147,13 +155,15 @@ Use `/mcp` to connect [Model Context Protocol](https://modelcontextprotocol.io)
147
155
 
148
156
  API keys for HTTP/SSE servers are entered in a masked prompt and sent as `Authorization: Bearer <value>`. Stdio authentication belongs in the command or wrapper; haze does not attach HTTP headers to stdio. Servers persist in `~/.haze/settings.json` under `mcpServers`. Discovery and cleanup have bounded deadlines, failures are isolated, and MCP tools never shadow built-ins.
149
157
 
150
- Saved settings live in `~/.haze/settings.json`. ChatGPT OAuth credentials live separately in `~/.haze/auth.json`; both files use private permissions. Provider keys and MCP headers require HTTPS unless the endpoint uses loopback HTTP (`localhost`, `*.localhost`, `127/8`, or `::1`). Keyless HTTP remains available, and local OpenAI-compatible providers do not need a key. If a settings or authentication file is malformed, haze shows an actionable error instead of treating it as empty. Configure everything inside haze with `/provider`, `/model`, and `/settings`; there are no environment variables to set. Provider presets carry curated per-model metadata (context window and output cap from the models.dev catalog) which the wizard writes into `modelLimits`.
158
+ Saved settings live in `~/.haze/settings.json`. ChatGPT OAuth credentials live separately in `~/.haze/auth.json`; both files use private permissions. Provider keys and MCP headers require HTTPS unless the endpoint uses loopback HTTP (`localhost`, `*.localhost`, `127/8`, or `::1`). Keyless HTTP remains available, and local OpenAI-compatible providers do not need a key. If a settings or authentication file is malformed, haze shows an actionable error instead of treating it as empty. Configure everything inside haze with `/provider`, `/model`, and `/settings`; there are no environment variables to set. Provider presets may carry per-model context and output limits. Live discovery is saved separately as `discoveredModelLimits`, so it can be refreshed without overwriting explicit `modelLimits`; each limit uses the user setting, then discovery, then the preset and catalog. Moving aliases without reliable limits are left unspecified. Previously saved `modelLimits` remain explicit overrides, including limits saved by earlier versions; remove an outdated value to allow discovery to take effect. Private-network endpoints default to local budgeting; set `providers[].location` to `"local"` or `"hosted"` to override detection. Credentialed remote HTTP is still refused.
151
159
 
152
160
  Switch the interface palette with `/themes`. The picker lists every built-in theme — light palettes and oh-my-zsh ports like `robbyrussell`, `af-magic`, and `solarized-dark` — and applies the choice immediately; `/themes <name>` sets one directly. The selection persists as `theme` in `~/.haze/settings.json`, and text already on screen keeps its old colors.
153
161
 
154
- Control reasoning effort with `/reasoning` (alias `/thinking`). The picker or `/reasoning <level>` sets `none`, `minimal`, `low`, `medium`, `high`, or `xhigh` for the active model in this session; it never writes settings. `/reasoning unset` omits the parameter, `/reasoning reset` drops the session override, and `/reasoning status` explains the current choice. Resolution follows run-scoped `--reasoning` → per-model session override → saved global `reasoning` setting → built-in default `low`. The level travels as the AI SDK's portable `reasoning` parameter from the next turn and appears beside the model in the status bar.
162
+ Control reasoning effort with `/reasoning` (alias `/thinking`). The picker and `/reasoning <level>` set a per-model session override, and show only levels known for the active provider and model. `/reasoning off` requests `none` (where supported); `/reasoning unset` omits the parameter and leaves the provider default in control; `/reasoning reset` removes the session override. `/reasoning status` reports the current choice. Resolution follows run-scoped `--reasoning` → per-model session override → saved global `reasoning` setting → built-in `low`. An unsupported explicit setting is reported and omitted, not silently mapped to another level. Mistral Large 4 offers `low`, `medium`, and `high`.
163
+
164
+ For unknown custom endpoints, reasoning is omitted until configured. Set `providers[].reasoningLevels` to an array such as `["none", "low", "high"]`, or set exact-model overrides in `providers[].modelReasoningLevels`, for example `{"my-model": ["low", "high"]}`. An empty array disables the option. `capabilities.reasoningEffort: false` disables it; `true` explicitly enables the standard portable levels. For binary custom servers, set `reasoningFormat` to `"thinking"` (sends `thinking.type` as `enabled` or `disabled`) or `"enable-thinking"` (sends `enable_thinking` as a boolean). The picker shows `none` and `high` as off and on for these formats. Provider defaults are not equivalent to off.
155
165
 
156
- Reasoning effort is capability-gated: `capabilities.reasoningEffort: true|false` on a provider explicitly enables or disables sending it. Without an override, local inference endpoints recognized by haze (`localhost`, `127.0.0.1`, `::1`, `0.0.0.0`, and `.local` hosts) omit it; hosted endpoints retain pass-through behavior. This avoids local servers interpreting unsupported levels as reasoning being enabled. Omission leaves the server's own default in control; it does not guarantee reasoning is off. For bare GPT-6+ model names, `minimal` is omitted, and `none` is omitted except for exactly `gpt-6-sol` and `gpt-6-luna`; unsupported choices are never silently promoted. The `reasoning_policy` stream event reports the effective policy.
166
+ Workers use the lowest known supported level, or the provider default when it is unknown. Compaction follows the active model's policy. OpenRouter uses its provider adapter to preserve structured reasoning data across tool calls. Session snapshots retain conversation content, tool outputs, attached file bytes, and provider continuation metadata in private session files; optional session secret redaction can still modify saved strings. Large snapshots use checksummed chunks, with a 64 MiB maximum per snapshot. When switching models or provider endpoints, haze converts previous tool calls and results to labeled conversation text and clears provider-specific reasoning and signatures before the new model sees the history. Resuming an older session without an endpoint fingerprint also establishes this boundary.
157
167
 
158
168
  haze focuses on chat, local tools, context files, sessions, and Markdown skills. Use `/skills` for workflows outside that core. Its interactive picker can generate a skill from a description, then enable, disable, validate, or remove it. For reviews, release prep, deploy checks, debugging routines, or a team-specific checklist, ask haze to create a skill and edit the resulting Markdown as needed.
159
169
 
@@ -478,7 +488,7 @@ haze saves durable workspace sessions in `~/.haze/sessions`. It writes a session
478
488
 
479
489
  Snapshots are written at turn boundaries, not per tool call. If haze crashes or is killed mid-turn, the session resumes from the last completed turn: work already on disk (file edits, command side effects) is not reflected in the session record, so after a crash verify the working tree (`git status`, `git diff`) before continuing. To keep long sessions from growing quadratically — every turn appends the full history again — session files are automatically compacted once superseded snapshots dominate the file: only the newest conversation and work-state snapshots are kept and the file is rewritten atomically.
480
490
 
481
- Session files are optimized for resume and audit, not token-by-token playback: completed user/assistant messages, tool lifecycle events, conversation snapshots, and work-state snapshots are persisted, but streaming `message_update` events are skipped. Large persisted tool outputs are replaced with previews and byte counts so a resumed model can reread current files instead of carrying stale megabytes forward.
491
+ Session files are optimized for resume and audit, not token-by-token playback: completed user/assistant messages, tool lifecycle events, conversation snapshots, and work-state snapshots are persisted, but streaming `message_update` events are skipped. Conversation snapshots preserve tool outputs and attachments; separate tool lifecycle events use bounded previews and byte counts.
482
492
 
483
493
  Long turns use bounded tool slices. Older successful tool results are compacted while failures and recent evidence remain verbatim, synthetic haze control nudges are not persisted as user requests, and token-pressure compaction preserves the structured work state.
484
494
 
@@ -503,8 +513,8 @@ Most haze behaviour needs no configuration; a few optional keys in `~/.haze/sett
503
513
  - `contextWindowFallbackTokens` / `localContextWindowFallbackTokens` (default 128K hosted / 32K local): context-window guess for models without limits metadata or a curated catalog entry. Every turn emits a `context_budget` event naming the window and its source, and the interactive warning fires once per model per session when the built-in default was used.
504
514
  - `manualCompaction` (`"llm-summary"` default, or `"heuristic"`): whether manual `/compact` asks the active model for a continuity summary or keeps the model-free bounded excerpt.
505
515
  - `theme` (string, default `purple`): name of a built-in palette (`/themes` lists and sets them, with `light` and oh-my-zsh ports like `robbyrussell` included). Unknown names fail loudly at startup with the valid names listed.
506
- - `reasoning` (`"none"` | `"minimal"` | `"low"` | `"medium"` | `"high"` | `"xhigh"` | `"provider-default"`, default `low`): saved global fallback for the portable reasoning parameter. Run-scoped and per-model session choices take precedence. The `provider-default` sentinel omits the parameter; `/reasoning` changes only the in-memory session choice.
507
- - `providers[].capabilities.reasoningEffort` (optional boolean): explicitly allow or omit reasoning effort for that provider. Without it, local inference endpoints omit the parameter and hosted OpenAI-compatible endpoints pass it through, subject to model-specific restrictions.
516
+ - `reasoning` (`"none"` | `"minimal"` | `"low"` | `"medium"` | `"high"` | `"xhigh"` | `"max"` | `"provider-default"`, default `low`): saved global fallback for the portable reasoning parameter. Run-scoped and per-model session choices take precedence. The `provider-default` sentinel omits the parameter; `/reasoning` changes only the in-memory session choice.
517
+ - `providers[].capabilities.reasoningEffort` (optional boolean): explicitly allow standard levels or omit reasoning effort. Unknown providers omit the parameter unless configured. `reasoningLevels`, `modelReasoningLevels`, and `reasoningFormat` configure custom endpoints as described above.
508
518
 
509
519
  ## Safety model
510
520
 
@@ -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.11",
4
+ "commit": "de1e7b5cc887745279fb91922b73c2e7e8c43d8e",
5
+ "builtAt": "2026-11-06T20:54:34.136Z"
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
+ }
@@ -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,11 @@
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';
3
4
  import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
4
5
  import { COMPACTION_LLM_MAX_OUTPUT_TOKENS } from '../../core/agent/budgets.js';
5
6
  import { clearToolOutputs } from '../../core/agent/toolOutputStore.js';
6
- import { modelWithConfig } from '../../llm/client.js';
7
+ import { modelWithConfig, providerRequestSettings } from '../../llm/client.js';
8
+ import { auxiliaryRequestOptions } from '../../core/providerContracts.js';
7
9
  import { createSession, findSession, forkSession, formatSession, latestSession, restoreSessionState } from '../../core/session/sessionStore.js';
8
10
  import { createLog as createLlmLog, endLog as endLlmLog } from '../../core/log/llmLog.js';
9
11
  import { displayMessagesFromConversation, estimateConversationTokens } from './chatMetrics.js';
@@ -56,21 +58,26 @@ export function createSessionLifecycle(deps) {
56
58
  applyRedactionSetting(session);
57
59
  deps.sessionRef.current = session;
58
60
  deps.onModelSelection?.(modelSelection);
59
- if (!modelSelection) {
61
+ const currentSelection = deps.modelSelection?.();
62
+ const endpointChanged = Boolean(currentSelection?.endpointFingerprint && (!modelSelection?.endpointFingerprint || modelSelection.endpointFingerprint !== currentSelection.endpointFingerprint));
63
+ const restoredConversation = endpointChanged ? transitionProviderConversation(conversation) : conversation;
64
+ if (!modelSelection && !endpointChanged) {
60
65
  const selection = deps.modelSelection?.();
61
66
  if (selection)
62
67
  deps.sessionRecorder()?.recordModelSelection(selection);
63
68
  }
64
- deps.conversationRef.current = conversation;
69
+ deps.conversationRef.current = restoredConversation;
70
+ if (endpointChanged && currentSelection)
71
+ deps.sessionRecorder()?.recordModelTransition(restoredConversation, currentSelection);
65
72
  deps.clearLiveMessages();
66
- const restoredMessages = displayMessagesFromConversation(conversation);
73
+ const restoredMessages = displayMessagesFromConversation(restoredConversation);
67
74
  deps.setTokenUsage({ ...EMPTY_TOKEN_USAGE, messages: estimateConversationTokens(restoredMessages).input, outputEstimate: estimateConversationTokens(restoredMessages).output });
68
75
  deps.workStateRef.current = workState;
69
76
  for (const error of parseErrors) {
70
77
  deps.debugLog(`Session parse error: ${error}`);
71
78
  }
72
79
  deps.setMessages(messages => {
73
- const restored = [{ role: 'system', text: `Resumed session: ${formatSession(session)}` }, ...restoredMessages];
80
+ 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
81
  return replaceTranscript ? restored : [...messages, ...restored];
75
82
  });
76
83
  // P1 resume path: a durable, unterminated goal frontier surfaces in the
@@ -210,26 +217,26 @@ export function createSessionLifecycle(deps) {
210
217
  // A submission/session change while the summary was pending must not be
211
218
  // overwritten — the stale compaction is reported and discarded instead.
212
219
  const sessionAtStart = deps.sessionRef.current;
220
+ const isStale = () => deps.sessionRef.current !== sessionAtStart || deps.conversationRef.current !== messages;
221
+ const discardStale = () => {
222
+ deps.setMessages(m => [...m, { role: 'system', text: 'Compaction result discarded: the session or conversation changed while the summary was being written.' }]);
223
+ return false;
224
+ };
213
225
  try {
214
226
  const selection = deps.modelSelection?.();
215
- const runtime = await modelWithConfig(selection ? { modelSelector: `${selection.provider}:${selection.model}` } : undefined);
227
+ const runtime = await modelWithConfig({ ...(selection ? { modelSelector: `${selection.provider}:${selection.model}` } : {}), reasoningByModel: deps.reasoningByModel?.() });
216
228
  if (!runtime?.model)
217
229
  throw new Error('no model provider configured');
218
- const summarization = await generateText({
230
+ const providerSettings = auxiliaryRequestOptions(providerRequestSettings(runtime.config), runtime.config.capabilities, 'compaction', COMPACTION_LLM_MAX_OUTPUT_TOKENS);
231
+ const summarization = streamText({
219
232
  model: runtime.model,
233
+ ...providerSettings,
220
234
  prompt: buildLlmCompactionPrompt({ older: split.older, instructions }),
221
- maxOutputTokens: COMPACTION_LLM_MAX_OUTPUT_TOKENS,
222
235
  abortSignal: AbortSignal.timeout(COMPACT_SUMMARY_TIMEOUT_MS),
223
236
  });
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();
237
+ const summaryText = (await summarization.text).trim();
238
+ if (isStale())
239
+ return discardStale();
233
240
  if (!summaryText)
234
241
  throw new Error('model returned an empty summary');
235
242
  const result = compactModelMessagesWithSummary(messages, { summaryText, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS, instructions, workState: deps.workStateRef.current });
@@ -243,6 +250,8 @@ export function createSessionLifecycle(deps) {
243
250
  return true;
244
251
  }
245
252
  catch (error) {
253
+ if (isStale())
254
+ return discardStale();
246
255
  deps.debugLog(`LLM compaction failed (${error instanceof Error ? error.message : String(error)}); falling back to the heuristic excerpt`);
247
256
  return compactConversationSync(instructions);
248
257
  }
@@ -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;
@@ -21,12 +21,10 @@ export function createSessionRecorder(getSession) {
21
21
  let conversationInFlight = false;
22
22
  let workStateInFlight = false;
23
23
  const writeConversation = (snapshot) => {
24
- const session = getSession();
25
- if (!session)
26
- return;
24
+ const { session, messages, at, selection } = snapshot;
27
25
  conversationInFlight = true;
28
26
  void writer
29
- .append({ session, entry: { type: 'conversation_snapshot', at: snapshot.at, messages: snapshot.messages } })
27
+ .append({ session, entry: { type: 'conversation_snapshot', at, messages, ...(selection ? { selection } : {}) } })
30
28
  .catch(() => undefined)
31
29
  .finally(() => {
32
30
  conversationInFlight = false;
@@ -61,19 +59,38 @@ export function createSessionRecorder(getSession) {
61
59
  writeWorkState(snapshot);
62
60
  };
63
61
  let lastModelSelection;
62
+ function recordModelSelection(selection) {
63
+ const session = getSession();
64
+ if (!session || (lastModelSelection?.session === session && lastModelSelection.provider === selection.provider && lastModelSelection.model === selection.model && lastModelSelection.endpointFingerprint === selection.endpointFingerprint))
65
+ return;
66
+ lastModelSelection = { session, ...selection };
67
+ appendEntry({ type: 'model_selection', at: new Date().toISOString(), selection });
68
+ }
64
69
  return {
65
- recordModelSelection(selection) {
70
+ recordModelSelection,
71
+ recordModelTransition(messages, selection) {
72
+ // Snapshot and selection must survive a crash together. Drop superseded
73
+ // queued snapshots before enqueuing the atomic transition record.
66
74
  const session = getSession();
67
- if (!session || (lastModelSelection?.session === session && lastModelSelection.provider === selection.provider && lastModelSelection.model === selection.model))
75
+ if (!session)
68
76
  return;
77
+ if (pendingConversation && pendingConversation.session !== session) {
78
+ const pending = pendingConversation;
79
+ void writer.append({ session: pending.session, entry: { type: 'conversation_snapshot', at: pending.at, messages: pending.messages, ...(pending.selection ? { selection: pending.selection } : {}) } }).catch(() => undefined);
80
+ }
81
+ pendingConversation = undefined;
82
+ appendEntry({ type: 'conversation_snapshot', at: new Date().toISOString(), messages, selection });
69
83
  lastModelSelection = { session, ...selection };
70
- appendEntry({ type: 'model_selection', at: new Date().toISOString(), selection });
71
84
  },
72
85
  recordUiMessage(message) {
73
86
  appendEntry({ type: 'ui_message', at: new Date().toISOString(), role: message.role, text: message.text });
74
87
  },
75
88
  recordConversation(messages) {
76
- pendingConversation = { messages, at: new Date().toISOString() };
89
+ const session = getSession();
90
+ if (!session)
91
+ return;
92
+ const selection = lastModelSelection?.session === session ? { provider: lastModelSelection.provider, model: lastModelSelection.model, ...(lastModelSelection.endpointFingerprint ? { endpointFingerprint: lastModelSelection.endpointFingerprint } : {}) } : undefined;
93
+ pendingConversation = { session, messages, at: new Date().toISOString(), ...(selection ? { selection } : {}) };
77
94
  drainConversation();
78
95
  },
79
96
  recordWorkState(state) {
@@ -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')