diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index dc66206d6..b69dd3f67 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -19,25 +19,26 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev ## Files -| File | Role | -| ---------------- | ------------------------------------------------------------------------------------------------- | -| `index.ts` | `runCli`: the global `--token`, `--gateway` and `--local`, the command lookup, the error boundary | -| `tree.ts` | The command tree — each node names the module that implements it | -| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | -| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | -| `errors.ts` | The error → code/exit mapping | -| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | -| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | -| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | -| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | -| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | -| `duration.ts` | `parseDuration` for `--ttl`-style flags | -| `termination.ts` | The signals and parent-exit wait a held lease blocks on | -| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | -| `stdio.ts` | `readPipedStdin`: a piped stdin for `simctl`/`adb`, read to EOF | -| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | -| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | -| `main.ts` | The bin; sets `process.exitCode` | +| File | Role | +| ----------------- | ------------------------------------------------------------------------------------------------- | +| `index.ts` | `runCli`: the global `--token`, `--gateway` and `--local`, the command lookup, the error boundary | +| `tree.ts` | The command tree — each node names the module that implements it | +| `environment.ts` | `buildCliEnvironment`: the ports a command may reach, from the ports it is handed | +| `types.ts` | `CliEnvironment` and its ports — types only, so routing loads no code | +| `errors.ts` | The error → code/exit mapping | +| `usage-error.ts` | `UsageError` and `withHelpHint`, the help pointer's one wording | +| `connect.ts` | `connectDaemonClient`: credential order, the admin session, the notice | +| `args.ts` | `commandArgs` / `requiredPositional` / `subcommandOrUsage` / `writeResult` | +| `commands/*.ts` | One module per command, `run(argv, context)`; loaded by the tree on a hit | +| `format.ts` | The human renderers for `status`, `worker list`, `daemon start`, etc. | +| `duration.ts` | `parseDuration` for `--ttl`-style flags | +| `termination.ts` | The signals and parent-exit wait a held lease blocks on | +| `log-file.ts` | `readLogFile`: `daemon.log` plus a rotated generation | +| `stdio.ts` | `readPipedStdin`: a piped stdin for `simctl`/`adb`, read to EOF | +| `remote-lease.ts` | `resolveRemoteLeaseId`: the requester's only lease, shared by `simctl`/`adb` and `rotate` | +| `passthrough.ts` | `spawnPassthrough`: runs a resolved simctl/adb command, stdio inherited | +| `follow-log.ts` | `followLog`: `daemon logs --follow` across rotations | +| `main.ts` | The bin; sets `process.exitCode` | `format.ts`, `duration.ts` and `termination.ts` are reached only from a command module, and `follow-log.ts` and `passthrough.ts` only from a dynamic import inside `environment.ts`. @@ -89,6 +90,10 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev fills the lease's device in and refuses another (ADR 0047). A piped stdin is read to EOF first; output chunks go to stdout and stderr. `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` become usage errors (exit 2). + 5a. **`simlock rotate [--lease ]`** — `parseOrientation` (contract) spells the + orientation, an unknown one is a usage error (exit 2); the lease is `--lease` (anywhere on the line) + or the requester's only lease (`resolveRemoteLeaseId`); `device.rotate` answers, and the line printed + is `Rotated lease to ` from the answer. Worker or gateway alike. 6. **`simlock events --follow`** — subscribe, then replay, then print buffered pushes not already replayed (by `eventKey`). `--since` without `--follow` never launches a daemon; with none running it reads `history.db` itself (read-only; no file is empty, an unreadable diff --git a/src/cli/commands/passthrough.ts b/src/cli/commands/passthrough.ts index 39861144b..5a5d0ac67 100644 --- a/src/cli/commands/passthrough.ts +++ b/src/cli/commands/passthrough.ts @@ -1,5 +1,6 @@ import type { SimlockAdminClient } from "../../admin/index.js"; import { asUsageIfRefused, UsageError } from "../errors.js"; +import { resolveRemoteLeaseId } from "../remote-lease.js"; import { connectDaemonClient } from "../connect.js"; import type { CommandContext } from "../tree.js"; @@ -103,26 +104,4 @@ function extractLeaseFlag(args: readonly string[]): { return { leaseFlag, rest: args.slice(index) }; } -async function resolveRemoteLeaseId( - client: SimlockAdminClient, - environment: CommandContext["environment"], -): Promise { - const { leases } = await client.listLeases(); - const own = - client.role === "admin" - ? leases.filter((lease) => lease.requesterId === environment.requesterId) - : leases; - if (own.length === 0) { - throw new UsageError( - `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, - ); - } - if (own.length > 1) { - throw new UsageError( - `${environment.requesterId} holds more than one lease (${own.map((lease) => lease.id).join(", ")}); pass --lease to name the device you mean`, - ); - } - return (own[0] as { readonly id: string }).id; -} - export { run }; diff --git a/src/cli/commands/rotate.ts b/src/cli/commands/rotate.ts new file mode 100644 index 000000000..ef824ccba --- /dev/null +++ b/src/cli/commands/rotate.ts @@ -0,0 +1,40 @@ +import { parseOrientation } from "../../contract/index.js"; +import { commandArgs, requiredPositional, UsageError } from "../args.js"; +import { connectDaemonClient } from "../connect.js"; +import { resolveRemoteLeaseId } from "../remote-lease.js"; +import type { CommandContext } from "../tree.js"; + +async function run( + argv: readonly string[], + { environment, token }: CommandContext, +): Promise { + const { help, lease, positionals } = commandArgs(argv, { + help: { type: "boolean", short: "h" }, + lease: { type: "string" }, + }); + if (help) { + environment.stdout.write( + "Usage: simlock rotate [--lease ]\n", + ); + return 0; + } + const parsed = parseOrientation(requiredPositional(positionals, "orientation")); + if (!parsed.ok) throw new UsageError(parsed.message); + const client = await connectDaemonClient(environment, token); + try { + const leaseId = + typeof lease === "string" ? lease : await resolveRemoteLeaseId(client, environment); + const requesterId = client.role === "admin" ? environment.requesterId : undefined; + const rotated = await client.rotate( + leaseId, + parsed.orientation, + requesterId === undefined ? undefined : { requesterId }, + ); + environment.stdout.write(`Rotated lease ${rotated.leaseId} to ${rotated.orientation}\n`); + return 0; + } finally { + await client.close(); + } +} + +export { run }; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ba8e24abd..01c3de2d2 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -10674,3 +10674,182 @@ describe("simlock worker update", () => { } }); }); + +describe("simlock rotate", () => { + const heldLease = { + deviceId: "dev_1", + grantedAt: 0, + id: "lse_mine", + lastRenewedAt: 0, + idChosenByRequester: false, + ownerId: "some-other-principal", + requesterId: "test-requester", + ttlDeadline: 60_000, + ttlMs: 60_000, + }; + + const two = [heldLease, { ...heldLease, deviceId: "dev_2", id: "lse_other" }]; + + async function rotateWith( + argv: readonly string[], + leases: readonly (typeof heldLease)[], + role: "admin" | "agent" = "admin", + daemonHome?: { role: "gateway"; dataDirectory: string; gatewayPresent: true }, + ) { + const output = outputCapture(); + const rotations: unknown[] = []; + let closes = 0; + const exitCode = await runCli( + argv, + output.environmentWith({ + ...(daemonHome === undefined ? {} : { daemonHome }), + connectAdmin: async () => + fakeClient({ + role, + close: () => { + closes += 1; + return Promise.resolve(); + }, + listLeases: () => Promise.resolve({ leases: [...leases] }), + rotate: (leaseId, orientation, options) => { + rotations.push({ leaseId, orientation, options }); + return Promise.resolve({ leaseId: `${leaseId}_answered`, orientation }); + }, + }), + }), + ); + return { closes: () => closes, exitCode, output, rotations }; + } + + it("a user runs simlock rotate [--lease ], on a worker or with --gateway, and sees Rotated lease to , or a usage error", async () => { + const only = await rotateWith(["rotate", "landscape-left"], [heldLease]); + expect(only.exitCode).toBe(0); + expect(only.rotations).toEqual([ + { + leaseId: "lse_mine", + orientation: "landscape_left", + options: { requesterId: "test-requester" }, + }, + ]); + expect(only.output.stdout).toBe("Rotated lease lse_mine_answered to landscape_left\n"); + expect(only.closes()).toBe(1); + + const asAgent = await rotateWith(["rotate", "landscape-left"], [heldLease], "agent"); + expect(asAgent.exitCode).toBe(0); + expect(asAgent.rotations).toEqual([ + { leaseId: "lse_mine", orientation: "landscape_left", options: undefined }, + ]); + + const gateway = { + role: "gateway", + dataDirectory: "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/simlock/gateway", + gatewayPresent: true, + } as const; + for (const argv of [ + ["--gateway", "rotate", "landscape-left"], + ["rotate", "landscape-left", "--gateway"], + ]) { + const throughGateway = await rotateWith(argv, [heldLease], "agent", gateway); + expect(throughGateway.exitCode, argv.join(" ")).toBe(0); + expect(throughGateway.rotations, argv.join(" ")).toEqual([ + { leaseId: "lse_mine", orientation: "landscape_left", options: undefined }, + ]); + expect(throughGateway.output.stdout, argv.join(" ")).toBe( + "Rotated lease lse_mine_answered to landscape_left\n", + ); + } + + for (const argv of [ + ["rotate", "--lease", "lse_other", "left"], + ["rotate", "left", "--lease", "lse_other"], + ["rotate", "left", "--lease=lse_other"], + ]) { + const named = await rotateWith(argv, two); + expect(named.exitCode).toBe(0); + expect(named.rotations).toEqual([ + { + leaseId: "lse_other", + orientation: "landscape_left", + options: { requesterId: "test-requester" }, + }, + ]); + } + + for (const [spelling, orientation] of [ + ["LEFT", "landscape_left"], + [" left ", "landscape_left"], + ["upside-down", "portrait_upside_down"], + ]) { + const spelled = await rotateWith(["rotate", spelling as string], [heldLease]); + expect(spelled.exitCode).toBe(0); + expect(spelled.output.stdout).toBe(`Rotated lease lse_mine_answered to ${orientation}\n`); + } + + const refusals: [readonly string[], readonly (typeof heldLease)[], RegExp][] = [ + [["rotate", "sideways"], [heldLease], /^Unknown orientation sideways; use portrait,/], + [["rotate", "auto"], [heldLease], /^Unknown orientation auto;/], + [["rotate", "landscapeLeft"], [heldLease], /^Unknown orientation landscapeLeft;/], + [["rotate"], [heldLease], /^Expected orientation/], + [["rotate", "left"], [], /test-requester/], + [["rotate", "left"], two, /lse_mine.*lse_other.*--lease /s], + ]; + for (const [argv, leases, message] of refusals) { + const refused = await rotateWith(argv, leases); + expect(refused.exitCode).toBe(2); + expect(refused.rotations).toEqual([]); + expect(JSON.parse(refused.output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringMatching(message) }, + }); + } + + const unsupported = outputCapture(); + let unsupportedCloses = 0; + await expect( + runCli( + ["rotate", "left", "--lease", "lse_android"], + unsupported.environmentWith({ + connectAdmin: async () => + fakeClient({ + close: () => { + unsupportedCloses += 1; + return Promise.resolve(); + }, + rotate: () => + Promise.reject( + new SimlockError( + "ROTATION_UNSUPPORTED", + "domain", + "Lease lse_android is on an Android emulator; only an iOS simulator can be rotated", + { + class: "emulator", + leaseId: "lse_android", + physical: false, + platform: "android", + }, + ), + ), + }), + }), + ), + ).resolves.toBe(12); + expect(JSON.parse(unsupported.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { + code: "ROTATION_UNSUPPORTED", + message: + "Lease lse_android is on an Android emulator; only an iOS simulator can be rotated", + }, + }); + expect(unsupported.stdout).toBe(""); + expect(unsupportedCloses).toBe(1); + + const help = await rotateWith(["rotate", "--help"], [heldLease]); + expect(help.exitCode).toBe(0); + expect(help.output.stdout).toBe( + "Usage: simlock rotate [--lease ]\n", + ); + expect(help.rotations).toEqual([]); + const listing = outputCapture(); + await runCli(["--help"], listing.environmentWith()); + expect(listing.stdout).toContain(" rotate [--lease ]"); + }); +}); diff --git a/src/cli/index.ts b/src/cli/index.ts index 05d6474d2..5af26b66f 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -33,6 +33,9 @@ Commands: device add --platform [--json] Enrol a physical device plugged into this host device remove [--json] Forget an enrolled physical device; the device is untouched + rotate [--lease ] + Turn the leased iOS simulator: portrait, portrait-upside-down, + landscape-left or landscape-right simctl Run xcrun simctl against Simlock's iOS device set adb Run adb against Simlock's adb server mcp Start the stdio MCP server diff --git a/src/cli/remote-lease.ts b/src/cli/remote-lease.ts new file mode 100644 index 000000000..8f874b8f3 --- /dev/null +++ b/src/cli/remote-lease.ts @@ -0,0 +1,25 @@ +import type { SimlockAdminClient } from "../admin/index.js"; +import { UsageError } from "./errors.js"; +import type { CommandContext } from "./tree.js"; + +export async function resolveRemoteLeaseId( + client: SimlockAdminClient, + environment: CommandContext["environment"], +): Promise { + const { leases } = await client.listLeases(); + const own = + client.role === "admin" + ? leases.filter((lease) => lease.requesterId === environment.requesterId) + : leases; + if (own.length === 0) { + throw new UsageError( + `No lease is held by ${environment.requesterId}: run \`simlock lease\` first, or set SIMLOCK_AGENT_ID to the id that holds it`, + ); + } + if (own.length > 1) { + throw new UsageError( + `${environment.requesterId} holds more than one lease (${own.map((lease) => lease.id).join(", ")}); pass --lease to name the device you mean`, + ); + } + return (own[0] as { readonly id: string }).id; +} diff --git a/src/cli/tree.ts b/src/cli/tree.ts index 75d477671..68298dc88 100644 --- a/src/cli/tree.ts +++ b/src/cli/tree.ts @@ -130,6 +130,7 @@ export const COMMANDS: readonly CommandNode[] = [ }, { name: "simctl", load: () => import("./commands/passthrough.js") }, { name: "adb", load: () => import("./commands/passthrough.js") }, + { name: "rotate", load: () => import("./commands/rotate.js") }, { name: "mcp", load: () => import("./commands/mcp.js") }, { name: "instructions", load: () => import("./commands/instructions.js") }, { name: "setup", load: () => import("./commands/setup.js") }, diff --git a/src/instructions/index.test.ts b/src/instructions/index.test.ts index 78eacddcd..c5906fdf3 100644 --- a/src/instructions/index.test.ts +++ b/src/instructions/index.test.ts @@ -31,6 +31,7 @@ const TOOL_NAMES = [ "release_simulator", "lease_status", "run_on_device", + "rotate_device", ]; const REQUIRED: Readonly> = { @@ -99,6 +100,7 @@ const REQUIRED: Readonly> = ...REFUSED_ADB_SEQUENCES.map(({ sequence }) => `\`simlock adb ${sequence.join(" ")}\``), "`simlock adb` refuses any option before the subcommand other than `-s`, `-t`, `-d` or `-e`", "`simlock adb shell`", + "`simlock rotate `", ...[ ERROR_TABLE.QUEUE_TIMEOUT.cliExitCode, ERROR_TABLE.NO_CAPACITY.cliExitCode, diff --git a/src/instructions/index.ts b/src/instructions/index.ts index 757d463bf..f0d53b30c 100644 --- a/src/instructions/index.ts +++ b/src/instructions/index.ts @@ -40,6 +40,7 @@ const SIMLOCK_CLI = `## simlock CLI - The JSON line holds \`lease.id\`, \`lease.ttlDeadline\`, \`device.address\` and \`environment\`. \`--export-env\` prints \`environment\` as shell \`export\` lines. - Release with \`simlock release \`, or stop the background \`simlock lease\`. - Reach the device through \`simlock simctl\` and \`simlock adb -s \`, or through the grant's \`environment\`. On another machine, use \`simlock simctl --lease \` and \`simlock adb --lease \`. +- Turn an iOS simulator with \`simlock rotate \` (\`portrait\`, \`portrait-upside-down\`, \`landscape-left\` or \`landscape-right\`); add \`--lease \` when you hold more than one lease. - If this machine runs a gateway and the operator says to use it, put \`--gateway\` right after \`simlock\`. Some commands are refused on purpose, because they break the device for Simlock or for other agents. Do not work around them; release the lease instead. @@ -61,13 +62,14 @@ Every failure writes one JSON line on stderr, \`{"error":{"code":"...","message" const MCP = `## MCP -When Simlock is connected to you as an MCP server, it has five tools: +When Simlock is connected to you as an MCP server, it has six tools: - \`list_devices\`: what can be leased. Call it before leasing. - \`lease_simulator\`: lease one device. It is renewed for you and released when the server exits. - \`release_simulator\`: give the device back. - \`lease_status\`: whether you still hold a lease, and which. Call it after a context compaction. - \`run_on_device\`: run one \`simctl\`, \`adb\` or \`devicectl\` command on your leased device, for example install and launch an app. Leave the device out; Simlock fills it in. It returns \`exitCode\`, \`stdout\`, \`stderr\` and \`truncated\`; a non-zero exit code is the command's answer, not an error. +- \`rotate_device\`: turn your leased iOS simulator to \`portrait\`, \`portrait-upside-down\`, \`landscape-left\` or \`landscape-right\`. It returns \`leaseId\` and \`orientation\`; an Android emulator is refused. Under Codex and pi, the MCP server and the CLI are two identities: use only one of them per session.`; diff --git a/src/mcp/AGENTS.md b/src/mcp/AGENTS.md index a76d0ff52..1a3a56572 100644 --- a/src/mcp/AGENTS.md +++ b/src/mcp/AGENTS.md @@ -41,8 +41,12 @@ Surface: [connect-your-agent.mdx](../../website/src/content/docs/docs/getting-st 32 768 characters; a non-zero exit is a result. No held lease: `NO_LEASE`. With a progress token: `notifications/progress` on the first output, then at most one a second, and every 10 s while silent (the session's clock). -4. **Serialize** — every tool call but `run_on_device` queues on one chain in `McpSession`; - `run_on_device` does not queue, so `lease_status` and `release_simulator` run while a command does. + - `rotate_device` → `device.rotate` on the held lease. Input: `orientation`, 1 to 64 characters, + parsed by the contract's `parseOrientation` (an unknown spelling: `BAD_REQUEST` with its + message, before any call). Result `{ leaseId, orientation }`. No held lease: `NO_LEASE`; the + daemon's refusal (`ROTATION_UNSUPPORTED`, `INPUT_UNAVAILABLE`) is the tool error. +4. **Serialize** — every tool call but `run_on_device` and `rotate_device` queues on one chain in + `McpSession`; those two do not queue, so `lease_status` and `release_simulator` run while a command does. 5. **Renew** — a grant starts `startLeaseRenewal` (lease-policy): every third of the TTL. 6. **Pushes** → MCP logging messages, logger `simlock`: lease lost (warning), device unhealthy (warning), device recovered (info). diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index 82a171164..1da44facf 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -14,6 +14,7 @@ import { z } from "zod"; import { + INPUT_ORIENTATIONS, leaseRecordSchema, leaseRequestFields, OPERATIONS, @@ -103,4 +104,13 @@ export type ListDevicesOutput = z.infer; export type ReleaseSimulatorInput = z.infer; export type ReleaseSimulatorOutput = z.infer; export type LeaseStatusOutput = z.infer; +export const rotateDeviceInputSchema = z.object({ orientation: z.string().min(1).max(64) }); + +export const rotateDeviceOutputSchema = z.object({ + leaseId: z.string(), + orientation: z.enum(INPUT_ORIENTATIONS), +}); + +export type RotateDeviceInput = z.infer; +export type RotateDeviceOutput = z.infer; export type RunOnDeviceInput = z.infer; diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index dce4303ea..177507238 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -16,7 +16,7 @@ import { leaseSimulatorInputSchema } from "./contracts.js"; import { createMcpServer } from "./server.js"; describe("MCP server (smoke)", () => { - it("advertises exactly the lease, catalog, status and run_on_device tools, and walks lease -> list -> status -> release", async () => { + it("advertises exactly the lease, catalog, status, run_on_device and rotate_device tools, and walks lease -> list -> status -> release", async () => { const client = new FakeSimlockClient(); const grant = sampleGrant(); client.requestLeaseImpl = () => Promise.resolve(grant); @@ -67,6 +67,7 @@ describe("MCP server (smoke)", () => { "release_simulator", "lease_status", "run_on_device", + "rotate_device", ]); expect(tools.tools.find((tool) => tool.name === "list_devices")?.description).toContain( "modelClasses", @@ -84,6 +85,8 @@ describe("MCP server (smoke)", () => { "stdin", "tool", ]); + const rotateTool = tools.tools.find((tool) => tool.name === "rotate_device"); + expect(Object.keys(rotateTool?.inputSchema.properties ?? {})).toEqual(["orientation"]); expect(runTool?.description).toBe( "Run one simctl, adb or devicectl command on this session's leased device, on the machine that holds it. Leave the device out: Simlock fills in the lease's UDID or serial, and refuses a command that names another device. File paths are on that machine. Output is text: stdout and stderr each keep their last 32768 characters, and truncated says when any was cut. A non-zero exitCode is the command's own answer, not a tool error. There is no terminal: a bare adb shell is refused, and an interactive command hangs until the time limit (10 minutes by default) stops it.", ); @@ -906,6 +909,83 @@ describe("MCP run_on_device alongside other tools", () => { }); }); +describe("MCP rotate_device", () => { + it("rotates the session's held lease and returns its id and the canonical orientation", async () => { + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant()); + client.rotateImpl = (leaseId, orientation) => Promise.resolve({ leaseId, orientation }); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + const { mcpClient, close } = await connectedServer(client); + try { + const never = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(never.isError).toBe(true); + expect(JSON.parse(text(never)).code).toBe("NO_LEASE"); + await call(mcpClient, "lease_simulator", { model: "iPhone 17 Pro", platform: "ios" }); + const result = await call(mcpClient, "rotate_device", { orientation: "landscape-left" }); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual({ + leaseId: "lease-1", + orientation: "landscape_left", + }); + expect(client.calls.filter((entry) => entry.method === "rotate")).toEqual([ + { input: { leaseId: "lease-1", orientation: "landscape_left" }, method: "rotate" }, + ]); + + for (const [spelling, canonical] of [ + ["LEFT", "landscape_left"], + [" upside-down ", "portrait_upside_down"], + ]) { + const spelled = await call(mcpClient, "rotate_device", { orientation: spelling }); + expect(spelled.isError).not.toBe(true); + expect(spelled.structuredContent).toEqual({ leaseId: "lease-1", orientation: canonical }); + } + for (const [orientation, bound] of [ + ["", "expected string to have >=1 characters"], + ["x".repeat(65), "expected string to have <=64 characters"], + ] as const) { + const refused = await call(mcpClient, "rotate_device", { orientation }); + expect(refused.isError).toBe(true); + expect(text(refused)).toContain(`Invalid arguments for tool rotate_device: Too `); + expect(text(refused)).toContain(bound); + } + const longest = await call(mcpClient, "rotate_device", { orientation: "x".repeat(64) }); + expect(JSON.parse(text(longest)).code).toBe("BAD_REQUEST"); + expect(client.calls.filter((entry) => entry.method === "rotate")).toHaveLength(3); + const unknown = await call(mcpClient, "rotate_device", { orientation: "sideways" }); + expect(unknown.isError).toBe(true); + expect(JSON.parse(text(unknown))).toEqual({ + code: "BAD_REQUEST", + message: + "Unknown orientation sideways; use portrait, portrait-upside-down, landscape-left or landscape-right", + }); + const unsupported = new SimlockError( + "ROTATION_UNSUPPORTED", + "domain", + "Lease lease-1 is on an Android emulator; only an iOS simulator can be rotated", + { class: "emulator", leaseId: "lease-1", physical: false, platform: "android" }, + ); + client.rotateImpl = () => Promise.reject(unsupported); + const refusal = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(refusal.isError).toBe(true); + expect(JSON.parse(text(refusal))).toEqual({ + code: "ROTATION_UNSUPPORTED", + message: unsupported.message, + }); + client.rotateImpl = (leaseId, orientation) => Promise.resolve({ leaseId, orientation }); + + await call(mcpClient, "release_simulator", { leaseId: "lease-1" }); + const released = await call(mcpClient, "rotate_device", { orientation: "left" }); + expect(released.isError).toBe(true); + expect(JSON.parse(text(released))).toEqual({ + code: "NO_LEASE", + message: "This MCP session holds no lease. Call lease_simulator first.", + }); + } finally { + await close(); + } + }); +}); + function call(client: Client, name: string, arguments_: Record) { return client.request( { method: "tools/call", params: { arguments: arguments_, name } }, diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 83b7f4147..e82a3c51f 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -15,6 +15,8 @@ import { listDevicesOutputSchema, releaseSimulatorInputSchema, releaseSimulatorOutputSchema, + rotateDeviceInputSchema, + rotateDeviceOutputSchema, runOnDeviceInputSchema, runOnDeviceOutputSchema, } from "./contracts.js"; @@ -346,6 +348,24 @@ export function createMcpServer( void server.server.sendLoggingMessage(deviceHealthLoggingMessage(notice)); }); + server.registerTool( + "rotate_device", + { + title: "Rotate device", + description: + "Turn this session's leased iOS simulator to portrait, portrait-upside-down, landscape-left or landscape-right. Only an iOS phone or tablet simulator rotates: an Android emulator, a physical device or an Apple TV is refused with ROTATION_UNSUPPORTED.", + inputSchema: rotateDeviceInputSchema, + outputSchema: rotateDeviceOutputSchema, + }, + async (input) => { + try { + return success(await session.rotateDevice(input)); + } catch (error: unknown) { + return failure(error); + } + }, + ); + return server; } diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 1a6188dd4..1b6e73c2d 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -8,6 +8,7 @@ import { type LeaseRequestInput, type SimlockClient, } from "../client/index.js"; +import { parseOrientation } from "../contract/index.js"; import { awaitWithin, RELEASE_TIMEOUT_MS, @@ -23,6 +24,8 @@ import type { ListDevicesOutput, ReleaseSimulatorInput, ReleaseSimulatorOutput, + RotateDeviceInput, + RotateDeviceOutput, RunOnDeviceInput, } from "./contracts.js"; @@ -300,6 +303,22 @@ export class McpSession { return client.exec({ ...input, leaseId }, { onOutput }); } + // why: not on `#mutate`, like `runOnDevice`; the parse is first so a bad spelling never reaches the daemon. + async rotateDevice(input: RotateDeviceInput): Promise { + this.#throwIfClosed(); + const parsed = parseOrientation(input.orientation); + if (!parsed.ok) throw new McpSessionError("BAD_REQUEST", parsed.message); + const leaseId = this.#heldLeaseId; + if (leaseId === undefined) { + throw new McpSessionError( + "NO_LEASE", + "This MCP session holds no lease. Call lease_simulator first.", + ); + } + const client = await this.#clientForUse(); + return client.rotate(leaseId, parsed.orientation); + } + /** Notifies when this session's held lease ends elsewhere (expiry or a force-release). */ onLeaseLost(listener: (notice: LeaseLostNotice) => void): () => void { this.#leaseLostListeners.add(listener); diff --git a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx index 30b1a9ac8..56eb92c1e 100644 --- a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx +++ b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx @@ -66,7 +66,7 @@ While the request waits in the queue or a device boots, `simlock lease` blocks a ## Use the MCP server -`simlock mcp` runs Simlock's MCP server over stdio. It has five tools: +`simlock mcp` runs Simlock's MCP server over stdio. It has six tools: | Tool | What it does | | --- | --- | @@ -75,6 +75,7 @@ While the request waits in the queue or a device boots, `simlock lease` blocks a | `release_simulator` | Releases this session's lease. | | `lease_status` | Reports this session's lease, or `held: false` when it has none. Safe to call any time, for example after the agent's context was compacted. Through a gateway it can report `held: false` for up to about a minute after the worker holding the lease restarts, while the worker is `starting`; do not request a new device on that answer, call it again. | | `run_on_device` | Runs one `simctl`, `adb` or `devicectl` command on this session's lease, on the machine that holds the device. Takes `tool`, `args` and, optionally, `stdin`. Never takes a device or a lease id: Simlock fills in the lease's device and refuses a command that names another. Returns `{exitCode, stdout, stderr, truncated}`; stdout and stderr each keep their last 32768 characters, and `truncated` says when any was cut. A non-zero `exitCode` is the command's own answer, not an error. Without a lease it answers `NO_LEASE`. There is no terminal, and a command that waits for input is stopped after the time limit (10 minutes by default). | +| `rotate_device` | Turns this session's iOS simulator to an orientation. Takes `orientation`: `portrait`, `portrait-upside-down`, `landscape-left` or `landscape-right`. Returns `{leaseId, orientation}`. Without a lease it answers `NO_LEASE`; an unknown spelling is `BAD_REQUEST`; an Android emulator, a physical device or an Apple TV is refused with `ROTATION_UNSUPPORTED`. | The server sends the short version of the rules to the client when it connects, and the full text as the resource `simlock://instructions`. It renews its lease while it runs, and releases it when the agent tool closes the connection. It also starts the daemon if it is not running. diff --git a/website/src/content/docs/docs/introduction/index.mdx b/website/src/content/docs/docs/introduction/index.mdx index ae51c80fc..c6cac2ca7 100644 --- a/website/src/content/docs/docs/introduction/index.mdx +++ b/website/src/content/docs/docs/introduction/index.mdx @@ -32,7 +32,7 @@ Simlock works by agreement, not by force. It does not hide other devices or bloc | Way in | Who it is for | | --- | --- | | CLI (`simlock lease`, `simlock release`) | Any agent that can run shell commands, and you at a terminal. | -| MCP server (`simlock mcp`) | Agents that use the Model Context Protocol. Five tools: list, lease, release, status, run a command. | +| MCP server (`simlock mcp`) | Agents that use the Model Context Protocol. Six tools: list, lease, release, status, run a command, rotate. | | HTTP API | Agents on another machine. They need a token from the operator. | | Programmatic client (`simlock/client`) | Node.js tools on the same machine that want to lease devices without running the CLI. | diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 2265b5f7c..cc91f18e2 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -15,6 +15,7 @@ This page lists what each command accepts. For what a command is for and when to | [`simlock release`](#simlock-release) | Give a lease back | [Lease lifecycle](/simlock/docs/using-devices/lease-lifecycle) | | [`simlock simctl`](#simlock-simctl) | Run `xcrun simctl` against Simlock's simulators | [Working with a device](/simlock/docs/using-devices/working-with-a-device) | | [`simlock adb`](#simlock-adb) | Run `adb` against Simlock's emulators | [Working with a device](/simlock/docs/using-devices/working-with-a-device) | +| [`simlock rotate`](#simlock-rotate) | Turn your leased iOS simulator to portrait, portrait-upside-down, landscape-left or landscape-right | — | | [`simlock catalog`](#simlock-catalog) | Show the models, runtimes and images you can lease | [Choosing a device](/simlock/docs/using-devices/choosing-a-device) | | [`simlock mcp`](#simlock-mcp) | Start the MCP server for an agent | [Connect your agent](/simlock/docs/getting-started/connect-your-agent) | | [`simlock instructions`](#simlock-instructions) | Print the rules an agent must follow, for its prompt | [Connect your agent](/simlock/docs/getting-started/connect-your-agent) | @@ -185,6 +186,21 @@ simlock adb [--lease ] The command exits with `adb`'s own exit code. Simlock refuses `adb kill-server`, flags that move adb to a different server, and (through a gateway) `adb shell` with no command, with `PASSTHROUGH_REFUSED` (exit 2). `-s`, `-t`, `-d` and `-e` are allowed before the subcommand. Through a gateway the worker adds `-s ` for an emulator, and refuses `-s` with another serial, `-e`, `-d` and `-t`. +## simlock rotate + +Turn your leased iOS simulator to an orientation, on a worker or through a gateway. It calls `device.rotate`, so only an iOS phone or tablet simulator turns. + +```text +simlock rotate [--lease ] +``` + +| Flag | Meaning | Default | +| --- | --- | --- | +| `` | `portrait`, `portrait-upside-down`, `landscape-left` or `landscape-right`. `left`, `right` and `upside-down` are short for the last three, case and surrounding spaces do not matter, and the underscore spellings (`landscape_left`) work too. | — | +| `--lease ` | The lease to turn, before or after the orientation. | Your only lease | + +It prints `Rotated lease to `, with the orientation spelled `portrait`, `portrait_upside_down`, `landscape_left` or `landscape_right`. An orientation Simlock does not know, or several leases without `--lease`, is a usage error (exit 2). A lease on an Android emulator, a physical device or an Apple TV fails with `ROTATION_UNSUPPORTED` (exit 12); an input helper that cannot start fails with `INPUT_UNAVAILABLE` (exit 1). + ## simlock catalog Show what you can lease: per platform, the installed runtimes and the default, the models grouped by class with the default model of each class, and, on Android, the installed system images. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). @@ -200,7 +216,7 @@ simlock catalog [--platform ] [--json] ## simlock mcp -Start Simlock's MCP server on stdin and stdout, for an agent to call. It offers the tools `list_devices`, `lease_simulator`, `release_simulator`, `lease_status` and `run_on_device`. See [Connect your agent](/simlock/docs/getting-started/connect-your-agent). +Start Simlock's MCP server on stdin and stdout, for an agent to call. It offers the tools `list_devices`, `lease_simulator`, `release_simulator`, `lease_status`, `run_on_device` and `rotate_device`. See [Connect your agent](/simlock/docs/getting-started/connect-your-agent). ```text simlock mcp diff --git a/website/src/site/content.ts b/website/src/site/content.ts index 86bde6c90..05dc4b5c5 100644 --- a/website/src/site/content.ts +++ b/website/src/site/content.ts @@ -195,7 +195,7 @@ export const home = { lang: "json", code: code.mcp, pkg: "simlock mcp", - note: "Five tools for agents that speak MCP: list, lease, release, status and run a command.", + note: "Six tools for agents that speak MCP: list, lease, release, status, run a command and rotate.", href: docs.connect, }, {