@aivin-labs/cli 1.0.3 → 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.
@@ -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,10 +179,14 @@ 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;
189
+ const MCP_WATCH_TIMEOUT_MS = 15000;
172
190
 
173
191
  // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
174
192
 
@@ -214,8 +232,12 @@ export function buildMcpManifest(name, description, opts) {
214
232
  const connectorIdsUsed = new Set();
215
233
  for (const field of opts.envFields || []) {
216
234
  initable.push(field.name);
217
- initial[field.name] = field.connectorId ? { source: 'static', connection_id: field.connectorId } : { source: 'static' };
218
- 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
+ }
219
241
  }
220
242
  const connectionId = opts.connectorId || (connectorIdsUsed.size > 0 ? [...connectorIdsUsed].sort()[0] : undefined);
221
243
 
@@ -587,37 +609,80 @@ export async function scanAndPublishMcp(url, options) {
587
609
  }
588
610
  }
589
611
 
590
- // Server-generated manifests come back with whatever `auth_secret_key`/`connection_id` the
591
- // build step inferred (often none) - offer to bind an existing/new connector to all of them here
592
- // rather than leaving that to be edited by hand after the fact. Skipped in non-TTY contexts, same
593
- // as every other prompt in this flow.
594
- 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) {
595
637
  const { attachConnector } = await inquirer.prompt([
596
- { 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
+ },
597
644
  ]);
598
645
  if (attachConnector) {
599
646
  const connectorId = await selectConnectorInteractive();
600
647
  if (connectorId) {
601
- for (const manifest of manifests) manifest.connection_id = connectorId;
602
- 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(', ')}).`));
603
658
  }
604
659
  }
605
660
  }
606
661
 
607
- // This is the point of no return - `aivin` has no `plugin delete`/`undeploy` command, so once
608
- // this POST succeeds the plugin(s) are live and visible to your whole org (and, with --publish,
609
- // queued for a community review that also can't be withdrawn from here) until someone removes
610
- // them from the platform directly. The checkbox above defaults every discovered item to checked,
611
- // so an unconfirmed "just press enter through it" run could deploy far more than intended -
612
- // require an explicit yes here rather than only gating on the (default-off, easy to skip) edit
613
- // prompt above.
614
- 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
+ }
615
680
  const scopeLabel = options.publish ? 'your org now, and submitted for community review' : 'your org';
616
681
  const { confirmDeploy } = await inquirer.prompt([
617
682
  {
618
683
  type: 'confirm',
619
684
  name: 'confirmDeploy',
620
- 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.`,
621
686
  default: false,
622
687
  },
623
688
  ]);
@@ -715,3 +780,58 @@ export async function scanAndPublishMcp(url, options) {
715
780
  }
716
781
  }
717
782
  }
