@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
@@ -1,13 +1,19 @@
1
1
  import { createOpenAI } from '@ai-sdk/openai';
2
2
  import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
3
+ import { createOpenRouter } from '@openrouter/ai-sdk-provider';
3
4
  import { discoverHazeBuildManifest } from '../config/hazeBuild.js';
4
5
  import { createHazeBuildModel } from './hazeBuild.js';
6
+ import { isMistralApi, reasoningLevelsForProvider, resolveProviderReasoning } from '../config/providerReasoning.js';
7
+ import { mistralRequestBody } from './mistralReasoning.js';
5
8
  import crypto from 'node:crypto';
9
+ import { isIP } from 'node:net';
6
10
  import { readSettings } from '../config/settings.js';
7
- import { catalogLimitsFor } from '../config/modelCatalog.js';
8
- import { activeModel, modelSelector, resolveModelSelector } from '../config/providers.js';
9
- import { assertCredentialedEndpointSecure } from '../config/endpointSecurity.js';
10
- import { effectiveRequestedReasoning, isStoredReasoning, reasoningCallSetting, resolveAttemptReasoning, resolveReasoningPolicy } from '../core/agent/reasoningPolicy.js';
11
+ import { catalogLimitsFor } from '../config/providerModelFacts.js';
12
+ import { ollamaModelLimits } from '../config/modelDiscovery.js';
13
+ import { presetModelLimitsForModels } from '../config/providerPresets.js';
14
+ import { activeModel, modelSelector, providerApiKey, resolveModelSelector } from '../config/providers.js';
15
+ import { assertCredentialedEndpointSecure, isLoopbackHostname } from '../config/endpointSecurity.js';
16
+ import { effectiveRequestedReasoning, isStoredReasoning, reasoningCallSetting, resolveAttemptReasoning, REASONING_LEVELS } from '../core/agent/reasoningPolicy.js';
11
17
  import { FALLBACK_CONTEXT_WINDOW_TOKENS, FALLBACK_LOCAL_CONTEXT_TOKENS } from '../core/agent/contextBudget.js';
12
18
  import { createChatGptCodexFetch } from './openaiCodex.js';
13
19
  const HAZE_SITE_URL = 'https://github.com/DenizOkcu/haze';
@@ -16,8 +22,24 @@ const HAZE_TITLE = 'Haze';
16
22
  // replaces authentication. Generate a non-credential sentinel at runtime so
17
23
  // static scanners cannot mistake a fixed placeholder for a shipped secret.
18
24
  const OAUTH_SDK_SENTINEL = `oauth-sentinel-${crypto.randomUUID()}`;
