@usestatemachines/sdk 0.9.1 → 0.10.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 (68) hide show
  1. package/README.md +16 -2
  2. package/agents/index.js +2 -2
  3. package/agents/llms.txt +4 -4
  4. package/esm/extensions/client.d.ts +31 -1
  5. package/esm/extensions/client.js +74 -2
  6. package/esm/extensions/errors.d.ts +7 -0
  7. package/esm/extensions/errors.js +46 -2
  8. package/esm/extensions/index.d.ts +2 -2
  9. package/esm/funcs/imports-complete.d.ts +12 -0
  10. package/esm/funcs/imports-complete.js +93 -0
  11. package/esm/funcs/imports-create.d.ts +12 -0
  12. package/esm/funcs/imports-create.js +89 -0
  13. package/esm/funcs/imports-delete.d.ts +12 -0
  14. package/esm/funcs/imports-delete.js +93 -0
  15. package/esm/funcs/imports-get.d.ts +12 -0
  16. package/esm/funcs/imports-get.js +93 -0
  17. package/esm/funcs/imports-list.d.ts +11 -0
  18. package/esm/funcs/imports-list.js +93 -0
  19. package/esm/lib/config.d.ts +2 -2
  20. package/esm/lib/config.js +2 -2
  21. package/esm/models/absent-reason.d.ts +36 -0
  22. package/esm/models/absent-reason.js +44 -0
  23. package/esm/models/absent-record-source.d.ts +13 -0
  24. package/esm/models/absent-record-source.js +14 -0
  25. package/esm/models/absent-record.d.ts +23 -0
  26. package/esm/models/absent-record.js +18 -0
  27. package/esm/models/create-snapshot-from-environment.d.ts +13 -0
  28. package/esm/models/create-snapshot-from-environment.js +12 -0
  29. package/esm/models/create-snapshot-from-import.d.ts +16 -0
  30. package/esm/models/create-snapshot-from-import.js +12 -0
  31. package/esm/models/create-snapshot.d.ts +9 -0
  32. package/esm/models/create-snapshot.js +14 -0
  33. package/esm/models/created-import.d.ts +38 -0
  34. package/esm/models/created-import.js +30 -0
  35. package/esm/models/import-problem.d.ts +40 -0
  36. package/esm/models/import-problem.js +28 -0
  37. package/esm/models/import-status.d.ts +13 -0
  38. package/esm/models/import-status.js +14 -0
  39. package/esm/models/import.d.ts +45 -0
  40. package/esm/models/import.js +36 -0
  41. package/esm/models/index.d.ts +12 -0
  42. package/esm/models/index.js +12 -0
  43. package/esm/models/operations/complete-import.d.ts +11 -0
  44. package/esm/models/operations/complete-import.js +11 -0
  45. package/esm/models/operations/create-import.d.ts +36 -0
  46. package/esm/models/operations/create-import.js +26 -0
  47. package/esm/models/operations/create-snapshot.d.ts +3 -14
  48. package/esm/models/operations/create-snapshot.js +2 -9
  49. package/esm/models/operations/delete-import.d.ts +11 -0
  50. package/esm/models/operations/delete-import.js +11 -0
  51. package/esm/models/operations/get-import.d.ts +11 -0
  52. package/esm/models/operations/get-import.js +11 -0
  53. package/esm/models/operations/index.d.ts +5 -0
  54. package/esm/models/operations/index.js +5 -0
  55. package/esm/models/operations/list-imports.d.ts +30 -0
  56. package/esm/models/operations/list-imports.js +25 -0
  57. package/esm/models/snapshot-app-load.d.ts +20 -0
  58. package/esm/models/snapshot-app-load.js +15 -0
  59. package/esm/models/snapshot-failure-union.d.ts +40 -0
  60. package/esm/models/snapshot-failure-union.js +42 -0
  61. package/esm/models/snapshot.d.ts +15 -17
  62. package/esm/models/snapshot.js +6 -17
  63. package/esm/sdk/imports.d.ts +10 -0
  64. package/esm/sdk/imports.js +27 -0
  65. package/esm/sdk/sdk.d.ts +3 -0
  66. package/esm/sdk/sdk.js +5 -0
  67. package/openapi.json +1258 -184
  68. package/package.json +1 -1
package/README.md CHANGED
@@ -68,7 +68,8 @@ dates, and API key kind. Expiry dates are `Date` objects when present, or `null`
68
68
  | `sm.apps` | `list(query?)`, `versions(appId, query?)` |
69
69
  | `sm.workspaces` | `list(query?)`, `get(id)` |
70
70
  | `sm.environments` | `create(input, options?)`, `list(query?)`, `get(id)`, `update(id, { name?, labels? })`, `delete(id)`, `wait(id, { status })`, `connect(id, appName, { actorId?, services? }?)` |
71
- | `sm.snapshots` | `create({ environmentId, name? }, options?)`, `list(query?)`, `get(id)`, `update(id, { name })`, `delete(id)`, `wait(id, { status })` |
71
+ | `sm.snapshots` | `create({ environmentId, name? } \| { importId, name? }, options?)`, `list(query?)`, `get(id)`, `update(id, { name })`, `delete(id)`, `wait(id, { status })` |
72
+ | `sm.imports` | `upload(zip, options?)`, `list(query?)`, `get(id)`, `delete(id)` |
72
73
  | `sm.requests` | `list(query)`, `get(id)`, `stats(query)`, `body(id, 'request' \| 'response')` |
73
74
  | `sm.auditEvents` | `list(query?)` |
74
75
 
@@ -174,6 +175,19 @@ delete during the snapshot fails it with `failure.code: 'interrupted'`. One snap
174
175
  `saving` per environment at a time. `sm.snapshots.delete(id)` deletes a `ready` or `failed`
175
176
  snapshot.
176
177
 
178
+ ```ts
179
+ const imported = await sm.imports.upload(await readFile('q3-export.zip'));
180
+ const built = await sm.snapshots.create({ importId: imported.id });
181
+ const copy = await sm.environments.create({ snapshotId: built.id });
182
+ ```
183
+
184
+ A snapshot from a `ready` import holds every app of the import, each on its default version,
185
+ with empty setup and services. Each app's `load` counts the records of the import that did not
186
+ load, as `absentCount`, and lists the first of them, as `absent`. An app that refuses the import
187
+ fails the snapshot with `failure.code: 'invalid_import'`, and `SnapshotFailedError.problems`
188
+ lists its problems. An environment from the snapshot does not load the import, so it starts
189
+ after the import is deleted.
190
+
177
191
  ## Waiting
178
192
 
179
193
  | Method | Waits for | Throws |
@@ -209,7 +223,7 @@ response body.
209
223
  | --- | --- | --- |
210
224
  | `StateMachinesError` | any failed call | `code`, `status`, `requestId`, `fields`, `retryAfterMs` |
211
225
  | `EnvironmentFailedError` (a `StateMachinesError`) | a waited environment failed | `environment` |
