@aivin-labs/cli 1.0.4 → 1.0.8
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/README.md +263 -216
- package/bin/cli.mjs +1780 -1361
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -245
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/codegen.mjs +61 -5
- package/bin/lib/connectors.mjs +55 -21
- package/bin/lib/deploy.mjs +25 -2
- package/bin/lib/mcpProxy.mjs +869 -773
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +696 -660
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +457 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +292 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +66 -0
- package/bin/lib/remote/client.mjs +726 -0
- package/bin/lib/remote/constants.mjs +173 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +245 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +249 -0
- package/bin/lib/remote/mascot/assets.mjs +218 -0
- package/bin/lib/remote/mascot/hostSource.mjs +362 -0
- package/bin/lib/remote/mascot/index.mjs +322 -0
- package/bin/lib/remote/mascot/labels.mjs +83 -0
- package/bin/lib/remote/mascot/strings.mjs +189 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +726 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +1353 -1274
- package/package.json +71 -62
|
@@ -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
|
+
}
|
|
@@ -8,9 +8,88 @@ import { randomUUID } from 'crypto';
|
|
|
8
8
|
import { flattenManifestFile } from '@aivin-labs/sdk';
|
|
9
9
|
import readline from 'readline';
|
|
10
10
|
import { requireArg, withProgressSpinner } from './util.mjs';
|
|
11
|
+
import { resolveWorkspace } from './workspace.mjs';
|
|
12
|
+
import { resolveConnectorAuth } from './pluginAuthResolve.mjs';
|
|
11
13
|
|
|
12
14
|
const DELETE_TIMEOUT_MS = 30000;
|
|
13
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
|
+
|
|
14
93
|
/**
|
|
15
94
|
* Resolves which manifest entry `plugin trigger` should invoke: the `--func` match if given, the
|
|
16
95
|
* one-and-only entry for a single-function/single-entry plugin, or a clear error listing the
|
|
@@ -60,6 +139,14 @@ export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine
|
|
|
60
139
|
denyReason = error.message;
|
|
61
140
|
resolve();
|
|
62
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
|
+
});
|
|
63
150
|
socket.on('connect', () => {
|
|
64
151
|
socket.emit('subscribe-plugin-logs', { plugin_id: pluginId }, (ack) => {
|
|
65
152
|
clearTimeout(giveUp);
|
|
@@ -90,6 +177,9 @@ async function withExecuteProgress(executeSessionId, { serverUrl, apiKey }) {
|
|
|
90
177
|
await new Promise((resolve) => {
|
|
91
178
|
const giveUp = setTimeout(resolve, 8000);
|
|
92
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(); });
|
|
93
183
|
socket.on('connect', () => {
|
|
94
184
|
socket.emit('join-room', { name: 'plugin-execute', rooms: [room] }, () => { clearTimeout(giveUp); resolve(); });
|
|
95
185
|
});
|
|
@@ -101,20 +191,18 @@ async function withExecuteProgress(executeSessionId, { serverUrl, apiKey }) {
|
|
|
101
191
|
/**
|
|
102
192
|
* `aivin plugin trigger` - invokes an already-deployed plugin for real via the same
|
|
103
193
|
* `POST /plugins/execute` the platform's own Playground uses (PluginExecutionService.executePlugin
|
|
104
|
-
* on the backend), and prints the result.
|
|
105
|
-
* -
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
* `<input>` can still be given alongside `-a` for fields you want to force rather than let the AI
|
|
110
|
-
* 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.
|
|
111
199
|
*
|
|
112
200
|
* By default this only surfaces what `/plugins/execute`'s response itself carries: `processing_log`
|
|
113
|
-
* (the mapping/execution stage messages, all at once, not the plugin's own internal console output)
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
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.
|
|
118
206
|
*
|
|
119
207
|
* `--id <pluginId>` skips the local manifest.json lookup - required for plugins with no scaffolded
|
|
120
208
|
* project directory, e.g. proxy plugins built by `aivin mcp <url>`, which deploy straight from an
|
|
@@ -147,6 +235,7 @@ export async function triggerPlugin(mission, inputJson, options) {
|
|
|
147
235
|
// MCP plugin from the Playground-equivalent flow was impossible outside the web app.
|
|
148
236
|
let entryId = options.id;
|
|
149
237
|
let entryLabel = options.id;
|
|
238
|
+
let inputSchema;
|
|
150
239
|
if (!entryId) {
|
|
151
240
|
const currentDir = process.cwd();
|
|
152
241
|
const manifestPath = path.join(currentDir, 'manifest.json');
|
|
@@ -157,108 +246,130 @@ export async function triggerPlugin(mission, inputJson, options) {
|
|
|
157
246
|
const entry = resolveTriggerEntry(manifest, options.func);
|
|
158
247
|
entryId = entry.id;
|
|
159
248
|
entryLabel = `${entry.name}${entry.func ? ` [${entry.func}]` : ''}`;
|
|
249
|
+
inputSchema = entry.input;
|
|
160
250
|
}
|
|
161
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
|
+
|
|
162
259
|
const body = { plugin_id: entryId };
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
try {
|
|
168
|
-
body.arguments = JSON.parse(inputJson);
|
|
169
|
-
} catch (error) {
|
|
170
|
-
throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
} else {
|
|
174
|
-
if (!mission || !inputJson) {
|
|
175
|
-
const usage = 'Usage: aivin plugin trigger "<mission>" \'<input JSON>\' (or: aivin plugin trigger -a "<prompt>")';
|
|
176
|
-
mission = await requireArg(mission, { prompt: 'Mission (why this run was triggered):', usage });
|
|
177
|
-
inputJson = await requireArg(inputJson, { prompt: 'Input (as a JSON string, e.g. {"text":"hello"}):', usage });
|
|
178
|
-
}
|
|
179
|
-
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) {
|
|
180
264
|
try {
|
|
181
265
|
body.arguments = JSON.parse(inputJson);
|
|
182
266
|
} catch (error) {
|
|
183
267
|
throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
|
|
184
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);
|
|
185
283
|
}
|
|
186
|
-
if (options.agent) body.agent_id = options.agent;
|
|
187
284
|
|
|
188
|
-
|
|
189
|
-
const apiKey = process.env.API_KEY;
|
|
190
|
-
if (!apiKey) {
|
|
191
|
-
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
192
|
-
}
|
|
193
|
-
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
285
|
+
if (options.agent) body.agent_id = options.agent;
|
|
194
286
|
// No client-side timeout here before meant a hung backend (or a genuinely stuck plugin - the
|
|
195
287
|
// server side already caps at MAX_DOCKER_TIMEOUT_MS/effectiveTimeout, but that's enforced on the
|
|
196
288
|
// backend, not by this CLI process) could leave `trigger` sitting forever with no feedback short
|
|
197
289
|
// of Ctrl+C. `AIVIN_TRIGGER_TIMEOUT_MS` overrides if 3 minutes isn't enough for a legitimately
|
|
198
290
|
// slow plugin.
|
|
199
291
|
const EXECUTE_TIMEOUT_MS = parseInt(process.env.AIVIN_TRIGGER_TIMEOUT_MS || '180000');
|
|
200
|
-
const WORKSPACE_LOOKUP_TIMEOUT_MS = 15000;
|
|
201
292
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
if (!workspaceId) {
|
|
213
|
-
throw new Error('No workspace found for this account. Pass --workspace <id>.');
|
|
214
|
-
}
|
|
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;
|
|
215
301
|
body.workspace_id = workspaceId;
|
|
216
302
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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
|
+
}
|
|
232
331
|
}
|
|
233
|
-
}
|
|
234
332
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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
|
+
}
|
|
238
352
|
|
|
239
|
-
let response;
|
|
240
|
-
try {
|
|
241
|
-
response = await withProgressSpinner(`🚀 Triggering ${entryLabel || entryId}`, progress.getCurrent, () =>
|
|
242
|
-
axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS }),
|
|
243
|
-
);
|
|
244
|
-
} catch (error) {
|
|
245
353
|
if (logWatcher?.subscribed) {
|
|
246
|
-
// Give trailing log lines from this failed call a moment to arrive before disconnecting.
|
|
247
354
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
248
355
|
}
|
|
249
356
|
logWatcher?.stop();
|
|
250
357
|
progress.stop();
|
|
251
|
-
const message = error.response?.data?.message || error.message;
|
|
252
|
-
throw new Error(`Trigger failed: ${message}`, { cause: error });
|
|
253
|
-
}
|
|
254
358
|
|
|
255
|
-
|
|
256
|
-
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
257
|
-
}
|
|
258
|
-
logWatcher?.stop();
|
|
259
|
-
progress.stop();
|
|
359
|
+
result = response.data ?? {};
|
|
260
360
|
|
|
261
|
-
|
|
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;
|
|
372
|
+
}
|
|
262
373
|
|
|
263
374
|
if (Array.isArray(result.processing_log) && result.processing_log.length) {
|
|
264
375
|
console.log(chalk.gray('\n--- Log ---'));
|
|
@@ -392,6 +503,12 @@ export async function streamPluginLogs(pluginId, options) {
|
|
|
392
503
|
console.error(chalk.red('❌'), `Connection failed: ${error.message}`);
|
|
393
504
|
stop();
|
|
394
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
|
+
});
|
|
395
512
|
});
|
|
396
513
|
}
|
|
397
514
|
|
|
@@ -509,10 +626,10 @@ export async function showPluginInfo(id, options) {
|
|
|
509
626
|
/**
|
|
510
627
|
* `aivin plugin ask "<mission>"` - the one-shot "just simulate the agent" mode: given a
|
|
511
628
|
* plain-language mission, it searches the plugin ecosystem the same relevance-ranked way the
|
|
512
|
-
* platform's own agent does to auto-select a plugin, picks the top match,
|
|
513
|
-
*
|
|
514
|
-
* Where `plugin search` + `plugin trigger --id <id
|
|
515
|
-
*
|
|
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.
|
|
516
633
|
*
|
|
517
634
|
* `--top <n>` (default 5) controls how many candidates are fetched so the runner-up(s) can be
|
|
518
635
|
* printed for context/debugging when the auto-pick looks wrong; only the #1 match is ever run.
|
|
@@ -552,7 +669,7 @@ export async function askPlugin(mission, options) {
|
|
|
552
669
|
}
|
|
553
670
|
console.log();
|
|
554
671
|
|
|
555
|
-
await triggerPlugin(mission, options.input, { ...options,
|
|
672
|
+
await triggerPlugin(mission, options.input, { ...options, id: chosen.id });
|
|
556
673
|
}
|
|
557
674
|
|
|
558
675
|
export function formatPluginListLine(plugin, isSelected) {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Khoá công khai ký bản phát hành CLI (Ed25519, 29/10/2026). Tự cập nhật chỉ cài bản có `SHA256SUMS.sig` ký bằng một khoá trong danh sách
|
|
3
|
+
* này — chiếm được trang tải (get.aivin.vn) cũng không đẩy được tệp chạy lạ xuống máy đã cài. Khoá bí mật KHÔNG nằm trên trang tải / CI
|
|
4
|
+
* (scripts/release-key.mjs tạo, scripts/sign-release.mjs ký). Đổi khoá: thêm khoá mới ở đây, phát hành một bản ký bằng khoá cũ, rồi mới ký
|
|
5
|
+
* bằng khoá mới; gỡ khoá cũ ở bản sau đó.
|
|
6
|
+
*/
|
|
7
|
+
export const RELEASE_PUBLIC_KEYS = Object.freeze([
|
|
8
|
+
{ id: '05b62965e1847716', key: 'QlThaBcc4Yl+ctV2MD+VuOOa0lu3yBxhiexprDarWHM=' },
|
|
9
|
+
]);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
|
|
4
|
+
|
|
5
|
+
export const REMOTE_ACTIVITY_LOG_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-activity.log');
|
|
6
|
+
const MAX_LOG_LINES = 500;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Ghi lại một hoạt động điều khiển từ xa vào nhật ký máy tính.
|
|
10
|
+
*/
|
|
11
|
+
export function logActivity(entry) {
|
|
12
|
+
try {
|
|
13
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
14
|
+
const line = JSON.stringify({
|
|
15
|
+
timestamp: new Date().toISOString(),
|
|
16
|
+
...entry,
|
|
17
|
+
}) + '\n';
|
|
18
|
+
|
|
19
|
+
fs.appendFileSync(REMOTE_ACTIVITY_LOG_FILE, line, 'utf8');
|
|
20
|
+
|
|
21
|
+
// Cắt tỉa nếu tập tin nhật ký vượt quá giới hạn
|
|
22
|
+
const content = fs.readFileSync(REMOTE_ACTIVITY_LOG_FILE, 'utf8');
|
|
23
|
+
const lines = content.trim().split('\n').filter(Boolean);
|
|
24
|
+
if (lines.length > MAX_LOG_LINES) {
|
|
25
|
+
const trimmed = lines.slice(-MAX_LOG_LINES).join('\n') + '\n';
|
|
26
|
+
fs.writeFileSync(REMOTE_ACTIVITY_LOG_FILE, trimmed, 'utf8');
|
|
27
|
+
}
|
|
28
|
+
} catch {
|
|
29
|
+
// Tránh để lỗi ghi nhật ký làm gián đoạn luồng chính
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Lấy danh sách các hoạt động gần đây nhất.
|
|
35
|
+
*/
|
|
36
|
+
export function getRecentLogs(limit = 50) {
|
|
37
|
+
try {
|
|
38
|
+
if (!fs.existsSync(REMOTE_ACTIVITY_LOG_FILE)) return [];
|
|
39
|
+
const content = fs.readFileSync(REMOTE_ACTIVITY_LOG_FILE, 'utf8');
|
|
40
|
+
const lines = content.trim().split('\n').filter(Boolean);
|
|
41
|
+
return lines
|
|
42
|
+
.slice(-Number(limit))
|
|
43
|
+
.map((line) => {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(line);
|
|
46
|
+
} catch {
|
|
47
|
+
return { message: line };
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
.reverse();
|
|
51
|
+
} catch {
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Xóa toàn bộ lịch sử hoạt động.
|
|
58
|
+
*/
|
|
59
|
+
export function clearLogs() {
|
|
60
|
+
try {
|
|
61
|
+
if (fs.existsSync(REMOTE_ACTIVITY_LOG_FILE)) {
|
|
62
|
+
fs.unlinkSync(REMOTE_ACTIVITY_LOG_FILE);
|
|
63
|
+
}
|
|
64
|
+
return { success: true };
|
|
65
|
+
} catch (err) {
|
|
66
|
+
throw new Error(`Không thể xóa nhật ký hoạt động: ${err.message}`);
|
|
67
|
+
}
|
|
68
|
+
}
|