dsh-apk-vm 0.8.0 → 0.10.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.
@@ -0,0 +1,592 @@
1
+ /**
2
+ * App Skills: a small, portable recipe format for "go to this page" flows.
3
+ *
4
+ * A Skill embeds its own Control Codebook and a list of semantic steps. Replay
5
+ * never uses recorded coordinates when a code resolves; repeated `waitFor`
6
+ * polling replaces fixed sleeps, so a replay is both faster and more reliable
7
+ * than raw input replay. Raw coordinate steps remain as an explicit fallback.
8
+ */
9
+
10
+ import { promises as fsp } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { parseUiHierarchy, snapshotIdForXml } from './ui-inspector.js';
13
+ import {
14
+ ControlMatchError,
15
+ findCodeEntry,
16
+ listCodes,
17
+ matchNodeFeatures,
18
+ normalizeCodebook,
19
+ resolveControl,
20
+ resolveSelector,
21
+ } from './control-codebook.js';
22
+ import { computeImageFeatures, decodePng } from './image-features.js';
23
+
24
+ export const SKILL_SCHEMA_VERSION = 1;
25
+
26
+ const STEP_ACTIONS = new Map([
27
+ ['tap', 'tap'],
28
+ ['click', 'tap'],
29
+ ['longpress', 'longPress'],
30
+ ['long_press', 'longPress'],
31
+ ['long-press', 'longPress'],
32
+ ['input', 'input'],
33
+ ['type', 'input'],
34
+ ['settext', 'input'],
35
+ ['launch', 'launch'],
36
+ ['open', 'launch'],
37
+ ['start', 'launch'],
38
+ ['waitfor', 'waitFor'],
39
+ ['wait', 'waitFor'],
40
+ ['assert', 'assert'],
41
+ ['key', 'key'],
42
+ ['press', 'key'],
43
+ ['swipe', 'swipe'],
44
+ ['scroll', 'swipe'],
45
+ ['sleep', 'sleep'],
46
+ ['delay', 'sleep'],
47
+ ['back', 'key'],
48
+ ]);
49
+
50
+ const ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
51
+ const DEFAULT_WAIT_MS = 6000;
52
+ const MAX_WAIT_MS = 120000;
53
+
54
+ function delay(ms) {
55
+ return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
56
+ }
57
+
58
+ function asString(value) {
59
+ return value === undefined || value === null ? '' : String(value).trim();
60
+ }
61
+
62
+ function clampNumber(value, fallback, min, max) {
63
+ const number = Number(value);
64
+ if (!Number.isFinite(number)) return fallback;
65
+ return Math.min(max, Math.max(min, number));
66
+ }
67
+
68
+ export function slugifySkillName(name) {
69
+ const base = asString(name)
70
+ .toLowerCase()
71
+ .replace(/[^a-z0-9._-]+/g, '-')
72
+ .replace(/^-+|-+$/g, '')
73
+ .slice(0, 48);
74
+ return base || `skill-${Date.now().toString(36)}`;
75
+ }
76
+
77
+ function selectorFromRaw(raw) {
78
+ if (!raw || typeof raw !== 'object') return null;
79
+ const selector = {};
80
+ for (const key of [
81
+ 'resourceId',
82
+ 'resourceIdContains',
83
+ 'text',
84
+ 'textAny',
85
+ 'textContains',
86
+ 'contentDesc',
87
+ 'contentDescContains',
88
+ 'className',
89
+ 'classNameContains',
90
+ 'packageName',
91
+ 'clickable',
92
+ 'enabled',
93
+ 'x',
94
+ 'y',
95
+ 'boundsRatio',
96
+ 'image',
97
+ ]) {
98
+ if (raw[key] !== undefined && raw[key] !== null && raw[key] !== '') selector[key] = raw[key];
99
+ }
100
+ return Object.keys(selector).length ? selector : null;
101
+ }
102
+
103
+ /** Normalise one recorded/declared step. Throws on a missing target. */
104
+ export function normalizeSkillStep(raw, index = 0) {
105
+ const source = raw && typeof raw === 'object' ? raw : {};
106
+ const actionKey = asString(source.action || source.type || 'tap').toLowerCase();
107
+ const action = STEP_ACTIONS.get(actionKey);
108
+ if (!action) throw new Error(`step #${index + 1} has unsupported action ${JSON.stringify(source.action)}`);
109
+ const step = { action };
110
+ const code = asString(source.code);
111
+ if (code) step.code = code;
112
+ const selector = selectorFromRaw(source.selector || (source.x !== undefined ? source : null));
113
+ if (selector) step.selector = selector;
114
+ if (source.value !== undefined) step.value = String(source.value);
115
+ if (source.text !== undefined && action === 'input' && step.value === undefined) step.value = String(source.text);
116
+ if (source.key !== undefined) step.key = String(source.key);
117
+ if (source.package !== undefined) step.package = asString(source.package);
118
+ if (source.packageName !== undefined && !step.package) step.package = asString(source.packageName);
119
+ if (source.activity !== undefined) step.activity = asString(source.activity);
120
+ if (source.timeoutMs !== undefined) step.timeoutMs = clampNumber(source.timeoutMs, DEFAULT_WAIT_MS, 0, MAX_WAIT_MS);
121
+ if (source.index !== undefined) step.index = clampNumber(source.index, null, 0, 500);
122
+ if (source.submit !== undefined) step.submit = source.submit === true;
123
+ if (source.exists !== undefined) step.exists = source.exists !== false;
124
+ if (source.durationMs !== undefined) step.durationMs = clampNumber(source.durationMs, 300, 1, 60000);
125
+ if (source.settleMs !== undefined) step.settleMs = clampNumber(source.settleMs, 250, 0, 10000);
126
+ if (source.description !== undefined) step.description = asString(source.description).slice(0, 200);
127
+
128
+ if (action === 'tap' || action === 'longPress' || action === 'input' || action === 'waitFor' || action === 'assert') {
129
+ if (!step.code && !step.selector) throw new Error(`step #${index + 1} (${action}) requires code or selector`);
130
+ }
131
+ if (action === 'input' && step.value === undefined) step.value = '';
132
+ if (action === 'key') {
133
+ if (!step.key && source.action && asString(source.action).toLowerCase() === 'back') step.key = 'BACK';
134
+ if (!step.key) throw new Error(`step #${index + 1} (key) requires key`);
135
+ }
136
+ if (action === 'swipe') {
137
+ const from = asString(source.fromCode || source.from);
138
+ const to = asString(source.toCode || source.to);
139
+ if (from) step.fromCode = from;
140
+ if (to) step.toCode = to;
141
+ if (!from && !to) {
142
+ for (const key of ['x1', 'y1', 'x2', 'y2']) {
143
+ if (!Number.isFinite(Number(source[key]))) throw new Error(`step #${index + 1} (swipe) requires x1,y1,x2,y2 or fromCode/toCode`);
144
+ step[key] = Number(source[key]);
145
+ }
146
+ }
147
+ }
148
+ if (action === 'sleep') step.ms = clampNumber(source.ms ?? source.durationMs, 250, 0, 60000);
149
+ return step;
150
+ }
151
+
152
+ export function normalizeSkillSteps(raw) {
153
+ if (!Array.isArray(raw)) return [];
154
+ return raw.map((step, index) => normalizeSkillStep(step, index));
155
+ }
156
+
157
+ /** Normalise/validate a complete Skill, including its embedded codebook. */
158
+ export function normalizeSkill(raw, defaults = {}) {
159
+ const source = raw && typeof raw === 'object' ? raw : {};
160
+ const name = asString(source.name) || asString(defaults.name) || 'Untitled skill';
161
+ const idRaw = asString(source.id) || asString(defaults.id) || slugifySkillName(name);
162
+ const id = slugifySkillName(idRaw);
163
+ const pkg = asString(source.package || source.packageName || defaults.package || defaults.packageName);
164
+ if (pkg && !/^[A-Za-z_][A-Za-z0-9_.]{1,200}$/.test(pkg)) throw new Error(`invalid package name: ${JSON.stringify(pkg)}`);
165
+ const codebook = normalizeCodebook(source.codebook || source.controlCodebook || {});
166
+ const steps = normalizeSkillSteps(source.steps || []);
167
+ const now = Date.now();
168
+ return {
169
+ schemaVersion: SKILL_SCHEMA_VERSION,
170
+ id,
171
+ name: name.slice(0, 120),
172
+ ...(pkg ? { package: pkg } : {}),
173
+ ...(asString(source.description) ? { description: asString(source.description).slice(0, 300) } : {}),
174
+ ...(asString(source.target) ? { target: asString(source.target).slice(0, 120) } : {}),
175
+ codebook,
176
+ steps,
177
+ ...(source.variables && typeof source.variables === 'object' ? { variables: source.variables } : {}),
178
+ createdAt: Number.isFinite(Number(source.createdAt)) ? Number(source.createdAt) : now,
179
+ updatedAt: now,
180
+ };
181
+ }
182
+
183
+ /** Persistent Skill storage. Skills are JSON files under the Host workspace. */
184
+ export class SkillStore {
185
+ constructor(options = {}) {
186
+ this.dir = path.resolve(String(options.dir || path.join(process.cwd(), '.apk-vm', 'skills')));
187
+ this.maxSkills = clampNumber(options.maxSkills, 200, 1, 2000);
188
+ }
189
+
190
+ async ensure() {
191
+ await fsp.mkdir(this.dir, { recursive: true });
192
+ return this.dir;
193
+ }
194
+
195
+ validateId(id) {
196
+ const value = asString(id);
197
+ if (!ID_RE.test(value)) throw new Error('skill id must be 1-64 chars: letters, digits, dot, underscore or dash');
198
+ return value;
199
+ }
200
+
201
+ fileFor(id) {
202
+ return path.join(this.dir, `${this.validateId(id)}.json`);
203
+ }
204
+
205
+ async list() {
206
+ await this.ensure();
207
+ const entries = await fsp.readdir(this.dir, { withFileTypes: true }).catch(() => []);
208
+ const skills = [];
209
+ for (const entry of entries) {
210
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
211
+ const file = path.join(this.dir, entry.name);
212
+ try {
213
+ const raw = JSON.parse(await fsp.readFile(file, 'utf8'));
214
+ const skill = normalizeSkill(raw, { id: entry.name.slice(0, -5) });
215
+ skills.push(skill);
216
+ } catch {
217
+ /* ignore a broken skill file; a single bad file must not hide the rest */
218
+ }
219
+ }
220
+ return skills.sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, this.maxSkills);
221
+ }
222
+
223
+ async get(id) {
224
+ const value = this.validateId(id);
225
+ try {
226
+ const raw = JSON.parse(await fsp.readFile(this.fileFor(value), 'utf8'));
227
+ return normalizeSkill(raw, { id: value });
228
+ } catch (error) {
229
+ if (error && error.code === 'ENOENT') return null;
230
+ throw error;
231
+ }
232
+ }
233
+
234
+ async save(skill) {
235
+ const normalized = normalizeSkill(skill);
236
+ await this.ensure();
237
+ if ((await this.list()).filter((entry) => entry.id !== normalized.id).length >= this.maxSkills) {
238
+ throw new Error(`too many skills (limit ${this.maxSkills})`);
239
+ }
240
+ const file = this.fileFor(normalized.id);
241
+ const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
242
+ await fsp.writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, 'utf8');
243
+ await fsp.rename(temporary, file);
244
+ return normalized;
245
+ }
246
+
247
+ async remove(id) {
248
+ const value = this.validateId(id);
249
+ try {
250
+ await fsp.unlink(this.fileFor(value));
251
+ return true;
252
+ } catch (error) {
253
+ if (error && error.code === 'ENOENT') return false;
254
+ throw error;
255
+ }
256
+ }
257
+ }
258
+
259
+ function skillSummary(skill) {
260
+ return {
261
+ id: skill.id,
262
+ name: skill.name,
263
+ package: skill.package || null,
264
+ description: skill.description || null,
265
+ target: skill.target || null,
266
+ steps: skill.steps.length,
267
+ codes: skill.codebook.entries.length,
268
+ codebookName: skill.codebook.name || null,
269
+ createdAt: skill.createdAt,
270
+ updatedAt: skill.updatedAt,
271
+ };
272
+ }
273
+
274
+ export { skillSummary };
275
+
276
+ /** In-memory recording session per VM instance. */
277
+ export class SkillRecorder {
278
+ constructor(options = {}) {
279
+ this.store = options.store;
280
+ this.sessions = new Map();
281
+ }
282
+
283
+ async start(instanceId, options = {}) {
284
+ const id = asString(instanceId) || 'default';
285
+ if (this.sessions.has(id)) throw new Error(`instance ${id} is already recording a Skill; stop or cancel it first`);
286
+ const name = asString(options.name) || `recorded-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}`;
287
+ const skillId = slugifySkillName(options.id || name);
288
+ const existing = await this.store.get(skillId).catch(() => null);
289
+ const suffix = existing ? `-${Date.now().toString(36).slice(-4)}` : '';
290
+ const draft = normalizeSkill({
291
+ id: skillId + suffix,
292
+ name,
293
+ package: options.packageName || options.package,
294
+ description: options.description,
295
+ target: options.target,
296
+ codebook: options.codebook || {},
297
+ steps: [],
298
+ });
299
+ const session = {
300
+ instanceId: id,
301
+ skill: draft,
302
+ startedAt: Date.now(),
303
+ };
304
+ this.sessions.set(id, session);
305
+ return { ...skillSummary(draft), recording: true, instance: id };
306
+ }
307
+
308
+ active(instanceId) {
309
+ return this.sessions.get(asString(instanceId) || 'default') || null;
310
+ }
311
+
312
+ async updateCodebook(instanceId, rawCodebook) {
313
+ const session = this.active(instanceId);
314
+ if (!session) throw new Error('no active Skill recording; call skill_start first');
315
+ session.skill.codebook = normalizeCodebook(rawCodebook);
316
+ return session.skill.codebook;
317
+ }
318
+
319
+ add(instanceId, step) {
320
+ const session = this.active(instanceId);
321
+ if (!session) throw new Error('no active Skill recording; call skill_start first');
322
+ const normalized = normalizeSkillStep(step, session.skill.steps.length);
323
+ session.skill.steps.push(normalized);
324
+ return { steps: session.skill.steps.length };
325
+ }
326
+
327
+ cancel(instanceId) {
328
+ const id = asString(instanceId) || 'default';
329
+ const session = this.sessions.get(id);
330
+ this.sessions.delete(id);
331
+ return session ? skillSummary(session.skill) : null;
332
+ }
333
+
334
+ async stop(instanceId, options = {}) {
335
+ const id = asString(instanceId) || 'default';
336
+ const session = this.sessions.get(id);
337
+ if (!session) throw new Error('no active Skill recording; call skill_start first');
338
+ const merged = {
339
+ ...session.skill,
340
+ ...(options.name ? { name: options.name } : {}),
341
+ ...(options.packageName || options.package ? { package: options.packageName || options.package } : {}),
342
+ ...(options.description ? { description: options.description } : {}),
343
+ steps: session.skill.steps,
344
+ };
345
+ if (!merged.steps.length) throw new Error('Skill recording has no steps; use control_tap/control_input while recording or cancel');
346
+ const saved = await this.store.save(merged);
347
+ this.sessions.delete(id);
348
+ return saved;
349
+ }
350
+ }
351
+
352
+ function interpolate(value, variables) {
353
+ const text = String(value === undefined || value === null ? '' : value);
354
+ return text.replace(/\{\{\s*([A-Za-z0-9_.-]{1,64})\s*\}\}/g, (_match, key) => {
355
+ if (!variables || !Object.prototype.hasOwnProperty.call(variables, key)) {
356
+ throw new Error(`missing Skill variable ${JSON.stringify(key)}`);
357
+ }
358
+ return String(variables[key]);
359
+ });
360
+ }
361
+
362
+ async function hierarchy(api) {
363
+ const dump = await api.uiDump();
364
+ const parsed = parseUiHierarchy(dump.xml);
365
+ return {
366
+ dump,
367
+ parsed,
368
+ nodes: parsed.nodes,
369
+ snapshotId: snapshotIdForXml(dump.xml),
370
+ screen: await api.screenSize().catch(() => null),
371
+ };
372
+ }
373
+
374
+ function isAmbiguous(error) {
375
+ return error instanceof ControlMatchError
376
+ && (error.ambiguous === true || /is ambiguous/i.test(String(error.message || '')));
377
+ }
378
+
379
+ async function attachImageFeatures(entry, nodes, api, screen) {
380
+ if (!entry || !entry.features || !entry.features.image) return;
381
+ const structural = nodes.filter((node) => matchNodeFeatures(node, { ...entry.features, image: undefined }, { screen }).ok);
382
+ if (!structural.length) return;
383
+ if (typeof api.screenshotBuffer !== 'function') return;
384
+ const buffer = await api.screenshotBuffer();
385
+ const decoded = decodePng(buffer);
386
+ for (const node of structural) {
387
+ if (!node.bounds) continue;
388
+ try {
389
+ node.imageFeatures = computeImageFeatures(buffer, node.bounds, { decoded });
390
+ } catch {
391
+ /* a tiny/invisible crop simply cannot match an image feature */
392
+ }
393
+ }
394
+ }
395
+
396
+ async function resolveStepTarget(step, codebook, state, api, options) {
397
+ if (step.code) {
398
+ const entry = findCodeEntry(codebook, step.code);
399
+ if (!entry) throw new ControlMatchError(`unknown control code ${JSON.stringify(step.code)}`, { code: step.code, codebookCodes: listCodes(codebook) });
400
+ await attachImageFeatures(entry, state.nodes, api, state.screen);
401
+ return resolveControl(codebook, step.code, state.nodes, { screen: state.screen, ...options });
402
+ }
403
+ return resolveSelector(step.selector, state.nodes, { screen: state.screen, ...options });
404
+ }
405
+
406
+ async function waitForStepTarget(step, codebook, api, options) {
407
+ const timeoutMs = clampNumber(step.timeoutMs, options.timeoutMs || DEFAULT_WAIT_MS, 0, MAX_WAIT_MS);
408
+ const pollMs = Math.max(80, Number(options.pollMs) || 180);
409
+ const deadline = Date.now() + timeoutMs;
410
+ let lastError = null;
411
+ let state = null;
412
+ do {
413
+ state = await hierarchy(api);
414
+ try {
415
+ return { state, target: await resolveStepTarget(step, codebook, state, api, options) };
416
+ } catch (error) {
417
+ lastError = error;
418
+ if (isAmbiguous(error)) throw error;
419
+ // An unknown code is a definition error: retrying the same hierarchy
420
+ // cannot make it appear, unlike a visible-control miss.
421
+ if (error instanceof ControlMatchError && Array.isArray(error.codebookCodes)) throw error;
422
+ if (Date.now() >= deadline) break;
423
+ await delay(pollMs);
424
+ }
425
+ } while (Date.now() <= deadline);
426
+ const wrapped = new Error(
427
+ `timed out after ${timeoutMs}ms waiting for ${step.code || JSON.stringify(step.selector || {})}`,
428
+ );
429
+ wrapped.cause = lastError;
430
+ wrapped.candidates = lastError && lastError.candidates ? lastError.candidates : [];
431
+ wrapped.lastSnapshotId = state && state.snapshotId;
432
+ throw wrapped;
433
+ }
434
+
435
+ async function runStep(step, codebook, api, options) {
436
+ if (step.action === 'launch') {
437
+ const pkg = step.package || options.package;
438
+ if (!pkg) throw new Error('launch step needs package or a Skill package');
439
+ const result = await api.launchPackage(pkg, step.activity);
440
+ await delay(Math.max(120, (step.settleMs || 250) / options.speed));
441
+ return { action: 'launch', package: pkg, result };
442
+ }
443
+ if (step.action === 'key') {
444
+ const result = await api.input({ type: 'key', key: step.key });
445
+ await delay(80 / options.speed);
446
+ return { action: 'key', key: step.key, result };
447
+ }
448
+ if (step.action === 'sleep') {
449
+ await delay(step.ms / options.speed);
450
+ return { action: 'sleep', ms: step.ms };
451
+ }
452
+ if (step.action === 'swipe') {
453
+ let from;
454
+ let to;
455
+ if (step.fromCode || step.toCode) {
456
+ const current = await hierarchy(api);
457
+ if (step.fromCode) from = await resolveControl(codebook, step.fromCode, current.nodes, { screen: current.screen });
458
+ if (step.toCode) to = await resolveControl(codebook, step.toCode, current.nodes, { screen: current.screen });
459
+ if (!from && to) from = to;
460
+ if (!to && from) to = from;
461
+ }
462
+ const x1 = from ? from.node.bounds.center.x : step.x1;
463
+ const y1 = from ? from.node.bounds.center.y : step.y1;
464
+ const x2 = to ? to.node.bounds.center.x : step.x2;
465
+ const y2 = to ? to.node.bounds.center.y : step.y2;
466
+ if (![x1, y1, x2, y2].every(Number.isFinite)) throw new Error('swipe needs resolvable from/to codes or x1,y1,x2,y2');
467
+ const result =
468
+ options.dryRun === true
469
+ ? { dryRun: true }
470
+ : await api.input({ type: 'swipe', x1, y1, x2, y2, durationMs: step.durationMs || 300 });
471
+ await delay(120 / options.speed);
472
+ return { action: 'swipe', x1, y1, x2, y2, result };
473
+ }
474
+
475
+ if (step.action === 'assert' && step.exists === false) {
476
+ const state = await hierarchy(api);
477
+ let target = null;
478
+ let miss = null;
479
+ try {
480
+ target = await resolveStepTarget(step, codebook, state, api, options);
481
+ } catch (error) {
482
+ if (isAmbiguous(error) || (error instanceof ControlMatchError && Array.isArray(error.codebookCodes))) throw error;
483
+ miss = error;
484
+ }
485
+ if (target) throw new Error(`assert failed: ${step.code || 'selector'} is visible`);
486
+ if (miss && miss instanceof ControlMatchError && Array.isArray(miss.codebookCodes)) throw miss;
487
+ return { action: 'assert', code: step.code || null, exists: false, snapshotId: state.snapshotId };
488
+ }
489
+ const waited = await waitForStepTarget(step, codebook, api, options);
490
+ const target = waited.target;
491
+ const center = target.node && target.node.bounds && target.node.bounds.center;
492
+ if (step.action === 'waitFor') return { action: 'waitFor', code: target.code, snapshotId: waited.state.snapshotId };
493
+ if (step.action === 'assert') {
494
+ if (step.exists === false) throw new Error(`assert failed: ${step.code || 'selector'} is visible`);
495
+ return { action: 'assert', code: target.code, exists: true, snapshotId: waited.state.snapshotId };
496
+ }
497
+ if (step.action === 'tap' || step.action === 'longPress' || step.action === 'input') {
498
+ if (!center) throw new Error(`control ${target.code} has no usable bounds`);
499
+ if (options.dryRun !== true) {
500
+ if (step.action === 'longPress') {
501
+ await api.input({ type: 'swipe', x1: center.x, y1: center.y, x2: center.x, y2: center.y, durationMs: step.durationMs || 800 });
502
+ } else {
503
+ await api.input({ type: 'tap', x: center.x, y: center.y });
504
+ }
505
+ await delay(120 / options.speed);
506
+ }
507
+ if (step.action === 'input') {
508
+ const value = interpolate(step.value, options.variables || {});
509
+ if (options.dryRun !== true && value) await api.input({ type: 'text', text: value.slice(0, 4096) });
510
+ if (step.submit === true && options.dryRun !== true) await api.input({ type: 'key', key: 'ENTER' });
511
+ await delay(100 / options.speed);
512
+ return { action: 'input', code: target.code, value, snapshotId: waited.state.snapshotId };
513
+ }
514
+ if (step.action === 'longPress') {
515
+ return { action: 'longPress', code: target.code, snapshotId: waited.state.snapshotId };
516
+ }
517
+ return { action: 'tap', code: target.code, snapshotId: waited.state.snapshotId };
518
+ }
519
+ throw new Error(`unsupported Skill step action: ${step.action}`);
520
+ }
521
+
522
+ /**
523
+ * Replay a Skill with wait-for-control polling. Returns a JSON-friendly report
524
+ * suitable for the Agent tool and the sidebar card.
525
+ */
526
+ export async function runSkill(skill, api, options = {}) {
527
+ const normalized = normalizeSkill(skill);
528
+ if (!normalized.package && normalized.steps.some((step) => step.action === 'launch' && !step.package)) {
529
+ throw new Error('Skill has a launch step but no package');
530
+ }
531
+ const startedAt = Date.now();
532
+ const settings = {
533
+ package: normalized.package,
534
+ variables: { ...(normalized.variables || {}), ...(options.variables || {}) },
535
+ timeoutMs: clampNumber(options.timeoutMs, DEFAULT_WAIT_MS, 0, MAX_WAIT_MS),
536
+ pollMs: clampNumber(options.pollMs, 180, 80, 5000),
537
+ speed: clampNumber(options.speed, 1, 0.1, 20),
538
+ dryRun: options.dryRun === true,
539
+ untilCode: asString(options.untilCode),
540
+ };
541
+ const events = [];
542
+ let stepsRun = 0;
543
+ let reached = settings.untilCode ? false : null;
544
+ try {
545
+ if (normalized.steps.length === 0) throw new Error('Skill has no steps');
546
+ for (let index = 0; index < normalized.steps.length; index += 1) {
547
+ const step = normalized.steps[index];
548
+ const event = await runStep(step, normalized.codebook, api, settings);
549
+ stepsRun += 1;
550
+ events.push({ index, ...event });
551
+ if (settings.untilCode) {
552
+ const state = await hierarchy(api);
553
+ try {
554
+ const target = await resolveStepTarget({ code: settings.untilCode }, normalized.codebook, state, api, {});
555
+ if (target && target.node) {
556
+ reached = true;
557
+ events.push({ index, action: 'until', code: settings.untilCode, snapshotId: state.snapshotId });
558
+ break;
559
+ }
560
+ } catch {
561
+ /* not reached yet */
562
+ }
563
+ }
564
+ }
565
+ const finalState = await hierarchy(api).catch(() => null);
566
+ return {
567
+ ok: true,
568
+ skillId: normalized.id,
569
+ name: normalized.name,
570
+ package: normalized.package || null,
571
+ stepsRun,
572
+ stepsTotal: normalized.steps.length,
573
+ reached,
574
+ untilCode: settings.untilCode || null,
575
+ snapshotId: finalState ? finalState.snapshotId : null,
576
+ durationMs: Date.now() - startedAt,
577
+ dryRun: settings.dryRun,
578
+ events,
579
+ };
580
+ } catch (error) {
581
+ const failure = new Error(error && error.message ? error.message : String(error));
582
+ failure.name = 'SkillRunError';
583
+ failure.skillId = normalized.id;
584
+ failure.stepsRun = stepsRun;
585
+ failure.stepIndex = stepsRun;
586
+ failure.step = normalized.steps[stepsRun] || null;
587
+ failure.candidates = error && error.candidates ? error.candidates : [];
588
+ failure.lastSnapshotId = error && error.lastSnapshotId ? error.lastSnapshotId : null;
589
+ failure.events = events;
590
+ throw failure;
591
+ }
592
+ }