212
- | `SnapshotFailedError` (a `StateMachinesError`) | a waited snapshot failed | `snapshot` |
226
+ | `SnapshotFailedError` (a `StateMachinesError`) | a waited snapshot failed | `snapshot` and `problems`. `problems` is empty unless an app refused the import that the snapshot was built from. |
213
227
  | `UnexpectedStatusError` | a waited resource cannot reach the status without another call | `resource`, `status` |
214
228
  | `WaitTimeoutError` | a wait passed `timeoutMs` | `resource` (the last read), `timeoutMs` |
215
229
 
package/agents/index.js CHANGED
@@ -4,7 +4,7 @@ export const prompt =
4
4
  "Set up State Machines in this existing repository so I can use disposable app environments with my coding agent.\n\n1. Read the repository instructions and inspect the existing State Machines workspace link and agent skill. Keep the repository's structure and conventions. Check that Node.js meets the CLI's runtime requirement. Use the pinned npx command below. A global CLI installation is not required.\n2. Run `npx @usestatemachines/cli@0.1.1 whoami --json`. If the project already has a `STATEMACHINES_API_KEY` loader, run the check through that loader without reading or displaying the secret. Use the same credential loader, CLI profile and API origin for every setup command below, including workspace discovery and init. Reuse valid access and confirm the returned account and organization match my task. If the existing API key or CLI profile works, skip sign-in and reuse it for setup. Do not create a replacement API key. Report an access denial or origin mismatch instead of changing accounts or permissions.\n3. Only when no project API key is configured and the access check reports a missing, expired or revoked CLI credential, run `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. Show me the returned verification URL and code. Wait for my approval before resuming the same login with `npx @usestatemachines/cli@0.1.1 login --resume --json`, using the same profile. If a login is already pending, resume it after approval instead of starting another. If the request expires, offer a new login. Never ask me to paste a credential into chat, print it or commit it.\n If a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\n4. Run `npx @usestatemachines/cli@0.1.1 init --agent <this-agent> --yes`, choosing `claude` for Claude Code or `codex` for Codex. Reuse the repository's existing workspace link. If the CLI needs a workspace, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask me which to use when more than one is available, then pass `--workspace <workspace-id>` to init. Do not replace a different workspace link or a customized skill without my approval. Read the installed skill and use its pinned npx commands for later work.\n5. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Do not add `--sdk`, `--quickstart` or `--env` to init unless I ask for those changes.\n6. Report where the skill was installed, which workspace is linked, and whether the agent needs to reload it. Setup alone does not verify an integration. Ask: \"What would you like to run or test?\" Wait for my answer before making further changes.\n\nIf this agent is not Claude Code or Codex but can run commands and has `STATEMACHINES_API_KEY`, download https://app.usestatemachines.com/skill.md itself with `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\"`. Never print the key. If this agent cannot fetch the file with that key, ask me to download https://app.usestatemachines.com/skill.md from my signed-in browser and provide the file. Do not request session cookies or credentials. Install that file in the agent's supported project-local skills directory, preserving any customized skill. If persistent skills are unsupported, read the file for this session and explain the limitation. Report setup as incomplete if the file is unavailable.\n";
5
5
 
6
6
  export const llmsTxt =
7
- "# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, Linear and Box, 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. Keep the same credential loader, CLI profile and API origin across setup commands. Otherwise, run `npx @usestatemachines/cli@0.1.1 whoami --json`. If it succeeds, confirm the account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, start `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. 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.1 login --resume --json` with the same profile to finish that attempt. Resume an existing pending login after approval instead of creating another. Report access denial or an API origin mismatch without changing accounts or permissions.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nFor `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.1 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.1`. 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- App version: `sm.apps.versions(appId)` lists an app's versions. Read the default one before you use the app: each service has a `visibility`, `limitations`, a `prompt` and, for MCP, `servers` with their `tools`. `actors` lists the app's users with `id`, `name` and `summary`.\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`. It throws when the credentials list no `api` service, as for Linear, whose clients call its `mcp` service. `crm.service('mcp').server(name)` returns one MCP server's `url` and `headers` for an MCP client. On an environment created with `tokenInUrl: true`, a Salesforce or Box MCP request without `Authorization` acts as the default actor. Linear refuses an MCP request without `Authorization`, so a Linear MCP client always sends the `mcp` service's headers. 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. On a `tokenInUrl` environment, each service and MCP server `url` carries the token and is a secret too.\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| `unauthenticated` | 401 | The key is missing, expired or revoked. |\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| `name_taken`, `last_owner`, `last_workspace`, `version_in_use`, `ui_disabled` | 409 | A workspace, member, version or UI session call conflicts with current state. Read `message`. |\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| `rate_limited` | 429 | Wait `retryAfterMs` when it is set, then retry. |\n| `internal_error` | 500 | Report `requestId`. |\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.1 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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://app.usestatemachines.com/docs): guides, concepts and reference ([llms.txt](https://app.usestatemachines.com/docs/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://app.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\nFetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" https://app.usestatemachines.com/docs/sdk-api/client.md`. Never print the key.\n";
7
+ "# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, Linear and Box, 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. Keep the same credential loader, CLI profile and API origin across setup commands. Otherwise, run `npx @usestatemachines/cli@0.1.1 whoami --json`. If it succeeds, confirm the account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, start `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. 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.1 login --resume --json` with the same profile to finish that attempt. Resume an existing pending login after approval instead of creating another. Report access denial or an API origin mismatch without changing accounts or permissions.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nFor `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.1 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.1`. 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- App version: `sm.apps.versions(appId)` lists an app's versions. Read the default one before you use the app: each service has a `visibility`, `limitations`, a `prompt` and, for MCP, `servers` with their `tools`. `actors` lists the app's users with `id`, `name` and `summary`.\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`. It throws when the credentials list no `api` service, as for Linear, whose clients call its `mcp` service. `crm.service('mcp').server(name)` returns one MCP server's `url` and `headers` for an MCP client. On an environment created with `tokenInUrl: true`, a Salesforce or Box MCP request without `Authorization` acts as the default actor. Linear refuses an MCP request without `Authorization`, so a Linear MCP client always sends the `mcp` service's headers. 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. On a `tokenInUrl` environment, each service and MCP server `url` carries the token and is a secret too.\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, or of an import. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.snapshots.create({ importId })` builds one from a `ready` import, and each app's `load` counts the records that did not load and lists the first of them. `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`, `internal_error` or `invalid_import`. For `invalid_import`, an app refused the import that the snapshot was built from: `failure.appName` names the app, and `failure.problems` lists each problem.\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, with the problems of a refused import in `problems`, 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| `unauthenticated` | 401 | The key is missing, expired or revoked. |\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. A snapshot needs a running environment or a `ready` import. |\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| `name_taken`, `last_owner`, `last_workspace`, `version_in_use`, `ui_disabled` | 409 | A workspace, member, version or UI session call conflicts with current state. Read `message`. |\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| `rate_limited` | 429 | Wait `retryAfterMs` when it is set, then retry. |\n| `internal_error` | 500 | Report `requestId`. |\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.1 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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://app.usestatemachines.com/docs): guides, concepts and reference ([llms.txt](https://app.usestatemachines.com/docs/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://app.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\nFetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" https://app.usestatemachines.com/docs/sdk-api/client.md`. Never print the key.\n";
8
8
 
