{{ message }}
Repository navigation
Expand file tree
/
Copy pathindex.test.ts
More file actions
2168 lines (1997 loc) · 72.4 KB
/
Copy pathindex.test.ts
File metadata and controls
2168 lines (1997 loc) · 72.4 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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { envFlagsMockFns, resetEnvFlagsMock } from '@sim/testing'
import { apiKeyByokMock, apiKeyByokMockFns } from '@sim/testing/mocks/api-key-byok.mock'
import { toolsMock, toolsMockFns } from '@sim/testing/mocks/tools.mock'
import {
workspaceFileSecretProvenanceMock,
workspaceFileSecretProvenanceMockFns,
} from '@sim/testing/mocks/workspace-file-secret-provenance.mock'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { mockAttachLargeFileRemoteUrls, mockExecuteRequest, mockUploadLargeFilesToProvider } =
vi.hoisted(() => ({
mockAttachLargeFileRemoteUrls: vi.fn(),
mockExecuteRequest: vi.fn(),
mockUploadLargeFilesToProvider: vi.fn(),
}))
vi.mock('@/lib/api-key/byok', () => apiKeyByokMock)
vi.mock('@/providers/registry', () => ({
getProviderExecutor: vi.fn().mockResolvedValue({
executeRequest: (...args: unknown[]) => mockExecuteRequest(...args),
}),
}))
vi.mock('@/providers/file-attachments.server', () => ({
attachLargeFileRemoteUrls: (...args: unknown[]) => mockAttachLargeFileRemoteUrls(...args),
canUseProviderLargeFilePath: () => true,
uploadLargeFilesToProvider: (...args: unknown[]) => mockUploadLargeFilesToProvider(...args),
}))
vi.mock(
'@/lib/uploads/contexts/workspace/file-secret-provenance',
() => workspaceFileSecretProvenanceMock
)
vi.mock('@/tools', () => toolsMock)
import type { AgentTurnState } from '@/lib/memory/conversation-types'
import { AgentTurnStateMachine } from '@/lib/memory/turn-state'
import type { ExecutionContext, NormalizedBlockOutput, StreamingExecution } from '@/executor/types'
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
import { executeProviderRequest } from '@/providers'
import * as conversationGeneration from '@/providers/conversation-generation'
import { captureProviderConversationStep } from '@/providers/conversation-history'
import {
isConversationHistoryNotice,
markConversationHistoryNotice,
} from '@/providers/conversation-metadata'
import { executeProviderTool } from '@/providers/runtime-context'
import type { AgentStreamEvent } from '@/providers/stream-events'
import type { ProviderRequest, ProviderResponse, ProviderToolConfig } from '@/providers/types'
import { prepareToolExecution } from '@/providers/utils'
const mockGetApiKeyWithBYOK = apiKeyByokMockFns.mockGetApiKeyWithBYOK
const mockExecuteTool = toolsMockFns.mockExecuteTool
mockExecuteTool.mockImplementation(async () => ({ success: true, output: {} }))
const mockFilterModelSafeWorkspaceFileAttachments =
workspaceFileSecretProvenanceMockFns.mockFilterModelSafeWorkspaceFileAttachments
mockFilterModelSafeWorkspaceFileAttachments.mockImplementation(async (attachments) => attachments)
const HOSTED_RATE_INPUT_COST = 0.340285
const HOSTED_RATE_OUTPUT_COST = 0.0387
const HOSTED_RATE_TOTAL_COST = HOSTED_RATE_INPUT_COST + HOSTED_RATE_OUTPUT_COST
const ARBITRARY_SCHEMA_CONTROL_KEYS = [
'$schema',
'format',
'contentEncoding',
'contentMediaType',
'type',
] as const
function makeAnthropicResponse(): ProviderResponse {
// Mirrors the shape produced by Anthropic core for a real BYOK execution
// (gross hosted-rate cost was written into time-segment cost by the trace
// enricher even though the block-level cost should be zeroed for BYOK).
return {
content: 'hello',
model: 'claude-opus-4-6',
tokens: { input: 68057, output: 1548, total: 69605 },
cost: {
input: HOSTED_RATE_INPUT_COST,
output: HOSTED_RATE_OUTPUT_COST,
total: HOSTED_RATE_TOTAL_COST,
pricing: { input: 5.0, output: 25.0, updatedAt: '2026-04-01' },
},
timing: {
startTime: '2026-04-30T21:27:37.878Z',
endTime: '2026-04-30T21:28:19.836Z',
duration: 41958,
timeSegments: [
{
type: 'model',
name: 'claude-opus-4-6',
startTime: 1777584457878,
endTime: 1777584499836,
duration: 41958,
tokens: { input: 68057, output: 1548, total: 69605 },
cost: {
input: HOSTED_RATE_INPUT_COST,
output: HOSTED_RATE_OUTPUT_COST,
total: HOSTED_RATE_TOTAL_COST,
},
},
],
},
}
}
function makeProviderTool(id: string, credential: string): ProviderToolConfig {
return {
id,
description: id,
params: { oauthCredential: credential },
parameters: { type: 'object', properties: {}, required: [] },
}
}
describe('executeProviderRequest — durable Agent continuation', () => {
const tool = makeProviderTool('http_request', 'credential-1')
const initialRequest: ProviderRequest = {
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Finish the work.' }],
tools: [tool],
workflowId: 'workflow-1',
executionId: 'execution-1',
blockId: 'agent-1',
}
const toolMessage = (ids: string[]) => ({
role: 'assistant',
content: 'Looking up records.',
tool_calls: ids.map((id) => ({
id,
type: 'function',
function: { name: 'http_request', arguments: JSON.stringify({ key: id }) },
})),
})
const response = (): ProviderResponse => ({
content: 'Finished.',
model: 'gpt-4o',
tokens: { input: 2, output: 1, total: 3 },
toolCalls: [],
})
beforeEach(() => {
mockExecuteRequest.mockReset().mockImplementation(async () => response())
mockExecuteTool.mockReset().mockResolvedValue({ success: true, output: { value: 'saved' } })
})
async function executeCall(request: ProviderRequest, id: string) {
const configuredTool = request.tools![0]
const { executionParams } = prepareToolExecution(configuredTool, { key: id }, request, id)
return executeProviderTool(configuredTool.id, executionParams)
}
it.each([undefined, { role: 'user', content: 'Actual current input' }])(
'does not bind a runtime history notice instead of current input %j',
async (currentInput) => {
const notice = { role: 'user', content: 'Some retained history was omitted.' }
markConversationHistoryNotice(notice)
const bindPrompt = vi.spyOn(conversationGeneration, 'bindConversationGenerationPrompt')
try {
await executeProviderRequest(
'openai',
{ ...initialRequest, messages: [...(currentInput ? [currentInput] : []), notice] },
{ agentConversation: new AgentTurnStateMachine({ save: vi.fn() }) }
)
expect(bindPrompt).toHaveBeenCalledWith(expect.anything(), currentInput)
const request = mockExecuteRequest.mock.calls[0][0] as ProviderRequest
expect(isConversationHistoryNotice(request.messages!.at(-1)!)).toBe(true)
expect(Object.keys(request.messages!.at(-1)!)).toEqual(['role', 'content'])
} finally {
bindPrompt.mockRestore()
}
}
)
it('carries completed work and usage to fallback without dispatching the tool again', async () => {
const session = new AgentTurnStateMachine({ save: vi.fn() })
mockExecuteRequest.mockImplementationOnce(async (request: ProviderRequest) => {
await captureProviderConversationStep(request, 'chat-completions', toolMessage(['call-1']), {
input: 7,
output: 3,
})
await executeCall(request, 'call-1')
throw new Error('Primary failed after the completed tool')
})
await expect(
executeProviderRequest('openai', initialRequest, { agentConversation: session })
).rejects.toThrow('Primary failed')
const result = (await executeProviderRequest(
'groq',
{ ...initialRequest, model: 'llama-3.3-70b-versatile' },
{ agentConversation: session }
)) as ProviderResponse
expect(mockExecuteTool).toHaveBeenCalledTimes(1)
const fallback = mockExecuteRequest.mock.calls[1][0] as ProviderRequest
expect(fallback.messages).toEqual([
...initialRequest.messages!,
expect.objectContaining({
role: 'assistant',
tool_calls: toolMessage(['call-1']).tool_calls,
}),
{ role: 'tool', name: 'http_request', tool_call_id: 'call-1', content: '{"value":"saved"}' },
])
expect(session.getPendingCalls()).toEqual([])
expect(result.tokens).toMatchObject({ input: 9, output: 4, total: 13 })
})
it('restores a partial parallel batch and only retries the call without a recorded result', async () => {
let checkpoint: AgentTurnState | undefined
const session = new AgentTurnStateMachine({
save: async (state) => {
checkpoint = state
},
})
mockExecuteRequest.mockImplementationOnce(async (request: ProviderRequest) => {
await captureProviderConversationStep(
request,
'chat-completions',
toolMessage(['done', 'pending'])
)
await executeCall(request, 'done')
throw new Error('Process stopped before the other result was recorded')
})
await expect(
executeProviderRequest('openai', initialRequest, { agentConversation: session })
).rejects.toThrow('Process stopped')
const pendingIdentity = session.getPendingCalls()[0].invocationId
const restored = new AgentTurnStateMachine({ save: vi.fn() }, checkpoint)
await executeProviderRequest('openai', initialRequest, { agentConversation: restored })
expect(mockExecuteTool).toHaveBeenCalledTimes(2)
expect(mockExecuteTool.mock.calls.map((call) => (call[1] as { key: string }).key)).toEqual([
'done',
'pending',
])
expect(mockExecuteTool.mock.calls[1][1]).toMatchObject({
_context: { invocationId: pendingIdentity },
})
expect(restored.getPendingCalls()).toEqual([])
const resumedRequest = mockExecuteRequest.mock.calls[1][0] as ProviderRequest
expect(resumedRequest.messages?.filter((message) => message.role === 'tool')).toHaveLength(2)
await executeProviderRequest('openai', initialRequest, { agentConversation: restored })
expect(mockExecuteTool).toHaveBeenCalledTimes(2)
})
it('preserves the ordinary provider path without an Agent memory session', async () => {
mockExecuteRequest.mockImplementationOnce(async (request: ProviderRequest) => {
await captureProviderConversationStep(request, 'chat-completions', toolMessage(['call-1']))
expect(request.resolveToolInvocationId).toBeUndefined()
await executeCall(request, 'call-1')
return response()
})
await executeProviderRequest('openai', initialRequest)
await executeProviderRequest('openai', initialRequest)
expect(mockExecuteTool).toHaveBeenCalledTimes(1)
expect(mockExecuteRequest.mock.calls[1][0].messages).toEqual(initialRequest.messages)
})
it('returns a completed checkpoint after current authorization without another model call', async () => {
const state: AgentTurnState = {
version: 1,
steps: [
{
id: 'final-step',
assistant: { role: 'assistant', content: '{"answer":42}' },
calls: [],
results: [],
usage: { input: 7, output: 3, cacheRead: 2 },
cost: { input: 0.4, output: 0.6, total: 1 },
},
],
final: { content: '{"answer":42}', model: 'claude-opus-4-6' },
}
const restored = new AgentTurnStateMachine({ save: vi.fn() }, state)
mockGetApiKeyWithBYOK.mockResolvedValueOnce({ apiKey: 'new-byok-key', isBYOK: true })
const result = (await executeProviderRequest(
'openai',
{ ...initialRequest, workspaceId: 'workspace-1' },
{ agentConversation: restored }
)) as ProviderResponse
expect(mockGetApiKeyWithBYOK).toHaveBeenCalledTimes(1)
expect(mockAttachLargeFileRemoteUrls).toHaveBeenCalledTimes(1)
expect(mockUploadLargeFilesToProvider).toHaveBeenCalledTimes(1)
expect(mockExecuteRequest).not.toHaveBeenCalled()
expect(mockExecuteTool).not.toHaveBeenCalled()
expect(result).toMatchObject({
content: '{"answer":42}',
model: 'claude-opus-4-6',
tokens: { input: 7, output: 3, cacheRead: 2, total: 12 },
cost: { input: 0.4, output: 0.6, total: 1 },
})
})
it('adds previous usage once when a stream completion callback is repeated', async () => {
const session = new AgentTurnStateMachine(
{ save: vi.fn() },
{
version: 1,
steps: [
{
id: 'previous-step',
assistant: { role: 'assistant', content: 'Partial answer' },
calls: [],
results: [],
usage: { input: 7, output: 3 },
cost: { input: 0.4, output: 0.6, total: 1 },
},
],
}
)
const onFullContent = vi.fn()
const streaming: StreamingExecution = {
stream: new ReadableStream(),
onFullContent,
execution: {
success: true,
logs: [],
metadata: { startTime: '', duration: 0 },
output: {
content: 'Finished.',
tokens: { input: 2, output: 1, total: 3 },
cost: { input: 0, output: 0, total: 0 },
},
},
}
mockExecuteRequest.mockResolvedValueOnce(streaming)
const result = (await executeProviderRequest(
'openai',
{ ...initialRequest, stream: true },
{ agentConversation: session }
)) as StreamingExecution
await Promise.all([result.onFullContent?.('Finished.'), result.onFullContent?.('Finished.')])
expect(result.execution.output.tokens).toMatchObject({ input: 9, output: 4, total: 13 })
expect(result.execution.output.cost).toMatchObject({ input: 0.4, output: 0.6, total: 1 })
expect(onFullContent).toHaveBeenCalledTimes(2)
})
it('retains prior billed usage when the finishing provider has no usage or cost', async () => {
const session = new AgentTurnStateMachine(
{ save: vi.fn() },
{
version: 1,
steps: [
{
id: 'previous-step',
assistant: { role: 'assistant', content: 'Partial answer' },
calls: [],
results: [],
usage: { input: 7, output: 3 },
cost: { input: 0.4, output: 0.6, total: 1 },
},
],
}
)
mockExecuteRequest.mockResolvedValueOnce({ content: 'Finished.', model: 'gpt-4o' })
const result = (await executeProviderRequest('openai', initialRequest, {
agentConversation: session,
})) as ProviderResponse
expect(result.tokens).toMatchObject({ input: 7, output: 3, total: 10 })
expect(result.cost).toMatchObject({ input: 0.4, output: 0.6, total: 1 })
})
it.each(['empty', 'cancelled', 'failed'])(
'retains prior usage when a %s stream never calls onFullContent',
async (exit) => {
const session = new AgentTurnStateMachine(
{ save: vi.fn() },
{
version: 1,
steps: [
{
id: 'previous-step',
assistant: { role: 'assistant', content: 'Partial answer' },
calls: [],
results: [],
usage: { input: 7, output: 3 },
cost: { input: 0.4, output: 0.6, total: 1 },
},
],
}
)
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'test-byok', isBYOK: true })
const output: NormalizedBlockOutput = { content: '' }
const writeUsage = () => {
output.tokens = { input: 2, output: 1, cacheRead: 4, total: 7 }
output.cost = { input: 2, output: 3, toolCost: 0.25, total: 5.25 }
}
const onFullContent = vi.fn()
const streaming: StreamingExecution = {
stream: new ReadableStream(
{
pull(controller) {
writeUsage()
if (exit === 'failed') controller.error(new Error('stream interrupted'))
else controller.close()
},
cancel: writeUsage,
},
{ highWaterMark: 0 }
),
onFullContent,
execution: {
success: true,
logs: [],
metadata: { startTime: '', duration: 0 },
output,
},
}
mockExecuteRequest.mockResolvedValueOnce(streaming)
const result = (await executeProviderRequest(
'openai',
{ ...initialRequest, workspaceId: 'workspace-1', stream: true },
{ agentConversation: session }
)) as StreamingExecution
expect(output.tokens).toMatchObject({ input: 7, output: 3, total: 10 })
expect(output.cost).toMatchObject({ input: 0.4, output: 0.6, total: 1 })
if (exit === 'cancelled') await result.stream.cancel()
else if (exit === 'failed')
await expect(result.stream.getReader().read()).rejects.toThrow('stream interrupted')
else await expect(result.stream.getReader().read()).resolves.toMatchObject({ done: true })
expect(output.tokens).toMatchObject({ input: 9, output: 4, cacheRead: 4, total: 17 })
expect(output.cost).toMatchObject({ input: 0.4, output: 0.6, toolCost: 0.25, total: 1.25 })
expect({ ...output }.cost).toMatchObject({ total: 1.25 })
expect(output.cost).toMatchObject({ total: 1.25 })
expect(onFullContent).not.toHaveBeenCalled()
}
)
it('does not replay pending tools after cancellation', async () => {
const session = new AgentTurnStateMachine({ save: vi.fn() })
mockExecuteRequest.mockImplementationOnce(async (request: ProviderRequest) => {
await captureProviderConversationStep(request, 'chat-completions', toolMessage(['pending']))
throw new Error('Process stopped')
})
await expect(
executeProviderRequest('openai', initialRequest, { agentConversation: session })
).rejects.toThrow('Process stopped')
const abort = new AbortController()
abort.abort()
await expect(
executeProviderRequest(
'openai',
{ ...initialRequest, abortSignal: abort.signal },
{
agentConversation: session,
}
)
).rejects.toMatchObject({ name: 'AbortError' })
expect(mockExecuteTool).not.toHaveBeenCalled()
expect(mockExecuteRequest).toHaveBeenCalledTimes(1)
})
it('propagates a nonretryable tool failure without another execution', async () => {
const session = new AgentTurnStateMachine({ save: vi.fn() })
const failure = Object.assign(new Error('Policy denied this operation'), { retryable: false })
mockExecuteTool.mockRejectedValueOnce(failure)
mockExecuteRequest.mockImplementationOnce(async (request: ProviderRequest) => {
await captureProviderConversationStep(request, 'chat-completions', toolMessage(['call-1']))
await executeCall(request, 'call-1')
return response()
})
await expect(
executeProviderRequest('openai', initialRequest, { agentConversation: session })
).rejects.toBe(failure)
expect(mockExecuteTool).toHaveBeenCalledTimes(1)
expect(mockExecuteRequest).toHaveBeenCalledTimes(1)
})
})
describe('executeProviderRequest — tool identities', () => {
it('passes trusted execution context to both attachment authorization stages without serializing it', async () => {
const executionContext = {
workflowId: 'workflow-1',
workspaceId: 'workspace-1',
executionId: 'execution-1',
} as ExecutionContext
mockExecuteRequest.mockResolvedValueOnce({ content: 'ready', model: 'test-model' })
await executeProviderRequest('anthropic', { model: 'test-model' }, { executionContext })
expect(mockAttachLargeFileRemoteUrls).toHaveBeenCalledWith(
expect.objectContaining({ model: 'test-model' }),
'anthropic',
executionContext
)
expect(mockUploadLargeFilesToProvider).toHaveBeenCalledWith(
expect.objectContaining({ model: 'test-model' }),
'anthropic',
executionContext
)
expect(mockExecuteRequest.mock.calls[0][0]).not.toHaveProperty('executionContext')
expect(mockExecuteRequest.mock.calls[0][0]).not.toHaveProperty('principal')
})
it('sends unique opaque ids and projects provider aliases out of the response', async () => {
const tools = [
makeProviderTool('gmail_send', 'credential-a'),
makeProviderTool('gmail_send', 'credential-b'),
]
mockExecuteRequest.mockImplementationOnce(async (request) => {
const alias = request.tools[1].id
expect(request.tools.map((tool: ProviderToolConfig) => tool.id)).toEqual([
'gmail_send',
'gmail_send__sim_2',
])
expect(alias).not.toContain('credential-b')
return {
content: 'sent',
model: 'test-model',
toolCalls: [{ name: alias, arguments: {} }],
timing: {
startTime: 'start',
endTime: 'end',
duration: 1,
timeSegments: [{ type: 'tool', name: alias, startTime: 0, endTime: 1, duration: 1 }],
},
}
})
const response = (await executeProviderRequest('anthropic', {
model: 'test-model',
tools,
})) as ProviderResponse
expect(response.toolCalls?.[0].name).toBe('gmail_send')
expect(response.timing?.timeSegments?.[0].name).toBe('gmail_send')
expect(tools[1].params.oauthCredential).toBe('credential-b')
})
it('keeps the alias map active while a streaming provider executes the selected instance', async () => {
const tools = [
makeProviderTool('gmail_send', 'credential-a'),
makeProviderTool('gmail_send', 'credential-b'),
]
mockExecuteRequest.mockImplementationOnce(async (request) => {
const selected = request.tools[1] as ProviderToolConfig
const output: NormalizedBlockOutput = {
toolCalls: { list: [], count: 0 },
providerTiming: { startTime: 'start', endTime: 'end', duration: 0, timeSegments: [] },
}
return {
streamFormat: 'agent-events-v1',
stream: new ReadableStream<AgentStreamEvent>({
async pull(controller) {
await executeProviderTool(selected.id, selected.params)
output.toolCalls = { list: [{ name: selected.id }], count: 1 }
controller.enqueue({ type: 'tool_call_start', id: 'call-1', name: selected.id })
controller.close()
},
}),
execution: { success: true, output },
}
})
const response = await executeProviderRequest('anthropic', {
model: 'test-model',
tools,
})
expect(response).not.toBeInstanceOf(ReadableStream)
expect(response).toHaveProperty('stream')
const streaming = response as StreamingExecution
const reader = (streaming.stream as ReadableStream<AgentStreamEvent>).getReader()
const event = await reader.read()
await reader.read()
expect(mockExecuteTool).toHaveBeenCalledWith(
'gmail_send',
{ oauthCredential: 'credential-b' },
expect.any(Object)
)
expect(event.value).toEqual({ type: 'tool_call_start', id: 'call-1', name: 'gmail_send' })
expect(streaming.execution.output.toolCalls?.list[0].name).toBe('gmail_send')
})
})
describe('executeProviderRequest — BYOK regression', () => {
it('zeroes block-level model cost for BYOK callers (existing behavior)', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
mockExecuteRequest.mockResolvedValue(makeAnthropicResponse())
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
expect(result.cost?.total).toBe(0)
expect(result.cost?.input).toBe(0)
expect(result.cost?.output).toBe(0)
})
it('zeroes per-segment model cost for BYOK callers so trace aggregation does not re-charge', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
mockExecuteRequest.mockResolvedValue(makeAnthropicResponse())
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
const segment = result.timing?.timeSegments?.[0]
expect(segment?.cost).toBeDefined()
expect(segment?.cost?.input).toBe(0)
expect(segment?.cost?.output).toBe(0)
expect(segment?.cost?.total).toBe(0)
// Tokens must be preserved so the UI still displays usage even when
// BYOK callers are not billed.
expect(segment?.tokens?.input).toBe(68057)
expect(segment?.tokens?.output).toBe(1548)
})
it('does not zero per-segment cost for non-BYOK hosted callers', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-rotating', isBYOK: false })
mockExecuteRequest.mockResolvedValue(makeAnthropicResponse())
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
const segment = result.timing?.timeSegments?.[0]
expect(segment?.cost?.total).toBeCloseTo(HOSTED_RATE_TOTAL_COST, 6)
})
/**
* Provider cost is now preferred over recomputation, because only the
* provider knows its cache tiers. Tool cost is the hazard in that branch:
* `executeProviderRequest` re-derives it from `toolResults`, so a provider
* that folded it into its own total must not have it counted twice.
*/
it('counts a provider-folded tool cost exactly once', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-rotating', isBYOK: false })
mockExecuteRequest.mockResolvedValue({
content: 'hi',
model: 'claude-opus-4-6',
tokens: { input: 100, output: 50, total: 150 },
cost: {
input: 0.0005,
output: 0.00125,
total: 0.00675,
toolCost: 0.005,
pricing: { input: 5.0, output: 25.0, updatedAt: '2026-04-01' },
},
toolResults: [{ cost: { total: 0.005 } }],
} as ProviderResponse)
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
expect(result.cost?.toolCost).toBeCloseTo(0.005, 8)
expect(result.cost?.total).toBeCloseTo(0.00675, 8)
})
it('adds failed Function cost once alongside successful tool results', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
mockExecuteTool.mockResolvedValueOnce({
success: false,
output: { cost: { total: 0.004 } },
error: 'execution failed',
})
mockExecuteRequest.mockImplementationOnce(async () => {
const execution = await executeProviderTool('function_execute', {})
expect(execution.rawResponse.success).toBe(false)
return {
...makeAnthropicResponse(),
toolResults: [{ cost: { total: 0.005 } }],
} as ProviderResponse
})
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
tools: [makeProviderTool('function_execute', 'credential')],
})) as ProviderResponse
expect(result.cost).toMatchObject({ input: 0, output: 0 })
expect(result.cost?.toolCost).toBeCloseTo(0.009, 8)
expect(result.cost?.total).toBeCloseTo(0.009, 8)
})
/**
* Gemini hands the same cost object to its response and its model segment.
* Adding tool cost by mutation would charge it to the segment too.
*/
it('does not leak tool cost into a segment sharing the provider cost object', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-rotating', isBYOK: false })
envFlagsMockFns.getCostMultiplier.mockReturnValue(1)
const sharedCost = {
input: 0.0005,
output: 0.00125,
total: 0.00175,
pricing: { input: 5.0, output: 25.0, updatedAt: '2026-04-01' },
}
mockExecuteRequest.mockResolvedValue({
content: 'hi',
model: 'claude-opus-4-6',
tokens: { input: 100, output: 50, total: 150 },
cost: sharedCost,
toolResults: [{ cost: { total: 0.004 } }],
timing: {
startTime: '2026-04-30T21:27:37.878Z',
endTime: '2026-04-30T21:27:38.000Z',
duration: 122,
timeSegments: [
{
type: 'model',
name: 'claude-opus-4-6',
startTime: 1777584457878,
endTime: 1777584457940,
duration: 62,
cost: sharedCost,
},
],
},
} as ProviderResponse)
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
expect(result.cost?.total).toBeCloseTo(0.00575, 8)
expect(result.timing?.timeSegments?.[0]?.cost?.total).toBeCloseTo(0.00175, 8)
})
it('keeps the provider cost rather than recomputing it from tokens', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-rotating', isBYOK: false })
// Cache-tier pricing this layer cannot rebuild from `tokens` alone.
mockExecuteRequest.mockResolvedValue({
content: 'hi',
model: 'claude-opus-4-6',
tokens: { input: 100, output: 50, total: 150, cacheRead: 900, cacheWrite: 400 },
cost: {
input: 0.0123,
output: 0.00125,
total: 0.01355,
pricing: { input: 5.0, output: 25.0, updatedAt: '2026-04-01' },
},
} as ProviderResponse)
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
expect(result.cost?.input).toBeCloseTo(0.0123, 8)
expect(result.cost?.total).toBeCloseTo(0.01355, 8)
})
it('preserves tool segment cost (BYOK does not suppress tool charges)', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
const responseWithToolSegment: ProviderResponse = {
content: 'hi',
model: 'claude-opus-4-6',
tokens: { input: 100, output: 50, total: 150 },
cost: {
input: 0.0005,
output: 0.00125,
total: 0.00175,
pricing: { input: 5.0, output: 25.0, updatedAt: '2026-04-01' },
},
timing: {
startTime: '2026-04-30T21:27:37.878Z',
endTime: '2026-04-30T21:27:38.000Z',
duration: 122,
timeSegments: [
{
type: 'model',
name: 'claude-opus-4-6',
startTime: 1777584457878,
endTime: 1777584457940,
duration: 62,
cost: { input: 0.0005, output: 0.00125, total: 0.00175 },
},
{
type: 'tool',
name: 'firecrawl_scrape',
startTime: 1777584457940,
endTime: 1777584458000,
duration: 60,
cost: { total: 0.01 },
},
],
},
}
mockExecuteRequest.mockResolvedValue(responseWithToolSegment)
const result = (await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
})) as ProviderResponse
const [model, tool] = result.timing!.timeSegments!
expect(model.cost?.total).toBe(0)
expect(tool.type).toBe('tool')
expect(tool.cost?.total).toBe(0.01)
})
it('zeroes per-segment cost on streaming responses for BYOK callers', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
const segments = [
{
type: 'model' as const,
name: 'claude-opus-4-6',
startTime: 1777584457878,
endTime: 1777584499836,
duration: 41958,
cost: {
input: HOSTED_RATE_INPUT_COST,
output: HOSTED_RATE_OUTPUT_COST,
total: HOSTED_RATE_TOTAL_COST,
},
},
]
const streamingResponse = {
stream: new ReadableStream(),
execution: {
success: true,
output: {
content: '',
model: 'claude-opus-4-6',
tokens: { input: 0, output: 0, total: 0 },
providerTiming: {
startTime: '2026-04-30T21:27:37.878Z',
endTime: '2026-04-30T21:28:19.836Z',
duration: 41958,
timeSegments: segments,
},
cost: {
input: HOSTED_RATE_INPUT_COST,
output: HOSTED_RATE_OUTPUT_COST,
total: HOSTED_RATE_TOTAL_COST,
},
},
logs: [],
},
}
mockExecuteRequest.mockResolvedValue(streamingResponse)
await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
stream: true,
})
expect(segments[0].cost.total).toBe(0)
expect(segments[0].cost.input).toBe(0)
expect(segments[0].cost.output).toBe(0)
})
})
/**
* Streaming and non-streaming must charge identically. Providers price tokens
* inside the stream drain without knowing key provenance or the margin, so the
* shared policy is installed on the live output before the stream is returned.
*/
describe('executeProviderRequest — streaming cost policy', () => {
beforeEach(() => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-rotating', isBYOK: false })
})
afterEach(resetEnvFlagsMock)
function makeStreamingExecution(initialCost?: Record<string, number>) {
return {
stream: new ReadableStream(),
execution: {
success: true,
output: {
content: '',
model: 'claude-opus-4-6',
tokens: { input: 0, output: 0, total: 0 },
...(initialCost ? { cost: initialCost } : {}),
},
logs: [],
},
}
}
it('applies the cost multiplier to cost the provider writes while streaming', async () => {
envFlagsMockFns.getCostMultiplier.mockReturnValue(2)
const streaming = makeStreamingExecution()
mockExecuteRequest.mockResolvedValue(streaming)
await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
stream: true,
})
streaming.execution.output.cost = { input: 1, output: 2, total: 3 }
expect(streaming.execution.output.cost).toMatchObject({ input: 2, output: 4, total: 6 })
})
it('does not charge for models Sim does not host', async () => {
const streaming = {
stream: new ReadableStream(),
execution: {
success: true,
output: {
content: '',
model: 'llama-3.3-70b-versatile',
tokens: { input: 0, output: 0, total: 0 },
},
logs: [],
},
}
mockExecuteRequest.mockResolvedValue(streaming)
await executeProviderRequest('groq', {
model: 'llama-3.3-70b-versatile',
workspaceId: 'ws-1',
stream: true,
})
streaming.execution.output.cost = { input: 0.5, output: 1.5, total: 2 }
expect(streaming.execution.output.cost).toMatchObject({ input: 0, output: 0, total: 0 })
})
it('keeps tool cost from a settled stream that priced its tools before returning', async () => {
mockGetApiKeyWithBYOK.mockResolvedValue({ apiKey: 'sk-byok', isBYOK: true })
const streaming = makeStreamingExecution({
input: 0.01,
output: 0.02,
total: 0.035,
toolCost: 0.005,
})
mockExecuteRequest.mockResolvedValue(streaming)
await executeProviderRequest('anthropic', {
model: 'claude-opus-4-6',
workspaceId: 'ws-1',
stream: true,
})
expect(streaming.execution.output.cost).toMatchObject({
input: 0,
output: 0,
total: 0.005,
toolCost: 0.005,
})
})
})
describe('executeProviderRequest — caller-prepared model input', () => {
beforeEach(() => {
mockExecuteRequest.mockResolvedValue({
content: 'ok',
model: 'test-model',
tokens: { input: 1, output: 1, total: 2 },
} as ProviderResponse)
})
it('does not rescan or rewrite a caller-prepared provider request', async () => {
const secret = 'quoted"secret\\with\nnewline'
const registry = new ResolvedSecretTraceRegistry([
{ name: 'TOKEN', plaintext: secret, encryptedValue: 'ciphertext' },
])
registry.recordResolved('TOKEN', secret)
await executeProviderRequest(
'anthropic',
{
model: 'test-model',
apiKey: secret,
systemPrompt: `system ${secret}`,
context: `context ${secret}`,
messages: [
{
role: 'user',
content: `message ${secret} __var_TOKEN`,
files: [
{
id: 'file-1',
name: `${secret}.txt`,
url: '/file',
size: 4,
type: 'text/plain',
key: 'file-key',
base64: 'c2FmZQ==',
},
],
},
{
role: 'assistant',
content: null,
name: 'assistant-safe',
You can’t perform that action at this time.
