testingterm 0.0.0-stage → 0.0.1

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.
Files changed (52) hide show
  1. package/AGENT-DOCS.md +77 -0
  2. package/LICENSE +21 -0
  3. package/dist/ai.d.ts +24 -0
  4. package/dist/attach.d.ts +6 -0
  5. package/dist/capabilities.d.ts +6 -0
  6. package/dist/chunks/ai-MISD5ZKB.js +260 -0
  7. package/dist/chunks/args-FJPX5SKE.js +8 -0
  8. package/dist/chunks/attach-STVPRW4U.js +30 -0
  9. package/dist/chunks/chunk-66N3P624.js +44 -0
  10. package/dist/chunks/chunk-IJ5VA4HN.js +41 -0
  11. package/dist/chunks/chunk-INTJPVJZ.js +191 -0
  12. package/dist/chunks/chunk-NM755IGG.js +658 -0
  13. package/dist/chunks/chunk-PA67Y4XN.js +65 -0
  14. package/dist/chunks/chunk-U52LFC23.js +68 -0
  15. package/dist/chunks/chunk-YFGNBX2I.js +229 -0
  16. package/dist/chunks/chunk-YHQYNBAN.js +801 -0
  17. package/dist/chunks/commands-IWTFRW33.js +540 -0
  18. package/dist/chunks/context-QML5TP36.js +14 -0
  19. package/dist/chunks/help-I5WIJHZM.js +359 -0
  20. package/dist/chunks/paths-X3C4P67K.js +18 -0
  21. package/dist/chunks/run-RNFQMMXD.js +95 -0
  22. package/dist/chunks/setup-WIZULKES.js +106 -0
  23. package/dist/chunks/themes.gen-E3CTYIQE.js +8 -0
  24. package/dist/chunks/upgrade-43JWCQ63.js +143 -0
  25. package/dist/chunks/verify-55DFXJOY.js +37 -0
  26. package/dist/cli/args.d.ts +13 -0
  27. package/dist/cli/commands.d.ts +5 -0
  28. package/dist/cli/help.d.ts +2 -0
  29. package/dist/cli/main.d.ts +2 -0
  30. package/dist/cli/main.js +83 -0
  31. package/dist/cli/run.d.ts +2 -0
  32. package/dist/cli/setup.d.ts +6 -0
  33. package/dist/cli/upgrade.d.ts +19 -0
  34. package/dist/cli/verify.d.ts +2 -0
  35. package/dist/context.d.ts +33 -0
  36. package/dist/engine.d.ts +56 -0
  37. package/dist/errors.d.ts +4 -0
  38. package/dist/expect.d.ts +62 -0
  39. package/dist/index.d.ts +27 -0
  40. package/dist/index.js +205 -0
  41. package/dist/install.d.ts +13 -0
  42. package/dist/instances.d.ts +23 -0
  43. package/dist/locator.d.ts +49 -0
  44. package/dist/paths.d.ts +7 -0
  45. package/dist/runner.d.ts +56 -0
  46. package/dist/sync.d.ts +8 -0
  47. package/dist/terminal.d.ts +146 -0
  48. package/dist/themes.gen.d.ts +4 -0
  49. package/dist/types.d.ts +214 -0
  50. package/package.json +41 -4
  51. package/skill/testingterm/SKILL.md +138 -0
  52. package/README.md +0 -3
