@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,858 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import axios from 'axios';
5
+ import inquirer from 'inquirer';
6
+ import { spawn, execFileSync } from 'child_process';
7
+ import os from 'os';
8
+ import { createHash, randomBytes } from 'crypto';
9
+ import { io } from 'socket.io-client';
10
+ import { primaryManifestEntry, createPluginProject, createHandler } from './scaffold.mjs';
11
+ import { withSpinner } from './util.mjs';
12
+ import { DEPLOY_EXCLUDE_DIRS, isEnvFile } from './deploy.mjs';
13
+
14
+ /**
15
+ * Static (not AI-generated) entry-point wrapper `aivin init` writes to src/main.ts - deterministic
16
+ * every time, so the only AI-generated file is src/service.ts (the actual business logic). Keeps
17
+ * protocol concerns (PluginResponse/PluginStatus/error_code) out of the business logic entirely -
18
+ * `execute()` just returns plain data or throws a plain Error.
19
+ */
20
+ export function buildInitMainWrapper() {
21
+ return `// This file is a thin, static wrapper - the real business logic lives in src/service.ts
22
+ // (regenerate it with \`aivin plugin make "<new description>"\`, targeting src/service.ts).
23
+ import { execute } from './service.ts';
24
+ import { PluginStatus, PluginErrorCode } from '@aivin-labs/sdk';
25
+ import type { PluginInput, PluginContext, PluginResponse } from '@aivin-labs/sdk';
26
+
27
+ export async function main(mission: string, input: PluginInput, ctx: PluginContext): Promise<PluginResponse> {
28
+ try {
29
+ const data = await execute(input, ctx);
30
+ return { status: PluginStatus.SUCCESS, data, message: 'Success' };
31
+ } catch (error: any) {
32
+ console.error('Plugin error:', error);
33
+ return {
34
+ status: PluginStatus.ERROR,
35
+ message: error.message,
36
+ error_code: PluginErrorCode.EXECUTION_FAILED,
37
+ };
38
+ }
39
+ }
40
+ `;
41
+ }
42
+
43
+ /**
44
+ * `aivin init`'s code generation - targets src/service.ts (a plain business-logic module, per
45
+ * CodeGenerationHelper's generic "utility file" branch on the backend) instead of src/main.ts (the
46
+ * "MAIN ENTRY POINT, must return PluginResponse" branch `plugin make` targets). Keeps the
47
+ * AI-generated file free of protocol boilerplate - src/main.ts (buildInitMainWrapper, above) is the
48
+ * only place that needs to know about PluginResponse/PluginStatus at all.
49
+ */
50
+ export async function generateServiceAndWrapper(pluginDir, description, options = {}) {
51
+ const manifestPath = path.join(pluginDir, 'manifest.json');
52
+ const servicePath = path.join(pluginDir, 'src', 'service.ts');
53
+ const mainPath = path.join(pluginDir, 'src', 'main.ts');
54
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
55
+
56
+ const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
57
+ const apiKey = process.env.API_KEY;
58
+ if (!apiKey) {
59
+ console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
60
+ }
61
+
62
+ const logic = `Write the core business logic for an Aivin plugin, as a single exported function:
63
+ export async function execute(input: PluginInput, ctx: PluginContext): Promise<any>
64
+ Rules:
65
+ - This is PURE business logic - do NOT return a PluginResponse/{status, data, message} envelope, do NOT import or reference PluginStatus/PluginErrorCode. Just return the actual result data, or throw a plain Error on failure - the caller (src/main.ts) handles wrapping it into the plugin's response format.
66
+ - "input" fields come from the manifest's "input" description below. Validate required fields are present at the start and throw a clear Error if not.
67
+ - Preferred: import only the namespace(s) you need directly, e.g. import { ai, vector, task, store, redis, mongo } from '@aivin-labs/sdk'; then call ai.prompt(...), vector.search(...), etc. Only fall back to import { call } from '@aivin-labs/sdk'; call(namespace, params) if no sugar method fits.
68
+ - Import types from '@aivin-labs/sdk' if needed: import type { PluginInput, PluginContext } from '@aivin-labs/sdk';
69
+
70
+ Business requirement:
71
+ ${description}`;
72
+
73
+ let response;
74
+ try {
75
+ response = await axios.post(
76
+ `${serverUrl}/code/generate`,
77
+ {
78
+ // No `workspace_files` - see makePluginFromDescription's comment on why that would trip
79
+ // the backend's surgical-edit/diff mode.
80
+ logic,
81
+ // code_id = the entry id, the stable identity of this code workspace on the server -
82
+ // it keys the Redis draft, the RAG index over previously generated files, and the live
83
+ // socket room. func = which export of src/main.ts this generation targets.
84
+ code_id: primaryManifestEntry(manifest).id,
85
+ func: primaryManifestEntry(manifest).func || 'main',
86
+ target_file: 'src/service.ts',
87
+ model: options.model,
88
+ provider: options.provider,
89
+ },
90
+ {
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ Authorization: `Bearer ${apiKey || 'dev-token'}`,
94
+ },
95
+ },
96
+ );
97
+ } catch (error) {
98
+ const message = error.response?.data?.message || error.message;
99
+ throw new Error(`Code generation failed: ${message}`, { cause: error });
100
+ }
101
+
102
+ const result = response.data ?? {};
103
+ if (!result.code) {
104
+ throw new Error('Aivin server did not return generated code.');
105
+ }
106
+ const looksLikeDiffBlob = /^\s*\{\s*"mode"\s*:\s*"(diff|full)"/.test(result.code);
107
+ if (looksLikeDiffBlob) {
108
+ throw new Error(
109
+ 'Aivin server returned an internal patch format instead of plain code - this is a server-side bug, not something to write to src/service.ts. Please report it.',
110
+ );
111
+ }
112
+
113
+ fs.mkdirSync(path.dirname(servicePath), { recursive: true });
114
+ fs.writeFileSync(servicePath, result.code);
115
+ fs.writeFileSync(mainPath, buildInitMainWrapper());
116
+
117
+ applyGeneratedManifestFields(manifestPath, manifest, result);
118
+ }
119
+
120
+ /**
121
+ * `aivin init [name]` - the guided, one-command replacement for `aivin create` + `aivin plugin
122
+ * make`: asks just what's needed (name, business description), scaffolds the project, and
123
+ * generates real working code from the description - split into src/service.ts (business logic,
124
+ * AI-generated) + src/main.ts (protocol wrapper, static/deterministic) instead of one file mixing
125
+ * both concerns, per the same architecture as `plugin make` targeting a non-main.ts file.
126
+ */
127
+ export async function initInteractive(options) {
128
+ console.log(chalk.blue('🚀 Aivin Plugin Init\n'));
129
+
130
+ const nameGivenUpfront = !!options.name;
131
+ if (nameGivenUpfront && !/^[a-z0-9-]+$/.test(options.name)) {
132
+ throw new Error('Plugin name must contain only lowercase letters, numbers, and hyphens');
133
+ }
134
+ const pluginDir = nameGivenUpfront ? path.join(process.cwd(), options.name) : process.cwd();
135
+ if (nameGivenUpfront && fs.existsSync(pluginDir)) {
136
+ throw new Error(`Directory already exists: ${pluginDir}`);
137
+ }
138
+
139
+ let pluginName = options.name || (nameGivenUpfront ? undefined : path.basename(process.cwd()));
140
+
141
+ const nameQuestion = nameGivenUpfront
142
+ ? []
143
+ : [
144
+ {
145
+ type: 'input',
146
+ name: 'name',
147
+ message: 'Plugin name:',
148
+ default: pluginName,
149
+ validate: (input) => {
150
+ if (!input.trim()) return 'Plugin name cannot be empty';
151
+ if (!/^[a-z0-9-]+$/.test(input))
152
+ return 'Plugin name must contain only lowercase letters, numbers, and hyphens';
153
+ return true;
154
+ },
155
+ },
156
+ ];
157
+
158
+ const answers = await inquirer.prompt([
159
+ ...nameQuestion,
160
+ {
161
+ type: 'input',
162
+ name: 'description',
163
+ message: 'What should this plugin do? (be specific - this is what generates your code)',
164
+ validate: (input) => (input.trim() ? true : 'A description is required to generate working code'),
165
+ },
166
+ ]);
167
+
168
+ pluginName = answers.name || pluginName;
169
+ const description = answers.description;
170
+
171
+ // Same as `aivin create`'s createInteractive: scaffolding into the current directory (no name
172
+ // given upfront) can land on top of an already-populated package.json - read it so
173
+ // createPackageJson merges into it instead of clobbering existing scripts/deps/name.
174
+ let currentPackageJson = null;
175
+ if (!nameGivenUpfront) {
176
+ const packageJsonPath = path.join(pluginDir, 'package.json');
177
+ if (fs.existsSync(packageJsonPath)) {
178
+ currentPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
179
+ }
180
+ }
181
+
182
+ console.log(chalk.gray(`\n📁 Scaffolding ${pluginName}...`));
183
+ // input/output start EMPTY (not the generic {data: "..."} placeholder `aivin create` writes) so
184
+ // generateServiceAndWrapper's applyGeneratedManifestFields (which only fills a field that's
185
+ // currently empty) actually applies the schema the AI infers from the description, instead of
186
+ // silently no-op'ing against an already-non-empty placeholder.
187
+ await createPluginProject(pluginDir, pluginName, description, { input: {}, output: {} }, currentPackageJson, {
188
+ skipHandler: true,
189
+ });
190
+
191
+ try {
192
+ await withSpinner('🤖 Generating business logic (src/service.ts)', () => generateServiceAndWrapper(pluginDir, description, options));
193
+ console.log(chalk.green('✅ src/service.ts + src/main.ts generated'));
194
+ } catch (error) {
195
+ // Don't leave a half-scaffolded project on generation failure - fall back to the plain
196
+ // placeholder handler (same one `aivin create` writes), so `aivin init` still leaves a working,
197
+ // deployable plugin the developer can fill in by hand or retry with `aivin plugin make`. Also
198
+ // restores the generic input/output placeholder - the empty {} above only makes sense once
199
+ // generation has actually filled it in.
200
+ console.error(chalk.yellow(`⚠️ Code generation failed (${error.message}) - falling back to a placeholder handler.`));
201
+ await createHandler(pluginDir, null);
202
+ const manifestPath = path.join(pluginDir, 'manifest.json');
203
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
204
+ const entry = primaryManifestEntry(manifest);
205
+ if (Object.keys(entry.input || {}).length === 0) entry.input = { data: 'object - Input data for processing' };
206
+ if (Object.keys(entry.output || {}).length === 0) entry.output = { data: 'object - Processed data result' };
207
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
208
+ }
209
+
210
+ console.log(chalk.green(`\n✅ Plugin initialized!`));
211
+ console.log(`📁 Directory: ${pluginDir}`);
212
+ console.log(chalk.cyan(`\n🔧 Next steps:`));
213
+ if (nameGivenUpfront) {
214
+ console.log(` cd ${pluginName} # Enter the new project directory`);
215
+ }
216
+ console.log(` npm install # Install dependencies`);
217
+ console.log(` npm start # Start plugin locally (gRPC server + HTTP test shim on :4001)`);
218
+ }
219
+
220
+ /** Single call to POST /code/generate - used directly for surgical per-file fixes in
221
+ * generateProjectWithSelfCorrection. Throws on network/API failure or if the server ever returns
222
+ * its internal diff-patch blob instead of plain source. */
223
+ export async function requestCodeGeneration(serverUrl, apiKey, payload) {
224
+ let response;
225
+ try {
226
+ response = await axios.post(`${serverUrl}/code/generate`, payload, {
227
+ headers: {
228
+ 'Content-Type': 'application/json',
229
+ Authorization: `Bearer ${apiKey || 'dev-token'}`,
230
+ },
231
+ });
232
+ } catch (error) {
233
+ const message = error.response?.data?.message || error.message;
234
+ throw new Error(`Code generation failed: ${message}`, { cause: error });
235
+ }
236
+ const result = response.data ?? {};
237
+ if (!result.code) {
238
+ throw new Error('Aivin server did not return generated code.');
239
+ }
240
+ const looksLikeDiffBlob = /^\s*\{\s*"mode"\s*:\s*"(diff|full)"/.test(result.code);
241
+ if (looksLikeDiffBlob) {
242
+ throw new Error(
243
+ 'Aivin server returned an internal patch format instead of plain code - this is a server-side bug, not something to write to src/main.ts. Please report it.',
244
+ );
245
+ }
246
+ return result;
247
+ }
248
+
249
+ // How many times to send tsc's own compiler errors back to the AI and ask it to fix them, on top
250
+ // of the first-pass generation. Bounded so a stubborn error (e.g. a package that genuinely isn't
251
+ // available in the plugin sandbox) doesn't loop forever burning generation calls.
252
+ export const CODEGEN_MAX_FIX_ATTEMPTS = 2;
253
+
254
+ /** Type-checks the freshly generated handler with the scaffolded project's own `typescript`
255
+ * devDependency - skipped (not failed) when `node_modules` isn't installed yet, e.g. running
256
+ * `plugin make`/`convert` straight after `aivin create` and before `npm install`. This is what
257
+ * gives the self-correction loop something concrete to react to: exact `file(line,col)` compiler
258
+ * errors, not a guess at what might be wrong. */
259
+ /**
260
+ * Runs asynchronously (spawn, not execSync) on purpose: this is also called as the `run_typecheck`
261
+ * tool during `plugin convert`, where the process must keep servicing its socket connection (ping/
262
+ * pong, other tool calls) while tsc runs - a synchronous execSync call blocks the whole event loop
263
+ * for as long as tsc takes, which on a real project can be many seconds and risks the server-side
264
+ * ping timeout disconnecting the socket mid-typecheck.
265
+ */
266
+ export function typeCheckHandler(currentDir) {
267
+ return new Promise((resolve) => {
268
+ const tscBin = path.join(currentDir, 'node_modules', 'typescript', 'bin', 'tsc');
269
+ if (!fs.existsSync(tscBin)) return resolve({ skipped: true, errors: [] });
270
+ const tsconfigPath = path.join(currentDir, 'tsconfig.json');
271
+ // --incremental caches type-check state in a .tsbuildinfo file (outside the project, keyed by
272
+ // a hash of its path - never written into the user's own directory, nothing to .gitignore).
273
+ // On a large `plugin convert` project, the fix loop can call this 2-3 times in one run; without
274
+ // this, every single call is a full cold recompile of every file, not just the 1-2 that changed
275
+ // since the last attempt.
276
+ const buildInfoDir = path.join(os.tmpdir(), 'aivin-tsc-cache');
277
+ const buildInfoPath = path.join(buildInfoDir, `${createHash('md5').update(currentDir).digest('hex')}.tsbuildinfo`);
278
+ fs.mkdirSync(buildInfoDir, { recursive: true });
279
+ const args = fs.existsSync(tsconfigPath)
280
+ ? ['--noEmit', '--incremental', '--tsBuildInfoFile', buildInfoPath, '-p', tsconfigPath]
281
+ : ['--noEmit', '--incremental', '--tsBuildInfoFile', buildInfoPath, '--skipLibCheck', 'src/main.ts'];
282
+ let output = '';
283
+ const child = spawn(process.execPath, [tscBin, ...args], { cwd: currentDir, stdio: ['ignore', 'pipe', 'pipe'] });
284
+ child.stdout.on('data', (chunk) => { output += chunk; });
285
+ child.stderr.on('data', (chunk) => { output += chunk; });
286
+ child.on('error', (error) => resolve({ skipped: false, errors: [error.message] }));
287
+ child.on('close', (code) => {
288
+ if (code === 0) return resolve({ skipped: false, errors: [] });
289
+ // tsc's real per-error lines all match this ("file(line,col): error TSxxxx: message") - filter
290
+ // out the trailing "Found N errors" summary line so only actionable lines go back to the AI.
291
+ const errorLines = output.split('\n').filter((line) => /error TS\d+/.test(line));
292
+ resolve({ skipped: false, errors: errorLines.length > 0 ? errorLines : [output.trim()].filter(Boolean) });
293
+ });
294
+ });
295
+ }
296
+
297
+ // Off-default ports so this doesn't collide with a real `aivin start` (4001/50051) the developer
298
+ // might already have running for the same or another plugin while `plugin convert` is going.
299
+ export const SMOKE_TEST_HTTP_PORT = 47401;
300
+
301
+ export const SMOKE_TEST_GRPC_BIND = '0.0.0.0:47451';
302
+
303
+ export const SMOKE_TEST_READY_TIMEOUT_MS = 15_000;
304
+
305
+ /**
306
+ * Runs `aivin plugin convert`'s `run_smoke_test` tool call: spawns the exact same runtime
307
+ * `aivin start` uses (the target project's own installed `@aivin-labs/sdk`'s `bin/server.mjs` -
308
+ * not anything bundled with this CLI package) against the just-generated project, waits for its
309
+ * local HTTP test shim to come up, POSTs the AI-generated sample input to it, and reports back
310
+ * whether the plugin actually ran successfully - not just whether it type-checks. Always kills the
311
+ * spawned process afterward, success or failure.
312
+ */
313
+ export async function runSmokeTestHandler(currentDir, args) {
314
+ const sdkPkgPath = path.join(currentDir, 'node_modules', '@aivin-labs', 'sdk');
315
+ if (!fs.existsSync(sdkPkgPath)) return { skipped: true };
316
+
317
+ const serverPath = path.join(sdkPkgPath, 'bin', 'server.mjs');
318
+ let stderrOutput = '';
319
+ const child = spawn(process.execPath, [serverPath], {
320
+ cwd: currentDir,
321
+ env: {
322
+ ...process.env,
323
+ LOCAL_TEST_PORT: String(SMOKE_TEST_HTTP_PORT),
324
+ SDK_GRPC_SERVER_BIND: SMOKE_TEST_GRPC_BIND,
325
+ NODE_ENV: 'development',
326
+ },
327
+ stdio: ['ignore', 'pipe', 'pipe'],
328
+ });
329
+ child.stderr.on('data', (chunk) => { stderrOutput += chunk.toString().slice(0, 500); });
330
+ child.on('error', () => {}); // reported via the readiness poll failing below, not here
331
+
332
+ try {
333
+ const deadline = Date.now() + SMOKE_TEST_READY_TIMEOUT_MS;
334
+ let ready = false;
335
+ while (Date.now() < deadline) {
336
+ try {
337
+ await axios.get(`http://localhost:${SMOKE_TEST_HTTP_PORT}/health`, { timeout: 1000 });
338
+ ready = true;
339
+ break;
340
+ } catch {
341
+ await new Promise((resolve) => setTimeout(resolve, 300));
342
+ }
343
+ }
344
+ if (!ready) {
345
+ return { skipped: false, success: false, error: `Local runtime didn't become ready within ${SMOKE_TEST_READY_TIMEOUT_MS / 1000}s${stderrOutput ? `: ${stderrOutput}` : ''}` };
346
+ }
347
+
348
+ let response;
349
+ try {
350
+ response = await axios.post(
351
+ `http://localhost:${SMOKE_TEST_HTTP_PORT}/invoke`,
352
+ { mission: args.mission || 'smoke-test', input: args.input || {} },
353
+ { timeout: 30_000, validateStatus: () => true },
354
+ );
355
+ } catch (error) {
356
+ return { skipped: false, success: false, error: error.message };
357
+ }
358
+
359
+ if (!response.data?.success) {
360
+ return { skipped: false, success: false, error: response.data?.error || `HTTP ${response.status}` };
361
+ }
362
+ const result = response.data.result;
363
+ if (result && typeof result === 'object' && 'status' in result && result.status !== 'success') {
364
+ return { skipped: false, success: false, error: result.message || `Plugin returned status: ${result.status}` };
365
+ }
366
+ return { skipped: false, success: true };
367
+ } finally {
368
+ child.kill('SIGTERM');
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Calls the real AI code generator (POST /code/generate - CodeHandler.generateCode on the
374
+ * frontend, same endpoint the browser CodeEditor uses). That endpoint's default output already
375
+ * targets `main(mission, input, ctx)` + `ctx.sdk.*` + `PluginResponse` - the same conventions this
376
+ * Docker-runtime SDK uses - so the prompt below is reinforcement, not an override.
377
+ */
378
+ /** Groups tsc error lines ("file(line,col): error TSxxxx: ...") by the file path they were
379
+ * reported against - used by generateProjectWithSelfCorrection to know which of a multi-file
380
+ * project's files to send back for a surgical fix. */
381
+ export function groupCompilerErrorsByFile(errors, knownPaths) {
382
+ const byFile = new Map();
383
+ for (const line of errors) {
384
+ const match = line.match(/^([^(]+)\(\d+,\d+\)/);
385
+ const filePath = match && knownPaths.has(match[1]) ? match[1] : undefined;
386
+ if (!filePath) continue;
387
+ if (!byFile.has(filePath)) byFile.set(filePath, []);
388
+ byFile.get(filePath).push(line);
389
+ }
390
+ return byFile;
391
+ }
392
+
393
+ /**
394
+ * Writes every file from `/code/generate-project`'s response, then runs a bounded self-correction
395
+ * loop generalized to N files: `typeCheckHandler` already type-checks the whole project (via
396
+ * tsconfig.json) regardless of file count, so this just needs to attribute errors back to the
397
+ * right file (groupCompilerErrorsByFile) and fix each one via a surgical `/code/generate` call
398
+ * (existingContent + target_file triggers the backend's surgical-edit path - the same mechanism
399
+ * `plugin convert`'s action="update" files use).
400
+ */
401
+ export async function generateProjectWithSelfCorrection(serverUrl, apiKey, currentDir, files, options) {
402
+ for (const [relPath, content] of Object.entries(files)) {
403
+ const fullPath = path.join(currentDir, ...relPath.split('/'));
404
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
405
+ fs.writeFileSync(fullPath, content);
406
+ }
407
+
408
+ const knownPaths = new Set(Object.keys(files));
409
+ for (let attempt = 0; attempt <= CODEGEN_MAX_FIX_ATTEMPTS; attempt++) {
410
+ const check = await withSpinner(attempt === 0 ? '🔎 Type-checking' : `🔧 Re-checking (attempt ${attempt}/${CODEGEN_MAX_FIX_ATTEMPTS})`, () => typeCheckHandler(currentDir));
411
+ if (check.skipped) {
412
+ console.log(chalk.gray(' (skipped type-check - run `npm install` first for the self-correction loop to catch compiler errors)'));
413
+ return files;
414
+ }
415
+ if (check.errors.length === 0) {
416
+ if (attempt > 0) console.log(chalk.green(`✅ Fixed - clean type-check after ${attempt} attempt(s)`));
417
+ return files;
418
+ }
419
+
420
+ const byFile = groupCompilerErrorsByFile(check.errors, knownPaths);
421
+ if (attempt === CODEGEN_MAX_FIX_ATTEMPTS || byFile.size === 0) {
422
+ console.log(chalk.yellow(`⚠️ ${check.errors.length} compiler error(s) remain${attempt > 0 ? ` after ${attempt} fix attempt(s)` : ''} - review manually:`));
423
+ check.errors.forEach((line) => console.log(chalk.gray(` ${line}`)));
424
+ return files;
425
+ }
426
+
427
+ console.log(chalk.yellow(`⚠️ ${check.errors.length} compiler error(s) across ${byFile.size} file(s) - asking the AI to fix...`));
428
+ for (const [relPath, errors] of byFile) {
429
+ const fullPath = path.join(currentDir, ...relPath.split('/'));
430
+ const result = await withSpinner(` fixing ${relPath}`, () =>
431
+ requestCodeGeneration(serverUrl, apiKey, {
432
+ logic: `Fix these compiler errors:\n${errors.join('\n')}`,
433
+ target_file: relPath,
434
+ workspace_files: { [relPath]: files[relPath] },
435
+ model: options.model,
436
+ provider: options.provider,
437
+ }),
438
+ );
439
+ files[relPath] = result.code;
440
+ fs.writeFileSync(fullPath, result.code);
441
+ }
442
+ }
443
+ return files;
444
+ }
445
+
446
+ /**
447
+ * `aivin plugin make` - complexity-adaptive since the backend now classifies the task first
448
+ * (see CodeEditorService.genFreshProject/CodeGenerationHelper.planFreshProject): a simple/moderate
449
+ * requirement still costs exactly one generation call and writes exactly src/main.ts, same as
450
+ * always; a genuinely complex one gets planned into a small multi-file project and a matching
451
+ * multi-entry manifest, instead of everything being crammed into one flat main().
452
+ */
453
+ export async function makePluginFromDescription(description, options = {}) {
454
+ const currentDir = process.cwd();
455
+ const manifestPath = path.join(currentDir, 'manifest.json');
456
+
457
+ if (!fs.existsSync(manifestPath)) {
458
+ throw new Error('manifest.json not found. Run `aivin create` first.');
459
+ }
460
+
461
+ // A project created by `aivin init` has src/service.ts (business logic) + a static src/main.ts
462
+ // wrapper - regenerating here should target service.ts too, or it'd overwrite that clean split
463
+ // with a single self-contained main.ts, silently undoing it.
464
+ if (fs.existsSync(path.join(currentDir, 'src', 'service.ts'))) {
465
+ console.log(chalk.gray('src/service.ts found - regenerating business logic there (main.ts wrapper unchanged).'));
466
+ await withSpinner('🤖 Generating business logic (src/service.ts)', () => generateServiceAndWrapper(currentDir, description, options));
467
+ console.log(chalk.green('✅ src/service.ts regenerated'));
468
+ console.log(chalk.cyan('\n🔧 Next steps:'));
469
+ console.log(' aivin start # test locally');
470
+ console.log(' aivin test # deploy to a test instance');
471
+ return;
472
+ }
473
+
474
+ const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
475
+ const apiKey = process.env.API_KEY;
476
+ if (!apiKey) {
477
+ console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
478
+ }
479
+
480
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
481
+ const entry = primaryManifestEntry(manifest);
482
+
483
+ let response;
484
+ try {
485
+ response = await withSpinner('🤖 Generating plugin', () =>
486
+ axios.post(
487
+ `${serverUrl}/code/generate-project`,
488
+ { logic: description, code_id: entry.id, model: options.model, provider: options.provider },
489
+ { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey || 'dev-token'}` } },
490
+ ),
491
+ );
492
+ } catch (error) {
493
+ const message = error.response?.data?.message || error.message;
494
+ throw new Error(`Code generation failed: ${message}`, { cause: error });
495
+ }
496
+
497
+ const { files, manifest: manifestFragment, plan } = response.data ?? {};
498
+ if (!files || Object.keys(files).length === 0) {
499
+ throw new Error('Aivin server did not return any generated files.');
500
+ }
501
+ if (plan?.multi_entry) {
502
+ console.log(chalk.blue(`🔎 ${plan.reasoning || 'Multiple independent capabilities detected'}`));
503
+ }
504
+
505
+ const finalFiles = await generateProjectWithSelfCorrection(serverUrl, apiKey, currentDir, files, options);
506
+ const fileList = Object.keys(finalFiles);
507
+ console.log(chalk.green(`✅ ${fileList.length} file(s) generated`), fileList.length > 1 ? chalk.gray(`(${fileList.join(', ')})`) : '');
508
+
509
+ if (manifestFragment?.plugins?.length) {
510
+ // multi_entry: backend planned 2+ independent capabilities - replace plugins[] with them.
511
+ // Fresh ids assigned locally - the server never allocates plugin ids, only `aivin deploy` does.
512
+ manifest.plugins = manifestFragment.plugins.map((p) => ({ id: randomBytes(16).toString('hex'), input: {}, initial: {}, ...p }));
513
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
514
+ console.log(chalk.green(`✅ manifest.json split into ${manifest.plugins.length} plugin entries`));
515
+ } else if (manifestFragment) {
516
+ applyGeneratedManifestFields(manifestPath, manifest, manifestFragment);
517
+ }
518
+
519
+ console.log(chalk.cyan('\n🔧 Next steps:'));
520
+ console.log(' aivin start # test locally');
521
+ console.log(' aivin test # deploy to a test instance');
522
+ }
523
+
524
+ /** Shared by `plugin make`/`plugin convert` - fills in whatever manifest fields the AI inferred
525
+ * alongside the code, but only ones you haven't already set yourself. Entry-level fields are
526
+ * patched on the primary plugins[] entry for the default manifest shape (see
527
+ * `primaryManifestEntry`), flat fields for the legacy single-object shape. */
528
+ export function applyGeneratedManifestFields(manifestPath, manifest, result) {
529
+ const entry = primaryManifestEntry(manifest);
530
+ let manifestChanged = false;
531
+ if (result.description && !entry.description) {
532
+ entry.description = result.description;
533
+ manifestChanged = true;
534
+ }
535
+ const instructions = result.instructions || result.instruction;
536
+ if (instructions && !entry.instructions) {
537
+ entry.instructions = instructions;
538
+ manifestChanged = true;
539
+ }
540
+ const inputSchema = result.input || result.input_schema;
541
+ if (inputSchema && (!entry.input || Object.keys(entry.input).length === 0)) {
542
+ entry.input = inputSchema;
543
+ manifestChanged = true;
544
+ }
545
+ if (manifestChanged) {
546
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
547
+ console.log(chalk.green('✅ manifest.json enriched from generated result'));
548
+ }
549
+ }
550
+
551
+ // Same dirs/files `aivin deploy` already ignores, plus lockfiles and binary-ish assets that are
552
+ // never worth reading as source. Only used to keep the TREE clean - actual file CONTENT is never
553
+ // read here; the backend requests specific paths back on demand (see runProjectToolServer).
554
+ export const CONVERT_EXCLUDE_DIRS = [...DEPLOY_EXCLUDE_DIRS, 'coverage', '.next', '.cache', '.vscode', '.idea'];
555
+
556
+ export const CONVERT_EXCLUDE_FILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', '.gitignore'];
557
+
558
+ export const CONVERT_BINARY_EXT = /\.(png|jpe?g|gif|webp|ico|svg|woff2?|ttf|eot|zip|tar|gz|pdf|mp4|mp3|wasm|node)$/i;
559
+
560
+ export const CONVERT_MAX_TREE_ENTRIES = 5000; // matches the backend's own cap (assertSafeProjectTree)
561
+
562
+ /**
563
+ * Builds the directory tree `plugin convert` uploads - paths + byte sizes ONLY, never content.
564
+ * Keeps the initial request cheap regardless of project size (previously this walked the whole
565
+ * project reading every file's content up front - wasteful and doesn't scale to a large/heavy
566
+ * project). The backend's ProjectConversionService scans this tree and asks for specific files
567
+ * back one at a time via `code:tool_call` (see runProjectToolServer below) as its own plan loop
568
+ * decides it actually needs them.
569
+ */
570
+ export function buildProjectTree(dir, basePath = '', entries = []) {
571
+ const items = fs.readdirSync(dir);
572
+ for (const item of items) {
573
+ if (entries.length >= CONVERT_MAX_TREE_ENTRIES) break;
574
+ const fullPath = path.join(dir, item);
575
+ const relativePath = path.join(basePath, item).split(path.sep).join('/');
576
+ const stat = fs.statSync(fullPath);
577
+ if (stat.isDirectory()) {
578
+ if (!CONVERT_EXCLUDE_DIRS.includes(item)) buildProjectTree(fullPath, relativePath, entries);
579
+ } else if (!CONVERT_EXCLUDE_FILES.includes(item) && !isEnvFile(item) && !CONVERT_BINARY_EXT.test(item)) {
580
+ entries.push({ path: relativePath, size: stat.size });
581
+ }
582
+ }
583
+ return entries;
584
+ }
585
+
586
+ /** Resolves a backend-requested relative path against the real project directory, rejecting
587
+ * anything that would escape it. This is the actual security boundary for the tool-call relay -
588
+ * the backend validates paths too (assertSafeProjectPath), but this process is the one holding
589
+ * the real filesystem, so this check is the one that actually matters. */
590
+ export function resolveProjectPath(currentDir, requestedPath) {
591
+ if (typeof requestedPath !== 'string' || !requestedPath) throw new Error('Invalid path');
592
+ const resolved = path.resolve(currentDir, requestedPath);
593
+ const rootWithSep = currentDir.endsWith(path.sep) ? currentDir : currentDir + path.sep;
594
+ if (resolved !== currentDir && !resolved.startsWith(rootWithSep)) {
595
+ throw new Error(`Path escapes project directory: ${requestedPath}`);
596
+ }
597
+ return resolved;
598
+ }
599
+
600
+ /** Best-effort `git status --porcelain -- <path>` for one file - execFileSync (argv array, no
601
+ * shell) rather than execSync, since `path` came from the backend's AI-generated plan and could
602
+ * contain characters that would be unsafe to interpolate into a shell string. Returns null (not
603
+ * an error) when the directory isn't a git repo, `git` isn't installed, or the file is clean -
604
+ * this is a confirmation hint, never a hard requirement. */
605
+ export function describeGitStatus(currentDir, relPath) {
606
+ try {
607
+ const output = execFileSync('git', ['status', '--porcelain', '--', relPath], { cwd: currentDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
608
+ const line = output.split('\n').find((l) => l.trim());
609
+ if (!line) return null;
610
+ const code = line.slice(0, 2).trim();
611
+ return code === '??' ? 'untracked' : 'has uncommitted changes';
612
+ } catch {
613
+ return null;
614
+ }
615
+ }
616
+
617
+ /** Warns (and, in an interactive terminal, asks to confirm) before a conversion that may overwrite
618
+ * existing files starts, if the project has uncommitted changes - conversion can pick actual
619
+ * existing files as action="update" targets, and there's no undo once create_file writes over
620
+ * one. Never blocks a non-git directory or non-interactive (CI/script) use - just informs. */
621
+ export async function warnIfGitDirty(currentDir) {
622
+ let statusOutput;
623
+ try {
624
+ statusOutput = execFileSync('git', ['status', '--porcelain'], { cwd: currentDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
625
+ } catch {
626
+ return; // not a git repo (or git missing) - nothing to warn about
627
+ }
628
+ const dirtyCount = statusOutput.split('\n').filter((l) => l.trim()).length;
629
+ if (dirtyCount === 0) return;
630
+ console.log(chalk.yellow(`⚠️ ${dirtyCount} uncommitted change(s) in this repo - conversion may update existing files based on what it reads.`));
631
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return; // can't prompt - warning above is all we can do
632
+ const { proceed } = await inquirer.prompt([{ type: 'confirm', name: 'proceed', message: 'Continue anyway?', default: false }]);
633
+ if (!proceed) throw new Error('Cancelled - commit or stash your changes first, then re-run.');
634
+ }
635
+
636
+ /** Executes one `code:tool_call` the backend sent during project conversion, against the real
637
+ * project directory on disk. See CodeDTO.ts's ProjectTool on the backend for the full contract. */
638
+ export async function executeProjectTool(currentDir, tool, args) {
639
+ switch (tool) {
640
+ case 'read_file': {
641
+ const filePath = resolveProjectPath(currentDir, args.path);
642
+ if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
643
+ throw new Error(`File not found: ${args.path}`);
644
+ }
645
+ return fs.readFileSync(filePath, 'utf8');
646
+ }
647
+ case 'grep': {
648
+ const regex = new RegExp(args.pattern, 'i');
649
+ const matches = [];
650
+ const walk = (dir, base = '') => {
651
+ for (const item of fs.readdirSync(dir)) {
652
+ if (matches.length >= 20) return;
653
+ const fullPath = path.join(dir, item);
654
+ const rel = path.join(base, item).split(path.sep).join('/');
655
+ const stat = fs.statSync(fullPath);
656
+ if (stat.isDirectory()) {
657
+ if (!CONVERT_EXCLUDE_DIRS.includes(item)) walk(fullPath, rel);
658
+ } else if (!CONVERT_BINARY_EXT.test(item) && stat.size > 0 && stat.size <= 200_000) {
659
+ if (regex.test(fs.readFileSync(fullPath, 'utf8'))) matches.push(rel);
660
+ }
661
+ }
662
+ };
663
+ walk(currentDir);
664
+ return matches;
665
+ }
666
+ case 'confirm_update': {
667
+ const filePath = resolveProjectPath(currentDir, args.path);
668
+ if (!fs.existsSync(filePath)) return { approved: true }; // nothing there to overwrite
669
+ const gitHint = describeGitStatus(currentDir, args.path);
670
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
671
+ // Non-interactive (CI/script) - can't prompt, so proceed but make the decision visible.
672
+ console.log(chalk.yellow(`⚠️ Non-interactive - overwriting existing file ${args.path}${gitHint ? ` (${gitHint})` : ''} without confirmation`));
673
+ return { approved: true };
674
+ }
675
+ const { approved } = await inquirer.prompt([
676
+ {
677
+ type: 'confirm',
678
+ name: 'approved',
679
+ message: `Overwrite existing file ${args.path}${gitHint ? ` (${gitHint})` : ''}?`,
680
+ default: false,
681
+ },
682
+ ]);
683
+ return { approved };
684
+ }
685
+ case 'create_file': {
686
+ const filePath = resolveProjectPath(currentDir, args.path);
687
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
688
+ fs.writeFileSync(filePath, args.content ?? '');
689
+ return { written: true };
690
+ }
691
+ case 'run_typecheck':
692
+ return await typeCheckHandler(currentDir);
693
+ case 'run_smoke_test':
694
+ return await runSmokeTestHandler(currentDir, args);
695
+ default:
696
+ throw new Error(`Unknown tool: ${tool}`);
697
+ }
698
+ }
699
+
700
+ /** Wires the socket side of the tool-call relay: joins the conversion's room, executes every
701
+ * `code:tool_call` the backend sends against the real project directory, replies with
702
+ * `code:tool_result`, and prints every `code:progress` event live so a loop that can take a
703
+ * while (scan → plan → generate → verify, possibly several files) doesn't look hung. */
704
+ export async function connectProjectToolServer(serverUrl, apiKey, codeId, currentDir) {
705
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true });
706
+
707
+ try {
708
+ await new Promise((resolve, reject) => {
709
+ socket.on('connect_error', (error) => reject(new Error(`Connection failed: ${error.message}`)));
710
+ socket.on('connect', () => {
711
+ socket.emit('code:join', { code_id: codeId }, (ack) => {
712
+ if (!ack?.success) reject(new Error(`Couldn't join conversion session: ${ack?.error || 'unknown error'}`));
713
+ else resolve();
714
+ });
715
+ });
716
+ });
717
+ } catch (error) {
718
+ // `reconnection: true` means a socket left connected-but-erroring here would keep retrying in
719
+ // the background forever - the caller never gets a `socket` reference back to clean it up since
720
+ // this function is what throws instead of returning one.
721
+ socket.disconnect();
722
+ throw error;
723
+ }
724
+
725
+ socket.on('code:tool_call', async (payload) => {
726
+ const { call_id, tool, args } = payload || {};
727
+ try {
728
+ const result = await executeProjectTool(currentDir, tool, args || {});
729
+ socket.emit('code:tool_result', { call_id, code_id: codeId, ok: true, result });
730
+ } catch (error) {
731
+ socket.emit('code:tool_result', { call_id, code_id: codeId, ok: false, error: error.message });
732
+ }
733
+ });
734
+
735
+ socket.on('code:progress', (payload) => {
736
+ console.log(chalk.gray(`[${new Date().toLocaleTimeString()}]`), payload?.message || '');
737
+ if (Array.isArray(payload?.errors)) payload.errors.forEach((e) => console.log(chalk.red(' '), e));
738
+ });
739
+
740
+ return socket;
741
+ }
742
+
743
+ /**
744
+ * `aivin plugin convert` - hands the existing project in the current directory to the backend's
745
+ * ProjectConversionService instead of generating locally: uploads only the directory tree (paths
746
+ * + sizes, never content), then answers `read_file`/`grep`/`create_file`/`run_typecheck` tool
747
+ * calls against the real project on disk as the backend's own scan → plan → generate → verify
748
+ * loop asks for them. The backend decides single-vs-multi-function and create-vs-update per file
749
+ * (see PLAN_PROJECT_INSTRUCTION on the backend) - this command no longer guesses that locally.
750
+ */
751
+ export async function convertExistingProject(hint, options = {}) {
752
+ const currentDir = process.cwd();
753
+ const manifestPath = path.join(currentDir, 'manifest.json');
754
+ const handlerPath = path.join(currentDir, 'src', 'main.ts');
755
+
756
+ await warnIfGitDirty(currentDir);
757
+
758
+ // --force re-runs the full scan/plan/generate/verify loop even if a previous `plugin convert`
759
+ // already wrote src/main.ts - for when that result turned out wrong, stale, or the project
760
+ // changed since. src/main.ts isn't special-cased out of the tree, so the backend's plan is free
761
+ // to mark it action="update"; the usual confirm_update prompt still gates actually overwriting it.
762
+ if (fs.existsSync(handlerPath) && !options.force) {
763
+ throw new Error(
764
+ 'src/main.ts already exists - `plugin convert` is for a project that isn\'t an Aivin plugin yet. ' +
765
+ 'Pass --force to re-run conversion anyway (e.g. the previous result was wrong or the project changed).',
766
+ );
767
+ }
768
+
769
+ let manifest;
770
+ let codeId;
771
+ if (fs.existsSync(manifestPath)) {
772
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
773
+ codeId = primaryManifestEntry(manifest)?.id || randomBytes(16).toString('hex');
774
+ } else {
775
+ // No `aivin create` needed first - infer a starting manifest from package.json (or the
776
+ // directory name) so there's less setup between "I have a project" and "it's a plugin".
777
+ let pkg = null;
778
+ const pkgPath = path.join(currentDir, 'package.json');
779
+ if (fs.existsSync(pkgPath)) {
780
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch { /* not JSON we can use */ }
781
+ }
782
+ const name = (pkg?.name || path.basename(currentDir)).replace('@aivin/plugin-', '').toLowerCase().replace(/[^a-z0-9-]/g, '-');
783
+ codeId = randomBytes(16).toString('hex');
784
+ // Same default plugins[] shape `aivin create`/`aivin init` scaffold - see createManifest.
785
+ manifest = {
786
+ version: '1.0.0',
787
+ author: '',
788
+ email: '',
789
+ plugins: [{ id: codeId, name, description: pkg?.description || '', func: 'main', input: {}, initial: {} }],
790
+ };
791
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
792
+ console.log(chalk.green('✅ manifest.json created'), chalk.gray(`(name: ${name})`));
793
+ }
794
+
795
+ const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
796
+ const apiKey = process.env.API_KEY;
797
+ if (!apiKey) {
798
+ console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
799
+ }
800
+
801
+ console.log(chalk.blue('📂 Scanning project tree...'));
802
+ const tree = buildProjectTree(currentDir);
803
+ if (tree.length === 0) {
804
+ throw new Error('No source files found in the current directory.');
805
+ }
806
+ console.log(chalk.gray(` ${tree.length} file(s) in tree (content read on demand by the server, never uploaded up front)`));
807
+
808
+ const socket = await connectProjectToolServer(serverUrl, apiKey, codeId, currentDir);
809
+
810
+ console.log(chalk.blue('🤖 Converting - this loops (scan → plan → generate → verify), watch for progress below...\n'));
811
+ let response;
812
+ try {
813
+ response = await axios.post(
814
+ `${serverUrl}/code/convert-project`,
815
+ {
816
+ logic: hint || 'Convert the project in the current directory into an Aivin plugin.',
817
+ code_id: codeId,
818
+ hint,
819
+ tree,
820
+ model: options.model,
821
+ provider: options.provider,
822
+ },
823
+ {
824
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey || 'dev-token'}` },
825
+ timeout: 600_000, // a real multi-file scan/plan/generate/verify loop can take several minutes
826
+ },
827
+ );
828
+ } catch (error) {
829
+ const message = error.response?.data?.message || error.message;
830
+ throw new Error(`Project conversion failed: ${message}`, { cause: error });
831
+ } finally {
832
+ socket.disconnect();
833
+ }
834
+
835
+ const { plan, manifest: manifestFragment, verification } = response.data ?? {};
836
+
837
+ if (manifestFragment?.plugins?.length) {
838
+ // Backend planned 2+ independent capabilities (multi_entry) - replace plugins[] with them.
839
+ // Fresh ids assigned locally - the server never allocates plugin ids, only `aivin deploy` does.
840
+ manifest.plugins = manifestFragment.plugins.map((p) => ({ id: randomBytes(16).toString('hex'), input: {}, initial: {}, ...p }));
841
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
842
+ console.log(chalk.green(`✅ manifest.json split into ${manifest.plugins.length} plugin entries`));
843
+ }
844
+
845
+ const isJsTsSource = !plan?.source_language || /^(type|java)script$/i.test(plan.source_language);
846
+ const languageNote = isJsTsSource ? '' : `, ported from ${plan.source_language}`;
847
+ console.log(chalk.green(`\n✅ Conversion done`), chalk.gray(`(${plan?.project_kind || 'generic'}${languageNote}, ${plan?.files?.length ?? 0} file(s))`));
848
+ if (!isJsTsSource) {
849
+ console.log(chalk.yellow(`⚠️ Source was ${plan.source_language}, not TypeScript - this is a translated port, not a mechanical conversion. Review generated logic especially carefully, and check for "limitation" comments left where no direct npm equivalent existed.`));
850
+ }
851
+ if (verification && !verification.success) {
852
+ console.log(chalk.yellow(`⚠️ ${verification.ran ? 'Type-check still finds issues after auto-fix attempts' : 'Verification was skipped'} - review before deploying.`));
853
+ }
854
+ console.log(chalk.yellow('\n⚠️ Review the generated code before relying on it - it\'s a strong starting point, not a guarantee.'));
855
+ console.log(chalk.cyan('\n🔧 Next steps:'));
856
+ console.log(' aivin start # test locally');
857
+ console.log(' aivin test # deploy to a test instance');
858
+ }