@usestatemachines/cli 0.0.0-stage → 0.1.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 (169) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +34 -2
  3. package/dist/agents/bundled.d.ts +5 -0
  4. package/dist/agents/bundled.js +6 -0
  5. package/dist/agents/destinations.d.ts +13 -0
  6. package/dist/agents/destinations.js +16 -0
  7. package/dist/api-internal.d.ts +62 -0
  8. package/dist/api-internal.js +348 -0
  9. package/dist/bin.d.ts +2 -0
  10. package/dist/bin.js +4 -0
  11. package/dist/command.d.ts +119 -0
  12. package/dist/command.js +195 -0
  13. package/dist/commands/api/command.d.ts +15 -0
  14. package/dist/commands/api/command.js +38 -0
  15. package/dist/commands/api/run.d.ts +4 -0
  16. package/dist/commands/api/run.js +24 -0
  17. package/dist/commands/apps/command.d.ts +19 -0
  18. package/dist/commands/apps/command.js +29 -0
  19. package/dist/commands/apps/list.d.ts +8 -0
  20. package/dist/commands/apps/list.js +10 -0
  21. package/dist/commands/connect/command.d.ts +34 -0
  22. package/dist/commands/connect/command.js +70 -0
  23. package/dist/commands/connect/run.d.ts +10 -0
  24. package/dist/commands/connect/run.js +71 -0
  25. package/dist/commands/doctor/command.d.ts +29 -0
  26. package/dist/commands/doctor/command.js +36 -0
  27. package/dist/commands/doctor/run.d.ts +13 -0
  28. package/dist/commands/doctor/run.js +12 -0
  29. package/dist/commands/env/command.d.ts +5 -0
  30. package/dist/commands/env/command.js +19 -0
  31. package/dist/commands/env/pull.d.ts +6 -0
  32. package/dist/commands/env/pull.js +6 -0
  33. package/dist/commands/environments/command.d.ts +121 -0
  34. package/dist/commands/environments/command.js +170 -0
  35. package/dist/commands/environments/create.d.ts +9 -0
  36. package/dist/commands/environments/create.js +42 -0
  37. package/dist/commands/environments/delete.d.ts +7 -0
  38. package/dist/commands/environments/delete.js +48 -0
  39. package/dist/commands/environments/get.d.ts +39 -0
  40. package/dist/commands/environments/get.js +5 -0
  41. package/dist/commands/environments/list.d.ts +41 -0
  42. package/dist/commands/environments/list.js +18 -0
  43. package/dist/commands/environments/wait.d.ts +39 -0
  44. package/dist/commands/environments/wait.js +21 -0
  45. package/dist/commands/init/command.d.ts +68 -0
  46. package/dist/commands/init/command.js +90 -0
  47. package/dist/commands/init/run.d.ts +8 -0
  48. package/dist/commands/init/run.js +422 -0
  49. package/dist/commands/link/command.d.ts +13 -0
  50. package/dist/commands/link/command.js +32 -0
  51. package/dist/commands/link/run.d.ts +12 -0
  52. package/dist/commands/link/run.js +7 -0
  53. package/dist/commands/login/command.d.ts +1 -0
  54. package/dist/commands/login/command.js +43 -0
  55. package/dist/commands/login/run.d.ts +30 -0
  56. package/dist/commands/login/run.js +43 -0
  57. package/dist/commands/login/schema.d.ts +33 -0
  58. package/dist/commands/login/schema.js +33 -0
  59. package/dist/commands/logout/command.d.ts +1 -0
  60. package/dist/commands/logout/command.js +24 -0
  61. package/dist/commands/logout/run.d.ts +10 -0
  62. package/dist/commands/logout/run.js +19 -0
  63. package/dist/commands/logout/schema.d.ts +10 -0
  64. package/dist/commands/logout/schema.js +10 -0
  65. package/dist/commands/profiles/command.d.ts +2 -0
  66. package/dist/commands/profiles/command.js +29 -0
  67. package/dist/commands/profiles/list.d.ts +20 -0
  68. package/dist/commands/profiles/list.js +10 -0
  69. package/dist/commands/profiles/schema.d.ts +24 -0
  70. package/dist/commands/profiles/schema.js +19 -0
  71. package/dist/commands/profiles/use.d.ts +7 -0
  72. package/dist/commands/profiles/use.js +7 -0
  73. package/dist/commands/requests/command.d.ts +39 -0
  74. package/dist/commands/requests/command.js +65 -0
  75. package/dist/commands/requests/get.d.ts +32 -0
  76. package/dist/commands/requests/get.js +15 -0
  77. package/dist/commands/requests/list.d.ts +27 -0
  78. package/dist/commands/requests/list.js +25 -0
  79. package/dist/commands/snapshots/command.d.ts +48 -0
  80. package/dist/commands/snapshots/command.js +80 -0
  81. package/dist/commands/snapshots/create.d.ts +7 -0
  82. package/dist/commands/snapshots/create.js +26 -0
  83. package/dist/commands/snapshots/delete.d.ts +34 -0
  84. package/dist/commands/snapshots/delete.js +8 -0
  85. package/dist/commands/snapshots/get.d.ts +35 -0
  86. package/dist/commands/snapshots/get.js +5 -0
  87. package/dist/commands/snapshots/list.d.ts +37 -0
  88. package/dist/commands/snapshots/list.js +10 -0
  89. package/dist/commands/unlink/command.d.ts +1 -0
  90. package/dist/commands/unlink/command.js +15 -0
  91. package/dist/commands/unlink/run.d.ts +7 -0
  92. package/dist/commands/unlink/run.js +8 -0
  93. package/dist/commands/whoami/command.d.ts +28 -0
  94. package/dist/commands/whoami/command.js +44 -0
  95. package/dist/commands/whoami/run.d.ts +5 -0
  96. package/dist/commands/whoami/run.js +39 -0
  97. package/dist/commands/workspaces/command.d.ts +33 -0
  98. package/dist/commands/workspaces/command.js +73 -0
  99. package/dist/commands/workspaces/list.d.ts +5 -0
  100. package/dist/commands/workspaces/list.js +42 -0
  101. package/dist/commands/workspaces/use.d.ts +5 -0
  102. package/dist/commands/workspaces/use.js +18 -0
  103. package/dist/config/project.d.ts +21 -0
  104. package/dist/config/project.js +105 -0
  105. package/dist/config/schema.d.ts +616 -0
  106. package/dist/config/schema.js +282 -0
  107. package/dist/context-types.d.ts +89 -0
  108. package/dist/context-types.js +56 -0
  109. package/dist/context.d.ts +13 -0
  110. package/dist/context.js +290 -0
  111. package/dist/credentials/sealing.d.ts +10 -0
  112. package/dist/credentials/sealing.js +72 -0
  113. package/dist/credentials/store.d.ts +17 -0
  114. package/dist/credentials/store.js +156 -0
  115. package/dist/doctor.d.ts +4 -0
  116. package/dist/doctor.js +239 -0
  117. package/dist/env-file.d.ts +10 -0
  118. package/dist/env-file.js +254 -0
  119. package/dist/errors.d.ts +784 -0
  120. package/dist/errors.js +459 -0
  121. package/dist/flags.d.ts +22 -0
  122. package/dist/flags.js +56 -0
  123. package/dist/generated/internal.d.ts +138 -0
  124. package/dist/generated/internal.js +2627 -0
  125. package/dist/generated/retry.d.ts +1 -0
  126. package/dist/generated/retry.js +11 -0
  127. package/dist/help.d.ts +408 -0
  128. package/dist/help.js +220 -0
  129. package/dist/io-types.d.ts +127 -0
  130. package/dist/io-types.js +1 -0
  131. package/dist/io.d.ts +13 -0
  132. package/dist/io.js +1017 -0
  133. package/dist/keys.d.ts +50 -0
  134. package/dist/keys.js +691 -0
  135. package/dist/link.d.ts +6 -0
  136. package/dist/link.js +58 -0
  137. package/dist/login.d.ts +92 -0
  138. package/dist/login.js +965 -0
  139. package/dist/main.d.ts +2 -0
  140. package/dist/main.js +126 -0
  141. package/dist/native-helper.d.ts +1 -0
  142. package/dist/native-helper.js +2 -0
  143. package/dist/output.d.ts +8 -0
  144. package/dist/output.js +135 -0
  145. package/dist/parser.d.ts +28 -0
  146. package/dist/parser.js +250 -0
  147. package/dist/program-types.d.ts +67 -0
  148. package/dist/program-types.js +14 -0
  149. package/dist/programs.d.ts +2 -0
  150. package/dist/programs.js +44 -0
  151. package/dist/project-roots.d.ts +3 -0
  152. package/dist/project-roots.js +26 -0
  153. package/dist/prompt.d.ts +3 -0
  154. package/dist/prompt.js +61 -0
  155. package/dist/registry.d.ts +2 -0
  156. package/dist/registry.js +44 -0
  157. package/dist/resources/create.d.ts +9 -0
  158. package/dist/resources/create.js +55 -0
  159. package/dist/resources/read.d.ts +15 -0
  160. package/dist/resources/read.js +69 -0
  161. package/dist/resources/schema.d.ts +177 -0
  162. package/dist/resources/schema.js +158 -0
  163. package/dist/text.d.ts +3 -0
  164. package/dist/text.js +19 -0
  165. package/dist/update.d.ts +22 -0
  166. package/dist/update.js +126 -0
  167. package/dist/version.d.ts +2 -0
  168. package/dist/version.js +2 -0
  169. package/package.json +52 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 State
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # State Machines CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The State Machines CLI signs you in, links a repository to a workspace, and manages environments through the State Machines API.
4
+ Programs receive workspace API keys through `run` or `env pull`. The account token stays inside the CLI.
5
+
6
+ ```sh
7
+ statemachines login
8
+ statemachines init --agent claude
9
+ statemachines run -- npm test
10
+ ```
11
+
12
+ Plain `init` links the repository and installs the selected agent skill. Add `--sdk` to install the SDK, `--quickstart` to write the example, or `--env` to pull a workspace key into `.env.local`.
13
+ Run `statemachines help --json` for command schemas, flags, errors, and exit codes.
14
+
15
+ Without an interactive terminal, commands return JSON and never prompt. Use `--workspace` to select a workspace and `--yes` to confirm a destructive command.
16
+ For agent sign-in, run `login --no-wait --json`, show the user its URL and code, then run `login --resume --json` after approval.
17
+
18
+ Approve only a login you started. A matching code does not identify the requesting computer.
19
+ `logout` revokes the account token and its workspace keys. Offline revocations stay pending until the API is reachable.
20
+
21
+ The package manifest defines the Node requirement and exact SDK dependency.
22
+ The installed package includes its API contracts and agent instructions. It does not require the management API source or monorepo templates.
23
+
24
+ ## Credential storage
25
+
26
+ `statemachines login` saves the CLI token in the system keychain. If the keychain write fails, the CLI saves the token in `credentials.json` in its configuration directory and prints a warning. Cancellation never falls back to the file. Other Node programs you run may read a macOS keychain item created by Node.
27
+
28
+ To choose the store yourself, set `STATEMACHINES_CREDENTIAL_STORE`:
29
+
30
+ - `file` saves credentials in `credentials.json` and never uses the keychain. Use it over SSH and on machines without a keychain service.
31
+ - `keychain` saves credentials only in the keychain, and a keychain failure stops the command.
32
+
33
+ ## Update notices
34
+
35
+ In an interactive terminal, the CLI checks npm for a newer version and prints a notice on stderr when one exists. To turn the notice off, set `STATEMACHINES_NO_UPDATE_NOTIFIER=1` or set `NO_UPDATE_NOTIFIER` to any value. The CLI never checks in CI, from `npx`, or when an agent runs it.
@@ -0,0 +1,5 @@
1
+ export declare const prompt: string;
2
+ export declare const llmsTxt: string;
3
+ export declare const skill: string;
4
+ export declare const quickstart: string;
5
+ export declare const cliCommand: string;
@@ -0,0 +1,6 @@
1
+ // Generated by scripts/build-agents.mjs from the SDK agent templates.
2
+ export const prompt = "Install the State Machines skill in this existing repository so I can use disposable app environments with my coding agent.\n\n1. Read the repository instructions. Run `npx @usestatemachines/cli@0.1.0 init --agent <this-agent> --yes`, using this agent's supported name from `npx @usestatemachines/cli@0.1.0 init --help`. If sign-in is required, ask for my agreement, then run `npx @usestatemachines/cli@0.1.0 login --no-wait --json`. Show the URL and code, wait for my approval, then run `npx @usestatemachines/cli@0.1.0 login --resume --json` and retry the same init command. If more than one workspace is available, ask which to use and pass `--workspace <workspace-id>`. If this agent cannot run commands or has no supported destination, download https://docs.usestatemachines.com/skill.md and install `state-machines/SKILL.md` in its supported project skills directory. Preserve a different installed copy. If persistent skills are unsupported, read the skill for this session and explain the limitation. Report a failed download or installation.\n2. Read the skill. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Keep the repository's existing conventions.\n3. Reuse the project's existing `STATEMACHINES_API_KEY` loader when present. Otherwise, use the skill's CLI sign-in steps after I agree to sign in. Never ask me to paste a credential into chat, print it, or commit it.\n4. Report where the skill was installed and whether the agent needs to reload it. Skill installation alone does not verify an API connection. Ask: \"What would you like to run or test?\" Wait for my answer before making further changes.\n";
3
+ export const llmsTxt = "# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\nUse the project's package manager to install or reuse `@usestatemachines/sdk`. It is ESM only and runs on Node.js and Cloudflare Workers, not browsers. `engines` in its `package.json` gives the Node.js versions. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. `new StateMachines()` reads the API key from `STATEMACHINES_API_KEY` and doesn't read `.env` files; in Cloudflare Workers, pass `apiKey` explicitly. Never print the key. The installed `node_modules/@usestatemachines/sdk/README.md` matches your version: read it before relying on memory. Read the bundled `agents/SKILL.md` for the task workflow. Reuse the project's secret loader and check the key in the process that runs the test, not just the current shell. Installing the skill does not require SDK installation, example files or remote resources. Ask what the user wants to run and wait. Install the SDK and verify access when their chosen task needs it. Run the connection check below only if the user asks to verify the connection. Do not choose a business workflow from the repository.\n\n## Get a credential\n\nIf the project's existing command loads `STATEMACHINES_API_KEY`, reuse that command and secret loader. Otherwise, run `npx @usestatemachines/cli@0.1.0 whoami --json`. If it succeeds, use the workspace commands below. If it exits with code 3, ask the user to sign in. Only after the user agrees, start `npx @usestatemachines/cli@0.1.0 login --no-wait --json`, show its `verificationUrl` and `userCode`, and wait for approval. A matching code does not identify the requesting computer. After that approval, run `npx @usestatemachines/cli@0.1.0 login --resume --json` with the same profile to finish that attempt.\n\nFor `cli.not_linked`, run `npx @usestatemachines/cli@0.1.0 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.0 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.0 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.0`. Use `help --json` for flags and result schemas:\n\n- `login`, `logout`, `whoami`, `profiles list`, and `profiles use`\n- `workspaces list`, `workspaces use`, `link`, `unlink`, and `init`\n- `apps list`, `environments create`, `environments list`, `environments get`, `environments wait`, and `environments delete`\n- `connect`, `snapshots create`, `snapshots list`, `snapshots get`, `snapshots delete`, `requests list`, and `requests get`\n- `run -- <command>`, `env pull`, `api`, `doctor`, `version`, `help`, and `completion`\n\n## Concepts\n\n- Environment: one disposable run of one or more apps. `const env = await sm.environments.create({ apps: ['salesforce'] })` creates it and waits until it is `running`. Use `{ wait: false }` to retain the ID before startup. Wait for `running` inside `try`, then delete the owned environment in `finally`, including after a wait failure.\n- Apps: a string names the app by its ID, and the app's name in the environment is the same string. Use `{ appId: 'salesforce', name: 'crm', setup }` for your own name, for two copies of one app, or for the app's setup. Later calls take the name.\n- Credentials: `const crm = await env.connect('salesforce')` returns `token`, `services` and `fetch`. Each service has an `id`, a `url` and the `headers` its requests need. The credentials always list each `public` service of the app's version. Pass `{ services: [id] }` to `connect()` to also list a service by its ID. A `preview` service is listed only when named. `crm.service('api')` returns the `api` service, which is the app URL. `crm.fetch(path)` joins `path` to the `api` service URL and adds its headers, which carry `Authorization: Bearer` with `token`. For Salesforce SOAP, also put `crm.token` in the envelope's `SessionHeader/sessionId`. `fetch` never sends your API key, never follows redirects and never retries. `token` and each service's `headers` are secrets.\n- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Find the app by name in `env.apps`, then page through `sm.apps.versions(appId)` to find its exact `versionId`. Read actor IDs from that version's `actors`.\n- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A delete during the snapshot fails it with `interrupted`.\n- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.\n- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.\n- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n\n## Statuses\n\nEnums are open: handle values you don't recognise.\n\n- Environment `status`: `starting`, `running`, `failed`, `deleted`. A `deleted` environment has a `reason` when State Machines deleted it: `expired`, `failed` (it never reached `running`) or `cancelled` (staff ended it). The `reason` is `null` when a caller deleted it. When the environment failed, `failure` is `{ appName, code, message }`, and `code` is `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. For `invalid_setup` and `invalid_services`, the app refused a value in `setup` or in `services`, and `message` starts with its path.\n- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.\n- `create` throws `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.\n- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.\n- `sm.environments.wait(id, { status })` and `sm.snapshots.wait(id, { status })` wait for any status, and throw once it cannot be reached without another call.\n\n## Limits\n\nWhen `sm.me().limits` is non-null:\n\n- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.\n- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `message`, `requestId`, `fields` and `retryAfterMs`. The SDK retries `502`, `503`, `504` and connection errors itself, until a deadline; `create` retries reuse one idempotency key. It retries nothing else.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |\n| `forbidden` | 403 | The key lacks the permission. |\n| `not_found` | 404 | Check the ID and the workspace. |\n| `invalid_status` | 409 | The status does not allow the call. Snapshots need a running environment. |\n| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |\n| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |\n| `workspace_archived` | 409 | The workspace is archived. |\n| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |\n| `version_unavailable` | 422 | The app has no default version. |\n| `environment_limit_reached` | 429 | Delete only this task’s known leftovers, or ask the user to free capacity. |\n| `unavailable` | 503 | Retried automatically. If `create` still has an unknown outcome, replay the same input with the key retained before the original call. Do not generate a new key. |\n\n## Errors from the app URL\n\n`crm.fetch` returns these as responses with the same JSON envelope, and never retries them. Assert the expected status and result. For writes, read back the stored result. Never blindly retry a write whose outcome is unknown.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment_not_running` | 409 | The environment is failed or deleted; `error.status` names it. Create another environment. |\n| `environment_starting` | 503 | For reads, wait `Retry-After` and retry. Check stored state before retrying an uncertain write. |\n| `environment_unavailable` | 503 | The app is restarting. For reads, wait `Retry-After`. Check stored state before retrying an uncertain write. |\n| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |\n| `invalid_setup` | 503 | The app refused its `setup` after the environment started, such as in a newer version. `error.message` starts with the path of the value. Create another environment with a `setup` that the app accepts. |\n| `invalid_services` | 503 | The app refused a value in `services` after the environment started. `error.message` starts with the path of the value. Create another environment with `services` that the app accepts. |\n| `unsupported_protocol` | 501 | The app does not serve this path, method or content type, or the request body is compressed. |\n\n## Quickstart\n\nUse the project's TypeScript runner with its secret loader, or pass that runner through `npx @usestatemachines/cli@0.1.0 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.0 run -- npx tsx state-quickstart.mts`. The check prints the response status and deletes the environment. Only after it prints `200`, report verified setup and the rerun command. Continue only with an explicitly supplied task. Otherwise, ask what to run next and wait with no setup environment left running.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Docs\n\n- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://docs.usestatemachines.com/skill.md): workflow, rules and troubleshooting for coding agents\n- [OpenAPI document](https://cdn.jsdelivr.net/npm/@usestatemachines/sdk/openapi.json): the HTTP API the SDK calls\n- [State Machines](https://usestatemachines.com): website\n";
4
+ export const skill = "---\nname: state-machines\ndescription: Use when setting up State Machines or running code, integration tests, or API experiments against disposable SaaS replicas such as Salesforce. Applies to @usestatemachines/sdk and STATEMACHINES_API_KEY, including environment creation, actors, snapshots, cleanup and recovery.\n---\n\n## Start with the user's task\n\nDuring skill installation, read the repository instructions and preserve its existing structure. Do not create a new project, install dependencies, write examples or create remote resources. Report the installed skill location and any reload requirement, then ask \"What would you like to run or test?\" and wait. Skill installation does not verify a connection.\n\nOnce the user chooses a task, inspect the project's package manager, runtime, runner and secret loader. Install or reuse a compatible `@usestatemachines/sdk` only when the task needs it. Read the installed README for API signatures and `package.json` for runtime requirements. The SDK is ESM and runs on Node.js and Cloudflare Workers, not in a browser. Follow the user's task and existing project conventions without requiring a separate onboarding example.\n\n## Get a credential\n\nThe SDK reads `STATEMACHINES_API_KEY` from the process environment. It does not load `.env` files. Use the project's existing test command or secret loader. An empty variable in your current shell does not prove that the test process lacks it. Verify presence without displaying the value. In Workers, pass the binding explicitly with `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`.\n\nIf the project's existing command loads `STATEMACHINES_API_KEY`, keep using that command and secret loader. Call `sm.me()` in that process to verify access and workspace scope. `me.limits` can be null.\n\nOtherwise, run `npx @usestatemachines/cli@0.1.0 whoami --json`. A successful result means you can use the workspace commands below. If it exits with code 3, ask the user to sign in. After the user agrees, complete this login:\n\n1. Run `npx @usestatemachines/cli@0.1.0 login --no-wait --json`.\n2. Show the returned `verificationUrl` and `userCode`. Ask the user to approve only the login you just started. A matching code does not identify the computer requesting access. Wait for the user to approve the login.\n3. After that approval, run `npx @usestatemachines/cli@0.1.0 login --resume --json` with the same profile used to start the login. Resume that attempt instead of starting another login.\n\nIf a command returns `cli.not_linked`, run `npx @usestatemachines/cli@0.1.0 workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@0.1.0 link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@0.1.0 run -- <command>`. The child receives a workspace key. The CLI keeps the credential out of its output.\n\nIf access is denied or the workspace differs from the task, report the blocker. Do not invite or remove members, or change permissions.\n\nNever print, log or commit API keys, `credentials.token`, the `headers` of `credentials.services`, environment dumps, or secret-file contents. Use synthetic test data.\n\n## Run the user’s chosen task\n\nApply this section after setup, once the user has chosen a task.\n\n- `sm.apps.list()` returns app IDs. Every list returns `{ data, nextCursor }`. Follow cursors until the required entry is found or `nextCursor` is null.\n- Create only the apps the task needs. A string such as `'salesforce'` is both its app ID and its name in the environment. For named apps, later `connect()` calls use the name.\n- `connect(appName)` uses the app's default actor, the Salesforce administrator. For another actor, find the matching app by name in `environment.apps`, read its `versionId`, then find that exact version through `sm.apps.versions(appId)`. Use an actor ID from its `actors`, never a role label, workspace member ID, or the first version in a list.\n- Check the app's services and [known differences](https://docs.usestatemachines.com/apps/known-differences.md) for the behavior under test. A replica does not import a customer's org or run arbitrary customer automation.\n- Configure the existing integration's test transport with the returned app URL and credentials. Verify its requests reach that URL. A successful standalone SDK request does not prove the integration uses the replica. If transport configuration needs a broader change, explain it before expanding the task.\n- Check the expected HTTP status and assert the result. For writes, read the stored data back and assert the relevant fields. For negative tests, assert the expected error. Do not weaken an assertion to make unsupported behavior pass.\n\n## Own the full lifecycle\n\nCreate with `{ wait: false }` to retain the accepted environment ID before waiting. Enter `try` immediately, then wait for `running`, connect and run the check inside it. Delete in `finally`, including after a startup failure, timeout or failed assertion. An aborted wait does not cancel the work that the API accepted. Cleanup must use a fresh, un-aborted signal. Preserve both verification and cleanup errors, and report the environment ID if deletion fails.\n\nDelete only environments created for this task. If the organization is at its limit, clean up a known leftover from this task or ask the user to free capacity. Do not delete unrelated environments or a user-supplied reusable snapshot.\n\nThe SDK retries management connection errors and `502`, `503`, `504` with one idempotency key per create call. To recover across separate attempts or a restart, retain the input and an explicit `idempotencyKey` before creation. Replay using the same input, key, workspace and caller. Do not create a replacement with a new key while the first outcome is unknown. See [operation recovery](https://docs.usestatemachines.com/sdk-api/recovery.md).\n\n## Optional connection check\n\nRun this only when the user asks to verify the connection. It proves the connection and cleanup, not an existing integration's behavior. Save it in the project's examples or test location. Use the existing TypeScript runner and secret loader, or pass that runner through `npx @usestatemachines/cli@0.1.0 run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.0 run -- npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Load details when needed\n\n- **Repeated fixtures or parallel tests:** Read [isolated tests](https://docs.usestatemachines.com/sdk-api/testing.md). Save seeded data with `env.snapshots.create({ name })`, then create each test's environment with `{ snapshotId }`. A snapshot in `saving` cannot be deleted yet. Retain its ID and wait for `ready` or `failed` before cleanup. Delete a reusable snapshot only when the task calls for it.\n- **Another actor, vendor client or SOAP:** Read [credentials](https://docs.usestatemachines.com/environments/credentials.md). `credentials.fetch()` confines requests to the app URL, adds its authentication headers, and never follows redirects. External clients must send a service's `headers` only to its `url` and disable redirects. For Salesforce SOAP, put the actor token in `SessionHeader/sessionId` in the envelope.\n- **Cloudflare Workers:** Pass the key explicitly. Use `{ wait: false }` and keep the environment ID across requests or in the job's state. A request ending does not cancel startup. Follow the worker's background-job lifecycle for polling and cleanup.\n- **Long runs:** Read `sm.me().limits` when non-null. The environment time limit covers starting and running. Use a supported `timeLimitMinutes` when the task needs it.\n\n## Recover without changing the test's meaning\n\nManagement failures throw SDK errors. App HTTP failures are returned as `Response` objects. Use `instanceof` with the SDK error classes. Native `credentials.fetch()` never retries. Read the State Machines error code in `error.code` and distinguish it from an app's own error.\n\n| Failure | Next action |\n| --- | --- |\n| `invalid_request` | Read `err.fields` and the installed method signature. |\n| `version_unavailable` | Discover the app ID and available versions. Stop if the required version is unavailable. |\n| `environment_limit_reached` | Clean up only this task's known leftovers, or report the capacity blocker. |\n| `EnvironmentFailedError` | Read `err.environment.failure` and clean up the owned environment. |\n| `WaitTimeoutError` or abort | Use the retained environment ID. If older code waited inside `create`, a non-null `WaitTimeoutError.resource` carries its ID. If neither an ID nor a replay key is recoverable, report unresolved cleanup. Do not guess from a list. Wait again only if the task should continue. Otherwise delete the owned environment. |\n| Unknown create outcome | Replay the retained input and idempotency key. Do not start another operation with a new key. |\n| `invalid_status` | Read the current resource status before choosing the next call. |\n| `snapshot_in_progress` | Find the saving snapshot for this environment and wait for it before creating another. |\n| `SnapshotFailedError` | Report the failure. Retry only if the task still needs a snapshot and the source environment is running. |\n| App `environment_not_running` | Inspect the environment. Do not silently switch the integration to another target. |\n| App `invalid_setup` or `invalid_services` | The app refused a value of `setup` or `services` after the start. `error.message` starts with its path. Create another environment with a value that the app accepts, and delete the owned one. |\n| App or gateway `503` | For a retryable read, honor `Retry-After`. For a write with an uncertain outcome, inspect stored state or report uncertainty before retrying. |\n| Cleanup failure | Preserve the task result, report the owned resource ID and retry deletion with valid access and a fresh signal. Do not report cleanup as successful. |\n\n## Finish with evidence\n\nLeave the smallest rerunnable test or example. Report the behavior checked, command, assertion result, SDK and app versions, selected actor, resource IDs without secrets, and cleanup outcome. Say when execution was blocked or only typechecking ran. A passing replica check establishes the asserted behavior for that version and actor, not full production compatibility.\n\nFind other guides through https://docs.usestatemachines.com/llms.txt. Read focused pages before the full documentation bundle. This dashboard also serves an agent index at https://app.usestatemachines.com/llms.txt.\n";
5
+ export const quickstart = "import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n";
6
+ export const cliCommand = 'npx @usestatemachines/cli@0.1.0';
@@ -0,0 +1,13 @@
1
+ export declare const agentDestinations: readonly [{
2
+ readonly id: 'claude';
3
+ readonly label: 'Claude Code';
4
+ readonly directory: '.claude';
5
+ readonly path: '.claude/skills/state-machines/SKILL.md';
6
+ readonly documentation: 'https://code.claude.com/docs/en/skills#choose-where-skills-load';
7
+ }, {
8
+ readonly id: 'codex';
9
+ readonly label: 'Codex';
10
+ readonly directory: '.agents';
11
+ readonly path: '.agents/skills/state-machines/SKILL.md';
12
+ readonly documentation: 'https://learn.chatgpt.com/docs/build-skills#where-codex-loads-local-skills';
13
+ }];
@@ -0,0 +1,16 @@
1
+ export const agentDestinations = [
2
+ {
3
+ id: 'claude',
4
+ label: 'Claude Code',
5
+ directory: '.claude',
6
+ path: '.claude/skills/state-machines/SKILL.md',
7
+ documentation: 'https://code.claude.com/docs/en/skills#choose-where-skills-load',
8
+ },
9
+ {
10
+ id: 'codex',
11
+ label: 'Codex',
12
+ directory: '.agents',
13
+ path: '.agents/skills/state-machines/SKILL.md',
14
+ documentation: 'https://learn.chatgpt.com/docs/build-skills#where-codex-loads-local-skills',
15
+ },
16
+ ];
@@ -0,0 +1,62 @@
1
+ import type { RawHttpResponse } from './command.js';
2
+ import type { ApiOrigin } from './context-types.js';
3
+ import { type CliErrorCode } from './errors.js';
4
+ import { parseCreateKey, parseKey, parseKeyList, parseKeyListQuery, parseLoginToken, parseStartedLogin, parseStartLogin, parseTokenList } from './generated/internal.js';
5
+ import type { EffectOptions, Io } from './io-types.js';
6
+ export declare const retryBudgetMs = 30000;
7
+ export type StartLoginInput = ReturnType<typeof parseStartLogin>;
8
+ export type StartedLogin = ReturnType<typeof parseStartedLogin>;
9
+ export type PollResult = ({
10
+ readonly kind: 'approved';
11
+ } & ReturnType<typeof parseLoginToken>) | {
12
+ readonly kind: 'pending' | 'slow-down';
13
+ readonly interval: number;
14
+ } | {
15
+ readonly kind: 'denied' | 'expired';
16
+ };
17
+ export type CreatedKey = {
18
+ readonly kind: 'created';
19
+ readonly apiKey: ReturnType<typeof parseKey>;
20
+ readonly secret: string;
21
+ } | {
22
+ readonly kind: 'replayed-without-secret';
23
+ readonly apiKey: ReturnType<typeof parseKey>;
24
+ };
25
+ export interface AnonymousApi {
26
+ start(input: StartLoginInput, options?: EffectOptions): Promise<StartedLogin>;
27
+ poll(deviceCode: string, options?: EffectOptions): Promise<PollResult>;
28
+ readiness(options?: EffectOptions): Promise<{
29
+ ready: boolean;
30
+ }>;
31
+ }
32
+ export interface AuthenticatedInternalApi {
33
+ collected(loginId: string, options?: EffectOptions): Promise<void>;
34
+ revokeCurrent(options?: EffectOptions): Promise<'revoked' | 'already-invalid'>;
35
+ listTokens(query?: {
36
+ cursor?: string;
37
+ limit?: number;
38
+ }, options?: EffectOptions): Promise<ReturnType<typeof parseTokenList>>;
39
+ listKeys(query: ReturnType<typeof parseKeyListQuery>, options?: EffectOptions): Promise<ReturnType<typeof parseKeyList>>;
40
+ createKey(input: ReturnType<typeof parseCreateKey>, idempotencyKey: string, options?: EffectOptions): Promise<CreatedKey>;
41
+ revokeKey(id: string, options?: EffectOptions): Promise<ReturnType<typeof parseKey>>;
42
+ raw(input: {
43
+ method: string;
44
+ path: string;
45
+ data: string | null;
46
+ }, options?: EffectOptions): Promise<RawHttpResponse>;
47
+ }
48
+ export interface ApiTransport {
49
+ readonly io: Io;
50
+ readonly fetch: typeof fetch;
51
+ readonly origin: ApiOrigin;
52
+ readonly options?: EffectOptions;
53
+ }
54
+ export declare function validateRawPath(path: string): string;
55
+ export declare function checkEffect(io: Io, options: EffectOptions, expired?: CliErrorCode): void;
56
+ export declare function withinDeadline<Value>(io: Io, options: EffectOptions, action: (signal: AbortSignal) => Promise<Value>, expired?: CliErrorCode): Promise<Value>;
57
+ export declare function bufferResponse(response: Response): Promise<Response>;
58
+ export declare function createSdkFetch(transport: ApiTransport & {
59
+ options: EffectOptions;
60
+ }): typeof fetch;
61
+ export declare function createAnonymousApi(transport: ApiTransport): AnonymousApi;
62
+ export declare function createAuthenticatedApi(transport: ApiTransport, token: string): AuthenticatedInternalApi;
@@ -0,0 +1,348 @@
1
+ import { StateMachinesError } from '@usestatemachines/sdk';
2
+ import { z } from 'zod';
3
+ import { CliError } from './errors.js';
4
+ import { parseApiError, parseCollected, parseCreatedKey, parseCreateKey, parseKey, parseKeyList, parseKeyListQuery, parseLoginToken, parsePollError, parseStartedLogin, parseStartLogin, parseTokenList, } from './generated/internal.js';
5
+ import { retryPolicy } from './generated/retry.js';
6
+ export const retryBudgetMs = 30_000;
7
+ export function validateRawPath(path) {
8
+ if (!path.startsWith('/v1/') || /[\\\s#]/.test(path)) {
9
+ throw new CliError('cli.path_refused');
10
+ }
11
+ let decoded = path.split('?')[0] ?? '';
12
+ for (let count = 0; count < 8; count++) {
13
+ if (/[\\\s?#]/.test(decoded) ||
14
+ decoded.includes('//') ||
15
+ decoded.split('/').some((part) => part === '.' || part === '..')) {
16
+ throw new CliError('cli.path_refused');
17
+ }
18
+ if (/^\/v1\/(?:cli(?:\/|$)|api-keys(?:\/|$))/i.test(decoded)) {
19
+ throw new CliError('cli.path_refused');
20
+ }
21
+ let next;
22
+ try {
23
+ next = decodeURIComponent(decoded);
24
+ }
25
+ catch {
26
+ throw new CliError('cli.path_refused');
27
+ }
28
+ if (next === decoded) {
29
+ return path;
30
+ }
31
+ decoded = next;
32
+ }
33
+ throw new CliError('cli.path_refused');
34
+ }
35
+ export function checkEffect(io, options, expired = 'cli.wait_timeout') {
36
+ if (options.signal.aborted) {
37
+ throw new CliError('cli.cancelled');
38
+ }
39
+ if (options.deadline !== null && io.now() >= options.deadline) {
40
+ throw new CliError(expired);
41
+ }
42
+ }
43
+ export async function withinDeadline(io, options, action, expired = 'cli.wait_timeout') {
44
+ checkEffect(io, options, expired);
45
+ const controller = new AbortController();
46
+ const signal = AbortSignal.any([controller.signal, options.signal]);
47
+ const timer = new AbortController();
48
+ let deadline = null;
49
+ if (options.deadline !== null) {
50
+ deadline = io
51
+ .sleep(Math.max(0, options.deadline - io.now()), {
52
+ signal: timer.signal,
53
+ deadline: null,
54
+ })
55
+ .then(() => {
56
+ controller.abort();
57
+ throw new CliError(expired);
58
+ });
59
+ }
60
+ try {
61
+ const operation = action(signal);
62
+ return await (deadline === null
63
+ ? operation
64
+ : Promise.race([operation, deadline]));
65
+ }
66
+ finally {
67
+ timer.abort();
68
+ }
69
+ }
70
+ export async function bufferResponse(response) {
71
+ const bytes = await response.arrayBuffer();
72
+ return new Response(bytes.byteLength === 0 ? null : bytes, {
73
+ status: response.status,
74
+ statusText: response.statusText,
75
+ headers: response.headers,
76
+ });
77
+ }
78
+ async function decode(response) {
79
+ try {
80
+ return await response.json();
81
+ }
82
+ catch {
83
+ throw new CliError('cli.invalid_response');
84
+ }
85
+ }
86
+ function parsed(parse, input) {
87
+ try {
88
+ return parse(input);
89
+ }
90
+ catch {
91
+ throw new CliError('cli.invalid_response');
92
+ }
93
+ }
94
+ function argument(parse, input) {
95
+ try {
96
+ return parse(input);
97
+ }
98
+ catch {
99
+ throw new CliError('cli.invalid_arguments');
100
+ }
101
+ }
102
+ async function apiFailure(response, body) {
103
+ let detail;
104
+ try {
105
+ detail = parseApiError(body === undefined ? await response.json() : body);
106
+ }
107
+ catch {
108
+ throw new StateMachinesError({
109
+ message: 'The API returned an unexpected response.',
110
+ status: response.status,
111
+ code: null,
112
+ requestId: response.headers.get('x-request-id'),
113
+ fields: null,
114
+ retryAfterMs: null,
115
+ });
116
+ }
117
+ const retry = response.headers.get('retry-after');
118
+ throw new StateMachinesError({
119
+ ...detail,
120
+ status: response.status,
121
+ retryAfterMs: retry !== null && /^\d+$/.test(retry) ? Number(retry) * 1000 : null,
122
+ });
123
+ }
124
+ function queryString(query) {
125
+ const params = new URLSearchParams();
126
+ for (const [key, value] of Object.entries(query)) {
127
+ if (value !== undefined) {
128
+ params.set(key, String(value));
129
+ }
130
+ }
131
+ return params.size === 0 ? '' : `?${params}`;
132
+ }
133
+ function requester(transport, token) {
134
+ const { io, origin } = transport;
135
+ const defaults = transport.options ?? { signal: io.signal, deadline: null };
136
+ return async (path, input, options = defaults) => {
137
+ const started = io.now();
138
+ const budgeted = started + retryBudgetMs < (options.deadline ?? Infinity);
139
+ const effects = budgeted
140
+ ? { ...options, deadline: started + retryBudgetMs }
141
+ : options;
142
+ const expired = budgeted ? 'cli.network' : 'cli.wait_timeout';
143
+ let delay = retryPolicy.initialInterval;
144
+ while (true) {
145
+ checkEffect(io, effects, expired);
146
+ let response;
147
+ try {
148
+ response = await withinDeadline(io, effects, async (signal) => {
149
+ const headers = new Headers(input.headers);
150
+ if (!headers.has('accept')) {
151
+ headers.set('accept', 'application/json');
152
+ }
153
+ if (token !== null) {
154
+ headers.set('authorization', `Bearer ${token}`);
155
+ }
156
+ if (input.data !== undefined) {
157
+ headers.set('content-type', 'application/json');
158
+ }
159
+ const response = await transport.fetch(`${origin}${path}`, {
160
+ method: input.method,
161
+ headers,
162
+ redirect: 'manual',
163
+ signal,
164
+ ...(input.data === undefined
165
+ ? {}
166
+ : {
167
+ body: typeof input.data === 'string'
168
+ ? input.data
169
+ : JSON.stringify(input.data),
170
+ }),
171
+ });
172
+ return bufferResponse(response);
173
+ }, expired);
174
+ }
175
+ catch (error) {
176
+ checkEffect(io, effects, expired);
177
+ if (error instanceof CliError) {
178
+ throw error;
179
+ }
180
+ if (!input.retry ||
181
+ !retryPolicy.retryConnectionErrors ||
182
+ io.now() - started + delay >= retryBudgetMs) {
183
+ throw new CliError('cli.network');
184
+ }
185
+ await io.sleep(delay, effects);
186
+ delay = Math.min(retryPolicy.maxInterval, delay * retryPolicy.exponent);
187
+ continue;
188
+ }
189
+ if (!input.retry ||
190
+ !retryPolicy.statusCodes.includes(response.status) ||
191
+ io.now() - started + delay >= retryBudgetMs) {
192
+ return response;
193
+ }
194
+ await response.body?.cancel();
195
+ await io.sleep(delay, effects);
196
+ delay = Math.min(retryPolicy.maxInterval, delay * retryPolicy.exponent);
197
+ }
198
+ };
199
+ }
200
+ export function createSdkFetch(transport) {
201
+ const request = requester(transport, null);
202
+ return async (resource, init) => {
203
+ const original = new Request(resource, init);
204
+ const url = new URL(original.url);
205
+ if (url.origin !== transport.origin) {
206
+ return transport.fetch(new Request(original, { redirect: 'manual' }));
207
+ }
208
+ const response = await request(`${url.pathname}${url.search}`, {
209
+ method: original.method,
210
+ headers: original.headers,
211
+ ...(original.body === null ? {} : { data: await original.text() }),
212
+ retry: true,
213
+ }, {
214
+ ...transport.options,
215
+ signal: AbortSignal.any([transport.options.signal, original.signal]),
216
+ });
217
+ if (retryPolicy.statusCodes.includes(response.status)) {
218
+ return apiFailure(response);
219
+ }
220
+ return response;
221
+ };
222
+ }
223
+ export function createAnonymousApi(transport) {
224
+ const request = requester(transport, null);
225
+ return {
226
+ async start(input, options) {
227
+ const body = parseStartLogin(input);
228
+ const response = await request('/v1/cli/logins', { method: 'POST', data: body, retry: false }, options);
229
+ if (!response.ok) {
230
+ return apiFailure(response);
231
+ }
232
+ const started = parsed(parseStartedLogin, await decode(response));
233
+ const verification = new URL(started.verificationUrl);
234
+ if (!/^[A-Za-z0-9_-]{43}$/.test(started.deviceCode) ||
235
+ started.expiresIn <= 0 ||
236
+ started.interval <= 0 ||
237
+ verification.username !== '' ||
238
+ verification.password !== '' ||
239
+ !(verification.protocol === 'https:' ||
240
+ (verification.protocol === 'http:' &&
241
+ ['localhost', '127.0.0.1'].includes(verification.hostname)))) {
242
+ throw new CliError('cli.invalid_response');
243
+ }
244
+ return started;
245
+ },
246
+ async poll(deviceCode, options) {
247
+ const response = await request('/v1/cli/logins/token', { method: 'POST', data: { deviceCode }, retry: true }, options);
248
+ if (response.status === 400) {
249
+ const body = await decode(response);
250
+ let outcome;
251
+ try {
252
+ outcome = parsePollError(body);
253
+ }
254
+ catch {
255
+ return apiFailure(response, body);
256
+ }
257
+ if ((outcome.error === 'authorization_pending' ||
258
+ outcome.error === 'slow_down') &&
259
+ outcome.interval <= 0) {
260
+ throw new CliError('cli.invalid_response');
261
+ }
262
+ switch (outcome.error) {
263
+ case 'authorization_pending':
264
+ return { kind: 'pending', interval: outcome.interval };
265
+ case 'slow_down':
266
+ return { kind: 'slow-down', interval: outcome.interval };
267
+ case 'access_denied':
268
+ return { kind: 'denied' };
269
+ case 'expired_token':
270
+ return { kind: 'expired' };
271
+ }
272
+ }
273
+ if (!response.ok) {
274
+ return apiFailure(response);
275
+ }
276
+ return {
277
+ kind: 'approved',
278
+ ...parsed(parseLoginToken, await decode(response)),
279
+ };
280
+ },
281
+ async readiness(options) {
282
+ const response = await request('/_state/ready', { method: 'GET', retry: false }, options);
283
+ if (!response.ok) {
284
+ return { ready: false };
285
+ }
286
+ return parsed((value) => z.object({ ready: z.boolean() }).parse(value), await decode(response));
287
+ },
288
+ };
289
+ }
290
+ export function createAuthenticatedApi(transport, token) {
291
+ const request = requester(transport, token);
292
+ async function json(path, input, parse, options) {
293
+ const response = await request(path, { retry: true, ...input }, options);
294
+ if (!response.ok) {
295
+ return apiFailure(response);
296
+ }
297
+ return parsed(parse, await decode(response));
298
+ }
299
+ return {
300
+ async collected(loginId, options) {
301
+ const result = await json(`/v1/cli/logins/${encodeURIComponent(loginId)}/collected`, { method: 'POST', retry: false }, parseCollected, options);
302
+ if (result.loginId !== loginId) {
303
+ throw new CliError('cli.invalid_response');
304
+ }
305
+ },
306
+ async revokeCurrent(options) {
307
+ const response = await request('/v1/cli/tokens/current', { method: 'DELETE', retry: false }, options);
308
+ if (response.status === 401) {
309
+ return 'already-invalid';
310
+ }
311
+ if (!response.ok) {
312
+ return apiFailure(response);
313
+ }
314
+ return 'revoked';
315
+ },
316
+ listTokens: (query = {}, options) => json(`/v1/cli/tokens${queryString(query)}`, { method: 'GET' }, parseTokenList, options),
317
+ listKeys: async (query, options) => json(`/v1/api-keys${queryString(argument(parseKeyListQuery, query))}`, { method: 'GET' }, parseKeyList, options),
318
+ async createKey(input, idempotencyKey, options) {
319
+ const result = await json('/v1/api-keys', {
320
+ method: 'POST',
321
+ data: parseCreateKey(input),
322
+ headers: { 'idempotency-key': idempotencyKey },
323
+ }, parseCreatedKey, options);
324
+ return result.secret === undefined
325
+ ? { kind: 'replayed-without-secret', apiKey: result.apiKey }
326
+ : { kind: 'created', apiKey: result.apiKey, secret: result.secret };
327
+ },
328
+ revokeKey: (id, options) => json(`/v1/api-keys/${encodeURIComponent(id)}`, { method: 'DELETE', retry: false }, parseKey, options),
329
+ async raw(input, options) {
330
+ const path = validateRawPath(input.path);
331
+ const response = await request(path, {
332
+ method: input.method,
333
+ ...(input.data === null ? {} : { data: input.data }),
334
+ retry: false,
335
+ }, options);
336
+ return {
337
+ status: response.status,
338
+ body: (async function* () {
339
+ if (response.body) {
340
+ for await (const chunk of response.body) {
341
+ yield chunk;
342
+ }
343
+ }
344
+ })(),
345
+ };
346
+ },
347
+ };
348
+ }
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runProcess } from './io.js';
3
+ import { main } from './main.js';
4
+ await runProcess(main);