@aivin-labs/cli 1.0.0 → 1.0.4
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/LICENSE +21 -0
- package/README.md +2 -0
- package/bin/cli.mjs +111 -6
- package/bin/lib/browserAutomation.mjs +138 -65
- package/bin/lib/browserTui.mjs +245 -0
- package/bin/lib/connectors.mjs +1 -0
- package/bin/lib/deploy.mjs +66 -8
- package/bin/lib/mcpProxy.mjs +476 -83
- package/bin/lib/missionStream.mjs +13 -9
- package/bin/lib/pluginTrigger.mjs +226 -13
- package/bin/lib/store.mjs +111 -11
- package/bin/lib/util.mjs +26 -0
- package/docs/CLI.md +220 -25
- package/package.json +5 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aivin Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -141,6 +141,8 @@ examples, and behavior notes for each one.
|
|
|
141
141
|
| `aivin deploy` | Deploy the current plugin to your org |
|
|
142
142
|
| `aivin test` | Deploy to a non-production instance, then smoke-test it and save a report |
|
|
143
143
|
| `aivin plugin search <query>` | Search the platform's plugin ecosystem for something to reuse |
|
|
144
|
+
| `aivin plugin info <id>` | Show one plugin's detail directly by id, no search query needed |
|
|
145
|
+
| `aivin plugin ask [mission]` | One-shot: auto-pick the best-matching plugin for a mission and trigger it, like an agent would |
|
|
144
146
|
| `aivin plugin make <description>` | AI-generate `src/main.ts` from a natural-language description |
|
|
145
147
|
| `aivin plugin convert [hint]` | Turn an existing project in the current directory into a plugin |
|
|
146
148
|
| `aivin plugin trigger [mission] [input]` | Invoke a deployed plugin for real and print the result |
|
package/bin/cli.mjs
CHANGED
|
@@ -22,10 +22,10 @@ import { requireArg } from './lib/util.mjs';
|
|
|
22
22
|
import { readStdin, createFromJSON, createInteractive, validatePluginConfig, validateMcpProxyConfig } from './lib/scaffold.mjs';
|
|
23
23
|
import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
|
|
24
24
|
import { initInteractive, makePluginFromDescription, convertExistingProject } from './lib/codegen.mjs';
|
|
25
|
-
import { searchPlugins, streamPluginLogs, triggerPlugin } from './lib/pluginTrigger.mjs';
|
|
25
|
+
import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
|
|
26
26
|
import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors } from './lib/connectors.mjs';
|
|
27
|
-
import { attachStore, createStore, deleteStore, detachStore, listStores, setStoreEnabled } from './lib/store.mjs';
|
|
28
|
-
import { buildMcpManifest, createMcpProxyPlugin, scanAndPublishMcp } from './lib/mcpProxy.mjs';
|
|
27
|
+
import { attachStore, createStore, deleteStore, detachStore, listStores, removeNode, setStoreEnabled } from './lib/store.mjs';
|
|
28
|
+
import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches } from './lib/mcpProxy.mjs';
|
|
29
29
|
import {
|
|
30
30
|
saveGlobalApiKey,
|
|
31
31
|
browserLogin,
|
|
@@ -336,6 +336,7 @@ program
|
|
|
336
336
|
)
|
|
337
337
|
.option('--workspace <id>', 'Workspace id to run the smoke test against (default: auto-picks your first one)')
|
|
338
338
|
.option('--no-smoke-test', 'Only deploy - skip the generated-input invoke test and report')
|
|
339
|
+
.option('--verify-proxy', 'Also invoke MCP proxy entries for real (empty input) instead of skipping them - only use if you know the underlying tool(s) have no meaningful side effects')
|
|
339
340
|
.action(async (options) => {
|
|
340
341
|
try {
|
|
341
342
|
await deployPlugin({
|
|
@@ -343,6 +344,7 @@ program
|
|
|
343
344
|
label: 'Deploying to test instance',
|
|
344
345
|
smokeTest: options.smokeTest !== false,
|
|
345
346
|
workspaceOverride: options.workspace,
|
|
347
|
+
verifyProxy: options.verifyProxy,
|
|
346
348
|
});
|
|
347
349
|
} catch (error) {
|
|
348
350
|
console.error(chalk.red('❌'), error.message);
|
|
@@ -356,11 +358,16 @@ pluginCommand
|
|
|
356
358
|
.command('search [query]')
|
|
357
359
|
.description("Search the platform's plugin ecosystem for something to reuse instead of writing it yourself")
|
|
358
360
|
.option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
|
|
361
|
+
.option('--mcp <server_id>', 'List every tool/resource/prompt plugin generated from one MCP server (the id printed by `aivin mcp`/`aivin plugin search`, e.g. "modelcontextprotocol-servers-src-everything") instead of doing a text search')
|
|
362
|
+
.option('--store <store_id>', 'Restrict to plugins hosted on one self-hosted plugin store (the id printed by `aivin pluginstore ls`) - combines with the text query/--mcp, not a replacement for them')
|
|
359
363
|
.option('--limit <n>', 'Max results to show')
|
|
360
364
|
.option('--plain', 'Print a flat list instead of the interactive browser (for scripts/CI)')
|
|
361
365
|
.action(async (query, options) => {
|
|
362
366
|
try {
|
|
363
|
-
|
|
367
|
+
// --mcp is an exact-id lookup, not a text search - the query string is optional in that mode.
|
|
368
|
+
if (!options.mcp) {
|
|
369
|
+
query = await requireArg(query, { prompt: 'What are you looking for?', usage: 'Usage: aivin plugin search "<query>"' });
|
|
370
|
+
}
|
|
364
371
|
await searchPlugins(query, options);
|
|
365
372
|
} catch (error) {
|
|
366
373
|
console.error(chalk.red('❌'), error.message);
|
|
@@ -368,6 +375,39 @@ pluginCommand
|
|
|
368
375
|
}
|
|
369
376
|
});
|
|
370
377
|
|
|
378
|
+
pluginCommand
|
|
379
|
+
.command('info <id>')
|
|
380
|
+
.description("Show one plugin's detail (input/output schema, setup needs) directly by id, no search query needed")
|
|
381
|
+
.option('--workspace <id>', 'Restrict to plugins visible in this workspace (default: your whole org)')
|
|
382
|
+
.option('--plain', 'Print flat instead of the interactive browser, if falling back to closest-match results')
|
|
383
|
+
.action(async (id, options) => {
|
|
384
|
+
try {
|
|
385
|
+
await showPluginInfo(id, options);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
console.error(chalk.red('❌'), error.message);
|
|
388
|
+
process.exit(1);
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
pluginCommand
|
|
393
|
+
.command('ask [mission]')
|
|
394
|
+
.description('One-shot: search for the best-matching plugin for a plain-language mission and trigger it right away, like an agent would')
|
|
395
|
+
.option('--top <n>', 'How many candidates to consider/print as runner-up context (default 5) - only the top match is ever run')
|
|
396
|
+
.option('-i, --input <json>', 'Force specific fields (as JSON) alongside the auto-mapped ones - explicit fields win')
|
|
397
|
+
.option('--workspace <id>', 'Workspace id to search/run against (default: auto-picks your first one)')
|
|
398
|
+
.option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
|
|
399
|
+
.option('--watch-logs', "Also stream the chosen plugin's own live console output inline")
|
|
400
|
+
.option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
|
|
401
|
+
.option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
|
|
402
|
+
.action(async (mission, options) => {
|
|
403
|
+
try {
|
|
404
|
+
await askPlugin(mission, options);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
console.error(chalk.red('❌'), error.message);
|
|
407
|
+
process.exit(1);
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
|
|
371
411
|
pluginCommand
|
|
372
412
|
.command('make [description]')
|
|
373
413
|
.description('Generate src/main.ts from a natural-language business description')
|
|
@@ -431,6 +471,20 @@ pluginCommand
|
|
|
431
471
|
}
|
|
432
472
|
});
|
|
433
473
|
|
|
474
|
+
pluginCommand
|
|
475
|
+
.command('delete [id]')
|
|
476
|
+
.description("Delete a plugin you own, or every plugin from one batch deploy at once with --group <groupId> (e.g. everything `aivin mcp <url>` generated in one run - see the group_id it prints after deploying)")
|
|
477
|
+
.option('--group <groupId>', 'Delete every plugin sharing this group_id instead of a single plugin by id')
|
|
478
|
+
.option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
|
|
479
|
+
.action(async (id, options) => {
|
|
480
|
+
try {
|
|
481
|
+
await deletePluginCmd(id, options);
|
|
482
|
+
} catch (error) {
|
|
483
|
+
console.error(chalk.red('❌'), error.message);
|
|
484
|
+
process.exit(1);
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
|
|
434
488
|
const connectorCommand = program.command('connector').description('Register and discover reusable connectors (OAuth apps / credential-form namespaces)');
|
|
435
489
|
|
|
436
490
|
connectorCommand
|
|
@@ -591,6 +645,19 @@ pluginStoreCommand
|
|
|
591
645
|
}
|
|
592
646
|
});
|
|
593
647
|
|
|
648
|
+
pluginStoreCommand
|
|
649
|
+
.command('rm-node [store_id] [node_id]')
|
|
650
|
+
.description('Remove one node from a store (e.g. one that never came online) without touching its other nodes - org admin not required')
|
|
651
|
+
.option('-y, --yes', 'Skip the confirmation prompt')
|
|
652
|
+
.action(async (storeId, nodeId, options) => {
|
|
653
|
+
try {
|
|
654
|
+
await removeNode(storeId, nodeId, options);
|
|
655
|
+
} catch (error) {
|
|
656
|
+
console.error(chalk.red('❌'), error.message);
|
|
657
|
+
process.exit(1);
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
|
|
594
661
|
pluginStoreCommand
|
|
595
662
|
.command('detach')
|
|
596
663
|
.description("Remove THIS machine's pairing only (local file only, no BE call) - the running aivin-service picks it up automatically")
|
|
@@ -613,6 +680,7 @@ mcpCommand
|
|
|
613
680
|
.option('--publish', 'Deploy to your org, then submit for community store review (needs admin approval)')
|
|
614
681
|
.option('--private', 'Deploy to your org only - default')
|
|
615
682
|
.option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
|
|
683
|
+
.option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
|
|
616
684
|
.action(async (url, options) => {
|
|
617
685
|
try {
|
|
618
686
|
url = await requireArg(url, {
|
|
@@ -641,8 +709,10 @@ mcpCommand
|
|
|
641
709
|
.option('--description <description>', 'Plugin description')
|
|
642
710
|
.option(
|
|
643
711
|
'--auth-secret-key <key>',
|
|
644
|
-
'Name of the workspace secret to use as the
|
|
712
|
+
'Name of the workspace secret to use as the token/credential, if the MCP server needs auth',
|
|
645
713
|
)
|
|
714
|
+
.option('--auth-type <type>', 'auth_type value to send (default: "bearer" when --auth-secret-key is set) - check your backend for which values it supports')
|
|
715
|
+
.option('--connector <id>', "Existing connector id for this plugin's connection_id (readiness/\"needs login\" display only - does NOT inject anything into the running MCP server; run with no flags for the interactive per-variable auth setup that actually does)")
|
|
646
716
|
.action(async (name, options) => {
|
|
647
717
|
try {
|
|
648
718
|
name = await requireArg(name, { prompt: 'Plugin name (lowercase letters, numbers, hyphens):', usage: 'Usage: aivin mcp create <name>' });
|
|
@@ -653,6 +723,41 @@ mcpCommand
|
|
|
653
723
|
}
|
|
654
724
|
});
|
|
655
725
|
|
|
726
|
+
mcpCommand
|
|
727
|
+
.command('watch [url]')
|
|
728
|
+
.description('Watch a GitHub repo/branch and auto-rescan+resync its plugins when the branch updates (checked server-side every ~5 min, no CLI process needs to stay running)')
|
|
729
|
+
.option('--branch <name>', "Branch to watch (default: the repo's default branch)")
|
|
730
|
+
.option('--list', 'List your watched repos instead of registering a new one')
|
|
731
|
+
.action(async (url, options) => {
|
|
732
|
+
try {
|
|
733
|
+
if (options.list) {
|
|
734
|
+
await listMcpWatches();
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
url = await requireArg(url, {
|
|
738
|
+
prompt: 'GitHub repo URL to watch:',
|
|
739
|
+
usage: 'Usage: aivin mcp watch <url> [--branch <name>] | aivin mcp watch --list',
|
|
740
|
+
});
|
|
741
|
+
await registerMcpWatch(url, options);
|
|
742
|
+
} catch (error) {
|
|
743
|
+
console.error(chalk.red('❌'), error.message);
|
|
744
|
+
process.exit(1);
|
|
745
|
+
}
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
mcpCommand
|
|
749
|
+
.command('unwatch <url>')
|
|
750
|
+
.description('Stop auto-resyncing a previously watched repo')
|
|
751
|
+
.option('--branch <name>', 'Branch to unwatch (default: all watched branches for this repo)')
|
|
752
|
+
.action(async (url, options) => {
|
|
753
|
+
try {
|
|
754
|
+
await unwatchMcp(url, options);
|
|
755
|
+
} catch (error) {
|
|
756
|
+
console.error(chalk.red('❌'), error.message);
|
|
757
|
+
process.exit(1);
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
|
|
656
761
|
program
|
|
657
762
|
.command('login')
|
|
658
763
|
.argument('[baseUrl]', 'Server to log into (REST API base) - defaults to production (api.aivin.cloud). Pass a staging/self-hosted host to switch the machine\'s active context to it, e.g. `aivin login beta-api.aivin.vn`.')
|
|
@@ -1231,7 +1336,7 @@ projectCommand
|
|
|
1231
1336
|
}
|
|
1232
1337
|
});
|
|
1233
1338
|
|
|
1234
|
-
export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest };
|
|
1339
|
+
export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName };
|
|
1235
1340
|
|
|
1236
1341
|
// Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
|
|
1237
1342
|
// not when this module is imported (e.g. by tests) - otherwise Commander
|
|
@@ -8,7 +8,8 @@ import { randomUUID } from 'crypto';
|
|
|
8
8
|
import WSClient from 'ws';
|
|
9
9
|
import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive, createAgent, pullAgentIntoWorkspace } from './workspace.mjs';
|
|
10
10
|
import { parseApiKeyClient } from './auth.mjs';
|
|
11
|
-
import { guessStartUrl,
|
|
11
|
+
import { guessStartUrl, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
|
|
12
|
+
import { watchBrowserMission } from './browserTui.mjs';
|
|
12
13
|
|
|
13
14
|
// ── `aivin browser` default mode: drive the user's OWN local, already-running browser ──────────
|
|
14
15
|
//
|
|
@@ -345,8 +346,13 @@ export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, p
|
|
|
345
346
|
* to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
|
|
346
347
|
* `close()` disconnects both sides; the user's actual browser window is never touched beyond this
|
|
347
348
|
* one CDP connection, closing the tunnel just detaches Puppeteer server-side.
|
|
349
|
+
*
|
|
350
|
+
* `onUnexpectedClose(side)` fires when either leg drops WITHOUT `close()` having been called first
|
|
351
|
+
* (side is 'backend' or 'chrome') - lets the caller distinguish "network/tunnel died mid-mission"
|
|
352
|
+
* from "we're done, tearing down deliberately" (Ctrl+C, mission finished) without guessing from
|
|
353
|
+
* timing alone. Never fires after a deliberate `close()`.
|
|
348
354
|
*/
|
|
349
|
-
export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
|
|
355
|
+
export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl, { onUnexpectedClose } = {}) {
|
|
350
356
|
const tunnelId = randomUUID();
|
|
351
357
|
const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
|
|
352
358
|
|
|
@@ -355,19 +361,23 @@ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
|
|
|
355
361
|
const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
|
|
356
362
|
const toChrome = new WSClient(chromeWsUrl);
|
|
357
363
|
|
|
358
|
-
|
|
364
|
+
let deliberateClose = false;
|
|
365
|
+
|
|
366
|
+
const relay = (from, to, side) => {
|
|
359
367
|
from.on('message', (data, isBinary) => {
|
|
360
368
|
if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
|
|
361
369
|
});
|
|
362
370
|
from.on('close', () => {
|
|
363
371
|
if (to.readyState === WSClient.OPEN) to.close();
|
|
372
|
+
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
364
373
|
});
|
|
365
374
|
from.on('error', () => {
|
|
366
375
|
if (to.readyState === WSClient.OPEN) to.close();
|
|
376
|
+
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
367
377
|
});
|
|
368
378
|
};
|
|
369
|
-
relay(toBackend, toChrome);
|
|
370
|
-
relay(toChrome, toBackend);
|
|
379
|
+
relay(toBackend, toChrome, 'backend');
|
|
380
|
+
relay(toChrome, toBackend, 'chrome');
|
|
371
381
|
|
|
372
382
|
const ready = Promise.all([
|
|
373
383
|
new Promise((resolve, reject) => {
|
|
@@ -381,6 +391,7 @@ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
|
|
|
381
391
|
]);
|
|
382
392
|
|
|
383
393
|
const close = () => {
|
|
394
|
+
deliberateClose = true;
|
|
384
395
|
try { toBackend.close(); } catch { /* already closed */ }
|
|
385
396
|
try { toChrome.close(); } catch { /* already closed */ }
|
|
386
397
|
};
|
|
@@ -452,71 +463,114 @@ export async function runBrowserMissionLocal(mission, options) {
|
|
|
452
463
|
console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
|
|
453
464
|
console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
|
|
454
465
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
466
|
+
// Retry the local tunnel on an UNEXPECTED drop (flaky WiFi) - checkpoint-resume already exists
|
|
467
|
+
// server-side (AIBrowserCheckpointService, matches on tenant + exact mission text), so re-firing
|
|
468
|
+
// the SAME mission through a fresh tunnel just continues where it left off instead of restarting.
|
|
469
|
+
// Only worth doing when we're actually watching (options.watch !== false) - without the log
|
|
470
|
+
// stream there's no reliable signal for "did the mission already finish" vs "tunnel just dropped",
|
|
471
|
+
// so a single un-retried attempt (old behavior) is what happens when watch is disabled.
|
|
472
|
+
const MAX_TUNNEL_RETRIES = 3;
|
|
473
|
+
let interrupted = false;
|
|
474
|
+
let terminalReason; // 'success' | 'failed' | undefined (still unresolved / gave up watching)
|
|
475
|
+
let attempt = 0;
|
|
476
|
+
|
|
477
|
+
while (!interrupted) {
|
|
478
|
+
attempt++;
|
|
479
|
+
if (attempt > 1) {
|
|
480
|
+
// Chrome's CDP websocket URL can go stale after a drop, and the browser itself may have
|
|
481
|
+
// closed too (user closed the window) - re-probe rather than blindly reusing the old URL.
|
|
482
|
+
const reprobe = await probeLocalChromeDebugger(debugPort);
|
|
483
|
+
if (!reprobe.wsUrl) {
|
|
484
|
+
console.log(chalk.red(`\n❌ Mất kết nối và không tìm lại được ${preferredId || 'Chrome/Edge'} đang chạy ở cổng ${debugPort} - trình duyệt có thể đã bị đóng. Dừng lại đây (mission có thể vẫn đang chạy trên server - kiểm tra lại bằng \`aivin browser --view\` hoặc chạy lại lệnh này).`));
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
chromeWsUrl = reprobe.wsUrl;
|
|
488
|
+
console.log(chalk.yellow(`\n🔄 Tunnel bị rớt kết nối bất ngờ - đang thử lại (lần ${attempt - 1}/${MAX_TUNNEL_RETRIES})...`));
|
|
489
|
+
}
|
|
462
490
|
|
|
463
|
-
|
|
464
|
-
|
|
491
|
+
let unexpectedDrop = false;
|
|
492
|
+
const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl, {
|
|
493
|
+
onUnexpectedClose: () => { unexpectedDrop = true; },
|
|
494
|
+
});
|
|
495
|
+
try {
|
|
496
|
+
await tunnel.ready;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
tunnel.close();
|
|
499
|
+
if (attempt > MAX_TUNNEL_RETRIES) throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
|
|
500
|
+
console.log(chalk.yellow(`\n⚠️ Không mở được tunnel (${error.message}) - đang thử lại (lần ${attempt}/${MAX_TUNNEL_RETRIES})...`));
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
465
503
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
}
|
|
481
|
-
|
|
504
|
+
const sessionId = `browser-cli-${randomUUID()}`;
|
|
505
|
+
console.log(chalk.gray(` Session: ${sessionId}`));
|
|
506
|
+
|
|
507
|
+
// Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
|
|
508
|
+
// between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
|
|
509
|
+
// Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
|
|
510
|
+
// touched the browser connection yet (confirmed while testing this) - the cancel request is what
|
|
511
|
+
// actually gets it to stop at its next chance to check. The tab this mission was using stays open
|
|
512
|
+
// either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
|
|
513
|
+
const onSigint = () => {
|
|
514
|
+
if (interrupted) return;
|
|
515
|
+
interrupted = true;
|
|
516
|
+
console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
|
|
517
|
+
requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
|
|
518
|
+
console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
|
|
519
|
+
);
|
|
520
|
+
tunnel.close();
|
|
521
|
+
console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
|
|
522
|
+
};
|
|
523
|
+
process.on('SIGINT', onSigint);
|
|
524
|
+
|
|
525
|
+
// Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
|
|
526
|
+
// the mission ends), so the log watcher has to already be listening before/as it fires, not after.
|
|
527
|
+
const missionPromise = axios.post(
|
|
528
|
+
// `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
|
|
529
|
+
// AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
|
|
530
|
+
// by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
|
|
531
|
+
`${serverUrl}/plugins/ai-browser/execute-interactive`,
|
|
532
|
+
{
|
|
533
|
+
mission,
|
|
534
|
+
workspace_id: workspace.id || workspace._id,
|
|
535
|
+
agent_id: agentId,
|
|
536
|
+
session_id: sessionId,
|
|
537
|
+
data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
|
|
538
|
+
},
|
|
539
|
+
authHeaders,
|
|
540
|
+
);
|
|
541
|
+
const watchPromise = options.watch !== false
|
|
542
|
+
? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
|
|
543
|
+
: Promise.resolve(undefined);
|
|
482
544
|
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
{
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
const watchPromise = options.watch !== false
|
|
500
|
-
? streamBrowserMissionLog(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
|
|
501
|
-
: Promise.resolve();
|
|
545
|
+
try {
|
|
546
|
+
// execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
|
|
547
|
+
// comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
|
|
548
|
+
// browser.run() call did). The REAL outcome is whatever the log stream above already printed
|
|
549
|
+
// (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
|
|
550
|
+
const [, watchReason] = await Promise.all([missionPromise, watchPromise]);
|
|
551
|
+
terminalReason = watchReason;
|
|
552
|
+
} catch (error) {
|
|
553
|
+
if (!interrupted) {
|
|
554
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
555
|
+
throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
|
|
556
|
+
}
|
|
557
|
+
} finally {
|
|
558
|
+
process.off('SIGINT', onSigint);
|
|
559
|
+
tunnel.close();
|
|
560
|
+
}
|
|
502
561
|
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
//
|
|
506
|
-
//
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
512
|
-
throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
|
|
562
|
+
if (interrupted) break;
|
|
563
|
+
if (terminalReason === 'success' || terminalReason === 'failed') break; // genuine mission outcome - done
|
|
564
|
+
// options.watch === false (no signal at all) or watch gave up on its own (idle/connect_error,
|
|
565
|
+
// NOT a tunnel drop) - neither is worth blindly retrying; only retry on a confirmed tunnel drop.
|
|
566
|
+
if (!unexpectedDrop) break;
|
|
567
|
+
if (attempt > MAX_TUNNEL_RETRIES) {
|
|
568
|
+
console.log(chalk.red(`\n❌ Đã thử lại ${MAX_TUNNEL_RETRIES} lần nhưng tunnel vẫn liên tục rớt kết nối - dừng theo dõi. Mission có thể vẫn đang chạy trên server.`));
|
|
569
|
+
break;
|
|
513
570
|
}
|
|
514
|
-
} finally {
|
|
515
|
-
process.off('SIGINT', onSigint);
|
|
516
|
-
tunnel.close();
|
|
517
571
|
}
|
|
518
572
|
|
|
519
|
-
if (!interrupted) {
|
|
573
|
+
if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
|
|
520
574
|
console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
|
|
521
575
|
}
|
|
522
576
|
}
|
|
@@ -569,7 +623,26 @@ export async function runBrowserMissionRemote(mission, options) {
|
|
|
569
623
|
const threadId = result.data?.thread_id;
|
|
570
624
|
console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
|
|
571
625
|
|
|
572
|
-
|
|
573
|
-
|
|
626
|
+
// Same cooperative-cancel wiring as the local-mode path above (requestBrowserCancel is
|
|
627
|
+
// tenant-scoped, not session/thread-scoped, so it applies here unchanged) - without this, Ctrl+C
|
|
628
|
+
// only stopped streamBrowserMissionLog's own SIGINT handler, which just disconnects the log
|
|
629
|
+
// socket and returns; the mission itself kept running server-side with nothing telling it to stop.
|
|
630
|
+
let interrupted = false;
|
|
631
|
+
const onSigint = () => {
|
|
632
|
+
if (interrupted) return;
|
|
633
|
+
interrupted = true;
|
|
634
|
+
console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
|
|
635
|
+
requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
|
|
636
|
+
console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
|
|
637
|
+
);
|
|
638
|
+
};
|
|
639
|
+
process.on('SIGINT', onSigint);
|
|
640
|
+
|
|
641
|
+
try {
|
|
642
|
+
if (options.watch !== false && threadId) {
|
|
643
|
+
await watchBrowserMission(serverUrl, apiKey, threadId, tenantClient);
|
|
644
|
+
}
|
|
645
|
+
} finally {
|
|
646
|
+
process.off('SIGINT', onSigint);
|
|
574
647
|
}
|
|
575
648
|
}
|