@usestatemachines/sdk 0.5.0 → 0.6.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/README.md +177 -521
- package/agents/SKILL.md +38 -47
- package/agents/index.js +7 -7
- package/agents/llms.txt +50 -46
- package/agents/prompt.md +11 -11
- package/esm/extensions/client.d.ts +104 -127
- package/esm/extensions/client.js +162 -322
- package/esm/extensions/credentials.d.ts +13 -0
- package/esm/extensions/credentials.js +73 -0
- package/esm/extensions/environment.d.ts +25 -0
- package/esm/extensions/environment.js +1 -0
- package/esm/extensions/errors.d.ts +42 -75
- package/esm/extensions/errors.js +125 -110
- package/esm/extensions/index.d.ts +6 -11
- package/esm/extensions/index.js +2 -7
- package/esm/extensions/wait.d.ts +17 -18
- package/esm/extensions/wait.js +60 -56
- package/esm/extensions/yaml.d.ts +6 -0
- package/esm/extensions/yaml.js +137 -0
- package/esm/funcs/{catalog-release.d.ts → apps-list.d.ts} +1 -1
- package/esm/funcs/{environments-get-connection.js → apps-list.js} +11 -16
- package/esm/funcs/{credential-get.d.ts → apps-versions.d.ts} +1 -1
- package/esm/funcs/{workspaces-events.js → apps-versions.js} +6 -7
- package/esm/funcs/{environments-get-connection.d.ts → audit-events-list.d.ts} +1 -1
- package/esm/funcs/audit-events-list.js +93 -0
- package/esm/funcs/{workspaces-events.d.ts → environments-connect.d.ts} +1 -1
- package/esm/funcs/{environments-reveal.js → environments-connect.js} +7 -6
- package/esm/funcs/environments-create.d.ts +2 -1
- package/esm/funcs/environments-create.js +5 -10
- package/esm/funcs/{environments-events.d.ts → environments-delete.d.ts} +1 -1
- package/esm/funcs/{environments-stop.js → environments-delete.js} +7 -6
- package/esm/funcs/environments-get.d.ts +2 -1
- package/esm/funcs/environments-get.js +2 -1
- package/esm/funcs/environments-list.d.ts +1 -1
- package/esm/funcs/environments-list.js +11 -16
- package/esm/funcs/environments-pause.d.ts +12 -0
- package/esm/funcs/{environments-suspend.js → environments-pause.js} +6 -5
- package/esm/funcs/environments-resume.d.ts +2 -1
- package/esm/funcs/environments-resume.js +2 -1
- package/esm/funcs/environments-update.d.ts +12 -0
- package/esm/funcs/{environments-events.js → environments-update.js} +9 -13
- package/esm/funcs/me.d.ts +11 -0
- package/esm/funcs/{catalog-get.js → me.js} +5 -5
- package/esm/funcs/{catalog-get.d.ts → requests-body.d.ts} +1 -1
- package/esm/funcs/{environments-get-request-payload.js → requests-body.js} +5 -9
- package/esm/funcs/{environments-get-request-stats.d.ts → requests-get.d.ts} +2 -1
- package/esm/funcs/{catalog-release.js → requests-get.js} +7 -6
- package/esm/funcs/{environments-stop.d.ts → requests-list.d.ts} +1 -1
- package/esm/funcs/{environments-list-requests.js → requests-list.js} +9 -14
- package/esm/funcs/requests-stats.d.ts +12 -0
- package/esm/funcs/{environments-get-request-stats.js → requests-stats.js} +10 -14
- package/esm/funcs/snapshots-create.d.ts +12 -0
- package/esm/funcs/{snapshots-capture.js → snapshots-create.js} +6 -11
- package/esm/funcs/snapshots-delete.d.ts +2 -1
- package/esm/funcs/snapshots-delete.js +2 -1
- package/esm/funcs/snapshots-get.d.ts +2 -1
- package/esm/funcs/snapshots-get.js +2 -1
- package/esm/funcs/snapshots-list.d.ts +1 -1
- package/esm/funcs/snapshots-list.js +9 -13
- package/esm/funcs/snapshots-update.d.ts +2 -1
- package/esm/funcs/snapshots-update.js +2 -1
- package/esm/funcs/workspaces-get.d.ts +2 -1
- package/esm/funcs/workspaces-get.js +2 -1
- package/esm/funcs/workspaces-list.d.ts +1 -1
- package/esm/funcs/workspaces-list.js +3 -1
- package/esm/lib/config.d.ts +3 -3
- package/esm/lib/config.js +3 -3
- package/esm/models/actor.d.ts +2 -3
- package/esm/models/actor.js +2 -3
- package/esm/models/{api-profile.d.ts → api.d.ts} +4 -4
- package/esm/models/{api-profile.js → api.js} +4 -5
- package/esm/models/app.d.ts +9 -1
- package/esm/models/app.js +7 -1
- package/esm/models/{event.d.ts → audit-event.d.ts} +6 -6
- package/esm/models/{event.js → audit-event.js} +7 -6
- package/esm/models/{request-payload-preview.d.ts → body-preview.d.ts} +4 -4
- package/esm/models/{request-payload-preview.js → body-preview.js} +5 -4
- package/esm/models/create-environment.d.ts +51 -0
- package/esm/models/create-environment.js +35 -0
- package/esm/models/credentials.d.ts +31 -0
- package/esm/models/credentials.js +31 -0
- package/esm/models/environment-failure.d.ts +22 -0
- package/esm/models/environment-failure.js +25 -0
- package/esm/models/environment-status.d.ts +14 -0
- package/esm/models/environment-status.js +15 -0
- package/esm/models/environment.d.ts +27 -27
- package/esm/models/environment.js +28 -27
- package/esm/models/error.d.ts +38 -0
- package/esm/models/error.js +39 -0
- package/esm/models/errors/{error-response.d.ts → error.d.ts} +5 -5
- package/esm/models/errors/{error-response.js → error.js} +4 -4
- package/esm/models/errors/index.d.ts +1 -1
- package/esm/models/errors/index.js +1 -1
- package/esm/models/index.d.ts +17 -20
- package/esm/models/index.js +17 -20
- package/esm/models/me.d.ts +66 -0
- package/esm/models/me.js +75 -0
- package/esm/models/operations/create-credentials.d.ts +25 -0
- package/esm/models/operations/create-credentials.js +20 -0
- package/esm/models/operations/create-environment.d.ts +14 -0
- package/esm/models/operations/create-environment.js +18 -0
- package/esm/models/operations/create-snapshot.d.ts +25 -0
- package/esm/models/operations/create-snapshot.js +25 -0
- package/esm/models/operations/delete-environment.d.ts +13 -0
- package/esm/models/operations/delete-environment.js +17 -0
- package/esm/models/operations/delete-snapshot.d.ts +0 -12
- package/esm/models/operations/delete-snapshot.js +0 -9
- package/esm/models/operations/get-environment.d.ts +0 -12
- package/esm/models/operations/get-environment.js +0 -9
- package/esm/models/operations/get-request-body.d.ts +21 -0
- package/esm/models/operations/{get-environment-request-payload.js → get-request-body.js} +3 -4
- package/esm/models/operations/get-request-stats.d.ts +51 -0
- package/esm/models/operations/get-request-stats.js +40 -0
- package/esm/models/operations/get-request.d.ts +11 -0
- package/esm/models/operations/get-request.js +11 -0
- package/esm/models/operations/get-snapshot.d.ts +0 -12
- package/esm/models/operations/get-snapshot.js +0 -9
- package/esm/models/operations/get-workspace.d.ts +0 -12
- package/esm/models/operations/get-workspace.js +0 -9
- package/esm/models/operations/index.d.ts +13 -16
- package/esm/models/operations/index.js +13 -16
- package/esm/models/operations/list-apps.d.ts +26 -0
- package/esm/models/operations/list-apps.js +23 -0
- package/esm/models/operations/list-audit-events.d.ts +30 -0
- package/esm/models/operations/list-audit-events.js +25 -0
- package/esm/models/operations/list-environments.d.ts +6 -21
- package/esm/models/operations/list-environments.js +3 -16
- package/esm/models/operations/list-requests.d.ts +68 -0
- package/esm/models/operations/list-requests.js +53 -0
- package/esm/models/operations/list-snapshots.d.ts +8 -6
- package/esm/models/operations/list-snapshots.js +4 -3
- package/esm/models/operations/list-versions.d.ts +28 -0
- package/esm/models/operations/list-versions.js +24 -0
- package/esm/models/operations/list-workspaces.d.ts +8 -4
- package/esm/models/operations/list-workspaces.js +7 -4
- package/esm/models/operations/pause-environment.d.ts +13 -0
- package/esm/models/operations/pause-environment.js +17 -0
- package/esm/models/operations/resume-environment.d.ts +0 -12
- package/esm/models/operations/resume-environment.js +0 -9
- package/esm/models/operations/update-environment.d.ts +29 -0
- package/esm/models/operations/update-environment.js +20 -0
- package/esm/models/operations/update-snapshot.d.ts +0 -14
- package/esm/models/operations/update-snapshot.js +0 -10
- package/esm/models/permission.d.ts +17 -0
- package/esm/models/permission.js +18 -0
- package/esm/models/principal.d.ts +20 -0
- package/esm/models/principal.js +24 -0
- package/esm/models/request-detail.d.ts +39 -0
- package/esm/models/request-detail.js +38 -0
- package/esm/models/{environment-request-stats.d.ts → request-stats.d.ts} +3 -3
- package/esm/models/{environment-request-stats.js → request-stats.js} +3 -3
- package/esm/models/request.d.ts +30 -0
- package/esm/models/{environment-request.js → request.js} +11 -11
- package/esm/models/snapshot-status.d.ts +13 -0
- package/esm/models/snapshot-status.js +14 -0
- package/esm/models/snapshot.d.ts +47 -0
- package/esm/models/snapshot.js +54 -0
- package/esm/models/version.d.ts +27 -0
- package/esm/models/version.js +31 -0
- package/esm/models/workspace.d.ts +2 -4
- package/esm/models/workspace.js +2 -4
- package/esm/sdk/apps.d.ts +6 -0
- package/esm/sdk/apps.js +15 -0
- package/esm/sdk/audit-events.d.ts +5 -0
- package/esm/sdk/audit-events.js +11 -0
- package/esm/sdk/environments.d.ts +8 -13
- package/esm/sdk/environments.js +18 -38
- package/esm/sdk/requests.d.ts +9 -0
- package/esm/sdk/requests.js +23 -0
- package/esm/sdk/sdk.d.ts +11 -8
- package/esm/sdk/sdk.js +16 -11
- package/esm/sdk/snapshots.d.ts +6 -5
- package/esm/sdk/snapshots.js +7 -7
- package/esm/sdk/workspaces.d.ts +1 -2
- package/esm/sdk/workspaces.js +0 -4
- package/openapi.json +1697 -2507
- package/package.json +15 -13
- package/esm/extensions/apps.d.ts +0 -18
- package/esm/extensions/apps.js +0 -39
- package/esm/extensions/connection.d.ts +0 -42
- package/esm/extensions/connection.js +0 -133
- package/esm/extensions/running-environment.d.ts +0 -46
- package/esm/extensions/running-environment.js +0 -66
- package/esm/funcs/create-environment-definition.d.ts +0 -11
- package/esm/funcs/create-environment-definition.js +0 -94
- package/esm/funcs/credential-get.js +0 -76
- package/esm/funcs/environments-get-request-payload.d.ts +0 -11
- package/esm/funcs/environments-get-request.d.ts +0 -11
- package/esm/funcs/environments-get-request.js +0 -96
- package/esm/funcs/environments-list-requests.d.ts +0 -11
- package/esm/funcs/environments-reveal.d.ts +0 -11
- package/esm/funcs/environments-suspend.d.ts +0 -11
- package/esm/funcs/snapshots-capture.d.ts +0 -11
- package/esm/models/app-instance-snapshot.d.ts +0 -15
- package/esm/models/app-instance-snapshot.js +0 -19
- package/esm/models/catalog.d.ts +0 -12
- package/esm/models/catalog.js +0 -15
- package/esm/models/connection-secret.d.ts +0 -30
- package/esm/models/connection-secret.js +0 -31
- package/esm/models/connection.d.ts +0 -40
- package/esm/models/connection.js +0 -44
- package/esm/models/create-environment-input.d.ts +0 -39
- package/esm/models/create-environment-input.js +0 -25
- package/esm/models/credential-kind.d.ts +0 -9
- package/esm/models/credential-kind.js +0 -10
- package/esm/models/credential.d.ts +0 -48
- package/esm/models/credential.js +0 -44
- package/esm/models/environment-app.d.ts +0 -45
- package/esm/models/environment-app.js +0 -47
- package/esm/models/environment-lifetime.d.ts +0 -10
- package/esm/models/environment-lifetime.js +0 -14
- package/esm/models/environment-request-detail.d.ts +0 -40
- package/esm/models/environment-request-detail.js +0 -39
- package/esm/models/environment-request.d.ts +0 -31
- package/esm/models/environment-snapshot.d.ts +0 -40
- package/esm/models/environment-snapshot.js +0 -42
- package/esm/models/error-response.d.ts +0 -57
- package/esm/models/error-response.js +0 -59
- package/esm/models/event-page.d.ts +0 -11
- package/esm/models/event-page.js +0 -16
- package/esm/models/operations/capture-snapshot.d.ts +0 -41
- package/esm/models/operations/capture-snapshot.js +0 -36
- package/esm/models/operations/create-environment-definition.d.ts +0 -153
- package/esm/models/operations/create-environment-definition.js +0 -93
- package/esm/models/operations/create-environments.d.ts +0 -27
- package/esm/models/operations/create-environments.js +0 -27
- package/esm/models/operations/get-catalog.d.ts +0 -13
- package/esm/models/operations/get-catalog.js +0 -13
- package/esm/models/operations/get-connection.d.ts +0 -25
- package/esm/models/operations/get-connection.js +0 -21
- package/esm/models/operations/get-credential.d.ts +0 -13
- package/esm/models/operations/get-credential.js +0 -13
- package/esm/models/operations/get-environment-request-payload.d.ts +0 -23
- package/esm/models/operations/get-environment-request-stats.d.ts +0 -70
- package/esm/models/operations/get-environment-request-stats.js +0 -55
- package/esm/models/operations/get-environment-request.d.ts +0 -25
- package/esm/models/operations/get-environment-request.js +0 -21
- package/esm/models/operations/get-release.d.ts +0 -23
- package/esm/models/operations/get-release.js +0 -20
- package/esm/models/operations/list-environment-events.d.ts +0 -15
- package/esm/models/operations/list-environment-events.js +0 -13
- package/esm/models/operations/list-environment-requests.d.ts +0 -75
- package/esm/models/operations/list-environment-requests.js +0 -59
- package/esm/models/operations/list-workspace-events.d.ts +0 -15
- package/esm/models/operations/list-workspace-events.js +0 -13
- package/esm/models/operations/reveal-connection.d.ts +0 -59
- package/esm/models/operations/reveal-connection.js +0 -55
- package/esm/models/operations/stop-environment.d.ts +0 -25
- package/esm/models/operations/stop-environment.js +0 -26
- package/esm/models/operations/suspend-environment.d.ts +0 -25
- package/esm/models/operations/suspend-environment.js +0 -26
- package/esm/models/release-actor.d.ts +0 -11
- package/esm/models/release-actor.js +0 -15
- package/esm/models/release.d.ts +0 -37
- package/esm/models/release.js +0 -39
- package/esm/sdk/catalog.d.ts +0 -6
- package/esm/sdk/catalog.js +0 -15
- package/esm/sdk/credential.d.ts +0 -5
- package/esm/sdk/credential.js +0 -11
package/agents/SKILL.md
CHANGED
|
@@ -1,80 +1,71 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: state-machines
|
|
3
|
-
description: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a
|
|
3
|
+
description: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a disposable copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - creating environments, credentials, choosing an actor, snapshots, pausing and resuming, cleanup, and errors such as environment_limit_reached and version_unavailable. Also use when the user mentions State Machines, STATEMACHINES_API_KEY or @usestatemachines/sdk.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
Read `node_modules/@usestatemachines/sdk/README.md` before relying on memory; it matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.
|
|
7
7
|
|
|
8
8
|
## Workflow
|
|
9
9
|
|
|
10
|
-
1. Check that `
|
|
11
|
-
2.
|
|
12
|
-
3. Open a `try` right after `
|
|
13
|
-
4.
|
|
14
|
-
5. Call the app with
|
|
15
|
-
6. In `finally`, `await env.stop()`; it ends the environment and discards its data. In CI, then `await env.waitUntilStopped()`.
|
|
10
|
+
1. Check that `STATEMACHINES_API_KEY` is set without printing it (`test -n "$STATEMACHINES_API_KEY"`). If it isn't, ask the user to set it; the SDK doesn't read `.env` files.
|
|
11
|
+
2. Create the environment with only the apps the task needs: `const env = await sm.environments.create({ apps: ['salesforce'] })`. Log `await sm.apps.list()` for each app's ID; don't guess IDs. `create` waits until the environment is `running`. If the start fails, the server deletes the environment and `create` throws `EnvironmentFailedError` with `err.environment.failure`.
|
|
12
|
+
3. Open a `try` right after `create` returns, and call `await env.delete()` in its `finally`. It deletes the environment and its data.
|
|
13
|
+
4. Get credentials for one app: `const crm = await env.connect('salesforce')`. This acts as the app's default actor, the Salesforce administrator. To act with another user's permissions, pass an `actorId` from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name.
|
|
14
|
+
5. Call the app with `crm.fetch(path)`. A leading `/` means the root of the app's `url`.
|
|
16
15
|
|
|
17
16
|
The whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.
|
|
18
17
|
|
|
19
18
|
```ts
|
|
20
19
|
import { StateMachines } from '@usestatemachines/sdk';
|
|
21
20
|
|
|
22
|
-
const sm = new StateMachines(); // reads
|
|
23
|
-
const env = await sm.environments.
|
|
21
|
+
const sm = new StateMachines(); // reads STATEMACHINES_API_KEY
|
|
22
|
+
const env = await sm.environments.create({ apps: ['salesforce'] });
|
|
24
23
|
|
|
25
24
|
try {
|
|
26
|
-
const salesforce = await env.connect('salesforce'
|
|
25
|
+
const salesforce = await env.connect('salesforce');
|
|
27
26
|
const res = await salesforce.fetch('/services/data/v67.0/limits');
|
|
28
27
|
console.log(res.status, await res.json());
|
|
29
28
|
} finally {
|
|
30
|
-
await env.
|
|
29
|
+
await env.delete();
|
|
31
30
|
}
|
|
32
31
|
```
|
|
33
32
|
|
|
34
33
|
## Rules
|
|
35
34
|
|
|
36
|
-
- Always
|
|
37
|
-
- `env.
|
|
38
|
-
- To
|
|
39
|
-
-
|
|
40
|
-
-
|
|
41
|
-
- Never print, log or commit `
|
|
42
|
-
- Salesforce's SOAP
|
|
43
|
-
- `
|
|
44
|
-
- Runtimes: Node.js
|
|
45
|
-
- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.
|
|
46
|
-
-
|
|
47
|
-
- To reuse seeded data, `await env.
|
|
48
|
-
- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `
|
|
35
|
+
- Always delete in `finally`.
|
|
36
|
+
- `env.pause()` releases the compute and keeps the data; it is not cleanup. `env.resume()` waits until `running` again. A paused or failed environment is deleted after one day, and still needs `env.delete()` once you are done.
|
|
37
|
+
- To create without waiting, pass `{ wait: false }`, then `sm.environments.wait(env.id, { status: 'running' })`.
|
|
38
|
+
- The time limit counts `starting` and `running`. `(await sm.me()).limits.timeLimitMinutes` gives its `default` and `maximum`. Set `timeLimitMinutes` in `create` for longer runs.
|
|
39
|
+
- Running environments are capped per organization: `limits.concurrentEnvironments` from `sm.me()`. Delete the ones you no longer need. A paused or failed environment doesn't count until it resumes.
|
|
40
|
+
- Never print, log or commit `STATEMACHINES_API_KEY`, `credentials.token` or `credentials.headers`.
|
|
41
|
+
- Salesforce's SOAP API takes the actor token in the envelope, not a header: put `crm.token` in `SessionHeader/sessionId`. `crm.fetch` then sends only the environment token header.
|
|
42
|
+
- `crm.fetch` never sends your API key, never follows redirects and only reaches URLs under the app's `url`.
|
|
43
|
+
- Runtimes: Node.js, at the versions in the package's `engines` field, and Cloudflare Workers. ESM only. TypeScript needs `lib: ["DOM"]` or `@types/node`. Never ship an API key to a browser.
|
|
44
|
+
- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`. A start takes longer than one request may last, so create with `{ wait: false }` and read `sm.environments.get(id)` in later requests until it is `running`, or pass a `signal` no shorter than the expected start.
|
|
45
|
+
- Every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.
|
|
46
|
+
- To reuse seeded data, `await env.snapshots.create({ name })` once, then `sm.environments.create({ snapshotId })` in place of `apps`.
|
|
47
|
+
- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `SnapshotFailedError`, `UnexpectedStatusError`, `WaitTimeoutError`), not by `name`.
|
|
49
48
|
|
|
50
49
|
## Recovering a failed create
|
|
51
50
|
|
|
52
|
-
The SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If
|
|
51
|
+
The SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If you need to replay a create whose outcome is unknown, pass your own key: `sm.environments.create(input, { idempotencyKey })`, and call it again with the same input and key. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency_key_reused`.
|
|
53
52
|
|
|
54
53
|
## Troubleshooting
|
|
55
54
|
|
|
56
55
|
| Symptom | Cause | Fix |
|
|
57
56
|
| --- | --- | --- |
|
|
58
|
-
| `
|
|
59
|
-
| `
|
|
60
|
-
| `
|
|
61
|
-
| `
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
65
|
-
| `
|
|
66
|
-
| `
|
|
67
|
-
| `
|
|
68
|
-
| `
|
|
69
|
-
|
|
|
70
|
-
|
|
|
71
|
-
| `not-ready`, 409 | Capture: the environment isn't `running` or an app isn't `ready`. Restore: the snapshot isn't `ready` yet. Delete: the snapshot is still `capturing`. | Capture from the handle `start()` returns. Before a restore or delete, `await sm.snapshots.waitUntilReady(snapshotId)`. |
|
|
72
|
-
| `capture-in-progress`, 409 | This environment is already capturing; one capture runs at a time. | `await sm.snapshots.waitUntilReady(<the running snapshot's id>)`, then capture again. |
|
|
73
|
-
| `snapshot-limit`, 429 | Older APIs only: too many captures were running. `capture` and `env.snapshot()` already retried it for 60 seconds. | Wait, then capture again. |
|
|
74
|
-
| `SnapshotFailedError` | The capture failed. `err.snapshot.errorCode` is `capture-failed`, or `capture-interrupted` when the API restarted mid-capture. The snapshot is kept. | Capture again with a new idempotency key (the default); the old key returns the same failed snapshot. |
|
|
75
|
-
| `SnapshotTimeoutError` | The snapshot wasn't `ready` within `readyTimeoutMs`. The capture continues on the server. | `await sm.snapshots.waitUntilReady(err.snapshotId)`. |
|
|
76
|
-
| `forbidden`, 403, from `sm.snapshots.delete` | The key lacks `snapshots:delete`. Keys created by members never hold it. | Use a key whose creator holds `snapshots:delete`, or keep the snapshot. |
|
|
77
|
-
| `release-unavailable`, 422, on a restore | No release on this deployment matches the snapshot's apps. | Start from `apps`, seed again and capture a new snapshot. |
|
|
78
|
-
| `TypeError: Pass apiKey or set STATE_API_KEY.` | No key in the environment. | Ask the user to set `STATE_API_KEY`; in Workers, pass `apiKey`. |
|
|
57
|
+
| `version_unavailable`, 422 | The app has no default version. | Check the app ID against `sm.apps.list()`. |
|
|
58
|
+
| `environment_limit_reached`, 429 | The organization is at its cap of running environments. | List them with `sm.environments.list({ status: ['starting', 'running'] })`, delete or pause one, then create again. |
|
|
59
|
+
| `invalid_status`, 409 | The status does not allow the call, for example pausing an environment that is `starting`. | Read `sm.environments.get(id)` and act on its `status`. |
|
|
60
|
+
| `invalid_request`, 400 | A wrong field. | Read `err.fields`, keyed by dotted path. |
|
|
61
|
+
| `EnvironmentFailedError` | The environment failed to start or resume. | Read `err.environment.failure`: `{ app, code, message }`. `invalid_settings` means the app refused its settings. |
|
|
62
|
+
| `UnexpectedStatusError` | The environment was paused or deleted while the SDK waited. | Read `err.status` and `err.resource`. |
|
|
63
|
+
| `WaitTimeoutError` | The status was not reached within `timeoutMs`. | Wait again with `sm.environments.wait(id, { status })`, or delete the environment. |
|
|
64
|
+
| `snapshot_in_progress`, 409 | The environment already has a snapshot in `saving`. | `const [running] = (await sm.snapshots.list({ environmentId: env.id, status: ['saving'] })).data`, then `await sm.snapshots.wait(running.id, { status: 'ready' })`, then create another. |
|
|
65
|
+
| `SnapshotFailedError` | The snapshot failed. `interrupted` means the environment was paused or deleted first. | Create another snapshot while the environment is `running`. |
|
|
66
|
+
| `environment_not_running`, 409, from `crm.fetch` | The environment is paused, failed or deleted. `crm.fetch` returns it as a response and never retries. | Read `(await res.json()).error.status`; `env.resume()` a paused or failed environment. |
|
|
67
|
+
| `environment_starting` or `environment_unavailable`, 503, from `crm.fetch` | The app is starting or restarting. | Wait the `Retry-After` seconds and call again. |
|
|
68
|
+
| A vendor client such as jsforce is refused by the gateway | The gateway needs `StateMachines-Environment-Token` on every request. | Prefer `crm.fetch`. If you pass `crm.headers` to another client, send them only to `crm.url` and disable redirects. |
|
|
69
|
+
| `TypeError: Pass apiKey or set STATEMACHINES_API_KEY.` | No key in the environment. | Ask the user to set `STATEMACHINES_API_KEY`; in Workers, pass `apiKey`. |
|
|
79
70
|
|
|
80
|
-
More: https://
|
|
71
|
+
More: https://docs.usestatemachines.com, https://app.usestatemachines.com/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk
|
package/agents/index.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
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 so this project can run code against a disposable replica of a SaaS app, such as Salesforce. Follow these steps in order.\n\n1. Install the SDK: `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js
|
|
4
|
+
"Set up State Machines so this project can run code against a disposable replica of a SaaS app, such as Salesforce. Follow these steps in order.\n\n1. Install the SDK: `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js, at the versions in its `engines` field, and on Cloudflare Workers, not in browsers.\n2. Check that `STATEMACHINES_API_KEY` is set without printing it: `test -n \"$STATEMACHINES_API_KEY\"`. If it is missing, stop and ask me to set it; the SDK doesn't read `.env` files. In Cloudflare Workers, pass the key as `new StateMachines({ apiKey })`.\n3. Save this quickstart unchanged as `state-quickstart.mts` and run `npx tsx state-quickstart.mts` to confirm the setup. It prints `200` and the Salesforce org's limits:\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\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\n4. Adapt it to my task. Log `await sm.apps.list()` to find each app's ID, and `await sm.apps.versions(appId)` for the actors and APIs of its versions; don't guess IDs. Create only the apps the task needs; a string such as `'salesforce'` names the app and also becomes its name in the environment. `connect()` acts as the app's default actor, the Salesforce administrator; to act as another user, pass an `actorId` from the version's `actors`. To reuse seeded data, create a snapshot once with `await env.snapshots.create()`, then `sm.environments.create({ snapshotId })`.\n5. Always call `env.delete()` in a `finally`; it deletes the environment and its data. If the start fails, the server deletes the environment itself and `create` throws `EnvironmentFailedError`. Pass your own `idempotencyKey` to `create`; if it throws with no response, call it again with the same input and key.\n6. Never print, log or commit keys or tokens, including `credentials.token` and `credentials.headers`.\n\nRead more: https://docs.usestatemachines.com, `node_modules/@usestatemachines/sdk/README.md`, https://app.usestatemachines.com/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\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, for tests and coding agents. Start, connect to, suspend, resume and stop them with the TypeScript SDK `@usestatemachines/sdk`.\n\nInstall with `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js 20.20 or later (22 or 24 recommended) and Cloudflare Workers, not browsers. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. `new StateMachines()` reads the API key from `STATE_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.\n\n## Concepts\n\n- Environment: one disposable run of one or more apps. `const env = await sm.environments.start({ apps: ['salesforce'] })` creates it, waits until it is `running` and returns a `RunningEnvironment`. If the environment fails or the wait times out or is aborted, `start()` stops the environment and rethrows the original error; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`. Always call `env.stop()` in a `finally`.\n- Suspend and resume: `env.suspend()` ends the sandboxes and keeps the data; the lifetime pauses. Await `env.waitUntilSuspended()`, later `env.resume()` and `env.waitUntilReady()` to run again on the same data. `env.stop()` ends the environment and discards its data; a suspended environment still needs it.\n- Apps: a string is shorthand for `{ key: s, appId: s }`, nothing more. Use the object form, such as `{ key: 'crm', appId: 'salesforce' }`, for your own key or two instances of one app. `appId` names the app in the catalog (`sm.catalog.get()`); `key` is your name for it in this environment, and later calls take the key.\n- Actor: one of the app's users; requests run with that user's permissions. Salesforce actor IDs are its user IDs, such as `005…`, never a role name. `await env.actors('salesforce')` lists them in the release's order. connect() acts as the environment's declared default connection's actor, or else the first actor, the administrator, unless you pass `actorId`; pick a less-privileged actor to test permissions.\n- API profile: one API of the app, with its path and versions. Salesforce offers several (`rest`, `soap-partner`, `bulk2`, `oauth`) and has no default, so always pass `apiId`: `env.connect('salesforce', { apiId: 'rest' })`.\n- Connection: `connection.fetch` never sends your API key, never follows redirects and never retries. `connection.headers()` returns live tokens: treat them as secrets. Salesforce's SOAP profile (`soap-partner`) takes the actor token in the envelope instead: put `connection.actorToken()`, also a secret, in `SessionHeader/sessionId`; `headers()` then carries only `X-State-Environment-Token`.\n- Full control: `sm.environments.create(input)` returns one `Environment` before the apps boot, `sm.environments.waitUntilReady(environment.id)` waits, and `sm.environments.connect(environment.id, key, options)` connects. Nothing on this path stops the environment for you; use it to keep a failed environment for inspection.\n- Snapshot: the saved data of a running environment's apps. Every app is paused while it is cut, so a multi-app snapshot is one instant (`consistency: 'environment'`); a single app is `'app_instance'`. `const snapshot = await env.snapshot({ name: 'seeded' })` captures it and waits until it is `ready`. `sm.environments.start({ snapshotId: snapshot.id })` starts a new environment from it, in place of `apps`; each app keeps its key. Capturing needs `snapshots:create` and `snapshots:read`, restoring needs `snapshots:read`, `rename` needs `snapshots:create`, and `sm.snapshots.delete(id)` needs `snapshots:delete`, which keys created by members don't hold. Snapshots are never deleted automatically, not even failed or timed-out ones: `SnapshotFailedError` and `SnapshotTimeoutError` carry `err.snapshotId`. `sm.snapshots` also has `create`, `waitUntilReady`, `get`, `list` and `rename`.\n- Recorded requests: `sm.environments.listRequests(env.id)` pages the calls made to the environment's apps (method, path, status, duration); `getRequest(env.id, id)` adds headers and bodies. Recording is best effort and SOAP bodies are not stored.\n- Vendor clients: the gateway needs `X-State-Environment-Token` on every request. A client such as jsforce only sends it if you configure custom headers. Prefer `connection.fetch`; if you pass `headers()` to another client, send them only to `connection.baseUrl` and disable redirects.\n- Pagination: `environments.list`, `environments.events`, `workspaces.events` and `snapshots.list` return 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`: `queued`, `starting`, `running`, `suspending`, `suspended`, `stopping`, `stopped`, `failed`. `stopReason`: `requested`, `expired`, `app_failed`, `owner_lost`. A suspended environment keeps its data and carries `suspendedAt`.\n- App `status`: `pending`, `starting`, `ready`, `recovering`, `suspended`, `stopping`, `stopped`, `failed`. A failed app carries `errorCode`.\n- App `disposal`: `pending`, `complete`, `failed`, `unknown`.\n- Snapshot `status`: `capturing`, `ready`, `failed`. A failed snapshot carries `errorCode`: `capture-failed`, `pause-failed` or `pause-lost` when the apps could not be held paused for the capture, or `capture-interrupted` when the API restarted mid-capture.\n- `start()` and `waitUntilReady` throw `EnvironmentFailedError` if the environment becomes `failed`, `suspending`, `suspended`, `stopping` or `stopped`, and `TimeoutError` after 10 minutes by default (`readyTimeoutMs` for `start()`, `timeoutMs` for `waitUntilReady`). `start()` then stops the environment; `waitUntilReady` never does.\n- `waitUntilSuspended` resolves when the environment is `suspended`, and throws `EnvironmentFailedError` if it ends instead.\n- `waitUntilStopped` resolves when the environment is `stopped` and every app's disposal is `complete`. A `failed` environment keeps its data for `resume()` and is not stopped until you call `stop()`. It throws `DisposalIncompleteError` if a disposal is `failed` or `unknown`, and `TimeoutError` if disposal stays `pending`.\n\n## Limits\n\n- Live environments are capped per organization: `(await sm.credential.get()).limits.liveEnvironments`.\n- `lifetimeMinutes` defaults to 15 minutes, or the deployment maximum if that is lower. Both are in `(await sm.credential.get()).limits.environmentLifetime`. Lifetime counts from the start, so boot uses part of it, and pauses while suspended; at the end the environment stops with `stopReason: 'expired'`.\n- A suspended environment doesn't count toward the live cap; resuming it does.\n- Always call `env.stop()` in a `finally`. In CI, then await `env.waitUntilStopped()`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `requestId` and `retryAfter`. The SDK retries `502`, `503`, `504`, connection errors and attempt timeouts itself, within a 10-minute retry budget (the last attempt can end later); `create` retries reuse one idempotency key. It retries nothing else: not `429`, other `4xx` or other `5xx`. The one exception is snapshot capture, which retries `429` `snapshot-limit` for up to 60 seconds with one idempotency key. `err.stopped === false` with `err.stopError` means the stop wasn't confirmed; `sm.environments.stop(err.environmentId)` is safe to repeat. Without `stopError`, you passed your own `idempotencyKey`, so `start()` left the environment running because another `start()` with that key may be using it; stop it only once nothing else needs it. Every error from `create`, including the create step of `start()`, carries `err.idempotencyKey`: `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same input returns the environment the first call created. Invalid `apps` fail before any request as a `StateMachinesError` (`status` null, `cause` a `TypeError`; don't replay it) with one of: `Pass at least one app.`, `App key \"<key>\" is used twice.` or `\"<s>\" can't be used as an app key; pass { key, appId } instead.`\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment-limit` | 429 | Not retried. Suspend or stop a live environment (`sm.environments.list({ status: 'live' })`), then start or resume again. |\n| `not-ready` | 409 | Only a running environment whose apps are all ready can be suspended. Wait for it, or stop it. |\n| `not-suspended` | 409 | Only a suspended environment can resume. After `suspend()`, await `waitUntilSuspended()` first. |\n| `suspend-in-progress` | 409 | The environment is suspending. Await `waitUntilSuspended()`, then stop it. |\n| `lifetime-too-long` | 422 | Lower `lifetimeMinutes` to at most `limits.environmentLifetime.maximumMinutes`. |\n| `release-unavailable` | 422 | Unknown or retired app or release. Check `appId` and `appReleaseId` against `sm.catalog.get()`. |\n| `release-unavailable` | 503 | This deployment doesn't serve the release. Retried within the budget; omit `appReleaseId` to use the default release, or contact support with the `requestId`. A failed app can carry it as `errorCode`. |\n| `connection-unavailable` | 409 | The app stopped or the environment is no longer `running`. If it is suspended, resume it; if it stopped or expired, start a new one. (Before revealing any token, connect() throws a `TypeError` for an app that isn't ready, an unknown actor, or a missing `apiId`.) |\n| `idempotency-conflict` | 409 | The idempotency key was used with a different input. Replay with the exact same input. |\n| `capture-in-progress` | 409 | This environment is already capturing a snapshot; one runs at a time. Wait for it, then capture again. |\n| `snapshot-limit` | 429 | Older APIs only. `capture` and `env.snapshot()` retry it for up to 60 seconds; if it still fails, wait and capture again. |\n| `not-ready` | 409 | Capture: the environment isn't `running` or an app isn't `ready`. Restore: the snapshot isn't `ready` yet; `await sm.snapshots.waitUntilReady(id)`. Delete: the snapshot is still `capturing`. |\n| `version-conflict` | 409 | `rename` sent a stale `expectedVersion`, or the snapshot was deleted. `get` it: if `deletedAt` is set it's gone, otherwise retry with its `version`. |\n| `release-unavailable` | 422 | On a restore: no release on this deployment matches the snapshot's apps. Start from `apps`, seed again and capture a new snapshot. |\n| `request-timeout` | 503 | Retried automatically. If `create` still fails, replay it with `err.idempotencyKey`. |\n\n## Quickstart\n\nSave it unchanged as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATE_API_KEY\nconst env = await sm.environments.start({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce', { apiId: 'rest' });\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.stop();\n}\n```\n\n## Docs\n\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://state-web.usestatemachines.workers.dev/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): product site\n";
|
|
7
|
+
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, pause, resume and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\nInstall with `npm install @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.\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`. Pass `{ wait: false }` to get it back at once in `starting`. Always call `env.delete()` in a `finally`.\n- Apps: a string names the app, and the app's name in the environment is the same string. Use `{ app: 'salesforce', name: 'crm', settings }` for your own name, for two copies of one app, or for settings. Later calls take the name.\n- Pause and resume: `env.pause()` releases the compute and keeps the data; the time limit stops counting. `env.resume()` boots the apps again on the same data and waits until `running`. A paused environment is deleted after one day.\n- Credentials: `const crm = await env.connect('salesforce')` returns `url`, `headers`, `token` and `fetch`. `crm.fetch(path)` joins `path` to `url`, adds `headers`, and puts `token` in the header of the API whose path matches: `Authorization: Bearer` for Salesforce REST and Bulk 2.0. For Salesforce SOAP, put `crm.token` in the envelope's `SessionHeader/sessionId` yourself. `fetch` never sends your API key, never follows redirects and never retries. `token` and `headers` are secrets.\n- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Read them from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`.\n- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A pause or delete during the snapshot fails it with `interrupted`.\n- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.\n- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.\n- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n\n## Statuses\n\nEnums are open: handle values you don't recognise.\n\n- Environment `status`: `starting`, `running`, `paused`, `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. A `failed` environment keeps its data for `resume()` and has `failure`: `{ app, code, message }` with `start_failed`, `resume_failed`, `restart_failed`, `version_unavailable` or `invalid_settings`.\n- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.\n- `create` and `resume` throw `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `paused` or `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.\n- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.\n- `sm.environments.wait(id, { status })` and `sm.snapshots.wait(id, { status })` wait for any status, and throw once it cannot be reached without another call.\n\n## Limits\n\n- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.\n- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `message`, `requestId`, `fields` and `retryAfterMs`. The SDK retries `502`, `503`, `504` and connection errors itself, until a deadline; `create` retries reuse one idempotency key. It retries nothing else.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |\n| `forbidden` | 403 | The key lacks the permission. |\n| `not_found` | 404 | Check the ID and the workspace. |\n| `invalid_status` | 409 | The status does not allow the call: pause needs `running`; resume needs `paused` or `failed`. |\n| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |\n| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |\n| `workspace_archived` | 409 | The workspace is archived. |\n| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |\n| `version_unavailable` | 422 | The app has no default version. |\n| `environment_limit_reached` | 429 | Pause or delete an environment, then create or resume again. |\n| `unavailable` | 503 | Retried automatically. If `create` still fails, call it again with the same input and your own `idempotencyKey`. |\n\n## Errors from the app URL\n\n`crm.fetch` returns these as responses with the same JSON envelope, and never retries them.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment_not_running` | 409 | The environment is paused, failed or deleted; `error.status` names it. Resume a paused or failed environment. |\n| `environment_starting` | 503 | Wait `Retry-After` and call again. |\n| `environment_unavailable` | 503 | The app is restarting. Wait `Retry-After` and call again. |\n| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |\n| `capacity_exceeded` | 429 | Too many requests in flight to the app. Send fewer at once. |\n| `unsupported_protocol` | 501 | The app does not serve this API version or protocol. |\n\n## Quickstart\n\nSave it unchanged as `state-quickstart.mts` and 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({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Docs\n\n- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://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";
|
|
8
8
|
|
|
9
9
|
export const skill =
|
|
10
|
-
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a sandboxed copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - starting environments, choosing an actor, snapshots, suspending and resuming, cleanup, and errors such as environment-limit and release-unavailable. Also use when the user mentions State Machines, STATE_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory; it matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATE_API_KEY` is set without printing it (`test -n \"$STATE_API_KEY\"`). If it isn't, ask the user to set it; the SDK doesn't read `.env` files.\n2. Start the environment with only the apps the task needs: `const env = await sm.environments.start({ apps: ['salesforce'] })`. Log `await sm.catalog.get()` for each app's ID and the actors and API profiles its release offers; don't guess IDs. A string app means `{ key: s, appId: s }`; use `{ key, appId }` for your own key. `start()` waits until the environment is `running`. If that fails, it stops the environment and rethrows; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`.\n3. Open a `try` right after `start()` returns, and call `env.stop()` in its `finally`.\n4. Connect through one API profile. Salesforce offers several and has no default, so pass `apiId`: `env.connect('salesforce', { apiId: 'rest' })`. This acts as the environment's declared default connection's actor, or else the app's first actor, the administrator. To act with another user's permissions, choose one from `await env.actors('salesforce')` and pass its `id` as `actorId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name, so read them instead of hard-coding one.\n5. Call the app with the connection's `fetch`. A leading `/` means the root of `baseUrl`.\n6. In `finally`, `await env.stop()`; it ends the environment and discards its data. In CI, then `await env.waitUntilStopped()`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATE_API_KEY\nconst env = await sm.environments.start({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce', { apiId: 'rest' });\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.stop();\n}\n```\n\n## Rules\n\n- Always stop in `finally`. `waitUntilStopped` confirms every app was disposed; use it in CI so a run fails when cleanup can't be confirmed.\n- `env.suspend()` ends the sandboxes and keeps the data, with the lifetime paused; it is not cleanup. Await `env.waitUntilSuspended()` before `env.resume()`, then `env.waitUntilReady()` before connecting again. A suspended environment still needs `env.stop()`.\n- To keep a failed environment for inspection, use the full-control path: `sm.environments.create`, then `sm.environments.waitUntilReady(environment.id)`, then `sm.environments.connect(environment.id, key, options)`. Nothing on that path stops the environment for you.\n- Lifetime counts from the start, including boot. It defaults to 15 minutes, or the deployment maximum if that is lower: `(await sm.credential.get()).limits.environmentLifetime`. Set `lifetimeMinutes` in `start` or `create` for longer runs.\n- Live environments are capped per organization: `limits.liveEnvironments` from `sm.credential.get()`. Stop the ones you no longer need; suspended ones don't count until they resume.\n- Never print, log or commit `STATE_API_KEY`, tokens, or `headers()` or `actorToken()` output.\n- Salesforce's SOAP profile (`soap-partner`) takes the actor token in the envelope, not a header: put `connection.actorToken()` in `SessionHeader/sessionId`. For it, `headers()` carries only `X-State-Environment-Token`.\n- `connection.fetch` never sends your API key, never follows redirects and only reaches URLs under `baseUrl`.\n- Runtimes: Node.js 20.20 or later (22 or 24 recommended), and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATE_API_KEY })`, and bound calls with `{ signal: AbortSignal.timeout(20_000) }`, since retries can take minutes.\n- `environments.list`, `environments.events`, `workspaces.events` and `snapshots.list` return one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshot({ name })` once, then `sm.environments.start({ snapshotId })` in place of `apps`. Capturing needs `snapshots:create` and `snapshots:read`. Snapshots are never deleted automatically, not even failed ones.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `DisposalIncompleteError`, `TimeoutError`, `SnapshotFailedError`, `SnapshotTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If `start()` or `create` still throws with `err.idempotencyKey`, the create failed: don't call it again as a new request, which can start a second environment. Call `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same `input`. Don't replay when `err.status` is `null` and `err.cause` is a `TypeError`: the input was invalid and nothing was sent; fix the input instead. A key only recovers a failed create: don't reuse the key of a `start()` whose wait failed, because the replay returns that stopped environment. With your own key, `start()` doesn't stop the environment on failure, because another `start()` with that key may be using it: the error carries `err.environmentId`, `err.stopped` is `false` and there is no `err.stopError`. Stop it only once nothing else needs it. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency-conflict`. Keys are kept for a day.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `release-unavailable`, 422 | Unknown or retired `appId` or `appReleaseId`. A string app is used as the `appId`. | Check the IDs against `sm.catalog.get()`. Omit `appReleaseId` for the default release. |\n| `release-unavailable`, 503, or a failed app with that `errorCode` | This deployment doesn't serve the release. The SDK retries a 503 within a 10-minute budget. | Omit `appReleaseId`. If it persists, report the `requestId`. Pass a `signal` to bound the wait. |\n| `environment-limit`, 429 | The organization is at its live-environment cap. Not retried. | `sm.environments.list({ status: 'live' })`, stop or suspend one you no longer need, then start again. |\n| `not-suspended` or `suspend-in-progress`, 409 | `resume()` before the environment finished suspending, or `stop()` while it suspends. | Await `env.waitUntilSuspended()` first. |\n| `lifetime-too-long`, 422 | `lifetimeMinutes` is above the maximum. | Use at most `limits.environmentLifetime.maximumMinutes`. |\n| `TypeError: Unknown actor <id> for <appKey>. Choose one of: <ids>.` | The `actorId` isn't one of the app's actors. No token was revealed. | Pass an `id` from `await env.actors(appKey)`, or omit `actorId` to act as the default actor. |\n| `TypeError: Choose one API for <appKey>: <ids>.` | The app has several API profiles and `apiId` is missing or unknown. Salesforce always needs one. | Pass `apiId` from the listed IDs, such as `rest`. |\n| `start()` rejects with `EnvironmentFailedError` or `TimeoutError` | The environment failed, or wasn't `running` within `readyTimeoutMs` (10 minutes by default). If `err.stopped` is `true`, `start()` already stopped it. | Read `err.environment` (`null` on a `TimeoutError` that saw no read): its `stopReason` and each app's `errorCode`. If `err.stopped` is `false`, read `err.stopError` and call `sm.environments.stop(err.environmentId)`. To keep a failed environment, use the full-control path. |\n| `StateMachinesError` (`status` null) for invalid `apps`: `Pass at least one app.`, `App key \"<key>\" is used twice.` or `\"<s>\" can't be used as an app key; pass { key, appId } instead.` | Empty list, duplicate key, or a string that isn't a valid key. No request was sent. | Pass one to ten apps with unique keys; use `{ key, appId }` when the ID isn't a valid key. |\n| `TypeError: App ... is not ready to connect` | On the full-control path, connect() ran before the app was `ready`. | Await `waitUntilReady` first, or use `start()`. |\n| `connection-unavailable`, 409 | The app stopped, or the environment is no longer `running`. | Check `sm.environments.get(env.id)`; if it is suspended, resume it; if it stopped or expired, start a new one. |\n| `EnvironmentFailedError` from `waitUntilReady` | On the full-control path, the environment became `failed`, `suspending`, `suspended`, `stopping` or `stopped`. | Read `err.environment.status`, its `stopReason` and each app's `errorCode`. Still stop it in `finally`. |\n| A vendor client such as jsforce is rejected by the gateway | The gateway needs `X-State-Environment-Token` on every request; jsforce only sends it with custom headers configured. | Prefer `connection.fetch`. If you pass `headers()` to another client, send them only to `baseUrl` and disable redirects. |\n| `not-ready`, 409 | Capture: the environment isn't `running` or an app isn't `ready`. Restore: the snapshot isn't `ready` yet. Delete: the snapshot is still `capturing`. | Capture from the handle `start()` returns. Before a restore or delete, `await sm.snapshots.waitUntilReady(snapshotId)`. |\n| `capture-in-progress`, 409 | This environment is already capturing; one capture runs at a time. | `await sm.snapshots.waitUntilReady(<the running snapshot's id>)`, then capture again. |\n| `snapshot-limit`, 429 | Older APIs only: too many captures were running. `capture` and `env.snapshot()` already retried it for 60 seconds. | Wait, then capture again. |\n| `SnapshotFailedError` | The capture failed. `err.snapshot.errorCode` is `capture-failed`, or `capture-interrupted` when the API restarted mid-capture. The snapshot is kept. | Capture again with a new idempotency key (the default); the old key returns the same failed snapshot. |\n| `SnapshotTimeoutError` | The snapshot wasn't `ready` within `readyTimeoutMs`. The capture continues on the server. | `await sm.snapshots.waitUntilReady(err.snapshotId)`. |\n| `forbidden`, 403, from `sm.snapshots.delete` | The key lacks `snapshots:delete`. Keys created by members never hold it. | Use a key whose creator holds `snapshots:delete`, or keep the snapshot. |\n| `release-unavailable`, 422, on a restore | No release on this deployment matches the snapshot's apps. | Start from `apps`, seed again and capture a new snapshot. |\n| `TypeError: Pass apiKey or set STATE_API_KEY.` | No key in the environment. | Ask the user to set `STATE_API_KEY`; in Workers, pass `apiKey`. |\n\nMore: https://state-web.usestatemachines.workers.dev/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n";
|
|
10
|
+
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a disposable copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - creating environments, credentials, choosing an actor, snapshots, pausing and resuming, cleanup, and errors such as environment_limit_reached and version_unavailable. Also use when the user mentions State Machines, STATEMACHINES_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory; it matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATEMACHINES_API_KEY` is set without printing it (`test -n \"$STATEMACHINES_API_KEY\"`). If it isn't, ask the user to set it; the SDK doesn't read `.env` files.\n2. Create the environment with only the apps the task needs: `const env = await sm.environments.create({ apps: ['salesforce'] })`. Log `await sm.apps.list()` for each app's ID; don't guess IDs. `create` waits until the environment is `running`. If the start fails, the server deletes the environment and `create` throws `EnvironmentFailedError` with `err.environment.failure`.\n3. Open a `try` right after `create` returns, and call `await env.delete()` in its `finally`. It deletes the environment and its data.\n4. Get credentials for one app: `const crm = await env.connect('salesforce')`. This acts as the app's default actor, the Salesforce administrator. To act with another user's permissions, pass an `actorId` from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name.\n5. Call the app with `crm.fetch(path)`. A leading `/` means the root of the app's `url`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and 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({ apps: ['salesforce'] });\n\ntry {\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## Rules\n\n- Always delete in `finally`.\n- `env.pause()` releases the compute and keeps the data; it is not cleanup. `env.resume()` waits until `running` again. A paused or failed environment is deleted after one day, and still needs `env.delete()` once you are done.\n- To create without waiting, pass `{ wait: false }`, then `sm.environments.wait(env.id, { status: 'running' })`.\n- The time limit counts `starting` and `running`. `(await sm.me()).limits.timeLimitMinutes` gives its `default` and `maximum`. Set `timeLimitMinutes` in `create` for longer runs.\n- Running environments are capped per organization: `limits.concurrentEnvironments` from `sm.me()`. Delete the ones you no longer need. A paused or failed environment doesn't count until it resumes.\n- Never print, log or commit `STATEMACHINES_API_KEY`, `credentials.token` or `credentials.headers`.\n- Salesforce's SOAP API takes the actor token in the envelope, not a header: put `crm.token` in `SessionHeader/sessionId`. `crm.fetch` then sends only the environment token header.\n- `crm.fetch` never sends your API key, never follows redirects and only reaches URLs under the app's `url`.\n- Runtimes: Node.js, at the versions in the package's `engines` field, and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`. A start takes longer than one request may last, so create with `{ wait: false }` and read `sm.environments.get(id)` in later requests until it is `running`, or pass a `signal` no shorter than the expected start.\n- Every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshots.create({ name })` once, then `sm.environments.create({ snapshotId })` in place of `apps`.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `SnapshotFailedError`, `UnexpectedStatusError`, `WaitTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If you need to replay a create whose outcome is unknown, pass your own key: `sm.environments.create(input, { idempotencyKey })`, and call it again with the same input and key. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency_key_reused`.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `version_unavailable`, 422 | The app has no default version. | Check the app ID against `sm.apps.list()`. |\n| `environment_limit_reached`, 429 | The organization is at its cap of running environments. | List them with `sm.environments.list({ status: ['starting', 'running'] })`, delete or pause one, then create again. |\n| `invalid_status`, 409 | The status does not allow the call, for example pausing an environment that is `starting`. | Read `sm.environments.get(id)` and act on its `status`. |\n| `invalid_request`, 400 | A wrong field. | Read `err.fields`, keyed by dotted path. |\n| `EnvironmentFailedError` | The environment failed to start or resume. | Read `err.environment.failure`: `{ app, code, message }`. `invalid_settings` means the app refused its settings. |\n| `UnexpectedStatusError` | The environment was paused or deleted while the SDK waited. | Read `err.status` and `err.resource`. |\n| `WaitTimeoutError` | The status was not reached within `timeoutMs`. | Wait again with `sm.environments.wait(id, { status })`, or delete the environment. |\n| `snapshot_in_progress`, 409 | The environment already has a snapshot in `saving`. | `const [running] = (await sm.snapshots.list({ environmentId: env.id, status: ['saving'] })).data`, then `await sm.snapshots.wait(running.id, { status: 'ready' })`, then create another. |\n| `SnapshotFailedError` | The snapshot failed. `interrupted` means the environment was paused or deleted first. | Create another snapshot while the environment is `running`. |\n| `environment_not_running`, 409, from `crm.fetch` | The environment is paused, failed or deleted. `crm.fetch` returns it as a response and never retries. | Read `(await res.json()).error.status`; `env.resume()` a paused or failed environment. |\n| `environment_starting` or `environment_unavailable`, 503, from `crm.fetch` | The app is starting or restarting. | Wait the `Retry-After` seconds and call again. |\n| A vendor client such as jsforce is refused by the gateway | The gateway needs `StateMachines-Environment-Token` on every request. | Prefer `crm.fetch`. If you pass `crm.headers` to another client, send them only to `crm.url` and disable redirects. |\n| `TypeError: Pass apiKey or set STATEMACHINES_API_KEY.` | No key in the environment. | Ask the user to set `STATEMACHINES_API_KEY`; in Workers, pass `apiKey`. |\n\nMore: https://docs.usestatemachines.com, https://app.usestatemachines.com/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n";
|
|
11
11
|
|
|
12
12
|
export const quickstart =
|
|
13
|
-
"import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads
|
|
13
|
+
"import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\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
15
|
export const templates = Object.freeze({
|
|
16
16
|
prompt:
|
|
17
|
-
"Set up State Machines so this project can run code against a disposable replica of a SaaS app, such as Salesforce. Follow these steps in order.\n\n1. Install the SDK: `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js
|
|
17
|
+
"Set up State Machines so this project can run code against a disposable replica of a SaaS app, such as Salesforce. Follow these steps in order.\n\n1. Install the SDK: `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js, at the versions in its `engines` field, and on Cloudflare Workers, not in browsers.\n2. Check that `STATEMACHINES_API_KEY` is set without printing it: `test -n \"$STATEMACHINES_API_KEY\"`. If it is missing, stop and ask me to set it; the SDK doesn't read `.env` files. In Cloudflare Workers, pass the key as `new StateMachines({ apiKey })`.\n3. Save this quickstart unchanged as `state-quickstart.mts` and run `npx tsx state-quickstart.mts` to confirm the setup. It prints `200` and the Salesforce org's limits:\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\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\n4. Adapt it to my task. Log `await sm.apps.list()` to find each app's ID, and `await sm.apps.versions(appId)` for the actors and APIs of its versions; don't guess IDs. Create only the apps the task needs; a string such as `'salesforce'` names the app and also becomes its name in the environment. `connect()` acts as the app's default actor, the Salesforce administrator; to act as another user, pass an `actorId` from the version's `actors`. To reuse seeded data, create a snapshot once with `await env.snapshots.create()`, then `sm.environments.create({ snapshotId })`.\n5. Always call `env.delete()` in a `finally`; it deletes the environment and its data. If the start fails, the server deletes the environment itself and `create` throws `EnvironmentFailedError`. Pass your own `idempotencyKey` to `create`; if it throws with no response, call it again with the same input and key.\n6. Never print, log or commit keys or tokens, including `credentials.token` and `credentials.headers`.\n\nRead more: https://docs.usestatemachines.com, `node_modules/@usestatemachines/sdk/README.md`, {{origin}}/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n",
|
|
18
18
|
llmsTxt:
|
|
19
|
-
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Start, connect to, suspend, resume and stop them with the TypeScript SDK `@usestatemachines/sdk`.\n\nInstall with `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js 20.20 or later (22 or 24 recommended) and Cloudflare Workers, not browsers. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. `new StateMachines()` reads the API key from `STATE_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.\n\n## Concepts\n\n- Environment: one disposable run of one or more apps. `const env = await sm.environments.start({ apps: ['salesforce'] })` creates it, waits until it is `running` and returns a `RunningEnvironment`. If the environment fails or the wait times out or is aborted, `start()` stops the environment and rethrows the original error; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`. Always call `env.stop()` in a `finally`.\n- Suspend and resume: `env.suspend()` ends the sandboxes and keeps the data; the lifetime pauses. Await `env.waitUntilSuspended()`, later `env.resume()` and `env.waitUntilReady()` to run again on the same data. `env.stop()` ends the environment and discards its data; a suspended environment still needs it.\n- Apps: a string is shorthand for `{ key: s, appId: s }`, nothing more. Use the object form, such as `{ key: 'crm', appId: 'salesforce' }`, for your own key or two instances of one app. `appId` names the app in the catalog (`sm.catalog.get()`); `key` is your name for it in this environment, and later calls take the key.\n- Actor: one of the app's users; requests run with that user's permissions. Salesforce actor IDs are its user IDs, such as `005…`, never a role name. `await env.actors('salesforce')` lists them in the release's order. connect() acts as the environment's declared default connection's actor, or else the first actor, the administrator, unless you pass `actorId`; pick a less-privileged actor to test permissions.\n- API profile: one API of the app, with its path and versions. Salesforce offers several (`rest`, `soap-partner`, `bulk2`, `oauth`) and has no default, so always pass `apiId`: `env.connect('salesforce', { apiId: 'rest' })`.\n- Connection: `connection.fetch` never sends your API key, never follows redirects and never retries. `connection.headers()` returns live tokens: treat them as secrets. Salesforce's SOAP profile (`soap-partner`) takes the actor token in the envelope instead: put `connection.actorToken()`, also a secret, in `SessionHeader/sessionId`; `headers()` then carries only `X-State-Environment-Token`.\n- Full control: `sm.environments.create(input)` returns one `Environment` before the apps boot, `sm.environments.waitUntilReady(environment.id)` waits, and `sm.environments.connect(environment.id, key, options)` connects. Nothing on this path stops the environment for you; use it to keep a failed environment for inspection.\n- Snapshot: the saved data of a running environment's apps. Every app is paused while it is cut, so a multi-app snapshot is one instant (`consistency: 'environment'`); a single app is `'app_instance'`. `const snapshot = await env.snapshot({ name: 'seeded' })` captures it and waits until it is `ready`. `sm.environments.start({ snapshotId: snapshot.id })` starts a new environment from it, in place of `apps`; each app keeps its key. Capturing needs `snapshots:create` and `snapshots:read`, restoring needs `snapshots:read`, `rename` needs `snapshots:create`, and `sm.snapshots.delete(id)` needs `snapshots:delete`, which keys created by members don't hold. Snapshots are never deleted automatically, not even failed or timed-out ones: `SnapshotFailedError` and `SnapshotTimeoutError` carry `err.snapshotId`. `sm.snapshots` also has `create`, `waitUntilReady`, `get`, `list` and `rename`.\n- Recorded requests: `sm.environments.listRequests(env.id)` pages the calls made to the environment's apps (method, path, status, duration); `getRequest(env.id, id)` adds headers and bodies. Recording is best effort and SOAP bodies are not stored.\n- Vendor clients: the gateway needs `X-State-Environment-Token` on every request. A client such as jsforce only sends it if you configure custom headers. Prefer `connection.fetch`; if you pass `headers()` to another client, send them only to `connection.baseUrl` and disable redirects.\n- Pagination: `environments.list`, `environments.events`, `workspaces.events` and `snapshots.list` return 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`: `queued`, `starting`, `running`, `suspending`, `suspended`, `stopping`, `stopped`, `failed`. `stopReason`: `requested`, `expired`, `app_failed`, `owner_lost`. A suspended environment keeps its data and carries `suspendedAt`.\n- App `status`: `pending`, `starting`, `ready`, `recovering`, `suspended`, `stopping`, `stopped`, `failed`. A failed app carries `errorCode`.\n- App `disposal`: `pending`, `complete`, `failed`, `unknown`.\n- Snapshot `status`: `capturing`, `ready`, `failed`. A failed snapshot carries `errorCode`: `capture-failed`, `pause-failed` or `pause-lost` when the apps could not be held paused for the capture, or `capture-interrupted` when the API restarted mid-capture.\n- `start()` and `waitUntilReady` throw `EnvironmentFailedError` if the environment becomes `failed`, `suspending`, `suspended`, `stopping` or `stopped`, and `TimeoutError` after 10 minutes by default (`readyTimeoutMs` for `start()`, `timeoutMs` for `waitUntilReady`). `start()` then stops the environment; `waitUntilReady` never does.\n- `waitUntilSuspended` resolves when the environment is `suspended`, and throws `EnvironmentFailedError` if it ends instead.\n- `waitUntilStopped` resolves when the environment is `stopped` and every app's disposal is `complete`. A `failed` environment keeps its data for `resume()` and is not stopped until you call `stop()`. It throws `DisposalIncompleteError` if a disposal is `failed` or `unknown`, and `TimeoutError` if disposal stays `pending`.\n\n## Limits\n\n- Live environments are capped per organization: `(await sm.credential.get()).limits.liveEnvironments`.\n- `lifetimeMinutes` defaults to 15 minutes, or the deployment maximum if that is lower. Both are in `(await sm.credential.get()).limits.environmentLifetime`. Lifetime counts from the start, so boot uses part of it, and pauses while suspended; at the end the environment stops with `stopReason: 'expired'`.\n- A suspended environment doesn't count toward the live cap; resuming it does.\n- Always call `env.stop()` in a `finally`. In CI, then await `env.waitUntilStopped()`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `requestId` and `retryAfter`. The SDK retries `502`, `503`, `504`, connection errors and attempt timeouts itself, within a 10-minute retry budget (the last attempt can end later); `create` retries reuse one idempotency key. It retries nothing else: not `429`, other `4xx` or other `5xx`. The one exception is snapshot capture, which retries `429` `snapshot-limit` for up to 60 seconds with one idempotency key. `err.stopped === false` with `err.stopError` means the stop wasn't confirmed; `sm.environments.stop(err.environmentId)` is safe to repeat. Without `stopError`, you passed your own `idempotencyKey`, so `start()` left the environment running because another `start()` with that key may be using it; stop it only once nothing else needs it. Every error from `create`, including the create step of `start()`, carries `err.idempotencyKey`: `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same input returns the environment the first call created. Invalid `apps` fail before any request as a `StateMachinesError` (`status` null, `cause` a `TypeError`; don't replay it) with one of: `Pass at least one app.`, `App key \"<key>\" is used twice.` or `\"<s>\" can't be used as an app key; pass { key, appId } instead.`\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment-limit` | 429 | Not retried. Suspend or stop a live environment (`sm.environments.list({ status: 'live' })`), then start or resume again. |\n| `not-ready` | 409 | Only a running environment whose apps are all ready can be suspended. Wait for it, or stop it. |\n| `not-suspended` | 409 | Only a suspended environment can resume. After `suspend()`, await `waitUntilSuspended()` first. |\n| `suspend-in-progress` | 409 | The environment is suspending. Await `waitUntilSuspended()`, then stop it. |\n| `lifetime-too-long` | 422 | Lower `lifetimeMinutes` to at most `limits.environmentLifetime.maximumMinutes`. |\n| `release-unavailable` | 422 | Unknown or retired app or release. Check `appId` and `appReleaseId` against `sm.catalog.get()`. |\n| `release-unavailable` | 503 | This deployment doesn't serve the release. Retried within the budget; omit `appReleaseId` to use the default release, or contact support with the `requestId`. A failed app can carry it as `errorCode`. |\n| `connection-unavailable` | 409 | The app stopped or the environment is no longer `running`. If it is suspended, resume it; if it stopped or expired, start a new one. (Before revealing any token, connect() throws a `TypeError` for an app that isn't ready, an unknown actor, or a missing `apiId`.) |\n| `idempotency-conflict` | 409 | The idempotency key was used with a different input. Replay with the exact same input. |\n| `capture-in-progress` | 409 | This environment is already capturing a snapshot; one runs at a time. Wait for it, then capture again. |\n| `snapshot-limit` | 429 | Older APIs only. `capture` and `env.snapshot()` retry it for up to 60 seconds; if it still fails, wait and capture again. |\n| `not-ready` | 409 | Capture: the environment isn't `running` or an app isn't `ready`. Restore: the snapshot isn't `ready` yet; `await sm.snapshots.waitUntilReady(id)`. Delete: the snapshot is still `capturing`. |\n| `version-conflict` | 409 | `rename` sent a stale `expectedVersion`, or the snapshot was deleted. `get` it: if `deletedAt` is set it's gone, otherwise retry with its `version`. |\n| `release-unavailable` | 422 | On a restore: no release on this deployment matches the snapshot's apps. Start from `apps`, seed again and capture a new snapshot. |\n| `request-timeout` | 503 | Retried automatically. If `create` still fails, replay it with `err.idempotencyKey`. |\n\n## Quickstart\n\nSave it unchanged as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATE_API_KEY\nconst env = await sm.environments.start({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce', { apiId: 'rest' });\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.stop();\n}\n```\n\n## Docs\n\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): product site\n",
|
|
19
|
+
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, pause, resume and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\nInstall with `npm install @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.\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`. Pass `{ wait: false }` to get it back at once in `starting`. Always call `env.delete()` in a `finally`.\n- Apps: a string names the app, and the app's name in the environment is the same string. Use `{ app: 'salesforce', name: 'crm', settings }` for your own name, for two copies of one app, or for settings. Later calls take the name.\n- Pause and resume: `env.pause()` releases the compute and keeps the data; the time limit stops counting. `env.resume()` boots the apps again on the same data and waits until `running`. A paused environment is deleted after one day.\n- Credentials: `const crm = await env.connect('salesforce')` returns `url`, `headers`, `token` and `fetch`. `crm.fetch(path)` joins `path` to `url`, adds `headers`, and puts `token` in the header of the API whose path matches: `Authorization: Bearer` for Salesforce REST and Bulk 2.0. For Salesforce SOAP, put `crm.token` in the envelope's `SessionHeader/sessionId` yourself. `fetch` never sends your API key, never follows redirects and never retries. `token` and `headers` are secrets.\n- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Read them from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`.\n- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A pause or delete during the snapshot fails it with `interrupted`.\n- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.\n- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.\n- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n\n## Statuses\n\nEnums are open: handle values you don't recognise.\n\n- Environment `status`: `starting`, `running`, `paused`, `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. A `failed` environment keeps its data for `resume()` and has `failure`: `{ app, code, message }` with `start_failed`, `resume_failed`, `restart_failed`, `version_unavailable` or `invalid_settings`.\n- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.\n- `create` and `resume` throw `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `paused` or `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.\n- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.\n- `sm.environments.wait(id, { status })` and `sm.snapshots.wait(id, { status })` wait for any status, and throw once it cannot be reached without another call.\n\n## Limits\n\n- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.\n- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `message`, `requestId`, `fields` and `retryAfterMs`. The SDK retries `502`, `503`, `504` and connection errors itself, until a deadline; `create` retries reuse one idempotency key. It retries nothing else.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |\n| `forbidden` | 403 | The key lacks the permission. |\n| `not_found` | 404 | Check the ID and the workspace. |\n| `invalid_status` | 409 | The status does not allow the call: pause needs `running`; resume needs `paused` or `failed`. |\n| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |\n| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |\n| `workspace_archived` | 409 | The workspace is archived. |\n| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |\n| `version_unavailable` | 422 | The app has no default version. |\n| `environment_limit_reached` | 429 | Pause or delete an environment, then create or resume again. |\n| `unavailable` | 503 | Retried automatically. If `create` still fails, call it again with the same input and your own `idempotencyKey`. |\n\n## Errors from the app URL\n\n`crm.fetch` returns these as responses with the same JSON envelope, and never retries them.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment_not_running` | 409 | The environment is paused, failed or deleted; `error.status` names it. Resume a paused or failed environment. |\n| `environment_starting` | 503 | Wait `Retry-After` and call again. |\n| `environment_unavailable` | 503 | The app is restarting. Wait `Retry-After` and call again. |\n| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |\n| `capacity_exceeded` | 429 | Too many requests in flight to the app. Send fewer at once. |\n| `unsupported_protocol` | 501 | The app does not serve this API version or protocol. |\n\n## Quickstart\n\nSave it unchanged as `state-quickstart.mts` and 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({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Docs\n\n- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill]({{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",
|
|
20
20
|
skill:
|
|
21
|
-
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a sandboxed copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - starting environments, choosing an actor, snapshots, suspending and resuming, cleanup, and errors such as environment-limit and release-unavailable. Also use when the user mentions State Machines, STATE_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory; it matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATE_API_KEY` is set without printing it (`test -n \"$STATE_API_KEY\"`). If it isn't, ask the user to set it; the SDK doesn't read `.env` files.\n2. Start the environment with only the apps the task needs: `const env = await sm.environments.start({ apps: ['salesforce'] })`. Log `await sm.catalog.get()` for each app's ID and the actors and API profiles its release offers; don't guess IDs. A string app means `{ key: s, appId: s }`; use `{ key, appId }` for your own key. `start()` waits until the environment is `running`. If that fails, it stops the environment and rethrows; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`.\n3. Open a `try` right after `start()` returns, and call `env.stop()` in its `finally`.\n4. Connect through one API profile. Salesforce offers several and has no default, so pass `apiId`: `env.connect('salesforce', { apiId: 'rest' })`. This acts as the environment's declared default connection's actor, or else the app's first actor, the administrator. To act with another user's permissions, choose one from `await env.actors('salesforce')` and pass its `id` as `actorId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name, so read them instead of hard-coding one.\n5. Call the app with the connection's `fetch`. A leading `/` means the root of `baseUrl`.\n6. In `finally`, `await env.stop()`; it ends the environment and discards its data. In CI, then `await env.waitUntilStopped()`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATE_API_KEY\nconst env = await sm.environments.start({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce', { apiId: 'rest' });\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.stop();\n}\n```\n\n## Rules\n\n- Always stop in `finally`. `waitUntilStopped` confirms every app was disposed; use it in CI so a run fails when cleanup can't be confirmed.\n- `env.suspend()` ends the sandboxes and keeps the data, with the lifetime paused; it is not cleanup. Await `env.waitUntilSuspended()` before `env.resume()`, then `env.waitUntilReady()` before connecting again. A suspended environment still needs `env.stop()`.\n- To keep a failed environment for inspection, use the full-control path: `sm.environments.create`, then `sm.environments.waitUntilReady(environment.id)`, then `sm.environments.connect(environment.id, key, options)`. Nothing on that path stops the environment for you.\n- Lifetime counts from the start, including boot. It defaults to 15 minutes, or the deployment maximum if that is lower: `(await sm.credential.get()).limits.environmentLifetime`. Set `lifetimeMinutes` in `start` or `create` for longer runs.\n- Live environments are capped per organization: `limits.liveEnvironments` from `sm.credential.get()`. Stop the ones you no longer need; suspended ones don't count until they resume.\n- Never print, log or commit `STATE_API_KEY`, tokens, or `headers()` or `actorToken()` output.\n- Salesforce's SOAP profile (`soap-partner`) takes the actor token in the envelope, not a header: put `connection.actorToken()` in `SessionHeader/sessionId`. For it, `headers()` carries only `X-State-Environment-Token`.\n- `connection.fetch` never sends your API key, never follows redirects and only reaches URLs under `baseUrl`.\n- Runtimes: Node.js 20.20 or later (22 or 24 recommended), and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATE_API_KEY })`, and bound calls with `{ signal: AbortSignal.timeout(20_000) }`, since retries can take minutes.\n- `environments.list`, `environments.events`, `workspaces.events` and `snapshots.list` return one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshot({ name })` once, then `sm.environments.start({ snapshotId })` in place of `apps`. Capturing needs `snapshots:create` and `snapshots:read`. Snapshots are never deleted automatically, not even failed ones.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `DisposalIncompleteError`, `TimeoutError`, `SnapshotFailedError`, `SnapshotTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If `start()` or `create` still throws with `err.idempotencyKey`, the create failed: don't call it again as a new request, which can start a second environment. Call `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same `input`. Don't replay when `err.status` is `null` and `err.cause` is a `TypeError`: the input was invalid and nothing was sent; fix the input instead. A key only recovers a failed create: don't reuse the key of a `start()` whose wait failed, because the replay returns that stopped environment. With your own key, `start()` doesn't stop the environment on failure, because another `start()` with that key may be using it: the error carries `err.environmentId`, `err.stopped` is `false` and there is no `err.stopError`. Stop it only once nothing else needs it. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency-conflict`. Keys are kept for a day.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `release-unavailable`, 422 | Unknown or retired `appId` or `appReleaseId`. A string app is used as the `appId`. | Check the IDs against `sm.catalog.get()`. Omit `appReleaseId` for the default release. |\n| `release-unavailable`, 503, or a failed app with that `errorCode` | This deployment doesn't serve the release. The SDK retries a 503 within a 10-minute budget. | Omit `appReleaseId`. If it persists, report the `requestId`. Pass a `signal` to bound the wait. |\n| `environment-limit`, 429 | The organization is at its live-environment cap. Not retried. | `sm.environments.list({ status: 'live' })`, stop or suspend one you no longer need, then start again. |\n| `not-suspended` or `suspend-in-progress`, 409 | `resume()` before the environment finished suspending, or `stop()` while it suspends. | Await `env.waitUntilSuspended()` first. |\n| `lifetime-too-long`, 422 | `lifetimeMinutes` is above the maximum. | Use at most `limits.environmentLifetime.maximumMinutes`. |\n| `TypeError: Unknown actor <id> for <appKey>. Choose one of: <ids>.` | The `actorId` isn't one of the app's actors. No token was revealed. | Pass an `id` from `await env.actors(appKey)`, or omit `actorId` to act as the default actor. |\n| `TypeError: Choose one API for <appKey>: <ids>.` | The app has several API profiles and `apiId` is missing or unknown. Salesforce always needs one. | Pass `apiId` from the listed IDs, such as `rest`. |\n| `start()` rejects with `EnvironmentFailedError` or `TimeoutError` | The environment failed, or wasn't `running` within `readyTimeoutMs` (10 minutes by default). If `err.stopped` is `true`, `start()` already stopped it. | Read `err.environment` (`null` on a `TimeoutError` that saw no read): its `stopReason` and each app's `errorCode`. If `err.stopped` is `false`, read `err.stopError` and call `sm.environments.stop(err.environmentId)`. To keep a failed environment, use the full-control path. |\n| `StateMachinesError` (`status` null) for invalid `apps`: `Pass at least one app.`, `App key \"<key>\" is used twice.` or `\"<s>\" can't be used as an app key; pass { key, appId } instead.` | Empty list, duplicate key, or a string that isn't a valid key. No request was sent. | Pass one to ten apps with unique keys; use `{ key, appId }` when the ID isn't a valid key. |\n| `TypeError: App ... is not ready to connect` | On the full-control path, connect() ran before the app was `ready`. | Await `waitUntilReady` first, or use `start()`. |\n| `connection-unavailable`, 409 | The app stopped, or the environment is no longer `running`. | Check `sm.environments.get(env.id)`; if it is suspended, resume it; if it stopped or expired, start a new one. |\n| `EnvironmentFailedError` from `waitUntilReady` | On the full-control path, the environment became `failed`, `suspending`, `suspended`, `stopping` or `stopped`. | Read `err.environment.status`, its `stopReason` and each app's `errorCode`. Still stop it in `finally`. |\n| A vendor client such as jsforce is rejected by the gateway | The gateway needs `X-State-Environment-Token` on every request; jsforce only sends it with custom headers configured. | Prefer `connection.fetch`. If you pass `headers()` to another client, send them only to `baseUrl` and disable redirects. |\n| `not-ready`, 409 | Capture: the environment isn't `running` or an app isn't `ready`. Restore: the snapshot isn't `ready` yet. Delete: the snapshot is still `capturing`. | Capture from the handle `start()` returns. Before a restore or delete, `await sm.snapshots.waitUntilReady(snapshotId)`. |\n| `capture-in-progress`, 409 | This environment is already capturing; one capture runs at a time. | `await sm.snapshots.waitUntilReady(<the running snapshot's id>)`, then capture again. |\n| `snapshot-limit`, 429 | Older APIs only: too many captures were running. `capture` and `env.snapshot()` already retried it for 60 seconds. | Wait, then capture again. |\n| `SnapshotFailedError` | The capture failed. `err.snapshot.errorCode` is `capture-failed`, or `capture-interrupted` when the API restarted mid-capture. The snapshot is kept. | Capture again with a new idempotency key (the default); the old key returns the same failed snapshot. |\n| `SnapshotTimeoutError` | The snapshot wasn't `ready` within `readyTimeoutMs`. The capture continues on the server. | `await sm.snapshots.waitUntilReady(err.snapshotId)`. |\n| `forbidden`, 403, from `sm.snapshots.delete` | The key lacks `snapshots:delete`. Keys created by members never hold it. | Use a key whose creator holds `snapshots:delete`, or keep the snapshot. |\n| `release-unavailable`, 422, on a restore | No release on this deployment matches the snapshot's apps. | Start from `apps`, seed again and capture a new snapshot. |\n| `TypeError: Pass apiKey or set STATE_API_KEY.` | No key in the environment. | Ask the user to set `STATE_API_KEY`; in Workers, pass `apiKey`. |\n\nMore: {{origin}}/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n",
|
|
21
|
+
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a disposable copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - creating environments, credentials, choosing an actor, snapshots, pausing and resuming, cleanup, and errors such as environment_limit_reached and version_unavailable. Also use when the user mentions State Machines, STATEMACHINES_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory; it matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATEMACHINES_API_KEY` is set without printing it (`test -n \"$STATEMACHINES_API_KEY\"`). If it isn't, ask the user to set it; the SDK doesn't read `.env` files.\n2. Create the environment with only the apps the task needs: `const env = await sm.environments.create({ apps: ['salesforce'] })`. Log `await sm.apps.list()` for each app's ID; don't guess IDs. `create` waits until the environment is `running`. If the start fails, the server deletes the environment and `create` throws `EnvironmentFailedError` with `err.environment.failure`.\n3. Open a `try` right after `create` returns, and call `await env.delete()` in its `finally`. It deletes the environment and its data.\n4. Get credentials for one app: `const crm = await env.connect('salesforce')`. This acts as the app's default actor, the Salesforce administrator. To act with another user's permissions, pass an `actorId` from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name.\n5. Call the app with `crm.fetch(path)`. A leading `/` means the root of the app's `url`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and 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({ apps: ['salesforce'] });\n\ntry {\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## Rules\n\n- Always delete in `finally`.\n- `env.pause()` releases the compute and keeps the data; it is not cleanup. `env.resume()` waits until `running` again. A paused or failed environment is deleted after one day, and still needs `env.delete()` once you are done.\n- To create without waiting, pass `{ wait: false }`, then `sm.environments.wait(env.id, { status: 'running' })`.\n- The time limit counts `starting` and `running`. `(await sm.me()).limits.timeLimitMinutes` gives its `default` and `maximum`. Set `timeLimitMinutes` in `create` for longer runs.\n- Running environments are capped per organization: `limits.concurrentEnvironments` from `sm.me()`. Delete the ones you no longer need. A paused or failed environment doesn't count until it resumes.\n- Never print, log or commit `STATEMACHINES_API_KEY`, `credentials.token` or `credentials.headers`.\n- Salesforce's SOAP API takes the actor token in the envelope, not a header: put `crm.token` in `SessionHeader/sessionId`. `crm.fetch` then sends only the environment token header.\n- `crm.fetch` never sends your API key, never follows redirects and only reaches URLs under the app's `url`.\n- Runtimes: Node.js, at the versions in the package's `engines` field, and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`. A start takes longer than one request may last, so create with `{ wait: false }` and read `sm.environments.get(id)` in later requests until it is `running`, or pass a `signal` no shorter than the expected start.\n- Every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshots.create({ name })` once, then `sm.environments.create({ snapshotId })` in place of `apps`.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `SnapshotFailedError`, `UnexpectedStatusError`, `WaitTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If you need to replay a create whose outcome is unknown, pass your own key: `sm.environments.create(input, { idempotencyKey })`, and call it again with the same input and key. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency_key_reused`.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `version_unavailable`, 422 | The app has no default version. | Check the app ID against `sm.apps.list()`. |\n| `environment_limit_reached`, 429 | The organization is at its cap of running environments. | List them with `sm.environments.list({ status: ['starting', 'running'] })`, delete or pause one, then create again. |\n| `invalid_status`, 409 | The status does not allow the call, for example pausing an environment that is `starting`. | Read `sm.environments.get(id)` and act on its `status`. |\n| `invalid_request`, 400 | A wrong field. | Read `err.fields`, keyed by dotted path. |\n| `EnvironmentFailedError` | The environment failed to start or resume. | Read `err.environment.failure`: `{ app, code, message }`. `invalid_settings` means the app refused its settings. |\n| `UnexpectedStatusError` | The environment was paused or deleted while the SDK waited. | Read `err.status` and `err.resource`. |\n| `WaitTimeoutError` | The status was not reached within `timeoutMs`. | Wait again with `sm.environments.wait(id, { status })`, or delete the environment. |\n| `snapshot_in_progress`, 409 | The environment already has a snapshot in `saving`. | `const [running] = (await sm.snapshots.list({ environmentId: env.id, status: ['saving'] })).data`, then `await sm.snapshots.wait(running.id, { status: 'ready' })`, then create another. |\n| `SnapshotFailedError` | The snapshot failed. `interrupted` means the environment was paused or deleted first. | Create another snapshot while the environment is `running`. |\n| `environment_not_running`, 409, from `crm.fetch` | The environment is paused, failed or deleted. `crm.fetch` returns it as a response and never retries. | Read `(await res.json()).error.status`; `env.resume()` a paused or failed environment. |\n| `environment_starting` or `environment_unavailable`, 503, from `crm.fetch` | The app is starting or restarting. | Wait the `Retry-After` seconds and call again. |\n| A vendor client such as jsforce is refused by the gateway | The gateway needs `StateMachines-Environment-Token` on every request. | Prefer `crm.fetch`. If you pass `crm.headers` to another client, send them only to `crm.url` and disable redirects. |\n| `TypeError: Pass apiKey or set STATEMACHINES_API_KEY.` | No key in the environment. | Ask the user to set `STATEMACHINES_API_KEY`; in Workers, pass `apiKey`. |\n\nMore: https://docs.usestatemachines.com, {{origin}}/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n",
|
|
22
22
|
});
|
package/agents/llms.txt
CHANGED
|
@@ -1,63 +1,66 @@
|
|
|
1
1
|
# State Machines
|
|
2
2
|
|
|
3
|
-
> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents.
|
|
3
|
+
> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, pause, resume and delete them with the TypeScript SDK `@usestatemachines/sdk`.
|
|
4
4
|
|
|
5
|
-
Install with `npm install @usestatemachines/sdk`. It is ESM only and runs on Node.js
|
|
5
|
+
Install with `npm install @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.
|
|
6
6
|
|
|
7
7
|
## Concepts
|
|
8
8
|
|
|
9
|
-
- Environment: one disposable run of one or more apps. `const env = await sm.environments.
|
|
10
|
-
-
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
- Vendor clients: the gateway needs `X-State-Environment-Token` on every request. A client such as jsforce only sends it if you configure custom headers. Prefer `connection.fetch`; if you pass `headers()` to another client, send them only to `connection.baseUrl` and disable redirects.
|
|
19
|
-
- Pagination: `environments.list`, `environments.events`, `workspaces.events` and `snapshots.list` return one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.
|
|
9
|
+
- 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`. Pass `{ wait: false }` to get it back at once in `starting`. Always call `env.delete()` in a `finally`.
|
|
10
|
+
- Apps: a string names the app, and the app's name in the environment is the same string. Use `{ app: 'salesforce', name: 'crm', settings }` for your own name, for two copies of one app, or for settings. Later calls take the name.
|
|
11
|
+
- Pause and resume: `env.pause()` releases the compute and keeps the data; the time limit stops counting. `env.resume()` boots the apps again on the same data and waits until `running`. A paused environment is deleted after one day.
|
|
12
|
+
- Credentials: `const crm = await env.connect('salesforce')` returns `url`, `headers`, `token` and `fetch`. `crm.fetch(path)` joins `path` to `url`, adds `headers`, and puts `token` in the header of the API whose path matches: `Authorization: Bearer` for Salesforce REST and Bulk 2.0. For Salesforce SOAP, put `crm.token` in the envelope's `SessionHeader/sessionId` yourself. `fetch` never sends your API key, never follows redirects and never retries. `token` and `headers` are secrets.
|
|
13
|
+
- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Read them from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`.
|
|
14
|
+
- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A pause or delete during the snapshot fails it with `interrupted`.
|
|
15
|
+
- 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.
|
|
16
|
+
- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.
|
|
17
|
+
- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.
|
|
20
18
|
|
|
21
19
|
## Statuses
|
|
22
20
|
|
|
23
21
|
Enums are open: handle values you don't recognise.
|
|
24
22
|
|
|
25
|
-
- Environment `status`: `
|
|
26
|
-
-
|
|
27
|
-
-
|
|
28
|
-
-
|
|
29
|
-
- `
|
|
30
|
-
- `waitUntilSuspended` resolves when the environment is `suspended`, and throws `EnvironmentFailedError` if it ends instead.
|
|
31
|
-
- `waitUntilStopped` resolves when the environment is `stopped` and every app's disposal is `complete`. A `failed` environment keeps its data for `resume()` and is not stopped until you call `stop()`. It throws `DisposalIncompleteError` if a disposal is `failed` or `unknown`, and `TimeoutError` if disposal stays `pending`.
|
|
23
|
+
- Environment `status`: `starting`, `running`, `paused`, `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. A `failed` environment keeps its data for `resume()` and has `failure`: `{ app, code, message }` with `start_failed`, `resume_failed`, `restart_failed`, `version_unavailable` or `invalid_settings`.
|
|
24
|
+
- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.
|
|
25
|
+
- `create` and `resume` throw `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `paused` or `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.
|
|
26
|
+
- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.
|
|
27
|
+
- `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.
|
|
32
28
|
|
|
33
29
|
## Limits
|
|
34
30
|
|
|
35
|
-
-
|
|
36
|
-
- `
|
|
37
|
-
- A suspended environment doesn't count toward the live cap; resuming it does.
|
|
38
|
-
- Always call `env.stop()` in a `finally`. In CI, then await `env.waitUntilStopped()`.
|
|
31
|
+
- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.
|
|
32
|
+
- `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'`.
|
|
39
33
|
|
|
40
34
|
## Errors and retries
|
|
41
35
|
|
|
42
|
-
A failed API call throws `StateMachinesError` with `status`, `code`, `requestId` and `
|
|
36
|
+
A 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.
|
|
43
37
|
|
|
44
38
|
| Code | Status | What to do |
|
|
45
39
|
| --- | --- | --- |
|
|
46
|
-
| `
|
|
47
|
-
| `
|
|
48
|
-
| `
|
|
49
|
-
| `
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
53
|
-
| `
|
|
54
|
-
| `
|
|
55
|
-
| `
|
|
56
|
-
| `
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
40
|
+
| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |
|
|
41
|
+
| `forbidden` | 403 | The key lacks the permission. |
|
|
42
|
+
| `not_found` | 404 | Check the ID and the workspace. |
|
|
43
|
+
| `invalid_status` | 409 | The status does not allow the call: pause needs `running`; resume needs `paused` or `failed`. |
|
|
44
|
+
| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |
|
|
45
|
+
| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |
|
|
46
|
+
| `workspace_archived` | 409 | The workspace is archived. |
|
|
47
|
+
| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |
|
|
48
|
+
| `version_unavailable` | 422 | The app has no default version. |
|
|
49
|
+
| `environment_limit_reached` | 429 | Pause or delete an environment, then create or resume again. |
|
|
50
|
+
| `unavailable` | 503 | Retried automatically. If `create` still fails, call it again with the same input and your own `idempotencyKey`. |
|
|
51
|
+
|
|
52
|
+
## Errors from the app URL
|
|
53
|
+
|
|
54
|
+
`crm.fetch` returns these as responses with the same JSON envelope, and never retries them.
|
|
55
|
+
|
|
56
|
+
| Code | Status | What to do |
|
|
57
|
+
| --- | --- | --- |
|
|
58
|
+
| `environment_not_running` | 409 | The environment is paused, failed or deleted; `error.status` names it. Resume a paused or failed environment. |
|
|
59
|
+
| `environment_starting` | 503 | Wait `Retry-After` and call again. |
|
|
60
|
+
| `environment_unavailable` | 503 | The app is restarting. Wait `Retry-After` and call again. |
|
|
61
|
+
| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |
|
|
62
|
+
| `capacity_exceeded` | 429 | Too many requests in flight to the app. Send fewer at once. |
|
|
63
|
+
| `unsupported_protocol` | 501 | The app does not serve this API version or protocol. |
|
|
61
64
|
|
|
62
65
|
## Quickstart
|
|
63
66
|
|
|
@@ -66,21 +69,22 @@ Save it unchanged as `state-quickstart.mts` and run `npx tsx state-quickstart.mt
|
|
|
66
69
|
```ts
|
|
67
70
|
import { StateMachines } from '@usestatemachines/sdk';
|
|
68
71
|
|
|
69
|
-
const sm = new StateMachines(); // reads
|
|
70
|
-
const env = await sm.environments.
|
|
72
|
+
const sm = new StateMachines(); // reads STATEMACHINES_API_KEY
|
|
73
|
+
const env = await sm.environments.create({ apps: ['salesforce'] });
|
|
71
74
|
|
|
72
75
|
try {
|
|
73
|
-
const salesforce = await env.connect('salesforce'
|
|
76
|
+
const salesforce = await env.connect('salesforce');
|
|
74
77
|
const res = await salesforce.fetch('/services/data/v67.0/limits');
|
|
75
78
|
console.log(res.status, await res.json());
|
|
76
79
|
} finally {
|
|
77
|
-
await env.
|
|
80
|
+
await env.delete();
|
|
78
81
|
}
|
|
79
82
|
```
|
|
80
83
|
|
|
81
84
|
## Docs
|
|
82
85
|
|
|
86
|
+
- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))
|
|
83
87
|
- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions
|
|
84
|
-
- [Agent skill](https://
|
|
88
|
+
- [Agent skill](https://app.usestatemachines.com/skill.md): workflow, rules and troubleshooting for coding agents
|
|
85
89
|
- [OpenAPI document](https://cdn.jsdelivr.net/npm/@usestatemachines/sdk/openapi.json): the HTTP API the SDK calls
|
|
86
|
-
- [State Machines](https://usestatemachines.com):
|
|
90
|
+
- [State Machines](https://usestatemachines.com): website
|