activitysmith-cli 1.15.0 → 1.17.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/README.md +109 -1
- package/package.json +1 -1
- package/src/auth.js +8 -2
- package/src/cli.js +356 -6
package/README.md
CHANGED
|
@@ -25,11 +25,14 @@ For example, a Codex agent can work on your computer, send a Push Notification w
|
|
|
25
25
|
## Quickstart
|
|
26
26
|
|
|
27
27
|
1. Run `activitysmith auth login` and approve access in your browser.
|
|
28
|
-
2. Run `activitysmith
|
|
28
|
+
2. Run `activitysmith devices list` to check that your iPhone is paired.
|
|
29
|
+
3. Run `activitysmith --help` to inspect available commands.
|
|
29
30
|
|
|
30
31
|
```bash
|
|
31
32
|
activitysmith auth login
|
|
32
33
|
|
|
34
|
+
activitysmith devices list
|
|
35
|
+
|
|
33
36
|
activitysmith push --title "Hello"
|
|
34
37
|
```
|
|
35
38
|
|
|
@@ -86,6 +89,44 @@ Or pass the key directly:
|
|
|
86
89
|
activitysmith --api-key "YOUR-API-KEY" push --title "Hello"
|
|
87
90
|
```
|
|
88
91
|
|
|
92
|
+
### Create an API key from the CLI
|
|
93
|
+
|
|
94
|
+
Create an API key for CI, servers, and scripts without opening the web app. The command uses the browser sign-in. The first time, it opens your browser so you can approve API key access.
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
activitysmith keys create --name "GitHub Actions"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The key is shown only once. Add `--raw` to print only the key, then pipe it straight into a secret store. The key never appears in your terminal:
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
activitysmith keys create --name "GitHub Actions" --raw | gh secret set ACTIVITYSMITH_API_KEY
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Add `--channels` to limit the key to some Channels:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
activitysmith keys create --name "Ops alerts" --channels ops,alerts
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
An API key cannot create another key. This command always uses the browser sign-in, even when `ACTIVITYSMITH_API_KEY` is set.
|
|
113
|
+
|
|
114
|
+
## Paired Devices
|
|
115
|
+
|
|
116
|
+
List the iPhones and iPads paired to your account. Active devices come first:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
activitysmith devices list
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
If no device is paired, the command prints the App Store link. Install ActivitySmith on your iPhone, sign in with the same account, and allow notifications.
|
|
123
|
+
|
|
124
|
+
Add `--include-inactive` to also list devices that can no longer receive deliveries:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
activitysmith devices list --include-inactive
|
|
128
|
+
```
|
|
129
|
+
|
|
89
130
|
## Push Notifications
|
|
90
131
|
|
|
91
132
|
### Send a Push Notification
|
|
@@ -651,6 +692,73 @@ Pass `0` to clear the badge.
|
|
|
651
692
|
activitysmith badge 0
|
|
652
693
|
```
|
|
653
694
|
|
|
695
|
+
## Approvals
|
|
696
|
+
|
|
697
|
+

