mixdog 0.9.46 → 0.9.49

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 (90) hide show
  1. package/package.json +14 -4
  2. package/scripts/agent-parallel-smoke.mjs +4 -1
  3. package/scripts/agent-route-batch-test.mjs +40 -0
  4. package/scripts/code-graph-aggregate-cwd-test.mjs +154 -0
  5. package/scripts/code-graph-description-contract.mjs +185 -0
  6. package/scripts/code-graph-disk-hit-test.mjs +55 -0
  7. package/scripts/code-graph-dispatch-test.mjs +96 -0
  8. package/scripts/compact-pressure-test.mjs +40 -0
  9. package/scripts/deferred-tool-loading-test.mjs +233 -0
  10. package/scripts/execution-completion-dedup-test.mjs +48 -0
  11. package/scripts/explore-prompt-policy-test.mjs +88 -3
  12. package/scripts/live-worker-smoke.mjs +68 -16
  13. package/scripts/memory-core-input-test.mjs +33 -13
  14. package/scripts/native-edit-wire-test.mjs +152 -0
  15. package/scripts/openai-oauth-ws-1006-retry-test.mjs +294 -16
  16. package/scripts/patch-binary-cache-test.mjs +181 -0
  17. package/scripts/prompt-immediate-render-test.mjs +89 -0
  18. package/scripts/provider-toolcall-test.mjs +280 -15
  19. package/scripts/shell-failure-diagnostics-test.mjs +211 -0
  20. package/scripts/statusline-quota-hysteresis-test.mjs +26 -1
  21. package/scripts/streaming-tail-window-test.mjs +29 -0
  22. package/scripts/tool-failures.mjs +21 -3
  23. package/scripts/tool-smoke.mjs +263 -38
  24. package/scripts/tool-tui-presentation-test.mjs +17 -1
  25. package/scripts/tui-perf-run.ps1 +26 -0
  26. package/scripts/tui-transcript-perf-test.mjs +7 -1
  27. package/scripts/verify-release-assets-test.mjs +647 -0
  28. package/scripts/verify-release-assets.mjs +293 -0
  29. package/scripts/windows-hide-spawn-options-test.mjs +19 -0
  30. package/src/cli.mjs +1 -0
  31. package/src/defaults/cycle3-review-prompt.md +10 -4
  32. package/src/defaults/memory-promote-prompt.md +4 -3
  33. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +16 -5
  34. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +35 -11
  35. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +35 -11
  36. package/src/runtime/agent/orchestrator/providers/custom-tool-wire.mjs +28 -0
  37. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +1 -1
  38. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +34 -34
  39. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +45 -38
  40. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +36 -11
  41. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +4 -4
  42. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +10 -6
  43. package/src/runtime/agent/orchestrator/session/loop/deferred-call-through.mjs +4 -3
  44. package/src/runtime/agent/orchestrator/session/loop/recall-fasttrack.mjs +4 -3
  45. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +16 -1
  46. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +2 -2
  47. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +0 -1
  48. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +13 -8
  49. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +30 -16
  50. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +25 -8
  51. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +69 -4
  52. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +5 -4
  53. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +1 -1
  54. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +12 -12
  55. package/src/runtime/agent/orchestrator/tools/patch/native-server.mjs +12 -7
  56. package/src/runtime/agent/orchestrator/tools/patch-binary-fetcher.mjs +77 -18
  57. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +11 -11
  58. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +99 -24
  59. package/src/runtime/memory/lib/memory-action-handlers.mjs +21 -11
  60. package/src/runtime/memory/lib/memory-cycle2-gate.mjs +13 -5
  61. package/src/runtime/memory/lib/memory-cycle2.mjs +8 -5
  62. package/src/runtime/memory/lib/memory-cycle3.mjs +41 -6
  63. package/src/runtime/memory/lib/query-handlers.mjs +49 -6
  64. package/src/runtime/memory/lib/recall-format.mjs +21 -6
  65. package/src/runtime/memory/tool-defs.mjs +2 -3
  66. package/src/session-runtime/context-status.mjs +25 -16
  67. package/src/session-runtime/model-route-api.mjs +2 -0
  68. package/src/session-runtime/runtime-core.mjs +2 -2
  69. package/src/session-runtime/session-turn-api.mjs +4 -1
  70. package/src/session-runtime/tool-catalog.mjs +113 -19
  71. package/src/session-runtime/tool-defs.mjs +1 -0
  72. package/src/standalone/agent-tool/helpers.mjs +25 -6
  73. package/src/standalone/agent-tool.mjs +75 -41
  74. package/src/tui/App.jsx +4 -0
  75. package/src/tui/app/input-parsers.mjs +8 -9
  76. package/src/tui/components/Markdown.jsx +6 -1
  77. package/src/tui/components/Message.jsx +11 -2
  78. package/src/tui/components/PromptInput.jsx +19 -21
  79. package/src/tui/components/Spinner.jsx +4 -4
  80. package/src/tui/components/StatusLine.jsx +6 -6
  81. package/src/tui/components/TranscriptItem.jsx +2 -2
  82. package/src/tui/components/prompt-input/immediate-render.mjs +47 -0
  83. package/src/tui/components/tool-execution/surface-detail.mjs +14 -9
  84. package/src/tui/dist/index.mjs +130 -45
  85. package/src/tui/engine/agent-job-feed.mjs +21 -2
  86. package/src/tui/engine/turn.mjs +12 -1
  87. package/src/tui/markdown/measure-rendered-rows.mjs +1 -1
  88. package/src/tui/markdown/streaming-markdown.mjs +20 -0
  89. package/src/ui/statusline.mjs +5 -5
  90. package/src/vendor/statusline/src/gateway/session-routes.mjs +22 -10
