@usestatemachines/sdk 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -6
- package/agents/index.js +2 -2
- package/agents/llms.txt +3 -2
- package/esm/extensions/client.d.ts +16 -4
- package/esm/extensions/client.js +17 -4
- package/esm/extensions/index.d.ts +2 -2
- package/esm/extensions/running-environment.d.ts +5 -5
- package/esm/extensions/running-environment.js +1 -1
- package/esm/extensions/wait.js +1 -1
- package/esm/funcs/{get-environment-exchange.d.ts → environments-get-request-payload.d.ts} +1 -1
- package/esm/funcs/environments-get-request-payload.js +100 -0
- package/esm/funcs/environments-get-request-stats.d.ts +11 -0
- package/esm/funcs/{get-environment-position.js → environments-get-request-stats.js} +17 -6
- package/esm/funcs/{list-environment-history.d.ts → environments-get-request.d.ts} +1 -1
- package/esm/funcs/{get-environment-exchange.js → environments-get-request.js} +6 -6
- package/esm/funcs/{get-environment-position.d.ts → environments-list-requests.d.ts} +1 -1
- package/esm/funcs/{list-environment-history.js → environments-list-requests.js} +13 -5
- package/esm/funcs/environments-resume.js +1 -0
- package/esm/funcs/environments-stop.js +1 -0
- package/esm/funcs/environments-suspend.js +1 -0
- package/esm/lib/config.d.ts +2 -2
- package/esm/lib/config.js +2 -2
- package/esm/models/environment-app.d.ts +0 -8
- package/esm/models/environment-app.js +0 -10
- package/esm/models/environment-request-detail.d.ts +40 -0
- package/esm/models/environment-request-detail.js +39 -0
- package/esm/models/environment-request-stats.d.ts +26 -0
- package/esm/models/environment-request-stats.js +31 -0
- package/esm/models/environment-request.d.ts +31 -0
- package/esm/models/environment-request.js +34 -0
- package/esm/models/error-response.d.ts +0 -1
- package/esm/models/error-response.js +0 -1
- package/esm/models/index.d.ts +4 -6
- package/esm/models/index.js +4 -6
- package/esm/models/operations/create-environment-definition.d.ts +10 -82
- package/esm/models/operations/create-environment-definition.js +4 -60
- package/esm/models/operations/get-environment-request-payload.d.ts +23 -0
- package/esm/models/operations/get-environment-request-payload.js +19 -0
- package/esm/models/operations/get-environment-request-stats.d.ts +70 -0
- package/esm/models/operations/get-environment-request-stats.js +55 -0
- package/esm/models/operations/get-environment-request.d.ts +25 -0
- package/esm/models/operations/get-environment-request.js +21 -0
- package/esm/models/operations/index.d.ts +4 -3
- package/esm/models/operations/index.js +4 -3
- package/esm/models/operations/list-environment-requests.d.ts +75 -0
- package/esm/models/operations/list-environment-requests.js +59 -0
- package/esm/models/operations/resume-environment.d.ts +2 -0
- package/esm/models/operations/resume-environment.js +8 -2
- package/esm/models/operations/stop-environment.d.ts +2 -0
- package/esm/models/operations/stop-environment.js +8 -2
- package/esm/models/operations/suspend-environment.d.ts +2 -0
- package/esm/models/operations/suspend-environment.js +8 -2
- package/esm/models/request-payload-preview.d.ts +31 -0
- package/esm/models/request-payload-preview.js +33 -0
- package/esm/sdk/environments.d.ts +4 -0
- package/esm/sdk/environments.js +16 -0
- package/esm/sdk/sdk.d.ts +0 -3
- package/esm/sdk/sdk.js +0 -12
- package/esm/types/smart-union.js +1 -2
- package/openapi.json +584 -524
- package/package.json +2 -2
- package/esm/models/environment-exchange.d.ts +0 -116
- package/esm/models/environment-exchange.js +0 -126
- package/esm/models/environment-position.d.ts +0 -25
- package/esm/models/environment-position.js +0 -32
- package/esm/models/history-body.d.ts +0 -28
- package/esm/models/history-body.js +0 -33
- package/esm/models/history-cause.d.ts +0 -48
- package/esm/models/history-cause.js +0 -63
- package/esm/models/history-position.d.ts +0 -11
- package/esm/models/history-position.js +0 -15
- package/esm/models/history-transaction.d.ts +0 -16
- package/esm/models/history-transaction.js +0 -20
- package/esm/models/operations/get-environment-exchange.d.ts +0 -25
- package/esm/models/operations/get-environment-exchange.js +0 -21
- package/esm/models/operations/get-environment-position.d.ts +0 -23
- package/esm/models/operations/get-environment-position.js +0 -20
- package/esm/models/operations/list-environment-history.d.ts +0 -28
- package/esm/models/operations/list-environment-history.js +0 -24
- package/esm/types/discriminated-union.d.ts +0 -24
- package/esm/types/discriminated-union.js +0 -60
package/README.md
CHANGED
|
@@ -103,11 +103,16 @@ await env.waitUntilReady();
|
|
|
103
103
|
whose apps are all ready can be suspended; anything else answers `409 not-ready`.
|
|
104
104
|
- While suspended, the lifetime is paused: `expiresAt` moves out by the suspended time when it
|
|
105
105
|
resumes, and the environment doesn't count toward the live-environment cap.
|
|
106
|
-
- `resume()`
|
|
107
|
-
`suspended`, and `429 environment-limit` when the cap is reached. `waitUntilSuspended()` resolves
|
|
106
|
+
- `resume()` starts it again; it answers `409 not-suspended` unless the environment is
|
|
107
|
+
`suspended` or `failed`, and `429 environment-limit` when the cap is reached. `waitUntilSuspended()` resolves
|
|
108
108
|
on `suspended` and throws `EnvironmentFailedError` if the environment ends instead.
|
|
109
109
|
- Suspending isn't cleanup: a suspended environment keeps its data until you stop it.
|
|
110
|
-
`stop()`
|
|
110
|
+
`stop()` interrupts ongoing work, including suspension and snapshot capture.
|
|
111
|
+
|
|
112
|
+
Lifecycle commands require orchestration availability. `stop`, `suspend` and `resume` each
|
|
113
|
+
send a fresh idempotency key and reuse it across automatic retries. You can pass your own
|
|
114
|
+
`{ idempotencyKey }`. Failures carry that key so you can retry the same command after a timeout;
|
|
115
|
+
a timeout does not establish whether the command was accepted.
|
|
111
116
|
|
|
112
117
|
## Full control
|
|
113
118
|
|
|
@@ -147,7 +152,7 @@ try {
|
|
|
147
152
|
3. `connect(id, appKey, { apiId, actorId })` returns a `Connection` to one app (see
|
|
148
153
|
[Connections](#connections)).
|
|
149
154
|
4. `stop(id)` returns as soon as the API accepts it, and a second call also resolves.
|
|
150
|
-
`waitUntilStopped(id)` resolves only when the environment is `stopped`
|
|
155
|
+
`waitUntilStopped(id)` resolves only when the environment is `stopped` **and**
|
|
151
156
|
every app's `disposal` is `complete`. If any disposal is `failed` or `unknown`, it throws
|
|
152
157
|
`DisposalIncompleteError` with the environment.
|
|
153
158
|
|
|
@@ -195,8 +200,10 @@ Pass `snapshotId` instead of `apps` to `start()` or `create()`. Each app keeps t
|
|
|
195
200
|
captured; `snapshotAppInstanceKeys` restores only some of them. The new environment's
|
|
196
201
|
`sourceEnvironmentSnapshotId` and each app's `sourceAppInstanceSnapshotId` name the source.
|
|
197
202
|
|
|
198
|
-
-
|
|
199
|
-
across apps
|
|
203
|
+
- Every app is paused while the snapshot is cut, so a multi-app snapshot records one instant
|
|
204
|
+
across apps (`consistency: 'environment'`). A single app, or a capture whose pause was refused,
|
|
205
|
+
is `'app_instance'`. It can only be taken while the environment is `running` and each app is
|
|
206
|
+
`ready`.
|
|
200
207
|
- `readyTimeoutMs` bounds the wait for `ready` (10 minutes by default), as in `start()`. While the
|
|
201
208
|
API is busy (429 `snapshot-limit`), the capture is retried with the same idempotency key for up
|
|
202
209
|
to 60 seconds.
|
|
@@ -460,6 +467,30 @@ const response = await fetch(new URL('services/data/v67.0/limits', salesforce.ba
|
|
|
460
467
|
});
|
|
461
468
|
```
|
|
462
469
|
|
|
470
|
+
## Recorded requests
|
|
471
|
+
|
|
472
|
+
Request history is best effort. Missing records do not mean that no requests ran.
|
|
473
|
+
Stored records remain readable after an environment stops.
|
|
474
|
+
|
|
475
|
+
```ts
|
|
476
|
+
const stats = await sm.environments.getRequestStats(env.id, {
|
|
477
|
+
from: new Date(Date.now() - 60 * 60_000),
|
|
478
|
+
to: new Date(),
|
|
479
|
+
});
|
|
480
|
+
console.log(stats.count, stats.p95Ms);
|
|
481
|
+
const page = await sm.environments.listRequests(env.id, { appKey: 'salesforce', limit: 20 });
|
|
482
|
+
const first = page.data[0];
|
|
483
|
+
if (first) {
|
|
484
|
+
const detail = await sm.environments.getRequest(env.id, first.id);
|
|
485
|
+
console.log(detail.status, detail.responseBody.preview);
|
|
486
|
+
const body = await sm.environments.getRequestPayload(env.id, first.id, 'response');
|
|
487
|
+
const bytes = await new Response(body).arrayBuffer();
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
Payload coverage reports credential redaction and omissions. The detail preview
|
|
492
|
+
is bounded; the payload method returns the full stored body as a byte stream.
|
|
493
|
+
|
|
463
494
|
## Supported runtimes
|
|
464
495
|
|
|
465
496
|
- **Node.js 20.20 or later**, with 22 or 24 recommended: Node 20 is past its end of life, and
|
|
@@ -476,6 +507,7 @@ TypeScript consumers need `lib: ["DOM"]` or `@types/node`, for the `fetch`, `Req
|
|
|
476
507
|
version.
|
|
477
508
|
- The API may add error codes and enum values, such as a new status or stop reason. Enums are
|
|
478
509
|
open: handle values you don't recognise.
|
|
510
|
+
- 0.5.0 removes database history and fork metadata. See [What's new in 0.5.0](#whats-new-in-050).
|
|
479
511
|
- 0.4.0 adds suspend and resume and keeps every 0.3.0 call: `stop` still ends the environment.
|
|
480
512
|
`Environment` gains `suspendedAt` and `sourceEnvironmentId`, so object literals typed as
|
|
481
513
|
`Environment` need them. A snapshot's `consistency` is now `'environment'`, `'app_instance'`
|
|
@@ -506,6 +538,27 @@ TypeScript consumers need `lib: ["DOM"]` or `@types/node`, for the `fetch`, `Req
|
|
|
506
538
|
releases don't declare a default actor yet.
|
|
507
539
|
- `await using` isn't supported. Stop the environment in `finally`.
|
|
508
540
|
|
|
541
|
+
## What's new in 0.5.0
|
|
542
|
+
|
|
543
|
+
### Added
|
|
544
|
+
|
|
545
|
+
- `sm.environments.listRequests`, `getRequest`, `getRequestPayload` and `getRequestStats`
|
|
546
|
+
read best-effort gateway request history, including after the environment stops.
|
|
547
|
+
- A failed environment retains its application data and can be resumed or stopped.
|
|
548
|
+
Stop takes priority over startup, recovery and snapshot capture.
|
|
549
|
+
|
|
550
|
+
### Removed
|
|
551
|
+
|
|
552
|
+
- The generated `listEnvironmentHistory`, `getEnvironmentPosition` and
|
|
553
|
+
`getEnvironmentExchange` operations and their history/position/exchange models.
|
|
554
|
+
Use the request-history methods above for recorded replica traffic.
|
|
555
|
+
- `EnvironmentApp.forkedAt`. Database object history and point-in-time forks are no longer
|
|
556
|
+
part of the API.
|
|
557
|
+
|
|
558
|
+
`waitUntilStopped()` now requires `stopped` and completed disposal. A retained `failed`
|
|
559
|
+
environment is not stopped. Lifecycle commands require Temporal availability; existing
|
|
560
|
+
replica traffic does not.
|
|
561
|
+
|
|
509
562
|
## What's new in 0.4.0
|
|
510
563
|
|
|
511
564
|
- `sm.environments.suspend(id)` ends an environment's sandboxes and keeps its data;
|
package/agents/index.js
CHANGED
|
@@ -4,7 +4,7 @@ export const prompt =
|
|
|
4
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 20.20 or later and on Cloudflare Workers, not in browsers.\n2. Check that `STATE_API_KEY` is set without printing it: `test -n \"$STATE_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 org's limits:\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\n4. Adapt it to my task. Log `await sm.catalog.get()` to find each app's ID and the actors and API profiles its release offers; don't guess IDs. Start only the apps the task needs; a string such as `'salesforce'` means `{ key: 'salesforce', appId: 'salesforce' }`. Salesforce always needs an `apiId`. `connect()` acts as the declared default connection's actor, or else the app's first actor, the administrator; to act as a specific user, pass an `actorId` from `await env.actors('salesforce')`. To reuse seeded data, `await env.snapshot()` once, then `sm.environments.start({ snapshotId })`.\n5. Always call `env.stop()` in a `finally`; it ends the environment and discards its data. In CI, then await `env.waitUntilStopped()` so the run fails if cleanup isn't confirmed. If `start()` fails after creating the environment, it stops it; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`. If the create itself fails, call `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same `input`; never retry without the key, which can start a second environment.\n6. Never print, log or commit keys or tokens, including `connection.headers()` and `connection.actorToken()`, which return live tokens.\n\nRead more: `node_modules/@usestatemachines/sdk/README.md`, https://state-web.usestatemachines.workers.dev/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, taken per 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- 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` or `failed` and every app's disposal is `complete`. 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. 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";
|
|
8
8
|
|
|
9
9
|
export const skill =
|
|
10
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";
|
|
@@ -16,7 +16,7 @@ export const templates = Object.freeze({
|
|
|
16
16
|
prompt:
|
|
17
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 20.20 or later and on Cloudflare Workers, not in browsers.\n2. Check that `STATE_API_KEY` is set without printing it: `test -n \"$STATE_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 org's limits:\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\n4. Adapt it to my task. Log `await sm.catalog.get()` to find each app's ID and the actors and API profiles its release offers; don't guess IDs. Start only the apps the task needs; a string such as `'salesforce'` means `{ key: 'salesforce', appId: 'salesforce' }`. Salesforce always needs an `apiId`. `connect()` acts as the declared default connection's actor, or else the app's first actor, the administrator; to act as a specific user, pass an `actorId` from `await env.actors('salesforce')`. To reuse seeded data, `await env.snapshot()` once, then `sm.environments.start({ snapshotId })`.\n5. Always call `env.stop()` in a `finally`; it ends the environment and discards its data. In CI, then await `env.waitUntilStopped()` so the run fails if cleanup isn't confirmed. If `start()` fails after creating the environment, it stops it; an `EnvironmentFailedError` or `TimeoutError` carries `err.environmentId` and `err.stopped`. If the create itself fails, call `sm.environments.start(input, { idempotencyKey: err.idempotencyKey })` with the same `input`; never retry without the key, which can start a second environment.\n6. Never print, log or commit keys or tokens, including `connection.headers()` and `connection.actorToken()`, which return live tokens.\n\nRead more: `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, taken per 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- 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` or `failed` and every app's disposal is `complete`. 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. 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",
|
|
20
20
|
skill:
|
|
21
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",
|
|
22
22
|
});
|
package/agents/llms.txt
CHANGED
|
@@ -13,7 +13,8 @@ Install with `npm install @usestatemachines/sdk`. It is ESM only and runs on Nod
|
|
|
13
13
|
- 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' })`.
|
|
14
14
|
- 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`.
|
|
15
15
|
- 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.
|
|
16
|
-
- Snapshot: the saved data of a running environment's apps,
|
|
16
|
+
- 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`.
|
|
17
|
+
- 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.
|
|
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.
|
|
18
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`.
|
|
19
20
|
|
|
@@ -27,7 +28,7 @@ Enums are open: handle values you don't recognise.
|
|
|
27
28
|
- 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.
|
|
28
29
|
- `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.
|
|
29
30
|
- `waitUntilSuspended` resolves when the environment is `suspended`, and throws `EnvironmentFailedError` if it ends instead.
|
|
30
|
-
- `waitUntilStopped` resolves when the environment is `stopped`
|
|
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`.
|
|
31
32
|
|
|
32
33
|
## Limits
|
|
33
34
|
|
|
@@ -4,9 +4,14 @@ import type { Connection as ConnectionDetails } from '../models/connection.js';
|
|
|
4
4
|
import type { ConnectionSecret } from '../models/connection-secret.js';
|
|
5
5
|
import type { Credential } from '../models/credential.js';
|
|
6
6
|
import type { Environment } from '../models/environment.js';
|
|
7
|
+
import type { EnvironmentRequest } from '../models/environment-request.js';
|
|
8
|
+
import type { EnvironmentRequestDetail } from '../models/environment-request-detail.js';
|
|
9
|
+
import type { EnvironmentRequestStats } from '../models/environment-request-stats.js';
|
|
7
10
|
import type { EnvironmentSnapshot } from '../models/environment-snapshot.js';
|
|
8
11
|
import type { EventPage } from '../models/event-page.js';
|
|
9
12
|
import type { CaptureSnapshotRequestBody } from '../models/operations/capture-snapshot.js';
|
|
13
|
+
import type { GetEnvironmentRequestStatsRequest } from '../models/operations/get-environment-request-stats.js';
|
|
14
|
+
import type { ListEnvironmentRequestsRequest } from '../models/operations/list-environment-requests.js';
|
|
10
15
|
import type { ListEnvironmentsRequest } from '../models/operations/list-environments.js';
|
|
11
16
|
import type { ListSnapshotsRequest } from '../models/operations/list-snapshots.js';
|
|
12
17
|
import type { ListWorkspacesRequest } from '../models/operations/list-workspaces.js';
|
|
@@ -33,6 +38,9 @@ export interface StateMachinesOptions {
|
|
|
33
38
|
export interface CallOptions {
|
|
34
39
|
signal?: AbortSignal;
|
|
35
40
|
}
|
|
41
|
+
export interface LifecycleOptions extends CallOptions {
|
|
42
|
+
idempotencyKey?: string;
|
|
43
|
+
}
|
|
36
44
|
export interface CreateOptions extends CallOptions {
|
|
37
45
|
idempotencyKey?: string;
|
|
38
46
|
workspaceId?: string;
|
|
@@ -93,18 +101,22 @@ export declare class StateMachines {
|
|
|
93
101
|
*/
|
|
94
102
|
create: (input: EnvironmentSource, options?: CreateOptions) => Promise<Environment>;
|
|
95
103
|
/** Ends the environment and discards its data. Safe to repeat. */
|
|
96
|
-
stop: (environmentId: string, options?:
|
|
104
|
+
stop: (environmentId: string, options?: LifecycleOptions | undefined) => Promise<Environment>;
|
|
97
105
|
/**
|
|
98
106
|
* Suspends a running environment: its sandboxes end and its data stays for `resume`.
|
|
99
107
|
* Its lifetime is paused meanwhile. Use `stop` to end it.
|
|
100
108
|
*/
|
|
101
|
-
suspend: (environmentId: string, options?:
|
|
102
|
-
/**
|
|
103
|
-
resume: (environmentId: string, options?:
|
|
109
|
+
suspend: (environmentId: string, options?: LifecycleOptions | undefined) => Promise<Environment>;
|
|
110
|
+
/** Resumes a suspended or failed environment using its retained data. */
|
|
111
|
+
resume: (environmentId: string, options?: LifecycleOptions | undefined) => Promise<Environment>;
|
|
104
112
|
events: (environmentId: string, query?: {
|
|
105
113
|
limit?: number;
|
|
106
114
|
cursor?: string;
|
|
107
115
|
}, options?: CallOptions | undefined) => Promise<EventPage>;
|
|
116
|
+
listRequests: (environmentId: string, query?: Omit<ListEnvironmentRequestsRequest, "environmentId">, options?: CallOptions | undefined) => Promise<Page<EnvironmentRequest>>;
|
|
117
|
+
getRequestStats: (environmentId: string, query: Omit<GetEnvironmentRequestStatsRequest, "environmentId">, options?: CallOptions | undefined) => Promise<EnvironmentRequestStats>;
|
|
118
|
+
getRequest: (environmentId: string, requestId: string, options?: CallOptions | undefined) => Promise<EnvironmentRequestDetail>;
|
|
119
|
+
getRequestPayload: (environmentId: string, requestId: string, direction: "request" | "response", options?: CallOptions | undefined) => Promise<ReadableStream<Uint8Array<ArrayBufferLike>>>;
|
|
108
120
|
/** The app's users, in the release's order. */
|
|
109
121
|
actors: (environmentId: string, appKey: string, options?: CallOptions | undefined) => Promise<ReleaseActor[]>;
|
|
110
122
|
getConnection: (environmentId: string, appKey: string, options?: CallOptions | undefined) => Promise<ConnectionDetails>;
|
package/esm/extensions/client.js
CHANGED
|
@@ -128,15 +128,19 @@ export class StateMachines {
|
|
|
128
128
|
}
|
|
129
129
|
},
|
|
130
130
|
/** Ends the environment and discards its data. Safe to repeat. */
|
|
131
|
-
stop: (environmentId, options) => this.#
|
|
131
|
+
stop: (environmentId, options) => this.#command('stop', environmentId, options),
|
|
132
132
|
/**
|
|
133
133
|
* Suspends a running environment: its sandboxes end and its data stays for `resume`.
|
|
134
134
|
* Its lifetime is paused meanwhile. Use `stop` to end it.
|
|
135
135
|
*/
|
|
136
|
-
suspend: (environmentId, options) => this.#
|
|
137
|
-
/**
|
|
138
|
-
resume: (environmentId, options) => this.#
|
|
136
|
+
suspend: (environmentId, options) => this.#command('suspend', environmentId, options),
|
|
137
|
+
/** Resumes a suspended or failed environment using its retained data. */
|
|
138
|
+
resume: (environmentId, options) => this.#command('resume', environmentId, options),
|
|
139
139
|
events: (environmentId, query = {}, options) => this.#call(options, (call) => this.#sdk.environments.events({ ...query, environmentId }, call)),
|
|
140
|
+
listRequests: (environmentId, query = {}, options) => this.#call(options, (call) => this.#sdk.environments.listRequests({ ...query, environmentId }, call)),
|
|
141
|
+
getRequestStats: (environmentId, query, options) => this.#unwrap(options, (call) => this.#sdk.environments.getRequestStats({ ...query, environmentId }, call)),
|
|
142
|
+
getRequest: (environmentId, requestId, options) => this.#unwrap(options, (call) => this.#sdk.environments.getRequest({ environmentId, requestId }, call)),
|
|
143
|
+
getRequestPayload: (environmentId, requestId, direction, options) => this.#call(options, (call) => this.#sdk.environments.getRequestPayload({ environmentId, requestId, direction }, call)),
|
|
140
144
|
/** The app's users, in the release's order. */
|
|
141
145
|
actors: async (environmentId, appKey, options) => (await this.environments.getConnection(environmentId, appKey, options))
|
|
142
146
|
.actors,
|
|
@@ -227,6 +231,15 @@ export class StateMachines {
|
|
|
227
231
|
/** Marks the snapshot deleted and returns it; safe to repeat. A capturing snapshot is a 409 `not-ready`. */
|
|
228
232
|
delete: (snapshotId, options) => this.#unwrap(options, (call) => this.#sdk.snapshots.delete({ snapshotId }, call)),
|
|
229
233
|
};
|
|
234
|
+
async #command(verb, environmentId, options = {}) {
|
|
235
|
+
const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
|
|
236
|
+
try {
|
|
237
|
+
return await this.#unwrap(options, (call) => this.#sdk.environments[verb]({ environmentId, idempotencyKey }, call));
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
throw new StateMachinesError(error, { idempotencyKey });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
230
243
|
async #createSnapshot(environmentId, input, options, busyMs) {
|
|
231
244
|
const idempotencyKey = options.idempotencyKey ?? crypto.randomUUID();
|
|
232
245
|
try {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export type { Fetcher, HTTPClientOptions } from '../lib/http.js';
|
|
2
2
|
export { HTTPClient } from '../lib/http.js';
|
|
3
3
|
export { ConnectionError, ErrorResponse, HTTPClientError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, ResponseValidationError, SDKValidationError, StateMachinesHTTPError, UnexpectedClientError, UnexpectedResponseError, } from '../models/errors/index.js';
|
|
4
|
-
export type { ApiProfile, App, AppInstanceSnapshot, Catalog, Connection as ConnectionDetails, ConnectionSecret, CreateEnvironmentInput, Credential, Environment, EnvironmentApp, EnvironmentSnapshot, Event, EventPage, Release, ReleaseActor, Workspace, } from '../models/index.js';
|
|
4
|
+
export type { ApiProfile, App, AppInstanceSnapshot, Catalog, Connection as ConnectionDetails, ConnectionSecret, CreateEnvironmentInput, Credential, Environment, EnvironmentApp, EnvironmentRequest, EnvironmentRequestDetail, EnvironmentRequestStats, EnvironmentSnapshot, Event, EventPage, Release, ReleaseActor, Workspace, } from '../models/index.js';
|
|
5
5
|
export { Code as ErrorCode, Disposal, EnvironmentStatus, StopReason, } from '../models/index.js';
|
|
6
6
|
export { Status as EnvironmentListStatus } from '../models/operations/list-environments.js';
|
|
7
7
|
export type { AppInput, EnvironmentInput, SnapshotEnvironmentInput, } from './apps.js';
|
|
8
|
-
export type { CallOptions, CaptureInput, CaptureOptions, ConnectOptions, CreateOptions, ListEnvironmentsQuery, ListSnapshotsQuery, Page, StartOptions, StateMachinesOptions, } from './client.js';
|
|
8
|
+
export type { CallOptions, CaptureInput, CaptureOptions, ConnectOptions, CreateOptions, LifecycleOptions, ListEnvironmentsQuery, ListSnapshotsQuery, Page, StartOptions, StateMachinesOptions, } from './client.js';
|
|
9
9
|
export { StateMachines } from './client.js';
|
|
10
10
|
export { Connection, formatActorHeader } from './connection.js';
|
|
11
11
|
export { DisposalIncompleteError, EnvironmentFailedError, SnapshotFailedError, SnapshotTimeoutError, StateMachinesError, TimeoutError, } from './errors.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Environment } from '../models/environment.js';
|
|
2
2
|
import type { EnvironmentSnapshot } from '../models/environment-snapshot.js';
|
|
3
3
|
import type { ReleaseActor } from '../models/release-actor.js';
|
|
4
|
-
import type { CallOptions, CaptureInput, CaptureOptions, ConnectOptions, StateMachines } from './client.js';
|
|
4
|
+
import type { CallOptions, CaptureInput, CaptureOptions, ConnectOptions, LifecycleOptions, StateMachines } from './client.js';
|
|
5
5
|
import type { Connection } from './connection.js';
|
|
6
6
|
import type { WaitOptions } from './wait.js';
|
|
7
7
|
/** A started environment. It remains the handle after `suspend()` and `stop()`. */
|
|
@@ -25,18 +25,18 @@ export declare class RunningEnvironment {
|
|
|
25
25
|
* Ends the sandboxes and keeps the data for `resume()`. Doesn't wait: use
|
|
26
26
|
* `waitUntilSuspended()` before resuming.
|
|
27
27
|
*/
|
|
28
|
-
suspend(options?:
|
|
28
|
+
suspend(options?: LifecycleOptions): Promise<Environment>;
|
|
29
29
|
/** Resolves when the environment is suspended and can resume. */
|
|
30
30
|
waitUntilSuspended(options?: WaitOptions): Promise<Environment>;
|
|
31
|
-
/** Runs a suspended environment again on its data. Use `waitUntilReady()` before connecting. */
|
|
32
|
-
resume(options?:
|
|
31
|
+
/** Runs a suspended or failed environment again on its data. Use `waitUntilReady()` before connecting. */
|
|
32
|
+
resume(options?: LifecycleOptions): Promise<Environment>;
|
|
33
33
|
/** Resolves when the environment is running again. */
|
|
34
34
|
waitUntilReady(options?: WaitOptions): Promise<Environment>;
|
|
35
35
|
/**
|
|
36
36
|
* Ends the environment and discards its data. Safe to call twice. Doesn't wait for
|
|
37
37
|
* disposal: use `waitUntilStopped()`.
|
|
38
38
|
*/
|
|
39
|
-
stop(options?:
|
|
39
|
+
stop(options?: LifecycleOptions): Promise<Environment>;
|
|
40
40
|
/** Resolves when the environment ended and every sandbox is confirmed disposed. */
|
|
41
41
|
waitUntilStopped(options?: WaitOptions): Promise<Environment>;
|
|
42
42
|
toJSON(): {
|
|
@@ -41,7 +41,7 @@ export class RunningEnvironment {
|
|
|
41
41
|
waitUntilSuspended(options) {
|
|
42
42
|
return this.#environments.waitUntilSuspended(this.id, options);
|
|
43
43
|
}
|
|
44
|
-
/** Runs a suspended environment again on its data. Use `waitUntilReady()` before connecting. */
|
|
44
|
+
/** Runs a suspended or failed environment again on its data. Use `waitUntilReady()` before connecting. */
|
|
45
45
|
resume(options) {
|
|
46
46
|
return this.#environments.resume(this.id, options);
|
|
47
47
|
}
|
package/esm/extensions/wait.js
CHANGED
|
@@ -88,7 +88,7 @@ export function suspended(environment) {
|
|
|
88
88
|
}
|
|
89
89
|
/** Resolves once the environment ended and every app's sandbox is confirmed disposed. */
|
|
90
90
|
export function disposed(environment) {
|
|
91
|
-
if (environment.status !== 'stopped'
|
|
91
|
+
if (environment.status !== 'stopped') {
|
|
92
92
|
return false;
|
|
93
93
|
}
|
|
94
94
|
const unconfirmed = environment.apps.some(({ disposal }) => disposal === 'failed' || disposal === 'unknown');
|
|
@@ -8,4 +8,4 @@ import { StateMachinesHTTPError } from "../models/errors/state-machines-http-err
|
|
|
8
8
|
import * as operations from "../models/operations/index.js";
|
|
9
9
|
import { APIPromise } from "../types/async.js";
|
|
10
10
|
import { Result } from "../types/fp.js";
|
|
11
|
-
export declare function
|
|
11
|
+
export declare function environmentsGetRequestPayload(client: StateMachinesCore, request: operations.GetEnvironmentRequestPayloadRequest, options?: RequestOptions): APIPromise<Result<ReadableStream<Uint8Array>, errors.ErrorResponse | StateMachinesHTTPError | ResponseValidationError | ConnectionError | RequestAbortedError | RequestTimeoutError | InvalidRequestError | UnexpectedClientError | SDKValidationError>>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
|
|
3
|
+
*/
|
|
4
|
+
import * as z from "zod/v4-mini";
|
|
5
|
+
import { encodeSimple } from "../lib/encodings.js";
|
|
6
|
+
import { matchStatusCode } from "../lib/http.js";
|
|
7
|
+
import * as M from "../lib/matchers.js";
|
|
8
|
+
import { compactMap } from "../lib/primitives.js";
|
|
9
|
+
import { safeParse } from "../lib/schemas.js";
|
|
10
|
+
import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js";
|
|
11
|
+
import { pathToFunc } from "../lib/url.js";
|
|
12
|
+
import * as errors from "../models/errors/index.js";
|
|
13
|
+
import * as operations from "../models/operations/index.js";
|
|
14
|
+
import { APIPromise } from "../types/async.js";
|
|
15
|
+
export function environmentsGetRequestPayload(client, request, options) {
|
|
16
|
+
return new APIPromise($do(client, request, options));
|
|
17
|
+
}
|
|
18
|
+
async function $do(client, request, options) {
|
|
19
|
+
const parsed = safeParse(request, (value) => z.parse(operations.GetEnvironmentRequestPayloadRequest$outboundSchema, value), "Input validation failed");
|
|
20
|
+
if (!parsed.ok) {
|
|
21
|
+
return [parsed, { status: "invalid" }];
|
|
22
|
+
}
|
|
23
|
+
const payload = parsed.value;
|
|
24
|
+
const body = null;
|
|
25
|
+
const pathParams = {
|
|
26
|
+
direction: encodeSimple("direction", payload.direction, {
|
|
27
|
+
explode: false,
|
|
28
|
+
charEncoding: "percent",
|
|
29
|
+
}),
|
|
30
|
+
environmentId: encodeSimple("environmentId", payload.environmentId, {
|
|
31
|
+
explode: false,
|
|
32
|
+
charEncoding: "percent",
|
|
33
|
+
}),
|
|
34
|
+
requestId: encodeSimple("requestId", payload.requestId, {
|
|
35
|
+
explode: false,
|
|
36
|
+
charEncoding: "percent",
|
|
37
|
+
}),
|
|
38
|
+
};
|
|
39
|
+
const path = pathToFunc("/v1/environments/{environmentId}/requests/{requestId}/payload/{direction}")(pathParams);
|
|
40
|
+
const headers = new Headers(compactMap({
|
|
41
|
+
Accept: "application/octet-stream",
|
|
42
|
+
}));
|
|
43
|
+
const secConfig = await extractSecurity(client._options.apiKey);
|
|
44
|
+
const securityInput = secConfig == null ? {} : { apiKey: secConfig };
|
|
45
|
+
const requestSecurity = resolveGlobalSecurity(securityInput);
|
|
46
|
+
const context = {
|
|
47
|
+
options: client._options,
|
|
48
|
+
baseURL: options?.serverURL ?? client._baseURL ?? "",
|
|
49
|
+
operationID: "getEnvironmentRequestPayload",
|
|
50
|
+
oAuth2Scopes: null,
|
|
51
|
+
resolvedSecurity: requestSecurity,
|
|
52
|
+
securitySource: client._options.apiKey,
|
|
53
|
+
retryConfig: options?.retries
|
|
54
|
+
|| client._options.retryConfig
|
|
55
|
+
|| {
|
|
56
|
+
strategy: "backoff",
|
|
57
|
+
backoff: {
|
|
58
|
+
initialInterval: 1000,
|
|
59
|
+
maxInterval: 5000,
|
|
60
|
+
exponent: 1.5,
|
|
61
|
+
maxElapsedTime: 600000,
|
|
62
|
+
},
|
|
63
|
+
retryConnectionErrors: true,
|
|
64
|
+
}
|
|
65
|
+
|| { strategy: "none" },
|
|
66
|
+
retryCodes: options?.retryCodes || ["502", "503", "504"],
|
|
67
|
+
};
|
|
68
|
+
const requestRes = client._createRequest(context, {
|
|
69
|
+
security: requestSecurity,
|
|
70
|
+
method: "GET",
|
|
71
|
+
baseURL: options?.serverURL,
|
|
72
|
+
path: path,
|
|
73
|
+
headers: headers,
|
|
74
|
+
body: body,
|
|
75
|
+
userAgent: client._options.userAgent,
|
|
76
|
+
timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1,
|
|
77
|
+
}, options);
|
|
78
|
+
if (!requestRes.ok) {
|
|
79
|
+
return [requestRes, { status: "invalid" }];
|
|
80
|
+
}
|
|
81
|
+
const req = requestRes.value;
|
|
82
|
+
const doResult = await client._do(req, {
|
|
83
|
+
context,
|
|
84
|
+
isErrorStatusCode: (statusCode) => matchStatusCode({ status: statusCode }, ["4XX", "5XX"]),
|
|
85
|
+
retryConfig: context.retryConfig,
|
|
86
|
+
retryCodes: context.retryCodes,
|
|
87
|
+
});
|
|
88
|
+
if (!doResult.ok) {
|
|
89
|
+
return [doResult, { status: "request-error", request: req }];
|
|
90
|
+
}
|
|
91
|
+
const response = doResult.value;
|
|
92
|
+
const responseFields = {
|
|
93
|
+
HttpMeta: { Response: response, Request: req },
|
|
94
|
+
};
|
|
95
|
+
const [result] = await M.match(M.stream(200, z.custom(x => x instanceof ReadableStream)), M.jsonErr([400, 401, 403, 404, 409, 413, 422, 429], errors.ErrorResponse$inboundSchema), M.jsonErr([500, 503], errors.ErrorResponse$inboundSchema), M.fail("4XX"), M.fail("5XX"))(response, req, { extraFields: responseFields });
|
|
96
|
+
if (!result.ok) {
|
|
97
|
+
return [result, { status: "complete", request: req, response }];
|
|
98
|
+
}
|
|
99
|
+
return [result, { status: "complete", request: req, response }];
|
|
100
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { StateMachinesCore } from "../core.js";
|
|
2
|
+
import { RequestOptions } from "../lib/sdks.js";
|
|
3
|
+
import { ConnectionError, InvalidRequestError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError } from "../models/errors/http-client-errors.js";
|
|
4
|
+
import * as errors from "../models/errors/index.js";
|
|
5
|
+
import { ResponseValidationError } from "../models/errors/response-validation-error.js";
|
|
6
|
+
import { SDKValidationError } from "../models/errors/sdk-validation-error.js";
|
|
7
|
+
import { StateMachinesHTTPError } from "../models/errors/state-machines-http-error.js";
|
|
8
|
+
import * as operations from "../models/operations/index.js";
|
|
9
|
+
import { APIPromise } from "../types/async.js";
|
|
10
|
+
import { Result } from "../types/fp.js";
|
|
11
|
+
export declare function environmentsGetRequestStats(client: StateMachinesCore, request: operations.GetEnvironmentRequestStatsRequest, options?: RequestOptions): APIPromise<Result<operations.GetEnvironmentRequestStatsResponse, errors.ErrorResponse | StateMachinesHTTPError | ResponseValidationError | ConnectionError | RequestAbortedError | RequestTimeoutError | InvalidRequestError | UnexpectedClientError | SDKValidationError>>;
|