mixdog 0.9.52 → 0.9.54

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 (124) hide show
  1. package/package.json +1 -1
  2. package/scripts/agent-model-liveness-test.mjs +68 -0
  3. package/scripts/anthropic-transport-policy-test.mjs +260 -0
  4. package/scripts/bench-run.mjs +2 -2
  5. package/scripts/compact-pressure-test.mjs +104 -0
  6. package/scripts/desktop-session-bridge-test.mjs +704 -0
  7. package/scripts/freevar-smoke.mjs +7 -4
  8. package/scripts/gemini-provider-test.mjs +396 -1
  9. package/scripts/grok-oauth-refresh-race-test.mjs +76 -1
  10. package/scripts/lifecycle-api-test.mjs +65 -4
  11. package/scripts/max-output-recovery-test.mjs +31 -0
  12. package/scripts/memory-core-input-test.mjs +10 -0
  13. package/scripts/openai-oauth-ws-1006-retry-test.mjs +144 -4
  14. package/scripts/openai-ws-early-settle-test.mjs +40 -0
  15. package/scripts/parent-abort-link-test.mjs +24 -0
  16. package/scripts/process-lifecycle-test.mjs +91 -22
  17. package/scripts/provider-admission-scheduler-test.mjs +4 -5
  18. package/scripts/provider-contract-test.mjs +326 -11
  19. package/scripts/provider-toolcall-test.mjs +269 -27
  20. package/scripts/session-orphan-sweep-test.mjs +27 -1
  21. package/src/lib/keychain-cjs.cjs +36 -23
  22. package/src/repl.mjs +11 -0
  23. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs +1 -13
  24. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +7 -8
  25. package/src/runtime/agent/orchestrator/agent-trace.mjs +33 -9
  26. package/src/runtime/agent/orchestrator/providers/anthropic-effort.mjs +7 -2
  27. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +76 -325
  28. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +10 -6
  29. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +68 -289
  30. package/src/runtime/agent/orchestrator/providers/gemini-cache.mjs +33 -5
  31. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +136 -27
  32. package/src/runtime/agent/orchestrator/providers/gemini.mjs +113 -144
  33. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +101 -190
  34. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +263 -0
  35. package/src/runtime/agent/orchestrator/providers/lib/env-utils.mjs +6 -0
  36. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +119 -0
  37. package/src/runtime/agent/orchestrator/providers/lib/grok-tool-schema.mjs +109 -0
  38. package/src/runtime/agent/orchestrator/providers/lib/openai-tool-args.mjs +70 -0
  39. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +19 -71
  40. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +35 -4
  41. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +3 -1
  42. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +96 -12
  43. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +15 -9
  44. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +81 -81
  45. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +15 -20
  46. package/src/runtime/agent/orchestrator/providers/openai-ws-delta.mjs +10 -10
  47. package/src/runtime/agent/orchestrator/providers/openai-ws-events.mjs +30 -3
  48. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +37 -28
  49. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +58 -20
  50. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +8 -0
  51. package/src/runtime/agent/orchestrator/session/context-compaction-policy.mjs +170 -0
  52. package/src/runtime/agent/orchestrator/session/context-utils.mjs +20 -223
  53. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +11 -17
  54. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +65 -12
  55. package/src/runtime/agent/orchestrator/session/manager/idle-cleanup.mjs +21 -5
  56. package/src/runtime/agent/orchestrator/session/manager/prefetch-bridge.mjs +3 -58
  57. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +24 -0
  58. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +23 -1
  59. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +57 -16
  60. package/src/runtime/agent/orchestrator/session/save-session-worker.mjs +2 -2
  61. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +7 -1
  62. package/src/runtime/agent/orchestrator/session/store/paths-heartbeat.mjs +52 -0
  63. package/src/runtime/agent/orchestrator/session/store/write-guards.mjs +62 -0
  64. package/src/runtime/agent/orchestrator/session/store.mjs +305 -127
  65. package/src/runtime/agent/orchestrator/stall-policy.mjs +6 -13
  66. package/src/runtime/agent/orchestrator/tools/builtin/lib/list-helpers.mjs +46 -0
  67. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-grep-chunks.mjs +173 -0
  68. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +117 -0
  69. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-insights.mjs +199 -0
  70. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-spawn-helpers.mjs +107 -0
  71. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +1 -40
  72. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +19 -277
  73. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +22 -298
  74. package/src/runtime/agent/orchestrator/tools/lib/shell-spawn-retry.mjs +67 -0
  75. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +1 -71
  76. package/src/runtime/channels/backends/discord-gateway.mjs +1 -1
  77. package/src/runtime/channels/backends/discord.mjs +6 -6
  78. package/src/runtime/channels/lib/config.mjs +15 -2
  79. package/src/runtime/channels/lib/memory-client.mjs +20 -3
  80. package/src/runtime/channels/lib/owned-runtime.mjs +19 -12
  81. package/src/runtime/channels/lib/status-snapshot.mjs +9 -0
  82. package/src/runtime/channels/lib/tool-dispatch.mjs +9 -5
  83. package/src/runtime/channels/lib/worker-main.mjs +16 -5
  84. package/src/runtime/memory/index.mjs +24 -198
  85. package/src/runtime/memory/lib/memory-action-handlers.mjs +2 -53
  86. package/src/runtime/memory/lib/memory-daemon-lifecycle.mjs +115 -0
  87. package/src/runtime/memory/lib/memory-port-advertiser.mjs +105 -0
  88. package/src/runtime/memory/lib/pg/supervisor.mjs +0 -4
  89. package/src/runtime/memory/lib/query-handlers.mjs +2 -122
  90. package/src/runtime/memory/lib/query-maintenance-handlers.mjs +126 -0
  91. package/src/runtime/memory/lib/tool-call-handler.mjs +57 -0
  92. package/src/runtime/search/lib/http-fetch.mjs +1 -1
  93. package/src/runtime/shared/config.mjs +58 -13
  94. package/src/runtime/shared/llm/cost.mjs +14 -4
  95. package/src/runtime/shared/memory-snapshot.mjs +245 -0
  96. package/src/runtime/shared/process-lifecycle.mjs +184 -34
  97. package/src/runtime/shared/process-shutdown.mjs +6 -0
  98. package/src/runtime/shared/resource-admission.mjs +7 -2
  99. package/src/session-runtime/channel-config-api.mjs +7 -7
  100. package/src/session-runtime/config-lifecycle.mjs +20 -17
  101. package/src/session-runtime/cwd-plugins.mjs +9 -7
  102. package/src/session-runtime/env.mjs +1 -2
  103. package/src/session-runtime/hitch-profile.mjs +45 -0
  104. package/src/session-runtime/lifecycle-api.mjs +36 -9
  105. package/src/session-runtime/mcp-glue.mjs +6 -11
  106. package/src/session-runtime/provider-init-key.mjs +17 -0
  107. package/src/session-runtime/runtime-core.mjs +44 -103
  108. package/src/session-runtime/runtime-paths.mjs +20 -0
  109. package/src/session-runtime/runtime-tool-routing.mjs +55 -0
  110. package/src/session-runtime/session-turn-api.mjs +1 -0
  111. package/src/session-runtime/tool-catalog-data.mjs +51 -0
  112. package/src/session-runtime/tool-catalog.mjs +15 -89
  113. package/src/standalone/agent-tool/spawn-preset.mjs +73 -0
  114. package/src/standalone/agent-tool/worker-rows.mjs +93 -0
  115. package/src/standalone/agent-tool.mjs +12 -162
  116. package/src/standalone/channel-admin.mjs +29 -0
  117. package/src/tui/App.jsx +11 -5
  118. package/src/tui/dist/index.mjs +233 -65
  119. package/src/tui/engine/session-api-ext.mjs +37 -4
  120. package/src/tui/engine/turn.mjs +31 -0
  121. package/src/tui/index.jsx +1 -0
  122. package/src/tui/lib/voice-setup.mjs +5 -5
  123. package/scripts/_devtools-stub.mjs +0 -1
  124. package/src/runtime/lib/keychain-cjs.cjs +0 -288
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import test from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { spawnSync } from 'node:child_process';
4
8
 