9
9
  export const skill =
10
10
  "---\nname: state-machines\ndescription: Use when setting up State Machines or running code, integration tests, MCP clients, or API experiments against disposable replicas of SaaS apps such as Salesforce, Linear and Box. Applies to @usestatemachines/sdk and STATEMACHINES_API_KEY, including environment creation, actors, MCP servers, seeding, 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 project 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. Keep the same credential loader, CLI profile and API origin across setup commands. 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.1 whoami --json`. Confirm the returned account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, complete this login:\n\n1. Run `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account.\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.1 login --resume --json` with the same profile used to start the login. Resume that attempt instead of starting another login. If it expired, offer a new login.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nIf a command returns `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@0.1.1 run -- <command>`. The child receives a workspace key. The CLI keeps the credential out of its output.\n\nIf access is denied, the API origin differs, 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. On a `tokenInUrl` environment, every service and MCP server `url` carries the token, so never print, log or commit those URLs either. Use synthetic test data.\n\n## Read the app before you use it\n\nApply the rest of this skill once the user has chosen a task. `sm.apps.list()` returns app IDs and each app's `defaultVersionId`. Every list returns `{ data, nextCursor }`. Follow cursors until you find the entry or `nextCursor` is null.\n\nRead the app's default version from `sm.apps.versions(appId)` before you write code. It is the current guidance for that app. Each of its `services` has an `id`, a `visibility`, `limitations` and a `prompt`, and a service that serves MCP lists its `servers` with their `tools`. Its `actors` are the app's users, each with an `id`, a `name` and a `summary`. Check the `limitations` against the behavior under test, as [known differences](https://app.usestatemachines.com/docs/apps/known-differences.md) does for Salesforce. A replica does not import a customer's data or run arbitrary customer automation.\n\n- Salesforce: the `api` service serves REST, Bulk API 2.0 and SOAP. Its `mcp` service is `preview`.\n- Box: the `api` service serves the Box Platform API, uploads and OAuth. Its `mcp` service is `preview`.\n- Linear: clients call the `mcp` service and its MCP server `linear`. Linear lists no `api` service. Its `ui` service is `preview`.\n\n## Create and connect\n\nCreate only the apps the task needs. A string such as `'linear'` is both the app ID and the app's name in the environment. Use `{ appId, name, setup, services }` to choose a name, run two copies of one app, pass `setup`, or configure a service. For example, `services` sets which MCP servers and tools the `mcp` service serves. Later calls take the name. Set `tokenInUrl: true` only for a client that cannot send headers.\n\n`env.connect(name)` acts as the app's default actor and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user, pass an `actorId` from the `actors` of the exact version that `env.apps` names for the app. Never use a role label, a workspace member ID, or the first version in a list.\n\n- `credentials.fetch(path)` calls the `api` service with its headers and never follows redirects. It throws when the credentials list no `api` service, as for Linear.\n- For MCP, `credentials.service('mcp').servers` lists the MCP servers, and `.server(name)` returns one server's `url` and `headers` to give the MCP client.\n- An external client must send a service's `headers` only to that service's `url`, with redirects off. For Salesforce SOAP, put the actor token in `SessionHeader/sessionId`. See [credentials](https://app.usestatemachines.com/docs/environments/credentials.md).\n- On a `tokenInUrl` environment, a Salesforce or Box MCP request without an `Authorization` header acts as the default actor. To act as `actorId`, send the service's headers. Linear refuses an MCP request without them, so a Linear MCP client always sends the `mcp` service's headers.\n\nPoint the existing integration's test transport at these URLs and credentials. If that needs a broader change, explain it before you expand the task.\n\n## Seed your own data\n\nCreate the data a test reads before the test runs. Write it through the app's own API or MCP tools as the actor that owns it: Salesforce REST, composite or Bulk API 2.0, Linear MCP create tools, or Box uploads. A Linear workspace starts with one team and no issues. Use `setup` only for identity and configuration. To reuse seeded data, save it with `env.snapshots.create({ name })`, then create each test's environment from `{ snapshotId }`. See [isolated tests](https://app.usestatemachines.com/docs/sdk-api/testing.md).\n\n## Verify the result\n\nAssert the expected status and 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. A successful standalone SDK request does not prove that the integration used the replica. Check its calls with `sm.requests.list({ environmentId })`.\n\n## Own the full lifecycle\n\nCreate with `{ wait: false }` to keep the accepted environment ID. Enter `try` immediately, then wait for `running`, connect and run the check inside it. Delete in `finally`, also after a startup failure, a timeout or a failed assertion. An aborted wait does not cancel the work that the API accepted, so clean up with a fresh, un-aborted signal. Keep both verification and cleanup errors, and report the environment ID if deletion fails.\n\nDelete only resources created for this task, never unrelated environments or a user-supplied snapshot. A snapshot in `saving` cannot be deleted yet. Keep its ID and wait for `ready` or `failed` first. In Cloudflare Workers, pass the key explicitly and keep the environment ID in the job's state. A request ending does not cancel startup.\n\nThe SDK retries management connection errors and `502`, `503` and `504` with one idempotency key per create call. To recover across attempts or a restart, keep the input and an explicit `idempotencyKey` before creation. Replay with 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://app.usestatemachines.com/docs/sdk-api/recovery.md).\n\nWhen `sm.me().limits` is non-null, it gives the cap on concurrent environments and the default and maximum `timeLimitMinutes`. The time limit covers starting and running.\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.1 run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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## 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. Read the State Machines error code in `error.code` and tell it apart from an app's own error.\n\n| Failure | Next action |\n| --- | --- |\n| `unauthenticated` | The key is missing, expired or revoked. Fix the credential in the process that runs the task. |\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.code`: `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. Clean up the owned environment. |\n| `WaitTimeoutError` or abort | Use the kept environment ID. A non-null `WaitTimeoutError.resource` also carries it. If neither an ID nor a replay key is available, report unresolved cleanup. Do not guess from a list. |\n| Unknown create outcome | Replay the kept input and idempotency key. Do not start another operation with a new key. |\n| `invalid_status` | Read the current resource status before you choose the next call. |\n| `snapshot_in_progress` | Wait for this environment's saving snapshot before you create 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`. `error.message` starts with its path. Create another environment with an accepted value, and delete the owned one. |\n| App or gateway `503` | For a read, honor `Retry-After`. For a write with an uncertain outcome, inspect stored state or report the uncertainty before you retry. |\n| Cleanup failure | Keep the task result, report the owned resource ID and retry deletion with 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://app.usestatemachines.com/docs/llms.txt. Read focused pages before the full documentation bundle. This dashboard also serves an agent index at https://app.usestatemachines.com/llms.txt. Fetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" https://app.usestatemachines.com/docs/sdk-api/client.md`. Never print the key.\n";
