unfazed 0.6.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +299 -78
  3. package/REFERENCE.md +284 -0
  4. package/dist/cli/login.d.ts +129 -0
  5. package/dist/cli/login.js +596 -0
  6. package/dist/cli/login.js.map +1 -0
  7. package/dist/cli/workflow.d.ts +31 -0
  8. package/dist/cli/workflow.js +157 -0
  9. package/dist/cli/workflow.js.map +1 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +173 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/client.d.ts +26 -5
  14. package/dist/client.js +93 -48
  15. package/dist/client.js.map +1 -1
  16. package/dist/credentials.d.ts +123 -0
  17. package/dist/credentials.js +317 -0
  18. package/dist/credentials.js.map +1 -0
  19. package/dist/errors.d.ts +64 -0
  20. package/dist/errors.js +95 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/generated/gql.d.ts +78 -2
  23. package/dist/generated/gql.js +21 -2
  24. package/dist/generated/gql.js.map +1 -1
  25. package/dist/generated/graphql.d.ts +505 -6
  26. package/dist/generated/graphql.js +439 -2
  27. package/dist/generated/graphql.js.map +1 -1
  28. package/dist/index.d.ts +25 -6
  29. package/dist/index.js +23 -5
  30. package/dist/index.js.map +1 -1
  31. package/dist/operations.d.ts +116 -5
  32. package/dist/operations.js +379 -7
  33. package/dist/operations.js.map +1 -1
  34. package/dist/reference.d.ts +18 -0
  35. package/dist/reference.generated.d.ts +2 -0
  36. package/dist/reference.generated.js +5 -0
  37. package/dist/reference.generated.js.map +1 -0
  38. package/dist/reference.js +38 -0
  39. package/dist/reference.js.map +1 -0
  40. package/dist/remote/app.js +2 -1
  41. package/dist/remote/app.js.map +1 -1
  42. package/dist/remote/world.d.ts +2 -2
  43. package/dist/remote/world.js +32 -16
  44. package/dist/remote/world.js.map +1 -1
  45. package/dist/unfazed.d.ts +545 -68
  46. package/dist/unfazed.js +688 -64
  47. package/dist/unfazed.js.map +1 -1
  48. package/dist/wait.d.ts +7 -0
  49. package/dist/wait.js.map +1 -1
  50. package/dist/workflow/nitro.js +5 -3
  51. package/dist/workflow/nitro.js.map +1 -1
  52. package/package.json +22 -6
  53. package/schema/SOURCE.json +4 -4
  54. package/schema/schema.graphqls +1628 -30
