Skip to content

Commit 95a1830

Browse files
committed
feat(examples): add runnable Node.js SDK examples under examples/sdk/
examples/test-app is a fixture and the repo's only prior examples/ content; the real SDK usage patterns lived only in website/docs/docs/client-api.md with no runnable script anywhere. Adds four standalone, typechecked examples covering the minimum surface from #1463: root client session (create -> open -> snapshot/tap -> close with typed error handling), agent-device/metro (normalizeBaseUrl/resolveRuntimeTransport), agent-device/contracts (centerOfRect on a snapshot node), and agent-device/batch (runBatch for a custom transport). Each imports the published `agent-device/...` subpaths rather than relative src/ paths. examples/sdk/tsconfig.json path-maps those subpaths to src/sdk/ so `pnpm typecheck` (now also run against this tsconfig) checks the examples in CI without a prior build, workspace link, or publish step. Running an example for real still resolves `agent-device` as a self-referencing package after `pnpm build`. src/__tests__/client-api-examples-drift.test.ts guards the examples against drifting from client-api.md's subpath API manifest in both directions, picked up automatically by the existing unit-core vitest project (no new script or workflow needed). examples/README.md indexes the new examples and notes that test-app/ remains a fixture, not an example; it is not renamed or moved. Refs #1463
1 parent 255deb6 commit 95a1830

8 files changed

Lines changed: 401 additions & 1 deletion

File tree

‎examples/README.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Examples
2+
3+
Runnable, typechecked Node.js examples for the `agent-device` SDK surface exposed to Node
4+
consumers. Source of truth for the API itself is
5+
[Typed Client](../website/docs/docs/client-api.md); `src/__tests__/client-api-examples-drift.test.ts`
6+
guards these files against drifting out of sync with that doc.
7+
8+
## sdk/
9+
10+
Standalone scripts under [`sdk/`](./sdk) exercise the published `agent-device` export map —
11+
`agent-device`, `agent-device/metro`, `agent-device/contracts`, and `agent-device/batch` — the same
12+
way a Node consumer or the agent-device-cloud bridge would. Each file:
13+
14+
- has a top comment stating what it demonstrates and its prerequisites (daemon running,
15+
device/simulator available);
16+
- typechecks without live hardware — `pnpm typecheck` resolves the `agent-device/...` imports
17+
against `src/sdk/` via [`examples/sdk/tsconfig.json`](./sdk/tsconfig.json)'s `paths`, so CI checks
18+
them without a build or publish step;
19+
- imports the package by name (`agent-device/...`), not a relative `src/` path, so it exercises the
20+
same surface a real consumer sees;
21+
- is runnable on its own with `node --experimental-strip-types` (repo Node is >=22.12) once the
22+
package is built (`pnpm build`) — running for real resolves `agent-device` as a self-referencing
23+
package, the same way an installed consumer would.
24+
25+
| Example | Subpath | Demonstrates |
26+
| --- | --- | --- |
27+
| [`client-session.ts`](./sdk/client-session.ts) | `agent-device` | `createAgentDeviceClient` → open → snapshot/tap → close, with typed error handling |
28+
| [`metro-runtime.ts`](./sdk/metro-runtime.ts) | `agent-device/metro` | `normalizeBaseUrl`, `resolveRuntimeTransport` |
29+
| [`contracts-result.ts`](./sdk/contracts-result.ts) | `agent-device/contracts` | typed result consumption via `centerOfRect` |
30+
| [`batch-orchestration.ts`](./sdk/batch-orchestration.ts) | `agent-device/batch` | `runBatch` for a custom transport |
31+
32+
## test-app/
33+
34+
[`test-app/`](./test-app) is the Expo dogfood fixture used for `agent-device` and `skillgym`
35+
experiments (see its own [README](./test-app/README.md)) — it is a test fixture, not an SDK usage
36+
example.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Batch orchestration for a custom transport: `runBatch` keeps step
3+
* validation, inherited flags, serial execution, partial results, and
4+
* daemon-shaped error envelopes aligned with the CLI's `batch` command, so a
5+
* bridge that owns command dispatch itself does not have to reimplement them.
6+
*
7+
* Demonstrates: `runBatch` from `agent-device/batch`, consumed against the
8+
* `DaemonResponse` result type from `agent-device/contracts`.
9+
*
10+
* Prerequisites: none — `dispatch` below is a stub; a real integration would
11+
* replace it with a call into the bridge's own command dispatcher.
12+
*
13+
* Run: node --experimental-strip-types examples/sdk/batch-orchestration.ts
14+
*/
15+
import { runBatch } from 'agent-device/batch';
16+
import type { DaemonResponse } from 'agent-device/contracts';
17+
18+
type BatchRequest = Parameters<typeof runBatch>[0];
19+
20+
async function dispatch(stepReq: unknown): Promise<Record<string, unknown>> {
21+
console.log('dispatching step', stepReq);
22+
return { handled: true };
23+
}
24+
25+
function bridgeErrorToDaemonResponse(error: unknown): Extract<DaemonResponse, { ok: false }> {
26+
return {
27+
ok: false,
28+
error: {
29+
code: 'COMMAND_FAILED',
30+
message: error instanceof Error ? error.message : 'Unknown bridge error',
31+
},
32+
};
33+
}
34+
35+
async function handleBatch(req: BatchRequest): Promise<DaemonResponse> {
36+
return await runBatch(req, req.session ?? 'default', async (stepReq) => {
37+
try {
38+
return { ok: true, data: await dispatch(stepReq) };
39+
} catch (error) {
40+
return bridgeErrorToDaemonResponse(error);
41+
}
42+
});
43+
}
44+
45+
const result = await handleBatch({
46+
command: 'batch',
47+
positionals: [],
48+
flags: {
49+
batchSteps: [
50+
{ command: 'wait', input: { text: 'Welcome' } },
51+
{ command: 'back', input: {} },
52+
],
53+
},
54+
});
55+
56+
if (result.ok) {
57+
console.log(`batch completed: ${JSON.stringify(result.data)}`);
58+
} else {
59+
console.error(`batch failed [${result.error.code}]: ${result.error.message}`);
60+
process.exitCode = 1;
61+
}