@@ -18,7 +18,7 @@ export const templates = Object.freeze({
18
18
  prompt:
19
19
  "Set up State Machines in this existing repository so I can use disposable app environments with my coding agent.\n\n1. Read the repository instructions and inspect the existing State Machines workspace link and agent skill. Keep the repository's structure and conventions. Check that Node.js meets the CLI's runtime requirement. Use the pinned npx command below. A global CLI installation is not required.\n2. Run `npx @usestatemachines/cli@0.1.1 whoami --json`. If the project already has a `STATEMACHINES_API_KEY` loader, run the check through that loader without reading or displaying the secret. Use the same credential loader, CLI profile and API origin for every setup command below, including workspace discovery and init. Reuse valid access and confirm the returned account and organization match my task. If the existing API key or CLI profile works, skip sign-in and reuse it for setup. Do not create a replacement API key. Report an access denial or origin mismatch instead of changing accounts or permissions.\n3. Only when no project API key is configured and the access check reports a missing, expired or revoked CLI credential, run `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. Show me the returned verification URL and code. Wait for my approval before resuming the same login with `npx @usestatemachines/cli@0.1.1 login --resume --json`, using the same profile. If a login is already pending, resume it after approval instead of starting another. If the request expires, offer a new login. Never ask me to paste a credential into chat, print it or commit it.\n If a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\n4. Run `npx @usestatemachines/cli@0.1.1 init --agent <this-agent> --yes`, choosing `claude` for Claude Code or `codex` for Codex. Reuse the repository's existing workspace link. If the CLI needs a workspace, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask me which to use when more than one is available, then pass `--workspace <workspace-id>` to init. Do not replace a different workspace link or a customized skill without my approval. Read the installed skill and use its pinned npx commands for later work.\n5. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Do not add `--sdk`, `--quickstart` or `--env` to init unless I ask for those changes.\n6. Report where the skill was installed, which workspace is linked, and whether the agent needs to reload it. Setup alone does not verify an integration. Ask: \"What would you like to run or test?\" Wait for my answer before making further changes.\n\nIf this agent is not Claude Code or Codex but can run commands and has `STATEMACHINES_API_KEY`, download {{origin}}/skill.md itself with `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\"`. Never print the key. If this agent cannot fetch the file with that key, ask me to download {{origin}}/skill.md from my signed-in browser and provide the file. Do not request session cookies or credentials. Install that file in the agent's supported project-local skills directory, preserving any customized skill. If persistent skills are unsupported, read the file for this session and explain the limitation. Report setup as incomplete if the file is unavailable.\n",
20
20
  llmsTxt:
21
- "# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, Linear and Box, 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. Keep the same credential loader, CLI profile and API origin across setup commands. Otherwise, run `npx @usestatemachines/cli@0.1.1 whoami --json`. If it succeeds, confirm the account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, start `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. 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.1 login --resume --json` with the same profile to finish that attempt. Resume an existing pending login after approval instead of creating another. Report access denial or an API origin mismatch without changing accounts or permissions.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nFor `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.1 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.1`. 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- App version: `sm.apps.versions(appId)` lists an app's versions. Read the default one before you use the app: each service has a `visibility`, `limitations`, a `prompt` and, for MCP, `servers` with their `tools`. `actors` lists the app's users with `id`, `name` and `summary`.\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`. It throws when the credentials list no `api` service, as for Linear, whose clients call its `mcp` service. `crm.service('mcp').server(name)` returns one MCP server's `url` and `headers` for an MCP client. On an environment created with `tokenInUrl: true`, a Salesforce or Box MCP request without `Authorization` acts as the default actor. Linear refuses an MCP request without `Authorization`, so a Linear MCP client always sends the `mcp` service's headers. 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. On a `tokenInUrl` environment, each service and MCP server `url` carries the token and is a secret too.\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| `unauthenticated` | 401 | The key is missing, expired or revoked. |\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| `name_taken`, `last_owner`, `last_workspace`, `version_in_use`, `ui_disabled` | 409 | A workspace, member, version or UI session call conflicts with current state. Read `message`. |\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| `rate_limited` | 429 | Wait `retryAfterMs` when it is set, then retry. |\n| `internal_error` | 500 | Report `requestId`. |\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.1 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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]({{origin}}/docs): guides, concepts and reference ([llms.txt]({{origin}}/docs/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill]({{origin}}/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\nFetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" {{origin}}/docs/sdk-api/client.md`. Never print the key.\n",
21
+ "# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, Linear and Box, 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. Keep the same credential loader, CLI profile and API origin across setup commands. Otherwise, run `npx @usestatemachines/cli@0.1.1 whoami --json`. If it succeeds, confirm the account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, start `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account. 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.1 login --resume --json` with the same profile to finish that attempt. Resume an existing pending login after approval instead of creating another. Report access denial or an API origin mismatch without changing accounts or permissions.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nFor `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.1 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.1`. 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- App version: `sm.apps.versions(appId)` lists an app's versions. Read the default one before you use the app: each service has a `visibility`, `limitations`, a `prompt` and, for MCP, `servers` with their `tools`. `actors` lists the app's users with `id`, `name` and `summary`.\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`. It throws when the credentials list no `api` service, as for Linear, whose clients call its `mcp` service. `crm.service('mcp').server(name)` returns one MCP server's `url` and `headers` for an MCP client. On an environment created with `tokenInUrl: true`, a Salesforce or Box MCP request without `Authorization` acts as the default actor. Linear refuses an MCP request without `Authorization`, so a Linear MCP client always sends the `mcp` service's headers. 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. On a `tokenInUrl` environment, each service and MCP server `url` carries the token and is a secret too.\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, or of an import. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.snapshots.create({ importId })` builds one from a `ready` import, and each app's `load` counts the records that did not load and lists the first of them. `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`, `internal_error` or `invalid_import`. For `invalid_import`, an app refused the import that the snapshot was built from: `failure.appName` names the app, and `failure.problems` lists each problem.\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, with the problems of a refused import in `problems`, 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| `unauthenticated` | 401 | The key is missing, expired or revoked. |\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. A snapshot needs a running environment or a `ready` import. |\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| `name_taken`, `last_owner`, `last_workspace`, `version_in_use`, `ui_disabled` | 409 | A workspace, member, version or UI session call conflicts with current state. Read `message`. |\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| `rate_limited` | 429 | Wait `retryAfterMs` when it is set, then retry. |\n| `internal_error` | 500 | Report `requestId`. |\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.1 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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]({{origin}}/docs): guides, concepts and reference ([llms.txt]({{origin}}/docs/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill]({{origin}}/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\nFetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" {{origin}}/docs/sdk-api/client.md`. Never print the key.\n",
22
22
  skill:
23
23
  "---\nname: state-machines\ndescription: Use when setting up State Machines or running code, integration tests, MCP clients, or API experiments against disposable replicas of SaaS apps such as Salesforce, Linear and Box. Applies to @usestatemachines/sdk and STATEMACHINES_API_KEY, including environment creation, actors, MCP servers, seeding, 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 project 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. Keep the same credential loader, CLI profile and API origin across setup commands. 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.1 whoami --json`. Confirm the returned account and organization match the task, then use the workspace commands below. If the CLI credential is missing, expired or revoked, complete this login:\n\n1. Run `npx @usestatemachines/cli@0.1.1 login --no-wait --json`. For an expired or revoked saved session, add `--yes` to replace that invalid session in the same profile. Do not replace a valid session for a different account.\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.1 login --resume --json` with the same profile used to start the login. Resume that attempt instead of starting another login. If it expired, offer a new login.\n\nIf a pending login's approval URL or code is unavailable, ask before recovering it. Explain that recovery may finish an already-approved login. After confirmation, run `npx @usestatemachines/cli@0.1.1 login --resume --json --stream` with the same profile and API origin. Keep that process running and show its URL and code. Request approval only for a recognized login. Wait for `signed-in` before continuing setup. Do not start another login or resume process. If streaming output is unavailable, report the blocker without reading credential files.\n\nIf a command returns `cli.not_linked`, run `npx @usestatemachines/cli@0.1.1 workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@0.1.1 link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@0.1.1 run -- <command>`. The child receives a workspace key. The CLI keeps the credential out of its output.\n\nIf access is denied, the API origin differs, 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. On a `tokenInUrl` environment, every service and MCP server `url` carries the token, so never print, log or commit those URLs either. Use synthetic test data.\n\n## Read the app before you use it\n\nApply the rest of this skill once the user has chosen a task. `sm.apps.list()` returns app IDs and each app's `defaultVersionId`. Every list returns `{ data, nextCursor }`. Follow cursors until you find the entry or `nextCursor` is null.\n\nRead the app's default version from `sm.apps.versions(appId)` before you write code. It is the current guidance for that app. Each of its `services` has an `id`, a `visibility`, `limitations` and a `prompt`, and a service that serves MCP lists its `servers` with their `tools`. Its `actors` are the app's users, each with an `id`, a `name` and a `summary`. Check the `limitations` against the behavior under test, as [known differences]({{origin}}/docs/apps/known-differences.md) does for Salesforce. A replica does not import a customer's data or run arbitrary customer automation.\n\n- Salesforce: the `api` service serves REST, Bulk API 2.0 and SOAP. Its `mcp` service is `preview`.\n- Box: the `api` service serves the Box Platform API, uploads and OAuth. Its `mcp` service is `preview`.\n- Linear: clients call the `mcp` service and its MCP server `linear`. Linear lists no `api` service. Its `ui` service is `preview`.\n\n## Create and connect\n\nCreate only the apps the task needs. A string such as `'linear'` is both the app ID and the app's name in the environment. Use `{ appId, name, setup, services }` to choose a name, run two copies of one app, pass `setup`, or configure a service. For example, `services` sets which MCP servers and tools the `mcp` service serves. Later calls take the name. Set `tokenInUrl: true` only for a client that cannot send headers.\n\n`env.connect(name)` acts as the app's default actor and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user, pass an `actorId` from the `actors` of the exact version that `env.apps` names for the app. Never use a role label, a workspace member ID, or the first version in a list.\n\n- `credentials.fetch(path)` calls the `api` service with its headers and never follows redirects. It throws when the credentials list no `api` service, as for Linear.\n- For MCP, `credentials.service('mcp').servers` lists the MCP servers, and `.server(name)` returns one server's `url` and `headers` to give the MCP client.\n- An external client must send a service's `headers` only to that service's `url`, with redirects off. For Salesforce SOAP, put the actor token in `SessionHeader/sessionId`. See [credentials]({{origin}}/docs/environments/credentials.md).\n- On a `tokenInUrl` environment, a Salesforce or Box MCP request without an `Authorization` header acts as the default actor. To act as `actorId`, send the service's headers. Linear refuses an MCP request without them, so a Linear MCP client always sends the `mcp` service's headers.\n\nPoint the existing integration's test transport at these URLs and credentials. If that needs a broader change, explain it before you expand the task.\n\n## Seed your own data\n\nCreate the data a test reads before the test runs. Write it through the app's own API or MCP tools as the actor that owns it: Salesforce REST, composite or Bulk API 2.0, Linear MCP create tools, or Box uploads. A Linear workspace starts with one team and no issues. Use `setup` only for identity and configuration. To reuse seeded data, save it with `env.snapshots.create({ name })`, then create each test's environment from `{ snapshotId }`. See [isolated tests]({{origin}}/docs/sdk-api/testing.md).\n\n## Verify the result\n\nAssert the expected status and 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. A successful standalone SDK request does not prove that the integration used the replica. Check its calls with `sm.requests.list({ environmentId })`.\n\n## Own the full lifecycle\n\nCreate with `{ wait: false }` to keep the accepted environment ID. Enter `try` immediately, then wait for `running`, connect and run the check inside it. Delete in `finally`, also after a startup failure, a timeout or a failed assertion. An aborted wait does not cancel the work that the API accepted, so clean up with a fresh, un-aborted signal. Keep both verification and cleanup errors, and report the environment ID if deletion fails.\n\nDelete only resources created for this task, never unrelated environments or a user-supplied snapshot. A snapshot in `saving` cannot be deleted yet. Keep its ID and wait for `ready` or `failed` first. In Cloudflare Workers, pass the key explicitly and keep the environment ID in the job's state. A request ending does not cancel startup.\n\nThe SDK retries management connection errors and `502`, `503` and `504` with one idempotency key per create call. To recover across attempts or a restart, keep the input and an explicit `idempotencyKey` before creation. Replay with 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]({{origin}}/docs/sdk-api/recovery.md).\n\nWhen `sm.me().limits` is non-null, it gives the cap on concurrent environments and the default and maximum `timeLimitMinutes`. The time limit covers starting and running.\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.1 run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.1 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## 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. Read the State Machines error code in `error.code` and tell it apart from an app's own error.\n\n| Failure | Next action |\n| --- | --- |\n| `unauthenticated` | The key is missing, expired or revoked. Fix the credential in the process that runs the task. |\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.code`: `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. Clean up the owned environment. |\n| `WaitTimeoutError` or abort | Use the kept environment ID. A non-null `WaitTimeoutError.resource` also carries it. If neither an ID nor a replay key is available, report unresolved cleanup. Do not guess from a list. |\n| Unknown create outcome | Replay the kept input and idempotency key. Do not start another operation with a new key. |\n| `invalid_status` | Read the current resource status before you choose the next call. |\n| `snapshot_in_progress` | Wait for this environment's saving snapshot before you create 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`. `error.message` starts with its path. Create another environment with an accepted value, and delete the owned one. |\n| App or gateway `503` | For a read, honor `Retry-After`. For a write with an uncertain outcome, inspect stored state or report the uncertainty before you retry. |\n| Cleanup failure | Keep the task result, report the owned resource ID and retry deletion with 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 {{origin}}/docs/llms.txt. Read focused pages before the full documentation bundle. This dashboard also serves an agent index at {{origin}}/llms.txt. Fetch a docs page as Markdown with the API key in the `Authorization` header, for example `curl -fsS -H \"Authorization: Bearer $STATEMACHINES_API_KEY\" {{origin}}/docs/sdk-api/client.md`. Never print the key.\n",
24
24
  });
