emd-agents 0.15.0 → 0.16.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,68 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { launchesIn } from "./jobstore.js";
4
+ import { runTool } from "./tool.js";
5
+ // The same message Expo's R key broadcasts to connected apps: the dev server's
6
+ // message socket relays a "reload" from a local client to every app.
7
+ export async function sendReload(port) {
8
+ const socket = new WebSocket(`ws://localhost:${port}/message`);
9
+ await new Promise((resolve, reject) => {
10
+ const timer = setTimeout(() => reject(new Error("socket timeout")), 5000);
11
+ socket.onopen = () => {
12
+ socket.send(JSON.stringify({ version: 2, method: "reload" }));
13
+ clearTimeout(timer);
14
+ resolve();
15
+ };
16
+ socket.onerror = () => {
17
+ clearTimeout(timer);
18
+ reject(new Error("socket error"));
19
+ };
20
+ });
21
+ // The server answers the close; a silent one must not hold this process.
22
+ await new Promise((resolve) => {
23
+ socket.onclose = () => resolve();
24
+ socket.close();
25
+ setTimeout(resolve, 1000).unref();
26
+ });
27
+ }
28
+ // The pid of the app when it runs on the device; undefined when it does not.
29
+ export async function runningPid(device, appId) {
30
+ try {
31
+ const { stdout } = await runTool("simctl spawn launchctl list", "xcrun", ["simctl", "spawn", device.id, "launchctl", "list"], 60);
32
+ const mark = `UIKitApplication:${appId}[`;
33
+ for (const line of stdout.split("\n")) {
34
+ if (!line.includes(mark))
35
+ continue;
36
+ const pid = Number(line.trim().split(/\s+/)[0]);
37
+ return Number.isInteger(pid) ? pid : undefined;
38
+ }
39
+ }
40
+ catch { }
41
+ return undefined;
42
+ }
43
+ // The earlier launch in this worktree whose dev server still listens on `port`,
44
+ // or undefined. `listening` tells which recorded dev server pids do.
45
+ export const earlierLaunch = (root, port, listening) =>
46
+ // Reloads share one dev server, so the newest run (its folder name starts
47
+ // with its start time) is the one whose log window is open.
48
+ launchesIn(root)
49
+ .filter(({ verdict, metro, device, logDir }) => verdict === "launched" &&
50
+ metro?.port === port &&
51
+ listening.includes(metro.pid) &&
52
+ device &&
53
+ logDir)
54
+ .sort((a, b) => basename(b.logDir ?? "").localeCompare(basename(a.logDir ?? "")))[0];
55
+ const bundled = /Bundled \d+ms/g;
56
+ const count = async (path) => ((await readFile(path, "utf8").catch(() => "")).match(bundled) ?? []).length;
57
+ // Resolves when the dev server log shows a bundle served after `before` bundles.
58
+ export async function untilBundled(logDir, before, seconds) {
59
+ const path = join(logDir, "metro.log");
60
+ const deadline = Date.now() + seconds * 1000;
61
+ while (Date.now() < deadline) {
62
+ if ((await count(path)) > before)
63
+ return true;
64
+ await new Promise((resolve) => setTimeout(resolve, 500));
65
+ }
66
+ return false;
67
+ }
68
+ export const bundlesServed = (logDir) => count(join(logDir, "metro.log"));
@@ -16,6 +16,7 @@ export declare const detectResultSchema: z.ZodObject<{
16
16
  ios: z.ZodOptional<z.ZodString>;
17
17
  android: z.ZodOptional<z.ZodString>;
18
18
  }, z.core.$strip>>;
