voyageai-cli 1.28.0 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const fs = require('fs');
5
+ const { WORKFLOW_PREFIX, VAICLI_WORKFLOW_PREFIX } = require('./npm-utils');
6
+ const { validateWorkflow, ALL_TOOLS } = require('./workflow');
7
+
8
+ const CATEGORIES = ['retrieval', 'analysis', 'ingestion', 'domain-specific', 'utility', 'integration'];
9
+
10
+ /**
11
+ * Predefined Lucide icon names available for workflow branding.
12
+ * These map to SVG paths served by the playground/store.
13
+ */
14
+ const BRANDING_ICONS = [
15
+ 'trophy', 'search', 'dollar-sign', 'split', 'file-search', 'database',
16
+ 'activity', 'globe', 'shield-alert', 'timer', 'refresh-cw', 'flask-conical',
17
+ 'target', 'code', 'clipboard-list', 'layers', 'bar-chart-3', 'heart-pulse',
18
+ 'brain', 'check-circle', 'zap', 'package', 'microscope', 'sparkle',
19
+ 'scale', 'file-text', 'filter',
20
+ ];
21
+
22
+ /**
23
+ * Default branding colors per category.
24
+ */
25
+ const CATEGORY_COLORS = {
26
+ retrieval: '#00D4AA',
27
+ analysis: '#8B5CF6',
28
+ ingestion: '#059669',
29
+ 'domain-specific': '#1E40AF',
30
+ utility: '#0D9488',
31
+ integration: '#0EA5E9',
32
+ };
33
+
34
+ /**
35
+ * Suggest a branding icon based on category and tools.
36
+ * @param {string} category
37
+ * @param {string[]} tools
38
+ * @returns {string}
39
+ */
40
+ function suggestBrandingIcon(category, tools) {
41
+ const t = new Set(tools);
42
+ if (t.has('estimate') && t.has('similarity')) return 'trophy';
43
+ if (t.has('ingest')) return 'database';
44
+ if (t.has('generate') && t.has('query')) return 'sparkle';
45
+ if (t.has('rerank') && t.has('search')) return 'target';
46
+ if (t.has('search')) return 'search';
47
+ if (t.has('similarity')) return 'scale';
48
+ if (t.has('generate')) return 'brain';
49
+ if (t.has('http')) return 'globe';
50
+ const catMap = {
51
+ retrieval: 'search', analysis: 'bar-chart-3', ingestion: 'database',
52
+ 'domain-specific': 'target', utility: 'zap', integration: 'package',
53
+ };
54
+ return catMap[category] || 'zap';
55
+ }
56
+
57
+ /**
58
+ * Guess a category based on the tools a workflow uses.
59
+ * @param {string[]} tools
60
+ * @returns {string}
61
+ */
62
+ function guessCategory(tools) {
63
+ const t = new Set(tools);
64
+ if (t.has('ingest') || t.has('chunk')) return 'ingestion';
65
+ if (t.has('generate') && (t.has('query') || t.has('search'))) return 'retrieval';
66
+ if (t.has('similarity') || t.has('aggregate')) return 'analysis';
67
+ if (t.has('http')) return 'integration';
68
+ if (t.has('query') || t.has('search') || t.has('rerank')) return 'retrieval';
69
+ return 'utility';
70
+ }
71
+
72
+ /**
73
+ * Extract tool names from a workflow definition's steps.
74
+ * @param {object} definition
75
+ * @returns {string[]}
76
+ */
77
+ function extractTools(definition) {
78
+ const tools = new Set();
79
+ if (!definition.steps) return [];
80
+ for (const step of definition.steps) {
81
+ if (step.tool && ALL_TOOLS.has(step.tool)) {
82
+ tools.add(step.tool);
83
+ }
84
+ // Check loop inline steps
85
+ if (step.tool === 'loop' && step.inputs?.step?.tool) {
86
+ tools.add(step.inputs.step.tool);
87
+ }
88
+ }
89
+ return [...tools];
90
+ }
91
+
92
+ /**
93
+ * Generate a package name from a workflow name.
94
+ * @param {string} name
95
+ * @param {{ scope?: string }} [options]
96
+ * @returns {string}
97
+ */
98
+ function toPackageName(name, options = {}) {
99
+ const slug = name
100
+ .toLowerCase()
101
+ .replace(/[^a-z0-9]+/g, '-')
102
+ .replace(/^-|-$/g, '');
103
+ const base = slug.startsWith(WORKFLOW_PREFIX.slice(0, -1))
104
+ ? slug
105
+ : WORKFLOW_PREFIX + slug;
106
+ if (options.scope === 'vaicli') {
107
+ return `@vaicli/${base}`;
108
+ }
109
+ return base;
110
+ }
111
+
112
+ /**
113
+ * Generate a README.md from workflow definition and package metadata.
114
+ * @param {object} pkg - package.json content
115
+ * @param {object} definition - workflow definition
116
+ * @returns {string}
117
+ */
118
+ function generateReadme(pkg, definition) {
119
+ const lines = [];
120
+ lines.push(`# ${pkg.name}`);
121
+ lines.push('');
122
+ lines.push(pkg.description || definition.description || 'A vai community workflow.');
123
+ lines.push('');
124
+
125
+ // Prerequisites
126
+ lines.push('## Prerequisites');
127
+ lines.push('');
128
+ lines.push('- [voyageai-cli](https://github.com/mrlynn/voyageai-cli) installed');
129
+ const tools = pkg.vai?.tools || [];
130
+ if (tools.includes('query') || tools.includes('search') || tools.includes('ingest')) {
131
+ lines.push('- A MongoDB collection with embedded documents');
132
+ }
133
+ if (tools.includes('generate')) {
134
+ lines.push('- An LLM provider configured (`vai config set llm-provider ...`)');
135
+ }
136
+ if (tools.includes('http')) {
137
+ lines.push('- Network access for external HTTP requests');
138
+ }
139
+ lines.push('');
140
+
141
+ // Inputs
142
+ const inputs = definition.inputs;
143
+ if (inputs && Object.keys(inputs).length > 0) {
144
+ lines.push('## Inputs');
145
+ lines.push('');
146
+ lines.push('| Input | Type | Required | Default | Description |');
147
+ lines.push('|-------|------|----------|---------|-------------|');
148
+ for (const [key, schema] of Object.entries(inputs)) {
149
+ const type = schema.type || 'string';
150
+ const req = schema.required ? 'Yes' : 'No';
151
+ const def = schema.default !== undefined ? String(schema.default) : '—';
152
+ const desc = schema.description || '';
153
+ lines.push(`| ${key} | ${type} | ${req} | ${def} | ${desc} |`);
154
+ }
155
+ lines.push('');
156
+ }
157
+
158
+ // Usage
159
+ lines.push('## Usage');
160
+ lines.push('');
161
+ lines.push('```bash');
162
+ const inputFlags = inputs
163
+ ? Object.entries(inputs)
164
+ .filter(([, s]) => s.required)
165
+ .map(([k]) => `--input ${k}="..."`)
166
+ .join(' \\\n ')
167
+ : '';
168
+ lines.push(`vai workflow run ${pkg.name}${inputFlags ? ' \\\n ' + inputFlags : ''}`);
169
+ lines.push('```');
170
+ lines.push('');
171
+
172
+ // Steps
173
+ if (definition.steps?.length) {
174
+ lines.push('## Steps');
175
+ lines.push('');
176
+ for (let i = 0; i < definition.steps.length; i++) {
177
+ const step = definition.steps[i];
178
+ lines.push(`${i + 1}. **${step.name || step.id}** — \`${step.tool}\``);
179
+ }
180
+ lines.push('');
181
+ }
182
+
183
+ lines.push('## License');
184
+ lines.push('');
185
+ lines.push(pkg.license || 'MIT');
186
+ lines.push('');
187
+
188
+ return lines.join('\n');
189
+ }
190
+
191
+ /**
192
+ * Scaffold a publish-ready npm package from a workflow definition.
193
+ *
194
+ * @param {object} options
195
+ * @param {object} options.definition - Workflow definition (parsed JSON)
196
+ * @param {string} options.name - Package name (without vai-workflow- prefix)
197
+ * @param {string} [options.author] - Author name
198
+ * @param {string} [options.description] - Package description
199
+ * @param {string} [options.category] - Workflow category
200
+ * @param {string[]} [options.tags] - Tags
201
+ * @param {string} [options.scope] - Scope ('vaicli' for official @vaicli packages)
202
+ * @param {string} [options.outputDir] - Output directory (default: ./vai-workflow-<name>/)
203
+ * @returns {{ dir: string, files: string[] }}
204
+ */
205
+ function scaffoldPackage(options) {
206
+ const { definition, name, author, description, category, tags, scope } = options;
207
+
208
+ const packageName = toPackageName(name, { scope });
209
+ // For scoped packages, use the unscoped part as the directory name
210
+ const dirName = packageName.startsWith('@') ? packageName.split('/')[1] : packageName;
211
+ const outputDir = options.outputDir || path.resolve(process.cwd(), dirName);
212
+
213
+ // Validate the workflow
214
+ const errors = validateWorkflow(definition);
215
+ if (errors.length > 0) {
216
+ throw new Error(`Workflow validation failed:\n ${errors.join('\n ')}`);
217
+ }
218
+
219
+ // Extract metadata
220
+ const tools = extractTools(definition);
221
+ const guessedCategory = category || guessCategory(tools);
222
+
223
+ // Build package.json
224
+ const pkg = {
225
+ name: packageName,
226
+ version: '1.0.0',
227
+ description: description || definition.description || '',
228
+ main: 'workflow.json',
229
+ keywords: ['vai-workflow', 'voyageai-cli', ...tools, ...(tags || [])],
230
+ vai: {
231
+ workflowVersion: '1.0',
232
+ category: guessedCategory,
233
+ tags: tags || [],
234
+ tools,
235
+ branding: {
236
+ icon: suggestBrandingIcon(guessedCategory, tools),
237
+ color: CATEGORY_COLORS[guessedCategory] || '#0D9488',
238
+ },
239
+ inputs: {},
240
+ },
241
+ files: ['workflow.json', 'README.md'],
242
+ license: 'MIT',
243
+ };
244
+
245
+ // Add publishConfig for scoped packages
246
+ if (scope === 'vaicli') {
247
+ pkg.publishConfig = { access: 'public' };
248
+ pkg.repository = {
249
+ type: 'git',
250
+ url: 'https://github.com/vaicli/workflows.git',
251
+ directory: `packages/${dirName}`,
252
+ };
253
+ }
254
+
255
+ if (author) {
256
+ pkg.author = author;
257
+ }
258
+
259
+ // Copy input descriptions to vai.inputs
260
+ if (definition.inputs) {
261
+ for (const [key, schema] of Object.entries(definition.inputs)) {
262
+ pkg.vai.inputs[key] = {
263
+ type: schema.type || 'string',
264
+ required: !!schema.required,
265
+ ...(schema.default !== undefined && { default: schema.default }),
266
+ description: schema.description || '',
267
+ };
268
+ }
269
+ }
270
+
271
+ // Generate files
272
+ const readme = generateReadme(pkg, definition);
273
+ const license = `MIT License\n\nCopyright (c) ${new Date().getFullYear()} ${author || 'Contributors'}\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n`;
274
+
275
+ // Write
276
+ fs.mkdirSync(outputDir, { recursive: true });
277
+ const files = [];
278
+
279
+ fs.writeFileSync(path.join(outputDir, 'package.json'), JSON.stringify(pkg, null, 2) + '\n');
280
+ files.push('package.json');
281
+
282
+ fs.writeFileSync(path.join(outputDir, 'workflow.json'), JSON.stringify(definition, null, 2) + '\n');
283
+ files.push('workflow.json');
284
+
285
+ fs.writeFileSync(path.join(outputDir, 'README.md'), readme);
286
+ files.push('README.md');
287
+
288
+ fs.writeFileSync(path.join(outputDir, 'LICENSE'), license);
289
+ files.push('LICENSE');
290
+
291
+ return { dir: outputDir, files };
292
+ }
293
+
294
+ /**
295
+ * Create an empty workflow template for interactive mode.
296
+ * @returns {object}
297
+ */
298
+ function emptyWorkflowTemplate() {
299
+ return {
300
+ name: '',
301
+ description: '',
302
+ version: '1.0.0',
303
+ inputs: {},
304
+ steps: [],
305
+ output: {},
306
+ };
307
+ }
308
+
309
+ module.exports = {
310
+ scaffoldPackage,
311
+ generateReadme,
312
+ extractTools,
313
+ guessCategory,
314
+ suggestBrandingIcon,
315
+ toPackageName,
316
+ emptyWorkflowTemplate,
317
+ CATEGORIES,
318
+ BRANDING_ICONS,
319
+ };