package/agents/llms.txt CHANGED
@@ -29,7 +29,7 @@ Prefix these commands with `npx @usestatemachines/cli@0.1.1`. Use `help --json`
29
29
  - App version: `sm.apps.versions(appId)` lists an app's versions. Read the default one before you use the app: each service has a `visibility`, `limitations`, a `prompt` and, for MCP, `servers` with their `tools`. `actors` lists the app's users with `id`, `name` and `summary`.
30
30
  - 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`. It throws when the credentials list no `api` service, as for Linear, whose clients call its `mcp` service. `crm.service('mcp').server(name)` returns one MCP server's `url` and `headers` for an MCP client. On an environment created with `tokenInUrl: true`, a Salesforce or Box MCP request without `Authorization` acts as the default actor. Linear refuses an MCP request without `Authorization`, so a Linear MCP client always sends the `mcp` service's headers. 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. On a `tokenInUrl` environment, each service and MCP server `url` carries the token and is a secret too.
31
31
  - 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`.
32
- - 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`.
32
+ - Snapshot: the saved data of every app of a running environment, taken at one moment, or of an import. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.snapshots.create({ importId })` builds one from a `ready` import, and each app's `load` counts the records that did not load and lists the first of them. `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`.
33
33
  - 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.
34
34
  - YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.
