@usestatemachines/sdk 0.7.0 → 0.8.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 +86 -33
- package/agents/SKILL.md +71 -48
- package/agents/index.d.ts +2 -0
- package/agents/index.js +9 -7
- package/agents/llms.txt +23 -15
- package/agents/prompt.md +5 -25
- package/esm/extensions/client.d.ts +11 -7
- package/esm/extensions/client.js +32 -49
- package/esm/extensions/credentials.d.ts +25 -8
- package/esm/extensions/credentials.js +75 -40
- package/esm/extensions/environment.d.ts +1 -1
- package/esm/extensions/errors.js +1 -1
- package/esm/extensions/index.d.ts +2 -2
- package/esm/extensions/yaml.js +14 -12
- package/esm/funcs/environments-creators.d.ts +11 -0
- package/esm/funcs/environments-creators.js +90 -0
- package/esm/funcs/environments-list.js +2 -0
- package/esm/funcs/requests-list.js +5 -1
- package/esm/funcs/requests-stats.js +5 -1
- package/esm/lib/config.d.ts +2 -2
- package/esm/lib/config.js +2 -2
- package/esm/models/app-entry.d.ts +8 -0
- package/esm/models/app-entry.js +11 -0
- package/esm/models/create-environment-app.d.ts +25 -0
- package/esm/models/create-environment-app.js +14 -0
- package/esm/models/create-environment.d.ts +3 -26
- package/esm/models/create-environment.js +2 -19
- package/esm/models/credential.d.ts +50 -0
- package/esm/models/credential.js +60 -0
- package/esm/models/credentials.d.ts +26 -5
- package/esm/models/credentials.js +20 -3
- package/esm/models/environment-failure.d.ts +3 -2
- package/esm/models/environment-failure.js +3 -2
- package/esm/models/environment.d.ts +4 -1
- package/esm/models/environment.js +2 -1
- package/esm/models/error.d.ts +1 -0
- package/esm/models/error.js +1 -0
- package/esm/models/index.d.ts +6 -1
- package/esm/models/index.js +6 -1
- package/esm/models/mcp-server.d.ts +11 -0
- package/esm/models/mcp-server.js +16 -0
- package/esm/models/mcp-tool.d.ts +12 -0
- package/esm/models/mcp-tool.js +16 -0
- package/esm/models/me.d.ts +2 -0
- package/esm/models/me.js +2 -0
- package/esm/models/operations/create-credentials.d.ts +2 -0
- package/esm/models/operations/create-credentials.js +1 -0
- package/esm/models/operations/get-request-stats.d.ts +10 -2
- package/esm/models/operations/get-request-stats.js +5 -1
- package/esm/models/operations/index.d.ts +1 -0
- package/esm/models/operations/index.js +1 -0
- package/esm/models/operations/list-environment-creators.d.ts +23 -0
- package/esm/models/operations/list-environment-creators.js +20 -0
- package/esm/models/operations/list-environments.d.ts +5 -1
- package/esm/models/operations/list-environments.js +2 -0
- package/esm/models/operations/list-requests.d.ts +10 -2
- package/esm/models/operations/list-requests.js +5 -1
- package/esm/models/request-detail.d.ts +8 -1
- package/esm/models/request-detail.js +5 -1
- package/esm/models/request-stats.d.ts +8 -0
- package/esm/models/request-stats.js +9 -0
- package/esm/models/request.d.ts +8 -1
- package/esm/models/request.js +5 -1
- package/esm/models/service.d.ts +25 -0
- package/esm/models/service.js +28 -0
- package/esm/models/snapshot.d.ts +7 -0
- package/esm/models/snapshot.js +3 -0
- package/esm/models/version.d.ts +2 -2
- package/esm/models/version.js +2 -2
- package/esm/sdk/environments.d.ts +1 -0
- package/esm/sdk/environments.js +4 -0
- package/esm/types/discriminated-union.d.ts +24 -0
- package/esm/types/discriminated-union.js +60 -0
- package/esm/types/smart-union.js +2 -1
- package/openapi.json +596 -116
- package/package.json +6 -1
- package/esm/models/api.d.ts +0 -17
- package/esm/models/api.js +0 -21
package/agents/index.js
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
// Generated by scripts/build-agents.mjs from templates/ and examples/quickstart.ts.
|
|
2
2
|
|
|
3
3
|
export const prompt =
|
|
4
|
-
"
|
|
4
|
+
"Install the State Machines skill in this existing repository so I can use disposable app environments with my coding agent.\n\n1. Read the repository instructions. Download the skill from https://docs.usestatemachines.com/skill.md and install it as `state-machines/SKILL.md` in this agent's supported project-local skills directory. Reuse an identical installed copy. Preserve customizations and ask before replacing a different copy. If persistent skills are unsupported, read it for this session and explain the limitation. If the download fails, report the blocker.\n2. Read the skill. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Keep the repository's existing conventions.\n3. The API key belongs in the project's existing secret configuration as `STATEMACHINES_API_KEY`. Never ask me to paste it into chat, print it or commit it. If I need help configuring it, identify the existing secret loader and explain where to save it without reading or displaying secret values.\n4. Report where the skill was installed and whether the agent needs to reload it. Skill installation alone does not verify an API connection. Ask: \"What would you like to run or test?\" Wait for my answer before making further changes.\n";
|
|
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. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\
|
|
7
|
+
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\nUse the project's package manager to install or reuse `@usestatemachines/sdk`. It is ESM only and runs on Node.js and Cloudflare Workers, not browsers. `engines` in its `package.json` gives the Node.js versions. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. `new StateMachines()` reads the API key from `STATEMACHINES_API_KEY` and doesn't read `.env` files; in Cloudflare Workers, pass `apiKey` explicitly. Never print the key. The installed `node_modules/@usestatemachines/sdk/README.md` matches your version: read it before relying on memory. Read the bundled `agents/SKILL.md` for the task workflow. Reuse the project's secret loader and check the key in the process that runs the test, not just the current shell. Installing the skill does not require SDK installation, example files or remote resources. Ask what the user wants to run and wait. Install the SDK and verify access when their chosen task needs it. Run the connection check below only if the user asks to verify the connection. Do not choose a business workflow from the repository.\n\n## Concepts\n\n- Environment: one disposable run of one or more apps. `const env = await sm.environments.create({ apps: ['salesforce'] })` creates it and waits until it is `running`. Use `{ wait: false }` to retain the ID before startup. Wait for `running` inside `try`, then delete the owned environment in `finally`, including after a wait failure.\n- Apps: a string names the app by its ID, and the app's name in the environment is the same string. Use `{ appId: 'salesforce', name: 'crm', setup }` for your own name, for two copies of one app, or for the app's setup. Later calls take the name.\n- Credentials: `const crm = await env.connect('salesforce')` returns `token`, `services` and `fetch`. Each service has an `id`, a `url` and the `headers` its requests need. The credentials always list each `public` service of the app's version. Pass `{ services: [id] }` to `connect()` to also list a service by its ID. A `preview` service is listed only when named. `crm.service('api')` returns the `api` service, which is the app URL. `crm.fetch(path)` joins `path` to the `api` service URL and adds its headers, which carry `Authorization: Bearer` with `token`. For Salesforce SOAP, also put `crm.token` in the envelope's `SessionHeader/sessionId`. `fetch` never sends your API key, never follows redirects and never retries. `token` and each service's `headers` are secrets.\n- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Find the app by name in `env.apps`, then page through `sm.apps.versions(appId)` to find its exact `versionId`. Read actor IDs from that version's `actors`.\n- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A delete during the snapshot fails it with `interrupted`.\n- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.\n- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.\n- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n\n## Statuses\n\nEnums are open: handle values you don't recognise.\n\n- Environment `status`: `starting`, `running`, `failed`, `deleted`. A `deleted` environment has a `reason` when State Machines deleted it: `expired`, `failed` (it never reached `running`) or `cancelled` (staff ended it). The `reason` is `null` when a caller deleted it. When the environment failed, `failure` is `{ appName, code, message }`, and `code` is `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. For `invalid_setup` and `invalid_services`, the app refused a value in `setup` or in `services`, and `message` starts with its path.\n- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.\n- `create` throws `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.\n- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.\n- `sm.environments.wait(id, { status })` and `sm.snapshots.wait(id, { status })` wait for any status, and throw once it cannot be reached without another call.\n\n## Limits\n\nWhen `sm.me().limits` is non-null:\n\n- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.\n- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `message`, `requestId`, `fields` and `retryAfterMs`. The SDK retries `502`, `503`, `504` and connection errors itself, until a deadline; `create` retries reuse one idempotency key. It retries nothing else.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |\n| `forbidden` | 403 | The key lacks the permission. |\n| `not_found` | 404 | Check the ID and the workspace. |\n| `invalid_status` | 409 | The status does not allow the call. Snapshots need a running environment. |\n| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |\n| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |\n| `workspace_archived` | 409 | The workspace is archived. |\n| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |\n| `version_unavailable` | 422 | The app has no default version. |\n| `environment_limit_reached` | 429 | Delete only this task’s known leftovers, or ask the user to free capacity. |\n| `unavailable` | 503 | Retried automatically. If `create` still has an unknown outcome, replay the same input with the key retained before the original call. Do not generate a new key. |\n\n## Errors from the app URL\n\n`crm.fetch` returns these as responses with the same JSON envelope, and never retries them. Assert the expected status and result. For writes, read back the stored result. Never blindly retry a write whose outcome is unknown.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment_not_running` | 409 | The environment is failed or deleted; `error.status` names it. Create another environment. |\n| `environment_starting` | 503 | For reads, wait `Retry-After` and retry. Check stored state before retrying an uncertain write. |\n| `environment_unavailable` | 503 | The app is restarting. For reads, wait `Retry-After`. Check stored state before retrying an uncertain write. |\n| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |\n| `invalid_setup` | 503 | The app refused its `setup` after the environment started, such as in a newer version. `error.message` starts with the path of the value. Create another environment with a `setup` that the app accepts. |\n| `invalid_services` | 503 | The app refused a value in `services` after the environment started. `error.message` starts with the path of the value. Create another environment with `services` that the app accepts. |\n| `unsupported_protocol` | 501 | The app does not serve this path, method or content type, or the request body is compressed. |\n\n## Quickstart\n\nUse the project's TypeScript runner and secret loader. For an empty Node.js project, save as `state-quickstart.mts` and run `npx tsx state-quickstart.mts` with the key available. The check prints the response status and deletes the environment. Only after it prints `200`, report verified setup and the rerun command. Continue only with an explicitly supplied task; otherwise ask what to run next and wait with no setup environment left running.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Docs\n\n- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://docs.usestatemachines.com/skill.md): workflow, rules and troubleshooting for coding agents\n- [OpenAPI document](https://cdn.jsdelivr.net/npm/@usestatemachines/sdk/openapi.json): the HTTP API the SDK calls\n- [State Machines](https://usestatemachines.com): website\n";
|
|
8
8
|
|
|
9
9
|
export const skill =
|
|
10
|
-
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a disposable copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - creating environments, credentials, choosing an actor, snapshots, cleanup, and errors such as environment_limit_reached and version_unavailable. Also use when the user mentions State Machines, STATEMACHINES_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory. It matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATEMACHINES_API_KEY` is set without printing it (`test -n \"$STATEMACHINES_API_KEY\"`). If it isn't, ask the user to set it. The SDK doesn't read `.env` files.\n2. Create the environment with only the apps the task needs: `const env = await sm.environments.create({ apps: ['salesforce'] })`. Log `await sm.apps.list()` for each app's ID. Don't guess IDs. `create` waits until the environment is `running`. If the start fails, the server deletes the environment and `create` throws `EnvironmentFailedError` with `err.environment.failure`.\n3. Open a `try` right after `create` returns, and call `await env.delete()` in its `finally`. It deletes the environment and its data.\n4. Get credentials for one app: `const crm = await env.connect('salesforce')`. This acts as the app's default actor, the Salesforce administrator. To act with another user's permissions, pass an `actorId` from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name.\n5. Call the app with `crm.fetch(path)`. A leading `/` means the root of the app's `url`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Rules\n\n- Always delete in `finally`.\n- To create without waiting, pass `{ wait: false }`, then `sm.environments.wait(env.id, { status: 'running' })`.\n- The time limit counts `starting` and `running`. `(await sm.me()).limits.timeLimitMinutes` gives its `default` and `maximum`. Set `timeLimitMinutes` in `create` for longer runs.\n- Running environments are capped per organization: `limits.concurrentEnvironments` from `sm.me()`. Delete the ones you no longer need.\n- Never print, log or commit `STATEMACHINES_API_KEY`, `credentials.token` or `credentials.headers`.\n- Salesforce's SOAP API takes the actor token in the envelope, not a header: put `crm.token` in `SessionHeader/sessionId`. `crm.fetch` then sends only the environment token header.\n- `crm.fetch` never sends your API key, never follows redirects and only reaches URLs under the app's `url`.\n- Runtimes: Node.js, at the versions in the package's `engines` field, and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`. A start takes longer than one request may last, so create with `{ wait: false }` and read `sm.environments.get(id)` in later requests until it is `running`, or pass a `signal` no shorter than the expected start.\n- Every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshots.create({ name })` once, then `sm.environments.create({ snapshotId })` in place of `apps`.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `SnapshotFailedError`, `UnexpectedStatusError`, `WaitTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If you need to replay a create whose outcome is unknown, pass your own key: `sm.environments.create(input, { idempotencyKey })`, and call it again with the same input and key. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency_key_reused`.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `version_unavailable`, 422 | The app has no default version. | Check the app ID against `sm.apps.list()`. |\n| `environment_limit_reached`, 429 | The organization is at its cap of running environments. | List them with `sm.environments.list({ status: ['starting', 'running'] })`, delete one, then create again. |\n| `invalid_status`, 409 | The status does not allow the call, for example taking a snapshot of an environment that is `starting`. | Read `sm.environments.get(id)` and act on its `status`. |\n| `invalid_request`, 400 | A wrong field. | Read `err.fields`, keyed by dotted path. |\n| `EnvironmentFailedError` | The environment failed to start. | Read `err.environment.failure`: `{ app, code, message }`. `invalid_settings` means the app refused its settings. |\n| `UnexpectedStatusError` | The environment was deleted while the SDK waited. | Read `err.status` and `err.resource`. |\n| `WaitTimeoutError` | The status was not reached within `timeoutMs`. | Wait again with `sm.environments.wait(id, { status })`, or delete the environment. |\n| `snapshot_in_progress`, 409 | The environment already has a snapshot in `saving`. | `const [running] = (await sm.snapshots.list({ environmentId: env.id, status: ['saving'] })).data`, then `await sm.snapshots.wait(running.id, { status: 'ready' })`, then create another. |\n| `SnapshotFailedError` | The snapshot failed. `interrupted` means the environment was deleted first. | Create another snapshot while the environment is `running`. |\n| `environment_not_running`, 409, from `crm.fetch` | The environment is failed or deleted. `crm.fetch` returns it as a response and never retries. | Read `(await res.json()).error.status`. Create a new environment if you need another run. |\n| `environment_starting` or `environment_unavailable`, 503, from `crm.fetch` | The app is starting or restarting. | Wait the `Retry-After` seconds and call again. |\n| A vendor client such as jsforce is refused by the gateway | The gateway needs `StateMachines-Environment-Token` on every request. | Prefer `crm.fetch`. If you pass `crm.headers` to another client, send them only to `crm.url` and disable redirects. |\n| `TypeError: Pass apiKey or set STATEMACHINES_API_KEY.` | No key in the environment. | Ask the user to set `STATEMACHINES_API_KEY`. In Workers, pass `apiKey`. |\n\nMore: https://docs.usestatemachines.com, https://app.usestatemachines.com/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n";
|
|
10
|
+
"---\nname: state-machines\ndescription: Use when setting up State Machines or running code, integration tests, or API experiments against disposable SaaS replicas such as Salesforce. Applies to @usestatemachines/sdk and STATEMACHINES_API_KEY, including environment creation, actors, snapshots, cleanup and recovery.\n---\n\n## Start with the user's task\n\nDuring skill installation, read the repository instructions and preserve its existing structure. Do not create a new project, install dependencies, write examples or create remote resources. Report the installed skill location and any reload requirement, then ask \"What would you like to run or test?\" and wait. Skill installation does not verify a connection.\n\nOnce the user chooses a task, inspect the project's package manager, runtime, runner and secret loader. Install or reuse a compatible `@usestatemachines/sdk` only when the task needs it. Read the installed README for API signatures and `package.json` for runtime requirements. The SDK is ESM and runs on Node.js and Cloudflare Workers, not in a browser. Follow the user's task and existing project conventions without requiring a separate onboarding example.\n\n## Check access in the right process\n\nThe SDK reads `STATEMACHINES_API_KEY` from the process environment. It does not load `.env` files. Use the project's existing test command or secret loader. An empty variable in your current shell does not prove that the test process lacks it. Verify presence without displaying the value. In Workers, pass the binding explicitly with `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`.\n\nCall `sm.me()` to verify access and workspace scope before creating resources. `me.limits` can be null. If the key is missing, prepare the local test or example and tell the user the exact local file, binding, or launch command to configure and rerun, without asking for the key in chat. Do not call the API until access is available. If access is denied or the workspace differs from the task, report the blocker. Do not invite or remove members, or change permissions.\n\nNever print, log or commit API keys, `credentials.token`, the `headers` of `credentials.services`, environment dumps, or secret-file contents. Use synthetic test data.\n\n## Run the user’s chosen task\n\nApply this section after setup, once the user has chosen a task.\n\n- `sm.apps.list()` returns app IDs. Every list returns `{ data, nextCursor }`. Follow cursors until the required entry is found or `nextCursor` is null.\n- Create only the apps the task needs. A string such as `'salesforce'` is both its app ID and its name in the environment. For named apps, later `connect()` calls use the name.\n- `connect(appName)` uses the app's default actor, the Salesforce administrator. For another actor, find the matching app by name in `environment.apps`, read its `versionId`, then find that exact version through `sm.apps.versions(appId)`. Use an actor ID from its `actors`, never a role label, workspace member ID, or the first version in a list.\n- Check the app's services and [known differences](https://docs.usestatemachines.com/apps/known-differences.md) for the behavior under test. A replica does not import a customer's org or run arbitrary customer automation.\n- Configure the existing integration's test transport with the returned app URL and credentials. Verify its requests reach that URL. A successful standalone SDK request does not prove the integration uses the replica. If transport configuration needs a broader change, explain it before expanding the task.\n- Check the expected HTTP status and assert the result. For writes, read the stored data back and assert the relevant fields. For negative tests, assert the expected error. Do not weaken an assertion to make unsupported behavior pass.\n\n## Own the full lifecycle\n\nCreate with `{ wait: false }` to retain the accepted environment ID before waiting. Enter `try` immediately, then wait for `running`, connect and run the check inside it. Delete in `finally`, including after a startup failure, timeout or failed assertion. An aborted wait does not cancel the work that the API accepted. Cleanup must use a fresh, un-aborted signal. Preserve both verification and cleanup errors, and report the environment ID if deletion fails.\n\nDelete only environments created for this task. If the organization is at its limit, clean up a known leftover from this task or ask the user to free capacity. Do not delete unrelated environments or a user-supplied reusable snapshot.\n\nThe SDK retries management connection errors and `502`, `503`, `504` with one idempotency key per create call. To recover across separate attempts or a restart, retain the input and an explicit `idempotencyKey` before creation. Replay using the same input, key, workspace and caller. Do not create a replacement with a new key while the first outcome is unknown. See [operation recovery](https://docs.usestatemachines.com/sdk-api/recovery.md).\n\n## Optional connection check\n\nRun this only when the user asks to verify the connection. It proves the connection and cleanup, not an existing integration's behavior. Save it in the project's examples or test location and run it with the existing TypeScript runner and secret loader. In a new Node.js project, `state-quickstart.mts` and `npx tsx state-quickstart.mts` are a fallback. Load the key into that process first.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Load details when needed\n\n- **Repeated fixtures or parallel tests:** Read [isolated tests](https://docs.usestatemachines.com/sdk-api/testing.md). Save seeded data with `env.snapshots.create({ name })`, then create each test's environment with `{ snapshotId }`. A snapshot in `saving` cannot be deleted yet. Retain its ID and wait for `ready` or `failed` before cleanup. Delete a reusable snapshot only when the task calls for it.\n- **Another actor, vendor client or SOAP:** Read [credentials](https://docs.usestatemachines.com/environments/credentials.md). `credentials.fetch()` confines requests to the app URL, adds its authentication headers, and never follows redirects. External clients must send a service's `headers` only to its `url` and disable redirects. For Salesforce SOAP, put the actor token in `SessionHeader/sessionId` in the envelope.\n- **Cloudflare Workers:** Pass the key explicitly. Use `{ wait: false }` and keep the environment ID across requests or in the job's state. A request ending does not cancel startup. Follow the worker's background-job lifecycle for polling and cleanup.\n- **Long runs:** Read `sm.me().limits` when non-null. The environment time limit covers starting and running. Use a supported `timeLimitMinutes` when the task needs it.\n\n## Recover without changing the test's meaning\n\nManagement failures throw SDK errors. App HTTP failures are returned as `Response` objects. Use `instanceof` with the SDK error classes. Native `credentials.fetch()` never retries. Read the State Machines error code in `error.code` and distinguish it from an app's own error.\n\n| Failure | Next action |\n| --- | --- |\n| `invalid_request` | Read `err.fields` and the installed method signature. |\n| `version_unavailable` | Discover the app ID and available versions. Stop if the required version is unavailable. |\n| `environment_limit_reached` | Clean up only this task's known leftovers, or report the capacity blocker. |\n| `EnvironmentFailedError` | Read `err.environment.failure` and clean up the owned environment. |\n| `WaitTimeoutError` or abort | Use the retained environment ID. If older code waited inside `create`, a non-null `WaitTimeoutError.resource` carries its ID. If neither an ID nor a replay key is recoverable, report unresolved cleanup. Do not guess from a list. Wait again only if the task should continue. Otherwise delete the owned environment. |\n| Unknown create outcome | Replay the retained input and idempotency key. Do not start another operation with a new key. |\n| `invalid_status` | Read the current resource status before choosing the next call. |\n| `snapshot_in_progress` | Find the saving snapshot for this environment and wait for it before creating another. |\n| `SnapshotFailedError` | Report the failure. Retry only if the task still needs a snapshot and the source environment is running. |\n| App `environment_not_running` | Inspect the environment. Do not silently switch the integration to another target. |\n| App `invalid_setup` or `invalid_services` | The app refused a value of `setup` or `services` after the start. `error.message` starts with its path. Create another environment with a value that the app accepts, and delete the owned one. |\n| App or gateway `503` | For a retryable read, honor `Retry-After`. For a write with an uncertain outcome, inspect stored state or report uncertainty before retrying. |\n| Cleanup failure | Preserve the task result, report the owned resource ID and retry deletion with valid access and a fresh signal. Do not report cleanup as successful. |\n\n## Finish with evidence\n\nLeave the smallest rerunnable test or example. Report the behavior checked, command, assertion result, SDK and app versions, selected actor, resource IDs without secrets, and cleanup outcome. Say when execution was blocked or only typechecking ran. A passing replica check establishes the asserted behavior for that version and actor, not full production compatibility.\n\nFind other guides through https://docs.usestatemachines.com/llms.txt. Read focused pages before the full documentation bundle. This dashboard also serves an agent index at https://app.usestatemachines.com/llms.txt.\n";
|
|
11
11
|
|
|
12
12
|
export const quickstart =
|
|
13
|
-
"import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n";
|
|
13
|
+
"import { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n";
|
|
14
|
+
|
|
15
|
+
export const cliVersion = null;
|
|
14
16
|
|
|
15
17
|
export const templates = Object.freeze({
|
|
16
18
|
prompt:
|
|
17
|
-
"
|
|
19
|
+
"Install the State Machines skill in this existing repository so I can use disposable app environments with my coding agent.\n\n1. Read the repository instructions. Download the skill from https://docs.usestatemachines.com/skill.md and install it as `state-machines/SKILL.md` in this agent's supported project-local skills directory. Reuse an identical installed copy. Preserve customizations and ask before replacing a different copy. If persistent skills are unsupported, read it for this session and explain the limitation. If the download fails, report the blocker.\n2. Read the skill. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Keep the repository's existing conventions.\n3. The API key belongs in the project's existing secret configuration as `STATEMACHINES_API_KEY`. Never ask me to paste it into chat, print it or commit it. If I need help configuring it, identify the existing secret loader and explain where to save it without reading or displaying secret values.\n4. Report where the skill was installed and whether the agent needs to reload it. Skill installation alone does not verify an API connection. Ask: \"What would you like to run or test?\" Wait for my answer before making further changes.\n",
|
|
18
20
|
llmsTxt:
|
|
19
|
-
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\
|
|
21
|
+
"# State Machines\n\n> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.\n\nUse the project's package manager to install or reuse `@usestatemachines/sdk`. It is ESM only and runs on Node.js and Cloudflare Workers, not browsers. `engines` in its `package.json` gives the Node.js versions. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. `new StateMachines()` reads the API key from `STATEMACHINES_API_KEY` and doesn't read `.env` files; in Cloudflare Workers, pass `apiKey` explicitly. Never print the key. The installed `node_modules/@usestatemachines/sdk/README.md` matches your version: read it before relying on memory. Read the bundled `agents/SKILL.md` for the task workflow. Reuse the project's secret loader and check the key in the process that runs the test, not just the current shell. Installing the skill does not require SDK installation, example files or remote resources. Ask what the user wants to run and wait. Install the SDK and verify access when their chosen task needs it. Run the connection check below only if the user asks to verify the connection. Do not choose a business workflow from the repository.\n\n## Concepts\n\n- Environment: one disposable run of one or more apps. `const env = await sm.environments.create({ apps: ['salesforce'] })` creates it and waits until it is `running`. Use `{ wait: false }` to retain the ID before startup. Wait for `running` inside `try`, then delete the owned environment in `finally`, including after a wait failure.\n- Apps: a string names the app by its ID, and the app's name in the environment is the same string. Use `{ appId: 'salesforce', name: 'crm', setup }` for your own name, for two copies of one app, or for the app's setup. Later calls take the name.\n- Credentials: `const crm = await env.connect('salesforce')` returns `token`, `services` and `fetch`. Each service has an `id`, a `url` and the `headers` its requests need. The credentials always list each `public` service of the app's version. Pass `{ services: [id] }` to `connect()` to also list a service by its ID. A `preview` service is listed only when named. `crm.service('api')` returns the `api` service, which is the app URL. `crm.fetch(path)` joins `path` to the `api` service URL and adds its headers, which carry `Authorization: Bearer` with `token`. For Salesforce SOAP, also put `crm.token` in the envelope's `SessionHeader/sessionId`. `fetch` never sends your API key, never follows redirects and never retries. `token` and each service's `headers` are secrets.\n- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Find the app by name in `env.apps`, then page through `sm.apps.versions(appId)` to find its exact `versionId`. Read actor IDs from that version's `actors`.\n- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A delete during the snapshot fails it with `interrupted`.\n- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.\n- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.\n- Pagination: every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n\n## Statuses\n\nEnums are open: handle values you don't recognise.\n\n- Environment `status`: `starting`, `running`, `failed`, `deleted`. A `deleted` environment has a `reason` when State Machines deleted it: `expired`, `failed` (it never reached `running`) or `cancelled` (staff ended it). The `reason` is `null` when a caller deleted it. When the environment failed, `failure` is `{ appName, code, message }`, and `code` is `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. For `invalid_setup` and `invalid_services`, the app refused a value in `setup` or in `services`, and `message` starts with its path.\n- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.\n- `create` throws `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.\n- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.\n- `sm.environments.wait(id, { status })` and `sm.snapshots.wait(id, { status })` wait for any status, and throw once it cannot be reached without another call.\n\n## Limits\n\nWhen `sm.me().limits` is non-null:\n\n- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.\n- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.\n\n## Errors and retries\n\nA failed API call throws `StateMachinesError` with `status`, `code`, `message`, `requestId`, `fields` and `retryAfterMs`. The SDK retries `502`, `503`, `504` and connection errors itself, until a deadline; `create` retries reuse one idempotency key. It retries nothing else.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `invalid_request` | 400 | Read `fields`, keyed by the dotted path of each wrong field. |\n| `forbidden` | 403 | The key lacks the permission. |\n| `not_found` | 404 | Check the ID and the workspace. |\n| `invalid_status` | 409 | The status does not allow the call. Snapshots need a running environment. |\n| `snapshot_in_progress` | 409 | Wait for the running snapshot, then create another. |\n| `idempotency_key_reused` | 409 | The key was used with a different input. Replay with the exact same input. |\n| `workspace_archived` | 409 | The workspace is archived. |\n| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |\n| `version_unavailable` | 422 | The app has no default version. |\n| `environment_limit_reached` | 429 | Delete only this task’s known leftovers, or ask the user to free capacity. |\n| `unavailable` | 503 | Retried automatically. If `create` still has an unknown outcome, replay the same input with the key retained before the original call. Do not generate a new key. |\n\n## Errors from the app URL\n\n`crm.fetch` returns these as responses with the same JSON envelope, and never retries them. Assert the expected status and result. For writes, read back the stored result. Never blindly retry a write whose outcome is unknown.\n\n| Code | Status | What to do |\n| --- | --- | --- |\n| `environment_not_running` | 409 | The environment is failed or deleted; `error.status` names it. Create another environment. |\n| `environment_starting` | 503 | For reads, wait `Retry-After` and retry. Check stored state before retrying an uncertain write. |\n| `environment_unavailable` | 503 | The app is restarting. For reads, wait `Retry-After`. Check stored state before retrying an uncertain write. |\n| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |\n| `invalid_setup` | 503 | The app refused its `setup` after the environment started, such as in a newer version. `error.message` starts with the path of the value. Create another environment with a `setup` that the app accepts. |\n| `invalid_services` | 503 | The app refused a value in `services` after the environment started. `error.message` starts with the path of the value. Create another environment with `services` that the app accepts. |\n| `unsupported_protocol` | 501 | The app does not serve this path, method or content type, or the request body is compressed. |\n\n## Quickstart\n\nUse the project's TypeScript runner and secret loader. For an empty Node.js project, save as `state-quickstart.mts` and run `npx tsx state-quickstart.mts` with the key available. The check prints the response status and deletes the environment. Only after it prints `200`, report verified setup and the rerun command. Continue only with an explicitly supplied task; otherwise ask what to run next and wait with no setup environment left running.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Docs\n\n- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))\n- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions\n- [Agent skill](https://docs.usestatemachines.com/skill.md): workflow, rules and troubleshooting for coding agents\n- [OpenAPI document](https://cdn.jsdelivr.net/npm/@usestatemachines/sdk/openapi.json): the HTTP API the SDK calls\n- [State Machines](https://usestatemachines.com): website\n",
|
|
20
22
|
skill:
|
|
21
|
-
"---\nname: state-machines\ndescription: Use when an agent or test needs a disposable replica of a SaaS app such as Salesforce, to run integration tests or try API calls against a disposable copy instead of a real org. Covers the @usestatemachines/sdk TypeScript SDK - creating environments, credentials, choosing an actor, snapshots, cleanup, and errors such as environment_limit_reached and version_unavailable. Also use when the user mentions State Machines, STATEMACHINES_API_KEY or @usestatemachines/sdk.\n---\n\nRead `node_modules/@usestatemachines/sdk/README.md` before relying on memory. It matches the installed version. If the package is missing, run `npm install @usestatemachines/sdk`.\n\n## Workflow\n\n1. Check that `STATEMACHINES_API_KEY` is set without printing it (`test -n \"$STATEMACHINES_API_KEY\"`). If it isn't, ask the user to set it. The SDK doesn't read `.env` files.\n2. Create the environment with only the apps the task needs: `const env = await sm.environments.create({ apps: ['salesforce'] })`. Log `await sm.apps.list()` for each app's ID. Don't guess IDs. `create` waits until the environment is `running`. If the start fails, the server deletes the environment and `create` throws `EnvironmentFailedError` with `err.environment.failure`.\n3. Open a `try` right after `create` returns, and call `await env.delete()` in its `finally`. It deletes the environment and its data.\n4. Get credentials for one app: `const crm = await env.connect('salesforce')`. This acts as the app's default actor, the Salesforce administrator. To act with another user's permissions, pass an `actorId` from the `actors` of the environment's version: the entry of `(await sm.apps.versions('salesforce')).data` whose `id` is `env.apps[0].versionId`. Salesforce actor IDs are its user IDs, such as `005…`, never a role name.\n5. Call the app with `crm.fetch(path)`. A leading `/` means the root of the app's `url`.\n\nThe whole flow, as the package ships it. It is ESM with top-level `await`: save it as `state-quickstart.mts` and run `npx tsx state-quickstart.mts`.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create({ apps: ['salesforce'] });\n\ntry {\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Rules\n\n- Always delete in `finally`.\n- To create without waiting, pass `{ wait: false }`, then `sm.environments.wait(env.id, { status: 'running' })`.\n- The time limit counts `starting` and `running`. `(await sm.me()).limits.timeLimitMinutes` gives its `default` and `maximum`. Set `timeLimitMinutes` in `create` for longer runs.\n- Running environments are capped per organization: `limits.concurrentEnvironments` from `sm.me()`. Delete the ones you no longer need.\n- Never print, log or commit `STATEMACHINES_API_KEY`, `credentials.token` or `credentials.headers`.\n- Salesforce's SOAP API takes the actor token in the envelope, not a header: put `crm.token` in `SessionHeader/sessionId`. `crm.fetch` then sends only the environment token header.\n- `crm.fetch` never sends your API key, never follows redirects and only reaches URLs under the app's `url`.\n- Runtimes: Node.js, at the versions in the package's `engines` field, and Cloudflare Workers. ESM only. TypeScript needs `lib: [\"DOM\"]` or `@types/node`. Never ship an API key to a browser.\n- In Cloudflare Workers, pass the key explicitly: `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`. A start takes longer than one request may last, so create with `{ wait: false }` and read `sm.environments.get(id)` in later requests until it is `running`, or pass a `signal` no shorter than the expected start.\n- Every `list` returns one page, `{ data, nextCursor }`. Pass `nextCursor` back as `cursor` until it is `null`.\n- To reuse seeded data, `await env.snapshots.create({ name })` once, then `sm.environments.create({ snapshotId })` in place of `apps`.\n- Check errors with `instanceof` (`StateMachinesError`, `EnvironmentFailedError`, `SnapshotFailedError`, `UnexpectedStatusError`, `WaitTimeoutError`), not by `name`.\n\n## Recovering a failed create\n\nThe SDK already retries `502`, `503`, `504` and connection errors with one idempotency key. If you need to replay a create whose outcome is unknown, pass your own key: `sm.environments.create(input, { idempotencyKey })`, and call it again with the same input and key. It returns the environment the first call created, or creates it if that call never arrived. A different input fails with `idempotency_key_reused`.\n\n## Troubleshooting\n\n| Symptom | Cause | Fix |\n| --- | --- | --- |\n| `version_unavailable`, 422 | The app has no default version. | Check the app ID against `sm.apps.list()`. |\n| `environment_limit_reached`, 429 | The organization is at its cap of running environments. | List them with `sm.environments.list({ status: ['starting', 'running'] })`, delete one, then create again. |\n| `invalid_status`, 409 | The status does not allow the call, for example taking a snapshot of an environment that is `starting`. | Read `sm.environments.get(id)` and act on its `status`. |\n| `invalid_request`, 400 | A wrong field. | Read `err.fields`, keyed by dotted path. |\n| `EnvironmentFailedError` | The environment failed to start. | Read `err.environment.failure`: `{ app, code, message }`. `invalid_settings` means the app refused its settings. |\n| `UnexpectedStatusError` | The environment was deleted while the SDK waited. | Read `err.status` and `err.resource`. |\n| `WaitTimeoutError` | The status was not reached within `timeoutMs`. | Wait again with `sm.environments.wait(id, { status })`, or delete the environment. |\n| `snapshot_in_progress`, 409 | The environment already has a snapshot in `saving`. | `const [running] = (await sm.snapshots.list({ environmentId: env.id, status: ['saving'] })).data`, then `await sm.snapshots.wait(running.id, { status: 'ready' })`, then create another. |\n| `SnapshotFailedError` | The snapshot failed. `interrupted` means the environment was deleted first. | Create another snapshot while the environment is `running`. |\n| `environment_not_running`, 409, from `crm.fetch` | The environment is failed or deleted. `crm.fetch` returns it as a response and never retries. | Read `(await res.json()).error.status`. Create a new environment if you need another run. |\n| `environment_starting` or `environment_unavailable`, 503, from `crm.fetch` | The app is starting or restarting. | Wait the `Retry-After` seconds and call again. |\n| A vendor client such as jsforce is refused by the gateway | The gateway needs `StateMachines-Environment-Token` on every request. | Prefer `crm.fetch`. If you pass `crm.headers` to another client, send them only to `crm.url` and disable redirects. |\n| `TypeError: Pass apiKey or set STATEMACHINES_API_KEY.` | No key in the environment. | Ask the user to set `STATEMACHINES_API_KEY`. In Workers, pass `apiKey`. |\n\nMore: https://docs.usestatemachines.com, {{origin}}/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk\n",
|
|
23
|
+
"---\nname: state-machines\ndescription: Use when setting up State Machines or running code, integration tests, or API experiments against disposable SaaS replicas such as Salesforce. Applies to @usestatemachines/sdk and STATEMACHINES_API_KEY, including environment creation, actors, snapshots, cleanup and recovery.\n---\n\n## Start with the user's task\n\nDuring skill installation, read the repository instructions and preserve its existing structure. Do not create a new project, install dependencies, write examples or create remote resources. Report the installed skill location and any reload requirement, then ask \"What would you like to run or test?\" and wait. Skill installation does not verify a connection.\n\nOnce the user chooses a task, inspect the project's package manager, runtime, runner and secret loader. Install or reuse a compatible `@usestatemachines/sdk` only when the task needs it. Read the installed README for API signatures and `package.json` for runtime requirements. The SDK is ESM and runs on Node.js and Cloudflare Workers, not in a browser. Follow the user's task and existing project conventions without requiring a separate onboarding example.\n\n## Check access in the right process\n\nThe SDK reads `STATEMACHINES_API_KEY` from the process environment. It does not load `.env` files. Use the project's existing test command or secret loader. An empty variable in your current shell does not prove that the test process lacks it. Verify presence without displaying the value. In Workers, pass the binding explicitly with `new StateMachines({ apiKey: env.STATEMACHINES_API_KEY })`.\n\nCall `sm.me()` to verify access and workspace scope before creating resources. `me.limits` can be null. If the key is missing, prepare the local test or example and tell the user the exact local file, binding, or launch command to configure and rerun, without asking for the key in chat. Do not call the API until access is available. If access is denied or the workspace differs from the task, report the blocker. Do not invite or remove members, or change permissions.\n\nNever print, log or commit API keys, `credentials.token`, the `headers` of `credentials.services`, environment dumps, or secret-file contents. Use synthetic test data.\n\n## Run the user’s chosen task\n\nApply this section after setup, once the user has chosen a task.\n\n- `sm.apps.list()` returns app IDs. Every list returns `{ data, nextCursor }`. Follow cursors until the required entry is found or `nextCursor` is null.\n- Create only the apps the task needs. A string such as `'salesforce'` is both its app ID and its name in the environment. For named apps, later `connect()` calls use the name.\n- `connect(appName)` uses the app's default actor, the Salesforce administrator. For another actor, find the matching app by name in `environment.apps`, read its `versionId`, then find that exact version through `sm.apps.versions(appId)`. Use an actor ID from its `actors`, never a role label, workspace member ID, or the first version in a list.\n- Check the app's services and [known differences](https://docs.usestatemachines.com/apps/known-differences.md) for the behavior under test. A replica does not import a customer's org or run arbitrary customer automation.\n- Configure the existing integration's test transport with the returned app URL and credentials. Verify its requests reach that URL. A successful standalone SDK request does not prove the integration uses the replica. If transport configuration needs a broader change, explain it before expanding the task.\n- Check the expected HTTP status and assert the result. For writes, read the stored data back and assert the relevant fields. For negative tests, assert the expected error. Do not weaken an assertion to make unsupported behavior pass.\n\n## Own the full lifecycle\n\nCreate with `{ wait: false }` to retain the accepted environment ID before waiting. Enter `try` immediately, then wait for `running`, connect and run the check inside it. Delete in `finally`, including after a startup failure, timeout or failed assertion. An aborted wait does not cancel the work that the API accepted. Cleanup must use a fresh, un-aborted signal. Preserve both verification and cleanup errors, and report the environment ID if deletion fails.\n\nDelete only environments created for this task. If the organization is at its limit, clean up a known leftover from this task or ask the user to free capacity. Do not delete unrelated environments or a user-supplied reusable snapshot.\n\nThe SDK retries management connection errors and `502`, `503`, `504` with one idempotency key per create call. To recover across separate attempts or a restart, retain the input and an explicit `idempotencyKey` before creation. Replay using the same input, key, workspace and caller. Do not create a replacement with a new key while the first outcome is unknown. See [operation recovery](https://docs.usestatemachines.com/sdk-api/recovery.md).\n\n## Optional connection check\n\nRun this only when the user asks to verify the connection. It proves the connection and cleanup, not an existing integration's behavior. Save it in the project's examples or test location and run it with the existing TypeScript runner and secret loader. In a new Node.js project, `state-quickstart.mts` and `npx tsx state-quickstart.mts` are a fallback. Load the key into that process first.\n\n```ts\nimport { StateMachines } from '@usestatemachines/sdk';\n\nconst sm = new StateMachines(); // reads STATEMACHINES_API_KEY\nconst env = await sm.environments.create(\n { apps: ['salesforce'] },\n { wait: false },\n);\n\ntry {\n await sm.environments.wait(env.id, { status: 'running' });\n const salesforce = await env.connect('salesforce');\n const res = await salesforce.fetch('/services/data/v67.0/limits');\n console.log(res.status, await res.json());\n} finally {\n await env.delete();\n}\n```\n\n## Load details when needed\n\n- **Repeated fixtures or parallel tests:** Read [isolated tests](https://docs.usestatemachines.com/sdk-api/testing.md). Save seeded data with `env.snapshots.create({ name })`, then create each test's environment with `{ snapshotId }`. A snapshot in `saving` cannot be deleted yet. Retain its ID and wait for `ready` or `failed` before cleanup. Delete a reusable snapshot only when the task calls for it.\n- **Another actor, vendor client or SOAP:** Read [credentials](https://docs.usestatemachines.com/environments/credentials.md). `credentials.fetch()` confines requests to the app URL, adds its authentication headers, and never follows redirects. External clients must send a service's `headers` only to its `url` and disable redirects. For Salesforce SOAP, put the actor token in `SessionHeader/sessionId` in the envelope.\n- **Cloudflare Workers:** Pass the key explicitly. Use `{ wait: false }` and keep the environment ID across requests or in the job's state. A request ending does not cancel startup. Follow the worker's background-job lifecycle for polling and cleanup.\n- **Long runs:** Read `sm.me().limits` when non-null. The environment time limit covers starting and running. Use a supported `timeLimitMinutes` when the task needs it.\n\n## Recover without changing the test's meaning\n\nManagement failures throw SDK errors. App HTTP failures are returned as `Response` objects. Use `instanceof` with the SDK error classes. Native `credentials.fetch()` never retries. Read the State Machines error code in `error.code` and distinguish it from an app's own error.\n\n| Failure | Next action |\n| --- | --- |\n| `invalid_request` | Read `err.fields` and the installed method signature. |\n| `version_unavailable` | Discover the app ID and available versions. Stop if the required version is unavailable. |\n| `environment_limit_reached` | Clean up only this task's known leftovers, or report the capacity blocker. |\n| `EnvironmentFailedError` | Read `err.environment.failure` and clean up the owned environment. |\n| `WaitTimeoutError` or abort | Use the retained environment ID. If older code waited inside `create`, a non-null `WaitTimeoutError.resource` carries its ID. If neither an ID nor a replay key is recoverable, report unresolved cleanup. Do not guess from a list. Wait again only if the task should continue. Otherwise delete the owned environment. |\n| Unknown create outcome | Replay the retained input and idempotency key. Do not start another operation with a new key. |\n| `invalid_status` | Read the current resource status before choosing the next call. |\n| `snapshot_in_progress` | Find the saving snapshot for this environment and wait for it before creating another. |\n| `SnapshotFailedError` | Report the failure. Retry only if the task still needs a snapshot and the source environment is running. |\n| App `environment_not_running` | Inspect the environment. Do not silently switch the integration to another target. |\n| App `invalid_setup` or `invalid_services` | The app refused a value of `setup` or `services` after the start. `error.message` starts with its path. Create another environment with a value that the app accepts, and delete the owned one. |\n| App or gateway `503` | For a retryable read, honor `Retry-After`. For a write with an uncertain outcome, inspect stored state or report uncertainty before retrying. |\n| Cleanup failure | Preserve the task result, report the owned resource ID and retry deletion with valid access and a fresh signal. Do not report cleanup as successful. |\n\n## Finish with evidence\n\nLeave the smallest rerunnable test or example. Report the behavior checked, command, assertion result, SDK and app versions, selected actor, resource IDs without secrets, and cleanup outcome. Say when execution was blocked or only typechecking ran. A passing replica check establishes the asserted behavior for that version and actor, not full production compatibility.\n\nFind other guides through https://docs.usestatemachines.com/llms.txt. Read focused pages before the full documentation bundle. This dashboard also serves an agent index at {{origin}}/llms.txt.\n",
|
|
22
24
|
});
|
package/agents/llms.txt
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
> State Machines runs disposable environments of replica SaaS apps, such as Salesforce, for tests and coding agents. Create, connect to, and delete them with the TypeScript SDK `@usestatemachines/sdk`.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Use the project's package manager to install or reuse `@usestatemachines/sdk`. It is ESM only and runs on Node.js and Cloudflare Workers, not browsers. `engines` in its `package.json` gives the Node.js versions. TypeScript needs `lib: ["DOM"]` or `@types/node`. `new StateMachines()` reads the API key from `STATEMACHINES_API_KEY` and doesn't read `.env` files; in Cloudflare Workers, pass `apiKey` explicitly. Never print the key. The installed `node_modules/@usestatemachines/sdk/README.md` matches your version: read it before relying on memory. Read the bundled `agents/SKILL.md` for the task workflow. Reuse the project's secret loader and check the key in the process that runs the test, not just the current shell. Installing the skill does not require SDK installation, example files or remote resources. Ask what the user wants to run and wait. Install the SDK and verify access when their chosen task needs it. Run the connection check below only if the user asks to verify the connection. Do not choose a business workflow from the repository.
|
|
6
6
|
|
|
7
7
|
## Concepts
|
|
8
8
|
|
|
9
|
-
- Environment: one disposable run of one or more apps. `const env = await sm.environments.create({ apps: ['salesforce'] })` creates it and waits until it is `running`.
|
|
10
|
-
- Apps: a string names the app, and the app's name in the environment is the same string. Use `{
|
|
11
|
-
- Credentials: `const crm = await env.connect('salesforce')` returns `
|
|
12
|
-
- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`.
|
|
9
|
+
- Environment: one disposable run of one or more apps. `const env = await sm.environments.create({ apps: ['salesforce'] })` creates it and waits until it is `running`. Use `{ wait: false }` to retain the ID before startup. Wait for `running` inside `try`, then delete the owned environment in `finally`, including after a wait failure.
|
|
10
|
+
- Apps: a string names the app by its ID, and the app's name in the environment is the same string. Use `{ appId: 'salesforce', name: 'crm', setup }` for your own name, for two copies of one app, or for the app's setup. Later calls take the name.
|
|
11
|
+
- Credentials: `const crm = await env.connect('salesforce')` returns `token`, `services` and `fetch`. Each service has an `id`, a `url` and the `headers` its requests need. The credentials always list each `public` service of the app's version. Pass `{ services: [id] }` to `connect()` to also list a service by its ID. A `preview` service is listed only when named. `crm.service('api')` returns the `api` service, which is the app URL. `crm.fetch(path)` joins `path` to the `api` service URL and adds its headers, which carry `Authorization: Bearer` with `token`. For Salesforce SOAP, also put `crm.token` in the envelope's `SessionHeader/sessionId`. `fetch` never sends your API key, never follows redirects and never retries. `token` and each service's `headers` are secrets.
|
|
12
|
+
- Actor: one of the app's users; requests run with that user's permissions. `connect()` acts as the app's default actor (for Salesforce, the administrator) unless you pass `actorId`. Salesforce actor IDs are its user IDs, such as `005…`. Find the app by name in `env.apps`, then page through `sm.apps.versions(appId)` to find its exact `versionId`. Read actor IDs from that version's `actors`.
|
|
13
13
|
- Snapshot: the saved data of every app of a running environment, taken at one moment. `await env.snapshots.create({ name: 'seeded' })` waits until it is `ready`. `sm.environments.create({ snapshotId })` creates a new environment from it, in place of `apps`; each app keeps its name and version. A delete during the snapshot fails it with `interrupted`.
|
|
14
14
|
- Recorded requests: `sm.requests.list({ environmentId })` pages the calls made to the environment's apps. `sm.requests.get(id)` adds headers and a preview of each body. `sm.requests.body(id, 'request')` or `'response'` returns the full body as bytes. Recording is best effort.
|
|
15
15
|
- YAML: `parseEnvironmentYaml(text)` turns a YAML document with the fields of `create` into its input.
|
|
@@ -19,7 +19,7 @@ Install with `npm install @usestatemachines/sdk`. It is ESM only and runs on Nod
|
|
|
19
19
|
|
|
20
20
|
Enums are open: handle values you don't recognise.
|
|
21
21
|
|
|
22
|
-
- Environment `status`: `starting`, `running`, `failed`, `deleted`. A `deleted` environment has a `reason` when State Machines deleted it: `expired`, `failed` (it never reached `running`) or `cancelled` (staff ended it). The `reason` is `null` when a caller deleted it.
|
|
22
|
+
- Environment `status`: `starting`, `running`, `failed`, `deleted`. A `deleted` environment has a `reason` when State Machines deleted it: `expired`, `failed` (it never reached `running`) or `cancelled` (staff ended it). The `reason` is `null` when a caller deleted it. When the environment failed, `failure` is `{ appName, code, message }`, and `code` is `start_failed`, `pause_removed`, `version_unavailable`, `invalid_setup` or `invalid_services`. For `invalid_setup` and `invalid_services`, the app refused a value in `setup` or in `services`, and `message` starts with its path.
|
|
23
23
|
- Snapshot `status`: `saving`, `ready`, `failed`, `deleted`. A failed snapshot has `failure.code` `interrupted` or `internal_error`.
|
|
24
24
|
- `create` throws `EnvironmentFailedError` when the environment fails, `UnexpectedStatusError` when it becomes `deleted` for another reason, and `WaitTimeoutError` when `timeoutMs` passes.
|
|
25
25
|
- `snapshots.create` throws `SnapshotFailedError` when the snapshot fails and `UnexpectedStatusError` when it was deleted.
|
|
@@ -27,6 +27,8 @@ Enums are open: handle values you don't recognise.
|
|
|
27
27
|
|
|
28
28
|
## Limits
|
|
29
29
|
|
|
30
|
+
When `sm.me().limits` is non-null:
|
|
31
|
+
|
|
30
32
|
- Running environments are capped per organization: `(await sm.me()).limits.concurrentEnvironments` counts `starting` and `running`.
|
|
31
33
|
- `timeLimitMinutes` has a default and a maximum: `(await sm.me()).limits.timeLimitMinutes`. It counts `starting` and `running` only; at the end the environment is deleted with `reason: 'expired'`.
|
|
32
34
|
|
|
@@ -45,32 +47,38 @@ A failed API call throws `StateMachinesError` with `status`, `code`, `message`,
|
|
|
45
47
|
| `workspace_archived` | 409 | The workspace is archived. |
|
|
46
48
|
| `body_too_large` | 413 | The request body is over the API's size limit. Send less. |
|
|
47
49
|
| `version_unavailable` | 422 | The app has no default version. |
|
|
48
|
-
| `environment_limit_reached` | 429 | Delete
|
|
49
|
-
| `unavailable` | 503 | Retried automatically. If `create` still
|
|
50
|
+
| `environment_limit_reached` | 429 | Delete only this task’s known leftovers, or ask the user to free capacity. |
|
|
51
|
+
| `unavailable` | 503 | Retried automatically. If `create` still has an unknown outcome, replay the same input with the key retained before the original call. Do not generate a new key. |
|
|
50
52
|
|
|
51
53
|
## Errors from the app URL
|
|
52
54
|
|
|
53
|
-
`crm.fetch` returns these as responses with the same JSON envelope, and never retries them.
|
|
55
|
+
`crm.fetch` returns these as responses with the same JSON envelope, and never retries them. Assert the expected status and result. For writes, read back the stored result. Never blindly retry a write whose outcome is unknown.
|
|
54
56
|
|
|
55
57
|
| Code | Status | What to do |
|
|
56
58
|
| --- | --- | --- |
|
|
57
59
|
| `environment_not_running` | 409 | The environment is failed or deleted; `error.status` names it. Create another environment. |
|
|
58
|
-
| `environment_starting` | 503 |
|
|
59
|
-
| `environment_unavailable` | 503 | The app is restarting.
|
|
60
|
+
| `environment_starting` | 503 | For reads, wait `Retry-After` and retry. Check stored state before retrying an uncertain write. |
|
|
61
|
+
| `environment_unavailable` | 503 | The app is restarting. For reads, wait `Retry-After`. Check stored state before retrying an uncertain write. |
|
|
60
62
|
| `response_too_large` | 502 | The response is over the size limit. Ask for less, for example with a smaller page. |
|
|
61
|
-
| `
|
|
63
|
+
| `invalid_setup` | 503 | The app refused its `setup` after the environment started, such as in a newer version. `error.message` starts with the path of the value. Create another environment with a `setup` that the app accepts. |
|
|
64
|
+
| `invalid_services` | 503 | The app refused a value in `services` after the environment started. `error.message` starts with the path of the value. Create another environment with `services` that the app accepts. |
|
|
65
|
+
| `unsupported_protocol` | 501 | The app does not serve this path, method or content type, or the request body is compressed. |
|
|
62
66
|
|
|
63
67
|
## Quickstart
|
|
64
68
|
|
|
65
|
-
|
|
69
|
+
Use the project's TypeScript runner and secret loader. For an empty Node.js project, save as `state-quickstart.mts` and run `npx tsx state-quickstart.mts` with the key available. The check prints the response status and deletes the environment. Only after it prints `200`, report verified setup and the rerun command. Continue only with an explicitly supplied task; otherwise ask what to run next and wait with no setup environment left running.
|
|
66
70
|
|
|
67
71
|
```ts
|
|
68
72
|
import { StateMachines } from '@usestatemachines/sdk';
|
|
69
73
|
|
|
70
74
|
const sm = new StateMachines(); // reads STATEMACHINES_API_KEY
|
|
71
|
-
const env = await sm.environments.create(
|
|
75
|
+
const env = await sm.environments.create(
|
|
76
|
+
{ apps: ['salesforce'] },
|
|
77
|
+
{ wait: false },
|
|
78
|
+
);
|
|
72
79
|
|
|
73
80
|
try {
|
|
81
|
+
await sm.environments.wait(env.id, { status: 'running' });
|
|
74
82
|
const salesforce = await env.connect('salesforce');
|
|
75
83
|
const res = await salesforce.fetch('/services/data/v67.0/limits');
|
|
76
84
|
console.log(res.status, await res.json());
|
|
@@ -83,6 +91,6 @@ try {
|
|
|
83
91
|
|
|
84
92
|
- [Documentation](https://docs.usestatemachines.com): guides, concepts and reference ([llms.txt](https://docs.usestatemachines.com/llms.txt))
|
|
85
93
|
- [npm package](https://www.npmjs.com/package/@usestatemachines/sdk): install, README and versions
|
|
86
|
-
- [Agent skill](https://
|
|
94
|
+
- [Agent skill](https://docs.usestatemachines.com/skill.md): workflow, rules and troubleshooting for coding agents
|
|
87
95
|
- [OpenAPI document](https://cdn.jsdelivr.net/npm/@usestatemachines/sdk/openapi.json): the HTTP API the SDK calls
|
|
88
96
|
- [State Machines](https://usestatemachines.com): website
|
package/agents/prompt.md
CHANGED
|
@@ -1,26 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
Install the State Machines skill in this existing repository so I can use disposable app environments with my coding agent.
|
|
2
2
|
|
|
3
|
-
1.
|
|
4
|
-
2.
|
|
5
|
-
3.
|
|
6
|
-
|
|
7
|
-
```ts
|
|
8
|
-
import { StateMachines } from '@usestatemachines/sdk';
|
|
9
|
-
|
|
10
|
-
const sm = new StateMachines(); // reads STATEMACHINES_API_KEY
|
|
11
|
-
const env = await sm.environments.create({ apps: ['salesforce'] });
|
|
12
|
-
|
|
13
|
-
try {
|
|
14
|
-
const salesforce = await env.connect('salesforce');
|
|
15
|
-
const res = await salesforce.fetch('/services/data/v67.0/limits');
|
|
16
|
-
console.log(res.status, await res.json());
|
|
17
|
-
} finally {
|
|
18
|
-
await env.delete();
|
|
19
|
-
}
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
4. Adapt it to my task. Log `await sm.apps.list()` to find each app's ID, and `await sm.apps.versions(appId)` for the actors and APIs of its versions. Don't guess IDs. Create only the apps the task needs. A string such as `'salesforce'` names the app and also becomes its name in the environment. `connect()` acts as the app's default actor, the Salesforce administrator. To act as another user, pass an `actorId` from the version's `actors`. To reuse seeded data, create a snapshot once with `await env.snapshots.create()`, then `sm.environments.create({ snapshotId })`.
|
|
23
|
-
5. Always call `env.delete()` in a `finally`. It deletes the environment and its data. If the start fails, the server deletes the environment itself and `create` throws `EnvironmentFailedError`. Pass your own `idempotencyKey` to `create`. If it throws with no response, call it again with the same input and key.
|
|
24
|
-
6. Never print, log or commit keys or tokens, including `credentials.token` and `credentials.headers`.
|
|
25
|
-
|
|
26
|
-
Read more: https://docs.usestatemachines.com, `node_modules/@usestatemachines/sdk/README.md`, https://app.usestatemachines.com/llms.txt and https://www.npmjs.com/package/@usestatemachines/sdk
|
|
3
|
+
1. Read the repository instructions. Download the skill from https://docs.usestatemachines.com/skill.md and install it as `state-machines/SKILL.md` in this agent's supported project-local skills directory. Reuse an identical installed copy. Preserve customizations and ask before replacing a different copy. If persistent skills are unsupported, read it for this session and explain the limitation. If the download fails, report the blocker.
|
|
4
|
+
2. Read the skill. Do not create a new project, install the SDK, write example code, change an integration or create remote resources during skill installation. Keep the repository's existing conventions.
|
|
5
|
+
3. The API key belongs in the project's existing secret configuration as `STATEMACHINES_API_KEY`. Never ask me to paste it into chat, print it or commit it. If I need help configuring it, identify the existing secret loader and explain where to save it without reading or displaying secret values.
|
|
6
|
+
4. Report where the skill was installed and whether the agent needs to reload it. Skill installation alone does not verify an API connection. Ask: "What would you like to run or test?" Wait for my answer before making further changes.
|
|
@@ -2,6 +2,7 @@ import type { App } from '../models/app.js';
|
|
|
2
2
|
import type { AuditEvent } from '../models/audit-event.js';
|
|
3
3
|
import type { CreateEnvironment } from '../models/create-environment.js';
|
|
4
4
|
import type { Me } from '../models/me.js';
|
|
5
|
+
import type { CreateCredentialsRequestBody } from '../models/operations/create-credentials.js';
|
|
5
6
|
import type { GetRequestStatsRequest } from '../models/operations/get-request-stats.js';
|
|
6
7
|
import type { ListAuditEventsRequest } from '../models/operations/list-audit-events.js';
|
|
7
8
|
import type { ListEnvironmentsRequest } from '../models/operations/list-environments.js';
|
|
@@ -21,7 +22,7 @@ import { type KnownEnvironmentStatus, type KnownSnapshotStatus, type WaitOptions
|
|
|
21
22
|
export interface StateMachinesOptions {
|
|
22
23
|
/** An API key or a member's access token. Defaults to `STATEMACHINES_API_KEY` where a `process` exists. */
|
|
23
24
|
apiKey?: string;
|
|
24
|
-
/** Defaults to `
|
|
25
|
+
/** Defaults to `STATEMACHINES_BASE_URL`, then the production API. Requires HTTPS, except HTTP on localhost or 127.0.0.1. */
|
|
25
26
|
baseUrl?: string;
|
|
26
27
|
/** The workspace for calls that name none. Member tokens need it; an API key has its own. */
|
|
27
28
|
workspaceId?: string;
|
|
@@ -41,10 +42,13 @@ export interface CreateEnvironmentOptions extends SignalOptions {
|
|
|
41
42
|
idempotencyKey?: string;
|
|
42
43
|
}
|
|
43
44
|
export type CreateSnapshotOptions = CreateEnvironmentOptions;
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
/**
|
|
46
|
+
* The body of the credentials call. `actorId` defaults to the app's default
|
|
47
|
+
* actor (for Salesforce, the administrator). `services` names more services
|
|
48
|
+
* to list, by ID. The credentials always list every `public` service, and a
|
|
49
|
+
* `preview` service only when `services` names it.
|
|
50
|
+
*/
|
|
51
|
+
export type ConnectOptions = Pick<CreateCredentialsRequestBody, 'actorId' | 'services'>;
|
|
48
52
|
export interface Page<T> {
|
|
49
53
|
data: T[];
|
|
50
54
|
nextCursor: string | null;
|
|
@@ -62,7 +66,7 @@ export type RequestStatsQuery = GetRequestStatsRequest;
|
|
|
62
66
|
export declare class StateMachines {
|
|
63
67
|
#private;
|
|
64
68
|
constructor(options?: StateMachinesOptions);
|
|
65
|
-
/** The caller: its principal, organization, workspace, permissions and limits. */
|
|
69
|
+
/** The caller: its credential, principal, organization, workspace, permissions and limits. */
|
|
66
70
|
me(): Promise<Me>;
|
|
67
71
|
readonly apps: {
|
|
68
72
|
list: (query?: PageQuery) => Promise<Page<App>>;
|
|
@@ -89,7 +93,7 @@ export declare class StateMachines {
|
|
|
89
93
|
*/
|
|
90
94
|
wait: (environmentId: string, options: WaitOptions<KnownEnvironmentStatus>) => Promise<Environment>;
|
|
91
95
|
/** Credentials for one app of the environment. */
|
|
92
|
-
connect: (environmentId: string,
|
|
96
|
+
connect: (environmentId: string, appName: string, options?: ConnectOptions) => Promise<Credentials>;
|
|
93
97
|
};
|
|
94
98
|
readonly snapshots: {
|
|
95
99
|
/** Creates a snapshot of a running environment and, unless `wait` is false, waits until it is `ready`. */
|
package/esm/extensions/client.js
CHANGED
|
@@ -2,7 +2,7 @@ import { SDK_METADATA } from '../lib/config.js';
|
|
|
2
2
|
import { HTTPClient } from '../lib/http.js';
|
|
3
3
|
import { StateMachines as Generated } from '../sdk/sdk.js';
|
|
4
4
|
import { bindCredentials } from './credentials.js';
|
|
5
|
-
import { CallerAbortedError,
|
|
5
|
+
import { CallerAbortedError, toStateMachinesError } from './errors.js';
|
|
6
6
|
import { linkSignal } from './signal.js';
|
|
7
7
|
import { environmentAt, poll, snapshotAt, } from './wait.js';
|
|
8
8
|
export class StateMachines {
|
|
@@ -10,10 +10,9 @@ export class StateMachines {
|
|
|
10
10
|
#fetch;
|
|
11
11
|
#workspaceId;
|
|
12
12
|
#callSignals = new Map();
|
|
13
|
-
#apis = new Map();
|
|
14
13
|
#lastCall = 0;
|
|
15
14
|
constructor(options = {}) {
|
|
16
|
-
const apiKey = options.apiKey ??
|
|
15
|
+
const apiKey = options.apiKey ?? environmentVariable('STATEMACHINES_API_KEY');
|
|
17
16
|
if (!apiKey) {
|
|
18
17
|
throw new TypeError('Pass apiKey or set STATEMACHINES_API_KEY.');
|
|
19
18
|
}
|
|
@@ -25,6 +24,7 @@ export class StateMachines {
|
|
|
25
24
|
if (!(attemptTimeoutMs > 0 && Number.isFinite(attemptTimeoutMs))) {
|
|
26
25
|
throw new RangeError('attemptTimeoutMs must be a positive, finite number.');
|
|
27
26
|
}
|
|
27
|
+
const baseUrl = baseUrlOrigin(options.baseUrl ?? environmentVariable('STATEMACHINES_BASE_URL'));
|
|
28
28
|
const fetcher = options.fetch;
|
|
29
29
|
// The arrow keeps `this` unbound; runtimes such as workerd reject fetch called on another object.
|
|
30
30
|
const httpClient = new HTTPClient(fetcher ? { fetcher: (input) => fetcher(input) } : {});
|
|
@@ -35,10 +35,10 @@ export class StateMachines {
|
|
|
35
35
|
apiKey,
|
|
36
36
|
userAgent: `statemachines-sdk-ts/${SDK_METADATA.sdkVersion}`,
|
|
37
37
|
httpClient,
|
|
38
|
-
...(
|
|
38
|
+
...(baseUrl === undefined ? {} : { serverURL: baseUrl }),
|
|
39
39
|
});
|
|
40
40
|
}
|
|
41
|
-
/** The caller: its principal, organization, workspace, permissions and limits. */
|
|
41
|
+
/** The caller: its credential, principal, organization, workspace, permissions and limits. */
|
|
42
42
|
me() {
|
|
43
43
|
return this.#call(undefined, (call) => this.#sdk.me(call));
|
|
44
44
|
}
|
|
@@ -80,7 +80,7 @@ export class StateMachines {
|
|
|
80
80
|
*/
|
|
81
81
|
wait: async (environmentId, options) => this.#bind(await poll(environmentId, (signal) => this.#read(signal, (call) => this.#sdk.environments.get({ environmentId }, call)), environmentAt(options.status), options)),
|
|
82
82
|
/** Credentials for one app of the environment. */
|
|
83
|
-
connect: (environmentId,
|
|
83
|
+
connect: (environmentId, appName, options = {}) => this.#connect(environmentId, appName, options),
|
|
84
84
|
};
|
|
85
85
|
snapshots = {
|
|
86
86
|
/** Creates a snapshot of a running environment and, unless `wait` is false, waits until it is `ready`. */
|
|
@@ -129,51 +129,18 @@ export class StateMachines {
|
|
|
129
129
|
? { ...input, workspaceId: this.#workspaceId }
|
|
130
130
|
: input;
|
|
131
131
|
}
|
|
132
|
-
async #connect(environmentId,
|
|
133
|
-
const body =
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
return entry ? this.#versionApis(entry.appId, entry.versionId) : [];
|
|
140
|
-
})(),
|
|
141
|
-
]);
|
|
142
|
-
return bindCredentials(credentials, apis, this.#fetch);
|
|
143
|
-
}
|
|
144
|
-
/** A version's APIs never change, so each is read once per client. */
|
|
145
|
-
#versionApis(appId, versionId) {
|
|
146
|
-
let apis = this.#apis.get(versionId);
|
|
147
|
-
if (!apis) {
|
|
148
|
-
apis = this.#findVersion(appId, versionId);
|
|
149
|
-
apis.catch(() => this.#apis.delete(versionId));
|
|
150
|
-
this.#apis.set(versionId, apis);
|
|
151
|
-
}
|
|
152
|
-
return apis;
|
|
153
|
-
}
|
|
154
|
-
async #findVersion(appId, versionId) {
|
|
155
|
-
let cursor;
|
|
156
|
-
do {
|
|
157
|
-
const page = await this.apps.versions(appId, cursor ? { cursor } : {});
|
|
158
|
-
const version = page.data.find(({ id }) => id === versionId);
|
|
159
|
-
if (version) {
|
|
160
|
-
return version.apis;
|
|
161
|
-
}
|
|
162
|
-
cursor = page.nextCursor ?? undefined;
|
|
163
|
-
} while (cursor);
|
|
164
|
-
throw new StateMachinesError({
|
|
165
|
-
message: `Version ${versionId} of ${appId} was not found.`,
|
|
166
|
-
status: null,
|
|
167
|
-
code: 'not_found',
|
|
168
|
-
requestId: null,
|
|
169
|
-
fields: null,
|
|
170
|
-
retryAfterMs: null,
|
|
171
|
-
});
|
|
132
|
+
async #connect(environmentId, appName, options) {
|
|
133
|
+
const body = {
|
|
134
|
+
...(options.actorId === undefined ? {} : { actorId: options.actorId }),
|
|
135
|
+
...(options.services === undefined ? {} : { services: options.services }),
|
|
136
|
+
};
|
|
137
|
+
const credentials = await this.#call(undefined, (call) => this.#sdk.environments.connect({ environmentId, appName, body }, call));
|
|
138
|
+
return bindCredentials(credentials, this.#fetch);
|
|
172
139
|
}
|
|
173
140
|
#bind(data) {
|
|
174
141
|
const { id } = data;
|
|
175
142
|
const helpers = {
|
|
176
|
-
connect: (
|
|
143
|
+
connect: (appName, options = {}) => this.#connect(id, appName, options),
|
|
177
144
|
delete: (options) => this.environments.delete(id, options),
|
|
178
145
|
refresh: () => this.environments.get(id),
|
|
179
146
|
snapshots: {
|
|
@@ -257,7 +224,23 @@ function waitOptions(options) {
|
|
|
257
224
|
...(options.signal ? { signal: options.signal } : {}),
|
|
258
225
|
};
|
|
259
226
|
}
|
|
260
|
-
function
|
|
227
|
+
function baseUrlOrigin(value) {
|
|
228
|
+
if (value === undefined) {
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
const origin = value.endsWith('/') ? value.slice(0, -1) : value;
|
|
232
|
+
const url = URL.canParse(origin) ? new URL(origin) : undefined;
|
|
233
|
+
if (!url ||
|
|
234
|
+
/[{}]/.test(origin) ||
|
|
235
|
+
origin !== url.origin ||
|
|
236
|
+
!(url.protocol === 'https:' ||
|
|
237
|
+
(url.protocol === 'http:' &&
|
|
238
|
+
(url.hostname === 'localhost' || url.hostname === '127.0.0.1')))) {
|
|
239
|
+
throw new TypeError('baseUrl or STATEMACHINES_BASE_URL must be an HTTPS origin, or HTTP with localhost or 127.0.0.1.');
|
|
240
|
+
}
|
|
241
|
+
return origin;
|
|
242
|
+
}
|
|
243
|
+
function environmentVariable(name) {
|
|
261
244
|
const runtime = globalThis;
|
|
262
|
-
return runtime.process?.env?.
|
|
245
|
+
return runtime.process?.env?.[name];
|
|
263
246
|
}
|