Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
1709 lines (1530 loc) · 58.6 KB
/
Copy pathutils.ts
File metadata and controls
1709 lines (1530 loc) · 58.6 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 { createLogger, type Logger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { omit } from '@sim/utils/object'
import type OpenAI from 'openai'
import type { BillingAttributionSnapshot } from '@/lib/billing/core/billing-attribution'
import { formatCreditCost } from '@/lib/billing/credits/conversion'
import { env } from '@/lib/core/config/env'
import { getBlacklistedProvidersFromEnv, isHosted } from '@/lib/core/config/env-flags'
import {
normalizeRecord,
normalizeStringRecord,
normalizeWorkflowVariables,
} from '@/lib/core/utils/records'
import type { CustomBlockToolBinding } from '@/lib/workflows/custom-blocks/operations'
import { isFileFieldType, type WorkflowInputField } from '@/lib/workflows/input-format'
import {
buildCanonicalIndex,
type CanonicalGroup,
type CanonicalModeOverrides,
isCanonicalPair,
resolveActiveCanonicalValue,
scopeCanonicalModesForTool,
} from '@/lib/workflows/subblocks/visibility'
import { assembleCustomBlockInputMapping, isCustomBlockType } from '@/blocks/custom/build-config'
import { isCustomTool } from '@/executor/constants'
import {
getComputerUseModels,
getEmbeddingModelPricing,
getHostedModels as getHostedModelsFromDefinitions,
getMaxOutputTokensForModel as getMaxOutputTokensForModelFromDefinitions,
getMaxTemperature as getMaxTempFromDefinitions,
getModelPricing as getModelPricingFromDefinitions,
getModelsWithDeepResearch,
getModelsWithoutMemory,
getModelsWithPromptCaching,
getModelsWithReasoningEffort,
getModelsWithTemperatureRange,
getModelsWithTemperatureSupport,
getModelsWithThinking,
getModelsWithVerbosity,
getProviderDefaultModel as getProviderDefaultModelFromDefinitions,
getProviderModels as getProviderModelsFromDefinitions,
getProvidersWithToolUsageControl,
getReasoningEffortValuesForModel as getReasoningEffortValuesForModelFromDefinitions,
getThinkingLevelsForModel as getThinkingLevelsForModelFromDefinitions,
getVerbosityValuesForModel as getVerbosityValuesForModelFromDefinitions,
isKnownModelLevelValue,
PROVIDER_DEFINITIONS,
supportsTemperature as supportsTemperatureFromDefinitions,
supportsToolUsageControl as supportsToolUsageControlFromDefinitions,
updateOllamaModels as updateOllamaModelsInDefinitions,
} from '@/providers/models'
import {
getProviderToolInputProvenance,
getProviderToolModelInputRegistry,
registerPreparedProviderToolInputProvenance,
} from '@/providers/tool-input-provenance'
import type { ProviderId, ProviderToolConfig } from '@/providers/types'
import { useProvidersStore } from '@/stores/providers/store'
import { mergeToolParameters } from '@/tools/merge-params'
import type { WorkflowToolExecutionContext } from '@/tools/types'
const logger = createLogger('ProviderUtils')
/**
* Checks if a workflow description is a default/placeholder description
*/
function isDefaultWorkflowDescription(
description: string | null | undefined,
name?: string
): boolean {
if (!description) return true
const normalizedDesc = description.toLowerCase().trim()
return (
description === name ||
normalizedDesc === 'new workflow' ||
normalizedDesc === 'your first workflow - start building here!'
)
}
/**
* Fetches workflow metadata (name and description) from the API
*/
async function fetchWorkflowMetadata(
workflowId: string,
executionContext: WorkflowToolExecutionContext | undefined
): Promise<{ name: string; description: string | null } | null> {
try {
if (!executionContext?.userId) {
throw new Error('Workflow metadata enrichment requires a trusted execution subject')
}
const { buildAPIUrl, buildExecutorDelegationHeaders } = await import('@/executor/utils/http')
const { executionScopeForTarget } = await import('@/executor/utils/delegation')
const headers = await buildExecutorDelegationHeaders({
subjectUserId: executionContext.userId,
workflowId,
...executionScopeForTarget(executionContext, workflowId),
})
const url = buildAPIUrl(`/api/workflows/${workflowId}`)
const response = await fetch(url.toString(), { headers })
if (!response.ok) {
await response.text().catch(() => {})
logger.warn(`Failed to fetch workflow metadata for ${workflowId}`)
return null
}
const { data } = await response.json()
return {
name: data?.name || 'Workflow',
description: data?.description || null,
}
} catch (error) {
logger.error('Error fetching workflow metadata:', error)
return null
}
}
/**
* Client-safe provider metadata.
* This object contains only model lists and patterns - no executeRequest implementations.
* For server-side execution, use @/providers/registry.
*/
export interface ProviderMetadata {
id: string
name: string
description: string
version: string
models: string[]
defaultModel: string
computerUseModels?: string[]
modelPatterns?: RegExp[]
}
/**
* Build provider metadata from PROVIDER_DEFINITIONS.
* This is client-safe as it doesn't import any provider implementations.
*/
function buildProviderMetadata(providerId: ProviderId): ProviderMetadata {
const def = PROVIDER_DEFINITIONS[providerId]
return {
id: providerId,
name: def?.name || providerId,
description: def?.description || '',
version: '1.0.0',
models: getProviderModelsFromDefinitions(providerId),
defaultModel: getProviderDefaultModelFromDefinitions(providerId),
modelPatterns: def?.modelPatterns,
}
}
export const providers: Record<ProviderId, ProviderMetadata> = {
ollama: buildProviderMetadata('ollama'),
'ollama-cloud': buildProviderMetadata('ollama-cloud'),
vllm: buildProviderMetadata('vllm'),
litellm: buildProviderMetadata('litellm'),
openai: {
...buildProviderMetadata('openai'),
computerUseModels: ['computer-use-preview'],
},
anthropic: {
...buildProviderMetadata('anthropic'),
computerUseModels: getComputerUseModels().filter((model) =>
getProviderModelsFromDefinitions('anthropic').includes(model)
),
},
google: buildProviderMetadata('google'),
vertex: buildProviderMetadata('vertex'),
'azure-openai': buildProviderMetadata('azure-openai'),
'azure-anthropic': buildProviderMetadata('azure-anthropic'),
deepseek: buildProviderMetadata('deepseek'),
xai: buildProviderMetadata('xai'),
cerebras: buildProviderMetadata('cerebras'),
groq: buildProviderMetadata('groq'),
sakana: buildProviderMetadata('sakana'),
nvidia: buildProviderMetadata('nvidia'),
meta: buildProviderMetadata('meta'),
zai: buildProviderMetadata('zai'),
kimi: buildProviderMetadata('kimi'),
mistral: buildProviderMetadata('mistral'),
bedrock: buildProviderMetadata('bedrock'),
openrouter: buildProviderMetadata('openrouter'),
fireworks: buildProviderMetadata('fireworks'),
together: buildProviderMetadata('together'),
baseten: buildProviderMetadata('baseten'),
}
export function updateOllamaProviderModels(models: string[]): void {
updateOllamaModelsInDefinitions(models)
providers.ollama.models = getProviderModelsFromDefinitions('ollama')
}
export function updateVLLMProviderModels(models: string[]): void {
const { updateVLLMModels } = require('@/providers/models')
updateVLLMModels(models)
providers.vllm.models = getProviderModelsFromDefinitions('vllm')
}
export function updateLiteLLMProviderModels(models: string[]): void {
const { updateLiteLLMModels } = require('@/providers/models')
updateLiteLLMModels(models)
providers.litellm.models = getProviderModelsFromDefinitions('litellm')
}
export async function updateOpenRouterProviderModels(models: string[]): Promise<void> {
const { updateOpenRouterModels } = await import('@/providers/models')
updateOpenRouterModels(models)
providers.openrouter.models = getProviderModelsFromDefinitions('openrouter')
}
export async function updateFireworksProviderModels(models: string[]): Promise<void> {
const { updateFireworksModels } = await import('@/providers/models')
updateFireworksModels(models)
providers.fireworks.models = getProviderModelsFromDefinitions('fireworks')
}
export async function updateOllamaCloudProviderModels(models: string[]): Promise<void> {
const { updateOllamaCloudModels } = await import('@/providers/models')
updateOllamaCloudModels(models)
providers['ollama-cloud'].models = getProviderModelsFromDefinitions('ollama-cloud')
}
export async function updateTogetherProviderModels(models: string[]): Promise<void> {
const { updateTogetherModels } = await import('@/providers/models')
updateTogetherModels(models)
providers.together.models = getProviderModelsFromDefinitions('together')
}
export async function updateBasetenProviderModels(models: string[]): Promise<void> {
const { updateBasetenModels } = await import('@/providers/models')
updateBasetenModels(models)
providers.baseten.models = getProviderModelsFromDefinitions('baseten')
}
export function getBaseModelProviders(): Record<string, ProviderId> {
const allProviders = Object.entries(providers)
.filter(
([providerId]) =>
providerId !== 'ollama' &&
providerId !== 'ollama-cloud' &&
providerId !== 'vllm' &&
providerId !== 'litellm' &&
providerId !== 'openrouter' &&
providerId !== 'fireworks' &&
providerId !== 'together' &&
providerId !== 'baseten'
)
.reduce(
(map, [providerId, config]) => {
config.models.forEach((model) => {
map[model.toLowerCase()] = providerId as ProviderId
})
return map
},
{} as Record<string, ProviderId>
)
return filterBlacklistedModelsFromProviderMap(allProviders)
}
function filterBlacklistedModelsFromProviderMap(
providerMap: Record<string, ProviderId>
): Record<string, ProviderId> {
const filtered: Record<string, ProviderId> = {}
for (const [model, providerId] of Object.entries(providerMap)) {
if (isProviderBlacklisted(providerId)) {
continue
}
if (!isModelBlacklisted(model)) {
filtered[model] = providerId
}
}
return filtered
}
export function getAllModelProviders(): Record<string, ProviderId> {
return Object.entries(providers).reduce(
(map, [providerId, config]) => {
config.models.forEach((model) => {
map[model.toLowerCase()] = providerId as ProviderId
})
return map
},
{} as Record<string, ProviderId>
)
}
/**
* The provider that declares `model`, or `null` when none does.
*
* The non-guessing half of {@link getProviderFromModel}. A caller that *gates*
* on the answer needs "unknown" to stay distinct from "ollama": this registry
* holds chat models only, so every embedding, speech, image and video model id
* would otherwise read as an Ollama model and be judged against an allowlist
* that was never about it.
*/
export function findProviderFromModel(model: string): ProviderId | null {
const normalizedModel = model.toLowerCase()
const declared = getAllModelProviders()[normalizedModel]
if (declared) return declared
for (const [id, config] of Object.entries(providers)) {
for (const pattern of config.modelPatterns ?? []) {
if (pattern.test(normalizedModel)) return id as ProviderId
}
}
return null
}
export function getProviderFromModel(model: string): ProviderId {
const normalizedModel = model.toLowerCase()
let providerId = findProviderFromModel(model)
if (!providerId) {
logger.warn(`No provider found for model: ${model}, defaulting to ollama`)
providerId = 'ollama'
}
if (isProviderBlacklisted(providerId)) {
throw new Error(`Provider "${providerId}" is not available`)
}
if (isModelBlacklisted(normalizedModel)) {
throw new Error(`Model "${model}" is not available`)
}
return providerId
}
export function getProvider(id: string): ProviderMetadata | undefined {
const providerId = id.split('/')[0] as ProviderId
return providers[providerId]
}
export function getProviderConfigFromModel(model: string): ProviderMetadata | undefined {
const providerId = getProviderFromModel(model)
return providers[providerId]
}
export function getAllModels(): string[] {
return Object.values(providers).flatMap((provider) => provider.models || [])
}
export function getAllProviderIds(): ProviderId[] {
return Object.keys(providers) as ProviderId[]
}
export function getProviderModels(providerId: ProviderId): string[] {
return getProviderModelsFromDefinitions(providerId)
}
export function isProviderBlacklisted(providerId: string): boolean {
return getBlacklistedProvidersFromEnv().includes(providerId.toLowerCase())
}
/**
* Get the list of blacklisted models from env var.
* BLACKLISTED_MODELS supports:
* - Exact model names: "gpt-4,claude-3-opus"
* - Prefix patterns with *: "claude-*,gpt-4-*" (matches models starting with that prefix)
*/
function getBlacklistedModels(): { models: string[]; prefixes: string[] } {
if (!env.BLACKLISTED_MODELS) return { models: [], prefixes: [] }
const entries = env.BLACKLISTED_MODELS.split(',').map((m) => m.trim().toLowerCase())
const models = entries.filter((e) => !e.endsWith('*'))
const prefixes = entries.filter((e) => e.endsWith('*')).map((e) => e.slice(0, -1))
return { models, prefixes }
}
function isModelBlacklisted(model: string): boolean {
const lowerModel = model.toLowerCase()
const blacklist = getBlacklistedModels()
if (blacklist.models.includes(lowerModel)) {
return true
}
if (blacklist.prefixes.some((prefix) => lowerModel.startsWith(prefix))) {
return true
}
return false
}
export function filterBlacklistedModels(models: string[]): string[] {
return models.filter((model) => !isModelBlacklisted(model))
}
export function getProviderIcon(model: string): React.ComponentType<{ className?: string }> | null {
const providerId = getProviderFromModel(model)
return PROVIDER_DEFINITIONS[providerId]?.icon || null
}
/**
* Generates prompt instructions for structured JSON output from a JSON schema.
* Used as a fallback when native structured outputs are not supported.
*/
export function generateSchemaInstructions(schema: any, schemaName?: string): string {
const name = schemaName || 'response'
return `IMPORTANT: You must respond with a valid JSON object that conforms to the following schema.
Do not include any text before or after the JSON object. Only output the JSON.
Schema name: ${name}
JSON Schema:
${JSON.stringify(schema, null, 2)}
Your response must be valid JSON that exactly matches this schema structure.`
}
export function generateStructuredOutputInstructions(responseFormat: any): string {
if (!responseFormat) return ''
if (responseFormat.schema || (responseFormat.type === 'object' && responseFormat.properties)) {
return ''
}
if (!responseFormat.fields) return ''
function generateFieldStructure(field: any): string {
if (field.type === 'object' && field.properties) {
return `{
${Object.entries(field.properties)
.map(([key, prop]: [string, any]) => `"${key}": ${prop.type === 'number' ? '0' : '"value"'}`)
.join(',\n ')}
}`
}
return field.type === 'string'
? '"value"'
: field.type === 'number'
? '0'
: field.type === 'boolean'
? 'true/false'
: '[]'
}
const exampleFormat = responseFormat.fields
.map((field: any) => ` "${field.name}": ${generateFieldStructure(field)}`)
.join(',\n')
const fieldDescriptions = responseFormat.fields
.map((field: any) => {
let desc = `${field.name} (${field.type})`
if (field.description) desc += `: ${field.description}`
if (field.type === 'object' && field.properties) {
desc += '\nProperties:'
Object.entries(field.properties).forEach(([key, prop]: [string, any]) => {
desc += `\n - ${key} (${(prop as any).type}): ${(prop as any).description || ''}`
})
}
return desc
})
.join('\n')
return `
Please provide your response in the following JSON format:
{
${exampleFormat}
}
Field descriptions:
${fieldDescriptions}
Your response MUST be valid JSON and include all the specified fields with their correct types.
Each metric should be an object containing 'score' (number) and 'reasoning' (string).`
}
export function extractAndParseJSON(content: string): any {
const trimmed = content.trim()
const firstBrace = trimmed.indexOf('{')
const lastBrace = trimmed.lastIndexOf('}')
if (firstBrace === -1 || lastBrace === -1) {
throw new Error('No JSON object found in content')
}
const jsonStr = trimmed.slice(firstBrace, lastBrace + 1)
try {
return JSON.parse(jsonStr)
} catch (_error) {
const cleaned = jsonStr
.replace(/\n/g, ' ')
.replace(/\s+/g, ' ')
.replace(/,\s*([}\]])/g, '$1')
try {
return JSON.parse(cleaned)
} catch (innerError) {
logger.error('Failed to parse JSON response', {
contentLength: content.length,
extractedLength: jsonStr.length,
cleanedLength: cleaned.length,
error: getErrorMessage(innerError, 'Unknown error'),
})
throw new Error(
`Failed to parse JSON after cleanup: ${getErrorMessage(innerError, 'Unknown error')}`
)
}
}
}
/**
* Resolves canonical pair ids (e.g. `tableId`, `knowledgeBaseId`) from a tool's
* raw params, preferring the active basic/advanced selector subblock source over
* a previously resolved canonical value.
*
* Selector subblocks persist their value under the subblock id (e.g.
* `tableSelector`), not the canonical id, so any lookup that keys off the
* canonical id — like the unique-tool-id suffix below — must resolve it first.
* Mode selection mirrors {@link transformBlockTool}'s execution-time
* `paramsTransform` so the resolved id matches the params the tool actually runs
* with. When the active selector has no value, the original canonical value is
* preserved for direct-id callers and nested tools in advanced mode.
*
* @returns The params with canonical resource ids resolved (non-destructive)
*/
function resolveCanonicalResourceParams(
params: Record<string, any>,
canonicalGroups: CanonicalGroup[],
scopedCanonicalModes?: CanonicalModeOverrides
): Record<string, any> {
if (canonicalGroups.length === 0) return params
const resolved = { ...params }
for (const group of canonicalGroups) {
// Route through the canonical SOT: an explicit scoped override wins, else the value heuristic -
// no `?? 'basic'` (which ignored an advanced-only value when basic was empty).
const explicitMode = scopedCanonicalModes?.[group.canonicalId]
const chosen = resolveActiveCanonicalValue(
group,
params,
explicitMode ? { [group.canonicalId]: explicitMode } : undefined
)
if (chosen !== undefined) resolved[group.canonicalId] = chosen
}
return resolved
}
/** JSON-schema type for a workflow input field (LLM tool schema). */
function inputFieldSchemaType(fieldType: string): string {
switch (fieldType) {
case 'number':
return 'number'
case 'boolean':
return 'boolean'
case 'object':
return 'object'
case 'array':
return 'array'
default:
return 'string'
}
}
/**
* Build the LLM tool schema for a custom block used as an agent tool: a single
* `inputMapping` object whose properties are the block's deployed input fields,
* keyed by the field's stable id (so it lines up with `assembleCustomBlockInputMapping`
* and the child's id→name remap) and marked required per the publisher's overrides.
* `file[]` fields are omitted — the model can't synthesize uploaded-file descriptors.
*/
function buildCustomBlockInputMappingSchema(
blockName: string,
inputFields: WorkflowInputField[],
requiredInputIds: string[]
): ProviderToolConfig['parameters'] {
const requiredSet = new Set(requiredInputIds)
const properties: Record<string, any> = {}
const requiredFields: string[] = []
for (const field of inputFields) {
if (isFileFieldType(field.type)) continue
const key = field.id ?? field.name
properties[key] = {
type: inputFieldSchemaType(field.type),
description: field.description ? `${field.name} — ${field.description}` : field.name,
}
if (requiredSet.has(key)) requiredFields.push(key)
}
return {
type: 'object',
properties: {
inputMapping: {
type: 'object',
description: `Input values for ${blockName}`,
properties,
required: requiredFields,
},
},
required: requiredFields.length > 0 ? ['inputMapping'] : [],
}
}
/**
* Transforms a block tool into a provider tool config with operation selection
*
* @param block The block to transform
* @param options Additional options including dependencies and selected operation
* @returns The provider tool config or null if transform fails
*/
/**
* Drops model-supplied arguments for params the tool declares off-limits to the
* model (`user-only` / `hidden`).
*
* Deliberately keyed on the declared visibility rather than on "absent from
* `parameters.properties`": an MCP or custom tool may legitimately accept keys
* beyond its advertised properties (`additionalProperties`), and silently
* dropping those would truncate its arguments. Only a param the tool itself
* marked as not-for-the-model is removed.
*/
function stripModelBlockedParams(
blockedParams: string[] | undefined,
llmArgs: Record<string, any>
): Record<string, any> {
if (!blockedParams?.length) return llmArgs
const blocked = new Set(blockedParams)
const filtered: Record<string, any> = {}
for (const [key, value] of Object.entries(llmArgs)) {
if (!blocked.has(key)) filtered[key] = value
}
return filtered
}
/** Reads a multi-select value that may still be JSON-encoded from `StoredTool.params`. */
function readMountedSecretNames(raw: unknown): string[] {
let value = raw
if (typeof value === 'string') {
try {
value = JSON.parse(value)
} catch {
// A bare name rather than a list — treat it as a single entry.
return value ? [value as string] : []
}
}
return Array.isArray(value)
? value.filter((name): name is string => typeof name === 'string' && name.length > 0)
: []
}
export async function transformBlockTool(
block: any,
options: {
selectedOperation?: string
getAllBlocks: () => any[]
getTool: (toolId: string) => any
getToolAsync?: (toolId: string) => Promise<any>
canonicalModes?: Record<string, 'basic' | 'advanced'>
enrichmentContext?: WorkflowToolExecutionContext
/**
* Server-only resolver for a custom (deploy-as-block) tool's binding (bound
* workflow + input schema), org-scoped to the consumer. Injected as a dependency
* — like `getAllBlocks`/`getTool` — so this client-reachable module never imports
* the DB-backed `operations` module. Omit for non-server callers that can't
* resolve authority; a custom block is then simply not offered as a tool.
*/
resolveCustomBlockBinding?: (blockType: string) => Promise<CustomBlockToolBinding | null>
/**
* Position of this tool within its parent agent block's `tool-input` array. Canonical-mode
* overrides are stored scoped by this index (`${toolIndex}:${canonicalId}`) rather than by
* `block.type`, so that two tool entries of the same type (e.g. two Table tools) don't share
* a canonical-mode override. Omit for tools with no such array position (e.g. Pi local tools).
*/
toolIndex?: number
}
): Promise<ProviderToolConfig | null> {
const {
selectedOperation,
getAllBlocks,
getTool,
getToolAsync,
canonicalModes,
enrichmentContext,
toolIndex,
} = options
const scopedCanonicalModes = scopeCanonicalModesForTool(canonicalModes, toolIndex, block.type)
const blockDef = getAllBlocks().find((b: any) => b.type === block.type)
if (!blockDef) {
logger.warn(`Block definition not found for type: ${block.type}`)
return null
}
// Custom (deploy-as-block) blocks resolve to the generic `workflow_executor`, but
// as an agent tool they must run through the authority boundary (owner identity,
// latest deployment, curated outputs) — not the plain workflow executor. Route
// them to the dedicated in-process `deployed_block_executor` tool, carrying the
// block TYPE (never a source workflow id) so authority is re-resolved server-side.
// Dynamic imports keep the DB/executor dependency graph out of client bundles.
if (isCustomBlockType(block.type)) {
const binding = await options.resolveCustomBlockBinding?.(block.type)
if (!binding) {
logger.warn(`Custom block tool binding not resolved for type: ${block.type}`)
return null
}
const customToolConfig = getTool('deployed_block_executor')
if (!customToolConfig) {
logger.warn('deployed_block_executor tool not registered')
return null
}
const inputMapping = assembleCustomBlockInputMapping(block.params || {})
// A `file[]` field is omitted from the model schema (the model can't synthesize
// upload descriptors). If such a field is REQUIRED and the user hasn't
// pre-filled it on the block, no invocation could ever satisfy the child's
// required-input check — so don't offer an unusable tool at all.
const prefilled = JSON.parse(inputMapping) as Record<string, unknown>
const requiredIds = new Set(binding.requiredInputIds)
const unfillableFileField = binding.inputFields.find((field) => {
const key = field.id ?? field.name
return isFileFieldType(field.type) && requiredIds.has(key) && !(key in prefilled)
})
if (unfillableFileField) {
logger.warn(
`Custom block ${block.type} not offered as a tool: required file input "${unfillableFileField.name}" has no preset value and cannot be supplied by the model`
)
return null
}
return {
// Unique per block so two custom-block tools never collide on the wire.
id: `deployed_block_executor_${block.type}`,
// Name/description come from the block itself — never the source workflow's
// metadata, which the consumer has no access to.
name: blockDef.name,
description: blockDef.description || customToolConfig.description,
params: {
blockType: block.type,
inputMapping,
},
parameters: buildCustomBlockInputMappingSchema(
blockDef.name,
binding.inputFields,
binding.requiredInputIds
),
}
}
let toolId: string | null = null
if ((blockDef.tools?.access?.length || 0) > 1) {
if (selectedOperation && blockDef.tools?.config?.tool) {
try {
toolId = blockDef.tools.config.tool({
...block.params,
operation: selectedOperation,
})
} catch (error) {
logger.error('Error selecting tool for block', {
blockType: block.type,
operation: selectedOperation,
error,
})
return null
}
} else {
toolId = blockDef.tools.access[0]
}
} else {
toolId = blockDef.tools?.access?.[0] || null
}
if (!toolId) {
logger.warn(`No tool ID found for block: ${block.type}`)
return null
}
let toolConfig: any
if (isCustomTool(toolId) && getToolAsync) {
toolConfig = await getToolAsync(toolId)
} else {
toolConfig = getTool(toolId)
}
if (!toolConfig) {
logger.warn(`Tool config not found for ID: ${toolId}`)
return null
}
const { createLLMToolSchema } = await import('@/tools/params')
const userProvidedParams = block.params || {}
const canonicalGroups: CanonicalGroup[] = blockDef?.subBlocks
? Object.values(buildCanonicalIndex(blockDef.subBlocks).groupsById).filter(isCanonicalPair)
: []
const resolvedResourceParams = resolveCanonicalResourceParams(
userProvidedParams,
canonicalGroups,
scopedCanonicalModes
)
const {
schema: llmSchema,
enrichedDescription,
modelBlockedParams,
} = await createLLMToolSchema(toolConfig, resolvedResourceParams, enrichmentContext)
let uniqueToolId = toolConfig.id
let toolName = toolConfig.name
let toolDescription = enrichedDescription || toolConfig.description
if (toolId === 'workflow_executor' && resolvedResourceParams.workflowId) {
uniqueToolId = `${toolConfig.id}_${resolvedResourceParams.workflowId}`
const workflowMetadata = await fetchWorkflowMetadata(
resolvedResourceParams.workflowId,
enrichmentContext
)
if (workflowMetadata) {
toolName = workflowMetadata.name || toolConfig.name
if (
workflowMetadata.description &&
!isDefaultWorkflowDescription(workflowMetadata.description, workflowMetadata.name)
) {
toolDescription = workflowMetadata.description
}
}
} else if (toolId === 'function_execute' && resolvedResourceParams.secretScope === 'selected') {
// Scoping alone would leave the model guessing: the secrets are injected
// server-side and nothing else advertises them. Names only — values never
// enter the provider request, matching the copilot's workspace-context rule.
// `StoredTool.params` holds strings, so a multi-select arrives JSON-encoded;
// the executor's paramsTransform parses it later, but this runs before that.
const mounted = readMountedSecretNames(resolvedResourceParams.mountedSecrets)
toolDescription = mounted.length
? `${toolDescription}\n\nWorkspace secret names available to this code: ${mounted.join(', ')}. Reference one with the exact {{NAME}} syntax. Its value is bound only while the code executes and is not included in the model request. No other secrets are readable.`
: `${toolDescription}\n\nThis code has no access to workspace secrets.`
} else if (toolId.startsWith('knowledge_') && resolvedResourceParams.knowledgeBaseId) {
uniqueToolId = `${toolConfig.id}_${resolvedResourceParams.knowledgeBaseId}`
} else if (toolId.startsWith('table_') && resolvedResourceParams.tableId) {
uniqueToolId = `${toolConfig.id}_${resolvedResourceParams.tableId}`
}
const blockParamsFn = blockDef?.tools?.config?.params as
| ((p: Record<string, any>) => Record<string, any>)
| undefined
const blockInputDefs = blockDef?.inputs as Record<string, any> | undefined
const needsTransform = blockParamsFn || blockInputDefs || canonicalGroups.length > 0
const paramsTransform = needsTransform
? (params: Record<string, any>): Record<string, any> => {
let result = { ...params }
for (const group of canonicalGroups) {
// Route through the canonical SOT: an explicit scoped override wins, else the value
// heuristic - no `?? 'basic'` (which dropped an advanced-only value when basic was empty).
const explicitMode = scopedCanonicalModes?.[group.canonicalId]
const chosen = resolveActiveCanonicalValue(
group,
result,
explicitMode ? { [group.canonicalId]: explicitMode } : undefined
)
const sourceIds = [group.basicId, ...group.advancedIds].filter(Boolean) as string[]
result = omit(result, sourceIds)
if (chosen !== undefined) {
result[group.canonicalId] = chosen
}
}
if (blockParamsFn) {
const transformed = blockParamsFn(result)
result = { ...result, ...transformed }
}
if (blockInputDefs) {
for (const [key, schema] of Object.entries(blockInputDefs)) {
const value = result[key]
if (typeof value === 'string' && value.trim().length > 0) {
const inputType = typeof schema === 'object' ? schema.type : schema
if (inputType === 'json' || inputType === 'array') {
try {
result[key] = JSON.parse(value.trim())
} catch {
// Not valid JSON — keep as string
}
}
}
}
}
return result
}
: undefined
return {
id: uniqueToolId,
name: toolName,
description: toolDescription,
params: userProvidedParams,
parameters: llmSchema,
modelBlockedParams,
paramsTransform,
}
}
/**
* Calculate cost for token usage based on model pricing
*
* @param model The model name
* @param promptTokens Number of prompt tokens used
* @param completionTokens Number of completion tokens used
* @param useCachedInput Whether to use cached input pricing (default: false)
* @param customMultiplier Optional custom multiplier to override the default cost multiplier
* @returns Cost calculation results with input, output and total costs
*/
export function calculateCost(
model: string,
promptTokens = 0,
completionTokens = 0,
useCachedInput = false,
inputMultiplier?: number,
outputMultiplier?: number
) {
let pricing = getEmbeddingModelPricing(model)
if (!pricing) {
pricing = getModelPricingFromDefinitions(model)
}
if (!pricing) {
const defaultPricing = {
input: 1.0,
cachedInput: 0.5,
output: 5.0,
updatedAt: '2025-03-21',
}
return {
input: 0,
output: 0,
total: 0,
pricing: defaultPricing,
}
}
const inputCost =
promptTokens *
(useCachedInput && pricing.cachedInput
? pricing.cachedInput / 1_000_000
: pricing.input / 1_000_000)
const outputCost = completionTokens * (pricing.output / 1_000_000)
const finalInputCost = inputCost * (inputMultiplier ?? 1)
const finalOutputCost = outputCost * (outputMultiplier ?? 1)
const finalTotalCost = finalInputCost + finalOutputCost
return {
input: Number.parseFloat(finalInputCost.toFixed(8)),
output: Number.parseFloat(finalOutputCost.toFixed(8)),
total: Number.parseFloat(finalTotalCost.toFixed(8)),
pricing,
}
}
/**
* Recursively enforces OpenAI strict-mode requirements on a JSON schema:
* - Sets `additionalProperties: false` on every object type.
* - Forces `required` to include ALL property keys.
*
* Required for any OpenAI-compatible backend that validates strict structured
* outputs (OpenAI, Azure OpenAI, and OpenAI routes behind proxies like LiteLLM),
* which reject schemas missing these constraints with an HTTP 400.
*/
export function enforceStrictSchema(schema: Record<string, unknown>): Record<string, unknown> {
if (!schema || typeof schema !== 'object') return schema
const result = { ...schema }
if (result.type === 'object') {
result.additionalProperties = false
if (result.properties && typeof result.properties === 'object') {
const propKeys = Object.keys(result.properties as Record<string, unknown>)
result.required = propKeys
result.properties = Object.fromEntries(
Object.entries(result.properties as Record<string, unknown>).map(([key, value]) => [
key,
enforceStrictSchema(value as Record<string, unknown>),
])
)
}
}
if (result.type === 'array' && result.items) {
result.items = enforceStrictSchema(result.items as Record<string, unknown>)
}
for (const keyword of ['anyOf', 'oneOf', 'allOf']) {
if (Array.isArray(result[keyword])) {
result[keyword] = (result[keyword] as Record<string, unknown>[]).map(enforceStrictSchema)
}
}