‎examples/sdk/client-session.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* Root client session: create a client, open an app, capture a snapshot, tap
3+
* a node, then close the session — with typed error handling via the
4+
* exported error helpers.
5+
*
6+
* Demonstrates: `createAgentDeviceClient`, `AppError`, `isAgentDeviceError`,
7+
* and `normalizeAgentDeviceError` from the `agent-device` root export.
8+
*
9+
* Prerequisites: an `agent-device` daemon target (a booted iOS simulator).
10+
* This file typechecks without one; running it for real also requires
11+
* `pnpm build` first, so the package resolves at runtime.
12+
*
13+
* Run: node --experimental-strip-types examples/sdk/client-session.ts
14+
*/
15+
import {
16+
AppError,
17+
createAgentDeviceClient,
18+
isAgentDeviceError,
19+
normalizeAgentDeviceError,
20+
} from 'agent-device';
21+
22+
async function main(): Promise<void> {
23+
const client = createAgentDeviceClient({
24+
session: 'sdk-example',
25+
lockPolicy: 'reject',
26+
lockPlatform: 'ios',
27+
});
28+
29+
try {
30+
const devices = await client.devices.list({ platform: 'ios' });
31+
const device = devices[0];
32+
if (!device) {
33+
throw new AppError('DEVICE_NOT_FOUND', 'No iOS device available');
34+
}
35+
36+
const capabilities = await client.devices.capabilities({ platform: 'ios' });
37+
if (!capabilities.availableCommands.includes('snapshot')) {
38+
throw new AppError('UNSUPPORTED_OPERATION', 'Selected target does not support snapshots');
39+
}
40+
41+
await client.apps.open({
42+
app: 'com.apple.Preferences',
43+
platform: 'ios',
44+
udid: device.id,
45+
});
46+
47+
const snapshot = await client.capture.snapshot({ interactiveOnly: true });
48+
const target = snapshot.nodes.find((node) => node.role === 'button');
49+
if (target) {
50+
await client.interactions.press({ ref: target.ref });
51+
}
52+
} catch (error) {
53+
if (isAgentDeviceError(error)) {
54+
const normalized = normalizeAgentDeviceError(error);
55+
console.error(`agent-device error [${normalized.code}]: ${normalized.message}`);
56+
if (normalized.hint) {
57+
console.error(`hint: ${normalized.hint}`);
58+
}
59+
process.exitCode = 1;
60+
return;
61+
}
62+
throw error;
63+
} finally {
64+
await client.sessions.close();
65+
}
66+
}
67+
68+
await main();

