@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.
@@ -0,0 +1,127 @@
1
+ import chalk from 'chalk';
2
+ import axios from 'axios';
3
+ import inquirer from 'inquirer';
4
+ import { openBrowser } from './auth.mjs';
5
+
6
+ const POLL_INTERVAL_MS = 3000;
7
+ const OAUTH_WAIT_TIMEOUT_MS = 3 * 60 * 1000;
8
+
9
+ /**
10
+ * `/plugins/execute` comes back `status: 'needs_auth'` when a plugin's connector isn't configured
11
+ * yet (PluginExecutionService.resolveExecutionAuth on the backend) - `data.auth_flow` tells us
12
+ * which of the two ways to fix that: 'oauth' (open a browser, same as the web app's "Connect"
13
+ * button) or 'form' (a handful of plain fields, e.g. SMTP host/user/pass - no browser involved).
14
+ * Returns true once the connector is actually usable (so the caller can retry the trigger), false
15
+ * if the user declined or it failed/timed out.
16
+ */
17
+ export async function resolveConnectorAuth(data, { serverUrl, apiKey, workspaceId }) {
18
+ const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
19
+ const provider = data?.auth_params?.provider;
20
+ if (!provider) return false;
21
+
22
+ return data.auth_flow === 'form'
23
+ ? resolveFormConnector(data, { serverUrl, authHeaders, workspaceId, provider })
24
+ : resolveOAuthConnector(data, { serverUrl, authHeaders, workspaceId, provider });
25
+ }
26
+
27
+ async function resolveOAuthConnector(data, { serverUrl, authHeaders, workspaceId, provider }) {
28
+ console.log(chalk.yellow(`\n⚠ This plugin needs you to connect "${provider}" first.`));
29
+ const { proceed } = await inquirer.prompt([
30
+ { type: 'confirm', name: 'proceed', message: 'Open your browser to connect now?', default: true },
31
+ ]);
32
+ if (!proceed) return false;
33
+
34
+ let triggerUrl;
35
+ try {
36
+ const initRes = await axios.post(
37
+ `${serverUrl}/plugins/auth/init`,
38
+ { workspace_id: workspaceId, provider, scopes: data.auth_params?.scopes },
39
+ authHeaders,
40
+ );
41
+ if (!initRes.data?.success) throw new Error(initRes.data?.error || 'init failed');
42
+ triggerUrl = initRes.data.trigger_url;
43
+ } catch (error) {
44
+ console.log(chalk.red(`Couldn't start the connect flow: ${error.response?.data?.error || error.message}`));
45
+ return false;
46
+ }
47
+
48
+ console.log(chalk.blue('🌐 Opening your browser to connect...'));
49
+ console.log(chalk.gray(` ${triggerUrl}`));
50
+ console.log(chalk.gray(' Not opened automatically? Paste that URL into your browser.'));
51
+ openBrowser(triggerUrl);
52
+
53
+ console.log(chalk.gray(' Waiting for you to finish in the browser (3 min timeout)...'));
54
+ const deadline = Date.now() + OAUTH_WAIT_TIMEOUT_MS;
55
+ while (Date.now() < deadline) {
56
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
57
+ try {
58
+ const statusRes = await axios.get(`${serverUrl}/plugins/auth/status`, {
59
+ ...authHeaders,
60
+ params: { workspace_id: workspaceId, provider },
61
+ });
62
+ const status = statusRes.data?.status;
63
+ // Anything other than these two "still needs work" states means the connection is now usable
64
+ // (PluginAuthService.resolveConnectionStatus only ever returns those two, or a connected state).
65
+ if (status && status !== 'needs_auth' && status !== 'needs_scope_upgrade') {
66
+ console.log(chalk.green(`āœ… Connected "${provider}".`));
67
+ return true;
68
+ }
69
+ } catch {
70
+ // Best-effort polling - a transient network blip shouldn't abort the whole wait.
71
+ }
72
+ }
73
+ console.log(chalk.yellow('Timed out waiting for the connection - run the command again once you\'ve connected.'));
74
+ return false;
75
+ }
76
+
77
+ async function resolveFormConnector(data, { serverUrl, authHeaders, workspaceId, provider }) {
78
+ const fields = data.auth_params?.form_fields;
79
+ if (!Array.isArray(fields) || fields.length === 0) {
80
+ console.log(
81
+ chalk.yellow(
82
+ `\n⚠ This plugin needs connector "${provider}" configured, but the CLI couldn't find its field list ` +
83
+ '- configure it from the web app\'s Settings → Connections instead.',
84
+ ),
85
+ );
86
+ return false;
87
+ }
88
+
89
+ console.log(chalk.yellow(`\n⚠ This plugin needs connector "${provider}" configured:`));
90
+ const values = {};
91
+ for (const field of fields) {
92
+ const label = field.label || field.name;
93
+ const message = field.description ? `${label} (${field.description}):` : `${label}:`;
94
+
95
+ if (field.type === 'boolean') {
96
+ const { value } = await inquirer.prompt([{ type: 'confirm', name: 'value', message, default: false }]);
97
+ values[field.name] = value;
98
+ continue;
99
+ }
100
+
101
+ const { value } = await inquirer.prompt([
102
+ {
103
+ type: field.type === 'secret' ? 'password' : 'input',
104
+ name: 'value',
105
+ message: field.required ? `${message} (required)` : message,
106
+ mask: field.type === 'secret' ? '*' : undefined,
107
+ validate: (input) => {
108
+ if (!input) return field.required ? 'Required' : true;
109
+ if (field.type === 'number' && Number.isNaN(Number(input))) return 'Enter a number';
110
+ return true;
111
+ },
112
+ },
113
+ ]);
114
+ if (!value) continue; // blank optional field - leave it out
115
+ values[field.name] = field.type === 'number' ? Number(value) : value;
116
+ }
117
+
118
+ try {
119
+ await axios.post(`${serverUrl}/plugins/auth/form`, { workspace_id: workspaceId, connector_id: provider, values }, authHeaders);
120
+ console.log(chalk.green(`āœ… Configured "${provider}".`));
121
+ return true;
122
+ } catch (error) {
123
+ const message = error.response?.data?.error || error.message;
124
+ console.log(chalk.red(`Couldn't save connector: ${message}`));
125
+ return false;
126
+ }
127
+ }
@@ -4,12 +4,92 @@ import fs from 'fs';
4
4
  import path from 'path';