35
35
  - Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.
@@ -39,9 +39,9 @@ Prefix these commands with `npx @usestatemachines/cli@0.1.1`. Use `help --json`
39
39
  Enums are open: handle values you don't recognise.
40
40
 
41
41
  - 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.
42
- - Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.
42
+ - Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted`, `internal_error` or `invalid_import`. For `invalid_import`, an app refused the import that the snapshot was built from: `failure.appName` names the app, and `failure.problems` lists each problem.
43
43
  - `create` throws `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.
44
- - `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.
44
+ - `snapshots.create` throws `SnapshotFailedError` when the snapshot fails, with the problems of a refused import in `problems`, and `UnexpectedStatusError` when it was deleted.
45
45
  - `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.
46
46
 
47
47
  ## Limits
@@ -61,7 +61,7 @@ A failed API call throws `StateMachinesError` with `status`, `code`, `message`,
61
61
  | `unauthenticated` | 401 | The key is missing, expired or revoked. |
62
62
  | `forbidden` | 403 | The key lacks the permission. |
63
63
  | `not_found` | 404 | Check the ID and the workspace. |
64
- | `invalid_status` | 409 | The status does not allow the call. Snapshots need a running environment. |
64
+ | `invalid_status` | 409 | The status does not allow the call. A snapshot needs a running environment or a `ready` import. |
65
65
  | `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |
66
66
  | `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |
67
67
  | `workspace_archived` | 409 | The workspace is archived. |
@@ -1,11 +1,13 @@
1
1
  import type { App } from '../models/app.js';
2
2
  import type { AuditEvent } from '../models/audit-event.js';
3
3
  import type { CreateEnvironment } from '../models/create-environment.js';
4
+ import type { Import } from '../models/import.js';
4
5
  import type { Me } from '../models/me.js';
5
6
  import type { CreateCredentialsRequestBody } from '../models/operations/create-credentials.js';
6
7
  import type { GetRequestStatsRequest } from '../models/operations/get-request-stats.js';
7
8
  import type { ListAuditEventsRequest } from '../models/operations/list-audit-events.js';
8
9
  import type { ListEnvironmentsRequest } from '../models/operations/list-environments.js';
10
+ import type { ListImportsRequest } from '../models/operations/list-imports.js';
9
11
  import type { ListRequestsRequest } from '../models/operations/list-requests.js';
10
12
  import type { ListSnapshotsRequest } from '../models/operations/list-snapshots.js';
11
13
  import type { ListWorkspacesRequest } from '../models/operations/list-workspaces.js';
@@ -42,6 +44,12 @@ export interface CreateEnvironmentOptions extends SignalOptions {
42
44
  idempotencyKey?: string;
43
45
  }
44
46
  export type CreateSnapshotOptions = CreateEnvironmentOptions;
47
+ export interface UploadImportOptions extends SignalOptions {
48
+ /** The import's workspace. Defaults to the client's `workspaceId`; an API key has its own. */
49
+ workspaceId?: string;
50
+ /** A repeat with the same key and the same bytes finds the same import. Defaults to a new UUID. */
51
+ idempotencyKey?: string;
52
+ }
45
53
  /**
46
54
  * The body of the credentials call. `actorId` defaults to the app's default
47
55
  * actor (for Salesforce, the administrator). `services` names more services
@@ -59,6 +67,7 @@ export type PageQuery = {
59
67
  };
60
68
  export type ListEnvironmentsQuery = ListEnvironmentsRequest;
61
69
  export type ListSnapshotsQuery = ListSnapshotsRequest;
70
+ export type ListImportsQuery = ListImportsRequest;
62
71
  export type ListAuditEventsQuery = ListAuditEventsRequest;
63
72
  export type ListWorkspacesQuery = ListWorkspacesRequest;
64
73
  export type ListRequestsQuery = ListRequestsRequest;
@@ -96,10 +105,18 @@ export declare class StateMachines {
96
105
  connect: (environmentId: string, appName: string, options?: ConnectOptions) => Promise<Credentials>;
97
106
  };
98
107
  readonly snapshots: {
99
- /** Creates a snapshot of a running environment and, unless `wait` is false, waits until it is `ready`. */
108
+ /**
109
+ * Creates a snapshot of a running environment, or builds one from a `ready` import,
110
+ * and, unless `wait` is false, waits until it is `ready`. A snapshot from an import
111
+ * takes every app of the import, each on its default version, with empty setup and
112
+ * services. An import that an app refuses throws `SnapshotFailedError` with its problems.
113
+ */
100
114
  create: (input: {
101
115
  environmentId: string;
102
116
  name?: string | null;
117
+ } | {
118
+ importId: string;
119
+ name?: string | null;
103
120
  }, options?: CreateEnvironmentOptions) => Promise<Snapshot>;
104
121
  /** Newest first. Leaves deleted snapshots out unless `status` asks for them. */
105
122
  list: (query?: ListSnapshotsRequest) => Promise<Page<Snapshot>>;
@@ -116,6 +133,19 @@ export declare class StateMachines {
116
133
  */
117
134
  wait: (snapshotId: string, options: WaitOptions<KnownSnapshotStatus>) => Promise<Snapshot>;
118
135
  };
