@aivin-labs/cli 1.0.4 → 1.0.5

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.
package/bin/cli.mjs CHANGED
@@ -23,9 +23,9 @@ import { readStdin, createFromJSON, createInteractive, validatePluginConfig, val
23
23
  import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
24
24
  import { initInteractive, makePluginFromDescription, convertExistingProject } from './lib/codegen.mjs';
25
25
  import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
26
- import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors } from './lib/connectors.mjs';
26
+ import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors, buildRegisterConnectorDto } from './lib/connectors.mjs';
27
27
  import { attachStore, createStore, deleteStore, detachStore, listStores, removeNode, setStoreEnabled } from './lib/store.mjs';
28
- import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches } from './lib/mcpProxy.mjs';
28
+ import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches, setFieldConnector } from './lib/mcpProxy.mjs';
29
29
  import {
30
30
  saveGlobalApiKey,
31
31
  browserLogin,
@@ -58,6 +58,7 @@ import {
58
58
  updateTaskById,
59
59
  deleteTaskById,
60
60
  createTask,
61
+ buildCreateTaskPayload,
61
62
  pickWorkspaceAndProject,
62
63
  createProjectCmd,
63
64
  updateProjectCmd,
@@ -393,10 +394,11 @@ pluginCommand
393
394
  .command('ask [mission]')
394
395
  .description('One-shot: search for the best-matching plugin for a plain-language mission and trigger it right away, like an agent would')
395
396
  .option('--top <n>', 'How many candidates to consider/print as runner-up context (default 5) - only the top match is ever run')
396
- .option('-i, --input <json>', 'Force specific fields (as JSON) alongside the auto-mapped ones - explicit fields win')
397
+ .option('-i, --input <json>', 'Input fields as a JSON string - skips the interactive field-by-field prompt')
397
398
  .option('--workspace <id>', 'Workspace id to search/run against (default: auto-picks your first one)')
398
399
  .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
399
400
  .option('--watch-logs', "Also stream the chosen plugin's own live console output inline")
401
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
400
402
  .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
401
403
  .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
402
404
  .action(async (mission, options) => {
@@ -441,12 +443,12 @@ pluginCommand
441
443
  pluginCommand
442
444
  .command('trigger [mission] [input]')
443
445
  .description('Invoke this deployed plugin for real and print the result - like the platform\'s Playground')
444
- .option('-a, --auto <prompt>', 'Natural-language prompt - the platform auto-maps it onto the input schema for you')
445
446
  .option('--id <pluginId>', 'Plugin id to trigger directly - skips the local manifest.json lookup (e.g. for `aivin mcp` plugins, which have no local project directory)')
446
447
  .option('--func <name>', 'Which function to trigger, for a multi-function plugin (matches name/func/id) - ignored when --id is given')
447
448
  .option('--workspace <id>', 'Workspace id to run against (default: auto-picks your first one)')
448
449
  .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
449
450
  .option('--watch-logs', 'Also stream the plugin\'s own live console output inline (same feed as `aivin plugin logs`) instead of needing a second terminal - requires permission to view that plugin\'s logs (your own/org\'s deployments; most store plugins from other orgs will just skip this and fall back to the REST result only)')
451
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
450
452
  .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
451
453
  .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
452
454
  .action(async (mission, input, options) => {
@@ -681,6 +683,7 @@ mcpCommand
681
683
  .option('--private', 'Deploy to your org only - default')
682
684
  .option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
683
685
  .option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
686
+ .option('-y, --yes', 'Skip the deploy confirmation prompt (required in non-TTY/CI contexts, which otherwise now refuse to deploy at all - see scanAndPublishMcp)')
684
687
  .action(async (url, options) => {
685
688
  try {
686
689
  url = await requireArg(url, {
@@ -1085,10 +1088,11 @@ taskCommand
1085
1088
  taskCommand
1086
1089
  .command('delete [id]')
1087
1090
  .description('Delete a task')
1088
- .action(async (id) => {
1091
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1092
+ .action(async (id, options) => {
1089
1093
  try {
1090
1094
  id = await requireArg(id, { prompt: 'Task id to delete:', usage: 'Usage: aivin task delete <id>' });
1091
- await deleteTaskById(id);
1095
+ await deleteTaskById(id, options);
1092
1096
  } catch (error) {
1093
1097
  console.error(chalk.red('❌'), error.message);
1094
1098
  process.exit(1);
@@ -1326,6 +1330,7 @@ projectCommand
1326
1330
  .command('delete [id]')
1327
1331
  .description('Delete a project')
1328
1332
  .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1333
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1329
1334
  .action(async (id, options) => {
1330
1335
  try {
1331
1336
  id = await requireArg(id, { prompt: 'Project id to delete:', usage: 'Usage: aivin project delete <id>' });
@@ -1336,7 +1341,7 @@ projectCommand
1336
1341
  }
1337
1342
  });
1338
1343
 
1339
- export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName };
1344
+ export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, setFieldConnector, buildRegisterConnectorDto, buildCreateTaskPayload };
1340
1345
 
1341
1346
  // Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
1342
1347
  // not when this module is imported (e.g. by tests) - otherwise Commander
@@ -75,6 +75,12 @@ function MissionTuiApp({ serverUrl, apiKey, threadId, tenantClient, idleTimeoutM
75
75
  appendLine(`⚠️ Không theo dõi được tiến độ trực tiếp (${error.message}) - mission vẫn tiếp tục.`, 'yellow');
76
76
  settle('connect_error');
77
77
  });
78
+ // ✅ FIX: chưa có listener 'error' nào ở đây - socket.io lỗi phía server (khác connect_error)
79
+ // trước đây sẽ throw và crash cả tiến trình CLI thay vì chỉ dừng theo dõi như connect_error.
80
+ socket.on('error', (error) => {
81
+ appendLine(`⚠️ Lỗi luồng tiến độ (${error?.message || error}) - mission vẫn tiếp tục.`, 'yellow');
82
+ settle('connect_error');
83
+ });
78
84
 
79
85
  // Học đúng sessionKey (clientId) của phiên HIL hiện tại - browser:cast-start bắn vào room
80
86
  // `client:<tenant>` (auto-join, cùng room browser:agent-step dùng - xem comment tại nơi emit
@@ -573,11 +573,18 @@ export function buildProjectTree(dir, basePath = '', entries = []) {
573
573
  if (entries.length >= CONVERT_MAX_TREE_ENTRIES) break;
574
574
  const fullPath = path.join(dir, item);
575
575
  const relativePath = path.join(basePath, item).split(path.sep).join('/');
576
- const stat = fs.statSync(fullPath);
577
- if (stat.isDirectory()) {
576
+ // lstat (not stat) so a symlink is never followed here - stat() would happily report a
577
+ // symlink-to-directory as isDirectory()==true and recurse into it, walking (and later, via
578
+ // resolveProjectPath/executeProjectTool, reading) whatever it actually points to outside the
579
+ // project (e.g. a symlink committed into a project pulled from an untrusted source pointing at
580
+ // ~/.ssh or ~/.aivin/credentials). Silently skipping is fine - a real project source file is
581
+ // never a symlink.
582
+ const lstat = fs.lstatSync(fullPath);
583
+ if (lstat.isSymbolicLink()) continue;
584
+ if (lstat.isDirectory()) {
578
585
  if (!CONVERT_EXCLUDE_DIRS.includes(item)) buildProjectTree(fullPath, relativePath, entries);
579
586
  } else if (!CONVERT_EXCLUDE_FILES.includes(item) && !isEnvFile(item) && !CONVERT_BINARY_EXT.test(item)) {
580
- entries.push({ path: relativePath, size: stat.size });
587
+ entries.push({ path: relativePath, size: lstat.size });
581
588
  }
582
589
  }
583
590
  return entries;
@@ -586,7 +593,15 @@ export function buildProjectTree(dir, basePath = '', entries = []) {
586
593
  /** Resolves a backend-requested relative path against the real project directory, rejecting
587
594
  * anything that would escape it. This is the actual security boundary for the tool-call relay -
588
595
  * 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. */
596
+ * the real filesystem, so this check is the one that actually matters.
597
+ *
598
+ * ✅ FIX: the lexical `startsWith` check alone only catches `../`-style escapes - a symlink
599
+ * physically located INSIDE the project (e.g. `project/link -> ~/.ssh` or `-> C:\Users\<user>`)
600
+ * has a lexically-valid, in-bounds path while its *real* target is anywhere on disk. Re-resolving
601
+ * through `fs.realpathSync` after the lexical check catches that: read_file/create_file/
602
+ * confirm_update all funnel through here, so a backend-driven (or AI-hallucinated, or a
603
+ * compromised backend's) tool-call requesting a project-relative path that happens to traverse
604
+ * such a symlink can no longer read/write files outside the project undetected. */
590
605
  export function resolveProjectPath(currentDir, requestedPath) {
591
606
  if (typeof requestedPath !== 'string' || !requestedPath) throw new Error('Invalid path');
592
607
  const resolved = path.resolve(currentDir, requestedPath);
@@ -594,6 +609,20 @@ export function resolveProjectPath(currentDir, requestedPath) {
594
609
  if (resolved !== currentDir && !resolved.startsWith(rootWithSep)) {
595
610
  throw new Error(`Path escapes project directory: ${requestedPath}`);
596
611
  }
612
+ // Symlink re-check: skip if the path doesn't exist yet (e.g. create_file writing a brand new
613
+ // file/directory - nothing to resolve, and the write itself lands at `resolved` on disk, not
614
+ // through any symlink since none exists there yet).
615
+ let real;
616
+ try {
617
+ real = fs.realpathSync(resolved);
618
+ } catch {
619
+ return resolved;
620
+ }
621
+ const realRoot = fs.realpathSync(currentDir);
622
+ const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
623
+ if (real !== realRoot && !real.startsWith(realRootWithSep)) {
624
+ throw new Error(`Path escapes project directory (symlink): ${requestedPath}`);
625
+ }
597
626
  return resolved;
598
627
  }
599
628
 
@@ -652,7 +681,11 @@ export async function executeProjectTool(currentDir, tool, args) {
652
681
  if (matches.length >= 20) return;
653
682
  const fullPath = path.join(dir, item);
654
683
  const rel = path.join(base, item).split(path.sep).join('/');
655
- const stat = fs.statSync(fullPath);
684
+ // lstat, not stat - this walker never goes through resolveProjectPath, so it needs its
685
+ // own symlink guard (same reasoning as buildProjectTree above) to avoid grepping through
686
+ // a symlink out of the project.
687
+ const stat = fs.lstatSync(fullPath);
688
+ if (stat.isSymbolicLink()) continue;
656
689
  if (stat.isDirectory()) {
657
690
  if (!CONVERT_EXCLUDE_DIRS.includes(item)) walk(fullPath, rel);
658
691
  } else if (!CONVERT_BINARY_EXT.test(item) && stat.size > 0 && stat.size <= 200_000) {
@@ -722,6 +755,29 @@ export async function connectProjectToolServer(serverUrl, apiKey, codeId, curren
722
755
  throw error;
723
756
  }
724
757
 
758
+ // ✅ FIX: no 'error' listener registered at all after the initial connect - a server-side
759
+ // socket.io error later in the (potentially several-minute) scan/plan/generate/verify loop would
760
+ // crash the whole CLI process instead of just being visible as a log line.
761
+ socket.on('error', (error) => {
762
+ console.log(chalk.red(` Socket error: ${error?.message || error}`));
763
+ });
764
+
765
+ // ✅ FIX: `code:join` was only ever emitted once, before this promise resolved - `reconnection:
766
+ // true` means the client transparently reconnects on a network blip, but the server-side room
767
+ // membership from the original `code:join` is gone with the old connection. Without re-joining,
768
+ // the tool-call relay silently "dies" after a reconnect (no more code:tool_call/code:progress
769
+ // ever arrives) while the backend's own HTTP request just keeps waiting until its own timeout -
770
+ // no early warning to the user that anything went wrong.
771
+ socket.on('reconnect', () => {
772
+ socket.emit('code:join', { code_id: codeId }, (ack) => {
773
+ if (!ack?.success) {
774
+ console.log(chalk.yellow(`⚠️ Reconnected but couldn't rejoin conversion session: ${ack?.error || 'unknown error'} - tool calls may stop arriving.`));
775
+ } else {
776
+ console.log(chalk.gray(' (reconnected)'));
777
+ }
778
+ });
779
+ });
780
+
725
781
  socket.on('code:tool_call', async (payload) => {
726
782
  const { call_id, tool, args } = payload || {};
727
783
  try {
@@ -2,7 +2,7 @@ import chalk from 'chalk';
2
2
  import axios from 'axios';
3
3
  import inquirer from 'inquirer';
4
4
  import { trustBadge, browseResults } from './pluginTrigger.mjs';
5
- import { withSpinner } from './util.mjs';
5
+ import { withSpinner, DEFAULT_API_TIMEOUT_MS } from './util.mjs';
6
6
 
7
7
  // ── Connectors - reusable OAuth apps / credential-form namespaces plugins can reference ────────
8
8
 
@@ -11,7 +11,11 @@ export function connectorAuthHeaders() {
11
11
  if (!apiKey) {
12
12
  console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
13
13
  }
14
- return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
14
+ // ✅ FIX: no call site in this file set a `timeout` before - worst case was `registerConnector`,
15
+ // where a hang meant re-typing an entire OAuth client_secret from scratch after Ctrl+C. Setting it
16
+ // once here (this object is passed straight through as the axios config everywhere it's used)
17
+ // covers every call site.
18
+ return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` }, timeout: DEFAULT_API_TIMEOUT_MS };
15
19
  }
16
20
 
17
21
  export function connectorBaseUrl() {
@@ -34,12 +38,16 @@ export function formatConnectorDetail(connector) {
34
38
  lines.push(`${chalk.gray('type')} ${connector.type}`);
35
39
  lines.push(`${chalk.gray('visibility')} ${connector.visibility}${connector.store_status ? ` (${connector.store_status})` : ''}`);
36
40
  if (connector.description) lines.push(`\n${connector.description}`);
37
- if (connector.type === 'oauth' && connector.oauth) {
38
- lines.push(`\n${chalk.gray('authorize_url')} ${connector.oauth.authorize_url}`);
39
- lines.push(`${chalk.gray('access_url')} ${connector.oauth.access_url}`);
40
- if (connector.oauth.scopes?.length) lines.push(`${chalk.gray('scopes')} ${connector.oauth.scopes.join(', ')}`);
41
- } else if (connector.type === 'credential_form' && connector.fields?.length) {
42
- lines.push(`\n${chalk.gray('fields')}\n${connector.fields.map(f => ` - ${f.name}${f.required ? ' (required)' : ''}${f.label ? `: ${f.label}` : ''}`).join('\n')}`);
41
+ // Backend's ConnectorManifest nests OAuth/form details under `config` (discriminated by `type`) -
42
+ // not top-level `oauth`/`fields` (see ConnectorDTO.ts's RegisterConnectorDto/ConnectorManifest and
43
+ // ConnectorService.sanitize, which keeps `config` intact). Reading the wrong path here used to
44
+ // print an empty detail section for every connector regardless of what it actually holds.
45
+ if (connector.type === 'oauth' && connector.config) {
46
+ lines.push(`\n${chalk.gray('authorize_url')} ${connector.config.authorize_url}`);
47
+ lines.push(`${chalk.gray('access_url')} ${connector.config.access_url}`);
48
+ if (connector.config.scopes?.length) lines.push(`${chalk.gray('scopes')} ${connector.config.scopes.join(', ')}`);
49
+ } else if (connector.type === 'credential_form' && connector.config?.fields?.length) {
50
+ lines.push(`\n${chalk.gray('fields')}\n${connector.config.fields.map(f => ` - ${f.name}${f.required ? ' (required)' : ''}${f.label ? `: ${f.label}` : ''}`).join('\n')}`);
43
51
  }
44
52
  lines.push(chalk.gray(`\nReference it from a plugin manifest's connection_id: "${connector.id}"`));
45
53
  return lines.join('\n');
@@ -109,6 +117,40 @@ export async function listConnectors(options) {
109
117
  }
110
118
  }
111
119
 
120
+ /**
121
+ * Pure assembly of the request body `POST /connectors/register` expects, split out of
122
+ * registerConnector() so it's unit-testable without stubbing inquirer prompts - this exact
123
+ * assembly (nesting under `config`, not top-level `oauth`/`fields`) is what drifted from the
124
+ * backend's actual RegisterConnectorDto before and broke every registration; a regression test
125
+ * pins the shape down going forward. `oauthAnswers`/`fields` are already-collected inquirer
126
+ * answers, not prompted here.
127
+ */
128
+ export function buildRegisterConnectorDto(base, { oauthAnswers, fields } = {}) {
129
+ const dto = { id: base.id, name: base.name, description: base.description || undefined, image: base.image || undefined, type: base.type, visibility: base.visibility };
130
+
131
+ // ⚠ Backend's RegisterConnectorDto expects these nested under `config` (discriminated by `type` -
132
+ // see ConnectorDTO.ts / ConnectorService.register, which reads `dto.config.authorize_url` /
133
+ // `dto.config.fields`, never a top-level `dto.oauth`/`dto.fields`). This used to send them
134
+ // top-level, which the backend's `config` field (now validated with `@IsObject()`, previously
135
+ // silently stripped by the global whitelist ValidationPipe for having no class-validator
136
+ // decorators at all) would see as missing/wrong-shaped - registration failed every time regardless
137
+ // of what was typed here.
138
+ if (base.type === 'oauth') {
139
+ dto.config = {
140
+ authorize_url: oauthAnswers.authorize_url,
141
+ access_url: oauthAnswers.access_url,
142
+ profile_url: oauthAnswers.profile_url || undefined,
143
+ client_id: oauthAnswers.client_id,
144
+ client_secret: oauthAnswers.client_secret,
145
+ scopes: oauthAnswers.scopes ? oauthAnswers.scopes.split(',').map((s) => s.trim()).filter(Boolean) : [],
146
+ };
147
+ } else {
148
+ if (!fields || fields.length === 0) throw new Error('credential_form connectors need at least one field');
149
+ dto.config = { fields };
150
+ }
151
+ return dto;
152
+ }
153
+
112
154
  export async function registerConnector() {
113
155
  console.log(chalk.blue('🔌 Register a new connector\n'));
114
156
 
@@ -137,10 +179,9 @@ export async function registerConnector() {
137
179
  },
138
180
  ]);
139
181
 
140
- const dto = { id: base.id, name: base.name, description: base.description || undefined, image: base.image || undefined, type: base.type, visibility: base.visibility };
141
-
182
+ let oauthAnswers, fields;
142
183
  if (base.type === 'oauth') {
143
- const oauth = await inquirer.prompt([
184
+ oauthAnswers = await inquirer.prompt([
144
185
  { type: 'input', name: 'authorize_url', message: 'Authorize URL:' },
145
186
  { type: 'input', name: 'access_url', message: 'Token/access URL:' },
146
187
  { type: 'input', name: 'profile_url', message: 'Profile URL (optional):' },
@@ -148,16 +189,8 @@ export async function registerConnector() {
148
189
  { type: 'password', name: 'client_secret', message: 'Client secret:' },
149
190
  { type: 'input', name: 'scopes', message: 'Scopes (comma-separated, optional):' },
150
191
  ]);
151
- dto.oauth = {
152
- authorize_url: oauth.authorize_url,
153
- access_url: oauth.access_url,
154
- profile_url: oauth.profile_url || undefined,
155
- client_id: oauth.client_id,
156
- client_secret: oauth.client_secret,
157
- scopes: oauth.scopes ? oauth.scopes.split(',').map((s) => s.trim()).filter(Boolean) : [],
158
- };
159
192
  } else {
160
- const fields = [];
193
+ fields = [];
161
194
  console.log(chalk.gray('Add the fields a user must fill in (leave name blank to stop):'));
162
195
  for (;;) {
163
196
  const f = await inquirer.prompt([
@@ -172,9 +205,10 @@ export async function registerConnector() {
172
205
  fields.push({ name: f.name, label: rest.label || undefined, type: rest.type, required: rest.required });
173
206
  }
174
207
  if (fields.length === 0) throw new Error('credential_form connectors need at least one field');
175
- dto.fields = fields;
176
208
  }
177
209
 
210
+ const dto = buildRegisterConnectorDto(base, { oauthAnswers, fields });
211
+
178
212
  // Warn about likely-duplicate connectors before submitting - registering "Gmail" when
179
213
  // official.google already covers the same thing just fragments the catalog.
180
214
  try {
@@ -17,6 +17,15 @@ export const DEPLOY_EXCLUDE_FILES = ['.gitignore', 'yarn.lock'];
17
17
  // secrets and must never end up in the uploaded `files` payload.
18
18
  export const isEnvFile = (name) => name === '.env' || name.startsWith('.env.');
19
19
 
20
+ // ✅ FIX: readDirectoryRecursive used to read EVERY file with `fs.readFileSync(fullPath, 'utf8')`
21
+ // unconditionally - any binary asset (image, font, .wasm, a zip fixture used by a test) gets
22
+ // decoded as UTF-8 text and silently mangled before upload, with no warning anywhere. The backend's
23
+ // PluginDeployRequestDto only ever accepts `files` as plain UTF-8 string content (no base64/binary
24
+ // path exists there), so there is currently no way to deploy a binary asset correctly through this
25
+ // command - skipping with a clear warning is strictly better than corrupting it and finding out only
26
+ // when the deployed plugin is actually exercised. Same extension list `plugin convert` already uses.
27
+ const DEPLOY_BINARY_EXT = /\.(png|jpe?g|gif|webp|ico|svg|woff2?|ttf|eot|zip|tar|gz|pdf|mp4|mp3|wasm|node)$/i;
28
+
20
29
  export function readDirectoryRecursive(dir, basePath = '') {
21
30
  const files = {};
22
31
  const items = fs.readdirSync(dir);
@@ -28,13 +37,20 @@ export function readDirectoryRecursive(dir, basePath = '') {
28
37
  // backslash-separated keys (e.g. "src\\main.ts") that the backend's POSIX filesystem treats as
29
38
  // one literal filename containing a backslash, not a nested path - breaking every deploy.
30
39
  const relativePath = basePath ? `${basePath}/${item}` : item;
31
- const stat = fs.statSync(fullPath);
40
+ // lstat (not stat) so a symlink is never followed and treated as a real directory/file to
41
+ // upload - same reasoning as codegen.mjs's buildProjectTree.
42
+ const stat = fs.lstatSync(fullPath);
43
+ if (stat.isSymbolicLink()) continue;
32
44
 
33
45
  if (stat.isDirectory()) {
34
46
  if (!DEPLOY_EXCLUDE_DIRS.includes(item)) {
35
47
  Object.assign(files, readDirectoryRecursive(fullPath, relativePath));
36
48
  }
37
49
  } else if (!DEPLOY_EXCLUDE_FILES.includes(item) && !isEnvFile(item)) {
50
+ if (DEPLOY_BINARY_EXT.test(item)) {
51
+ console.log(chalk.yellow(`⚠️ Skipping "${relativePath}" - binary files aren't supported by \`aivin deploy\` (would be corrupted if uploaded as text).`));
52
+ continue;
53
+ }
38
54
  files[relativePath] = fs.readFileSync(fullPath, 'utf8');
39
55
  }
40
56
  }
@@ -95,7 +111,10 @@ export function ensureLockfile(currentDir) {
95
111
 
96
112
  console.log(chalk.gray(' No package-lock.json found - generating one (required for the container build)...'));
97
113
  try {
98
- execSync('npm install --package-lock-only', { cwd: currentDir, stdio: 'pipe' });
114
+ // ✅ FIX: no timeout - a hung npm registry (corporate proxy, network drop mid-request, a
115
+ // private-package auth prompt npm can't actually show under `stdio: 'pipe'`) used to hang
116
+ // `aivin deploy`/`aivin test` indefinitely with no feedback beyond "generating one...".
117
+ execSync('npm install --package-lock-only', { cwd: currentDir, stdio: 'pipe', timeout: 60000 });
99
118
  } catch (error) {
100
119
  throw new Error(
101
120
  `Failed to generate package-lock.json: ${error.stderr?.toString().trim() || error.message}`,
@@ -331,6 +350,10 @@ export async function deployPlugin({ endpointPath, label, smokeTest, workspaceOv
331
350
  'Content-Type': 'application/json',
332
351
  Authorization: `Bearer ${apiKey || 'dev-token'}`,
333
352
  },
353
+ // ✅ FIX: no timeout at all before - a hung/overloaded backend meant this could sit forever
354
+ // with no way out short of Ctrl+C. 5 minutes (not the usual short default) since this call
355
+ // covers the actual container build/scan, which can legitimately take a while.
356
+ timeout: 300000,
334
357
  });
335
358
 
336
359
  clearInterval(loadingInterval);
@@ -19,6 +19,20 @@ const CONNECTOR_SEARCH_TIMEOUT_MS = 15000;
19
19
  // suffixes common enough to be obvious (GITHUB_TOKEN -> "github", SLACK_BOT_TOKEN -> "slack") and
20
20
  // takes the first remaining word - wrong guesses cost nothing since it's an editable default, not
21
21
  // an auto-pick.
22
+ /**
23
+ * Writes one env-var field's connector binding into a manifest's `initial` map, the one operation
24
+ * that actually matters for a credential to get injected at runtime (see PluginProxyService.
25
+ * resolveMcpEnv on the backend - it only ever reads `manifest.initial[field].connection_id`, never
26
+ * a bare top-level `connection_id`). Both `buildMcpManifest` (`mcp create`) and `scanAndPublishMcp`'s
27
+ * "attach a connector" step (`mcp <url>`) need this exact same write - previously the latter
28
+ * reimplemented (and got wrong) its own version of it, which is exactly how that bug happened.
29
+ * Pulling it out here means there's only one place to get it right, and future changes to the
30
+ * `initial[field]` shape can't drift between the two commands again.
31
+ */
32
+ export function setFieldConnector(initial, fieldName, connectorId) {
33
+ initial[fieldName] = { ...(initial[fieldName] || {}), source: 'static', connection_id: connectorId };
34
+ }
35
+
22
36
  export function guessConnectorQueryFromEnvVarName(envVarName) {
23
37
  const suffixes = ['_PERSONAL_ACCESS_TOKEN', '_ACCESS_TOKEN', '_AUTH_TOKEN', '_BOT_TOKEN', '_API_KEY', '_SECRET_KEY', '_TOKEN', '_SECRET', '_KEY', '_PAT'];
24
38
  const upper = (envVarName || '').toUpperCase();
@@ -165,7 +179,10 @@ export function parseMcpArgs(argsString) {
165
179
  // short of Ctrl+C (the exact failure mode `plugin trigger` already guards against - see its
166
180
  // EXECUTE_TIMEOUT_MS). Scanning gets more headroom since it may have to handshake a live remote
167
181
  // MCP server, not just hit this platform's own backend.
168
- const MCP_SCAN_TIMEOUT_MS = 60000;
182
+ // A scan includes README/source discovery, one AI extraction, and up to 30s of container
183
+ // verification. Sixty seconds regularly cut off a healthy cold npx scan before the backend could
184
+ // return its AI fallback, producing Axios' misleading "timeout of 60000ms exceeded" error.
185
+ const MCP_SCAN_TIMEOUT_MS = 180000;
169
186
  const MCP_BUILD_TIMEOUT_MS = 30000;
170
187
  const MCP_DEPLOY_TIMEOUT_MS = 60000;
171
188
  const MCP_SUBMIT_TIMEOUT_MS = 30000;
@@ -215,8 +232,12 @@ export function buildMcpManifest(name, description, opts) {
215
232
  const connectorIdsUsed = new Set();
216
233
  for (const field of opts.envFields || []) {
217
234
  initable.push(field.name);
218
- initial[field.name] = field.connectorId ? { source: 'static', connection_id: field.connectorId } : { source: 'static' };
219
- if (field.connectorId) connectorIdsUsed.add(field.connectorId);
235
+ if (field.connectorId) {
236
+ setFieldConnector(initial, field.name, field.connectorId);
237
+ connectorIdsUsed.add(field.connectorId);
238
+ } else {
239
+ initial[field.name] = { source: 'static' };
240
+ }
220
241
  }
221
242
  const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
222
243
 
@@ -588,37 +609,80 @@ export async function scanAndPublishMcp(url, options) {
588
609
  }
589
610
  }
590
611
 
591
- // Server-generated manifests come back with whatever `auth_secret_key`/`connection_id` the
592
- // build step inferred (often none) - offer to bind an existing/new connector to all of them here
593
- // rather than leaving that to be edited by hand after the fact. Skipped in non-TTY contexts, same
594
- // as every other prompt in this flow.
595
- if (process.stdout.isTTY && process.stdin.isTTY) {
612
+ // Server-generated manifests come back with whatever `metadata.required_env_vars`/`initial` the
613
+ // build step inferred (deterministic per-server connection_id, often no registered connector yet)
614
+ // - offer to bind an existing/new connector to all of them here rather than leaving that to be
615
+ // edited by hand after the fact. Skipped in non-TTY contexts, same as every other prompt in this
616
+ // flow, and skipped entirely when nothing here actually needs a credential (e.g. mcp-server-fetch)
617
+ // so this doesn't ask a pointless question every single run.
618
+ //
619
+ // ⚠ Must write `manifest.initial[field].connection_id` per required field, NOT just a top-level
620
+ // `manifest.connection_id` (what this used to do). PluginProxyService.resolveMcpEnv on the backend
621
+ // only ever reads `manifest.initial[field].connection_id` to inject a credential into the spawned
622
+ // MCP process - a bare top-level `connection_id` only feeds the "requires logging in" readiness
623
+ // badge. Worse, on deploy `PluginStoreService.sanitizeUpsertConnectionIds` silently NULLS a
624
+ // top-level `connection_id` that no `initial` field references, unless it happens to match an
625
+ // already-registered CONNECTOR OF TYPE OAUTH specifically (`ConnectorService.
626
+ // existingOAuthConnectorIds` filters `type: 'oauth'`, excluding `credential_form` connectors
627
+ // entirely). So attaching a freshly-registered API-key/form connector here used to print a
628
+ // confident "Attached connector X" and then have the backend quietly drop it on deploy - the exact
629
+ // same pitfall `mcp create`'s own `buildMcpManifest` already works around (see its comment), which
630
+ // this flow had drifted out of sync with.
631
+ const requiredFieldNames = new Set();
632
+ for (const m of manifests) {
633
+ for (const f of m.metadata?.required_env_vars || []) requiredFieldNames.add(f.name);
634
+ for (const key of Object.keys(m.initial || {})) requiredFieldNames.add(key);
635
+ }
636
+ if (requiredFieldNames.size > 0 && process.stdout.isTTY && process.stdin.isTTY) {
596
637
  const { attachConnector } = await inquirer.prompt([
597
- { type: 'confirm', name: 'attachConnector', message: '\nAttach a connector for auth to all of these? (optional)', default: false },
638
+ {
639
+ type: 'confirm',
640
+ name: 'attachConnector',
641
+ message: `\nAttach a connector for auth (${[...requiredFieldNames].join(', ')})? (optional)`,
642
+ default: false,
643
+ },
598
644
  ]);
599
645
  if (attachConnector) {
600
646
  const connectorId = await selectConnectorInteractive();
601
647
  if (connectorId) {
602
- for (const manifest of manifests) manifest.connection_id = connectorId;
603
- console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s).`));
648
+ for (const manifest of manifests) {
649
+ manifest.initial = manifest.initial || {};
650
+ for (const fieldName of requiredFieldNames) {
651
+ setFieldConnector(manifest.initial, fieldName, connectorId);
652
+ }
653
+ // Derived readiness-display value only, same convention as buildMcpManifest - not read for
654
+ // actual credential injection (see the warning above).
655
+ manifest.connection_id = connectorId;
656
+ }
657
+ console.log(chalk.gray(` Attached connector "${connectorId}" to ${manifests.length} manifest(s) (${[...requiredFieldNames].join(', ')}).`));
604
658
  }
605
659
  }
606
660
  }
607
661
 
608
- // This is the point of no return - `aivin` has no `plugin delete`/`undeploy` command, so once
609
- // this POST succeeds the plugin(s) are live and visible to your whole org (and, with --publish,
610
- // queued for a community review that also can't be withdrawn from here) until someone removes
611
- // them from the platform directly. The checkbox above defaults every discovered item to checked,
612
- // so an unconfirmed "just press enter through it" run could deploy far more than intended -
613
- // require an explicit yes here rather than only gating on the (default-off, easy to skip) edit
614
- // prompt above.
615
- if (process.stdout.isTTY && process.stdin.isTTY) {
662
+ // This is a real, consequential action - once this POST succeeds the plugin(s) are live and
663
+ // visible to your whole org (and, with --publish, queued for a community review that also can't
664
+ // be withdrawn from here) until someone removes them via `aivin plugin delete`. The checkbox
665
+ // above defaults every discovered item to checked, so an unconfirmed "just press enter through
666
+ // it" run could deploy far more than intended - require an explicit yes here rather than only
667
+ // gating on the (default-off, easy to skip) edit prompt above.
668
+ //
669
+ // ✅ FIX: this used to only ask when both stdout/stdin were a TTY, and silently proceeded to
670
+ // deploy (with every item checked) whenever either wasn't - e.g. piping output through `| tee
671
+ // log.txt` or running inside any CI job makes stdout non-TTY. That meant the "point of no return"
672
+ // this comment used to warn about could trigger with zero confirmation and zero way to opt in to
673
+ // skipping it on purpose. Now: `--yes`/`-y` skips the prompt explicitly (same pattern as `plugin
674
+ // delete`/`pluginstore rm`), a real TTY still gets the interactive prompt, and anything else
675
+ // (non-TTY without --yes) refuses to deploy instead of silently proceeding.
676
+ if (!options.yes) {
677
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
678
+ throw new Error('Refusing to deploy without confirmation in a non-interactive session - pass --yes to deploy anyway.');
679
+ }
616
680
  const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
617
681
  const { confirmDeploy } = await inquirer.prompt([
618
682
  {
619
683
  type: 'confirm',
620
684
  name: 'confirmDeploy',
621
- message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? This can't be undone from the CLI.`,
685
+ message: `\nDeploy ${manifests.length} plugin(s) to ${scopeLabel}? Remove them later with \`aivin plugin delete\` if needed.`,
622
686
  default: false,
623
687
  },
624
688
  ]);
@@ -14,7 +14,19 @@ export async function runBrowserMission(mission, options) {
14
14
  // without starting a new mission. Useful if the auto-open above was missed/closed by accident.
15
15
  // Same for both modes - the viewer just reacts to whatever browser:cast-start fires next.
16
16
  if (options.view) {
17
- await openBrowserViewer(serverUrl, apiKey, tenantClient);
17
+ // ✅ FIX: openBrowserViewer's own HTTP server keeps listening (and with it the whole CLI
18
+ // process, since a live listener holds the Node event loop open) until something explicitly
19
+ // closes it - streamBrowserMissionLog's `stop()` does that for the auto-opened-on-HIL case, but
20
+ // this standalone --view path never had an equivalent, so `aivin browser --view` never exited
21
+ // on its own - Ctrl+C looked like the only way out, with no indication that was expected.
22
+ const server = await openBrowserViewer(serverUrl, apiKey, tenantClient);
23
+ console.log(chalk.gray(' Press Ctrl+C to close the viewer and exit.'));
24
+ await new Promise((resolve) => {
25
+ process.on('SIGINT', () => {
26
+ server.close();
27
+ resolve();
28
+ });
29
+ });
18
30
  return;
19
31
  }
20
32
 
@@ -5,6 +5,7 @@ import http from 'http';
5
5
  import os from 'os';
6
6
  import fs from 'fs';
7
7
  import { execSync, spawn } from 'child_process';
8
+ import { randomBytes } from 'crypto';
8
9
  import { fileURLToPath } from 'url';
9
10
  import { dirname } from 'path';
10
11
  import { openBrowser } from './auth.mjs';
@@ -76,6 +77,14 @@ export function streamMissionLog(serverUrl, apiKey, threadId, { idleTimeoutMs =
76
77
  console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
77
78
  stop();
78
79
  });
80
+ // ✅ FIX: socket.io-client's generic 'error' event (server-side middleware/auth failure, not
81
+ // the connection-level 'connect_error') has no listener registered anywhere in this file - an
82
+ // EventEmitter with no 'error' handler throws on that event, which crashes this whole CLI
83
+ // process outright instead of just ending the log stream gracefully like connect_error does.
84
+ socket.on('error', (error) => {
85
+ console.log(chalk.yellow(`⚠️ Live progress stream error (${error?.message || error}) - the run continues regardless.`));
86
+ stop();
87
+ });
79
88
 
80
89
  for (const eventName of MISSION_LOG_EVENTS) {
81
90
  socket.on(eventName, (payload) => {
@@ -291,17 +300,32 @@ export function browserViewerHtml({ serverUrl, apiKey, tenantClient }) {
291
300
  * Serves the viewer page on a random local port (127.0.0.1 only - never exposed beyond this
292
301
  * machine) and opens it in the default OS browser. The HTTP server is torn down when the CLI
293
302
  * process exits (SIGINT/mission end) - it only needs to live for the duration of `aivin browser`.
303
+ *
304
+ * ✅ FIX: the page embeds the real API_KEY in plaintext (see browserViewerHtml) so the viewer's own
305
+ * socket.io connection can authenticate - loopback-only binding keeps this off the network, but
306
+ * anything ELSE already running on this same machine (another local process, another browser tab
307
+ * that guesses/scans the port before the real one connects) could previously just GET the port and
308
+ * read the key straight out of the page source, no auth needed. A random one-time token in the URL
309
+ * closes that window - only whoever already has the exact URL this function printed/opened can
310
+ * actually get the page back.
294
311
  */
295
312
  export function openBrowserViewer(serverUrl, apiKey, tenantClient) {
296
313
  return new Promise((resolve) => {
314
+ const token = randomBytes(16).toString('hex');
297
315
  const html = browserViewerHtml({ serverUrl, apiKey, tenantClient });
298
316
  const server = http.createServer((req, res) => {
317
+ const reqToken = new URL(req.url, 'http://127.0.0.1').searchParams.get('t');
318
+ if (reqToken !== token) {
319
+ res.writeHead(403, { 'Content-Type': 'text/plain' });
320
+ res.end('Forbidden');
321
+ return;
322
+ }
299
323
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
300
324
  res.end(html);
301
325
  });
302
326
  server.listen(0, '127.0.0.1', () => {
303
327
  const port = server.address().port;
304
- const url = `http://127.0.0.1:${port}/`;
328
+ const url = `http://127.0.0.1:${port}/?t=${token}`;
305
329
  console.log(chalk.cyan(`\n🖥️ Mở phiên tương tác trực tiếp: ${url}`));
306
330
  openBrowser(url);
307
331
  resolve(server);
@@ -358,6 +382,13 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
358
382
  console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
359
383
  stop('connect_error');
360
384
  });
385
+ // ✅ FIX: see the identical fix/comment on streamMissionLog above - no 'error' listener meant a
386
+ // server-side socket.io error here could crash the whole CLI process instead of just ending the
387
+ // watcher.
388
+ socket.on('error', (error) => {
389
+ console.log(chalk.yellow(`⚠️ Live progress stream error (${error?.message || error}) - the run continues regardless.`));
390
+ stop('connect_error');
391
+ });
361
392
 
362
393
  for (const eventName of MISSION_LOG_EVENTS) {
363
394
  socket.on(eventName, (payload) => {