activitysmith-cli 1.16.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.
Files changed (3) hide show
  1. package/README.md +67 -0
  2. package/package.json +1 -1
  3. package/src/cli.js +220 -5
package/README.md CHANGED
@@ -692,6 +692,73 @@ Pass `0` to clear the badge.
692
692
  activitysmith badge 0
693
693
  ```
694
694
 
695
+ ## Approvals
696
+
697
+ ![Approval Live Activity on an iPhone Lock Screen with Send and Deny buttons](https://cdn.activitysmith.com/features/ai-agent-approval-live-activity-phone.png)
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
+
695
762
  ## Metadata
696
763
 
697
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.16.0",
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/cli.js CHANGED
@@ -1221,7 +1221,7 @@ const buildErrorDetails = async (error) => {
1221
1221
  // Set when a command authenticates with the browser sign-in rather than an API key.
1222
1222
  let usingSignIn = false;
1223
1223
 
1224
- const handleError = async (error, options) => {
1224
+ const handleError = async (error, options, exitCode = 1) => {
1225
1225
  const details = await buildErrorDetails(error);
1226
1226
  // Disconnecting the CLI in the web app rejects its token at once, before it expires.
1227
1227
  if (usingSignIn && details.status === 401) {
@@ -1256,7 +1256,7 @@ const handleError = async (error, options) => {
1256
1256
  }
1257
1257
  }
1258
1258
 
1259
- process.exit(1);
1259
+ process.exit(exitCode);
1260
1260
  };
1261
1261
 
1262
1262
  // Returns the API key, or a current access token from the saved sign-in. The REST API accepts
@@ -1439,9 +1439,7 @@ metricsCommand
1439
1439
  .description("Update a widget metric value")
1440
1440
  .argument("<metric-key>", "Metric key")
1441
1441
  .argument("<value>", "Metric value")
1442
- .option("--metadata <json>", "Metadata JSON object shown in ActivitySmith details")
1443
- .option("--metadata-file <path>", "Path to a Metadata JSON object file")
1444
- .action(async (metricKey, rawValue) => {
1442
+ .action(async (metricKey, rawValue) => {
1445
1443
  const globalOptions = program.opts();
1446
1444
 
1447
1445
  try {
@@ -1837,6 +1835,223 @@ keysCommand
1837
1835
  }
1838
1836
  });
1839
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
+
1840
2055
  const authCommand = program
1841
2056
  .command("auth")
1842
2057
  .description("Sign in through the browser and manage the saved sign-in");