136
+ readonly imports: {
137
+ /**
138
+ * Uploads an import's zip file and resolves with the import as its check left it:
139
+ * `ready`, or `invalid` with its problems. An import that is no longer `uploading` resolves
140
+ * as it is. The zip file goes to the upload URL under `signal` alone, without `attemptTimeoutMs`.
141
+ */
142
+ upload: (zip: Uint8Array<ArrayBufferLike>, options?: UploadImportOptions) => Promise<Import>;
143
+ /** Newest first. Leaves deleted imports out unless `status` asks for them. */
144
+ list: (query?: ListImportsRequest) => Promise<Page<Import>>;
145
+ get: (importId: string) => Promise<Import>;
146
+ /** Removes the import's zip file once no build reads it. Snapshots built from it keep their data. Safe to repeat. */
147
+ delete: (importId: string, options?: SignalOptions) => Promise<Import>;
148
+ };
119
149
  readonly requests: {
120
150
  /** Calls the gateway recorded for one environment, newest first. Recording is best effort. */
121
151
  list: (query: ListRequestsRequest) => Promise<Page<Request>>;
@@ -2,7 +2,7 @@ import { SDK_METADATA } from '../lib/config.js';
2
2
  import { HTTPClient } from '../lib/http.js';
3
3
  import { StateMachines as Generated } from '../sdk/sdk.js';
4
4
  import { bindCredentials } from './credentials.js';
5
- import { CallerAbortedError, toStateMachinesError } from './errors.js';
5
+ import { CallerAbortedError, StateMachinesError, toStateMachinesError, uploadRefused, uploadUnanswered, } from './errors.js';
6
6
  import { linkSignal } from './signal.js';
7
7
  import { environmentAt, poll, snapshotAt, } from './wait.js';
8
8
  export class StateMachines {
@@ -83,7 +83,12 @@ export class StateMachines {
83
83
  connect: (environmentId, appName, options = {}) => this.#connect(environmentId, appName, options),
84
84
  };
85
85
  snapshots = {
86
- /** Creates a snapshot of a running environment and, unless `wait` is false, waits until it is `ready`. */
86
+ /**
87
+ * Creates a snapshot of a running environment, or builds one from a `ready` import,
88
+ * and, unless `wait` is false, waits until it is `ready`. A snapshot from an import
89
+ * takes every app of the import, each on its default version, with empty setup and
90
+ * services. An import that an app refuses throws `SnapshotFailedError` with its problems.
91
+ */
87
92
  create: async (input, options = {}) => {
88
93
  const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
89
94
  const created = await this.#call(options.signal, (call) => this.#sdk.snapshots.create({ idempotencyKey, body: input }, call));
@@ -107,6 +112,36 @@ export class StateMachines {
107
112
  */
108
113
  wait: (snapshotId, options) => poll(snapshotId, (signal) => this.#read(signal, (call) => this.#sdk.snapshots.get({ snapshotId }, call)), snapshotAt(options.status), options),
109
114
  };
115
+ imports = {
116
+ /**
117
+ * Uploads an import's zip file and resolves with the import as its check left it:
118
+ * `ready`, or `invalid` with its problems. An import that is no longer `uploading` resolves
119
+ * as it is. The zip file goes to the upload URL under `signal` alone, without `attemptTimeoutMs`.
120
+ */
121
+ upload: async (zip, options = {}) => {
122
+ const { signal } = options;
123
+ const bytes = unshared(zip);
124
+ const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
125
+ const body = this.#inWorkspace({
126
+ ...(options.workspaceId === undefined
127
+ ? {}
128
+ : { workspaceId: options.workspaceId }),
129
+ sizeBytes: bytes.byteLength,
130
+ digest: await sha256(bytes),
131
+ });
132
+ const created = await this.#call(signal, (call) => this.#sdk.imports.create({ idempotencyKey, body }, call));
133
+ if (created.upload === null) {
134
+ return created.import;
135
+ }
136
+ await this.#send(created.upload, bytes, signal);
137
+ return this.#call(signal, (call) => this.#sdk.imports.complete({ importId: created.import.id }, call));
138
+ },
139
+ /** Newest first. Leaves deleted imports out unless `status` asks for them. */
140
+ list: (query = {}) => this.#call(undefined, (call) => this.#sdk.imports.list(this.#inWorkspace(query), call)),
141
+ get: (importId) => this.#call(undefined, (call) => this.#sdk.imports.get({ importId }, call)),
142
+ /** Removes the import's zip file once no build reads it. Snapshots built from it keep their data. Safe to repeat. */
143
+ delete: (importId, options = {}) => this.#call(options.signal, (call) => this.#sdk.imports.delete({ importId }, call)),
144
+ };
110
145
  requests = {
111
146
  /** Calls the gateway recorded for one environment, newest first. Recording is best effort. */
112
147
  list: (query) => this.#call(undefined, (call) => this.#sdk.requests.list(query, call)),
@@ -137,6 +172,34 @@ export class StateMachines {
137
172
  const credentials = await this.#call(undefined, (call) => this.#sdk.environments.connect({ environmentId, appName, body }, call));
138
173
  return bindCredentials(credentials, this.#fetch);
139
174
  }
175
+ async #send(upload, zip, signal) {
176
+ const fetcher = this.#fetch ?? fetch;
177
+ const scope = linkSignal(signal);
178
+ // fetch sets Content-Length from the body, and a browser refuses to set it.
179
+ const headers = Object.entries(upload.headers).filter(([name]) => name.toLowerCase() !== 'content-length');
180
+ try {
181
+ const response = await fetcher(new Request(upload.url, {
182
+ method: upload.method,
183
+ headers,
184
+ body: zip,
185
+ signal: scope.signal,
186
+ }));
187
+ // A bucket answers 412 to `If-None-Match: *` once the bytes arrived.
188
+ if (!(response.ok || response.status === 409 || response.status === 412)) {
189
+ throw uploadRefused(response);
190
+ }
191
+ }
192
+ catch (error) {
193
+ throw signal?.aborted
194
+ ? toStateMachinesError(new CallerAbortedError(signal.reason))
195
+ : error instanceof StateMachinesError
196
+ ? error
197
+ : uploadUnanswered(error);
198
+ }
199
+ finally {
200
+ scope.close();
201
+ }
202
+ }
140
203
  #bind(data) {
141
204
  const { id } = data;
142
205
  const helpers = {
@@ -216,6 +279,15 @@ function addAttemptTimeout(httpClient, timeoutMs, calls) {
216
279
  }
217
280
  });
218
281
  }
282
+ function unshared(bytes) {
283
+ return bytes.buffer instanceof ArrayBuffer
284
+ ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
285
+ : new Uint8Array(bytes);
286
+ }
287
+ async function sha256(bytes) {
288
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
289
+ return `sha256:${Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
290
+ }
219
291
  function waitOptions(options) {
220
292
  return {
221
293
  ...(options.timeoutMs === undefined
@@ -1,5 +1,6 @@
1
1
  import type { Environment as EnvironmentData } from '../models/environment.js';
2
2
  import type { ErrorCode } from '../models/error.js';
3
+ import type { ImportProblem } from '../models/import-problem.js';
3
4
  import type { Snapshot } from '../models/snapshot.js';
4
5
  export interface ErrorDetails {
5
6
  readonly message: string;
@@ -37,6 +38,8 @@ export declare class EnvironmentFailedError extends StateMachinesError {
37
38
  export declare class SnapshotFailedError extends StateMachinesError {
38
39
  readonly snapshot: Snapshot;
39
40
  readonly name = "SnapshotFailedError";
41
+ /** The problems of an import that an app refused, errors before warnings. Empty for every other failure. */
42
+ readonly problems: readonly ImportProblem[];
40
43
  constructor(snapshot: Snapshot);
41
44
  }
42
45
  /** The resource reached a status from which the awaited one needs a call of yours. */
@@ -58,6 +61,10 @@ export declare class CallerAbortedError extends Error {
58
61
  readonly name = "CallerAbortedError";
59
62
  constructor(reason: unknown);
60
63
  }
64
+ /** An upload URL that answered with a status that ends the upload. The message never includes the body. */
65
+ export declare function uploadRefused(response: Response): StateMachinesError;
66
+ /** An upload URL that gave no answer. The message never names the URL, which carries a signature. */
67
+ export declare function uploadUnanswered(cause: unknown): StateMachinesError;
61
68
  /** The SDK refused input before sending it, as the API would with `invalid_request`. */
62
69
  export declare function invalidInput(message: string, fields: Record<string, string[]>): StateMachinesError;
63
70
  export declare function toStateMachinesError(error: unknown): StateMachinesError;
@@ -2,6 +2,7 @@ import { ErrorT } from '../models/errors/error.js';
2
2
  import { ConnectionError, RequestTimeoutError, } from '../models/errors/http-client-errors.js';
3
3
  import { ResponseValidationError } from '../models/errors/response-validation-error.js';
4
4
  import { StateMachinesHTTPError } from '../models/errors/state-machines-http-error.js';
5
+ import { isUnknown } from '../types/discriminated-union.js';
5
6
  /**
6
7
  * Any failed call: an error response, an invalid response, no response at all, or input
7
8
  * the SDK refused before sending. The message never includes a response body.
@@ -54,19 +55,41 @@ export class EnvironmentFailedError extends StateMachinesError {
54
55
  this.environment = environment;
55
56
  }
56
57
  }
58
+ function firstProblem(problems) {
59
+ const [first] = problems;
60
+ if (first === undefined) {
61
+ return '';
62
+ }
63
+ return problems.length === 1
64
+ ? ` ${problemLine(first)}`
65
+ : ` First of ${problems.length} listed problems: ${problemLine(first)}`;
66
+ }
67
+ function problemLine(problem) {
68
+ const place = problem.line === null ? problem.file : `${problem.file}:${problem.line}`;
69
+ const at = problem.pointer === null ? '' : ` ${problem.pointer || '/'}`;
70
+ return `${place}${at} ${problem.severity} ${problem.code} ${problem.message}`;
71
+ }
57
72
  /** A snapshot that ended `failed` while the SDK waited for it. */
58
73
  export class SnapshotFailedError extends StateMachinesError {
59
74
  snapshot;
60
75
  name = 'SnapshotFailedError';
76
+ /** The problems of an import that an app refused, errors before warnings. Empty for every other failure. */
77
+ problems;
61
78
  constructor(snapshot) {
62
- const failure = snapshot.failure;
79
+ const failure = snapshot.failure === null || isUnknown(snapshot.failure)
80
+ ? null
81
+ : snapshot.failure;
82
+ const refused = failure?.code === 'invalid_import' ? failure : null;
83
+ const problems = refused?.problems ?? [];
84
+ const app = refused?.appName === undefined ? '' : `, app ${refused.appName}`;
63
85
  super({
64
86
  ...noResponse,
65
87
  message: failure
66
- ? `Snapshot ${snapshot.id} failed: ${failure.message} (${failure.code}).`
88
+ ? `Snapshot ${snapshot.id} failed: ${failure.message} (${failure.code}${app}).${firstProblem(problems)}`
67
89
  : `Snapshot ${snapshot.id} failed.`,
68
90
  });
69
91
  this.snapshot = snapshot;
92
+ this.problems = problems;
70
93
  }
71
94
  }
72
95
  /** The resource reached a status from which the awaited one needs a call of yours. */
@@ -98,6 +121,27 @@ export class CallerAbortedError extends Error {
98
121
  super('The caller aborted the request.', { cause: reason });
99
122
  }
100
123
  }
124
+ /** An upload URL that answered with a status that ends the upload. The message never includes the body. */
125
+ export function uploadRefused(response) {
126
+ const details = {
127
+ ...noResponse,
128
+ message: `HTTP ${response.status} from the upload URL`,
129
+ status: response.status,
130
+ requestId: response.headers.get('request-id'),
131
+ retryAfterMs: retryAfterMs(response.headers),
132
+ };
133
+ return retryableStatuses.has(response.status)
134
+ ? transientError(details)
135
+ : new StateMachinesError(details);
136
+ }
137
+ /** An upload URL that gave no answer. The message never names the URL, which carries a signature. */
138
+ export function uploadUnanswered(cause) {
139
+ return transientError({
140
+ ...noResponse,
141
+ message: 'The upload URL did not answer.',
142
+ cause,
143
+ });
144
+ }
101
145
  /** The SDK refused input before sending it, as the API would with `invalid_request`. */
102
146
  export function invalidInput(message, fields) {
103
147
  return new StateMachinesError({
@@ -1,5 +1,5 @@
1
- export type { Actor, App, AppEntry, AuditEvent, BodyPreview, CreateEnvironment, CreateEnvironmentApp, EnvironmentApp, EnvironmentFailure, EnvironmentFailureCode, EnvironmentStatus, ErrorCode, Me, Permission, Principal, RequestDetail, RequestStats, RequestT as Request, Snapshot, SnapshotStatus, Version, Workspace, } from '../models/index.js';
2
- export type { ConnectOptions, CreateEnvironmentOptions, CreateSnapshotOptions, ListAuditEventsQuery, ListEnvironmentsQuery, ListRequestsQuery, ListSnapshotsQuery, ListWorkspacesQuery, Page, PageQuery, RequestStatsQuery, SignalOptions, StateMachinesOptions, } from './client.js';
1
+ export type { Actor, App, AppEntry, AuditEvent, BodyPreview, CreateEnvironment, CreateEnvironmentApp, EnvironmentApp, EnvironmentFailure, EnvironmentFailureCode, EnvironmentStatus, ErrorCode, Import, ImportApp, ImportProblem, ImportStatus, Me, Permission, Principal, RequestDetail, RequestStats, RequestT as Request, Snapshot, SnapshotStatus, Version, Workspace, } from '../models/index.js';
2
+ export type { ConnectOptions, CreateEnvironmentOptions, CreateSnapshotOptions, ListAuditEventsQuery, ListEnvironmentsQuery, ListImportsQuery, ListRequestsQuery, ListSnapshotsQuery, ListWorkspacesQuery, Page, PageQuery, RequestStatsQuery, SignalOptions, StateMachinesOptions, UploadImportOptions, } from './client.js';
3
3
  export { StateMachines } from './client.js';
4
4
  export type { Credentials, McpServerCredentials, ServiceCredentials, } from './credentials.js';
5
5
  export type { Environment, EnvironmentHelpers } from './environment.js';