‎examples/sdk/contracts-result.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Typed result consumption from `agent-device/contracts`: compute the center
3+
* point of a snapshot node's rect, using the same `centerOfRect` helper the
4+
* daemon and CLI use internally.
5+
*
6+
* Demonstrates: `centerOfRect` from `agent-device/contracts`, consumed
7+
* against the `CaptureSnapshotResult` shape returned by the root client.
8+
*
9+
* Prerequisites: an `agent-device` daemon target with an app already open.
10+
* This file typechecks without one.
11+
*
12+
* Run: node --experimental-strip-types examples/sdk/contracts-result.ts
13+
*/
14+
import { createAgentDeviceClient } from 'agent-device';
15+
import { centerOfRect } from 'agent-device/contracts';
16+
17+
async function main(): Promise<void> {
18+
const client = createAgentDeviceClient({ session: 'sdk-example' });
19+
20+
try {
21+
const snapshot = await client.capture.snapshot({ interactiveOnly: true });
22+
const node = snapshot.nodes.find((candidate) => candidate.rect !== undefined);
23+
if (!node?.rect) {
24+
throw new Error('No visible node with a rect in the snapshot');
25+
}
26+
27+
const center = centerOfRect(node.rect);
28+
console.log(
29+
`center of ${node.role ?? 'node'} "${node.label ?? node.ref}": (${center.x}, ${center.y})`,
30+
);
31+
} finally {
32+
await client.sessions.close();
33+
}
34+
}
35+
36+
await main();

‎examples/sdk/metro-runtime.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Metro runtime helpers: normalize a Metro base URL and resolve the
3+
* host/port/scheme a client should connect through, given the runtime hints
4+
* a daemon response (or `AppOpenOptions.runtime`) carries.
5+
*
6+
* Demonstrates: `normalizeBaseUrl` and `resolveRuntimeTransport` from
7+
* `agent-device/metro`.
8+
*
9+
* Prerequisites: none — both functions are pure and need no daemon, device,
10+
* or running Metro bundler.
11+
*
12+
* Run: node --experimental-strip-types examples/sdk/metro-runtime.ts
13+
*/
14+
import { normalizeBaseUrl, resolveRuntimeTransport } from 'agent-device/metro';
15+
import type { SessionRuntimeHints } from 'agent-device/contracts';
16+
17+
const baseUrl = normalizeBaseUrl('https://metro.example.dev///');
18+
console.log(`normalized base URL: ${baseUrl}`);
19+
20+
const hints: SessionRuntimeHints = {
21+
platform: 'ios',
22+
metroHost: 'metro.example.dev',
23+
metroPort: 443,
24+
};
25+
26+
const transport = resolveRuntimeTransport(hints);
27+
if (!transport) {
28+
throw new Error('Unable to resolve a Metro runtime transport from the provided hints');
29+
}
30+
31+
console.log(`resolved transport: ${transport.scheme}://${transport.host}:${transport.port}`);

‎examples/sdk/tsconfig.json‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"extends": "../../tsconfig.json",
3+
"compilerOptions": {
4+
"paths": {
5+
"agent-device": ["../../src/sdk/index.ts"],
6+
"agent-device/io": ["../../src/sdk/io.ts"],
7+
"agent-device/artifacts": ["../../src/sdk/artifacts.ts"],
8+
"agent-device/metro": ["../../src/sdk/metro.ts"],
9+
"agent-device/batch": ["../../src/sdk/batch.ts"],
10+
"agent-device/remote-config": ["../../src/sdk/remote-config.ts"],
11+
"agent-device/install-source": ["../../src/sdk/install-source.ts"],
12+
"agent-device/android-adb": ["../../src/sdk/android-adb.ts"],
13+
"agent-device/contracts": ["../../src/sdk/contracts.ts"],
14+
"agent-device/selectors": ["../../src/sdk/selectors.ts"],
15+
"agent-device/finders": ["../../src/sdk/finders.ts"]
16+
}
17+
},
18+
// Scoped to this directory only: these examples import `agent-device/...`
19+
// by package name (the published export map), and `paths` above resolves
20+
// those specifiers straight to `src/sdk/` so CI typechecks them without a
21+
// prior build, workspace link, or publish step. Running an example for real
22+
// still resolves `agent-device` as a self-referencing package (needs
23+
// `pnpm build`), matching how a real consumer would import it.
24+
"include": [".", "../../src/global.d.ts"]
25+
}

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@
146146
"check:unit": "pnpm test:unit && pnpm test:smoke",
147147
"check": "pnpm check:tooling && pnpm check:fallow && pnpm check:unit",
148148
"prepack": "pnpm check:mcp-metadata && pnpm build:all && pnpm package:apple-runner:npm && pnpm package:android-snapshot-helper:npm && pnpm package:android-ime-helper:npm",
149-
"typecheck": "tsc -p tsconfig.json",
149+
"typecheck": "tsc -p tsconfig.json && tsc -p examples/sdk/tsconfig.json",
150150
"test-app:install": "pnpm install --dir examples/test-app",
151151
"test-app:start": "pnpm --dir examples/test-app start",
152152
"test-app:ios": "pnpm --dir examples/test-app ios",

0 commit comments

Comments
 (0)