@@ -1 +1 @@
1
- {"version":3,"file":"unfazed.js","sourceRoot":"","sources":["../src/unfazed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAA2C,MAAM,aAAa,CAAC;AACrF,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,eAAe,EACf,mBAAmB,EACnB,wBAAwB,EACxB,kBAAkB,IAAI,UAAU,EAChC,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,GAAG,MAAM,iBAAiB,CAAC;AAYvC,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAoB,MAAM,WAAW,CAAC;AA6QlF;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,OAAO;IAClB,6EAA6E;IACpE,MAAM,CAAgB;IAE/B,YAAY,UAA0B,EAAE;QACtC,MAAM,EAAE,MAAM,EAAE,GAAG,aAAa,EAAE,GAAG,OAAO,CAAC;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,IAAI,aAAa,CAAC,aAAa,CAAC,CAAC;IAC3D,CAAC;IAED,+EAA+E;IAE/E,uEAAuE;IACvE,KAAK,CAAC,MAAM,CAAC,OAAwB;QACnC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,CAAC;QACtE,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,+EAA+E;IAE/E,iFAAiF;IACjF,KAAK,CAAC,eAAe,C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AE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC;AAED,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC;AAE/B;;;;;;GAMG;AACH,SAAS,SAAS,CAAC,CAAS;IAC1B,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAC/B,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,UAAU,CACjB,KAAuB,EACvB,SAAiB,EACjB,aAAqB;IAErB,MAAM,OAAO,GAAuB,EAAE,CAAC;IACvC,IAAI,OAAO,GAAqB,EAAE,CAAC;IACnC,IAAI,KAAK,GAAG,CAAC,CAAC;IAEd,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,0EAA0E;QAC1E,qCAAqC;QACrC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5D,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,SAAS,IAAI,KAAK,GAAG,IAAI,GAAG,aAAa,CAAC,EAAE,CAAC;YACxF,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,OAAO,GAAG,EAAE,CAAC;YACb,KAAK,GAAG,CAAC,CAAC;QACZ,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnB,KAAK,IAAI,IAAI,CAAC;IAChB,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9C,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { UnfazedClient, type ClientOptions, type RequestOptions } from \"./client.js\";\nimport {\n DEPLOYMENT_NOT_FOUND,\n UnfazedConflictError,\n UnfazedDeployError,\n UnfazedGraphQLError,\n UnfazedNotFoundError,\n UnfazedRunError,\n WORKSPACE_NOT_FOUND,\n isDuplicateWorkspaceName,\n isNotFoundSentinel as isNotFound,\n looksLikeCASConflict,\n} from \"./errors.js\";\nimport * as ops from \"./operations.js\";\nimport type {\n CreateDeploymentInput,\n DeploymentFieldsFragment,\n ListDeploymentsInput,\n RunFieldsFragment,\n RunStatus,\n ServiceMode,\n ServiceRuntime,\n SdkCreateWorkspaceMutation,\n SdkRunHarnessesQuery,\n} from \"./generated/graphql.js\";\nimport { pollWithBackoff, resolveWaitOptions, type WaitOptions } from \"./wait.js\";\n\n/** A deployment as the workflow layer returns it. */\nexport type Deployment = DeploymentFieldsFragment;\n\n/** An agent run as the workflow layer returns it. */\nexport type Run = RunFieldsFragment;\n/** One harness preset of the box image, from {@link Unfazed.listRunHarnesses}. */\nexport type RunHarness = SdkRunHarnessesQuery[\"runHarnesses\"][number];\n\n/**\n * A workspace as {@link Unfazed.createWorkspace} and\n * {@link Unfazed.ensureWorkspace} return it.\n *\n * Derived from the generated mutation type rather than hand-written, so the\n * two documents selecting these fields cannot drift apart without a compile\n * error — which is exactly what makes `ensureWorkspace` able to return either\n * a listed or a freshly created workspace under one type.\n */\nexport type Workspace = SdkCreateWorkspaceMutation[\"createWorkspace\"][\"workspace\"];\n\n/** Options for {@link Unfazed.deleteWorkspace}. */\nexport type DeleteWorkspaceOptions = {\n /**\n * Also delete every deployment snapshotted from the workspace, stopping\n * their service VMs. **Defaults to `true`** — see the method docs for why.\n */\n withDeployments?: boolean;\n /** Resolve `false` instead of throwing when the workspace is not visible. */\n ignoreNotFound?: boolean;\n} & RequestOptions;\n\n/** Options for {@link Unfazed.deleteDeployment}. */\nexport type DeleteDeploymentOptions = {\n /** Resolve `false` instead of throwing when the deployment is not visible. */\n ignoreNotFound?: boolean;\n} & RequestOptions;\n\n/** A file record returned by any write/list operation. */\nexport interface WorkspaceFile {\n path: string;\n sizeBytes: number;\n size: string;\n sha256: string;\n updatedAt: string;\n}\n\n/** One env var in a workspace- or app-scoped view. Secret values are never returned. */\nexport interface EnvVar {\n name: string;\n value: string | null;\n secret: boolean;\n alias: string | null;\n inherited: boolean;\n masked: boolean;\n updatedAt: string;\n}\n\n/**\n * A file's contents for {@link Unfazed.writeFiles}.\n *\n * A bare string is text — the overwhelmingly common case, and what makes\n * `{ \"server.ts\": code }` read well. Binary goes through `bytes` or `base64`,\n * which route to `writeWorkspaceBase64File` instead.\n */\nexport type FileContent =\n | string\n | { text: string }\n | { base64: string }\n | { bytes: Uint8Array | ArrayBuffer };\n\n/** Files keyed by workspace-relative path. */\nexport type FilesMap = Record<string, FileContent>;\n\nexport interface WriteFilesOptions {\n /**\n * Max files per GraphQL request. Default 20.\n *\n * The batch is one document with N aliased root fields; too many at once\n * makes a single oversized request whose failure is all-or-nothing to\n * diagnose. Twenty keeps a typical app to one or two round trips.\n */\n batchSize?: number;\n /**\n * Max total payload bytes per request. Default 4 MiB. Whichever limit trips\n * first closes the batch, so one large file cannot blow the request up.\n */\n maxBatchBytes?: number;\n signal?: AbortSignal;\n}\n\n/** Common options for the deploy helpers. */\nexport interface DeployOptions {\n workspaceId: string;\n alias?: string;\n /**\n * Block until the deployment reaches a terminal status.\n *\n * `createDeployment` returns BUILDING immediately; the build, VM boot and\n * health probe run in the background. With `wait: true` the call resolves\n * only on READY and throws {@link UnfazedDeployError} on FAILED — which is\n * what makes a one-script deploy possible.\n */\n wait?: boolean;\n /** Backoff/timeout knobs used when `wait` is true. */\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\nexport interface DeployServiceOptions extends DeployOptions {\n /** Omit to auto-detect: a root go.mod+main.go is GO, otherwise BUN. */\n runtime?: ServiceRuntime;\n /** Omit for ON_DEMAND. Only set ALWAYS_ON to keep the VM warm. */\n serviceMode?: ServiceMode;\n healthPath?: string;\n /** Standard 5-field cron spec. Prefer ON_DEMAND + cron over ALWAYS_ON. */\n cronSchedule?: string;\n /** Path the cron tick POSTs to. Defaults to /cron when cronSchedule is set. */\n cronPath?: string;\n}\n\nexport interface DeployStaticOptions extends DeployOptions {\n /** Serve index.html for missing paths (single-page apps). */\n spaMode?: boolean;\n}\n\nexport interface DeployBoxOptions extends DeployOptions {\n /** VM size. Omit for platform defaults (2048 MiB / 2 vCPU / 8 GiB disk). */\n resources?: { memMiB?: number; vcpus?: number; diskGiB?: number };\n}\n\nexport interface RollbackOptions {\n /** The alias to roll back. */\n alias: string;\n /**\n * Release to restore. Omit to pick the most recent READY release that is not\n * the current holder — i.e. \"undo the last deploy\".\n */\n to?: string;\n /**\n * Re-list-and-retry attempts when the compare-and-swap guard is rejected.\n * Default 1. Each retry refreshes the guard from a fresh read; the TARGET\n * release stays pinned, so a retry can never silently roll back to something\n * other than what was chosen.\n *\n * Ignored when {@link expectedCurrentId} is set — see there.\n */\n retries?: number;\n /**\n * The release you believe currently holds the alias. When set, the rollback\n * proceeds only if that is still true.\n *\n * This turns the rollback from \"undo whatever is live now\" into a checked\n * operation: if the live holder is anything else, you get\n * {@link UnfazedConflictError} BEFORE any mutation is sent, so a rollback\n * script can never act on a world that moved since you inspected it.\n *\n * It also disables the CAS retry, necessarily: a rejected guard means the\n * alias moved, and the alias having moved is precisely the precondition you\n * asked to be enforced. Retrying would refresh the guard to the new holder\n * and roll back the very deploy the precondition existed to protect.\n */\n expectedCurrentId?: string;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Unfazed.createRun}. */\nexport interface CreateRunOptions {\n workspaceId: string;\n /** Delivered to the guest as `/work/prompt.md` and `$UNFZ_RUN_PROMPT` (max 64 KiB). */\n prompt?: string;\n /** A named preset from the image's `/etc/unfazed/harnesses.json`. Mutually exclusive in effect with `command` — set one. */\n harness?: string;\n /** Runs anything else with `sh -c`, instead of a named `harness`. */\n command?: string;\n /** Up to 20 single-line shell commands run in `/work` before the harness; the first failure fails the run. */\n setup?: string[];\n /** Up to 10 `owner/repo:path` GitHub references, cloned into `/work/.claude/skills/<name>` first. */\n skills?: string[];\n /**\n * Up to 20 shell commands run in `/work` AFTER the harness exited 0 —\n * tests, a build, `test -f out.txt`. The first failure FAILS the run\n * (`error` \"verification failed\", `verifyExitCode`). Without `verify`,\n * SUCCEEDED only means the harness exited cleanly: an agent that answered\n * \"I could not do this\" still succeeds — read `run.result.text` in that\n * case. Skipped in plan mode.\n */\n verify?: string[];\n /** VM memory. Omit for the platform default. */\n memoryMiB?: number;\n /** Wall-clock cap in seconds. Omit for the platform default; capped at 3600. */\n maxSeconds?: number;\n /** Up to 20 immutable labels for your own correlation (a ticket id, a PR). Echoed back on every read. */\n metadata?: unknown;\n /** Copy the workspace's files into `/work`. Default true. */\n includeFiles?: boolean;\n /**\n * `\"human\"` routes the harness's guarded actions (permission prompts) to\n * the run's owner: the run shows BLOCKED with the question until it is\n * answered ({@link Unfazed.answerRun}, the dashboard). Omit for the\n * harness's own defaults.\n */\n approval?: \"human\";\n /**\n * `\"plan\"` asks the harness to research and write a plan WITHOUT acting\n * (Claude Code runs in `--permission-mode plan`); the plan is the run's\n * transcript. Approve it with {@link Unfazed.followUpRun}. Omit to do the task.\n */\n mode?: \"plan\";\n /**\n * `\"read-only\"` (the default) or `\"read-write\"`. A read-only run gets the\n * app's integrations' read-only credentials (none where the product has no\n * read-only key), only their read MCP tools, and a platform token that\n * cannot deploy or write env; read-write gets the app's own credentials,\n * read+write tools and a deploy-capable token. Ask for read-write only\n * when the run must change things.\n */\n access?: \"read-only\" | \"read-write\";\n /**\n * The app (alias) whose integrations the run gets. Implicit when the\n * workspace has one app; required when it has several.\n */\n alias?: string;\n /** The run this one continues. Usually set for you by {@link Unfazed.followUpRun}. */\n parentRunId?: string;\n /**\n * Block until the run reaches a terminal status.\n *\n * `createRun` itself already returns RUNNING or — on a boot failure —\n * FAILED with `error` set; `wait: true` additionally polls a RUNNING run\n * through to SUCCEEDED/FAILED/CANCELLED. Either way this resolves with the\n * run, never throws for FAILED: see {@link Unfazed.waitForRun}.\n */\n wait?: boolean;\n /** Backoff/timeout knobs used when `wait` is true. */\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Unfazed.followUpRun}. */\nexport interface FollowUpRunOptions {\n /** What to do next. For a plan run: the go-ahead (and any changes to the plan). */\n prompt: string;\n /** `\"plan\"` to plan again instead of executing; omit to execute. */\n mode?: \"plan\";\n /** Override the parent's approval; omit to inherit it. */\n approval?: \"human\" | \"\";\n /** Override the parent's wall clock (seconds). */\n maxSeconds?: number;\n metadata?: unknown;\n /** As for {@link CreateRunOptions.wait}. */\n wait?: boolean;\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\n/** Filter/paging for {@link Unfazed.listRuns}. */\nexport interface ListRunsFilter {\n workspaceId?: string;\n status?: RunStatus;\n limit?: number;\n offset?: number;\n}\n\nexport interface UnfazedOptions extends ClientOptions {\n /** Use an existing core client instead of constructing one. */\n client?: UnfazedClient;\n}\n\n/**\n * Layer 2 — the agent workflow layer.\n *\n * Wraps the chains an agent actually performs (create → write → deploy → wait\n * → read logs → roll back) so a code-mode script does in one call what would\n * otherwise be many round trips through a model's context. Everything here is\n * built on {@link UnfazedClient}, exposed as `.client` for anything not\n * wrapped.\n *\n * ```ts\n * const unfazed = new Unfazed(); // reads UNFZ_API_TOKEN\n * const ws = await unfazed.createWorkspace(\"hello\");\n * await unfazed.writeFiles(ws.id, { \"server.ts\": code });\n * const app = await unfazed.deployService({ workspaceId: ws.id, alias: \"hello\", wait: true });\n * console.log(app.url);\n * ```\n */\nexport class Unfazed {\n /** The underlying typed GraphQL client. Use it for un-wrapped operations. */\n readonly client: UnfazedClient;\n\n constructor(options: UnfazedOptions = {}) {\n const { client, ...clientOptions } = options;\n this.client = client ?? new UnfazedClient(clientOptions);\n }\n\n /* ---------------------------------------------------------------- identity */\n\n /** Who this token authenticates as, plus usage and resource limits. */\n async whoami(options?: RequestOptions) {\n const data = await this.client.query(ops.WhoamiDocument, {}, options);\n return data.whoami;\n }\n\n /* -------------------------------------------------------------- workspaces */\n\n /** Creates a source workspace — the container for files, env and deployments. */\n async createWorkspace(name: string, options?: RequestOptions) {\n const data = await this.client.mutate(ops.CreateWorkspaceDocument, { name }, options);\n return data.createWorkspace.workspace;\n }\n\n /** Workspaces visible to this token. */\n async listWorkspaces(options?: RequestOptions) {\n const data = await this.client.query(ops.ListWorkspacesDocument, {}, options);\n return data.workspaces;\n }\n\n /**\n * Deletes a workspace and everything anchored to it — deployments, env, and\n * a BOX's persistent data disk. Not recoverable.\n *\n * **The cascade is opt-out, not opt-in.** The server refuses to delete a\n * workspace that has ANY deployment history — including FAILED records, and\n * including deployments whose alias was long since taken over by something\n * else — unless the mutation carries `withDeployments`. Since almost every\n * workspace an agent creates gets deployed at least once, defaulting to\n * `false` would make this method fail on nearly every real workspace, so it\n * defaults to **`true`**: the behaviour this docstring has always promised.\n *\n * Pass `withDeployments: false` for the strict variant, which refuses rather\n * than cascading and is the safer choice when you are deleting a workspace\n * you did not create:\n *\n * ```ts\n * await unfazed.deleteWorkspace(ws.id); // cascade\n * await unfazed.deleteWorkspace(ws.id, { withDeployments: false }); // refuse if deployed\n * await unfazed.deleteWorkspace(id, { ignoreNotFound: true }); // false, not a throw\n * ```\n *\n * With `ignoreNotFound` a workspace that is absent (or belongs to someone\n * else — the server returns one indistinguishable sentinel for both, on\n * purpose) resolves to `false` instead of throwing, which makes teardown in\n * a `finally` block idempotent.\n */\n async deleteWorkspace(\n workspaceId: string,\n options: DeleteWorkspaceOptions = {},\n ): Promise<boolean> {\n const withDeployments = options.withDeployments ?? true;\n try {\n const data = await this.client.mutate(\n ops.DeleteWorkspaceDocument,\n { workspaceID: workspaceId, withDeployments },\n options,\n );\n return data.deleteWorkspace.ok;\n } catch (e) {\n if (options.ignoreNotFound && isNotFound(e, WORKSPACE_NOT_FOUND)) return false;\n throw e;\n }\n }\n\n /**\n * Returns the workspace named `name`, creating it only if it does not exist.\n *\n * Workspace names are unique per owner, case-insensitively — a second\n * `createWorkspace(\"Hello\")` after a `createWorkspace(\"hello\")` is an error,\n * not a second workspace. That makes the bare create a poor fit for any\n * script that might run twice; this is the re-runnable form.\n *\n * ```ts\n * const ws = await unfazed.ensureWorkspace(\"greeter\"); // safe to re-run\n * ```\n *\n * Costs one list, plus one create only on a miss. The create is still\n * guarded: if a concurrent caller wins the race, the duplicate-name error is\n * caught and the now-existing workspace is returned instead of thrown.\n */\n async ensureWorkspace(name: string, options?: RequestOptions) {\n const existing = await this.#findWorkspaceByName(name, options);\n if (existing) return existing;\n\n try {\n return await this.createWorkspace(name, options);\n } catch (e) {\n // Lost a create/create race, or the server's case folding is stricter\n // than ours. Either way the workspace exists now — re-read rather than\n // failing a script whose intent was \"make sure this exists\".\n if (!isDuplicateWorkspaceName(e)) throw e;\n const raced = await this.#findWorkspaceByName(name, options);\n if (raced) return raced;\n // The name is taken by something we cannot see. Surface the real error.\n throw e;\n }\n }\n\n /* ------------------------------------------------------------------- files */\n\n /**\n * Writes many files in as few requests as possible.\n *\n * The API is one-file-per-mutation, so writing a 12-file app naively costs 12\n * round trips. This batches them into a single GraphQL document with one\n * ALIASED root field per file (`f0: writeWorkspaceTextFile(...)`,\n * `f1: ...`), which the server resolves in one request.\n *\n * ```ts\n * await unfazed.writeFiles(ws.id, {\n * \"server.ts\": serverCode,\n * \"unfazed.json\": JSON.stringify({ entry: \"server.ts\" }),\n * \"public/logo.png\": { bytes: pngBytes },\n * });\n * ```\n *\n * Batches are NOT atomic: GraphQL resolves each aliased field independently,\n * so a partial failure leaves earlier writes committed. The thrown\n * {@link UnfazedGraphQLError} carries `data` with whichever aliases\n * succeeded, and `error.path` identifies the ones that did not.\n */\n async writeFiles(\n workspaceId: string,\n files: FilesMap,\n options: WriteFilesOptions = {},\n ): Promise<WorkspaceFile[]> {\n const entries = Object.entries(files).map(([path, content]) => normalizeFile(path, content));\n if (entries.length === 0) return [];\n\n const batchSize = options.batchSize ?? 20;\n const maxBatchBytes = options.maxBatchBytes ?? 4 * 1024 * 1024;\n\n const written: WorkspaceFile[] = [];\n for (const batch of chunkFiles(entries, batchSize, maxBatchBytes)) {\n written.push(...(await this.#writeBatch(workspaceId, batch, options.signal)));\n }\n return written;\n }\n\n /** Writes one text file. Prefer {@link writeFiles} for more than one. */\n async writeFile(\n workspaceId: string,\n path: string,\n text: string,\n options?: RequestOptions,\n ): Promise<WorkspaceFile> {\n const data = await this.client.mutate(\n ops.WriteTextFileDocument,\n { workspaceID: workspaceId, path, text },\n options,\n );\n return data.writeWorkspaceTextFile.file;\n }\n\n /** Writes one binary file. Accepts raw bytes or a base64 string. */\n async writeBinaryFile(\n workspaceId: string,\n path: string,\n content: Uint8Array | ArrayBuffer | { base64: string },\n options?: RequestOptions,\n ): Promise<WorkspaceFile> {\n const contentBase64 = \"base64\" in content ? content.base64 : toBase64(content);\n const data = await this.client.mutate(\n ops.WriteBase64FileDocument,\n { workspaceID: workspaceId, path, contentBase64 },\n options,\n );\n return data.writeWorkspaceBase64File.file;\n }\n\n /** Lists workspace files (paginated). */\n async listFiles(\n workspaceId: string,\n input: { limit?: number; offset?: number; order?: string } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ListFilesDocument,\n { input: { workspaceID: workspaceId, ...input } },\n options,\n );\n return data.workspaceFilesPage;\n }\n\n /** Reads a text file, optionally a byte range of it. Null when absent. */\n async readFile(\n workspaceId: string,\n path: string,\n input: { offset?: number; limit?: number } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ReadFileDocument,\n { input: { workspaceID: workspaceId, path, ...input } },\n options,\n );\n return data.readWorkspaceFile;\n }\n\n /**\n * Deletes a workspace file.\n *\n * Returns `false` when there was nothing to delete — an absent path is not\n * an error. See the `ok: false` convention on {@link deleteEnv}.\n */\n async deleteFile(\n workspaceId: string,\n path: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.DeleteFileDocument,\n { workspaceID: workspaceId, path },\n options,\n );\n return data.deleteWorkspaceFile.ok;\n }\n\n /* ----------------------------------------------------------------- deploys\n *\n * Every deploy method here MINTS A NEW RELEASE on every call. There is no\n * content dedupe: deploying byte-identical files twice produces two distinct\n * releases with two ids, both real, both counting against retention (which\n * keeps only the most recent few per alias and prunes the rest). Deploying\n * in a retry loop is therefore not free — it churns the release history and\n * can push a release you still wanted to roll back to out of retention.\n * Check {@link getDeployment} or {@link listReleases} before redeploying if\n * you only meant to converge.\n */\n\n /**\n * Deploys the workspace as a SERVICE (an HTTP server).\n *\n * With `wait: true` this resolves only once the build, VM boot and health\n * probe have all passed.\n *\n * Passing the same `alias` again redeploys that alias — a new release that\n * takes over the alias when it goes READY. Omitting `alias` lets the server\n * generate one, which means a different app on every call.\n */\n deployService(options: DeployServiceOptions): Promise<Deployment> {\n const { workspaceId, alias, runtime, serviceMode, healthPath, cronSchedule, cronPath } =\n options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"SERVICE\",\n ...(alias === undefined ? {} : { alias }),\n ...(runtime === undefined ? {} : { runtime }),\n ...(serviceMode === undefined ? {} : { serviceMode }),\n ...(healthPath === undefined ? {} : { healthPath }),\n ...(cronSchedule === undefined ? {} : { cronSchedule }),\n ...(cronPath === undefined ? {} : { cronPath }),\n },\n options,\n );\n }\n\n /** Deploys the workspace as a STATIC site. */\n deployStatic(options: DeployStaticOptions): Promise<Deployment> {\n const { workspaceId, alias, spaMode } = options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"STATIC\",\n ...(alias === undefined ? {} : { alias }),\n ...(spaMode === undefined ? {} : { spaMode }),\n },\n options,\n );\n }\n\n /**\n * Deploys a BOX: a persistent always-on Linux VM with a data disk that\n * survives stops and redeploys. A dev machine, not an HTTP service. The\n * result's `sshCommand` is how you get in.\n *\n * ⚠️ **Omitting `alias` creates a NEW BOX every single call.** There is no\n * \"the workspace's box\" to update: with no alias the server generates a\n * fresh random one, so a script run twice leaves you with two box records,\n * not one redeployed box.\n *\n * The data disk, meanwhile, is keyed by WORKSPACE — one disk, shared by\n * every box in the workspace, and it is the box's real identity. Since only\n * one VM can hold that disk read-write, the second box cannot even start\n * while the first is running (`box data disk for workspace ... is attached\n * to VM ...; stop it first`). The result is a pile of dead box records\n * fighting over one disk.\n *\n * **Always pass an explicit `alias` in anything re-runnable.** Redeploying\n * the same alias is the in-place update you actually want.\n *\n * ```ts\n * await unfazed.deployBox({ workspaceId: ws.id, alias: \"dev\" }); // re-runnable\n * ```\n */\n deployBox(options: DeployBoxOptions): Promise<Deployment> {\n const { workspaceId, alias, resources } = options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"BOX\",\n ...(alias === undefined ? {} : { alias }),\n ...(resources === undefined ? {} : { boxResources: resources }),\n },\n options,\n );\n }\n\n /** Escape hatch: deploy with a raw CreateDeploymentInput. */\n deploy(\n input: CreateDeploymentInput,\n options: Omit<DeployOptions, \"workspaceId\"> = {},\n ): Promise<Deployment> {\n return this.#deploy(input, options);\n }\n\n async #deploy(\n input: CreateDeploymentInput,\n options: Omit<DeployOptions, \"workspaceId\">,\n ): Promise<Deployment> {\n const requestOptions: RequestOptions = options.signal ? { signal: options.signal } : {};\n const data = await this.client.mutate(ops.CreateDeploymentDocument, { input }, requestOptions);\n const deployment = data.createDeployment.deployment;\n if (!options.wait) return deployment;\n return this.waitForDeployment(deployment.id, {\n ...options.waitOptions,\n ...(options.signal ? { signal: options.signal } : {}),\n });\n }\n\n /**\n * Polls a deployment until it is READY, throwing on FAILED or timeout.\n *\n * BUILDING is the only non-terminal status; READY and FAILED are terminal.\n * The poll query selects six fields rather than the full deployment, because\n * this runs every few seconds for potentially minutes — then the READY\n * deployment is re-read in full so callers get the same shape `deployService`\n * returns without `wait`.\n */\n async waitForDeployment(deploymentId: string, waitOptions: WaitOptions = {}): Promise<Deployment> {\n const resolved = resolveWaitOptions(waitOptions);\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n let last: { id: string; status: string; error: string | null } | null = null;\n\n await pollWithBackoff<true>(\n async () => {\n const data = await this.client.query(\n ops.PollDeploymentDocument,\n { id: deploymentId },\n requestOptions,\n );\n const d = data.deployment;\n if (!d) {\n throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);\n }\n last = d;\n if (d.status === \"READY\") return { done: true, value: true };\n if (d.status === \"FAILED\") {\n throw new UnfazedDeployError(\n \"FAILED\",\n deploymentId,\n d,\n `unfazed: deployment ${deploymentId} FAILED${d.error ? `: ${d.error}` : \"\"}`,\n );\n }\n return { done: false };\n },\n resolved,\n () =>\n new UnfazedDeployError(\n \"TIMEOUT\",\n deploymentId,\n last,\n `unfazed: deployment ${deploymentId} still ${\n (last as { status?: string } | null)?.status ?? \"BUILDING\"\n } after ${resolved.timeoutMs}ms`,\n ),\n );\n\n const full = await this.getDeployment(deploymentId, requestOptions);\n if (!full) throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);\n return full;\n }\n\n /** Reads one deployment by id. Null when absent. */\n async getDeployment(\n deploymentId: string,\n options?: RequestOptions,\n ): Promise<Deployment | null> {\n const data = await this.client.query(ops.GetDeploymentDocument, { id: deploymentId }, options);\n return data.deployment;\n }\n\n /** Reads the deployment currently serving an alias. Null when absent. */\n async getDeploymentByAlias(\n alias: string,\n options?: RequestOptions,\n ): Promise<Deployment | null> {\n const data = await this.client.query(ops.GetDeploymentByAliasDocument, { alias }, options);\n return data.deploymentByAlias;\n }\n\n /** Lists deployments (paginated, filterable by kind/alias/workspace). */\n async listDeployments(input: ListDeploymentsInput = {}, options?: RequestOptions) {\n const data = await this.client.query(ops.ListDeploymentsDocument, { input }, options);\n return data.deploymentsPage;\n }\n\n /* ------------------------------------------------------- runtime & logging */\n\n /** Live VM status: health, in-flight requests, restarts, RAM ceiling. */\n async getStatus(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.query(\n ops.ServiceStatusDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.serviceStatus;\n }\n\n /**\n * Tail of the service's stdout/stderr.\n *\n * The point of doing this from a script rather than through tool calls: you\n * can filter locally. `(await unfazed.getLogs(id)).stderr.split(\"\\n\")\n * .filter(l => l.includes(\"ERROR\"))` costs a model zero context, where the\n * same tail through an MCP tool spends all of it.\n */\n async getLogs(\n deploymentId: string,\n input: { tailBytes?: number } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ServiceLogsDocument,\n { deploymentID: deploymentId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.serviceLogs;\n }\n\n /** Deployment lifecycle events — build, boot, probe, cron, restarts. */\n async getEvents(deploymentId: string, limit?: number, options?: RequestOptions) {\n const data = await this.client.query(\n ops.DeploymentEventsDocument,\n { deploymentID: deploymentId, limit: limit ?? null },\n options,\n );\n return data.deploymentEvents;\n }\n\n /** Restarts a service's VM. */\n async restartService(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.mutate(\n ops.RestartServiceDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.restartService;\n }\n\n /** Stops a service's VM. An on-demand service cold-starts again on request. */\n async stopService(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.mutate(\n ops.StopServiceDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.stopService;\n }\n\n /**\n * Deletes a deployment: stops its VM, releases its alias, drops its release.\n *\n * With `ignoreNotFound` a deployment that is absent — or belongs to another\n * tenant, which the server reports identically so ids cannot be probed —\n * resolves to `false` instead of throwing, making cleanup loops idempotent.\n */\n async deleteDeployment(\n deploymentId: string,\n options: DeleteDeploymentOptions = {},\n ): Promise<boolean> {\n try {\n const data = await this.client.mutate(\n ops.DeleteDeploymentDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.deleteDeployment.ok;\n } catch (e) {\n if (options.ignoreNotFound && isNotFound(e, DEPLOYMENT_NOT_FOUND)) return false;\n throw e;\n }\n }\n\n /* ------------------------------------------------------------ env & secrets\n *\n * Workspace values are SERVICE defaults for every app in the source; app\n * values override them for one alias. Both are SNAPSHOTTED into a release at\n * deploy time — changing either does not affect a running app until you\n * redeploy that alias. Old releases are immutable, and STATIC gets no env.\n */\n\n /**\n * Sets a workspace-default env var. Redeploy the alias to apply it.\n *\n * A name is either plain or secret, never both: this DELETES a workspace\n * secret of the same name. {@link setSecret} displaces a plain var the same\n * way. Last write wins, and the kind flips silently — so re-running a setup\n * script that calls `setSecret(\"API_KEY\", ...)` after one that called\n * `setEnv(\"API_KEY\", ...)` quietly converts it, and vice versa.\n */\n async setEnv(\n workspaceId: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetWorkspaceEnvDocument,\n { workspaceID: workspaceId, name, value },\n options,\n );\n return data.setWorkspaceEnv.env;\n }\n\n /**\n * Sets a workspace-default secret. The value is never readable again.\n *\n * Mutually exclusive with {@link setEnv}: this DELETES a plain workspace var\n * of the same name. See {@link setEnv} for the displacement rule.\n */\n async setSecret(\n workspaceId: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetWorkspaceSecretDocument,\n { workspaceID: workspaceId, name, value },\n options,\n );\n return data.setWorkspaceSecret.env;\n }\n\n /**\n * Sets many workspace env vars in one request, via aliased mutations —\n * the same batching trick as {@link writeFiles}.\n *\n * Pass `{ secret: true }` to route them all to `setWorkspaceSecret`.\n *\n * It inherits {@link writeFiles}' failure semantics too: the batch is NOT\n * atomic. GraphQL resolves each aliased field independently, so a rejected\n * name (over the limit, malformed, whatever) leaves the vars before it\n * already committed. The thrown {@link UnfazedGraphQLError} carries `data`\n * with the aliases that succeeded and `errors[].path` naming those that did\n * not — do not assume \"it threw\" means \"nothing was written\".\n *\n * Each name still displaces its opposite kind, exactly as {@link setEnv} and\n * {@link setSecret} do one at a time.\n */\n async setEnvMany(\n workspaceId: string,\n vars: Record<string, string>,\n options: { secret?: boolean; signal?: AbortSignal } = {},\n ): Promise<EnvVar[]> {\n const entries = Object.entries(vars);\n if (entries.length === 0) return [];\n\n const field = options.secret ? \"setWorkspaceSecret\" : \"setWorkspaceEnv\";\n const varDefs = [\"$workspaceID: ID!\"];\n const fields: string[] = [];\n const variables: Record<string, string> = { workspaceID: workspaceId };\n\n entries.forEach(([name, value], i) => {\n varDefs.push(`$n${i}: String!`, `$v${i}: String!`);\n variables[`n${i}`] = name;\n variables[`v${i}`] = value;\n fields.push(\n ` e${i}: ${field}(input: { workspaceID: $workspaceID, name: $n${i}, value: $v${i} }) { env { ${ENV_SELECTION} } }`,\n );\n });\n\n const document = `mutation SdkSetEnvBatch(${varDefs.join(\", \")}) {\\n${fields.join(\"\\n\")}\\n}`;\n const data = await this.client.mutate<Record<string, { env: EnvVar }>, typeof variables>(\n document,\n variables,\n options.signal ? { signal: options.signal } : {},\n );\n return entries.map((_, i) => data[`e${i}`]!.env);\n }\n\n /**\n * Deletes a workspace-default env var (plain or secret).\n *\n * **The `ok: false` convention.** A `false` here does NOT mean failure — it\n * means \"nothing to do, the world is already in the state you asked for\".\n * The var did not exist. Every `ok`-returning mutation in this SDK follows\n * the rule ({@link deleteFile}, {@link inheritAppEnv}, {@link removeAppEnv}),\n * so the idempotent-cleanup pattern is simply to ignore the boolean; a real\n * failure throws.\n */\n async deleteEnv(workspaceId: string, name: string, options?: RequestOptions): Promise<boolean> {\n const data = await this.client.mutate(\n ops.DeleteWorkspaceEnvDocument,\n { workspaceID: workspaceId, name },\n options,\n );\n return data.deleteWorkspaceEnv.ok;\n }\n\n /** Workspace-default env vars. Secret values are redacted. */\n async listEnv(workspaceId: string, options?: RequestOptions): Promise<EnvVar[]> {\n const data = await this.client.query(\n ops.ListWorkspaceEnvDocument,\n { workspaceID: workspaceId },\n options,\n );\n return data.workspaceEnv;\n }\n\n /**\n * Sets an env var for ONE alias, overriding the workspace default.\n *\n * Displaces both of the other states this name could be in for the app: it\n * deletes an app SECRET of the same name, and it CLEARS a REMOVE mask left\n * by {@link removeAppEnv}. So setting a value is also the way to un-block a\n * masked name, and a name is only ever one of plain / secret / masked.\n */\n async setAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetAppEnvDocument,\n { workspaceID: workspaceId, alias, name, value },\n options,\n );\n return data.setAppEnv.env;\n }\n\n /**\n * Sets a secret for ONE alias, overriding the workspace default.\n *\n * Like {@link setAppEnv}, this deletes a plain app var of the same name and\n * clears a REMOVE mask for it.\n */\n async setAppSecret(\n workspaceId: string,\n alias: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetAppSecretDocument,\n { workspaceID: workspaceId, alias, name, value },\n options,\n );\n return data.setAppSecret.env;\n }\n\n /**\n * REMOVE: blocks this name for the app entirely — the app override, the\n * workspace default, and integration enrichment. Not the same as deleting an\n * override; use {@link inheritAppEnv} for that.\n *\n * This WRITES A MASK, and the mask is a real, persistent row. Two things\n * follow that surprise people:\n *\n * - It is written even when nothing was inherited. Masking a name that no\n * workspace default and no integration ever provided is not a no-op; it\n * leaves a tombstone that keeps blocking the name if a default appears\n * later. Clear it with {@link inheritAppEnv}.\n * - It COSTS A SLOT. A workspace gets 128 env entries total — that budget\n * is shared across the workspace defaults AND every app scope combined,\n * not 128 per scope — and masks count toward it just like values do.\n * Masking names in a loop can exhaust the workspace's env budget.\n *\n * Returns `false` when the exact mask was already present (a second call for\n * the same name), per the {@link deleteEnv} `ok: false` convention. It\n * returns `true` when it had something to change — including converting an\n * existing override into a mask.\n */\n async removeAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.RemoveAppEnvDocument,\n { workspaceID: workspaceId, alias, name },\n options,\n );\n return data.removeAppEnv.ok;\n }\n\n /**\n * INHERIT: clears the app override/mask so workspace and integration values\n * apply again. This is the undo for both {@link setAppEnv} and\n * {@link removeAppEnv}.\n *\n * Returns `false` when there was no override and no mask to clear — nothing\n * to do, not a failure. See {@link deleteEnv}.\n */\n async inheritAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.InheritAppEnvDocument,\n { workspaceID: workspaceId, alias, name },\n options,\n );\n return data.inheritAppEnv.ok;\n }\n\n /** The effective env view for one alias: overrides, inherited and masked. */\n async listAppEnv(\n workspaceId: string,\n alias: string,\n options?: RequestOptions,\n ): Promise<EnvVar[]> {\n const data = await this.client.query(\n ops.ListAppEnvDocument,\n { workspaceID: workspaceId, alias },\n options,\n );\n return data.appEnv;\n }\n\n /* -------------------------------------------------- releases & rollback */\n\n /**\n * An alias's terminal release history, newest first.\n *\n * Exactly one entry has `aliasHeld: true` — the live release. FAILED entries\n * appear on purpose (they are rejected promotions, so a kept-live previous\n * release is never mistaken for a silent fallback) and cannot be rolled back\n * to. Retention keeps only the most recent few per alias, default 5.\n */\n async listReleases(alias: string, options?: RequestOptions): Promise<Deployment[]> {\n const data = await this.client.query(ops.ListReleasesDocument, { alias }, options);\n return data.deploymentReleases;\n }\n\n /**\n * Rolls an alias back to a prior release, handling the whole compare-and-swap\n * protocol in one call.\n *\n * The server requires the caller to prove it observed the current state: you\n * must pass the live release's id AND its opaque `aliasRevision`, and the\n * swap fails if either changed since you listed — including same-id ABA. So\n * this method does the full dance: list releases, find the `aliasHeld` entry,\n * pick the target, and submit both guard values.\n *\n * On a rejected guard it re-lists and retries (default once). The TARGET is\n * pinned across retries while the guard is refreshed, so a concurrent deploy\n * can never redirect the rollback to a different release than the one chosen.\n *\n * ```ts\n * await unfazed.rollback({ alias: \"my-app\" }); // undo last deploy\n * await unfazed.rollback({ alias: \"my-app\", to: relId }); // to a specific release\n * await unfazed.rollback({ alias: \"my-app\", to: relId, expectedCurrentId: liveId });\n * ```\n *\n * ⚠️ **A bare `rollback({ alias })` is a TOGGLE, not an idempotent step.**\n * It means \"restore the most recent READY release that is not the live one\",\n * which is a different release each time the alias moves. Run the same\n * script twice and the second run rolls back the rollback — A → B → A → B,\n * forever, with each hop a real alias swap. Nothing errors, because every\n * individual call did exactly what it was asked.\n *\n * In anything re-runnable — a retry loop, a CI job, an agent that might redo\n * a step — pin the outcome instead:\n *\n * - `to:` names the release you want live, so re-running is a no-op-ish\n * convergence rather than a flip (a second run then reports the target\n * already holds the alias instead of moving it);\n * - `expectedCurrentId:` states what you expect to be live now, so a second\n * run fails loudly instead of silently undoing the first.\n */\n async rollback(options: RollbackOptions): Promise<Deployment> {\n const { alias, signal, expectedCurrentId } = options;\n // A caller-supplied precondition and the CAS retry are mutually exclusive:\n // retrying re-guards against whatever holds the alias NOW, which is the\n // one thing `expectedCurrentId` exists to refuse.\n const retries = expectedCurrentId === undefined ? (options.retries ?? 1) : 0;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n\n let targetId = options.to;\n\n for (let attempt = 0; ; attempt++) {\n const releases = await this.listReleases(alias, requestOptions);\n if (releases.length === 0) {\n throw new UnfazedNotFoundError(`unfazed: alias \"${alias}\" has no release history`);\n }\n\n const current = releases.find((r) => r.aliasHeld);\n if (!current) {\n throw new UnfazedNotFoundError(\n `unfazed: alias \"${alias}\" has no current release holding the alias`,\n );\n }\n\n // The caller's precondition, checked before anything is sent. Failing\n // here rather than at the server keeps a violated expectation from\n // costing an alias swap, and reports the holder we actually observed.\n if (expectedCurrentId !== undefined && current.id !== expectedCurrentId) {\n throw new UnfazedConflictError(\n `unfazed: alias \"${alias}\" is held by ${current.id}, not the expected ` +\n `${expectedCurrentId} — it moved since you read it; re-read and decide again`,\n [],\n );\n }\n\n // Pin the target on the first pass so a retry refreshes only the guard.\n if (targetId === undefined) {\n const previous = releases.find((r) => r.id !== current.id && r.status === \"READY\");\n if (!previous) {\n throw new UnfazedNotFoundError(\n `unfazed: alias \"${alias}\" has no prior READY release to roll back to ` +\n `(history: ${releases.map((r) => `${r.id}:${r.status}`).join(\", \")})`,\n );\n }\n targetId = previous.id;\n }\n\n const target = releases.find((r) => r.id === targetId);\n if (!target) {\n throw new UnfazedNotFoundError(\n `unfazed: release ${targetId} is not in alias \"${alias}\"'s history ` +\n `(it may have been pruned; retention keeps only the most recent few)`,\n );\n }\n if (target.id === current.id) {\n throw new UnfazedConflictError(\n `unfazed: release ${targetId} already holds alias \"${alias}\"`,\n [],\n );\n }\n if (target.status !== \"READY\") {\n throw new UnfazedConflictError(\n `unfazed: release ${targetId} is ${target.status}, only READY releases can be restored`,\n [],\n );\n }\n\n try {\n const data = await this.client.mutate(\n ops.RollbackDocument,\n {\n deploymentID: target.id,\n expectedCurrentDeploymentID: current.id,\n expectedCurrentAliasRevision: current.aliasRevision,\n },\n requestOptions,\n );\n return data.rollbackDeployment;\n } catch (e) {\n const retryable =\n e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors) && attempt < retries;\n if (!retryable) {\n if (e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors)) {\n throw new UnfazedConflictError(\n `unfazed: rollback of \"${alias}\" lost the compare-and-swap after ${\n attempt + 1\n } attempt(s) — the alias is being deployed concurrently. ${e.message}`,\n e.errors,\n );\n }\n throw e;\n }\n // Loop: re-list, rebuild the guard, keep the same target.\n }\n }\n }\n\n /* --------------------------------------------------------------- agent runs\n *\n * A run is the past-tense counterpart to a deployment: boot a fresh VM off\n * the box image, hand it a prompt, let a harness work for up to an hour,\n * keep the transcript, meter what it cost, reap the VM. Deployments answer\n * \"what is running\"; runs answer \"what happened\". Inside a run, `new\n * Unfazed()` is already authenticated — the platform injects\n * UNFZ_API_TOKEN / UNFZ_API_URL, at most the parent's scopes, revoked when\n * the run settles.\n */\n\n /**\n * Starts an agent run.\n *\n * Resolves once the VM has started (status RUNNING) — or, on a boot\n * failure, once the run has already settled FAILED with `error` set. A\n * boot failure is a normal return value here, not a thrown error, with or\n * without `wait`.\n *\n * ```ts\n * const run = await unfazed.createRun({\n * workspaceId: ws.id,\n * harness: \"claude-code\",\n * prompt: \"Fix the failing test in test/foo.test.ts and open a PR.\",\n * wait: true,\n * });\n * console.log(run.status, run.usage.mibSeconds);\n * ```\n *\n * With `wait: true` this additionally polls a RUNNING run through to a\n * terminal status — see {@link waitForRun} for exactly what \"terminal\"\n * means and how a timeout is reported.\n */\n async createRun(options: CreateRunOptions): Promise<Run> {\n const {\n workspaceId,\n prompt,\n harness,\n command,\n setup,\n skills,\n verify,\n memoryMiB,\n maxSeconds,\n metadata,\n includeFiles,\n approval,\n mode,\n access,\n alias,\n parentRunId,\n wait,\n waitOptions,\n signal,\n } = options;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n const data = await this.client.mutate(\n ops.CreateRunDocument,\n {\n input: {\n workspaceID: workspaceId,\n ...(prompt === undefined ? {} : { prompt }),\n ...(harness === undefined ? {} : { harness }),\n ...(command === undefined ? {} : { command }),\n ...(setup === undefined ? {} : { setup }),\n ...(skills === undefined ? {} : { skills }),\n ...(verify === undefined ? {} : { verify }),\n ...(memoryMiB === undefined ? {} : { memoryMiB }),\n ...(maxSeconds === undefined ? {} : { maxSeconds }),\n ...(metadata === undefined ? {} : { metadata }),\n ...(includeFiles === undefined ? {} : { includeFiles }),\n ...(approval === undefined ? {} : { approval }),\n ...(mode === undefined ? {} : { mode }),\n ...(access === undefined ? {} : { access }),\n ...(alias === undefined ? {} : { alias }),\n ...(parentRunId === undefined ? {} : { parentRunID: parentRunId }),\n },\n },\n requestOptions,\n );\n const run = data.createRun;\n // Unlike createDeployment (always BUILDING), createRun can come back\n // already terminal — a boot failure settles FAILED synchronously. Only\n // poll when there is actually something to wait for.\n if (!wait || isTerminalRunStatus(run.status)) return run;\n return this.waitForRun(run.id, {\n ...waitOptions,\n ...(signal ? { signal } : {}),\n });\n }\n\n /**\n * Polls a run until it leaves QUEUED/RUNNING, throwing only on timeout.\n *\n * Terminal is defined negatively — anything that is not QUEUED or RUNNING —\n * matching the platform's own status machine, so an unknown future status\n * still ends the wait instead of looping forever. **SUCCEEDED, FAILED and\n * CANCELLED are all returned normally**: a run that executed and exited\n * non-zero is a completed answer (read `run.error` / `run.exitCode`), not\n * an exception the way a FAILED deployment is. Only running out of time\n * throws, as {@link UnfazedRunError} with `reason: \"TIMEOUT\"`.\n */\n async waitForRun(runId: string, waitOptions: WaitOptions = {}): Promise<Run> {\n const resolved = resolveWaitOptions(waitOptions);\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n let last: { id: string; status: RunStatus; error: string | null; exitCode: number | null } | null =\n null;\n\n await pollWithBackoff<true>(\n async () => {\n const data = await this.client.query(ops.PollRunDocument, { id: runId }, requestOptions);\n const r = data.run;\n last = r;\n if (isTerminalRunStatus(r.status)) return { done: true, value: true };\n return { done: false };\n },\n resolved,\n () =>\n new UnfazedRunError(\n \"TIMEOUT\",\n runId,\n last,\n `unfazed: run ${runId} still ${(last as { status?: string } | null)?.status ?? \"QUEUED\"} after ${resolved.timeoutMs}ms`,\n ),\n );\n\n return this.getRun(runId, requestOptions);\n }\n\n /** Reads one run by id. Throws if it does not exist or is not visible to you. */\n async getRun(runId: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.query(ops.GetRunDocument, { id: runId }, options);\n return data.run;\n }\n\n /**\n * The harness presets a run may name (`createRun({ harness })`): name,\n * title, what it is, and the workspace secrets it requires (set them with\n * {@link Unfazed.setSecret} before the run). Empty when the node's box\n * image carries no catalogue.\n */\n async listRunHarnesses(options?: RequestOptions): Promise<RunHarness[]> {\n const data = await this.client.query(ops.ListRunHarnessesDocument, {}, options);\n return data.runHarnesses;\n }\n\n /** Your agent runs, newest first, optionally filtered by workspace/status. */\n async listRuns(filter: ListRunsFilter = {}, options?: RequestOptions) {\n const { workspaceId, status, limit, offset } = filter;\n const data = await this.client.query(\n ops.ListRunsDocument,\n {\n input: {\n ...(workspaceId === undefined ? {} : { workspaceID: workspaceId }),\n ...(status === undefined ? {} : { status }),\n ...(limit === undefined ? {} : { limit }),\n ...(offset === undefined ? {} : { offset }),\n },\n },\n options,\n );\n return data.runs;\n }\n\n /**\n * Stops a run: a QUEUED run is cancelled at once, a RUNNING run's VM is\n * killed and the run settles CANCELLED shortly after (`waitForRun` to\n * observe it). Idempotent on an already-CANCELLED run; a run that has\n * already SUCCEEDED or FAILED cannot be cancelled and the server rejects\n * the call (thrown as {@link UnfazedGraphQLError}) — check `status` first\n * when that is a routine case for you.\n */\n async cancelRun(runId: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.mutate(ops.CancelRunDocument, { id: runId }, options);\n return data.cancelRun;\n }\n\n /**\n * Continues a FINISHED run with a new instruction: a new run in the same\n * workspace that inherits the parent's harness (or command), setup, skills\n * and approval, with the parent's task, outcome and the end of its\n * transcript prepended to `prompt` as context. This is how a plan is\n * approved — `createRun({ mode: \"plan\" })` writes the plan, `followUpRun`\n * with the go-ahead executes it — and how work continues after a run\n * exited. The new run carries `parentRunID` and `depth`; chains are capped\n * server-side. A live run cannot be followed up (the server refuses):\n * answer it or wait for it.\n *\n * ```ts\n * const plan = await unfazed.createRun({ workspaceId, harness: \"claude-code\", prompt: \"plan the migration\", mode: \"plan\", wait: true });\n * const done = await unfazed.followUpRun(plan.id, { prompt: \"go ahead\", wait: true });\n * ```\n */\n async followUpRun(runId: string, options: FollowUpRunOptions): Promise<Run> {\n const { prompt, mode, approval, maxSeconds, metadata, wait, waitOptions, signal } = options;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n const data = await this.client.mutate(\n ops.FollowUpRunDocument,\n {\n input: {\n runID: runId,\n prompt,\n ...(mode === undefined ? {} : { mode }),\n ...(approval === undefined ? {} : { approval }),\n ...(maxSeconds === undefined ? {} : { maxSeconds }),\n ...(metadata === undefined ? {} : { metadata }),\n },\n },\n requestOptions,\n );\n const run = data.followUpRun;\n if (!wait || isTerminalRunStatus(run.status)) return run;\n return this.waitForRun(run.id, { ...waitOptions, ...(signal ? { signal } : {}) });\n }\n\n /**\n * Answers a BLOCKED run's pending question (`run.question`); the run\n * resumes with the text. For a question with `options`, answer with one\n * of them. Only a BLOCKED run accepts an answer — anything else is\n * refused by the server.\n *\n * A run blocks when the agent inside calls `request_human_input`, or when\n * it was created with `approval: \"human\"` and its harness asks permission\n * for a guarded action. `waitForRun` keeps waiting through BLOCKED (it is\n * not terminal); poll `getRun` and look at `question` to notice one.\n */\n async answerRun(runId: string, answer: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.mutate(ops.AnswerRunDocument, { id: runId, answer }, options);\n return data.answerRun;\n }\n\n /** A run's own history, oldest first (started, cancel requested, settled). */\n async runEvents(runId: string, input: { limit?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunEventsDocument,\n { runID: runId, limit: input.limit ?? null },\n options,\n );\n return data.runEvents;\n }\n\n /**\n * The live tail of a RUNNING run's console. Once the run has settled this\n * comes back empty with `running: false` — read {@link runTranscript}\n * instead, which is the stored, durable copy.\n */\n async runConsole(runId: string, input: { tailBytes?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunConsoleDocument,\n { id: runId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.runConsole;\n }\n\n /**\n * The bounded end of a finished run's stored transcript (secrets\n * redacted). `available` is false until the run settles and the transcript\n * is copied out of the VM's console file — check `run.transcriptAvailable`\n * or poll this after {@link waitForRun} resolves.\n */\n async runTranscript(runId: string, input: { tailBytes?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunTranscriptDocument,\n { id: runId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.runTranscript;\n }\n\n /* -------------------------------------------------------------- internals */\n\n /**\n * Finds a visible workspace by name, the way the server compares names.\n *\n * The server rejects duplicates with Go's `strings.EqualFold`, so matching\n * must be case-insensitive here too or `ensureWorkspace` would try to create\n * a \"new\" workspace the server considers a duplicate. An exact-case hit wins\n * over a folded one, which only matters if a name ever slipped past the\n * uniqueness check.\n */\n async #findWorkspaceByName(\n name: string,\n options?: RequestOptions,\n ): Promise<Workspace | undefined> {\n const workspaces = await this.listWorkspaces(options);\n const folded = name.toLowerCase();\n return (\n workspaces.find((w) => w.name === name) ??\n workspaces.find((w) => w.name.toLowerCase() === folded)\n );\n }\n\n async #writeBatch(\n workspaceId: string,\n batch: NormalizedFile[],\n signal?: AbortSignal,\n ): Promise<WorkspaceFile[]> {\n const varDefs = [\"$workspaceID: ID!\"];\n const fields: string[] = [];\n const variables: Record<string, string> = { workspaceID: workspaceId };\n\n batch.forEach((file, i) => {\n variables[`p${i}`] = file.path;\n variables[`c${i}`] = file.content;\n varDefs.push(`$p${i}: String!`, `$c${i}: String!`);\n fields.push(\n file.kind === \"text\"\n ? ` f${i}: writeWorkspaceTextFile(input: { workspaceID: $workspaceID, path: $p${i}, text: $c${i} }) { file { ${FILE_SELECTION} } }`\n : ` f${i}: writeWorkspaceBase64File(input: { workspaceID: $workspaceID, path: $p${i}, contentBase64: $c${i} }) { file { ${FILE_SELECTION} } }`,\n );\n });\n\n // Built at runtime rather than codegen'd: the field COUNT varies per call,\n // so no static document can express it. The field shapes are still fixed\n // and typed below, and each individual mutation is codegen-validated by its\n // single-file twin in operations.ts.\n const document = `mutation SdkWriteFilesBatch(${varDefs.join(\", \")}) {\\n${fields.join(\"\\n\")}\\n}`;\n\n const data = await this.client.mutate<\n Record<string, { file: WorkspaceFile }>,\n typeof variables\n >(document, variables, signal ? { signal } : {});\n\n return batch.map((_, i) => data[`f${i}`]!.file);\n }\n}\n\nconst FILE_SELECTION = \"path sizeBytes size sha256 updatedAt\";\nconst ENV_SELECTION = \"name value secret alias inherited masked updatedAt\";\n\n/**\n * Terminal = anything but QUEUED or RUNNING, defined negatively exactly like\n * the platform's own `IsTerminalRunStatus` — so a future status this SDK does\n * not know about yet still ends a wait instead of polling forever.\n */\nfunction isTerminalRunStatus(status: string): boolean {\n return status !== \"QUEUED\" && status !== \"RUNNING\";\n}\n\ninterface NormalizedFile {\n path: string;\n kind: \"text\" | \"base64\";\n content: string;\n}\n\nfunction normalizeFile(path: string, content: FileContent): NormalizedFile {\n if (typeof content === \"string\") return { path, kind: \"text\", content };\n if (\"text\" in content) return { path, kind: \"text\", content: content.text };\n if (\"base64\" in content) return { path, kind: \"base64\", content: content.base64 };\n return { path, kind: \"base64\", content: toBase64(content.bytes) };\n}\n\nfunction toBase64(input: Uint8Array | ArrayBuffer): string {\n const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);\n // Node/Bun have Buffer; browsers and workers do not.\n const maybeBuffer = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(e: string): string } } })\n .Buffer;\n if (maybeBuffer) return maybeBuffer.from(bytes).toString(\"base64\");\n\n let binary = \"\";\n const CHUNK = 0x8000; // avoid blowing the argument limit on large files\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary);\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * UTF-8 byte length, which is what the wire actually costs.\n *\n * `String.length` counts UTF-16 code units and undercounts by up to 3x on\n * non-ASCII text — a CJK or emoji-heavy payload would sail past a budget it\n * had already blown.\n */\nfunction utf8Bytes(s: string): number {\n return utf8.encode(s).length;\n}\n\n/**\n * Splits files into request-sized batches.\n *\n * Closes a batch on whichever limit trips first — count or bytes — but always\n * emits at least one file per batch, so a single file larger than\n * `maxBatchBytes` still gets sent (and fails loudly at the server's limit)\n * rather than silently vanishing into an empty batch.\n */\nfunction chunkFiles(\n files: NormalizedFile[],\n batchSize: number,\n maxBatchBytes: number,\n): NormalizedFile[][] {\n const batches: NormalizedFile[][] = [];\n let current: NormalizedFile[] = [];\n let bytes = 0;\n\n for (const file of files) {\n // Measured once per file, so the encode cost is linear in the payload the\n // request was going to carry anyway.\n const size = utf8Bytes(file.content) + utf8Bytes(file.path);\n if (current.length > 0 && (current.length >= batchSize || bytes + size > maxBatchBytes)) {\n batches.push(current);\n current = [];\n bytes = 0;\n }\n current.push(file);\n bytes += size;\n }\n if (current.length > 0) batches.push(current);\n return batches;\n}\n"]}
1
+ {"version":3,"file":"unfazed.js","sourceRoot":"","sources":["../src/unfazed.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAA2C,MAAM,aAAa,CAAC;AACrF,OA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qCAAqC;QACrC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5D,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,SAAS,IAAI,KAAK,GAAG,IAAI,GAAG,aAAa,CAAC,EAAE,CAAC;YACxF,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACtB,OAAO,GAAG,EAAE,CAAC;YACb,KAAK,GAAG,CAAC,CAAC;QACZ,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnB,KAAK,IAAI,IAAI,CAAC;IAChB,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9C,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { UnfazedClient, type ClientOptions, type RequestOptions } from \"./client.js\";\nimport {\n type GraphQLResponseError,\n DEPLOYMENT_NOT_FOUND,\n UnfazedConflictError,\n UnfazedDeployError,\n UnfazedError,\n UnfazedGraphQLError,\n UnfazedNotFoundError,\n UnfazedRunError,\n UnfazedTimeoutError,\n UnfazedUnconfirmedAppsError,\n UnfazedWriteError,\n WORKSPACE_NOT_FOUND,\n isAppNotFound,\n isDuplicateWorkspaceName,\n isNotFoundSentinel as isNotFound,\n isUnconfirmedAppsRefusal,\n isTooManyWaits,\n isUnsupportedField,\n looksLikeCASConflict,\n} from \"./errors.js\";\nimport * as ops from \"./operations.js\";\nimport type {\n AppErrorGroupFieldsFragment,\n CreateDeploymentInput,\n DeploymentEventType,\n DeploymentFieldsFragment,\n FileCommitFieldsFragment,\n ListDeploymentsInput,\n RunFieldsFragment,\n RunStatus,\n ServiceMode,\n ServiceRuntime,\n SdkAppCommitQuery,\n SdkAppCommitsQuery,\n SdkAppErrorGroupQuery,\n SdkAppErrorsQuery,\n SdkCreateWorkspaceMutation,\n SdkDeleteAppMutation,\n SdkDeploymentEventsQuery,\n SdkEventTypesQuery,\n SdkPollEventsQuery,\n SdkRestoreVersionMutation,\n SdkRunHarnessesQuery,\n SdkWorkspaceLiveAppsQuery,\n} from \"./generated/graphql.js\";\nimport { pollWithBackoff, resolveWaitOptions, type WaitOptions } from \"./wait.js\";\n\n/** A deployment as the workflow layer returns it. */\nexport type Deployment = DeploymentFieldsFragment;\n\n/** An agent run as the workflow layer returns it. */\nexport type Run = RunFieldsFragment;\n/** One harness preset of the box image, from {@link Unfazed.listRunHarnesses}. */\nexport type RunHarness = SdkRunHarnessesQuery[\"runHarnesses\"][number];\n\n/**\n * A workspace as {@link Unfazed.createWorkspace} and\n * {@link Unfazed.ensureWorkspace} return it.\n *\n * Derived from the generated mutation type rather than hand-written, so the\n * two documents selecting these fields cannot drift apart without a compile\n * error — which is exactly what makes `ensureWorkspace` able to return either\n * a listed or a freshly created workspace under one type.\n */\nexport type Workspace = SdkCreateWorkspaceMutation[\"createWorkspace\"][\"workspace\"];\n\n/**\n * An app a workspace serves right now, from {@link Unfazed.liveApps}: its\n * alias, the deployment serving it, and the custom domains routing to it\n * (listed for the app's owner only).\n */\nexport type LiveApp = NonNullable<SdkWorkspaceLiveAppsQuery[\"workspace\"]>[\"liveApps\"][number];\n\n/** What {@link Unfazed.deleteApp} removed, as the server reports it. */\nexport type DeleteAppResult = SdkDeleteAppMutation[\"deleteApp\"];\n\n/** Options for {@link Unfazed.deleteWorkspace}. */\nexport type DeleteWorkspaceOptions = (\n | {\n /**\n * Omitted or `false`: delete the workspace only when it has no\n * deployment records left. The server refuses otherwise, and deletes\n * nothing.\n */\n withDeployments?: false;\n /** Only with `withDeployments: true`. */\n confirmAliases?: undefined;\n }\n | {\n /**\n * Also delete every deployment snapshotted from the workspace, stopping\n * its VMs. This takes EVERY app the workspace serves offline, so\n * `confirmAliases` must name them.\n */\n withDeployments: true;\n /**\n * Exactly the aliases of the apps the workspace serves\n * ({@link Unfazed.liveApps}), in any order: every app this delete takes\n * offline. `[]` when it serves none (only failed or retired records are\n * left). A missing or extra alias makes the server refuse and delete\n * nothing ({@link UnfazedUnconfirmedAppsError}). The SDK never fills\n * this in for you.\n */\n confirmAliases: readonly string[];\n }\n) & {\n /** Resolve `false` instead of throwing when the workspace is not visible. */\n ignoreNotFound?: boolean;\n} & RequestOptions;\n\n/** The app {@link Unfazed.deleteApp} deletes. */\nexport interface AppRef {\n workspaceId: string;\n /** The app's alias in that workspace. */\n alias: string;\n}\n\n/** Options for {@link Unfazed.deleteApp}. */\nexport type DeleteAppOptions = {\n /**\n * Resolve `null` instead of throwing when the app is not in the workspace\n * (already deleted) or the workspace is not visible.\n */\n ignoreNotFound?: boolean;\n} & RequestOptions;\n\n/** Options for {@link Unfazed.deleteDeployment}. */\nexport type DeleteDeploymentOptions = {\n /** Resolve `false` instead of throwing when the deployment is not visible. */\n ignoreNotFound?: boolean;\n} & RequestOptions;\n\n/** A file record returned by any write/list operation. */\nexport interface WorkspaceFile {\n path: string;\n sizeBytes: number;\n size: string;\n sha256: string;\n updatedAt: string;\n}\n\n/** One env var in a workspace- or app-scoped view. Secret values are never returned. */\nexport interface EnvVar {\n name: string;\n value: string | null;\n secret: boolean;\n alias: string | null;\n inherited: boolean;\n masked: boolean;\n updatedAt: string;\n}\n\n/**\n * The commit a write made on an app with platform git, exactly as MCP\n * `write_workspace_files` reports it.\n *\n * The three states of a write: SAVED (the call returned: the app's files\n * have it, and the next deploy uses it); COMMITTED (`committed && !waiting`:\n * it is in the app's history, `listCommits`); DEPLOYED (a deploy of those\n * files went READY: `deployService({ wait: true })`, or — only when\n * `deploys` is true — the import of the branch head the write triggers).\n *\n * - `waiting: true` — saved, and the commit waits for the git server; it\n * lands in order. `sha` is null until then. Nothing to retry; await it with\n * {@link Unfazed.waitForCommit} (or `writeFiles(…, { waitForCommit: true })`).\n * - `committed: false` — git already held exactly these files.\n * - `conflicts` — a push changed the same paths meanwhile: the head (`sha`,\n * a merge) keeps the pushed version; yours is `writeSHA`.\n * - `paused` — platform git is paused for recovery: saved, committed later.\n */\nexport type FileCommit = FileCommitFieldsFragment;\n\n/** One file's outcome in {@link Unfazed.writeFiles}, in the order given. */\nexport interface FileWriteOutcome {\n path: string;\n ok: boolean;\n /** Why this path was not written; null when it was. */\n error: string | null;\n /** The written file; null when it was not. */\n file: WorkspaceFile | null;\n}\n\n/** What {@link Unfazed.writeFiles} wrote (MCP `write_workspace_files`' answer). */\nexport interface WriteFilesResult {\n workspaceId: string;\n /** Every file's outcome, in the order of the map. */\n files: FileWriteOutcome[];\n written: number;\n failed: number;\n /** Bytes written (decoded). */\n totalBytes: number;\n /**\n * The commit the call made on an app with platform git; null on any other\n * app, and on a platform too old to report it. A map over one request's\n * limits (100 files, 32 MiB) is several requests and several commits: this\n * is the last, `commits` has them all.\n */\n commit: FileCommit | null;\n /** One commit per request, in order. Usually exactly one. */\n commits: FileCommit[];\n /**\n * With `waitForCommit`, when a commit was waiting: the branch head once\n * every waiting write had landed (this write is in its history).\n */\n landed?: CommitsLanded;\n}\n\n/** A single-file write's answer: the file, and the commit it made. */\nexport type WrittenFile = WorkspaceFile & { commit: FileCommit | null };\n\n/** What {@link Unfazed.waitForCommit} saw once no write was waiting. */\nexport interface CommitsLanded {\n branch: string;\n /** The branch head: every write made before the wait is in its history. */\n head: string | null;\n /** How long the wait took, in ms. */\n waitedMs: number;\n}\n\n/** One page of an app's platform git history ({@link Unfazed.listCommits}). */\nexport type CommitPage = SdkAppCommitsQuery[\"appCommits\"];\n/** One commit with its diff ({@link Unfazed.getCommit}). */\nexport type CommitDetail = SdkAppCommitQuery[\"appCommit\"];\n\n/** Options for {@link Unfazed.restoreVersion} (MCP `restore_version`). */\nexport interface RestoreVersionOptions {\n workspaceId: string;\n /** Full 40-character sha of the commit whose files the app gets back. */\n sha: string;\n /** Refuse, changing nothing, unless the branch head is still this commit. */\n expectedHead?: string;\n /** Message of the new commit; default `Restore <short sha> (<its message>)`. */\n commitMessage?: string;\n /**\n * When the restore deploys (`deploys: true`, an app that deploys every\n * push), wait for that deploy: resolve once the import of the new commit\n * finished with every deployment it made, throw {@link UnfazedDeployError}\n * when it failed.\n */\n wait?: boolean;\n /** Timeout/backoff for `wait`; default 10 minutes. */\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\n/** What {@link Unfazed.restoreVersion} did. */\nexport type RestoreVersionResult = SdkRestoreVersionMutation[\"restoreAppVersion\"] & {\n /**\n * With `wait` and `deploys`: the deployments the restore's import made (one\n * per alias it deploys), READY. Absent without `wait` or when nothing\n * deploys.\n */\n deployments?: Deployment[];\n};\n\n/** A service app's error group (MCP `list_errors`). Title, type, culprit and level are untrusted app text. */\nexport type ErrorGroup = AppErrorGroupFieldsFragment;\n/** One page of error groups ({@link Unfazed.listErrors}). */\nexport type ErrorGroupPage = SdkAppErrorsQuery[\"appErrors\"];\n/** One error group with its latest occurrence ({@link Unfazed.getErrorGroup}). */\nexport type ErrorGroupDetail = SdkAppErrorGroupQuery[\"appErrorGroup\"];\n/** Names one error group of one app. */\nexport interface ErrorGroupRef extends AppRef {\n /** The group's id (from listErrors, or `group_id` of an error.new / error.regressed event). */\n groupId: string;\n}\n/** Filter/paging for {@link Unfazed.listErrors}. */\nexport interface ListErrorsOptions extends AppRef {\n status?: \"open\" | \"resolved\" | \"muted\";\n /** 1 to 100; default 20. */\n limit?: number;\n /** The previous page's `nextCursor`. */\n cursor?: string;\n}\n\n/** An event type {@link Unfazed.pollEvents} reads (MCP `list_event_types`). */\nexport type EventType = SdkEventTypesQuery[\"platformEventTypes\"][number];\n/** A page of events (MCP `poll_events` / `wait_for_events`). */\nexport type EventPage = SdkPollEventsQuery[\"pollEvents\"];\n/** One event: `name` (deployment.finished, service.crashed, error.new, git.conflict, …), and minimal `data`. */\nexport type PlatformEvent = EventPage[\"events\"][number];\n/** Which events to read (MCP `poll_events`' input). */\nexport interface EventsInput {\n /** Event types; omit for every type you may receive. */\n names?: string[];\n /** Filters per type, keyed by its name: `{ \"deployment.finished\": { alias: \"shop\", status: \"FAILED\" } }`. */\n arguments?: Record<string, Record<string, unknown>>;\n /** Where to continue; omit to start from now (nothing is replayed). */\n cursor?: string;\n /** At most this many events. */\n max?: number;\n}\n\n/**\n * A deployment event. `type` is the event's own name — `\"service.vm_started\"`,\n * `\"deployment.build_finished\"` — exactly as MCP `list_deployment_events` and\n * `wait_for_deployment` report it.\n */\nexport interface DeploymentEvent {\n id: string;\n deploymentID: string;\n /** The event's name as the platform writes it, e.g. `\"deployment.phases\"`. */\n type: string;\n /**\n * The GraphQL enum (`SERVICE_VM_STARTED`, …), `UNKNOWN` for every name the\n * enum does not list (`deployment.build_finished`, `deployment.phases`, …).\n * Match on `type` instead.\n */\n typeEnum: DeploymentEventType;\n /** @deprecated Same as `type` (before 0.8.0 `type` was the enum). */\n rawType: string;\n severity: SdkDeploymentEventsQuery[\"deploymentEvents\"][number][\"severity\"];\n message: string;\n vmID: string | null;\n /** The event's fields; timing events carry their phases as `*_ms` strings ({@link parseDeploymentTimings}). */\n metadata: Record<string, string> | null;\n createdAt: string;\n}\n\n/**\n * A deploy's phases as the platform measured them: from `deployment.phases`\n * (recorded when the deploy goes READY) and `deployment.build_finished`.\n * Milliseconds.\n */\nexport interface PlatformTimings {\n /** Deployment created → READY, on the platform's clock. Null until `deployment.phases` is recorded. */\n totalMs: number | null;\n /** The build, as the build VM's host measured it. */\n buildMs: number | null;\n /** Promotion: health probe and alias switch (and a worker's pickup and boot). */\n promoteMs: number | null;\n /**\n * Every other measured phase by name: the build VM's (`vm_install`,\n * `vm_build`, `vm_bundle`, `vm_collect`, `image`, `vm`, `return`,\n * `extract`) and the promotion's (`admission`, `worker_pickup`, `boot`, …).\n */\n phases: Record<string, number>;\n /** `local` or `worker`. */\n buildMode: string | null;\n artifactTransport: string | null;\n buildMemoryMiB: number | null;\n}\n\n/** Wall time this client spent on a deploy with `wait: true`. Milliseconds. */\nexport interface ClientTimings {\n /** Sending createDeployment until its answer. */\n createMs: number;\n /** Its answer until the client saw the final status. */\n waitMs: number;\n /** `createMs + waitMs`: what the caller waited. Compare with `platform.totalMs`. */\n totalMs: number;\n /** Requests the wait made: one per server-side wait (up to 45 s each), or one per poll. */\n waitRequests: number;\n /** `\"server\"`: the platform's server-side wait; `\"poll\"`: polling (platforms without it). */\n waitMode: \"server\" | \"poll\";\n}\n\n/** Both sides of a deploy's time ({@link DeployResult.timings}). */\nexport interface DeployTimings {\n client: ClientTimings;\n /** Null when the platform recorded none (yet), or with `timings: false`. */\n platform: PlatformTimings | null;\n}\n\n/** A deploy's answer: the deployment, and with `wait: true` its timings. */\nexport type DeployResult = Deployment & {\n /** With `wait: true`: the platform's phases and this client's wall time. */\n timings?: DeployTimings;\n};\n\n/**\n * A file's contents for {@link Unfazed.writeFiles}.\n *\n * A bare string is text — the overwhelmingly common case, and what makes\n * `{ \"server.ts\": code }` read well. Binary goes through `bytes` or `base64`,\n * which route to `writeWorkspaceBase64File` instead.\n */\nexport type FileContent =\n | string\n | { text: string }\n | { base64: string }\n | { bytes: Uint8Array | ArrayBuffer };\n\n/** Files keyed by workspace-relative path. */\nexport type FilesMap = Record<string, FileContent>;\n\nexport interface WriteFilesOptions {\n /**\n * On an app with platform git: the message of the call's commit. Default\n * names the files. Ignored on other apps.\n */\n commitMessage?: string;\n /**\n * When the commit waits for the git server (`commit.waiting`), resolve only\n * once it landed ({@link Unfazed.waitForCommit}); `true` or the wait's\n * options. The result's `landed` names the branch head then.\n */\n waitForCommit?: boolean | WaitOptions;\n /**\n * Resolve with the result even when some files failed, instead of throwing\n * {@link UnfazedWriteError}. Read `failed` and `files[].error` then.\n */\n allowPartial?: boolean;\n /**\n * Max files per request. Default 100, the platform's per-call limit. A\n * request is ONE commit on an app with platform git, so a map that needs\n * several requests is several commits.\n */\n batchSize?: number;\n /**\n * Max payload bytes per request (text, or base64 as sent). Default 32 MiB,\n * the platform's per-call total. Whichever limit trips first closes a\n * request; a single file over it is still sent, and refused on its own.\n */\n maxBatchBytes?: number;\n signal?: AbortSignal;\n}\n\n/** Common options for the deploy helpers. */\nexport interface DeployOptions {\n workspaceId: string;\n alias?: string;\n /**\n * Block until the deployment reaches a terminal status.\n *\n * `createDeployment` returns BUILDING immediately; the build, VM boot and\n * health probe run in the background. With `wait: true` the call resolves\n * only on READY and throws {@link UnfazedDeployError} on FAILED — which is\n * what makes a one-script deploy possible.\n */\n wait?: boolean;\n /** Backoff/timeout knobs used when `wait` is true. */\n waitOptions?: WaitOptions;\n /**\n * With `wait: true`, read the platform's phase timings once the deploy is\n * READY (one more request) into `result.timings.platform`. Default true;\n * `false` skips the read (`timings.platform` is null).\n */\n timings?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface DeployServiceOptions extends DeployOptions {\n /** Omit to auto-detect: a root go.mod+main.go is GO, otherwise BUN. */\n runtime?: ServiceRuntime;\n /** Omit for ON_DEMAND. Only set ALWAYS_ON to keep the VM warm. */\n serviceMode?: ServiceMode;\n healthPath?: string;\n /** Standard 5-field cron spec. Prefer ON_DEMAND + cron over ALWAYS_ON. */\n cronSchedule?: string;\n /** Path the cron tick POSTs to. Defaults to /cron when cronSchedule is set. */\n cronPath?: string;\n}\n\nexport interface DeployStaticOptions extends DeployOptions {\n /** Serve index.html for missing paths (single-page apps). */\n spaMode?: boolean;\n}\n\nexport interface DeployBoxOptions extends DeployOptions {\n /**\n * VM size. Omit a field for the platform default; the server's\n * `BoxResourcesInput` is authoritative. Today: 4096 MiB RAM (min 512, max\n * 16384), 4 vCPU (max 16) and a 32 GiB disk (max 128), unless the platform\n * operator raised the box's limit; a node may clamp lower. `diskGiB` sizes\n * the disk when it is first created; a later redeploy asking for more grows\n * it before the box boots, and it never shrinks.\n */\n resources?: { memMiB?: number; vcpus?: number; diskGiB?: number };\n}\n\nexport interface RollbackOptions {\n /** The alias to roll back. */\n alias: string;\n /**\n * Release to restore. Omit to pick the most recent READY release that is not\n * the current holder — i.e. \"undo the last deploy\".\n */\n to?: string;\n /**\n * Re-list-and-retry attempts when the compare-and-swap guard is rejected.\n * Default 1. Each retry refreshes the guard from a fresh read; the TARGET\n * release stays pinned, so a retry can never silently roll back to something\n * other than what was chosen.\n *\n * Ignored when {@link expectedCurrentId} is set — see there.\n */\n retries?: number;\n /**\n * The release you believe currently holds the alias. When set, the rollback\n * proceeds only if that is still true.\n *\n * This turns the rollback from \"undo whatever is live now\" into a checked\n * operation: if the live holder is anything else, you get\n * {@link UnfazedConflictError} BEFORE any mutation is sent, so a rollback\n * script can never act on a world that moved since you inspected it.\n *\n * It also disables the CAS retry, necessarily: a rejected guard means the\n * alias moved, and the alias having moved is precisely the precondition you\n * asked to be enforced. Retrying would refresh the guard to the new holder\n * and roll back the very deploy the precondition existed to protect.\n */\n expectedCurrentId?: string;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Unfazed.createRun}. */\nexport interface CreateRunOptions {\n workspaceId: string;\n /** Delivered to the guest as `/work/prompt.md` and `$UNFZ_RUN_PROMPT` (max 64 KiB). */\n prompt?: string;\n /** A named preset from the image's `/etc/unfazed/harnesses.json`. Mutually exclusive in effect with `command` — set one. */\n harness?: string;\n /** Runs anything else with `sh -c`, instead of a named `harness`. */\n command?: string;\n /** Up to 20 single-line shell commands run in `/work` before the harness; the first failure fails the run. */\n setup?: string[];\n /** Up to 10 `owner/repo:path` GitHub references, cloned into `/work/.claude/skills/<name>` first. */\n skills?: string[];\n /**\n * Up to 20 shell commands run in `/work` AFTER the harness exited 0 —\n * tests, a build, `test -f out.txt`. The first failure FAILS the run\n * (`error` \"verification failed\", `verifyExitCode`). Without `verify`,\n * SUCCEEDED only means the harness exited cleanly: an agent that answered\n * \"I could not do this\" still succeeds — read `run.result.text` in that\n * case. Skipped in plan mode.\n */\n verify?: string[];\n /** VM memory. Omit for the platform default. */\n memoryMiB?: number;\n /** Wall-clock cap in seconds. Omit for the platform default; capped at 3600. */\n maxSeconds?: number;\n /** Up to 20 immutable labels for your own correlation (a ticket id, a PR). Echoed back on every read. */\n metadata?: unknown;\n /** Copy the workspace's files into `/work`. Default true. */\n includeFiles?: boolean;\n /**\n * `\"human\"` routes the harness's guarded actions (permission prompts) to\n * the run's owner: the run shows BLOCKED with the question until it is\n * answered ({@link Unfazed.answerRun}, the dashboard). Omit for the\n * harness's own defaults.\n */\n approval?: \"human\";\n /**\n * `\"plan\"` asks the harness to research and write a plan WITHOUT acting\n * (Claude Code runs in `--permission-mode plan`); the plan is the run's\n * transcript. Approve it with {@link Unfazed.followUpRun}. Omit to do the task.\n */\n mode?: \"plan\";\n /**\n * `\"read-only\"` (the default) or `\"read-write\"`. A read-only run gets the\n * app's integrations' read-only credentials (none where the product has no\n * read-only key), only their read MCP tools, and a platform token that\n * cannot deploy or write env; read-write gets the app's own credentials,\n * read+write tools and a deploy-capable token. Ask for read-write only\n * when the run must change things.\n */\n access?: \"read-only\" | \"read-write\";\n /**\n * The app (alias) whose integrations the run gets. Implicit when the\n * workspace has one app; required when it has several.\n */\n alias?: string;\n /** The run this one continues. Usually set for you by {@link Unfazed.followUpRun}. */\n parentRunId?: string;\n /**\n * Block until the run reaches a terminal status.\n *\n * `createRun` itself already returns RUNNING or — on a boot failure —\n * FAILED with `error` set; `wait: true` additionally polls a RUNNING run\n * through to SUCCEEDED/FAILED/CANCELLED. Either way this resolves with the\n * run, never throws for FAILED: see {@link Unfazed.waitForRun}.\n */\n wait?: boolean;\n /** Backoff/timeout knobs used when `wait` is true. */\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Unfazed.followUpRun}. */\nexport interface FollowUpRunOptions {\n /** What to do next. For a plan run: the go-ahead (and any changes to the plan). */\n prompt: string;\n /** `\"plan\"` to plan again instead of executing; omit to execute. */\n mode?: \"plan\";\n /** Override the parent's approval; omit to inherit it. */\n approval?: \"human\" | \"\";\n /** Override the parent's wall clock (seconds). */\n maxSeconds?: number;\n metadata?: unknown;\n /** As for {@link CreateRunOptions.wait}. */\n wait?: boolean;\n waitOptions?: WaitOptions;\n signal?: AbortSignal;\n}\n\n/** Filter/paging for {@link Unfazed.listRuns}. */\nexport interface ListRunsFilter {\n workspaceId?: string;\n status?: RunStatus;\n limit?: number;\n offset?: number;\n}\n\nexport interface UnfazedOptions extends ClientOptions {\n /** Use an existing core client instead of constructing one. */\n client?: UnfazedClient;\n}\n\n/**\n * Layer 2 — the agent workflow layer.\n *\n * Wraps the chains an agent actually performs (create → write → deploy → wait\n * → read logs → roll back) so a code-mode script does in one call what would\n * otherwise be many round trips through a model's context. Everything here is\n * built on {@link UnfazedClient}, exposed as `.client` for anything not\n * wrapped.\n *\n * ```ts\n * const unfazed = new Unfazed(); // UNFZ_API_TOKEN, else your `npx unfazed login`\n * const ws = await unfazed.createWorkspace(\"hello\");\n * await unfazed.writeFiles(ws.id, { \"server.ts\": code });\n * const app = await unfazed.deployService({ workspaceId: ws.id, alias: \"hello\", wait: true });\n * console.log(app.url);\n * ```\n */\nexport class Unfazed {\n /** The underlying typed GraphQL client. Use it for un-wrapped operations. */\n readonly client: UnfazedClient;\n\n constructor(options: UnfazedOptions = {}) {\n const { client, ...clientOptions } = options;\n this.client = client ?? new UnfazedClient(clientOptions);\n }\n\n /* ---------------------------------------------------------------- identity */\n\n /** Who this token authenticates as, plus usage and resource limits. */\n async whoami(options?: RequestOptions) {\n const data = await this.client.query(ops.WhoamiDocument, {}, options);\n return data.whoami;\n }\n\n /* -------------------------------------------------------------- workspaces */\n\n /** Creates a source workspace — the container for files, env and deployments. */\n async createWorkspace(name: string, options?: RequestOptions) {\n const data = await this.client.mutate(ops.CreateWorkspaceDocument, { name }, options);\n return data.createWorkspace.workspace;\n }\n\n /** Workspaces visible to this token. */\n async listWorkspaces(options?: RequestOptions) {\n const data = await this.client.query(ops.ListWorkspacesDocument, {}, options);\n return data.workspaces;\n }\n\n /**\n * Deletes a workspace — its files, env and secrets, and a BOX's persistent\n * data disk — and, with `withDeployments`, every app it serves.\n *\n * A workspace can serve several apps (each `unfazed.json` `apps[]` entry, or\n * several aliases deployed into it), so deleting one with its deployments is\n * never implicit: **name exactly the apps it takes offline** in\n * `confirmAliases`. The server compares them with the workspace's live apps\n * and refuses, deleting nothing, on a missing or extra alias; the refusal\n * ({@link UnfazedUnconfirmedAppsError}) lists every live app with its\n * domains. The SDK never fills the list in: look it up deliberately with\n * {@link liveApps} and decide. To delete one app and keep the rest, use\n * {@link deleteApp}.\n *\n * ```ts\n * await unfazed.deleteWorkspace(ws.id); // only when no deployment is left\n * await unfazed.deleteWorkspace(ws.id, { withDeployments: true, confirmAliases: [\"web\", \"api\"] });\n * await unfazed.deleteWorkspace(ws.id, { withDeployments: true, confirmAliases: [] }); // serves no app\n * await unfazed.deleteWorkspace(id, { ignoreNotFound: true }); // false, not a throw\n * ```\n *\n * Without `withDeployments` the server refuses while ANY deployment record\n * is left — FAILED ones included — with `still has deployments; delete them\n * first`. A workspace whose deploys all failed serves no app: delete it with\n * `withDeployments: true, confirmAliases: []`.\n *\n * What is deleted disappears at once — gone from your views, its names and\n * aliases free, its VMs stopped — but the platform keeps it for 30 days:\n * within that time support (the platform operator) can restore it exactly\n * as it was. You cannot restore it yourself; ask support. After 30 days it\n * is erased for good.\n *\n * With `ignoreNotFound` a workspace that is absent (or belongs to someone\n * else — the server returns one indistinguishable sentinel for both, on\n * purpose) resolves to `false` instead of throwing, which makes teardown in\n * a `finally` block idempotent.\n */\n async deleteWorkspace(\n workspaceId: string,\n options: DeleteWorkspaceOptions = {},\n ): Promise<boolean> {\n const withDeployments = options.withDeployments === true;\n const confirmAliases = options.confirmAliases;\n // The types already require both together; these guard plain JavaScript\n // callers, before anything is sent.\n if (withDeployments && !Array.isArray(confirmAliases)) {\n throw new UnfazedError(\n `unfazed: nothing was deleted: deleteWorkspace(\"${workspaceId}\", { withDeployments: true }) ` +\n \"takes every app the workspace serves offline, so it needs confirmAliases naming exactly \" +\n `those apps ([] when it serves none). Look them up with unfazed.liveApps(\"${workspaceId}\"); ` +\n \"to delete one app, use unfazed.deleteApp.\",\n );\n }\n if (!withDeployments && confirmAliases !== undefined) {\n throw new UnfazedError(\n \"unfazed: nothing was deleted: confirmAliases applies only with withDeployments: true.\",\n );\n }\n try {\n const data = await this.client.mutate(\n ops.DeleteWorkspaceDocument,\n withDeployments\n ? { workspaceID: workspaceId, withDeployments, confirmAliases: [...confirmAliases!] }\n : { workspaceID: workspaceId, withDeployments },\n options,\n );\n return data.deleteWorkspace.ok;\n } catch (e) {\n if (options.ignoreNotFound && isNotFound(e, WORKSPACE_NOT_FOUND)) return false;\n if (isUnconfirmedAppsRefusal(e)) {\n throw new UnfazedUnconfirmedAppsError(workspaceId, [...(confirmAliases ?? [])], e.errors, e.data);\n }\n throw e;\n }\n }\n\n /**\n * The apps a workspace serves right now, by alias, with the deployment\n * serving each and its custom domains: everything\n * `deleteWorkspace(id, { withDeployments: true, … })` takes offline, and the\n * exact list its `confirmAliases` must name.\n *\n * It is a lookup for you to read, not something to pipe into a delete\n * unseen: check that the apps are the ones you mean to take down.\n *\n * ```ts\n * const live = await unfazed.liveApps(ws.id); // [{ alias: \"web\", deploymentID, domains: [] }, …]\n * ```\n *\n * Throws {@link UnfazedNotFoundError} when the workspace is absent or not\n * visible to this token.\n */\n async liveApps(workspaceId: string, options?: RequestOptions): Promise<LiveApp[]> {\n const data = await this.client.query(ops.WorkspaceLiveAppsDocument, { id: workspaceId }, options);\n if (!data.workspace) {\n throw new UnfazedNotFoundError(`unfazed: workspace ${workspaceId} not found`);\n }\n return data.workspace.liveApps;\n }\n\n /**\n * Deletes ONE app of a workspace and nothing else: every deployment of the\n * alias there (live release, retained releases, failed and building\n * attempts — its VM stops, its URL and custom domains stop serving), its App\n * State, its app-scoped env and secrets, and its integration bindings. The\n * workspace, its files and defaults, its other apps (`otherApps` in the\n * result) and a box's data disk stay.\n *\n * ```ts\n * const gone = await unfazed.deleteApp({ workspaceId: ws.id, alias: \"docs\" });\n * gone.deployments; // records deleted\n * gone.otherApps; // the workspace's apps still serving, untouched\n * ```\n *\n * In a git-linked workspace pushes and syncs skip the alias while\n * `unfazed.json` `apps[]` still declares it (`skippedOnSync: true`): remove\n * it from `apps[]`, or bring it back with the GraphQL `syncRepo` mutation's\n * `restoreApps` (through {@link client}). The server refuses while a git\n * import of the workspace runs. Owner only.\n *\n * What is deleted disappears at once, but the platform keeps the app for 30\n * days: within that time support (the platform operator) can restore it\n * exactly as it was. You cannot restore it yourself; ask support. After 30\n * days it is erased for good. A custom domain's record stays with the alias,\n * so a restored app serves it again.\n *\n * A delete that stops part-way throws with the server's message, which says\n * so; deleting again finishes it. With `ignoreNotFound`, an app that is not\n * in the workspace (already deleted) or a workspace that is not visible\n * resolves to `null` instead of throwing.\n */\n async deleteApp(app: AppRef, options: DeleteAppOptions & { ignoreNotFound: true }): Promise<DeleteAppResult | null>;\n async deleteApp(app: AppRef, options?: DeleteAppOptions & { ignoreNotFound?: false }): Promise<DeleteAppResult>;\n async deleteApp(app: AppRef, options?: DeleteAppOptions): Promise<DeleteAppResult | null>;\n async deleteApp(app: AppRef, options: DeleteAppOptions = {}): Promise<DeleteAppResult | null> {\n try {\n const data = await this.client.mutate(\n ops.DeleteAppDocument,\n { workspaceID: app.workspaceId, alias: app.alias },\n options,\n );\n return data.deleteApp;\n } catch (e) {\n if (options.ignoreNotFound && (isNotFound(e, WORKSPACE_NOT_FOUND) || isAppNotFound(e, app.alias))) {\n return null;\n }\n throw e;\n }\n }\n\n /**\n * Returns the workspace named `name`, creating it only if it does not exist.\n *\n * Workspace names are unique per owner, case-insensitively — a second\n * `createWorkspace(\"Hello\")` after a `createWorkspace(\"hello\")` is an error,\n * not a second workspace. That makes the bare create a poor fit for any\n * script that might run twice; this is the re-runnable form.\n *\n * ```ts\n * const ws = await unfazed.ensureWorkspace(\"greeter\"); // safe to re-run\n * ```\n *\n * Costs one list, plus one create only on a miss. The create is still\n * guarded: if a concurrent caller wins the race, the duplicate-name error is\n * caught and the now-existing workspace is returned instead of thrown.\n */\n async ensureWorkspace(name: string, options?: RequestOptions) {\n const existing = await this.#findWorkspaceByName(name, options);\n if (existing) return existing;\n\n try {\n return await this.createWorkspace(name, options);\n } catch (e) {\n // Lost a create/create race, or the server's case folding is stricter\n // than ours. Either way the workspace exists now — re-read rather than\n // failing a script whose intent was \"make sure this exists\".\n if (!isDuplicateWorkspaceName(e)) throw e;\n const raced = await this.#findWorkspaceByName(name, options);\n if (raced) return raced;\n // The name is taken by something we cannot see. Surface the real error.\n throw e;\n }\n }\n\n /* ------------------------------------------------------------------- files */\n\n /**\n * Writes many files in ONE request — and, on an app with platform git, ONE\n * commit — exactly as MCP `write_workspace_files` does.\n *\n * ```ts\n * const out = await unfazed.writeFiles(ws.id, {\n * \"server.ts\": serverCode,\n * \"package.json\": JSON.stringify(pkg),\n * \"public/logo.png\": { bytes: pngBytes },\n * }, { commitMessage: \"Add the server\" });\n * out.commit; // { sha, committed, waiting, conflicts, writeSHA, … } or null\n * ```\n *\n * A call is not transactional: files are written in order, each atomically,\n * and a file's failure does not undo the others. When any file fails this\n * throws {@link UnfazedWriteError} (its `result` lists what was written and\n * `failed` what was not; retry only those), unless `allowPartial`. A\n * repeated path keeps its last content.\n *\n * On an app with platform git the commit is made before any file is\n * written: if it fails, the request fails and nothing is written. `commit`\n * may come back `waiting` — the files are saved and the commit lands in\n * order; pass `waitForCommit: true` (or call {@link waitForCommit}) to\n * resolve only once it has. See {@link FileCommit} for saved, committed and\n * deployed.\n *\n * One request carries up to 100 files and 32 MiB; a bigger map is split\n * into several requests, each its own commit (`commits`). On a platform\n * older than the batch write the SDK falls back to one mutation per file\n * (one commit each) and reports `commit: null`.\n */\n async writeFiles(\n workspaceId: string,\n files: FilesMap,\n options: WriteFilesOptions = {},\n ): Promise<WriteFilesResult> {\n const entries = Object.entries(files).map(([path, content]) => normalizeFile(path, content));\n const result: WriteFilesResult = {\n workspaceId,\n files: [],\n written: 0,\n failed: 0,\n totalBytes: 0,\n commit: null,\n commits: [],\n };\n if (entries.length === 0) return result;\n\n const batchSize = Math.min(options.batchSize ?? MAX_BATCH_FILES, MAX_BATCH_FILES);\n const maxBatchBytes = options.maxBatchBytes ?? MAX_BATCH_BYTES;\n const requestOptions: RequestOptions = options.signal ? { signal: options.signal } : {};\n\n for (const batch of chunkFiles(entries, batchSize, maxBatchBytes)) {\n const written = this.#legacyWrites\n ? await this.#writeBatchLegacy(workspaceId, batch, requestOptions)\n : await this.#writeBatch(workspaceId, batch, options.commitMessage, requestOptions);\n result.files.push(...written.files);\n result.written += written.written;\n result.failed += written.failed;\n result.totalBytes += written.totalBytes;\n if (written.commit) {\n result.commits.push(written.commit);\n result.commit = written.commit;\n }\n }\n\n // Only a waiting commit lands by itself; a paused one waits for the\n // operator's recovery, which no client wait should block on.\n if (options.waitForCommit && result.commits.some((c) => c.waiting)) {\n const waitOptions = options.waitForCommit === true ? {} : options.waitForCommit;\n result.landed = await this.waitForCommit(workspaceId, {\n ...waitOptions,\n ...(options.signal ? { signal: options.signal } : {}),\n });\n }\n if (result.failed > 0 && !options.allowPartial) {\n throw new UnfazedWriteError(\n result,\n result.files.filter((f) => !f.ok).map((f) => ({ path: f.path, error: f.error ?? \"not written\" })),\n );\n }\n return result;\n }\n\n /**\n * Writes one text file: {@link writeFiles} with one entry, so it is one\n * commit with `commitMessage` on an app with platform git, and the answer\n * carries that commit. Throws {@link UnfazedWriteError} when it is refused.\n */\n async writeFile(\n workspaceId: string,\n path: string,\n text: string,\n options: Omit<WriteFilesOptions, \"allowPartial\" | \"batchSize\" | \"maxBatchBytes\"> = {},\n ): Promise<WrittenFile> {\n return this.#writeOne(workspaceId, path, text, options);\n }\n\n /** Writes one binary file (raw bytes or base64), like {@link writeFile}. */\n async writeBinaryFile(\n workspaceId: string,\n path: string,\n content: Uint8Array | ArrayBuffer | { base64: string },\n options: Omit<WriteFilesOptions, \"allowPartial\" | \"batchSize\" | \"maxBatchBytes\"> = {},\n ): Promise<WrittenFile> {\n const file: FileContent =\n content instanceof Uint8Array || content instanceof ArrayBuffer ? { bytes: content } : content;\n return this.#writeOne(workspaceId, path, file, options);\n }\n\n async #writeOne(\n workspaceId: string,\n path: string,\n content: FileContent,\n options: Omit<WriteFilesOptions, \"allowPartial\" | \"batchSize\" | \"maxBatchBytes\">,\n ): Promise<WrittenFile> {\n const out = await this.writeFiles(workspaceId, { [path]: content }, options);\n const file = out.files[0]?.file;\n if (!file) throw new UnfazedError(`unfazed: ${path} was not written`);\n return { ...file, commit: out.commit };\n }\n\n /**\n * Waits until no file write of the app waits for its commit: platform git\n * commits a write at once, but when the git server is slow the write is\n * saved and its commit `waiting`, landing in order. Resolves with the\n * branch head then — every write made before the call is in its history.\n * An app without platform git resolves at once (`head: null`).\n *\n * Default timeout 2 minutes; throws {@link UnfazedTimeoutError} past it\n * (the writes stay saved, and still land).\n */\n async waitForCommit(workspaceId: string, waitOptions: WaitOptions = {}): Promise<CommitsLanded> {\n const resolved = resolveWaitOptions({\n timeoutMs: 120_000,\n initialIntervalMs: 250,\n maxIntervalMs: 2_000,\n ...waitOptions,\n });\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n const started = resolved.now();\n let waiting = 0;\n return pollWithBackoff<CommitsLanded>(\n async () => {\n let page;\n try {\n page = (await this.client.query(ops.AppCommitsWaitingDocument, { workspaceID: workspaceId }, requestOptions))\n .appCommits;\n } catch (e) {\n if (!(e instanceof UnfazedGraphQLError)) throw e;\n // The history can be unreadable while writes still wait: keep waiting.\n if (e.errors.some((x) => /waiting to be committed/i.test(x.message))) return { done: false };\n // An app without platform git has no commits to wait for.\n if (e.errors.some((x) => NO_PLATFORM_GIT.test(x.message))) {\n return { done: true, value: { branch: \"\", head: null, waitedMs: resolved.now() - started } };\n }\n throw e;\n }\n waiting = page.waitingCommits;\n if (page.waitingCommits > 0) return { done: false };\n return { done: true, value: { branch: page.branch, head: page.head ?? null, waitedMs: resolved.now() - started } };\n },\n resolved,\n () =>\n new UnfazedTimeoutError(\n `unfazed: ${waiting} write(s) of workspace ${workspaceId} still wait for their commit after ${resolved.timeoutMs}ms; ` +\n \"they are saved and land in order\",\n ),\n );\n }\n\n /** Lists workspace files (paginated). */\n async listFiles(\n workspaceId: string,\n input: { limit?: number; offset?: number; order?: string } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ListFilesDocument,\n { input: { workspaceID: workspaceId, ...input } },\n options,\n );\n return data.workspaceFilesPage;\n }\n\n /** Reads a text file, optionally a byte range of it. Null when absent. */\n async readFile(\n workspaceId: string,\n path: string,\n input: { offset?: number; limit?: number } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ReadFileDocument,\n { input: { workspaceID: workspaceId, path, ...input } },\n options,\n );\n return data.readWorkspaceFile;\n }\n\n /**\n * Deletes a workspace file.\n *\n * Returns `false` when there was nothing to delete — an absent path is not\n * an error. See the `ok: false` convention on {@link deleteEnv}.\n */\n async deleteFile(\n workspaceId: string,\n path: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.DeleteFileDocument,\n { workspaceID: workspaceId, path },\n options,\n );\n return data.deleteWorkspaceFile.ok;\n }\n\n /* ----------------------------------------------------------------- deploys\n *\n * Every deploy method here MINTS A NEW RELEASE on every call. There is no\n * content dedupe: deploying byte-identical files twice produces two distinct\n * releases with two ids, both real, both counting against retention (which\n * keeps only the most recent few per alias and prunes the rest). Deploying\n * in a retry loop is therefore not free — it churns the release history and\n * can push a release you still wanted to roll back to out of retention.\n * Check {@link getDeployment} or {@link listReleases} before redeploying if\n * you only meant to converge.\n */\n\n /**\n * Deploys the workspace as a SERVICE (an HTTP server).\n *\n * With `wait: true` this resolves only once the build, VM boot and health\n * probe have all passed.\n *\n * Passing the same `alias` again redeploys that alias — a new release that\n * takes over the alias when it goes READY. Omitting `alias` lets the server\n * generate one, which means a different app on every call.\n */\n deployService(options: DeployServiceOptions): Promise<DeployResult> {\n const { workspaceId, alias, runtime, serviceMode, healthPath, cronSchedule, cronPath } =\n options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"SERVICE\",\n ...(alias === undefined ? {} : { alias }),\n ...(runtime === undefined ? {} : { runtime }),\n ...(serviceMode === undefined ? {} : { serviceMode }),\n ...(healthPath === undefined ? {} : { healthPath }),\n ...(cronSchedule === undefined ? {} : { cronSchedule }),\n ...(cronPath === undefined ? {} : { cronPath }),\n },\n options,\n );\n }\n\n /** Deploys the workspace as a STATIC site. */\n deployStatic(options: DeployStaticOptions): Promise<DeployResult> {\n const { workspaceId, alias, spaMode } = options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"STATIC\",\n ...(alias === undefined ? {} : { alias }),\n ...(spaMode === undefined ? {} : { spaMode }),\n },\n options,\n );\n }\n\n /**\n * Deploys a BOX: a persistent always-on Linux VM with a data disk that\n * survives stops and redeploys. A dev machine, not an HTTP service. The\n * result's `sshCommand` is how you get in.\n *\n * ⚠️ **Omitting `alias` creates a NEW BOX every single call.** There is no\n * \"the workspace's box\" to update: with no alias the server generates a\n * fresh random one, so a script run twice leaves you with two box records,\n * not one redeployed box.\n *\n * The data disk, meanwhile, is keyed by WORKSPACE — one disk, shared by\n * every box in the workspace, and it is the box's real identity. Since only\n * one VM can hold that disk read-write, the second box cannot even start\n * while the first is running (`box data disk for workspace ... is attached\n * to VM ...; stop it first`). The result is a pile of dead box records\n * fighting over one disk.\n *\n * **Always pass an explicit `alias` in anything re-runnable.** Redeploying\n * the same alias is the in-place update you actually want.\n *\n * ```ts\n * await unfazed.deployBox({ workspaceId: ws.id, alias: \"dev\" }); // re-runnable\n * ```\n */\n deployBox(options: DeployBoxOptions): Promise<DeployResult> {\n const { workspaceId, alias, resources } = options;\n return this.#deploy(\n {\n workspaceID: workspaceId,\n kind: \"BOX\",\n ...(alias === undefined ? {} : { alias }),\n ...(resources === undefined ? {} : { boxResources: resources }),\n },\n options,\n );\n }\n\n /** Escape hatch: deploy with a raw CreateDeploymentInput. */\n deploy(\n input: CreateDeploymentInput,\n options: Omit<DeployOptions, \"workspaceId\"> = {},\n ): Promise<DeployResult> {\n return this.#deploy(input, options);\n }\n\n async #deploy(\n input: CreateDeploymentInput,\n options: Omit<DeployOptions, \"workspaceId\">,\n ): Promise<DeployResult> {\n const requestOptions: RequestOptions = options.signal ? { signal: options.signal } : {};\n const now = options.waitOptions?.now ?? (() => Date.now());\n const sent = now();\n const data = await this.client.mutate(ops.CreateDeploymentDocument, { input }, requestOptions);\n const deployment = data.createDeployment.deployment;\n if (!options.wait) return deployment;\n const created = now();\n const waited = await this.#waitTerminal(deployment.id, {\n ...options.waitOptions,\n ...(options.signal ? { signal: options.signal } : {}),\n });\n const seen = now();\n const timings: DeployTimings = {\n client: {\n createMs: created - sent,\n waitMs: seen - created,\n totalMs: seen - sent,\n waitRequests: waited.requests,\n waitMode: waited.mode,\n },\n platform: null,\n };\n if (options.timings !== false) {\n timings.platform = await this.#readyTimings(deployment.id, options.waitOptions, requestOptions);\n }\n return { ...waited.deployment, timings };\n }\n\n /**\n * Waits until a deployment is READY, throwing {@link UnfazedDeployError} on\n * FAILED or timeout (default 10 minutes).\n *\n * It waits SERVER-SIDE (MCP `wait_for_deployment`): each request blocks on\n * the control plane until the deployment leaves BUILDING — woken by the\n * deploy pipeline itself — or 45 s pass, and comes back with the full\n * deployment; so READY reaches you one round trip after it happens, not at\n * the next poll. A NEW app that starts directly on its server is READY\n * before it serves there; the wait covers that landing too. On a platform\n * without the server-side wait, or when the platform refuses one because\n * the account already holds its cap of waits in progress (16), it polls\n * instead (`waitOptions.mode: \"poll\"` forces that), every 0.5 s backing\n * off to 3 s by default.\n */\n async waitForDeployment(deploymentId: string, waitOptions: WaitOptions = {}): Promise<Deployment> {\n return (await this.#waitTerminal(deploymentId, waitOptions)).deployment;\n }\n\n async #waitTerminal(\n deploymentId: string,\n waitOptions: WaitOptions,\n ): Promise<{ deployment: Deployment; requests: number; mode: \"server\" | \"poll\" }> {\n const now = waitOptions.now ?? (() => Date.now());\n const started = now();\n if ((waitOptions.mode ?? \"server\") === \"server\" && !this.#noServerWait) {\n try {\n return await this.#serverWait(deploymentId, waitOptions);\n } catch (e) {\n if (isUnsupportedField(e, \"waitForDeployment\")) {\n // An older platform: poll, and do not ask again on this instance.\n this.#noServerWait = true;\n } else if (!isTooManyWaits(e)) {\n throw e;\n }\n // Past the platform's cap on waits in progress (many parallel waits\n // of one account): this wait polls instead, for what is left of its\n // budget.\n }\n }\n const timeoutMs = Math.max(0, (waitOptions.timeoutMs ?? 600_000) - (now() - started));\n return this.#pollWait(deploymentId, { ...waitOptions, timeoutMs });\n }\n\n async #serverWait(\n deploymentId: string,\n waitOptions: WaitOptions,\n ): Promise<{ deployment: Deployment; requests: number; mode: \"server\" }> {\n const resolved = resolveWaitOptions(waitOptions);\n const deadline = resolved.now() + resolved.timeoutMs;\n let last: Deployment | null = null;\n let landing = false;\n for (let requests = 1; ; requests++) {\n if (resolved.signal?.aborted) throw new UnfazedTimeoutError(\"unfazed: wait aborted\");\n const remaining = deadline - resolved.now();\n if (requests > 1 && remaining <= 0) {\n throw new UnfazedDeployError(\n \"TIMEOUT\",\n deploymentId,\n last,\n `unfazed: deployment ${deploymentId} still ${last?.status ?? \"BUILDING\"}` +\n `${landing ? \" (READY, still landing on its server)\" : \"\"} after ${resolved.timeoutMs}ms`,\n );\n }\n const seconds = Math.max(1, Math.min(SERVER_WAIT_SECONDS, Math.ceil(remaining / 1000)));\n let answer;\n try {\n answer = (\n await this.client.query(\n ops.WaitForDeploymentDocument,\n { id: deploymentId, timeoutSeconds: seconds },\n // The request is a long poll: give it the wait plus a round trip,\n // whatever the client's default per-request timeout is.\n { ...(resolved.signal ? { signal: resolved.signal } : {}), timeoutMs: (seconds + 30) * 1000 },\n )\n ).waitForDeployment;\n } catch (e) {\n if (isNotFound(e, DEPLOYMENT_NOT_FOUND)) {\n throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);\n }\n throw e;\n }\n const d = answer.deployment;\n last = d;\n if (answer.timedOut) {\n landing = d.status === \"READY\";\n continue;\n }\n if (d.status === \"READY\") return { deployment: d, requests, mode: \"server\" };\n throw new UnfazedDeployError(\n \"FAILED\",\n deploymentId,\n d,\n `unfazed: deployment ${deploymentId} ${d.status}${d.error ? `: ${d.error}` : \"\"}`,\n );\n }\n }\n\n async #pollWait(\n deploymentId: string,\n waitOptions: WaitOptions,\n ): Promise<{ deployment: Deployment; requests: number; mode: \"poll\" }> {\n const resolved = resolveWaitOptions({ initialIntervalMs: 500, maxIntervalMs: 3_000, ...waitOptions });\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n let last: { id: string; status: string; error: string | null } | null = null;\n let requests = 0;\n\n await pollWithBackoff<true>(\n async () => {\n requests++;\n const data = await this.client.query(\n ops.PollDeploymentDocument,\n { id: deploymentId },\n requestOptions,\n );\n const d = data.deployment;\n if (!d) {\n throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);\n }\n last = d;\n if (d.status === \"READY\") return { done: true, value: true };\n if (d.status === \"FAILED\") {\n throw new UnfazedDeployError(\n \"FAILED\",\n deploymentId,\n d,\n `unfazed: deployment ${deploymentId} FAILED${d.error ? `: ${d.error}` : \"\"}`,\n );\n }\n return { done: false };\n },\n resolved,\n () =>\n new UnfazedDeployError(\n \"TIMEOUT\",\n deploymentId,\n last,\n `unfazed: deployment ${deploymentId} still ${\n (last as { status?: string } | null)?.status ?? \"BUILDING\"\n } after ${resolved.timeoutMs}ms`,\n ),\n );\n\n // The poll query is narrow; re-read the READY deployment in full so the\n // answer has the shape deployService returns without `wait`.\n const full = await this.getDeployment(deploymentId, requestOptions);\n if (!full) throw new UnfazedNotFoundError(`unfazed: deployment ${deploymentId} not found`);\n return { deployment: full, requests: requests + 1, mode: \"poll\" };\n }\n\n /**\n * The platform's measured phases of a deploy ({@link PlatformTimings}),\n * from its timing events. Null when it recorded none (a deploy that is\n * still building, or one from before timings existed).\n */\n async getDeploymentTimings(deploymentId: string, options?: RequestOptions): Promise<PlatformTimings | null> {\n return parseDeploymentTimings(await this.getEvents(deploymentId, 100, options));\n }\n\n /**\n * The timings of a deploy that just went READY. `deployment.phases` is\n * written right after the READY transition, so a read that races it is\n * retried once.\n */\n async #readyTimings(\n deploymentId: string,\n waitOptions: WaitOptions | undefined,\n requestOptions: RequestOptions,\n ): Promise<PlatformTimings | null> {\n try {\n const first = await this.getDeploymentTimings(deploymentId, requestOptions);\n if (first?.totalMs != null) return first;\n const sleep = waitOptions?.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n await sleep(250, requestOptions.signal);\n return (await this.getDeploymentTimings(deploymentId, requestOptions)) ?? first;\n } catch {\n // Timings are a diagnostic: never fail a deploy that went READY.\n return null;\n }\n }\n\n /** Reads one deployment by id. Null when absent. */\n async getDeployment(\n deploymentId: string,\n options?: RequestOptions,\n ): Promise<Deployment | null> {\n const data = await this.client.query(ops.GetDeploymentDocument, { id: deploymentId }, options);\n return data.deployment;\n }\n\n /** Reads the deployment currently serving an alias. Null when absent. */\n async getDeploymentByAlias(\n alias: string,\n options?: RequestOptions,\n ): Promise<Deployment | null> {\n const data = await this.client.query(ops.GetDeploymentByAliasDocument, { alias }, options);\n return data.deploymentByAlias;\n }\n\n /** Lists deployments (paginated, filterable by kind/alias/workspace). */\n async listDeployments(input: ListDeploymentsInput = {}, options?: RequestOptions) {\n const data = await this.client.query(ops.ListDeploymentsDocument, { input }, options);\n return data.deploymentsPage;\n }\n\n /* ------------------------------------------------------- runtime & logging */\n\n /** Live VM status: health, in-flight requests, restarts, RAM ceiling. */\n async getStatus(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.query(\n ops.ServiceStatusDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.serviceStatus;\n }\n\n /**\n * Tail of the service's stdout/stderr.\n *\n * The point of doing this from a script rather than through tool calls: you\n * can filter locally. `(await unfazed.getLogs(id)).stderr.split(\"\\n\")\n * .filter(l => l.includes(\"ERROR\"))` costs a model zero context, where the\n * same tail through an MCP tool spends all of it.\n */\n async getLogs(\n deploymentId: string,\n input: { tailBytes?: number } = {},\n options?: RequestOptions,\n ) {\n const data = await this.client.query(\n ops.ServiceLogsDocument,\n { deploymentID: deploymentId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.serviceLogs;\n }\n\n /**\n * Deployment lifecycle events — build, boot, probe, cron, restarts — the\n * most recent `limit` (default 20), oldest first.\n *\n * `type` is the event's own name, as MCP reports it:\n * `\"deployment.build_finished\"`, `\"deployment.phases\"`,\n * `\"service.vm_started\"`, `\"service.crashed\"`. (`typeEnum` keeps the GraphQL\n * enum, which reads `UNKNOWN` for names it does not list.) Timing events\n * carry their phases in `metadata`; {@link getDeploymentTimings} turns them\n * into numbers.\n *\n * ```ts\n * const events = await unfazed.getEvents(app.id, 50);\n * events.filter((e) => e.type === \"deployment.build_finished\");\n * ```\n */\n async getEvents(deploymentId: string, limit?: number, options?: RequestOptions): Promise<DeploymentEvent[]> {\n const data = await this.client.query(\n ops.DeploymentEventsDocument,\n { deploymentID: deploymentId, limit: limit ?? null },\n options,\n );\n return data.deploymentEvents.map(toDeploymentEvent);\n }\n\n /** Restarts a service's VM. */\n async restartService(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.mutate(\n ops.RestartServiceDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.restartService;\n }\n\n /** Stops a service's VM. An on-demand service cold-starts again on request. */\n async stopService(deploymentId: string, options?: RequestOptions) {\n const data = await this.client.mutate(\n ops.StopServiceDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.stopService;\n }\n\n /**\n * Deletes a deployment: stops its VM, releases its alias, drops its release.\n * To delete a whole app — every release of the alias, its env, App State and\n * bindings — use {@link deleteApp}.\n *\n * The platform keeps a deleted release for 30 days: within that time\n * support (the platform operator) can restore it; then it is erased for\n * good.\n *\n * With `ignoreNotFound` a deployment that is absent — or belongs to another\n * tenant, which the server reports identically so ids cannot be probed —\n * resolves to `false` instead of throwing, making cleanup loops idempotent.\n */\n async deleteDeployment(\n deploymentId: string,\n options: DeleteDeploymentOptions = {},\n ): Promise<boolean> {\n try {\n const data = await this.client.mutate(\n ops.DeleteDeploymentDocument,\n { deploymentID: deploymentId },\n options,\n );\n return data.deleteDeployment.ok;\n } catch (e) {\n if (options.ignoreNotFound && isNotFound(e, DEPLOYMENT_NOT_FOUND)) return false;\n throw e;\n }\n }\n\n /* ------------------------------------------------------------ env & secrets\n *\n * Workspace values are SERVICE defaults for every app in the source; app\n * values override them for one alias. Both are SNAPSHOTTED into a release at\n * deploy time — changing either does not affect a running app until you\n * redeploy that alias. Old releases are immutable, and STATIC gets no env.\n */\n\n /**\n * Sets a workspace-default env var. Redeploy the alias to apply it.\n *\n * A name is either plain or secret, never both: this DELETES a workspace\n * secret of the same name. {@link setSecret} displaces a plain var the same\n * way. Last write wins, and the kind flips silently — so re-running a setup\n * script that calls `setSecret(\"API_KEY\", ...)` after one that called\n * `setEnv(\"API_KEY\", ...)` quietly converts it, and vice versa.\n */\n async setEnv(\n workspaceId: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetWorkspaceEnvDocument,\n { workspaceID: workspaceId, name, value },\n options,\n );\n return data.setWorkspaceEnv.env;\n }\n\n /**\n * Sets a workspace-default secret. The value is never readable again.\n *\n * Mutually exclusive with {@link setEnv}: this DELETES a plain workspace var\n * of the same name. See {@link setEnv} for the displacement rule.\n */\n async setSecret(\n workspaceId: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetWorkspaceSecretDocument,\n { workspaceID: workspaceId, name, value },\n options,\n );\n return data.setWorkspaceSecret.env;\n }\n\n /**\n * Sets many workspace env vars in one request, via aliased mutations —\n * the same batching trick as {@link writeFiles}.\n *\n * Pass `{ secret: true }` to route them all to `setWorkspaceSecret`.\n *\n * It inherits {@link writeFiles}' failure semantics too: the batch is NOT\n * atomic. GraphQL resolves each aliased field independently, so a rejected\n * name (over the limit, malformed, whatever) leaves the vars before it\n * already committed. The thrown {@link UnfazedGraphQLError} carries `data`\n * with the aliases that succeeded and `errors[].path` naming those that did\n * not — do not assume \"it threw\" means \"nothing was written\".\n *\n * Each name still displaces its opposite kind, exactly as {@link setEnv} and\n * {@link setSecret} do one at a time.\n */\n async setEnvMany(\n workspaceId: string,\n vars: Record<string, string>,\n options: { secret?: boolean; signal?: AbortSignal } = {},\n ): Promise<EnvVar[]> {\n const entries = Object.entries(vars);\n if (entries.length === 0) return [];\n\n const field = options.secret ? \"setWorkspaceSecret\" : \"setWorkspaceEnv\";\n const varDefs = [\"$workspaceID: ID!\"];\n const fields: string[] = [];\n const variables: Record<string, string> = { workspaceID: workspaceId };\n\n entries.forEach(([name, value], i) => {\n varDefs.push(`$n${i}: String!`, `$v${i}: String!`);\n variables[`n${i}`] = name;\n variables[`v${i}`] = value;\n fields.push(\n ` e${i}: ${field}(input: { workspaceID: $workspaceID, name: $n${i}, value: $v${i} }) { env { ${ENV_SELECTION} } }`,\n );\n });\n\n const document = `mutation SdkSetEnvBatch(${varDefs.join(\", \")}) {\\n${fields.join(\"\\n\")}\\n}`;\n const data = await this.client.mutate<Record<string, { env: EnvVar }>, typeof variables>(\n document,\n variables,\n options.signal ? { signal: options.signal } : {},\n );\n return entries.map((_, i) => data[`e${i}`]!.env);\n }\n\n /**\n * Deletes a workspace-default env var (plain or secret).\n *\n * **The `ok: false` convention.** A `false` here does NOT mean failure — it\n * means \"nothing to do, the world is already in the state you asked for\".\n * The var did not exist. Every `ok`-returning mutation in this SDK follows\n * the rule ({@link deleteFile}, {@link inheritAppEnv}, {@link removeAppEnv}),\n * so the idempotent-cleanup pattern is simply to ignore the boolean; a real\n * failure throws.\n */\n async deleteEnv(workspaceId: string, name: string, options?: RequestOptions): Promise<boolean> {\n const data = await this.client.mutate(\n ops.DeleteWorkspaceEnvDocument,\n { workspaceID: workspaceId, name },\n options,\n );\n return data.deleteWorkspaceEnv.ok;\n }\n\n /** Workspace-default env vars. Secret values are redacted. */\n async listEnv(workspaceId: string, options?: RequestOptions): Promise<EnvVar[]> {\n const data = await this.client.query(\n ops.ListWorkspaceEnvDocument,\n { workspaceID: workspaceId },\n options,\n );\n return data.workspaceEnv;\n }\n\n /**\n * Sets an env var for ONE alias, overriding the workspace default.\n *\n * Displaces both of the other states this name could be in for the app: it\n * deletes an app SECRET of the same name, and it CLEARS a REMOVE mask left\n * by {@link removeAppEnv}. So setting a value is also the way to un-block a\n * masked name, and a name is only ever one of plain / secret / masked.\n */\n async setAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetAppEnvDocument,\n { workspaceID: workspaceId, alias, name, value },\n options,\n );\n return data.setAppEnv.env;\n }\n\n /**\n * Sets a secret for ONE alias, overriding the workspace default.\n *\n * Like {@link setAppEnv}, this deletes a plain app var of the same name and\n * clears a REMOVE mask for it.\n */\n async setAppSecret(\n workspaceId: string,\n alias: string,\n name: string,\n value: string,\n options?: RequestOptions,\n ): Promise<EnvVar> {\n const data = await this.client.mutate(\n ops.SetAppSecretDocument,\n { workspaceID: workspaceId, alias, name, value },\n options,\n );\n return data.setAppSecret.env;\n }\n\n /**\n * REMOVE: blocks this name for the app entirely — the app override, the\n * workspace default, and integration enrichment. Not the same as deleting an\n * override; use {@link inheritAppEnv} for that.\n *\n * This WRITES A MASK, and the mask is a real, persistent row. Two things\n * follow that surprise people:\n *\n * - It is written even when nothing was inherited. Masking a name that no\n * workspace default and no integration ever provided is not a no-op; it\n * leaves a tombstone that keeps blocking the name if a default appears\n * later. Clear it with {@link inheritAppEnv}.\n * - It COSTS A SLOT. A workspace gets 128 env entries total — that budget\n * is shared across the workspace defaults AND every app scope combined,\n * not 128 per scope — and masks count toward it just like values do.\n * Masking names in a loop can exhaust the workspace's env budget.\n *\n * Returns `false` when the exact mask was already present (a second call for\n * the same name), per the {@link deleteEnv} `ok: false` convention. It\n * returns `true` when it had something to change — including converting an\n * existing override into a mask.\n */\n async removeAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.RemoveAppEnvDocument,\n { workspaceID: workspaceId, alias, name },\n options,\n );\n return data.removeAppEnv.ok;\n }\n\n /**\n * INHERIT: clears the app override/mask so workspace and integration values\n * apply again. This is the undo for both {@link setAppEnv} and\n * {@link removeAppEnv}.\n *\n * Returns `false` when there was no override and no mask to clear — nothing\n * to do, not a failure. See {@link deleteEnv}.\n */\n async inheritAppEnv(\n workspaceId: string,\n alias: string,\n name: string,\n options?: RequestOptions,\n ): Promise<boolean> {\n const data = await this.client.mutate(\n ops.InheritAppEnvDocument,\n { workspaceID: workspaceId, alias, name },\n options,\n );\n return data.inheritAppEnv.ok;\n }\n\n /** The effective env view for one alias: overrides, inherited and masked. */\n async listAppEnv(\n workspaceId: string,\n alias: string,\n options?: RequestOptions,\n ): Promise<EnvVar[]> {\n const data = await this.client.query(\n ops.ListAppEnvDocument,\n { workspaceID: workspaceId, alias },\n options,\n );\n return data.appEnv;\n }\n\n /* -------------------------------------------------- releases & rollback */\n\n /**\n * An alias's terminal release history, newest first.\n *\n * Exactly one entry has `aliasHeld: true` — the live release. FAILED entries\n * appear on purpose (they are rejected promotions, so a kept-live previous\n * release is never mistaken for a silent fallback) and cannot be rolled back\n * to. Retention keeps only the most recent few per alias, default 5.\n */\n async listReleases(alias: string, options?: RequestOptions): Promise<Deployment[]> {\n const data = await this.client.query(ops.ListReleasesDocument, { alias }, options);\n return data.deploymentReleases;\n }\n\n /**\n * Rolls an alias back to a prior release, handling the whole compare-and-swap\n * protocol in one call.\n *\n * The server requires the caller to prove it observed the current state: you\n * must pass the live release's id AND its opaque `aliasRevision`, and the\n * swap fails if either changed since you listed — including same-id ABA. So\n * this method does the full dance: list releases, find the `aliasHeld` entry,\n * pick the target, and submit both guard values.\n *\n * On a rejected guard it re-lists and retries (default once). The TARGET is\n * pinned across retries while the guard is refreshed, so a concurrent deploy\n * can never redirect the rollback to a different release than the one chosen.\n *\n * ```ts\n * await unfazed.rollback({ alias: \"my-app\" }); // undo last deploy\n * await unfazed.rollback({ alias: \"my-app\", to: relId }); // to a specific release\n * await unfazed.rollback({ alias: \"my-app\", to: relId, expectedCurrentId: liveId });\n * ```\n *\n * ⚠️ **A bare `rollback({ alias })` is a TOGGLE, not an idempotent step.**\n * It means \"restore the most recent READY release that is not the live one\",\n * which is a different release each time the alias moves. Run the same\n * script twice and the second run rolls back the rollback — A → B → A → B,\n * forever, with each hop a real alias swap. Nothing errors, because every\n * individual call did exactly what it was asked.\n *\n * In anything re-runnable — a retry loop, a CI job, an agent that might redo\n * a step — pin the outcome instead:\n *\n * - `to:` names the release you want live, so re-running is a no-op-ish\n * convergence rather than a flip (a second run then reports the target\n * already holds the alias instead of moving it);\n * - `expectedCurrentId:` states what you expect to be live now, so a second\n * run fails loudly instead of silently undoing the first.\n */\n async rollback(options: RollbackOptions): Promise<Deployment> {\n const { alias, signal, expectedCurrentId } = options;\n // A caller-supplied precondition and the CAS retry are mutually exclusive:\n // retrying re-guards against whatever holds the alias NOW, which is the\n // one thing `expectedCurrentId` exists to refuse.\n const retries = expectedCurrentId === undefined ? (options.retries ?? 1) : 0;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n\n let targetId = options.to;\n\n for (let attempt = 0; ; attempt++) {\n const releases = await this.listReleases(alias, requestOptions);\n if (releases.length === 0) {\n throw new UnfazedNotFoundError(`unfazed: alias \"${alias}\" has no release history`);\n }\n\n const current = releases.find((r) => r.aliasHeld);\n if (!current) {\n throw new UnfazedNotFoundError(\n `unfazed: alias \"${alias}\" has no current release holding the alias`,\n );\n }\n\n // The caller's precondition, checked before anything is sent. Failing\n // here rather than at the server keeps a violated expectation from\n // costing an alias swap, and reports the holder we actually observed.\n if (expectedCurrentId !== undefined && current.id !== expectedCurrentId) {\n throw new UnfazedConflictError(\n `unfazed: alias \"${alias}\" is held by ${current.id}, not the expected ` +\n `${expectedCurrentId} — it moved since you read it; re-read and decide again`,\n [],\n );\n }\n\n // Pin the target on the first pass so a retry refreshes only the guard.\n if (targetId === undefined) {\n const previous = releases.find((r) => r.id !== current.id && r.status === \"READY\");\n if (!previous) {\n throw new UnfazedNotFoundError(\n `unfazed: alias \"${alias}\" has no prior READY release to roll back to ` +\n `(history: ${releases.map((r) => `${r.id}:${r.status}`).join(\", \")})`,\n );\n }\n targetId = previous.id;\n }\n\n const target = releases.find((r) => r.id === targetId);\n if (!target) {\n throw new UnfazedNotFoundError(\n `unfazed: release ${targetId} is not in alias \"${alias}\"'s history ` +\n `(it may have been pruned; retention keeps only the most recent few)`,\n );\n }\n if (target.id === current.id) {\n throw new UnfazedConflictError(\n `unfazed: release ${targetId} already holds alias \"${alias}\"`,\n [],\n );\n }\n if (target.status !== \"READY\") {\n throw new UnfazedConflictError(\n `unfazed: release ${targetId} is ${target.status}, only READY releases can be restored`,\n [],\n );\n }\n\n try {\n const data = await this.client.mutate(\n ops.RollbackDocument,\n {\n deploymentID: target.id,\n expectedCurrentDeploymentID: current.id,\n expectedCurrentAliasRevision: current.aliasRevision,\n },\n requestOptions,\n );\n return data.rollbackDeployment;\n } catch (e) {\n const retryable =\n e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors) && attempt < retries;\n if (!retryable) {\n if (e instanceof UnfazedGraphQLError && looksLikeCASConflict(e.errors)) {\n throw new UnfazedConflictError(\n `unfazed: rollback of \"${alias}\" lost the compare-and-swap after ${\n attempt + 1\n } attempt(s) — the alias is being deployed concurrently. ${e.message}`,\n e.errors,\n );\n }\n throw e;\n }\n // Loop: re-list, rebuild the guard, keep the same target.\n }\n }\n }\n\n /* ------------------------------------------------------- platform git history\n *\n * An app with platform git (MCP `enable_platform_git`; apps get it by\n * themselves at their next change) keeps every file write, push and restore\n * as a commit. These are MCP's history tools.\n */\n\n /**\n * The app's commits, newest first (MCP `list_commits`): `limit` per page\n * (default 20, max 100), `before: page.nextBefore` for the next. `deployed`\n * says what every live alias runs; `waitingCommits` counts writes whose\n * commit has not landed yet.\n */\n async listCommits(\n workspaceId: string,\n input: { limit?: number; before?: string } = {},\n options?: RequestOptions,\n ): Promise<CommitPage> {\n const data = await this.client.query(\n ops.AppCommitsDocument,\n { workspaceID: workspaceId, limit: input.limit ?? null, before: input.before ?? null },\n options,\n );\n return data.appCommits;\n }\n\n /**\n * One commit (full 40-character sha) with the paths it changed and a\n * unified diff against its first parent, capped at 64 KiB (MCP\n * `get_commit`). Commit messages and diffs are untrusted text.\n */\n async getCommit(workspaceId: string, sha: string, options?: RequestOptions): Promise<CommitDetail> {\n const data = await this.client.query(ops.AppCommitDocument, { workspaceID: workspaceId, sha }, options);\n return data.appCommit;\n }\n\n /**\n * Gives the app back the files of an earlier commit as ONE new commit on\n * its branch (MCP `restore_version`); nothing is rewritten, and a restore is\n * undone by restoring the commit before it.\n *\n * When the app deploys every push (`deploys: true`), the new commit is\n * imported and deployed like a push. That deploy is queued behind the\n * restore, so the platform answers before it exists; with `wait: true` the\n * SDK waits for the import of the new commit and resolves with the\n * deployments it made (READY), or throws {@link UnfazedDeployError} with\n * the import's error.\n *\n * ```ts\n * const page = await unfazed.listCommits(ws.id);\n * const back = await unfazed.restoreVersion({ workspaceId: ws.id, sha: page.commits[1]!.sha, wait: true });\n * back.deployments?.[0]?.url;\n * ```\n */\n async restoreVersion(options: RestoreVersionOptions): Promise<RestoreVersionResult> {\n const requestOptions: RequestOptions = options.signal ? { signal: options.signal } : {};\n const data = await this.client.mutate(\n ops.RestoreVersionDocument,\n {\n workspaceID: options.workspaceId,\n sha: options.sha,\n expectedHead: options.expectedHead ?? null,\n message: options.commitMessage ?? null,\n },\n requestOptions,\n );\n const restored: RestoreVersionResult = data.restoreAppVersion;\n if (!options.wait || !restored.deploys) return restored;\n return {\n ...restored,\n deployments: await this.#waitForImport(options.workspaceId, restored.sha, {\n ...options.waitOptions,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n };\n }\n\n /**\n * Waits until the app's git link has imported `sha` (READY: its deploys\n * are done) and returns the deployments of that commit; throws on a FAILED\n * import of it.\n */\n async #waitForImport(workspaceId: string, sha: string, waitOptions: WaitOptions): Promise<Deployment[]> {\n const resolved = resolveWaitOptions({ initialIntervalMs: 500, maxIntervalMs: 3_000, ...waitOptions });\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n let last: { lastImportedCommit?: string | null; lastImportStatus?: string; lastImportError?: string | null } | null =\n null;\n await pollWithBackoff<true>(\n async () => {\n const data = await this.client.query(ops.WorkspaceGitSourceDocument, { id: workspaceId }, requestOptions);\n const src = data.workspace?.gitSource ?? null;\n if (!src) throw new UnfazedNotFoundError(`unfazed: workspace ${workspaceId} has no git source`);\n last = src;\n if (src.lastImportedCommit !== sha) return { done: false };\n if (src.lastImportStatus === \"READY\") return { done: true, value: true };\n if (src.lastImportStatus === \"FAILED\") {\n throw new UnfazedDeployError(\n \"FAILED\",\n \"\",\n null,\n `unfazed: the import of ${sha.slice(0, 7)} failed${src.lastImportError ? `: ${src.lastImportError}` : \"\"}`,\n );\n }\n return { done: false };\n },\n resolved,\n () =>\n new UnfazedDeployError(\n \"TIMEOUT\",\n \"\",\n null,\n `unfazed: ${sha.slice(0, 7)} was not imported after ${resolved.timeoutMs}ms` +\n (last ? ` (last import: ${last.lastImportStatus} ${last.lastImportedCommit?.slice(0, 7) ?? \"\"})` : \"\"),\n ),\n );\n const page = await this.listDeployments({ workspaceID: workspaceId, limit: 50 }, requestOptions);\n return page.items.filter((d) => d.gitCommit === sha);\n }\n\n /* ------------------------------------------------------------- app errors\n *\n * Native error tracking: a service app's uncaught exceptions, unhandled\n * rejections, panics and Sentry SDK reports, grouped, kept on its server\n * for 30 days. These are MCP's error tools. Titles, stacks and requests are\n * what the app reported: untrusted text.\n */\n\n /** A service app's error groups, most recently seen first (MCP `list_errors`). */\n async listErrors(input: ListErrorsOptions, options?: RequestOptions): Promise<ErrorGroupPage> {\n const data = await this.client.query(\n ops.AppErrorsDocument,\n {\n workspaceID: input.workspaceId,\n alias: input.alias,\n status: input.status ?? null,\n limit: input.limit ?? null,\n cursor: input.cursor ?? null,\n },\n options,\n );\n return data.appErrors;\n }\n\n /**\n * One error group with its latest occurrence whole (a Sentry event: stack,\n * request), its recent occurrences and the deployments it was seen in (MCP\n * `get_error_group`).\n */\n async getErrorGroup(ref: ErrorGroupRef, options?: RequestOptions): Promise<ErrorGroupDetail> {\n const data = await this.client.query(\n ops.AppErrorGroupDocument,\n { workspaceID: ref.workspaceId, alias: ref.alias, groupID: ref.groupId },\n options,\n );\n return data.appErrorGroup;\n }\n\n /**\n * Marks a group resolved in the app's current deployment, once its fix is\n * deployed (MCP `resolve_error_group`); another deployment reporting it\n * opens it again. Only on your human's say-so or a fix you verified.\n */\n async resolveErrorGroup(ref: ErrorGroupRef, options?: RequestOptions): Promise<ErrorGroup> {\n const data = await this.client.mutate(ops.ResolveErrorGroupDocument, { input: errorGroupInput(ref) }, options);\n return data.resolveAppErrorGroup;\n }\n\n /** Mutes an expected group: still counted, never regresses or notifies (MCP `mute_error_group`). */\n async muteErrorGroup(ref: ErrorGroupRef, options?: RequestOptions): Promise<ErrorGroup> {\n const data = await this.client.mutate(ops.MuteErrorGroupDocument, { input: errorGroupInput(ref) }, options);\n return data.muteAppErrorGroup;\n }\n\n /** Opens a resolved or muted group again (MCP `reopen_error_group`). */\n async reopenErrorGroup(ref: ErrorGroupRef, options?: RequestOptions): Promise<ErrorGroup> {\n const data = await this.client.mutate(ops.ReopenErrorGroupDocument, { input: errorGroupInput(ref) }, options);\n return data.reopenAppErrorGroup;\n }\n\n /* ------------------------------------------------------------------ events\n *\n * What happened to the apps, runs and domains you can see —\n * deployment.finished, service.crashed, error.new, error.regressed,\n * git.conflict, run.finished, … — instead of re-polling status. The same\n * feed and cursors as MCP `poll_events` / `wait_for_events`.\n */\n\n /** The event types, with each one's filters and payload schema (MCP `list_event_types`). */\n async listEventTypes(options?: RequestOptions): Promise<EventType[]> {\n const data = await this.client.query(ops.EventTypesDocument, {}, options);\n return data.platformEventTypes;\n }\n\n /**\n * Events since `cursor` (MCP `poll_events`). Omit `cursor` to start from now\n * — nothing is replayed — and pass the returned `cursor` back: at once while\n * `hasMore`, otherwise after `nextPollMs`, or to {@link waitForEvents}.\n * `truncated` means events may be missing: re-read state.\n */\n async pollEvents(input: EventsInput = {}, options?: RequestOptions): Promise<EventPage> {\n const data = await this.client.query(ops.PollEventsDocument, { input: eventsInput(input) }, options);\n return data.pollEvents;\n }\n\n /**\n * {@link pollEvents} that waits server-side until an event arrives (MCP\n * `wait_for_events`), for up to `timeoutMs` (default 45 s; longer waits are\n * several server waits of up to 45 s, continuing from each cursor). A\n * timeout is not an error: the page has `timedOut: true`, no events and a\n * cursor to wait again with. The platform caps an account's waits in\n * progress (16, deploy waits included); past it this throws an error that\n * `isTooManyWaits` recognizes: poll then.\n *\n * ```ts\n * let page = await unfazed.pollEvents({ names: [\"deployment.finished\"] }); // from now\n * page = await unfazed.waitForEvents({ names: [\"deployment.finished\"], cursor: page.cursor, timeoutMs: 120_000 });\n * ```\n */\n async waitForEvents(\n input: EventsInput & { timeoutMs?: number } = {},\n options: RequestOptions & { now?: () => number } = {},\n ): Promise<EventPage> {\n const now = options.now ?? (() => Date.now());\n const deadline = now() + (input.timeoutMs ?? SERVER_WAIT_SECONDS * 1000);\n let cursor = input.cursor;\n for (;;) {\n const remaining = deadline - now();\n const seconds = Math.max(1, Math.min(SERVER_WAIT_SECONDS, Math.ceil(remaining / 1000)));\n const { now: _now, ...requestOptions } = options;\n const data = await this.client.query(\n ops.WaitForEventsDocument,\n { input: eventsInput({ ...input, ...(cursor === undefined ? {} : { cursor }) }), timeoutSeconds: seconds },\n { ...requestOptions, timeoutMs: (seconds + 30) * 1000 },\n );\n const page = data.waitForEvents;\n if (!page.timedOut || deadline - now() <= 0) return page;\n cursor = page.cursor;\n }\n }\n\n /* --------------------------------------------------------------- agent runs\n *\n * A run is the past-tense counterpart to a deployment: boot a fresh VM off\n * the box image, hand it a prompt, let a harness work for up to an hour,\n * keep the transcript, meter what it cost, reap the VM. Deployments answer\n * \"what is running\"; runs answer \"what happened\". Inside a run, `new\n * Unfazed()` is already authenticated — the platform injects\n * UNFZ_API_TOKEN / UNFZ_API_URL, at most the parent's scopes, revoked when\n * the run settles.\n */\n\n /**\n * Starts an agent run.\n *\n * Resolves once the VM has started (status RUNNING) — or, on a boot\n * failure, once the run has already settled FAILED with `error` set. A\n * boot failure is a normal return value here, not a thrown error, with or\n * without `wait`.\n *\n * ```ts\n * const run = await unfazed.createRun({\n * workspaceId: ws.id,\n * harness: \"claude-code\",\n * prompt: \"Fix the failing test in test/foo.test.ts and open a PR.\",\n * wait: true,\n * });\n * console.log(run.status, run.usage.mibSeconds);\n * ```\n *\n * With `wait: true` this additionally polls a RUNNING run through to a\n * terminal status — see {@link waitForRun} for exactly what \"terminal\"\n * means and how a timeout is reported.\n */\n async createRun(options: CreateRunOptions): Promise<Run> {\n const {\n workspaceId,\n prompt,\n harness,\n command,\n setup,\n skills,\n verify,\n memoryMiB,\n maxSeconds,\n metadata,\n includeFiles,\n approval,\n mode,\n access,\n alias,\n parentRunId,\n wait,\n waitOptions,\n signal,\n } = options;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n const data = await this.client.mutate(\n ops.CreateRunDocument,\n {\n input: {\n workspaceID: workspaceId,\n ...(prompt === undefined ? {} : { prompt }),\n ...(harness === undefined ? {} : { harness }),\n ...(command === undefined ? {} : { command }),\n ...(setup === undefined ? {} : { setup }),\n ...(skills === undefined ? {} : { skills }),\n ...(verify === undefined ? {} : { verify }),\n ...(memoryMiB === undefined ? {} : { memoryMiB }),\n ...(maxSeconds === undefined ? {} : { maxSeconds }),\n ...(metadata === undefined ? {} : { metadata }),\n ...(includeFiles === undefined ? {} : { includeFiles }),\n ...(approval === undefined ? {} : { approval }),\n ...(mode === undefined ? {} : { mode }),\n ...(access === undefined ? {} : { access }),\n ...(alias === undefined ? {} : { alias }),\n ...(parentRunId === undefined ? {} : { parentRunID: parentRunId }),\n },\n },\n requestOptions,\n );\n const run = data.createRun;\n // Unlike createDeployment (always BUILDING), createRun can come back\n // already terminal — a boot failure settles FAILED synchronously. Only\n // poll when there is actually something to wait for.\n if (!wait || isTerminalRunStatus(run.status)) return run;\n return this.waitForRun(run.id, {\n ...waitOptions,\n ...(signal ? { signal } : {}),\n });\n }\n\n /**\n * Polls a run until it leaves QUEUED/RUNNING, throwing only on timeout.\n *\n * Terminal is defined negatively — anything that is not QUEUED or RUNNING —\n * matching the platform's own status machine, so an unknown future status\n * still ends the wait instead of looping forever. **SUCCEEDED, FAILED and\n * CANCELLED are all returned normally**: a run that executed and exited\n * non-zero is a completed answer (read `run.error` / `run.exitCode`), not\n * an exception the way a FAILED deployment is. Only running out of time\n * throws, as {@link UnfazedRunError} with `reason: \"TIMEOUT\"`.\n */\n async waitForRun(runId: string, waitOptions: WaitOptions = {}): Promise<Run> {\n const resolved = resolveWaitOptions(waitOptions);\n const requestOptions: RequestOptions = resolved.signal ? { signal: resolved.signal } : {};\n let last: { id: string; status: RunStatus; error: string | null; exitCode: number | null } | null =\n null;\n\n await pollWithBackoff<true>(\n async () => {\n const data = await this.client.query(ops.PollRunDocument, { id: runId }, requestOptions);\n const r = data.run;\n last = r;\n if (isTerminalRunStatus(r.status)) return { done: true, value: true };\n return { done: false };\n },\n resolved,\n () =>\n new UnfazedRunError(\n \"TIMEOUT\",\n runId,\n last,\n `unfazed: run ${runId} still ${(last as { status?: string } | null)?.status ?? \"QUEUED\"} after ${resolved.timeoutMs}ms`,\n ),\n );\n\n return this.getRun(runId, requestOptions);\n }\n\n /** Reads one run by id. Throws if it does not exist or is not visible to you. */\n async getRun(runId: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.query(ops.GetRunDocument, { id: runId }, options);\n return data.run;\n }\n\n /**\n * The harness presets a run may name (`createRun({ harness })`): name,\n * title, what it is, and the workspace secrets it requires (set them with\n * {@link Unfazed.setSecret} before the run). Empty when the node's box\n * image carries no catalogue.\n */\n async listRunHarnesses(options?: RequestOptions): Promise<RunHarness[]> {\n const data = await this.client.query(ops.ListRunHarnessesDocument, {}, options);\n return data.runHarnesses;\n }\n\n /** Your agent runs, newest first, optionally filtered by workspace/status. */\n async listRuns(filter: ListRunsFilter = {}, options?: RequestOptions) {\n const { workspaceId, status, limit, offset } = filter;\n const data = await this.client.query(\n ops.ListRunsDocument,\n {\n input: {\n ...(workspaceId === undefined ? {} : { workspaceID: workspaceId }),\n ...(status === undefined ? {} : { status }),\n ...(limit === undefined ? {} : { limit }),\n ...(offset === undefined ? {} : { offset }),\n },\n },\n options,\n );\n return data.runs;\n }\n\n /**\n * Stops a run: a QUEUED run is cancelled at once, a RUNNING run's VM is\n * killed and the run settles CANCELLED shortly after (`waitForRun` to\n * observe it). Idempotent on an already-CANCELLED run; a run that has\n * already SUCCEEDED or FAILED cannot be cancelled and the server rejects\n * the call (thrown as {@link UnfazedGraphQLError}) — check `status` first\n * when that is a routine case for you.\n */\n async cancelRun(runId: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.mutate(ops.CancelRunDocument, { id: runId }, options);\n return data.cancelRun;\n }\n\n /**\n * Continues a FINISHED run with a new instruction: a new run in the same\n * workspace that inherits the parent's harness (or command), setup, skills\n * and approval, with the parent's task, outcome and the end of its\n * transcript prepended to `prompt` as context. This is how a plan is\n * approved — `createRun({ mode: \"plan\" })` writes the plan, `followUpRun`\n * with the go-ahead executes it — and how work continues after a run\n * exited. The new run carries `parentRunID` and `depth`; chains are capped\n * server-side. A live run cannot be followed up (the server refuses):\n * answer it or wait for it.\n *\n * ```ts\n * const plan = await unfazed.createRun({ workspaceId, harness: \"claude-code\", prompt: \"plan the migration\", mode: \"plan\", wait: true });\n * const done = await unfazed.followUpRun(plan.id, { prompt: \"go ahead\", wait: true });\n * ```\n */\n async followUpRun(runId: string, options: FollowUpRunOptions): Promise<Run> {\n const { prompt, mode, approval, maxSeconds, metadata, wait, waitOptions, signal } = options;\n const requestOptions: RequestOptions = signal ? { signal } : {};\n const data = await this.client.mutate(\n ops.FollowUpRunDocument,\n {\n input: {\n runID: runId,\n prompt,\n ...(mode === undefined ? {} : { mode }),\n ...(approval === undefined ? {} : { approval }),\n ...(maxSeconds === undefined ? {} : { maxSeconds }),\n ...(metadata === undefined ? {} : { metadata }),\n },\n },\n requestOptions,\n );\n const run = data.followUpRun;\n if (!wait || isTerminalRunStatus(run.status)) return run;\n return this.waitForRun(run.id, { ...waitOptions, ...(signal ? { signal } : {}) });\n }\n\n /**\n * Answers a BLOCKED run's pending question (`run.question`); the run\n * resumes with the text. For a question with `options`, answer with one\n * of them. Only a BLOCKED run accepts an answer — anything else is\n * refused by the server.\n *\n * A run blocks when the agent inside calls `request_human_input`, or when\n * it was created with `approval: \"human\"` and its harness asks permission\n * for a guarded action. `waitForRun` keeps waiting through BLOCKED (it is\n * not terminal); poll `getRun` and look at `question` to notice one.\n */\n async answerRun(runId: string, answer: string, options?: RequestOptions): Promise<Run> {\n const data = await this.client.mutate(ops.AnswerRunDocument, { id: runId, answer }, options);\n return data.answerRun;\n }\n\n /** A run's own history, oldest first (started, cancel requested, settled). */\n async runEvents(runId: string, input: { limit?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunEventsDocument,\n { runID: runId, limit: input.limit ?? null },\n options,\n );\n return data.runEvents;\n }\n\n /**\n * The live tail of a RUNNING run's console. Once the run has settled this\n * comes back empty with `running: false` — read {@link runTranscript}\n * instead, which is the stored, durable copy.\n */\n async runConsole(runId: string, input: { tailBytes?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunConsoleDocument,\n { id: runId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.runConsole;\n }\n\n /**\n * The bounded end of a finished run's stored transcript (secrets\n * redacted). `available` is false until the run settles and the transcript\n * is copied out of the VM's console file — check `run.transcriptAvailable`\n * or poll this after {@link waitForRun} resolves.\n */\n async runTranscript(runId: string, input: { tailBytes?: number } = {}, options?: RequestOptions) {\n const data = await this.client.query(\n ops.RunTranscriptDocument,\n { id: runId, tailBytes: input.tailBytes ?? null },\n options,\n );\n return data.runTranscript;\n }\n\n /* -------------------------------------------------------------- internals */\n\n /**\n * Finds a visible workspace by name, the way the server compares names.\n *\n * The server rejects duplicates with Go's `strings.EqualFold`, so matching\n * must be case-insensitive here too or `ensureWorkspace` would try to create\n * a \"new\" workspace the server considers a duplicate. An exact-case hit wins\n * over a folded one, which only matters if a name ever slipped past the\n * uniqueness check.\n */\n async #findWorkspaceByName(\n name: string,\n options?: RequestOptions,\n ): Promise<Workspace | undefined> {\n const workspaces = await this.listWorkspaces(options);\n const folded = name.toLowerCase();\n return (\n workspaces.find((w) => w.name === name) ??\n workspaces.find((w) => w.name.toLowerCase() === folded)\n );\n }\n\n /** Set once the platform turned out to predate writeWorkspaceFiles. */\n #legacyWrites = false;\n /** Set once the platform turned out to predate the server-side deployment wait. */\n #noServerWait = false;\n\n /** One request of {@link writeFiles}: one call of the batch mutation, one commit. */\n async #writeBatch(\n workspaceId: string,\n batch: NormalizedFile[],\n commitMessage: string | undefined,\n requestOptions: RequestOptions,\n ): Promise<BatchOutcome> {\n try {\n const data = await this.client.mutate(\n ops.WriteFilesDocument,\n {\n workspaceID: workspaceId,\n files: batch.map((f) => ({\n path: f.path,\n content: f.content,\n ...(f.kind === \"base64\" ? { encoding: \"base64\" } : {}),\n })),\n commitMessage: commitMessage ?? null,\n },\n requestOptions,\n );\n const out = data.writeWorkspaceFiles;\n return {\n files: out.files.map((f) => ({ path: f.path, ok: f.ok, error: f.error ?? null, file: f.file ?? null })),\n written: out.written,\n failed: out.failed,\n totalBytes: out.totalBytes,\n commit: out.commit ?? null,\n };\n } catch (e) {\n if (!isUnsupportedField(e, \"writeWorkspaceFiles\") && !isUnsupportedField(e, \"WorkspaceFileWriteInput\")) throw e;\n // A platform older than the batch mutation: one mutation per file, as\n // before 0.8.0. It reports no commit.\n this.#legacyWrites = true;\n return this.#writeBatchLegacy(workspaceId, batch, requestOptions);\n }\n }\n\n /**\n * The pre-0.8.0 batch: one document with one ALIASED single-file mutation\n * per file. One request, but one commit per file on an app with platform\n * git, and no commit in the answer. Used only against platforms without\n * writeWorkspaceFiles.\n */\n async #writeBatchLegacy(\n workspaceId: string,\n batch: NormalizedFile[],\n requestOptions: RequestOptions,\n ): Promise<BatchOutcome> {\n const varDefs = [\"$workspaceID: ID!\"];\n const fields: string[] = [];\n const variables: Record<string, string> = { workspaceID: workspaceId };\n\n batch.forEach((file, i) => {\n variables[`p${i}`] = file.path;\n variables[`c${i}`] = file.content;\n varDefs.push(`$p${i}: String!`, `$c${i}: String!`);\n fields.push(\n file.kind === \"text\"\n ? ` f${i}: writeWorkspaceTextFile(input: { workspaceID: $workspaceID, path: $p${i}, text: $c${i} }) { file { ${FILE_SELECTION} } }`\n : ` f${i}: writeWorkspaceBase64File(input: { workspaceID: $workspaceID, path: $p${i}, contentBase64: $c${i} }) { file { ${FILE_SELECTION} } }`,\n );\n });\n\n // Built at runtime rather than codegen'd: the field COUNT varies per call,\n // so no static document can express it. The field shapes are still fixed,\n // and each individual mutation is codegen-validated by its single-file\n // twin in operations.ts.\n const document = `mutation SdkWriteFilesBatch(${varDefs.join(\", \")}) {\\n${fields.join(\"\\n\")}\\n}`;\n\n let data: Record<string, { file: WorkspaceFile } | null>;\n let errors: GraphQLResponseError[] = [];\n try {\n data = await this.client.mutate<Record<string, { file: WorkspaceFile } | null>, typeof variables>(\n document,\n variables,\n requestOptions,\n );\n } catch (e) {\n // Fields answered independently: keep what landed, name what did not.\n if (!(e instanceof UnfazedGraphQLError) || !e.data) throw e;\n data = e.data as Record<string, { file: WorkspaceFile } | null>;\n errors = e.errors;\n }\n const files = batch.map((f, i): FileWriteOutcome => {\n const file = data[`f${i}`]?.file ?? null;\n if (file) return { path: f.path, ok: true, error: null, file };\n const error = errors.find((x) => x.path?.[0] === `f${i}`)?.message ?? \"not written\";\n return { path: f.path, ok: false, error, file: null };\n });\n const written = files.filter((f) => f.ok);\n return {\n files,\n written: written.length,\n failed: files.length - written.length,\n totalBytes: written.reduce((sum, f) => sum + (f.file?.sizeBytes ?? 0), 0),\n commit: null,\n };\n }\n}\n\n/** One request's share of a {@link WriteFilesResult}. */\ninterface BatchOutcome {\n files: FileWriteOutcome[];\n written: number;\n failed: number;\n totalBytes: number;\n commit: FileCommit | null;\n}\n\n/** The platform's per-call limits of writeWorkspaceFiles (MCP's too). */\nconst MAX_BATCH_FILES = 100;\nconst MAX_BATCH_BYTES = 32 * 1024 * 1024;\n\n/** One server-side wait's budget, under the ~60 s a proxy or client allows a request. */\nconst SERVER_WAIT_SECONDS = 45;\n\n/** How the platform says an app keeps no history in platform git. */\nconst NO_PLATFORM_GIT = /platform git is not enabled|its history is there|has no git repository/i;\n\n/** The enum lists only the events it was written for; anything newer is UNKNOWN there. */\nfunction toDeploymentEvent(event: SdkDeploymentEventsQuery[\"deploymentEvents\"][number]): DeploymentEvent {\n return {\n id: event.id,\n deploymentID: event.deploymentID,\n type: event.rawType,\n typeEnum: event.type,\n rawType: event.rawType,\n severity: event.severity,\n message: event.message,\n vmID: event.vmID ?? null,\n metadata: (event.metadata as Record<string, string> | null | undefined) ?? null,\n createdAt: event.createdAt,\n };\n}\n\n/**\n * A deploy's phases from its events: `deployment.phases` (written when it went\n * READY: build, promotion and its split, total) over `deployment.build_finished`\n * (the build VM's own phases). Every `*_ms` field becomes a number. Null when\n * neither event is there.\n */\nexport function parseDeploymentTimings(events: readonly Pick<DeploymentEvent, \"type\" | \"metadata\">[]): PlatformTimings | null {\n const latest = (type: string) => [...events].reverse().find((e) => e.type === type)?.metadata ?? null;\n const build = latest(\"deployment.build_finished\");\n const ready = latest(\"deployment.phases\");\n if (!build && !ready) return null;\n const merged: Record<string, string> = { ...build, ...ready };\n const ms = (name: string): number | null => {\n const value = merged[`${name}_ms`];\n if (value === undefined) return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n };\n const phases: Record<string, number> = {};\n for (const [key, value] of Object.entries(merged)) {\n if (!key.endsWith(\"_ms\")) continue;\n const name = key.slice(0, -3);\n if (name === \"total\" || name === \"build\" || name === \"promote\") continue;\n const n = Number(value);\n if (Number.isFinite(n)) phases[name] = n;\n }\n const memory = Number(merged[\"build_memory_mib\"]);\n return {\n totalMs: ready ? ms(\"total\") : null,\n buildMs: ms(\"build\"),\n promoteMs: ms(\"promote\"),\n phases,\n buildMode: merged[\"build_mode\"] ?? null,\n artifactTransport: merged[\"artifact_transport\"] ?? null,\n buildMemoryMiB: Number.isFinite(memory) && merged[\"build_memory_mib\"] !== undefined ? memory : null,\n };\n}\n\nfunction errorGroupInput(ref: ErrorGroupRef) {\n return { workspaceID: ref.workspaceId, alias: ref.alias, groupID: ref.groupId };\n}\n\nfunction eventsInput(input: EventsInput) {\n return {\n ...(input.names === undefined ? {} : { names: input.names }),\n ...(input.arguments === undefined ? {} : { arguments: input.arguments }),\n ...(input.cursor === undefined ? {} : { cursor: input.cursor }),\n ...(input.max === undefined ? {} : { max: input.max }),\n };\n}\n\nconst FILE_SELECTION = \"path sizeBytes size sha256 updatedAt\";\nconst ENV_SELECTION = \"name value secret alias inherited masked updatedAt\";\n\n/**\n * Terminal = anything but QUEUED or RUNNING, defined negatively exactly like\n * the platform's own `IsTerminalRunStatus` — so a future status this SDK does\n * not know about yet still ends a wait instead of polling forever.\n */\nfunction isTerminalRunStatus(status: string): boolean {\n return status !== \"QUEUED\" && status !== \"RUNNING\";\n}\n\ninterface NormalizedFile {\n path: string;\n kind: \"text\" | \"base64\";\n content: string;\n}\n\nfunction normalizeFile(path: string, content: FileContent): NormalizedFile {\n if (typeof content === \"string\") return { path, kind: \"text\", content };\n if (\"text\" in content) return { path, kind: \"text\", content: content.text };\n if (\"base64\" in content) return { path, kind: \"base64\", content: content.base64 };\n return { path, kind: \"base64\", content: toBase64(content.bytes) };\n}\n\nfunction toBase64(input: Uint8Array | ArrayBuffer): string {\n const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);\n // Node/Bun have Buffer; browsers and workers do not.\n const maybeBuffer = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(e: string): string } } })\n .Buffer;\n if (maybeBuffer) return maybeBuffer.from(bytes).toString(\"base64\");\n\n let binary = \"\";\n const CHUNK = 0x8000; // avoid blowing the argument limit on large files\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary);\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * UTF-8 byte length, which is what the wire actually costs.\n *\n * `String.length` counts UTF-16 code units and undercounts by up to 3x on\n * non-ASCII text — a CJK or emoji-heavy payload would sail past a budget it\n * had already blown.\n */\nfunction utf8Bytes(s: string): number {\n return utf8.encode(s).length;\n}\n\n/**\n * Splits files into request-sized batches.\n *\n * Closes a batch on whichever limit trips first — count or bytes — but always\n * emits at least one file per batch, so a single file larger than\n * `maxBatchBytes` still gets sent (and fails loudly at the server's limit)\n * rather than silently vanishing into an empty batch.\n */\nfunction chunkFiles(\n files: NormalizedFile[],\n batchSize: number,\n maxBatchBytes: number,\n): NormalizedFile[][] {\n const batches: NormalizedFile[][] = [];\n let current: NormalizedFile[] = [];\n let bytes = 0;\n\n for (const file of files) {\n // Measured once per file, so the encode cost is linear in the payload the\n // request was going to carry anyway.\n const size = utf8Bytes(file.content) + utf8Bytes(file.path);\n if (current.length > 0 && (current.length >= batchSize || bytes + size > maxBatchBytes)) {\n batches.push(current);\n current = [];\n bytes = 0;\n }\n current.push(file);\n bytes += size;\n }\n if (current.length > 0) batches.push(current);\n return batches;\n}\n"]}