@phren/cli 0.3.28 → 0.3.30

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 (45) hide show
  1. package/dist/bridge/hand-off-queue.d.ts +6 -0
  2. package/dist/bridge/hand-off-queue.js +29 -9
  3. package/dist/bridge/resources.d.ts +21 -0
  4. package/dist/bridge/resources.js +58 -2
  5. package/dist/bridge/server-launch.js +2 -1
  6. package/dist/bridge/server-routes.js +33 -2
  7. package/dist/bridge/simulators.d.ts +3 -1
  8. package/dist/bridge/simulators.js +40 -5
  9. package/dist/bridge/task-routes.d.ts +282 -0
  10. package/dist/bridge/task-routes.js +162 -0
  11. package/dist/bridge/uploads.d.ts +4 -0
  12. package/dist/bridge/uploads.js +15 -0
  13. package/dist/bridge-hook.mjs +4292 -2993
  14. package/dist/cli/namespaces-store.js +32 -1
  15. package/dist/cli/namespaces-tasks.d.ts +1 -0
  16. package/dist/cli/namespaces-tasks.js +55 -4
  17. package/dist/cli/ops.d.ts +2 -1
  18. package/dist/cli/ops.js +20 -4
  19. package/dist/cli-registry.js +5 -4
  20. package/dist/data/task-contract.d.ts +75 -0
  21. package/dist/data/task-contract.js +161 -0
  22. package/dist/data/task-format.d.ts +20 -0
  23. package/dist/data/task-format.js +55 -0
  24. package/dist/data/task-metadata.d.ts +10 -0
  25. package/dist/data/task-metadata.js +24 -0
  26. package/dist/data/task-store-directory.d.ts +21 -0
  27. package/dist/data/task-store-directory.js +37 -0
  28. package/dist/data/tasks.d.ts +38 -2
  29. package/dist/data/tasks.js +221 -28
  30. package/dist/modules/registry.js +3 -3
  31. package/dist/shell/input.js +49 -4
  32. package/dist/shell/state-store.d.ts +1 -0
  33. package/dist/shell/state-store.js +2 -0
  34. package/dist/shell/view.js +19 -3
  35. package/dist/store-registry.d.ts +12 -1
  36. package/dist/store-registry.js +52 -4
  37. package/dist/sync/task-claim.d.ts +1 -0
  38. package/dist/sync/task-claim.js +8 -1
  39. package/dist/sync/task-merge.d.ts +0 -9
  40. package/dist/sync/task-merge.js +48 -1
  41. package/dist/tools/tasks.js +31 -18
  42. package/dist/ui/page.js +1 -0
  43. package/dist/ui/scripts.js +64 -5
  44. package/dist/ui/server.js +18 -0
  45. package/package.json +1 -1
