forked from dwgx/WindsurfAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcascade-native-bridge.test.js
More file actions
874 lines (804 loc) · 38.8 KB
/
Copy pathcascade-native-bridge.test.js
File metadata and controls
874 lines (804 loc) · 38.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
// v2.0.65 (#115) — Cascade native tool bridge.
//
// Validates that:
// 1. canMapAllTools correctly admits supported tools and rejects mixed/
// unknown sets so emulation fallback fires.
// 2. Forward + reverse argument translators round-trip per known tool.
// 3. shouldUseNativeBridge auto-on heuristic fires for GPT/responses,
// stays off for Claude/Gemini and for unmapped tools.
// 4. buildAdditionalStepsFromHistory produces decodable trajectory step
// protos when prior assistant tool_calls + tool results are present.
// 5. windsurf.parseTrajectorySteps surfaces native cascade step kinds
// (view_file=14, run_command=28, grep_search_v2=105, find=34,
// list_directory=15, write_to_file=23) as toolCalls with
// cascade_native:true and the right name + args.
// 6. buildSendCascadeMessageRequest writes additional_steps to field 9
// (repeated CortexTrajectoryStep).
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import {
TOOL_MAP, CASCADE_STEP,
canMapAllTools, partitionTools, shouldUseNativeBridge,
buildAdditionalStep, buildAdditionalStepsFromHistory, buildReverseLookup,
parseNativeFunctionCallsFromText, NativeFunctionCallStreamParser,
} from '../src/cascade-native-bridge.js';
import {
parseTrajectorySteps,
buildSendCascadeMessageRequest,
} from '../src/windsurf.js';
import {
parseFields, getField, getAllFields, writeMessageField, writeVarintField, writeStringField,
} from '../src/proto.js';
const fnTool = (name) => ({ type: 'function', function: { name, parameters: { type: 'object' } } });
describe('canMapAllTools', () => {
it('admits only mature default-native tools without an explicit tool allowlist', () => {
const prev = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
try {
assert.equal(canMapAllTools([fnTool('Bash'), fnTool('shell_command'), fnTool('run_command')]), true);
assert.equal(canMapAllTools([fnTool('Read'), fnTool('Bash'), fnTool('Glob')]), false);
} finally {
if (prev === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = prev;
}
});
it('rejects when ANY tool is unmapped', () => {
assert.equal(canMapAllTools([fnTool('Read'), fnTool('get_weather')]), false);
});
it('rejects empty / non-array input', () => {
assert.equal(canMapAllTools([]), false);
assert.equal(canMapAllTools(null), false);
assert.equal(canMapAllTools(undefined), false);
});
it('admits Codex-style command names by default and other native names only when allowlisted', () => {
const prev = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
try {
assert.equal(canMapAllTools([fnTool('run_command')]), true);
assert.equal(canMapAllTools([fnTool('view_file'), fnTool('run_command'), fnTool('find')]), false);
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = 'view_file,run_command,find';
assert.equal(canMapAllTools([fnTool('view_file'), fnTool('run_command'), fnTool('find')]), true);
} finally {
if (prev === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = prev;
}
});
it('admits mixed Claude Code + Codex names when explicitly allowlisted', () => {
const prev = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = 'Read,run_command,Grep';
try {
assert.equal(canMapAllTools([fnTool('Read'), fnTool('run_command'), fnTool('Grep')]), true);
} finally {
if (prev === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = prev;
}
});
});
describe('shouldUseNativeBridge — auto-on heuristic', () => {
const tools = [fnTool('Read'), fnTool('Bash')];
it('GPT family on /v1/responses route → OFF (v2.0.70 reverts auto-on for GPT — cascade native grammar makes GPT fabricate)', () => {
// v2.0.66 had GPT auto-on, v2.0.70 reverts after end-to-end probe
// showed markers=none and PROBE fabricated. GPT family now goes
// through emulation + gpt_native dialect.
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'gpt-5.5-medium', provider: 'openai', route: 'responses' }),
false,
);
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'o4-mini', provider: 'openai', route: 'responses' }),
false,
);
});
it('GPT family on /v1/chat/completions → off (default emulation path)', () => {
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'gpt-5.5-medium', provider: 'openai', route: 'chat' }),
false,
);
});
it('Anthropic Claude → OFF by default (v2.0.75 #124 regression fix — bridge runs tools in REMOTE cascade sandbox, but client tools expect LOCAL execution; hang forever)', () => {
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'claude-sonnet-4.6', provider: 'anthropic', route: 'responses' }),
false,
);
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'claude-sonnet-4.6', provider: 'anthropic', route: 'chat' }),
false,
);
});
it('Gemini → off (no auto-on — emulation works fine for it)', () => {
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'gemini-2.5-flash', provider: 'google', route: 'responses' }),
false,
);
});
it('partial-mapped tools on Claude → OFF (post-v2.0.75 — same #124 logic, no client wants remote execution by default)', () => {
assert.equal(
shouldUseNativeBridge([fnTool('Read'), fnTool('get_weather')], {
modelKey: 'claude-sonnet-4.6', provider: 'anthropic', route: 'responses',
}),
false,
);
});
it('zero mapped tools → off (no point booting native path)', () => {
assert.equal(
shouldUseNativeBridge([fnTool('get_weather'), fnTool('update_plan')], {
modelKey: 'gpt-5.5-medium', provider: 'openai', route: 'responses',
}),
false,
);
});
it('explicit env override forces on for any mapped tool set (deployer opting into remote execution)', () => {
const orig = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE;
const toolsOrig = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE = '1';
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = 'Read,Bash';
try {
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'claude-sonnet-4-6', provider: 'anthropic', route: 'chat' }),
true,
);
// GPT too, when explicitly enabled.
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'gpt-5.5-medium', provider: 'openai', route: 'responses' }),
true,
);
} finally {
if (orig === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE = orig;
if (toolsOrig === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = toolsOrig;
}
});
it('all_mapped mode enables only when every function tool maps', () => {
const orig = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE;
const toolsOrig = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE = 'all_mapped';
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = 'Read,Bash,Grep,Glob';
try {
assert.equal(
shouldUseNativeBridge([fnTool('Read'), fnTool('Bash'), fnTool('Grep'), fnTool('Glob')], {
modelKey: 'claude-sonnet-4.6', provider: 'anthropic', route: 'chat',
}),
true,
);
assert.equal(
shouldUseNativeBridge([fnTool('Read'), fnTool('Bash'), fnTool('update_plan')], {
modelKey: 'claude-sonnet-4.6', provider: 'anthropic', route: 'chat',
}),
false,
);
} finally {
if (orig === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE = orig;
if (toolsOrig === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_TOOLS = toolsOrig;
}
});
it('OFF override beats auto-on', () => {
const offOrig = process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_OFF;
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_OFF = '1';
try {
assert.equal(
shouldUseNativeBridge(tools, { modelKey: 'gpt-5.5-medium', provider: 'openai', route: 'responses' }),
false,
);
} finally {
if (offOrig === undefined) delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_OFF;
else process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_OFF = offOrig;
}
});
});
describe('TOOL_MAP — forward / reverse round-trip per kind', () => {
it('Read ↔ view_file preserves file_path / offset / limit', () => {
const original = { file_path: '/abs/path/foo.ts', offset: 10, limit: 200 };
const cascade = TOOL_MAP.Read.forward(original);
assert.equal(cascade.absolute_path_uri, 'file:///abs/path/foo.ts');
assert.equal(cascade.offset, 10);
assert.equal(cascade.limit, 200);
const back = TOOL_MAP.Read.reverse(cascade);
assert.deepEqual(back, original);
});
it('Bash ↔ run_command preserves command (and cwd if present)', () => {
const original = { command: 'npm test --silent' };
const cascade = TOOL_MAP.Bash.forward(original);
assert.equal(cascade.command_line, 'npm test --silent');
const back = TOOL_MAP.Bash.reverse(cascade);
assert.equal(back.command, 'npm test --silent');
// cwd round-trip
const withCwd = TOOL_MAP.Bash.forward({ command: 'ls', cwd: '/tmp' });
assert.equal(TOOL_MAP.Bash.reverse(withCwd).cwd, '/tmp');
});
it('Grep ↔ grep_search_v2 preserves pattern + flags', () => {
const original = { pattern: 'foo', '-i': true, head_limit: 50, glob: '*.js' };
const cascade = TOOL_MAP.Grep.forward(original);
assert.equal(cascade.pattern, 'foo');
assert.equal(cascade.case_insensitive, true);
assert.equal(cascade.head_limit, 50);
assert.equal(cascade.glob, '*.js');
const back = TOOL_MAP.Grep.reverse(cascade);
assert.equal(back.pattern, 'foo');
assert.equal(back['-i'], true);
assert.equal(back.head_limit, 50);
assert.equal(back.glob, '*.js');
});
it('Glob ↔ find preserves pattern + path', () => {
const cascade = TOOL_MAP.Glob.forward({ pattern: '**/*.ts', path: 'src' });
assert.equal(cascade.pattern, '**/*.ts');
assert.equal(cascade.search_directory, 'src');
const back = TOOL_MAP.Glob.reverse(cascade);
assert.equal(back.pattern, '**/*.ts');
assert.equal(back.path, 'src');
});
it('Write ↔ write_to_file preserves file_path + content', () => {
const cascade = TOOL_MAP.Write.forward({ file_path: '/tmp/x.txt', content: 'hello\n' });
assert.equal(cascade.target_file_uri, 'file:///tmp/x.txt');
assert.deepEqual(cascade.code_content, ['hello\n']);
const back = TOOL_MAP.Write.reverse(cascade);
assert.equal(back.file_path, '/tmp/x.txt');
assert.equal(back.content, 'hello\n');
});
});
describe('buildReverseLookup', () => {
it('inverts caller tools by cascade kind', () => {
const lookup = buildReverseLookup([fnTool('Read'), fnTool('Bash'), fnTool('Grep')]);
assert.deepEqual(lookup.get('view_file'), ['Read']);
assert.deepEqual(lookup.get('run_command'), ['Bash']);
assert.deepEqual(lookup.get('grep_search_v2'), ['Grep']);
});
it('returns empty map for empty input', () => {
const lookup = buildReverseLookup([]);
assert.equal(lookup.size, 0);
});
it('handles caller declaring multiple tools that map to same kind', () => {
const lookup = buildReverseLookup([fnTool('Read'), fnTool('view_file'), fnTool('read_file')]);
const list = lookup.get('view_file');
assert.ok(list.includes('Read'));
assert.ok(list.includes('view_file'));
assert.ok(list.includes('read_file'));
});
});
describe('parseNativeFunctionCallsFromText', () => {
it('maps Claude provider-native read_file invoke back to caller Read', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const out = parseNativeFunctionCallsFromText(
'I will inspect it.\n<function_calls>\n<invoke name="read_file">\n<parameter name="path">/tmp/a.txt</parameter>\n</invoke>\n</function_calls>',
lookup,
);
assert.equal(out.toolCalls.length, 1);
assert.equal(out.toolCalls[0].name, 'Read');
assert.deepEqual(JSON.parse(out.toolCalls[0].argumentsJson), { file_path: '/tmp/a.txt' });
assert.ok(!out.text.includes('<function_calls>'));
assert.ok(!out.text.includes('<invoke'));
});
it('drops unknown invokes instead of leaking XML or inventing caller tools', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const text = '<function_calls><invoke name="unknown_tool"><parameter name="x">1</parameter></invoke></function_calls>';
const out = parseNativeFunctionCallsFromText(text, lookup);
assert.equal(out.toolCalls.length, 0);
assert.equal(out.text, '');
});
it('drops known invokes when the caller did not declare a matching tool', () => {
const lookup = buildReverseLookup([fnTool('Bash')]);
const text = 'before <function_calls><invoke name="read_file"><parameter name="path">README.md</parameter></invoke></function_calls> after';
const out = parseNativeFunctionCallsFromText(text, lookup);
assert.equal(out.toolCalls.length, 0);
assert.equal(out.text, 'before after');
});
it('stream parser withholds provider-native XML until it can emit a tool_call', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const parser = new NativeFunctionCallStreamParser(lookup);
const a = parser.feed('<function_calls>\n<invoke name="read_file">\n');
assert.equal(a.text, '');
assert.equal(a.toolCalls.length, 0);
const b = parser.feed('<parameter name="path">README.md</parameter>\n');
assert.equal(b.text, '');
assert.equal(b.toolCalls.length, 0);
const c = parser.feed('</invoke>\n</function_calls>');
assert.equal(c.text, '');
assert.equal(c.toolCalls.length, 1);
assert.equal(c.toolCalls[0].name, 'Read');
assert.deepEqual(JSON.parse(c.toolCalls[0].argumentsJson), { file_path: 'README.md' });
const tail = parser.flush();
assert.equal(tail.text, '');
assert.equal(tail.toolCalls.length, 0);
});
it('stream parser holds partial opening tags across chunk boundaries', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const parser = new NativeFunctionCallStreamParser(lookup);
const a = parser.feed('prefix <fun');
assert.equal(a.text, 'prefix ');
assert.equal(a.toolCalls.length, 0);
const b = parser.feed('ction_calls><invoke name="read_file"><parameter name="path">a.txt</parameter></invoke></function_calls> suffix');
assert.equal(b.text, ' suffix');
assert.equal(b.toolCalls.length, 1);
assert.deepEqual(JSON.parse(b.toolCalls[0].argumentsJson), { file_path: 'a.txt' });
});
it('stream parser drops incomplete XML on flush', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const parser = new NativeFunctionCallStreamParser(lookup);
assert.deepEqual(parser.feed('start <function_calls><invoke name="read_file">'), { text: 'start ', toolCalls: [] });
const tail = parser.flush();
assert.equal(tail.text, '');
assert.equal(tail.toolCalls.length, 0);
});
it('non-stream parser drops dangling function_calls blocks', () => {
const lookup = buildReverseLookup([fnTool('Read')]);
const out = parseNativeFunctionCallsFromText('prefix <function_calls><invoke name="read_file">', lookup);
assert.equal(out.text, 'prefix');
assert.equal(out.toolCalls.length, 0);
});
});
describe('buildAdditionalStep / buildAdditionalStepsFromHistory', () => {
it('view_file step encodes envelope with type=14 + content overlay', () => {
const buf = buildAdditionalStep('view_file', {
absolute_path_uri: 'file:///foo.ts',
content: 'console.log("hi")',
});
assert.ok(Buffer.isBuffer(buf));
const fields = parseFields(buf);
const typeField = getField(fields, 1, 0);
assert.equal(typeField.value, 14);
const oneof = getField(fields, 14, 2);
assert.ok(oneof, 'view_file body should be on field 14');
const body = parseFields(oneof.value);
assert.equal(getField(body, 1, 2).value.toString('utf8'), 'file:///foo.ts');
assert.equal(getField(body, 4, 2).value.toString('utf8'), 'console.log("hi")');
});
it('run_command step puts command_line on field 23 + combined_output on 21', () => {
const buf = buildAdditionalStep('run_command', {
command_line: 'echo hi',
full_output: 'hi\n',
exit_code: 0,
});
const fields = parseFields(buf);
assert.equal(getField(fields, 1, 0).value, 28);
const body = parseFields(getField(fields, 28, 2).value);
assert.equal(getField(body, 23, 2).value.toString('utf8'), 'echo hi');
const combined = parseFields(getField(body, 21, 2).value);
assert.equal(getField(combined, 1, 2).value.toString('utf8'), 'hi\n');
});
it('full assistant→tool history → trajectory step buffers', () => {
const messages = [
{ role: 'user', content: 'find me a file' },
{
role: 'assistant',
content: null,
tool_calls: [{
id: 'call_1',
type: 'function',
function: { name: 'Read', arguments: JSON.stringify({ file_path: '/etc/hosts' }) },
}],
},
{ role: 'tool', tool_call_id: 'call_1', content: '127.0.0.1 localhost\n' },
];
const steps = buildAdditionalStepsFromHistory(messages);
assert.equal(steps.length, 1);
const fields = parseFields(steps[0]);
assert.equal(getField(fields, 1, 0).value, 14); // CortexStepType view_file = 14
const body = parseFields(getField(fields, 14, 2).value);
assert.equal(getField(body, 4, 2).value.toString('utf8'), '127.0.0.1 localhost\n');
});
it('WebFetch history encodes tool result as read_url_content web_document', () => {
const messages = [
{
role: 'assistant',
content: null,
tool_calls: [{
id: 'call_fetch',
type: 'function',
function: { name: 'WebFetch', arguments: JSON.stringify({ url: 'https://example.com/docs' }) },
}],
},
{ role: 'tool', tool_call_id: 'call_fetch', content: 'fetched document body' },
];
const steps = buildAdditionalStepsFromHistory(messages);
assert.equal(steps.length, 1);
const fields = parseFields(steps[0]);
assert.equal(getField(fields, 1, 0).value, 40);
const body = parseFields(getField(fields, 40, 2).value);
assert.equal(getField(body, 1, 2).value.toString('utf8'), 'https://example.com/docs');
assert.equal(getField(body, 5, 2), null, 'read_url_content must not encode legacy top-level summary field 5');
const doc = parseFields(getField(body, 2, 2).value);
assert.equal(getField(doc, 2, 2).value.toString('utf8'), 'fetched document body');
assert.equal(getField(doc, 3, 2).value.toString('utf8'), 'https://example.com/docs');
});
it('skips unmapped tool_calls (fall back to emulation path)', () => {
const messages = [
{
role: 'assistant',
tool_calls: [{
id: 'call_x',
function: { name: 'get_weather', arguments: '{}' },
}],
},
{ role: 'tool', tool_call_id: 'call_x', content: 'sunny' },
];
const steps = buildAdditionalStepsFromHistory(messages);
assert.equal(steps.length, 0);
});
});
describe('parseTrajectorySteps — native step recognition', () => {
// Helpers to build a CortexTrajectoryStep envelope by hand. We avoid
// calling buildAdditionalStep here so tests double-cover encoder / decoder
// independently.
const wrapStep = (typeEnum, oneofField, bodyBuf) =>
Buffer.concat([
writeVarintField(1, typeEnum),
writeVarintField(4, 3), // status DONE
writeMessageField(oneofField, bodyBuf),
]);
// GetCascadeTrajectoryStepsResponse is `repeated CortexTrajectoryStep steps = 1`
const wrapResponse = (...stepBufs) =>
Buffer.concat(stepBufs.map(b => writeMessageField(1, b)));
it('view_file step → toolCall with name=view_file + arguments + result', () => {
const body = Buffer.concat([
writeStringField(1, 'file:///abs/foo.ts'),
writeVarintField(11, 0),
writeVarintField(12, 100),
writeStringField(4, 'console.log("hi")\n'),
]);
const resp = wrapResponse(wrapStep(14, 14, body));
const steps = parseTrajectorySteps(resp);
assert.equal(steps.length, 1);
const calls = steps[0].toolCalls.filter(tc => tc.cascade_native);
assert.equal(calls.length, 1);
assert.equal(calls[0].name, 'view_file');
const args = JSON.parse(calls[0].argumentsJson);
assert.equal(args.absolute_path_uri, 'file:///abs/foo.ts');
assert.equal(args.limit, 100);
assert.equal(calls[0].result, 'console.log("hi")\n');
});
it('run_command step → toolCall with combined_output observation', () => {
const combinedOutput = writeStringField(1, 'hi\n');
const body = Buffer.concat([
writeStringField(23, 'echo hi'),
writeMessageField(21, combinedOutput),
]);
const resp = wrapResponse(wrapStep(28, 28, body));
const steps = parseTrajectorySteps(resp);
const calls = steps[0].toolCalls.filter(tc => tc.cascade_native);
assert.equal(calls.length, 1);
assert.equal(calls[0].name, 'run_command');
assert.equal(calls[0].result, 'hi\n');
const args = JSON.parse(calls[0].argumentsJson);
assert.equal(args.command_line, 'echo hi');
});
it('grep_search_v2 step (field 105) → toolCall name grep_search_v2', () => {
const body = Buffer.concat([
writeStringField(2, 'todo'),
writeStringField(3, 'src'),
writeStringField(15, 'src/foo.ts:10:// todo\n'),
]);
const resp = wrapResponse(wrapStep(105, 105, body));
const steps = parseTrajectorySteps(resp);
const calls = steps[0].toolCalls.filter(tc => tc.cascade_native);
assert.equal(calls.length, 1);
assert.equal(calls[0].name, 'grep_search_v2');
assert.equal(calls[0].result, 'src/foo.ts:10:// todo\n');
});
it('list_directory step → children joined as result', () => {
const body = Buffer.concat([
writeStringField(1, 'file:///src'),
writeStringField(2, 'foo.ts'),
writeStringField(2, 'bar.ts'),
]);
const resp = wrapResponse(wrapStep(15, 15, body));
const steps = parseTrajectorySteps(resp);
const calls = steps[0].toolCalls.filter(tc => tc.cascade_native);
assert.equal(calls.length, 1);
assert.equal(calls[0].name, 'list_directory');
assert.equal(calls[0].result, 'foo.ts\nbar.ts');
});
it('multiple native steps in same trajectory all surface', () => {
const viewBody = Buffer.concat([writeStringField(1, 'file:///a.ts'), writeStringField(4, 'A')]);
const cmdBody = Buffer.concat([writeStringField(23, 'ls'), writeMessageField(21, writeStringField(1, 'a.ts\n'))]);
const resp = wrapResponse(wrapStep(14, 14, viewBody), wrapStep(28, 28, cmdBody));
const steps = parseTrajectorySteps(resp);
assert.equal(steps.length, 2);
assert.equal(steps[0].toolCalls.filter(tc => tc.cascade_native).length, 1);
assert.equal(steps[1].toolCalls.filter(tc => tc.cascade_native).length, 1);
});
});
describe('buildSendCascadeMessageRequest — additional_steps on field 9', () => {
it('includes each step as repeated field 9', () => {
const stepA = buildAdditionalStep('view_file', { absolute_path_uri: 'file:///a', content: 'A' });
const stepB = buildAdditionalStep('run_command', { command_line: 'ls', full_output: 'a\n' });
const proto = buildSendCascadeMessageRequest(
'k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess',
{ additionalSteps: [stepA, stepB] },
);
const fields = parseFields(proto);
const additional = getAllFields(fields, 9).filter(f => f.wireType === 2);
assert.equal(additional.length, 2, 'two repeated additional_steps expected on field 9');
});
it('omits field 9 when no additionalSteps provided', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {});
const fields = parseFields(proto);
assert.equal(getAllFields(fields, 9).length, 0);
});
it('nativeMode=true switches planner_mode to DEFAULT (1) and adds tool_config', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['view_file', 'run_command'],
});
const top = parseFields(proto);
const cfgField = getField(top, 5, 2);
assert.ok(cfgField, 'cascade_config required on field 5');
const cfg = parseFields(cfgField.value);
const planner = parseFields(getField(cfg, 1, 2).value);
// CascadePlannerConfig.tool_config = field 13 (CascadeToolConfig)
const toolCfg = getField(planner, 13, 2);
assert.ok(toolCfg, 'CascadePlannerConfig.tool_config (field 13) should be set in nativeMode');
const tc = parseFields(toolCfg.value);
const allow = getAllFields(tc, 32).map(f => f.value.toString('utf8'));
assert.ok(allow.includes('view_file'));
assert.ok(allow.includes('run_command'));
// conversational planner sub-config (field 2) → planner_mode (field 4) = DEFAULT (1)
const conv = parseFields(getField(planner, 2, 2).value);
const mode = getField(conv, 4, 0);
assert.equal(mode.value, 1, 'planner_mode in nativeMode should be DEFAULT (1)');
assert.equal(getField(conv, 10, 2), null, 'nativeMode must not write a no-tool tool_calling_section');
assert.equal(getField(conv, 12, 2), null, 'nativeMode must not write a no-tool additional_instructions_section');
});
it('native allowlist experiment aliases still enable the matching tool sub-configs', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['read_file', 'grep_v2', 'list_dir'],
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const tc = parseFields(getField(planner, 13, 2).value);
const allow = getAllFields(tc, 32).map(f => f.value.toString('utf8'));
assert.deepEqual(allow, ['read_file', 'grep_v2', 'list_dir']);
assert.ok(getField(tc, 10, 2), 'read_file should still enable ViewFileToolConfig field 10');
assert.ok(getField(tc, 33, 2), 'grep_v2 should still enable GrepV2ToolConfig field 33');
assert.ok(getField(tc, 19, 2), 'list_dir should enable ListDirToolConfig field 19');
assert.equal(getField(tc, 5, 2), null, 'list_dir experiment should not also enable FindToolConfig');
});
it('native tool config raw overrides inject exact sub-config bytes for protocol experiments', () => {
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW = 'read_file:0a03616263;grep_v2:base64:EgJwYQ==';
try {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['read_file', 'grep_v2'],
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const tc = parseFields(getField(planner, 13, 2).value);
assert.equal(getField(tc, 10, 2).value.toString('hex'), '0a03616263');
assert.equal(getField(tc, 33, 2).value.toString('hex'), '12027061');
assert.deepEqual(getAllFields(tc, 32).map(f => f.value.toString('utf8')), ['read_file', 'grep_v2']);
} finally {
delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW;
}
});
it('native tool config raw overrides can inject unknown top-level fields for matrix experiments', () => {
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW = 'field42:0a03776562;field40:';
try {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['search_web', 'read_url_content'],
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const tc = parseFields(getField(planner, 13, 2).value);
assert.equal(getField(tc, 42, 2).value.toString('hex'), '0a03776562');
assert.equal(getField(tc, 40, 2).value.length, 0);
assert.deepEqual(getAllFields(tc, 32).map(f => f.value.toString('utf8')), ['search_web', 'read_url_content']);
} finally {
delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW;
}
});
it('native allowlist emits confirmed WebSearch/WebFetch tool-config fields', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['search_web', 'read_url_content'],
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const tc = parseFields(getField(planner, 13, 2).value);
assert.equal(getField(tc, 13, 2).value.length, 0, 'search_web should use SearchWebToolConfig field 13');
assert.equal(getField(tc, 37, 2).value.length, 0, 'read_url_content should use ReadUrlContentToolConfig field 37');
assert.deepEqual(getAllFields(tc, 32).map(f => f.value.toString('utf8')), ['search_web', 'read_url_content']);
});
it('native tool config raw overrides support web tool aliases', () => {
process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW = 'search_web:0800;read_url_content:0a00';
try {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['search_web', 'read_url_content'],
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const tc = parseFields(getField(planner, 13, 2).value);
assert.equal(getField(tc, 13, 2).value.toString('hex'), '0800');
assert.equal(getField(tc, 37, 2).value.toString('hex'), '0a00');
} finally {
delete process.env.WINDSURFAPI_NATIVE_TOOL_BRIDGE_CONFIG_RAW;
}
});
it('nativeMode=true can carry environment facts without tool emulation schema', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {
nativeMode: true,
nativeAllowlist: ['view_file'],
nativeEnvironment: '- Working directory: /repo\n- Platform: linux',
});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
const conv = parseFields(getField(planner, 2, 2).value);
assert.equal(getField(conv, 4, 0).value, 1, 'nativeMode still uses DEFAULT planner');
assert.equal(getField(conv, 10, 2), null, 'native env must not inject tool_calling_section schemas');
const additional = getField(conv, 12, 2);
assert.ok(additional, 'native env should be written to additional_instructions_section');
const section = parseFields(additional.value);
const text = getField(section, 2, 2)?.value?.toString('utf8') || '';
assert.match(text, /Working directory: \/repo/);
assert.match(text, /built-in IDE tools/);
assert.doesNotMatch(text, /You have access to the following functions/);
assert.doesNotMatch(text, /<tool_call>/);
});
it('nativeMode=false (default) keeps planner_mode = NO_TOOL (3) and skips tool_config', () => {
const proto = buildSendCascadeMessageRequest('k', 'cid', 'hi', 12345, 'MODEL_TEST', 'sess', {});
const top = parseFields(proto);
const cfg = parseFields(getField(top, 5, 2).value);
const planner = parseFields(getField(cfg, 1, 2).value);
assert.equal(getField(planner, 13, 2), null, 'tool_config should NOT be set when nativeMode is off');
const conv = parseFields(getField(planner, 2, 2).value);
assert.equal(getField(conv, 4, 0).value, 3);
});
});
describe('CASCADE_STEP type constants — sanity', () => {
it('matches proto field numbers used in oneof', () => {
assert.equal(CASCADE_STEP.view_file.typeEnum, 14);
assert.equal(CASCADE_STEP.run_command.typeEnum, 28);
assert.equal(CASCADE_STEP.grep_search_v2.typeEnum, 105);
assert.equal(CASCADE_STEP.find.typeEnum, 34);
assert.equal(CASCADE_STEP.list_directory.typeEnum, 15);
assert.equal(CASCADE_STEP.write_to_file.typeEnum, 23);
});
});
// ─── v2.0.66 (#115) — partition mode + codex CLI mapping ──────────────
describe('partitionTools — v2.0.66 mixed-mapping splitter', () => {
it('splits mapped vs unmapped on a real codex CLI 0.128 toolset (web_search default-off)', () => {
// Captured live from `dump-codex-tools.mjs`: codex CLI 0.128 declares
// these 11 tools by default. Native web search/fetch remain opt-in in
// the bridge allowlist, so the default mapped set stays shell-only.
const codexTools = [
'shell_command', 'update_plan', 'request_user_input',
'apply_patch', 'web_search', 'view_image',
'spawn_agent', 'send_input', 'resume_agent', 'wait_agent', 'close_agent',
].map(fnTool);
const part = partitionTools(codexTools);
assert.equal(part.hasAny, true);
const mappedNames = part.mapped.map(t => t.function.name).sort();
assert.deepEqual(mappedNames, ['shell_command']);
assert.equal(part.unmapped.length, 10);
assert.ok(part.unmapped.find(t => t.function.name === 'apply_patch'));
assert.ok(part.unmapped.find(t => t.function.name === 'update_plan'));
assert.ok(part.unmapped.find(t => t.function.name === 'web_search'));
});
it('returns hasAny=false when no tool maps', () => {
const part = partitionTools([fnTool('get_weather'), fnTool('rng')]);
assert.equal(part.hasAny, false);
assert.equal(part.mapped.length, 0);
assert.equal(part.unmapped.length, 2);
});
it('Claude Code-style tools keep Read/Glob out of the default native scope', () => {
const part = partitionTools([fnTool('Read'), fnTool('Bash'), fnTool('Glob')]);
assert.equal(part.hasAny, true);
assert.deepEqual(part.mapped.map(t => t.function.name), ['Bash']);
assert.deepEqual(part.unmapped.map(t => t.function.name), ['Read', 'Glob']);
});
it('skips non-function entries gracefully', () => {
const part = partitionTools([
fnTool('Read'),
{ type: 'web_search' },
{ type: 'function' }, // missing function.name
{ type: 'function', function: { name: '' } },
]);
assert.equal(part.mapped.length, 0);
assert.equal(part.unmapped.length, 1);
});
});
describe('TOOL_MAP — codex CLI 0.128 shell_command mapping (v2.0.66)', () => {
it('shell_command ↔ run_command preserves command + workdir', () => {
const fwd = TOOL_MAP.shell_command.forward({
command: 'pytest -x',
workdir: 'D:/Project/foo',
timeout_ms: 30000,
});
assert.equal(fwd.command_line, 'pytest -x');
assert.equal(fwd.cwd, 'D:/Project/foo');
assert.equal(fwd.blocking, true);
const back = TOOL_MAP.shell_command.reverse(fwd);
assert.equal(back.command, 'pytest -x');
assert.equal(back.workdir, 'D:/Project/foo');
});
it('shell_command reverse maps cascade combined_output → codex shell schema', () => {
// Simulates the trajectory step → tool_call reverse direction the
// proxy uses when surfacing a cascade-side run_command back to the
// codex CLI client.
const back = TOOL_MAP.shell_command.reverse({
command_line: 'echo hi',
cwd: '/tmp',
stdout: 'hi\n',
});
assert.equal(back.command, 'echo hi');
assert.equal(back.workdir, '/tmp');
});
});
describe('canMapAllTools (legacy strict gate, kept for compat)', () => {
it('still returns false when ANY tool is unmapped', () => {
assert.equal(canMapAllTools([fnTool('Read'), fnTool('get_weather')]), false);
assert.equal(canMapAllTools([fnTool('Read'), fnTool('Bash'), fnTool('Glob')]), false);
});
});
describe('mergeReasoningEffortIntoModel — v2.0.66 reasoning_effort fold-in', () => {
it('codex CLI shape (reasoning.effort) folds into bare gpt-5.5', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
assert.equal(
mergeReasoningEffortIntoModel('gpt-5.5', { reasoning: { effort: 'xhigh' } }),
'gpt-5.5-xhigh',
);
assert.equal(
mergeReasoningEffortIntoModel('gpt-5.5', { reasoning: { effort: 'high' } }),
'gpt-5.5-high',
);
});
it('OpenAI-style (top-level reasoning_effort) also works', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
assert.equal(
mergeReasoningEffortIntoModel('gpt-5.5', { reasoning_effort: 'low' }),
'gpt-5.5-low',
);
});
it('replaces an existing effort suffix when the caller sends an explicit effort field', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
assert.equal(
mergeReasoningEffortIntoModel('gpt-5.5-xhigh', { reasoning: { effort: 'medium' } }),
'gpt-5.5-medium',
);
assert.equal(
mergeReasoningEffortIntoModel('claude-opus-4-8-medium', { reasoning: { effort: 'xhigh' } }),
'claude-opus-4-8-xhigh',
);
assert.equal(
mergeReasoningEffortIntoModel('claude-opus-4.8', { reasoning_effort: 'max' }),
'claude-opus-4.8-max',
);
});
it('returns input unchanged when effort missing', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
assert.equal(mergeReasoningEffortIntoModel('gpt-5.5', {}), 'gpt-5.5');
assert.equal(mergeReasoningEffortIntoModel('gpt-5.5', { reasoning: {} }), 'gpt-5.5');
assert.equal(mergeReasoningEffortIntoModel('gpt-5.5', { reasoning: { effort: '' } }), 'gpt-5.5');
});
it('returns input unchanged for unknown effort strings (catalog has no -bogus variant)', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
assert.equal(mergeReasoningEffortIntoModel('gpt-5.5', { reasoning_effort: 'bogus' }), 'gpt-5.5');
});
it('returns input unchanged when merged model is not in catalog', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
// claude models don't have effort suffixes — the merged form
// `claude-sonnet-4.6-xhigh` doesn't exist in models.js, so the helper
// refuses to swap.
assert.equal(
mergeReasoningEffortIntoModel('claude-sonnet-4.6', { reasoning: { effort: 'xhigh' } }),
'claude-sonnet-4.6',
);
});
it('handles `minimal` by mapping to `none` (windsurf catalog naming)', async () => {
const { mergeReasoningEffortIntoModel } = await import('../src/handlers/chat.js');
// gpt-5.5-none is in the catalog (the lowest tier alias)
assert.equal(
mergeReasoningEffortIntoModel('gpt-5.5', { reasoning_effort: 'minimal' }),
'gpt-5.5-none',
);
});
});