@aivin-labs/cli 1.0.4 ā 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.mjs +12 -7
- package/bin/lib/browserTui.mjs +6 -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 +84 -20
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +32 -1
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +25 -0
- package/package.json +1 -1
|
@@ -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) {
|
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
|
-
|
|
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
|
|
package/bin/lib/tasks.mjs
CHANGED
|
@@ -161,10 +161,26 @@ export async function updateTaskById(id, options) {
|
|
|
161
161
|
console.log(chalk.gray(` Status: ${task.status}`));
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
|
|
164
|
+
// ā
FIX: had no confirmation at all before - unlike every other destructive command in this CLI
|
|
165
|
+
// (`plugin delete`, `pluginstore rm`/`rm-node`), a typo'd id here deleted immediately with nothing
|
|
166
|
+
// to catch it. Same `-y/--yes` escape hatch for scripts/CI as those commands.
|
|
167
|
+
export async function deleteTaskById(id, options = {}) {
|
|
165
168
|
const serverUrl = missionServerUrl();
|
|
166
169
|
const authHeaders = missionAuthHeaders();
|
|
167
170
|
|
|
171
|
+
if (!options.yes) {
|
|
172
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
173
|
+
throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
|
|
174
|
+
}
|
|
175
|
+
const { confirm } = await inquirer.prompt([
|
|
176
|
+
{ type: 'confirm', name: 'confirm', message: `Delete task "${id}"? This can't be undone.`, default: false },
|
|
177
|
+
]);
|
|
178
|
+
if (!confirm) {
|
|
179
|
+
console.log(chalk.gray('Cancelled.'));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
168
184
|
try {
|
|
169
185
|
await axios.delete(`${serverUrl}/task/${id}/delete`, authHeaders);
|
|
170
186
|
} catch (error) {
|
|
@@ -175,6 +191,23 @@ export async function deleteTaskById(id) {
|
|
|
175
191
|
console.log(chalk.green(`ā
Task ${id} deleted.`));
|
|
176
192
|
}
|
|
177
193
|
|
|
194
|
+
/**
|
|
195
|
+
* Pure assembly of `POST /task/create`'s body, split out of createTask() so it's unit-testable
|
|
196
|
+
* without stubbing axios/inquirer. Backend's TaskService._sanitizeCreateTaskInput whitelists
|
|
197
|
+
* `description`, not `content` - sending the wrong key here used to look like success (200 + a
|
|
198
|
+
* task id back) while silently dropping the user's actual text, which is exactly the kind of drift
|
|
199
|
+
* a regression test on this function's output shape catches going forward.
|
|
200
|
+
*/
|
|
201
|
+
export function buildCreateTaskPayload(description, workspaceId, options = {}) {
|
|
202
|
+
return {
|
|
203
|
+
title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
|
|
204
|
+
description,
|
|
205
|
+
workspace_id: workspaceId,
|
|
206
|
+
project_id: options.project,
|
|
207
|
+
assign_id: options.assignee,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
178
211
|
export async function createTask(description, options) {
|
|
179
212
|
const serverUrl = missionServerUrl();
|
|
180
213
|
const authHeaders = missionAuthHeaders();
|
|
@@ -188,13 +221,7 @@ export async function createTask(description, options) {
|
|
|
188
221
|
try {
|
|
189
222
|
response = await axios.post(
|
|
190
223
|
`${serverUrl}/task/create`,
|
|
191
|
-
|
|
192
|
-
title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
|
|
193
|
-
content: description,
|
|
194
|
-
workspace_id: workspace.id || workspace._id,
|
|
195
|
-
project_id: options.project,
|
|
196
|
-
assign_id: options.assignee,
|
|
197
|
-
},
|
|
224
|
+
buildCreateTaskPayload(description, workspace.id || workspace._id, options),
|
|
198
225
|
authHeaders,
|
|
199
226
|
);
|
|
200
227
|
} catch (error) {
|
|
@@ -336,9 +363,26 @@ export async function updateProjectCmd(projectId, options) {
|
|
|
336
363
|
console.log(chalk.green(`ā
Project ${projectId} updated.`));
|
|
337
364
|
}
|
|
338
365
|
|
|
366
|
+
// ā
FIX: had no confirmation at all before, and deleting a project is more consequential than
|
|
367
|
+
// deleting a single task (its tasks go with it) - same missing-protection issue as deleteTaskById
|
|
368
|
+
// above, same `-y/--yes` fix.
|
|
339
369
|
export async function deleteProjectCmd(projectId, options) {
|
|
340
370
|
const serverUrl = missionServerUrl();
|
|
341
371
|
const authHeaders = missionAuthHeaders();
|
|
372
|
+
|
|
373
|
+
if (!options.yes) {
|
|
374
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
375
|
+
throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
|
|
376
|
+
}
|
|
377
|
+
const { confirm } = await inquirer.prompt([
|
|
378
|
+
{ type: 'confirm', name: 'confirm', message: `Delete project "${projectId}"? Its tasks go with it. This can't be undone.`, default: false },
|
|
379
|
+
]);
|
|
380
|
+
if (!confirm) {
|
|
381
|
+
console.log(chalk.gray('Cancelled.'));
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
342
386
|
const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
|
|
343
387
|
await deleteProjectById(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, projectId });
|
|
344
388
|
console.log(chalk.green(`ā
Project ${projectId} deleted.`));
|