@@ -56,6 +56,7 @@ export declare class HandOffQueue {
56
56
  private root;
57
57
  private now;
58
58
  private lastPrune;
59
+ private ticking?;
59
60
  constructor(options: QueueOptions);
60
61
  private serial;
61
62
  private file;
@@ -69,7 +70,12 @@ export declare class HandOffQueue {
69
70
  enqueue(input: unknown): Promise<Json>;
70
71
  status(id: string, target: Target): Promise<Json>;
71
72
  private attempt;
73
+ /** Coalesced: the Hook calls this every 5 s whether or not the last tick
74
+ * finished, and queuing each behind the lock would hold every enqueue and
75
+ * status behind a backlog that grows faster than a slow tick drains it. */
72
76
  tick(): Promise<void>;
77
+ private sweep;
78
+ private noticeId;
73
79
  /** Hold enqueues and delivery while the Hook validates and closes a worker.
74
80
  * A new hand-off cannot be accepted between the pending check and closure. */
75
81
  whenNoPending(target: Target, close: () => Promise<Json>): Promise<Json>;
@@ -34,6 +34,7 @@ export class HandOffQueue {
34
34
  root;
35
35
  now;
36
36
  lastPrune = -Infinity;
37
+ ticking;
37
38
  constructor(options) {
38
39
  this.options = options;
39
40
  this.root = options.root ?? path.join(bridgeRoot(), "hand-offs");
@@ -192,12 +193,18 @@ export class HandOffQueue {
192
193
  delete row.error;
193
194
  await this.save(row);
194
195
  }
196
+ /** Coalesced: the Hook calls this every 5 s whether or not the last tick
197
+ * finished, and queuing each behind the lock would hold every enqueue and
198
+ * status behind a backlog that grows faster than a slow tick drains it. */
195
199
  tick() {
196
- return this.serial(async () => {
200
+ return this.ticking ??= this.sweep().finally(() => { this.ticking = undefined; });
201
+ }
202
+ async sweep() {
203
+ const remote = await this.serial(async () => {
197
204
  let rows = await this.rows();
198
205
  if (this.now() - this.lastPrune >= DAY)
199
206
  rows = await this.prune(rows);
200
- const attempted = new Set();
207
+ const attempted = new Set(), remote = [];
201
208
  for (const row of rows)
202
209
  if (row.state === "queued") {
203
210
  const key = JSON.stringify(row.target);
@@ -208,16 +215,12 @@ export class HandOffQueue {
208
215
  }
209
216
  for (const row of rows)
210
217
  if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
211
- // A notice is itself an idempotent queued hand-off, without an origin.
212
- const id = `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
213
218
  if (row.originComputer) {
214
- const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, id, row.originComputer).catch(() => undefined);
215
- if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
216
- continue;
217
- row.notified = true;
218
- await this.save(row);
219
+ remote.push(row);
219
220
  continue;
220
221
  }
222
+ // A notice is itself an idempotent queued hand-off, without an origin.
223
+ const id = this.noticeId(row);
221
224
  if (!await this.read(id)) {
222
225
  const pane = await this.options.validate(row.origin).catch(() => undefined);
223
226
  if (!pane || typeof pane.terminal_id !== "string")
@@ -229,8 +232,25 @@ export class HandOffQueue {
229
232
  row.notified = true;
230
233
  await this.save(row);
231
234
  }
235
+ return remote;
232
236
  });
237
+ // Sent outside the lock: the sender's Hook may be holding its own lock
238
+ // while it waits on this one, and two Hooks each waiting on the other
239
+ // left both refusing every hand-off until a peer request timed out.
240
+ await Promise.all(remote.map(async (row) => {
241
+ const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row), row.originComputer).catch(() => undefined);
242
+ if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
243
+ return;
244
+ await this.serial(async () => {
245
+ const current = await this.read(row.deliveryId);
246
+ if (current && !current.notified) {
247
+ current.notified = true;
248
+ await this.save(current);
249
+ }
250
+ });
251
+ }));
233
252
  }
253
+ noticeId(row) { return `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`; }
234
254
  /** Hold enqueues and delivery while the Hook validates and closes a worker.
235
255
  * A new hand-off cannot be accepted between the pending check and closure. */
236
256
  whenNoPending(target, close) {
@@ -63,6 +63,7 @@ export interface ComputerResources {
63
63
  charging: boolean;
64
64
  onAC: boolean;
65
65
  };
66
+ hardware?: ComputerHardware;
66
67
  heavy: HeavyProcess[];
67
68
  /** 0 idle to 1 saturated, per resource and overall (the highest), so every client fills its gauge the same way. */
68
69
  pressure: {
@@ -74,6 +75,25 @@ export interface ComputerResources {
74
75
  level: "ok" | "busy" | "stressed";
75
76
  warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
76
77
  }
78
+ /** What the computer is, read once per Hook run: "MacBook Pro", "Apple M1 Max",
79
+ * 32 GB; on Linux the DMI vendor and product ("Dell XPS 13 9310") and the CPU's
80
+ * model name. Never a serial number or any other identifier. */
81
+ export interface ComputerHardware {
82
+ model?: string;
83
+ chip?: string;
84
+ memoryBytes: number;
85
+ cores: number;
86
+ }
87
+ /** `system_profiler SPHardwareDataType -json` → model and chip. Intel Macs name
88
+ * the processor in `cpu_type` instead of `chip_type`. */
89
+ export declare function parseMacHardware(json: string): Pick<ComputerHardware, "model" | "chip">;
90
+ /** DMI vendor and product → "Dell XPS 13 9310", "Lenovo ThinkPad X1 Carbon";
91
+ * placeholder strings firmware leaves in are dropped. */
92
+ export declare function linuxModel(vendor: string | undefined, product: string | undefined, version?: string): string | undefined;
93
+ /** /proc/cpuinfo's first `model name`, without the (R)/(TM) marks, "CPU" and clock. */
94
+ export declare function linuxChip(cpuinfo: string): string | undefined;
95
+ /** Read once; the answer can't change while the Hook runs. */
96
+ export declare function computerHardware(platform?: NodeJS.Platform): Promise<ComputerHardware>;
77
97
  /** A `ps` row; `pgid` is the process group the job registry attributes work by. */
78
98
  export interface ProcessRow extends ProcessLike {
79
99
  cpu: number;
@@ -136,6 +156,7 @@ export interface ResourceDeps {
136
156
  panes: Set<string>;
137
157
  servers: Set<string>;
138
158
  } | undefined>;
159
+ hardware?: () => Promise<ComputerHardware | undefined>;
139
160
  jobs?: JobSource;
140
161
  }
141
162
  export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
@@ -23,6 +23,61 @@ export const RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS"
23
23
  /** Below this much free disk, or above twice the cores in load, a computer is stressed. */
24
24
  export const LOW_DISK_BYTES = 10 * 1024 ** 3;
25
25
  const GB = 1024 ** 3;
26
+ /** `system_profiler SPHardwareDataType -json` → model and chip. Intel Macs name
27
+ * the processor in `cpu_type` instead of `chip_type`. */
28
+ export function parseMacHardware(json) {
29
+ const item = JSON.parse(json).SPHardwareDataType?.[0] ?? {};
30
+ const text = (value) => typeof value === "string" && value.trim() ? value.trim().slice(0, 80) : undefined;
31
+ const model = text(item.machine_name), chip = text(item.chip_type) ?? text(item.cpu_type);
32
+ return { ...(model ? { model } : {}), ...(chip ? { chip } : {}) };
33
+ }
34
+ /** DMI vendor and product → "Dell XPS 13 9310", "Lenovo ThinkPad X1 Carbon";
35
+ * placeholder strings firmware leaves in are dropped. */
36
+ export function linuxModel(vendor, product, version) {
37
+ const clean = (value) => {
38
+ const text = value?.replace(/\s+/g, " ").trim();
39
+ return text && !/^(to be filled|default string|system (product name|manufacturer)|not specified|none|o\.e\.m\.?|unknown)/i.test(text) ? text : undefined;
40
+ };
41
+ const brand = clean(vendor)?.replace(/,?\s+(Inc\.?|Corporation|Corp\.?|Co\.,? Ltd\.?|Ltd\.?|GmbH|Technology)$/i, "");
42
+ // Lenovo puts the marketing name in product_version and a part number in product_name.
43
+ const name = brand === "LENOVO" || brand === "Lenovo" ? clean(version) ?? clean(product) : clean(product);
44
+ if (!name)
45
+ return brand;
46
+ const label = brand && !name.toLowerCase().startsWith(brand.toLowerCase()) ? `${brand === "LENOVO" ? "Lenovo" : brand} ${name}` : name;
47
+ return label.slice(0, 80);
48
+ }
49
+ /** /proc/cpuinfo's first `model name`, without the (R)/(TM) marks, "CPU" and clock. */
50
+ export function linuxChip(cpuinfo) {
51
+ const raw = /^model name\s*:\s*(.+)$/m.exec(cpuinfo)?.[1];
52
+ const chip = raw?.replace(/\((R|TM|tm|r)\)/g, "").replace(/\s+@\s+.*$/, "").replace(/\bCPU\b/g, "")
53
+ .replace(/\b\d+-Core Processor\b/i, "").replace(/\s+/g, " ").trim();
54
+ return chip ? chip.slice(0, 80) : undefined;
55
+ }
56
+ let hardwareRead;
57
+ /** Read once; the answer can't change while the Hook runs. */
58
+ export function computerHardware(platform = process.platform) {
59
+ hardwareRead ??= (async () => {
60
+ const base = { memoryBytes: totalmem(), cores: cpus().length || 1 };
61
+ if (platform === "darwin") {
62
+ // system_profiler takes about half a second, more under load.
63
+ const found = await exec("/usr/sbin/system_profiler", ["SPHardwareDataType", "-json"], { timeout: 20_000, maxBuffer: 1024 * 1024 })
64
+ .then(result => parseMacHardware(result.stdout)).catch(() => undefined);
65
+ // A failed read is tried again on the next collection rather than kept.
66
+ if (!found)
67
+ hardwareRead = undefined;
68
+ return { ...found, ...base };
69
+ }
70
+ if (platform === "linux") {
71
+ const dmi = (name) => readFile(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => undefined);
72
+ const [vendor, product, version, cpuinfo] = await Promise.all([dmi("sys_vendor"), dmi("product_name"), dmi("product_version"),
73
+ readFile("/proc/cpuinfo", "utf8").catch(() => "")]);
74
+ const model = linuxModel(vendor, product, version), chip = linuxChip(cpuinfo);
75
+ return { ...(model ? { model } : {}), ...(chip ? { chip } : {}), ...base };
76
+ }
77
+ return base;
78
+ })();
79
+ return hardwareRead;
80
+ }
26
81
  /** `ps -axo pid=,ppid=,pgid=,pcpu=,rss=,comm=` paired with the `args=` listing by
27
82
  * pid. The older five-column stats (no pgid) still parse, with pgid 0. */
28
83
  export function parsePs(stats, args) {
@@ -341,7 +396,7 @@ export async function collectResources(deps) {
341
396
  const cores = cpus().length || 1;
342
397
  const platform = deps.platform;
343
398
  const registry = deps.jobs ?? new JobRegistry();
344
- const [memory, disk, battery, rows, registered] = await Promise.all([
399
+ const [memory, disk, battery, rows, registered, hardware] = await Promise.all([
345
400
  platform === "darwin" ? darwinMemory()
346
401
  : platform === "linux" ? readFile("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() }))
347
402
  : Promise.resolve({ totalBytes: totalmem() }),
@@ -350,6 +405,7 @@ export async function collectResources(deps) {
350
405
  : platform === "linux" ? linuxBattery() : Promise.resolve(undefined),
351
406
  deps.processes().catch(() => []),
352
407
  registry.list().catch(() => []),
408
+ (deps.hardware ?? (() => computerHardware(platform)))().catch(() => undefined),
353
409
  ]);
354
410
  // Pane pids cost one terminal call per pane: only when there is a job to name.
355
411
  const preliminary = heavyProcesses(rows, new Map(), registered);
@@ -361,7 +417,7 @@ export async function collectResources(deps) {
361
417
  const value = {
362
418
  collectedAt: new Date(deps.now()).toISOString(), platform, uptimeSeconds: Math.round(uptime()),
363
419
  cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
364
- memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}),
420
+ memory, ...(disk ? { disk } : {}), ...(battery ? { battery } : {}), ...(hardware ? { hardware } : {}),
365
421
  heavy: owners.size || jobs.length ? heavyProcesses(rows, owners, jobs) : preliminary,
366
422
  };
367
423
  return { ...value, ...assess(value) };
@@ -514,7 +514,8 @@ async function startSession(server, data, options) {
514
514
  }
515
515
  return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
516
516
  // The caller types the brief itself unless it went with the launch.
517
- ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief } : {}),
517
+ ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
518
+ briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
518
519
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
519
520
  }
520
521
  export async function workspaceAction(server, operation, data) {
@@ -1,3 +1,4 @@
1
+ import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
1
2
  import { ownerInboxView } from "./owner-inbox-view.js";
2
3
  import { closeFinishedWorker } from "./worker-close.js";
3
4
  import { reportWorker, readIntegrator, setIntegrator } from "./worker-reports.js";
@@ -31,7 +32,7 @@ import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projec
31
32
  import { approvalDecisions, BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
32
33
  import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
33
34
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, runningChildAgents, targetTranscriptPath } from "./transcripts.js";
34
- import { listUploads, saveUpload, uploadImage } from "./uploads.js";
35
+ import { listUploads, removeUpload, saveUpload, uploadImage } from "./uploads.js";
35
36
  import { currentModel, currentStep } from "./steps.js";
36
37
  import { capacityRoom, usageForCaller } from "./usage.js";
37
38
  import { readFinalTurn } from "./schedule-watch.js";
@@ -80,6 +81,13 @@ export function capabilitiesForModules(snapshot) {
80
81
  for (const name of ["memory", "tasks", "hook", "git", "schedules"])
81
82
  if (snapshot.has(name))
82
83
  result[name] = true;
84
+ if (snapshot.has("tasks")) {
85
+ result.taskDependencies = true;
86
+ result.taskWriterSafety = true;
87
+ result.taskAtomicCreate = true;
88
+ result.taskAtomicSave = true;
89
+ result.taskBoundLaunch = true;
90
+ }
83
91
  return result;
84
92
  }
85
93
  export function requireRoute(snapshot, method, route) {
@@ -297,6 +305,12 @@ export function createRouteHandler(ctx) {
297
305
  }
298
306
  else if (request.method === "GET") {
299
307
  switch (url.pathname) {
308
+ case "/v1/tasks":
309
+ result = getTaskRoute(modules.store, url);
310
+ break;
311
+ case "/v1/tasks/stores":
312
+ result = await getTaskDirectoryRoute(modules.store);
313
+ break;
300
314
  case "/v1/health":
301
315
  result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
302
316
  break;
@@ -623,7 +637,19 @@ export function createRouteHandler(ctx) {
623
637
  }
624
638
  else if (request.method === "POST") {
625
639
  const data = await body(request);
626
- if (url.pathname === "/v1/subagents/resume") {
640
+ if (url.pathname === "/v1/tasks/launch") {
641
+ result = await launches.run(async () => launchTaskRoute(modules.store, selectedServer(url), data));
642
+ }
643
+ else if (url.pathname === "/v1/tasks/save") {
644
+ result = saveTaskRoute(modules.store, data);
645
+ }
646
+ else if (url.pathname === "/v1/tasks/create") {
647
+ result = createTaskRoute(modules.store, data);
648
+ }
649
+ else if (url.pathname === "/v1/tasks/update") {
650
+ result = updateTaskRoute(modules.store, data);
651
+ }
652
+ else if (url.pathname === "/v1/subagents/resume") {
627
653
  result = await fanoutMessages.send(data);
628
654
  }
629
655
  else if (url.pathname === "/v1/subagents/archive-finished") {
@@ -766,6 +792,11 @@ export function createRouteHandler(ctx) {
766
792
  const { name, bytes } = uploadBody(data);
767
793
  result = { ok: true, path: await saveUpload("files", name, bytes) };
768
794
  }
795
+ else if (url.pathname === "/v1/files/delete") {
796
+ // One of those files, removed by the path the listing gave.
797
+ await removeUpload("files", z.string().parse(data.path));
798
+ result = { ok: true };
799
+ }
769
800
  else if (url.pathname === "/v1/projects/add") {
770
801
  // Enrolling a repository with phren from the phone: an existing
771
802
  // checkout, or a clone. Serialized like launches — one at a time.
@@ -7,7 +7,7 @@ export declare function simulatorScreenshot(udid: string): Promise<Buffer>;
7
7
  * URL go through simctl; touches and keys go through the Simulator app's
8
8
  * window with UI scripting, which needs Accessibility for the Hook's node. */
9
9
  export type SimulatorAction = {
10
- action: "boot" | "shutdown" | "home" | "lock" | "screenshot-ready";
10
+ action: "boot" | "shutdown" | "home" | "lock" | "screenshot-ready" | "accessibility-settings";
11
11
  } | {
12
12
  action: "launch";
13
13
  bundleId: string;
@@ -23,6 +23,8 @@ export type SimulatorAction = {
23
23
  text: string;
24
24
  submit?: boolean;
25
25
  };
26
+ /** The steps for the Accessibility grant, for the 403 and the docs. */
27
+ export declare function accessibilityHelp(binary: string): string;
26
28
  export declare function simulatorAct(udid: string, request: SimulatorAction): Promise<Json>;
27
29
  /** The apps a simulator has, for the launcher. */
28
30
  export declare function simulatorApps(udid: string): Promise<Json[]>;
@@ -56,7 +56,8 @@ export async function simulatorScreenshot(udid) {
56
56
  /** The native helper (native/simtap.swift) that finds the Simulator window
57
57
  * through the Accessibility API and posts touches and keys with CGEvent.
58
58
  * AppleScript would need Automation consent, which a launchd agent can never
59
- * be prompted for; the helper needs one Accessibility grant, added by hand.
59
+ * be prompted for; the helper needs one Accessibility grant. Its `prompt`
60
+ * command puts it in the Accessibility list and shows the system dialog.
60
61
  * Compiled once per Hook version with swiftc, which any Mac with the
61
62
  * simulators has. */
62
63
  let building;
@@ -99,20 +100,27 @@ function simtap(name, ...args) {
99
100
  inputQueue = task;
100
101
  return task;
101
102
  }
102
- async function executeSimtap(name, ...args) {
103
+ /** The helper, hashed again right before it runs. */
104
+ async function verifiedHelper() {
103
105
  const binary = await helper();
104
106
  const saved = await readFile(binary + ".sha256", "utf8").then(JSON.parse).catch(() => undefined);
105
107
  const binarySha = createHash("sha256").update(await readFile(binary)).digest("hex");
106
108
  if (!saved || saved.binarySha !== binarySha)
107
109
  throw new BridgeError(409, "Simulator input helper integrity check failed.");
110
+ return binary;
111
+ }
112
+ async function executeSimtap(name, ...args) {
113
+ const binary = await verifiedHelper();
108
114
  try {
109
115
  await exec(binary, [name, ...args], { timeout: 60_000 });
110
116
  }
111
117
  catch (error) {
112
118
  const failure = error;
113
119
  const message = String(failure?.stderr ?? failure?.message ?? "");
114
- if (/accessibility/.test(message))
115
- throw new BridgeError(403, `Touches and keys need one permission on the Mac: System Settings → Privacy & Security → Accessibility → add ${binary}`);
120
+ if (/accessibility/.test(message)) {
121
+ await promptAccessibility(binary, false);
122
+ throw new BridgeError(403, accessibilityHelp(binary), { code: "simulator-accessibility", helper: binary });
123
+ }
116
124
  if (/no window/.test(message))
117
125
  throw new BridgeError(409, "That simulator has no window on screen.");
118
126
  if (/not running/.test(message))
@@ -120,12 +128,29 @@ async function executeSimtap(name, ...args) {
120
128
  throw new BridgeError(409, `The simulator did not take that: ${message.slice(0, 160) || "unknown error"}`);
121
129
  }
122
130
  }
131
+ /** The steps for the Accessibility grant, for the 403 and the docs. */
132
+ export function accessibilityHelp(binary) {
133
+ return "Touches and keys need Accessibility for Phren's simulator helper. On the Mac, open System Settings → Privacy & Security → Accessibility and switch on simtap. "
134
+ + `If it isn't listed, click +, press ⌘⇧G, paste ${binary} and click Open.`;
135
+ }
136
+ /** Asks macOS for the helper's Accessibility grant: the helper joins the
137
+ * Accessibility list, switched off, and the system dialog shows. Once per Hook
138
+ * run unless the person asks again, so a burst of taps raises one dialog.
139
+ * Resolves whether the helper is already trusted. */
140
+ let prompted = false;
141
+ async function promptAccessibility(binary, force) {
142
+ if (prompted && !force)
143
+ return false;
144
+ prompted = true;
145
+ return exec(binary, ["-", "prompt"], { timeout: 15_000 }).then(() => true, () => false);
146
+ }
147
+ const ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
123
148
  // macOS virtual key codes.
124
149
  const KEY_H = "4", KEY_L = "37";
125
150
  export async function simulatorAct(udid, request) {
126
151
  if (!UDID.test(udid))
127
152
  throw new BridgeError(400, "Invalid simulator identifier.");
128
- if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request.action))
153
+ if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request.action))
129
154
  throw new BridgeError(400, "Unknown simulator action.");
130
155
  if (process.platform !== "darwin")
131
156
  throw new BridgeError(404, "Simulators run on macOS only.");
@@ -169,6 +194,16 @@ export async function simulatorAct(udid, request) {
169
194
  break;
170
195
  }
171
196
  case "screenshot-ready": break;
197
+ case "accessibility-settings": {
198
+ // The phone's "Open Accessibility settings": ask for the grant again and
199
+ // open the pane on this Mac, where the switch is.
200
+ const binary = await verifiedHelper();
201
+ const trusted = await promptAccessibility(binary, true);
202
+ await exec("/usr/bin/open", [ACCESSIBILITY_PANE], { timeout: 15_000 }).catch(() => {
203
+ throw new BridgeError(409, "Couldn't open System Settings on the Mac.");
204
+ });
205
+ return { ok: true, trusted, helper: binary };
206
+ }
172
207
  default: throw new BridgeError(400, "Unknown simulator action.");
173
208
  }
174
209
  return { ok: true };