@nomac/sdk 0.0.0-stage → 1.0.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,134 @@
1
+ import { type Transport } from "./http.ts";
2
+ import type { OperationOptions, PhoneLinks, PhoneRecording, PhoneSession, PhoneStartOptions, SessionToken, StopNotice, ToolName, ToolResult, ViewLink } from "./types.ts";
3
+ /** The account's phones (iPhone and iPad Simulators): start one (for one of your users with a label), read one, list them. */
4
+ export declare class Phones {
5
+ #private;
6
+ constructor(http: Transport);
7
+ /**
8
+ * Starts a phone and answers it at once, usually queued: phone.waitUntilReady() follows it (a phone from the pool is ready
9
+ * in seconds). With reuse and a label, the user's live phone is the answer (phone.reused). The same idempotencyKey retries.
10
+ */
11
+ start(options?: PhoneStartOptions, { idempotencyKey }?: {
12
+ idempotencyKey?: string;
13
+ }): Promise<Phone>;
14
+ /** The account's phones, newest first; with label, one user's. */
15
+ list({ label }?: {
16
+ label?: string;
17
+ }): Promise<Phone[]>;
18
+ /** A phone by its id, read. */
19
+ get(id: string): Promise<Phone>;
20
+ }
21
+ /** A phone: its session (state, device, label, cost, deadlines) and links, and what can be done with it. */
22
+ export declare class Phone {
23
+ #private;
24
+ readonly id: string;
25
+ session: PhoneSession;
26
+ links: PhoneLinks | undefined;
27
+ /** Whether a start with reuse answered this live phone instead of a new one. */
28
+ readonly reused: boolean;
29
+ /** As of the last refresh(): set in the phone's last 15 minutes before a limit or the credit's end. */
30
+ stopNotice: StopNotice | null;
31
+ /** As of stop() or the last refresh(): the MP4 of a screen_record the phone's stop ended. */
32
+ recording: PhoneRecording | null;
33
+ constructor(http: Transport, session: PhoneSession, links?: PhoneLinks, reused?: boolean);
34
+ get state(): import("./types.ts").SessionState;
35
+ /** Reads the phone again. */
36
+ refresh(): Promise<this>;
37
+ /** Waits until the phone is ready (a phone from the pool takes seconds; a queued one up to 5 minutes). */
38
+ waitUntilReady({ timeoutMs, intervalMs }?: {
39
+ timeoutMs?: number;
40
+ intervalMs?: number;
41
+ }): Promise<this>;
42
+ /**
43
+ * Runs one of the phone's tools (ui_look, ui_act, app_run, tests_run, app_control, ...) and waits for its result: {text,
44
+ * content, isError, raw}. A long build that hands back a job is followed with job_status until it ends, unless waitForJobs is false.
45
+ */
46
+ tool(name: ToolName | (string & {}), args?: Record<string, unknown>, { idempotencyKey, intervalMs, timeoutMs, waitForJobs }?: {
47
+ idempotencyKey?: string;
48
+ intervalMs?: number;
49
+ timeoutMs?: number;
50
+ waitForJobs?: boolean;
51
+ }): Promise<ToolResult>;
52
+ /** Stops a running tool call; a finished one is answered as it is. */
53
+ cancel(callId: string): Promise<Record<string, any>>;
54
+ /**
55
+ * A git repository into the phone's workspace: {url, ref?, token? | secret?}. A private repository's token is token itself
56
+ * (used for this fetch, kept nowhere) or secret, the account's secret holding it. Answers {root, commit}: root is the path
57
+ * app_run and tests_run take.
58
+ */
59
+ fetchGit({ url, ref, token, secret }: {
60
+ url: string;
61
+ ref?: string;
62
+ token?: string;
63
+ secret?: string;
64
+ }, { idempotencyKey, timeoutMs }?: OperationOptions): Promise<{
65
+ state: "done";
66
+ root: string;
67
+ commit: string;
68
+ }>;
69
+ /** An archive (.tar.gz or .zip of a project, or of a Simulator .app) into the workspace under name, up to 2 GiB. Answers {root, app?}. */
70
+ uploadArchive(data: Uint8Array | ArrayBuffer | Blob, { name, idempotencyKey, timeoutMs }?: OperationOptions & {
71
+ name?: string;
72
+ }): Promise<{
73
+ state: "done";
74
+ root: string;
75
+ app?: string;
76
+ }>;
77
+ /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
78
+ viewLink({ control, minutes }?: {
79
+ control?: boolean;
80
+ minutes?: number;
81
+ }): Promise<ViewLink>;
82
+ /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
83
+ token({ minutes }?: {
84
+ minutes?: number;
85
+ }): Promise<SessionToken>;
86
+ /** Revokes every token and link of this phone made so far; the phone runs on. The account's key only. */
87
+ revokeTokens(): Promise<{
88
+ revoked_at: string;
89
+ }>;
90
+ /** The phone's replay: recording, saving after its stop, then ready with its video, its calls and a link. */
91
+ replay(): Promise<{
92
+ state: "recording" | "saving" | "ready" | "none";
93
+ link: string;
94
+ video_url?: string;
95
+ log_url?: string;
96
+ urls_expire_at?: string;
97
+ started_at?: string;
98
+ seconds?: number;
99
+ [field: string]: unknown;
100
+ }>;
101
+ /** Saves the phone's apps, their data, its keychain and permissions under name, for the account (and the label). */
102
+ saveState(name: string, { idempotencyKey, timeoutMs }?: OperationOptions): Promise<{
103
+ state: "done";
104
+ bytes?: number;
105
+ ms?: number;
106
+ device?: string;
107
+ [field: string]: unknown;
108
+ }>;
109
+ /** Puts a saved state back, onto a phone of the same model and iOS. */
110
+ restoreState(name: string, { idempotencyKey, timeoutMs }?: OperationOptions): Promise<{
111
+ state: "done";
112
+ bytes?: number;
113
+ ms?: number;
114
+ device?: string;
115
+ [field: string]: unknown;
116
+ }>;
117
+ /** The saved states, one per name (its newest save). */
118
+ listStates(): Promise<Array<{
119
+ name: string;
120
+ device: string | null;
121
+ bytes: number | null;
122
+ saved_at: string;
123
+ }>>;
124
+ deleteState(name: string): Promise<{
125
+ state: "done";
126
+ [field: string]: unknown;
127
+ }>;
128
+ /** More time (60 minutes by default, up to 8 hours in all), its spend cap with it; the account's key only. A repeat adds more. */
129
+ extend({ minutes }?: {
130
+ minutes?: number;
131
+ }): Promise<this>;
132
+ /** Stops the phone: its apps and data go, its workspace stays for the next phone, its replay is saved. */
133
+ stop(): Promise<this>;
134
+ }
package/dist/phone.js ADDED
@@ -0,0 +1,196 @@
1
+ import { NoMacError, requestKey } from "./errors.js";
2
+ import { asBytes, hex, sleep } from "./http.js";
3
+ const SESSIONS = "/api/v1/simulator/sessions";
4
+ const ENDED = new Set(["stopping", "stopped", "failed"]);
5
+ const JOB = /Next: job_status \{job_id: "([^"]+)"\}/;
6
+ // job_status's answer while the job still runs (simulator-use's tools/jobs.ts): read it again with the same job.
7
+ const STILL_RUNNING = /\nNext: job_status again, or job_cancel\./;
8
+ /** The account's phones (iPhone and iPad Simulators): start one (for one of your users with a label), read one, list them. */
9
+ export class Phones {
10
+ #http;
11
+ constructor(http) {
12
+ this.#http = http;
13
+ }
14
+ /**
15
+ * Starts a phone and answers it at once, usually queued: phone.waitUntilReady() follows it (a phone from the pool is ready
16
+ * in seconds). With reuse and a label, the user's live phone is the answer (phone.reused). The same idempotencyKey retries.
17
+ */
18
+ async start(options = {}, { idempotencyKey = requestKey("start") } = {}) {
19
+ const answer = await this.#http.request("POST", SESSIONS, { body: options, idempotencyKey });
20
+ return new Phone(this.#http, answer.session, answer.links, Boolean(answer.reused));
21
+ }
22
+ /** The account's phones, newest first; with label, one user's. */
23
+ async list({ label } = {}) {
24
+ const answer = await this.#http.request("GET", `${SESSIONS}${label ? `?label=${encodeURIComponent(label)}` : ""}`);
25
+ return answer.sessions.map(session => new Phone(this.#http, session));
26
+ }
27
+ /** A phone by its id, read. */
28
+ async get(id) {
29
+ return new Phone(this.#http, { id }).refresh();
30
+ }
31
+ }
32
+ /** A phone: its session (state, device, label, cost, deadlines) and links, and what can be done with it. */
33
+ export class Phone {
34
+ #http;
35
+ id;
36
+ session;
37
+ links;
38
+ /** Whether a start with reuse answered this live phone instead of a new one. */
39
+ reused;
40
+ /** As of the last refresh(): set in the phone's last 15 minutes before a limit or the credit's end. */
41
+ stopNotice = null;
42
+ /** As of stop() or the last refresh(): the MP4 of a screen_record the phone's stop ended. */
43
+ recording = null;
44
+ constructor(http, session, links, reused = false) {
45
+ this.#http = http;
46
+ this.id = session.id;
47
+ this.session = session;
48
+ this.links = links;
49
+ this.reused = reused;
50
+ }
51
+ get state() {
52
+ return this.session.state;
53
+ }
54
+ #path(rest = "") {
55
+ return `${SESSIONS}/${encodeURIComponent(this.id)}${rest}`;
56
+ }
57
+ /** Reads the phone again. */
58
+ async refresh() {
59
+ const answer = await this.#http.request("GET", this.#path());
60
+ this.session = answer.session;
61
+ this.links = answer.links ?? this.links;
62
+ this.stopNotice = answer.stop_notice ?? null;
63
+ this.recording = answer.recording ?? null;
64
+ return this;
65
+ }
66
+ /** Waits until the phone is ready (a phone from the pool takes seconds; a queued one up to 5 minutes). */
67
+ async waitUntilReady({ timeoutMs = 6 * 60_000, intervalMs = 1_000 } = {}) {
68
+ const by = Date.now() + timeoutMs;
69
+ for (;;) {
70
+ if (this.state === "ready")
71
+ return this;
72
+ if (ENDED.has(this.state))
73
+ throw new NoMacError("phone_ended", `The phone ended before it was ready (${this.session.failure_code ?? this.state}).`, 0, this.session);
74
+ if (Date.now() >= by)
75
+ throw new NoMacError("timeout", `The phone was not ready within ${Math.round(timeoutMs / 1000)} s (${this.state}).`, 0, this.session);
76
+ await sleep(intervalMs);
77
+ await this.refresh();
78
+ }
79
+ }
80
+ /**
81
+ * Runs one of the phone's tools (ui_look, ui_act, app_run, tests_run, app_control, ...) and waits for its result: {text,
82
+ * content, isError, raw}. A long build that hands back a job is followed with job_status until it ends, unless waitForJobs is false.
83
+ */
84
+ async tool(name, args = {}, { idempotencyKey = requestKey(name), intervalMs = 1_000, timeoutMs = 60 * 60_000, waitForJobs = true } = {}) {
85
+ const by = Date.now() + timeoutMs;
86
+ let result = await this.#call(name, args, idempotencyKey, by, intervalMs);
87
+ const job = waitForJobs && !result.isError ? JOB.exec(result.text)?.[1] : undefined;
88
+ // Each job_status waits up to 40 s for the job; one still running answers "job_status again".
89
+ // Followed until it ends or timeoutMs is spent: a running build is never answered as if it had finished.
90
+ for (let rounds = 0; job; rounds++) {
91
+ result = await this.#call("job_status", { job_id: job }, requestKey("job_status"), by, intervalMs);
92
+ if (result.isError || !STILL_RUNNING.test(result.text))
93
+ break;
94
+ if (Date.now() >= by || rounds >= 10_000)
95
+ throw new NoMacError("timeout", `${name}'s job ${job} was still running; read it later with phone.tool("job_status", { job_id: "${job}" }).`, 0, result.raw);
96
+ }
97
+ return result;
98
+ }
99
+ async #call(name, args, idempotencyKey, by, intervalMs) {
100
+ let answer = await this.#http.request("POST", this.#path(`/tools/${encodeURIComponent(name)}`), { body: args, idempotencyKey });
101
+ while (answer.state === "running" && typeof answer.id === "string") {
102
+ if (Date.now() >= by)
103
+ throw new NoMacError("timeout", `${name} was still running; cancel it with phone.cancel("${answer.id}") or read it later.`, 0, answer);
104
+ await sleep(intervalMs);
105
+ answer = await this.#http.request("GET", this.#path(`/calls/${answer.id}`));
106
+ }
107
+ if (answer.state === "cancelled")
108
+ return { text: `${name} was cancelled.`, content: [], isError: true, notices: [], stopNotice: answer.stop_notice ?? null, raw: answer };
109
+ if (!answer.result)
110
+ throw new NoMacError(answer.error ?? "tool_failed", `${name} failed on the phone: ${answer.message ?? answer.error ?? answer.state}.`, 0, answer);
111
+ const content = answer.result.content ?? [];
112
+ const text = content.filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n");
113
+ return { text, content, isError: Boolean(answer.result.isError), notices: Array.isArray(answer.notices) ? answer.notices : [], stopNotice: answer.stop_notice ?? null, raw: answer };
114
+ }
115
+ /** Stops a running tool call; a finished one is answered as it is. */
116
+ async cancel(callId) {
117
+ return this.#http.request("POST", this.#path(`/calls/${encodeURIComponent(callId)}/cancel`));
118
+ }
119
+ // An operation the phone runs for a while (a fetch, a save): the same request with the same key reads it until done.
120
+ async #operation(path, body, idempotencyKey, timeoutMs = 30 * 60_000, intervalMs = 1_000) {
121
+ const by = Date.now() + timeoutMs;
122
+ for (;;) {
123
+ const answer = await this.#http.request("POST", this.#path(path), { body, idempotencyKey });
124
+ if (answer.state === "running") {
125
+ if (Date.now() >= by)
126
+ throw new NoMacError("timeout", `The phone was still at it after ${Math.round(timeoutMs / 60_000)} minutes; the same call with idempotencyKey ${idempotencyKey} reads it later.`, 0, answer);
127
+ await sleep(intervalMs);
128
+ continue;
129
+ }
130
+ if (answer.state === "failed")
131
+ throw new NoMacError(answer.error ?? "operation_failed", answer.message ?? `The phone could not do it (${answer.error ?? "failed"}).`, 0, answer);
132
+ return answer;
133
+ }
134
+ }
135
+ /**
136
+ * A git repository into the phone's workspace: {url, ref?, token? | secret?}. A private repository's token is token itself
137
+ * (used for this fetch, kept nowhere) or secret, the account's secret holding it. Answers {root, commit}: root is the path
138
+ * app_run and tests_run take.
139
+ */
140
+ async fetchGit({ url, ref, token, secret }, { idempotencyKey = requestKey("git"), timeoutMs } = {}) {
141
+ return this.#operation("/sync/git", { url, ...(ref ? { ref } : {}), ...(token ? { token } : {}), ...(secret ? { secret } : {}) }, idempotencyKey, timeoutMs);
142
+ }
143
+ /** An archive (.tar.gz or .zip of a project, or of a Simulator .app) into the workspace under name, up to 2 GiB. Answers {root, app?}. */
144
+ async uploadArchive(data, { name, idempotencyKey = requestKey("upload"), timeoutMs } = {}) {
145
+ const bytes = await asBytes(data);
146
+ const sha256 = hex(await crypto.subtle.digest("SHA-256", bytes));
147
+ const link = await this.#http.request("POST", this.#path("/sync/upload"), { body: { size: bytes.byteLength, sha256 } });
148
+ await this.#http.upload(link.upload_url, bytes);
149
+ return this.#operation("/sync/fetch", { sha256, ...(name ? { name } : {}) }, idempotencyKey, timeoutMs);
150
+ }
151
+ /** A link to the phone's live view for a person, no sign-in: watch only, or control: true. */
152
+ async viewLink({ control = false, minutes } = {}) {
153
+ return this.#http.request("POST", this.#path("/view"), { body: { control, ...(minutes ? { minutes } : {}) } });
154
+ }
155
+ /** A token for this phone only, for your user or their agent: new NoMac({ token }).phone(id). 2 hours by default, a day at most. */
156
+ async token({ minutes } = {}) {
157
+ return this.#http.request("POST", this.#path("/token"), { body: minutes ? { minutes } : {} });
158
+ }
159
+ /** Revokes every token and link of this phone made so far; the phone runs on. The account's key only. */
160
+ async revokeTokens() {
161
+ return this.#http.request("DELETE", this.#path("/token"));
162
+ }
163
+ /** The phone's replay: recording, saving after its stop, then ready with its video, its calls and a link. */
164
+ async replay() {
165
+ return this.#http.request("GET", this.#path("/replay"));
166
+ }
167
+ /** Saves the phone's apps, their data, its keychain and permissions under name, for the account (and the label). */
168
+ async saveState(name, { idempotencyKey = requestKey("state"), timeoutMs } = {}) {
169
+ return this.#operation("/state", { action: "save", name }, idempotencyKey, timeoutMs);
170
+ }
171
+ /** Puts a saved state back, onto a phone of the same model and iOS. */
172
+ async restoreState(name, { idempotencyKey = requestKey("state"), timeoutMs } = {}) {
173
+ return this.#operation("/state", { action: "restore", name }, idempotencyKey, timeoutMs);
174
+ }
175
+ /** The saved states, one per name (its newest save). */
176
+ async listStates() {
177
+ return (await this.#operation("/state", { action: "list" }, requestKey("state"))).states ?? [];
178
+ }
179
+ async deleteState(name) {
180
+ return this.#operation("/state", { action: "delete", name }, requestKey("state"));
181
+ }
182
+ /** More time (60 minutes by default, up to 8 hours in all), its spend cap with it; the account's key only. A repeat adds more. */
183
+ async extend({ minutes } = {}) {
184
+ const answer = await this.#http.request("POST", this.#path("/extend"), { body: minutes ? { minutes } : {} });
185
+ this.session = answer.session;
186
+ this.stopNotice = answer.stop_notice ?? null;
187
+ return this;
188
+ }
189
+ /** Stops the phone: its apps and data go, its workspace stays for the next phone, its replay is saved. */
190
+ async stop() {
191
+ const answer = await this.#http.request("DELETE", this.#path());
192
+ this.session = answer.session;
193
+ this.recording = answer.recording ?? null;
194
+ return this;
195
+ }
196
+ }