783
+
784
+ function extractApiErrorMessage(error) {
785
+ return error.response?.data?.message?.message || error.response?.data?.message || error.message;
786
+ }
787
+
788
+ /**
789
+ * Register (or reactivate) a server-side watch on a GitHub repo+branch previously scanned via
790
+ * `aivin mcp <url>` - the backend cron-checks the branch's HEAD commit every ~5 min and
791
+ * auto-rescans+resyncs the plugins it owns when it changes. No CLI process needs to stay running;
792
+ * this call just registers the watch and returns.
793
+ */
794
+ export async function registerMcpWatch(url, options = {}) {
795
+ let watch;
796
+ try {
797
+ const res = await withSpinner('👀 Registering watch', () =>
798
+ axios.post(`${connectorBaseUrl()}/plugins/mcp-watch`, { url, branch: options.branch },
799
+ { ...connectorAuthHeaders(), timeout: MCP_WATCH_TIMEOUT_MS }));
800
+ watch = res.data;
801
+ } catch (error) {
802
+ throw new Error(`Watch registration failed: ${extractApiErrorMessage(error)}`, { cause: error });
803
+ }
804
+ console.log(chalk.green(`✅ Watching ${watch.repo_id} @ ${watch.branch}`));
805
+ console.log(chalk.gray(' Checked server-side every ~5 min - no need to keep this terminal open.'));
806
+ }
807
+
808
+ /** Stop auto-resyncing a previously watched repo. Does not touch already-deployed plugins. */
809
+ export async function unwatchMcp(url, options = {}) {
810
+ try {
811
+ await axios.delete(`${connectorBaseUrl()}/plugins/mcp-watch`,
812
+ { ...connectorAuthHeaders(), data: { url, branch: options.branch } });
813
+ } catch (error) {
814
+ throw new Error(`Unwatch failed: ${extractApiErrorMessage(error)}`, { cause: error });
815
+ }
816
+ console.log(chalk.green('✅ Watch removed - deployed plugins are untouched.'));
817
+ }
818
+
819
+ /** List the caller's watched repos. */
820
+ export async function listMcpWatches() {
821
+ let watches;
822
+ try {
823
+ const res = await axios.get(`${connectorBaseUrl()}/plugins/mcp-watch`, connectorAuthHeaders());
824
+ watches = res.data || [];
825
+ } catch (error) {
826
+ throw new Error(`Listing watches failed: ${extractApiErrorMessage(error)}`, { cause: error });
827
+ }
828
+ if (watches.length === 0) {
829
+ console.log(chalk.gray('No watched repos. Run `aivin mcp watch <url>` to add one.'));
830
+ return;
831
+ }
832
+ watches.forEach((w) => {
833
+ console.log(`${chalk.bold(w.repo_id)} @ ${w.branch} ${chalk.gray(`[${w.status}]`)}`);
834
+ console.log(chalk.gray(` sha: ${w.last_known_sha || '(not yet checked)'} last checked: ${w.last_checked_at || 'never'}`));
835
+ if (w.status === 'error') console.log(chalk.red(` ⚠ ${w.last_error}`));
836
+ });
837
+ }
@@ -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);
@@ -328,31 +352,42 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
328
352
  const statusIcon = (status) =>
329
353
  status === 'error' ? chalk.red('✗') : status === 'success' ? chalk.green('✓') : status === 'warning' ? chalk.yellow('!') : chalk.gray('·');
330
354
 
331
- const stop = () => {
355
+ // `reason` lets the caller (browserAutomation.mjs's tunnel-retry loop) tell a genuine mission
356
+ // outcome ('success'/'failed'/'cancelled') apart from "we just gave up watching"
357
+ // ('idle'/'sigint'/'connect_error') - only the latter group is worth retrying on tunnel drop.
358
+ const stop = (reason) => {
332
359
  if (settled) return;
333
360
  settled = true;
334
361
  clearTimeout(idleTimer);
335
362
  socket.disconnect();
336
- process.off('SIGINT', stop);
363
+ process.off('SIGINT', onSigint);
337
364
  // The auto-opened HIL viewer keeps a listening HTTP server alive (and with it the whole
338
365
  // process) past the point the mission actually finished - close it along with everything else.
339
366
  viewerServer?.close();
340
- resolve();
367
+ resolve(reason);
341
368
  };
342
369
 
343
370
  const bumpIdleTimer = () => {
344
371
  clearTimeout(idleTimer);
345
372
  idleTimer = setTimeout(() => {
346
373
  console.log(chalk.gray(`\n(no activity for ${Math.round(idleTimeoutMs / 1000)}s - stopped watching; the run may still be going in the background)`));
347
- stop();
374
+ stop('idle');
348
375
  }, idleTimeoutMs);
349
376
  };
350
377
 
351
- process.on('SIGINT', stop);
378
+ const onSigint = () => stop('sigint');
379
+ process.on('SIGINT', onSigint);
352
380
 
353
381
  socket.on('connect_error', (error) => {
354
382
  console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
355
- stop();
383
+ stop('connect_error');
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');
356
391
  });
357
392
 
358
393
  for (const eventName of MISSION_LOG_EVENTS) {
@@ -397,7 +432,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
397
432
  if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
398
433
  const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
399
434
  sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
400
- stop();
435
+ stop(ok ? 'success' : 'failed');
401
436
  }
402
437
  });
403
438
  }
@@ -409,7 +444,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
409
444
  // even though the backend was emitting a full trace the whole time. `detail` (when present)
410
445
  // carries the LLM's actual per-action reasoning (AIBrowserActionItem.reason), not just the
411
446
  // truncated one-line summary meant for a chat bubble.
412
- const STEP_ICON = { perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
447
+ const STEP_ICON = { planning: '📋', perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
413
448
  socket.on('browser:agent-step', (payload) => {
414
449
  if (!payload) return;
415
450
  bumpIdleTimer();