activitysmith-cli 1.18.1 → 1.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "activitysmith-cli",
3
- "version": "1.18.1",
3
+ "version": "1.20.0",
4
4
  "description": "Command-line interface for ActivitySmith. Send Push Notifications, start, update, and end Live Activities, and set App Icon Badge Counts from your terminal.",
5
5
  "keywords": [
6
6
  "activitysmith",
package/src/agent.js ADDED
@@ -0,0 +1,49 @@
1
+ // The coding agent running the CLI, read from the environment it sets for its shell commands.
2
+ // Requests send it as X-ActivitySmith-Agent, so Push Notifications and approvals show the agent's
3
+ // name and icon, such as "Claude Code needs your approval", instead of the CLI's own sign-in name.
4
+ // The API accepts only the ids below and ignores anything else.
5
+
6
+ // AI_AGENT is the shared convention ("claude-code_2-1-321_agent"); check it by prefix.
7
+ const AI_AGENT_PREFIXES = [
8
+ ["claude-code", "claude-code"],
9
+ ["codex", "codex"],
10
+ ["cursor", "cursor"],
11
+ ];
12
+
13
+ /** Environment variables this reads, so tests can clear them. */
14
+ export const AGENT_ENV_VARS = [
15
+ "AI_AGENT",
16
+ "CLAUDECODE",
17
+ "CLAUDE_CODE",
18
+ "CLAUDE_CODE_IS_COWORK",
19
+ "CODEX_THREAD_ID",
20
+ "CODEX_SANDBOX",
21
+ "CODEX_CI",
22
+ "CURSOR_AGENT",
23
+ "CURSOR_EXTENSION_HOST_ROLE",
24
+ "CURSOR_TRACE_ID",
25
+ ];
26
+
27
+ export function detectAgent(env = process.env) {
28
+ // Cowork runs Claude Code, so it is checked before AI_AGENT names Claude Code.
29
+ if ((env.CLAUDECODE || env.CLAUDE_CODE) && env.CLAUDE_CODE_IS_COWORK) return "claude-cowork";
30
+
31
+ const aiAgent = String(env.AI_AGENT ?? "").trim().toLowerCase();
32
+ const fromAiAgent = AI_AGENT_PREFIXES.find(([prefix]) => aiAgent.startsWith(prefix));
33
+ if (fromAiAgent) return fromAiAgent[1];
34
+
35
+ if (env.CLAUDECODE || env.CLAUDE_CODE) return "claude-code";
36
+ if (env.CODEX_THREAD_ID || env.CODEX_SANDBOX || env.CODEX_CI) return "codex";
37
+ if (env.CURSOR_AGENT || env.CURSOR_EXTENSION_HOST_ROLE === "agent-exec") return "cursor";
38
+ // Every terminal in Cursor sets this, so it comes last: Claude Code or Codex running inside
39
+ // Cursor's terminal is still that agent.
40
+ if (env.CURSOR_TRACE_ID) return "cursor";
41
+ return null;
42
+ }
43
+
44
+ export const AGENT_HEADER = "X-ActivitySmith-Agent";
45
+
46
+ export function agentHeaders(env = process.env) {
47
+ const agent = detectAgent(env);
48
+ return agent ? { [AGENT_HEADER]: agent } : {};
49
+ }
@@ -0,0 +1,206 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+
5
+ // Limits from the backend approval review contract (backend docs/approval-review.md).
6
+ export const APPROVAL_LIMITS = {
7
+ minOptions: 2,
8
+ maxOptions: 4,
9
+ optionLabel: 80,
10
+ maxChangedFiles: 200,
11
+ changedFilePath: 500,
12
+ maxLinks: 5,
13
+ linkTitle: 120,
14
+ linkUrl: 2000,
15
+ maxScreenshots: 5,
16
+ screenshotTitle: 60,
17
+ screenshotBytes: 2 * 1024 * 1024,
18
+ };
19
+
20
+ const OPTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
21
+ const DEFAULT_OPTION_IDS = ["a", "b", "c", "d"];
22
+
23
+ // --option "left=Keep the left layout" or --option "Keep the left layout" (ID a, b, c, d by position).
24
+ export const parseOptionArgument = (value) => {
25
+ const separator = value.indexOf("=");
26
+ const id = separator > 0 ? value.slice(0, separator).trim() : "";
27
+ if (separator > 0 && OPTION_ID_PATTERN.test(id)) {
28
+ return { id, label: value.slice(separator + 1).trim() };
29
+ }
30
+ return { id: null, label: value.trim() };
31
+ };
32
+
33
+ export const buildApprovalOptions = (entries, { recommended, screenshots = {} } = {}) => {
34
+ if (entries.length === 0) {
35
+ if (recommended) throw new Error("--recommended needs --option.");
36
+ if (Object.keys(screenshots).length > 0) throw new Error("--option-screenshot needs --option.");
37
+ return undefined;
38
+ }
39
+ if (entries.length < APPROVAL_LIMITS.minOptions || entries.length > APPROVAL_LIMITS.maxOptions) {
40
+ throw new Error(`Give 2 to 4 --option values, not ${entries.length}.`);
41
+ }
42
+ const options = entries.map((entry, index) => ({ id: entry.id ?? DEFAULT_OPTION_IDS[index], label: entry.label }));
43
+ const ids = new Set();
44
+ for (const option of options) {
45
+ if (!option.label) throw new Error(`Option ${option.id} needs a label.`);
46
+ if (option.label.length > APPROVAL_LIMITS.optionLabel) {
47
+ throw new Error(`Option ${option.id} label is longer than ${APPROVAL_LIMITS.optionLabel} characters.`);
48
+ }
49
+ if (ids.has(option.id)) throw new Error(`Option ID ${option.id} is used twice.`);
50
+ ids.add(option.id);
51
+ }
52
+ if (recommended && !ids.has(recommended)) {
53
+ throw new Error(`--recommended ${recommended} is not one of the option IDs: ${[...ids].join(", ")}.`);
54
+ }
55
+ for (const id of Object.keys(screenshots)) {
56
+ if (!ids.has(id)) throw new Error(`--option-screenshot ${id} is not one of the option IDs: ${[...ids].join(", ")}.`);
57
+ }
58
+ return options.map((option) => (option.id === recommended ? { ...option, recommended: true } : option));
59
+ };
60
+
61
+ // --option-screenshot "left=shots/left.png"
62
+ export const parseOptionScreenshotArgument = (value) => {
63
+ const separator = value.indexOf("=");
64
+ const id = separator > 0 ? value.slice(0, separator).trim() : "";
65
+ const path = separator > 0 ? value.slice(separator + 1).trim() : "";
66
+ if (!id || !path) throw new Error("--option-screenshot must be <option-id>=<file>.");
67
+ return { id, path };
68
+ };
69
+
70
+ // --screenshot "shots/after.png" or --screenshot "shots/after.png=New settings page"
71
+ export const parseScreenshotArgument = (value) => {
72
+ const separator = value.indexOf("=");
73
+ const path = (separator > 0 ? value.slice(0, separator) : value).trim();
74
+ const title = separator > 0 ? value.slice(separator + 1).trim() : "";
75
+ if (!path) throw new Error("--screenshot needs a file path.");
76
+ if (title.length > APPROVAL_LIMITS.screenshotTitle) {
77
+ throw new Error(`Screenshot title "${title}" is longer than ${APPROVAL_LIMITS.screenshotTitle} characters.`);
78
+ }
79
+ return { path, ...(title ? { title } : {}) };
80
+ };
81
+
82
+ // --change "src/app.ts:12:3" (path, lines added, lines removed). Paths may contain colons.
83
+ export const parseChangeArgument = (value) => {
84
+ const match = /^(.+):(\d+):(\d+)$/.exec(value.trim());
85
+ if (!match || !match[1].trim()) throw new Error(`--change must be <path>:<added>:<removed>, such as src/app.ts:12:3. Got "${value}".`);
86
+ return { path: match[1].trim(), added: Number(match[2]), removed: Number(match[3]) };
87
+ };
88
+
89
+ // --link "Pull request=https://github.com/acme/app/pull/42" or --link "https://...".
90
+ export const parseLinkArgument = (value) => {
91
+ const trimmed = value.trim();
92
+ const separator = trimmed.indexOf("=https://");
93
+ const title = separator > 0 ? trimmed.slice(0, separator).trim() : "";
94
+ const url = separator > 0 ? trimmed.slice(separator + 1).trim() : trimmed;
95
+ let parsed;
96
+ try {
97
+ parsed = new URL(url);
98
+ } catch {
99
+ throw new Error(`--link must be <title>=<https URL> or an https URL. Got "${value}".`);
100
+ }
101
+ if (parsed.protocol !== "https:") throw new Error(`Links must use https. Got "${url}".`);
102
+ if (url.length > APPROVAL_LIMITS.linkUrl) throw new Error(`Link URL is longer than ${APPROVAL_LIMITS.linkUrl} characters.`);
103
+ if (title.length > APPROVAL_LIMITS.linkTitle) throw new Error(`Link title is longer than ${APPROVAL_LIMITS.linkTitle} characters.`);
104
+ return { title: title || url.slice(0, APPROVAL_LIMITS.linkTitle), url };
105
+ };
106
+
107
+ // Parses `git diff --numstat -z --no-renames`. Binary files report "-" and count as 0 lines.
108
+ export const parseGitNumstat = (output) =>
109
+ output
110
+ .split("\0")
111
+ .filter(Boolean)
112
+ .map((record) => {
113
+ const [added, removed, ...pathParts] = record.split("\t");
114
+ return {
115
+ path: pathParts.join("\t").replace(/^\n+/, ""),
116
+ added: Number.parseInt(added, 10) || 0,
117
+ removed: Number.parseInt(removed, 10) || 0,
118
+ };
119
+ })
120
+ .filter((file) => file.path);
121
+
122
+ const execFileAsync = promisify(execFile);
123
+
124
+ // File changes from git: the uncommitted changes against HEAD, or a range such as main...HEAD.
125
+ export const readGitChanges = async (range, { cwd = process.cwd() } = {}) => {
126
+ const args = ["diff", "--numstat", "-z", "--no-renames", typeof range === "string" && range ? range : "HEAD"];
127
+ try {
128
+ const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: 16 * 1024 * 1024 });
129
+ return parseGitNumstat(stdout);
130
+ } catch (error) {
131
+ const reason = String(error.stderr || error.message || "").trim().split("\n")[0];
132
+ throw new Error(`Could not read changes with git ${args.join(" ")}: ${reason}`);
133
+ }
134
+ };
135
+
136
+ // Keeps the most changed files when there are more than the API accepts.
137
+ export const buildApprovalChanges = (files) => {
138
+ if (files.length === 0) return { changes: undefined, omitted: 0 };
139
+ for (const file of files) {
140
+ if (file.path.length > APPROVAL_LIMITS.changedFilePath) {
141
+ throw new Error(`Changed file path is longer than ${APPROVAL_LIMITS.changedFilePath} characters: ${file.path.slice(0, 80)}...`);
142
+ }
143
+ }
144
+ const kept =
145
+ files.length > APPROVAL_LIMITS.maxChangedFiles
146
+ ? [...files].sort((a, b) => b.added + b.removed - (a.added + a.removed)).slice(0, APPROVAL_LIMITS.maxChangedFiles)
147
+ : files;
148
+ return { changes: { files: kept }, omitted: files.length - kept.length };
149
+ };
150
+
151
+ // Reads the type from the file signature, as the API does, so a renamed file fails before upload.
152
+ export const detectImageType = (data) => {
153
+ if (data.length > 8 && data[0] === 0x89 && data.subarray(1, 4).toString("ascii") === "PNG") return "image/png";
154
+ if (data.length > 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return "image/jpeg";
155
+ if (data.length > 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") {
156
+ return "image/webp";
157
+ }
158
+ return null;
159
+ };
160
+
161
+ export const readScreenshotFile = async (path) => {
162
+ let data;
163
+ try {
164
+ data = await readFile(path);
165
+ } catch (error) {
166
+ throw new Error(`Could not read screenshot ${path}: ${error.code === "ENOENT" ? "no such file" : error.message}`);
167
+ }
168
+ const contentType = detectImageType(data);
169
+ if (!contentType) throw new Error(`Screenshot ${path} is not a PNG, JPEG, or WebP image.`);
170
+ if (data.length > APPROVAL_LIMITS.screenshotBytes) {
171
+ throw new Error(`Screenshot ${path} is ${(data.length / 1024 / 1024).toFixed(1)} MB. The limit is 2 MB.`);
172
+ }
173
+ return { data, contentType };
174
+ };
175
+
176
+ // One line for each final status. Exit codes are in APPROVAL_EXIT in cli.js.
177
+ export const approvalResultLines = (approval) => {
178
+ switch (approval?.status) {
179
+ case "approved":
180
+ return ["Approved."];
181
+ case "rejected":
182
+ return ["Rejected. Do not continue with the action."];
183
+ case "replied":
184
+ return [
185
+ "Replied. Read the reply and follow it. Do not run the original action unless the reply says to.",
186
+ "Reply:",
187
+ approval.reply ?? "",
188
+ ];
189
+ case "chosen": {
190
+ const option = approval.selected_option ?? approval.options?.find((item) => item.id === approval.selected_option_id);
191
+ return [
192
+ `Chosen: ${option?.label ?? approval.selected_option_id}`,
193
+ `Option ID: ${approval.selected_option_id}`,
194
+ "Do the chosen option.",
195
+ ];
196
+ }
197
+ case "timed_out":
198
+ return ["Timed out. No decision within 30 minutes. Do not continue with the action."];
199
+ case "cancelled":
200
+ return ["Cancelled. Do not continue with the action."];
201
+ case "pending":
202
+ return ["Pending."];
203
+ default:
204
+ return [`Status: ${approval?.status}`];
205
+ }
206
+ };
package/src/cli.js CHANGED
@@ -1,7 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { Command, InvalidArgumentError, Option } from "commander";
4
+ import { agentHeaders } from "./agent.js";
4
5
  import { loadMetadata } from "./metadata.js";
6
+ import {
7
+ APPROVAL_LIMITS,
8
+ approvalResultLines,
9
+ buildApprovalChanges,
10
+ buildApprovalOptions,
11
+ parseChangeArgument,
12
+ parseLinkArgument,
13
+ parseOptionArgument,
14
+ parseOptionScreenshotArgument,
15
+ parseScreenshotArgument,
16
+ readGitChanges,
17
+ readScreenshotFile,
18
+ } from "./approvals.js";
5
19
  import {
6
20
  API_KEYS_SCOPE,
7
21
  DEFAULT_API_RESOURCE,
@@ -285,6 +299,12 @@ const credentialSource = (options) => {
285
299
  return readCredentials() ? "auth login" : null;
286
300
  };
287
301
 
302
+ // Names the coding agent running the CLI, so its Push Notifications show that agent's icon.
303
+ const agentRequestInit = () => {
304
+ const headers = agentHeaders();
305
+ return Object.keys(headers).length > 0 ? { headers } : undefined;
306
+ };
307
+
288
308
  const createClient = (apiKey) =>
289
309
  new ActivitySmith({
290
310
  apiKey,
@@ -1373,10 +1393,10 @@ const pushCommand = program
1373
1393
 
1374
1394
  const isReplacement = options.replace !== undefined;
1375
1395
  const response = isReplacement
1376
- ? await client.notifications.replace(options.replace.trim(), pushNotificationRequest)
1396
+ ? await client.notifications.replace(options.replace.trim(), pushNotificationRequest, agentRequestInit())
1377
1397
  : await client.notifications.sendPushNotification({
1378
1398
  pushNotificationRequest,
1379
- });
1399
+ }, agentRequestInit());
1380
1400
  const devicesNotified = response?.devices_notified ?? response?.devicesNotified;
1381
1401
  const notificationId = response?.notification_id ?? response?.notificationId;
1382
1402
 
@@ -1783,16 +1803,18 @@ const APP_STORE_URL = "https://apps.apple.com/us/app/activitysmith/id6752254835"
1783
1803
 
1784
1804
  // Account endpoints the generated SDK does not cover. Same API and SDK header as the SDK client, so
1785
1805
  // errors print the same way and usage shows the CLI version.
1786
- const apiRequest = async (path, { token, method = "GET", body } = {}) => {
1806
+ // `rawBody` with `contentType` sends bytes as they are, such as a screenshot upload.
1807
+ const apiRequest = async (path, { token, method = "GET", body, rawBody, contentType } = {}) => {
1787
1808
  const response = await fetch(`${DEFAULT_API_RESOURCE}${path}`, {
1788
1809
  method,
1789
1810
  headers: {
1790
1811
  Authorization: `Bearer ${token}`,
1791
1812
  Accept: "application/json",
1792
1813
  "X-ActivitySmith-SDK": `cli-v${version}`,
1793
- ...(body ? { "Content-Type": "application/json" } : {}),
1814
+ ...agentHeaders(),
1815
+ ...(rawBody ? { "Content-Type": contentType } : body ? { "Content-Type": "application/json" } : {}),
1794
1816
  },
1795
- ...(body ? { body: JSON.stringify(body) } : {}),
1817
+ ...(rawBody ? { body: rawBody } : body ? { body: JSON.stringify(body) } : {}),
1796
1818
  });
1797
1819
  if (!response.ok) {
1798
1820
  const error = new Error(`Request failed with status ${response.status}`);
@@ -1905,12 +1927,19 @@ keysCommand
1905
1927
  });
1906
1928
 
1907
1929
  // Approvals. Agents ask the user for approval before an action the user wants to approve, such as
1908
- // sending an email or deploying, and go ahead only when this exits 0.
1930
+ // sending an email or deploying, and go ahead only when this exits 0. The request is a Push
1931
+ // Notification that opens a review screen in the iOS app (backend docs/approval-review.md).
1909
1932
  const APPROVAL_SCOPE_TYPES = ["working_directory", "repository", "project", "environment", "customer", "account", "resource"];
1910
- const APPROVAL_COLORS = ["lime", "green", "cyan", "blue", "purple", "magenta", "red", "orange", "yellow", "gray"];
1911
1933
  // Each request waits at most this long on the server, then the CLI asks again.
1912
1934
  const APPROVAL_POLL_SECONDS = 45;
1913
- const APPROVAL_EXIT = { approved: 0, not_approved: 1, error: 2, pending: 3 };
1935
+ const APPROVAL_EXIT = { approved: 0, not_approved: 1, error: 2, pending: 3, replied: 4, chosen: 5 };
1936
+ // Approvals are always Push Notifications now. The API ignores these, so old scripts keep working.
1937
+ const DEPRECATED_APPROVAL_FLAGS = [
1938
+ ["delivery", "--delivery"],
1939
+ ["color", "--color"],
1940
+ ["icon", "--icon"],
1941
+ ["badge", "--badge"],
1942
+ ];
1914
1943
 
1915
1944
  const parseApprovalScope = (value) => {
1916
1945
  const separator = value.indexOf(":");
@@ -1924,13 +1953,6 @@ const parseApprovalScope = (value) => {
1924
1953
  return { type, value: scopeValue };
1925
1954
  };
1926
1955
 
1927
- const parseApprovalColor = (value) => {
1928
- if (!APPROVAL_COLORS.includes(value)) {
1929
- throw new InvalidArgumentError(`color must be one of ${APPROVAL_COLORS.join(", ")}`);
1930
- }
1931
- return value;
1932
- };
1933
-
1934
1956
  const parsePositiveSeconds = (value) => {
1935
1957
  const parsed = Number(value);
1936
1958
  if (!Number.isInteger(parsed) || parsed < 1) {
@@ -1939,11 +1961,20 @@ const parsePositiveSeconds = (value) => {
1939
1961
  return parsed;
1940
1962
  };
1941
1963
 
1942
- const APPROVAL_RESULT_LINES = {
1943
- approved: "Approved.",
1944
- rejected: "Rejected. Do not continue with the action.",
1945
- timed_out: "Timed out. No decision within 30 minutes. Do not continue with the action.",
1946
- cancelled: "Cancelled. Do not continue with the action.",
1964
+ // Wraps a parser for a repeatable option so commander reports its errors as invalid arguments.
1965
+ const repeatable = (parse) => (value, previous = []) => {
1966
+ try {
1967
+ return [...previous, parse(value)];
1968
+ } catch (error) {
1969
+ throw new InvalidArgumentError(error.message);
1970
+ }
1971
+ };
1972
+
1973
+ const APPROVAL_EXIT_BY_STATUS = {
1974
+ approved: APPROVAL_EXIT.approved,
1975
+ replied: APPROVAL_EXIT.replied,
1976
+ chosen: APPROVAL_EXIT.chosen,
1977
+ pending: APPROVAL_EXIT.pending,
1947
1978
  };
1948
1979
 
1949
1980
  // Waits until the approval is decided, or until `timeoutSeconds` pass, then prints the result and exits.
@@ -1968,28 +1999,67 @@ const waitForApproval = async (approvalId, token, timeoutSeconds, globalOptions)
1968
1999
  ]);
1969
2000
  process.exit(APPROVAL_EXIT.pending);
1970
2001
  }
1971
- outputResult(result, globalOptions, [APPROVAL_RESULT_LINES[status] ?? `Status: ${status}`]);
1972
- process.exit(status === "approved" ? APPROVAL_EXIT.approved : APPROVAL_EXIT.not_approved);
2002
+ outputResult(result, globalOptions, approvalResultLines(result.approval));
2003
+ process.exit(APPROVAL_EXIT_BY_STATUS[status] ?? APPROVAL_EXIT.not_approved);
2004
+ };
2005
+
2006
+ // Uploads each screenshot file once, even when --screenshot and --option-screenshot name the same file.
2007
+ const uploadApprovalScreenshots = async (screenshotArgs, optionScreenshotArgs, token, globalOptions) => {
2008
+ const entries = [...screenshotArgs];
2009
+ for (const { path } of optionScreenshotArgs) {
2010
+ if (!entries.some((entry) => entry.path === path)) entries.push({ path });
2011
+ }
2012
+ if (entries.length > APPROVAL_LIMITS.maxScreenshots) {
2013
+ throw new Error(`An approval can show at most ${APPROVAL_LIMITS.maxScreenshots} screenshots, not ${entries.length}.`);
2014
+ }
2015
+ const files = await Promise.all(entries.map((entry) => readScreenshotFile(entry.path)));
2016
+
2017
+ const idByPath = new Map();
2018
+ const screenshots = [];
2019
+ for (const [index, entry] of entries.entries()) {
2020
+ if (!globalOptions.json) console.error(`Uploading screenshot ${entry.path}`);
2021
+ const result = await apiRequest("/approvals/screenshots", {
2022
+ token,
2023
+ method: "POST",
2024
+ rawBody: files[index].data,
2025
+ contentType: files[index].contentType,
2026
+ });
2027
+ const id = result.screenshot?.id;
2028
+ if (!id) throw new Error(`The API did not return a screenshot ID for ${entry.path}. Run the command again.`);
2029
+ idByPath.set(entry.path, id);
2030
+ screenshots.push({ id, ...(entry.title ? { title: entry.title } : {}) });
2031
+ }
2032
+ const screenshotIdByOption = Object.fromEntries(optionScreenshotArgs.map(({ id, path }) => [id, idByPath.get(path)]));
2033
+ return { screenshots, screenshotIdByOption };
1973
2034
  };
1974
2035
 
2036
+ // A mistyped flag is a failed request (exit 2), not a rejection (exit 1).
2037
+ const exitWithApprovalError = (error) => process.exit(error.exitCode === 0 ? 0 : APPROVAL_EXIT.error);
2038
+
1975
2039
  const approvalCommand = program
1976
2040
  .command("approval")
1977
2041
  .description("Let your agents ask for your approval on your iPhone before they act")
1978
2042
  .addHelpText(
1979
2043
  "after",
1980
2044
  `
2045
+ The request is a Push Notification. A tap opens a review screen where you approve, reject,
2046
+ choose an option, or reply with text.
2047
+
1981
2048
  Exit codes for request and wait:
1982
2049
  0 Approved. Continue with the action.
1983
2050
  1 Rejected, timed out, or cancelled. Do not continue.
1984
2051
  2 The request failed, for example no paired device.
1985
- 3 Still pending after --timeout or with --no-wait. Run approval wait with the approval ID.`
2052
+ 3 Still pending after --timeout or with --no-wait. Run approval wait with the approval ID.
2053
+ 4 Replied. The reply text follows "Reply:". Follow it instead of the original action.
2054
+ 5 Chosen. The chosen option follows "Chosen:" and "Option ID:". Do that option.`
1986
2055
  );
1987
2056
 
1988
2057
  approvalCommand
1989
2058
  .command("request")
1990
- .description("Send an approval request with two buttons to the iPhone and wait for the decision")
2059
+ .description("Send an approval request to the iPhone and wait for the decision")
2060
+ .exitOverride(exitWithApprovalError)
1991
2061
  .argument("<question>", 'The decision to make, such as "Send the pricing update email to 214 customers?"')
1992
- .option("--details <text>", "Short context that helps decide")
2062
+ .option("--details <text>", "Context that helps decide, up to 4,000 characters. Shown in full on the review screen")
1993
2063
  .option("--approve-label <label>", "Approve button title, a concrete verb such as Send or Deploy", "Approve")
1994
2064
  .option("--reject-label <label>", "Reject button title, such as Cancel or Don't Send", "Reject")
1995
2065
  .option("--command <command>", "The exact command waiting for approval. Do not shorten or rewrite it")
@@ -1999,35 +2069,78 @@ approvalCommand
1999
2069
  `Where the action applies, such as environment:production. Types: ${APPROVAL_SCOPE_TYPES.join(", ")} (default: working_directory:<current directory> with --command)`,
2000
2070
  parseApprovalScope
2001
2071
  )
2002
- .addOption(
2003
- new Option("--delivery <surface>", "Live Activity, Push Notification, or auto: a Live Activity with a Push Notification fallback")
2004
- .choices(["auto", "live_activity", "push_notification"])
2005
- .default("auto")
2072
+ .option(
2073
+ "--option <[id=]label>",
2074
+ "A choice instead of approve and reject. Repeat 2 to 4 times. IDs default to a, b, c, d",
2075
+ repeatable(parseOptionArgument)
2006
2076
  )
2007
- .option("--color <color>", "Live Activity color (default: blue)", parseApprovalColor)
2008
- .option("--icon <symbol>", "SF Symbol for the Live Activity (default: sparkles)")
2009
- .option("--badge <title>", "Short Live Activity badge such as Email or Deploy (default: Agent)")
2077
+ .option("--recommended <option-id>", "The option you would pick. At most one")
2078
+ .option(
2079
+ "--option-screenshot <option-id=file>",
2080
+ "A screenshot that shows one option. Repeatable",
2081
+ repeatable(parseOptionScreenshotArgument)
2082
+ )
2083
+ .option(
2084
+ "--screenshot <file[=title]>",
2085
+ "A PNG, JPEG, or WebP up to 2 MB to show on the review screen. Repeatable, 5 at most",
2086
+ repeatable(parseScreenshotArgument)
2087
+ )
2088
+ .option(
2089
+ "--git-changes [range]",
2090
+ "Show the changed files and line counts from git diff: uncommitted changes, or a range such as main...HEAD"
2091
+ )
2092
+ .option("--change <path:added:removed>", "A changed file and its line counts, such as src/app.ts:12:3. Repeatable", repeatable(parseChangeArgument))
2093
+ .option("--link <[title=]url>", "An https link to open from the review screen, such as a pull request. Repeatable, 5 at most", repeatable(parseLinkArgument))
2010
2094
  .option("--channels <slugs>", "Comma-separated channel slugs. Omit to ask on every paired device")
2011
2095
  .option("--timeout <seconds>", "Stop waiting after this many seconds and exit 3 if still pending", parsePositiveSeconds)
2012
2096
  .option("--no-wait", "Send the request, print the approval ID, and exit without waiting")
2097
+ .option("--delivery <surface>", "Deprecated and ignored. Approvals are always Push Notifications")
2098
+ .option("--color <color>", "Deprecated and ignored")
2099
+ .option("--icon <symbol>", "Deprecated and ignored")
2100
+ .option("--badge <title>", "Deprecated and ignored")
2013
2101
  .action(async (question, options) => {
2014
2102
  const globalOptions = program.opts();
2015
2103
 
2016
2104
  try {
2017
- const token = await requireApiKey(globalOptions);
2105
+ const ignored = DEPRECATED_APPROVAL_FLAGS.filter(([key]) => options[key] !== undefined).map(([, flag]) => flag);
2106
+ if (ignored.length > 0 && !globalOptions.json) {
2107
+ console.error(`Ignoring ${ignored.join(", ")}: approvals are always Push Notifications.`);
2108
+ }
2109
+
2018
2110
  const tool = options.tool ?? (options.command ? "shell" : undefined);
2019
- if (options.command && !tool) throw new Error("Provide --tool with --command.");
2020
2111
  const scope = options.scope ?? (options.command ? { type: "working_directory", value: process.cwd() } : undefined);
2021
- const appearance = {
2022
- ...(options.color ? { color: options.color } : {}),
2023
- ...(options.icon ? { icon: { symbol: options.icon } } : {}),
2024
- ...(options.badge ? { badge: { title: options.badge } } : {}),
2025
- };
2112
+ const optionScreenshotArgs = options.optionScreenshot ?? [];
2113
+ const optionScreenshotPaths = Object.fromEntries(optionScreenshotArgs.map(({ id, path }) => [id, path]));
2114
+ // Validate everything before uploading or sending anything.
2115
+ const approvalOptions = buildApprovalOptions(options.option ?? [], {
2116
+ recommended: options.recommended,
2117
+ screenshots: optionScreenshotPaths,
2118
+ });
2119
+ const links = options.link ?? [];
2120
+ if (links.length > APPROVAL_LIMITS.maxLinks) {
2121
+ throw new Error(`An approval can show at most ${APPROVAL_LIMITS.maxLinks} links, not ${links.length}.`);
2122
+ }
2123
+ const changedFiles = [
2124
+ ...(options.gitChanges !== undefined ? await readGitChanges(options.gitChanges) : []),
2125
+ ...(options.change ?? []),
2126
+ ];
2127
+ const { changes, omitted } = buildApprovalChanges(changedFiles);
2128
+ if (omitted > 0 && !globalOptions.json) {
2129
+ console.error(`Showing the ${APPROVAL_LIMITS.maxChangedFiles} most changed files. ${omitted} more are left out.`);
2130
+ }
2026
2131
  const channels = String(options.channels ?? "")
2027
2132
  .split(",")
2028
2133
  .map((slug) => slug.trim())
2029
2134
  .filter(Boolean);
2030
2135
 
2136
+ const token = await requireApiKey(globalOptions);
2137
+ const { screenshots, screenshotIdByOption } = await uploadApprovalScreenshots(
2138
+ options.screenshot ?? [],
2139
+ optionScreenshotArgs,
2140
+ token,
2141
+ globalOptions
2142
+ );
2143
+
2031
2144
  const result = await apiRequest("/approvals", {
2032
2145
  token,
2033
2146
  method: "POST",
@@ -2036,10 +2149,18 @@ approvalCommand
2036
2149
  ...(options.details ? { details: options.details } : {}),
2037
2150
  ...(tool ? { execution_context: { tool, ...(options.command ? { command: options.command } : {}) } } : {}),
2038
2151
  ...(scope ? { scope } : {}),
2039
- delivery: options.delivery,
2152
+ ...(changes ? { changes } : {}),
2153
+ ...(links.length > 0 ? { links } : {}),
2154
+ ...(screenshots.length > 0 ? { screenshots } : {}),
2155
+ ...(approvalOptions
2156
+ ? {
2157
+ options: approvalOptions.map((option) =>
2158
+ screenshotIdByOption[option.id] ? { ...option, screenshot_id: screenshotIdByOption[option.id] } : option
2159
+ ),
2160
+ }
2161
+ : {}),
2040
2162
  approve_label: options.approveLabel,
2041
2163
  reject_label: options.rejectLabel,
2042
- ...(Object.keys(appearance).length > 0 ? { appearance } : {}),
2043
2164
  ...(channels.length > 0 ? { target_channel_slugs: channels } : {}),
2044
2165
  },
2045
2166
  });
@@ -2065,6 +2186,7 @@ approvalCommand
2065
2186
  approvalCommand
2066
2187
  .command("wait")
2067
2188
  .description("Wait for the decision on an approval request")
2189
+ .exitOverride(exitWithApprovalError)
2068
2190
  .argument("<approval-id>", "Approval ID from approval request")
2069
2191
  .option("--timeout <seconds>", "Stop waiting after this many seconds and exit 3 if still pending", parsePositiveSeconds)
2070
2192
  .action(async (approvalId, options) => {
@@ -2088,9 +2210,8 @@ approvalCommand
2088
2210
  try {
2089
2211
  const token = await requireApiKey(globalOptions);
2090
2212
  const result = await apiRequest(`/approvals/${encodeURIComponent(approvalId)}`, { token });
2091
- const status = result.approval?.status;
2092
2213
  outputResult(result, globalOptions, [
2093
- status === "pending" ? "Pending." : (APPROVAL_RESULT_LINES[status] ?? `Status: ${status}`),
2214
+ ...approvalResultLines(result.approval),
2094
2215
  `Approval ID: ${approvalId}`,
2095
2216
  result.approval?.question ? `Question: ${result.approval.question}` : null,
2096
2217
  ]);