5
9
  import {
6
10
  OpenAICompatProvider,
@@ -8,8 +12,14 @@ import {
8
12
  applyCompatProviderChatOptions,
9
13
  parseToolCalls,
10
14
  } from '../src/runtime/agent/orchestrator/providers/openai-compat.mjs';
11
- import { consumeCompatChatCompletionStream } from '../src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs';
15
+ import {
16
+ consumeCompatChatCompletionStream,
17
+ consumeCompatResponsesStream,
18
+ } from '../src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs';
19
+ import { useXaiResponsesWebSocket } from '../src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs';
20
+ import { classifyError } from '../src/runtime/agent/orchestrator/providers/retry-classifier.mjs';
12
21
  import { GrokOAuthProvider } from '../src/runtime/agent/orchestrator/providers/grok-oauth.mjs';
22
+ import { sendViaWebSocket } from '../src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs';
13
23
  import {
14
24
  OpenCodeGoProvider,
15
25
  isAnthropicGoModel,
@@ -17,6 +27,11 @@ import {
17
27
  resolveOpenCodeGoBaseURLs,
18
28
  } from '../src/runtime/agent/orchestrator/providers/opencode-go.mjs';
19
29
  import { uncachedInputTokensForProvider } from '../src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs';
30
+ import { resolveTraceUsageInput } from '../src/runtime/agent/orchestrator/agent-trace.mjs';
31
+ import {
32
+ billableInputTokensForProvider,
33
+ isInclusiveProvider,
34
+ } from '../src/runtime/shared/llm/cost.mjs';
20
35
 
21
36
  function stream(events) {
22
37
  return {
@@ -173,17 +188,143 @@ test('OpenCode Go normalizes both route families to inclusive provider usage', a
173
188
  provider.openai = { send: async () => openaiRaw };
174
189
  const anthropic = await provider.send([], 'minimax-m3', [], {});
175
190
  assert.equal(OpenCodeGoProvider.inputExcludesCache, false);
191
+ assert.equal(isInclusiveProvider('opencode-go'), true);
176
192
  assert.equal(anthropic.usage.inputTokens, 100);
177
193
  assert.equal(anthropic.usage.promptTokens, 100);
178
194
  assert.equal(uncachedInputTokensForProvider('opencode-go', anthropic.usage.inputTokens, 35, 5), 60);
195
+ assert.equal(billableInputTokensForProvider('opencode-go', 100, 35, 5), 60);
196
+ assert.deepEqual(resolveTraceUsageInput({
197
+ provider: 'opencode-go',
198
+ inputTokens: 60,
199
+ cachedTokens: 35,
200
+ cacheWriteTokens: 5,
201
+ inputTokensInclusive: false,
202
+ }), {
203
+ uncachedInputTokens: 60,
204
+ promptTokens: 100,
205
+ });
179
206
  assert.equal(anthropic.usage.inputTokens, 100, 'context footprint is inclusive');
180
207
 
181
208
  const openai = await provider.send([], 'glm-5.2', [], {});
182
209
  assert.equal(openai, openaiRaw);
183
210
  assert.equal(uncachedInputTokensForProvider('opencode-go', openai.usage.inputTokens, 40, 0), 60);
211
+ assert.equal(billableInputTokensForProvider('opencode-go', 100, 40, 0), 60);
212
+ assert.deepEqual(resolveTraceUsageInput({
213
+ provider: 'opencode-go',
214
+ inputTokens: 100,
215
+ cachedTokens: 40,
216
+ cacheWriteTokens: 0,
217
+ }), {
218
+ uncachedInputTokens: 60,
219
+ promptTokens: 100,
220
+ });
184
221
  assert.equal(openai.usage.inputTokens, 100, 'context footprint remains inclusive');
185
222
  });
186
223
 
224
+ test('OpenCode Go Anthropic delegation traces additive inner usage before inclusive outer normalization', (t) => {
225
+ const tempDir = mkdtempSync(join(tmpdir(), 'mixdog-opencode-go-trace-'));
226
+ const tracePath = join(tempDir, 'agent-trace.jsonl');
227
+ t.after(() => rmSync(tempDir, { recursive: true, force: true }));
228
+
229
+ const openCodeGoUrl = new URL('../src/runtime/agent/orchestrator/providers/opencode-go.mjs', import.meta.url).href;
230
+ const anthropicUrl = new URL('../src/runtime/agent/orchestrator/providers/anthropic.mjs', import.meta.url).href;
231
+ const traceUrl = new URL('../src/runtime/agent/orchestrator/agent-trace.mjs', import.meta.url).href;
232
+ const fixture = `
233
+ const { OpenCodeGoProvider } = await import(${JSON.stringify(openCodeGoUrl)});
234
+ const { AnthropicProvider } = await import(${JSON.stringify(anthropicUrl)});
235
+ const { drainAgentTrace } = await import(${JSON.stringify(traceUrl)});
236
+
237
+ const encoder = new TextEncoder();
238
+ const events = [
239
+ { type: 'message_start', message: {
240
+ model: 'minimax-m3',
241
+ usage: {
242
+ input_tokens: 60,
243
+ cache_read_input_tokens: 35,
244
+ cache_creation_input_tokens: 5,
245
+ },
246
+ } },
247
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 5 } },
248
+ { type: 'message_stop' },
249
+ ];
250
+ const chunks = events.map((event) => encoder.encode(
251
+ 'event: ' + event.type + '\\ndata: ' + JSON.stringify(event) + '\\n\\n'
252
+ ));
253
+ let chunkIndex = 0;
254
+ const response = {
255
+ ok: true,
256
+ status: 200,
257
+ headers: new Map(),
258
+ body: { getReader() {
259
+ return {
260
+ read() {
261
+ return chunkIndex < chunks.length
262
+ ? Promise.resolve({ done: false, value: chunks[chunkIndex++] })
263
+ : Promise.resolve({ done: true, value: undefined });
264
+ },
265
+ cancel() { return Promise.resolve(); },
266
+ releaseLock() {},
267
+ };
268
+ } },
269
+ };
270
+
271
+ const inner = Object.create(AnthropicProvider.prototype);
272
+ inner.name = 'opencode-go';
273
+ inner.config = { disableBetaHeaders: true };
274
+ inner.fastModeBetaHeaderLatched = false;
275
+ inner.client = { messages: { create() {
276
+ return { asResponse: async () => response };
277
+ } } };
278
+
279
+ const outer = Object.create(OpenCodeGoProvider.prototype);
280
+ outer.anthropic = inner;
281
+ outer.openai = { send() { throw new Error('wrong OpenCode Go route'); } };
282
+ const result = await outer.send(
283
+ [{ role: 'user', content: 'fixture' }],
284
+ 'minimax-m3',
285
+ [],
286
+ { sessionId: 'opencode-go-additive-trace' },
287
+ );
288
+ await drainAgentTrace();
289
+ process.stdout.write(JSON.stringify(result.usage));
290
+ `;
291
+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', fixture], {
292
+ cwd: new URL('..', import.meta.url),
293
+ encoding: 'utf8',
294
+ env: {
295
+ ...process.env,
296
+ MIXDOG_AGENT_TRACE_DISABLE: '0',
297
+ MIXDOG_AGENT_TRACE_LOCAL_DISABLE: '0',
298
+ MIXDOG_AGENT_TRACE_PATH: tracePath,
299
+ },
300
+ });
301
+ assert.equal(child.status, 0, child.stderr || child.stdout);
302
+
303
+ const outerUsage = JSON.parse(child.stdout);
304
+ assert.deepEqual(outerUsage, {
305
+ inputTokens: 100,
306
+ outputTokens: 5,
307
+ cachedTokens: 35,
308
+ cacheWriteTokens: 5,
309
+ promptTokens: 100,
310
+ });
311
+ const traceRows = readFileSync(tracePath, 'utf8')
312
+ .trim()
313
+ .split(/\r?\n/)
314
+ .map((line) => JSON.parse(line));
315
+ const innerUsage = traceRows.find((row) => (
316
+ row.kind === 'usage_raw'
317
+ && row.session_id === 'opencode-go-additive-trace'
318
+ ));
319
+ assert.ok(innerUsage, 'delegated Anthropic route must emit usage_raw');
320
+ assert.equal(innerUsage.payload.provider, 'opencode-go');
321
+ assert.equal(innerUsage.input_tokens, 60);
322
+ assert.equal(innerUsage.cached_tokens, 35);
323
+ assert.equal(innerUsage.cache_write_tokens, 5);
324
+ assert.equal(innerUsage.uncached_input_tokens, 60);
325
+ assert.equal(innerUsage.prompt_tokens, 100);
326
+ });
327
+
187
328
  test('constructing Grok OAuth is network inert', () => {
188
329
  const provider = new GrokOAuthProvider({
189
330
  preconnectFn: () => { throw new Error('constructor attempted outbound preconnect'); },
@@ -205,13 +346,18 @@ test('Grok OAuth end-to-end HTTP Responses path is hermetic through inner compat
205
346
  },
206
347
  responsesTransport: 'http',
207
348
  });
208
- provider.ensureAuth = async () => ({ access_token: 'fixture-token' });
209
- const inner = provider._ensureInner('fixture-token', 'grok-4.5');
210
- assert.equal(inner.config.preconnect, false, 'Grok seam must propagate to inner compat');
211
- assert.equal(typeof inner.config.preconnectFn, 'function');
212
- inner.client = {
213
- responses: {
214
- create: async () => stream([
349
+ provider.ensureAuth = async () => ({ access_token: 'fixture-token', user_id: 'fixture-user' });
350
+ const ensureInner = provider._ensureInner.bind(provider);
351
+ let capturedInner = null;
352
+ let capturedParams = null;
353
+ provider._ensureInner = (...args) => {
354
+ const inner = ensureInner(...args);
355
+ capturedInner = inner;
356
+ inner.client = {
357
+ responses: {
358
+ create: async (params) => {
359
+ capturedParams = params;
360
+ return stream([
215
361
  { type: 'response.created', response: { id: 'resp_fixture', model: 'grok-4.5' } },
216
362
  { type: 'response.output_text.delta', delta: 'hermetic' },
217
363
  {
@@ -224,20 +370,66 @@ test('Grok OAuth end-to-end HTTP Responses path is hermetic through inner compat
224
370
  usage: { input_tokens: 3, output_tokens: 1 },
225
371
  },
226
372
  },
227
- ]),
228
- },
373
+ ]);
374
+ },
375
+ },
376
+ };
377
+ return inner;
229
378
  };
230
379
 
231
380
  const result = await provider.send(
232
381
  [{ role: 'user', content: 'fixture' }],
233
382
  'grok-4.5',
234
383
  [],
235
- { sessionId: 'hermetic-grok-contract' },
384
+ { sessionId: 'hermetic-grok-contract', iteration: 2 },
236
385
  );
237
386
  assert.equal(result.content, 'hermetic');
238
387
  assert.equal(result.usage.inputTokens, 3);
388
+ assert.equal(capturedInner.config.preconnect, false, 'Grok seam must propagate to inner compat');
389
+ assert.equal(typeof capturedInner.config.preconnectFn, 'function');
390
+ assert.equal(capturedInner.baseURL, 'https://cli-chat-proxy.grok.com/v1');
391
+ assert.equal(capturedInner.config.responsesTransport, 'http');
392
+ assert.equal(capturedInner.defaultHeaders['x-grok-conv-id'], undefined);
393
+ assert.equal(capturedInner.defaultHeaders['x-grok-session-id'], 'hermetic-grok-contract');
394
+ assert.match(capturedInner.defaultHeaders['x-grok-req-id'], /^[0-9a-f-]{36}$/);
395
+ assert.equal(capturedInner.defaultHeaders['x-grok-model-override'], 'grok-4.5');
396
+ assert.equal(capturedInner.defaultHeaders['x-grok-turn-idx'], '2');
397
+ assert.equal(capturedInner.defaultHeaders['x-grok-user-id'], 'fixture-user');
398
+ assert.equal(capturedParams.store, false);
399
+ assert.deepEqual(capturedParams.include, ['reasoning.encrypted_content']);
400
+ assert.equal(result.providerState.xaiResponses.store, false);
401
+ assert.equal(result.providerState.xaiResponses.previousResponseId, null);
239
402
  });
240
403
 
404
+ test('xAI Responses defaults to HTTP and keeps WebSocket behind explicit opt-in', () => {
405
+ assert.equal(useXaiResponsesWebSocket({}, {}), false);
406
+ assert.equal(useXaiResponsesWebSocket({}, { responsesTransport: 'http' }), false);
407
+ assert.equal(useXaiResponsesWebSocket({}, { responsesTransport: 'websocket' }), true);
408
+ });
409
+
410
+ for (const event of [
411
+ { type: 'response.failed', response: { error: { message: 'forbidden' } } },
412
+ { type: 'error', message: 'forbidden' },
413
+ ]) {
414
+ test(`xAI ${event.type} stream event is retryable 500-equivalent without changing other compat labels`, async () => {
415
+ const xaiError = await consumeCompatResponsesStream(stream([event]), {
416
+ label: 'xai:responses',
417
+ parseResponsesToolCalls: () => [],
418
+ responseOutputText: () => '',
419
+ }).then(() => null, (err) => err);
420
+ assert.equal(xaiError.httpStatus, 500);
421
+ assert.equal(classifyError(xaiError), 'transient');
422
+
423
+ const otherError = await consumeCompatResponsesStream(stream([event]), {
424
+ label: 'other-compat',
425
+ parseResponsesToolCalls: () => [],
426
+ responseOutputText: () => '',
427
+ }).then(() => null, (err) => err);
428
+ assert.equal(otherError.httpStatus, 403);
429
+ assert.equal(classifyError(otherError), 'auth');
430
+ });
431
+ }
432
+
241
433
  test('Grok OAuth does not refresh/replay a 401 after visible tool dispatch', async () => {
242
434
  const provider = Object.create(GrokOAuthProvider.prototype);
243
435
  provider.config = { preconnect: false };
@@ -266,3 +458,126 @@ test('Grok OAuth does not refresh/replay a 401 after visible tool dispatch', asy
266
458
  assert.equal(dispatched, 1);
267
459
  assert.equal(authCalls, 1);
268
460
  });
461
+
462
+ test('xAI WS to HTTP fallback preserves completed warmup usage and cost ticks', async (t) => {
463
+ const priorTransport = process.env.MIXDOG_OAI_TRANSPORT;
464
+ process.env.MIXDOG_OAI_TRANSPORT = 'auto';
465
+ t.after(() => {
466
+ if (priorTransport == null) delete process.env.MIXDOG_OAI_TRANSPORT;
467
+ else process.env.MIXDOG_OAI_TRANSPORT = priorTransport;
468
+ });
469
+ const provider = new OpenAICompatProvider('xai', {
470
+ apiKey: 'fixture',
471
+ preconnect: false,
472
+ responsesTransport: 'websocket',
473
+ });
474
+ const warmup = {
475
+ requestBody: { generate: false },
476
+ usage: { inputTokens: 10, outputTokens: 1, cachedTokens: 4, promptTokens: 10, raw: { cost_in_usd_ticks: 100 } },
477
+ };
478
+ provider._doSendXaiResponsesWebSocket = async () => {
479
+ const err = Object.assign(new Error('upgrade required'), { httpStatus: 426 });
480
+ Object.defineProperty(err, '__warmup', { value: warmup });
481
+ throw err;
482
+ };
483
+ provider._doSendXaiResponses = async () => ({
484
+ content: 'fallback',
485
+ usage: { inputTokens: 20, outputTokens: 2, cachedTokens: 5, promptTokens: 20, raw: { cost_in_usd_ticks: 200 }, costUsd: 0.00000002 },
486
+ });
487
+ const result = await provider._doSend([], 'grok-4.5', [], {});
488
+ assert.equal(result.usage.inputTokens, 30);
489
+ assert.equal(result.usage.mainInputTokens, 20);
490
+ assert.equal(result.usage.raw.cost_in_usd_ticks, 300);
491
+ assert.equal(result.usage.costUsd, 0.00000003);
492
+ });
493
+
494
+ test('xAI WS warmup billing exposes only main request usage as context', async () => {
495
+ let streams = 0;
496
+ const result = await sendViaWebSocket({
497
+ auth: { type: 'xai', apiKey: 'fixture' },
498
+ body: { model: 'grok-4.5', input: [{ role: 'user', content: 'main' }] },
499
+ sendOpts: {},
500
+ externalSignal: null,
501
+ poolKey: 'xai-warmup-accounting',
502
+ cacheKey: 'xai-warmup-accounting',
503
+ iteration: 1,
504
+ useModel: 'grok-4.5',
505
+ traceProvider: 'xai',
506
+ includeResponseId: true,
507
+ warmupBody: { model: 'grok-4.5', input: [], generate: false },
508
+ _acquireWithRetryFn: async () => ({ entry: { socket: { close() {} } }, reused: false }),
509
+ _sendFrameFn: async () => {},
510
+ _streamFn: async ({ state }) => {
511
+ streams += 1;
512
+ return state.warmup
513
+ ? {
514
+ content: '',
515
+ model: 'grok-4.5',
516
+ toolCalls: [],
517
+ usage: { inputTokens: 10, outputTokens: 1, cachedTokens: 4, promptTokens: 10, raw: { cost_in_usd_ticks: 100 } },
518
+ responseId: 'warm',
519
+ responseItems: [],
520
+ }
521
+ : {
522
+ content: 'done',
523
+ model: 'grok-4.5',
524
+ toolCalls: [],
525
+ usage: { inputTokens: 20, outputTokens: 2, cachedTokens: 5, promptTokens: 20, raw: { cost_in_usd_ticks: 200 } },
526
+ responseId: 'main',
527
+ responseItems: [],
528
+ closeSocket: true,
529
+ };
530
+ },
531
+ _agentTraceFn: () => {},
532
+ _sendSpanTraceFn: () => {},
533
+ });
534
+ assert.equal(streams, 2);
535
+ assert.equal(result.usage.inputTokens, 30);
536
+ assert.equal(result.usage.mainInputTokens, 20);
537
+ assert.equal(result.usage.raw.cost_in_usd_ticks, 300);
538
+ });
539
+
540
+ test('xAI safe 401 replay carries completed warmup into the retry', async () => {
541
+ const provider = new OpenAICompatProvider('xai', { apiKey: 'fixture', preconnect: false });
542
+ const warmup = { usage: { inputTokens: 10 } };
543
+ let attempts = 0;
544
+ provider.reloadApiKey = () => {};
545
+ provider._doSend = async (_messages, _model, _tools, opts) => {
546
+ attempts += 1;
547
+ if (attempts === 1) {
548
+ const err = Object.assign(new Error('401'), { httpStatus: 401 });
549
+ Object.defineProperty(err, '__warmup', { value: warmup });
550
+ throw err;
551
+ }
552
+ assert.equal(opts._carriedWarmup, warmup);
553
+ return { content: 'retried' };
554
+ };
555
+ assert.equal((await provider.send([], 'grok-4.5', [], {})).content, 'retried');
556
+ assert.equal(attempts, 2);
557
+ });
558
+
559
+ for (const status of [401, 403]) {
560
+ test(`Grok OAuth safe ${status} replay carries completed warmup to refreshed xAI inner`, async () => {
561
+ const provider = Object.create(GrokOAuthProvider.prototype);
562
+ provider.config = { preconnect: false };
563
+ const warmup = { usage: { inputTokens: 10 } };
564
+ let authCalls = 0;
565
+ provider.ensureAuth = async ({ forceRefresh = false } = {}) => {
566
+ authCalls += 1;
567
+ return { access_token: forceRefresh ? 'fresh' : 'stale' };
568
+ };
569
+ provider._ensureInner = (token) => ({
570
+ _doSend: async (_messages, _model, _tools, opts) => {
571
+ if (token === 'stale') {
572
+ const err = Object.assign(new Error(String(status)), { httpStatus: status });
573
+ Object.defineProperty(err, '__warmup', { value: warmup });
574
+ throw err;
575
+ }
576
+ assert.equal(opts._carriedWarmup, warmup);
577
+ return { content: 'retried' };
578
+ },
579
+ });
580
+ assert.equal((await provider.send([], 'grok-4.5', [], {})).content, 'retried');
581
+ assert.equal(authCalls, 2);
582
+ });
583
+ }