@@ -5,16 +5,27 @@ import { tmpdir } from 'node:os'
5
5
  import { join } from 'node:path'
6
6
  import { normalizeCoreInput } from '../src/runtime/memory/lib/core-memory-store.mjs'
7
7
  import { createMemoryActionHandlers } from '../src/runtime/memory/lib/memory-action-handlers.mjs'
8
+ import { TOOL_DEFS as MEMORY_TOOL_DEFS } from '../src/runtime/memory/tool-defs.mjs'
9
+ import { parseMemoryCandidateRows, parseMemoryCoreRows } from '../src/tui/app/input-parsers.mjs'
8
10
 
9
- test('core content aliases summary and derives a bounded element', () => {
11
+ test('memory mutation schema omits category while recall keeps its internal filter', () => {
12
+ const memoryTool = MEMORY_TOOL_DEFS.find((tool) => tool.name === 'memory')
13
+ const recallTool = MEMORY_TOOL_DEFS.find((tool) => tool.name === 'recall')
14
+ assert.equal(Object.hasOwn(memoryTool.inputSchema.properties, 'category'), false)
15
+ assert.doesNotMatch(memoryTool.description, /category/i)
16
+ assert.equal(Object.hasOwn(recallTool.inputSchema.properties, 'category'), true)
17
+ })
18
+
19
+ test('core content aliases summary, derives an element, and accepts no category', () => {
10
20
  const content = 'A durable preference that callers should receive concise answers.'
11
- const input = normalizeCoreInput({ content, category: 'preference' }, {
21
+ const input = normalizeCoreInput({ content }, {
12
22
  requireElement: true,
13
23
  requireSummary: true,
14
- requireCategory: true,
24
+ requireCategory: false,
15
25
  })
16
26
  assert.equal(input.summary, content)
17
27
  assert.equal(input.element, content.slice(0, 40))
28
+ assert.equal(input.category, 'fact')
18
29
  assert.deepEqual(input.errors, [])
19
30
  })
20
31
 
@@ -34,12 +45,11 @@ test('core add reports every invalid field and cwd project hint together', async
34
45
  cwd,
35
46
  element: 'x'.repeat(41),
36
47
  summary: 'y'.repeat(101),
37
- category: 'unknown',
38
48
  })
39
49
  assert.equal(result.isError, true)
40
50
  assert.equal(
41
51
  result.text,
42
- 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool (cwd suggests "owner/repo"); element too long (41/40 chars, remove 1); summary too long (101/100 chars, remove 1); invalid category "unknown". Valid: rule, constraint, decision, fact, goal, preference, task, issue',
52
+ 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool (cwd suggests "owner/repo"); element too long (41/40 chars, remove 1); summary too long (101/100 chars, remove 1)',
43
53
  )
44
54
  } finally {
45
55
  await rm(cwd, { recursive: true, force: true })
@@ -58,13 +68,11 @@ test('core add rejects blank project_id in the batched error', async () => {
58
68
  project_id: ' ',
59
69
  element: 'x'.repeat(41),
60
70
  summary: 'y'.repeat(101),
61
- category: 'unknown',
62
71
  })
63
72
  assert.equal(result.isError, true)
64
73
  assert.match(result.text, /^core add: project_id required —/)
65
74
  assert.match(result.text, /element too long \(41\/40 chars, remove 1\)/)
66
75
  assert.match(result.text, /summary too long \(101\/100 chars, remove 1\)/)
67
- assert.match(result.text, /invalid category "unknown"/)
68
76
  })
69
77
 
70
78
  test('core add folds project_id "*" into the batched error', async () => {
@@ -79,12 +87,10 @@ test('core add folds project_id "*" into the batched error', async () => {
79
87
  project_id: '*',
80
88
  element: 'x'.repeat(41),
81
89
  summary: 'y'.repeat(101),
82
- category: 'unknown',
83
90
  })
84
91
  assert.equal(result.isError, true)
85
92
  assert.match(result.text, /^core add: project_id "\*" only valid for op="list"; element too long/)
86
93
  assert.match(result.text, /summary too long \(101\/100 chars, remove 1\)/)
87
- assert.match(result.text, /invalid category "unknown"/)
88
94
  })
89
95
 
90
96
  test('core add suppresses malformed cwd project hints', async () => {
@@ -103,7 +109,6 @@ test('core add suppresses malformed cwd project hints', async () => {
103
109
  cwd,
104
110
  element: 'durable preference',
105
111
  summary: 'Callers prefer concise answers.',
106
- category: 'preference',
107
112
  })
108
113
  assert.equal(result.text, 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool')
109
114
  } finally {
@@ -119,7 +124,7 @@ test('core edit by id succeeds without project_id', async () => {
119
124
  readMainConfig: () => ({}),
120
125
  editCoreImpl: async (dataDir, id, patch) => {
121
126
  call = { dataDir, id, patch }
122
- return { id: Number(id), element: patch.element, summary: patch.summary, category: patch.category }
127
+ return { id: Number(id), element: patch.element, summary: patch.summary, category: 'preference' }
123
128
  },
124
129
  })
125
130
  const result = await handleMemoryAction({
@@ -128,10 +133,25 @@ test('core edit by id succeeds without project_id', async () => {
128
133
  id: 7,
129
134
  element: 'reply style',
130
135
  summary: 'Use concise answers.',
131
- category: 'preference',
132
136
  })
133
137
  assert.equal(result.isError, undefined)
134
- assert.equal(result.text, 'core edited (id=7): [preference] reply style — Use concise answers.')
138
+ assert.equal(result.text, 'core edited (id=7): reply style — Use concise answers.')
135
139
  assert.equal(call.id, 7)
136
140
  assert.equal(call.patch.project_id, undefined)
141
+ assert.equal(call.patch.category, undefined)
142
+ })
143
+
144
+ test('category-free core and candidate rows remain selectable in the TUI', () => {
145
+ const [core] = parseMemoryCoreRows('COMMON:\nid=7 reply style — Use concise answers.')
146
+ assert.equal(core._id, 7)
147
+ assert.equal(core._element, 'reply style')
148
+ assert.equal(core._summary, 'Use concise answers.')
149
+ assert.equal(Object.hasOwn(core, '_category'), false)
150
+
151
+ const [candidate] = parseMemoryCandidateRows(
152
+ 'id=9 project=COMMON score=1.60 coding agent refs — Use C:\\Project\\refs. (durable)',
153
+ )
154
+ assert.equal(candidate._id, 9)
155
+ assert.equal(candidate.label, '#9 coding agent refs')
156
+ assert.equal(candidate._projectId, null)
137
157
  })
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { once } from 'node:events';
6
+ import {
7
+ existsSync,
8
+ mkdtempSync,
9
+ readFileSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import test from 'node:test';
16
+ import {
17
+ closeNativePatchServerForTests,
18
+ runServerEdit,
19
+ } from '../src/runtime/agent/orchestrator/tools/patch.mjs';
20
+
21
+ const binary = process.env.MIXDOG_EDIT_NATIVE_BIN;
22
+ assert.ok(binary, 'MIXDOG_EDIT_NATIVE_BIN must point to the release mixdog-patch binary');
23
+ assert.ok(existsSync(binary), `native EDIT test binary does not exist: ${binary}`);
24
+
25
+ const responseFields = [
26
+ 'replacements',
27
+ 'readMs',
28
+ 'applyMs',
29
+ 'writeMs',
30
+ 'totalMs',
31
+ 'tier',
32
+ 'contentHash',
33
+ 'roundtripMs',
34
+ ];
35
+
36
+ function digest(content) {
37
+ return createHash('sha256').update(content).digest('hex');
38
+ }
39
+
40
+ function assertCompleteResponse(response, { replacements, tier, content }) {
41
+ assert.deepEqual(Object.keys(response), responseFields, 'EDIT response must expose all eight decoded fields');
42
+ assert.equal(response.replacements, replacements);
43
+ assert.equal(response.tier, tier);
44
+ assert.match(response.contentHash, /^[a-f0-9]{64}$/);
45
+ assert.equal(response.contentHash, digest(content), 'EDIT response hash must describe the resulting bytes');
46
+ for (const field of ['readMs', 'applyMs', 'writeMs', 'totalMs', 'roundtripMs']) {
47
+ assert.ok(Number.isFinite(response[field]) && response[field] >= 0, `${field} must be a non-negative number`);
48
+ }
49
+ }
50
+
51
+ function edit(fullPath, oldString, newString, options = {}) {
52
+ return runServerEdit({
53
+ fullPath,
54
+ oldBuf: Buffer.from(oldString, 'utf8'),
55
+ newBuf: Buffer.from(newString, 'utf8'),
56
+ ...options,
57
+ });
58
+ }
59
+
60
+ async function rawEdit(fullPath, oldString, newString, { replaceAll = false, dryRun = false } = {}) {
61
+ const pathBuf = Buffer.from(fullPath, 'utf8');
62
+ const oldBuf = Buffer.from(oldString, 'utf8');
63
+ const newBuf = Buffer.from(newString, 'utf8');
64
+ const child = spawn(binary, ['--server'], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
65
+ const stdout = [];
66
+ const stderr = [];
67
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
68
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
69
+ child.stdin.end(Buffer.concat([
70
+ Buffer.from(`EDIT ${pathBuf.length} ${oldBuf.length} ${newBuf.length} ${replaceAll ? 1 : 0} ${dryRun ? 1 : 0}\n`),
71
+ pathBuf,
72
+ oldBuf,
73
+ newBuf,
74
+ Buffer.from('QUIT\n'),
75
+ ]));
76
+ const [code] = await once(child, 'exit');
77
+ assert.equal(code, 0, `raw native EDIT server failed: ${Buffer.concat(stderr).toString('utf8')}`);
78
+ return Buffer.concat(stdout).toString('utf8').trimEnd();
79
+ }
80
+
81
+ function assertRawResponse(line) {
82
+ const fields = line.split('\t');
83
+ assert.equal(fields.length, 8, 'raw EDIT response must contain exactly eight tab-delimited fields');
84
+ assert.equal(fields[0], 'OK');
85
+ for (const index of [2, 3, 4, 5]) {
86
+ assert.notEqual(fields[index], '', `raw EDIT timing field ${index} must be present`);
87
+ assert.match(fields[index], /^\d+(?:\.\d+)?$/, `raw EDIT timing field ${index} must be numeric`);
88
+ }
89
+ }
90
+
91
+ test('native EDIT production wire path preserves matching and response invariants', async (t) => {
92
+ const root = mkdtempSync(join(tmpdir(), 'mixdog-native-edit-wire-'));
93
+ try {
94
+ await t.test('rejects ambiguity, then reports the replace-all repeat count and full response', async () => {
95
+ const path = join(root, 'repeats.txt');
96
+ writeFileSync(path, 'token token token\n', 'utf8');
97
+
98
+ await assert.rejects(
99
+ edit(path, 'token', 'value'),
100
+ (error) => {
101
+ assert.equal(error.message, 'old_string found 3 times');
102
+ return true;
103
+ },
104
+ );
105
+ assert.equal(readFileSync(path, 'utf8'), 'token token token\n');
106
+
107
+ const expected = 'value value value\n';
108
+ assertRawResponse(await rawEdit(path, 'token', 'value', { replaceAll: true, dryRun: true }));
109
+ const response = await edit(path, 'token', 'value', { replaceAll: true });
110
+ assert.equal(readFileSync(path, 'utf8'), expected);
111
+ assertCompleteResponse(response, { replacements: 3, tier: 'exact', content: expected });
112
+ });
113
+
114
+ await t.test('rejects a 30-line folded match without writing', async () => {
115
+ const path = join(root, 'folded-30.txt');
116
+ const source = Array.from({ length: 30 }, (_, i) => `line ${i + 1} “value”`).join('\n');
117
+ const foldedNeedle = Array.from({ length: 30 }, (_, i) => `line ${i + 1} "value"`).join('\n');
118
+ writeFileSync(path, source, 'utf8');
119
+
120
+ await assert.rejects(
121
+ edit(path, foldedNeedle, 'unsafe replacement'),
122
+ /old_string is 30 lines \(>= 30\)\./,
123
+ );
124
+ assert.equal(readFileSync(path, 'utf8'), source);
125
+ });
126
+
127
+ await t.test('absorbs the deleted line newline', async () => {
128
+ const path = join(root, 'delete-crlf.txt');
129
+ const source = 'keep\r\ndelete me\r\nafter\r\n';
130
+ const expected = 'keep\r\nafter\r\n';
131
+ writeFileSync(path, source, 'utf8');
132
+
133
+ const response = await edit(path, 'delete me', '');
134
+ assert.equal(readFileSync(path, 'utf8'), expected);
135
+ assertCompleteResponse(response, { replacements: 1, tier: 'exact', content: expected });
136
+ });
137
+
138
+ await t.test('preserves CRLF while lowering an LF-authored replacement', async () => {
139
+ const path = join(root, 'preserve-crlf.txt');
140
+ const source = 'head\r\nold a\r\nold b\r\ntail\r\n';
141
+ const expected = 'head\r\nnew a\r\nnew b\r\ntail\r\n';
142
+ writeFileSync(path, source, 'utf8');
143
+
144
+ const response = await edit(path, 'old a\nold b', 'new a\nnew b');
145
+ assert.equal(readFileSync(path, 'utf8'), expected);
146
+ assertCompleteResponse(response, { replacements: 1, tier: 'crlf', content: expected });
147
+ });
148
+ } finally {
149
+ await closeNativePatchServerForTests();
150
+ rmSync(root, { recursive: true, force: true });
151
+ }
152
+ });
@@ -2,7 +2,8 @@
2
2
  import test from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
4
  import { OpenAIOAuthProvider } from '../src/runtime/agent/orchestrator/providers/openai-oauth.mjs';
5
- import { sendViaWebSocket } from '../src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs';
5
+ import { _acquireWithRetry, sendViaWebSocket } from '../src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs';
6
+ import { _sendFrame } from '../src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs';
6
7
 
7
8
  function close1006() {
8
9
  const err = new Error('WebSocket closed abnormally');
@@ -27,28 +28,153 @@ function wsArgs(overrides = {}) {
27
28
  };
28
29
  }
29
30
 
31
+ test('acquire timeout reconnects successfully with progress, not a terminal WS error', async () => {
32
+ const oldWrite = process.stderr.write;
33
+ const oldQuiet = process.env.MIXDOG_QUIET_PROVIDER_LOG;
34
+ let stderr = '';
35
+ let attempts = 0;
36
+ const stages = [];
37
+ try {
38
+ delete process.env.MIXDOG_QUIET_PROVIDER_LOG;
39
+ process.stderr.write = (chunk) => {
40
+ stderr += String(chunk);
41
+ return true;
42
+ };
43
+ const result = await sendViaWebSocket(wsArgs({
44
+ onStageChange: (stage, detail) => stages.push({ stage, detail }),
45
+ _acquireWithRetryFn: (opts) => _acquireWithRetry({
46
+ ...opts,
47
+ maxAttempts: 2,
48
+ _sleepFn: async () => {},
49
+ _acquire: async () => {
50
+ attempts += 1;
51
+ if (attempts === 1) {
52
+ throw Object.assign(new Error('OpenAI OAuth WS acquire timed out before open'), {
53
+ code: 'EWSACQUIRETIMEOUT',
54
+ });
55
+ }
56
+ return { entry: entry(), reused: false };
57
+ },
58
+ }),
59
+ _streamFn: async () => ({
60
+ content: 'recovered',
61
+ model: 'gpt-5.5',
62
+ toolCalls: [],
63
+ usage: {},
64
+ closeSocket: true,
65
+ }),
66
+ }));
67
+ assert.equal(result.content, 'recovered');
68
+ assert.equal(attempts, 2);
69
+ assert.deepEqual(
70
+ stages.filter(({ stage }) => stage === 'reconnecting'),
71
+ [{ stage: 'reconnecting', detail: {
72
+ attempt: 1,
73
+ max: 1,
74
+ classifier: 'acquire_timeout',
75
+ message: 'Reconnecting... 1/1',
76
+ } }],
77
+ );
78
+ assert.doesNotMatch(stderr, /Reconnecting/);
79
+ assert.doesNotMatch(stderr, /acquire timed out|handshake failed|terminal/i);
80
+ } finally {
81
+ process.stderr.write = oldWrite;
82
+ if (oldQuiet == null) delete process.env.MIXDOG_QUIET_PROVIDER_LOG;
83
+ else process.env.MIXDOG_QUIET_PROVIDER_LOG = oldQuiet;
84
+ }
85
+ });
86
+
87
+ for (const failure of ['callback error', 'callback timeout']) {
88
+ test(`send ${failure} drops the socket and retries on a fresh one`, async () => {
89
+ const acquires = [];
90
+ const sockets = [];
91
+ let acquireIndex = 0;
92
+ const result = await sendViaWebSocket(wsArgs({
93
+ _acquireWithRetryFn: async (opts) => {
94
+ acquires.push(opts.forceFresh);
95
+ const isFirst = acquireIndex++ === 0;
96
+ const socket = {
97
+ readyState: 1,
98
+ terminated: false,
99
+ send(_payload, callback) {
100
+ if (!isFirst) queueMicrotask(() => callback());
101
+ else if (failure === 'callback error') {
102
+ queueMicrotask(() => callback(new Error('write failed')));
103
+ }
104
+ },
105
+ terminate() {
106
+ this.terminated = true;
107
+ this.readyState = 3;
108
+ },
109
+ close() {
110
+ this.readyState = 3;
111
+ },
112
+ };
113
+ sockets.push(socket);
114
+ return { entry: { socket }, reused: false };
115
+ },
116
+ _sendFrameFn: (wsEntry, frame, span) => _sendFrame(wsEntry, frame, span, 10),
117
+ _streamFn: async () => ({
118
+ content: 'recovered',
119
+ model: 'gpt-5.5',
120
+ toolCalls: [],
121
+ usage: {},
122
+ closeSocket: true,
123
+ }),
124
+ }));
125
+
126
+ assert.equal(result.content, 'recovered');
127
+ assert.deepEqual(acquires, [false, true]);
128
+ assert.equal(sockets[0].terminated, true);
129
+ assert.notEqual(sockets[1], sockets[0]);
130
+ });
131
+ }
132
+
30
133
  test('pre-response 1006 opens a fresh WS and replays the same request', async () => {
31
134
  const acquires = [];
32
135
  const frames = [];
136
+ const stages = [];
137
+ let stderr = '';
138
+ const oldWrite = process.stderr.write;
33
139
  let streams = 0;
34
- const result = await sendViaWebSocket(wsArgs({
35
- _acquireWithRetryFn: async (opts) => {
36
- acquires.push(opts.forceFresh);
37
- return { entry: entry(), reused: false };
38
- },
39
- _sendFrameFn: async (_entry, frame) => { frames.push(frame); },
40
- _streamFn: async () => {
41
- streams += 1;
42
- if (streams === 1) throw close1006();
43
- return { content: 'recovered', model: 'gpt-5.5', toolCalls: [], usage: {}, closeSocket: true };
44
- },
45
- }));
140
+ let result;
141
+ try {
142
+ process.stderr.write = (chunk) => {
143
+ stderr += String(chunk);
144
+ return true;
145
+ };
146
+ result = await sendViaWebSocket(wsArgs({
147
+ onStageChange: (stage, detail) => stages.push({ stage, detail }),
148
+ _acquireWithRetryFn: async (opts) => {
149
+ acquires.push(opts.forceFresh);
150
+ return { entry: entry(), reused: false };
151
+ },
152
+ _sendFrameFn: async (_entry, frame) => { frames.push(frame); },
153
+ _streamFn: async () => {
154
+ streams += 1;
155
+ if (streams === 1) throw close1006();
156
+ return { content: 'recovered', model: 'gpt-5.5', toolCalls: [], usage: {}, closeSocket: true };
157
+ },
158
+ }));
159
+ } finally {
160
+ process.stderr.write = oldWrite;
161
+ }
46
162
 
47
163
  assert.equal(result.content, 'recovered');
48
164
  assert.deepEqual(acquires, [false, true], 'retry must acquire a fresh socket');
49
165
  assert.equal(frames.length, 2);
50
166
  assert.deepEqual(frames[1].input, frames[0].input, 'retry must replay the same input');
51
167
  assert.equal(result.__midstreamRetries, 1);
168
+ assert.deepEqual(
169
+ stages.filter(({ stage }) => stage === 'reconnecting'),
170
+ [{ stage: 'reconnecting', detail: {
171
+ attempt: 1,
172
+ max: 4,
173
+ classifier: 'ws_1006',
174
+ message: 'Reconnecting... 1/4',
175
+ } }],
176
+ );
177
+ assert.doesNotMatch(stderr, /mid-stream recovered|Reconnecting/);
52
178
  });
53
179
 
54
180
  test('successful iteration emits one compact send-spans row', async () => {
@@ -97,7 +223,7 @@ test('exhausted pre-response 1006 retries reach the HTTP/SSE fallback', async ()
97
223
  provider.ensureAuth = async () => ({ access_token: 'test-token' });
98
224
  let streamAttempts = 0;
99
225
  let httpCalls = 0;
100
- const result = await provider.send([], 'gpt-5.5', [], {
226
+ const sendOpts = {
101
227
  sessionId: 'openai-oauth-ws-1006-fallback-test',
102
228
  _prebuiltBody: { model: 'gpt-5.5', input: [], prompt_cache_key: 'openai-oauth-ws-1006-fallback-test' },
103
229
  _sendViaWebSocketFn: (args) => sendViaWebSocket({
@@ -114,11 +240,14 @@ test('exhausted pre-response 1006 retries reach the HTTP/SSE fallback', async ()
114
240
  httpCalls += 1;
115
241
  return { content: 'http-recovered', toolCalls: [], usage: {} };
116
242
  },
117
- });
243
+ };
244
+ const result = await provider.send([], 'gpt-5.5', [], sendOpts);
245
+ const stickyResult = await provider.send([], 'gpt-5.5', [], sendOpts);
118
246
 
119
247
  assert.equal(streamAttempts, 5, 'all bounded ws_1006 attempts must run before fallback');
120
- assert.equal(httpCalls, 1);
248
+ assert.equal(httpCalls, 2);
121
249
  assert.equal(result.content, 'http-recovered');
250
+ assert.equal(stickyResult.content, 'http-recovered');
122
251
  } finally {
123
252
  for (const [name, value] of Object.entries(savedEnv)) {
124
253
  if (value == null) delete process.env[name];
@@ -127,6 +256,155 @@ test('exhausted pre-response 1006 retries reach the HTTP/SSE fallback', async ()
127
256
  }
128
257
  });
129
258
 
259
+ test('sticky HTTP fallback is isolated by session and expired entries are cleaned', async () => {
260
+ const savedEnv = Object.fromEntries([
261
+ 'MIXDOG_OAI_TRANSPORT',
262
+ 'MIXDOG_OPENAI_HTTP_FALLBACK',
263
+ 'MIXDOG_OPENAI_OAUTH_WS_WARMUP',
264
+ 'MIXDOG_AGENT_TRACE_DISABLE',
265
+ ].map((name) => [name, process.env[name]]));
266
+ Object.assign(process.env, {
267
+ MIXDOG_OAI_TRANSPORT: 'auto',
268
+ MIXDOG_OPENAI_HTTP_FALLBACK: '1',
269
+ MIXDOG_OPENAI_OAUTH_WS_WARMUP: '0',
270
+ MIXDOG_AGENT_TRACE_DISABLE: '1',
271
+ });
272
+ try {
273
+ const provider = new OpenAIOAuthProvider({});
274
+ provider.ensureAuth = async () => ({ access_token: 'test-token' });
275
+ const wsCalls = [];
276
+ const httpCalls = [];
277
+ let sessionAFailed = false;
278
+ const sendFor = (sessionId) => provider.send([], 'gpt-5.5', [], {
279
+ sessionId,
280
+ _prebuiltBody: { model: 'gpt-5.5', input: [], prompt_cache_key: sessionId },
281
+ _sendViaWebSocketFn: async () => {
282
+ wsCalls.push(sessionId);
283
+ if (sessionId === 'sticky-session-a' && !sessionAFailed) {
284
+ sessionAFailed = true;
285
+ throw Object.assign(new Error('ws retries exhausted'), {
286
+ code: 'ECONNRESET',
287
+ retryClassifier: 'reset',
288
+ wsRetriesExhausted: true,
289
+ });
290
+ }
291
+ return { content: `ws-${sessionId}`, toolCalls: [], usage: {} };
292
+ },
293
+ _sendViaHttpSseFn: async () => {
294
+ httpCalls.push(sessionId);
295
+ return { content: `http-${sessionId}`, toolCalls: [], usage: {} };
296
+ },
297
+ });
298
+
299
+ assert.equal((await sendFor('sticky-session-a')).content, 'http-sticky-session-a');
300
+ assert.equal((await sendFor('sticky-session-b')).content, 'ws-sticky-session-b');
301
+ assert.equal((await sendFor('sticky-session-a')).content, 'http-sticky-session-a');
302
+ assert.deepEqual(wsCalls, ['sticky-session-a', 'sticky-session-b']);
303
+ assert.deepEqual(httpCalls, ['sticky-session-a', 'sticky-session-a']);
304
+
305
+ provider._httpFallbackUntilByPoolKey.set('sticky-session-a', Date.now() - 1);
306
+ assert.equal((await sendFor('sticky-session-a')).content, 'ws-sticky-session-a');
307
+ assert.equal(provider._httpFallbackUntilByPoolKey.has('sticky-session-a'), false);
308
+ } finally {
309
+ for (const [name, value] of Object.entries(savedEnv)) {
310
+ if (value == null) delete process.env[name];
311
+ else process.env[name] = value;
312
+ }
313
+ }
314
+ });
315
+
316
+ test('close 1000 after tool dispatch refuses WS replay and HTTP fallback', async () => {
317
+ const savedEnv = Object.fromEntries([
318
+ 'MIXDOG_OAI_TRANSPORT',
319
+ 'MIXDOG_OPENAI_HTTP_FALLBACK',
320
+ 'MIXDOG_OPENAI_OAUTH_WS_WARMUP',
321
+ 'MIXDOG_AGENT_TRACE_DISABLE',
322
+ ].map((name) => [name, process.env[name]]));
323
+ Object.assign(process.env, {
324
+ MIXDOG_OAI_TRANSPORT: 'auto',
325
+ MIXDOG_OPENAI_HTTP_FALLBACK: '1',
326
+ MIXDOG_OPENAI_OAUTH_WS_WARMUP: '0',
327
+ MIXDOG_AGENT_TRACE_DISABLE: '1',
328
+ });
329
+ try {
330
+ const provider = new OpenAIOAuthProvider({});
331
+ provider.ensureAuth = async () => ({ access_token: 'test-token' });
332
+ let acquires = 0;
333
+ let httpCalls = 0;
334
+ await assert.rejects(
335
+ provider.send([], 'gpt-5.5', [], {
336
+ sessionId: 'openai-oauth-ws-1000-tool-test',
337
+ _prebuiltBody: { model: 'gpt-5.5', input: [], prompt_cache_key: 'openai-oauth-ws-1000-tool-test' },
338
+ _sendViaWebSocketFn: (args) => sendViaWebSocket({
339
+ ...args,
340
+ _acquireWithRetryFn: async () => {
341
+ acquires += 1;
342
+ return { entry: entry(), reused: false };
343
+ },
344
+ _sendFrameFn: async () => {},
345
+ _streamFn: async ({ state }) => {
346
+ state.sawResponseCreated = true;
347
+ state.emittedToolCall = true;
348
+ throw Object.assign(new Error('WebSocket closed normally before completion'), {
349
+ wsCloseCode: 1000,
350
+ });
351
+ },
352
+ }),
353
+ _sendViaHttpSseFn: async () => {
354
+ httpCalls += 1;
355
+ return { content: 'unsafe fallback', toolCalls: [], usage: {} };
356
+ },
357
+ }),
358
+ (err) => err.wsCloseCode === 1000
359
+ && err.emittedToolCall === true
360
+ && err.unsafeToRetry === true,
361
+ );
362
+ assert.equal(acquires, 1);
363
+ assert.equal(httpCalls, 0);
364
+ } finally {
365
+ for (const [name, value] of Object.entries(savedEnv)) {
366
+ if (value == null) delete process.env[name];
367
+ else process.env[name] = value;
368
+ }
369
+ }
370
+ });
371
+
372
+ test('post-tool unknown-model errors never refresh or recursively replay', async () => {
373
+ for (const shape of [
374
+ { httpStatus: 404, message: 'not found' },
375
+ { message: 'model_not_found: unavailable model' },
376
+ ]) {
377
+ const provider = new OpenAIOAuthProvider({});
378
+ provider.ensureAuth = async () => ({ access_token: 'test-token' });
379
+ let wsCalls = 0;
380
+ let refreshCalls = 0;
381
+ provider._refreshModelCache = async () => {
382
+ refreshCalls += 1;
383
+ return [];
384
+ };
385
+ const unsafe = Object.assign(new Error(shape.message), shape, {
386
+ emittedToolCall: true,
387
+ unsafeToRetry: true,
388
+ });
389
+ await assert.rejects(
390
+ provider.send([], 'gpt-5.5', [], {
391
+ sessionId: `post-tool-model-${shape.httpStatus || 'message'}`,
392
+ _prebuiltBody: { model: 'gpt-5.5', input: [] },
393
+ _sendViaWebSocketFn: async () => {
394
+ wsCalls += 1;
395
+ throw unsafe;
396
+ },
397
+ _sendViaHttpSseFn: async () => {
398
+ throw new Error('unsafe HTTP fallback');
399
+ },
400
+ }),
401
+ (err) => err === unsafe,
402
+ );
403
+ assert.equal(wsCalls, 1);
404
+ assert.equal(refreshCalls, 0);
405
+ }
406
+ });
407
+
130
408
  test('post-emission 1006 refuses replay after text or tool output', async () => {
131
409
  for (const emitted of ['emittedText', 'emittedToolCall']) {
132
410
  let acquires = 0;