@aivin-labs/cli 1.0.0
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 +214 -0
- package/bin/assets/aivin-icon.png +0 -0
- package/bin/cli.mjs +1256 -0
- package/bin/lib/auth.mjs +355 -0
- package/bin/lib/browserAutomation.mjs +575 -0
- package/bin/lib/codegen.mjs +858 -0
- package/bin/lib/connectors.mjs +217 -0
- package/bin/lib/context.mjs +149 -0
- package/bin/lib/deploy.mjs +350 -0
- package/bin/lib/mcpProxy.mjs +380 -0
- package/bin/lib/mission.mjs +68 -0
- package/bin/lib/missionStream.mjs +656 -0
- package/bin/lib/pluginTrigger.mjs +535 -0
- package/bin/lib/scaffold.mjs +653 -0
- package/bin/lib/store.mjs +204 -0
- package/bin/lib/tasks.mjs +345 -0
- package/bin/lib/util.mjs +40 -0
- package/bin/lib/workspace.mjs +280 -0
- package/docs/CHANGELOG.md +8 -0
- package/docs/CLI.md +1079 -0
- package/docs/GETTING_STARTED.md +234 -0
- package/package.json +59 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { io } from 'socket.io-client';
|
|
2
|
+
import chalk from 'chalk';
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import axios from 'axios';
|
|
6
|
+
import { flattenManifestFile } from '@aivin-labs/sdk';
|
|
7
|
+
import readline from 'readline';
|
|
8
|
+
import { requireArg } from './util.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Resolves which manifest entry `plugin trigger` should invoke: the `--func` match if given, the
|
|
12
|
+
* one-and-only entry for a single-function/single-entry plugin, or a clear error listing the
|
|
13
|
+
* choices for a multi-function plugin with no `--func` given.
|
|
14
|
+
*/
|
|
15
|
+
export function resolveTriggerEntry(manifest, funcOption) {
|
|
16
|
+
const entries = Array.isArray(manifest) ? manifest : [manifest];
|
|
17
|
+
if (funcOption) {
|
|
18
|
+
const entry = entries.find((m) => m.func === funcOption || m.name === funcOption || m.id === funcOption);
|
|
19
|
+
if (!entry) {
|
|
20
|
+
const known = entries.map((m) => `${m.name}${m.func ? ` [${m.func}]` : ''}`).join(', ');
|
|
21
|
+
throw new Error(`No entry matches "${funcOption}". Known: ${known}`);
|
|
22
|
+
}
|
|
23
|
+
return entry;
|
|
24
|
+
}
|
|
25
|
+
if (entries.length === 1) return entries[0];
|
|
26
|
+
const known = entries.map((m) => `${m.name} [${m.func}]`).join(', ');
|
|
27
|
+
throw new Error(`This is a multi-function plugin - pass --func <name> to pick one. Known: ${known}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Subscribes to a deployed plugin's live console output over the same Socket.IO channel
|
|
32
|
+
* `aivin plugin logs` uses (`subscribe-plugin-logs` / `plugin-log`), but returns as soon as
|
|
33
|
+
* subscribing settles (success OR denial) instead of running until Ctrl+C - meant to be opened
|
|
34
|
+
* right before a single `trigger` call and stopped right after, not to own the process lifetime.
|
|
35
|
+
*
|
|
36
|
+
* Subscribing is permission-scoped server-side to plugins you can see the container logs for
|
|
37
|
+
* (your own/org's deployments) - triggering a plugin from the public store that some other org
|
|
38
|
+
* owns will very likely have this come back `subscribed: false`. That's expected, not an error:
|
|
39
|
+
* the caller falls back to the REST result only, same as before `--watch-logs` existed.
|
|
40
|
+
*/
|
|
41
|
+
export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine }) {
|
|
42
|
+
// Explicit connect timeout (not just socket.io-client's own ~20s default) so `trigger
|
|
43
|
+
// --watch-logs` fails fast into "no live output" instead of leaving the whole command feeling
|
|
44
|
+
// stuck for a while first.
|
|
45
|
+
const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
|
|
46
|
+
let subscribed = false;
|
|
47
|
+
let denyReason;
|
|
48
|
+
|
|
49
|
+
await new Promise((resolve) => {
|
|
50
|
+
const giveUp = setTimeout(() => {
|
|
51
|
+
denyReason = 'timed out connecting';
|
|
52
|
+
resolve();
|
|
53
|
+
}, 8000);
|
|
54
|
+
socket.on('connect_error', (error) => {
|
|
55
|
+
clearTimeout(giveUp);
|
|
56
|
+
denyReason = error.message;
|
|
57
|
+
resolve();
|
|
58
|
+
});
|
|
59
|
+
socket.on('connect', () => {
|
|
60
|
+
socket.emit('subscribe-plugin-logs', { plugin_id: pluginId }, (ack) => {
|
|
61
|
+
clearTimeout(giveUp);
|
|
62
|
+
if (ack?.success) subscribed = true;
|
|
63
|
+
else denyReason = ack?.error || 'no permission to view this plugin\'s logs';
|
|
64
|
+
resolve();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
if (subscribed) socket.on('plugin-log', onLine);
|
|
70
|
+
return { subscribed, denyReason, stop: () => socket.disconnect() };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* `aivin plugin trigger` - invokes an already-deployed plugin for real via the same
|
|
75
|
+
* `POST /plugins/execute` the platform's own Playground uses (PluginExecutionService.executePlugin
|
|
76
|
+
* on the backend), and prints the result. Two modes:
|
|
77
|
+
* - Direct: `<mission>` + `<input>` (a JSON string) sent as `purpose`/`arguments` as-is.
|
|
78
|
+
* - Auto (`-a/--auto <prompt>`): sends the prompt as `raw_text` instead - the backend's own
|
|
79
|
+
* `mapDataToSchema` maps it onto `manifest.input` for you (same mechanism the Playground's "Thử
|
|
80
|
+
* nghiệm" tab uses), same as pasting a free-text request into the platform's chat-style tester.
|
|
81
|
+
* `<input>` can still be given alongside `-a` for fields you want to force rather than let the AI
|
|
82
|
+
* infer - explicit `arguments` win over auto-mapped ones per field.
|
|
83
|
+
*
|
|
84
|
+
* By default this only surfaces what `/plugins/execute`'s response itself carries: `processing_log`
|
|
85
|
+
* (the mapping/execution stage messages, all at once, not the plugin's own internal console output)
|
|
86
|
+
* and `mapped_arguments` (only present when `-a` was used). Pass `--watch-logs` to also stream the
|
|
87
|
+
* plugin's own console.log/console.error output inline (subscribes right before the call, same feed
|
|
88
|
+
* `aivin plugin logs` tails) instead of needing a second terminal - see `watchPluginLogLines` for
|
|
89
|
+
* why this silently does nothing for a plugin you don't have log-view permission on.
|
|
90
|
+
*
|
|
91
|
+
* `--id <pluginId>` skips the local manifest.json lookup - required for plugins with no scaffolded
|
|
92
|
+
* project directory, e.g. proxy plugins built by `aivin mcp <url>`, which deploy straight from an
|
|
93
|
+
* in-memory scan and never write a manifest.json anywhere.
|
|
94
|
+
*
|
|
95
|
+
* `--save` writes this run's result to `.test/trigger/<timestamp>.json`; `--compare <file>` diffs
|
|
96
|
+
* the current run against a previously saved one - a lightweight way to turn ad-hoc "thử nghiệm"
|
|
97
|
+
* calls (your own plugin mid-development, or someone else's from the store) into a regression check,
|
|
98
|
+
* without needing the full `aivin test` deploy+smoke-test flow.
|
|
99
|
+
*/
|
|
100
|
+
export async function triggerPlugin(mission, inputJson, options) {
|
|
101
|
+
// Read + validate --compare's file upfront, before spending a real (possibly side-effecting,
|
|
102
|
+
// possibly billable) invocation on a typo'd path.
|
|
103
|
+
let compareAgainst;
|
|
104
|
+
if (options.compare) {
|
|
105
|
+
const comparePath = path.resolve(process.cwd(), options.compare);
|
|
106
|
+
if (!fs.existsSync(comparePath)) {
|
|
107
|
+
throw new Error(`--compare file not found: ${comparePath}`);
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
compareAgainst = JSON.parse(fs.readFileSync(comparePath, 'utf8'));
|
|
111
|
+
} catch (error) {
|
|
112
|
+
throw new Error(`--compare file isn't valid JSON (${comparePath}): ${error.message}`, { cause: error });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// `--id` bypasses the manifest.json lookup entirely - needed for plugins that were never
|
|
117
|
+
// scaffolded into a local directory (e.g. `aivin mcp <url>` deploys straight from a scan, no
|
|
118
|
+
// src/manifest.json on disk to resolve `entry` from). Without this, testing a freshly-converted
|
|
119
|
+
// MCP plugin from the Playground-equivalent flow was impossible outside the web app.
|
|
120
|
+
let entryId = options.id;
|
|
121
|
+
let entryLabel = options.id;
|
|
122
|
+
if (!entryId) {
|
|
123
|
+
const currentDir = process.cwd();
|
|
124
|
+
const manifestPath = path.join(currentDir, 'manifest.json');
|
|
125
|
+
if (!fs.existsSync(manifestPath)) {
|
|
126
|
+
throw new Error('manifest.json not found. Run this from your plugin\'s directory, or pass --id <pluginId>.');
|
|
127
|
+
}
|
|
128
|
+
const manifest = flattenManifestFile(JSON.parse(fs.readFileSync(manifestPath, 'utf8')));
|
|
129
|
+
const entry = resolveTriggerEntry(manifest, options.func);
|
|
130
|
+
entryId = entry.id;
|
|
131
|
+
entryLabel = `${entry.name}${entry.func ? ` [${entry.func}]` : ''}`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const body = { plugin_id: entryId };
|
|
135
|
+
if (options.auto) {
|
|
136
|
+
body.raw_text = options.auto;
|
|
137
|
+
body.purpose = mission || options.auto;
|
|
138
|
+
if (inputJson) {
|
|
139
|
+
try {
|
|
140
|
+
body.arguments = JSON.parse(inputJson);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
if (!mission || !inputJson) {
|
|
147
|
+
const usage = 'Usage: aivin plugin trigger "<mission>" \'<input JSON>\' (or: aivin plugin trigger -a "<prompt>")';
|
|
148
|
+
mission = await requireArg(mission, { prompt: 'Mission (why this run was triggered):', usage });
|
|
149
|
+
inputJson = await requireArg(inputJson, { prompt: 'Input (as a JSON string, e.g. {"text":"hello"}):', usage });
|
|
150
|
+
}
|
|
151
|
+
body.purpose = mission;
|
|
152
|
+
try {
|
|
153
|
+
body.arguments = JSON.parse(inputJson);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new Error(`Invalid JSON for <input>: ${error.message}`, { cause: error });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (options.agent) body.agent_id = options.agent;
|
|
159
|
+
|
|
160
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
161
|
+
const apiKey = process.env.API_KEY;
|
|
162
|
+
if (!apiKey) {
|
|
163
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
164
|
+
}
|
|
165
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
166
|
+
// No client-side timeout here before meant a hung backend (or a genuinely stuck plugin - the
|
|
167
|
+
// server side already caps at MAX_DOCKER_TIMEOUT_MS/effectiveTimeout, but that's enforced on the
|
|
168
|
+
// backend, not by this CLI process) could leave `trigger` sitting forever with no feedback short
|
|
169
|
+
// of Ctrl+C. `AIVIN_TRIGGER_TIMEOUT_MS` overrides if 3 minutes isn't enough for a legitimately
|
|
170
|
+
// slow plugin.
|
|
171
|
+
const EXECUTE_TIMEOUT_MS = parseInt(process.env.AIVIN_TRIGGER_TIMEOUT_MS || '180000');
|
|
172
|
+
const WORKSPACE_LOOKUP_TIMEOUT_MS = 15000;
|
|
173
|
+
|
|
174
|
+
let workspaceId = options.workspace;
|
|
175
|
+
if (!workspaceId) {
|
|
176
|
+
try {
|
|
177
|
+
const wsRes = await axios.get(`${serverUrl}/workspace/list`, { ...authHeaders, timeout: WORKSPACE_LOOKUP_TIMEOUT_MS });
|
|
178
|
+
const workspaces = Array.isArray(wsRes.data) ? wsRes.data : wsRes.data?.items || [];
|
|
179
|
+
workspaceId = workspaces[0]?.id || workspaces[0]?._id;
|
|
180
|
+
} catch (error) {
|
|
181
|
+
throw new Error(`Couldn't look up a workspace to run against (${error.message}). Pass --workspace <id>.`, { cause: error });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (!workspaceId) {
|
|
185
|
+
throw new Error('No workspace found for this account. Pass --workspace <id>.');
|
|
186
|
+
}
|
|
187
|
+
body.workspace_id = workspaceId;
|
|
188
|
+
|
|
189
|
+
let logWatcher;
|
|
190
|
+
if (options.watchLogs) {
|
|
191
|
+
logWatcher = await watchPluginLogLines(entryId, {
|
|
192
|
+
serverUrl,
|
|
193
|
+
apiKey,
|
|
194
|
+
onLine: (payload) => {
|
|
195
|
+
const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
|
|
196
|
+
const streamColor = payload.stream === 'stderr' ? chalk.red : payload.stream === 'system' ? chalk.yellow : chalk.gray;
|
|
197
|
+
console.log(chalk.gray(`[${time}]`), streamColor(payload.line));
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
if (logWatcher.subscribed) {
|
|
201
|
+
console.log(chalk.blue(`📡 Watching live console output for ${entryLabel || entryId}...`));
|
|
202
|
+
} else {
|
|
203
|
+
console.log(chalk.gray(`(--watch-logs: no live console output - ${logWatcher.denyReason})`));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
console.log(chalk.blue(`🚀 Triggering ${entryLabel || entryId}...`));
|
|
208
|
+
|
|
209
|
+
let response;
|
|
210
|
+
try {
|
|
211
|
+
response = await axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS });
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (logWatcher?.subscribed) {
|
|
214
|
+
// Give trailing log lines from this failed call a moment to arrive before disconnecting.
|
|
215
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
216
|
+
}
|
|
217
|
+
logWatcher?.stop();
|
|
218
|
+
const message = error.response?.data?.message || error.message;
|
|
219
|
+
throw new Error(`Trigger failed: ${message}`, { cause: error });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (logWatcher?.subscribed) {
|
|
223
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
224
|
+
}
|
|
225
|
+
logWatcher?.stop();
|
|
226
|
+
|
|
227
|
+
const result = response.data ?? {};
|
|
228
|
+
|
|
229
|
+
if (Array.isArray(result.processing_log) && result.processing_log.length) {
|
|
230
|
+
console.log(chalk.gray('\n--- Log ---'));
|
|
231
|
+
for (const line of result.processing_log) {
|
|
232
|
+
const icon = line.status === 'error' ? chalk.red('✗') : chalk.gray('·');
|
|
233
|
+
console.log(`${icon} ${line.message}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (result.mapped_arguments) {
|
|
238
|
+
console.log(chalk.gray('\n--- Auto-mapped input ---'));
|
|
239
|
+
console.log(JSON.stringify(result.mapped_arguments, null, 2));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const status = String(result.status || '').toLowerCase();
|
|
243
|
+
const ok = ['success', 'waiting', 'needs_auth', 'hil_timeout'].includes(status) || result.status === undefined;
|
|
244
|
+
const resultLabel = `--- Result: ${result.status || 'unknown'} ---`;
|
|
245
|
+
console.log(ok ? chalk.green(`\n${resultLabel}`) : chalk.red(`\n${resultLabel}`));
|
|
246
|
+
if (result.message) console.log(chalk.gray(`Message: ${result.message}`));
|
|
247
|
+
if (result.error_code) console.log(chalk.gray(`Error code: ${result.error_code}`));
|
|
248
|
+
console.log(JSON.stringify(result.data ?? null, null, 2));
|
|
249
|
+
|
|
250
|
+
if (compareAgainst) {
|
|
251
|
+
printTriggerDiff(compareAgainst.result ?? {}, result);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (options.save) {
|
|
255
|
+
const currentDir = process.cwd();
|
|
256
|
+
const dir = path.join(currentDir, '.test', 'trigger');
|
|
257
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
258
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
259
|
+
const savePath = path.join(dir, `${timestamp}.json`);
|
|
260
|
+
fs.writeFileSync(
|
|
261
|
+
savePath,
|
|
262
|
+
JSON.stringify({ plugin_id: entryId, mission: body.purpose, arguments: body.arguments, result }, null, 2),
|
|
263
|
+
);
|
|
264
|
+
console.log(chalk.gray(`\nSaved: ${path.relative(currentDir, savePath)} (--compare ${path.relative(currentDir, savePath)} next time)`));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!ok) process.exitCode = 1;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Prints a before/after summary for `trigger --compare <file>` - status changes are the headline
|
|
272
|
+
* (a plugin that used to succeed now failing, or vice versa, is the actual regression signal most
|
|
273
|
+
* of the time), full data payloads only get dumped when they actually differ so an unchanged
|
|
274
|
+
* comparison stays a two-line "nothing moved" instead of two walls of identical JSON.
|
|
275
|
+
*/
|
|
276
|
+
export function printTriggerDiff(oldResult, newResult) {
|
|
277
|
+
console.log(chalk.gray('\n--- Compare ---'));
|
|
278
|
+
|
|
279
|
+
const oldStatus = oldResult.status ?? 'unknown';
|
|
280
|
+
const newStatus = newResult.status ?? 'unknown';
|
|
281
|
+
if (oldStatus === newStatus) {
|
|
282
|
+
console.log(chalk.gray(`Status: ${newStatus} (unchanged)`));
|
|
283
|
+
} else {
|
|
284
|
+
console.log(chalk.yellow(`Status: ${oldStatus} → ${newStatus} (CHANGED)`));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const oldData = JSON.stringify(oldResult.data ?? null, null, 2);
|
|
288
|
+
const newData = JSON.stringify(newResult.data ?? null, null, 2);
|
|
289
|
+
if (oldData === newData) {
|
|
290
|
+
console.log(chalk.gray('Data: unchanged'));
|
|
291
|
+
} else {
|
|
292
|
+
console.log(chalk.yellow('Data: CHANGED'));
|
|
293
|
+
console.log(chalk.gray(' --- before ---'));
|
|
294
|
+
console.log(oldData.split('\n').map((l) => ` ${l}`).join('\n'));
|
|
295
|
+
console.log(chalk.gray(' --- after ---'));
|
|
296
|
+
console.log(newData.split('\n').map((l) => ` ${l}`).join('\n'));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* `aivin plugin logs [pluginId]` - tails a deployed plugin's own container stdout/stderr live, over
|
|
302
|
+
* the same Socket.IO channel the platform's own Playground log panel uses (subscribe-plugin-logs /
|
|
303
|
+
* plugin-log, see src/base/SocketIO.ts on the backend). `pluginId` defaults to the current
|
|
304
|
+
* directory's manifest.json id (like `plugin trigger`'s `--func` resolution), so `aivin plugin logs`
|
|
305
|
+
* with no args works from inside a plugin's own project directory.
|
|
306
|
+
*/
|
|
307
|
+
export async function streamPluginLogs(pluginId, options) {
|
|
308
|
+
let resolvedId = pluginId;
|
|
309
|
+
if (!resolvedId) {
|
|
310
|
+
const manifestPath = path.join(process.cwd(), 'manifest.json');
|
|
311
|
+
if (!fs.existsSync(manifestPath)) {
|
|
312
|
+
throw new Error('No pluginId given and manifest.json not found. Pass a pluginId or run from your plugin\'s directory.');
|
|
313
|
+
}
|
|
314
|
+
const manifest = flattenManifestFile(JSON.parse(fs.readFileSync(manifestPath, 'utf8')));
|
|
315
|
+
resolvedId = resolveTriggerEntry(manifest, options.func).id;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
319
|
+
const apiKey = process.env.API_KEY;
|
|
320
|
+
if (!apiKey) {
|
|
321
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
console.log(chalk.blue(`📡 Watching live logs for ${resolvedId}... (Ctrl+C to stop)\n`));
|
|
325
|
+
|
|
326
|
+
const socket = io(serverUrl, {
|
|
327
|
+
auth: { token: apiKey || 'dev-token' },
|
|
328
|
+
transports: ['websocket'],
|
|
329
|
+
reconnection: true,
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
const streamColor = (stream) => (stream === 'stderr' ? chalk.red : stream === 'system' ? chalk.yellow : chalk.gray);
|
|
333
|
+
|
|
334
|
+
await new Promise((resolve) => {
|
|
335
|
+
let settled = false;
|
|
336
|
+
const stop = () => {
|
|
337
|
+
if (settled) return;
|
|
338
|
+
settled = true;
|
|
339
|
+
socket.disconnect();
|
|
340
|
+
process.off('SIGINT', stop);
|
|
341
|
+
resolve();
|
|
342
|
+
};
|
|
343
|
+
process.on('SIGINT', stop);
|
|
344
|
+
|
|
345
|
+
socket.on('connect', () => {
|
|
346
|
+
socket.emit('subscribe-plugin-logs', { plugin_id: resolvedId }, (ack) => {
|
|
347
|
+
if (!ack?.success) {
|
|
348
|
+
console.error(chalk.red('❌'), `Couldn't subscribe: ${ack?.error || 'unknown error'}`);
|
|
349
|
+
stop();
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
socket.on('plugin-log', (payload) => {
|
|
354
|
+
const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
|
|
355
|
+
console.log(chalk.gray(`[${time}]`), streamColor(payload.stream)(payload.line));
|
|
356
|
+
});
|
|
357
|
+
socket.on('connect_error', (error) => {
|
|
358
|
+
console.error(chalk.red('❌'), `Connection failed: ${error.message}`);
|
|
359
|
+
stop();
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export async function searchPlugins(query, options) {
|
|
365
|
+
const serverUrl = process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
|
|
366
|
+
const apiKey = process.env.API_KEY;
|
|
367
|
+
if (!apiKey) {
|
|
368
|
+
console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
|
|
369
|
+
}
|
|
370
|
+
const authHeaders = { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
|
|
371
|
+
|
|
372
|
+
const params = { query };
|
|
373
|
+
if (options.workspace) params.workspace_id = options.workspace;
|
|
374
|
+
if (options.limit) params.limit = options.limit;
|
|
375
|
+
|
|
376
|
+
let response;
|
|
377
|
+
try {
|
|
378
|
+
response = await axios.get(`${serverUrl}/plugins/search`, { ...authHeaders, params });
|
|
379
|
+
} catch (error) {
|
|
380
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
381
|
+
throw new Error(`Search failed: ${message}`, { cause: error });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// `?limit`/`?page` given -> { items, total, ... } (paged); otherwise a bare array (the same
|
|
385
|
+
// relevance-ranked lookup the platform's own agent uses to auto-select a plugin for a mission).
|
|
386
|
+
const data = response.data;
|
|
387
|
+
const results = Array.isArray(data) ? data : data?.items || [];
|
|
388
|
+
|
|
389
|
+
if (results.length === 0) {
|
|
390
|
+
console.log(chalk.yellow(`No plugins found matching "${query}".`));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Interactive browser needs a real terminal to read raw keypresses - fall back to a flat
|
|
395
|
+
// print for scripts/CI or when the user explicitly asks for it with --plain.
|
|
396
|
+
if (process.stdout.isTTY && process.stdin.isTTY && !options.plain) {
|
|
397
|
+
await browseResults(results, `Found ${results.length} plugin(s) matching "${query}":\n`, formatPluginListLine, formatPluginDetail);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
console.log(chalk.blue(`Found ${results.length} plugin(s) matching "${query}":\n`));
|
|
402
|
+
for (const plugin of results) {
|
|
403
|
+
console.log(chalk.bold(plugin.name || plugin.id) + chalk.gray(` (${plugin.id})`));
|
|
404
|
+
if (plugin.description) console.log(` ${plugin.description}`);
|
|
405
|
+
if (plugin.version) console.log(chalk.gray(` v${plugin.version}`));
|
|
406
|
+
console.log();
|
|
407
|
+
}
|
|
408
|
+
console.log(
|
|
409
|
+
chalk.gray(
|
|
410
|
+
`Call one from your own plugin with: import { call } from '@aivin-labs/sdk'; await call('<plugin_id>', params).`,
|
|
411
|
+
),
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function formatPluginListLine(plugin, isSelected) {
|
|
416
|
+
const marker = isSelected ? chalk.cyan('❯ ') : ' ';
|
|
417
|
+
const label = plugin.name || plugin.id;
|
|
418
|
+
const name = isSelected ? chalk.bold.cyan(label) : label;
|
|
419
|
+
const badge = plugin.is_official ? chalk.green(' ✓') : '';
|
|
420
|
+
return `${marker}${name}${badge}${chalk.gray(` (${plugin.id})`)}`;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
export function trustBadge(plugin) {
|
|
424
|
+
if (plugin.is_official) return chalk.green('✓ official');
|
|
425
|
+
if (plugin.verification_status === 'VERIFIED' || plugin.is_verified) return chalk.cyan('✓ verified');
|
|
426
|
+
return chalk.yellow('community (unverified)');
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export function formatPluginDetail(plugin) {
|
|
430
|
+
const lines = [];
|
|
431
|
+
lines.push(chalk.bold.cyan(plugin.name || plugin.id) + ' ' + trustBadge(plugin));
|
|
432
|
+
lines.push(chalk.gray(plugin.id));
|
|
433
|
+
if (plugin.version) lines.push(`${chalk.gray('version')} v${plugin.version}`);
|
|
434
|
+
if (plugin.author) lines.push(`${chalk.gray('author')} ${plugin.author}`);
|
|
435
|
+
if (plugin.type) lines.push(`${chalk.gray('type')} ${plugin.type}`);
|
|
436
|
+
if (typeof plugin.rating === 'number') lines.push(`${chalk.gray('rating')} ${plugin.rating.toFixed(1)}/5`);
|
|
437
|
+
if (typeof plugin._similarity === 'number') {
|
|
438
|
+
lines.push(`${chalk.gray('match')} ${(plugin._similarity * 100).toFixed(0)}%`);
|
|
439
|
+
}
|
|
440
|
+
if (Array.isArray(plugin.capabilities) && plugin.capabilities.length > 0) {
|
|
441
|
+
lines.push(`${chalk.gray('capabilities')} ${plugin.capabilities.join(', ')}`);
|
|
442
|
+
}
|
|
443
|
+
// `initable`: input fields the AI can't fill on its own (API key, token, secret, base_url...)
|
|
444
|
+
// - the user has to configure them once before this plugin can run.
|
|
445
|
+
if (Array.isArray(plugin.initable) && plugin.initable.length > 0) {
|
|
446
|
+
lines.push(chalk.yellow(`⚠ needs setup first: ${plugin.initable.join(', ')}`));
|
|
447
|
+
}
|
|
448
|
+
// `connection_id`: this plugin is bound to a workspace connector (OAuth-based) - the user has
|
|
449
|
+
// to log in to that connector before the plugin can run, separate from `initable`'s plain
|
|
450
|
+
// credential fields.
|
|
451
|
+
if (plugin.connection_id) {
|
|
452
|
+
lines.push(chalk.yellow(`⚠ requires logging in to a connector (${plugin.connection_id}) first`));
|
|
453
|
+
}
|
|
454
|
+
if (plugin.description) lines.push(`\n${plugin.description}`);
|
|
455
|
+
if (plugin.input) lines.push(`\n${chalk.gray('input schema')}\n${JSON.stringify(plugin.input, null, 2)}`);
|
|
456
|
+
if (plugin.output) lines.push(`\n${chalk.gray('output schema')}\n${JSON.stringify(plugin.output, null, 2)}`);
|
|
457
|
+
lines.push(
|
|
458
|
+
chalk.gray(
|
|
459
|
+
`\nCall it with: import { call } from '@aivin-labs/sdk'; await call('${plugin.id}', params).`,
|
|
460
|
+
),
|
|
461
|
+
);
|
|
462
|
+
return lines.join('\n');
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Simple raw-keypress list/detail browser: ↑/↓ to move, space/enter to open an item's detail
|
|
466
|
+
// view, esc/backspace to go back to the listing, q/ctrl+c to exit. No extra deps - built on
|
|
467
|
+
// node's own readline keypress events since inquirer's prompts don't support this drill-down.
|
|
468
|
+
// Generic over what's being browsed (plugins, connectors, ...) via the format callbacks.
|
|
469
|
+
export function browseResults(results, headerText, formatLine, formatDetail) {
|
|
470
|
+
return new Promise((resolve) => {
|
|
471
|
+
let index = 0;
|
|
472
|
+
let mode = 'list'; // 'list' | 'detail'
|
|
473
|
+
|
|
474
|
+
const render = () => {
|
|
475
|
+
// console.clear() no-ops on some Windows TTY hosts (older PowerShell console, plain
|
|
476
|
+
// cmd.exe) - writing the cursor-reset + clear-down sequence directly is what TUI libs
|
|
477
|
+
// like blessed/ink do and works consistently across terminals.
|
|
478
|
+
readline.cursorTo(process.stdout, 0, 0);
|
|
479
|
+
readline.clearScreenDown(process.stdout);
|
|
480
|
+
if (mode === 'list') {
|
|
481
|
+
console.log(chalk.blue(headerText));
|
|
482
|
+
for (let i = 0; i < results.length; i++) {
|
|
483
|
+
console.log(formatLine(results[i], i === index));
|
|
484
|
+
}
|
|
485
|
+
console.log(chalk.gray('\n↑/↓ move space/enter view details q quit'));
|
|
486
|
+
} else {
|
|
487
|
+
console.log(formatDetail(results[index]));
|
|
488
|
+
console.log(chalk.gray('\nesc/backspace back q quit'));
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const onKeypress = (str, key) => {
|
|
493
|
+
if (!key) return;
|
|
494
|
+
if (key.ctrl && key.name === 'c') {
|
|
495
|
+
cleanup();
|
|
496
|
+
process.exit(0);
|
|
497
|
+
}
|
|
498
|
+
if (mode === 'list') {
|
|
499
|
+
if (key.name === 'up') {
|
|
500
|
+
index = (index - 1 + results.length) % results.length;
|
|
501
|
+
render();
|
|
502
|
+
} else if (key.name === 'down') {
|
|
503
|
+
index = (index + 1) % results.length;
|
|
504
|
+
render();
|
|
505
|
+
} else if (key.name === 'return' || key.name === 'space' || str === ' ') {
|
|
506
|
+
mode = 'detail';
|
|
507
|
+
render();
|
|
508
|
+
} else if (key.name === 'q' || key.name === 'escape') {
|
|
509
|
+
cleanup();
|
|
510
|
+
resolve();
|
|
511
|
+
}
|
|
512
|
+
} else {
|
|
513
|
+
if (key.name === 'escape' || key.name === 'backspace') {
|
|
514
|
+
mode = 'list';
|
|
515
|
+
render();
|
|
516
|
+
} else if (key.name === 'q') {
|
|
517
|
+
cleanup();
|
|
518
|
+
resolve();
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
const cleanup = () => {
|
|
524
|
+
process.stdin.setRawMode(false);
|
|
525
|
+
process.stdin.pause();
|
|
526
|
+
process.stdin.removeListener('keypress', onKeypress);
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
readline.emitKeypressEvents(process.stdin);
|
|
530
|
+
process.stdin.setRawMode(true);
|
|
531
|
+
process.stdin.on('keypress', onKeypress);
|
|
532
|
+
process.stdin.resume();
|
|
533
|
+
render();
|
|
534
|
+
});
|
|
535
|
+
}
|