19
+ problem: z.ZodOptional<z.ZodString>;
19
20
  commands: z.ZodOptional<z.ZodObject<{
20
21
  run: z.ZodObject<{
21
22
  ios: z.ZodOptional<z.ZodString>;
@@ -49,6 +50,8 @@ export declare const launchResultSchema: z.ZodObject<{
49
50
  }, z.core.$strip>>;
50
51
  appId: z.ZodOptional<z.ZodString>;
51
52
  appPid: z.ZodOptional<z.ZodNumber>;
53
+ appIdSet: z.ZodOptional<z.ZodString>;
54
+ reloadFailed: z.ZodOptional<z.ZodString>;
52
55
  port: z.ZodOptional<z.ZodNumber>;
53
56
  metro: z.ZodOptional<z.ZodObject<{
54
57
  pid: z.ZodNumber;
@@ -61,8 +64,11 @@ export declare const launchResultSchema: z.ZodObject<{
61
64
  action: z.ZodEnum<{
62
65
  built: "built";
63
66
  reused: "reused";
67
+ installed: "installed";
68
+ reloaded: "reloaded";
64
69
  }>;
65
70
  reason: z.ZodOptional<z.ZodString>;
71
+ xcodebuildSeconds: z.ZodOptional<z.ZodNumber>;
66
72
  }, z.core.$strip>>;
67
73
  screen: z.ZodOptional<z.ZodObject<{
68
74
  waited: z.ZodNumber;
@@ -75,8 +81,31 @@ export declare const launchResultSchema: z.ZodObject<{
75
81
  }, z.core.$strip>>;
76
82
  logDir: z.ZodOptional<z.ZodString>;
77
83
  seconds: z.ZodOptional<z.ZodNumber>;
84
+ phases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
78
85
  }, z.core.$strip>;
79
86
  export type LaunchResult = z.infer<typeof launchResultSchema>;
87
+ export declare const inputResultSchema: z.ZodObject<{
88
+ verdict: z.ZodEnum<{
89
+ failed: "failed";
90
+ ok: "ok";
91
+ }>;
92
+ reason: z.ZodOptional<z.ZodString>;
93
+ backend: z.ZodOptional<z.ZodEnum<{
94
+ axe: "axe";
95
+ maestro: "maestro";
96
+ }>>;
97
+ fellBack: z.ZodOptional<z.ZodArray<z.ZodObject<{
98
+ backend: z.ZodEnum<{
99
+ axe: "axe";
100
+ maestro: "maestro";
101
+ }>;
102
+ reason: z.ZodString;
103
+ }, z.core.$strip>>>;
104
+ seconds: z.ZodOptional<z.ZodNumber>;
105
+ retyped: z.ZodOptional<z.ZodString>;
106
+ note: z.ZodOptional<z.ZodString>;
107
+ }, z.core.$strip>;
108
+ export type InputResult = z.infer<typeof inputResultSchema>;
80
109
  export declare const checkResultSchema: z.ZodObject<{
81
110
  verdict: z.ZodEnum<{
82
111
  error: "error";
@@ -118,28 +147,31 @@ export declare const checkResultSchema: z.ZodObject<{
118
147
  }>>;
119
148
  agrees: z.ZodOptional<z.ZodBoolean>;
120
149
  }, z.core.$strip>>;
121
- }, z.core.$strip>;
122
- export type CheckResult = z.infer<typeof checkResultSchema>;
123
- export declare const inputResultSchema: z.ZodObject<{
124
- verdict: z.ZodEnum<{
125
- failed: "failed";
126
- ok: "ok";
127
- }>;
128
- reason: z.ZodOptional<z.ZodString>;
129
- backend: z.ZodOptional<z.ZodEnum<{
130
- axe: "axe";
131
- maestro: "maestro";
132
- }>>;
133
- fellBack: z.ZodOptional<z.ZodArray<z.ZodObject<{
134
- backend: z.ZodEnum<{
150
+ evidenceDir: z.ZodOptional<z.ZodString>;
151
+ notPassed: z.ZodOptional<z.ZodArray<z.ZodString>>;
152
+ actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
153
+ verdict: z.ZodEnum<{
154
+ failed: "failed";
155
+ ok: "ok";
156
+ }>;
157
+ reason: z.ZodOptional<z.ZodString>;
158
+ backend: z.ZodOptional<z.ZodEnum<{
135
159
  axe: "axe";
136
160
  maestro: "maestro";
137
- }>;
138
- reason: z.ZodString;
161
+ }>>;
162
+ fellBack: z.ZodOptional<z.ZodArray<z.ZodObject<{
163
+ backend: z.ZodEnum<{
164
+ axe: "axe";
165
+ maestro: "maestro";
166
+ }>;
167
+ reason: z.ZodString;
168
+ }, z.core.$strip>>>;
169
+ seconds: z.ZodOptional<z.ZodNumber>;
170
+ retyped: z.ZodOptional<z.ZodString>;
171
+ note: z.ZodOptional<z.ZodString>;
139
172
  }, z.core.$strip>>>;
140
- seconds: z.ZodOptional<z.ZodNumber>;
141
173
  }, z.core.$strip>;
142
- export type InputResult = z.infer<typeof inputResultSchema>;
174
+ export type CheckResult = z.infer<typeof checkResultSchema>;
143
175
  export declare const evidenceResultSchema: z.ZodObject<{
144
176
  verdict: z.ZodEnum<{
145
177
  failed: "failed";
@@ -184,6 +216,8 @@ export declare const jobViewSchema: z.ZodObject<{
184
216
  }, z.core.$strip>>;
185
217
  appId: z.ZodOptional<z.ZodString>;
186
218
  appPid: z.ZodOptional<z.ZodNumber>;
219
+ appIdSet: z.ZodOptional<z.ZodString>;
220
+ reloadFailed: z.ZodOptional<z.ZodString>;
187
221
  port: z.ZodOptional<z.ZodNumber>;
188
222
  metro: z.ZodOptional<z.ZodObject<{
189
223
  pid: z.ZodNumber;
@@ -196,8 +230,11 @@ export declare const jobViewSchema: z.ZodObject<{
196
230
  action: z.ZodEnum<{
197
231
  built: "built";
198
232
  reused: "reused";
233
+ installed: "installed";
234
+ reloaded: "reloaded";
199
235
  }>;
200
236
  reason: z.ZodOptional<z.ZodString>;
237
+ xcodebuildSeconds: z.ZodOptional<z.ZodNumber>;
201
238
  }, z.core.$strip>>;
202
239
  screen: z.ZodOptional<z.ZodObject<{
203
240
  waited: z.ZodNumber;
@@ -210,6 +247,7 @@ export declare const jobViewSchema: z.ZodObject<{
210
247
  }, z.core.$strip>>;
211
248
  logDir: z.ZodOptional<z.ZodString>;
212
249
  seconds: z.ZodOptional<z.ZodNumber>;
250
+ phases: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
213
251
  }, z.core.$strip>, z.ZodObject<{
214
252
  verdict: z.ZodEnum<{
215
253
  error: "error";
@@ -251,6 +289,29 @@ export declare const jobViewSchema: z.ZodObject<{
251
289
  }>>;
252
290
  agrees: z.ZodOptional<z.ZodBoolean>;
253
291
  }, z.core.$strip>>;
292
+ evidenceDir: z.ZodOptional<z.ZodString>;
293
+ notPassed: z.ZodOptional<z.ZodArray<z.ZodString>>;
294
+ actions: z.ZodOptional<z.ZodArray<z.ZodObject<{
295
+ verdict: z.ZodEnum<{
296
+ failed: "failed";
297
+ ok: "ok";
298
+ }>;
299
+ reason: z.ZodOptional<z.ZodString>;
300
+ backend: z.ZodOptional<z.ZodEnum<{
301
+ axe: "axe";
302
+ maestro: "maestro";
303
+ }>>;
304
+ fellBack: z.ZodOptional<z.ZodArray<z.ZodObject<{
305
+ backend: z.ZodEnum<{
306
+ axe: "axe";
307
+ maestro: "maestro";
308
+ }>;
309
+ reason: z.ZodString;
310
+ }, z.core.$strip>>>;
311
+ seconds: z.ZodOptional<z.ZodNumber>;
312
+ retyped: z.ZodOptional<z.ZodString>;
313
+ note: z.ZodOptional<z.ZodString>;
314
+ }, z.core.$strip>>>;
254
315
  }, z.core.$strip>]>>;
255
316
  }, z.core.$strip>;
256
317
  export type JobView = z.infer<typeof jobViewSchema>;
@@ -12,6 +12,10 @@ export const detectResultSchema = z.object({
12
12
  stack: z.enum(stackIds).optional(),
13
13
  platforms: z.array(z.enum(platforms)).optional(),
14
14
  appIds: perPlatform.optional(),
15
+ // Why `launch` cannot go on: the app config could not be read (for example,
16
+ // dependencies are not installed), or an ios/ folder exists with no iOS app ID
17
+ // in the config.
18
+ problem: z.string().optional(),
15
19
  commands: z.object({ run: perPlatform, server: z.string() }).optional(),
16
20
  packageManager: z.enum(packageManagers).optional(),
17
21
  maestroFlows: z.array(z.string()).optional(),
@@ -30,6 +34,11 @@ export const launchResultSchema = z.object({
30
34
  device: z.object({ id: z.string(), name: z.string() }).optional(),
31
35
  appId: z.string().optional(),
32
36
  appPid: z.number().optional(),
37
+ // The iOS app ID that Expo's build wrote to the app config (ios.bundleIdentifier)
38
+ // because the app had none. Absent when the app already had one.
39
+ appIdSet: z.string().optional(),
40
+ // Why a reload did not work and the app was relaunched instead.
41
+ reloadFailed: z.string().optional(),
33
42
  // The Metro port reserved for this worktree; set on a failure after it was.
34
43
  port: z.number().optional(),
35
44
  // The dev server left running for the app; the next launch in this worktree
@@ -38,11 +47,16 @@ export const launchResultSchema = z.object({
38
47
  // The log stream that captures the app's tagged lines; the next launch in
39
48
  // this worktree stops it.
40
49
  logStream: z.object({ pid: z.number() }).optional(),
41
- // Whether the Xcode build ran or an installed build was reused; why it ran.
50
+ // Whether the Xcode build ran, an installed build was reused, an earlier
51
+ // build was installed again, or the running app was reloaded from the dev
52
+ // server; why it was not reused.
42
53
  build: z
43
54
  .object({
44
- action: z.enum(["built", "reused"]),
55
+ action: z.enum(["built", "reused", "installed", "reloaded"]),
45
56
  reason: z.string().optional(),
57
+ // xcodebuild's own seconds, from its timing summary (#208). Its slowest
58
+ // steps are at the end of build.log.
59
+ xcodebuildSeconds: z.number().optional(),
46
60
  })
47
61
  .optional(),
48
62
  // Set when AXe is installed: seconds `launch` waited until AXe could read the
@@ -59,10 +73,28 @@ export const launchResultSchema = z.object({
59
73
  // Full build and server logs live here; read them only when needed.
60
74
  logDir: z.string().optional(),
61
75
  seconds: z.number().optional(),
76
+ // Seconds each phase took, in order (#203): project, replace, clone, boot,
77
+ // server, reuse or build, open, screen. Only the phases that ran.
78
+ phases: z.record(z.string(), z.number()).optional(),
62
79
  });
63
80
  const fellBackSchema = z
64
81
  .array(z.object({ backend: z.enum(backendIds), reason: z.string() }))
65
82
  .optional();
83
+ // A tap, typing or swipe (decision 0009). ok: the backend did it; only a check
84
+ // shows whether the app reacted. failed: it could not, and `reason` says why.
85
+ export const inputResultSchema = z.object({
86
+ verdict: z.enum(["ok", "failed"]),
87
+ reason: z.string().optional(),
88
+ backend: z.enum(backendIds).optional(),
89
+ fellBack: fellBackSchema,
90
+ // A tap by testID or text: seconds from start to finish, which includes
91
+ // the wait for the element. `type`: seconds until the text showed.
92
+ seconds: z.number().optional(),
93
+ // `type`: the rest of the text, when it had to be typed a second time.
94
+ retyped: z.string().optional(),
95
+ // `type` in a secure field: what could and could not be confirmed.
96
+ note: z.string().optional(),
97
+ });
66
98
  // The verdict comes only from log events and UI elements. The agent's own
67
99
  // reading of a screenshot is recorded next to it as a second opinion and never
68
100
  // changes the verdict.
@@ -108,17 +140,13 @@ export const checkResultSchema = z.object({
108
140
  agrees: z.boolean().optional(),
109
141
  })
110
142
  .optional(),
111
- });
112
- // A tap, typing or swipe (decision 0009). ok: the backend did it; only a check
113
- // shows whether the app reacted. failed: it could not, and `reason` says why.
114
- export const inputResultSchema = z.object({
115
- verdict: z.enum(["ok", "failed"]),
116
- reason: z.string().optional(),
117
- backend: z.enum(backendIds).optional(),
118
- fellBack: fellBackSchema,
119
- // A tap by testID or text: seconds from start to finish, which includes
120
- // the wait for the element.
121
- seconds: z.number().optional(),
143
+ // The run's evidence folder, rewritten after this check (#207), and the
144
+ // worktree's check names whose last verdict is not passed. Report each.
145
+ evidenceDir: z.string().optional(),
146
+ notPassed: z.array(z.string()).optional(),
147
+ // The actions the check ran before it read, in order, with each outcome
148
+ // (#207). A failed action stops the rest and the read.
149
+ actions: z.array(inputResultSchema).optional(),
122
150
  });
123
151
  export const evidenceResultSchema = z.object({
124
152
  verdict: z.enum(["written", "failed"]),
@@ -67,11 +67,24 @@ const skillSource = () => fileURLToPath(new URL("../../", import.meta.url));
67
67
  const emdServer = () => skillSource().split(sep).includes("node_modules")
68
68
  ? `npx -y emd-agents@${version()} mcp`
69
69
  : `${process.execPath} ${fileURLToPath(new URL("../bin.js", import.meta.url))} mcp`;
70
+ // Claude Code's CLI lets one stdio tool call run for hours, so EMD waits up to
71
+ // this long per call there and an agent polls less (#223). Codex and Cursor
72
+ // stop a call at 60 s by default and keep EMD's short waits.
73
+ const longWaitSeconds = 100;
70
74
  function commands(ids) {
71
- const to = ids.flatMap((id) => ["-a", id]);
75
+ const to = (some) => some.flatMap((id) => ["-a", id]);
76
+ const add = (some, env = []) => [
77
+ "npx",
78
+ ["-y", addMcp, emdServer(), "-n", "emd", "-g", ...to(some), ...env, "-y"],
79
+ ];
80
+ const long = ids.filter((id) => id === "claude-code");
81
+ const short = ids.filter((id) => id !== "claude-code");
72
82
  return [
73
- ["npx", ["-y", addMcp, emdServer(), "-n", "emd", "-g", ...to, "-y"]],
74
- ["npx", ["-y", skillsCli, "add", skillSource(), "-g", ...to, "-y"]],
83
+ ...(long.length > 0
84
+ ? [add(long, ["--env", `EMD_WAIT_SECONDS=${longWaitSeconds}`])]
85
+ : []),
86
+ ...(short.length > 0 ? [add(short)] : []),
87
+ ["npx", ["-y", skillsCli, "add", skillSource(), "-g", ...to(ids), "-y"]],
75
88
  ];
76
89
  }
77
90
  const shown = ([command, args]) => [command, ...args.map((a) => (/\s/.test(a) ? `"${a}"` : a))].join(" ");
@@ -12,9 +12,11 @@ export declare function parseSdkVersion(output: string): number[] | undefined;
12
12
  export declare function boot(device: Device): Promise<void>;
13
13
  export declare function appAccessibilityOn(device: Device): Promise<boolean>;
14
14
  export declare function enableAppAccessibility(device: Device): Promise<void>;
15
+ export declare function plainKeyboard(device: Device): Promise<void>;
15
16
  export declare function terminateApp(device: Device, appId: string): Promise<void>;
16
17
  export declare function launchApp(device: Device, appId: string): Promise<number>;
17
18
  export declare function appInstalled(device: Device, appId: string): Promise<boolean>;
19
+ export declare function installApp(device: Device, appPath: string): Promise<void>;
18
20
  export declare function cloneDevice(base: Device, name: string): Promise<string>;
19
21
  export type Simulator = {
20
22
  id: string;
@@ -1,3 +1,5 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
1
3
  import { runTool } from "./tool.js";
2
4
  export async function listDevices() {
3
5
  const { stdout } = await runTool("simctl list", "xcrun", ["simctl", "list", "devices", "available", "--json"], 60);
@@ -90,21 +92,32 @@ export async function appAccessibilityOn(device) {
90
92
  return false;
91
93
  }
92
94
  }
93
- // Turns it on, on a simulator EMD made. The setting stays on the device; an
95
+ // Sets a boolean preference inside the simulator. It stays on the device; an
94
96
  // app that is already running must restart to see it.
95
- export async function enableAppAccessibility(device) {
97
+ async function writeBool(device, domain, key, value) {
96
98
  await runTool("simctl spawn defaults write", "xcrun", [
97
99
  "simctl",
98
100
  "spawn",
99
101
  device.id,
100
102
  "defaults",
101
103
  "write",
102
- "com.apple.Accessibility",
103
- accessibilityKey,
104
+ domain,
105
+ key,
104
106
  "-bool",
105
- "true",
107
+ String(value),
106
108
  ], 60);
107
109
  }
110
+ // Turns it on, on a simulator EMD made.
111
+ export async function enableAppAccessibility(device) {
112
+ await writeBool(device, "com.apple.Accessibility", accessibilityKey, true);
113
+ }
114
+ // Turns off Predictive Text and Auto-Correction on a simulator EMD made, as
115
+ // Appium's WebDriverAgent does before tests (same keys). Predictions add new
116
+ // text to the screen while `type` waits for its keys, and corrections change
117
+ // the typed text.
118
+ export async function plainKeyboard(device) {
119
+ await Promise.all(["KeyboardPrediction", "KeyboardAutocorrection"].map((key) => writeBool(device, "com.apple.Preferences", key, false)));
120
+ }
108
121
  // Stops the app if it runs; a later launch then starts it fresh. Not running is
109
122
  // not a failure.
110
123
  export async function terminateApp(device, appId) {
@@ -121,16 +134,21 @@ export async function launchApp(device, appId) {
121
134
  throw new Error(`unexpected output: ${stdout}`);
122
135
  return pid;
123
136
  }
124
- // True when the app is installed on the device.
137
+ // True when the app is installed on the device. `simctl` can name a container
138
+ // whose app files are gone, so the app's Info.plist must exist.
125
139
  export async function appInstalled(device, appId) {
126
140
  try {
127
- await runTool("simctl get_app_container", "xcrun", ["simctl", "get_app_container", device.id, appId], 60);
128
- return true;
141
+ const { stdout } = await runTool("simctl get_app_container", "xcrun", ["simctl", "get_app_container", device.id, appId], 60);
142
+ return existsSync(join(stdout.trim(), "Info.plist"));
129
143
  }
130
144
  catch {
131
145
  return false;
132
146
  }
133
147
  }
148
+ // Installs a built `.app` on the device.
149
+ export async function installApp(device, appPath) {
150
+ await runTool("simctl install", "xcrun", ["simctl", "install", device.id, appPath], 120);
151
+ }
134
152
  // A new simulator with the same type and runtime as `base`; returns its UDID.
135
153
  // The base must be shut down.
136
154
  export async function cloneDevice(base, name) {
@@ -1 +1,2 @@
1
+ export declare function defaultWait(short: number, cancelled: boolean, configured?: string | undefined): number;
1
2
  export declare function startServer(): void;
@@ -1,13 +1,100 @@
1
1
  import { McpServer } from "@modelcontextprotocol/server";
2
2
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
3
  import { z } from "zod";
4
- import { detect, detectResultSchema, directions, evidence, evidenceResultSchema, inputResultSchema, jobViewSchema, logs, logsResultSchema, startJob, swipe, tap, typeText, version, waitForJob, } from "../core/index.js";
4
+ import { detect, detectResultSchema, directions, evidence, evidenceResultSchema, inputResultSchema, jobStatus, jobViewSchema, logs, logsResultSchema, startJob, swipe, tap, typeText, version, waitForJob, } from "../core/index.js";
5
+ // Fast work returns its result in the same call, so the agent needs no
6
+ // job_status call (#207). 25 s keeps a 2x margin under a 60 s client timeout.
7
+ const waitSeconds = z
8
+ .number()
9
+ .min(0)
10
+ .max(110)
11
+ .optional()
12
+ .describe("How long to wait for the work to end before returning the job. Default 25, or longer where setup allowed it.");
13
+ // The default wait, in seconds, of a tool whose own default is `short`. setup
14
+ // sets EMD_WAIT_SECONDS (0 to 110) for clients that let one call run that long
15
+ // (#223). Once a client has cancelled a call, the session keeps `short`.
16
+ export function defaultWait(short, cancelled, configured = process.env.EMD_WAIT_SECONDS) {
17
+ const seconds = Number(configured);
18
+ return cancelled ||
19
+ !configured ||
20
+ !Number.isFinite(seconds) ||
21
+ seconds < 0 ||
22
+ seconds > 110
23
+ ? short
24
+ : seconds;
25
+ }
26
+ // How often a wait reports progress, when the call asks for it (#223).
27
+ const progressSeconds = 15;
28
+ // Waits for a job like waitForJob. While it waits it sends the job's step as
29
+ // progress, at once and then every 15 s, when the call carries a progress
30
+ // token: a client that resets its timeout on progress keeps the call alive.
31
+ // A cancelled call ends at once and calls `onCancel`. A call more than 2 s
32
+ // past its wait means this process got no CPU: one stderr line says so, and
33
+ // stderr reaches the client's log even after the client has given up (#198).
34
+ async function waitTimed(tool, jobId, wait, ctx, onCancel, since = Date.now()) {
35
+ const { signal, notify, _meta } = ctx.mcpReq;
36
+ const token = _meta?.progressToken;
37
+ const report = () => {
38
+ if (token === undefined)
39
+ return;
40
+ const view = jobStatus(jobId);
41
+ notify({
42
+ method: "notifications/progress",
43
+ params: {
44
+ progressToken: token,
45
+ progress: Math.round((Date.now() - since) / 1000),
46
+ message: view?.step ?? view?.status,
47
+ },
48
+ }).catch(() => { });
49
+ };
50
+ report();
51
+ const timer = setInterval(report, progressSeconds * 1000);
52
+ signal.addEventListener("abort", onCancel, { once: true });
53
+ try {
54
+ const job = await waitForJob(jobId, wait, jobStatus, signal);
55
+ const took = (Date.now() - since) / 1000;
56
+ if (took > wait + 2) {
57
+ console.error(`emd: ${tool} took ${took.toFixed(1)} s with a ${wait} s wait.`);
58
+ }
59
+ return job;
60
+ }
61
+ finally {
62
+ clearInterval(timer);
63
+ signal.removeEventListener("abort", onCancel);
64
+ }
65
+ }
66
+ // A tap's target, for the tap tool and a check's actions.
67
+ const tapTarget = {
68
+ id: z.string().optional().describe("The element's testID."),
69
+ text: z
70
+ .string()
71
+ .optional()
72
+ .describe("Its visible text or accessibility label, exactly."),
73
+ x: z.number().optional().describe("A point's x, in points."),
74
+ y: z.number().optional().describe("A point's y, in points."),
75
+ };
76
+ // Actions a check runs before it reads, with the tap, type and swipe tools'
77
+ // inputs (#207).
78
+ const actions = z
79
+ .array(z.union([
80
+ z.object({ tap: z.object(tapTarget) }).strict(),
81
+ z.object({ type: z.string() }).strict(),
82
+ z.object({ swipe: z.enum(directions) }).strict(),
83
+ ]))
84
+ .max(10)
85
+ .optional()
86
+ .describe('Taps, typing and swipes to run first, in order, each as the tap, type or swipe tool would: e.g. [{"tap":{"id":"name-field"}},{"type":"Ada"},{"tap":{"text":"Save"}}]. A failed one stops the rest and the check does not count.');
5
87
  const reply = (result) => ({
6
88
  content: [{ type: "text", text: JSON.stringify(result) }],
7
89
  structuredContent: result,
8
90
  });
9
91
  function buildServer() {
10
92
  const server = new McpServer({ name: "emd", version: version() });
93
+ // Set once the client cancels one of EMD's calls (#223).
94
+ let cancelled = false;
95
+ const onCancel = () => {
96
+ cancelled = true;
97
+ };
11
98
  server.registerTool("detect", {
12
99
  description: "Detect the mobile stack of a project directory and what launching it needs: platforms, app IDs, run commands, package manager. At a workspace root, `apps` lists the app folders to detect instead. Returns a small result, not file contents.",
13
100
  inputSchema: z.object({
@@ -25,7 +112,7 @@ function buildServer() {
25
112
  };
26
113
  });
27
114
  server.registerTool("launch", {
28
- description: "Start building the app, installing it on an iOS simulator and launching it, leaving its dev server running. Returns a job within seconds; the work takes up to minutes. Then call job_status with the jobId until status is succeeded or failed.",
115
+ description: "Build the app, install it on an iOS simulator and launch it, leaving its dev server running. Waits up to waitSeconds (default 25, or longer where setup allowed it): a relaunch or reload often ends in time and returns its result. A build takes minutes: then it returns the job, and you call job_status with the jobId until status is succeeded or failed.",
29
116
  inputSchema: z.object({
30
117
  dir: z
31
118
  .string()
@@ -40,24 +127,28 @@ function buildServer() {
40
127
  .positive()
41
128
  .optional()
42
129
  .describe("How long the build may take. Default 900."),
130
+ waitSeconds,
43
131
  }),
44
132
  outputSchema: jobViewSchema,
45
- }, async (input) => {
46
- const job = startJob("launch", input);
133
+ }, async ({ waitSeconds: wait, ...input }, ctx) => {
134
+ const since = Date.now();
135
+ const started = startJob("launch", input);
136
+ const job = (await waitTimed("launch", started.jobId, wait ?? defaultWait(25, cancelled), ctx, onCancel, since)) ?? started;
47
137
  return {
48
138
  content: [{ type: "text", text: JSON.stringify(job) }],
49
139
  structuredContent: job,
50
140
  };
51
141
  });
52
142
  server.registerTool("job_status", {
53
- description: "Where a job is: queued, running (with the current step and seconds), succeeded or failed. Waits up to waitSeconds (default 50) and returns as soon as the job ends, so call it again right away if it is still running; do not sleep or poll in between. When finished, includes the result. For launch: the device, app ID and log directory, or on failure the reason and the first relevant error lines, not the log. For check: the verdict, which expectations were found, and a screenshot path.",
143
+ description: "Where a job is: queued, running (with the current step and seconds), succeeded or failed. Waits up to waitSeconds (default 30, or longer where setup allowed it) and returns as soon as the job ends, so call it again right away if it is still running; do not sleep or poll in between. When finished, includes the result. For launch: the device, app ID and log directory, or on failure the reason and the first relevant error lines, not the log. For check: the verdict, which expectations were found, and a screenshot path.",
54
144
  inputSchema: z.object({
55
145
  jobId: z.string().describe("The jobId a tool such as launch returned."),
56
146
  waitSeconds: z.number().min(0).max(110).optional(),
57
147
  }),
58
148
  outputSchema: jobViewSchema,
59
- }, async ({ jobId, waitSeconds }) => {
60
- const job = await waitForJob(jobId, waitSeconds ?? 50);
149
+ }, async ({ jobId, waitSeconds }, ctx) => {
150
+ // 30 s: a 2x margin under a 60 s client timeout (#198).
151
+ const job = await waitTimed("job_status", jobId, waitSeconds ?? defaultWait(30, cancelled), ctx, onCancel);
61
152
  if (!job) {
62
153
  return {
63
154
  isError: true,
@@ -94,7 +185,7 @@ function buildServer() {
94
185
  };
95
186
  });
96
187
  server.registerTool("check", {
97
- description: "Check a run against what you expect, from signals a machine can read, not your own judgment: tagged log events the app wrote ([EMD:<tag>] lines) and elements on the simulator's screen (by testID or by text). After a tap, type or swipe, check right away; a check reads again for up to 10 s what is still missing. Starts a job and returns it within seconds; call job_status until it finishes, which can take a minute. The result's verdict is passed, failed (fix the cause and check again), stopped (the retry limit is reached: stop and report what is missing) or error (the check could not run; not counted). Your reading of the returned screenshot may be passed as agentReading; it is recorded as a second opinion and never changes the verdict.",
188
+ description: "Check a run against what you expect, from signals a machine can read, not your own judgment: tagged log events the app wrote ([EMD:<tag>] lines) and elements on the simulator's screen (by testID or by text). Give the taps, typing and swipes that lead to the moment as actions, or check right after them; a check reads again for up to 10 s what is still missing. Waits up to waitSeconds (default 25, or longer where setup allowed it) and returns the finished result when the check ends in time; otherwise returns the job: call job_status until it finishes. The result's verdict is passed, failed (fix the cause and check again), stopped (the retry limit is reached: stop and report what is missing) or error (the check could not run; not counted). Your reading of the returned screenshot may be passed as agentReading; it is recorded as a second opinion and never changes the verdict. Each check rewrites the run's evidence folder and returns its path (evidenceDir) and the check names whose last verdict is not passed (notPassed).",
98
189
  inputSchema: z.object({
99
190
  jobId: z.string().describe("The launch job whose run to check."),
100
191
  logs: z
@@ -127,10 +218,14 @@ function buildServer() {
127
218
  .enum(["pass", "fail"])
128
219
  .optional()
129
220
  .describe("Your reading of the screenshot. Second opinion only."),
221
+ actions,
222
+ waitSeconds,
130
223
  }),
131
224
  outputSchema: jobViewSchema,
132
- }, async (input) => {
133
- const job = startJob("check", input);
225
+ }, async ({ waitSeconds: wait, ...input }, ctx) => {
226
+ const since = Date.now();
227
+ const started = startJob("check", input);
228
+ const job = (await waitTimed("check", started.jobId, wait ?? defaultWait(25, cancelled), ctx, onCancel, since)) ?? started;
134
229
  return {
135
230
  content: [{ type: "text", text: JSON.stringify(job) }],
136
231
  structuredContent: job,
@@ -139,20 +234,11 @@ function buildServer() {
139
234
  const jobId = z.string().describe("The launch job whose app to act on.");
140
235
  server.registerTool("tap", {
141
236
  description: "Tap the launched app: an element by testID or by visible text, or a point. Give one target. Waits up to 10 s for the element, and the result's seconds says how long the tap took. If it never appears, nothing is tapped. A result of ok means the tap was sent; call check to see what the app did.",
142
- inputSchema: z.object({
143
- jobId,
144
- id: z.string().optional().describe("The element's testID."),
145
- text: z
146
- .string()
147
- .optional()
148
- .describe("Its visible text or accessibility label, exactly."),
149
- x: z.number().optional().describe("A point's x, in points."),
150
- y: z.number().optional().describe("A point's y, in points."),
151
- }),
237
+ inputSchema: z.object({ jobId, ...tapTarget }),
152
238
  outputSchema: inputResultSchema,
153
239
  }, async (input) => reply(await tap(input)));
154
240
  server.registerTool("type", {
155
- description: "Type text into the field that has focus. Tap the field first. Letters, digits and US keyboard symbols only.",
241
+ description: "Type text into the field that has focus. Tap the field first. Letters, digits and US keyboard symbols only. ok means the text shows on screen (secure fields: bullets grew by its length); this can take up to 40 s. failed says what the screen shows.",
156
242
  inputSchema: z.object({
157
243
  jobId,
158
244
  text: z.string().describe("The text to type."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emd-agents",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Build, run, check and prove mobile changes from any coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {