-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathget-blocks-metadata-tool.ts
More file actions
1188 lines (1061 loc) · 36.7 KB
/
get-blocks-metadata-tool.ts
File metadata and controls
1188 lines (1061 loc) · 36.7 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 { existsSync, readFileSync } from 'fs'
import { join } from 'path'
import { createLogger } from '@sim/logger'
import { getCopilotToolDescription } from '@/lib/copilot/tool-descriptions'
import type { BaseServerTool } from '@/lib/copilot/tools/server/base-tool'
import { GetBlocksMetadataInput, GetBlocksMetadataResult } from '@/lib/copilot/tools/shared/schemas'
import { getAllowedIntegrationsFromEnv, isHosted } from '@/lib/core/config/feature-flags'
import { registry as blockRegistry } from '@/blocks/registry'
import { AuthMode, type BlockConfig, isHiddenFromDisplay } from '@/blocks/types'
import { getUserPermissionConfig } from '@/ee/access-control/utils/permission-check'
import { PROVIDER_DEFINITIONS } from '@/providers/models'
import { tools as toolsRegistry } from '@/tools/registry'
import { getTrigger, isTriggerValid } from '@/triggers'
import { SYSTEM_SUBBLOCK_IDS } from '@/triggers/constants'
export interface CopilotSubblockMetadata {
id: string
type: string
title?: string
required?: boolean
description?: string
placeholder?: string
layout?: string
mode?: string
hidden?: boolean
condition?: any
// Dropdown/combobox options
options?: { id: string; label?: string; hasIcon?: boolean }[]
// Numeric constraints
min?: number
max?: number
step?: number
integer?: boolean
// Text input properties
rows?: number
password?: boolean
multiSelect?: boolean
// Code/generation properties
language?: string
generationType?: string
// OAuth/credential properties
serviceId?: string
requiredScopes?: string[]
// File properties
mimeType?: string
acceptedTypes?: string
multiple?: boolean
maxSize?: number
// Other properties
connectionDroppable?: boolean
columns?: string[]
wandConfig?: any
availableTriggers?: string[]
triggerProvider?: string
dependsOn?: string[]
canonicalParamId?: string
defaultValue?: any
value?: string // 'function' if it's a function, undefined otherwise
}
export interface CopilotToolMetadata {
id: string
name: string
description?: string
inputs?: any
outputs?: any
}
export interface CopilotTriggerMetadata {
id: string
outputs?: any
configFields?: any
}
export interface CopilotBlockMetadata {
id: string
name: string
description: string
bestPractices?: string
inputSchema: CopilotSubblockMetadata[]
inputDefinitions?: Record<string, any>
triggerAllowed?: boolean
authType?: 'OAuth' | 'API Key' | 'Bot Token'
tools: CopilotToolMetadata[]
triggers: CopilotTriggerMetadata[]
operationInputSchema: Record<string, CopilotSubblockMetadata[]>
operations?: Record<
string,
{
toolId?: string
toolName?: string
description?: string
inputs?: Record<string, any>
outputs?: Record<string, any>
inputSchema?: CopilotSubblockMetadata[]
}
>
outputs?: Record<string, any>
yamlDocumentation?: string
}
export const getBlocksMetadataServerTool: BaseServerTool<
ReturnType<typeof GetBlocksMetadataInput.parse>,
ReturnType<typeof GetBlocksMetadataResult.parse>
> = {
name: 'get_blocks_metadata',
inputSchema: GetBlocksMetadataInput,
outputSchema: GetBlocksMetadataResult,
async execute(
{ blockIds }: ReturnType<typeof GetBlocksMetadataInput.parse>,
context?: { userId: string }
): Promise<ReturnType<typeof GetBlocksMetadataResult.parse>> {
const logger = createLogger('GetBlocksMetadataServerTool')
logger.debug('Executing get_blocks_metadata', { count: blockIds?.length })
const permissionConfig = context?.userId ? await getUserPermissionConfig(context.userId) : null
const allowedIntegrations =
permissionConfig?.allowedIntegrations ?? getAllowedIntegrationsFromEnv()
const result: Record<string, CopilotBlockMetadata> = {}
for (const blockId of blockIds || []) {
if (allowedIntegrations != null && !allowedIntegrations.includes(blockId.toLowerCase())) {
logger.debug('Block not allowed by permission group', { blockId })
continue
}
let metadata: any
if (SPECIAL_BLOCKS_METADATA[blockId]) {
const specialBlock = SPECIAL_BLOCKS_METADATA[blockId]
const { commonParameters, operationParameters } = splitParametersByOperation(
specialBlock.subBlocks || [],
specialBlock.inputs || {}
)
metadata = {
id: specialBlock.id,
name: specialBlock.name,
description: specialBlock.description || '',
inputSchema: commonParameters,
inputDefinitions: specialBlock.inputs || {},
tools: [],
triggers: [],
operationInputSchema: operationParameters,
outputs: specialBlock.outputs,
}
;(metadata as any).subBlocks = undefined
} else {
const blockConfig: BlockConfig | undefined = blockRegistry[blockId]
if (!blockConfig) {
logger.debug('Block not found in registry', { blockId })
continue
}
if (blockConfig.hideFromToolbar) {
logger.debug('Skipping block hidden from toolbar', { blockId })
continue
}
const tools: CopilotToolMetadata[] = Array.isArray(blockConfig.tools?.access)
? blockConfig.tools!.access.map((toolId) => {
const tool = toolsRegistry[toolId]
if (!tool) return { id: toolId, name: toolId }
return {
id: toolId,
name: tool.name || toolId,
description: getCopilotToolDescription(tool, {
isHosted,
fallbackName: toolId,
}),
inputs: tool.params || {},
outputs: tool.outputs || {},
}
})
: []
const triggers: CopilotTriggerMetadata[] = []
const availableTriggerIds = blockConfig.triggers?.available || []
for (const tid of availableTriggerIds) {
if (!isTriggerValid(tid)) {
logger.debug('Invalid trigger ID found in block config', { blockId, triggerId: tid })
continue
}
const trig = getTrigger(tid)
const configFields: Record<string, any> = {}
for (const subBlock of trig.subBlocks) {
if (subBlock.mode === 'trigger' && !SYSTEM_SUBBLOCK_IDS.includes(subBlock.id)) {
const fieldDef: any = {
type: subBlock.type,
required: subBlock.required || false,
}
if (subBlock.title) fieldDef.title = subBlock.title
if (subBlock.description) fieldDef.description = subBlock.description
if (subBlock.placeholder) fieldDef.placeholder = subBlock.placeholder
if (subBlock.defaultValue !== undefined) fieldDef.default = subBlock.defaultValue
if (subBlock.options && Array.isArray(subBlock.options)) {
fieldDef.options = subBlock.options.map((opt: any) => ({
id: opt.id,
label: opt.label || opt.id,
}))
}
if (subBlock.condition) {
const cond =
typeof subBlock.condition === 'function'
? subBlock.condition()
: subBlock.condition
if (cond) {
fieldDef.condition = cond
}
}
configFields[subBlock.id] = fieldDef
}
}
triggers.push({
id: tid,
outputs: trig.outputs || {},
configFields,
})
}
const blockInputs = computeBlockLevelInputs(blockConfig)
const { commonParameters, operationParameters } = splitParametersByOperation(
Array.isArray(blockConfig.subBlocks)
? blockConfig.subBlocks.filter((sb) => sb.mode !== 'trigger')
: [],
blockInputs
)
const operationInputs = computeOperationLevelInputs(blockConfig)
const operationIds = resolveOperationIds(blockConfig, operationParameters)
const operations: Record<string, any> = {}
for (const opId of operationIds) {
const resolvedToolId = resolveToolIdForOperation(blockConfig, opId)
const toolCfg = resolvedToolId ? toolsRegistry[resolvedToolId] : undefined
const toolParams: Record<string, any> = toolCfg?.params || {}
const toolOutputs: Record<string, any> = toolCfg?.outputs
? Object.fromEntries(
Object.entries(toolCfg.outputs).filter(([_, def]) => !isHiddenFromDisplay(def))
)
: {}
const filteredToolParams: Record<string, any> = {}
for (const [k, v] of Object.entries(toolParams)) {
if (!(k in blockInputs)) filteredToolParams[k] = v
}
operations[opId] = {
toolId: resolvedToolId,
toolName: toolCfg?.name || resolvedToolId,
description: toolCfg
? getCopilotToolDescription(toolCfg, {
isHosted,
fallbackName: resolvedToolId,
})
: undefined,
inputs: { ...filteredToolParams, ...(operationInputs[opId] || {}) },
outputs: toolOutputs,
inputSchema: operationParameters[opId] || [],
}
}
const filteredOutputs = blockConfig.outputs
? Object.fromEntries(
Object.entries(blockConfig.outputs).filter(([_, def]) => !isHiddenFromDisplay(def))
)
: undefined
metadata = {
id: blockId,
name: blockConfig.name || blockId,
description: blockConfig.longDescription || blockConfig.description || '',
bestPractices: blockConfig.bestPractices,
inputSchema: commonParameters,
inputDefinitions: blockInputs,
triggerAllowed: !!blockConfig.triggerAllowed,
authType: resolveAuthType(blockConfig.authMode),
tools,
triggers,
operationInputSchema: operationParameters,
operations,
outputs: filteredOutputs,
}
}
try {
const workingDir = process.cwd()
const isInAppsSim = workingDir.endsWith('/apps/sim') || workingDir.endsWith('\\apps\\sim')
const basePath = isInAppsSim ? join(workingDir, '..', '..') : workingDir
const docPath = join(
basePath,
'apps',
'docs',
'content',
'docs',
'yaml',
'blocks',
`${DOCS_FILE_MAPPING[blockId] || blockId}.mdx`
)
if (existsSync(docPath)) {
metadata.yamlDocumentation = readFileSync(docPath, 'utf-8')
}
} catch (error) {
logger.warn('Failed to read YAML documentation file', {
error: error instanceof Error ? error.message : String(error),
})
}
if (metadata) {
result[blockId] = removeNullish(metadata) as CopilotBlockMetadata
}
}
const transformedResult: Record<string, any> = {}
for (const [blockId, metadata] of Object.entries(result)) {
transformedResult[blockId] = transformBlockMetadata(metadata)
}
return GetBlocksMetadataResult.parse({ metadata: transformedResult })
},
}
function transformBlockMetadata(metadata: CopilotBlockMetadata): any {
const transformed: any = {
blockType: metadata.id,
name: metadata.name,
description: metadata.description,
}
if (metadata.bestPractices) {
transformed.bestPractices = metadata.bestPractices
}
if (metadata.authType) {
transformed.authType = metadata.authType
if (metadata.authType === 'OAuth') {
transformed.requiredCredentials = {
type: 'oauth',
service: metadata.id, // e.g., 'gmail', 'slack', etc.
description: `OAuth authentication required for ${metadata.name}`,
}
} else if (metadata.authType === 'API Key') {
transformed.requiredCredentials = {
type: 'api_key',
description: `API key required for ${metadata.name}`,
}
} else if (metadata.authType === 'Bot Token') {
transformed.requiredCredentials = {
type: 'bot_token',
description: `Bot token required for ${metadata.name}`,
}
}
}
const inputs = extractInputs(metadata)
if (inputs.required.length > 0 || inputs.optional.length > 0) {
transformed.inputs = inputs
}
const hasOperations = metadata.operations && Object.keys(metadata.operations).length > 0
if (hasOperations && metadata.operations) {
const blockLevelInputs = new Set(Object.keys(metadata.inputDefinitions || {}))
transformed.operations = Object.entries(metadata.operations).reduce(
(acc, [opId, opData]) => {
acc[opId] = {
name: opData.toolName || opId,
description: opData.description,
inputs: extractOperationInputs(opData, blockLevelInputs),
outputs: formatOutputsFromDefinition(opData.outputs || {}),
}
return acc
},
{} as Record<string, any>
)
}
if (!hasOperations) {
const outputs = extractOutputs(metadata)
if (outputs.length > 0) {
transformed.outputs = outputs
}
}
if (metadata.triggers && metadata.triggers.length > 0) {
transformed.triggers = metadata.triggers.map((t) => ({
id: t.id,
outputs: formatOutputsFromDefinition(t.outputs || {}),
configFields: t.configFields || {},
}))
}
if (metadata.yamlDocumentation) {
transformed.yamlDocumentation = metadata.yamlDocumentation
}
return transformed
}
function extractInputs(metadata: CopilotBlockMetadata): {
required: any[]
optional: any[]
} {
const required: any[] = []
const optional: any[] = []
const inputDefs = metadata.inputDefinitions || {}
for (const schema of metadata.inputSchema || []) {
// Skip trigger subBlocks - they're handled separately in triggers.configFields
if (schema.mode === 'trigger') {
continue
}
if (schema.id === 'triggerConfig' || schema.type === 'trigger-config') {
continue
}
const inputDef = inputDefs[schema.id] || inputDefs[schema.canonicalParamId || '']
let description = schema.description || inputDef?.description || schema.title
if (schema.id === 'operation') {
description = 'Operation to perform'
}
const input: any = {
name: schema.id,
type: mapSchemaTypeToSimpleType(schema.type, schema),
description,
}
if (schema.options && schema.options.length > 0) {
input.options = schema.options.map((opt) => opt.id || opt.label)
}
if (inputDef?.enum && Array.isArray(inputDef.enum)) {
input.options = inputDef.enum
}
if (schema.defaultValue !== undefined) {
input.default = schema.defaultValue
} else if (inputDef?.default !== undefined) {
input.default = inputDef.default
}
if (schema.type === 'slider' || schema.type === 'number-input') {
if (schema.min !== undefined) input.min = schema.min
if (schema.max !== undefined) input.max = schema.max
} else if (inputDef?.minimum !== undefined || inputDef?.maximum !== undefined) {
if (inputDef.minimum !== undefined) input.min = inputDef.minimum
if (inputDef.maximum !== undefined) input.max = inputDef.maximum
}
const example = generateInputExample(schema, inputDef)
if (example !== undefined) {
input.example = example
}
const isOperationField =
schema.id === 'operation' &&
metadata.operations &&
Object.keys(metadata.operations).length > 0
const isRequired = schema.required || inputDef?.required || isOperationField
if (isRequired) {
required.push(input)
} else {
optional.push(input)
}
}
return { required, optional }
}
function extractOperationInputs(
opData: any,
blockLevelInputs: Set<string>
): {
required: any[]
optional: any[]
} {
const required: any[] = []
const optional: any[] = []
const inputs = opData.inputs || {}
for (const [key, inputDef] of Object.entries(inputs)) {
if (blockLevelInputs.has(key)) {
continue
}
const input: any = {
name: key,
type: (inputDef as any)?.type || 'string',
description: (inputDef as any)?.description,
}
if ((inputDef as any)?.enum) {
input.options = (inputDef as any).enum
}
if ((inputDef as any)?.default !== undefined) {
input.default = (inputDef as any).default
}
if ((inputDef as any)?.example !== undefined) {
input.example = (inputDef as any).example
}
if ((inputDef as any)?.required) {
required.push(input)
} else {
optional.push(input)
}
}
return { required, optional }
}
function extractOutputs(metadata: CopilotBlockMetadata): any[] {
const outputs: any[] = []
if (metadata.outputs && Object.keys(metadata.outputs).length > 0) {
return formatOutputsFromDefinition(metadata.outputs)
}
if (metadata.operations && Object.keys(metadata.operations).length > 0) {
const firstOp = Object.values(metadata.operations)[0]
return formatOutputsFromDefinition(firstOp.outputs || {})
}
return outputs
}
function formatOutputsFromDefinition(outputDefs: Record<string, any>): any[] {
const outputs: any[] = []
for (const [key, def] of Object.entries(outputDefs)) {
const output: any = {
name: key,
type: typeof def === 'string' ? def : def?.type || 'any',
}
if (typeof def === 'object') {
if (def.description) output.description = def.description
if (def.example) output.example = def.example
}
outputs.push(output)
}
return outputs
}
function mapSchemaTypeToSimpleType(schemaType: string, schema: CopilotSubblockMetadata): string {
const typeMap: Record<string, string> = {
'short-input': 'string',
'long-input': 'string',
'code-input': 'string',
'number-input': 'number',
slider: 'number',
dropdown: 'string',
combobox: 'string',
toggle: 'boolean',
'json-input': 'json',
'file-upload': 'file',
'multi-select': 'array',
'credential-input': 'credential',
'oauth-credential': 'credential',
'oauth-input': 'credential',
}
const mappedType = typeMap[schemaType] || schemaType
if (schema.multiSelect) return 'array'
return mappedType
}
function generateInputExample(schema: CopilotSubblockMetadata, inputDef?: any): any {
if (inputDef?.example !== undefined) return inputDef.example
switch (schema.type) {
case 'short-input':
case 'long-input':
if (schema.id === 'systemPrompt') return 'You are a helpful assistant...'
if (schema.id === 'userPrompt') return 'What is the weather today?'
if (schema.placeholder) return schema.placeholder
return undefined
case 'number-input':
case 'slider':
return schema.defaultValue ?? schema.min ?? 0
case 'toggle':
return schema.defaultValue ?? false
case 'json-input':
return schema.defaultValue ?? {}
case 'dropdown':
case 'combobox':
if (schema.options && schema.options.length > 0) {
return schema.options[0].id
}
return undefined
default:
return undefined
}
}
function processSubBlock(sb: any): CopilotSubblockMetadata {
const processed: CopilotSubblockMetadata = {
id: sb.id,
type: sb.type,
}
const optionalFields = {
title: sb.title,
required: sb.required,
description: sb.description,
placeholder: sb.placeholder,
layout: sb.layout,
mode: sb.mode,
hidden: sb.hidden,
canonicalParamId: sb.canonicalParamId,
defaultValue: sb.defaultValue,
// Numeric constraints
min: sb.min,
max: sb.max,
step: sb.step,
integer: sb.integer,
// Text input properties
rows: sb.rows,
password: sb.password,
multiSelect: sb.multiSelect,
// Code/generation properties
language: sb.language,
generationType: sb.generationType,
// OAuth/credential properties
serviceId: sb.serviceId,
requiredScopes: sb.requiredScopes,
// File properties
mimeType: sb.mimeType,
acceptedTypes: sb.acceptedTypes,
multiple: sb.multiple,
maxSize: sb.maxSize,
// Other properties
connectionDroppable: sb.connectionDroppable,
columns: sb.columns,
wandConfig: sb.wandConfig,
availableTriggers: sb.availableTriggers,
triggerProvider: sb.triggerProvider,
dependsOn: sb.dependsOn,
}
// Add non-null optional fields
for (const [key, value] of Object.entries(optionalFields)) {
if (value !== undefined && value !== null) {
;(processed as any)[key] = value
}
}
// Handle condition normalization
const condition = normalizeCondition(sb.condition)
if (condition !== undefined) {
processed.condition = condition
}
// Handle value field (check if it's a function)
if (typeof sb.value === 'function') {
processed.value = 'function'
}
// Process options with icon detection
const options = resolveSubblockOptions(sb)
if (options) {
processed.options = options
}
return processed
}
function resolveAuthType(
authMode: AuthMode | undefined
): 'OAuth' | 'API Key' | 'Bot Token' | undefined {
if (!authMode) return undefined
if (authMode === AuthMode.OAuth) return 'OAuth'
if (authMode === AuthMode.ApiKey) return 'API Key'
if (authMode === AuthMode.BotToken) return 'Bot Token'
return undefined
}
/**
* Gets all available models from PROVIDER_DEFINITIONS as static options.
* This provides fallback data when store state is not available server-side.
* Excludes dynamic providers (ollama, vllm, openrouter, fireworks) which require runtime fetching.
*/
function getStaticModelOptions(): { id: string; label?: string }[] {
const models: { id: string; label?: string }[] = []
for (const provider of Object.values(PROVIDER_DEFINITIONS)) {
// Skip providers with dynamic/fetched models
if (
provider.id === 'ollama' ||
provider.id === 'vllm' ||
provider.id === 'openrouter' ||
provider.id === 'fireworks'
) {
continue
}
if (provider?.models) {
for (const model of provider.models) {
models.push({ id: model.id, label: model.id })
}
}
}
return models
}
/**
* Attempts to call a dynamic options function with fallback data injected.
* When the function accesses store state that's unavailable server-side,
* this provides static fallback data from known sources.
*
* @param optionsFn - The options function to call
* @returns Options array or undefined if options cannot be resolved
*/
function callOptionsWithFallback(
optionsFn: () => any[]
): { id: string; label?: string; hasIcon?: boolean }[] | undefined {
// Get static model data to use as fallback
const staticModels = getStaticModelOptions()
// Create a mock providers state with static data
const mockProvidersState = {
providers: {
base: { models: staticModels.map((m) => m.id) },
ollama: { models: [] },
vllm: { models: [] },
openrouter: { models: [] },
fireworks: { models: [] },
},
}
// Store original getState if it exists
let originalGetState: (() => any) | undefined
let store: any
try {
// Try to get the providers store module
// eslint-disable-next-line @typescript-eslint/no-require-imports
store = require('@/stores/providers')
if (store?.useProvidersStore?.getState) {
originalGetState = store.useProvidersStore.getState
// Temporarily replace getState with our mock
store.useProvidersStore.getState = () => mockProvidersState
}
} catch {
// Store module not available, continue with mock
}
try {
const result = optionsFn()
return result
} finally {
// Restore original getState
if (store?.useProvidersStore && originalGetState) {
store.useProvidersStore.getState = originalGetState
}
}
}
function resolveSubblockOptions(
sb: any
): { id: string; label?: string; hasIcon?: boolean }[] | undefined {
// Skip if subblock uses fetchOptions (async network calls)
if (sb.fetchOptions) {
return undefined
}
let rawOptions: any[] | undefined
try {
if (typeof sb.options === 'function') {
// Try calling with fallback data injection for store-dependent options
rawOptions = callOptionsWithFallback(sb.options)
} else {
rawOptions = sb.options
}
} catch {
// Options function failed even with fallback, skip
return undefined
}
if (!Array.isArray(rawOptions) || rawOptions.length === 0) {
return undefined
}
const normalized = rawOptions
.map((opt: any) => {
if (!opt) return undefined
const id = typeof opt === 'object' ? opt.id : opt
if (id === undefined || id === null) return undefined
const result: { id: string; label?: string; hasIcon?: boolean } = {
id: String(id),
}
if (typeof opt === 'object' && typeof opt.label === 'string') {
result.label = opt.label
}
if (typeof opt === 'object' && opt.icon) {
result.hasIcon = true
}
return result
})
.filter((o): o is { id: string; label?: string; hasIcon?: boolean } => o !== undefined)
return normalized.length > 0 ? normalized : undefined
}
function removeNullish(obj: any): any {
if (!obj || typeof obj !== 'object') return obj
const cleaned: any = Array.isArray(obj) ? [] : {}
for (const [key, value] of Object.entries(obj)) {
if (value !== null && value !== undefined) {
cleaned[key] = value
}
}
return cleaned
}
function normalizeCondition(condition: any): any | undefined {
try {
if (!condition) return undefined
if (typeof condition === 'function') {
return condition()
}
return condition
} catch {
return undefined
}
}
function splitParametersByOperation(
subBlocks: any[],
blockInputsForDescriptions?: Record<string, any>
): {
commonParameters: CopilotSubblockMetadata[]
operationParameters: Record<string, CopilotSubblockMetadata[]>
} {
const commonParameters: CopilotSubblockMetadata[] = []
const operationParameters: Record<string, CopilotSubblockMetadata[]> = {}
for (const sb of subBlocks || []) {
const cond = normalizeCondition(sb.condition)
const processed = processSubBlock(sb)
if (cond && cond.field === 'operation' && !cond.not && cond.value !== undefined) {
const values: any[] = Array.isArray(cond.value) ? cond.value : [cond.value]
for (const v of values) {
const key = String(v)
if (!operationParameters[key]) operationParameters[key] = []
operationParameters[key].push(processed)
}
} else {
// Override description from inputDefinitions if available (by id or canonicalParamId)
if (blockInputsForDescriptions) {
const candidates = [sb.id, sb.canonicalParamId].filter(Boolean)
for (const key of candidates) {
const bi = (blockInputsForDescriptions as any)[key as string]
if (bi && typeof bi.description === 'string') {
processed.description = bi.description
break
}
}
}
commonParameters.push(processed)
}
}
return { commonParameters, operationParameters }
}
function computeBlockLevelInputs(blockConfig: BlockConfig): Record<string, any> {
const inputs = blockConfig.inputs || {}
const subBlocks: any[] = Array.isArray(blockConfig.subBlocks)
? blockConfig.subBlocks.filter((sb) => sb.mode !== 'trigger')
: []
const byParamKey: Record<string, any[]> = {}
for (const sb of subBlocks) {
if (sb.id) {
byParamKey[sb.id] = byParamKey[sb.id] || []
byParamKey[sb.id].push(sb)
}
if (sb.canonicalParamId) {
byParamKey[sb.canonicalParamId] = byParamKey[sb.canonicalParamId] || []
byParamKey[sb.canonicalParamId].push(sb)
}
}
const blockInputs: Record<string, any> = {}
for (const key of Object.keys(inputs)) {
const sbs = byParamKey[key] || []
const isOperationGated = sbs.some((sb) => {
const cond = normalizeCondition(sb.condition)
return cond && cond.field === 'operation' && !cond.not && cond.value !== undefined
})
if (!isOperationGated) {
blockInputs[key] = inputs[key]
}
}
return blockInputs
}
function computeOperationLevelInputs(
blockConfig: BlockConfig
): Record<string, Record<string, any>> {
const inputs = blockConfig.inputs || {}
const subBlocks = Array.isArray(blockConfig.subBlocks)
? blockConfig.subBlocks.filter((sb) => sb.mode !== 'trigger')
: []
const opInputs: Record<string, Record<string, any>> = {}
for (const sb of subBlocks) {
const cond = normalizeCondition(sb.condition)
if (!cond || cond.field !== 'operation' || cond.not) continue
const keys: string[] = []
if (sb.canonicalParamId) keys.push(sb.canonicalParamId)
if (sb.id) keys.push(sb.id)
const values = Array.isArray(cond.value) ? cond.value : [cond.value]
for (const key of keys) {
if (!(key in inputs)) continue
for (const v of values) {
const op = String(v)
if (!opInputs[op]) opInputs[op] = {}
opInputs[op][key] = inputs[key]
}
}
}
return opInputs
}
function resolveOperationIds(
blockConfig: BlockConfig,
operationParameters: Record<string, CopilotSubblockMetadata[]>
): string[] {
const opBlock = (blockConfig.subBlocks || []).find((sb) => sb.id === 'operation')
if (opBlock && Array.isArray(opBlock.options)) {
const ids = opBlock.options.map((o) => o.id).filter(Boolean)
if (ids.length > 0) return ids
}
return Object.keys(operationParameters)
}
function resolveToolIdForOperation(blockConfig: BlockConfig, opId: string): string | undefined {
try {
const toolSelector = blockConfig.tools?.config?.tool
if (typeof toolSelector === 'function') {
const maybeToolId = toolSelector({ operation: opId })
if (typeof maybeToolId === 'string') return maybeToolId
}
} catch (error) {
const toolLogger = createLogger('GetBlocksMetadataServerTool')
toolLogger.warn('Failed to resolve tool ID for operation', {
error: error instanceof Error ? error.message : String(error),
})
}
return undefined
}
const DOCS_FILE_MAPPING: Record<string, string> = {}
const SPECIAL_BLOCKS_METADATA: Record<string, any> = {
loop: {
id: 'loop',
name: 'Loop',
description: 'Control flow block for iterating over collections or repeating actions',
longDescription:
'Control flow block for iterating over collections or repeating actions serially',
bestPractices: `
- Set reasonable limits for iterations.
- Use forEach for collection processing, for loops for fixed iterations.
- Cannot have loops/parallels inside a loop block.
- For yaml it needs to connect blocks inside to the start field of the block.
- IMPORTANT for while/doWhile: The condition is evaluated BEFORE each iteration starts, so blocks INSIDE the loop cannot be referenced in the condition (their outputs don't exist yet when the condition runs).