19
- function isOpenRouter(providerName, baseURL) {
20
- return providerName === 'openrouter' || /openrouter\.ai/i.test(baseURL);
25
+ function isOpenRouter(_providerName, baseURL) {
26
+ try {
27
+ return new URL(baseURL).hostname.toLowerCase() === 'openrouter.ai';
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ /** Groq Qwen requires parsed reasoning when tools are present. */
34
+ function groqRequestTransform(baseURL, model) {
35
+ try {
36
+ if (new URL(baseURL).hostname.toLowerCase() !== 'api.groq.com' || model.toLowerCase() !== 'qwen/qwen3.8-27b')
37
+ return undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ return body => Array.isArray(body.tools) && body.tools.length ? { ...body, reasoning_format: 'parsed' } : body;
21
43
  }
22
44
  function openRouterHeaders(providerName, baseURL) {
23
45
  if (!isOpenRouter(providerName, baseURL))
@@ -28,19 +50,21 @@ function openRouterHeaders(providerName, baseURL) {
28
50
  };
29
51
  }
30
52
  /** True when the endpoint is OpenAI's own API, not a gateway/local server speaking the compatible subset. */
31
- function isDirectOpenAi(providerName, baseURL, providerKind) {
32
- return providerKind !== 'chatgpt-codex' && (providerName === 'openai' || /api\.openai\.com/i.test(baseURL));
53
+ function isDirectOpenAi(_providerName, baseURL, providerKind) {
54
+ try {
55
+ return providerKind !== 'chatgpt-codex' && new URL(baseURL).hostname.toLowerCase() === 'api.openai.com';
56
+ }
57
+ catch {
58
+ return false;
59
+ }
33
60
  }
34
- function capabilities(providerName, baseURL, providerKind, explicit) {
61
+ function capabilities(provider, modelName) {
62
+ const { name: providerName, url: baseURL, kind: providerKind } = provider;
35
63
  const directOpenAI = isDirectOpenAi(providerName, baseURL, providerKind);
36
64
  const openRouter = isOpenRouter(providerName, baseURL);
37
- // Reasoning-effort support is explicit-first: a user override wins either
38
- // way. Otherwise loopback/local inference servers (LM Studio, Ollama,
39
- // llama.cpp) default to `false`: their own reasoning switches coerce
40
- // unsupported levels — even `none` — to `on` (LM Studio), inverting the
41
- // request, and subagent workers rely on `none` meaning off. Hosted
42
- // OpenAI-compatible endpoints keep the SDK pass-through (`true`).
43
- const supportsReasoningEffort = explicit?.reasoningEffort ?? (providerKind === 'haze-build' || !isLocalProviderUrl(baseURL));
65
+ // The same profile drives UI choices, main requests, and worker defaults.
66
+ const levels = reasoningLevelsForProvider(provider, modelName);
67
+ const supportsReasoningEffort = levels.length > 0;
44
68
  return {
45
69
  reportsCacheUsage: providerKind === 'haze-build' || directOpenAI || openRouter,
46
70
  supportsPromptCacheKey: directOpenAI,
@@ -49,45 +73,40 @@ function capabilities(providerName, baseURL, providerKind, explicit) {
49
73
  supportsServerCompaction: false,
50
74
  supportsTextVerbosity: directOpenAI,
51
75
  supportsReasoningEffort,
76
+ ...(openRouter ? { reasoningTransport: 'openrouter' } : {}),
77
+ ...(supportsReasoningEffort && (!openRouter || provider.reasoningLevels || provider.modelReasoningLevels?.[modelName]) ? { workerReasoningEffort: REASONING_LEVELS.find(level => levels.includes(level)) } : {}),
52
78
  ...(providerKind === 'haze-build' ? { supportsBinaryThinking: true } : {}),
53
79
  };
54
80
  }
55
- /**
56
- * Match the pinned OpenAI SDK's GPT-6+ effort restrictions before transport.
57
- * Unsupported choices are omitted, not promoted to a different effort; the
58
- * policy retains the request and explains why the provider default will apply.
59
- */
60
- function reasoningPolicyForModel(modelName, requested, caps) {
61
- const policy = resolveReasoningPolicy({ requested, capabilities: caps });
62
- if (policy.effective === 'disabled')
63
- return policy;
64
- const version = /^gpt-(\d+)(?:\.\d+)?(?:-.+)?$/.exec(modelName);
65
- const supportsNone = modelName === 'gpt-6-sol' || modelName === 'gpt-6-luna';
66
- if (version && Number(version[1]) >= 6 && (requested === 'minimal' || (requested === 'none' && !supportsNone))) {
67
- return { requested, effective: 'disabled', reason: `${modelName} does not support reasoning effort ${requested}; parameter omitted (provider default). Choose low, medium, high, xhigh, or unset.` };
68
- }
69
- return policy;
70
- }
71
81
  /** True for loopback/local inference servers, whose effective window is server-configured (often far below the model's). */
72
82
  export function isLocalProviderUrl(url) {
73
83
  try {
74
84
  const hostname = new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g, '');
75
- return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '0.0.0.0' || hostname.endsWith('.local');
85
+ if (isLoopbackHostname(hostname) || hostname === '0.0.0.0' || hostname.endsWith('.local'))
86
+ return true;
87
+ if (isIP(hostname) === 4) {
88
+ const [a, b] = hostname.split('.').map(Number);
89
+ return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254);
90
+ }
91
+ return isIP(hostname) === 6 && /^(?:f[cd]|fe[89ab])/i.test(hostname);
76
92
  }
77
93
  catch {
78
94
  return false;
79
95
  }
80
96
  }
81
- function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessionReasoningByModel, deployment) {
97
+ export function isLocalProvider(provider) {
98
+ return provider.location ? provider.location === 'local' : isLocalProviderUrl(provider.url);
99
+ }
100
+ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessionReasoningByModel, deployment, freshLocalLimits) {
82
101
  const baseURL = selection.provider.url;
83
102
  const providerKind = selection.provider.kind;
84
- const configuredKey = providerKind === 'chatgpt-codex' ? undefined : selection.provider.key ?? settings.apiKey;
103
+ const configuredKey = providerKind === 'chatgpt-codex' ? undefined : providerApiKey(settings, selection.provider);
85
104
  assertCredentialedEndpointSecure(baseURL, configuredKey);
86
105
  const apiKey = configuredKey ?? 'not-needed';
87
106
  const name = selection.model;
88
107
  const cacheSeed = cwd ?? process.cwd();
89
108
  const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
90
- const caps = capabilities(selection.provider.name, baseURL, providerKind, selection.provider.capabilities);
109
+ const caps = capabilities(selection.provider, name);
91
110
  const selector = modelSelector(selection.provider, name);
92
111
  // The full precedence chain lives in one pure resolver
93
112
  // (`resolveAttemptReasoning`): run-scoped override → session per-model map →
@@ -102,25 +121,30 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessio
102
121
  globalSetting: isStoredReasoning(settings.reasoning) ? settings.reasoning : undefined,
103
122
  });
104
123
  const requestedReasoning = effectiveRequestedReasoning(storedReasoning);
105
- const resolvedPolicy = reasoningPolicyForModel(name, requestedReasoning, caps);
124
+ const resolvedPolicy = resolveProviderReasoning(selection.provider, name, requestedReasoning);
106
125
  const reasoningPolicy = deployment && resolvedPolicy.effective !== 'disabled'
107
126
  ? { ...resolvedPolicy, reason: `haze.build binary thinking ${requestedReasoning === 'none' ? 'off' : 'on'}; effort levels do not imply different compute budgets` }
108
127
  : resolvedPolicy;
109
- // Transport split mirrors the wire reality: OpenAI's own endpoints and the
110
- // codex OAuth kind ride @ai-sdk/openai (Responses access, `prompt_cache_key`,
111
- // catalog effort remapping); every other endpoint — gateways, local servers,
112
- // custom proxies — speaks the compatible subset and rides
113
- // @ai-sdk/openai-compatible. `includeUsage` is mandatory there: the openai
114
- // package always streams `include_usage` and context estimation depends on
115
- // provider usage. Reasoning levels pass through verbatim (no catalog remap).
128
+ // Preserve native reasoning continuation on Responses and OpenRouter.
116
129
  const headers = openRouterHeaders(selection.provider.name, baseURL);
130
+ const customFormat = selection.provider.reasoningFormat;
131
+ const transformRequestBody = customFormat === 'thinking' || customFormat === 'enable-thinking'
132
+ ? (body) => {
133
+ if (typeof body.reasoning_effort !== 'string')
134
+ return body;
135
+ const { reasoning_effort: effort, ...rest } = body;
136
+ return customFormat === 'thinking' ? { ...rest, thinking: { type: effort === 'none' ? 'disabled' : 'enabled' } } : { ...rest, enable_thinking: effort !== 'none' };
137
+ }
138
+ : isMistralApi(baseURL) ? mistralRequestBody : groqRequestTransform(baseURL, name);
117
139
  const model = deployment
118
140
  ? createHazeBuildModel({ baseURL, apiKey, manifest: deployment })
119
141
  : providerKind === 'chatgpt-codex'
120
142
  ? createOpenAI({ apiKey: OAUTH_SDK_SENTINEL, baseURL, fetch: createChatGptCodexFetch(selection.provider.name) }).responses(name)
121
143
  : isDirectOpenAi(selection.provider.name, baseURL, providerKind)
122
- ? createOpenAI({ apiKey, baseURL, headers }).chat(name)
123
- : createOpenAICompatible({ name: selection.provider.name, baseURL, apiKey, headers, includeUsage: true }).chatModel(name);
144
+ ? /^gpt-6(?:\.|-)/i.test(name) ? createOpenAI({ apiKey, baseURL, headers }).responses(name) : createOpenAI({ apiKey, baseURL, headers }).chat(name)
145
+ : isOpenRouter(selection.provider.name, baseURL)
146
+ ? createOpenRouter({ apiKey, baseURL, headers, compatibility: 'strict' }).chat(name)
147
+ : createOpenAICompatible({ name: selection.provider.name, baseURL, apiKey, headers, includeUsage: true, ...(transformRequestBody ? { transformRequestBody } : {}) }).chatModel(name);
124
148
  const limits = modelLimitsFor(selection.provider, name);
125
149
  // Class-aware fallback so unknown local models (server-configured window,
126
150
  // silent truncation) stay conservative while unknown hosted models get the
@@ -130,16 +154,22 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessio
130
154
  // overrides the built-in default; the source tag distinguishes an
131
155
  // intentional guess (no warning) from the default guess (warned once per
132
156
  // session) (RH-005).
133
- const isLocal = isLocalProviderUrl(baseURL);
157
+ const isLocal = isLocalProvider(selection.provider);
158
+ // Local loaded context can change on restart; a persisted discovery is only a
159
+ // hint to re-probe, never a safe runtime budget on its own.
160
+ const discovered = isLocal ? freshLocalLimits?.[name] : selection.provider.discoveredModelLimits?.[name];
161
+ const preset = isLocal ? undefined : presetModelLimitsForModels(selection.provider, [name])[name];
134
162
  const catalog = isLocal ? undefined : catalogLimitsFor(name);
135
163
  const userFallback = isLocal ? settings.localContextWindowFallbackTokens : settings.contextWindowFallbackTokens;
136
164
  const fallbackTokens = userFallback ?? (isLocal ? FALLBACK_LOCAL_CONTEXT_TOKENS : FALLBACK_CONTEXT_WINDOW_TOKENS);
137
165
  const contextWindowSource = limits.contextWindowTokens !== undefined
138
166
  ? 'settings'
139
- : catalog
140
- ? 'catalog'
141
- : userFallback !== undefined ? 'user-fallback' : 'default-fallback';
142
- const maxOutputTokens = limits.maxOutputTokens ?? catalog?.maxOutputTokens;
167
+ : discovered?.contextWindowTokens !== undefined ? 'discovery'
168
+ : preset?.contextWindowTokens !== undefined ? 'preset'
169
+ : catalog
170
+ ? 'catalog'
171
+ : userFallback !== undefined ? 'user-fallback' : 'default-fallback';
172
+ const maxOutputTokens = limits.maxOutputTokens ?? discovered?.maxOutputTokens ?? preset?.maxOutputTokens ?? catalog?.maxOutputTokens;
143
173
  return {
144
174
  model,
145
175
  selector,
@@ -147,11 +177,12 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessio
147
177
  providerName: selection.provider.name,
148
178
  providerKind,
149
179
  baseURL,
180
+ isLocal,
150
181
  modelName: name,
151
182
  cacheKey,
152
183
  capabilities: caps,
153
184
  reasoningPolicy,
154
- contextWindowTokens: deployment ? Math.min(limits.contextWindowTokens ?? deployment.contextWindowTokens, deployment.contextWindowTokens) : limits.contextWindowTokens ?? catalog?.contextWindowTokens ?? fallbackTokens,
185
+ contextWindowTokens: deployment ? Math.min(limits.contextWindowTokens ?? deployment.contextWindowTokens, deployment.contextWindowTokens) : limits.contextWindowTokens ?? discovered?.contextWindowTokens ?? preset?.contextWindowTokens ?? catalog?.contextWindowTokens ?? fallbackTokens,
155
186
  contextWindowSource: deployment ? 'deployment' : contextWindowSource,
156
187
  ...(deployment ? { deployment, maxOutputTokens: Math.min(limits.maxOutputTokens ?? deployment.maxOutputTokens, deployment.maxOutputTokens),
157
188
  warnings: [
@@ -189,10 +220,17 @@ export async function modelWithConfig(session, settings) {
189
220
  selection = activeModel(resolvedSettings);
190
221
  if (!selection)
191
222
  return undefined;
223
+ assertCredentialedEndpointSecure(selection.provider.url, selection.provider.kind === 'chatgpt-codex' ? undefined : providerApiKey(resolvedSettings, selection.provider));
192
224
  const deployment = selection.provider.kind === 'haze-build' ? await discoverHazeBuildManifest(selection.provider) : undefined;
193
225
  if (deployment && selection.model !== deployment.model)
194
226
  throw new Error(`haze.build currently serves ${deployment.model}; choose it explicitly via /model.`);
195
- return runtimeForSelection(resolvedSettings, selection, session?.cwd, session?.reasoningOverride, session?.reasoningByModel, deployment);
227
+ const freshLocalLimits = await refreshLocalLimits(selection, resolvedSettings);
228
+ return runtimeForSelection(resolvedSettings, selection, session?.cwd, session?.reasoningOverride, session?.reasoningByModel, deployment, freshLocalLimits);
229
+ }
230
+ async function refreshLocalLimits(selection, settings) {
231
+ if (!isLocalProvider(selection.provider) || selection.provider.kind === 'haze-build' || selection.provider.modelLimits?.[selection.model]?.contextWindowTokens !== undefined || !selection.provider.discoveredModelLimits?.[selection.model])
232
+ return undefined;
233
+ return ollamaModelLimits({ baseUrl: selection.provider.url, models: [selection.model], conservativeCap: settings.localContextWindowFallbackTokens ?? FALLBACK_LOCAL_CONTEXT_TOKENS, timeoutMs: 1000 }).catch(() => undefined);
196
234
  }
197
235
  export async function resolveWorkerRuntime(input) {
198
236
  const requested = input.selector?.trim();
@@ -201,6 +239,7 @@ export async function resolveWorkerRuntime(input) {
201
239
  const resolved = resolveModelSelector(input.settings, requested);
202
240
  if (resolved.status !== 'found')
203
241
  return { status: resolved.status, message: resolved.status === 'ambiguous' ? `Worker model ${requested} is ambiguous; use provider:model.` : `Worker model ${requested} is not configured. Configure it via /provider or remove subagents.workerModel.` };
242
+ assertCredentialedEndpointSecure(resolved.provider.url, resolved.provider.kind === 'chatgpt-codex' ? undefined : providerApiKey(input.settings, resolved.provider));
204
243
  // The active deployment was fetched and validated for this attempt. An
205
244
  // explicit worker selecting that same provider/model can reuse it rather
206
245
  // than making a second network round trip; different endpoints still refresh.
@@ -214,9 +253,10 @@ export async function resolveWorkerRuntime(input) {
214
253
  : undefined;
215
254
  if (deployment && resolved.model !== deployment.model)
216
255
  return { status: 'missing', message: `haze.build currently serves ${deployment.model}.` };
217
- selected = runtimeForSelection(input.settings, { provider: resolved.provider, model: resolved.model }, input.cwd, undefined, undefined, deployment);
256
+ const selection = { provider: resolved.provider, model: resolved.model };
257
+ selected = runtimeForSelection(input.settings, selection, input.cwd, undefined, undefined, deployment, await refreshLocalLimits(selection, input.settings));
218
258
  }
219
- return { status: 'found', runtime: { model: selected.model, selector: selected.selector, providerName: selected.config.providerName, capabilities: selected.config.capabilities, requestOptions: providerRequestSettings(selected.config), contextWindowTokens: selected.config.contextWindowTokens, maxOutputTokens: selected.config.maxOutputTokens, ...(selected.config.deployment ? { nativeMaxConcurrency: Math.min(2, selected.config.deployment.activeSequences) } : {}) } };
259
+ return { status: 'found', runtime: { model: selected.model, selector: selected.selector, providerName: selected.config.providerName, capabilities: selected.config.capabilities, requestOptions: providerRequestSettings(selected.config), contextWindowTokens: selected.config.contextWindowTokens, maxOutputTokens: selected.config.maxOutputTokens, ...(selected.config.deployment ? { nativeMaxConcurrency: selected.config.deployment.activeSequences } : {}) } };
220
260
  }
221
261
  export function providerRequestSettings(config) {
222
262
  // Top-level AI SDK `reasoning` setting; the key is omitted entirely when the
@@ -232,12 +272,21 @@ export function providerRequestSettings(config) {
232
272
  ...(reasoning ? { reasoning } : {}),
233
273
  };
234
274
  }
275
+ if (isOpenRouter(config.providerName, config.baseURL))
276
+ return {
277
+ headers: { 'x-session-id': config.cacheKey },
278
+ ...(reasoning ? { providerOptions: { openrouter: { reasoning: { effort: reasoning } } } } : {}),
279
+ };
235
280
  const caps = config.capabilities;
236
281
  const openaiOptions = {};
237
282
  if (caps.supportsPromptCacheKey)
238
283
  openaiOptions.promptCacheKey = config.cacheKey;
239
284
  if (caps.supportsTextVerbosity)
240
285
  openaiOptions.textVerbosity = 'low';
286
+ if (caps.supportsPromptCacheKey && /^gpt-6(?:\.|-)/i.test(config.modelName)) {
287
+ openaiOptions.store = false;
288
+ openaiOptions.include = ['reasoning.encrypted_content'];
289
+ }
241
290
  const providerOptions = Object.keys(openaiOptions).length > 0 ? { openai: openaiOptions } : undefined;
242
291
  return {
243
292
  ...(providerOptions ? { providerOptions } : {}),
@@ -896,7 +896,7 @@ export declare const hazeTools: {
896
896
  } | {
897
897
  handle: string;
898
898
  rawHandle: string;
899
- omittedChars: number;
899
+ omittedChars: number | undefined;
900
900
  rawChars: number;
901
901
  returnedChars: number;
902
902
  rawTokensEstimate: number;
@@ -961,7 +961,7 @@ export declare const hazeTools: {
961
961
  } | {
962
962
  handle: string;
963
963
  rawHandle: string;
964
- omittedChars: number;
964
+ omittedChars: number | undefined;
965
965
  rawChars: number;
966
966
  returnedChars: number;
967
967
  rawTokensEstimate: number;
@@ -1027,7 +1027,7 @@ export declare const hazeTools: {
1027
1027
  } | {
1028
1028
  handle: string;
1029
1029
  rawHandle: string;
1030
- omittedChars: number;
1030
+ omittedChars: number | undefined;
1031
1031
  rawChars: number;
1032
1032
  returnedChars: number;
1033
1033
  rawTokensEstimate: number;
@@ -1112,7 +1112,7 @@ export declare const hazeTools: {
1112
1112
  } | {
1113
1113
  handle: string;
1114
1114
  rawHandle: string;
1115
- omittedChars: number;
1115
+ omittedChars: number | undefined;
1116
1116
  rawChars: number;
1117
1117
  returnedChars: number;
1118
1118
  rawTokensEstimate: number;
@@ -1205,7 +1205,7 @@ export declare const hazeTools: {
1205
1205
  } | {
1206
1206
  handle: string;
1207
1207
  rawHandle: string;
1208
- omittedChars: number;
1208
+ omittedChars: number | undefined;
1209
1209
  rawChars: number;
1210
1210
  returnedChars: number;
1211
1211
  rawTokensEstimate: number;
@@ -1270,7 +1270,7 @@ export declare const hazeTools: {
1270
1270
  } | {
1271
1271
  handle: string;
1272
1272
  rawHandle: string;
1273
- omittedChars: number;
1273
+ omittedChars: number | undefined;
1274
1274
  rawChars: number;
1275
1275
  returnedChars: number;
1276
1276
  rawTokensEstimate: number;
@@ -1336,7 +1336,7 @@ export declare const hazeTools: {
1336
1336
  } | {
1337
1337
  handle: string;
1338
1338
  rawHandle: string;
1339
- omittedChars: number;
1339
+ omittedChars: number | undefined;
1340
1340
  rawChars: number;
1341
1341
  returnedChars: number;
1342
1342
  rawTokensEstimate: number;
@@ -1421,7 +1421,7 @@ export declare const hazeTools: {
1421
1421
  } | {
1422
1422
  handle: string;
1423
1423
  rawHandle: string;
1424
- omittedChars: number;
1424
+ omittedChars: number | undefined;
1425
1425
  rawChars: number;
1426
1426
  returnedChars: number;
1427
1427
  rawTokensEstimate: number;
@@ -1514,7 +1514,7 @@ export declare const hazeTools: {
1514
1514
  } | {
1515
1515
  handle: string;
1516
1516
  rawHandle: string;
1517
- omittedChars: number;
1517
+ omittedChars: number | undefined;
1518
1518
  rawChars: number;
1519
1519
  returnedChars: number;
1520
1520
  rawTokensEstimate: number;
@@ -1579,7 +1579,7 @@ export declare const hazeTools: {
1579
1579
  } | {
1580
1580
  handle: string;
1581
1581
  rawHandle: string;
1582
- omittedChars: number;
1582
+ omittedChars: number | undefined;
1583
1583
  rawChars: number;
1584
1584
  returnedChars: number;
1585
1585
  rawTokensEstimate: number;
@@ -1645,7 +1645,7 @@ export declare const hazeTools: {
1645
1645
  } | {
1646
1646
  handle: string;
1647
1647
  rawHandle: string;
1648
- omittedChars: number;
1648
+ omittedChars: number | undefined;
1649
1649
  rawChars: number;
1650
1650
  returnedChars: number;
1651
1651
  rawTokensEstimate: number;
@@ -1722,7 +1722,7 @@ export declare const hazeTools: {
1722
1722
  } | {
1723
1723
  handle: string;
1724
1724
  rawHandle: string;
1725
- omittedChars: number;
1725
+ omittedChars: number | undefined;
1726
1726
  rawChars: number;
1727
1727
  returnedChars: number;
1728
1728
  rawTokensEstimate: number;
@@ -1815,7 +1815,7 @@ export declare const hazeTools: {
1815
1815
  } | {
1816
1816
  handle: string;
1817
1817
  rawHandle: string;
1818
- omittedChars: number;
1818
+ omittedChars: number | undefined;
1819
1819
  rawChars: number;
1820
1820
  returnedChars: number;
1821
1821
  rawTokensEstimate: number;
@@ -1880,7 +1880,7 @@ export declare const hazeTools: {
1880
1880
  } | {
1881
1881
  handle: string;
1882
1882
  rawHandle: string;
1883
- omittedChars: number;
1883
+ omittedChars: number | undefined;
1884
1884
  rawChars: number;
1885
1885
  returnedChars: number;
1886
1886
  rawTokensEstimate: number;
@@ -1946,7 +1946,7 @@ export declare const hazeTools: {
1946
1946
  } | {
1947
1947
  handle: string;
1948
1948
  rawHandle: string;
1949
- omittedChars: number;
1949
+ omittedChars: number | undefined;
1950
1950
  rawChars: number;
1951
1951
  returnedChars: number;
1952
1952
  rawTokensEstimate: number;
@@ -2023,7 +2023,7 @@ export declare const hazeTools: {
2023
2023
  } | {
2024
2024
  handle: string;
2025
2025
  rawHandle: string;
2026
- omittedChars: number;
2026
+ omittedChars: number | undefined;
2027
2027
  rawChars: number;
2028
2028
  returnedChars: number;
2029
2029
  rawTokensEstimate: number;
@@ -0,0 +1,2 @@
1
+ /** Convert the compatible SDK's reasoning history back to Mistral ThinkChunks. */
2
+ export declare function mistralRequestBody(body: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,17 @@
1
+ /** Convert the compatible SDK's reasoning history back to Mistral ThinkChunks. */
2
+ export function mistralRequestBody(body) {
3
+ if (!Array.isArray(body.messages))
4
+ return body;
5
+ return { ...body, messages: body.messages.map((value) => {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value))
7
+ return value;
8
+ const message = value;
9
+ if (message.role !== 'assistant' || typeof message.reasoning_content !== 'string' || !message.reasoning_content)
10
+ return value;
11
+ const { reasoning_content, ...rest } = message;
12
+ const content = [{ type: 'thinking', thinking: [{ type: 'text', text: reasoning_content }] }];
13
+ if (typeof message.content === 'string' && message.content)
14
+ content.push({ type: 'text', text: message.content });
15
+ return { ...rest, content };
16
+ }) };
17
+ }
@@ -0,0 +1,5 @@
1
+ /** Mistral Vibe's browser flow exchanges a PKCE verifier for an API key. */
2
+ export declare function startMistralVibeLogin(fetchImpl?: typeof fetch): Promise<{
3
+ url: string;
4
+ complete: () => Promise<string>;
5
+ }>;
@@ -0,0 +1,63 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ const CONSOLE_ORIGIN = 'https://console.mistral.ai';
4
+ const AUTH_BASE = `${CONSOLE_ORIGIN}/api/vibe/sign-in`;
5
+ function validatedUrl(value, api) {
6
+ if (typeof value !== 'string')
7
+ throw new Error('Mistral sign-in returned an invalid URL.');
8
+ const url = new URL(value);
9
+ if (url.origin !== CONSOLE_ORIGIN || url.username || url.password || (api && !url.pathname.startsWith('/api/'))) {
10
+ throw new Error('Mistral sign-in returned an unexpected URL.');
11
+ }
12
+ return url.href;
13
+ }
14
+ async function jsonRequest(url, init, fetchImpl) {
15
+ const response = await fetchImpl(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(15_000) });
16
+ if (!response.ok)
17
+ throw new Error(`Mistral sign-in request failed (HTTP ${response.status}).`);
18
+ const data = await response.json();
19
+ if (!data || typeof data !== 'object' || Array.isArray(data))
20
+ throw new Error('Mistral sign-in returned an invalid response.');
21
+ return data;
22
+ }
23
+ /** Mistral Vibe's browser flow exchanges a PKCE verifier for an API key. */
24
+ export async function startMistralVibeLogin(fetchImpl = fetch) {
25
+ const verifier = randomBytes(64).toString('base64url');
26
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
27
+ const post = (body) => ({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
28
+ const process = await jsonRequest(AUTH_BASE, post({ code_challenge: challenge, code_challenge_method: 'S256' }), fetchImpl);
29
+ const url = validatedUrl(process.sign_in_url, false);
30
+ const pollUrl = validatedUrl(process.poll_url, true);
31
+ const processId = process.process_id;
32
+ const expires = typeof process.expires_at === 'string' ? Date.parse(process.expires_at) : NaN;
33
+ if (typeof processId !== 'string' || !/^[a-zA-Z0-9_-]{1,200}$/.test(processId) || !Number.isFinite(expires) || expires <= Date.now()) {
34
+ throw new Error('Mistral sign-in returned invalid process details.');
35
+ }
36
+ const deadline = Math.min(expires, Date.now() + 10 * 60_000);
37
+ return { url, complete: async () => {
38
+ let failures = 0;
39
+ while (Date.now() < deadline) {
40
+ let status;
41
+ try {
42
+ status = await jsonRequest(pollUrl, {}, fetchImpl);
43
+ failures = 0;
44
+ }
45
+ catch {
46
+ if (++failures >= 3)
47
+ throw new Error('Mistral sign-in status could not be retrieved.');
48
+ await delay(Math.min(3000, Math.max(0, deadline - Date.now())));
49
+ continue;
50
+ }
51
+ if (status.status === 'completed' && typeof status.exchange_token === 'string' && status.exchange_token) {
52
+ const result = await jsonRequest(`${AUTH_BASE}/${processId}/exchange`, post({ exchange_token: status.exchange_token, code_verifier: verifier }), fetchImpl);
53
+ if (typeof result.api_key !== 'string' || !result.api_key)
54
+ throw new Error('Mistral sign-in did not return an API key.');
55
+ return result.api_key;
56
+ }
57
+ if (status.status !== 'pending')
58
+ throw new Error('Mistral sign-in was denied, expired, or returned an invalid status.');
59
+ await delay(Math.min(3000, Math.max(0, deadline - Date.now())));
60
+ }
61
+ throw new Error('Mistral sign-in timed out.');
62
+ } };
63
+ }
@@ -64,8 +64,6 @@ export async function assembleRequestContext(input) {
64
64
  const usesNativeWorker = nativeWorker?.status === 'found' ? nativeWorker.provider.kind === 'haze-build' : !workerSelector && input.modelRuntime?.config.providerKind === 'haze-build';
65
65
  const profileName = input.subagentOverrides?.profile ?? settings.subagents?.defaultProfile ?? (usesNativeWorker ? 'haze-build' : undefined);
66
66
  let profile = resolveExecutionProfile(profileName, settings.subagents?.profiles, input.subagentOverrides?.maxConcurrency);
67
- if (profile && usesNativeWorker)
68
- profile = { ...profile, maxConcurrency: Math.min(profile.maxConcurrency, 2) };
69
67
  let blockedReason = profile ? undefined : `Unknown subagent profile ${profileName}. Configure subagents.profiles or select a built-in profile.`;
70
68
  let workerRuntime;
71
69
  if (input.modelRuntime) {
@@ -81,12 +79,15 @@ export async function assembleRequestContext(input) {
81
79
  workerRuntime ??= {
82
80
  ...fallbackWorkerRuntime(input.model, input.modelRuntime?.selector, input.modelRuntime?.config.providerName),
83
81
  capabilities: input.modelRuntime?.config.capabilities ?? fallbackProviderCapabilities(),
84
- // The fallback path must honour the live deployment cap too, or a
85
- // single-sequence (quality) deployment could still admit two workers.
86
- ...(input.modelRuntime?.config.deployment ? { nativeMaxConcurrency: Math.min(2, input.modelRuntime.config.deployment.activeSequences) } : {}),
82
+ ...(input.modelRuntime?.config.deployment ? { nativeMaxConcurrency: input.modelRuntime.config.deployment.activeSequences } : {}),
87
83
  };
88
- if (profile && workerRuntime.nativeMaxConcurrency)
89
- profile = { ...profile, maxConcurrency: Math.min(profile.maxConcurrency, workerRuntime.nativeMaxConcurrency) };
84
+ // The deployment manifest is authoritative for this client's native-worker
85
+ // allowance: raise it and clients follow; a future multi-tenant server
86
+ // lowers it and every client backs off without a release. Deployments that
87
+ // advertise nothing stay conservative at 2.
88
+ const nativeWorkerCap = workerRuntime.nativeMaxConcurrency ?? (usesNativeWorker ? 2 : undefined);
89
+ if (profile && nativeWorkerCap)
90
+ profile = { ...profile, maxConcurrency: Math.min(profile.maxConcurrency, nativeWorkerCap) };
90
91
  const executionScope = input.executionScope ?? {
91
92
  mutationPolicy: new WorkspaceMutationPolicy(),
92
93
  coordinator: new SubagentCoordinator(profile ?? resolveExecutionProfile(undefined, undefined), input.onSubagentEvent),
@@ -11,6 +11,7 @@ import { toolsContextFor } from './tools/toolContext.js';
11
11
  import { assembleWorkerContext, workerTaskMessage } from './workerContext.js';
12
12
  import { fallbackWorkerRuntime, normalizeSubagentInput, subagentInputSchema, } from '../core/subagent/contracts.js';
13
13
  import { COMPATIBILITY_PROFILE } from '../core/subagent/executionProfiles.js';
14
+ import { auxiliaryRequestOptions } from '../core/providerContracts.js';
14
15
  import { SubagentCoordinator } from '../core/subagent/subagentCoordinator.js';
15
16
  import { resolveWorkspacePath, workspaceRelativePath } from '../utils/path.js';
16
17
  class WorkerCapacityError extends Error {
@@ -100,19 +101,22 @@ export async function runSubagent(task, options) {
100
101
  const release = mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate')
101
102
  ? await mutationPolicy.acquire(mutationOwner, options.abortSignal).catch(() => undefined)
102
103
  : undefined;
103
- if (mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate') && !release)
104
+ // When a mutation slot is required but acquisition failed, `release` is
105
+ // undefined here, so there is nothing to release; the try/finally below only
106
+ // releases a slot that was actually acquired.
107
+ if (mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate') && !release) {
104
108
  return terminalResult(task, runtime, profile, options.deadlineExpired?.() ? 'deadline_exceeded' : 'cancelled', 'Worker cancelled before workspace admission.', options.queueMs);
109
+ }
105
110
  try {
106
- const { omitMaxOutputTokens, ...providerRequestOptions } = runtime.requestOptions;
107
- // Workers always run with reasoning disabled. Session/main-turn reasoning
111
+ const providerRequestOptions = auxiliaryRequestOptions(runtime.requestOptions, runtime.capabilities, 'worker', outputTokens);
112
+ // Workers use the lowest supported reasoning effort. Session/main-turn reasoning
108
113
  // effort rides the inherited request options; on reasoning models its
109
114
  // hidden tokens count against the worker's bounded maxOutputTokens, so a
110
115
  // `high` session could burn the whole worker budget on thinking and return
111
116
  // `no_output` (observed live: glm-5.3 @ high reasoning, 2026-10-04).
112
117
  // Applied only when the worker protocol supports the option; other
113
- // protocols cannot express it and must keep the runtime unchanged.
114
- if (runtime.capabilities.supportsReasoningEffort || runtime.capabilities.supportsBinaryThinking)
115
- providerRequestOptions.reasoning = 'none';
118
+ // protocols cannot express it and must keep the runtime unchanged. Some
119
+ // models have no off switch and use low instead of none.
116
120
  // Use the streaming model path even though workers return one collected
117
121
  // capsule. ChatGPT Codex's Responses endpoint requires `stream: true`;
118
122
  // `generateText` takes the non-streaming doGenerate path and is rejected.
@@ -122,7 +126,6 @@ export async function runSubagent(task, options) {
122
126
  messages: [{ role: 'user', content: workerTaskMessage(task) }],
123
127
  tools: budgetedTools,
124
128
  stopWhen: isStepCount(maxSteps),
125
- ...(!omitMaxOutputTokens ? { maxOutputTokens: outputTokens } : {}),
126
129
  maxRetries: profile.maxRetries,
127
130
  ...providerRequestOptions,
128
131
  abortSignal: options.abortSignal,
@@ -174,6 +177,11 @@ export async function runSubagent(task, options) {
174
177
  }
175
178
  },
176
179
  });
180
+ // Surface a stream error as soon as streamText returns, before awaiting the
181
+ // result promises, so the real onError payload is surfaced rather than a
182
+ // Promise.all wrapper that could mask it.
183
+ if (streamError)
184
+ throw streamError;
177
185
  const [text, usage, steps] = await Promise.all([result.text, result.usage, result.steps]);
178
186
  if (streamError)
179
187
  throw streamError;
@@ -2,5 +2,11 @@ function isObject(value) {
2
2
  return typeof value === 'object' && value != null;
3
3
  }
4
4
  export function isValidationSummary(value) {
5
- return isObject(value) && typeof value.summaryText === 'string' && Array.isArray(value.diagnostics);
5
+ // Require the discriminating fields too, not just summaryText/diagnostics, so
6
+ // a shape that merely has those two cannot be narrowed to a full ValidationSummary.
7
+ return isObject(value)
8
+ && typeof value.kind === 'string'
9
+ && typeof value.status === 'string'
10
+ && typeof value.summaryText === 'string'
11
+ && Array.isArray(value.diagnostics);
6
12
  }