dsh-apk-vm 0.12.4 → 0.13.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/CHANGELOG.md +126 -10
- package/CHANGELOG.zh-CN.md +191 -0
- package/README.md +188 -36
- package/client.js +358 -22
- package/cordis.patch.yml +56 -0
- package/docs/AGENTS.md +62 -12
- package/docs/PRIVACY.md +11 -1
- package/docs/RELEASING.md +11 -5
- package/index.js +389 -26
- package/lib/activity-log.js +22 -0
- package/lib/android.js +290 -2
- package/lib/autosetup.js +211 -13
- package/lib/http-owner.js +101 -10
- package/lib/instances.js +484 -11
- package/lib/jdk.js +90 -11
- package/lib/lease-store.js +67 -0
- package/lib/memory.js +272 -0
- package/lib/setup.js +444 -30
- package/lib/storage.js +125 -4
- package/lib/vm-ownership.js +233 -20
- package/package.json +7 -4
package/index.js
CHANGED
|
@@ -25,8 +25,8 @@ import { fileURLToPath } from 'node:url';
|
|
|
25
25
|
import { AndroidVm } from './lib/android.js';
|
|
26
26
|
import { InstanceManager } from './lib/instances.js';
|
|
27
27
|
import { defaultInstanceNamesPath } from './lib/instance-names.js';
|
|
28
|
-
import { OWNER_SCOPE, normalizeScope } from './lib/vm-ownership.js';
|
|
29
|
-
import { checkOwnerAccess, ownerFromHttp } from './lib/http-owner.js';
|
|
28
|
+
import { OWNER_SCOPE, VmLeaseConflict, normalizeScope } from './lib/vm-ownership.js';
|
|
29
|
+
import { TAKEOVER_HEADER, checkOwnerAccess, ownerFromHttp, takeoverFromHttp } from './lib/http-owner.js';
|
|
30
30
|
import { ScrcpySession, annexbToAvcc, CONTROL_MESSAGE_TYPE } from './lib/scrcpy.js';
|
|
31
31
|
import { detectEnvironment, createAvd, installSystemImage, installSdkPackages, bootstrapSdk, DEFAULT_SYSTEM_IMAGE } from './lib/setup.js';
|
|
32
32
|
import { createAutoSetup } from './lib/autosetup.js';
|
|
@@ -38,7 +38,15 @@ import { FlowRecorder } from './lib/flows.js';
|
|
|
38
38
|
import { normalizeCodebook, resolveControl, suggestFeatures } from './lib/control-codebook.js';
|
|
39
39
|
import { attachNodeImageFeatures } from './lib/image-features.js';
|
|
40
40
|
import { SkillStore, SkillRecorder, runSkill, normalizeSkill, skillSummary } from './lib/app-skills.js';
|
|
41
|
-
import {
|
|
41
|
+
import {
|
|
42
|
+
collectStorage,
|
|
43
|
+
cleanTempFiles,
|
|
44
|
+
cleanSnapshots,
|
|
45
|
+
cleanOrphanAvds,
|
|
46
|
+
cleanCorruptSnapshots,
|
|
47
|
+
cleanCrashDumps,
|
|
48
|
+
formatBytes,
|
|
49
|
+
} from './lib/storage.js';
|
|
42
50
|
import { buildApksFromAab, aabInfo, detectBundletool } from './lib/aab.js';
|
|
43
51
|
import { readHarFile, summarizeHar, filterHar, toCurl } from './lib/har.js';
|
|
44
52
|
import { runAssertions, compareScreenshot, createTestReport, reportMarkdown } from './lib/ui-tests.js';
|
|
@@ -70,7 +78,7 @@ const SCRCPY_JAR = path.join(PLUGIN_DIR, 'lib', 'vendor', 'scrcpy-server-v5.0.1.
|
|
|
70
78
|
*/
|
|
71
79
|
const AGENT_GUIDE_PATH = path.join(PLUGIN_DIR, 'docs', 'AGENTS.md');
|
|
72
80
|
// Single source of truth for the tool action enum (schema + early validation).
|
|
73
|
-
const TOOL_ACTIONS = Object.freeze(["info", "shell", "logcat", "getprop", "setprop", "packages", "install", "push", "pull", "reboot", "root", "force_stop", "clear_data", "uninstall", "rotate", "ui_dump", "inspect_ui", "proxy", "install_ca", "network", "record", "perf", "screenshot", "tap", "swipe", "long_press", "key", "text", "apk_info", "find_ui", "assert_text", "tap_text", "clipboard_get", "clipboard_set", "devices", "attach_device", "detach_device", "start", "stop", "list_instances", "create_instance", "rename_instance", "destroy_instance", "owner_status", "claim_vm", "release_vm", "flow_start", "flow_stop", "flow_list", "flow_replay", "storage", "clean_storage", "skill_list", "skill_get", "skill_save", "skill_delete", "skill_start", "skill_stop", "skill_cancel", "skill_run", "skill_codebook", "control_ui", "control_features", "control_codebook", "control_tap", "control_input", "control_long_press", "control_swipe", "control_assert", "control_wait", "control_launch", "webview", "tap_css", "tap_selector", "type_text", "wait_for", "env_snapshot", "env_restore", "adb", "guide"]);
|
|
81
|
+
const TOOL_ACTIONS = Object.freeze(["info", "shell", "logcat", "getprop", "setprop", "packages", "install", "push", "pull", "reboot", "root", "force_stop", "clear_data", "uninstall", "rotate", "ui_dump", "inspect_ui", "proxy", "install_ca", "network", "record", "perf", "screenshot", "tap", "swipe", "long_press", "key", "text", "apk_info", "find_ui", "assert_text", "tap_text", "clipboard_get", "clipboard_set", "devices", "attach_device", "detach_device", "start", "stop", "list_instances", "create_instance", "rename_instance", "destroy_instance", "owner_status", "claim_vm", "release_vm", "lock_vm", "unlock_vm", "flow_start", "flow_stop", "flow_list", "flow_replay", "storage", "clean_storage", "skill_list", "skill_get", "skill_save", "skill_delete", "skill_start", "skill_stop", "skill_cancel", "skill_run", "skill_codebook", "control_ui", "control_features", "control_codebook", "control_tap", "control_input", "control_long_press", "control_swipe", "control_assert", "control_wait", "control_launch", "webview", "tap_css", "tap_selector", "type_text", "wait_for", "env_snapshot", "env_restore", "adb", "guide"]);
|
|
74
82
|
|
|
75
83
|
|
|
76
84
|
let agentGuideCache;
|
|
@@ -121,6 +129,28 @@ function loadMediaSettings(dataRoot, cfg) {
|
|
|
121
129
|
}
|
|
122
130
|
}
|
|
123
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Optional AVD hardware profile ("lite" mode) for memory-constrained hosts.
|
|
134
|
+
* A null result means "standard": the existing defaults are kept untouched.
|
|
135
|
+
* InstanceManager normalizes the same setting for extra instances.
|
|
136
|
+
*/
|
|
137
|
+
const VM_PRESET_LITE = Object.freeze({
|
|
138
|
+
name: 'lite',
|
|
139
|
+
ramSizeMb: 1024,
|
|
140
|
+
cores: 2,
|
|
141
|
+
gpuMode: 'swiftshader_indirect',
|
|
142
|
+
frameFps: 1,
|
|
143
|
+
scrcpyMaxSize: 720,
|
|
144
|
+
scrcpyMaxFps: 30,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
function normalizeVmPreset(value) {
|
|
148
|
+
if (!value || value === 'standard') return null;
|
|
149
|
+
if (value === 'lite') return VM_PRESET_LITE;
|
|
150
|
+
if (typeof value === 'object' && !Array.isArray(value)) return { name: 'custom', ...value };
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
|
|
124
154
|
function isReady(vm) {
|
|
125
155
|
return vm && vm.state === 'ready';
|
|
126
156
|
}
|
|
@@ -329,6 +359,20 @@ export function apply(ctx, config = {}) {
|
|
|
329
359
|
const dataRoot = resolveRoots(ctx, cfg.roots)[0] || process.cwd();
|
|
330
360
|
const mediaSettings = loadMediaSettings(dataRoot, cfg);
|
|
331
361
|
const initialMedia = mediaLaunchOptions(mediaSettings);
|
|
362
|
+
// Lite mode is applied to the default VM as well: GPU + frame rate are part
|
|
363
|
+
// of the AndroidVm options (the AVD RAM/CPU profile is patched separately),
|
|
364
|
+
// while extra instances get the same profile from InstanceManager.
|
|
365
|
+
const vmPreset = normalizeVmPreset(cfg.vmPreset);
|
|
366
|
+
const presetGpuMode = vmPreset && typeof vmPreset.gpuMode === 'string' ? vmPreset.gpuMode : null;
|
|
367
|
+
const presetFrameFps = vmPreset && Number.isFinite(Number(vmPreset.frameFps)) ? Number(vmPreset.frameFps) : null;
|
|
368
|
+
// Operation-lock policy. enforcement: 'all' (default, hard block for every
|
|
369
|
+
// other client), 'agents' (other agents are blocked but the local panel can
|
|
370
|
+
// still operate), 'off' (locks are advisory and never block). control: 'all'
|
|
371
|
+
// (agents or the panel may lock/unlock) or 'user' (panel/user only).
|
|
372
|
+
const lockEnforcement = cfg.lockEnforcement === 'agents' || cfg.lockEnforcement === 'off'
|
|
373
|
+
? cfg.lockEnforcement
|
|
374
|
+
: 'all';
|
|
375
|
+
const lockControl = cfg.lockControl === 'user' ? 'user' : 'all';
|
|
332
376
|
const vm = new AndroidVm({
|
|
333
377
|
sdkRoot: cfg.sdkRoot || process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || undefined,
|
|
334
378
|
adbPath: cfg.adbPath || undefined,
|
|
@@ -343,7 +387,7 @@ export function apply(ctx, config = {}) {
|
|
|
343
387
|
apkRoots: Array.isArray(cfg.roots) ? cfg.roots : undefined,
|
|
344
388
|
bootTimeoutMs: cfg.bootTimeoutMs || undefined,
|
|
345
389
|
// Fast-boot strategy: host GPU + hypervisor detection + quick-boot snapshots.
|
|
346
|
-
gpuMode: cfg.gpuMode || undefined,
|
|
390
|
+
gpuMode: presetGpuMode || cfg.gpuMode || undefined,
|
|
347
391
|
accel: cfg.accel || undefined,
|
|
348
392
|
requireAccel: cfg.requireAccel !== false,
|
|
349
393
|
quickBoot: cfg.quickBoot !== false,
|
|
@@ -365,7 +409,20 @@ export function apply(ctx, config = {}) {
|
|
|
365
409
|
baseAvdName: cfg.avdName || 'dsh_apk',
|
|
366
410
|
namesFile: defaultInstanceNamesPath(dataRoot),
|
|
367
411
|
maxInstances: cfg.maxInstances || 3,
|
|
412
|
+
// Memory guard + optional lite hardware profile (see lib/memory.js).
|
|
413
|
+
vmPreset: cfg.vmPreset || 'standard',
|
|
414
|
+
memoryGuard: cfg.memoryGuard !== false,
|
|
415
|
+
hostReserveMb: cfg.hostReserveMb,
|
|
416
|
+
estimatedVmMb: cfg.estimatedVmMb,
|
|
417
|
+
memoryPressureReap: cfg.memoryPressureReap !== false,
|
|
368
418
|
gpuMode: cfg.gpuMode || 'host',
|
|
419
|
+
// Resident shared default VM: it is never released/deleted. After an
|
|
420
|
+
// idle period it suspends into a quick-boot snapshot, later it is
|
|
421
|
+
// marked stopped; any tool/panel/stream activity resumes it on demand.
|
|
422
|
+
defaultVm: vm,
|
|
423
|
+
sharedResident: cfg.sharedResident !== false,
|
|
424
|
+
sharedSuspendAfterMs: cfg.sharedSuspendAfterMs,
|
|
425
|
+
sharedStopAfterMs: cfg.sharedStopAfterMs,
|
|
369
426
|
snapshotName: cfg.snapshotName || 'default_boot',
|
|
370
427
|
scrcpyJarPath: SCRCPY_JAR,
|
|
371
428
|
scrcpyMaxSize: cfg.scrcpyMaxSize || 960,
|
|
@@ -373,6 +430,9 @@ export function apply(ctx, config = {}) {
|
|
|
373
430
|
scrcpyMaxFps: cfg.scrcpyMaxFps || 60,
|
|
374
431
|
idleTimeoutMs: cfg.instanceIdleMs || 15 * 60 * 1000,
|
|
375
432
|
leaseTtlMs: cfg.leaseTtlMs || 30 * 60 * 1000,
|
|
433
|
+
leaseReservationTtlMs: cfg.leaseReservationTtlMs || undefined,
|
|
434
|
+
// Dedicated (conversation/project) leases survive a plugin/DSH restart.
|
|
435
|
+
leasesFile: path.join(dataRoot, '.apk-vm', 'leases.json'),
|
|
376
436
|
dnsServers: Array.isArray(cfg.dnsServers) ? cfg.dnsServers.map(String) : undefined,
|
|
377
437
|
networkMode: cfg.networkMode || undefined,
|
|
378
438
|
tcpdumpPath: cfg.tcpdumpPath || undefined,
|
|
@@ -388,6 +448,9 @@ export function apply(ctx, config = {}) {
|
|
|
388
448
|
let disposeInstanceRoutes = null;
|
|
389
449
|
const flowRecorder = new FlowRecorder();
|
|
390
450
|
const cdpBridges = new Map();
|
|
451
|
+
// Lite mode: keep the default AVD small on memory-constrained hosts. Fire and
|
|
452
|
+
// forget — a missing AVD is normal before auto-setup runs.
|
|
453
|
+
void applyVmPresetToDefaultAvd();
|
|
391
454
|
if (instanceManager) {
|
|
392
455
|
instanceManager.onCreated = (id) => {
|
|
393
456
|
registerInstanceRoutes?.(id);
|
|
@@ -418,7 +481,7 @@ export function apply(ctx, config = {}) {
|
|
|
418
481
|
const frame = { buffer: null, at: 0, inFlight: null, receivedAt: [] };
|
|
419
482
|
const screen = { value: null, at: 0 };
|
|
420
483
|
const preferAutoStart = cfg.autoStart !== false;
|
|
421
|
-
let streamFps = Number.isFinite(Number(cfg.frameFps)) ? Math.min(10, Math.max(1, Math.round(Number(cfg.frameFps)))) : 2;
|
|
484
|
+
let streamFps = Number.isFinite(Number(presetFrameFps || cfg.frameFps)) ? Math.min(10, Math.max(1, Math.round(Number(presetFrameFps || cfg.frameFps)))) : 2;
|
|
422
485
|
|
|
423
486
|
function measuredFrameFps() {
|
|
424
487
|
const now = Date.now();
|
|
@@ -571,6 +634,52 @@ export function apply(ctx, config = {}) {
|
|
|
571
634
|
}
|
|
572
635
|
}
|
|
573
636
|
|
|
637
|
+
/**
|
|
638
|
+
* SDK download/install knobs shared by auto-setup and the manual panel steps.
|
|
639
|
+
* These map straight onto lib/setup.js options; unknown/empty values are left
|
|
640
|
+
* untouched so the defaults keep working.
|
|
641
|
+
*/
|
|
642
|
+
function provisionNetworkOptions() {
|
|
643
|
+
const options = {};
|
|
644
|
+
if (Array.isArray(cfg.sdkManagerArgs) && cfg.sdkManagerArgs.length) options.sdkManagerArgs = cfg.sdkManagerArgs.map(String);
|
|
645
|
+
if (cfg.sdkManagerEnv && typeof cfg.sdkManagerEnv === 'object' && !Array.isArray(cfg.sdkManagerEnv)) options.sdkManagerEnv = cfg.sdkManagerEnv;
|
|
646
|
+
if (cfg.networkProxy && typeof cfg.networkProxy === 'object' && !Array.isArray(cfg.networkProxy)) options.networkProxy = cfg.networkProxy;
|
|
647
|
+
if (typeof cfg.commandLineToolsUrl === 'string' && cfg.commandLineToolsUrl) options.commandLineToolsUrl = cfg.commandLineToolsUrl;
|
|
648
|
+
if (typeof cfg.commandLineToolsSha256 === 'string' && cfg.commandLineToolsSha256) options.commandLineToolsSha256 = cfg.commandLineToolsSha256;
|
|
649
|
+
return options;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Lite mode patches the default AVD too (extra instances get the profile from
|
|
654
|
+
* InstanceManager). config.ini is plain text and is read at the next boot, so
|
|
655
|
+
* this is best-effort: a missing AVD just means setup has not created it yet.
|
|
656
|
+
*/
|
|
657
|
+
async function applyVmPresetToDefaultAvd() {
|
|
658
|
+
try {
|
|
659
|
+
if (!vmPreset) return;
|
|
660
|
+
const ramSizeMb = Number(vmPreset.ramSizeMb);
|
|
661
|
+
const cores = Number(vmPreset.cores);
|
|
662
|
+
if (!Number.isFinite(ramSizeMb) && !Number.isFinite(cores)) return;
|
|
663
|
+
const avdHome = process.env.ANDROID_AVD_HOME || path.join(os.homedir(), '.android', 'avd');
|
|
664
|
+
const avd = String(cfg.avdName || 'dsh_apk');
|
|
665
|
+
const configPath = path.join(avdHome, `${avd}.avd`, 'config.ini');
|
|
666
|
+
if (!existsSync(configPath)) return;
|
|
667
|
+
let text = readFileSync(configPath, 'utf8');
|
|
668
|
+
if (!text.endsWith('\n')) text += '\n';
|
|
669
|
+
const setKey = (key, value) => {
|
|
670
|
+
const line = `${key}=${value}`;
|
|
671
|
+
const pattern = new RegExp(`^${key}=.*$`, 'm');
|
|
672
|
+
text = pattern.test(text) ? text.replace(pattern, line) : `${text}${line}\n`;
|
|
673
|
+
};
|
|
674
|
+
if (Number.isFinite(ramSizeMb) && ramSizeMb > 0) setKey('hw.ramSize', String(Math.round(ramSizeMb)));
|
|
675
|
+
if (Number.isFinite(cores) && cores > 0) setKey('hw.cpu.ncore', String(Math.round(cores)));
|
|
676
|
+
await fsp.writeFile(configPath, text, 'utf8');
|
|
677
|
+
vm._pushLog(`applied the ${vmPreset.name || 'custom'} VM preset to the default AVD ${avd}`);
|
|
678
|
+
} catch (error) {
|
|
679
|
+
vm._pushLog(`applying the VM preset to the default AVD failed: ${error && error.message ? error.message : error}`);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
574
683
|
function buildAutoSetup(enabled) {
|
|
575
684
|
return createAutoSetup({
|
|
576
685
|
enabled,
|
|
@@ -583,6 +692,12 @@ export function apply(ctx, config = {}) {
|
|
|
583
692
|
jdkRoot: configuredJdkRoot,
|
|
584
693
|
jdkMirror: cfg.jdkMirror,
|
|
585
694
|
jdkVersion: cfg.jdkVersion,
|
|
695
|
+
// Download reliability knobs (lib/autosetup.js): retries with backoff,
|
|
696
|
+
// cumulative disk budget, and SDK-manager/network overrides.
|
|
697
|
+
stepRetries: cfg.setupRetries,
|
|
698
|
+
retryDelayMs: cfg.retryDelayMs,
|
|
699
|
+
minFreeDiskBytes: cfg.minFreeDiskBytes,
|
|
700
|
+
...provisionNetworkOptions(),
|
|
586
701
|
log: autoSetupLog,
|
|
587
702
|
onUpdate: (snapshot) => {
|
|
588
703
|
if (snapshot.state === lastAutoSetupState) return;
|
|
@@ -889,6 +1004,7 @@ export function apply(ctx, config = {}) {
|
|
|
889
1004
|
function handleScrcpyClient(client) {
|
|
890
1005
|
const st = getScrcpyState();
|
|
891
1006
|
st.clients.add(client);
|
|
1007
|
+
if (instanceManager) instanceManager.noteSharedActivity();
|
|
892
1008
|
sendScrcpyInit(st);
|
|
893
1009
|
if (st.initSent && st.session && st.session.state === 'running') {
|
|
894
1010
|
// A late client only has delta frames; ask the encoder for a fresh keyframe.
|
|
@@ -1491,6 +1607,7 @@ export function apply(ctx, config = {}) {
|
|
|
1491
1607
|
|
|
1492
1608
|
function maybeAutoStart(status) {
|
|
1493
1609
|
if (!preferAutoStart || autoStartKicked) return;
|
|
1610
|
+
if (vm._crashLoop === true) return; // crash-loop breaker: require a manual start
|
|
1494
1611
|
if (!status || status.state !== 'stopped') return;
|
|
1495
1612
|
if (!vm.emulatorPath && !vm.serial) return; // nothing this plugin can start
|
|
1496
1613
|
if (status.serial) return;
|
|
@@ -1564,6 +1681,13 @@ export function apply(ctx, config = {}) {
|
|
|
1564
1681
|
stream: { fps: streamFps, hostFps: measuredFrameFps(), h264: scrcpyStatus() },
|
|
1565
1682
|
origin: serverOrigin,
|
|
1566
1683
|
multiInstance: Boolean(instanceManager),
|
|
1684
|
+
// Host memory + effective instance cap + lite profile (lib/memory.js).
|
|
1685
|
+
// Guarded so an older lib/instances.js never breaks the state route.
|
|
1686
|
+
memory: instanceManager && typeof instanceManager.memory === 'function' ? instanceManager.memory() : null,
|
|
1687
|
+
// Resident shared default VM policy state (suspended/stopped/idle timers).
|
|
1688
|
+
shared: instanceManager && typeof instanceManager.sharedStatus === 'function' ? instanceManager.sharedStatus() : null,
|
|
1689
|
+
// Operation-lock policy: 'all' | 'agents' | 'off' + lock control 'all' | 'user'.
|
|
1690
|
+
lockPolicy: { enforcement: lockEnforcement, control: lockControl },
|
|
1567
1691
|
client: lastClientReport,
|
|
1568
1692
|
owner: instanceManager ? instanceManager.ownerInfo('default') : null,
|
|
1569
1693
|
instances: [
|
|
@@ -1592,6 +1716,37 @@ export function apply(ctx, config = {}) {
|
|
|
1592
1716
|
};
|
|
1593
1717
|
}
|
|
1594
1718
|
|
|
1719
|
+
/** Journal an ownership transition (claim/release/takeover) with owner metadata. */
|
|
1720
|
+
// Owned by the plugin scope (not a single HTTP route set): tool calls can
|
|
1721
|
+
// journal takeovers too, so this must stay reachable from resolveToolApi.
|
|
1722
|
+
function recordOwnershipAction(action, instanceId, owner, previous = null) {
|
|
1723
|
+
try {
|
|
1724
|
+
const descriptor = owner && typeof owner === 'object'
|
|
1725
|
+
? {
|
|
1726
|
+
key: owner.key || null,
|
|
1727
|
+
label: owner.label || null,
|
|
1728
|
+
scope: owner.scope || null,
|
|
1729
|
+
role: owner.role || null,
|
|
1730
|
+
}
|
|
1731
|
+
: null;
|
|
1732
|
+
if (!descriptor || !descriptor.key) return;
|
|
1733
|
+
const previousLabel = previous && (previous.label || previous.key)
|
|
1734
|
+
? String(previous.label || previous.key)
|
|
1735
|
+
: null;
|
|
1736
|
+
void activityLog.record({
|
|
1737
|
+
action: 'ownership',
|
|
1738
|
+
source: 'http',
|
|
1739
|
+
tool: 'panel',
|
|
1740
|
+
instanceId: String(instanceId || 'default'),
|
|
1741
|
+
summary: `${action} ${instanceId}${previousLabel ? ` (was ${previousLabel})` : ''} -> ${descriptor.label || descriptor.key}`,
|
|
1742
|
+
ok: true,
|
|
1743
|
+
owner: descriptor,
|
|
1744
|
+
});
|
|
1745
|
+
} catch {
|
|
1746
|
+
/* activity logging must never break ownership */
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1595
1750
|
/** Android SDK root shared by the storage route and the apk_vm storage action. */
|
|
1596
1751
|
function storageSdkRoot() {
|
|
1597
1752
|
if (vm.sdkRoot) return vm.sdkRoot;
|
|
@@ -1689,16 +1844,35 @@ export function apply(ctx, config = {}) {
|
|
|
1689
1844
|
if (!instanceManager) return true;
|
|
1690
1845
|
const lease = instanceManager.ownerInfo(instanceId);
|
|
1691
1846
|
const incoming = httpOwnerFromRequest(req);
|
|
1692
|
-
const
|
|
1847
|
+
const mutating = req.method !== 'GET' && req.method !== 'HEAD';
|
|
1848
|
+
const takeover = takeoverFromHttp(req.headers || {}, requestQuery(req));
|
|
1849
|
+
const access = checkOwnerAccess(lease, incoming, instanceId, { mutating, takeover, lockMode: lockEnforcement });
|
|
1693
1850
|
if (!access.ok) {
|
|
1694
1851
|
sendJson(res, access.status || 409, {
|
|
1695
1852
|
ok: false,
|
|
1696
1853
|
error: access.error,
|
|
1697
1854
|
code: access.code || 'vm-busy',
|
|
1698
1855
|
owner: access.owner || lease,
|
|
1856
|
+
reserved: access.reserved === true,
|
|
1857
|
+
reservedUntil: access.reservedUntil || null,
|
|
1699
1858
|
});
|
|
1700
1859
|
return false;
|
|
1701
1860
|
}
|
|
1861
|
+
if (access.takeover) {
|
|
1862
|
+
try {
|
|
1863
|
+
const result = instanceManager.claimOwner(instanceId, incoming, { force: true });
|
|
1864
|
+
recordOwnershipAction('takeover', instanceId, incoming, result.previous || lease);
|
|
1865
|
+
return true;
|
|
1866
|
+
} catch (error) {
|
|
1867
|
+
sendJson(res, error.status === 409 ? 409 : 400, {
|
|
1868
|
+
ok: false,
|
|
1869
|
+
error: error.message,
|
|
1870
|
+
code: error.code || null,
|
|
1871
|
+
owner: error.owner || null,
|
|
1872
|
+
});
|
|
1873
|
+
return false;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1702
1876
|
if (access.autoClaim) {
|
|
1703
1877
|
try {
|
|
1704
1878
|
instanceManager.claimOwner(instanceId, incoming);
|
|
@@ -1713,6 +1887,7 @@ export function apply(ctx, config = {}) {
|
|
|
1713
1887
|
}
|
|
1714
1888
|
}
|
|
1715
1889
|
if (access.touch) instanceManager.touchOwner(instanceId, incoming.key);
|
|
1890
|
+
if (mutating && instanceId === 'default') instanceManager.noteSharedActivity();
|
|
1716
1891
|
return true;
|
|
1717
1892
|
}
|
|
1718
1893
|
|
|
@@ -1981,6 +2156,22 @@ export function apply(ctx, config = {}) {
|
|
|
1981
2156
|
if (ok && specSafe.shotAction) {
|
|
1982
2157
|
shot = await captureActivityShotBound(specSafe);
|
|
1983
2158
|
}
|
|
2159
|
+
let owner = null;
|
|
2160
|
+
try {
|
|
2161
|
+
if (instanceManager) {
|
|
2162
|
+
const incoming = httpOwnerFromRequest(req);
|
|
2163
|
+
if (incoming) {
|
|
2164
|
+
owner = {
|
|
2165
|
+
key: incoming.key,
|
|
2166
|
+
label: incoming.label,
|
|
2167
|
+
scope: incoming.scope,
|
|
2168
|
+
role: incoming.role,
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
} catch {
|
|
2173
|
+
owner = null;
|
|
2174
|
+
}
|
|
1984
2175
|
await activityLog.record({
|
|
1985
2176
|
action: String(specSafe.action || 'http').slice(0, 100),
|
|
1986
2177
|
source: 'http',
|
|
@@ -1992,6 +2183,7 @@ export function apply(ctx, config = {}) {
|
|
|
1992
2183
|
durationMs: Math.max(0, Date.now() - startedAt),
|
|
1993
2184
|
argsPreview: specSafe.argsPreview || null,
|
|
1994
2185
|
shot: shot || undefined,
|
|
2186
|
+
owner: owner || undefined,
|
|
1995
2187
|
});
|
|
1996
2188
|
} catch {
|
|
1997
2189
|
/* activity logging must never break a request */
|
|
@@ -2444,6 +2636,12 @@ export function apply(ctx, config = {}) {
|
|
|
2444
2636
|
} else if (action === 'orphan-avds') {
|
|
2445
2637
|
if (body.confirm !== true) throw new Error('orphan AVD cleanup requires confirm:true');
|
|
2446
2638
|
result = await cleanOrphanAvds({ knownAvds: known(), activeAvds: active() });
|
|
2639
|
+
} else if (action === 'corrupt-snapshots') {
|
|
2640
|
+
if (body.confirm !== true) throw new Error('corrupt snapshot cleanup requires confirm:true');
|
|
2641
|
+
result = await cleanCorruptSnapshots({ activeAvds: active() });
|
|
2642
|
+
} else if (action === 'crash-dumps') {
|
|
2643
|
+
if (body.confirm !== true) throw new Error('crash dump cleanup requires confirm:true');
|
|
2644
|
+
result = await cleanCrashDumps();
|
|
2447
2645
|
} else {
|
|
2448
2646
|
throw new Error(`unsupported storage action: ${action || '(missing)'}`);
|
|
2449
2647
|
}
|
|
@@ -2522,6 +2720,7 @@ export function apply(ctx, config = {}) {
|
|
|
2522
2720
|
jdkRoot: configuredJdkRoot,
|
|
2523
2721
|
systemImage: cfg.systemImage || DEFAULT_SYSTEM_IMAGE,
|
|
2524
2722
|
acceptLicenses: true,
|
|
2723
|
+
...provisionNetworkOptions(),
|
|
2525
2724
|
});
|
|
2526
2725
|
setupCache = null;
|
|
2527
2726
|
sendJson(res, 200, { ok: result.ok === true, action, result });
|
|
@@ -2542,6 +2741,7 @@ export function apply(ctx, config = {}) {
|
|
|
2542
2741
|
jdkRoot: configuredJdkRoot,
|
|
2543
2742
|
packages,
|
|
2544
2743
|
acceptLicenses: true,
|
|
2744
|
+
...provisionNetworkOptions(),
|
|
2545
2745
|
});
|
|
2546
2746
|
setupCache = null;
|
|
2547
2747
|
sendJson(res, 200, { ok: result.ok === true, action, result });
|
|
@@ -2557,6 +2757,7 @@ export function apply(ctx, config = {}) {
|
|
|
2557
2757
|
jdkRoot: configuredJdkRoot,
|
|
2558
2758
|
packages: Array.isArray(body.packages) ? body.packages : undefined,
|
|
2559
2759
|
acceptLicenses: true,
|
|
2760
|
+
...provisionNetworkOptions(),
|
|
2560
2761
|
});
|
|
2561
2762
|
setupCache = null;
|
|
2562
2763
|
sendJson(res, 200, { ok: result.ok === true, action, result });
|
|
@@ -2599,14 +2800,15 @@ export function apply(ctx, config = {}) {
|
|
|
2599
2800
|
source: 'panel',
|
|
2600
2801
|
});
|
|
2601
2802
|
try {
|
|
2602
|
-
const admin = owner.role === 'admin';
|
|
2603
2803
|
if (action === 'claim') {
|
|
2604
|
-
const result = instanceManager.claimOwner(instanceId, owner, { force: body.force === true
|
|
2804
|
+
const result = instanceManager.claimOwner(instanceId, owner, { force: body.force === true });
|
|
2805
|
+
recordOwnershipAction(result.previous ? 'takeover' : 'claim', instanceId, owner, result.previous || null);
|
|
2605
2806
|
sendJson(res, 200, { ok: true, instanceId, ...result });
|
|
2606
2807
|
return;
|
|
2607
2808
|
}
|
|
2608
2809
|
if (action === 'release') {
|
|
2609
|
-
const released = instanceManager.releaseOwner(instanceId, owner, { force: body.force === true
|
|
2810
|
+
const released = instanceManager.releaseOwner(instanceId, owner, { force: body.force === true });
|
|
2811
|
+
recordOwnershipAction('release', instanceId, owner, released || null);
|
|
2610
2812
|
sendJson(res, 200, { ok: true, instanceId, released });
|
|
2611
2813
|
return;
|
|
2612
2814
|
}
|
|
@@ -2614,6 +2816,19 @@ export function apply(ctx, config = {}) {
|
|
|
2614
2816
|
sendJson(res, 200, { ok: true, owner: instanceManager.touchOwner(instanceId, owner.key) });
|
|
2615
2817
|
return;
|
|
2616
2818
|
}
|
|
2819
|
+
if (action === 'lock') {
|
|
2820
|
+
const locked = instanceManager.lockOwner(instanceId, owner, { force: false });
|
|
2821
|
+
recordOwnershipAction('lock', instanceId, owner, locked);
|
|
2822
|
+
sendJson(res, 200, { ok: true, instanceId, owner: locked });
|
|
2823
|
+
return;
|
|
2824
|
+
}
|
|
2825
|
+
if (action === 'unlock') {
|
|
2826
|
+
const admin = String((req.headers && req.headers['x-apk-vm-role']) || '') === 'admin' && isLoopbackRequest(req);
|
|
2827
|
+
const unlocked = instanceManager.unlockOwner(instanceId, owner, { force: admin && body.force === true });
|
|
2828
|
+
recordOwnershipAction('unlock', instanceId, owner, unlocked);
|
|
2829
|
+
sendJson(res, 200, { ok: true, instanceId, owner: unlocked });
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2617
2832
|
sendJson(res, 200, {
|
|
2618
2833
|
ok: true,
|
|
2619
2834
|
default: instanceManager.ownerInfo('default'),
|
|
@@ -2774,6 +2989,11 @@ export function apply(ctx, config = {}) {
|
|
|
2774
2989
|
|
|
2775
2990
|
if (!rest) {
|
|
2776
2991
|
if (req.method === 'DELETE') {
|
|
2992
|
+
const confirmed = url.searchParams.get('confirm') === '1' || url.searchParams.get('confirm') === 'true';
|
|
2993
|
+
if (!confirmed) {
|
|
2994
|
+
sendError(res, 400, `destroying instance ${id} requires ?confirm=1 (the instance AVD and its data are deleted)`);
|
|
2995
|
+
return;
|
|
2996
|
+
}
|
|
2777
2997
|
await instanceManager.destroy(id);
|
|
2778
2998
|
disposeInstanceRoutes?.(id);
|
|
2779
2999
|
sendJson(res, 200, { ok: true, id, destroyed: true });
|
|
@@ -3734,7 +3954,15 @@ export function apply(ctx, config = {}) {
|
|
|
3734
3954
|
for (const profile of profiles) {
|
|
3735
3955
|
remotes.push(await collectRemoteInventory({ profile }));
|
|
3736
3956
|
}
|
|
3737
|
-
|
|
3957
|
+
const inventory = buildEmulatorInventory({ local, remotes });
|
|
3958
|
+
if (instanceManager && typeof instanceManager.memory === 'function') {
|
|
3959
|
+
try {
|
|
3960
|
+
inventory.memory = instanceManager.memory();
|
|
3961
|
+
} catch {
|
|
3962
|
+
inventory.memory = null;
|
|
3963
|
+
}
|
|
3964
|
+
}
|
|
3965
|
+
sendJson(res, 200, inventory);
|
|
3738
3966
|
} catch (error) {
|
|
3739
3967
|
sendError(res, 500, error && error.message ? error.message : String(error));
|
|
3740
3968
|
}
|
|
@@ -4577,6 +4805,7 @@ export function apply(ctx, config = {}) {
|
|
|
4577
4805
|
const intervalMs = Math.max(30_000, Number(cfg.instanceReapIntervalMs) || 60_000);
|
|
4578
4806
|
const timer = setInterval(() => {
|
|
4579
4807
|
void instanceManager.reapIdle().catch(() => {});
|
|
4808
|
+
void instanceManager.reconcileShared().catch(() => {});
|
|
4580
4809
|
}, intervalMs);
|
|
4581
4810
|
if (typeof timer.unref === 'function') timer.unref();
|
|
4582
4811
|
return () => clearInterval(timer);
|
|
@@ -4846,7 +5075,7 @@ export function apply(ctx, config = {}) {
|
|
|
4846
5075
|
}
|
|
4847
5076
|
|
|
4848
5077
|
function ownerTakeoverRequested(args) {
|
|
4849
|
-
return Boolean(args && (args.ownerForce === true || args.takeover === true));
|
|
5078
|
+
return Boolean(args && (args.ownerForce === true || args.takeover === true || args.force === true));
|
|
4850
5079
|
}
|
|
4851
5080
|
|
|
4852
5081
|
async function resolveToolApi(args, exec) {
|
|
@@ -4866,9 +5095,21 @@ export function apply(ctx, config = {}) {
|
|
|
4866
5095
|
const owner = toolOwnerContext(args, exec);
|
|
4867
5096
|
const force = ownerTakeoverRequested(args);
|
|
4868
5097
|
const previousDefaultOwner = instanceManager ? instanceManager.ownerInfo('default') : null;
|
|
5098
|
+
// A locked VM refuses every mutating tool call from a different owner, even
|
|
5099
|
+
// when the call resolves through a saved agent mapping or ownerForce.
|
|
5100
|
+
const assertUnlocked = (id) => {
|
|
5101
|
+
if (!instanceManager || !instanceManager.leaseBook) return;
|
|
5102
|
+
if (lockEnforcement === 'off') return;
|
|
5103
|
+
const lease = instanceManager.leaseBook.get(id);
|
|
5104
|
+
if (lease && lease.locked === true && lease.key !== owner.key) {
|
|
5105
|
+
throw new VmLeaseConflict(id, lease);
|
|
5106
|
+
}
|
|
5107
|
+
};
|
|
4869
5108
|
if (requested) {
|
|
4870
5109
|
if (requested === 'default') {
|
|
4871
|
-
|
|
5110
|
+
const claim = instanceManager ? instanceManager.claimOwner('default', owner, { force }) : null;
|
|
5111
|
+
if (claim && claim.previous) recordOwnershipAction('takeover', 'default', owner, claim.previous);
|
|
5112
|
+
assertUnlocked('default');
|
|
4872
5113
|
const api = defaultToolApi();
|
|
4873
5114
|
if (exec && exec.agent) void restoreSharedDesktop(api, owner, previousDefaultOwner);
|
|
4874
5115
|
return api;
|
|
@@ -4876,11 +5117,14 @@ export function apply(ctx, config = {}) {
|
|
|
4876
5117
|
if (!instanceManager) throw new Error('multi-instance support is disabled');
|
|
4877
5118
|
const instance = instanceManager.get(requested);
|
|
4878
5119
|
if (!instance) throw new Error(`unknown apk_vm instance: ${requested}`);
|
|
4879
|
-
instanceManager.claimOwner(instance.id, owner, { force });
|
|
5120
|
+
const claim = instanceManager.claimOwner(instance.id, owner, { force });
|
|
5121
|
+
if (claim && claim.previous) recordOwnershipAction('takeover', instance.id, owner, claim.previous);
|
|
5122
|
+
assertUnlocked(instance.id);
|
|
4880
5123
|
return extraToolApi(instance);
|
|
4881
5124
|
}
|
|
4882
5125
|
if (instanceManager && exec && (exec.agent || owner.sessionId)) {
|
|
4883
5126
|
const assigned = await instanceManager.forOwner(owner, { force });
|
|
5127
|
+
assertUnlocked(assigned && assigned.default === true ? 'default' : assigned && assigned.id);
|
|
4884
5128
|
if (assigned && assigned.default === true) {
|
|
4885
5129
|
const api = defaultToolApi();
|
|
4886
5130
|
if (exec && exec.agent) void restoreSharedDesktop(api, owner, previousDefaultOwner);
|
|
@@ -4889,19 +5133,58 @@ export function apply(ctx, config = {}) {
|
|
|
4889
5133
|
if (assigned && assigned.id) registerInstanceRoutes?.(assigned.id);
|
|
4890
5134
|
return extraToolApi(assigned);
|
|
4891
5135
|
}
|
|
5136
|
+
assertUnlocked('default');
|
|
4892
5137
|
return defaultToolApi();
|
|
4893
5138
|
}
|
|
4894
5139
|
|
|
5140
|
+
/** Reject a promise that takes too long, with a structured, actionable error. */
|
|
5141
|
+
function withToolTimeout(promise, timeoutMs, message) {
|
|
5142
|
+
let timer;
|
|
5143
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
5144
|
+
timer = setTimeout(() => {
|
|
5145
|
+
const error = new Error(message);
|
|
5146
|
+
error.code = 'vm-long-wait';
|
|
5147
|
+
reject(error);
|
|
5148
|
+
}, timeoutMs);
|
|
5149
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
5150
|
+
});
|
|
5151
|
+
return Promise.race([Promise.resolve(promise), timeout]).finally(() => clearTimeout(timer));
|
|
5152
|
+
}
|
|
5153
|
+
|
|
5154
|
+
const TOOL_READY_WAIT_MS = 120 * 1000;
|
|
5155
|
+
const TOOL_START_WAIT_MS = 180 * 1000;
|
|
4895
5156
|
async function ensureToolApiReady(api, action) {
|
|
4896
5157
|
let status = await api.status();
|
|
4897
5158
|
if (isReady(status)) return status;
|
|
4898
5159
|
if (action !== 'stop' && action !== 'start') {
|
|
4899
|
-
// Tool calls are expected to operate on a running VM; boot on demand
|
|
4900
|
-
|
|
5160
|
+
// Tool calls are expected to operate on a running VM; boot on demand, but
|
|
5161
|
+
// never block the agent forever: a foreign/wedged emulator can keep the VM
|
|
5162
|
+
// in booting for the full 1200s boot timeout, which reads as a hang.
|
|
5163
|
+
const budget = TOOL_READY_WAIT_MS;
|
|
5164
|
+
try {
|
|
5165
|
+
await withToolTimeout(
|
|
5166
|
+
Promise.resolve().then(() => api.start()),
|
|
5167
|
+
budget,
|
|
5168
|
+
`APK VM instance ${api.id} did not become ready within ${Math.round(budget / 1000)}s; it may be waiting for a foreign or wedged emulator. Check state/logTail, stop it if needed, then retry.`,
|
|
5169
|
+
);
|
|
5170
|
+
} catch (error) {
|
|
5171
|
+
if (error && error.code === 'vm-long-wait') {
|
|
5172
|
+
status = await api.status().catch(() => status);
|
|
5173
|
+
if (isReady(status)) return status;
|
|
5174
|
+
error.state = status && status.state;
|
|
5175
|
+
error.serial = status && status.serial;
|
|
5176
|
+
}
|
|
5177
|
+
throw error;
|
|
5178
|
+
}
|
|
4901
5179
|
status = await api.status();
|
|
4902
5180
|
}
|
|
4903
5181
|
if (!isReady(status)) {
|
|
4904
|
-
|
|
5182
|
+
const error = new Error(
|
|
5183
|
+
`APK VM instance ${api.id} is not ready (state: ${status.state}); it may still be starting. Check state/logTail, then retry or stop it.`,
|
|
5184
|
+
);
|
|
5185
|
+
error.code = 'vm-not-ready';
|
|
5186
|
+
error.state = status.state;
|
|
5187
|
+
throw error;
|
|
4905
5188
|
}
|
|
4906
5189
|
return status;
|
|
4907
5190
|
}
|
|
@@ -5163,7 +5446,7 @@ export function apply(ctx, config = {}) {
|
|
|
5163
5446
|
}
|
|
5164
5447
|
}
|
|
5165
5448
|
|
|
5166
|
-
async function recordToolActivity(args, outcome, startedAt) {
|
|
5449
|
+
async function recordToolActivity(args, outcome, startedAt, exec = null) {
|
|
5167
5450
|
try {
|
|
5168
5451
|
const action = String((args && args.action) || '').toLowerCase() || '(missing)';
|
|
5169
5452
|
// Reading the playbook is not a VM operation and its summary is the whole
|
|
@@ -5173,17 +5456,32 @@ export function apply(ctx, config = {}) {
|
|
|
5173
5456
|
const failure = outcome && outcome.result && outcome.result.error;
|
|
5174
5457
|
let shot = null;
|
|
5175
5458
|
if (ACTIVITY_SHOT_ACTIONS.has(action)) shot = await captureActivityShot(args);
|
|
5459
|
+
let owner = null;
|
|
5460
|
+
try {
|
|
5461
|
+
if (instanceManager) {
|
|
5462
|
+
const contextOwner = instanceManager.ownerFor(toolOwnerContext(args, exec));
|
|
5463
|
+
owner = {
|
|
5464
|
+
key: contextOwner.key,
|
|
5465
|
+
label: contextOwner.label,
|
|
5466
|
+
scope: contextOwner.scope,
|
|
5467
|
+
role: contextOwner.role,
|
|
5468
|
+
};
|
|
5469
|
+
}
|
|
5470
|
+
} catch {
|
|
5471
|
+
owner = null;
|
|
5472
|
+
}
|
|
5176
5473
|
await activityLog.record({
|
|
5177
5474
|
action,
|
|
5178
5475
|
source: 'tool',
|
|
5179
5476
|
tool: 'apk_vm',
|
|
5180
|
-
instanceId: String((args && args.instance) || 'default'),
|
|
5477
|
+
instanceId: String((exec && exec.apkvmInstanceId) || (args && args.instance) || 'default'),
|
|
5181
5478
|
summary: outcome && outcome.summary ? String(outcome.summary).slice(0, 500) : ok ? 'ok' : 'failed',
|
|
5182
5479
|
ok,
|
|
5183
5480
|
error: failure ? String((failure && failure.message) || failure).slice(0, 800) : null,
|
|
5184
5481
|
durationMs: Math.max(0, Date.now() - startedAt),
|
|
5185
5482
|
argsPreview: activityArgsPreview(args),
|
|
5186
5483
|
shot: shot || undefined,
|
|
5484
|
+
owner: owner || undefined,
|
|
5187
5485
|
});
|
|
5188
5486
|
} catch {
|
|
5189
5487
|
/* activity logging must never break the tool */
|
|
@@ -5203,7 +5501,7 @@ export function apply(ctx, config = {}) {
|
|
|
5203
5501
|
'WebView actions use Chrome DevTools Protocol (CDP): webview list|eval|click|wait_for|insert_text over the app WebView. ' +
|
|
5204
5502
|
'tap_selector clicks a DOM selector through CDP so CSS/dpr/status-bar math is not needed; type_text injects UTF-8 (including Chinese) through the scrcpy control stream. ' +
|
|
5205
5503
|
'App-operation Skills use a persisted Control Codebook (stable codes such as LOGIN_BTN or A01) instead of raw coordinates; record once with skill_start + control_* then replay with skill_run to reach a page quickly. ' +
|
|
5206
|
-
'VM ownership: pass ownerScope=conversation or project to use a dedicated VM for this session/project; shared is the default. owner_status / claim_vm / release_vm inspect or change the current lease. A VM owned by another conversation is never taken silently: the tool returns a vm-busy error unless ownerForce=true (explicit takeover). ' +
|
|
5504
|
+
'VM ownership: pass ownerScope=conversation or project to use a dedicated VM for this session/project; shared is the default. Dedicated reservations are persisted (<profile>/.apk-vm/leases.json) and survive plugin restarts; other owners must use ownerForce=true (alias force=true) to take one over. owner_status / claim_vm / release_vm inspect or change the current lease. lock_vm / unlock_vm turn a lease into a hard lock: while locked, every mutating request from another agent or the panel is rejected with vm-locked (ownerForce cannot steal a locked VM); only the lock owner can control it, and a local admin can force an unlock from the panel. A VM owned by another conversation is never taken silently: the tool returns a vm-busy error unless ownerForce=true (explicit takeover). ' +
|
|
5207
5505
|
'Multi-instance: pass `instance` to target an isolated VM; omit it to use the calling Agent\'s ' +
|
|
5208
5506
|
'assigned instance (first Agent gets the default VM, later Agents get isolated instances). ' +
|
|
5209
5507
|
'Use shell for low-level Android commands, logcat for logs, ' +
|
|
@@ -5224,7 +5522,8 @@ export function apply(ctx, config = {}) {
|
|
|
5224
5522
|
instance: { type: 'string', description: 'Target VM instance id (default or an extra instance from list_instances). Omit for the calling Agent\'s assigned instance.' },
|
|
5225
5523
|
ownerScope: { type: 'string', enum: ['shared', 'conversation', 'project'], description: 'VM ownership scope: shared (default), conversation (dedicated per DSH session), or project (dedicated per workspace).' },
|
|
5226
5524
|
ownerLabel: { type: 'string', description: 'Optional human-readable owner label shown in the VM panel.' },
|
|
5227
|
-
ownerForce: { type: 'boolean', description: 'Explicitly take over a VM owned by another conversation/project (default false; conflicts return vm-busy).' },
|
|
5525
|
+
ownerForce: { type: 'boolean', description: 'Explicitly take over a VM owned/reserved by another conversation/project (default false; conflicts return vm-busy). force is accepted as an alias. Does not override a locked VM (vm-locked).' },
|
|
5526
|
+
force: { type: 'boolean', description: 'Alias for ownerForce: explicitly take over a VM reserved by another conversation/project. Does not override a locked VM (vm-locked).' },
|
|
5228
5527
|
instanceName: { type: 'string', description: 'create_instance: optional name for the new isolated instance.' },
|
|
5229
5528
|
start: { type: 'boolean', description: 'create_instance: start the new instance immediately when true.' },
|
|
5230
5529
|
command: { type: 'string', description: 'Shell command for action=shell.' },
|
|
@@ -5269,9 +5568,16 @@ export function apply(ctx, config = {}) {
|
|
|
5269
5568
|
port: { type: 'integer', description: 'proxy: HTTP proxy port (1-65535).' },
|
|
5270
5569
|
bypass: { type: 'string', description: 'proxy: optional no-proxy/exclusion list.' },
|
|
5271
5570
|
flowId: { type: 'string', description: 'flow_replay: saved flow id from flow_list.' },
|
|
5272
|
-
storageAction: {
|
|
5571
|
+
storageAction: {
|
|
5572
|
+
type: 'string',
|
|
5573
|
+
description: 'clean_storage: temp|snapshots|orphan-avds|corrupt-snapshots|crash-dumps.',
|
|
5574
|
+
},
|
|
5273
5575
|
avdName: { type: 'string', description: 'clean_storage snapshots: target AVD (defaults to the active AVD).' },
|
|
5274
|
-
confirm: {
|
|
5576
|
+
confirm: {
|
|
5577
|
+
type: 'boolean',
|
|
5578
|
+
description:
|
|
5579
|
+
'Destructive actions require confirm=true: destroy_instance, and clean_storage snapshots/orphan-avds/corrupt-snapshots/crash-dumps.',
|
|
5580
|
+
},
|
|
5275
5581
|
networkAction: { type: 'string', description: 'network: info|mode|dns|hosts|test|validate|pcap|proxy|forward-add|forward-remove|reverse-add|reverse-remove|reverse-list.' },
|
|
5276
5582
|
networkMode: { type: 'string', description: 'network mode: isolated|shared.' },
|
|
5277
5583
|
localPort: { type: 'integer', description: 'port forward: host loopback port.' },
|
|
@@ -5350,7 +5656,7 @@ export function apply(ctx, config = {}) {
|
|
|
5350
5656
|
});
|
|
5351
5657
|
}
|
|
5352
5658
|
// Fire-and-forget: the timeline must never slow down the Agent's call.
|
|
5353
|
-
void recordToolActivity(args, outcome, startedAt);
|
|
5659
|
+
void recordToolActivity(args, outcome, startedAt, exec);
|
|
5354
5660
|
return outcome;
|
|
5355
5661
|
},
|
|
5356
5662
|
|
|
@@ -5416,7 +5722,18 @@ export function apply(ctx, config = {}) {
|
|
|
5416
5722
|
// device should trigger owner assignment/leasing.
|
|
5417
5723
|
let toolApiPromise = null;
|
|
5418
5724
|
const getToolApi = () => {
|
|
5419
|
-
if (!toolApiPromise)
|
|
5725
|
+
if (!toolApiPromise) {
|
|
5726
|
+
toolApiPromise = resolveToolApi(args, exec).then((api) => {
|
|
5727
|
+
// The activity journal must name the VM that actually served the
|
|
5728
|
+
// call: implicit resolution may pick a different instance than the
|
|
5729
|
+
// requested/default id.
|
|
5730
|
+
if (api && exec) exec.apkvmInstanceId = api.id;
|
|
5731
|
+
// A default-VM tool call is real activity: keep the resident VM
|
|
5732
|
+
// awake instead of suspending it under an active agent.
|
|
5733
|
+
if (api && api.id === 'default' && instanceManager) instanceManager.noteSharedActivity();
|
|
5734
|
+
return api;
|
|
5735
|
+
});
|
|
5736
|
+
}
|
|
5420
5737
|
return toolApiPromise;
|
|
5421
5738
|
};
|
|
5422
5739
|
|
|
@@ -5474,6 +5791,11 @@ export function apply(ctx, config = {}) {
|
|
|
5474
5791
|
const id = args.instance || args.name;
|
|
5475
5792
|
if (!id) throw new Error('destroy_instance requires instance');
|
|
5476
5793
|
if (id === 'default') throw new Error('the default instance cannot be destroyed');
|
|
5794
|
+
if (args.confirm !== true) {
|
|
5795
|
+
throw new Error(
|
|
5796
|
+
`destroy_instance requires confirm=true: it deletes the instance AVD ${id} and all of its data. Inspect it first, then retry with confirm=true.`,
|
|
5797
|
+
);
|
|
5798
|
+
}
|
|
5477
5799
|
const result = await instanceManager.destroy(id);
|
|
5478
5800
|
disposeInstanceRoutes?.(id);
|
|
5479
5801
|
return { ok: true, summary: `destroyed instance ${id}`, result };
|
|
@@ -5565,6 +5887,7 @@ export function apply(ctx, config = {}) {
|
|
|
5565
5887
|
if (id !== 'default' && !instanceManager.get(id)) throw new Error(`unknown instance: ${id}`);
|
|
5566
5888
|
const owner = toolOwnerContext(args, exec);
|
|
5567
5889
|
const result = instanceManager.claimOwner(id, owner, { force: ownerTakeoverRequested(args) });
|
|
5890
|
+
if (result.previous) recordOwnershipAction('takeover', id, owner, result.previous);
|
|
5568
5891
|
return {
|
|
5569
5892
|
ok: true,
|
|
5570
5893
|
summary: `claimed ${id} for ${result.lease.label}${result.previous ? ` (took over from ${result.previous.label})` : ''}`,
|
|
@@ -5577,12 +5900,41 @@ export function apply(ctx, config = {}) {
|
|
|
5577
5900
|
if (id !== 'default' && !instanceManager.get(id)) throw new Error(`unknown instance: ${id}`);
|
|
5578
5901
|
const owner = toolOwnerContext(args, exec);
|
|
5579
5902
|
const released = instanceManager.releaseOwner(id, owner, { force: ownerTakeoverRequested(args) });
|
|
5903
|
+
if (released) recordOwnershipAction('release', id, owner, released);
|
|
5580
5904
|
return {
|
|
5581
5905
|
ok: true,
|
|
5582
5906
|
summary: released ? `released ${id} (was ${released.label})` : `${id} is not leased`,
|
|
5583
5907
|
result: { instanceId: id, released },
|
|
5584
5908
|
};
|
|
5585
5909
|
}
|
|
5910
|
+
if (action === 'lock_vm') {
|
|
5911
|
+
if (!instanceManager) throw new Error('multi-instance support is disabled');
|
|
5912
|
+
if (lockControl === 'user') throw new Error('vm-lock-restricted: only the user can lock a VM (use the panel Lock button); ask the user to lock it instead');
|
|
5913
|
+
const id = String(args.instance || 'default');
|
|
5914
|
+
if (id !== 'default' && !instanceManager.get(id)) throw new Error(`unknown instance: ${id}`);
|
|
5915
|
+
const owner = toolOwnerContext(args, exec);
|
|
5916
|
+
const locked = instanceManager.lockOwner(id, owner, { force: false });
|
|
5917
|
+
recordOwnershipAction('lock', id, owner, locked);
|
|
5918
|
+
return {
|
|
5919
|
+
ok: true,
|
|
5920
|
+
summary: `locked ${id} for ${locked.label}; other agents and users are blocked until unlock_vm`,
|
|
5921
|
+
result: { instanceId: id, owner: locked },
|
|
5922
|
+
};
|
|
5923
|
+
}
|
|
5924
|
+
if (action === 'unlock_vm') {
|
|
5925
|
+
if (!instanceManager) throw new Error('multi-instance support is disabled');
|
|
5926
|
+
if (lockControl === 'user') throw new Error('vm-lock-restricted: only the user can unlock a VM (use the panel Unlock button); ask the user to unlock it instead');
|
|
5927
|
+
const id = String(args.instance || 'default');
|
|
5928
|
+
if (id !== 'default' && !instanceManager.get(id)) throw new Error(`unknown instance: ${id}`);
|
|
5929
|
+
const owner = toolOwnerContext(args, exec);
|
|
5930
|
+
const unlocked = instanceManager.unlockOwner(id, owner, { force: false });
|
|
5931
|
+
recordOwnershipAction('unlock', id, owner, unlocked);
|
|
5932
|
+
return {
|
|
5933
|
+
ok: true,
|
|
5934
|
+
summary: `unlocked ${id}${unlocked ? ` (was locked by ${unlocked.label})` : ''}`,
|
|
5935
|
+
result: { instanceId: id, owner: unlocked },
|
|
5936
|
+
};
|
|
5937
|
+
}
|
|
5586
5938
|
|
|
5587
5939
|
const api = await getToolApi();
|
|
5588
5940
|
if (action === 'flow_list') {
|
|
@@ -5760,6 +6112,12 @@ export function apply(ctx, config = {}) {
|
|
|
5760
6112
|
} else if (storageAction === 'orphan-avds') {
|
|
5761
6113
|
if (args.confirm !== true) throw new Error('clean_storage orphan-avds requires confirm=true');
|
|
5762
6114
|
result = await cleanOrphanAvds({ knownAvds, activeAvds });
|
|
6115
|
+
} else if (storageAction === 'corrupt-snapshots') {
|
|
6116
|
+
if (args.confirm !== true) throw new Error('clean_storage corrupt-snapshots requires confirm=true');
|
|
6117
|
+
result = await cleanCorruptSnapshots({ activeAvds });
|
|
6118
|
+
} else if (storageAction === 'crash-dumps') {
|
|
6119
|
+
if (args.confirm !== true) throw new Error('clean_storage crash-dumps requires confirm=true');
|
|
6120
|
+
result = await cleanCrashDumps();
|
|
5763
6121
|
} else throw new Error(`unsupported storageAction: ${storageAction}`);
|
|
5764
6122
|
return {
|
|
5765
6123
|
ok: true,
|
|
@@ -5840,7 +6198,12 @@ export function apply(ctx, config = {}) {
|
|
|
5840
6198
|
throw new Error(`unsupported networkAction: ${networkAction}`);
|
|
5841
6199
|
}
|
|
5842
6200
|
if (action === 'start') {
|
|
5843
|
-
const
|
|
6201
|
+
const timeoutMs = Math.max(15000, Math.min(300000, Number(args.timeoutMs) || TOOL_START_WAIT_MS));
|
|
6202
|
+
const snapshot = await withToolTimeout(
|
|
6203
|
+
Promise.resolve().then(() => api.start()),
|
|
6204
|
+
timeoutMs,
|
|
6205
|
+
`APK VM instance ${api.id} did not finish starting within ${Math.round(timeoutMs / 1000)}s; it may be waiting for a foreign or wedged emulator. Check state/logTail, stop it if needed, then retry.`,
|
|
6206
|
+
);
|
|
5844
6207
|
return { ok: true, summary: `started ${api.id}`, result: snapshot || {} };
|
|
5845
6208
|
}
|
|
5846
6209
|
if (action === 'stop') {
|