@usestatemachines/sdk 0.12.3 → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agents/SKILL.md +8 -8
- package/agents/index.d.ts +1 -1
- package/agents/index.js +7 -7
- package/agents/llms.txt +5 -5
- package/agents/prompt.md +4 -4
- package/esm/lib/config.d.ts +2 -2
- package/esm/lib/config.js +2 -2
- package/openapi.json +0 -1
- package/package.json +1 -1
package/agents/SKILL.md
CHANGED
|
@@ -15,17 +15,17 @@ The SDK reads `STATEMACHINES_API_KEY` from the process environment. It does not
|
|
|
15
15
|
|
|
16
16
|
If 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.
|
|
17
17
|
|
|
18
|
-
Otherwise, run `npx @usestatemachines/cli@
|
|
18
|
+
Otherwise, run `npx @usestatemachines/cli@latest 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:
|
|
19
19
|
|
|
20
|
-
1. Run `npx @usestatemachines/cli@
|
|
20
|
+
1. Run `npx @usestatemachines/cli@latest 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.
|
|
21
21
|
2. 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.
|
|
22
|
-
3. After that approval, run `npx @usestatemachines/cli@
|
|
22
|
+
3. After that approval, run `npx @usestatemachines/cli@latest 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.
|
|
23
23
|
|
|
24
|
-
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@
|
|
24
|
+
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@latest 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.
|
|
25
25
|
|
|
26
|
-
If a command returns `cli.not_linked`, run `npx @usestatemachines/cli@
|
|
26
|
+
If a command returns `cli.not_linked`, run `npx @usestatemachines/cli@latest workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json` with the selected ID.
|
|
27
27
|
|
|
28
|
-
Run the user's existing command with `npx @usestatemachines/cli@
|
|
28
|
+
Run the user's existing command with `npx @usestatemachines/cli@latest run -- <command>`. The child receives a workspace key. The CLI keeps the credential out of its output.
|
|
29
29
|
|
|
30
30
|
If 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.
|
|
31
31
|
|
|
@@ -62,7 +62,7 @@ Point the existing integration's test transport at these URLs and credentials. I
|
|
|
62
62
|
Use a browser only when the task needs an app's UI. Each entry of `env.apps` lists the app's UI in `browserServices`, with each service's `id` and the `documents` routes that a session can open first. Linear's `ui` service is one. A UI session signs one browser in to the service as one actor.
|
|
63
63
|
|
|
64
64
|
1. Create the environment with `{ wait: false }` and keep its ID. `open` waits for `running`, so you do not need to wait first.
|
|
65
|
-
2. Start `npx @usestatemachines/cli@
|
|
65
|
+
2. Start `npx @usestatemachines/cli@latest open <environment-id> --json` in the background. It opens the only app with a browser service, and that app's only browser service. When the environment has more, name the app as the second argument and the service with `--service`. `--actor` takes a user as `connect --actor` does.
|
|
66
66
|
3. Read the line `Open http://127.0.0.1:<port>/<token> in the browser ...` from the command's stderr. While the environment starts, the line `Waiting for <environment-id> to run (now starting).` comes first. If the environment fails or is deleted first, the command fails and prints no link. Open that URL in your browser tool before you do anything else. The command launches the session only when the browser opens the URL, and the browser then loads the app as the actor.
|
|
67
67
|
4. Use the app in that browser tab. The command exits once the browser opened the link, and its JSON result names the session, the actor, the path that it opened and when the session expires.
|
|
68
68
|
5. Read each write back through the app's MCP server or API with `env.connect`. Do not trust the page alone.
|
|
@@ -94,7 +94,7 @@ When `sm.me().limits` is non-null, it gives the cap on concurrent environments a
|
|
|
94
94
|
|
|
95
95
|
## Optional connection check
|
|
96
96
|
|
|
97
|
-
Run 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@
|
|
97
|
+
Run 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@latest run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@latest run -- npx tsx state-quickstart.mts`.
|
|
98
98
|
|
|
99
99
|
```ts
|
|
100
100
|
import { StateMachines } from '@usestatemachines/sdk';
|
package/agents/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const skill: string;
|
|
|
8
8
|
|
|
9
9
|
export declare const quickstart: string;
|
|
10
10
|
|
|
11
|
-
export declare const
|
|
11
|
+
export declare const cli: 'latest' | 'none';
|
|
12
12
|
|
|
13
13
|
export declare const templates: Readonly<
|
|
14
14
|
Record<'prompt' | 'llmsTxt' | 'skill', string>
|
package/agents/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
// Generated by scripts/build-agents.mjs from templates/ and examples/quickstart.ts.
|
|
2
2
|
|
|
3
3
|
export const prompt =
|
|
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@
|
|
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@latest 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@latest 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@latest 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@latest 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@latest 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@latest 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.5 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.5 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.5 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.5 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.5 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.5 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.5 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.5`. 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`, `open`, `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 users of the app's seed, for display. They do not say who can act.\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`, an MCP request without `Authorization` acts as the app's default user. 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: the user of the app that a call acts as. Requests run with that user's permissions. `connect()` acts as the app's default user unless you pass `as`: the email, username or ID of any user who can sign in to the running app, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. When the app's data came from an import whose `actors` names users for the app, the default user is the first of them. Otherwise it is the app's administrator. `credentials.actor` names that user, with the app's own `id`, such as a Salesforce `005…` ID. `env.actors(appName, { search })` pages through the users who can act, the default user first. `env.connectAll({ as })` connects to every app as one person: `credentials` holds each app that lets the user act, by app name, and `errors` holds the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws. A user that the app does not have throws `ActorNotFoundError`, whose `nearest` lists the nearest users who can act. A user that the app does not let sign in throws `ActorCannotSignInError`.\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.snapshots.create({ import: data })` takes the import as one object, the manifest with each app's `records` by object, then uploads it and builds the snapshot in one call. A problem at line N of `<app>/records/<Object>.jsonl` names `data.apps.<app>.records.<Object>[N - 1]`. `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- UI session: a browser signed in to a browser service of an app, such as Linear's `ui`, as one actor. Each entry of `env.apps` lists its `browserServices`. `env.launchUiSession(appName, { serviceId, mode, launcherOrigin, entryPath, as })` returns a one-use `grant` that lives for a short time. A page on `launcherOrigin` posts it to `exchangeUrl`, and the browser then loads the app. `entryPath` takes the path and query of a vendor's record URL, such as one that an MCP tool returns. `env.revokeUiSession(appName, sessionId)` ends the session.\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. With `{ import }`, it throws `ImportInvalidError`, with the problems in `problems`, when the check leaves the uploaded import `invalid`, and it creates no snapshot.\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| `actor_cannot_sign_in` | 409 | The app does not let the user sign in now, such as an inactive user. `fields.as` gives the reason. Do not act as another user to make the test pass. |\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| `actor_not_found` | 422 | The app has no user with that email, username or ID. `err.nearest` lists the nearest users who can act. Check the name with `env.actors(appName, { search })`. |\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.5 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.5 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@latest 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@latest 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@latest 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@latest 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@latest workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@latest run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@latest`. 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`, `open`, `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 users of the app's seed, for display. They do not say who can act.\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`, an MCP request without `Authorization` acts as the app's default user. 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: the user of the app that a call acts as. Requests run with that user's permissions. `connect()` acts as the app's default user unless you pass `as`: the email, username or ID of any user who can sign in to the running app, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. When the app's data came from an import whose `actors` names users for the app, the default user is the first of them. Otherwise it is the app's administrator. `credentials.actor` names that user, with the app's own `id`, such as a Salesforce `005…` ID. `env.actors(appName, { search })` pages through the users who can act, the default user first. `env.connectAll({ as })` connects to every app as one person: `credentials` holds each app that lets the user act, by app name, and `errors` holds the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws. A user that the app does not have throws `ActorNotFoundError`, whose `nearest` lists the nearest users who can act. A user that the app does not let sign in throws `ActorCannotSignInError`.\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.snapshots.create({ import: data })` takes the import as one object, the manifest with each app's `records` by object, then uploads it and builds the snapshot in one call. A problem at line N of `<app>/records/<Object>.jsonl` names `data.apps.<app>.records.<Object>[N - 1]`. `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- UI session: a browser signed in to a browser service of an app, such as Linear's `ui`, as one actor. Each entry of `env.apps` lists its `browserServices`. `env.launchUiSession(appName, { serviceId, mode, launcherOrigin, entryPath, as })` returns a one-use `grant` that lives for a short time. A page on `launcherOrigin` posts it to `exchangeUrl`, and the browser then loads the app. `entryPath` takes the path and query of a vendor's record URL, such as one that an MCP tool returns. `env.revokeUiSession(appName, sessionId)` ends the session.\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. With `{ import }`, it throws `ImportInvalidError`, with the problems in `problems`, when the check leaves the uploaded import `invalid`, and it creates no snapshot.\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| `actor_cannot_sign_in` | 409 | The app does not let the user sign in now, such as an inactive user. `fields.as` gives the reason. Do not act as another user to make the test pass. |\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| `actor_not_found` | 422 | The app has no user with that email, username or ID. `err.nearest` lists the nearest users who can act. Check the name with `env.actors(appName, { search })`. |\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@latest run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@latest 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
|
-
"---\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.5 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.5 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.5 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.5 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.5 workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@0.1.5 link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@0.1.5 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 users of the app's seed, for display. They do not say who can act. 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 never calls the vendor and does not run arbitrary customer automation. An environment holds a customer's org data only when it starts from a snapshot created from an import of that data.\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 user and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user of the app, pass `as` with the user's email, username or ID, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. Any user who can sign in to the running app can act, including a user that the test created. `credentials.actor` names the user that the credentials act as. Never pass a role label or a workspace member ID.\n\n- `env.actors(name, { search })` pages through the users who can act, the default user first. Use it to find a user when the task does not name one by email, username or ID.\n- `env.connectAll({ as })` connects to every app of the environment as one person. Its `credentials` hold each app that lets the user act, by app name. Its `errors` hold the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws.\n- A user that the app does not have throws `ActorNotFoundError`, and `err.nearest` lists the nearest users who can act. A user that the app does not let sign in now, such as an inactive user, throws `ActorCannotSignInError`.\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, an MCP request without an `Authorization` header acts as the app's default user. To act as the user of the credentials, send the 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## Use an app in a browser\n\nUse a browser only when the task needs an app's UI. Each entry of `env.apps` lists the app's UI in `browserServices`, with each service's `id` and the `documents` routes that a session can open first. Linear's `ui` service is one. A UI session signs one browser in to the service as one actor.\n\n1. Create the environment with `{ wait: false }` and keep its ID. `open` waits for `running`, so you do not need to wait first.\n2. Start `npx @usestatemachines/cli@0.1.5 open <environment-id> --json` in the background. It opens the only app with a browser service, and that app's only browser service. When the environment has more, name the app as the second argument and the service with `--service`. `--actor` takes a user as `connect --actor` does.\n3. Read the line `Open http://127.0.0.1:<port>/<token> in the browser ...` from the command's stderr. While the environment starts, the line `Waiting for <environment-id> to run (now starting).` comes first. If the environment fails or is deleted first, the command fails and prints no link. Open that URL in your browser tool before you do anything else. The command launches the session only when the browser opens the URL, and the browser then loads the app as the actor.\n4. Use the app in that browser tab. The command exits once the browser opened the link, and its JSON result names the session, the actor, the path that it opened and when the session expires.\n5. Read each write back through the app's MCP server or API with `env.connect`. Do not trust the page alone.\n6. Delete the environment. The session ends with it.\n\nThe link works once. While the command runs, a second visit shows that the link was used. After the command exits, the link no longer answers. Run `open` again for a new link. The session's grant lives for a short time, which is why the command launches the session only when the browser opens the link. If no browser opens the link within the `--timeout` seconds, the command fails with `cli.wait_timeout`.\n\nA page titled `Access required` or `Open this app again` means that the session ended. Run `open` again for a new link. If `open` then fails because the environment is deleted, create a new environment.\n\nTo open one record, pass its URL to `--path`. MCP tools return the vendor's URLs, such as `https://linear.app/<workspace>/issue/<id>/<slug>` for a Linear issue, and the replica serves the same paths. The command keeps the URL's path and query and opens them in the replica. A vendor URL that you open as it is goes to the vendor, not to the replica. Without `--path`, the command opens the service's first route without parameters. The API refuses a path that matches none of the service's `documents` routes.\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 start from records, users and files that you write in one file, build a snapshot from an import, as [build a snapshot from an import](https://app.usestatemachines.com/docs/snapshots/import.md) shows. 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.5 run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.5 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| `ActorNotFoundError` | The app has no user with that email, username or ID. Check `err.nearest` or `env.actors(appName, { search })`. Act as another user only when the task allows it. |\n| `ActorCannotSignInError` | The app does not let the user sign in now, for the reason in `err.fields.as`. Report it. Do not act as another user to make the test pass. |\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";
|
|
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@latest 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@latest 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@latest 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@latest 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@latest workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@latest 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 users of the app's seed, for display. They do not say who can act. 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 never calls the vendor and does not run arbitrary customer automation. An environment holds a customer's org data only when it starts from a snapshot created from an import of that data.\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 user and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user of the app, pass `as` with the user's email, username or ID, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. Any user who can sign in to the running app can act, including a user that the test created. `credentials.actor` names the user that the credentials act as. Never pass a role label or a workspace member ID.\n\n- `env.actors(name, { search })` pages through the users who can act, the default user first. Use it to find a user when the task does not name one by email, username or ID.\n- `env.connectAll({ as })` connects to every app of the environment as one person. Its `credentials` hold each app that lets the user act, by app name. Its `errors` hold the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws.\n- A user that the app does not have throws `ActorNotFoundError`, and `err.nearest` lists the nearest users who can act. A user that the app does not let sign in now, such as an inactive user, throws `ActorCannotSignInError`.\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, an MCP request without an `Authorization` header acts as the app's default user. To act as the user of the credentials, send the 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## Use an app in a browser\n\nUse a browser only when the task needs an app's UI. Each entry of `env.apps` lists the app's UI in `browserServices`, with each service's `id` and the `documents` routes that a session can open first. Linear's `ui` service is one. A UI session signs one browser in to the service as one actor.\n\n1. Create the environment with `{ wait: false }` and keep its ID. `open` waits for `running`, so you do not need to wait first.\n2. Start `npx @usestatemachines/cli@latest open <environment-id> --json` in the background. It opens the only app with a browser service, and that app's only browser service. When the environment has more, name the app as the second argument and the service with `--service`. `--actor` takes a user as `connect --actor` does.\n3. Read the line `Open http://127.0.0.1:<port>/<token> in the browser ...` from the command's stderr. While the environment starts, the line `Waiting for <environment-id> to run (now starting).` comes first. If the environment fails or is deleted first, the command fails and prints no link. Open that URL in your browser tool before you do anything else. The command launches the session only when the browser opens the URL, and the browser then loads the app as the actor.\n4. Use the app in that browser tab. The command exits once the browser opened the link, and its JSON result names the session, the actor, the path that it opened and when the session expires.\n5. Read each write back through the app's MCP server or API with `env.connect`. Do not trust the page alone.\n6. Delete the environment. The session ends with it.\n\nThe link works once. While the command runs, a second visit shows that the link was used. After the command exits, the link no longer answers. Run `open` again for a new link. The session's grant lives for a short time, which is why the command launches the session only when the browser opens the link. If no browser opens the link within the `--timeout` seconds, the command fails with `cli.wait_timeout`.\n\nA page titled `Access required` or `Open this app again` means that the session ended. Run `open` again for a new link. If `open` then fails because the environment is deleted, create a new environment.\n\nTo open one record, pass its URL to `--path`. MCP tools return the vendor's URLs, such as `https://linear.app/<workspace>/issue/<id>/<slug>` for a Linear issue, and the replica serves the same paths. The command keeps the URL's path and query and opens them in the replica. A vendor URL that you open as it is goes to the vendor, not to the replica. Without `--path`, the command opens the service's first route without parameters. The API refuses a path that matches none of the service's `documents` routes.\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 start from records, users and files that you write in one file, build a snapshot from an import, as [build a snapshot from an import](https://app.usestatemachines.com/docs/snapshots/import.md) shows. 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@latest run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@latest 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| `ActorNotFoundError` | The app has no user with that email, username or ID. Check `err.nearest` or `env.actors(appName, { search })`. Act as another user only when the task allows it. |\n| `ActorCannotSignInError` | The app does not let the user sign in now, for the reason in `err.fields.as`. Report it. Do not act as another user to make the test pass. |\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";
|
|
11
11
|
|
|
12
12
|
export const quickstart =
|
|
13
13
|
"import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n";
|
|
14
14
|
|
|
15
|
-
export const
|
|
15
|
+
export const cli = 'latest';
|
|
16
16
|
|
|
17
17
|
export const templates = Object.freeze({
|
|
18
18
|
prompt:
|
|
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@
|
|
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@latest 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@latest 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@latest 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@latest 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@latest 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@latest 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.5 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.5 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.5 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.5 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.5 workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@0.1.5 link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@0.1.5 run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@0.1.5`. 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`, `open`, `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 users of the app's seed, for display. They do not say who can act.\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`, an MCP request without `Authorization` acts as the app's default user. 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: the user of the app that a call acts as. Requests run with that user's permissions. `connect()` acts as the app's default user unless you pass `as`: the email, username or ID of any user who can sign in to the running app, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. When the app's data came from an import whose `actors` names users for the app, the default user is the first of them. Otherwise it is the app's administrator. `credentials.actor` names that user, with the app's own `id`, such as a Salesforce `005…` ID. `env.actors(appName, { search })` pages through the users who can act, the default user first. `env.connectAll({ as })` connects to every app as one person: `credentials` holds each app that lets the user act, by app name, and `errors` holds the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws. A user that the app does not have throws `ActorNotFoundError`, whose `nearest` lists the nearest users who can act. A user that the app does not let sign in throws `ActorCannotSignInError`.\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.snapshots.create({ import: data })` takes the import as one object, the manifest with each app's `records` by object, then uploads it and builds the snapshot in one call. A problem at line N of `<app>/records/<Object>.jsonl` names `data.apps.<app>.records.<Object>[N - 1]`. `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- UI session: a browser signed in to a browser service of an app, such as Linear's `ui`, as one actor. Each entry of `env.apps` lists its `browserServices`. `env.launchUiSession(appName, { serviceId, mode, launcherOrigin, entryPath, as })` returns a one-use `grant` that lives for a short time. A page on `launcherOrigin` posts it to `exchangeUrl`, and the browser then loads the app. `entryPath` takes the path and query of a vendor's record URL, such as one that an MCP tool returns. `env.revokeUiSession(appName, sessionId)` ends the session.\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. With `{ import }`, it throws `ImportInvalidError`, with the problems in `problems`, when the check leaves the uploaded import `invalid`, and it creates no snapshot.\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| `actor_cannot_sign_in` | 409 | The app does not let the user sign in now, such as an inactive user. `fields.as` gives the reason. Do not act as another user to make the test pass. |\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| `actor_not_found` | 422 | The app has no user with that email, username or ID. `err.nearest` lists the nearest users who can act. Check the name with `env.actors(appName, { search })`. |\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.5 run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.5 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@latest 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@latest 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@latest 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@latest 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@latest workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@latest run -- <command>`. Never print or commit a credential.\n\n## CLI commands\n\nPrefix these commands with `npx @usestatemachines/cli@latest`. 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`, `open`, `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 users of the app's seed, for display. They do not say who can act.\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`, an MCP request without `Authorization` acts as the app's default user. 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: the user of the app that a call acts as. Requests run with that user's permissions. `connect()` acts as the app's default user unless you pass `as`: the email, username or ID of any user who can sign in to the running app, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. When the app's data came from an import whose `actors` names users for the app, the default user is the first of them. Otherwise it is the app's administrator. `credentials.actor` names that user, with the app's own `id`, such as a Salesforce `005…` ID. `env.actors(appName, { search })` pages through the users who can act, the default user first. `env.connectAll({ as })` connects to every app as one person: `credentials` holds each app that lets the user act, by app name, and `errors` holds the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws. A user that the app does not have throws `ActorNotFoundError`, whose `nearest` lists the nearest users who can act. A user that the app does not let sign in throws `ActorCannotSignInError`.\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.snapshots.create({ import: data })` takes the import as one object, the manifest with each app's `records` by object, then uploads it and builds the snapshot in one call. A problem at line N of `<app>/records/<Object>.jsonl` names `data.apps.<app>.records.<Object>[N - 1]`. `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- UI session: a browser signed in to a browser service of an app, such as Linear's `ui`, as one actor. Each entry of `env.apps` lists its `browserServices`. `env.launchUiSession(appName, { serviceId, mode, launcherOrigin, entryPath, as })` returns a one-use `grant` that lives for a short time. A page on `launcherOrigin` posts it to `exchangeUrl`, and the browser then loads the app. `entryPath` takes the path and query of a vendor's record URL, such as one that an MCP tool returns. `env.revokeUiSession(appName, sessionId)` ends the session.\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. With `{ import }`, it throws `ImportInvalidError`, with the problems in `problems`, when the check leaves the uploaded import `invalid`, and it creates no snapshot.\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| `actor_cannot_sign_in` | 409 | The app does not let the user sign in now, such as an inactive user. `fields.as` gives the reason. Do not act as another user to make the test pass. |\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| `actor_not_found` | 422 | The app has no user with that email, username or ID. `err.nearest` lists the nearest users who can act. Check the name with `env.actors(appName, { search })`. |\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@latest run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@latest 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
|
-
"---\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.5 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.5 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.5 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.5 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.5 workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@0.1.5 link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@0.1.5 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 users of the app's seed, for display. They do not say who can act. Check the `limitations` against the behavior under test, as [known differences]({{origin}}/docs/apps/known-differences.md) does for Salesforce. A replica never calls the vendor and does not run arbitrary customer automation. An environment holds a customer's org data only when it starts from a snapshot created from an import of that data.\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 user and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user of the app, pass `as` with the user's email, username or ID, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. Any user who can sign in to the running app can act, including a user that the test created. `credentials.actor` names the user that the credentials act as. Never pass a role label or a workspace member ID.\n\n- `env.actors(name, { search })` pages through the users who can act, the default user first. Use it to find a user when the task does not name one by email, username or ID.\n- `env.connectAll({ as })` connects to every app of the environment as one person. Its `credentials` hold each app that lets the user act, by app name. Its `errors` hold the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws.\n- A user that the app does not have throws `ActorNotFoundError`, and `err.nearest` lists the nearest users who can act. A user that the app does not let sign in now, such as an inactive user, throws `ActorCannotSignInError`.\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, an MCP request without an `Authorization` header acts as the app's default user. To act as the user of the credentials, send the 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## Use an app in a browser\n\nUse a browser only when the task needs an app's UI. Each entry of `env.apps` lists the app's UI in `browserServices`, with each service's `id` and the `documents` routes that a session can open first. Linear's `ui` service is one. A UI session signs one browser in to the service as one actor.\n\n1. Create the environment with `{ wait: false }` and keep its ID. `open` waits for `running`, so you do not need to wait first.\n2. Start `npx @usestatemachines/cli@0.1.5 open <environment-id> --json` in the background. It opens the only app with a browser service, and that app's only browser service. When the environment has more, name the app as the second argument and the service with `--service`. `--actor` takes a user as `connect --actor` does.\n3. Read the line `Open http://127.0.0.1:<port>/<token> in the browser ...` from the command's stderr. While the environment starts, the line `Waiting for <environment-id> to run (now starting).` comes first. If the environment fails or is deleted first, the command fails and prints no link. Open that URL in your browser tool before you do anything else. The command launches the session only when the browser opens the URL, and the browser then loads the app as the actor.\n4. Use the app in that browser tab. The command exits once the browser opened the link, and its JSON result names the session, the actor, the path that it opened and when the session expires.\n5. Read each write back through the app's MCP server or API with `env.connect`. Do not trust the page alone.\n6. Delete the environment. The session ends with it.\n\nThe link works once. While the command runs, a second visit shows that the link was used. After the command exits, the link no longer answers. Run `open` again for a new link. The session's grant lives for a short time, which is why the command launches the session only when the browser opens the link. If no browser opens the link within the `--timeout` seconds, the command fails with `cli.wait_timeout`.\n\nA page titled `Access required` or `Open this app again` means that the session ended. Run `open` again for a new link. If `open` then fails because the environment is deleted, create a new environment.\n\nTo open one record, pass its URL to `--path`. MCP tools return the vendor's URLs, such as `https://linear.app/<workspace>/issue/<id>/<slug>` for a Linear issue, and the replica serves the same paths. The command keeps the URL's path and query and opens them in the replica. A vendor URL that you open as it is goes to the vendor, not to the replica. Without `--path`, the command opens the service's first route without parameters. The API refuses a path that matches none of the service's `documents` routes.\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 start from records, users and files that you write in one file, build a snapshot from an import, as [build a snapshot from an import]({{origin}}/docs/snapshots/import.md) shows. 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.5 run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@0.1.5 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| `ActorNotFoundError` | The app has no user with that email, username or ID. Check `err.nearest` or `env.actors(appName, { search })`. Act as another user only when the task allows it. |\n| `ActorCannotSignInError` | The app does not let the user sign in now, for the reason in `err.fields.as`. Report it. Do not act as another user to make the test pass. |\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",
|
|
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@latest 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@latest 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@latest 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@latest 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@latest workspaces list --json`. Ask the user which workspace to use when there is more than one. Run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json` with the selected ID.\n\nRun the user's existing command with `npx @usestatemachines/cli@latest 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 users of the app's seed, for display. They do not say who can act. Check the `limitations` against the behavior under test, as [known differences]({{origin}}/docs/apps/known-differences.md) does for Salesforce. A replica never calls the vendor and does not run arbitrary customer automation. An environment holds a customer's org data only when it starts from a snapshot created from an import of that data.\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 user and lists each `public` service. Pass `{ services: ['mcp'] }` to also list a `preview` service. To act as another user of the app, pass `as` with the user's email, username or ID, such as `env.connect('salesforce', { as: 'alice.park@acme.example' })`. Any user who can sign in to the running app can act, including a user that the test created. `credentials.actor` names the user that the credentials act as. Never pass a role label or a workspace member ID.\n\n- `env.actors(name, { search })` pages through the users who can act, the default user first. Use it to find a user when the task does not name one by email, username or ID.\n- `env.connectAll({ as })` connects to every app of the environment as one person. Its `credentials` hold each app that lets the user act, by app name. Its `errors` hold the `ActorNotFoundError` or `ActorCannotSignInError` of each other app. Any other error throws.\n- A user that the app does not have throws `ActorNotFoundError`, and `err.nearest` lists the nearest users who can act. A user that the app does not let sign in now, such as an inactive user, throws `ActorCannotSignInError`.\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, an MCP request without an `Authorization` header acts as the app's default user. To act as the user of the credentials, send the 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## Use an app in a browser\n\nUse a browser only when the task needs an app's UI. Each entry of `env.apps` lists the app's UI in `browserServices`, with each service's `id` and the `documents` routes that a session can open first. Linear's `ui` service is one. A UI session signs one browser in to the service as one actor.\n\n1. Create the environment with `{ wait: false }` and keep its ID. `open` waits for `running`, so you do not need to wait first.\n2. Start `npx @usestatemachines/cli@latest open <environment-id> --json` in the background. It opens the only app with a browser service, and that app's only browser service. When the environment has more, name the app as the second argument and the service with `--service`. `--actor` takes a user as `connect --actor` does.\n3. Read the line `Open http://127.0.0.1:<port>/<token> in the browser ...` from the command's stderr. While the environment starts, the line `Waiting for <environment-id> to run (now starting).` comes first. If the environment fails or is deleted first, the command fails and prints no link. Open that URL in your browser tool before you do anything else. The command launches the session only when the browser opens the URL, and the browser then loads the app as the actor.\n4. Use the app in that browser tab. The command exits once the browser opened the link, and its JSON result names the session, the actor, the path that it opened and when the session expires.\n5. Read each write back through the app's MCP server or API with `env.connect`. Do not trust the page alone.\n6. Delete the environment. The session ends with it.\n\nThe link works once. While the command runs, a second visit shows that the link was used. After the command exits, the link no longer answers. Run `open` again for a new link. The session's grant lives for a short time, which is why the command launches the session only when the browser opens the link. If no browser opens the link within the `--timeout` seconds, the command fails with `cli.wait_timeout`.\n\nA page titled `Access required` or `Open this app again` means that the session ended. Run `open` again for a new link. If `open` then fails because the environment is deleted, create a new environment.\n\nTo open one record, pass its URL to `--path`. MCP tools return the vendor's URLs, such as `https://linear.app/<workspace>/issue/<id>/<slug>` for a Linear issue, and the replica serves the same paths. The command keeps the URL's path and query and opens them in the replica. A vendor URL that you open as it is goes to the vendor, not to the replica. Without `--path`, the command opens the service's first route without parameters. The API refuses a path that matches none of the service's `documents` routes.\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 start from records, users and files that you write in one file, build a snapshot from an import, as [build a snapshot from an import]({{origin}}/docs/snapshots/import.md) shows. 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@latest run -- <command>`. For an empty Node.js project, save `state-quickstart.mts` and run `npx @usestatemachines/cli@latest 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| `ActorNotFoundError` | The app has no user with that email, username or ID. Check `err.nearest` or `env.actors(appName, { search })`. Act as another user only when the task allows it. |\n| `ActorCannotSignInError` | The app does not let the user sign in now, for the reason in `err.fields.as`. Report it. Do not act as another user to make the test pass. |\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
|
@@ -6,15 +6,15 @@ Use the project's package manager to install or reuse `@usestatemachines/sdk`. I
|
|
|
6
6
|
|
|
7
7
|
## Get a credential
|
|
8
8
|
|
|
9
|
-
If 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@
|
|
9
|
+
If 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@latest 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@latest 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@latest 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.
|
|
10
10
|
|
|
11
|
-
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@
|
|
11
|
+
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@latest 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.
|
|
12
12
|
|
|
13
|
-
For `cli.not_linked`, run `npx @usestatemachines/cli@
|
|
13
|
+
For `cli.not_linked`, run `npx @usestatemachines/cli@latest workspaces list --json`. Ask which workspace to use when there is more than one, then run `npx @usestatemachines/cli@latest link --workspace <workspace-id> --json`. Run the user's existing code with `npx @usestatemachines/cli@latest run -- <command>`. Never print or commit a credential.
|
|
14
14
|
|
|
15
15
|
## CLI commands
|
|
16
16
|
|
|
17
|
-
Prefix these commands with `npx @usestatemachines/cli@
|
|
17
|
+
Prefix these commands with `npx @usestatemachines/cli@latest`. Use `help --json` for flags and result schemas:
|
|
18
18
|
|
|
19
19
|
- `login`, `logout`, `whoami`, `profiles list`, and `profiles use`
|
|
20
20
|
- `workspaces list`, `workspaces use`, `link`, `unlink`, and `init`
|
|
@@ -92,7 +92,7 @@ A failed API call throws `StateMachinesError` with `status`, `code`, `message`,
|
|
|
92
92
|
|
|
93
93
|
## Quickstart
|
|
94
94
|
|
|
95
|
-
Use the project's TypeScript runner with its secret loader, or pass that runner through `npx @usestatemachines/cli@
|
|
95
|
+
Use the project's TypeScript runner with its secret loader, or pass that runner through `npx @usestatemachines/cli@latest run -- <command>`. For an empty Node.js project, save as `state-quickstart.mts` and run `npx @usestatemachines/cli@latest 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.
|
|
96
96
|
|
|
97
97
|
```ts
|
|
98
98
|
import { StateMachines } from '@usestatemachines/sdk';
|
package/agents/prompt.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
Set up State Machines in this existing repository so I can use disposable app environments with my coding agent.
|
|
2
2
|
|
|
3
3
|
1. 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.
|
|
4
|
-
2. Run `npx @usestatemachines/cli@
|
|
5
|
-
3. Only when no project API key is configured and the access check reports a missing, expired or revoked CLI credential, run `npx @usestatemachines/cli@
|
|
6
|
-
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@
|
|
4
|
+
2. Run `npx @usestatemachines/cli@latest 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.
|
|
5
|
+
3. Only when no project API key is configured and the access check reports a missing, expired or revoked CLI credential, run `npx @usestatemachines/cli@latest 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@latest 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.
|
|
6
|
+
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@latest 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.
|
|
7
7
|
|
|
8
|
-
4. Run `npx @usestatemachines/cli@
|
|
8
|
+
4. Run `npx @usestatemachines/cli@latest 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@latest 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.
|
|
9
9
|
5. 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.
|
|
10
10
|
6. 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.
|
|
11
11
|
|
package/esm/lib/config.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ export declare function serverURLFromOptions(options: SDKOptions): URL | null;
|
|
|
31
31
|
export declare const SDK_METADATA: {
|
|
32
32
|
readonly language: "typescript";
|
|
33
33
|
readonly openapiDocVersion: "1.0.0";
|
|
34
|
-
readonly sdkVersion: "0.
|
|
34
|
+
readonly sdkVersion: "0.13.1";
|
|
35
35
|
readonly genVersion: "2.941.0";
|
|
36
|
-
readonly userAgent: "speakeasy-sdk/typescript 0.
|
|
36
|
+
readonly userAgent: "speakeasy-sdk/typescript 0.13.1 2.941.0 1.0.0 @usestatemachines/sdk";
|
|
37
37
|
};
|
package/esm/lib/config.js
CHANGED
|
@@ -24,7 +24,7 @@ export function serverURLFromOptions(options) {
|
|
|
24
24
|
export const SDK_METADATA = {
|
|
25
25
|
language: "typescript",
|
|
26
26
|
openapiDocVersion: "1.0.0",
|
|
27
|
-
sdkVersion: "0.
|
|
27
|
+
sdkVersion: "0.13.1",
|
|
28
28
|
genVersion: "2.941.0",
|
|
29
|
-
userAgent: "speakeasy-sdk/typescript 0.
|
|
29
|
+
userAgent: "speakeasy-sdk/typescript 0.13.1 2.941.0 1.0.0 @usestatemachines/sdk",
|
|
30
30
|
};
|
package/openapi.json
CHANGED