|
|
698
|
+
|
|
699
|
+
Let your agents ask for your approval before they act, such as sending an email to customers or deploying to production. The request reaches your iPhone as a Live Activity or an actionable Push Notification, both with two buttons. The agent waits until you tap one and continues only when you approve.
|
|
700
|
+
|
|
701
|
+
```bash
|
|
702
|
+
activitysmith approval request "Send the pricing update email to 214 customers?" \
|
|
703
|
+
--approve-label "Send" \
|
|
704
|
+
--reject-label "Don't Send"
|
|
705
|
+
```
|
|
706
|
+
|
|
707
|
+
When you approve, the command prints `Approved.` and exits with code `0`. The agent, or a script, runs the action only after that:
|
|
708
|
+
|
|
709
|
+
```bash
|
|
710
|
+
activitysmith approval request "Deploy to production?" --approve-label "Deploy" && ./deploy.sh
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
Exit codes for `approval request` and `approval wait`:
|
|
714
|
+
|
|
715
|
+
- `0`: Approved. Continue with the action.
|
|
716
|
+
- `1`: Rejected, timed out after 30 minutes, or cancelled. Do not continue.
|
|
717
|
+
- `2`: The request failed, for example because no device is paired.
|
|
718
|
+
- `3`: Still pending after `--timeout`, or sent with `--no-wait`.
|
|
719
|
+
|
|
720
|
+
### Show the exact command
|
|
721
|
+
|
|
722
|
+
Add `--command` with the exact command that waits for approval. The request shows the command and the current directory:
|
|
723
|
+
|
|
724
|
+
```bash
|
|
725
|
+
activitysmith approval request "Run the database migration?" \
|
|
726
|
+
--approve-label "Migrate" \
|
|
727
|
+
--command "npm run db:migrate -- --env production"
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
Add `--details` for short context. Add `--scope` to show where the action applies, such as `environment:production`.
|
|
731
|
+
|
|
732
|
+
### Wait in steps
|
|
733
|
+
|
|
734
|
+
Some agents stop shell commands after a few minutes. Add `--timeout` to stop waiting early. The command then prints the approval ID and exits with code `3`. Run `approval wait` to keep waiting:
|
|
735
|
+
|
|
736
|
+
```bash
|
|
737
|
+
activitysmith approval request "Publish the release notes?" --timeout 100
|
|
738
|
+
activitysmith approval wait apr_Xk3pQ8mV2nR7tL9w --timeout 100
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
### Check or cancel a request
|
|
742
|
+
|
|
743
|
+
```bash
|
|
744
|
+
activitysmith approval get apr_Xk3pQ8mV2nR7tL9w
|
|
745
|
+
activitysmith approval cancel apr_Xk3pQ8mV2nR7tL9w
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
Cancel a request when the action is no longer needed. Its buttons stop working, and a Live Activity updates to show the request was cancelled.
|
|
749
|
+
|
|
750
|
+
### Change how the request looks
|
|
751
|
+
|
|
752
|
+
By default, the request is a Live Activity, with an actionable Push Notification as the fallback. Add `--delivery push_notification` to always send a Push Notification, or `--delivery live_activity` to always send a Live Activity. Use `--badge`, `--color`, and `--icon` to change the Live Activity:
|
|
753
|
+
|
|
754
|
+
```bash
|
|
755
|
+
activitysmith approval request "Refund order #4821 for $129?" \
|
|
756
|
+
--approve-label "Refund" \
|
|
757
|
+
--badge "Billing" \
|
|
758
|
+
--color orange \
|
|
759
|
+
--icon creditcard
|
|
760
|
+
```
|
|
761
|
+
|
|
654
762
|
## Metadata
|
|
655
763
|
|
|
656
764
|
Metadata adds extra information to Push Notification and Live Activity details in ActivitySmith. It does not appear in the notification or Live Activity on your device.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "activitysmith-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.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/auth.js
CHANGED
|
@@ -16,6 +16,10 @@ export const CLIENT_NAME = "ActivitySmith CLI";
|
|
|
16
16
|
export const CLIENT_ID = "https://activitysmith.com/.well-known/oauth-client/activitysmith-cli.json";
|
|
17
17
|
// Sending Push Notifications, Live Activities, badges, and widget values. Nothing else.
|
|
18
18
|
export const LOGIN_SCOPES = "mcp:write";
|
|
19
|
+
// Asked for only by `activitysmith keys create`, which signs in again so the user approves it in the browser.
|
|
20
|
+
export const API_KEYS_SCOPE = "api_keys:write";
|
|
21
|
+
|
|
22
|
+
export const hasScope = (credentials, scope) => String(credentials?.scope ?? "").split(/\s+/).includes(scope);
|
|
19
23
|
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
20
24
|
// Refresh a little early so a token does not expire mid-request.
|
|
21
25
|
const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60 * 1000;
|
|
@@ -95,13 +99,13 @@ export const discoverOAuthServer = async ({ issuer, fetchImpl }) => {
|
|
|
95
99
|
return metadata;
|
|
96
100
|
};
|
|
97
101
|
|
|
98
|
-
export const buildAuthorizeUrl = ({ authorizationEndpoint, redirectUri, challenge, state, resource }) => {
|
|
102
|
+
export const buildAuthorizeUrl = ({ authorizationEndpoint, redirectUri, challenge, state, resource, scope = LOGIN_SCOPES }) => {
|
|
99
103
|
const url = new URL(authorizationEndpoint);
|
|
100
104
|
url.search = new URLSearchParams({
|
|
101
105
|
response_type: "code",
|
|
102
106
|
client_id: CLIENT_ID,
|
|
103
107
|
redirect_uri: redirectUri,
|
|
104
|
-
scope
|
|
108
|
+
scope,
|
|
105
109
|
state,
|
|
106
110
|
code_challenge: challenge,
|
|
107
111
|
code_challenge_method: "S256",
|
|
@@ -255,6 +259,7 @@ export const login = async ({
|
|
|
255
259
|
log = (line) => console.error(line),
|
|
256
260
|
now = Date.now,
|
|
257
261
|
timeoutMs = LOGIN_TIMEOUT_MS,
|
|
262
|
+
scope = LOGIN_SCOPES,
|
|
258
263
|
} = {}) => {
|
|
259
264
|
let previous = null;
|
|
260
265
|
try {
|
|
@@ -275,6 +280,7 @@ export const login = async ({
|
|
|
275
280
|
challenge,
|
|
276
281
|
state,
|
|
277
282
|
resource,
|
|
283
|
+
scope,
|
|
278
284
|
});
|
|
279
285
|
const opened = noBrowser ? false : await launchBrowser(authorizeUrl);
|
|
280
286
|
log(opened ? "Opened your browser to sign in to ActivitySmith." : "Open this URL in a browser to sign in to ActivitySmith:");
|
package/src/cli.js
CHANGED
|
@@ -2,7 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
import { Command, InvalidArgumentError, Option } from "commander";
|
|
4
4
|
import { loadMetadata } from "./metadata.js";
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
API_KEYS_SCOPE,
|
|
7
|
+
DEFAULT_API_RESOURCE,
|
|
8
|
+
LOGIN_SCOPES,
|
|
9
|
+
credentialsPath,
|
|
10
|
+
getAccessToken,
|
|
11
|
+
hasScope,
|
|
12
|
+
login,
|
|
13
|
+
logout,
|
|
14
|
+
readCredentials,
|
|
15
|
+
} from "./auth.js";
|
|
6
16
|
import ActivitySmith from "activitysmith";
|
|
7
17
|
import { createRequire } from "module";
|
|
8
18
|
import { readFile } from "fs/promises";
|
|
@@ -1211,7 +1221,7 @@ const buildErrorDetails = async (error) => {
|
|
|
1211
1221
|
// Set when a command authenticates with the browser sign-in rather than an API key.
|
|
1212
1222
|
let usingSignIn = false;
|
|
1213
1223
|
|
|
1214
|
-
const handleError = async (error, options) => {
|
|
1224
|
+
const handleError = async (error, options, exitCode = 1) => {
|
|
1215
1225
|
const details = await buildErrorDetails(error);
|
|
1216
1226
|
// Disconnecting the CLI in the web app rejects its token at once, before it expires.
|
|
1217
1227
|
if (usingSignIn && details.status === 401) {
|
|
@@ -1246,7 +1256,7 @@ const handleError = async (error, options) => {
|
|
|
1246
1256
|
}
|
|
1247
1257
|
}
|
|
1248
1258
|
|
|
1249
|
-
process.exit(
|
|
1259
|
+
process.exit(exitCode);
|
|
1250
1260
|
};
|
|
1251
1261
|
|
|
1252
1262
|
// Returns the API key, or a current access token from the saved sign-in. The REST API accepts
|
|
@@ -1429,9 +1439,7 @@ metricsCommand
|
|
|
1429
1439
|
.description("Update a widget metric value")
|
|
1430
1440
|
.argument("<metric-key>", "Metric key")
|
|
1431
1441
|
.argument("<value>", "Metric value")
|
|
1432
|
-
.
|
|
1433
|
-
.option("--metadata-file <path>", "Path to a Metadata JSON object file")
|
|
1434
|
-
.action(async (metricKey, rawValue) => {
|
|
1442
|
+
.action(async (metricKey, rawValue) => {
|
|
1435
1443
|
const globalOptions = program.opts();
|
|
1436
1444
|
|
|
1437
1445
|
try {
|
|
@@ -1702,6 +1710,348 @@ addLiveActivityActionOptions(addContentStateOptions(
|
|
|
1702
1710
|
{ includeAutoDismiss: true, includeAutoDismissSeconds: true }
|
|
1703
1711
|
));
|
|
1704
1712
|
|
|
1713
|
+
const APP_STORE_URL = "https://apps.apple.com/us/app/activitysmith/id6752254835";
|
|
1714
|
+
|
|
1715
|
+
// Account endpoints the generated SDK does not cover. Same API and SDK header as the SDK client, so
|
|
1716
|
+
// errors print the same way and usage shows the CLI version.
|
|
1717
|
+
const apiRequest = async (path, { token, method = "GET", body } = {}) => {
|
|
1718
|
+
const response = await fetch(`${DEFAULT_API_RESOURCE}${path}`, {
|
|
1719
|
+
method,
|
|
1720
|
+
headers: {
|
|
1721
|
+
Authorization: `Bearer ${token}`,
|
|
1722
|
+
Accept: "application/json",
|
|
1723
|
+
"X-ActivitySmith-SDK": `cli-v${version}`,
|
|
1724
|
+
...(body ? { "Content-Type": "application/json" } : {}),
|
|
1725
|
+
},
|
|
1726
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
1727
|
+
});
|
|
1728
|
+
if (!response.ok) {
|
|
1729
|
+
const error = new Error(`Request failed with status ${response.status}`);
|
|
1730
|
+
error.response = response;
|
|
1731
|
+
throw error;
|
|
1732
|
+
}
|
|
1733
|
+
return response.json();
|
|
1734
|
+
};
|
|
1735
|
+
|
|
1736
|
+
const describeDevice = (device) => {
|
|
1737
|
+
const name = device.device_name || device.device_type || "Device";
|
|
1738
|
+
const system = [device.system_name, device.system_version].filter(Boolean).join(" ");
|
|
1739
|
+
const details = [system, device.is_active ? "active" : "inactive", device.user_email].filter(Boolean);
|
|
1740
|
+
return `- ${name} (${details.join(", ")}) ID: ${device.device_id}`;
|
|
1741
|
+
};
|
|
1742
|
+
|
|
1743
|
+
const devicesCommand = program
|
|
1744
|
+
.command("devices")
|
|
1745
|
+
.description("List the iPhones and iPads paired to your account");
|
|
1746
|
+
|
|
1747
|
+
devicesCommand
|
|
1748
|
+
.command("list", { isDefault: true })
|
|
1749
|
+
.description("List paired devices, active ones first")
|
|
1750
|
+
.option("--include-inactive", "Also list devices that can no longer receive deliveries")
|
|
1751
|
+
.action(async (options) => {
|
|
1752
|
+
const globalOptions = program.opts();
|
|
1753
|
+
|
|
1754
|
+
try {
|
|
1755
|
+
const token = await requireApiKey(globalOptions);
|
|
1756
|
+
const query = options.includeInactive ? "?include_inactive=true" : "";
|
|
1757
|
+
const result = await apiRequest(`/account/devices${query}`, { token });
|
|
1758
|
+
const devices = Array.isArray(result.devices) ? result.devices : [];
|
|
1759
|
+
const active = devices.filter((device) => device.is_active).length;
|
|
1760
|
+
outputResult(
|
|
1761
|
+
result,
|
|
1762
|
+
globalOptions,
|
|
1763
|
+
devices.length === 0
|
|
1764
|
+
? [
|
|
1765
|
+
"No paired devices.",
|
|
1766
|
+
"Install ActivitySmith from the App Store, sign in with this account, and allow notifications:",
|
|
1767
|
+
APP_STORE_URL,
|
|
1768
|
+
]
|
|
1769
|
+
: [
|
|
1770
|
+
`${devices.length} ${devices.length === 1 ? "device" : "devices"}, ${active} active:`,
|
|
1771
|
+
...devices.map(describeDevice),
|
|
1772
|
+
result.meta?.has_more ? "More devices exist. Use --json to see the meta.next_offset value." : null,
|
|
1773
|
+
]
|
|
1774
|
+
);
|
|
1775
|
+
} catch (error) {
|
|
1776
|
+
await handleError(error, globalOptions);
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
|
|
1780
|
+
const keysCommand = program
|
|
1781
|
+
.command("keys")
|
|
1782
|
+
.description("Create API keys for CI, servers, and scripts");
|
|
1783
|
+
|
|
1784
|
+
keysCommand
|
|
1785
|
+
.command("create")
|
|
1786
|
+
.description(
|
|
1787
|
+
"Create an API key with the browser sign-in. The first time, approve API key access in the browser"
|
|
1788
|
+
)
|
|
1789
|
+
.requiredOption("--name <name>", 'Key name, such as "GitHub Actions"')
|
|
1790
|
+
.option("--channels <slugs>", "Comma-separated channel slugs. The key reaches only these Channels")
|
|
1791
|
+
.option("--raw", "Print only the key on standard output, for piping it into a secret store")
|
|
1792
|
+
.action(async (options) => {
|
|
1793
|
+
const globalOptions = program.opts();
|
|
1794
|
+
|
|
1795
|
+
try {
|
|
1796
|
+
// API keys cannot create keys, so this always uses the browser sign-in, even when an API key is set.
|
|
1797
|
+
let stored = null;
|
|
1798
|
+
try {
|
|
1799
|
+
stored = readCredentials();
|
|
1800
|
+
} catch {
|
|
1801
|
+
// An unreadable sign-in is replaced by the login below.
|
|
1802
|
+
}
|
|
1803
|
+
if (!hasScope(stored, API_KEYS_SCOPE)) {
|
|
1804
|
+
console.error("Approve API key access in the browser so the CLI can create API keys.");
|
|
1805
|
+
await login({ scope: `${LOGIN_SCOPES} ${API_KEYS_SCOPE}` });
|
|
1806
|
+
}
|
|
1807
|
+
const token = await getAccessToken();
|
|
1808
|
+
usingSignIn = true;
|
|
1809
|
+
const channels = String(options.channels ?? "")
|
|
1810
|
+
.split(",")
|
|
1811
|
+
.map((slug) => slug.trim())
|
|
1812
|
+
.filter(Boolean);
|
|
1813
|
+
const result = await apiRequest("/account/api-keys", {
|
|
1814
|
+
token,
|
|
1815
|
+
method: "POST",
|
|
1816
|
+
body: { name: options.name, ...(channels.length > 0 ? { channels } : {}) },
|
|
1817
|
+
});
|
|
1818
|
+
const key = result.api_key?.key;
|
|
1819
|
+
if (!key) {
|
|
1820
|
+
throw new Error("The API did not return a key. Run the command again.");
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
if (options.raw) {
|
|
1824
|
+
process.stdout.write(`${key}\n`);
|
|
1825
|
+
console.error(`Created API key "${result.api_key.name}". Store it as a secret and never commit it.`);
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
outputResult(result, globalOptions, [
|
|
1829
|
+
`Created API key "${result.api_key.name}".`,
|
|
1830
|
+
`Key: ${key}`,
|
|
1831
|
+
"This is the only time the key is shown. Store it as a secret named ACTIVITYSMITH_API_KEY and never commit it.",
|
|
1832
|
+
]);
|
|
1833
|
+
} catch (error) {
|
|
1834
|
+
await handleError(error, globalOptions);
|
|
1835
|
+
}
|
|
1836
|
+
});
|
|
1837
|
+
|
|
1838
|
+
// Approvals. Agents ask the user for approval before an action the user wants to approve, such as
|
|
1839
|
+
// sending an email or deploying, and go ahead only when this exits 0.
|
|
1840
|
+
const APPROVAL_SCOPE_TYPES = ["working_directory", "repository", "project", "environment", "customer", "account", "resource"];
|
|
1841
|
+
const APPROVAL_COLORS = ["lime", "green", "cyan", "blue", "purple", "magenta", "red", "orange", "yellow", "gray"];
|
|
1842
|
+
// Each request waits at most this long on the server, then the CLI asks again.
|
|
1843
|
+
const APPROVAL_POLL_SECONDS = 45;
|
|
1844
|
+
const APPROVAL_EXIT = { approved: 0, not_approved: 1, error: 2, pending: 3 };
|
|
1845
|
+
|
|
1846
|
+
const parseApprovalScope = (value) => {
|
|
1847
|
+
const separator = value.indexOf(":");
|
|
1848
|
+
const type = separator > 0 ? value.slice(0, separator).trim() : "";
|
|
1849
|
+
const scopeValue = separator > 0 ? value.slice(separator + 1).trim() : "";
|
|
1850
|
+
if (!APPROVAL_SCOPE_TYPES.includes(type) || !scopeValue) {
|
|
1851
|
+
throw new InvalidArgumentError(
|
|
1852
|
+
`scope must be <type>:<value>, where type is one of ${APPROVAL_SCOPE_TYPES.join(", ")}`
|
|
1853
|
+
);
|
|
1854
|
+
}
|
|
1855
|
+
return { type, value: scopeValue };
|
|
1856
|
+
};
|
|
1857
|
+
|
|
1858
|
+
const parseApprovalColor = (value) => {
|
|
1859
|
+
if (!APPROVAL_COLORS.includes(value)) {
|
|
1860
|
+
throw new InvalidArgumentError(`color must be one of ${APPROVAL_COLORS.join(", ")}`);
|
|
1861
|
+
}
|
|
1862
|
+
return value;
|
|
1863
|
+
};
|
|
1864
|
+
|
|
1865
|
+
const parsePositiveSeconds = (value) => {
|
|
1866
|
+
const parsed = Number(value);
|
|
1867
|
+
if (!Number.isInteger(parsed) || parsed < 1) {
|
|
1868
|
+
throw new InvalidArgumentError("timeout must be a whole number of seconds, 1 or more");
|
|
1869
|
+
}
|
|
1870
|
+
return parsed;
|
|
1871
|
+
};
|
|
1872
|
+
|
|
1873
|
+
const APPROVAL_RESULT_LINES = {
|
|
1874
|
+
approved: "Approved.",
|
|
1875
|
+
rejected: "Rejected. Do not continue with the action.",
|
|
1876
|
+
timed_out: "Timed out. No decision within 30 minutes. Do not continue with the action.",
|
|
1877
|
+
cancelled: "Cancelled. Do not continue with the action.",
|
|
1878
|
+
};
|
|
1879
|
+
|
|
1880
|
+
// Waits until the approval is decided, or until `timeoutSeconds` pass, then prints the result and exits.
|
|
1881
|
+
const waitForApproval = async (approvalId, token, timeoutSeconds, globalOptions) => {
|
|
1882
|
+
const deadline = timeoutSeconds ? Date.now() + timeoutSeconds * 1000 : Number.POSITIVE_INFINITY;
|
|
1883
|
+
let result;
|
|
1884
|
+
while (true) {
|
|
1885
|
+
const remaining = Math.ceil((deadline - Date.now()) / 1000);
|
|
1886
|
+
const wait = Math.max(1, Math.min(APPROVAL_POLL_SECONDS, remaining));
|
|
1887
|
+
const startedAt = Date.now();
|
|
1888
|
+
result = await apiRequest(`/approvals/${encodeURIComponent(approvalId)}?wait=${wait}`, { token });
|
|
1889
|
+
if (result.approval?.status !== "pending" || Date.now() >= deadline) break;
|
|
1890
|
+
// The server normally holds the request until it decides or the wait ends; never ask again in a tight loop.
|
|
1891
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(0, 1000 - (Date.now() - startedAt))));
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
const status = result.approval?.status;
|
|
1895
|
+
if (status === "pending") {
|
|
1896
|
+
outputResult(result, globalOptions, [
|
|
1897
|
+
`Still pending. Approval ID: ${approvalId}`,
|
|
1898
|
+
`Run activitysmith approval wait ${approvalId} to keep waiting.`,
|
|
1899
|
+
]);
|
|
1900
|
+
process.exit(APPROVAL_EXIT.pending);
|
|
1901
|
+
}
|
|
1902
|
+
outputResult(result, globalOptions, [APPROVAL_RESULT_LINES[status] ?? `Status: ${status}`]);
|
|
1903
|
+
process.exit(status === "approved" ? APPROVAL_EXIT.approved : APPROVAL_EXIT.not_approved);
|
|
1904
|
+
};
|
|
1905
|
+
|
|
1906
|
+
const approvalCommand = program
|
|
1907
|
+
.command("approval")
|
|
1908
|
+
.description("Let your agents ask for your approval on your iPhone before they act")
|
|
1909
|
+
.addHelpText(
|
|
1910
|
+
"after",
|
|
1911
|
+
`
|
|
1912
|
+
Exit codes for request and wait:
|
|
1913
|
+
0 Approved. Continue with the action.
|
|
1914
|
+
1 Rejected, timed out, or cancelled. Do not continue.
|
|
1915
|
+
2 The request failed, for example no paired device.
|
|
1916
|
+
3 Still pending after --timeout or with --no-wait. Run approval wait with the approval ID.`
|
|
1917
|
+
);
|
|
1918
|
+
|
|
1919
|
+
approvalCommand
|
|
1920
|
+
.command("request")
|
|
1921
|
+
.description("Send an approval request with two buttons to the iPhone and wait for the decision")
|
|
1922
|
+
.argument("<question>", 'The decision to make, such as "Send the pricing update email to 214 customers?"')
|
|
1923
|
+
.option("--details <text>", "Short context that helps decide")
|
|
1924
|
+
.option("--approve-label <label>", "Approve button title, a concrete verb such as Send or Deploy", "Approve")
|
|
1925
|
+
.option("--reject-label <label>", "Reject button title, such as Cancel or Don't Send", "Reject")
|
|
1926
|
+
.option("--command <command>", "The exact command waiting for approval. Do not shorten or rewrite it")
|
|
1927
|
+
.option("--tool <name>", "Name of the operation waiting for approval (default: shell with --command)")
|
|
1928
|
+
.option(
|
|
1929
|
+
"--scope <type:value>",
|
|
1930
|
+
`Where the action applies, such as environment:production. Types: ${APPROVAL_SCOPE_TYPES.join(", ")} (default: working_directory:<current directory> with --command)`,
|
|
1931
|
+
parseApprovalScope
|
|
1932
|
+
)
|
|
1933
|
+
.addOption(
|
|
1934
|
+
new Option("--delivery <surface>", "Live Activity, Push Notification, or auto: a Live Activity with a Push Notification fallback")
|
|
1935
|
+
.choices(["auto", "live_activity", "push_notification"])
|
|
1936
|
+
.default("auto")
|
|
1937
|
+
)
|
|
1938
|
+
.option("--color <color>", "Live Activity color (default: blue)", parseApprovalColor)
|
|
1939
|
+
.option("--icon <symbol>", "SF Symbol for the Live Activity (default: sparkles)")
|
|
1940
|
+
.option("--badge <title>", "Short Live Activity badge such as Email or Deploy (default: Agent)")
|
|
1941
|
+
.option("--channels <slugs>", "Comma-separated channel slugs. Omit to ask on every paired device")
|
|
1942
|
+
.option("--timeout <seconds>", "Stop waiting after this many seconds and exit 3 if still pending", parsePositiveSeconds)
|
|
1943
|
+
.option("--no-wait", "Send the request, print the approval ID, and exit without waiting")
|
|
1944
|
+
.action(async (question, options) => {
|
|
1945
|
+
const globalOptions = program.opts();
|
|
1946
|
+
|
|
1947
|
+
try {
|
|
1948
|
+
const token = await requireApiKey(globalOptions);
|
|
1949
|
+
const tool = options.tool ?? (options.command ? "shell" : undefined);
|
|
1950
|
+
if (options.command && !tool) throw new Error("Provide --tool with --command.");
|
|
1951
|
+
const scope = options.scope ?? (options.command ? { type: "working_directory", value: process.cwd() } : undefined);
|
|
1952
|
+
const appearance = {
|
|
1953
|
+
...(options.color ? { color: options.color } : {}),
|
|
1954
|
+
...(options.icon ? { icon: { symbol: options.icon } } : {}),
|
|
1955
|
+
...(options.badge ? { badge: { title: options.badge } } : {}),
|
|
1956
|
+
};
|
|
1957
|
+
const channels = String(options.channels ?? "")
|
|
1958
|
+
.split(",")
|
|
1959
|
+
.map((slug) => slug.trim())
|
|
1960
|
+
.filter(Boolean);
|
|
1961
|
+
|
|
1962
|
+
const result = await apiRequest("/approvals", {
|
|
1963
|
+
token,
|
|
1964
|
+
method: "POST",
|
|
1965
|
+
body: {
|
|
1966
|
+
question,
|
|
1967
|
+
...(options.details ? { details: options.details } : {}),
|
|
1968
|
+
...(tool ? { execution_context: { tool, ...(options.command ? { command: options.command } : {}) } } : {}),
|
|
1969
|
+
...(scope ? { scope } : {}),
|
|
1970
|
+
delivery: options.delivery,
|
|
1971
|
+
approve_label: options.approveLabel,
|
|
1972
|
+
reject_label: options.rejectLabel,
|
|
1973
|
+
...(Object.keys(appearance).length > 0 ? { appearance } : {}),
|
|
1974
|
+
...(channels.length > 0 ? { target_channel_slugs: channels } : {}),
|
|
1975
|
+
},
|
|
1976
|
+
});
|
|
1977
|
+
const approvalId = result.approval?.id;
|
|
1978
|
+
if (!approvalId) throw new Error("The API did not return an approval ID. Run the command again.");
|
|
1979
|
+
|
|
1980
|
+
if (options.wait === false) {
|
|
1981
|
+
outputResult(result, globalOptions, [
|
|
1982
|
+
`Approval requested. Approval ID: ${approvalId}`,
|
|
1983
|
+
`Run activitysmith approval wait ${approvalId} to wait for the decision.`,
|
|
1984
|
+
]);
|
|
1985
|
+
process.exit(APPROVAL_EXIT.pending);
|
|
1986
|
+
}
|
|
1987
|
+
if (!globalOptions.json) {
|
|
1988
|
+
console.error(`Approval requested. Waiting for the decision on the iPhone. Approval ID: ${approvalId}`);
|
|
1989
|
+
}
|
|
1990
|
+
await waitForApproval(approvalId, token, options.timeout, globalOptions);
|
|
1991
|
+
} catch (error) {
|
|
1992
|
+
await handleError(error, globalOptions, APPROVAL_EXIT.error);
|
|
1993
|
+
}
|
|
1994
|
+
});
|
|
1995
|
+
|
|
1996
|
+
approvalCommand
|
|
1997
|
+
.command("wait")
|
|
1998
|
+
.description("Wait for the decision on an approval request")
|
|
1999
|
+
.argument("<approval-id>", "Approval ID from approval request")
|
|
2000
|
+
.option("--timeout <seconds>", "Stop waiting after this many seconds and exit 3 if still pending", parsePositiveSeconds)
|
|
2001
|
+
.action(async (approvalId, options) => {
|
|
2002
|
+
const globalOptions = program.opts();
|
|
2003
|
+
|
|
2004
|
+
try {
|
|
2005
|
+
const token = await requireApiKey(globalOptions);
|
|
2006
|
+
await waitForApproval(approvalId, token, options.timeout, globalOptions);
|
|
2007
|
+
} catch (error) {
|
|
2008
|
+
await handleError(error, globalOptions, APPROVAL_EXIT.error);
|
|
2009
|
+
}
|
|
2010
|
+
});
|
|
2011
|
+
|
|
2012
|
+
approvalCommand
|
|
2013
|
+
.command("get")
|
|
2014
|
+
.description("Show the current state of an approval request without waiting")
|
|
2015
|
+
.argument("<approval-id>", "Approval ID from approval request")
|
|
2016
|
+
.action(async (approvalId) => {
|
|
2017
|
+
const globalOptions = program.opts();
|
|
2018
|
+
|
|
2019
|
+
try {
|
|
2020
|
+
const token = await requireApiKey(globalOptions);
|
|
2021
|
+
const result = await apiRequest(`/approvals/${encodeURIComponent(approvalId)}`, { token });
|
|
2022
|
+
const status = result.approval?.status;
|
|
2023
|
+
outputResult(result, globalOptions, [
|
|
2024
|
+
status === "pending" ? "Pending." : (APPROVAL_RESULT_LINES[status] ?? `Status: ${status}`),
|
|
2025
|
+
`Approval ID: ${approvalId}`,
|
|
2026
|
+
result.approval?.question ? `Question: ${result.approval.question}` : null,
|
|
2027
|
+
]);
|
|
2028
|
+
} catch (error) {
|
|
2029
|
+
await handleError(error, globalOptions, APPROVAL_EXIT.error);
|
|
2030
|
+
}
|
|
2031
|
+
});
|
|
2032
|
+
|
|
2033
|
+
approvalCommand
|
|
2034
|
+
.command("cancel")
|
|
2035
|
+
.description("Withdraw a pending approval request that is no longer needed")
|
|
2036
|
+
.argument("<approval-id>", "Approval ID from approval request")
|
|
2037
|
+
.action(async (approvalId) => {
|
|
2038
|
+
const globalOptions = program.opts();
|
|
2039
|
+
|
|
2040
|
+
try {
|
|
2041
|
+
const token = await requireApiKey(globalOptions);
|
|
2042
|
+
const result = await apiRequest(`/approvals/${encodeURIComponent(approvalId)}/cancel`, { token, method: "POST" });
|
|
2043
|
+
const status = result.approval?.status;
|
|
2044
|
+
outputResult(result, globalOptions, [
|
|
2045
|
+
status === "cancelled"
|
|
2046
|
+
? "Approval request cancelled. It can no longer be approved."
|
|
2047
|
+
: `Not cancelled: the request is already ${String(status).replace("_", " ")}.`,
|
|
2048
|
+
`Approval ID: ${approvalId}`,
|
|
2049
|
+
]);
|
|
2050
|
+
} catch (error) {
|
|
2051
|
+
await handleError(error, globalOptions, APPROVAL_EXIT.error);
|
|
2052
|
+
}
|
|
2053
|
+
});
|
|
2054
|
+
|
|
1705
2055
|
const authCommand = program
|
|
1706
2056
|
.command("auth")
|
|
1707
2057
|
.description("Sign in through the browser and manage the saved sign-in");
|