@@ -0,0 +1,801 @@
1
+ import {
2
+ resolveCapabilities,
3
+ syncTheme
4
+ } from "./chunk-INTJPVJZ.js";
5
+ import {
6
+ EngineError,
7
+ newId,
8
+ removeInstance,
9
+ socketPath,
10
+ startEngine,
11
+ writeInstance
12
+ } from "./chunk-YFGNBX2I.js";
13
+ import {
14
+ currentScope,
15
+ rootScope,
16
+ safeName,
17
+ scopes,
18
+ settings
19
+ } from "./chunk-IJ5VA4HN.js";
20
+ import {
21
+ PACKAGE_ROOT
22
+ } from "./chunk-PA67Y4XN.js";
23
+
24
+ // src/locator.ts
25
+ import { setTimeout as sleep } from "node:timers/promises";
26
+ var POLL_MS = 30;
27
+ var LocatorError = class extends Error {
28
+ screen;
29
+ constructor(message, screen) {
30
+ super(message);
31
+ this.name = "LocatorError";
32
+ this.screen = screen;
33
+ }
34
+ };
35
+ var Locator = class _Locator {
36
+ terminal;
37
+ query;
38
+ exact;
39
+ index;
40
+ constructor(terminal, query, exact, index) {
41
+ this.terminal = terminal;
42
+ this.query = query;
43
+ this.exact = exact;
44
+ this.index = index;
45
+ }
46
+ toString() {
47
+ const nth = this.index === null ? "" : this.index === -1 ? ".last()" : `.nth(${this.index})`;
48
+ return `getByText(${this.query instanceof RegExp ? String(this.query) : JSON.stringify(this.query)})${nth}`;
49
+ }
50
+ // fixme: placeholder copy
51
+ /** The first match. */
52
+ first() {
53
+ return new _Locator(this.terminal, this.query, this.exact, 0);
54
+ }
55
+ // fixme: placeholder copy
56
+ /** The last match. */
57
+ last() {
58
+ return new _Locator(this.terminal, this.query, this.exact, -1);
59
+ }
60
+ // fixme: placeholder copy
61
+ /** The match at `index`, counting from 0 in reading order. */
62
+ nth(index) {
63
+ return new _Locator(this.terminal, this.query, this.exact, index);
64
+ }
65
+ // fixme: placeholder copy
66
+ /** Every current match, without waiting. */
67
+ async all() {
68
+ let boxes = await this.terminal.find(this.query);
69
+ if (this.exact && typeof this.query === "string") {
70
+ const lines = (await this.terminal.screen()).lines;
71
+ boxes = boxes.filter((box) => {
72
+ const line = lines[box.row] ?? "";
73
+ const chars = [...line];
74
+ const before = chars[box.col - 1];
75
+ const after = chars[box.col + [...box.text].length];
76
+ return (before === void 0 || /\s/.test(before)) && (after === void 0 || /\s/.test(after));
77
+ });
78
+ }
79
+ return boxes;
80
+ }
81
+ // fixme: placeholder copy
82
+ /** How many places match right now. */
83
+ async count() {
84
+ return (await this.all()).length;
85
+ }
86
+ // fixme: placeholder copy
87
+ /** Whether it matches right now, without waiting. */
88
+ async isVisible() {
89
+ return await this.count() > 0;
90
+ }
91
+ pick(boxes) {
92
+ if (boxes.length === 0) return null;
93
+ if (this.index === null) return boxes.length === 1 ? boxes[0] : "ambiguous";
94
+ return (this.index === -1 ? boxes.at(-1) : boxes[this.index]) ?? null;
95
+ }
96
+ // fixme: placeholder copy
97
+ /** Wait for the text, then return where it is on screen. Errors if several places match and no index was chosen. */
98
+ async box(options = {}) {
99
+ const timeout = options.timeout ?? this.terminal.timeout;
100
+ const deadline = Date.now() + timeout;
101
+ try {
102
+ await this.terminal.waitForText(this.query, { timeout });
103
+ } catch (error) {
104
+ const screen = error.screen;
105
+ throw new LocatorError(`${this} did not appear within ${timeout}ms`, screen);
106
+ }
107
+ for (; ; ) {
108
+ const boxes = await this.all();
109
+ const picked = this.pick(boxes);
110
+ if (picked === "ambiguous") {
111
+ const places = boxes.map((b) => ` row ${b.row}, col ${b.col}: ${JSON.stringify(b.text)}`).join("\n");
112
+ throw new LocatorError(`${this} matched ${boxes.length} places; use .first(), .last() or .nth(i) to pick one:
113
+ ${places}`);
114
+ }
115
+ if (picked) return picked;
116
+ if (Date.now() >= deadline) {
117
+ throw new LocatorError(`${this} did not appear within ${timeout}ms`, await this.terminal.text().catch(() => void 0));
118
+ }
119
+ await sleep(POLL_MS);
120
+ }
121
+ }
122
+ // fixme: placeholder copy
123
+ /** Wait until the text is visible (default) or hidden. */
124
+ async waitFor(options = {}) {
125
+ if (options.state !== "hidden") {
126
+ await this.box(options);
127
+ return;
128
+ }
129
+ const timeout = options.timeout ?? this.terminal.timeout;
130
+ if (typeof this.query === "string" && !this.exact && this.index === null) {
131
+ await this.terminal.waitForGone(this.query, { timeout });
132
+ return;
133
+ }
134
+ const deadline = Date.now() + timeout;
135
+ while (await this.count() > 0) {
136
+ if (Date.now() >= deadline) throw new LocatorError(`${this} was still visible after ${timeout}ms`, await this.terminal.text());
137
+ await sleep(POLL_MS);
138
+ }
139
+ }
140
+ // fixme: placeholder copy
141
+ /** Wait for the text and click its center. */
142
+ async click(options = {}) {
143
+ const box = await this.box(options);
144
+ await this.terminal.click(box.center, options);
145
+ return box;
146
+ }
147
+ // fixme: placeholder copy
148
+ /** Wait for the text and double click it. */
149
+ async dblclick(options = {}) {
150
+ return this.click({ ...options, count: 2 });
151
+ }
152
+ // fixme: placeholder copy
153
+ /** Wait for the text and move the mouse over it. */
154
+ async hover(options = {}) {
155
+ const box = await this.box(options);
156
+ await this.terminal.move(box.center);
157
+ return box;
158
+ }
159
+ };
160
+
161
+ // src/terminal.ts
162
+ import fs from "node:fs";
163
+ import path from "node:path";
164
+ import { setTimeout as sleep2 } from "node:timers/promises";
165
+ var SHELL_BUILTINS = /* @__PURE__ */ new Set(["exit", "cd", "export", "source", ".", "set", "unset", "alias", "eval", "exec", "read", "trap", "wait", "ulimit", "umask", "shift", "return", "break", "continue", "readonly", "local", "type", "hash", "jobs", "fg", "bg"]);
166
+ function argv(command) {
167
+ if (command === void 0) return [];
168
+ if (Array.isArray(command)) return command;
169
+ const simple = /^[\w@%+=:,./-]+(\s+[\w@%+=:,./-]+)*$/.test(command.trim()) && !SHELL_BUILTINS.has(command.trim().split(/\s+/)[0]);
170
+ return ["/bin/sh", "-c", simple ? `exec ${command.trim()}` : command];
171
+ }
172
+ function label(command) {
173
+ if (command.length === 0) return "shell";
174
+ if (command[0] === "/bin/sh" && command[1] === "-c") return command[2].replace(/^exec\s+/, "").split(/\s+/)[0];
175
+ return path.basename(command[0]);
176
+ }
177
+ function regexParams(query, key = "text") {
178
+ if (query instanceof RegExp) return { regex: query.source, flags: query.flags };
179
+ return { [key]: query };
180
+ }
181
+ var Terminal = class _Terminal {
182
+ id;
183
+ name;
184
+ artifacts;
185
+ command;
186
+ // fixme: placeholder copy
187
+ /** Default timeout for waits, locators and assertions, in milliseconds. */
188
+ timeout;
189
+ connection;
190
+ engine;
191
+ scope;
192
+ slowMo;
193
+ videoMode;
194
+ geometry = null;
195
+ shots = 0;
196
+ closing = null;
197
+ home = null;
198
+ recordingPath = null;
199
+ // fixme: placeholder copy
200
+ /** What this terminal supports, after presets are applied. */
201
+ capabilities;
202
+ constructor(options, scope) {
203
+ this.scope = scope;
204
+ this.id = newId();
205
+ this.command = argv(options.command);
206
+ this.name = safeName(options.name ?? label(this.command));
207
+ this.artifacts = path.resolve(options.artifacts ?? scope.artifacts);
208
+ this.timeout = options.timeout ?? settings.timeout;
209
+ this.slowMo = options.slowMo ?? settings.slowMo;
210
+ const env = {};
211
+ const removed = [];
212
+ for (const [key, value] of Object.entries(options.env ?? {})) {
213
+ if (value === void 0) removed.push(key);
214
+ else env[key] = value;
215
+ }
216
+ if (options.isolate) {
217
+ this.home = fs.mkdtempSync(path.join(this.artifacts, `.home-${this.name}-`));
218
+ Object.assign(env, {
219
+ HOME: this.home,
220
+ XDG_CONFIG_HOME: path.join(this.home, ".config"),
221
+ XDG_DATA_HOME: path.join(this.home, ".local", "share"),
222
+ XDG_STATE_HOME: path.join(this.home, ".local", "state"),
223
+ XDG_CACHE_HOME: path.join(this.home, ".cache"),
224
+ ZDOTDIR: this.home
225
+ });
226
+ }
227
+ this.videoMode = options.record ? "on" : settings.video;
228
+ const record = typeof options.record === "string" ? path.resolve(options.record) : this.videoMode !== "off" ? this.file("mp4") : void 0;
229
+ this.recordingPath = record ?? null;
230
+ const profile = typeof options.profile === "string" ? path.resolve(options.profile) : options.profile || settings.profile ? this.file("profile.json") : void 0;
231
+ const headed = options.headed ?? settings.headed;
232
+ this.capabilities = resolveCapabilities(options.capabilities ?? settings.capabilities);
233
+ const requested = options.theme ?? settings.theme ?? "dark";
234
+ const synced = syncTheme(requested);
235
+ const config = {
236
+ command: this.command,
237
+ cwd: options.cwd ? path.resolve(options.cwd) : process.cwd(),
238
+ env,
239
+ cols: options.cols ?? 100,
240
+ rows: options.rows ?? 30,
241
+ fontSize: options.fontSize ?? synced?.fontSize ?? 13,
242
+ scale: options.scale ?? 2,
243
+ padding: options.padding ?? 8,
244
+ theme: synced?.theme ?? requested,
245
+ headed,
246
+ stdio: true,
247
+ listen: socketPath(this.id),
248
+ record,
249
+ fps: options.fps ?? 30,
250
+ overlay: options.overlay ?? true,
251
+ profile,
252
+ keepAlive: false,
253
+ cursor: options.cursor ?? true,
254
+ title: options.name ? `testingterm \u2014 ${options.name}` : void 0,
255
+ capabilities: this.capabilities
256
+ };
257
+ const saved = {};
258
+ for (const key of removed) {
259
+ saved[key] = process.env[key];
260
+ delete process.env[key];
261
+ }
262
+ try {
263
+ this.engine = startEngine(config);
264
+ } finally {
265
+ for (const [key, value] of Object.entries(saved)) if (value !== void 0) process.env[key] = value;
266
+ }
267
+ this.connection = this.engine.connection;
268
+ writeInstance({
269
+ id: this.id,
270
+ name: this.name,
271
+ pid: this.engine.process.pid ?? 0,
272
+ socket: config.listen,
273
+ command: this.command,
274
+ cwd: config.cwd,
275
+ cols: config.cols,
276
+ rows: config.rows,
277
+ createdAt: Date.now(),
278
+ owner: "script",
279
+ ownerPid: process.pid,
280
+ artifacts: this.artifacts,
281
+ headed
282
+ });
283
+ this.engine.process.once("exit", () => removeInstance(this.id));
284
+ }
285
+ // fixme: placeholder copy
286
+ /** Start a program in a new terminal. See {@link launch}. */
287
+ static launch(options = {}) {
288
+ const scope = currentScope();
289
+ fs.mkdirSync(path.resolve(options.artifacts ?? scope.artifacts), { recursive: true });
290
+ const terminal = new _Terminal(options, scope);
291
+ scope.terminals.add(terminal);
292
+ return terminal;
293
+ }
294
+ file(extension, stem) {
295
+ return path.join(this.artifacts, `${stem ?? `${this.name}-${this.id}`}.${extension}`);
296
+ }
297
+ step(action) {
298
+ this.scope.steps.push({ at: Date.now() - this.scope.started, action, terminal: this.name });
299
+ }
300
+ tag(promise) {
301
+ return promise.catch((error) => {
302
+ if (error && typeof error === "object") error.terminal ??= this;
303
+ throw error;
304
+ });
305
+ }
306
+ async act(op, params, action) {
307
+ this.step(action);
308
+ const reply = await this.tag(this.connection.request(op, params));
309
+ if (this.slowMo > 0) await sleep2(this.slowMo);
310
+ return reply;
311
+ }
312
+ async geometryInfo() {
313
+ if (!this.geometry) this.geometry = await this.connection.request("info");
314
+ return this.geometry;
315
+ }
316
+ // fixme: placeholder copy
317
+ /** The engine's own process id, the program's process id, sizes and recording state. */
318
+ async info() {
319
+ const { id: _, ok: __, ...rest } = await this.connection.request("info");
320
+ return rest;
321
+ }
322
+ // fixme: placeholder copy
323
+ /** Read the visible screen: text, lines, cursor, title and terminal modes. */
324
+ async screen() {
325
+ const { id: _, ok: __, version: ___, ...screen } = await this.connection.request("screen");
326
+ return screen;
327
+ }
328
+ // fixme: placeholder copy
329
+ /** The visible screen as plain text. */
330
+ async text() {
331
+ return (await this.screen()).text;
332
+ }
333
+ // fixme: placeholder copy
334
+ /** Every line the program printed, including lines scrolled off the top. */
335
+ async scrollback() {
336
+ return (await this.connection.request("scrollback")).text;
337
+ }
338
+ // fixme: placeholder copy
339
+ /** The screen as rows of styled spans with colors and attributes, for checking how text looks. */
340
+ async styles() {
341
+ const rows = (await this.connection.request("screen", { styles: true })).styles;
342
+ return rows.map((spans) => {
343
+ const trimmed = [...spans];
344
+ while (trimmed.length && !trimmed.at(-1).text.trim() && Object.keys(trimmed.at(-1)).length === 2) trimmed.pop();
345
+ if (trimmed.length && Object.keys(trimmed.at(-1)).length === 2) trimmed[trimmed.length - 1] = { ...trimmed.at(-1), text: trimmed.at(-1).text.trimEnd() };
346
+ return trimmed;
347
+ });
348
+ }
349
+ // fixme: placeholder copy
350
+ /** Type text like a person at a keyboard. `\n` presses Enter. */
351
+ async type(text, options = {}) {
352
+ await this.act("type", { text, delay: options.delay ?? 0 }, `type ${JSON.stringify(text)}`);
353
+ }
354
+ // fixme: placeholder copy
355
+ /** Press keys: "Enter", "ctrl+c", "shift+Tab", "Up", "F5", "a". Pass several to press them in order. */
356
+ async press(keys, options = {}) {
357
+ const list = Array.isArray(keys) ? keys : [keys];
358
+ await this.act("press", { keys: list, count: options.count ?? 1 }, `press ${list.join(" ")}${options.count ? ` \xD7${options.count}` : ""}`);
359
+ }
360
+ // fixme: placeholder copy
361
+ /** Paste text, wrapped in bracketed paste when the program asked for it. */
362
+ async paste(text) {
363
+ await this.act("paste", { text }, `paste ${text.length} chars`);
364
+ }
365
+ point(point) {
366
+ return "col" in point ? { x: point.col, y: point.row, unit: "cell" } : { x: point.x, y: point.y };
367
+ }
368
+ describePoint(point) {
369
+ return "col" in point ? `cell ${point.col},${point.row}` : `${Math.round(point.x)},${Math.round(point.y)}`;
370
+ }
371
+ // fixme: placeholder copy
372
+ /** Click at a point in screenshot pixels, or at a cell with `{ col, row }`. Only programs that turned on mouse reporting see clicks. */
373
+ async click(point, options = {}) {
374
+ return this.act("mouse", { action: "click", ...this.point(point), button: options.button, count: options.count ?? 1, mods: options.modifiers }, `click ${this.describePoint(point)}`);
375
+ }
376
+ // fixme: placeholder copy
377
+ /** Double click at a point. */
378
+ async dblclick(point, options = {}) {
379
+ return this.click(point, { ...options, count: 2 });
380
+ }
381
+ // fixme: placeholder copy
382
+ /** Move the mouse to a point (hover). */
383
+ async move(point) {
384
+ await this.act("mouse", { action: "move", ...this.point(point) }, `move ${this.describePoint(point)}`);
385
+ }
386
+ // fixme: placeholder copy
387
+ /** Press a mouse button down at a point. */
388
+ async down(point, options = {}) {
389
+ await this.act("mouse", { action: "down", ...this.point(point), button: options.button }, `mouse down ${this.describePoint(point)}`);
390
+ }
391
+ // fixme: placeholder copy
392
+ /** Release a mouse button at a point. */
393
+ async up(point, options = {}) {
394
+ await this.act("mouse", { action: "up", ...this.point(point), button: options.button }, `mouse up ${this.describePoint(point)}`);
395
+ }
396
+ // fixme: placeholder copy
397
+ /** Drag from one point to another with the left button held. */
398
+ async drag(from, to, options = {}) {
399
+ await this.down(from);
400
+ const steps = Math.max(1, options.steps ?? 5);
401
+ const geometry = await this.geometryInfo();
402
+ const pixel = (p) => "col" in p ? { x: geometry.padding + (p.col + 0.5) * geometry.cellWidth, y: geometry.padding + (p.row + 0.5) * geometry.cellHeight } : p;
403
+ const a = pixel(from);
404
+ const b = pixel(to);
405
+ for (let i = 1; i <= steps; i++) {
406
+ await this.connection.request("mouse", { action: "move", x: a.x + (b.x - a.x) * i / steps, y: a.y + (b.y - a.y) * i / steps });
407
+ }
408
+ await this.up(to);
409
+ }
410
+ // fixme: placeholder copy
411
+ /** Scroll the mouse wheel. Positive lines scroll down. */
412
+ async wheel(lines, at) {
413
+ const geometry = await this.geometryInfo();
414
+ const point = at ?? { x: geometry.width / 2, y: geometry.height / 2 };
415
+ await this.act("mouse", { action: "wheel", deltaY: lines, ...this.point(point) }, `wheel ${lines}`);
416
+ }
417
+ // fixme: placeholder copy
418
+ /** Find text on the screen. The locator waits for the text before acting on it. */
419
+ getByText(text, options = {}) {
420
+ return new Locator(this, text, options.exact ?? false, null);
421
+ }
422
+ // fixme: placeholder copy
423
+ /** Every place `text` appears on the screen right now, with pixel and cell positions. */
424
+ async find(text) {
425
+ const reply = await this.connection.request("find", text instanceof RegExp ? { regex: text.source, flags: text.flags } : { text });
426
+ return reply.matches;
427
+ }
428
+ wait(params, options, action) {
429
+ this.step(action);
430
+ return this.tag(this.connection.request("wait", { ...params, timeout: options.timeout ?? this.timeout, scrollback: options.scrollback ?? false }));
431
+ }
432
+ // fixme: placeholder copy
433
+ /** Wait until the text (or a regex match) is on the screen. Resolves with the matched text. */
434
+ async waitForText(text, options = {}) {
435
+ const reply = await this.wait(regexParams(text), options, `wait for ${String(text)}`);
436
+ return reply.match ?? String(text);
437
+ }
438
+ // fixme: placeholder copy
439
+ /** Wait until the text is no longer on the screen. */
440
+ async waitForGone(text, options = {}) {
441
+ await this.wait({ gone: text }, options, `wait for ${JSON.stringify(text)} to disappear`);
442
+ }
443
+ // fixme: placeholder copy
444
+ /** Wait until the program has printed nothing for `ms` milliseconds. */
445
+ async waitForIdle(ms = 100, options = {}) {
446
+ await this.wait({ idle: ms }, options, `wait for ${ms}ms of quiet`);
447
+ }
448
+ // fixme: placeholder copy
449
+ /** Wait until the screen has not changed for `ms` milliseconds. Useful after animations and spinners. */
450
+ async waitForStable(ms = 150, options = {}) {
451
+ await this.wait({ stable: ms }, options, `wait for the screen to settle for ${ms}ms`);
452
+ }
453
+ // fixme: placeholder copy
454
+ /** Wait until the window title contains `title`. */
455
+ async waitForTitle(title, options = {}) {
456
+ await this.wait({ title }, options, `wait for title ${JSON.stringify(title)}`);
457
+ }
458
+ // fixme: placeholder copy
459
+ /** Wait for the program to exit and return its exit code. */
460
+ async waitForExit(options = {}) {
461
+ const reply = await this.wait({ exit: true }, options, "wait for exit");
462
+ return { exitCode: reply.exitCode ?? null, signal: reply.signal ?? null };
463
+ }
464
+ // fixme: placeholder copy
465
+ /** Save a PNG of the terminal exactly as a person would see it. */
466
+ async screenshot(options = {}) {
467
+ const file = options.path ? path.resolve(options.path) : this.file("png", `${this.name}-${this.id}-${options.name ? safeName(options.name) : String(++this.shots).padStart(2, "0")}`);
468
+ const reply = await this.connection.request("screenshot", { path: file, cursor: options.cursor });
469
+ this.scope.produced.push(file);
470
+ this.step(`screenshot ${file}`);
471
+ return { path: reply.path, width: reply.width, height: reply.height };
472
+ }
473
+ // fixme: placeholder copy
474
+ /** Start recording a video. Stop it with {@link stopRecording}. */
475
+ async startRecording(options = {}) {
476
+ const file = options.path ? path.resolve(options.path) : this.file("mp4", `${this.name}-${this.id}-${Date.now()}`);
477
+ await this.connection.request("record", { action: "start", path: file, fps: options.fps });
478
+ this.recordingPath = file;
479
+ return file;
480
+ }
481
+ // fixme: placeholder copy
482
+ /** Stop the video and return its path. */
483
+ async stopRecording() {
484
+ const reply = await this.connection.request("record", { action: "stop" });
485
+ this.recordingPath = null;
486
+ this.scope.produced.push(reply.path);
487
+ return { path: reply.path, durationMs: reply.durationMs };
488
+ }
489
+ // fixme: placeholder copy
490
+ /** Start a performance profile: program output, CPU and memory, frames, and every action. */
491
+ async startProfile(options = {}) {
492
+ const file = options.path ? path.resolve(options.path) : this.file("profile.json", `${this.name}-${this.id}-${Date.now()}`);
493
+ await this.connection.request("profile", { action: "start", path: file });
494
+ return file;
495
+ }
496
+ // fixme: placeholder copy
497
+ /** Stop the profile and return its path. Open it at https://ui.perfetto.dev. */
498
+ async stopProfile() {
499
+ const reply = await this.connection.request("profile", { action: "stop" });
500
+ this.scope.produced.push(reply.path);
501
+ return reply.path;
502
+ }
503
+ // fixme: placeholder copy
504
+ /** Switch to another theme while the program runs: a name like "Dracula", or colors like `{ base: "Nord", background: "#000000" }`. */
505
+ async setTheme(theme) {
506
+ await this.act("theme", { theme: syncTheme(theme)?.theme ?? theme }, `theme ${typeof theme === "string" ? theme : JSON.stringify(theme)}`);
507
+ }
508
+ // fixme: placeholder copy
509
+ /** Change the grid size; the program gets SIGWINCH. */
510
+ async resize(cols, rows) {
511
+ this.geometry = null;
512
+ await this.act("resize", { cols, rows }, `resize ${cols}x${rows}`);
513
+ }
514
+ // fixme: placeholder copy
515
+ /** Send a signal to the program, like "SIGINT" or "SIGTERM". */
516
+ async signal(signal) {
517
+ await this.act("signal", { signal }, `signal ${signal}`);
518
+ }
519
+ // fixme: placeholder copy
520
+ /** Tell the program the terminal gained or lost focus (if it asked to know). */
521
+ async focus(focused = true) {
522
+ await this.act("focus", { focused }, focused ? "focus" : "blur");
523
+ }
524
+ // fixme: placeholder copy
525
+ /** Scroll the terminal's own view into history (negative is up). Changes screenshots, not the program. */
526
+ async scroll(lines) {
527
+ await this.act("scroll", { lines }, `scroll ${lines}`);
528
+ }
529
+ // fixme: placeholder copy
530
+ /**
531
+ * Experimental: ask a coding agent (Claude Code or Codex, through ACP) to look at the terminal and check
532
+ * something that is hard to assert in code. Throws when the agent says the check failed.
533
+ */
534
+ async verify(expectation, options = {}) {
535
+ const { verify } = await import("./ai-MISD5ZKB.js");
536
+ this.step(`verify ${JSON.stringify(expectation)}`);
537
+ const result = await verify(this, expectation, options, this.scope, new Error().stack ?? "");
538
+ this.scope.produced.push(...result.artifacts);
539
+ if (!result.pass && !options.soft) {
540
+ const error = new Error(`${result.error ? `verify could not run: ${result.error}` : `verify failed: ${expectation}
541
+ ${result.agent} says: ${result.reason}`}${result.artifacts.length ? `
542
+ artifacts:
543
+ ${result.artifacts.join("\n ")}` : ""}`);
544
+ error.name = "VerifyError";
545
+ throw error;
546
+ }
547
+ return result;
548
+ }
549
+ // fixme: placeholder copy
550
+ /** Results that agents and other tools reported with `testingterm report`. */
551
+ async reports() {
552
+ return (await this.connection.request("reports")).reports;
553
+ }
554
+ // fixme: placeholder copy
555
+ /** The socket other processes (the testingterm CLI, agents) use to reach this terminal. */
556
+ get socket() {
557
+ return socketPath(this.id);
558
+ }
559
+ async failureArtifacts() {
560
+ const files = [];
561
+ try {
562
+ files.push((await this.screenshot({ name: "failure" })).path);
563
+ const text = this.file("txt", `${this.name}-${this.id}-failure`);
564
+ fs.writeFileSync(text, await this.scrollback().catch(() => ""));
565
+ files.push(text);
566
+ } catch {
567
+ }
568
+ return files;
569
+ }
570
+ // fixme: placeholder copy
571
+ /** Stop the program and the terminal. Finishes any video and profile and returns their paths. */
572
+ close(options = {}) {
573
+ this.closing ??= (async () => {
574
+ let summary = {};
575
+ try {
576
+ const reply = await this.connection.request("close");
577
+ summary = { video: reply.video, profile: reply.profile };
578
+ } catch (error) {
579
+ if (!(error instanceof EngineError)) throw error;
580
+ }
581
+ this.connection.close();
582
+ removeInstance(this.id);
583
+ this.scope.terminals.delete(this);
584
+ if (summary.video && this.videoMode === "retain-on-failure" && !options.keepVideo) {
585
+ fs.rmSync(summary.video, { force: true });
586
+ summary.video = void 0;
587
+ }
588
+ if (summary.video) this.scope.produced.push(summary.video);
589
+ if (summary.profile) this.scope.produced.push(summary.profile);
590
+ if (this.home) fs.rmSync(this.home, { recursive: true, force: true });
591
+ return summary;
592
+ })();
593
+ return this.closing;
594
+ }
595
+ get recording() {
596
+ return this.recordingPath;
597
+ }
598
+ };
599
+
600
+ // src/runner.ts
601
+ import fs2 from "node:fs";
602
+ import module from "node:module";
603
+ import os from "node:os";
604
+ import path2 from "node:path";
605
+ import { fileURLToPath, pathToFileURL } from "node:url";
606
+ var registry = [];
607
+ var OWN = path2.resolve(PACKAGE_ROOT);
608
+ function callerFile() {
609
+ for (const frame of (new Error().stack ?? "").split("\n").slice(2)) {
610
+ const match = /\(?((?:file:\/\/)?\/[^():]+):\d+:\d+\)?\s*$/.exec(frame);
611
+ if (!match) continue;
612
+ const file = match[1].startsWith("file://") ? fileURLToPath(match[1]) : match[1];
613
+ if (!file.startsWith(OWN)) {
614
+ try {
615
+ return fs2.realpathSync(file);
616
+ } catch {
617
+ return file;
618
+ }
619
+ }
620
+ }
621
+ return "unknown";
622
+ }
623
+ function register(name, fn, options, flags) {
624
+ registry.push({ name, fn, file: callerFile(), only: Boolean(flags.only), skip: Boolean(flags.skip), options });
625
+ }
626
+ var test = Object.assign((name, fn, options = {}) => register(name, fn, options, {}), {
627
+ only: (name, fn, options = {}) => register(name, fn, options, { only: true }),
628
+ skip: (name, fn, options = {}) => register(name, fn, options, { skip: true })
629
+ });
630
+ function normalizeLaunch(command, options = {}) {
631
+ if (command === void 0) return options;
632
+ if (typeof command === "string" || Array.isArray(command)) return { ...options, command };
633
+ return { ...command, ...options };
634
+ }
635
+ var hooked = false;
636
+ function hookResolution() {
637
+ if (hooked) return;
638
+ hooked = true;
639
+ const built = path2.join(PACKAGE_ROOT, "dist", "index.js");
640
+ const entry = pathToFileURL(fs2.existsSync(built) ? built : path2.join(PACKAGE_ROOT, "src", "index.ts")).href;
641
+ const registerHooks = module.registerHooks;
642
+ registerHooks?.({
643
+ resolve(specifier, context, next) {
644
+ if (specifier === "testingterm") return { url: entry, shortCircuit: true, format: "module" };
645
+ return next(specifier, context);
646
+ }
647
+ });
648
+ }
649
+ function scopeFor(name, file, artifacts) {
650
+ return { name, file, artifacts, terminals: /* @__PURE__ */ new Set(), produced: [], steps: [], started: Date.now() };
651
+ }
652
+ function describeError(error) {
653
+ if (error instanceof Error) {
654
+ const screen = error.screen;
655
+ const clean = ["AssertionError", "LocatorError", "VerifyError", "EngineError", "TimeoutError"].includes(error.name);
656
+ const message = clean ? error.message : error.stack ?? error.message;
657
+ return { message, screen };
658
+ }
659
+ return { message: String(error) };
660
+ }
661
+ async function finish(scope, failed, error) {
662
+ const produced = [...scope.produced];
663
+ const culprit = error?.terminal;
664
+ for (const terminal of [...scope.terminals]) {
665
+ if (failed && (!culprit || culprit === terminal)) produced.push(...await terminal.failureArtifacts().catch(() => []));
666
+ const summary = await terminal.close({ keepVideo: failed }).catch(() => ({}));
667
+ if (summary.video) produced.push(summary.video);
668
+ if (summary.profile) produced.push(summary.profile);
669
+ }
670
+ return [...new Set(produced)].filter((file) => fs2.existsSync(file));
671
+ }
672
+ async function withTimeout(promise, ms, name) {
673
+ let timer;
674
+ try {
675
+ return await Promise.race([
676
+ promise,
677
+ // fixme: placeholder copy
678
+ new Promise((_, reject) => {
679
+ timer = setTimeout(() => {
680
+ const error = new Error(`test "${name}" timed out after ${ms}ms`);
681
+ error.name = "TimeoutError";
682
+ reject(error);
683
+ }, ms);
684
+ })
685
+ ]);
686
+ } finally {
687
+ clearTimeout(timer);
688
+ }
689
+ }
690
+ async function runCase(test2, root, defaults) {
691
+ const base = path2.basename(test2.file).replace(/\.[^.]+$/, "");
692
+ const started = Date.now();
693
+ if (test2.skip) return { file: test2.file, name: test2.name, status: "skipped", durationMs: 0, attempts: 0, artifacts: [] };
694
+ const retries = test2.options.retries ?? defaults.retries;
695
+ let last = null;
696
+ for (let attempt = 1; attempt <= retries + 1; attempt++) {
697
+ const artifacts = path2.join(root, safeName(`${base}-${test2.name}${attempt > 1 ? `-retry${attempt - 1}` : ""}`));
698
+ fs2.mkdirSync(artifacts, { recursive: true });
699
+ const scope = scopeFor(test2.name, test2.file, artifacts);
700
+ const context = {
701
+ name: test2.name,
702
+ artifacts,
703
+ launch: (command, options) => scopes.run(scope, () => Terminal.launch(normalizeLaunch(command, options)))
704
+ };
705
+ let error = null;
706
+ try {
707
+ await scopes.run(scope, () => withTimeout(Promise.resolve().then(() => test2.fn(context)), test2.options.timeout ?? defaults.timeout, test2.name));
708
+ } catch (caught) {
709
+ error = caught;
710
+ }
711
+ const files = await finish(scope, error !== null, error);
712
+ if (error === null) return { file: test2.file, name: test2.name, status: "passed", durationMs: Date.now() - started, attempts: attempt, artifacts: files };
713
+ const described = describeError(error);
714
+ last = { file: test2.file, name: test2.name, status: "failed", durationMs: Date.now() - started, attempts: attempt, error: described.message, screen: described.screen, artifacts: files };
715
+ }
716
+ return last;
717
+ }
718
+ async function runFile(file, options) {
719
+ const absolute = fs2.realpathSync(path2.resolve(file));
720
+ const base = path2.basename(absolute).replace(/\.[^.]+$/, "");
721
+ const scope = scopeFor(base, absolute, path2.join(options.artifacts, safeName(base)));
722
+ fs2.mkdirSync(scope.artifacts, { recursive: true });
723
+ const before = registry.length;
724
+ const started = Date.now();
725
+ let error = null;
726
+ try {
727
+ await scopes.run(scope, () => import(pathToFileURL(absolute).href));
728
+ } catch (caught) {
729
+ error = caught;
730
+ }
731
+ const declared = registry.slice(before).filter((t) => t.file === absolute || t.file === "unknown");
732
+ const results = [];
733
+ const scriptFailed = error !== null;
734
+ if (declared.length === 0 || scriptFailed) {
735
+ const files = await finish(scope, scriptFailed, error);
736
+ const described = scriptFailed ? describeError(error) : null;
737
+ const result = {
738
+ file: absolute,
739
+ name: base,
740
+ status: scriptFailed ? "failed" : "passed",
741
+ durationMs: Date.now() - started,
742
+ attempts: 1,
743
+ error: described?.message,
744
+ screen: described?.screen,
745
+ artifacts: files
746
+ };
747
+ options.onResult?.(result);
748
+ results.push(result);
749
+ if (declared.length === 0) return results;
750
+ } else {
751
+ await finish(scope, false);
752
+ }
753
+ const only = declared.some((t) => t.only);
754
+ for (const test2 of declared) {
755
+ const selected = (!only || test2.only) && (!options.grep || options.grep.test(test2.name));
756
+ if (!selected && options.grep && !only) continue;
757
+ const result = selected ? await runCase(test2, scope.artifacts, options) : { file: absolute, name: test2.name, status: "skipped", durationMs: 0, attempts: 0, artifacts: [] };
758
+ options.onResult?.(result);
759
+ results.push(result);
760
+ }
761
+ return results;
762
+ }
763
+ async function runFiles(files, options) {
764
+ hookResolution();
765
+ const started = Date.now();
766
+ settings.artifacts = options.artifacts;
767
+ rootScope.artifacts = options.artifacts;
768
+ const queue = [...files];
769
+ const results = [];
770
+ const workers = Array.from({ length: Math.max(1, Math.min(options.workers, files.length)) }, async () => {
771
+ for (let file = queue.shift(); file !== void 0; file = queue.shift()) {
772
+ const index = files.indexOf(file);
773
+ results[index] = await runFile(file, options);
774
+ }
775
+ });
776
+ await Promise.all(workers);
777
+ const tests = results.flat();
778
+ return { ok: tests.every((t) => t.status !== "failed"), durationMs: Date.now() - started, artifacts: options.artifacts, tests };
779
+ }
780
+ function evalFile(code, dir) {
781
+ fs2.mkdirSync(dir, { recursive: true });
782
+ const file = path2.join(dir, `eval-${process.pid}.mjs`);
783
+ fs2.writeFileSync(file, `import { launch, expect, test, Terminal } from "testingterm";
784
+ ${code}
785
+ `);
786
+ return file;
787
+ }
788
+ function defaultWorkers() {
789
+ return Math.max(1, Math.min(8, os.availableParallelism?.() ?? os.cpus().length));
790
+ }
791
+
792
+ export {
793
+ LocatorError,
794
+ Locator,
795
+ Terminal,
796
+ test,
797
+ normalizeLaunch,
798
+ runFiles,
799
+ evalFile,
800
+ defaultWorkers
801
+ };