@aivin-labs/cli 1.0.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,653 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import inquirer from 'inquirer';
5
+ import { randomBytes } from 'crypto';
6
+ import { createRequire } from 'module';
7
+
8
+ // The @aivin-labs/sdk version THIS CLI itself depends on (declared in this package's own
9
+ // package.json, resolved via its "./package.json" export) - not this CLI's own version, which is
10
+ // versioned independently since the cli/sdk package split. This is what a fresh `aivin create`/
11
+ // `aivin init` scaffold pins its own `@aivin-labs/sdk` dependency to.
12
+ const SDK_VERSION = JSON.parse(
13
+ fs.readFileSync(createRequire(import.meta.url).resolve('@aivin-labs/sdk/package.json'), 'utf8'),
14
+ ).version;
15
+
16
+ export function readStdin() {
17
+ return new Promise((resolve, reject) => {
18
+ let data = '';
19
+ process.stdin.setEncoding('utf8');
20
+ process.stdin.on('data', (chunk) => (data += chunk));
21
+ process.stdin.on('end', () => resolve(data.trim()));
22
+ process.stdin.on('error', reject);
23
+ });
24
+ }
25
+
26
+ // AI-friendly JSON mode
27
+ export async function createFromJSON(jsonConfig, options) {
28
+ try {
29
+ let config;
30
+
31
+ if (typeof jsonConfig === 'string') {
32
+ try {
33
+ config = JSON.parse(jsonConfig);
34
+ } catch (parseError) {
35
+ if (fs.existsSync(jsonConfig)) {
36
+ config = JSON.parse(fs.readFileSync(jsonConfig, 'utf8'));
37
+ } else {
38
+ throw new Error('Invalid JSON: ' + parseError.message, { cause: parseError });
39
+ }
40
+ }
41
+ } else {
42
+ config = jsonConfig;
43
+ }
44
+
45
+ const validationResult = validatePluginConfig(config);
46
+ if (!validationResult.valid) {
47
+ throw new Error(`Validation failed: ${validationResult.errors.join(', ')}`);
48
+ }
49
+
50
+ const pluginDir = path.join(process.cwd(), options.outputDir || '', config.name);
51
+
52
+ if (fs.existsSync(pluginDir) && !config.overwrite) {
53
+ throw new Error(`Directory exists: ${pluginDir}`);
54
+ }
55
+
56
+ if (!options.silent) {
57
+ console.log(chalk.blue('šŸ¤– Creating plugin:'), config.name);
58
+ }
59
+
60
+ await createPluginProject(pluginDir, config.name, config.description || 'AI plugin', config);
61
+
62
+ if (!options.silent) {
63
+ console.log(chalk.green('āœ… Created:'), pluginDir);
64
+ console.log(chalk.cyan('\nšŸ”§ Next steps:'));
65
+ console.log(` cd ${path.relative(process.cwd(), pluginDir)} # Enter the new project directory`);
66
+ console.log(` npm install # Install dependencies`);
67
+ console.log(` npm start # Start plugin (local gRPC server + HTTP test shim)`);
68
+ }
69
+
70
+ return {
71
+ success: true,
72
+ pluginDir,
73
+ name: config.name,
74
+ description: config.description,
75
+ timestamp: new Date().toISOString(),
76
+ };
77
+ } catch (error) {
78
+ if (!options.silent) {
79
+ console.error(chalk.red('āŒ'), error.message);
80
+ }
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ // Config validation
86
+ export function validatePluginConfig(config) {
87
+ const errors = [];
88
+
89
+ if (!config.name) {
90
+ errors.push('Missing name');
91
+ } else if (!/^[a-z0-9-]+$/.test(config.name)) {
92
+ errors.push('Invalid name format');
93
+ }
94
+
95
+ if (!config.description) {
96
+ errors.push('Missing description');
97
+ }
98
+
99
+ if (config.proxy_config?.type === 'mcp') {
100
+ errors.push(...validateMcpProxyConfig(config.proxy_config).map((e) => `proxy_config.${e}`));
101
+ }
102
+
103
+ return { valid: errors.length === 0, errors };
104
+ }
105
+
106
+ /**
107
+ * Matches the backend's McpProxyConfig (src/plugins/dto/proxy/McpProxyConfig.ts): which fields
108
+ * are required depends on `mcp_transport` (stdio needs a command, sse needs a url) and on
109
+ * `mcp_kind` (tool/resource/prompt each point at a different identifying field).
110
+ */
111
+ export function validateMcpProxyConfig(proxyConfig) {
112
+ const errors = [];
113
+
114
+ if (proxyConfig.mcp_transport === 'stdio') {
115
+ if (!proxyConfig.mcp_command) errors.push('mcp_command is required for stdio transport');
116
+ } else if (proxyConfig.mcp_transport === 'sse') {
117
+ if (!proxyConfig.mcp_url) errors.push('mcp_url is required for sse transport');
118
+ } else {
119
+ errors.push('mcp_transport must be "stdio" or "sse"');
120
+ }
121
+
122
+ const kind = proxyConfig.mcp_kind || 'tool';
123
+ if (kind === 'tool' && !proxyConfig.mcp_tool_name) {
124
+ errors.push('mcp_tool_name is required when mcp_kind is "tool"');
125
+ } else if (kind === 'resource' && !proxyConfig.mcp_resource_uri) {
126
+ errors.push('mcp_resource_uri is required when mcp_kind is "resource"');
127
+ } else if (kind === 'prompt' && !proxyConfig.mcp_prompt_name) {
128
+ errors.push('mcp_prompt_name is required when mcp_kind is "prompt"');
129
+ }
130
+
131
+ return errors;
132
+ }
133
+
134
+ // Interactive mode
135
+ export async function createInteractive(options) {
136
+ console.log(chalk.blue('šŸš€ Aivin Plugin Creator\n'));
137
+
138
+ // A name given upfront (positional arg or --name) means "scaffold a new project folder for me" -
139
+ // matching `aivin mcp create <name>` and the --json/--stdin path below, both of which already
140
+ // nest into a subdirectory named after the plugin. Without one, `aivin create` scaffolds into the
141
+ // current directory - you've already mkdir'd/cd'd into your target folder yourself.
142
+ const nameGivenUpfront = !!options.name;
143
+ if (nameGivenUpfront && !/^[a-z0-9-]+$/.test(options.name)) {
144
+ throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
145
+ }
146
+ const pluginDir = nameGivenUpfront ? path.join(process.cwd(), options.name) : process.cwd();
147
+
148
+ if (nameGivenUpfront && fs.existsSync(pluginDir)) {
149
+ throw new Error(`Directory already exists: ${pluginDir}`);
150
+ }
151
+
152
+ let pluginName = options.name;
153
+
154
+ let currentPackageJson = null;
155
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
156
+ if (!nameGivenUpfront && fs.existsSync(packageJsonPath)) {
157
+ currentPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
158
+ pluginName =
159
+ pluginName ||
160
+ currentPackageJson.name?.replace('@aivin/plugin-', '') ||
161
+ path.basename(process.cwd());
162
+ } else if (!nameGivenUpfront) {
163
+ pluginName = pluginName || path.basename(process.cwd());
164
+ }
165
+
166
+ // A name given upfront (positional arg or --name) is used as-is, no re-prompt - the whole point
167
+ // of providing it was to skip that question.
168
+ const nameQuestion = nameGivenUpfront
169
+ ? []
170
+ : [
171
+ {
172
+ type: 'input',
173
+ name: 'name',
174
+ message: 'Plugin name:',
175
+ default: pluginName,
176
+ validate: (input) => {
177
+ if (!input.trim()) return 'Plugin name cannot be empty';
178
+ if (!/^[a-z0-9-]+$/.test(input))
179
+ return 'Plugin name must contain only lowercase letters, numbers, and hyphens';
180
+ return true;
181
+ },
182
+ },
183
+ ];
184
+
185
+ const answers = await inquirer.prompt([
186
+ ...nameQuestion,
187
+ {
188
+ type: 'input',
189
+ name: 'description',
190
+ message: 'Plugin description:',
191
+ default: currentPackageJson?.description || 'New Aivin plugin',
192
+ },
193
+ ]);
194
+
195
+ pluginName = answers.name || pluginName;
196
+
197
+ await createPluginProject(pluginDir, pluginName, answers.description, null, currentPackageJson);
198
+ console.log(chalk.green(`\nāœ… Plugin files created successfully!`));
199
+ console.log(`šŸ“ Directory: ${pluginDir}`);
200
+ console.log(chalk.cyan(`\nšŸ”§ Next steps:`));
201
+ if (nameGivenUpfront) {
202
+ console.log(` cd ${pluginName} # Enter the new project directory`);
203
+ }
204
+ console.log(` npm install # Install dependencies`);
205
+ console.log(` npm start # Start plugin locally (gRPC server + HTTP test shim on :4001)`);
206
+ }
207
+
208
+ export async function createPluginProject(
209
+ pluginDir,
210
+ name,
211
+ description,
212
+ aiConfig = null,
213
+ currentPackageJson = null,
214
+ { skipHandler = false } = {},
215
+ ) {
216
+ if (!fs.existsSync(pluginDir)) {
217
+ fs.mkdirSync(pluginDir, { recursive: true });
218
+ }
219
+
220
+ const tasks = [
221
+ createManifest(pluginDir, name, description, aiConfig),
222
+ createPackageJson(pluginDir, name, description, currentPackageJson),
223
+ createTsConfig(pluginDir),
224
+ createEnv(pluginDir),
225
+ createGitignore(pluginDir),
226
+ // `skipHandler` is only ever true for `aivin init`'s flow (see below) - the AGENTS.md content
227
+ // differs depending on whether this project will end up with the src/service.ts split or one
228
+ // plain src/main.ts, so it doubles as that signal here.
229
+ createAgentsGuide(pluginDir, { usesServiceSplit: skipHandler }),
230
+ createTestFile(pluginDir, { usesServiceSplit: skipHandler }),
231
+ ];
232
+ // `aivin init` writes its own src/main.ts (static wrapper) + src/service.ts (AI-generated business
233
+ // logic) right after this returns - skip the generic placeholder handler so it isn't written and
234
+ // immediately overwritten.
235
+ if (!skipHandler) tasks.push(createHandler(pluginDir, aiConfig));
236
+ await Promise.all(tasks);
237
+ }
238
+
239
+ /**
240
+ * AGENTS.md - the emerging cross-tool convention (Claude Code, Cursor, and others all read this
241
+ * file automatically on open, unlike docs/AI-Plugin-Guide.md in the *SDK's own* repo, which a
242
+ * coding agent working inside a freshly-scaffolded plugin project - a completely different
243
+ * directory - has no way to discover on its own). Kept short on purpose: this is a primer to get
244
+ * an agent oriented fast, not a full reference - it points to the installed package's own README
245
+ * for depth instead of duplicating it.
246
+ */
247
+ export async function createAgentsGuide(pluginDir, { usesServiceSplit = false } = {}) {
248
+ const agentsPath = path.join(pluginDir, 'AGENTS.md');
249
+ if (fs.existsSync(agentsPath)) return;
250
+
251
+ const filesSection = usesServiceSplit
252
+ ? `## The files that matter
253
+
254
+ - **\`manifest.json\`** - shared fields (version/author) + a \`plugins: []\` array, one entry per exported function (the scaffold has one entry whose \`func\` points at \`main\`). Each entry's \`input\`/\`output\` field descriptions are used for auto-mapping natural-language prompts onto real args. Full reference: \`node_modules/@aivin-labs/sdk/docs/MANIFEST.md\`.
255
+ - **\`src/service.ts\`** - the actual business logic. Edit this. A single exported \`execute(input, ctx)\` that returns plain result data, or throws a plain \`Error\` on failure - no \`PluginResponse\`/\`PluginStatus\` to think about here.
256
+ - **\`src/main.ts\`** - a thin, static wrapper. Do NOT edit this or add logic to it - it just calls \`execute()\` and packages the result into the \`PluginResponse\` the platform expects. Its filename is fixed (the runtime always loads exactly this file), unlike \`service.ts\` which is just this project's convention.`
257
+ : `## The two files that matter
258
+
259
+ - **\`manifest.json\`** - shared fields (version/author) + a \`plugins: []\` array, one entry per exported function (the scaffold has one entry whose \`func\` points at \`main\`). Each entry's \`input\`/\`output\` field descriptions are used for auto-mapping natural-language prompts onto real args. Full reference: \`node_modules/@aivin-labs/sdk/docs/MANIFEST.md\`.
260
+ - **\`src/main.ts\`** - exports exactly one \`main(mission, input, ctx)\` entry point, returning a \`PluginResponse\` (\`{ status: PluginStatus.SUCCESS | ERROR | FAIL, data?, message?, error_code? }\`).`;
261
+
262
+ const regenerateCommand = usesServiceSplit
263
+ ? `\`aivin plugin make "<description>"\` - regenerate \`src/service.ts\` from a plain-language description (detected automatically; \`src/main.ts\` is left untouched).`
264
+ : `\`aivin plugin make "<description>"\` - regenerate \`src/main.ts\` from a plain-language description.`;
265
+
266
+ const testFileName = usesServiceSplit ? 'test/service.test.ts' : 'test/main.test.ts';
267
+ const testTargetName = usesServiceSplit ? 'execute()' : 'main()';
268
+
269
+ const content = `# AGENTS.md
270
+
271
+ This is an Aivin plugin project (\`@aivin-labs/sdk\`). Quick orientation for a coding agent working in this directory.
272
+
273
+ ${filesSection}
274
+
275
+ ## Calling the platform - import what you need from \`@aivin-labs/sdk\`
276
+
277
+ **Always use this style** in any code you write or generate here:
278
+
279
+ \`\`\`typescript
280
+ import { ai } from '@aivin-labs/sdk';
281
+ import { PluginStatus } from '@aivin-labs/sdk';
282
+ import type { PluginInput, PluginContext, PluginResponse } from '@aivin-labs/sdk';
283
+
284
+ export async function main(mission: string, input: PluginInput, ctx: PluginContext): Promise<PluginResponse> {
285
+ const summary = await ai.prompt(\`Summarize: \${input.text}\`);
286
+ return { status: PluginStatus.SUCCESS, data: summary };
287
+ }
288
+ \`\`\`
289
+
290
+ \`ctx.sdk.*\` is the legacy mechanism - it still works (same client under the hood) but is NOT recommended; don't generate new code with it. Its one remaining niche: calling the platform from somewhere that isn't guaranteed to be inside a running \`main()\` invocation, where the top-level import's \`AsyncLocalStorage\` scoping doesn't reach.
291
+
292
+ Namespaces available: \`ai\`, \`knowledge\`, \`vector\`, \`datasource\`, \`causality\`, \`attachment\`, \`workspace\`, \`agent\`, \`browser\`, \`project\`, \`table\`, \`code\`, \`task\`, \`message\`, \`notification\`, \`realtime\`, \`queue\`, \`usage\`, \`automation\`, \`resource\`, \`session\`, \`file\`, \`setting\`, \`store\`, \`redis\`, \`mongo\`. Full per-namespace reference: \`node_modules/@aivin-labs/sdk/docs/sdk/*.md\`.
293
+
294
+ ## Reusing another plugin instead of writing new logic
295
+
296
+ Before implementing something from scratch, check if a plugin already does it:
297
+
298
+ \`\`\`bash
299
+ aivin plugin search "what you're trying to do"
300
+ \`\`\`
301
+
302
+ Call one from your own \`main()\` with \`import { call } from '@aivin-labs/sdk'\` then \`await call('<plugin_id>.<purpose>', params)\`.
303
+
304
+ ## Commands you'll actually use
305
+
306
+ - \`aivin start\` - run this plugin locally (gRPC server + HTTP test shim on :4001).
307
+ - \`aivin start --debug\` - same, plus logs every \`sdk.*\` call live as it happens (human-readable one-liner per call). \`--debug-json\` prints the same events as one JSON object per line instead - prefer this when *you* (the coding agent) are the one reading the output, so you can parse it instead of pattern-matching free text.
308
+ - \`npm test\` - runs \`${testFileName}\` (Node's built-in test runner + native TS execution, no extra tooling). Mocks the SDK with \`createMockSDK\`/\`withMockSDK\` from \`@aivin-labs/sdk\` - no real backend, no gRPC round trip. **Keep this file in sync whenever you change what \`${testTargetName}\` calls or returns** - update the mocked \`handlers\` and assertions together with the logic, don't let it go stale.
309
+ - \`aivin test\` - deploy to a *real* test instance and smoke-test it with generated input (unlike \`npm test\`, this hits the actual backend) - writes a JSON report to \`.test/\`, read that file for structured pass/fail instead of parsing the console output.
310
+ - \`aivin plugin trigger "<mission>" '<input JSON>'\` - invoke an already-deployed plugin for real.
311
+ - \`aivin plugin logs\` - tail this plugin's own console output live, once deployed.
312
+ - ${regenerateCommand}
313
+
314
+ ## Debugging a failure
315
+
316
+ 1. Reproduce locally first: \`aivin start --debug-json\`, then \`curl -X POST http://localhost:4001/invoke -H 'content-type: application/json' -d '{"input":{...}}'\` in another terminal (or read the JSON lines this process prints as it runs, if you're driving it directly).
317
+ 2. Each \`sdk.*\` call's own error message is usually the fastest signal - namespaces validated with zod (\`automation.*\`, \`resource.*\`, \`store.*\`, \`table.*\`) throw \`[namespace.method] invalid params - field: reason\` immediately on a bad shape, before any network call.
318
+ 3. If a call's *shape* is right but the *result* is wrong, check the relevant \`node_modules/@aivin-labs/sdk/docs/sdk/*.md\` page - several namespaces have "Notes & caveats" documenting real field names/behavior that differ from what you'd guess (e.g. \`automation.createJob\` takes \`mission\`/\`schedule_condition\`, not \`name\`/\`schedule\`).
319
+
320
+ Full docs: \`node_modules/@aivin-labs/sdk/README.md\` and \`node_modules/@aivin-labs/sdk/docs/\`.
321
+ `;
322
+ fs.writeFileSync(agentsPath, content);
323
+ }
324
+
325
+ /**
326
+ * A real, runnable example test using createMockSDK/withMockSDK/createMockContext - not just
327
+ * documentation. Deliberately written to still PASS against the literal placeholder handler
328
+ * `createHandler` writes (which calls no SDK method at all) - the mocked `ai.prompt` handler is
329
+ * simply never invoked in that case, and the assertions on `status`/`data.processed` hold either
330
+ * way. Once real logic replaces the placeholder (by hand or via `aivin plugin make`), this file is
331
+ * a starting point to adapt, exactly like `src/main.ts`/`src/service.ts` themselves are.
332
+ */
333
+ export async function createTestFile(pluginDir, { usesServiceSplit = false } = {}) {
334
+ const testDir = path.join(pluginDir, 'test');
335
+ if (!fs.existsSync(testDir)) fs.mkdirSync(testDir, { recursive: true });
336
+
337
+ const testPath = path.join(testDir, usesServiceSplit ? 'service.test.ts' : 'main.test.ts');
338
+ if (fs.existsSync(testPath)) return;
339
+
340
+ const content = usesServiceSplit
341
+ ? `// Tests the real business logic in src/service.ts directly - src/main.ts is a thin, static
342
+ // wrapper (see AGENTS.md) not worth testing on its own. Adapt the mocked handlers/assertions
343
+ // below once execute() calls something other than what's here now.
344
+ import { test } from 'node:test';
345
+ import assert from 'node:assert/strict';
346
+ import { createMockSDK, withMockSDK } from '@aivin-labs/sdk';
347
+ import { execute } from '../src/service.ts';
348
+
349
+ test('execute() returns a result', async () => {
350
+ const { client, calls } = createMockSDK({
351
+ handlers: {
352
+ // Add one entry per namespace.method execute() actually calls - see the error message
353
+ // a missing handler throws for the exact string to use, or docs/sdk/*.md in
354
+ // node_modules/@aivin-labs/sdk.
355
+ 'ai.prompt': async ({ quest }) => \`Echo: \${quest}\`,
356
+ },
357
+ });
358
+
359
+ const result = await withMockSDK(client, () => execute({ text: 'hello' } as any, {} as any));
360
+
361
+ assert.ok(result !== undefined);
362
+ // Uncomment once execute() actually calls something:
363
+ // assert.equal(calls[0]?.namespace, 'ai.prompt');
364
+ void calls;
365
+ });
366
+ `
367
+ : `// Adapt the mocked handlers/assertions below once main() calls something other than what's
368
+ // here now (the placeholder calls no SDK method at all, so this passes as-is against a fresh
369
+ // \`aivin create\`/\`aivin init\` scaffold).
370
+ import { test } from 'node:test';
371
+ import assert from 'node:assert/strict';
372
+ import { createMockSDK, withMockSDK, createMockContext } from '@aivin-labs/sdk';
373
+ import { main } from '../src/main.ts';
374
+
375
+ test('main() returns a success response', async () => {
376
+ const { client, calls } = createMockSDK({
377
+ handlers: {
378
+ // Add one entry per namespace.method main() actually calls - see the error message
379
+ // a missing handler throws for the exact string to use, or docs/sdk/*.md in
380
+ // node_modules/@aivin-labs/sdk.
381
+ 'ai.prompt': async ({ quest }) => \`Echo: \${quest}\`,
382
+ },
383
+ });
384
+ const ctx = createMockContext(client);
385
+
386
+ const result = await withMockSDK(client, () => main('test mission', { text: 'hello' }, ctx));
387
+
388
+ assert.equal(result.status, 'success');
389
+ // Uncomment once main() actually calls something:
390
+ // assert.equal(calls[0]?.namespace, 'ai.prompt');
391
+ void calls;
392
+ });
393
+ `;
394
+
395
+ fs.writeFileSync(testPath, content);
396
+ }
397
+
398
+ export async function createGitignore(pluginDir) {
399
+ const gitignorePath = path.join(pluginDir, '.gitignore');
400
+ if (fs.existsSync(gitignorePath)) return;
401
+
402
+ const content = ['node_modules/', 'dist/', '.env', '.env.*', '*.log', '.test/', ''].join('\n');
403
+ fs.writeFileSync(gitignorePath, content);
404
+ }
405
+
406
+ // Fields that belong once at the top level of the default { ...commonFields, plugins: [...] }
407
+ // manifest shape, shared by every entry - everything else is entry-specific.
408
+ export const SHARED_MANIFEST_FIELDS = ['version', 'author', 'email', 'license', 'connection_id'];
409
+
410
+ // CLI-only config keys that may arrive via `aivin create --json` but have no business being
411
+ // persisted into manifest.json.
412
+ export const NON_MANIFEST_CONFIG_KEYS = ['handlerCode', 'overwrite'];
413
+
414
+ export async function createManifest(pluginDir, name, description, aiConfig) {
415
+ const manifestPath = path.join(pluginDir, 'manifest.json');
416
+ let currentManifest = null;
417
+ if (fs.existsSync(manifestPath)) {
418
+ currentManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
419
+ }
420
+
421
+ const overrides = { ...(currentManifest || {}), ...(aiConfig || {}) };
422
+ for (const key of NON_MANIFEST_CONFIG_KEYS) delete overrides[key];
423
+
424
+ // Proxy plugins keep the flat single-object shape: they have no src/main.ts export to name in a
425
+ // plugins[] entry's required `func` field.
426
+ if (overrides.proxy_config) {
427
+ const flatManifest = {
428
+ id: randomBytes(16).toString('hex'),
429
+ name,
430
+ description,
431
+ version: '1.0.0',
432
+ author: '',
433
+ email: '',
434
+ initial: {},
435
+ ...overrides,
436
+ };
437
+ fs.writeFileSync(manifestPath, JSON.stringify(flatManifest, null, 2));
438
+ return;
439
+ }
440
+
441
+ // An existing plugins[] manifest is already in the default shape - keep it, only filling in
442
+ // missing shared fields.
443
+ if (Array.isArray(overrides.plugins)) {
444
+ const newManifest = { version: '1.0.0', author: '', email: '', ...overrides };
445
+ fs.writeFileSync(manifestPath, JSON.stringify(newManifest, null, 2));
446
+ return;
447
+ }
448
+
449
+ const shared = {};
450
+ const entryOverrides = {};
451
+ for (const [key, value] of Object.entries(overrides)) {
452
+ if (SHARED_MANIFEST_FIELDS.includes(key)) shared[key] = value;
453
+ else entryOverrides[key] = value;
454
+ }
455
+
456
+ // The default manifest shape: shared fields once at the top level + a plugins[] array, here with
457
+ // a single entry backed by src/main.ts's `main` export. Matches what deploy/runtime already
458
+ // understand for multi-function plugins (see docs/MANIFEST.md) - adding a second function later
459
+ // is just appending another entry. `id` is a local placeholder until the plugin is first
460
+ // deployed, at which point the server assigns (and this CLI writes back) the real one.
461
+ const newManifest = {
462
+ version: '1.0.0',
463
+ author: '',
464
+ email: '',
465
+ ...shared,
466
+ plugins: [
467
+ {
468
+ id: randomBytes(16).toString('hex'),
469
+ name,
470
+ description,
471
+ func: 'main',
472
+ input: {
473
+ data: 'object - Input data for processing',
474
+ },
475
+ output: {
476
+ data: 'object - Processed data result',
477
+ },
478
+ trigger_type: ['manual', 'api', 'chat'],
479
+ initial: {},
480
+ ...entryOverrides,
481
+ },
482
+ ],
483
+ };
484
+
485
+ fs.writeFileSync(manifestPath, JSON.stringify(newManifest, null, 2));
486
+ }
487
+
488
+ /**
489
+ * The one entry of a default (single-entry plugins[]) manifest, or the manifest itself for the
490
+ * flat single-object shape - for CLI paths that need to read/patch entry-level fields
491
+ * (`id`, `input`, `description`, ...) without caring which shape is on disk. Mutating the returned
492
+ * object mutates the manifest it came from.
493
+ */
494
+ export function primaryManifestEntry(manifest) {
495
+ if (manifest && Array.isArray(manifest.plugins) && manifest.plugins.length > 0) {
496
+ return manifest.plugins[0];
497
+ }
498
+ return manifest;
499
+ }
500
+
501
+ export async function createHandler(pluginDir, aiConfig) {
502
+ const header =
503
+ '// Import just the namespace(s) you need - see docs/SDK.md for the full list\n' +
504
+ '// (ai, vector, knowledge, task, store, redis, mongo, workspace, agent, realtime, queue, ...).\n' +
505
+ "import { ai } from '@aivin-labs/sdk';\n" +
506
+ "import type { PluginInput, PluginContext, PluginResponse } from '@aivin-labs/sdk';\n" +
507
+ "import { PluginStatus, PluginErrorCode } from '@aivin-labs/sdk';";
508
+
509
+ let handlerContent;
510
+
511
+ if (aiConfig && aiConfig.handlerCode) {
512
+ handlerContent = `${header}\n\n${aiConfig.handlerCode}\n`;
513
+ } else {
514
+ // One entry point to start with - the scaffolded manifest.json's plugins[0] points at this
515
+ // `main` export via its `func` field. To add more functions, export more named functions here
516
+ // and append one plugins[] entry per function - see docs/MANIFEST.md#multi-function-plugins.
517
+ handlerContent = `${header}
518
+
519
+ export async function main(mission: string, input: PluginInput, ctx: PluginContext): Promise<PluginResponse> {
520
+ try {
521
+ console.log('Plugin main called:', { mission, input });
522
+
523
+ // Example: const summary = await ai.prompt(\`Summarize: \${JSON.stringify(input)}\`);
524
+
525
+ return {
526
+ status: PluginStatus.SUCCESS,
527
+ data: {
528
+ processed: input,
529
+ timestamp: new Date().toISOString()
530
+ },
531
+ message: 'Plugin executed successfully!'
532
+ };
533
+ } catch (error: any) {
534
+ console.error('Plugin error:', error);
535
+ return {
536
+ status: PluginStatus.ERROR,
537
+ message: error.message,
538
+ error_code: PluginErrorCode.EXECUTION_FAILED
539
+ };
540
+ }
541
+ }
542
+ `;
543
+ }
544
+
545
+ const srcDir = path.join(pluginDir, 'src');
546
+ if (!fs.existsSync(srcDir)) {
547
+ fs.mkdirSync(srcDir, { recursive: true });
548
+ }
549
+ fs.writeFileSync(path.join(srcDir, 'main.ts'), handlerContent);
550
+ }
551
+
552
+ export async function createPackageJson(pluginDir, name, description, currentPackageJson = null) {
553
+ const newPackageJson = {
554
+ name,
555
+ version: '1.0.0',
556
+ description,
557
+ type: 'module',
558
+ scripts: {
559
+ // `aivin-server` (from @aivin-labs/sdk's own `bin` field) boots the plugin directly - no
560
+ // dependency on @aivin-labs/cli at all. This is what the deployed container's `npm start`
561
+ // actually runs (see DockerHelper.createDockerCompose on the backend), so it must keep
562
+ // working with ONLY @aivin-labs/sdk installed. For local dev, `aivin start` (from
563
+ // @aivin-labs/cli) wraps this same binary with extra flags (--debug, --no-watch, ...).
564
+ start: 'aivin-server',
565
+ // Node's own native TS execution (same mechanism PluginServer.loadPlugin uses to load
566
+ // src/main.ts directly, no separate compile step) - not a new tool/dependency to learn.
567
+ test: 'node --test test/**/*.test.ts',
568
+ },
569
+ dependencies: {
570
+ // Pinned to an exact version, not "latest" - the platform's own AI security scan flags
571
+ // "latest"/range dependency pins as a supply-chain risk (a later, unreviewed version could
572
+ // get pulled in silently) and blocks deployment over it. Reads the version of @aivin-labs/sdk
573
+ // this CLI itself depends on, so it can't drift from what's actually published to npm.
574
+ '@aivin-labs/sdk': SDK_VERSION,
575
+ },
576
+ devDependencies: {
577
+ '@types/node': '^24.0.0',
578
+ typescript: '^5.9.3',
579
+ },
580
+ keywords: ['aivin', 'plugin'],
581
+ engines: { node: '>=22.0.0' },
582
+ };
583
+
584
+ if (currentPackageJson) {
585
+ const merged = { ...currentPackageJson, ...newPackageJson };
586
+ merged.scripts = { ...newPackageJson.scripts, ...currentPackageJson.scripts };
587
+ merged.dependencies = { ...currentPackageJson.dependencies, ...newPackageJson.dependencies };
588
+ merged.devDependencies = {
589
+ ...newPackageJson.devDependencies,
590
+ ...currentPackageJson.devDependencies,
591
+ };
592
+ merged.keywords = [
593
+ ...new Set([...(currentPackageJson.keywords || []), ...newPackageJson.keywords]),
594
+ ];
595
+
596
+ fs.writeFileSync(path.join(pluginDir, 'package.json'), JSON.stringify(merged, null, 2));
597
+ } else {
598
+ fs.writeFileSync(path.join(pluginDir, 'package.json'), JSON.stringify(newPackageJson, null, 2));
599
+ }
600
+ }
601
+
602
+ export async function createTsConfig(pluginDir) {
603
+ const tsConfigPath = path.join(pluginDir, 'tsconfig.json');
604
+ if (fs.existsSync(tsConfigPath)) return;
605
+
606
+ const tsConfig = {
607
+ compilerOptions: {
608
+ target: 'ES2022',
609
+ lib: ['ES2022'],
610
+ module: 'ESNext',
611
+ moduleResolution: 'node',
612
+ allowSyntheticDefaultImports: true,
613
+ esModuleInterop: true,
614
+ strict: true,
615
+ skipLibCheck: true,
616
+ forceConsistentCasingInFileNames: true,
617
+ resolveJsonModule: true,
618
+ allowImportingTsExtensions: true,
619
+ noEmit: true,
620
+ noImplicitAny: false,
621
+ noImplicitReturns: false,
622
+ noImplicitThis: false,
623
+ noUnusedLocals: false,
624
+ noUnusedParameters: false,
625
+ useUnknownInCatchVariables: false,
626
+ },
627
+ include: ['src/**/*'],
628
+ exclude: ['node_modules', '**/*.test.ts', '**/*.spec.ts'],
629
+ };
630
+
631
+ fs.writeFileSync(tsConfigPath, JSON.stringify(tsConfig, null, 2));
632
+ }
633
+
634
+ export async function createEnv(pluginDir) {
635
+ const envPath = path.join(pluginDir, '.env');
636
+ if (fs.existsSync(envPath)) return;
637
+
638
+ const envContent = [
639
+ '# Local development only. In production the container gets these injected automatically',
640
+ '# by the Aivin host (see DockerHelper.createDockerCompose on the backend) - you do not set',
641
+ '# them yourself when deploying.',
642
+ '',
643
+ 'NODE_ENV=development',
644
+ '',
645
+ '# SDK calls default to the production backend (api.aivin.cloud) if this is left unset -',
646
+ '# uncomment to point `npm start` / the local test HTTP shim at a local/dev backend instead.',
647
+ '# SDK_GRPC_ENDPOINT=localhost:50051',
648
+ '# SDK_GRPC_SECRET=',
649
+ '',
650
+ ];
651
+
652
+ fs.writeFileSync(envPath, envContent.join('\n'));
653
+ }