5
5
  import axios from 'axios';
6
6
  import inquirer from 'inquirer';
7
+ import { randomUUID } from 'crypto';
7
8
  import { flattenManifestFile } from '@aivin-labs/sdk';
8
9
  import readline from 'readline';
9
- import { requireArg } from './util.mjs';
10
+ import { requireArg, withProgressSpinner } from './util.mjs';
11
+ import { resolveWorkspace } from './workspace.mjs';
12
+ import { resolveConnectorAuth } from './pluginAuthResolve.mjs';
10
13
 
11
14
  const DELETE_TIMEOUT_MS = 30000;
12
15
 
16
+ /**
17
+ * Parses one manifest `input` field's declared shape, e.g. `"object - Input data for processing"`
18
+ * or `"number - How many items"`, into `{ type, description }` - `type` drives which inquirer
19
+ * prompt kind `promptInputFields` uses below. Unrecognized/missing type text falls back to a plain
20
+ * string prompt, since that's a safe default for anything free-text.
21
+ */
22
+ function parseFieldSpec(spec) {
23
+ if (typeof spec !== 'string') return { type: 'string', description: '' };
24
+ const match = spec.match(/^\s*(\w+)\s*-?\s*(.*)$/);
25
+ if (!match) return { type: 'string', description: spec };
26
+ const type = match[1].toLowerCase();
27
+ return { type: ['string', 'number', 'integer', 'boolean', 'object', 'array'].includes(type) ? type : 'string', description: match[2] || '' };
28
+ }
29
+
30
+ /**
31
+ * Interactive replacement for the old "-a/--auto <prompt>, let the backend's mapDataToSchema guess
32
+ * your input" flow: walks a plugin's manifest `input` schema (`{ fieldName: "type - description" }`)
33
+ * field by field and asks the user directly, instead of asking for one raw JSON blob or an
34
+ * AI-guessed mapping. A blank answer omits that field from the result entirely so optional fields
35
+ * stay optional. Falls back to a single generic `data` field when no schema is available at all
36
+ * (e.g. `--id` given for a plugin whose schema lookup came back empty).
37
+ */
38
+ async function promptInputFields(schema) {
39
+ const fields = schema && typeof schema === 'object' ? Object.entries(schema) : [];
40
+ if (fields.length === 0) {
41
+ const { data } = await inquirer.prompt([
42
+ { type: 'input', name: 'data', message: 'Input data (as a JSON string, e.g. {"text":"hello"}), or leave blank for none:' },
43
+ ]);
44
+ if (!data) return {};
45
+ try {
46
+ return JSON.parse(data);
47
+ } catch (error) {
48
+ throw new Error(`Invalid JSON for input: ${error.message}`, { cause: error });
49
+ }
50
+ }
51
+
52
+ const result = {};
53
+ for (const [fieldName, spec] of fields) {
54
+ const { type, description } = parseFieldSpec(spec);
55
+ const label = description ? `${fieldName} (${type}) - ${description}:` : `${fieldName} (${type}):`;
56
+
57
+ if (type === 'boolean') {
58
+ const { value } = await inquirer.prompt([{ type: 'confirm', name: 'value', message: label, default: false }]);
59
+ result[fieldName] = value;
60
+ continue;
61
+ }
62
+
63
+ const { value } = await inquirer.prompt([
64
+ {
65
+ type: 'input',
66
+ name: 'value',
67
+ message: label,
68
+ validate: (input) => {
69
+ if (!input) return true; // blank = skip this field
70
+ if ((type === 'number' || type === 'integer') && Number.isNaN(Number(input))) return 'Enter a number';
71
+ if ((type === 'object' || type === 'array') && !tryParseJson(input)) return 'Enter valid JSON';
72
+ return true;
73
+ },
74
+ },
75
+ ]);
76
+ if (!value) continue; // blank = optional field, leave it out
77
+ if (type === 'number' || type === 'integer') result[fieldName] = Number(value);
78
+ else if (type === 'object' || type === 'array') result[fieldName] = JSON.parse(value);
79
+ else result[fieldName] = value;
80
+ }
81
+ return result;
82
+ }
83
+
84
+ function tryParseJson(input) {
85
+ try {
86
+ JSON.parse(input);
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+
13
93
  /**
14
94
  * Resolves which manifest entry `plugin trigger` should invoke: the `--func` match if given, the
15
95
  * one-and-only entry for a single-function/single-entry plugin, or a clear error listing the
@@ -59,6 +139,14 @@ export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine
59
139
  denyReason = error.message;
60
140
  resolve();
61
141
  });
142
+ // āœ… FIX: no 'error' listener anywhere for this socket - a server-side socket.io error (not the
143
+ // connection-level 'connect_error') would crash the whole CLI process instead of just falling
144
+ // back to "no live output" like connect_error does.
145
+ socket.on('error', (error) => {
146
+ clearTimeout(giveUp);
147
+ denyReason = error?.message || String(error);
148
+ resolve();
149
+ });
62
150
  socket.on('connect', () => {
63
151
  socket.emit('subscribe-plugin-logs', { plugin_id: pluginId }, (ack) => {
64
152
  clearTimeout(giveUp);
@@ -73,23 +161,48 @@ export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine
73
161
  return { subscribed, denyReason, stop: () => socket.disconnect() };
74
162
  }
75
163
 
164
+ /**
165
+ * Realtime stage/percent progress for a single `trigger` call — mirrors `withScanLog`/
166
+ * `scanAndPublishMcp` (`mcpProxy.mjs`, used for `aivin mcp <url>`'s scan step): join the Socket.IO
167
+ * room BEFORE the caller sends its POST (so no early progress events are missed), then track the
168
+ * latest `plugin-execute-progress` payload for a spinner to poll. Useful for the same reason as
169
+ * `--watch-logs` — a cold-start Docker install can take 60-150s+ with zero feedback otherwise —
170
+ * but this is on by default (no flag needed) since it's cheap and doesn't require log-view
171
+ * permission the way `--watch-logs` does.
172
+ */
173
+ async function withExecuteProgress(executeSessionId, { serverUrl, apiKey }) {
174
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
175
+ const room = `plugin-execute:${executeSessionId}`;
176
+ let current = { stage: 'starting', percent: 0, message: 'Đang gửi yêu cầu...' };
177
+ await new Promise((resolve) => {
178
+ const giveUp = setTimeout(resolve, 8000);
179
+ socket.on('connect_error', () => { clearTimeout(giveUp); resolve(); });
180
+ // āœ… FIX: same missing 'error' handler class of bug as watchPluginLogLines above - without it a
181
+ // server-side socket.io error crashes the CLI instead of just skipping the live progress bar.
182
+ socket.on('error', () => { clearTimeout(giveUp); resolve(); });
183
+ socket.on('connect', () => {
184
+ socket.emit('join-room', { name: 'plugin-execute', rooms: [room] }, () => { clearTimeout(giveUp); resolve(); });
185
+ });
186
+ });
187
+ socket.on('plugin-execute-progress', (payload) => { current = payload; });
188
+ return { getCurrent: () => current, stop: () => socket.disconnect() };
189
+ }
190
+
76
191
  /**
77
192
  * `aivin plugin trigger` - invokes an already-deployed plugin for real via the same
78
193
  * `POST /plugins/execute` the platform's own Playground uses (PluginExecutionService.executePlugin
79
- * on the backend), and prints the result. Two modes:
80
- * - Direct: `<mission>` + `<input>` (a JSON string) sent as `purpose`/`arguments` as-is.
81
- * - Auto (`-a/--auto <prompt>`): sends the prompt as `raw_text` instead - the backend's own
82
- * `mapDataToSchema` maps it onto `manifest.input` for you (same mechanism the Playground's "Thį»­
83
- * nghiệm" tab uses), same as pasting a free-text request into the platform's chat-style tester.
84
- * `<input>` can still be given alongside `-a` for fields you want to force rather than let the AI
85
- * infer - explicit `arguments` win over auto-mapped ones per field.
194
+ * on the backend), and prints the result. `<mission>` + `<input>` (a JSON string) are sent as
195
+ * `purpose`/`arguments` as-is; if either is missing, this prompts for it interactively - mission as
196
+ * free text, input field-by-field from the plugin's manifest `input` schema (see
197
+ * `promptInputFields`). No more auto-mapping (`-a/--auto`, backend's `mapDataToSchema`) - the user
198
+ * fills in every field themselves instead of the AI guessing at a free-text prompt.
86
199
  *
87
200
  * By default this only surfaces what `/plugins/execute`'s response itself carries: `processing_log`
88
- * (the mapping/execution stage messages, all at once, not the plugin's own internal console output)
89
- * and `mapped_arguments` (only present when `-a` was used). Pass `--watch-logs` to also stream the
90
- * plugin's own console.log/console.error output inline (subscribes right before the call, same feed
91
- * `aivin plugin logs` tails) instead of needing a second terminal - see `watchPluginLogLines` for
92
- * why this silently does nothing for a plugin you don't have log-view permission on.
201
+ * (the mapping/execution stage messages, all at once, not the plugin's own internal console output).
202
+ * Pass `--watch-logs` to also stream the plugin's own console.log/console.error output inline
203
+ * (subscribes right before the call, same feed `aivin plugin logs` tails) instead of needing a
204
+ * second terminal - see `watchPluginLogLines` for why this silently does nothing for a plugin you
205
+ * don't have log-view permission on.
93
206
  *
94
207
  * `--id <pluginId>` skips the local manifest.json lookup - required for plugins with no scaffolded
95
208
  * project directory, e.g. proxy plugins built by `aivin mcp <url>`, which deploy straight from an
@@ -122,6 +235,7 @@ export async function triggerPlugin(mission, inputJson, options) {
122
235
  // MCP plugin from the Playground-equivalent flow was impossible outside the web app.
123
236
  let entryId = options.id;
124
237
  let entryLabel = options.id;
238
+ let inputSchema;
125
239
  if (!entryId) {
126
240
  const currentDir = process.cwd();
127
241
  const manifestPath = path.join(currentDir, 'manifest.json');
@@ -132,102 +246,130 @@ export async function triggerPlugin(mission, inputJson, options) {
132
246
  const entry = resolveTriggerEntry(manifest, options.func);
133
247
  entryId = entry.id;
134
248
  entryLabel = `${entry.name}${entry.func ? ` [${entry.func}]` : ''}`;
249
+ inputSchema = entry.input;
135
250
  }
136
251
 
252
+ const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
253
+ const apiKey = process.env.API_KEY;
254
+ if (!apiKey) {
255
+ console.log(chalk.yellow('āš ļø API_KEY not set - run `aivin login` first'));
256
+ }
257
+ const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
258
+
137
259
  const body = { plugin_id: entryId };
138
- if (options.auto) {
139
- body.raw_text = options.auto;
140
- body.purpose = mission || options.auto;
141
- if (inputJson) {
142
- try {
143
- body.arguments = JSON.parse(inputJson);
144
- } catch (error) {
145
- throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
146
- }
147
- }
148
- } else {
149
- if (!mission || !inputJson) {
150
- const usage = 'Usage: aivin plugin trigger "<mission>" \'<input JSON>\' (or: aivin plugin trigger -a "<prompt>")';
151
- mission = await requireArg(mission, { prompt: 'Mission (why this run was triggered):', usage });
152
- inputJson = await requireArg(inputJson, { prompt: 'Input (as a JSON string, e.g. {"text":"hello"}):', usage });
153
- }
154
- body.purpose = mission;
260
+ mission = await requireArg(mission, { prompt: 'Mission (why this run was triggered):', usage: 'Usage: aivin plugin trigger "<mission>" \'<input JSON>\'' });
261
+ body.purpose = mission;
262
+
263
+ if (inputJson) {
155
264
  try {
156
265
  body.arguments = JSON.parse(inputJson);
157
266
  } catch (error) {
158
267
  throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
159
268
  }
269
+ } else {
270
+ // No auto-mapping anymore - ask the user for each input field directly instead of guessing
271
+ // (or asking for one raw JSON blob) on their behalf.
272
+ if (!inputSchema && options.id) {
273
+ try {
274
+ const res = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params: { query: options.id, limit: 10 } });
275
+ const results = Array.isArray(res.data) ? res.data : res.data?.items || [];
276
+ inputSchema = results.find((p) => p.id === options.id)?.input;
277
+ } catch {
278
+ // Best-effort only - falls back to the generic single-field prompt below.
279
+ }
280
+ }
281
+ console.log(chalk.gray(`\nInput for ${entryLabel || entryId}:`));
282
+ body.arguments = await promptInputFields(inputSchema);
160
283
  }
161
- if (options.agent) body.agent_id = options.agent;
162
284
 
163
- const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
164
- const apiKey = process.env.API_KEY;
165
- if (!apiKey) {
166
- console.log(chalk.yellow('āš ļø API_KEY not set - run `aivin login` first'));
167
- }
168
- const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
285
+ if (options.agent) body.agent_id = options.agent;
169
286
  // No client-side timeout here before meant a hung backend (or a genuinely stuck plugin - the
170
287
  // server side already caps at MAX_DOCKER_TIMEOUT_MS/effectiveTimeout, but that's enforced on the
171
288
  // backend, not by this CLI process) could leave `trigger` sitting forever with no feedback short
172
289
  // of Ctrl+C. `AIVIN_TRIGGER_TIMEOUT_MS` overrides if 3 minutes isn't enough for a legitimately
173
290
  // slow plugin.
174
291
  const EXECUTE_TIMEOUT_MS = parseInt(process.env.AIVIN_TRIGGER_TIMEOUT_MS || '180000');
175
- const WORKSPACE_LOOKUP_TIMEOUT_MS = 15000;
176
292
 
177
- let workspaceId = options.workspace;
178
- if (!workspaceId) {
179
- try {
180
- const wsRes = await axios.get(`${serverUrl}/workspace/list`, { ...authHeaders, timeout: WORKSPACE_LOOKUP_TIMEOUT_MS });
181
- const workspaces = Array.isArray(wsRes.data) ? wsRes.data : wsRes.data?.items || [];
182
- workspaceId = workspaces[0]?.id || workspaces[0]?._id;
183
- } catch (error) {
184
- throw new Error(`Couldn't look up a workspace to run against (${error.message}). Pass --workspace <id>.`, { cause: error });
185
- }
186
- }
187
- if (!workspaceId) {
188
- throw new Error('No workspace found for this account. Pass --workspace <id>.');
189
- }
293
+ // āœ… FIX: this used to only look up/validate a workspace when `--workspace` was OMITTED, and
294
+ // trusted an explicitly-passed `--workspace <id>` as-is with no existence check - every other
295
+ // command taking `--workspace` (aivin do/browser/agent .../task ...) routes through
296
+ // resolveWorkspace(), which validates it and throws a clear "not found or not accessible" error.
297
+ // A typo'd/wrong id here instead sailed straight through to the backend and came back as
298
+ // whatever generic error `/plugins/execute` happens to give for an invalid workspace_id.
299
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
300
+ const workspaceId = workspace.id || workspace._id;
190
301
  body.workspace_id = workspaceId;
191
302
 
192
- let logWatcher;
193
- if (options.watchLogs) {
194
- logWatcher = await watchPluginLogLines(entryId, {
195
- serverUrl,
196
- apiKey,
197
- onLine: (payload) => {
198
- const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
199
- const streamColor = payload.stream === 'stderr' ? chalk.red : payload.stream === 'system' ? chalk.yellow : chalk.gray;
200
- console.log(chalk.gray(`[${time}]`), streamColor(payload.line));
201
- },
202
- });
203
- if (logWatcher.subscribed) {
204
- console.log(chalk.blue(`šŸ“” Watching live console output for ${entryLabel || entryId}...`));
205
- } else {
206
- console.log(chalk.gray(`(--watch-logs: no live console output - ${logWatcher.denyReason})`));
303
+ // A run can come back needing a connector that isn't set up yet (`status: 'needs_auth'`) - rather
304
+ // than just printing that and leaving the user to go set it up and re-run the whole command by
305
+ // hand, offer to resolve it right here (OAuth: open a browser and wait; form: prompt for the
306
+ // fields) and automatically retry the exact same call once. Only in an interactive terminal - a
307
+ // script/CI run with no TTY just gets the needs_auth result printed, same as before this existed.
308
+ // `logWatcher` is re-subscribed each attempt (not hoisted outside the loop) so `--watch-logs`
309
+ // still streams live output on the post-auth retry, not just the first (doomed-to-fail) attempt.
310
+ let result;
311
+ let attempt = 0;
312
+ for (;;) {
313
+ attempt++;
314
+
315
+ let logWatcher;
316
+ if (options.watchLogs) {
317
+ logWatcher = await watchPluginLogLines(entryId, {
318
+ serverUrl,
319
+ apiKey,
320
+ onLine: (payload) => {
321
+ const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
322
+ const streamColor = payload.stream === 'stderr' ? chalk.red : payload.stream === 'system' ? chalk.yellow : chalk.gray;
323
+ console.log(chalk.gray(`[${time}]`), streamColor(payload.line));
324
+ },
325
+ });
326
+ if (logWatcher.subscribed) {
327
+ console.log(chalk.blue(`šŸ“” Watching live console output for ${entryLabel || entryId}...`));
328
+ } else {
329
+ console.log(chalk.gray(`(--watch-logs: no live console output - ${logWatcher.denyReason})`));
330
+ }
207
331
  }
208
- }
209
332
 
210
- console.log(chalk.blue(`šŸš€ Triggering ${entryLabel || entryId}...`));
333
+ const executeSessionId = randomUUID();
334
+ body.execute_session_id = executeSessionId;
335
+ const progress = await withExecuteProgress(executeSessionId, { serverUrl, apiKey });
336
+
337
+ let response;
338
+ try {
339
+ response = await withProgressSpinner(`šŸš€ Triggering ${entryLabel || entryId}`, progress.getCurrent, () =>
340
+ axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS }),
341
+ );
342
+ } catch (error) {
343
+ if (logWatcher?.subscribed) {
344
+ // Give trailing log lines from this failed call a moment to arrive before disconnecting.
345
+ await new Promise((resolve) => setTimeout(resolve, 300));
346
+ }
347
+ logWatcher?.stop();
348
+ progress.stop();
349
+ const message = error.response?.data?.message || error.message;
350
+ throw new Error(`Trigger failed: ${message}`, { cause: error });
351
+ }
211
352
 
212
- let response;
213
- try {
214
- response = await axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS });
215
- } catch (error) {
216
353
  if (logWatcher?.subscribed) {
217
- // Give trailing log lines from this failed call a moment to arrive before disconnecting.
218
354
  await new Promise((resolve) => setTimeout(resolve, 300));
219
355
  }
220
356
  logWatcher?.stop();
221
- const message = error.response?.data?.message || error.message;
222
- throw new Error(`Trigger failed: ${message}`, { cause: error });
223
- }
224
-
225
- if (logWatcher?.subscribed) {
226
- await new Promise((resolve) => setTimeout(resolve, 300));
357
+ progress.stop();
358
+
359
+ result = response.data ?? {};
360
+
361
+ // `--no-auth-prompt` -> commander sets options.authPrompt = false (negatable option convention -
362
+ // there is no options.noAuthPrompt). Defaults to true (flag omitted) so this is opt-out, not opt-in.
363
+ const canResolveNow = attempt === 1 && options.authPrompt !== false && process.stdout.isTTY && process.stdin.isTTY;
364
+ if (String(result.status || '').toLowerCase() === 'needs_auth' && canResolveNow) {
365
+ const connected = await resolveConnectorAuth(result.data, { serverUrl, apiKey, workspaceId });
366
+ if (connected) {
367
+ console.log(chalk.gray('\nRetrying...'));
368
+ continue;
369
+ }
370
+ }
371
+ break;
227
372
  }
228
- logWatcher?.stop();
229
-
230
- const result = response.data ?? {};
231
373
 
232
374
  if (Array.isArray(result.processing_log) && result.processing_log.length) {
233
375
  console.log(chalk.gray('\n--- Log ---'));
@@ -361,6 +503,12 @@ export async function streamPluginLogs(pluginId, options) {
361
503
  console.error(chalk.red('āŒ'), `Connection failed: ${error.message}`);
362
504
  stop();
363
505
  });
506
+ // āœ… FIX: same missing 'error' handler class of bug as above - without it a server-side
507
+ // socket.io error crashes the CLI (`aivin plugin logs`) instead of just ending the tail cleanly.
508
+ socket.on('error', (error) => {
509
+ console.error(chalk.red('āŒ'), `Log stream error: ${error?.message || error}`);
510
+ stop();
511
+ });
364
512
  });
365
513
  }
366
514
 
@@ -478,10 +626,10 @@ export async function showPluginInfo(id, options) {
478
626
  /**
479
627
  * `aivin plugin ask "<mission>"` - the one-shot "just simulate the agent" mode: given a
480
628
  * plain-language mission, it searches the plugin ecosystem the same relevance-ranked way the
481
- * platform's own agent does to auto-select a plugin, picks the top match, and immediately triggers
482
- * it with that same mission auto-mapped onto the input schema (`plugin trigger -a` under the hood).
483
- * Where `plugin search` + `plugin trigger --id <id> -a "..."` is the two-step "pick, then run" flow,
484
- * `ask` collapses both into what an agent actually does at execution time - no manual id copy/paste.
629
+ * platform's own agent does to auto-select a plugin, picks the top match, then triggers it -
630
+ * prompting for each input field directly (`plugin trigger` under the hood, no auto-mapping).
631
+ * Where `plugin search` + `plugin trigger --id <id>` is the two-step "pick, then run" flow, `ask`
632
+ * collapses both into one - no manual id copy/paste, but input is still filled in by hand.
485
633
  *
486
634
  * `--top <n>` (default 5) controls how many candidates are fetched so the runner-up(s) can be
487
635
  * printed for context/debugging when the auto-pick looks wrong; only the #1 match is ever run.
@@ -521,7 +669,7 @@ export async function askPlugin(mission, options) {
521
669
  }
522
670
  console.log();
523
671
 
524
- await triggerPlugin(mission, options.input, { ...options, auto: mission, id: chosen.id });
672
+ await triggerPlugin(mission, options.input, { ...options, id: chosen.id });
525
673
  }
526
674
 
527
675
  export function formatPluginListLine(plugin, isSelected) {
package/bin/lib/store.mjs CHANGED
@@ -4,7 +4,7 @@ import path from 'path';
4
4
  import chalk from 'chalk';
5
5
  import axios from 'axios';
6
6
  import inquirer from 'inquirer';
7
- import { withSpinner, requireArg } from './util.mjs';
7
+ import { withSpinner, requireArg, DEFAULT_API_TIMEOUT_MS } from './util.mjs';
8
8
 
9
9
  // ── Plugin store (self-host aivin-service worker) — attach/create/ls/enable/disable/detach ──────
10
10
  //
@@ -19,7 +19,11 @@ export function storeAuthHeaders() {
19
19
  if (!apiKey) {
20
20
  console.log(chalk.yellow('āš ļø API_KEY not set - run `aivin login` first'));
21
21
  }
22
- return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
22
+ // āœ… FIX: every axios call in this file passes this object straight through as its request config
23
+ // (never overriding timeout) - none of them had a `timeout` before, so a hung/overloaded backend
24
+ // left the spinner spinning forever with no way out short of Ctrl+C. Setting it once here covers
25
+ // every call site instead of patching each individually.
26
+ return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` }, timeout: DEFAULT_API_TIMEOUT_MS };
23
27
  }
24
28
 
25
29
  export function storeBaseUrl() {
@@ -51,7 +55,17 @@ function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, storeName, n
51
55
  ...(sdkGrpcEndpoint ? { sdk_grpc_endpoint: sdkGrpcEndpoint } : {}),
52
56
  paired_at: new Date().toISOString(),
53
57
  };
58
+ // `mode: 0o600` only actually restricts access on POSIX (Linux/macOS) - Node's `mode` option maps
59
+ // to very little on Windows NTFS (no real per-user read restriction the way POSIX permission bits
60
+ // do), so on Windows this file's `worker_token` is effectively readable by any account that can
61
+ // read this directory at all. Encrypting it at rest would need a real key-management decision
62
+ // (where does the encryption key itself live, without just moving the same problem one level
63
+ // down?) - out of scope for a CLI-side fix, so surfacing the risk explicitly instead of silently
64
+ // relying on a permission bit that doesn't do what it looks like it does on this platform.
54
65
  fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 });
66
+ if (process.platform === 'win32') {
67
+ console.log(chalk.gray(` Note: on Windows, "${filePath}" is only as protected as the folder it's in (0o600 has no POSIX-style effect here) - keep this machine/account access appropriately restricted.`));
68
+ }
55
69
  return filePath;
56
70
  }
57
71