@idyl-sh/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +188 -2
- package/dist/computer-connection.d.ts +200 -0
- package/dist/computer-connection.js +1019 -0
- package/dist/computer-connection.js.map +1 -0
- package/dist/computer-connection.wasm +0 -0
- package/dist/index.cjs +14636 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +5146 -0
- package/dist/index.d.ts +5146 -0
- package/dist/index.js +14563 -0
- package/dist/index.js.map +1 -0
- package/package.json +105 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api/billing-errors.ts","../src/api/storage-errors.ts","../src/errors.ts","../src/internal/abort.ts","../src/resource/decode-error.ts","../src/internal/strictdecode.ts","../src/resource/base64.ts","../src/internal/dpop.ts","../src/resource/validation.ts","../src/internal/endpoints.ts","../src/resource/json.ts","../src/resource/id.ts","../src/api/network.ts","../src/internal/apipath.ts","../src/internal/placement.ts","../src/internal/version.ts","../src/client-product.ts","../src/credential.ts","../src/internal/browser.ts","../src/internal/transport.ts","../src/resource/workload-network.ts","../src/resource/egress-allow-rule.ts","../src/resource/shapes.ts","../src/resource/secret.ts","../src/internal/options.ts","../src/services/account.ts","../src/resource/byte-quantity.ts","../src/resource/cpu.ts","../src/resource/memory.ts","../src/resource/micropod-network.ts","../src/resource/uuid-id.ts","../src/resource/computer-execution-settings.ts","../src/resource/volume.ts","../src/api/computer-size.ts","../src/internal/envelopes.ts","../src/services/computer-sizes.ts","../src/services/identity.ts","../src/client/access-key-file.ts","../src/internal/unwrap.ts","../src/services/access-keys.ts","../src/client/common.ts","../src/client/access-keys.ts","../src/resource/duration.ts","../src/api/computer-cell-save.ts","../src/api/computer-notebook-name.ts","../src/api/computer-session-endpoint.ts","../src/api/workload-session.ts","../src/api/computer-session.ts","../src/api/billing.ts","../src/api/storage.ts","../src/internal/listquery.ts","../src/services/billing.ts","../src/client/records.ts","../src/client/billing.ts","../src/api/wait.ts","../src/resource/idle-timeout.ts","../src/api/computer-owner.ts","../src/api/files.ts","../src/api/upload-transfer.ts","../src/resource/sha256.ts","../src/internal/storage-upload.ts","../src/api/file-status.ts","../src/internal/routing.ts","../src/services/storage.ts","../src/api/computer-operations.ts","../src/services/computer-operations.ts","../src/api/computer-awake.ts","../src/api/computer-recovery.ts","../src/resource/storage.ts","../src/resource/computer.ts","../src/api/computer-image.ts","../src/api/computer.ts","../src/internal/zone.ts","../src/wait.ts","../src/api/computer-cell.ts","../src/api/computer-execution-settings.ts","../src/api/journal.ts","../src/services/computer-journal.ts","../src/api/computer-secrets.ts","../src/services/computer-secrets.ts","../src/services/computer-sessions.ts","../src/services/computers.ts","../src/api/vault.ts","../src/services/vault-secrets.ts","../src/client/decryptions.ts","../src/client/download.ts","../src/client/files.ts","../src/client/secrets.ts","../src/client/settings.ts","../src/api/computer-session-host-key.ts","../src/computer-connection/frames.ts","../src/computer-connection/files.ts","../src/computer-connection/trust.ts","../src/computer-connection/trust-floor.ts","../src/computer-connection/connector.ts","../src/client/connections.ts","../src/client/exec.ts","../src/client/terminal.ts","../src/services/computer-endpoint-sessions.ts","../src/client/computer.ts","../src/client/identity.ts","../src/client/network-trust.ts","../src/client/idyl.ts","../src/client/codes.ts"],"names":["text","milliseconds","field","parsed","pending","array","bytes","identity","served","problem","envelope","namespace","variables","attachments","image","asRecord","isRecord","account","publicMembers","exchange","count","optional","isDigit","instant","micros","value","billing","padded","hash","UINT64_MAX","closed","facts","retryable","signal","upload","options","mode","watch","listed","encoder","versionOf","objectOf","updateRequest","integer","json","decoder","payload","isCleanAbsolutePath","utf8","session","verified","SETTLE_POLL_MS","selector","offsetOf","service","computers","profiles","ERROR_CODE_SESSION_FINAL","ERROR_CODE_SIZE_BELOW_USAGE","ERROR_CODE_VERSION_NOT_FOUND","ERROR_CODE_UPLOAD_CONFLICT","ERROR_CODE_UPLOAD_EXPIRED","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. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The codes below refuse a request, or fail an operation, because of an\n * Account's billing. Each is carried by the structured API error, and\n * clients classify on the code, never on the message. A refused request\n * changes nothing. The helpers that read each refusal's details, and the\n * details types they return, are `isOutOfUsage`, `sizeNotInPlan`,\n * `sizeBelowUsage` and `spendCapReached` beside the error classes.\n */\n\n/**\n * Returned with HTTP 402 when a Computer's Account has used its month's\n * allowance and its extra usage, and auto-refill cannot buy more (standing\n * `out`). It refuses a session at once, and fails a wake and a pending\n * session (reason `OUT_OF_USAGE`). It carries no details. A purchase, an upgrade or the\n * start of the Account's next period lets its Computers wake again.\n */\nexport const ERROR_CODE_OUT_OF_USAGE = \"OUT_OF_USAGE\";\n\n/**\n * Returned with HTTP 402 when a wake, or a change of a Computer's CPU and\n * memory to a larger size, names a size larger than the Account's plan\n * includes. A change to a size no larger than the Computer's own is never\n * refused with this error. It refuses a resize at once, and fails a wake and\n * a pending session (reason `SIZE_NOT_IN_PLAN`). The details carry the keys\n * {@link SIZE_NOT_IN_PLAN_DETAIL_SIZE},\n * {@link SIZE_NOT_IN_PLAN_DETAIL_LARGEST_SIZE},\n * {@link SIZE_NOT_IN_PLAN_DETAIL_PLAN} and\n * {@link SIZE_NOT_IN_PLAN_DETAIL_PLAN_NAME}; see `SizeNotInPlanDetails`. A\n * resize to a size the plan includes, or an upgrade to the plan named, lets the\n * Computer wake.\n */\nexport const ERROR_CODE_SIZE_NOT_IN_PLAN = \"SIZE_NOT_IN_PLAN\";\n\n/**\n * The reason a wake fails when it would take the vCPU of the Account's awake\n * Computers past what its plan allows at once. It fails a wake and a\n * pending session (reason `VCPU_LIMIT_REACHED`). It carries no details. Computers already awake keep\n * running. Putting another Computer to sleep, or upgrading to a plan with a\n * higher limit, lets the Computer wake. The count can briefly lag a change, so\n * a wake just after a sleep can fail with it and succeed when asked again.\n */\nexport const ERROR_CODE_VCPU_LIMIT_REACHED = \"VCPU_LIMIT_REACHED\";\n\n/**\n * Returned with HTTP 429 and `Retry-After` when an Account with a download limit\n * has downloaded as much of its saved files as one window allows. An Account has\n * a limit on a free trial, on no plan, and on a paid plan while it is out of\n * usage. It refuses a download at once, and a download under way ends when it\n * passes the limit. The details carry `limitBytes` and `usedBytes`. A new window\n * opens when `Retry-After` has passed. On a paid plan, a purchase, an upgrade or\n * the start of the Account's next period lifts the limit.\n */\nexport const ERROR_CODE_DOWNLOAD_LIMIT_REACHED = \"DOWNLOAD_LIMIT_REACHED\";\n\n/**\n * The reason a plan change or a purchase failed because the card was\n * declined, or could not be charged without the user, as an auto-refill\n * cannot. The plan in force is unchanged and nothing was charged. It is\n * also why auto-refill was turned off (`BillingAutoRefillStop`). The card\n * is changed in a portal session.\n */\nexport const ERROR_CODE_PAYMENT_DECLINED = \"PAYMENT_DECLINED\";\n\n/**\n * Why auto-refill was turned off when a payment of the Account was\n * disputed with its card's issuer (`BillingAutoRefillStop`).\n */\nexport const ERROR_CODE_PAYMENT_DISPUTED = \"PAYMENT_DISPUTED\";\n\n/**\n * The reason a plan change or a purchase failed because its\n * `BillingAction` expired before the user completed the payment. Nothing\n * was charged; a new change or purchase starts again.\n */\nexport const ERROR_CODE_ACTION_EXPIRED = \"ACTION_EXPIRED\";\n\n/**\n * The reason a pending plan change failed because a later plan change of\n * the Account replaced it. No charge was made.\n */\nexport const ERROR_CODE_PLAN_CHANGE_SUPERSEDED = \"PLAN_CHANGE_SUPERSEDED\";\n\n/**\n * The reason an upgrade failed because the platform could not make it as\n * priced. The plan in force is unchanged and nothing was charged. The same\n * change can be made again later.\n */\nexport const ERROR_CODE_PLAN_CHANGE_UNAVAILABLE = \"PLAN_CHANGE_UNAVAILABLE\";\n\n/**\n * Returned with HTTP 422 when a plan change names a plan the platform does\n * not offer: one `AccountBillingStatus.plans` does not list.\n */\nexport const ERROR_CODE_PLAN_NOT_OFFERED = \"PLAN_NOT_OFFERED\";\n\n/**\n * Returned with HTTP 402 when a purchase of extra usage, or an update that\n * turns auto-refill on, is made on a plan that does not include extra\n * usage (`BillingPlanOffer.extraUsage`). It carries no details. An upgrade\n * to a plan that includes it lets the Account buy.\n */\nexport const ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN = \"EXTRA_USAGE_NOT_IN_PLAN\";\n\n/**\n * Returned with HTTP 409 when a purchase of extra usage would take what\n * the current period has bought, purchases paid and pending, past the\n * Account's spend cap. The details carry the keys\n * {@link SPEND_CAP_REACHED_DETAIL_SPEND_CAP} and\n * {@link SPEND_CAP_REACHED_DETAIL_BOUGHT}; see\n * `SpendCapReachedDetails`. A higher cap, a smaller amount or the\n * next period lets the purchase through.\n */\nexport const ERROR_CODE_SPEND_CAP_REACHED = \"SPEND_CAP_REACHED\";\n\n/**\n * Returned with HTTP 422 when an update would leave auto-refill on with no\n * spend cap set: auto-refill never buys without a cap. It carries no\n * details.\n */\nexport const ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP =\n \"AUTO_REFILL_NEEDS_SPEND_CAP\";\n\n/** The details key of a `SIZE_NOT_IN_PLAN` refusal naming the size refused, a `ComputerSize` string. */\nexport const SIZE_NOT_IN_PLAN_DETAIL_SIZE = \"size\";\n\n/**\n * The details key of a `SIZE_NOT_IN_PLAN` refusal naming the largest size\n * the Account's plan includes, a `ComputerSize` string.\n */\nexport const SIZE_NOT_IN_PLAN_DETAIL_LARGEST_SIZE = \"largestSize\";\n\n/**\n * The details key of a `SIZE_NOT_IN_PLAN` refusal naming the smallest plan\n * that includes the size, a `BillingPlan` string. It is absent when no plan\n * includes it.\n */\nexport const SIZE_NOT_IN_PLAN_DETAIL_PLAN = \"plan\";\n\n/**\n * The details key of a `SIZE_NOT_IN_PLAN` refusal naming that plan's name\n * for display, such as `Max 5x`, a string. It is absent when no plan\n * includes the size.\n */\nexport const SIZE_NOT_IN_PLAN_DETAIL_PLAN_NAME = \"planName\";\n\n/** The details key of a `SPEND_CAP_REACHED` refusal naming the Account's spend cap, in micro-dollars. */\nexport const SPEND_CAP_REACHED_DETAIL_SPEND_CAP = \"spendCapMicros\";\n\n/**\n * The details key of a `SPEND_CAP_REACHED` refusal naming what the current\n * period has bought, purchases paid and pending, before the refused\n * purchase, in micro-dollars.\n */\nexport const SPEND_CAP_REACHED_DETAIL_BOUGHT = \"boughtMicros\";\n\n/**\n * The details key of a `SIZE_BELOW_USAGE` refusal naming the bytes the\n * resource's current files use, a whole number. Earlier versions do not\n * count.\n */\nexport const SIZE_BELOW_USAGE_DETAIL_USED_BYTES = \"usedBytes\";\n\n/**\n * The details key of a `SIZE_BELOW_USAGE` refusal naming the size the\n * refused change would leave for those files, in bytes, a whole number.\n */\nexport const SIZE_BELOW_USAGE_DETAIL_SIZE_BYTES = \"sizeBytes\";\n\n/**\n * The details key of a `SIZE_BELOW_USAGE` refusal naming the\n * `ComputerSize` the refused change names, a string. It is present only\n * when the refusal is of a change to a Computer's CPU and memory.\n */\nexport const SIZE_BELOW_USAGE_DETAIL_COMPUTER_SIZE = \"computerSize\";\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/** Storage error codes classify API refusals; clients never parse human messages. */\n/**\n * Refuses, with HTTP 409, a size smaller than the resource's measured\n * referenced bytes: a storage size, or a change of a Computer's CPU and\n * memory to a size whose disk cannot hold its current files. Earlier\n * versions do not count. The details carry the keys\n * `SIZE_BELOW_USAGE_DETAIL_USED_BYTES` and\n * `SIZE_BELOW_USAGE_DETAIL_SIZE_BYTES`, and, for a Computer's size,\n * `SIZE_BELOW_USAGE_DETAIL_COMPUTER_SIZE`; see `SizeBelowUsageDetails`.\n * Freeing space lets the change through.\n */\nexport const ERROR_CODE_SIZE_BELOW_USAGE = \"SIZE_BELOW_USAGE\";\n\n/** ErrorCodeSizeAboveCap refuses a requested size above the applicable Account or Subnet cap. */\nexport const ERROR_CODE_SIZE_ABOVE_CAP = \"SIZE_ABOVE_CAP\";\n\n/** ErrorCodeHeadMoved reports that the selected files head changed before the operation could act. */\nexport const ERROR_CODE_HEAD_MOVED = \"HEAD_MOVED\";\n\n/** ErrorCodeUploadExpired reports an upload whose inactivity deadline ended its publication eligibility. */\nexport const ERROR_CODE_UPLOAD_EXPIRED = \"UPLOAD_EXPIRED\";\n\n/** ErrorCodeUploadCancelled reports a cancelled upload, which can no longer publish. */\nexport const ERROR_CODE_UPLOAD_CANCELLED = \"UPLOAD_CANCELLED\";\n\n/** ErrorCodeUploadConflict reports overlapping file changes since the upload base; the upload ends in conflict. */\nexport const ERROR_CODE_UPLOAD_CONFLICT = \"UPLOAD_CONFLICT\";\n\n/** ErrorCodeChangeSequenceMismatch refuses reuse of an accepted change sequence with a different fingerprint. */\nexport const ERROR_CODE_CHANGE_SEQUENCE_MISMATCH = \"CHANGE_SEQUENCE_MISMATCH\";\n\n/** ErrorCodeVersionNotFound reports a version number or name absent from the addressed resource. */\nexport const ERROR_CODE_VERSION_NOT_FOUND = \"VERSION_NOT_FOUND\";\n\n/** ErrorCodeResultExpired reports a result payload no longer retained; it does not grant a repeated effect. */\nexport const ERROR_CODE_RESULT_EXPIRED = \"RESULT_EXPIRED\";\n\n/** ErrorCodeForkCrossNamespace refuses a fork across Namespace authority boundaries. */\nexport const ERROR_CODE_FORK_CROSS_NAMESPACE = \"FORK_CROSS_NAMESPACE\";\n\n/** ErrorCodeForkNotQuiescent refuses a fork whose source cannot establish the required copy point. */\nexport const ERROR_CODE_FORK_NOT_QUIESCENT = \"FORK_NOT_QUIESCENT\";\n\n/** ErrorCodePathInvalid refuses a structurally invalid byte path or a mutation of reserved runtime state. */\nexport const ERROR_CODE_PATH_INVALID = \"PATH_INVALID\";\n\n/** ErrorCodeNameNotNFC refuses a newly created name that is not UTF-8 NFC; existing byte names remain addressable. */\nexport const ERROR_CODE_NAME_NOT_NFC = \"NAME_NOT_NFC\";\n\n/** ErrorCodeStorageNotOpen refuses storage operations for an Account whose storage feature is not open. */\nexport const ERROR_CODE_STORAGE_NOT_OPEN = \"STORAGE_NOT_OPEN\";\n\n/** Storage pending reasons describe the prerequisite the resource is waiting for. */\nexport const STORAGE_PENDING_REASON_WAITING_FOR_DISK = \"WaitingForDisk\";\n\n/** StoragePendingReasonNoViewCapableNode waits for capacity that advertises verified views. */\nexport const STORAGE_PENDING_REASON_NO_VIEW_CAPABLE_NODE = \"NoViewCapableNode\";\n\n/** StoragePendingReasonWaitingForVersion waits until the machine has applied the requested floor. */\nexport const STORAGE_PENDING_REASON_WAITING_FOR_VERSION = \"WaitingForVersion\";\n\n/** Refuses a transfer part that skips the accepted contiguous prefix. */\nexport const ERROR_CODE_CHANGE_SEQUENCE_GAP = \"CHANGE_SEQUENCE_GAP\";\n/** Refuses a part or completion digest that differs from accepted bytes. */\nexport const ERROR_CODE_UPLOAD_DIGEST_MISMATCH = \"UPLOAD_DIGEST_MISMATCH\";\n/** Refuses a request body above the transfer's advertised per-part budget. */\nexport const ERROR_CODE_UPLOAD_PART_TOO_LARGE = \"UPLOAD_PART_TOO_LARGE\";\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/**\n * How the package reports a failure. Every failure is an error class a\n * caller classifies by its class and its stable code; a message is for\n * people and is never a contract.\n *\n * - An invalid argument or option throws a `TypeError` naming the field,\n * before any request is sent.\n * - A request IDYL refuses rejects with an {@link ApiError}. Its `code` is\n * stable: classify it with {@link isApiCode} and the `ERROR_CODE_*`\n * constants, never by its message. {@link ComputerNotAwakeError} is the\n * code with a class of its own.\n * - A request that does not complete rejects with a\n * {@link TransportError}, classified by its `code`.\n * - A command that ends other than with exit code 0 rejects with an\n * {@link ExitError}, one whose changes cannot be saved with a\n * {@link CommandSaveError}, and one whose session fails before its end\n * is known with a {@link CommandSessionError}.\n * - A Computer session that ends before it opens is a\n * {@link ComputerSessionEndedError}, a session trust bundle the client\n * refuses is a {@link SessionTrustError}, and a session frame that cannot\n * be read is a {@link FrameError}.\n *\n * A cancelled call rejects with its signal's reason.\n *\n * @example\n * ```ts\n * import { ERROR_CODE_INSUFFICIENT_CAPACITY, isApiCode } from \"@idyl-sh/sdk\";\n *\n * try {\n * await computer.wake();\n * } catch (error) {\n * if (!isApiCode(error, ERROR_CODE_INSUFFICIENT_CAPACITY)) throw error;\n * // No machine has room for the Computer; a later wake may succeed.\n * }\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { JsonObject } from \"./resource/json.js\";\nimport { ERROR_CODE_CLIENT_UPGRADE_REQUIRED } from \"./api/types.js\";\nimport type { UploadTransfer } from \"./api/upload-transfer.js\";\nimport type { BillingPlan, ComputerSize } from \"./api/billing.js\";\nimport {\n ERROR_CODE_OUT_OF_USAGE,\n ERROR_CODE_SIZE_NOT_IN_PLAN,\n ERROR_CODE_SPEND_CAP_REACHED,\n SIZE_BELOW_USAGE_DETAIL_COMPUTER_SIZE,\n SIZE_BELOW_USAGE_DETAIL_SIZE_BYTES,\n SIZE_BELOW_USAGE_DETAIL_USED_BYTES,\n SIZE_NOT_IN_PLAN_DETAIL_LARGEST_SIZE,\n SIZE_NOT_IN_PLAN_DETAIL_PLAN,\n SIZE_NOT_IN_PLAN_DETAIL_PLAN_NAME,\n SIZE_NOT_IN_PLAN_DETAIL_SIZE,\n SPEND_CAP_REACHED_DETAIL_BOUGHT,\n SPEND_CAP_REACHED_DETAIL_SPEND_CAP,\n} from \"./api/billing-errors.js\";\nimport { ERROR_CODE_SIZE_BELOW_USAGE } from \"./api/storage-errors.js\";\n\n/** What a non-2xx response carried. */\nexport interface ApiErrorOptions {\n /** The response's HTTP status. */\n readonly status: number;\n /**\n * The server's message, which the error carries as `detail`; the empty\n * string when the response carried none.\n */\n readonly message: string;\n /** The stable error code, when the response carried one. */\n readonly code?: string;\n /** The structured context the code documents, when the response carried any. */\n readonly details?: JsonObject;\n /** The server's request identifier, when the response carried one. */\n readonly requestId?: string;\n /** The delay `Retry-After` advertised, in milliseconds, when the response carried one. */\n readonly retryAfterMs?: number;\n /** The failure behind this one, which the error carries as `cause`. */\n readonly cause?: unknown;\n}\n\n/**\n * A request IDYL refused: a non-2xx response from the IDYL API. `code` is\n * what a caller branches on. `message` is the sentence composed for logs\n * from the status and the code; it never carries `detail`, and is not a\n * contract either.\n *\n * Match it with `instanceof`, or classify it with {@link isApiCode}.\n */\nexport class ApiError extends Error {\n /** The response's HTTP status. */\n readonly status: number;\n /** The stable error code, when the endpoint publishes one. */\n declare readonly code?: string;\n /**\n * The server's message: prose for a person, never parsed, and absent\n * when the response carried none. When the error body could not be read\n * it is the sentence that says so, and on a route held to a disclosure\n * allow-list it is the fixed sentence `request failed` outside the\n * listed codes.\n */\n declare readonly detail?: string;\n /**\n * Structured context, where the code documents one; {@link sizeNotInPlan},\n * {@link sizeBelowUsage} and {@link spendCapReached} are its readers.\n */\n declare readonly details?: JsonObject;\n /** The server's request identifier, when it returned one. */\n declare readonly requestId?: string;\n /** The delay the server advertised through `Retry-After`, in milliseconds, when it sent one. */\n declare readonly retryAfterMs?: number;\n\n /**\n * Builds the error from what a non-2xx response carried. The package\n * builds every `ApiError` it rejects with; a caller builds one to stand\n * in for a refusal, as in a test.\n */\n constructor(options: ApiErrorOptions) {\n super(describeApiError(options), causeOption(options.cause));\n this.name = \"ApiError\";\n this.status = options.status;\n if (options.code !== undefined) this.code = options.code;\n if (options.message !== \"\") this.detail = options.message;\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.retryAfterMs !== undefined) {\n this.retryAfterMs = options.retryAfterMs;\n }\n }\n}\n\n/**\n * The message of an API error: the status and, when it has the shape of a\n * stable code, the code. The server's own message is carried in `detail`\n * and never reaches the message, so nothing a server wrote is logged by a\n * caller that logs errors.\n */\nfunction describeApiError(options: ApiErrorOptions): string {\n const status = describeStatus(options.status);\n const code = options.code ?? \"\";\n return /^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(code)\n ? `IDYL API: ${status}: ${code}`\n : `IDYL API: ${status}`;\n}\n\n/**\n * The platform's refusal of a `files` session on a Computer that is not\n * awake, carrying `COMPUTER_NOT_AWAKE` with HTTP 409. The refusal neither\n * wakes the Computer nor keeps it awake; a caller lists the Computer's\n * saved files instead.\n */\nexport class ComputerNotAwakeError extends ApiError {\n /** Builds the error from what the refusal carried. */\n constructor(options: ApiErrorOptions) {\n super(options);\n this.name = \"ComputerNotAwakeError\";\n }\n}\n\n/** The code on {@link ComputerNotAwakeError}. */\nconst COMPUTER_NOT_AWAKE = \"COMPUTER_NOT_AWAKE\";\n\n/**\n * Builds the error a non-2xx response becomes: a\n * {@link ComputerNotAwakeError} for `COMPUTER_NOT_AWAKE`, an\n * {@link ApiError} otherwise.\n */\nexport function apiError(options: ApiErrorOptions): ApiError {\n switch (options.code) {\n case COMPUTER_NOT_AWAKE:\n return new ComputerNotAwakeError(options);\n default:\n return new ApiError(options);\n }\n}\n\n/**\n * Why a request did not complete. The vocabulary is closed and only grows.\n *\n * - `network_error`: the request failed before any response: a refused\n * connection, a reset, a failed name lookup, or a TLS failure.\n * - `timeout`: the request did not complete within the client's request\n * timeout.\n * - `redirect_refused`: the server answered with a redirect. The package\n * never follows one, so a credential is never replayed to a host the\n * server chose.\n * - `response_too_large`: the response body exceeds the package's bound.\n * - `invalid_response`: the response cannot be used: it is not exactly one\n * JSON value, or it contradicts the request it answers.\n */\nexport type TransportErrorCode =\n | \"network_error\"\n | \"timeout\"\n | \"redirect_refused\"\n | \"response_too_large\"\n | \"invalid_response\";\n\n/**\n * A request that did not complete: no answer arrived from the platform, or\n * the answer could not be used. `code` classifies the error. The message is a\n * fixed sentence built from the code and, where one helps, a fixed detail\n * naming the rule that failed: it never carries a token, a command, its output,\n * or text a peer sent. `cause` carries the underlying failure when there is\n * one.\n *\n * A request that failed this way may or may not have reached the platform,\n * so the package never retries it, with one exception: the reads of\n * `files.download`, which change nothing and resume on their own.\n */\nexport class TransportError extends Error {\n /** Why the request did not complete. */\n readonly code: TransportErrorCode;\n\n /**\n * Builds the error. The package builds every `TransportError` it rejects\n * with; a caller builds one to stand in for a failed request, as in a\n * test.\n *\n * @param code why the request did not complete\n * @param message a fixed sentence naming the rule that failed, never\n * text a peer sent\n * @param options `cause`, the underlying failure, when there is one\n */\n constructor(\n code: TransportErrorCode,\n message: string,\n options?: { readonly cause?: unknown },\n ) {\n super(message, causeOption(options?.cause));\n this.name = \"TransportError\";\n this.code = code;\n }\n}\n\n/** Reports whether `error` is an HTTP 404 {@link ApiError}. */\nexport function isNotFound(error: unknown): error is ApiError {\n return isApiStatus(error, 404);\n}\n\n/** Reports whether `error` is an {@link ApiError} with the given HTTP status. */\nexport function isApiStatus(error: unknown, status: number): error is ApiError {\n return error instanceof ApiError && error.status === status;\n}\n\n/**\n * Reports whether `error` is an {@link ApiError} carrying the given stable code.\n *\n * @param error any value a `catch` receives\n * @param code the stable code to match, such as an `ERROR_CODE_*` constant\n */\nexport function isApiCode(error: unknown, code: string): error is ApiError {\n return error instanceof ApiError && error.code === code;\n}\n\n/**\n * Reports whether `error` is the API's refusal of the product release a\n * request named in its `Idyl-Client` header as below the minimum it\n * supports: an {@link ApiError}, with HTTP 426 Upgrade Required, carrying\n * {@link ERROR_CODE_CLIENT_UPGRADE_REQUIRED}. The refusal's `details` name\n * the product, the minimum and latest versions, and the upgrade URL under\n * the `CLIENT_UPGRADE_REQUIRED_DETAIL_*` keys, each a string. See\n * `ClientProduct`.\n */\nexport function isClientUpgradeRequired(error: unknown): error is ApiError {\n return isApiCode(error, ERROR_CODE_CLIENT_UPGRADE_REQUIRED);\n}\n\n/**\n * The details of a `SIZE_NOT_IN_PLAN` refusal. A key the refusal does not\n * carry, or carries in another form, reads as the empty string.\n */\nexport interface SizeNotInPlanDetails {\n /** The size refused. */\n readonly size: ComputerSize;\n /** The largest size the Account's plan includes. */\n readonly largestSize: ComputerSize;\n /**\n * The smallest plan that includes `size`; the empty string when no plan\n * includes that size.\n */\n readonly plan: BillingPlan;\n /** That plan's name for display; the empty string when no plan includes `size`. */\n readonly planName: string;\n}\n\n/**\n * The details of a `SIZE_BELOW_USAGE` refusal. A key the refusal does not\n * carry, or carries in another form, reads as zero or the empty string.\n */\nexport interface SizeBelowUsageDetails {\n /** The bytes the resource's current files use. Earlier versions do not count. */\n readonly usedBytes: number;\n /** The bytes the refused size would leave for them. */\n readonly sizeBytes: number;\n /**\n * The size a refused Computer resize names; the empty string for any\n * other refusal.\n */\n readonly computerSize: ComputerSize;\n}\n\n/**\n * The details of a `SPEND_CAP_REACHED` refusal, each a whole number of\n * micro-dollars. The purchase the cap still allows is `spendCapMicros` less\n * `boughtMicros`, when that is positive. A key the refusal does not carry,\n * or carries in another form, reads as zero.\n */\nexport interface SpendCapReachedDetails {\n /** The Account's spend cap. */\n readonly spendCapMicros: number;\n /**\n * What the current period has bought, purchases paid and pending, before\n * the refused purchase.\n */\n readonly boughtMicros: number;\n}\n\n/**\n * Reports whether `error` is the refusal of a Computer's wake or session\n * because its Account has used its month's allowance and its extra usage:\n * an {@link ApiError}, with HTTP 402, carrying `ERROR_CODE_OUT_OF_USAGE`. A\n * wake or a session that fails later for the same cause carries the code as\n * its reason instead.\n *\n * @param error any value a `catch` receives\n */\nexport function isOutOfUsage(error: unknown): error is ApiError {\n return isApiCode(error, ERROR_CODE_OUT_OF_USAGE);\n}\n\n/**\n * The details of `error` when it is the refusal of a Computer's size as\n * larger than its Account's plan includes, an {@link ApiError} carrying\n * `ERROR_CODE_SIZE_NOT_IN_PLAN`: the size refused, the plan's largest size,\n * and the smallest plan that includes the size. `undefined` for any other\n * error. The details are read as a response is: a key the details do not\n * name is ignored, and a key the error does not carry, or carries in\n * another form, reads as the empty string.\n *\n * @param error any value a `catch` receives\n */\nexport function sizeNotInPlan(\n error: unknown,\n): SizeNotInPlanDetails | undefined {\n if (!isApiCode(error, ERROR_CODE_SIZE_NOT_IN_PLAN)) return undefined;\n const details = error.details;\n return Object.freeze({\n size: detailString(details, SIZE_NOT_IN_PLAN_DETAIL_SIZE),\n largestSize: detailString(details, SIZE_NOT_IN_PLAN_DETAIL_LARGEST_SIZE),\n plan: detailString(details, SIZE_NOT_IN_PLAN_DETAIL_PLAN),\n planName: detailString(details, SIZE_NOT_IN_PLAN_DETAIL_PLAN_NAME),\n });\n}\n\n/**\n * The details of `error` when it is the refusal of a size whose disk cannot\n * hold a resource's current files, an {@link ApiError} carrying\n * `ERROR_CODE_SIZE_BELOW_USAGE`: the bytes the files use, the bytes the size\n * holds, and, for a Computer's resize, the size it names. `undefined` for\n * any other error. The details are read as {@link sizeNotInPlan} reads its\n * own: a key carried in another form, a byte count below zero or past\n * `Number.MAX_SAFE_INTEGER` included, reads as zero or the empty string.\n *\n * @param error any value a `catch` receives\n */\nexport function sizeBelowUsage(\n error: unknown,\n): SizeBelowUsageDetails | undefined {\n if (!isApiCode(error, ERROR_CODE_SIZE_BELOW_USAGE)) return undefined;\n const details = error.details;\n return Object.freeze({\n usedBytes: detailCount(details, SIZE_BELOW_USAGE_DETAIL_USED_BYTES, 0),\n sizeBytes: detailCount(details, SIZE_BELOW_USAGE_DETAIL_SIZE_BYTES, 0),\n computerSize: detailString(details, SIZE_BELOW_USAGE_DETAIL_COMPUTER_SIZE),\n });\n}\n\n/**\n * The details of `error` when it is the refusal of a purchase of extra\n * usage that would pass the Account's spend cap, an {@link ApiError}\n * carrying `ERROR_CODE_SPEND_CAP_REACHED`: the cap and what the period has\n * bought, in micro-dollars. `undefined` for any other error. The details\n * are read as {@link sizeNotInPlan} reads its own: a key carried in another\n * form, an amount past the safe-integer range included, reads as zero.\n *\n * @param error any value a `catch` receives\n */\nexport function spendCapReached(\n error: unknown,\n): SpendCapReachedDetails | undefined {\n if (!isApiCode(error, ERROR_CODE_SPEND_CAP_REACHED)) return undefined;\n const details = error.details;\n return Object.freeze({\n spendCapMicros: detailCount(\n details,\n SPEND_CAP_REACHED_DETAIL_SPEND_CAP,\n Number.MIN_SAFE_INTEGER,\n ),\n boughtMicros: detailCount(\n details,\n SPEND_CAP_REACHED_DETAIL_BOUGHT,\n Number.MIN_SAFE_INTEGER,\n ),\n });\n}\n\n/** The string under `key`, or the empty string when it is absent or not a string. */\nfunction detailString(details: JsonObject | undefined, key: string): string {\n const value = details?.[key];\n return typeof value === \"string\" ? value : \"\";\n}\n\n/**\n * The whole number under `key` from `minimum` up to\n * `Number.MAX_SAFE_INTEGER`, or zero when it is absent or not such a number.\n */\nfunction detailCount(\n details: JsonObject | undefined,\n key: string,\n minimum: number,\n): number {\n const value = details?.[key];\n return typeof value === \"number\" &&\n Number.isSafeInteger(value) &&\n value >= minimum\n ? value\n : 0;\n}\n\n/**\n * The refusal of a client configuration whose `clientProduct` is partially\n * set or breaks the documented `name` and `version` grammar. Thrown by the\n * client constructors before any request is made. It is a `TypeError`, as\n * every other configuration refusal is, and `instanceof` tells it apart.\n */\nexport class InvalidClientProductError extends TypeError {\n constructor(reason: string) {\n super(`invalid client product: ${reason}`);\n this.name = \"InvalidClientProductError\";\n }\n}\n\nfunction causeOption(cause: unknown): ErrorOptions | undefined {\n return cause === undefined ? undefined : { cause };\n}\n\n/**\n * The reason phrase for each status, as the reference contract renders it, so one status\n * reads the same in every IDYL SDK's error message.\n */\nconst STATUS_TEXT: Readonly<Record<number, string>> = {\n 100: \"Continue\",\n 101: \"Switching Protocols\",\n 102: \"Processing\",\n 103: \"Early Hints\",\n 200: \"OK\",\n 201: \"Created\",\n 202: \"Accepted\",\n 203: \"Non-Authoritative Information\",\n 204: \"No Content\",\n 205: \"Reset Content\",\n 206: \"Partial Content\",\n 207: \"Multi-Status\",\n 208: \"Already Reported\",\n 226: \"IM Used\",\n 300: \"Multiple Choices\",\n 301: \"Moved Permanently\",\n 302: \"Found\",\n 303: \"See Other\",\n 304: \"Not Modified\",\n 305: \"Use Proxy\",\n 307: \"Temporary Redirect\",\n 308: \"Permanent Redirect\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Request Entity Too Large\",\n 414: \"Request URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Requested Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 425: \"Too Early\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 451: \"Unavailable For Legal Reasons\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\",\n};\n\n/**\n * Renders an HTTP status as `404 Not Found`, with the reason phrase the reference\n * contract renders, or as `HTTP 599` when the status has none.\n */\nexport function describeStatus(status: number): string {\n const text = STATUS_TEXT[status];\n return text === undefined\n ? `HTTP ${String(status)}`\n : `${String(status)} ${text}`;\n}\n\n/** What a command wrote before it ended. */\nexport interface CommandOutput {\n /** Its standard output, decoded as UTF-8. */\n readonly stdout: string;\n /** Its standard error, decoded as UTF-8. */\n readonly stderr: string;\n}\n\n/**\n * A command ran and ended other than with exit code 0. Its changes were saved\n * as usual; `code` and `signal` are what a caller branches on.\n */\nexport class ExitError extends Error implements CommandOutput {\n /** Its exit code, when it exited by itself. */\n declare readonly code?: number;\n /** The signal that ended it, when one did. */\n declare readonly signal?: string;\n /** Its standard output, decoded as UTF-8. */\n readonly stdout: string;\n /** Its standard error, decoded as UTF-8. */\n readonly stderr: string;\n\n /**\n * Builds the error from how the command ended. The package builds every\n * `ExitError` it rejects with.\n *\n * @param code the exit code, or `undefined` when the command did not exit\n * by itself\n * @param signal the signal that ended it, or `undefined` when none did\n * @param output what the command wrote\n */\n constructor(\n code: number | undefined,\n signal: string | undefined,\n output: CommandOutput,\n ) {\n super(\n code === undefined\n ? \"command ended without an exit code\"\n : `command exited with code ${String(code)}`,\n );\n this.name = \"ExitError\";\n if (code !== undefined) this.code = code;\n if (signal !== undefined) this.signal = signal;\n this.stdout = output.stdout;\n this.stderr = output.stderr;\n }\n}\n\n/**\n * A command ran but its changes could not be saved, so a read of the files does\n * not show them. `exitCode` is how the command itself ended.\n */\nexport class CommandSaveError extends Error implements CommandOutput {\n /**\n * Why the save failed, as the platform states it, such as\n * `SAVE_REASON_COMPUTER_SIZE`.\n */\n declare readonly reason?: string;\n /** The command's own exit code, when it exited by itself. */\n declare readonly exitCode?: number;\n /** Its standard output, decoded as UTF-8. */\n readonly stdout: string;\n /** Its standard error, decoded as UTF-8. */\n readonly stderr: string;\n\n /**\n * Builds the error from the save's outcome. The package builds every\n * `CommandSaveError` it rejects with.\n *\n * @param reason why the save failed, or `undefined` when the platform\n * states no reason\n * @param exitCode the command's exit code, or `undefined` when it did not\n * exit by itself\n * @param output what the command wrote\n */\n constructor(\n reason: string | undefined,\n exitCode: number | undefined,\n output: CommandOutput,\n ) {\n super(\"command ran but its changes could not be saved\");\n this.name = \"CommandSaveError\";\n if (reason !== undefined) this.reason = reason;\n if (exitCode !== undefined) this.exitCode = exitCode;\n this.stdout = output.stdout;\n this.stderr = output.stderr;\n }\n}\n\n/**\n * A command's session failed before the command's end was known, so the\n * command may not have run, or may have been cut short. The message names\n * the code alone.\n */\nexport class CommandSessionError extends Error implements CommandOutput {\n /**\n * The session's error code: `broken` and `no_exit` name a connection that\n * ended without an exit, and `output_too_large` a stream past the 16 MiB\n * a command keeps.\n */\n readonly code: string;\n /** Its standard output so far, decoded as UTF-8. */\n readonly stdout: string;\n /** Its standard error so far, decoded as UTF-8. */\n readonly stderr: string;\n\n /**\n * Builds the error from the session's failure. The package builds every\n * `CommandSessionError` it rejects with.\n *\n * @param code the session's error code\n * @param output what the command wrote before the session failed\n */\n constructor(code: string, output: CommandOutput) {\n super(\n /^[a-z_]+$/u.test(code)\n ? `command session failed: ${code}`\n : \"command session failed\",\n );\n this.name = \"CommandSessionError\";\n this.code = code;\n this.stdout = output.stdout;\n this.stderr = output.stderr;\n }\n}\n\n/** Durable ingestion failure. Classify using transfer.failure.code, never its prose. */\nexport class UploadTransferFailedError extends Error {\n constructor(readonly transfer: UploadTransfer) {\n super(\n transfer.failure?.code\n ? `upload transfer failed: ${transfer.failure.code}`\n : \"upload transfer failed\",\n );\n this.name = \"UploadTransferFailedError\";\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/**\n * A signal derived from an optional parent and an optional timeout. `cleanup`\n * releases the listener and timer the signal holds; it is called when the\n * work the signal guards has finished, whether or not the signal fired.\n */\nexport interface ManagedSignal {\n readonly signal: AbortSignal;\n cleanup(): void;\n}\n\n/**\n * Builds a signal that aborts with the parent's reason when `parent` aborts\n * and with a `TimeoutError` `DOMException` carrying `timeoutMessage` when\n * `timeoutMs` elapses first. An already-aborted parent aborts the result\n * immediately. `timeoutMs` is milliseconds and must be positive when given;\n * `undefined` sets no timeout.\n */\nexport function managedSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number | undefined,\n timeoutMessage: string,\n): ManagedSignal {\n if (\n timeoutMs !== undefined &&\n (!Number.isFinite(timeoutMs) || timeoutMs <= 0)\n ) {\n throw new TypeError(\"timeoutMs must be greater than zero\");\n }\n const controller = new AbortController();\n const abortFromParent = (): void => {\n controller.abort(parent?.reason ?? abortError());\n };\n if (parent?.aborted === true) abortFromParent();\n else parent?.addEventListener(\"abort\", abortFromParent, { once: true });\n\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n controller.abort(new DOMException(timeoutMessage, \"TimeoutError\"));\n }, timeoutMs);\n\n return {\n signal: controller.signal,\n cleanup(): void {\n if (timer !== undefined) clearTimeout(timer);\n parent?.removeEventListener(\"abort\", abortFromParent);\n },\n };\n}\n\n/**\n * Resolves with `value` unless `signal` aborts first, in which case it\n * rejects with the signal's reason, unchanged. The underlying work is not cancelled by\n * this function; the caller passes `signal` to it separately. A rejection\n * that is not an `Error` is wrapped so the cause is preserved.\n */\nexport async function abortable<T>(\n value: PromiseLike<T> | T,\n signal: AbortSignal,\n): Promise<T> {\n signal.throwIfAborted();\n return await new Promise<T>((resolve, reject) => {\n const onAbort = (): void => {\n // The caller's reason, whatever it is, is what the wait rejects with.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(value).then(\n (result) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(result);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(asError(error));\n },\n );\n });\n}\n\n/**\n * Resolves after `milliseconds`, or rejects with the signal's reason if\n * `signal` aborts first. The timer is cleared on abort so nothing is left\n * running.\n */\nexport async function delay(\n milliseconds: number,\n signal: AbortSignal,\n): Promise<void> {\n signal.throwIfAborted();\n await new Promise<void>((resolve, reject) => {\n const onAbort = (): void => {\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(signal.reason);\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, milliseconds);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/** The reason `signal` aborted with, as an `Error`. */\nexport function abortReason(signal: AbortSignal): Error {\n const reason: unknown = signal.reason;\n if (reason instanceof Error) return reason;\n return abortError(\n typeof reason === \"string\" && reason !== \"\" ? reason : undefined,\n );\n}\n\nfunction abortError(message = \"this operation was aborted\"): DOMException {\n return new DOMException(message, \"AbortError\");\n}\n\nfunction asError(reason: unknown): Error {\n if (reason instanceof Error) return reason;\n return new Error(\"operation failed with a non-Error rejection\", {\n cause: reason,\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/**\n * Why a strict decode refused a document. The vocabulary is closed and only\n * grows: a value is never renamed or removed, and a new value is a new case\n * to handle.\n *\n * - `invalid_json`: the text is not one well-formed JSON value.\n * - `duplicate_field`: an object names the same key twice.\n * - `trailing_content`: a second value follows the first.\n * - `unknown_field`: the document names a field the kind does not declare.\n * - `missing_field`: a field the kind requires is absent or `null`.\n * - `wrong_type`: a value is not the JSON type the field declares.\n * - `invalid_value`: a value has the right JSON type but is not a valid\n * spelling of the field, such as a CPU quantity of `\"fast\"`.\n */\nexport type StrictDecodeReason =\n | \"invalid_json\"\n | \"duplicate_field\"\n | \"trailing_content\"\n | \"unknown_field\"\n | \"missing_field\"\n | \"wrong_type\"\n | \"invalid_value\";\n\n/** What a {@link StrictDecodeError} reports. */\nexport interface StrictDecodeErrorOptions {\n readonly reason: StrictDecodeReason;\n readonly path: string;\n readonly message: string;\n readonly cause?: unknown;\n}\n\n/**\n * A submission the strict decoder refused.\n *\n * `reason` is the classification to branch on and `path` locates the field\n * from the root of the document, in the form `spec.containers[0].imageURI`;\n * it is empty when the rejection is about the document as a whole. `message`\n * is prose for people and is never parsed. The cause, when there is one, is\n * the error the field's own codec raised.\n */\nexport class StrictDecodeError extends Error {\n readonly reason: StrictDecodeReason;\n readonly path: string;\n\n constructor(options: StrictDecodeErrorOptions) {\n super(\n options.message,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = \"StrictDecodeError\";\n this.reason = options.reason;\n this.path = options.path;\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Strict submission decoding: one implementation, used by every resource and\n * API contract that decodes a document a caller wrote.\n *\n * A document decodes as exactly one JSON value with no unknown fields, no\n * duplicate object keys, and no trailing content, and every rejection names\n * the field by its full path from the root of the document, in the form\n * `spec.containers[0].imageURI`, so a caller can be pointed at the part of the\n * submission that is wrong rather than at the submission.\n *\n * A contract declares its wire shape once, next to its type, with the\n * combinators below. The shape drives both directions: decoding checks the\n * document against it and builds the typed value, and encoding renders the\n * typed value back to its wire document with the reference contract's omission rules, so\n * what this package emits is what the reference contract emits.\n *\n * The same shapes read a response, in lenient mode: a field the shape does\n * not declare is carried as it arrived, a value the shape cannot read is\n * carried as it arrived, and only what a codec canonicalizes, a quantity or\n * a duration, is normalized. Which mode applies belongs to the call site: a\n * submission is strict, an observation is lenient, and no type decides.\n */\nimport { StrictDecodeError } from \"../resource/decode-error.js\";\nimport type { Integer, JsonObject, JsonValue } from \"../resource/json.js\";\n\n/**\n * How a document is read. `strict` refuses a field the shape does not\n * declare, a value of the wrong type, and a missing required field.\n * `lenient` carries an undeclared field and an unreadable value as they\n * arrived, reads a missing required field as its zero value, and normalizes\n * only what a codec canonicalizes.\n */\nexport type DecodeMode = \"strict\" | \"lenient\";\n\n/**\n * The wire shape of one value: how it is checked, decoded, encoded, and what\n * its zero value is. The reference contract's omission rules need both `isZero` (the\n * `omitzero` test, which omits a struct or quantity whose every part is zero)\n * and `isEmpty` (the `omitempty` test, which omits a false, zero, empty\n * string, empty array, or empty map but never a struct).\n */\nexport interface Shape<T> {\n /**\n * Reports the first field under `value` that the shape does not declare,\n * by throwing. Object keys are visited in sorted order so a document with\n * several unknown fields is refused on the same one every time. A value\n * whose JSON type does not fit the shape is left for `decode` to report.\n */\n readonly unknownFields: (value: unknown, path: string) => void;\n /**\n * Builds the typed value, or throws a {@link StrictDecodeError}. In\n * lenient mode a container carries what it cannot read instead of\n * throwing; a scalar shape needs no mode, because the container that\n * holds it decides what to do with its refusal.\n */\n readonly decode: (\n value: unknown,\n path: string,\n mode?: DecodeMode,\n numberToken?: string,\n ) => T;\n /** Renders the typed value as the JSON value the wire carries. */\n readonly encode: (value: T) => JsonValue;\n /** The value the reference contract reads an absent field as. */\n readonly zero: () => T;\n /** Whether the reference contract's `omitzero` would omit the value. */\n readonly isZero: (value: T) => boolean;\n /** Whether the reference contract's `omitempty` would omit the value. */\n readonly isEmpty: (value: T) => boolean;\n}\n\n/**\n * How a field is read and written. A `required` field must be present in the\n * document; a `value` field reads as its zero value when absent, as a Go\n * struct field does; an `optional` field reads as `undefined`. Omission on\n * encode follows the Go tag the field carries: `never` for a plain field,\n * `undefined` for a pointer, `empty` for `omitempty`, `zero` for `omitzero`.\n */\nexport interface Field<T> {\n readonly shape: Shape<T>;\n readonly presence: \"required\" | \"value\" | \"optional\";\n readonly omit: \"never\" | \"undefined\" | \"empty\" | \"zero\";\n /** Refuses null on submission, or retains it as a JSON payload rather than an absent pointer. */\n readonly null?: \"refuse\" | \"preserve\";\n}\n\n/** A field that is always present on the typed value. */\nexport interface PresentField<T> extends Field<T> {\n readonly presence: \"required\" | \"value\";\n}\n\n/** A field that may be absent from the typed value. */\nexport interface OptionalField<T> extends Field<T> {\n readonly presence: \"optional\";\n}\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: Record<never, never> extends Pick<T, K> ? K : never;\n}[keyof T];\n\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\n\n/**\n * The fields of an object shape, keyed by wire name. A property the type\n * declares as optional takes an {@link OptionalField}; every other property\n * takes a {@link PresentField}, so the shape and the type cannot disagree\n * about which fields may be absent.\n */\nexport type ObjectFields<T> = {\n readonly [K in RequiredKeys<T>]: PresentField<T[K]>;\n} & {\n readonly [K in OptionalKeys<T>]: OptionalField<Exclude<T[K], undefined>>;\n};\n\n/** A field the document must state. It is always written. */\nexport function required<T>(shape: Shape<T>): PresentField<T> {\n return { shape, presence: \"required\", omit: \"never\" };\n}\n\n/**\n * A field the document may omit, read as the shape's zero value when it does.\n * It is always written, zero included.\n */\nexport function always<T>(shape: Shape<T>): PresentField<T> {\n return { shape, presence: \"value\", omit: \"never\" };\n}\n\n/** A Go `omitempty` field: absent when unset, omitted when empty. */\nexport function omitEmpty<T>(shape: Shape<T>): OptionalField<T> {\n return { shape, presence: \"optional\", omit: \"empty\" };\n}\n\n/**\n * A Go `omitempty` array or map that the type declares as always present:\n * it reads as empty when absent and is omitted when empty, so a document\n * never carries `[]` or `{}` for it and code never reads `undefined`.\n */\nexport function collection<T>(shape: Shape<T>): PresentField<T> {\n return { shape, presence: \"value\", omit: \"empty\" };\n}\n\n/** A Go `omitzero` field: absent when unset, omitted when zero. */\nexport function omitZero<T>(shape: Shape<T>): OptionalField<T> {\n return { shape, presence: \"optional\", omit: \"zero\" };\n}\n\n/**\n * A Go pointer field with `omitempty`: absent when unset, otherwise written\n * whatever its value, so a present `false` or an empty object reaches the\n * wire.\n */\nexport function pointer<T>(shape: Shape<T>): OptionalField<T> {\n return { shape, presence: \"optional\", omit: \"undefined\" };\n}\n\n/** An optional pointer whose explicit null is refused on a strict submission. */\nexport function explicitPointer<T>(shape: Shape<T>): OptionalField<T> {\n return { ...pointer(shape), null: \"refuse\" };\n}\n\n/**\n * A JSON string carried as it is. The type parameter names the string union\n * the field declares; membership is not judged here, because a vocabulary\n * belongs to whoever reports it and validation is where a caller's own value\n * is held to the set this SDK names.\n */\nexport function string<T extends string = string>(): Shape<T> {\n return {\n unknownFields: noUnknownFields,\n decode: (value, path) => {\n if (typeof value !== \"string\") throw wrongType(path, \"a string\");\n return value as T;\n },\n encode: (value) => value,\n zero: () => \"\" as T,\n isZero: (value) => value === \"\",\n isEmpty: (value) => value === \"\",\n };\n}\n\n/** A JSON boolean. */\nexport function boolean(): Shape<boolean> {\n return {\n unknownFields: noUnknownFields,\n decode: (value, path) => {\n if (typeof value !== \"boolean\") throw wrongType(path, \"a boolean\");\n return value;\n },\n encode: (value) => value,\n zero: () => false,\n isZero: (value) => !value,\n isEmpty: (value) => !value,\n };\n}\n\n/** A number-valued integer; narrower Go widths are stated explicitly. */\nexport function integer(options: {\n readonly unsigned: boolean;\n readonly bits?: 8 | 16 | 32;\n}): Shape<number>;\n/** A full-width Go integral field, represented exactly as number or bigint. */\nexport function integer(options: {\n readonly unsigned: boolean;\n readonly bits: 64;\n}): Shape<Integer>;\nexport function integer(options: {\n readonly unsigned: boolean;\n readonly bits?: 8 | 16 | 32 | 64;\n}): Shape<number> | Shape<Integer> {\n const description = options.unsigned\n ? \"a non-negative integer\"\n : \"an integer\";\n const bits = options.bits;\n const minimum = options.unsigned\n ? 0n\n : bits === undefined\n ? BigInt(Number.MIN_SAFE_INTEGER)\n : -(1n << BigInt(bits - 1));\n const maximum =\n bits === undefined\n ? BigInt(Number.MAX_SAFE_INTEGER)\n : (1n << BigInt(options.unsigned ? bits : bits - 1)) - 1n;\n function checked(\n value: unknown,\n path: string,\n mode?: DecodeMode,\n numberToken?: string,\n ): Integer {\n if (\n mode !== \"lenient\" &&\n numberToken !== undefined &&\n (!INTEGER_TOKEN.test(numberToken) ||\n (options.unsigned && numberToken.startsWith(\"-\")))\n ) {\n throw wrongType(path, description);\n }\n if (!isIntegerValue(value)) {\n throw wrongType(path, description);\n }\n const exact = BigInt(value);\n if (exact < minimum || exact > maximum) throw wrongType(path, description);\n return numberOrBigInt(exact);\n }\n const shape: Shape<Integer> = {\n unknownFields: noUnknownFields,\n decode: checked,\n encode: (value) => checked(value, \"\"),\n zero: () => 0,\n isZero: (value) => value === 0 || value === 0n,\n isEmpty: (value) => value === 0 || value === 0n,\n };\n return shape;\n}\n\n/** A known Go float64 field; integral tokens are rounded to its IEEE-754 value. */\nexport function float64(): Shape<number> {\n function valueOf(value: unknown, path: string, mode?: DecodeMode): number {\n if (typeof value !== \"number\" && typeof value !== \"bigint\")\n throw wrongType(path, \"a number\");\n const valueAsNumber = Number(value);\n if (\n !Number.isFinite(valueAsNumber) &&\n (typeof value === \"bigint\" || mode !== \"lenient\")\n )\n throw wrongType(path, \"a finite float64 value\");\n return valueAsNumber;\n }\n const shape: Shape<number> = {\n unknownFields: noUnknownFields,\n decode: valueOf,\n encode: (value) => valueOf(value, \"\"),\n zero: () => 0,\n isZero: (value) => value === 0,\n isEmpty: (value) => value === 0,\n };\n FLOAT64_SHAPES.add(shape);\n return shape;\n}\n\n// Marks known float64 shapes and maps without changing plain public values\n// or unknown integers.\nconst FLOAT64_SHAPES = new WeakSet();\nconst FLOAT64_MAPS = new WeakSet();\n\n/** Narrows an exact integral value only when a number can carry every digit. */\nexport function numberOrBigInt(value: bigint): Integer {\n return value >= BigInt(Number.MIN_SAFE_INTEGER) &&\n value <= BigInt(Number.MAX_SAFE_INTEGER)\n ? Number(value)\n : value;\n}\n\nconst uint64Shape = integer({ unsigned: true, bits: 64 });\nconst int64Shape = integer({ unsigned: false, bits: 64 });\n\nfunction fitsInteger(value: unknown, shape: Shape<Integer>): value is Integer {\n try {\n shape.decode(value, \"\");\n return true;\n } catch (error) {\n if (error instanceof StrictDecodeError) return false;\n throw error;\n }\n}\n\n/** Whether a supplied operand fits the canonical unsigned 64-bit field. */\nexport function isUint64(value: unknown): value is Integer {\n return fitsInteger(value, uint64Shape);\n}\n\n/** Whether a supplied operand fits the canonical signed 64-bit field. */\nexport function isInt64(value: unknown): value is Integer {\n return fitsInteger(value, int64Shape);\n}\n\n/** The integral JSON value type, without imposing a field's wire width. */\nexport function isIntegerValue(value: unknown): value is Integer {\n return (\n typeof value === \"bigint\" ||\n (typeof value === \"number\" && Number.isInteger(value))\n );\n}\n\n/** Numeric equality across the two exact integral representations. */\nexport function integerEqual(left: unknown, right: unknown): boolean {\n return isIntegerValue(left) && isIntegerValue(right)\n ? BigInt(left) === BigInt(right)\n : left === right;\n}\n\n/** The actual exact integer represented by a number or bigint operand. */\nexport function integerText(value: Integer): string {\n if (typeof value === \"number\" && !Number.isInteger(value))\n throw new TypeError(\"value must be an integer\");\n return BigInt(value).toString();\n}\n\n/** How a scalar with its own spelling decodes and encodes. */\nexport interface ScalarCodec<T> {\n /**\n * Parses the wire spelling, throwing a `TypeError` that names what is\n * wrong with it. The message is carried into the decode error's message\n * and the `TypeError` into its cause.\n */\n readonly decode: (text: string) => T;\n /** Renders the canonical wire spelling. */\n readonly encode: (value: T) => string;\n readonly zero: () => T;\n readonly isZero: (value: T) => boolean;\n /**\n * Whether a JSON number is accepted as the spelling of itself, as the\n * reference contract reads `cpu: 1` as the string `1`.\n */\n readonly acceptsNumber?: boolean;\n}\n\n/**\n * A value that travels as a JSON string in a spelling of its own, such as a\n * quantity or a duration. The codec judges the spelling; a spelling it\n * refuses is an `invalid_value` rejection carrying the codec's error as its\n * cause.\n */\nexport function scalar<T>(codec: ScalarCodec<T>): Shape<T> {\n return {\n unknownFields: noUnknownFields,\n decode: (value, path) => {\n let text: string;\n if (typeof value === \"string\") {\n text = value;\n } else if (\n codec.acceptsNumber === true &&\n (typeof value === \"bigint\" ||\n (typeof value === \"number\" && Number.isFinite(value)))\n ) {\n text =\n typeof value === \"bigint\" || Number.isInteger(value)\n ? integerText(value)\n : String(value);\n } else {\n throw wrongType(path, \"a string\");\n }\n try {\n return codec.decode(text);\n } catch (error) {\n if (error instanceof TypeError) throw invalidValue(path, error);\n throw error;\n }\n },\n encode: (value) => codec.encode(value),\n zero: codec.zero,\n isZero: codec.isZero,\n isEmpty: codec.isZero,\n };\n}\n\n/**\n * A JSON object carried as it is, with no declared fields: the value of a\n * field whose contents belong to whoever wrote them, such as a document a\n * report embeds. Nothing under it is refused, and it is written back\n * verbatim.\n */\nexport function jsonObject(): Shape<JsonObject> {\n return {\n unknownFields: noUnknownFields,\n decode: (value, path) => {\n if (!isPlainObject(value)) throw wrongType(path, \"an object\");\n return value as JsonObject;\n },\n encode: (value) => value,\n zero: () => ({}),\n isZero: (value) => Object.keys(value).length === 0,\n isEmpty: (value) => Object.keys(value).length === 0,\n };\n}\n\n/**\n * Any JSON value carried as it arrived, for a field the reference contract declares as\n * raw JSON. Its zero value is `null`, which is also the one value an\n * `omitempty` field omits; a pointer field writes whatever it holds.\n */\nexport function jsonValue(): Shape<JsonValue> {\n return {\n unknownFields: noUnknownFields,\n decode: (value, path) => {\n if (value === undefined) throw wrongType(path, \"a JSON value\");\n return value as JsonValue;\n },\n encode: (value) => value,\n zero: () => null,\n isZero: (value) => value === null,\n isEmpty: (value) => value === null,\n };\n}\n\n/** A JSON array of one element shape. */\nexport function array<T>(element: Shape<T>): Shape<readonly T[]> {\n return {\n unknownFields: (value, path) => {\n if (!Array.isArray(value)) return;\n value.forEach((item: unknown, index) => {\n element.unknownFields(item, indexPath(path, index));\n });\n },\n decode: (value, path, mode) => {\n if (!Array.isArray(value)) {\n if (mode === \"lenient\") return value as readonly T[];\n throw wrongType(path, \"an array\");\n }\n return value.map((item: unknown, index) =>\n decodeChild(\n element,\n item,\n indexPath(path, index),\n mode,\n numberTokenAt(value, String(index)),\n ),\n );\n },\n encode: (value) => value.map((item) => element.encode(item)),\n zero: () => [],\n isZero: (value) => value.length === 0,\n isEmpty: (value) => value.length === 0,\n };\n}\n\n/**\n * A JSON object with arbitrary string keys and one value shape. Keys are\n * written in sorted order, as the reference contract writes a map.\n */\nexport function map<T>(value: Shape<T>): Shape<Readonly<Record<string, T>>> {\n return {\n unknownFields: (document, path) => {\n if (!isPlainObject(document)) return;\n for (const key of sortedKeys(document)) {\n value.unknownFields(document[key], fieldPath(path, key));\n }\n },\n decode: (document, path, mode) => {\n if (!isPlainObject(document)) {\n if (mode === \"lenient\") return document as Readonly<Record<string, T>>;\n throw wrongType(path, \"an object\");\n }\n const decoded: Record<string, T> = {};\n for (const key of Object.keys(document)) {\n Object.defineProperty(decoded, key, {\n value: decodeChild(\n value,\n document[key],\n fieldPath(path, key),\n mode,\n numberTokenAt(document, key),\n ),\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n if (FLOAT64_SHAPES.has(value)) FLOAT64_MAPS.add(decoded);\n return decoded;\n },\n encode: (record) => {\n const encoded: Record<string, JsonValue> = {};\n for (const key of Object.keys(record).sort()) {\n const item = record[key];\n if (item !== undefined)\n Object.defineProperty(encoded, key, {\n value: value.encode(item),\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n if (FLOAT64_SHAPES.has(value)) FLOAT64_MAPS.add(encoded);\n return encoded;\n },\n zero: () => ({}),\n isZero: (record) => Object.keys(record).length === 0,\n isEmpty: (record) => Object.keys(record).length === 0,\n };\n}\n\n/**\n * A JSON object with declared fields. A field the document names that the\n * shape does not declare is refused by `unknownFields` and carried as it\n * arrived by a lenient decode; a `null` reads as absence, as it does in the\n * reference contract. Fields are written in declaration order.\n */\nexport function object<T extends object>(fields: ObjectFields<T>): Shape<T> {\n const entries = Object.entries<Field<unknown>>(fields);\n const declared = new Map(entries);\n return {\n unknownFields: (value, path) => {\n if (!isPlainObject(value)) return;\n for (const key of sortedKeys(value)) {\n const field = declared.get(key);\n if (field === undefined) {\n throw new StrictDecodeError({\n reason: \"unknown_field\",\n path: fieldPath(path, key),\n message: `unknown field ${JSON.stringify(fieldPath(path, key))}`,\n });\n }\n field.shape.unknownFields(value[key], fieldPath(path, key));\n }\n },\n decode: (value, path, mode) => {\n if (!isPlainObject(value)) {\n if (mode === \"lenient\" && path !== \"\") return value as T;\n throw path === \"\"\n ? new StrictDecodeError({\n reason: \"wrong_type\",\n path,\n message: \"document must be an object\",\n })\n : wrongType(path, \"an object\");\n }\n const decoded: Record<string, unknown> = {};\n for (const [key, field] of entries) {\n const raw = Object.hasOwn(value, key) ? value[key] : undefined;\n if (raw === null && field.null === \"refuse\" && mode !== \"lenient\") {\n throw new StrictDecodeError({\n reason: \"invalid_value\",\n path: fieldPath(path, key),\n message: `${fieldPath(path, key)} must not be null`,\n });\n }\n if (raw === null && field.null === \"preserve\") {\n decoded[key] = field.shape.decode(null, fieldPath(path, key), mode);\n continue;\n }\n if (raw === undefined || raw === null) {\n if (field.presence === \"required\" && mode !== \"lenient\") {\n throw new StrictDecodeError({\n reason: \"missing_field\",\n path: fieldPath(path, key),\n message: `missing field ${JSON.stringify(fieldPath(path, key))}`,\n });\n }\n if (field.presence !== \"optional\") decoded[key] = field.shape.zero();\n continue;\n }\n decoded[key] = decodeChild(\n field.shape,\n raw,\n fieldPath(path, key),\n mode,\n numberTokenAt(value, key),\n );\n }\n if (mode === \"lenient\") {\n for (const key of Object.keys(value)) {\n if (!declared.has(key))\n Object.defineProperty(decoded, key, {\n value: value[key],\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n }\n return decoded as T;\n },\n encode: (value) => {\n const record = value as Readonly<Record<string, unknown>>;\n const encoded: Record<string, JsonValue> = {};\n for (const [key, field] of entries) {\n const item = record[key];\n if (item === undefined) {\n if (field.omit === \"never\") {\n encoded[key] = field.shape.encode(field.shape.zero());\n }\n continue;\n }\n if (field.omit === \"empty\" && field.shape.isEmpty(item)) continue;\n if (field.omit === \"zero\" && field.shape.isZero(item)) continue;\n encoded[key] = field.shape.encode(item);\n }\n return encoded;\n },\n zero: () => {\n const zero: Record<string, unknown> = {};\n for (const [key, field] of entries) {\n if (field.presence !== \"optional\") zero[key] = field.shape.zero();\n }\n return zero as T;\n },\n isZero: (value) => {\n const record = value as Readonly<Record<string, unknown>>;\n return entries.every(([key, field]) => {\n const item = record[key];\n return item === undefined || field.shape.isZero(item);\n });\n },\n isEmpty: () => false,\n };\n}\n\n/**\n * The half of a shape that reads: what a document router holds for each\n * kind it can decode. A shape of one kind is a decoder of any union that\n * includes the kind, which is what lets one table route to every kind's\n * shape without pretending they share an encoder.\n */\nexport type Decoder<T> = Pick<Shape<T>, \"unknownFields\" | \"decode\">;\n\n/**\n * Decodes JSON text as one document: well-formed, no duplicate object keys\n * anywhere, no trailing content, and no field the shape does not declare.\n */\nexport function decodeText<T>(text: string, shape: Decoder<T>): T {\n const parsed = new Scanner(text, \"strict\").readDocument();\n shape.unknownFields(parsed.value, \"\");\n return shape.decode(parsed.value, \"\", \"strict\", parsed.numberToken);\n}\n\n/**\n * Decodes a value a caller already parsed. Duplicate keys cannot be detected\n * in a parsed value, because parsing already kept one of them; a caller that\n * holds the text uses {@link decodeText}.\n *\n * `mode` defaults to strict. A lenient decode skips the unknown-field walk\n * and carries what the shape does not declare or cannot read; the document\n * itself must still be an object.\n */\nexport function decodeValue<T>(\n value: unknown,\n shape: Decoder<T>,\n mode: DecodeMode = \"strict\",\n): T {\n if (mode !== \"lenient\") shape.unknownFields(value, \"\");\n return shape.decode(value, \"\", mode);\n}\n\n/**\n * Decodes one child value. In lenient mode a value the child shape refuses\n * is carried as it arrived, so one unreadable field never discards the\n * document around it.\n */\nfunction decodeChild<T>(\n shape: Shape<T>,\n raw: unknown,\n path: string,\n mode: DecodeMode | undefined,\n numberToken?: string,\n): T {\n if (mode !== \"lenient\") return shape.decode(raw, path, mode, numberToken);\n try {\n return shape.decode(raw, path, mode, numberToken);\n } catch (error) {\n if (error instanceof StrictDecodeError) return raw as T;\n throw error;\n }\n}\n\n/**\n * Parses exactly one JSON value from its original text. Strict submissions\n * refuse duplicate keys by path; lenient observations keep the last value.\n * Both modes refuse malformed syntax and content after the value.\n */\nexport function parseText(\n text: string,\n mode: DecodeMode = \"strict\",\n): JsonValue {\n return new Scanner(text, mode).readDocument().value;\n}\n\n/**\n * The sole JSON reader. It checks the grammar and builds values from their\n * original tokens, so integral digits never pass through a rounded number.\n * Objects and arrays use an explicit stack, as does the nesting check.\n */\nclass Scanner {\n private index = 0;\n private scalarNumberToken: string | undefined;\n\n constructor(\n private readonly text: string,\n private readonly mode: DecodeMode,\n ) {}\n\n readDocument(): { readonly value: JsonValue; readonly numberToken?: string } {\n this.skipWhitespace();\n if (this.index >= this.text.length) {\n throw this.invalid(\"unexpected end of input\");\n }\n const parsed = this.scanValue(\"\");\n this.skipWhitespace();\n if (this.index < this.text.length) {\n if (startsValue(this.text[this.index] ?? \"\")) {\n throw new StrictDecodeError({\n reason: \"trailing_content\",\n path: \"\",\n message: \"multiple JSON values are not allowed\",\n });\n }\n throw this.invalid(\n `unexpected character ${JSON.stringify(this.text[this.index] ?? \"\")}`,\n );\n }\n return parsed;\n }\n\n private scanValue(path: string): {\n readonly value: JsonValue;\n readonly numberToken?: string;\n } {\n const open: Frame[] = [];\n let root: JsonValue = null;\n let rootNumberToken: string | undefined;\n const append = (value: JsonValue, numberToken?: string): void => {\n const parent = open[open.length - 1];\n if (parent === undefined) {\n root = value;\n rootNumberToken = numberToken;\n } else if (parent.kind === \"object\") {\n Object.defineProperty(parent.value, parent.key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n rememberNumberToken(parent.value, parent.key, value, numberToken);\n } else {\n parent.value.push(value);\n rememberNumberToken(\n parent.value,\n String(parent.index),\n value,\n numberToken,\n );\n }\n };\n for (;;) {\n this.skipWhitespace();\n const character = this.text[this.index];\n if (character === \"{\" || character === \"[\") {\n if (open.length >= MAX_NESTING_DEPTH) {\n throw this.invalid(\"exceeded max depth\");\n }\n this.index += 1;\n this.skipWhitespace();\n const value = character === \"{\" ? {} : [];\n append(value);\n const close = character === \"{\" ? \"}\" : \"]\";\n if (this.text[this.index] === close) {\n this.index += 1;\n } else if (character === \"{\") {\n const frame: ObjectFrame = {\n kind: \"object\",\n path,\n seen: new Set(),\n value,\n key: \"\",\n };\n open.push(frame);\n path = this.scanKey(frame);\n continue;\n } else {\n open.push({\n kind: \"array\",\n path,\n index: 0,\n value: value as JsonValue[],\n });\n path = indexPath(path, 0);\n continue;\n }\n } else {\n this.scalarNumberToken = undefined;\n const value = this.scanScalar(character);\n append(value, this.scalarNumberToken);\n }\n for (;;) {\n const frame = open[open.length - 1];\n if (frame === undefined) {\n return rootNumberToken === undefined\n ? { value: root }\n : { value: root, numberToken: rootNumberToken };\n }\n this.skipWhitespace();\n if (this.text[this.index] === \",\") {\n this.index += 1;\n if (frame.kind === \"object\") {\n path = this.scanKey(frame);\n } else {\n frame.index += 1;\n path = indexPath(frame.path, frame.index);\n }\n break;\n }\n this.expect(frame.kind === \"object\" ? \"}\" : \"]\");\n open.pop();\n }\n }\n }\n\n private scanKey(frame: ObjectFrame): string {\n this.skipWhitespace();\n if (this.text[this.index] !== '\"') {\n throw this.invalid(\"expected an object key\");\n }\n const key = this.scanString();\n if (this.mode !== \"lenient\" && frame.seen.has(key)) {\n throw new StrictDecodeError({\n reason: \"duplicate_field\",\n path: fieldPath(frame.path, key),\n message: `duplicate field ${JSON.stringify(fieldPath(frame.path, key))}`,\n });\n }\n frame.seen.add(key);\n frame.key = key;\n this.skipWhitespace();\n this.expect(\":\");\n return fieldPath(frame.path, key);\n }\n\n private scanScalar(character: string | undefined): JsonValue {\n switch (character) {\n case '\"':\n return this.scanString();\n case \"t\":\n this.scanLiteral(\"true\");\n return true;\n case \"f\":\n this.scanLiteral(\"false\");\n return false;\n case \"n\":\n this.scanLiteral(\"null\");\n return null;\n case undefined:\n throw this.invalid(\"unexpected end of input\");\n default:\n if (character === \"-\" || isDigit(character)) return this.scanNumber();\n throw this.invalid(`unexpected character ${JSON.stringify(character)}`);\n }\n }\n\n private scanString(): string {\n this.index += 1;\n let value = \"\";\n for (;;) {\n const character = this.text[this.index];\n if (character === undefined) throw this.invalid(\"unterminated string\");\n if (character === '\"') {\n this.index += 1;\n return value;\n }\n if (character === \"\\\\\") {\n value += this.scanEscape();\n continue;\n }\n if (character < \" \") throw this.invalid(\"control character in string\");\n value += character;\n this.index += 1;\n }\n }\n\n private scanEscape(): string {\n const escaped = this.text[this.index + 1];\n this.index += 2;\n switch (escaped) {\n case '\"':\n return '\"';\n case \"\\\\\":\n return \"\\\\\";\n case \"/\":\n return \"/\";\n case \"b\":\n return \"\\b\";\n case \"f\":\n return \"\\f\";\n case \"n\":\n return \"\\n\";\n case \"r\":\n return \"\\r\";\n case \"t\":\n return \"\\t\";\n case \"u\": {\n const digits = this.text.slice(this.index, this.index + 4);\n if (!/^[0-9a-fA-F]{4}$/u.test(digits))\n throw this.invalid(\"invalid unicode escape\");\n this.index += 4;\n return String.fromCharCode(Number.parseInt(digits, 16));\n }\n default:\n throw this.invalid(\"invalid escape sequence\");\n }\n }\n\n private scanNumber(): number | bigint {\n NUMBER.lastIndex = this.index;\n const match = NUMBER.exec(this.text);\n if (match === null) throw this.invalid(\"invalid number\");\n const token = match[0];\n this.index += token.length;\n this.scalarNumberToken = token;\n if (INTEGER_TOKEN.test(token)) {\n const exact = BigInt(token);\n if (exact !== 0n) return numberOrBigInt(exact);\n }\n return Number(token);\n }\n\n private scanLiteral(literal: string): void {\n if (!this.text.startsWith(literal, this.index)) {\n throw this.invalid(\n `unexpected character ${JSON.stringify(this.text[this.index] ?? \"\")}`,\n );\n }\n this.index += literal.length;\n }\n\n private expect(character: string): void {\n if (this.text[this.index] !== character) {\n throw this.invalid(\n this.index >= this.text.length\n ? \"unexpected end of input\"\n : `expected ${JSON.stringify(character)}`,\n );\n }\n this.index += 1;\n }\n\n private skipWhitespace(): void {\n for (;;) {\n const character = this.text[this.index];\n if (\n character === \" \" ||\n character === \"\\n\" ||\n character === \"\\r\" ||\n character === \"\\t\"\n ) {\n this.index += 1;\n continue;\n }\n return;\n }\n }\n\n private invalid(detail: string): StrictDecodeError {\n return new StrictDecodeError({\n reason: \"invalid_json\",\n path: \"\",\n message: `invalid JSON at offset ${String(this.index)}: ${detail}`,\n });\n }\n}\n\n/** Original number syntax belongs to the reader, never to a public wrapper. */\nconst numberTokens = new WeakMap<\n object,\n Map<\n string,\n {\n readonly value: JsonValue;\n readonly token: string;\n }\n >\n>();\n\nfunction rememberNumberToken(\n container: object,\n key: string,\n value: JsonValue,\n token?: string,\n): void {\n if (token === undefined) {\n numberTokens.get(container)?.delete(key);\n return;\n }\n let tokens = numberTokens.get(container);\n if (tokens === undefined) {\n tokens = new Map();\n numberTokens.set(container, tokens);\n }\n tokens.set(key, { value, token });\n}\n\nfunction numberTokenAt(container: object, key: string): string | undefined {\n const source = numberTokens.get(container)?.get(key);\n const value = (container as Readonly<Record<string, unknown>>)[key];\n return source !== undefined && Object.is(source.value, value)\n ? source.token\n : undefined;\n}\n\n/**\n * Writes exact integral JSON values and the shortest spelling of known\n * float64 fields. The explicit stack also permits deeply nested values.\n */\nexport function renderValue(value: JsonValue, space?: number | string): string {\n const gap =\n typeof space === \"number\"\n ? \" \".repeat(Math.max(0, Math.min(10, Math.trunc(space))))\n : (space?.slice(0, 10) ?? \"\");\n const parts: string[] = [];\n const active = new WeakSet();\n type Part =\n | { readonly text: string }\n | {\n readonly value: JsonValue;\n readonly depth: number;\n readonly float64?: boolean;\n }\n | { readonly leave: object };\n const pending: Part[] = [{ value, depth: 0 }];\n for (;;) {\n const part = pending.pop();\n if (part === undefined) return parts.join(\"\");\n if (\"text\" in part) {\n parts.push(part.text);\n continue;\n }\n if (\"leave\" in part) {\n active.delete(part.leave);\n continue;\n }\n const item = part.value;\n if (\n part.float64 === true &&\n (typeof item === \"number\" || typeof item === \"bigint\")\n ) {\n const float = Number(item);\n if (!Number.isFinite(float))\n throw new TypeError(\"float64 value cannot be written as JSON\");\n parts.push(Object.is(float, -0) ? \"-0\" : JSON.stringify(float));\n continue;\n }\n if (typeof item === \"bigint\") {\n parts.push(integerText(item));\n continue;\n }\n if (typeof item === \"number\") {\n parts.push(\n Number.isInteger(item) ? integerText(item) : JSON.stringify(item),\n );\n continue;\n }\n if (\n typeof item === \"string\" ||\n typeof item === \"boolean\" ||\n item === null\n ) {\n parts.push(JSON.stringify(item));\n continue;\n }\n if (typeof item !== \"object\")\n throw new TypeError(\"value cannot be written as JSON\");\n if (active.has(item))\n throw new TypeError(\"circular value cannot be written as JSON\");\n active.add(item);\n const array = Array.isArray(item);\n const entries = array\n ? Array.from(\n item,\n (entry: JsonValue, index: number) =>\n [String(index), entry ?? null] as const,\n )\n : Object.entries<JsonValue | undefined>(item).filter(\n (entry): entry is [string, JsonValue] => entry[1] !== undefined,\n );\n const indent = gap.repeat(part.depth);\n const childIndent = gap.repeat(part.depth + 1);\n const newline = gap === \"\" ? \"\" : \"\\n\";\n parts.push(array ? \"[\" : \"{\");\n pending.push({ leave: item });\n pending.push({\n text:\n entries.length === 0\n ? array\n ? \"]\"\n : \"}\"\n : `${newline}${indent}${array ? \"]\" : \"}\"}`,\n });\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index];\n if (entry === undefined) continue;\n pending.push({\n value: entry[1],\n depth: part.depth + 1,\n ...(FLOAT64_MAPS.has(item) ? { float64: true } : {}),\n });\n if (!array)\n pending.push({\n text: `${JSON.stringify(entry[0])}:${gap === \"\" ? \"\" : \" \"}`,\n });\n pending.push({\n text: `${index === 0 ? \"\" : \",\"}${newline}${childIndent}`,\n });\n }\n }\n}\n\n/** An object the scanner has opened and not yet closed. */\ninterface ObjectFrame {\n readonly kind: \"object\";\n readonly path: string;\n readonly seen: Set<string>;\n readonly value: Record<string, JsonValue>;\n key: string;\n}\n\n/** An array the scanner has opened and not yet closed. */\ninterface ArrayFrame {\n readonly kind: \"array\";\n readonly path: string;\n index: number;\n readonly value: JsonValue[];\n}\n\ntype Frame = ObjectFrame | ArrayFrame;\n\n/** The plain integral syntax accepted by Go integer submission fields. */\nconst INTEGER_TOKEN = /^-?(?:0|[1-9][0-9]*)$/u;\n\n/** The JSON number grammar, matched in place from the scanner's position. */\nconst NUMBER = /-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/uy;\n\n/**\n * The deepest nesting of objects and arrays a document may carry, the same\n * bound the reference contract's decoder applies.\n */\nconst MAX_NESTING_DEPTH = 10_000;\n\nfunction startsValue(character: string): boolean {\n return (\n character === \"{\" ||\n character === \"[\" ||\n character === '\"' ||\n character === \"-\" ||\n character === \"t\" ||\n character === \"f\" ||\n character === \"n\" ||\n isDigit(character)\n );\n}\n\nfunction isDigit(character: string): boolean {\n return character >= \"0\" && character <= \"9\";\n}\n\nfunction noUnknownFields(): void {\n // A scalar declares no fields, so there is nothing under it to refuse.\n}\n\nfunction isPlainObject(\n value: unknown,\n): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction sortedKeys(value: Readonly<Record<string, unknown>>): string[] {\n return Object.keys(value).sort();\n}\n\nfunction wrongType(path: string, expected: string): StrictDecodeError {\n return new StrictDecodeError({\n reason: \"wrong_type\",\n path,\n message: `field ${JSON.stringify(path)} must be ${expected}`,\n });\n}\n\nfunction invalidValue(path: string, cause: TypeError): StrictDecodeError {\n return new StrictDecodeError({\n reason: \"invalid_value\",\n path,\n message: `invalid field ${JSON.stringify(path)}: ${cause.message}`,\n cause,\n });\n}\n\n/** Joins a field onto a path the way the reference contract does: `spec.template`. */\nexport function fieldPath(path: string, field: string): string {\n return path === \"\" ? field : `${path}.${field}`;\n}\n\n/** Joins an index onto a path the way the reference contract does: `containers[0]`. */\nexport function indexPath(path: string, index: number): string {\n return `${path}[${String(index)}]`;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Standard base64 with padding, the encoding a Go byte slice takes on the\n * wire. It is implemented over `btoa` and `atob`, which every supported\n * runtime provides, in chunks so a value at a service's ceiling never\n * spreads one call's arguments. `bytesShape` is how a byte field declares\n * itself in a wire shape: bytes in hand, base64 text on the wire.\n */\nimport { scalar, type Shape } from \"../internal/strictdecode.js\";\n\nconst BASE64 =\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;\n\nconst CHUNK = 0x8000;\n\n/** Renders bytes as standard base64 with padding. */\nexport function encodeBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK));\n }\n return btoa(binary);\n}\n\n/**\n * Reads standard base64 with padding, as strictly as the reference contract reads it: no\n * whitespace, no URL alphabet, no missing padding. Throws a `TypeError` for\n * any other text.\n */\nexport function decodeBase64(text: string): Uint8Array {\n if (!BASE64.test(text)) throw new TypeError(\"invalid base64\");\n const binary = atob(text);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/**\n * A byte field as its Go codec reads it: `Uint8Array` in hand and standard\n * base64 with padding on the wire, empty being the zero value an `omitempty`\n * tag omits. Text that is not base64 is refused by the field's path.\n */\nexport const bytesShape: Shape<Uint8Array> = scalar<Uint8Array>({\n decode: decodeBase64,\n encode: encodeBase64,\n zero: () => new Uint8Array(),\n isZero: (value) => value.byteLength === 0,\n});\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Proofs of possession (RFC 9449, DPoP) in the one profile the API verifies.\n * A proof is a compact JWS of type `dpop+jwt`, signed `EdDSA` (Ed25519) or\n * `ES256` (ECDSA P-256), whose header carries the public key's JWK and\n * nothing else, and whose claims name one request: a fresh 128-bit `jti`,\n * the method (`htm`), the URL as scheme, host and path (`htu`), the time\n * (`iat`), the hash of the access token presented (`ath`), the hash of the\n * raw query (`htq`), the request's `Content-Digest` (`htd`) and the hash of\n * the headers that change what the request means (`hth`). WebCrypto alone\n * signs and hashes, so a private key may be non-extractable.\n */\nimport { encodeBase64 } from \"../resource/base64.js\";\n\n/** The algorithms a proof is signed with. */\nexport type ProofAlgorithm = \"EdDSA\" | \"ES256\";\n\n/** The public half of a key as a JSON Web Key, public members only. */\nexport interface PublicJwk {\n readonly kty: \"OKP\" | \"EC\";\n readonly crv: \"Ed25519\" | \"P-256\";\n readonly x: string;\n readonly y?: string;\n}\n\n/** What a proof states about a key, derived once per key. */\ninterface KeyProfile {\n readonly alg: ProofAlgorithm;\n readonly jwk: PublicJwk;\n /** The base64url protected header every proof by the key carries. */\n readonly header: string;\n /** The RFC 7638 SHA-256 thumbprint of `jwk`, unpadded base64url. */\n readonly thumbprint: string;\n}\n\n/**\n * The request headers a proof's `hth` covers, in the order it covers them:\n * every client header a service reads to decide what an operation does.\n */\nexport const SEMANTIC_HEADERS = [\n \"content-type\",\n \"idempotency-key\",\n \"if-match\",\n \"if-none-match\",\n \"last-event-id\",\n] as const;\n\n/** The sentence an unsupported key is refused with. */\nconst UNSUPPORTED_KEY = \"must be an Ed25519 or ECDSA P-256 key pair\";\n\n/** Each public key's profile, exported and hashed once. */\nconst profiles = new WeakMap<CryptoKey, Promise<KeyProfile>>();\n\n/**\n * Reports why `key` cannot sign proofs, or `undefined` when it can: it must\n * be a WebCrypto key pair of one Ed25519 or ECDSA P-256 key whose private\n * half may sign. The wording completes a sentence that names the key's\n * origin.\n */\nexport function keyPairProblem(key: unknown): string | undefined {\n if (typeof key !== \"object\" || key === null) return \"is required\";\n const { publicKey, privateKey } = key as Partial<CryptoKeyPair>;\n if (!isCryptoKey(publicKey) || !isCryptoKey(privateKey)) {\n return \"must be a CryptoKeyPair\";\n }\n if (publicKey.type !== \"public\" || privateKey.type !== \"private\") {\n return \"must be a CryptoKeyPair\";\n }\n const algorithm = algorithmOf(publicKey);\n if (algorithm === undefined || algorithmOf(privateKey) !== algorithm) {\n return UNSUPPORTED_KEY;\n }\n if (!privateKey.usages.includes(\"sign\")) {\n return \"has a private key that may not sign\";\n }\n return undefined;\n}\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Partial<CryptoKey>).type === \"string\" &&\n typeof (value as Partial<CryptoKey>).algorithm === \"object\" &&\n Array.isArray((value as Partial<CryptoKey>).usages)\n );\n}\n\n/** The proof algorithm a key's WebCrypto algorithm signs with, if any. */\nfunction algorithmOf(key: CryptoKey): ProofAlgorithm | undefined {\n const algorithm = key.algorithm as Partial<EcKeyAlgorithm>;\n if (algorithm.name === \"Ed25519\") return \"EdDSA\";\n if (algorithm.name === \"ECDSA\" && algorithm.namedCurve === \"P-256\") {\n return \"ES256\";\n }\n return undefined;\n}\n\n/**\n * The profile of a public key: its JWK, algorithm, protected header and\n * thumbprint. The JWK is exported once per key and kept while the key is;\n * a failed export is not kept. Throws a `TypeError` for a key that is not\n * an Ed25519 or P-256 public key, or whose public half cannot be exported.\n */\nexport async function keyProfile(publicKey: CryptoKey): Promise<KeyProfile> {\n let profile = profiles.get(publicKey);\n if (profile === undefined) {\n profile = deriveProfile(publicKey);\n profiles.set(publicKey, profile);\n profile.catch(() => {\n profiles.delete(publicKey);\n });\n }\n return await profile;\n}\n\nasync function deriveProfile(publicKey: CryptoKey): Promise<KeyProfile> {\n const alg =\n isCryptoKey(publicKey) && publicKey.type === \"public\"\n ? algorithmOf(publicKey)\n : undefined;\n if (alg === undefined) throw new TypeError(`key ${UNSUPPORTED_KEY}`);\n let exported: JsonWebKey;\n try {\n exported = await crypto.subtle.exportKey(\"jwk\", publicKey);\n } catch (cause) {\n throw new TypeError(\"key's public half cannot be exported\", { cause });\n }\n const jwk = publicMembers(exported, alg);\n const header = base64url(\n new TextEncoder().encode(\n JSON.stringify({ typ: \"dpop+jwt\", alg, jwk: orderedJwk(jwk) }),\n ),\n );\n return Object.freeze({\n alg,\n jwk,\n header,\n thumbprint: await thumbprintOf(jwk),\n });\n}\n\n/** The public members of an exported JWK, judged for shape. */\nfunction publicMembers(exported: JsonWebKey, alg: ProofAlgorithm): PublicJwk {\n const { kty, crv, x, y } = exported;\n if (alg === \"EdDSA\") {\n if (kty === \"OKP\" && crv === \"Ed25519\" && coordinate(x)) {\n return Object.freeze({ kty, crv, x });\n }\n } else if (\n kty === \"EC\" &&\n crv === \"P-256\" &&\n coordinate(x) &&\n coordinate(y)\n ) {\n return Object.freeze({ kty, crv, x, y });\n }\n throw new TypeError(`key ${UNSUPPORTED_KEY}`);\n}\n\n/** Whether `value` is 32 bytes as unpadded base64url. */\nexport function coordinate(value: unknown): value is string {\n return typeof value === \"string\" && /^[A-Za-z0-9_-]{43}$/u.test(value);\n}\n\n/** A JWK with its members in the order a proof header writes them. */\nfunction orderedJwk(jwk: PublicJwk): PublicJwk {\n return jwk.y === undefined\n ? { kty: jwk.kty, crv: jwk.crv, x: jwk.x }\n : { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };\n}\n\n/**\n * The RFC 7638 SHA-256 thumbprint of a public JWK, unpadded base64url: the\n * hash of its required members in lexicographic order.\n */\nexport async function thumbprintOf(jwk: PublicJwk): Promise<string> {\n const canonical =\n jwk.y === undefined\n ? { crv: jwk.crv, kty: jwk.kty, x: jwk.x }\n : { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n return await hash(JSON.stringify(canonical));\n}\n\n/** What one proof names. */\nexport interface ProofRequest {\n readonly method: string;\n /** The URL the request is sent to, as `fetch` receives it. */\n readonly url: URL;\n /**\n * The {@link hash} of the access token the request presents; absent when\n * it presents none, or presents a refresh token, which its key alone binds.\n */\n readonly ath?: string;\n /** The request's `Content-Digest`; absent for a request that sends none. */\n readonly contentDigest?: string;\n /** The request's headers, whose semantic members `hth` covers. */\n readonly headers: Headers;\n /** The time the proof states, in milliseconds since the epoch. */\n readonly now: number;\n}\n\n/**\n * Signs a proof for one request with `key`, a key pair `keyPairProblem`\n * admits. Every call states a fresh `jti`, so no two proofs are alike.\n */\nexport async function prove(\n key: CryptoKeyPair,\n request: ProofRequest,\n): Promise<string> {\n const profile = await keyProfile(key.publicKey);\n const { url } = request;\n const query = url.search.startsWith(\"?\") ? url.search.slice(1) : url.search;\n const semantic = semanticHeaders(request.headers);\n const claims = {\n jti: base64url(crypto.getRandomValues(new Uint8Array(16))),\n htm: request.method,\n htu: `${url.protocol}//${url.host.toLowerCase()}${url.pathname}`,\n iat: Math.floor(request.now / 1000),\n ...(request.ath === undefined ? {} : { ath: request.ath }),\n ...(query === \"\" ? {} : { htq: await hash(query) }),\n ...(request.contentDigest === undefined\n ? {}\n : { htd: request.contentDigest }),\n ...(semantic === \"\" ? {} : { hth: await hash(semantic) }),\n };\n const signed = `${profile.header}.${base64url(\n new TextEncoder().encode(JSON.stringify(claims)),\n )}`;\n return `${signed}.${base64url(await sign(key.privateKey, profile.alg, signed))}`;\n}\n\n/**\n * The text `hth` hashes: `<name>:<value>\\n` for each semantic header the\n * request carries, in {@link SEMANTIC_HEADERS} order; empty when it carries\n * none.\n */\nexport function semanticHeaders(headers: Headers): string {\n let text = \"\";\n for (const name of SEMANTIC_HEADERS) {\n const value = headers.get(name);\n if (value !== null) text += `${name}:${value}\\n`;\n }\n return text;\n}\n\n/**\n * Signs `message`: Ed25519 over the message itself, ES256 over its SHA-256\n * as the 64-byte r||s of RFC 7518 §3.4, which is WebCrypto's own encoding.\n */\nasync function sign(\n privateKey: CryptoKey,\n alg: ProofAlgorithm,\n message: string,\n): Promise<Uint8Array> {\n const data = new TextEncoder().encode(message);\n let signature: ArrayBuffer;\n try {\n signature =\n alg === \"EdDSA\"\n ? await crypto.subtle.sign({ name: \"Ed25519\" }, privateKey, data)\n : await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n privateKey,\n data,\n );\n } catch (cause) {\n throw new TypeError(\"credential key could not sign the proof\", { cause });\n }\n const bytes = new Uint8Array(signature);\n if (bytes.byteLength !== 64) {\n throw new TypeError(\"credential key returned a malformed signature\");\n }\n return bytes;\n}\n\n/** The unpadded base64url SHA-256 of `text`'s UTF-8 bytes. */\nexport async function hash(text: string): Promise<string> {\n return base64url(\n new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(text)),\n ),\n );\n}\n\n/** The RFC 9530 `Content-Digest` of `body`, in its `sha-256` form. */\nexport async function contentDigest(body: Uint8Array): Promise<string> {\n const digest = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", body as Uint8Array<ArrayBuffer>),\n );\n return `sha-256=:${encodeBase64(digest)}:`;\n}\n\n/** Unpadded base64url. */\nexport function base64url(bytes: Uint8Array): string {\n return encodeBase64(bytes)\n .replace(/\\+/gu, \"-\")\n .replace(/\\//gu, \"_\")\n .replace(/=+$/u, \"\");\n}\n\n/** Reads unpadded base64url strictly; `undefined` for any other text. */\nexport function decodeBase64url(text: string): Uint8Array | undefined {\n if (!/^[A-Za-z0-9_-]*$/u.test(text) || text.length % 4 === 1) {\n return undefined;\n }\n const binary = atob(\n text.replace(/-/gu, \"+\").replace(/_/gu, \"/\") +\n \"=\".repeat((4 - (text.length % 4)) % 4),\n );\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n // A second spelling of the same bytes, with stray low bits in the last\n // character, is not the canonical encoding.\n return base64url(bytes) === text ? bytes : undefined;\n}\n\n/**\n * The clock proofs state: the local clock plus the offset the API's last\n * `Date` header showed, so a skewed local clock does not make proofs stale.\n * One clock is shared by every transport of a client.\n */\nexport class ProofClock {\n #offsetMs = 0;\n\n /** The API's time now, in milliseconds since the epoch, as best known. */\n now(): number {\n return Date.now() + this.#offsetMs;\n }\n\n /** Learns the API's clock from a response's `Date` header, when it has one. */\n observe(response: Response): void {\n const date = response.headers.get(\"date\");\n if (date === null) return;\n const at = Date.parse(date);\n if (Number.isFinite(at)) this.#offsetMs = at - Date.now();\n }\n}\n\n/**\n * Whether `response` refused the request's proof, as a proof that stated a\n * skewed time is refused: a 401 whose `WWW-Authenticate` names\n * `invalid_dpop_proof`.\n */\nexport function proofRefused(response: Response): boolean {\n return (\n response.status === 401 &&\n (response.headers.get(\"www-authenticate\") ?? \"\").includes(\n 'error=\"invalid_dpop_proof\"',\n )\n );\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Helpers the resource validators share. Every validator throws a\n * `TypeError` whose message names the first violation, and a validator that\n * delegates to another prefixes the delegate's message with the field it\n * was checking, so a message reads from the manifest root down:\n * `spec: invalid template spec: containers[0].name is required`.\n */\n\n/**\n * Runs `validate` and rethrows its `TypeError` with `prefix` and a colon in\n * front of the message, keeping the original as the cause.\n */\nexport function prefixed(prefix: string, validate: () => void): void {\n try {\n validate();\n } catch (error) {\n if (error instanceof TypeError) {\n throw new TypeError(`${prefix}: ${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Runs `validate` and rethrows its `TypeError` with `prefix` and a dot in\n * front of the message, keeping the original as the cause, so a delegate\n * that names its own field reads as one path: `spec.idleTimeout: ...`.\n */\nexport function pathPrefixed(prefix: string, validate: () => void): void {\n try {\n validate();\n } catch (error) {\n if (error instanceof TypeError) {\n throw new TypeError(`${prefix}.${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Whether `value` is well-formed: every surrogate code unit is part of a\n * pair, so the string encodes as valid UTF-8.\n */\nexport function isWellFormed(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false;\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return false;\n }\n }\n return true;\n}\n\n/** The message of `error` when it is an `Error`, or its string form otherwise. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * How a Network domain becomes the public endpoints a client addresses. The\n * conventional hosts are derived from the domain, an explicit entry overrides\n * the derived one, and every endpoint is held to the same rule: an absolute\n * origin with no path, query, fragment, or user information. Every client\n * resolves its endpoints here, naming the one endpoint it cannot do\n * without.\n */\n\nimport { errorMessage } from \"../resource/validation.js\";\n\n/** The public endpoints an endpoint set may name, each an absolute origin. */\nexport interface EndpointSet {\n readonly api?: string;\n readonly identity?: string;\n readonly meta?: string;\n}\n\n/** Which endpoint a client requires; the others are optional. */\nexport type RequiredEndpoint = \"API\" | \"identity\" | \"meta\";\n\n/**\n * Derives the conventional public endpoints for a Network, keeps explicit\n * overrides, requires the named endpoint, and canonicalizes every configured\n * endpoint. The required endpoint is validated first so its error takes\n * precedence. Throws a `TypeError` naming the problem.\n */\nexport function resolveEndpointSet(\n network: string | undefined,\n configured: EndpointSet | undefined,\n allowHttp: boolean,\n required: \"API\",\n): EndpointSet & { readonly api: string };\nexport function resolveEndpointSet(\n network: string | undefined,\n configured: EndpointSet | undefined,\n allowHttp: boolean,\n required: \"identity\",\n): EndpointSet & { readonly identity: string };\nexport function resolveEndpointSet(\n network: string | undefined,\n configured: EndpointSet | undefined,\n allowHttp: boolean,\n required: \"meta\",\n): EndpointSet & { readonly meta: string };\nexport function resolveEndpointSet(\n network: string | undefined,\n configured: EndpointSet | undefined,\n allowHttp: boolean,\n required: RequiredEndpoint,\n): EndpointSet {\n const endpoints = { ...configured };\n if (network !== undefined) {\n validateNetworkDomain(network);\n endpoints.api ??= `https://api.${network}`;\n endpoints.identity ??= `https://identity.${network}`;\n endpoints.meta ??= `https://meta.${network}`;\n }\n const requiredValue =\n required === \"API\"\n ? endpoints.api\n : required === \"identity\"\n ? endpoints.identity\n : endpoints.meta;\n if (requiredValue === undefined) {\n throw new TypeError(\n `${required} endpoint is required when network is not configured`,\n );\n }\n const requiredEndpoint = validateEndpoint(required, requiredValue, allowHttp);\n const api =\n required === \"API\"\n ? requiredEndpoint\n : optionalEndpoint(\"API\", endpoints.api, allowHttp);\n const identity =\n required === \"identity\"\n ? requiredEndpoint\n : optionalEndpoint(\"identity\", endpoints.identity, allowHttp);\n const meta =\n required === \"meta\"\n ? requiredEndpoint\n : optionalEndpoint(\"meta\", endpoints.meta, allowHttp);\n return Object.freeze({\n ...(api === undefined ? {} : { api }),\n ...(identity === undefined ? {} : { identity }),\n ...(meta === undefined ? {} : { meta }),\n });\n}\n\nfunction optionalEndpoint(\n label: string,\n raw: string | undefined,\n allowHttp: boolean,\n): string | undefined {\n return raw === undefined\n ? undefined\n : validateEndpoint(label, raw, allowHttp);\n}\n\n/**\n * Holds a Network domain to a bare DNS name: no scheme, port, path, query,\n * fragment, user information, or surrounding whitespace. Throws a\n * `TypeError` naming the problem.\n */\nexport function validateNetworkDomain(network: string): void {\n if (network === \"\" || network.trim() !== network) {\n throw new TypeError(\n \"network domain must be a non-empty DNS name without surrounding whitespace\",\n );\n }\n let parsed: URL;\n try {\n parsed = new URL(`https://${network}`);\n } catch (cause) {\n throw new TypeError(`invalid network domain ${JSON.stringify(network)}`, {\n cause,\n });\n }\n if (\n parsed.hostname !== network.toLowerCase() ||\n parsed.port !== \"\" ||\n parsed.pathname !== \"/\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n parsed.username !== \"\" ||\n network.includes(\"/\") ||\n network.startsWith(\".\") ||\n network.endsWith(\".\")\n ) {\n throw new TypeError(`invalid network domain ${JSON.stringify(network)}`);\n }\n}\n\n/**\n * Holds an endpoint to an absolute `https:` origin (or `http:` when\n * `allowHttp`) with no path, query, fragment, or user information, and\n * returns it in canonical origin form. Throws a `TypeError` naming `label`\n * and the problem.\n */\nexport function validateEndpoint(\n label: string,\n raw: string,\n allowHttp: boolean,\n): string {\n if (raw.trim() !== raw) {\n throw new TypeError(\n `${label} endpoint must not have leading or trailing whitespace`,\n );\n }\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch (cause) {\n throw new TypeError(`${label} endpoint: ${errorMessage(cause)}`, {\n cause,\n });\n }\n if (\n parsed.protocol !== \"https:\" &&\n !(allowHttp && parsed.protocol === \"http:\")\n ) {\n throw new TypeError(`${label} endpoint must use https`);\n }\n if (parsed.host === \"\" || parsed.username !== \"\" || parsed.password !== \"\") {\n throw new TypeError(\n `${label} endpoint must be an absolute URL without user information`,\n );\n }\n if (parsed.pathname !== \"/\" && parsed.pathname !== \"\") {\n throw new TypeError(`${label} endpoint must not include a path`);\n }\n if (parsed.search !== \"\" || parsed.hash !== \"\") {\n throw new TypeError(\n `${label} endpoint must not include a query or fragment`,\n );\n }\n return parsed.origin;\n}\n\n/**\n * Turns the bare API host discovery advertises into the origin requests are\n * sent to, under the client's scheme. The host is a hostname with an\n * optional port and nothing else: no scheme, path, query, fragment, user\n * information, or surrounding whitespace. Throws a `TypeError` naming the\n * problem.\n */\nexport function endpointForHost(\n scheme: \"https:\" | \"http:\",\n host: string,\n): string {\n if (host === \"\" || host.trim() !== host || host.includes(\"://\")) {\n throw new TypeError(\n \"must be a hostname without a scheme or surrounding whitespace\",\n );\n }\n let parsed: URL | undefined;\n try {\n parsed = new URL(`${scheme}//${host}`);\n } catch {\n parsed = undefined;\n }\n if (\n parsed === undefined ||\n parsed.host === \"\" ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.pathname !== \"/\" ||\n parsed.search !== \"\" ||\n parsed.hash !== \"\" ||\n /[/?#@\\\\]/u.test(host)\n ) {\n throw new TypeError(\n \"must be a hostname without a path, query, fragment, or user information\",\n );\n }\n return parsed.origin;\n}\n\n/**\n * The metadata endpoint the network's public metadata is read from. Throws a `TypeError`\n * saying one is required when the client resolved none.\n */\nexport function requireMeta(endpoint: string | undefined): string {\n if (endpoint === undefined) {\n throw new TypeError(\n \"meta endpoint is required; configure network or endpoints.meta\",\n );\n }\n return endpoint;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseText, renderValue } from \"../internal/strictdecode.js\";\n\n/**\n * An integral value. Values within the safe JavaScript range are normally\n * numbers; larger values are bigint so every digit remains exact.\n */\nexport type Integer = number | bigint;\n\n/** A JSON scalar; bigint is written as an unquoted integral JSON number. */\nexport type JsonPrimitive = string | number | bigint | boolean | null;\n\n/** A JSON array, read-only once received. */\nexport type JsonArray = readonly JsonValue[];\n\n/** A JSON object, read-only once received. */\nexport interface JsonObject {\n readonly [key: string]: JsonValue;\n}\n\n/** Any JSON value, read-only once received. */\nexport type JsonValue = JsonPrimitive | JsonArray | JsonObject;\n\n/**\n * Reads one JSON value without rounding integral tokens. Ordinary safe\n * integers are numbers and larger integral tokens are bigint. Fractions and\n * exponent-form values keep their floating-point number representation.\n * Duplicate object keys retain their last value, as on a lenient response read.\n */\nexport function parseJson(text: string): JsonValue {\n return parseText(text, \"lenient\");\n}\n\n/**\n * Writes JSON with bigint as unquoted numeric tokens. An integral number is\n * written as its actual exact integer value; use bigint when constructing\n * a value that cannot be represented exactly as a JavaScript number.\n * Non-finite numbers render as null, as with JSON.stringify. Circular\n * values cannot be written as JSON.\n */\nexport function stringifyJson(\n value: JsonValue,\n space?: number | string,\n): string {\n return renderValue(value, space);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Branded } from \"./brand.js\";\n\n/** The fixed character width of every twelve-digit public identifier. */\nexport const ID_LENGTH = 12;\n\n/**\n * The canonical identifier of an Account: twelve non-sequential ASCII digits.\n */\nexport type AccountId = Branded<\"AccountId\">;\n\n/**\n * The canonical identifier of an Organization: twelve non-sequential ASCII\n * digits.\n */\nexport type OrganizationId = Branded<\"OrganizationId\">;\n\n/** The address of the place a Computer lives in: twelve ASCII digits. */\nexport type SubnetSlug = Branded<\"SubnetSlug\">;\n\n/**\n * Reports what is wrong with `value` as a twelve-digit identifier, or\n * `undefined` when it is one. The message names the family through `label`.\n */\nfunction publicIdProblem(value: string, label: string): string | undefined {\n if (value.length !== ID_LENGTH) {\n return `invalid ${label}: must be exactly ${String(ID_LENGTH)} digits, got ${String(value.length)} characters`;\n }\n if (!/^[0-9]{12}$/u.test(value)) {\n return `invalid ${label}: must contain only ASCII digits`;\n }\n return undefined;\n}\n\nfunction parsePublicId(value: string, label: string): string {\n const problem = publicIdProblem(value, label);\n if (problem !== undefined) throw new TypeError(problem);\n return value;\n}\n\nfunction isPublicId(value: unknown): value is string {\n return typeof value === \"string\" && publicIdProblem(value, \"\") === undefined;\n}\n\n/**\n * Converts a raw string to an {@link AccountId}.\n *\n * @param value An Account's identifier, as twelve ASCII digits.\n * @throws {@link TypeError} `value` is not exactly twelve ASCII digits; the\n * message names the identifier's family\n */\nexport function parseAccountId(value: string): AccountId {\n return parsePublicId(value, \"account ID\") as AccountId;\n}\n\n/** Reports whether `value` is a string in {@link AccountId} form. */\nexport function isAccountId(value: unknown): value is AccountId {\n return isPublicId(value);\n}\n\n/**\n * Converts a raw string to a {@link SubnetSlug}. Throws a `TypeError` naming\n * the family when `value` is not exactly twelve ASCII digits.\n */\nexport function parseSubnetSlug(value: string): SubnetSlug {\n if (value.length !== ID_LENGTH) {\n throw new TypeError(\n `subnet slug must be exactly ${String(ID_LENGTH)} characters`,\n );\n }\n if (!/^[0-9]{12}$/u.test(value)) {\n throw new TypeError(\"subnet slug must match [0-9]{12}\");\n }\n return value as SubnetSlug;\n}\n\n/** Reports whether `value` is a string in {@link SubnetSlug} form. */\nexport function isSubnetSlug(value: unknown): value is SubnetSlug {\n return isPublicId(value);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseJson } from \"../resource/json.js\";\nimport type { JsonObject } from \"../resource/json.js\";\nimport { parseSubnetSlug } from \"../resource/id.js\";\nimport {\n always,\n decodeValue,\n object,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\n\n/**\n * A network's public metadata, served anonymously by its metadata endpoint.\n * It names what every Account of the network shares, so a client reads it\n * once and needs no credential to do so.\n *\n * `computerSubnet` is the twelve-digit address of the place every Account's\n * Computers live in. The network names one such place for all of its\n * Accounts, and no Account chooses it. Whether an Account may use it, and\n * the host of its API, come from the Account's own discovery, which the\n * metadata does not repeat.\n */\nexport interface Network {\n readonly computerSubnet: string;\n}\n\nconst networkShape: Shape<Network> = object<Network>({\n computerSubnet: always(string()),\n});\n\n/**\n * Reads a network's metadata as served, leniently. `document` is JSON text\n * or a value already parsed from JSON. A field this package does not\n * declare is carried as it arrived, and a missing field reads as its zero\n * value. Nothing is judged; {@link validateNetwork} judges.\n */\nexport function decodeNetwork(document: unknown): Network {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, networkShape, \"lenient\");\n}\n\n/** Renders a network's metadata as the endpoint serves it. */\nexport function encodeNetwork(network: Network): JsonObject {\n return networkShape.encode(network) as JsonObject;\n}\n\n/**\n * Judges that the metadata names the place for Computers by a canonical\n * twelve-digit address. Throws a `TypeError`.\n */\nexport function validateNetwork(network: Network): void {\n if (network.computerSubnet === \"\") {\n throw new TypeError(\"network metadata names no place for computers\");\n }\n try {\n parseSubnetSlug(network.computerSubnet);\n } catch (cause) {\n throw new TypeError(\n \"network metadata names an invalid place for computers\",\n { cause },\n );\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The REST paths the SDK addresses.\n *\n * The containment model is expressed once. Account, Namespace, Subnet, and\n * resource segments are assembled here and nowhere else, and every segment\n * interpolated into a path is escaped, so a name carrying a slash, a percent\n * sign, or a question mark addresses the resource it names rather than a\n * different route.\n *\n * The scopes it takes are the public ones. A resource that lives in a Subnet\n * is addressed by its Namespace scope on the API host of the Subnet it lives\n * in, so its paths carry no Subnet segment of their own.\n */\nimport type { NamespaceScope } from \"../api/types.js\";\n\n/** The Account path, with `suffix` appended when it is not empty. */\nexport function account(accountId: string, suffix = \"\"): string {\n return join(`/v1/accounts/${encodeURIComponent(accountId)}`, suffix);\n}\n\n/**\n * The path of one account-scoped resource addressed by name within a\n * collection, such as a Namespace, with `suffix` appended when it is not\n * empty.\n */\nexport function accountResource(\n accountId: string,\n collection: string,\n name: string,\n suffix = \"\",\n): string {\n return resourceWithin(account(accountId), collection, name, suffix);\n}\n\n/**\n * The path of one resource addressed by name within a collection beneath\n * `path`, with `suffix` appended when it is not empty. `path` is already\n * escaped by its builder; `name` is escaped here.\n */\nexport function resourceWithin(\n path: string,\n collection: string,\n name: string,\n suffix = \"\",\n): string {\n return join(`${path}/${collection}/${encodeURIComponent(name)}`, suffix);\n}\n\n/** The path of one Namespace, with `suffix` appended when it is not empty. */\nexport function namespace(scope: NamespaceScope, suffix = \"\"): string {\n return join(\n accountResource(scope.accountId, \"namespaces\", scope.namespace),\n suffix,\n );\n}\n\n/** The path of one Namespace-scoped resource. */\nexport function namespaceResource(\n scope: NamespaceScope,\n collection: string,\n name: string,\n): string {\n return namespace(scope, `${collection}/${encodeURIComponent(name)}`);\n}\n\n/**\n * The path of one Computer addressed by its stable identifier rather than\n * its name. The `by-id` segment is reserved on the platform, so no Computer\n * name can collide with it.\n */\nexport function computerById(scope: NamespaceScope, id: string): string {\n return namespace(scope, `computers/by-id/${encodeURIComponent(id)}`);\n}\n\n/**\n * The path of the attachments of one Secret, addressed by its stable\n * identifier, across the Computers of a Namespace. The `by-secret` segment\n * is reserved on the platform beside `by-id`, so no Computer name can\n * collide with it.\n */\nexport function computersBySecret(\n scope: NamespaceScope,\n secretId: string,\n): string {\n return namespace(\n scope,\n `computers/by-secret/${encodeURIComponent(secretId)}`,\n );\n}\n\n/** The Secret attachment states of the Computer addressed by name. */\nexport function computerSecrets(scope: NamespaceScope, name: string): string {\n return namespace(scope, `computers/${encodeURIComponent(name)}/secrets`);\n}\n\n/**\n * The Secret attachment states of the Computer addressed by its stable\n * identifier.\n */\nexport function computerSecretsById(scope: NamespaceScope, id: string): string {\n return `${computerById(scope, id)}/secrets`;\n}\n\n/**\n * The record of the Vault values opened for the Computer addressed by its\n * stable identifier. The record lives under the Namespace's vault path, not\n * under the Computer's, so a Computer read never carries it.\n */\nexport function vaultDecryptionsOfComputer(\n scope: NamespaceScope,\n id: string,\n): string {\n return namespace(\n scope,\n `vault/computers/${encodeURIComponent(id)}/decryptions`,\n );\n}\n\n/**\n * The session collection of the Computer addressed by name, or, with\n * `sessionId`, one session in it.\n */\nexport function computerSessions(\n scope: NamespaceScope,\n name: string,\n sessionId?: string,\n): string {\n return collectionMember(\n namespace(scope, `computers/${encodeURIComponent(name)}/sessions`),\n sessionId,\n );\n}\n\n/**\n * The session collection of the Computer addressed by its stable\n * identifier, or, with `sessionId`, one session in it.\n */\nexport function computerSessionsById(\n scope: NamespaceScope,\n id: string,\n sessionId?: string,\n): string {\n return collectionMember(`${computerById(scope, id)}/sessions`, sessionId);\n}\n\n/**\n * The journal of the Computer addressed by name, or, with `entryId`, one\n * entry of it.\n */\nexport function computerJournal(\n scope: NamespaceScope,\n name: string,\n entryId?: string,\n): string {\n return collectionMember(\n namespace(scope, `computers/${encodeURIComponent(name)}/journal`),\n entryId,\n );\n}\n\n/**\n * The journal of the Computer addressed by its stable identifier, or, with\n * `entryId`, one entry of it.\n */\nexport function computerJournalById(\n scope: NamespaceScope,\n id: string,\n entryId?: string,\n): string {\n return collectionMember(`${computerById(scope, id)}/journal`, entryId);\n}\n\nfunction collectionMember(collection: string, member?: string): string {\n return member === undefined\n ? collection\n : `${collection}/${encodeURIComponent(member)}`;\n}\n\n/**\n * The path of one Subnet within an Account, with `suffix` appended when it is\n * not empty.\n */\nexport function accountSubnet(\n accountId: string,\n subnetSlug: string,\n suffix = \"\",\n): string {\n return join(\n account(accountId, `subnets/${encodeURIComponent(subnetSlug)}`),\n suffix,\n );\n}\n\n/** The Account the presented credential acts as, on the identity endpoint. */\nexport const CURRENT_ACCOUNT = \"/account\";\n\n/** Account signup, on the API endpoint. */\nexport const SIGNUP = \"/v1/signup\";\n\n/** What a new Account would start with, on the API endpoint. */\nexport const SIGNUP_OFFER = \"/v1/signup/offer\";\n\n/** Requests a one-time sign-in code, on the identity endpoint. */\nexport const LOGIN_START = \"/login/start\";\n\n/** Requests that the one-time sign-in code be sent again. */\nexport const LOGIN_RESEND = \"/login/resend\";\n\n/** Verifies a one-time sign-in code. */\nexport const LOGIN_VERIFY = \"/login/verify\";\n\n/** Exchanges a refresh token for a profile access token. */\nexport const TOKEN_PROFILE = \"/token/profile\";\n\n/** The profiles a refresh token may assume. */\nexport const TOKEN_PROFILES = \"/token/profiles\";\n\n/** Ends the sign-in the presented refresh token belongs to. */\nexport const LOGOUT = \"/logout\";\n\n/** Exchanges an access key for an access token, on the identity endpoint. */\nexport const TOKEN_ACCESS_KEY = \"/token/access-key\";\n\n/** Issues a one-time code bound to a browser's S256 PKCE transaction. */\nexport const BROWSER_AUTHORIZE = \"/browser/authorize\";\n\n/** Redeems a browser authorization code. */\nexport const BROWSER_EXCHANGE = \"/browser/exchange\";\n\n/** The calling person's access keys, on the API endpoint. */\nexport const ACCESS_KEYS = \"/v1/access-keys\";\n\n/** The path of one of the calling person's access keys. */\nexport function accessKey(accessKeyId: string): string {\n return `${ACCESS_KEYS}/${encodeURIComponent(accessKeyId)}`;\n}\n\n/** The network's public metadata, read anonymously from the meta endpoint. */\nexport const NETWORK_METADATA = \"/v1/network\";\n\n/** Every size a Computer can run at, read anonymously from the meta endpoint. */\nexport const COMPUTER_SIZES = \"/v1/computer-sizes\";\n\n/**\n * Appends a suffix that is already escaped by its caller. An empty suffix\n * leaves the path addressing the scope itself rather than a route beneath it.\n */\nfunction join(path: string, suffix: string): string {\n return suffix === \"\" ? path : `${path}/${suffix}`;\n}\n\n/** One storage child of an already escaped Computer address. */\nexport function storageChild(\n base: string,\n collection: string,\n member?: string,\n suffix = \"\",\n): string {\n return join(collectionMember(join(base, collection), member), suffix);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Where an Account's Computers live. IDYL assigns the place, and a client\n * learns it in two reads: the network's public metadata names the Subnet\n * every Account's Computers live in, and the Account's deployable-Subnet\n * discovery advertises the host of its API. The package never lists Subnets\n * to choose one, never guesses one, and names none in an option, a type, or\n * a message.\n *\n * Whether the Account may use the place is the platform's decision: the\n * package judges nothing about it, and a refusal arrives as the `ApiError`\n * of the request it refused. Discovery that names no API host for the\n * place is IDYL's misconfiguration, which no caller can act on, and is a\n * plain `Error` that names no place.\n *\n * A resolved place is kept for the life of the client, per Account. A\n * failed read is never kept: the next operation reads again.\n */\nimport { decodeNetwork, validateNetwork } from \"../api/network.js\";\nimport { TransportError } from \"../errors.js\";\nimport { parseSubnetSlug } from \"../resource/id.js\";\nimport type { AccountId, SubnetSlug } from \"../resource/id.js\";\nimport { errorMessage } from \"../resource/validation.js\";\nimport { abortable } from \"./abort.js\";\nimport { account, NETWORK_METADATA } from \"./apipath.js\";\nimport type { ServiceState } from \"./context.js\";\nimport { endpointForHost, requireMeta } from \"./endpoints.js\";\n\n/**\n * The place an Account's Computers live in, and the origin of its API.\n * `zone` is the trust scope discovery names for the place, which a\n * Computer connection holds its session trust to; empty when discovery\n * names none.\n */\nexport interface AssignedPlacement {\n readonly subnet: SubnetSlug;\n readonly endpoint: string;\n readonly zone: string;\n}\n\n/** What one resolution takes. */\nexport interface PlacementRequest {\n readonly signal?: AbortSignal;\n}\n\n/**\n * The one seam placement is resolved through: the place `accountId`'s\n * Computers live in and the origin of its API.\n */\nexport interface PlacementSource {\n resolve(\n accountId: AccountId,\n request?: PlacementRequest,\n ): Promise<AssignedPlacement>;\n}\n\n/**\n * The placement source of a client on an IDYL network: the network's public\n * metadata names the Computer Subnet, read once, anonymously, and shared by\n * every Account; the Account's discovery advertises its API host. Concurrent operations share one read, and a caller's signal ends\n * only its own wait.\n */\nexport function networkPlacement(state: ServiceState): PlacementSource {\n let computerSubnet: Promise<SubnetSlug> | undefined;\n const managed = new Map<AccountId, Promise<AssignedPlacement>>();\n\n const subnet = (): Promise<SubnetSlug> => {\n computerSubnet ??= readComputerSubnet(state).catch((error: unknown) => {\n computerSubnet = undefined;\n throw error;\n });\n return computerSubnet;\n };\n\n return {\n async resolve(accountId, request = {}) {\n const signal = request.signal ?? new AbortController().signal;\n let placement = managed.get(accountId);\n if (placement === undefined) {\n placement = subnet()\n .then((slug) => discover(state, accountId, slug))\n .catch((error: unknown) => {\n managed.delete(accountId);\n throw error;\n });\n managed.set(accountId, placement);\n }\n return await abortable(placement, signal);\n },\n };\n}\n\n/**\n * Reads the network's public metadata and returns the Subnet every\n * Account's Computers live in. Throws a `TypeError` when the metadata names\n * none or names one that is not a canonical slug.\n */\nasync function readComputerSubnet(state: ServiceState): Promise<SubnetSlug> {\n const served = await state.transport.anonymousJson<unknown>(\n \"GET\",\n requireMeta(state.endpoints.meta),\n NETWORK_METADATA,\n );\n try {\n const metadata = decodeNetwork(served);\n validateNetwork(metadata);\n return parseSubnetSlug(metadata.computerSubnet);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n \"network metadata names no valid place for computers\",\n { cause },\n );\n }\n}\n\n/**\n * Finds `slug` in the Account's deployable-Subnet discovery and returns it\n * with the origin of its API. Throws a plain `Error` that names no place\n * when discovery advertises no API host for it.\n */\nasync function discover(\n state: ServiceState,\n accountId: AccountId,\n slug: SubnetSlug,\n): Promise<AssignedPlacement> {\n const discovery = asRecord(\n await state.transport.json<unknown>(\n \"GET\",\n state.endpoints.api,\n account(accountId, \"deployable-subnet-identities\"),\n ),\n );\n const identities = discovery[\"identities\"];\n const identity = (Array.isArray(identities) ? identities : [])\n .map(asRecord)\n .find((candidate) => candidate[\"slug\"] === slug);\n const host =\n identity === undefined\n ? \"\"\n : stringField(asRecord(identity[\"hosts\"]), \"api\");\n if (host === \"\") {\n throw new Error(\"IDYL advertises no computer API for this account\");\n }\n let endpoint: string;\n try {\n endpoint = endpointForHost(state.scheme, host);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n `computer API host: ${errorMessage(cause)}`,\n { cause },\n );\n }\n const zone = identity === undefined ? \"\" : stringField(identity, \"zone\");\n return { subnet: slug, endpoint, zone };\n}\n\n/**\n * A response read leniently: a value that is not an object reads as an\n * empty one, so a missing field is judged by the rule that consumes it\n * rather than by a schema.\n */\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction stringField(record: Record<string, unknown>, key: string): string {\n const value = record[key];\n return typeof value === \"string\" ? value : \"\";\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/**\n * The package version, kept equal to `package.json` by test. It is the only\n * place the version is spelled in source.\n */\nexport const SDK_VERSION = \"0.1.0\";\n\n/** The `User-Agent` sent when a client does not override it. */\nexport const DEFAULT_USER_AGENT = `idyl-sdk-typescript/${SDK_VERSION}`;\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The product a client names on every request it sends to the IDYL API, in\n * the `Idyl-Client` header, and the one judgement of what that name may be.\n */\nimport { InvalidClientProductError } from \"./errors.js\";\nimport { SDK_VERSION } from \"./internal/version.js\";\n\n/**\n * Names the program on whose behalf the SDK sends requests. It is sent on\n * every request to the IDYL API, event streams included, as the\n * `Idyl-Client` header with the value `<name>/<version>`, so each request\n * names exactly one product. The API can refuse a release below the minimum\n * version it supports for that product with the code\n * {@link ERROR_CODE_CLIENT_UPGRADE_REQUIRED}; see\n * {@link isClientUpgradeRequired}.\n *\n * A client configured without one names the SDK itself:\n * `idyl-sdk-typescript` and the package version. A program with its own\n * release line, such as a web console or a command-line tool built on the\n * SDK, names itself instead so the minimum that applies is its own.\n */\nexport interface ClientProduct {\n /**\n * The product token: a lowercase ASCII letter followed by at most 63\n * lowercase ASCII letters, digits, or hyphens, such as `idyl-console`.\n */\n readonly name: string;\n /**\n * The product's release: `dev` for a build that records no release, or a\n * Semantic Versioning 2.0.0 version without a leading `v`, such as\n * `0.2.7`, `1.0.0-rc.1`, or `1.0.0+build.5`.\n */\n readonly version: string;\n}\n\n/** The product the SDK names when a client does not name its own. */\nconst SDK_PRODUCT = \"idyl-sdk-typescript\";\n/** The version of a build that records no release. */\nconst DEV_VERSION = \"dev\";\n\nconst PRODUCT_PATTERN = /^[a-z][a-z0-9-]{0,63}$/u;\n/**\n * The Semantic Versioning 2.0.0 grammar without a leading `v`: numeric\n * identifiers carry no leading zeros, and the prerelease and build parts\n * are optional.\n */\nconst VERSION_PATTERN = new RegExp(\n \"^(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\" +\n \"(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\\\\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?\" +\n \"(\\\\+[0-9a-zA-Z-]+(\\\\.[0-9a-zA-Z-]+)*)?$\",\n \"u\",\n);\n\n/**\n * The `Idyl-Client` header value `product` names: `<name>/<version>`, or\n * the SDK's own product and package version when `product` is `undefined`\n * or names neither field. Throws an {@link InvalidClientProductError} when\n * exactly one field is set or either breaks its grammar.\n */\nexport function clientIdentification(\n product: ClientProduct | undefined,\n): string {\n if (\n product === undefined ||\n (product.name === \"\" && product.version === \"\")\n ) {\n return identification(SDK_PRODUCT, sdkVersion());\n }\n if (product.name === \"\" || product.version === \"\") {\n throw new InvalidClientProductError(\"name and version must both be set\");\n }\n if (!PRODUCT_PATTERN.test(product.name)) {\n throw new InvalidClientProductError(\n `product ${JSON.stringify(product.name)} must be a lowercase letter followed by at most 63 lowercase letters, digits, or hyphens`,\n );\n }\n if (\n product.version !== DEV_VERSION &&\n !VERSION_PATTERN.test(product.version)\n ) {\n throw new InvalidClientProductError(\n `version ${JSON.stringify(product.version)} must be \"${DEV_VERSION}\" or a semantic version without a leading v`,\n );\n }\n return identification(product.name, product.version);\n}\n\n/** The package version when it is a semantic version, otherwise `dev`. */\nfunction sdkVersion(): string {\n return VERSION_PATTERN.test(SDK_VERSION) ? SDK_VERSION : DEV_VERSION;\n}\n\nfunction identification(name: string, version: string): string {\n return `${name}/${version}`;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { keyPairProblem, keyProfile } from \"./internal/dpop.js\";\n\n/**\n * An access token and the key it is bound to.\n *\n * Every token IDYL issues is bound to a key its holder keeps (RFC 9449,\n * DPoP) and is accepted only with a proof of possession of that key made\n * for the one request it accompanies. The package signs that proof with\n * `key` for every request, retries included. `key` is a WebCrypto key pair\n * of an Ed25519 or ECDSA P-256 key; its private half may be\n * non-extractable, since only `crypto.subtle.sign` is used, and it never\n * leaves the runtime's key store through the package.\n */\nexport interface Credential {\n /** The access token, presented as issued and never inspected. */\n readonly accessToken: string;\n /** The key pair the token is bound to, which signs each request's proof. */\n readonly key: CryptoKeyPair;\n}\n\n/** What a {@link CredentialSource} receives when a request needs a credential. */\nexport interface CredentialContext {\n /**\n * Aborted when the request is cancelled or exceeds its timeout. A source\n * that performs its own network call passes this signal through so a\n * cancelled request does not leave a token exchange running.\n */\n readonly signal: AbortSignal;\n}\n\n/**\n * Supplies the credential for a request. `credential` is called for every\n * authenticated request rather than once at construction, so a source that\n * refreshes or rotates a short-lived token is adopted without rebuilding\n * the client.\n *\n * Every token is opaque to the package: it is presented with a proof and\n * never inspected, logged, or stored beyond its own request. A source may be\n * consulted concurrently by requests in flight at once.\n */\nexport interface CredentialSource {\n /**\n * Returns the credential for one request. A rejection fails that request\n * with the source's error, and the next request asks again.\n *\n * @param context The request's context, whose `signal` ends when the\n * request is cancelled.\n * @throws {@link Error} whatever the source throws or rejects with; the\n * request fails with it and sends nothing\n */\n credential(context: CredentialContext): Credential | Promise<Credential>;\n}\n\n/**\n * A fixed access token and its key. An access token expires within an hour,\n * so prefer a refreshing {@link CredentialSource}, such as\n * `accessKeyCredentials`, for a long-running program.\n *\n * @param accessToken An access token IDYL issued for `key`.\n * @param key The Ed25519 or ECDSA P-256 key pair the token is bound to.\n * @throws {@link TypeError} `accessToken` is empty or contains whitespace or\n * control characters, or `key` is not an Ed25519 or ECDSA P-256 key pair\n * whose private key may sign\n */\nexport function staticCredential(\n accessToken: string,\n key: CryptoKeyPair,\n): CredentialSource {\n const problem =\n typeof accessToken === \"string\" ? tokenProblem(accessToken) : \"is required\";\n if (problem !== undefined) {\n throw new TypeError(`credential access token ${problem}`);\n }\n const keyProblem = keyPairProblem(key);\n if (keyProblem !== undefined) {\n throw new TypeError(`credential key ${keyProblem}`);\n }\n const credential: Credential = Object.freeze({ accessToken, key });\n return Object.freeze({ credential: () => credential });\n}\n\n/**\n * Adapts a function into a {@link CredentialSource}. The function is called\n * for every authenticated request with the request's\n * {@link CredentialContext}.\n *\n * @param source Returns the credential for one request, or a promise of one.\n * @throws {@link TypeError} `source` is not a function\n */\nexport function credentialSourceFunc(\n source: (context: CredentialContext) => Credential | Promise<Credential>,\n): CredentialSource {\n if (typeof source !== \"function\") {\n throw new TypeError(\"credential source function is required\");\n }\n return Object.freeze({\n credential: (context: CredentialContext) => source(context),\n });\n}\n\n/**\n * The RFC 7638 SHA-256 thumbprint of an Ed25519 or ECDSA P-256 public key,\n * unpadded base64url: the `cnf.jkt` of every token bound to the key, and\n * the `dpopJkt` a browser hand-off names. The key's JWK is exported once\n * and kept while the key is.\n *\n * @param publicKey The public half of an Ed25519 or ECDSA P-256 key pair.\n * @throws {@link TypeError} `publicKey` is any other key, or its public half\n * cannot be exported\n */\nexport async function keyThumbprint(publicKey: CryptoKey): Promise<string> {\n return (await keyProfile(publicKey)).thumbprint;\n}\n\n/**\n * Reports why `token` cannot be presented as a credential, or `undefined`\n * when it can. The wording completes a sentence that names the token's\n * origin.\n */\nexport function tokenProblem(token: string): string | undefined {\n if (token.length === 0 || token.trim().length === 0) return \"is empty\";\n if (/\\s/u.test(token)) return \"contains whitespace\";\n for (const character of token) {\n const code = character.codePointAt(0) ?? 0;\n if (code < 0x20 || code === 0x7f) return \"contains control characters\";\n }\n return undefined;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * What the SDK knows about the runtime it is loaded in. It answers one\n * question, whether the runtime is a browser document, from the global\n * object alone, and it is the only place that question is asked. One\n * behaviour follows from the answer: who owns the `User-Agent` header.\n */\n\n/** The globals a browser document defines and every other runtime lacks. */\ninterface DocumentScope {\n readonly window?: unknown;\n readonly document?: unknown;\n}\n\n/**\n * Reports whether `scope`, the global object by default, is a browser\n * document. A runtime is one when its global object carries both `window`\n * and `document` as objects: Node.js, Bun, Deno, and Workers-class\n * runtimes define neither together.\n */\nexport function isBrowserDocument(scope: object = globalThis): boolean {\n const { window, document } = scope as DocumentScope;\n return isObject(window) && isObject(document);\n}\n\n/**\n * Reports whether `scope`, the global object by default, is a browser\n * document, where the browser owns the `User-Agent` header. A browser sets\n * that header itself on every request. Chromium discards a value a script\n * sets; WebKit and Gecko send it, but as a header outside the CORS\n * safelist, so a cross-origin request carrying it needs the server's\n * preflight to admit `user-agent` and fails when it does not. The transport\n * therefore leaves the default `User-Agent` to the browser here and sends\n * it everywhere else.\n */\nexport function browserOwnsUserAgent(scope: object = globalThis): boolean {\n return isBrowserDocument(scope);\n}\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && value !== null;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseJson, stringifyJson } from \"../resource/json.js\";\n/*\n * The HTTP layer. It builds a request against a base URL and a caller-supplied\n * path, presents the key-bound credential with a fresh proof of possession of\n * its key, reads the response under fixed size bounds, and turns a non-2xx\n * status into an ApiError. It knows nothing about IDYL routes: no path is\n * spelled here and no policy about which endpoint serves what lives here. It\n * decides only what is true of every request the SDK makes: every proof names\n * exactly the request it accompanies, credentials are never replayed across a\n * redirect, a response body cannot grow without bound, and an error body is\n * never trusted to be an envelope.\n */\nimport { errorMessage } from \"../resource/validation.js\";\nimport { clientIdentification, type ClientProduct } from \"../client-product.js\";\nimport type { Credential, CredentialSource } from \"../credential.js\";\nimport { tokenProblem } from \"../credential.js\";\nimport { type ApiError, apiError, TransportError } from \"../errors.js\";\nimport type { JsonObject, JsonValue } from \"../resource/json.js\";\nimport { abortable, managedSignal } from \"./abort.js\";\nimport { browserOwnsUserAgent } from \"./browser.js\";\nimport {\n contentDigest,\n hash,\n keyPairProblem,\n ProofClock,\n proofRefused,\n prove,\n} from \"./dpop.js\";\nimport { DEFAULT_USER_AGENT } from \"./version.js\";\n\n/** The default per-request timeout, in milliseconds. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n/**\n * The request header naming the one product a request is sent on behalf of,\n * as `<product>/<version>`. The API applies the minimum supported version of\n * exactly that product.\n */\nconst CLIENT_HEADER = \"idyl-client\";\n/** The largest success body the transport reads, in bytes. */\nexport const MAX_SUCCESS_BODY_BYTES = 16 * 1024 * 1024;\n/** The largest error body the transport reads, in bytes. */\nexport const MAX_ERROR_BODY_BYTES = 64 * 1024;\n/**\n * How much of a non-envelope error body is carried into the error message;\n * the rest is summarized by length.\n */\nconst MAX_FALLBACK_ERROR_MESSAGE_BYTES = 512;\n\n/** The `fetch` function the transport calls. */\nexport type Fetch = typeof globalThis.fetch;\n\n/** What builds a {@link Transport}. */\nexport interface TransportOptions {\n /**\n * Supplies the credential of every authenticated request. `undefined`\n * builds a transport whose authenticated requests are refused with a\n * `TypeError` before anything is sent.\n */\n readonly credential?: CredentialSource;\n /**\n * The clock proofs state, shared by the transports of one client so each\n * learns the API's time from every response. `undefined` gives the\n * transport a clock of its own.\n */\n readonly clock?: ProofClock;\n /**\n * Performs every request. It is called with no receiver, exactly as a\n * caller writing `fetch(url, init)` would call it, and is bound to\n * nothing. `undefined` uses `globalThis.fetch`; construction fails when\n * neither exists.\n */\n readonly fetch?: Fetch;\n /** Bounds each request, in milliseconds. `undefined` allows 30000. */\n readonly requestTimeoutMs?: number;\n /**\n * Overrides the `User-Agent`. `undefined` or blank sends the SDK default\n * where the SDK sends one: in a browser document the browser owns that\n * header and the default is left to it, while an explicit value is sent\n * on every runtime. See {@link browserOwnsUserAgent}.\n */\n readonly userAgent?: string;\n /**\n * The product named in the `Idyl-Client` header of every request.\n * `undefined` names the SDK itself. Construction throws an\n * `InvalidClientProductError` when it is partially set or malformed.\n */\n readonly clientProduct?: ClientProduct;\n /** Admits `http:` base URLs, for local development and tests only. */\n readonly allowHttp?: boolean;\n}\n\n/** Per-request options. */\nexport interface RequestOptions {\n /** Cancels the request, the credential lookup, and the body read. */\n readonly signal?: AbortSignal;\n /** Encoded as the JSON request body; absent sends no body. */\n readonly body?: unknown;\n /**\n * `json` decodes exactly one JSON value; `none` expects no body and drains\n * one if present. `undefined` reads `json`.\n */\n readonly response?: \"json\" | \"none\";\n /** Additional request headers, added after the SDK's own. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Refuses a request whose encoded body exceeds this many bytes, with a\n * `TypeError` naming the size and the bound, before any credential is\n * consulted or byte is sent. `undefined` sends a body of any size.\n */\n readonly maxRequestBodyBytes?: number;\n /**\n * The disclosure allow-list of a route that carries secret material. The\n * status and the stable code of an error always reach the caller; the\n * server's message and details reach it only when this reports the code\n * as safe, and every other message is replaced with a fixed one so no\n * server-controlled text can carry material into a caller's logs.\n * `undefined` relays every message.\n */\n readonly safeErrorCode?: (code: string) => boolean;\n}\n\n/**\n * The errors raised because the injected `fetch` itself rejected: the\n * exchange failed before any response, as a refused connection, a reset, a\n * failed name lookup, or a TLS failure does. They are recorded by identity\n * so the error a caller receives stays a plain `Error`.\n */\nconst fetchFailures = new WeakSet<Error>();\n\n/**\n * Whether `error` is a request whose `fetch` rejected before any response:\n * a failure of the connection rather than an answer from the platform.\n */\nexport function isFetchFailure(error: unknown): boolean {\n return error instanceof Error && fetchFailures.has(error);\n}\n\n/**\n * What an identity exchange presents in place of the credential source's\n * credential: the key it proves and, when it has one, the refresh token\n * bound to that key. A refresh token is bound by its key alone, so a proof\n * that presents one names no token hash.\n */\nexport interface Presentation {\n readonly key: CryptoKeyPair;\n readonly refreshToken?: string;\n}\n\n/** What one request presents: a key, and the token bound to it if any. */\ninterface Presented {\n readonly key: CryptoKeyPair;\n readonly token?: string;\n /** The hash of an access token, which the proof names as `ath`. */\n readonly ath?: string;\n}\n\n/** How a request authenticates. */\ntype Authentication = \"source\" | \"anonymous\" | Presentation;\n\n/**\n * Performs JSON requests. One instance is shared by a client and every client\n * scoped from it, and it is safe to use concurrently.\n */\nexport class Transport {\n readonly #credential: CredentialSource | undefined;\n readonly #clock: ProofClock;\n readonly #fetch: Fetch;\n readonly #requestTimeoutMs: number;\n readonly #userAgent: string | undefined;\n readonly #clientIdentification: string;\n readonly #allowHttp: boolean;\n /** The last access token presented and its hash, computed once per token. */\n #ath: { readonly token: string; readonly hash: Promise<string> } | undefined;\n\n constructor(options: TransportOptions) {\n if (\n options.credential !== undefined &&\n typeof (options.credential as Partial<CredentialSource>).credential !==\n \"function\"\n ) {\n throw new TypeError(\"credential must be a CredentialSource\");\n }\n const timeout = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new TypeError(\"requestTimeoutMs must be greater than zero\");\n }\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n if (typeof fetchImplementation !== \"function\") {\n throw new TypeError(\n \"fetch is unavailable in this runtime; supply one in the configuration\",\n );\n }\n const userAgent = options.userAgent?.trim() ?? \"\";\n this.#clientIdentification = clientIdentification(options.clientProduct);\n this.#credential = options.credential;\n this.#clock = options.clock ?? new ProofClock();\n this.#fetch = fetchImplementation;\n this.#requestTimeoutMs = timeout;\n this.#userAgent =\n userAgent !== \"\"\n ? userAgent\n : browserOwnsUserAgent()\n ? undefined\n : DEFAULT_USER_AGENT;\n this.#allowHttp = options.allowHttp ?? false;\n }\n\n /**\n * Sends an authenticated request to `origin` + `path` and decodes its JSON\n * response. `path` begins with a slash and may carry a query string. The\n * credential source is consulted once for this request under the\n * request's signal, so a cancelled request never leaves a token lookup\n * running, and every attempt carries a proof of its own.\n */\n async json<T>(\n method: string,\n origin: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n return (await this.#send(method, origin, path, options, \"source\")) as T;\n }\n\n /**\n * Sends a request with no credential and no proof. It exists for the\n * documented identity endpoints and the network's public metadata and\n * Computer sizes, whose contract is anonymous; every other request goes\n * through {@link json}.\n */\n async anonymousJson<T>(\n method: string,\n origin: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n return (await this.#send(method, origin, path, options, \"anonymous\")) as T;\n }\n\n /**\n * Sends an identity exchange: a request that proves `presentation.key`\n * and presents the refresh token bound to it, or no token at all, in\n * place of the credential source's credential. The refresh token and the\n * key are judged before anything is sent, and a refusal never names the\n * token.\n */\n async exchangeJson<T>(\n method: string,\n origin: string,\n path: string,\n presentation: Presentation,\n options: RequestOptions = {},\n ): Promise<T> {\n return (await this.#send(method, origin, path, options, presentation)) as T;\n }\n\n /**\n * Opens caller-owned saved content with caller cancellation and no transfer\n * timeout. `conditions` are request headers such as `Range`; judging the\n * answer to them is the caller's.\n */\n async openContent(\n origin: string,\n path: string,\n accept: string,\n signal: AbortSignal | undefined,\n conditions?: Readonly<Record<string, string>>,\n method = \"GET\",\n ): Promise<Response> {\n return await this.#content(\n method,\n origin,\n path,\n accept,\n undefined,\n undefined,\n signal,\n conditions,\n );\n }\n\n /**\n * Sends a body and reads one bounded JSON receipt. Bytes are sent as they\n * are, which every runtime supports; a stream is sent as a streaming\n * request body, which not every browser does. Neither carries a\n * `Content-Digest`: a transfer part's integrity rides the digest its query\n * names, which the proof covers.\n */\n async sendContent(\n origin: string,\n path: string,\n contentType: string,\n body: Uint8Array<ArrayBuffer> | ReadableStream<Uint8Array>,\n signal: AbortSignal | undefined,\n ): Promise<unknown> {\n const response = await this.#content(\n \"PUT\",\n origin,\n path,\n \"application/json\",\n contentType,\n body,\n signal,\n );\n return decodeOne(\n await bodyRead(\"PUT\", signal ?? new AbortController().signal, () =>\n readBodyLimited(response, MAX_SUCCESS_BODY_BYTES),\n ),\n );\n }\n\n async #content(\n method: string,\n origin: string,\n path: string,\n accept: string,\n contentType: string | undefined,\n body: Uint8Array<ArrayBuffer> | ReadableStream<Uint8Array> | undefined,\n signal: AbortSignal | undefined,\n conditions?: Readonly<Record<string, string>>,\n ): Promise<Response> {\n const target = resolveTarget(origin, path, this.#allowHttp);\n const requestSignal = signal ?? new AbortController().signal;\n requestSignal.throwIfAborted();\n const headers = new Headers({ accept, ...conditions });\n if (this.#userAgent !== undefined)\n headers.set(\"user-agent\", this.#userAgent);\n headers.set(CLIENT_HEADER, this.#clientIdentification);\n if (contentType !== undefined) headers.set(\"content-type\", contentType);\n const presented = await this.#sourceCredential(requestSignal);\n const init: RequestInit & {\n readonly signal: AbortSignal;\n readonly headers: Headers;\n readonly duplex?: \"half\";\n } = {\n method,\n headers,\n signal: requestSignal,\n ...(body === undefined\n ? {}\n : body instanceof ReadableStream\n ? { body, duplex: \"half\" as const }\n : { body }),\n };\n const failure = `${method} content transfer failed`;\n // A stream is read as it is sent, so only a request whose body can be\n // sent again is retried after a refused proof.\n const replayable = !(body instanceof ReadableStream);\n let response = await this.#attempt(target, init, presented, failure);\n if (replayable && proofRefused(response)) {\n await discardBody(response);\n response = await this.#attempt(target, init, presented, failure);\n }\n if (!response.ok) throw await decodeApiError(response);\n return response;\n }\n\n /**\n * The credential source's credential for one request, resolved under\n * `signal` and judged for shape. Throws a `TypeError` naming the source\n * when it returns something that cannot be presented, and when the\n * transport has no source at all.\n */\n async #sourceCredential(signal: AbortSignal): Promise<Presented> {\n const source = this.#credential;\n if (source === undefined) {\n throw new TypeError(\"credential is required for authenticated requests\");\n }\n const credential: unknown = await abortable(\n Promise.resolve()\n .then(() => source.credential({ signal }))\n .catch((cause: unknown) => {\n // A source that rejects with something other than an error is\n // reported as its own failure, the rejection kept as the cause.\n throw cause instanceof Error\n ? cause\n : new TypeError(\"credential source rejected\", { cause });\n }),\n signal,\n );\n if (typeof credential !== \"object\" || credential === null) {\n throw new TypeError(\"credential source returned no credential\");\n }\n const { accessToken, key } = credential as Partial<Credential>;\n if (typeof accessToken !== \"string\") {\n throw new TypeError(\n \"credential source returned a non-string access token\",\n );\n }\n const problem = tokenProblem(accessToken);\n if (problem !== undefined) {\n throw new TypeError(\n `credential source returned an access token that ${problem}`,\n );\n }\n if (key === undefined) {\n throw new TypeError(\"credential source returned no key\");\n }\n const keyProblem = keyPairProblem(key);\n if (keyProblem !== undefined) {\n throw new TypeError(\n `credential source returned a key that ${keyProblem}`,\n );\n }\n return { key, token: accessToken, ath: await this.#hashOf(accessToken) };\n }\n\n /** The hash of an access token, computed once while it is the current one. */\n async #hashOf(token: string): Promise<string> {\n if (this.#ath?.token !== token) {\n this.#ath = { token, hash: hash(token) };\n }\n return await this.#ath.hash;\n }\n\n /**\n * One attempt of a request: the credential's headers and a fresh proof\n * for exactly this request, set last so the proof covers the headers the\n * request carries, then the request itself. `digest` is the request body's\n * `Content-Digest`, sent and proved with it.\n */\n async #attempt(\n target: URL,\n init: RequestInit & {\n readonly signal: AbortSignal;\n readonly headers: Headers;\n },\n presented: Presented | undefined,\n failure: string,\n digest?: string,\n ): Promise<Response> {\n if (presented !== undefined) {\n const { headers } = init;\n if (presented.token === undefined) headers.delete(\"authorization\");\n else headers.set(\"authorization\", `DPoP ${presented.token}`);\n if (digest !== undefined) headers.set(\"content-digest\", digest);\n headers.set(\n \"dpop\",\n await prove(presented.key, {\n method: init.method ?? \"GET\",\n url: target,\n headers,\n now: this.#clock.now(),\n ...(presented.ath === undefined ? {} : { ath: presented.ath }),\n ...(digest === undefined ? {} : { contentDigest: digest }),\n }),\n );\n // Signing completes off the caller's turn; a request cancelled\n // meanwhile is never sent.\n if (init.signal.aborted) throw init.signal.reason;\n }\n return await this.#dispatch(target, init, failure);\n }\n\n /**\n * Performs one request through the configured `fetch` and returns a\n * response that is not a redirect. `init` is sent with `redirect` set to\n * `manual`, the one mode every runtime accepts, so a redirect the server\n * chose is handed back instead of followed, and it is refused here before\n * anything else about the response is consulted: a response whose `type`\n * is `opaqueredirect`, the shape a browser hands back with status 0, or\n * whose status is 300 through 399 fails as a `TransportError` with code\n * `redirect_refused` and the fixed sentence `redirect refused`, its body\n * discarded unread and its headers never read, so no credential is\n * replayed, no second request is made, and nothing the redirecting peer\n * wrote reaches a caller's logs. Any other response's `Date` sets the\n * clock proofs state. `fetch` is called with no receiver: a\n * browser implements it as an operation of its global object and refuses\n * any other receiver with a `TypeError`, so the held function is never\n * invoked as a method of the transport, and an injected implementation is\n * called exactly as a caller writing `fetch(url, init)` would call it. A\n * `fetch` that rejects fails with `failure` as the message and the\n * rejection as `cause`, unless `init.signal` was aborted, in which case\n * the signal's reason is thrown.\n */\n async #dispatch(\n target: URL,\n init: RequestInit & { readonly signal: AbortSignal },\n failure: string,\n ): Promise<Response> {\n let response: Response;\n try {\n const fetchImplementation = this.#fetch;\n response = await fetchImplementation(target, {\n ...init,\n redirect: \"manual\",\n });\n } catch (cause) {\n if (init.signal.aborted) throw init.signal.reason;\n const error = new TransportError(\"network_error\", failure, { cause });\n fetchFailures.add(error);\n throw error;\n }\n if (isRedirect(response)) {\n await discardBody(response);\n throw new TransportError(\"redirect_refused\", \"redirect refused\");\n }\n this.#clock.observe(response);\n return response;\n }\n\n async #send(\n method: string,\n origin: string,\n path: string,\n options: RequestOptions,\n authentication: Authentication,\n ): Promise<unknown> {\n const target = resolveTarget(origin, path, this.#allowHttp);\n const explicit =\n typeof authentication === \"object\"\n ? presentationOf(authentication)\n : undefined;\n const managed = managedSignal(\n options.signal,\n this.#requestTimeoutMs,\n `request exceeded ${String(this.#requestTimeoutMs)} ms`,\n );\n try {\n managed.signal.throwIfAborted();\n let body: string | undefined;\n if (options.body !== undefined) {\n body = stringifyJson(options.body as JsonValue);\n const limit = options.maxRequestBodyBytes;\n if (limit !== undefined) {\n const size = new TextEncoder().encode(body).byteLength;\n if (size > limit) {\n throw new TypeError(\n `request body is ${String(size)} bytes, maximum is ${String(limit)}`,\n );\n }\n }\n }\n const headers = new Headers({ accept: \"application/json\" });\n if (this.#userAgent !== undefined) {\n headers.set(\"user-agent\", this.#userAgent);\n }\n if (body !== undefined) headers.set(\"content-type\", \"application/json\");\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n headers.set(name, value);\n }\n // Set last so a request names exactly one product whatever extra\n // headers it carries.\n headers.set(CLIENT_HEADER, this.#clientIdentification);\n const presented =\n authentication === \"source\"\n ? await this.#sourceCredential(managed.signal)\n : explicit;\n // `fetch` sends a string body as its UTF-8 bytes, the bytes the\n // digest is computed over.\n const digest =\n presented === undefined || body === undefined\n ? undefined\n : await contentDigest(new TextEncoder().encode(body));\n const init = {\n method,\n headers,\n signal: managed.signal,\n ...(body === undefined ? {} : { body }),\n };\n const failure = `${method} request failed`;\n let response = await this.#attempt(\n target,\n init,\n presented,\n failure,\n digest,\n );\n // A proof refused, as one stating a skewed time is, is retried once\n // with a fresh proof at the clock the refusal's `Date` set.\n if (presented !== undefined && proofRefused(response)) {\n await discardBody(response);\n response = await this.#attempt(\n target,\n init,\n presented,\n failure,\n digest,\n );\n }\n if (!response.ok) {\n throw await decodeApiError(response, options.safeErrorCode);\n }\n if (options.response === \"none\" || response.status === 204) {\n await bodyRead(method, managed.signal, () =>\n drainBody(response, MAX_SUCCESS_BODY_BYTES),\n );\n return undefined;\n }\n const bytes = await bodyRead(method, managed.signal, () =>\n readBodyLimited(response, MAX_SUCCESS_BODY_BYTES),\n );\n return decodeOne(bytes);\n } catch (error) {\n // The request timeout aborts the managed signal while the caller's own\n // signal stays live; only that abort is the transport's timeout.\n if (managed.signal.aborted && options.signal?.aborted !== true) {\n throw new TransportError(\n \"timeout\",\n `request exceeded ${String(this.#requestTimeoutMs)} ms`,\n { cause: error },\n );\n }\n throw error;\n } finally {\n managed.cleanup();\n }\n }\n}\n\n/**\n * An identity exchange's presentation, judged before anything is sent: a\n * refresh token, when there is one, that can be presented, and a key pair\n * that can sign. A refusal names the field, never the token.\n */\nfunction presentationOf(presentation: Presentation): Presented {\n const { key, refreshToken } = presentation;\n if (refreshToken !== undefined) {\n const problem =\n typeof refreshToken === \"string\"\n ? tokenProblem(refreshToken)\n : \"is required\";\n if (problem !== undefined) throw new TypeError(`refresh token ${problem}`);\n }\n const problem = keyPairProblem(key);\n if (problem !== undefined) throw new TypeError(`key ${problem}`);\n return refreshToken === undefined ? { key } : { key, token: refreshToken };\n}\n\nfunction resolveTarget(origin: string, path: string, allowHttp: boolean): URL {\n if (!path.startsWith(\"/\")) {\n throw new TypeError(\n `request path ${JSON.stringify(path)} must begin with /`,\n );\n }\n const base = new URL(origin);\n if (base.protocol !== \"https:\" && !(allowHttp && base.protocol === \"http:\")) {\n throw new TypeError(\"request origin must use https\");\n }\n const target = new URL(path, base);\n if (target.origin !== base.origin) {\n throw new TypeError(\"request path must not change the origin\");\n }\n target.hash = \"\";\n return target;\n}\n\n/**\n * Reads a non-2xx response as an ApiError. With `safeErrorCode`, the body\n * is held to the disclosure posture of a secret-carrying route: the status\n * and the code are always relayed, and the message and details only under\n * a code the allow-list names; anything else, a code outside the list or a\n * body that is not the envelope at all, is replaced with a fixed message.\n */\nasync function decodeApiError(\n response: Response,\n safeErrorCode?: (code: string) => boolean,\n): Promise<ApiError> {\n const metadata = responseMetadata(response);\n let bytes: Uint8Array;\n try {\n bytes = await readBodyLimited(response, MAX_ERROR_BODY_BYTES);\n } catch (cause) {\n return apiError({\n status: response.status,\n message: `API error response could not be read: ${errorMessage(cause)}`,\n ...metadata,\n cause,\n });\n }\n const text = decodeUtf8(bytes).trim();\n let envelope = parseErrorEnvelope(text);\n if (safeErrorCode !== undefined && !safeErrorCode(envelope.code ?? \"\")) {\n envelope = {\n error: \"request failed\",\n ...(envelope.code === undefined ? {} : { code: envelope.code }),\n };\n }\n let message = envelope.error;\n if (message === \"\") message = truncateFallbackErrorMessage(text);\n return apiError({\n status: response.status,\n message,\n ...(envelope.code === undefined ? {} : { code: envelope.code }),\n ...(envelope.details === undefined ? {} : { details: envelope.details }),\n ...metadata,\n });\n}\n\ninterface ErrorEnvelope {\n readonly error: string;\n readonly code?: string;\n readonly details?: JsonObject;\n}\n\n/**\n * Reads the error envelope leniently: a body that is not one yields an empty\n * envelope rather than a failure, so the bounded raw text becomes the message.\n */\nfunction parseErrorEnvelope(text: string): ErrorEnvelope {\n let body: unknown;\n try {\n body = text === \"\" ? undefined : parseJson(text);\n } catch {\n return { error: \"\" };\n }\n if (!isRecord(body)) return { error: \"\" };\n const error = typeof body[\"error\"] === \"string\" ? body[\"error\"].trim() : \"\";\n const code = typeof body[\"code\"] === \"string\" ? body[\"code\"] : undefined;\n const details = isRecord(body[\"details\"]) ? body[\"details\"] : undefined;\n return {\n error,\n ...(code === undefined ? {} : { code }),\n ...(details === undefined ? {} : { details }),\n };\n}\n\nfunction responseMetadata(response: Response): {\n readonly requestId?: string;\n readonly retryAfterMs?: number;\n} {\n const requestId = response.headers.get(\"x-request-id\");\n const retryAfterMs = parseRetryAfter(\n response.headers.get(\"retry-after\"),\n Date.now(),\n );\n return {\n ...(requestId === null || requestId === \"\" ? {} : { requestId }),\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n };\n}\n\n/**\n * Reads `Retry-After` as a non-negative number of delay seconds or as an HTTP\n * date. A date in the past yields zero; a header that is absent or unreadable\n * yields `undefined`. Only a value that names a month is read as a date, so a\n * malformed number is unreadable rather than a date invented from its digits.\n */\nexport function parseRetryAfter(\n raw: string | null,\n now: number,\n): number | undefined {\n if (raw === null) return undefined;\n const value = raw.trim();\n if (/^[0-9]+$/u.test(value)) return Number(value) * 1_000;\n if (!/[A-Za-z]/u.test(value)) return undefined;\n const at = Date.parse(value);\n if (!Number.isFinite(at)) return undefined;\n return Math.max(0, at - now);\n}\n\nfunction truncateFallbackErrorMessage(message: string): string {\n const bytes = new TextEncoder().encode(message);\n if (bytes.byteLength <= MAX_FALLBACK_ERROR_MESSAGE_BYTES) return message;\n const prefix = new TextDecoder(\"utf-8\", { fatal: false }).decode(\n bytes.subarray(0, MAX_FALLBACK_ERROR_MESSAGE_BYTES),\n { stream: true },\n );\n return `${prefix}... (truncated, ${String(bytes.byteLength)} bytes total)`;\n}\n\nasync function drainBody(response: Response, limit: number): Promise<void> {\n if (response.body === null) return;\n try {\n await readBodyLimited(response, limit);\n } catch {\n // A body that was not expected is discarded whatever its size.\n }\n}\n\n/**\n * Reports whether a response handed back under `redirect: \"manual\"` is a\n * redirect. A browser hands back an opaque redirect, `type` `opaqueredirect`\n * with status 0 and nothing else; every other runtime hands back the 3xx\n * response itself.\n */\nfunction isRedirect(response: Response): boolean {\n return (\n response.type === \"opaqueredirect\" ||\n (response.status >= 300 && response.status <= 399)\n );\n}\n\n/**\n * Releases a body that will not be read, so a runtime that holds a\n * connection open for an unconsumed body does not keep it. Cancelling\n * settles the stream without pulling a byte from it.\n */\nasync function discardBody(response: Response): Promise<void> {\n try {\n await response.body?.cancel();\n } catch {\n // A body that refuses cancellation is left to the runtime; the\n // response is refused either way.\n }\n}\n\n/**\n * Reads the whole body, refusing one that declares or delivers more than\n * `limit` bytes. An over-limit stream is cancelled so the connection is not\n * left draining.\n */\nasync function readBodyLimited(\n response: Response,\n limit: number,\n): Promise<Uint8Array> {\n const declared = response.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > limit) {\n await response.body?.cancel();\n throw new TransportError(\n \"response_too_large\",\n `response body exceeds ${String(limit)} bytes`,\n );\n }\n if (response.body === null) return new Uint8Array();\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > limit) {\n await reader.cancel();\n throw new TransportError(\n \"response_too_large\",\n `response body exceeds ${String(limit)} bytes`,\n );\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const result = new Uint8Array(length);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n}\n\n/**\n * Decodes exactly one JSON value. An empty body and a body carrying more than\n * one value are both rejected; unknown fields are carried as-is, which is the\n * read leniency the contract requires.\n */\nfunction decodeOne(bytes: Uint8Array): unknown {\n const text = decodeUtf8(bytes);\n if (text.trim() === \"\") {\n throw new TransportError(\n \"invalid_response\",\n \"decode response: empty response body\",\n );\n }\n try {\n return parseJson(text);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n \"decode response: expected exactly one JSON value\",\n { cause },\n );\n }\n}\n\n/**\n * Decodes a body as UTF-8, reading any byte sequence that is not as a\n * replacement character, as the reference contract reads it. A malformed byte is never a\n * reason to lose the status of an error response or to refuse a value the\n * server sent.\n */\nfunction decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder(\"utf-8\", { fatal: false }).decode(bytes);\n}\n\nfunction isRecord(value: unknown): value is Record<string, JsonValue> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Reads a response body. A read that fails because the connection did,\n * neither by an abort nor by the package's own bounds, is a\n * `TransportError` with code `network_error`, retried as a failed `fetch`\n * is.\n */\nasync function bodyRead<T>(\n method: string,\n signal: AbortSignal,\n read: () => Promise<T>,\n): Promise<T> {\n try {\n return await read();\n } catch (cause) {\n if (signal.aborted || cause instanceof TransportError) throw cause;\n throw bodyFailure(`${method} response body failed`, cause);\n }\n}\n\n/**\n * The `network_error` a body that broke off in transit is reported as,\n * recorded as a connection failure.\n */\nexport function bodyFailure(message: string, cause: unknown): TransportError {\n const error = new TransportError(\"network_error\", message, { cause });\n fetchFailures.add(error);\n return error;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n array,\n boolean,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { prefixed } from \"./validation.js\";\n\n/**\n * The network intent of a Computer's execution environment, independent of\n * its isolation class: an isolation class constrains compute isolation\n * only, and every network class is enforced by the host outside the\n * environment's sandbox. The tokens are the kebab-case taxonomy the\n * platform defines.\n *\n * - `none` requests no network access; egress rules cannot be combined\n * with it.\n * - `internet` requests outbound access to the public internet with every\n * local network denied: the host's own addresses, the networks the host\n * is directly connected to, and the private, shared, loopback,\n * link-local (cloud instance metadata included), multicast, and reserved\n * ranges. Name resolution reaches the resolvers the host is configured\n * with, and nothing else on a local network. Nothing outside the host can\n * open a connection to the environment. Egress rules cannot be combined\n * with it. It is the class settings that omit their network run with.\n * - `restricted-egress` requests deny-by-default networking where only the\n * destinations allowed by the egress block are reachable and local\n * networks stay denied. It is the only class that accepts an egress\n * block.\n * - `unrestricted` requests ordinary outbound access with no\n * platform-imposed egress filtering, local networks included; egress\n * rules cannot be combined with it.\n *\n * The union is open: a class the platform reports that this SDK does not\n * know is carried as a string rather than rejected on read.\n */\nexport type NetworkClass =\n | \"none\"\n | \"internet\"\n | \"restricted-egress\"\n | \"unrestricted\"\n | (string & Record<never, never>);\n\n/** Network intent. */\nexport interface WorkloadNetwork {\n /**\n * The requested network policy. Required whenever the network block is\n * present; settings that omit the whole block run with class `internet`.\n */\n readonly class?: NetworkClass;\n /** Allowed outbound destinations for a restricted-egress network. */\n readonly egress?: WorkloadNetworkEgress;\n}\n\n/** Restricted-egress allow intent. */\nexport interface WorkloadNetworkEgress {\n /**\n * Structured allow rules: `dns`, or `tcp:<port>:<dns-hostname>`. TCP\n * targets are DNS hostnames, never IP literals.\n */\n readonly allow?: readonly string[];\n /**\n * Must be `true` whenever `allow` is set. Local networks remain denied\n * while the listed destinations are allowed.\n */\n readonly denyLocalNetworks?: boolean;\n}\n\nexport const workloadNetworkEgressShape: Shape<WorkloadNetworkEgress> =\n object<WorkloadNetworkEgress>({\n allow: omitEmpty(array(string())),\n denyLocalNetworks: pointer(boolean()),\n });\n\nexport const workloadNetworkShape: Shape<WorkloadNetwork> =\n object<WorkloadNetwork>({\n class: omitEmpty(string<NetworkClass>()),\n egress: pointer(workloadNetworkEgressShape),\n });\n\n/**\n * Judges a network class a caller wrote: exactly the four supported\n * classes are accepted, and the empty string is reported as required.\n */\nexport function validateNetworkClass(networkClass: NetworkClass): void {\n switch (networkClass) {\n case \"none\":\n case \"internet\":\n case \"restricted-egress\":\n case \"unrestricted\":\n return;\n case \"\":\n throw new TypeError(\"network class is required\");\n default:\n throw new TypeError(\n `unknown network class ${JSON.stringify(networkClass)} (supported: none, internet, restricted-egress, unrestricted)`,\n );\n }\n}\n\n/**\n * Judges the network intent as a whole: the class is valid, an egress block\n * is only permitted with the `restricted-egress` class, and a\n * restricted-egress block carries well-formed allow rules with\n * `denyLocalNetworks` explicitly `true` whenever allow rules are present.\n * Throws a `TypeError` naming the first violation.\n */\nexport function validateWorkloadNetwork(network: WorkloadNetwork): void {\n validateWorkloadNetworkWith(network, validateWorkloadNetworkEgressAllowRule);\n}\n\n/**\n * {@link validateWorkloadNetwork}, holding each allow entry to `allowRule`.\n * Throws a `TypeError` naming the first violation.\n */\nexport function validateWorkloadNetworkWith(\n network: WorkloadNetwork,\n allowRule: (rule: string) => void,\n): void {\n const networkClass = network.class ?? \"\";\n validateNetworkClass(networkClass);\n switch (networkClass) {\n case \"none\":\n case \"internet\":\n case \"unrestricted\":\n if (network.egress !== undefined) {\n throw new TypeError(\n `network.egress is not supported with network.class ${networkClass}`,\n );\n }\n return;\n case \"restricted-egress\":\n validateRestrictedEgressPolicy(network.egress, allowRule);\n return;\n default:\n return;\n }\n}\n\nfunction validateRestrictedEgressPolicy(\n egress: WorkloadNetworkEgress | undefined,\n allowRule: (rule: string) => void,\n): void {\n if (egress === undefined) return;\n if (egress.denyLocalNetworks === false) {\n throw new TypeError(\n \"network.egress.denyLocalNetworks must be true for network.class restricted-egress\",\n );\n }\n const allow = egress.allow ?? [];\n if (allow.length > 0 && egress.denyLocalNetworks === undefined) {\n throw new TypeError(\n \"network.egress.denyLocalNetworks must be explicit true when network.egress.allow is set\",\n );\n }\n allow.forEach((rule, index) => {\n prefixed(`network.egress.allow[${String(index)}] is invalid`, () => {\n allowRule(rule);\n });\n });\n}\n\n/**\n * Judges a Pod's restricted-egress allow rule: `dns`, or\n * `tcp:<port>:<dns-hostname>` with a port between 1 and 65535 and a\n * well-formed, non-local DNS hostname. A Micropod's rules are judged by\n * `validateMicropodEgressAllowRule`, which accepts these and more.\n */\nexport function validateWorkloadNetworkEgressAllowRule(rule: string): void {\n if (rule === \"\") throw new TypeError(\"allow rule is required\");\n if (rule.trim() !== rule) {\n throw new TypeError(\"allow rule must not contain surrounding whitespace\");\n }\n if (rule === \"dns\") return;\n\n const firstColon = rule.indexOf(\":\");\n if (firstColon === -1) {\n throw new TypeError(\"expected dns or tcp:<port>:<dns-hostname>\");\n }\n const protocol = rule.slice(0, firstColon);\n const rest = rule.slice(firstColon + 1);\n if (protocol !== \"tcp\") {\n throw new TypeError(\n `unsupported egress protocol ${JSON.stringify(protocol)} (supported: tcp, dns)`,\n );\n }\n const secondColon = rest.indexOf(\":\");\n if (secondColon === -1) {\n throw new TypeError(\"expected tcp:<port>:<dns-hostname>\");\n }\n const portValue = rest.slice(0, secondColon);\n const host = rest.slice(secondColon + 1);\n if (portValue === \"\") throw new TypeError(\"tcp egress port is required\");\n if (\n !/^\\d+$/u.test(portValue) ||\n Number(portValue) === 0 ||\n Number(portValue) > 65535\n ) {\n throw new TypeError(\n `tcp egress port ${JSON.stringify(portValue)} must be between 1 and 65535`,\n );\n }\n validateNetworkTargetHost(host);\n}\n\nfunction validateNetworkTargetHost(host: string): void {\n if (host === \"\") throw new TypeError(\"egress host is required\");\n if (looksLikeIpAddress(host)) {\n throw new TypeError(\n `egress host ${JSON.stringify(host)} must be a DNS hostname, not an IP literal`,\n );\n }\n if (host.includes(\"*\")) {\n throw new TypeError(\n `egress host ${JSON.stringify(host)} must be a DNS hostname, not a wildcard`,\n );\n }\n validateNetworkTargetHostname(host);\n}\n\n/** Judges a DNS hostname an egress rule names. Throws a `TypeError`. */\nexport function validateNetworkTargetHostname(host: string): void {\n const quoted = JSON.stringify(host);\n if (host.length > 253) {\n throw new TypeError(`egress host ${quoted} exceeds 253 characters`);\n }\n if (host.endsWith(\".\")) {\n throw new TypeError(`egress host ${quoted} must not end with a dot`);\n }\n const lower = host.toLowerCase();\n if (\n lower === \"localhost\" ||\n lower.endsWith(\".localhost\") ||\n lower.endsWith(\".local\")\n ) {\n throw new TypeError(`egress host ${quoted} is a denied local hostname`);\n }\n for (const label of host.split(\".\")) {\n if (label.length === 0) {\n throw new TypeError(`egress host ${quoted} contains an empty DNS label`);\n }\n if (label.length > 63) {\n throw new TypeError(\n `egress host ${quoted} contains a DNS label longer than 63 characters`,\n );\n }\n if (label.startsWith(\"-\") || label.endsWith(\"-\")) {\n throw new TypeError(\n `egress host ${quoted} contains a DNS label with a leading or trailing hyphen`,\n );\n }\n for (const character of label) {\n if (!/^[a-zA-Z0-9-]$/u.test(character)) {\n throw new TypeError(\n `egress host ${quoted} contains invalid DNS label character ${JSON.stringify(character)}`,\n );\n }\n }\n }\n}\n\n/** Whether `host` reads as an IP literal rather than a DNS hostname. */\nexport function looksLikeIpAddress(host: string): boolean {\n const looksIpv4 = host.includes(\".\") && /^[0-9.]+$/u.test(host);\n const looksIpv6 = host.includes(\":\") && /^[0-9a-fA-F:.]+$/u.test(host);\n return looksIpv4 || looksIpv6;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n looksLikeIpAddress,\n validateNetworkTargetHostname,\n} from \"./workload-network.js\";\n\n/**\n * The allow entry that lets a restricted-egress network resolve the hostnames\n * its other entries cover. It names no destination.\n */\nexport const EGRESS_ALLOW_DNS = \"dns\";\n\n/** The transport an egress allow rule covers. */\nexport type EgressProtocol = \"tcp\" | \"udp\";\n\n/** The IPv4 destinations no egress rule reaches, as `[address, bits]`. */\nconst LOCAL_NETWORK_RANGES: readonly (readonly [string, number])[] = [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10],\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16],\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n];\n\n/**\n * One destination a Micropod's restricted-egress network allows, parsed from\n * `<protocol>:<port>:<destination>`. A rule states either a hostname, in\n * `host`, or an address range, in `range`.\n */\nexport interface EgressAllowRule {\n /** The transport the rule covers. */\n readonly protocol: EgressProtocol;\n /** The destination port, between 1 and 65535. */\n readonly port: number;\n /** The lowercase hostname the rule covers; absent on an address or range. */\n readonly host?: string;\n /**\n * True when the rule was written `*.<host>`, and so covers `host` and every\n * name below it, at any depth.\n */\n readonly wildcard?: boolean;\n /**\n * The IPv4 range the rule covers, a single address held as a `/32`; absent\n * on a hostname.\n */\n readonly range?: string;\n}\n\n/** The address of a dotted-quad IPv4 literal as an unsigned 32-bit value. */\nfunction ipv4Value(text: string): number | undefined {\n const parts = text.split(\".\");\n if (parts.length !== 4) return undefined;\n let value = 0;\n for (const part of parts) {\n if (!/^(?:0|[1-9][0-9]{0,2})$/u.test(part) || Number(part) > 255) {\n return undefined;\n }\n value = value * 256 + Number(part);\n }\n return value;\n}\n\n/** The first address of the `/bits` range around `value`. */\nfunction masked(value: number, bits: number): number {\n const size = 2 ** (32 - bits);\n return Math.floor(value / size) * size;\n}\n\n/** The IPv4 range of an address or canonical range. */\nfunction parseEgressRange(destination: string): string {\n const quoted = JSON.stringify(destination);\n const invalid = new TypeError(\n `egress host ${quoted} is not a valid IPv4 address or range`,\n );\n const slash = destination.indexOf(\"/\");\n const address = slash === -1 ? destination : destination.slice(0, slash);\n const length = slash === -1 ? \"32\" : destination.slice(slash + 1);\n if (address.includes(\":\")) {\n if (/^[0-9a-fA-F:.]+$/u.test(address) && address.includes(\"::\")) {\n throw new TypeError(\n `egress host ${quoted} is an IPv6 destination, which is not supported`,\n );\n }\n throw invalid;\n }\n const value = ipv4Value(address);\n if (\n value === undefined ||\n !/^(?:0|[1-9][0-9]?)$/u.test(length) ||\n Number(length) > 32\n ) {\n throw invalid;\n }\n const bits = Number(length);\n if (masked(value, bits) !== value) {\n throw new TypeError(`egress range ${quoted} must have no host bits set`);\n }\n for (const [local, localBits] of LOCAL_NETWORK_RANGES) {\n const start = ipv4Value(local);\n if (\n start !== undefined &&\n localBits <= bits &&\n masked(value, localBits) === start\n ) {\n throw new TypeError(\n `egress host ${quoted} is inside the local network range ${local}/${String(localBits)}`,\n );\n }\n }\n return `${address}/${String(bits)}`;\n}\n\n/**\n * The lowercase name below the wildcard of `*.<name>`: at least two labels,\n * a DNS hostname rather than an IP literal. Throws a `TypeError`.\n */\nexport function parseEgressWildcard(destination: string): string {\n const quoted = JSON.stringify(destination);\n const name = destination.startsWith(\"*.\") ? destination.slice(2) : undefined;\n if (name === undefined || !name.includes(\".\") || name.includes(\"*\")) {\n throw new TypeError(\n `egress host ${quoted} must write a wildcard as *.<name> with at least two labels in the name`,\n );\n }\n if (looksLikeIpAddress(name)) {\n throw new TypeError(\n `egress host ${quoted} must write a wildcard below a DNS hostname, not an IP literal`,\n );\n }\n validateNetworkTargetHostname(name);\n return name.toLowerCase();\n}\n\n/**\n * Parses a destination allow rule of a Micropod's network: `tcp` or `udp`, a\n * port between 1 and 65535, and one destination, a DNS hostname, a wildcard\n * such as `*.example.com`, an IPv4 address, or a canonical IPv4 range such as\n * `93.184.216.0/24`.\n *\n * It refuses a rule that could never work: a local hostname, a wildcard with\n * fewer than two labels after `*.` or anywhere but as the whole leftmost\n * label, an address or range wholly inside the local network ranges, a range\n * with host bits set, and IPv6. {@link EGRESS_ALLOW_DNS} names no destination\n * and is refused here; {@link validateMicropodEgressAllowRule} accepts it.\n * Throws a `TypeError`.\n */\nexport function parseEgressAllowRule(rule: string): EgressAllowRule {\n if (rule === \"\") throw new TypeError(\"allow rule is required\");\n if (rule.trim() !== rule) {\n throw new TypeError(\"allow rule must not contain surrounding whitespace\");\n }\n const firstColon = rule.indexOf(\":\");\n if (firstColon === -1) {\n throw new TypeError(\"expected dns or <tcp|udp>:<port>:<destination>\");\n }\n const protocol = rule.slice(0, firstColon);\n if (protocol !== \"tcp\" && protocol !== \"udp\") {\n throw new TypeError(\n `unsupported egress protocol ${JSON.stringify(protocol)} (supported: tcp, udp, dns)`,\n );\n }\n const rest = rule.slice(firstColon + 1);\n const secondColon = rest.indexOf(\":\");\n if (secondColon === -1) {\n throw new TypeError(\"expected <tcp|udp>:<port>:<destination>\");\n }\n const portValue = rest.slice(0, secondColon);\n const destination = rest.slice(secondColon + 1);\n if (portValue === \"\") throw new TypeError(\"egress port is required\");\n if (\n !/^\\d+$/u.test(portValue) ||\n Number(portValue) === 0 ||\n Number(portValue) > 65535\n ) {\n throw new TypeError(\n `egress port ${JSON.stringify(portValue)} must be between 1 and 65535`,\n );\n }\n const port = Number(portValue);\n if (destination === \"\") throw new TypeError(\"egress host is required\");\n if (destination.includes(\"/\") || looksLikeIpAddress(destination)) {\n return { protocol, port, range: parseEgressRange(destination) };\n }\n if (destination.includes(\"*\")) {\n return {\n protocol,\n port,\n host: parseEgressWildcard(destination),\n wildcard: true,\n };\n }\n validateNetworkTargetHostname(destination);\n return { protocol, port, host: destination.toLowerCase() };\n}\n\n/**\n * Judges one allow entry of a Micropod's network: {@link EGRESS_ALLOW_DNS}, or\n * a rule {@link parseEgressAllowRule} accepts. Throws a `TypeError`.\n */\nexport function validateMicropodEgressAllowRule(rule: string): void {\n if (rule !== EGRESS_ALLOW_DNS) parseEgressAllowRule(rule);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Wire shapes shared by more than one resource: identifiers whose codec\n * judges the spelling, and RFC 3339 instants. Each quantity declares its own\n * shape next to its type.\n */\nimport { scalar, type Shape } from \"../internal/strictdecode.js\";\n\n/**\n * A twelve-digit public identifier as its Go codec reads it: either the\n * empty string, which is the unset zero value, or exactly twelve ASCII\n * digits. `parse` is the family's own parser and names the family in the\n * rejection.\n */\nexport function publicIdShape<T extends string>(\n parse: (value: string) => T,\n): Shape<T> {\n return scalar<T>({\n decode: (text) => (text === \"\" ? (\"\" as T) : parse(text)),\n encode: (value) => value,\n zero: () => \"\" as T,\n isZero: (value) => value === \"\",\n });\n}\n\nconst RFC3339 =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/u;\n\n/**\n * Parses an RFC 3339 instant such as `2026-01-02T03:04:05Z`, throwing a\n * `TypeError` for any other spelling or an out-of-range date. The value is\n * carried as the string it arrived as; a `Date` is one conversion away and\n * would lose the offset and any sub-millisecond precision.\n */\nexport function parseTimestamp(text: string): string {\n const match = RFC3339.exec(text);\n if (match === null) {\n throw new TypeError(\n `invalid timestamp ${JSON.stringify(text)}: must be RFC 3339`,\n );\n }\n const [, year, month, day, hour, minute, second] = match;\n const utc = Date.UTC(\n Number(year),\n Number(month) - 1,\n Number(day),\n Number(hour),\n Number(minute),\n Number(second),\n );\n const probe = new Date(utc);\n if (\n Number.isNaN(utc) ||\n probe.getUTCMonth() !== Number(month) - 1 ||\n probe.getUTCDate() !== Number(day) ||\n probe.getUTCHours() !== Number(hour) ||\n probe.getUTCMinutes() !== Number(minute) ||\n Number(second) > 60\n ) {\n throw new TypeError(\n `invalid timestamp ${JSON.stringify(text)}: out of range`,\n );\n }\n return text;\n}\n\n/** An RFC 3339 instant; empty is the unset zero the wire omits. */\nexport const timestampShape: Shape<string> = scalar<string>({\n decode: parseTimestamp,\n encode: (value) => value,\n zero: () => \"\",\n isZero: (value) => value === \"\",\n});\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Vault Secrets: the document a write submits, the redacted document every\n * read returns, and their validation.\n *\n * A Secret holds either keyed binary values, which a Pod mounts as files, or\n * one value that IDYL adds to a Computer's requests to the origins the\n * Secret allows, so that the value never enters the Computer. Its source\n * states where that value comes from, and its egress where the value may go:\n * the exact HTTPS origins that receive it and the one place in a request it\n * fills.\n *\n * A Computer that attaches the Secret holds a placeholder in an environment\n * variable in its place. When the Computer sends a request to one of the\n * Secret's origins, IDYL puts the value in place of the placeholder where the\n * credential says, and sends the request on over TLS verified against the\n * origin. A placeholder anywhere else, or sent to any other origin, is sent\n * as written. The origin receives the value and can record it or return it\n * in a response, so an origin should be the API host that needs it.\n *\n * Refusals never contain a value or a key.\n */\nimport {\n always,\n array,\n integer,\n map,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n decodeValue,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { bytesShape } from \"./base64.js\";\nimport { parseEgressWildcard } from \"./egress-allow-rule.js\";\nimport { parseJson, type Integer } from \"./json.js\";\nimport { timestampShape } from \"./shapes.js\";\nimport type { ResourceId } from \"./uuid-id.js\";\nimport { errorMessage, isWellFormed, prefixed } from \"./validation.js\";\nimport {\n looksLikeIpAddress,\n validateNetworkTargetHostname,\n} from \"./workload-network.js\";\n\n/** The most keys one keyed Secret version holds. */\nexport const MAX_VAULT_SECRET_KEYS = 64;\n/** The most UTF-8 bytes one Secret key takes. */\nexport const MAX_VAULT_SECRET_KEY_BYTES = 255;\n/** The most bytes one keyed Secret value holds. */\nexport const MAX_VAULT_SECRET_VALUE_BYTES = 256 * 1024;\n/** The most bytes all the values of one keyed Secret version hold. */\nexport const MAX_VAULT_SECRET_TOTAL_BYTES = 1024 * 1024;\n/** The most bytes of a private key in PEM form. */\nexport const MAX_VAULT_PRIVATE_KEY_BYTES = 256 * 1024;\n/** The most bytes a stored source value holds, so that it fits in one header. */\nexport const MAX_SECRET_SOURCE_VALUE_BYTES = 8 * 1024;\n/** The most origins one Secret's egress states. */\nexport const MAX_SECRET_EGRESS_ORIGINS = 16;\n/** The most bytes of the header name a `header` credential fills. */\nexport const MAX_SECRET_EGRESS_HEADER_BYTES = 128;\n/**\n * The port of an origin that states none. It is also the one port a written\n * origin may name, because the value is added only to requests on it.\n */\nexport const DEFAULT_SECRET_EGRESS_ORIGIN_PORT = 443;\n\n/** The ports a Computer's egress gateway serves itself, which no origin names. */\nconst RESERVED_ORIGIN_PORTS: ReadonlySet<number> = new Set([53, 7300, 7301]);\n\n/** The form of a Vault resource name and of an explicitly stated Namespace. */\nconst REFERENCE_NAME_FORM = /^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/u;\n\n/**\n * The manifest kind of a Vault resource. Open, as the platform may name\n * more; {@link validateSecret} and {@link validateRedactedSecret} judge it.\n */\nexport type VaultResourceKind =\n \"Secret\" | \"TLSCertificate\" | (string & Record<never, never>);\n\n/** The identity every Vault resource carries. */\nexport interface VaultResourceMetadata {\n /** The resource's ID. `undefined` on a write, which the platform assigns. */\n readonly id?: ResourceId;\n /** The resource's name, unique within its Namespace and Subnet. Always written. */\n readonly name: string;\n /** The Namespace the resource lives in; `undefined` takes the addressed one. */\n readonly namespace?: string;\n /** The Subnet the resource lives in, as its twelve-digit slug. Always written. */\n readonly subnet: string;\n readonly labels?: Readonly<Record<string, string>>;\n readonly annotations?: Readonly<Record<string, string>>;\n /** When the resource was created, an RFC 3339 time. */\n readonly createdAt?: string;\n /** When the resource last changed, an RFC 3339 time. */\n readonly updatedAt?: string;\n /** When the resource was deleted, an RFC 3339 time; `undefined` while it is not. */\n readonly deletedAt?: string;\n}\n\n/**\n * The place in a request a Secret's value fills:\n *\n * - `basic-password`, the password of HTTP Basic authentication when the\n * whole password is the placeholder;\n * - `header`, the header the credential names when its whole value is the\n * placeholder;\n * - `authorization-token`, the token of an `Authorization` header that uses\n * the scheme the credential names, such as `Authorization: Bearer\n * <token>`. It is filled only when the request carries exactly one\n * `Authorization` header, and that header's value is the scheme, compared\n * without regard to case, then one or more spaces, then a token that is\n * wholly the placeholder. The scheme and the spaces are sent as written. A\n * request with two `Authorization` headers, another scheme, or the\n * placeholder as part of a longer token is sent as written.\n *\n * Open; {@link validateSecretEgressCredential} judges it.\n */\nexport type SecretEgressCredentialType =\n | \"basic-password\"\n | \"header\"\n | \"authorization-token\"\n | (string & Record<never, never>);\n\n/**\n * The authentication scheme of the `Authorization` header whose token an\n * `authorization-token` credential fills. The set is closed, and each scheme\n * has one spelling: `Bearer`, the scheme of RFC 6750, which most API\n * clients send an API key or an access token in, and `token`, which the\n * GitHub CLI sends a GitHub token in. The type is open so that a read\n * carries any scheme; {@link validateSecretEgressCredential} judges it.\n */\nexport type SecretEgressAuthorizationScheme =\n \"Bearer\" | \"token\" | (string & Record<never, never>);\n\n/**\n * The place in a request a Secret's value fills. The value replaces the\n * placeholder only where the whole of that place is the placeholder; a\n * placeholder anywhere else in a request, including the URL, the body,\n * another header, or part of a longer value, is sent as written.\n */\nexport interface SecretEgressCredential {\n /** The place the value fills. Always written. */\n readonly type: SecretEgressCredentialType;\n /**\n * The name of the header the value fills, for type `header`, matched\n * without regard to case, such as `PRIVATE-TOKEN`. An HTTP field name\n * other than one that frames the request or controls the connection.\n * `undefined` for every other type.\n */\n readonly header?: string;\n /**\n * The authentication scheme of the `Authorization` header whose token the\n * value fills, for type `authorization-token`: `Bearer` or `token`.\n * `undefined` for every other type.\n */\n readonly scheme?: SecretEgressAuthorizationScheme;\n}\n\n/** Where a Secret's value may go: the origins that receive it, and the place it fills. */\nexport interface SecretEgress {\n /**\n * The HTTPS origins that receive the value, each `https://<host>` with an\n * optional `:<port>`, as {@link parseSecretEgressOrigin} admits; a\n * wildcard is written as the whole leftmost label, `https://*.example.com`.\n * The value goes to no other origin. A write names port 443 only, by\n * leaving the port out or by writing `:443`; see\n * {@link validateSecretSpec}. 1 to {@link MAX_SECRET_EGRESS_ORIGINS}, none\n * repeated. Always written.\n */\n readonly origins: readonly string[];\n /** The place in a request the value fills. Always written. */\n readonly credential: SecretEgressCredential;\n}\n\n/** A GitHub App installation whose installation tokens a Secret sends as its value. */\nexport interface SecretGitHubAppSource {\n /** The GitHub App's ID, as GitHub shows it on the App's settings. At least 1. */\n readonly appId: Integer;\n /** The ID of the App's installation whose repositories the tokens reach. At least 1. */\n readonly installationId: Integer;\n /**\n * A private key of the App, in the PEM form GitHub downloads. Write-only:\n * it stays in Vault, and no read returns it.\n */\n readonly privateKey: string;\n}\n\n/**\n * Where a Secret's value comes from: exactly one of a stored `value` and a\n * `githubApp`. Its material is write-only; a read reports the kind of\n * source and none of its material.\n */\nexport interface SecretSource {\n /**\n * A value stored in Vault: printable ASCII, from space to tilde, at most\n * {@link MAX_SECRET_SOURCE_VALUE_BYTES} bytes, with no line break.\n */\n readonly value?: string;\n /**\n * When the stored value stops being valid, an RFC 3339 time, as its issuer\n * states it. The Secret's health turns to `expiring` seven days before it\n * and to `expired` at it, and a value past it is never sent. Stated only\n * with `value`.\n */\n readonly expiresAt?: string;\n /**\n * A GitHub App installation whose tokens Vault mints: each lasts one hour,\n * is minted when one is needed, and is sent as the value.\n */\n readonly githubApp?: SecretGitHubAppSource;\n}\n\n/**\n * What a Secret holds: exactly one of `data` and `source`, and `egress`\n * exactly when it states `source`.\n */\nexport interface SecretSpec {\n /** Binary values keyed by projection-safe names, for a Pod to mount as files. */\n readonly data?: Readonly<Record<string, Uint8Array>>;\n /** Where the Secret's one value comes from; never stated with `data`. */\n readonly source?: SecretSource;\n /** Where the value may go; required with `source`, and absent without it. */\n readonly egress?: SecretEgress;\n}\n\n/** The document a Secret write submits. */\nexport interface Secret {\n /** Always `Secret`. */\n readonly kind: VaultResourceKind;\n readonly metadata: VaultResourceMetadata;\n readonly spec: SecretSpec;\n}\n\n/** One key of a keyed Secret, without its value. */\nexport interface SecretKeyMetadata {\n readonly name: string;\n /** The length of the key's value; `undefined` reads as zero. */\n readonly sizeBytes?: Integer;\n}\n\n/** A stored source value, without the value. */\nexport interface RedactedSecretValueSource {\n /** The length of the current version's value. Always written. */\n readonly sizeBytes: Integer;\n /** When the current version stops being valid; `undefined` when its writer stated none. */\n readonly expiresAt?: string;\n}\n\n/** A GitHub App source, without its private key. */\nexport interface RedactedSecretGitHubAppSource {\n readonly appId: Integer;\n readonly installationId: Integer;\n}\n\n/** The kind of a Secret's source, as a read reports it: exactly one is present. */\nexport interface RedactedSecretSource {\n readonly value?: RedactedSecretValueSource;\n readonly githubApp?: RedactedSecretGitHubAppSource;\n}\n\n/**\n * What a read reports of a Secret: its keys or the kind of its source, its\n * egress in full, and its versions. It never carries a value.\n */\nexport interface RedactedSecretSpec {\n /** The keys of a keyed Secret; `undefined` when it states a source. */\n readonly keys?: readonly SecretKeyMetadata[];\n /** The kind of the Secret's source; present exactly when `keys` is absent. */\n readonly source?: RedactedSecretSource;\n /** The Secret's egress, present exactly with `source`. */\n readonly egress?: SecretEgress;\n /** The current version, from 1. Always written. */\n readonly currentVersion: Integer;\n /** How many versions are kept. Always written. */\n readonly versionCount: Integer;\n}\n\n/**\n * The lifecycle of a Vault resource: `active`, `tombstone` once deleted\n * while its versions are kept, or `purged`. Open; the validator judges it.\n */\nexport type VaultResourceState =\n \"active\" | \"tombstone\" | \"purged\" | (string & Record<never, never>);\n\n/**\n * Whether a Vault resource's current version can be used: `healthy`,\n * `not_yet_valid`, `expired`, `expiring` within seven days, or\n * `source_failed` when its source cannot produce a value. Open; the\n * validator judges it.\n */\nexport type VaultResourceHealth =\n | \"healthy\"\n | \"not_yet_valid\"\n | \"expired\"\n | \"expiring\"\n | \"source_failed\"\n | (string & Record<never, never>);\n\n/** The lifecycle and validity of a Vault resource. */\nexport interface VaultResourceStatus {\n /** Always written. */\n readonly state: VaultResourceState;\n /** `undefined` when the platform reports none. */\n readonly health?: VaultResourceHealth;\n /** The resource's version for optimistic concurrency, from 1. Always written. */\n readonly resourceVersion: Integer;\n}\n\n/** The redacted document every Secret read returns. */\nexport interface RedactedSecret {\n readonly kind: VaultResourceKind;\n readonly metadata: VaultResourceMetadata;\n readonly spec: RedactedSecretSpec;\n readonly status: VaultResourceStatus;\n}\n\n/**\n * One parsed origin of a Secret's egress. Two spellings of one origin, such\n * as `https://example.com` and `https://EXAMPLE.com:443`, parse to equal\n * values.\n */\nexport interface SecretEgressOrigin {\n /** The lowercase host name; for a wildcard origin, the name below the wildcard. */\n readonly host: string;\n /** Whether the origin was written `https://*.<host>`. */\n readonly wildcard: boolean;\n /** The TCP port, {@link DEFAULT_SECRET_EGRESS_ORIGIN_PORT} when the origin states none. */\n readonly port: number;\n}\n\nconst vaultResourceMetadataShape: Shape<VaultResourceMetadata> =\n object<VaultResourceMetadata>({\n id: omitEmpty(string<ResourceId>()),\n name: always(string()),\n namespace: omitEmpty(string()),\n subnet: always(string()),\n labels: omitEmpty(map(string())),\n annotations: omitEmpty(map(string())),\n createdAt: omitZero(timestampShape),\n updatedAt: omitZero(timestampShape),\n deletedAt: pointer(timestampShape),\n });\n\nconst secretEgressShape: Shape<SecretEgress> = object<SecretEgress>({\n origins: always(array(string())),\n credential: always(\n object<SecretEgressCredential>({\n type: always(string<SecretEgressCredentialType>()),\n header: omitEmpty(string()),\n scheme: omitEmpty(string<SecretEgressAuthorizationScheme>()),\n }),\n ),\n});\n\nconst int64 = integer({ unsigned: false, bits: 64 });\nconst uint64 = integer({ unsigned: true, bits: 64 });\n\n/** The wire shape of a Secret's spec. */\nexport const secretSpecShape: Shape<SecretSpec> = object<SecretSpec>({\n data: omitEmpty(map(bytesShape)),\n source: pointer(\n object<SecretSource>({\n value: omitEmpty(string()),\n expiresAt: pointer(timestampShape),\n githubApp: pointer(\n object<SecretGitHubAppSource>({\n appId: always(int64),\n installationId: always(int64),\n privateKey: always(string()),\n }),\n ),\n }),\n ),\n egress: pointer(secretEgressShape),\n});\n\n/** The wire shape of the document a Secret write submits. */\nexport const secretShape: Shape<Secret> = object<Secret>({\n kind: always(string<VaultResourceKind>()),\n metadata: always(vaultResourceMetadataShape),\n spec: always(secretSpecShape),\n});\n\n/** The wire shape of the redacted document a Secret read returns. */\nexport const redactedSecretShape: Shape<RedactedSecret> =\n object<RedactedSecret>({\n kind: always(string<VaultResourceKind>()),\n metadata: always(vaultResourceMetadataShape),\n spec: always(\n object<RedactedSecretSpec>({\n keys: omitEmpty(\n array(\n object<SecretKeyMetadata>({\n name: always(string()),\n sizeBytes: omitEmpty(uint64),\n }),\n ),\n ),\n source: pointer(\n object<RedactedSecretSource>({\n value: pointer(\n object<RedactedSecretValueSource>({\n sizeBytes: always(uint64),\n expiresAt: pointer(timestampShape),\n }),\n ),\n githubApp: pointer(\n object<RedactedSecretGitHubAppSource>({\n appId: always(int64),\n installationId: always(int64),\n }),\n ),\n }),\n ),\n egress: pointer(secretEgressShape),\n currentVersion: always(uint64),\n versionCount: always(uint64),\n }),\n ),\n status: always(\n object<VaultResourceStatus>({\n state: always(string<VaultResourceState>()),\n health: omitEmpty(string<VaultResourceHealth>()),\n resourceVersion: always(uint64),\n }),\n ),\n });\n\n/**\n * Reads a redacted Secret leniently, from a parsed value or its JSON text: a\n * field, state or health newer than this package is carried rather than\n * refused, and {@link validateRedactedSecret} judges it.\n */\nexport function decodeRedactedSecret(document: unknown): RedactedSecret {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, redactedSecretShape, \"lenient\");\n}\n\nconst encoder = new TextEncoder();\n\nfunction utf8Length(value: string): number {\n return encoder.encode(value).byteLength;\n}\n\n/**\n * Judges a Secret write: its kind is `Secret`, its name is a valid Vault\n * name, it names its Subnet, a Namespace it states is valid, and its spec is\n * one {@link validateSecretSpec} admits. Throws a `TypeError`.\n */\nexport function validateSecret(secret: Secret): void {\n validateVaultEnvelope(secret.kind, secret.metadata);\n validateSecretSpec(secret.spec);\n}\n\n/**\n * Judges a Secret spec: exactly one of `data` and `source`. Data holds 1 to\n * {@link MAX_VAULT_SECRET_KEYS} keys {@link validateVaultSecretKey} admits,\n * within the byte bounds. A source is one {@link validateSecretSource}\n * admits, stated with an egress {@link validateSecretEgress} admits whose\n * every origin names port 443, the one port the value is added to requests\n * on. An origin on another port is refused with the sentence `origin must\n * use port 443`, as `spec.egress.origins[<i>]: origin must use port 443`.\n * Throws a `TypeError` that never contains a value.\n */\nexport function validateSecretSpec(spec: SecretSpec): void {\n const data = spec.data ?? {};\n const keys = Object.keys(data);\n if (spec.source !== undefined) {\n if (keys.length !== 0) {\n throw new TypeError(\"spec.data must not be stated with spec.source\");\n }\n prefixed(\"spec.source\", () => {\n validateSecretSource(spec.source ?? {});\n });\n if (spec.egress === undefined) {\n throw new TypeError(\"spec.egress is required with spec.source\");\n }\n validateSpecEgress(spec.egress);\n validateWrittenPorts(spec.egress);\n return;\n }\n if (spec.egress !== undefined) {\n throw new TypeError(\"spec.egress requires spec.source\");\n }\n if (keys.length === 0) {\n throw new TypeError(\"spec.data must contain at least one key\");\n }\n if (keys.length > MAX_VAULT_SECRET_KEYS) {\n throw new TypeError(\n `spec.data has ${String(keys.length)} keys, maximum is ${String(MAX_VAULT_SECRET_KEYS)}`,\n );\n }\n let total = 0;\n for (const key of keys.sort()) {\n const quoted = JSON.stringify(key);\n prefixed(`spec.data key ${quoted}`, () => {\n validateVaultSecretKey(key);\n });\n const size = data[key]?.byteLength ?? 0;\n if (size > MAX_VAULT_SECRET_VALUE_BYTES) {\n throw new TypeError(\n `spec.data key ${quoted} is ${String(size)} bytes, maximum is ${String(MAX_VAULT_SECRET_VALUE_BYTES)}`,\n );\n }\n total += size;\n if (total > MAX_VAULT_SECRET_TOTAL_BYTES) {\n throw new TypeError(\n `spec.data is ${String(total)} decoded bytes, maximum is ${String(MAX_VAULT_SECRET_TOTAL_BYTES)}`,\n );\n }\n }\n}\n\n/** Judges one stable, projection-safe key of a keyed Secret. Throws a `TypeError`. */\nexport function validateVaultSecretKey(key: string): void {\n if (key === \"\") throw new TypeError(\"must not be empty\");\n if (!isWellFormed(key)) throw new TypeError(\"must be valid UTF-8\");\n const size = utf8Length(key);\n if (size > MAX_VAULT_SECRET_KEY_BYTES) {\n throw new TypeError(\n `is ${String(size)} bytes, maximum is ${String(MAX_VAULT_SECRET_KEY_BYTES)}`,\n );\n }\n if (key === \".\" || key === \"..\") {\n throw new TypeError(\"must not be a traversal component\");\n }\n if (/[/\\\\\\0]/u.test(key)) {\n throw new TypeError(\"must not contain slash, backslash, or NUL\");\n }\n}\n\n/**\n * Judges a source: exactly one of `value` and `githubApp`, and well-formed\n * material. A stored value is printable ASCII of at most\n * {@link MAX_SECRET_SOURCE_VALUE_BYTES} bytes; an expiry goes only with it.\n * A GitHub App states IDs of at least 1 and a PEM private key of at most\n * {@link MAX_VAULT_PRIVATE_KEY_BYTES} bytes. Throws a `TypeError` that never\n * contains the material.\n */\nexport function validateSecretSource(source: SecretSource): void {\n const value = source.value ?? \"\";\n if ((value === \"\") === (source.githubApp === undefined)) {\n throw new TypeError(\"must state exactly one of value and githubApp\");\n }\n if (source.githubApp !== undefined) {\n if (source.expiresAt !== undefined) {\n throw new TypeError(\"expiresAt is stated only with value\");\n }\n validateGitHubAppSource(source.githubApp);\n return;\n }\n const bytes = encoder.encode(value);\n if (bytes.byteLength > MAX_SECRET_SOURCE_VALUE_BYTES) {\n throw new TypeError(\n `value is ${String(bytes.byteLength)} bytes, maximum is ${String(MAX_SECRET_SOURCE_VALUE_BYTES)}`,\n );\n }\n const unprintable = bytes.findIndex((byte) => byte < 0x20 || byte > 0x7e);\n if (unprintable !== -1) {\n throw new TypeError(\n `value byte ${String(unprintable)} is not printable ASCII`,\n );\n }\n if (source.expiresAt !== undefined && isZeroTime(source.expiresAt)) {\n throw new TypeError(\"expiresAt must be a time\");\n }\n}\n\nfunction validateGitHubAppSource(app: SecretGitHubAppSource): void {\n if (!atLeastOne(app.appId)) {\n throw new TypeError(\"githubApp.appId must be at least 1\");\n }\n if (!atLeastOne(app.installationId)) {\n throw new TypeError(\"githubApp.installationId must be at least 1\");\n }\n if (app.privateKey === \"\") {\n throw new TypeError(\"githubApp.privateKey is required\");\n }\n const size = utf8Length(app.privateKey);\n if (size > MAX_VAULT_PRIVATE_KEY_BYTES) {\n throw new TypeError(\n `githubApp.privateKey is ${String(size)} bytes, maximum is ${String(MAX_VAULT_PRIVATE_KEY_BYTES)}`,\n );\n }\n if (!app.privateKey.startsWith(\"-----BEGIN \")) {\n throw new TypeError(\"githubApp.privateKey must be PEM\");\n }\n}\n\n/**\n * Refuses, for an egress {@link validateSecretEgress} admits, the first\n * origin that names a port other than\n * {@link DEFAULT_SECRET_EGRESS_ORIGIN_PORT}. Its sentence is part of the\n * contract.\n */\nfunction validateWrittenPorts(egress: SecretEgress): void {\n egress.origins.forEach((raw, index) => {\n const { port } = parseSecretEgressOrigin(raw);\n if (port !== DEFAULT_SECRET_EGRESS_ORIGIN_PORT) {\n throw new TypeError(\n `spec.egress.origins[${String(index)}]: origin must use port 443`,\n );\n }\n });\n}\n\n/**\n * Judges an egress: 1 to {@link MAX_SECRET_EGRESS_ORIGINS} origins\n * {@link parseSecretEgressOrigin} admits, no origin twice in any spelling,\n * and a credential {@link validateSecretEgressCredential} admits. Throws a\n * `TypeError` naming the field, such as `origins[0]: ...`.\n *\n * It judges an egress as it is read, and so admits an origin on any port\n * {@link parseSecretEgressOrigin} admits. A write is judged by\n * {@link validateSecretSpec}, which also requires every origin to name\n * port 443.\n */\nexport function validateSecretEgress(egress: SecretEgress): void {\n if (egress.origins.length === 0) {\n throw new TypeError(\"origins must name at least one origin\");\n }\n if (egress.origins.length > MAX_SECRET_EGRESS_ORIGINS) {\n throw new TypeError(\n `origins has ${String(egress.origins.length)} entries, maximum is ${String(MAX_SECRET_EGRESS_ORIGINS)}`,\n );\n }\n const seen = new Map<string, number>();\n egress.origins.forEach((raw, index) => {\n let origin: SecretEgressOrigin;\n try {\n origin = parseSecretEgressOrigin(raw);\n } catch (cause) {\n throw new TypeError(`origins[${String(index)}]: ${errorMessage(cause)}`, {\n cause,\n });\n }\n const canonical = formatSecretEgressOrigin(origin);\n const previous = seen.get(canonical);\n if (previous !== undefined) {\n throw new TypeError(\n `origins[${String(index)}] duplicates origins[${String(previous)}]`,\n );\n }\n seen.set(canonical, index);\n });\n prefixed(\"credential\", () => {\n validateSecretEgressCredential(egress.credential);\n });\n}\n\n/** The header names, lowercase, that frame a request or control its connection. */\nconst REFUSED_HEADERS: ReadonlySet<string> = new Set([\n \"connection\",\n \"content-length\",\n \"host\",\n \"keep-alive\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/** An HTTP field name: one or more token characters of RFC 9110. */\nconst HTTP_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/u;\n\n/**\n * Judges a credential: a type this package names; a header exactly when the\n * type is `header`, an HTTP field name of at most\n * {@link MAX_SECRET_EGRESS_HEADER_BYTES} bytes that neither frames the\n * request nor controls the connection; and a scheme exactly when the type is\n * `authorization-token`, one of `Bearer` and `token` spelled as they are.\n * Throws a `TypeError`.\n */\nexport function validateSecretEgressCredential(\n credential: SecretEgressCredential,\n): void {\n const { type } = credential;\n const header = credential.header ?? \"\";\n const scheme = credential.scheme ?? \"\";\n switch (type) {\n case \"basic-password\":\n case \"header\":\n case \"authorization-token\":\n break;\n case \"\":\n throw new TypeError(\"type is required\");\n default:\n throw new TypeError(`unknown credential type ${JSON.stringify(type)}`);\n }\n if (type !== \"authorization-token\" && scheme !== \"\") {\n throw new TypeError(`scheme must be absent for type ${type}`);\n }\n if (type === \"authorization-token\") {\n if (header !== \"\") {\n throw new TypeError(`header must be absent for type ${type}`);\n }\n switch (scheme) {\n case \"Bearer\":\n case \"token\":\n return;\n case \"\":\n throw new TypeError(\"scheme is required\");\n default:\n throw new TypeError(\n `unknown authorization scheme ${JSON.stringify(scheme)}`,\n );\n }\n }\n if (type !== \"header\") {\n if (header !== \"\") {\n throw new TypeError(`header must be absent for type ${type}`);\n }\n return;\n }\n if (header === \"\") throw new TypeError(`header is required for type ${type}`);\n const size = utf8Length(header);\n if (size > MAX_SECRET_EGRESS_HEADER_BYTES) {\n throw new TypeError(\n `header is ${String(size)} bytes, maximum is ${String(MAX_SECRET_EGRESS_HEADER_BYTES)}`,\n );\n }\n if (!HTTP_TOKEN.test(header)) {\n throw new TypeError(\"header must be an HTTP field name\");\n }\n if (REFUSED_HEADERS.has(header.toLowerCase())) {\n throw new TypeError(\n `header ${header} frames the request or controls the connection`,\n );\n }\n}\n\n/**\n * Parses an origin a Secret's value may go to: `https://`, a host, and an\n * optional `:<port>`, with no user, path, query or fragment. The host is a\n * DNS name, or a wildcard written as the whole leftmost label, such as\n * `*.example.com`, below a name of at least two labels. It refuses an IP\n * address or range, a local host name, and the ports 53, 7300 and 7301,\n * which a Computer's egress gateway serves itself. A Secret write further\n * requires port 443; see {@link validateSecretSpec}. Throws a `TypeError`.\n */\nexport function parseSecretEgressOrigin(origin: string): SecretEgressOrigin {\n if (!origin.startsWith(\"https://\")) {\n throw new TypeError(\"origin must begin with https://\");\n }\n const authority = origin.slice(\"https://\".length);\n if (authority === \"\") throw new TypeError(\"origin must state a host\");\n if (/[/?#@\\\\]/u.test(authority)) {\n throw new TypeError(\n \"origin must not state a user, path, query or fragment\",\n );\n }\n if (authority.startsWith(\"[\")) {\n throw new TypeError(\"origin must name a host, not an IP address\");\n }\n const colon = authority.indexOf(\":\");\n const host = colon === -1 ? authority : authority.slice(0, colon);\n let port = DEFAULT_SECRET_EGRESS_ORIGIN_PORT;\n if (colon !== -1) {\n const text = authority.slice(colon + 1);\n const value = /^[0-9]{1,5}$/u.test(text) ? Number(text) : 0;\n if (value < 1 || value > 65535 || text.startsWith(\"0\")) {\n throw new TypeError(\n `origin port ${JSON.stringify(text)} must be between 1 and 65535`,\n );\n }\n port = value;\n }\n if (RESERVED_ORIGIN_PORTS.has(port)) {\n throw new TypeError(\n `origin port ${String(port)} is reserved for the Computer's gateway`,\n );\n }\n if (host === \"\") throw new TypeError(\"origin must state a host\");\n if (looksLikeIpAddress(host)) {\n throw new TypeError(\"origin must name a host, not an IP address\");\n }\n if (host.includes(\"*\")) {\n return { host: parseEgressWildcard(host), wildcard: true, port };\n }\n validateNetworkTargetHostname(host);\n return { host: host.toLowerCase(), wildcard: false, port };\n}\n\n/**\n * The canonical spelling of an origin: `https://`, the lowercase host, and\n * the port when it is not {@link DEFAULT_SECRET_EGRESS_ORIGIN_PORT}.\n */\nexport function formatSecretEgressOrigin(origin: SecretEgressOrigin): string {\n const host = origin.wildcard ? `*.${origin.host}` : origin.host;\n return origin.port === DEFAULT_SECRET_EGRESS_ORIGIN_PORT\n ? `https://${host}`\n : `https://${host}:${String(origin.port)}`;\n}\n\n/**\n * Judges a redacted Secret as this package understands it: its envelope,\n * its status, versions of at least 1, and either keys or the kind of a\n * source with its egress. A read never requires it: a document a newer\n * platform reports is carried as it arrived. Throws a `TypeError`.\n */\nexport function validateRedactedSecret(secret: RedactedSecret): void {\n validateVaultEnvelope(secret.kind, secret.metadata);\n prefixed(\"status\", () => {\n validateVaultResourceStatus(secret.status);\n });\n const { spec } = secret;\n if (!atLeastOne(spec.currentVersion)) {\n throw new TypeError(\"spec.currentVersion must be greater than zero\");\n }\n if (!atLeastOne(spec.versionCount)) {\n throw new TypeError(\"spec.versionCount must be greater than zero\");\n }\n if (spec.source !== undefined) {\n if ((spec.keys ?? []).length !== 0) {\n throw new TypeError(\"spec.keys must be absent with spec.source\");\n }\n prefixed(\"spec.source\", () => {\n validateRedactedSecretSource(spec.source ?? {});\n });\n if (spec.egress === undefined) {\n throw new TypeError(\"spec.egress is required with spec.source\");\n }\n validateSpecEgress(spec.egress);\n return;\n }\n if (spec.egress !== undefined) {\n throw new TypeError(\"spec.egress requires spec.source\");\n }\n const keys = spec.keys ?? [];\n if (keys.length === 0) {\n throw new TypeError(\"spec.keys must contain at least one key\");\n }\n if (keys.length > MAX_VAULT_SECRET_KEYS) {\n throw new TypeError(\n `spec.keys has ${String(keys.length)} entries, maximum is ${String(MAX_VAULT_SECRET_KEYS)}`,\n );\n }\n const seen = new Set<string>();\n keys.forEach((key, index) => {\n const field = `spec.keys[${String(index)}]`;\n prefixed(`${field}.name`, () => {\n validateVaultSecretKey(key.name);\n });\n const size = BigInt(key.sizeBytes ?? 0);\n if (size > BigInt(MAX_VAULT_SECRET_VALUE_BYTES)) {\n throw new TypeError(\n `${field}.sizeBytes is ${size.toString()}, maximum is ${String(MAX_VAULT_SECRET_VALUE_BYTES)}`,\n );\n }\n if (seen.has(key.name)) {\n throw new TypeError(\n `${field}.name duplicates ${JSON.stringify(key.name)}`,\n );\n }\n seen.add(key.name);\n });\n}\n\nfunction validateRedactedSecretSource(source: RedactedSecretSource): void {\n if ((source.value === undefined) === (source.githubApp === undefined)) {\n throw new TypeError(\"must state exactly one of value and githubApp\");\n }\n if (source.githubApp !== undefined) {\n if (\n !atLeastOne(source.githubApp.appId) ||\n !atLeastOne(source.githubApp.installationId)\n ) {\n throw new TypeError(\n \"githubApp.appId and githubApp.installationId must be at least 1\",\n );\n }\n return;\n }\n const size = BigInt(source.value?.sizeBytes ?? 0);\n if (size > BigInt(MAX_SECRET_SOURCE_VALUE_BYTES)) {\n throw new TypeError(\n `value.sizeBytes is ${size.toString()}, maximum is ${String(MAX_SECRET_SOURCE_VALUE_BYTES)}`,\n );\n }\n}\n\n/**\n * Judges a Vault resource's status: a state and a health this package\n * names, and a resource version of at least 1. Throws a `TypeError`.\n */\nexport function validateVaultResourceStatus(status: VaultResourceStatus): void {\n switch (status.state) {\n case \"active\":\n case \"tombstone\":\n case \"purged\":\n break;\n default:\n throw new TypeError(\n `unknown Vault resource state ${JSON.stringify(status.state)}`,\n );\n }\n switch (status.health ?? \"\") {\n case \"\":\n case \"healthy\":\n case \"not_yet_valid\":\n case \"expired\":\n case \"expiring\":\n case \"source_failed\":\n break;\n default:\n throw new TypeError(\n `unknown Vault resource health ${JSON.stringify(status.health)}`,\n );\n }\n if (!atLeastOne(status.resourceVersion)) {\n throw new TypeError(\"resourceVersion must be greater than zero\");\n }\n}\n\n/** Judges a Vault resource name or an explicitly stated Namespace. Throws a `TypeError`. */\nexport function validateVaultReferenceName(label: string, name: string): void {\n if (name === \"\") throw new TypeError(`${label} is required`);\n if (name === \".\" || name === \"..\" || !REFERENCE_NAME_FORM.test(name)) {\n throw new TypeError(`${label} ${JSON.stringify(name)} is invalid`);\n }\n}\n\nfunction validateVaultEnvelope(\n kind: VaultResourceKind,\n metadata: VaultResourceMetadata,\n): void {\n if (kind === \"\") throw new TypeError(\"vault resource kind is required\");\n if (kind !== \"Secret\" && kind !== \"TLSCertificate\") {\n throw new TypeError(`unknown Vault resource kind ${JSON.stringify(kind)}`);\n }\n if (kind !== \"Secret\") throw new TypeError('kind must be \"Secret\"');\n validateVaultReferenceName(\"metadata.name\", metadata.name);\n if (metadata.subnet.trim() === \"\") {\n throw new TypeError(\"metadata.subnet is required\");\n }\n const namespace = metadata.namespace ?? \"\";\n if (namespace !== \"\") {\n validateVaultReferenceName(\"metadata.namespace\", namespace);\n }\n}\n\nfunction validateSpecEgress(egress: SecretEgress): void {\n try {\n validateSecretEgress(egress);\n } catch (cause) {\n throw new TypeError(`spec.egress.${errorMessage(cause)}`, { cause });\n }\n}\n\nfunction atLeastOne(value: Integer): boolean {\n return BigInt(value) >= 1n;\n}\n\n/**\n * The instant the reference contract reads as no time at all,\n * `0001-01-01T00:00:00Z`, in milliseconds since the epoch.\n */\nconst ZERO_TIME_MS = -62_135_596_800_000;\n\nfunction isZeroTime(timestamp: string): boolean {\n return Date.parse(timestamp) === ZERO_TIME_MS;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The per-call arguments a service judges before any request: the signal\n * it forwards to the transport and the name it requires. A service passes\n * only the signal it was given, never the caller's object itself, so a\n * property a caller did not mean for the transport cannot reach it.\n */\n\n/** The `signal` option alone: present when set, absent otherwise. */\nexport function signalOption(signal: AbortSignal | undefined): {\n readonly signal?: AbortSignal;\n} {\n return signal === undefined ? {} : { signal };\n}\n\n/**\n * Judges a caller-supplied name before any request: throws a `TypeError`\n * reading `<label> is required` unless `value` is a string with something\n * other than whitespace in it, and returns it unchanged. The path builder\n * escapes it; nothing here does.\n */\nexport function requireNonBlank(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new TypeError(`${label} is required`);\n }\n return value;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The Account a client's credential acts as, read from the identity API's\n * current-account route, and the Account's own routes on the global API.\n */\nimport type { DeleteOrgAccountResponse } from \"../api/account.js\";\nimport type { CurrentAccountResponse } from \"../api/auth.js\";\nimport { account, CURRENT_ACCOUNT } from \"../internal/apipath.js\";\nimport type { ServiceState } from \"../internal/context.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport type { AccountId } from \"../resource/id.js\";\n\n/**\n * The Account the client's credential acts as. Throws a `TypeError` when\n * the client has no identity endpoint.\n */\nexport async function getCurrentAccount(\n state: ServiceState,\n options: RequestOptions = {},\n): Promise<CurrentAccountResponse> {\n return await state.transport.json<CurrentAccountResponse>(\n \"GET\",\n requireIdentity(state.endpoints.identity),\n CURRENT_ACCOUNT,\n signalOption(options.signal),\n );\n}\n\n/** Deletes `accountId`, as `DELETE /v1/accounts/{account}` on the global API. */\nexport async function deleteAccount(\n state: ServiceState,\n accountId: AccountId,\n options: RequestOptions = {},\n): Promise<DeleteOrgAccountResponse> {\n return await state.transport.json<DeleteOrgAccountResponse>(\n \"DELETE\",\n state.endpoints.api,\n account(accountId),\n signalOption(options.signal),\n );\n}\n\nfunction requireIdentity(endpoint: string | undefined): string {\n if (endpoint === undefined) {\n throw new TypeError(\n \"identity endpoint is required; configure network or endpoints.identity\",\n );\n }\n return endpoint;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { numberOrBigInt } from \"../internal/strictdecode.js\";\nimport type { Integer } from \"./json.js\";\n/*\n * The syntax shared by memory and volume quantities: a whole number followed\n * by an optional unit suffix from the binary (IEC) or decimal (SI) family.\n * Nothing here is public; `memory.ts` and `volume.ts` own the exported\n * codecs and differ only in which suffixes they accept and how they render\n * a byte count.\n */\n\n/** Byte counts for the supported IEC (binary) and SI (decimal) prefixes. */\nexport const BYTES_PER_KIB = 1024n;\nexport const BYTES_PER_MIB = 1024n * BYTES_PER_KIB;\nexport const BYTES_PER_GIB = 1024n * BYTES_PER_MIB;\nexport const BYTES_PER_TIB = 1024n * BYTES_PER_GIB;\nexport const BYTES_PER_KB = 1000n;\nexport const BYTES_PER_MB = 1000n * BYTES_PER_KB;\nexport const BYTES_PER_GB = 1000n * BYTES_PER_MB;\nexport const BYTES_PER_TB = 1000n * BYTES_PER_GB;\n\n/** The largest value a Go `uint64` holds, which bounds every quantity. */\nexport const MAX_UINT64 = (1n << 64n) - 1n;\n\n/**\n * The unit suffixes memory and volume quantities share, each paired with the\n * number of bytes one unit represents. The suffix is the unit's wire token.\n */\nexport type ByteUnit = \"Ki\" | \"Mi\" | \"Gi\" | \"Ti\" | \"B\" | \"K\" | \"M\" | \"G\" | \"T\";\n\nconst UNIT_BYTES: Readonly<Record<ByteUnit, bigint>> = {\n Ki: BYTES_PER_KIB,\n Mi: BYTES_PER_MIB,\n Gi: BYTES_PER_GIB,\n Ti: BYTES_PER_TIB,\n B: 1n,\n K: BYTES_PER_KB,\n M: BYTES_PER_MB,\n G: BYTES_PER_GB,\n T: BYTES_PER_TB,\n};\n\n/** Whether `suffix` names a supported unit. */\nexport function isByteUnit(suffix: string): suffix is ByteUnit {\n return Object.hasOwn(UNIT_BYTES, suffix);\n}\n\n/** The number of bytes one unit of `unit` represents. */\nexport function unitBytes(unit: ByteUnit): bigint {\n return UNIT_BYTES[unit];\n}\n\ninterface ByteLadderRung {\n readonly suffix: ByteUnit;\n readonly factor: bigint;\n}\n\n/**\n * The binary and decimal ladders spell an exact byte count in the largest\n * unit that divides it, largest unit first.\n */\nexport const BINARY_LADDER: readonly ByteLadderRung[] = [\n { suffix: \"Ti\", factor: BYTES_PER_TIB },\n { suffix: \"Gi\", factor: BYTES_PER_GIB },\n { suffix: \"Mi\", factor: BYTES_PER_MIB },\n { suffix: \"Ki\", factor: BYTES_PER_KIB },\n];\n\nconst DECIMAL_LADDER: readonly ByteLadderRung[] = [\n { suffix: \"T\", factor: BYTES_PER_TB },\n { suffix: \"G\", factor: BYTES_PER_GB },\n { suffix: \"M\", factor: BYTES_PER_MB },\n { suffix: \"K\", factor: BYTES_PER_KB },\n];\n\n/**\n * Bounds how many digits of a rejected fractional quantity are examined when\n * looking for an exact alternative. Twenty digits cover every `uint64`, so a\n * longer part cannot produce a spelling that decodes.\n */\nconst MAX_SUGGESTION_DIGITS = 20;\n\nconst BYTE_QUANTITY = /^(\\d+)(?:\\.(\\d+))?([A-Za-z]*)$/u;\n\n/** A parsed byte-denominated quantity: a whole value in a unit. */\nexport interface ParsedByteQuantity {\n readonly value: Integer;\n readonly unit: ByteUnit;\n}\n\n/**\n * Parses `raw` as a whole number with an optional unit suffix; no suffix\n * means bytes. Fractional quantities are refused rather than truncated, and\n * when the written value is a whole number of bytes the error names the\n * exact whole-unit spelling. `kind` names the quantity in errors (`memory`,\n * `volume`). Values and byte counts that do not fit a `uint64` are refused.\n */\nexport function parseByteQuantity(\n kind: string,\n raw: string,\n): ParsedByteQuantity {\n const written = raw.trim();\n const match = BYTE_QUANTITY.exec(written);\n if (match === null) {\n throw new TypeError(`invalid ${kind} value format: ${written}`);\n }\n const wholePart = match[1] ?? \"\";\n const fractionalPart = match[2] ?? \"\";\n const suffix = match[3] ?? \"\";\n let unit: ByteUnit = \"B\";\n if (suffix !== \"\") {\n if (!isByteUnit(suffix)) {\n throw new TypeError(`unsupported ${kind} unit: ${suffix}`);\n }\n unit = suffix;\n }\n const factor = unitBytes(unit);\n if (fractionalPart !== \"\") {\n throw fractionalQuantityError(\n kind,\n written,\n wholePart,\n fractionalPart,\n suffix,\n factor,\n );\n }\n const value = BigInt(wholePart);\n if (value > MAX_UINT64) {\n throw new TypeError(\n `invalid ${kind} value ${JSON.stringify(written)}: value out of range`,\n );\n }\n if (value * factor > MAX_UINT64) {\n throw new TypeError(\n `${kind} value ${JSON.stringify(written)} overflows bytes`,\n );\n }\n return { value: numberOrBigInt(value), unit };\n}\n\nfunction fractionalQuantityError(\n kind: string,\n written: string,\n wholePart: string,\n fractionalPart: string,\n suffix: string,\n factor: bigint,\n): TypeError {\n const unitName = suffix === \"\" ? \"bytes\" : suffix;\n const alternative = exactWholeQuantity(wholePart, fractionalPart, factor);\n if (alternative !== undefined) {\n return new TypeError(\n `${kind} value ${written} is not a whole number of ${unitName}; write ${alternative}`,\n );\n }\n return new TypeError(\n `${kind} value ${written} is not a whole number of ${unitName}; fractional quantities are not accepted`,\n );\n}\n\n/**\n * Renders `<wholePart>.<fractionalPart>` scaled by `factor` as a whole\n * quantity string, when the scaled value is a whole number of bytes that\n * fits a `uint64`, so the suggestion always decodes to exactly the value\n * the caller wrote.\n */\nfunction exactWholeQuantity(\n wholePart: string,\n fractionalPart: string,\n factor: bigint,\n): string | undefined {\n if (\n wholePart.length > MAX_SUGGESTION_DIGITS ||\n fractionalPart.length > MAX_SUGGESTION_DIGITS\n ) {\n return undefined;\n }\n const digits = BigInt(wholePart + fractionalPart) * factor;\n const scale = 10n ** BigInt(fractionalPart.length);\n if (digits % scale !== 0n) return undefined;\n const bytes = digits / scale;\n if (bytes > MAX_UINT64) return undefined;\n return spellExactBytes(bytes, ladderFor(factor));\n}\n\n/**\n * Picks the unit family a suggestion is spelled in from the unit the caller\n * wrote, so a decimal suffix is suggested back with a decimal suffix. Bytes\n * and every binary unit fall through to the binary ladder.\n */\nfunction ladderFor(factor: bigint): readonly ByteLadderRung[] {\n return DECIMAL_LADDER.some((rung) => rung.factor === factor)\n ? DECIMAL_LADDER\n : BINARY_LADDER;\n}\n\n/**\n * Renders a byte count in the largest unit of the ladder that divides it\n * exactly, falling back to an explicit byte count.\n */\nexport function spellExactBytes(\n bytes: bigint,\n ladder: readonly ByteLadderRung[],\n): string {\n for (const rung of ladder) {\n if (bytes >= rung.factor && bytes % rung.factor === 0n) {\n return `${String(bytes / rung.factor)}${rung.suffix}`;\n }\n }\n return `${String(bytes)}B`;\n}\n\n/**\n * Compares two byte counts, returning -1, 0, or 1. It is the ordering every\n * byte-denominated quantity uses once normalized to bytes.\n */\nexport function compareBytes(left: bigint, right: bigint): -1 | 0 | 1 {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"./json.js\";\nimport {\n scalar,\n numberOrBigInt,\n integerText,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { MAX_UINT64 } from \"./byte-quantity.js\";\n\n/**\n * The unit a {@link CpuQuantity} is denominated in: `m` for millicores,\n * thousandths of a vCPU, or `c` for whole vCPUs. Quantity strings only ever\n * carry the `m` suffix; a vCPU quantity renders as a bare number.\n */\nexport type CpuUnit = \"m\" | \"c\";\n\n/**\n * An amount of CPU as a whole number of millicores or of vCPUs (1 vCPU =\n * 1000 millicores). It is the value form of the compact string a manifest\n * carries, `500m`, `4`, or `1.5`, which {@link decodeCpu} reads and\n * {@link formatCpu} writes; the wire never carries it as an object.\n *\n * Two quantities that name the same amount in different units are different\n * values: compare amounts with {@link compareCpu}, not by field. A `value` of\n * zero means no CPU in either unit.\n */\nexport interface CpuQuantity {\n readonly value: Integer;\n readonly unit: CpuUnit;\n}\n\n/**\n * Bounds an acceptable amount of CPU, inclusive at both ends. An end\n * left `undefined` is unconstrained.\n */\nexport interface CpuQuantityRange {\n readonly min?: CpuQuantity;\n readonly max?: CpuQuantity;\n}\n\nconst MILLICORES_PER_VCPU = 1000n;\nconst MILLICORES = /^(\\d+)m$/u;\nconst VCPUS = /^(?:\\d+(?:\\.\\d*)?|\\.\\d+)$/u;\n\n/**\n * Parses a CPU string. It accepts millicores with an `m` suffix (`500m`) and\n * whole or decimal vCPU counts (`4`, `1.5`, `.25`). Decimal input is limited\n * to three fractional digits, the millicore resolution, and decodes to\n * millicores unless it reduces to a whole vCPU count. Surrounding whitespace\n * is ignored. Throws a `TypeError` for any other syntax, for a value that\n * would overflow a 64-bit millicore count.\n */\nexport function decodeCpu(text: string): CpuQuantity {\n const trimmed = text.trim();\n if (trimmed === \"\") throw new TypeError(\"empty CPU value\");\n\n const millicores = MILLICORES.exec(trimmed);\n if (millicores !== null) {\n const value = BigInt(millicores[1] ?? \"0\");\n if (value > MAX_UINT64) {\n throw new TypeError(\n `invalid millicores value ${JSON.stringify(trimmed)}: value out of range`,\n );\n }\n return { value: numberOrBigInt(value), unit: \"m\" };\n }\n\n if (VCPUS.test(trimmed)) return parseVcpus(trimmed);\n\n throw new TypeError(`invalid CPU format: ${trimmed}`);\n}\n\nfunction parseVcpus(raw: string): CpuQuantity {\n const dot = raw.indexOf(\".\");\n const wholePart = dot === -1 ? raw : raw.slice(0, dot);\n const whole = wholePart === \"\" ? 0n : BigInt(wholePart);\n if (whole > MAX_UINT64) {\n throw new TypeError(\n `invalid CPU value ${JSON.stringify(raw)}: value out of range`,\n );\n }\n if (dot === -1) {\n if (whole > MAX_UINT64 / MILLICORES_PER_VCPU) {\n throw new TypeError(\n `invalid CPU value ${JSON.stringify(raw)}: CPU value overflows millicores`,\n );\n }\n return { value: numberOrBigInt(whole), unit: \"c\" };\n }\n\n const fractionalPart = raw.slice(dot + 1);\n if (fractionalPart.length > 3) {\n throw new TypeError(\n `invalid CPU value ${JSON.stringify(raw)}: fractional CPU precision exceeds millicores`,\n );\n }\n const fractionalMillicores = BigInt(fractionalPart.padEnd(3, \"0\"));\n if (whole > (MAX_UINT64 - fractionalMillicores) / MILLICORES_PER_VCPU) {\n throw new TypeError(\n `invalid CPU value ${JSON.stringify(raw)}: CPU value overflows millicores`,\n );\n }\n const millicores = whole * MILLICORES_PER_VCPU + fractionalMillicores;\n if (millicores % MILLICORES_PER_VCPU === 0n) {\n return {\n value: numberOrBigInt(millicores / MILLICORES_PER_VCPU),\n unit: \"c\",\n };\n }\n return { value: numberOrBigInt(millicores), unit: \"m\" };\n}\n\n/**\n * Renders the quantity in the syntax {@link decodeCpu} accepts. The\n * rendering is canonical as well as lossless: a whole vCPU amount renders\n * as a bare number (`4`) whichever unit it is held in, a sub-vCPU amount\n * renders in millicores (`500m`), and zero renders as `0` in every unit,\n * so one amount of CPU has one spelling.\n */\nexport function formatCpu(quantity: CpuQuantity): string {\n const value = BigInt(quantity.value);\n if (value === 0n) return \"0\";\n if (quantity.unit === \"c\") return integerText(quantity.value);\n if (value % 1000n === 0n) return String(value / 1000n);\n return `${integerText(quantity.value)}m`;\n}\n\n/**\n * The quantity in millicores, the common unit for comparison. A vCPU count\n * beyond what a `number` holds exactly is returned as the nearest\n * representable value.\n */\nexport function cpuMillicores(quantity: CpuQuantity): number {\n return Number(millicoresExact(quantity));\n}\n\n/** Whether the quantity requests no CPU, in whichever unit it is held. */\nexport function isZeroCpu(quantity: CpuQuantity): boolean {\n return BigInt(quantity.value) === 0n;\n}\n\n/**\n * Orders two quantities by amount, so 1 vCPU and `1000m` compare equal even\n * though their fields differ. Returns -1 when `left` is the smaller amount,\n * 0 when the two are equal, and 1 when `left` is the larger.\n */\nexport function compareCpu(left: CpuQuantity, right: CpuQuantity): -1 | 0 | 1 {\n const a = millicoresExact(left);\n const b = millicoresExact(right);\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n\n/**\n * The wire shape of a CPU quantity: the compact string, or the bare number\n * a manifest converted from YAML carries for `cpu: 1`.\n */\nexport const cpuQuantityShape: Shape<CpuQuantity> = scalar<CpuQuantity>({\n decode: decodeCpu,\n encode: formatCpu,\n zero: () => ({ value: 0, unit: \"m\" }),\n isZero: isZeroCpu,\n acceptsNumber: true,\n});\n\n/** The exact millicore count, for arithmetic that must not round. */\nexport function millicoresExact(quantity: CpuQuantity): bigint {\n const value = BigInt(quantity.value);\n return quantity.unit === \"c\" ? value * MILLICORES_PER_VCPU : value;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"./json.js\";\nimport { scalar, integerText, type Shape } from \"../internal/strictdecode.js\";\nimport {\n BINARY_LADDER,\n compareBytes,\n parseByteQuantity,\n unitBytes,\n type ByteUnit,\n} from \"./byte-quantity.js\";\n\n/**\n * The unit a {@link MemoryQuantity} is denominated in. Both the binary (IEC,\n * powers of 1024) family, `Ki`, `Mi`, `Gi`, and `Ti`, and the decimal (SI,\n * powers of 1000) family, `K`, `M`, `G`, and `T`, are supported; `B` is raw\n * bytes. The token of each unit is exactly the suffix {@link decodeMemory}\n * accepts for it.\n */\nexport type MemoryUnit = ByteUnit;\n\n/**\n * An amount of memory as a whole number in a declared unit, so 4 GiB is\n * `{ value: 4, unit: \"Gi\" }`. It is the value form of the compact string a\n * manifest carries, `512Mi` or `4G`, which {@link decodeMemory} reads and\n * {@link formatMemory} writes; the wire never carries it as an object.\n *\n * Two quantities that name the same amount in different units are different\n * values: compare amounts with {@link compareMemory}, not by field. A\n * `value` of zero means no memory in every unit.\n */\nexport interface MemoryQuantity {\n readonly value: Integer;\n readonly unit: MemoryUnit;\n}\n\n/**\n * Bounds an acceptable amount of memory, inclusive at both ends. An end\n * left `undefined` is unconstrained.\n */\nexport interface MemoryQuantityRange {\n readonly min?: MemoryQuantity;\n readonly max?: MemoryQuantity;\n}\n\n/**\n * Parses a memory string such as `512Mi`, `4G`, or `1048576`. The value is\n * a whole non-negative number optionally followed by one of the supported\n * unit suffixes; no suffix means bytes. A fractional quantity is refused\n * rather than truncated, and the error names the exact whole-unit spelling\n * when one exists (`1.5Gi` is refused in favour of `1536Mi`). Throws a\n * `TypeError` for an unknown suffix, malformed input, a byte count that\n * would overflow 64 bits.\n */\nexport function decodeMemory(text: string): MemoryQuantity {\n return parseByteQuantity(\"memory\", text);\n}\n\n/**\n * Renders the quantity in the syntax {@link decodeMemory} accepts. A byte\n * quantity is promoted to the largest binary unit that represents it\n * exactly, so 4194304 bytes render as `4Mi` while 1500 bytes render as\n * `1500B`; every other unit renders as its value and suffix. The rendering\n * is lossless: decoding it yields the same number of bytes.\n */\nexport function formatMemory(quantity: MemoryQuantity): string {\n if (quantity.unit === \"B\") {\n const bytes = BigInt(quantity.value);\n for (const rung of BINARY_LADDER) {\n if (bytes >= rung.factor && bytes % rung.factor === 0n) {\n return `${String(bytes / rung.factor)}${rung.suffix}`;\n }\n }\n return `${integerText(quantity.value)}B`;\n }\n return `${integerText(quantity.value)}${quantity.unit}`;\n}\n\n/**\n * The quantity in bytes, the common unit for comparison. A byte count\n * beyond what a `number` holds exactly is returned as the nearest\n * representable value.\n */\nexport function memoryBytes(quantity: MemoryQuantity): number {\n return Number(bytesExact(quantity));\n}\n\n/** Whether the quantity requests no memory, in whichever unit it is held. */\nexport function isZeroMemory(quantity: MemoryQuantity): boolean {\n return BigInt(quantity.value) === 0n;\n}\n\n/**\n * Orders two quantities by amount, so `4096Ki` and `4Mi` compare equal even\n * though their fields differ. Returns -1 when `left` is the smaller amount,\n * 0 when the two are equal, and 1 when `left` is the larger.\n */\nexport function compareMemory(\n left: MemoryQuantity,\n right: MemoryQuantity,\n): -1 | 0 | 1 {\n return compareBytes(bytesExact(left), bytesExact(right));\n}\n\n/**\n * The wire shape of a memory quantity: the compact string, or the bare\n * number a manifest converted from YAML carries for a byte count.\n */\nexport const memoryQuantityShape: Shape<MemoryQuantity> =\n scalar<MemoryQuantity>({\n decode: decodeMemory,\n encode: formatMemory,\n zero: () => ({ value: 0, unit: \"B\" }),\n isZero: isZeroMemory,\n acceptsNumber: true,\n });\n\n/** The exact byte count, for arithmetic that must not round. */\nexport function bytesExact(quantity: MemoryQuantity): bigint {\n return BigInt(quantity.value) * unitBytes(quantity.unit);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n EGRESS_ALLOW_DNS,\n parseEgressAllowRule,\n validateMicropodEgressAllowRule,\n} from \"./egress-allow-rule.js\";\nimport {\n validateWorkloadNetworkWith,\n type WorkloadNetwork,\n} from \"./workload-network.js\";\n\n/**\n * The most distinct protocol and port pairs the allow entries of a Micropod's\n * network may name. Each pair holds one socket open for the Micropod's life.\n */\nexport const MAX_MICROPOD_EGRESS_PORTS = 32;\n\n/**\n * Judges a network a Micropod runs with, as a Computer's execution environment and a\n * Subnet's `restricted-egress` default network are held to it. It holds the\n * structure `validateWorkloadNetwork` holds, with the allow entries of the\n * Micropod network profile:\n *\n * - the class is `none`, `restricted-egress`, or `internet`;\n * `unrestricted`, which would reach the host and the networks it is on,\n * is refused;\n * - each allow entry is one {@link validateMicropodEgressAllowRule} accepts,\n * which adds UDP, wildcard hostnames, IPv4 addresses, and IPv4 ranges to the\n * entries a Pod accepts;\n * - the allow entries name at most {@link MAX_MICROPOD_EGRESS_PORTS}\n * distinct protocol and port pairs.\n *\n * Each refusal names the field it concerns. Throws a `TypeError`.\n */\nexport function validateMicropodNetwork(network: WorkloadNetwork): void {\n validateWorkloadNetworkWith(network, validateMicropodEgressAllowRule);\n if (network.class === \"unrestricted\") {\n throw new TypeError(\n \"network.class unrestricted is not supported for a Micropod\",\n );\n }\n const ports = new Set<string>();\n (network.egress?.allow ?? []).forEach((rule, index) => {\n if (rule === EGRESS_ALLOW_DNS) return;\n const { protocol, port } = parseEgressAllowRule(rule);\n ports.add(`${protocol}:${String(port)}`);\n if (ports.size > MAX_MICROPOD_EGRESS_PORTS) {\n throw new TypeError(\n `network.egress.allow[${String(index)}]: too many distinct egress ports (max ${String(MAX_MICROPOD_EGRESS_PORTS)})`,\n );\n }\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Branded } from \"./brand.js\";\n\n/*\n * The identifiers below name platform records whose public form is a UUID\n * string. Each is a distinct family, so an ID of one kind cannot be passed\n * where an ID of another kind is expected, and each admits one spelling: the\n * canonical lowercase 8-4-4-4-12 form. The braced, URN, and unhyphenated forms\n * that general UUID parsers accept, and uppercase hexadecimal, are second\n * spellings of the same value.\n *\n * None of these families carries a codec: the string is the wire form, and\n * `parse*` judges a value where a caller is about to send one.\n */\n\nconst CANONICAL_UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/u;\n\n/**\n * Identifies a Computer. A Computer is addressed by name or by this ID on\n * the public routes; the ID is the record's server-assigned identifier and\n * outlives any reuse of the name.\n */\nexport type ComputerId = Branded<\"ComputerId\">;\n\n/**\n * Identifies a session of a Computer. It is assigned when the session is\n * created and names it on the Computer's session routes for the whole of\n * its life, before and after it is attached. It is not the identifier of\n * the attachment the session carries once it is ready.\n */\nexport type ComputerSessionId = Branded<\"ComputerSessionId\">;\n\n/**\n * Identifies a requested change of an Account's plan and its retained\n * result.\n */\nexport type BillingPlanChangeId = Branded<\"BillingPlanChangeId\">;\n\n/** Identifies a purchase of extra usage by an Account. */\nexport type BillingPurchaseId = Branded<\"BillingPurchaseId\">;\n\n/**\n * Identifies one entry of a Computer's journal. It is assigned when the\n * entry is admitted and never changes; an entry that records a Computer\n * session's Cell carries the same ID as that Cell.\n */\nexport type JournalEntryId = Branded<\"JournalEntryId\">;\n\n/**\n * Identifies a Namespace. A Namespace is addressed by name within its Account\n * on public routes; this is the record's server-assigned stable identifier.\n */\nexport type NamespaceId = Branded<\"NamespaceId\">;\n\n/**\n * Identifies an access key: a public key registered for a person or a\n * service account. It names the key's record; the private key never leaves\n * its holder.\n */\nexport type AccessKeyId = Branded<\"AccessKeyId\">;\n\n/**\n * Identifies an access profile as the sign-in and token-exchange surface\n * names it, wherever a caller chooses which profile to assume.\n */\nexport type ProfileId = Branded<\"ProfileId\">;\n\n/**\n * Converts a raw string to an {@link AccessKeyId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseAccessKeyId(value: string): AccessKeyId {\n return parseUuidId(value, \"access key ID\") as AccessKeyId;\n}\n\n/**\n * Converts a raw string to a {@link ProfileId}, admitting only the canonical\n * UUID form.\n *\n * @param value A profile's identifier, as a lowercase canonical UUID.\n * @throws {@link TypeError} `value` is not a lowercase canonical UUID; the\n * message names the identifier's family\n */\nexport function parseProfileId(value: string): ProfileId {\n return parseUuidId(value, \"profile ID\") as ProfileId;\n}\n\nfunction parseUuidId(value: string, label: string): string {\n if (!CANONICAL_UUID.test(value)) {\n throw new TypeError(`${label} must be a canonical UUID`);\n }\n return value;\n}\n\n/**\n * Identifies one platform resource record, such as a Vault Secret, by the ID\n * its metadata reports. The ID outlives any reuse of the resource's name.\n */\nexport type ResourceId = Branded<\"ResourceId\">;\n\n/**\n * Converts a raw string to a {@link ResourceId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseResourceId(value: string): ResourceId {\n return parseUuidId(value, \"resource ID\") as ResourceId;\n}\n\n/** Reports whether `value` is a string in canonical {@link ResourceId} form. */\nexport function isResourceId(value: unknown): value is ResourceId {\n return isUuidId(value);\n}\n\n/** Reports whether `value` is a string in canonical UUID form. */\nexport function isUuidId(value: unknown): value is string {\n return typeof value === \"string\" && CANONICAL_UUID.test(value);\n}\n\n/**\n * Converts a raw string to a {@link ComputerId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseComputerId(value: string): ComputerId {\n return parseUuidId(value, \"computer ID\") as ComputerId;\n}\n\n/** Reports whether `value` is a string in canonical {@link ComputerId} form. */\nexport function isComputerId(value: unknown): value is ComputerId {\n return isUuidId(value);\n}\n\n/**\n * Converts a raw string to a {@link ComputerSessionId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseComputerSessionId(value: string): ComputerSessionId {\n return parseUuidId(value, \"computer session ID\") as ComputerSessionId;\n}\n\n/** Reports whether `value` is a string in canonical {@link ComputerSessionId} form. */\nexport function isComputerSessionId(\n value: unknown,\n): value is ComputerSessionId {\n return isUuidId(value);\n}\n\n/**\n * Converts a raw string to a {@link JournalEntryId}, admitting only\n * the canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseJournalEntryId(value: string): JournalEntryId {\n return parseUuidId(value, \"journal entry ID\") as JournalEntryId;\n}\n\n/** Reports whether `value` is a string in canonical {@link JournalEntryId} form. */\nexport function isJournalEntryId(value: unknown): value is JournalEntryId {\n return isUuidId(value);\n}\n\n/**\n * Converts a raw string to a {@link NamespaceId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseNamespaceId(value: string): NamespaceId {\n return parseUuidId(value, \"namespace ID\") as NamespaceId;\n}\n\n/** Reports whether `value` is a string in canonical {@link NamespaceId} form. */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return isUuidId(value);\n}\n\n/** Identifies one storage operation by its stable canonical UUID. */\nexport type StorageOperationId = Branded<\"StorageOperationId\">;\n\n/** Parses the canonical UUID of one storage operation; throws a TypeError otherwise. */\nexport function parseStorageOperationId(value: string): StorageOperationId {\n return parseUuidId(value, \"storage operation ID\") as StorageOperationId;\n}\n\n/** Reports whether value is a canonical storage operation identity. */\nexport function isStorageOperationId(\n value: unknown,\n): value is StorageOperationId {\n return isUuidId(value);\n}\n\n/**\n * Identifies one wake or sleep of a Computer, and its retained result, by\n * its stable canonical UUID.\n */\nexport type ComputerOperationId = Branded<\"ComputerOperationId\">;\n\n/** Parses the canonical UUID of one wake or sleep; throws a TypeError otherwise. */\nexport function parseComputerOperationId(value: string): ComputerOperationId {\n return parseUuidId(value, \"computer operation ID\") as ComputerOperationId;\n}\n\n/** Reports whether value is a canonical computer operation identity. */\nexport function isComputerOperationId(\n value: unknown,\n): value is ComputerOperationId {\n return isUuidId(value);\n}\n\n/**\n * Converts a raw string to a {@link BillingPlanChangeId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseBillingPlanChangeId(value: string): BillingPlanChangeId {\n return parseUuidId(value, \"billing plan change ID\") as BillingPlanChangeId;\n}\n\n/** Reports whether `value` is a string in canonical {@link BillingPlanChangeId} form. */\nexport function isBillingPlanChangeId(\n value: unknown,\n): value is BillingPlanChangeId {\n return isUuidId(value);\n}\n\n/**\n * Converts a raw string to a {@link BillingPurchaseId}, admitting only the\n * canonical UUID form. Throws a `TypeError` naming the family otherwise.\n */\nexport function parseBillingPurchaseId(value: string): BillingPurchaseId {\n return parseUuidId(value, \"billing purchase ID\") as BillingPurchaseId;\n}\n\n/** Reports whether `value` is a string in canonical {@link BillingPurchaseId} form. */\nexport function isBillingPurchaseId(\n value: unknown,\n): value is BillingPurchaseId {\n return isUuidId(value);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { stringifyJson, type Integer, type JsonValue } from \"./json.js\";\nimport {\n always,\n array,\n integer,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { cpuQuantityShape, millicoresExact, type CpuQuantity } from \"./cpu.js\";\nimport {\n bytesExact,\n memoryQuantityShape,\n type MemoryQuantity,\n} from \"./memory.js\";\nimport { validateMicropodNetwork } from \"./micropod-network.js\";\nimport { isResourceId, type ResourceId } from \"./uuid-id.js\";\nimport { errorMessage } from \"./validation.js\";\nimport {\n workloadNetworkShape,\n type WorkloadNetwork,\n} from \"./workload-network.js\";\n\n/**\n * The most bytes the canonical JSON encoding of a Computer's execution environment\n * settings may take. Configuration larger than this belongs in a file of\n * the Computer.\n */\nexport const MAX_COMPUTER_EXECUTION_SETTINGS_BYTES = 16 * 1024;\n\n/**\n * The prefix of the environment variables IDYL sets in a Computer's\n * execution environment. An environment variable whose name begins with it is refused.\n */\nexport const COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX = \"IDYL_\";\n\n/**\n * The OS image of a Computer's execution environment: exactly one of `idyl` and `ref`.\n *\n * An IDYL image names an entry of the IDYL image catalog of the Computer's\n * Subnet. Each start runs that entry's current pinned image, so the\n * Computer receives IDYL's security patches for the same image, the same\n * OS and versions, at its next start, and its journal records each patch it\n * starts on. Another OS or version is another catalog name, which only a\n * write chooses.\n *\n * An own image is an OCI image reference, pullable without credentials,\n * used exactly as given and never patched by IDYL. A reference by tag is\n * pulled again at every start, so the computer runs what the registry serves\n * under the tag then; a reference by digest never changes. The image must\n * contain the executable IDYL starts as the computer's main process; one\n * that does not fails at start.\n */\nexport interface ComputerExecutionSettingsImage {\n /**\n * The name of an IDYL image catalog entry: 1 to 63 lowercase letters,\n * digits, `.`, and `-`, beginning and ending with a letter or digit, such\n * as `ubuntu-24.04`.\n */\n readonly idyl?: string;\n /**\n * The OCI image reference of the user's own image, without whitespace,\n * such as `ghcr.io/example/toolbox@sha256:<digest>`.\n */\n readonly ref?: string;\n}\n\n/** One environment variable every process of a Computer starts with. */\nexport interface ComputerEnvironmentVariable {\n /**\n * A letter or underscore, then letters, digits, or underscores. Names\n * beginning with {@link COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX} are reserved\n * for IDYL. Always written.\n */\n readonly name: string;\n /** The value; it may be empty and must not contain a NUL byte. Always written. */\n readonly value: string;\n}\n\n/**\n * The name of a size a Computer runs at, such as `small`: its whole CPU and\n * memory limits and the most disk it can use. The platform owns the sizes,\n * and `idyl.computers.sizes()` lists them, so a size is an identifier rather\n * than a closed set: 1 to 32 lowercase letters, digits and hyphens,\n * beginning with a letter.\n */\nexport type ComputerSize = string;\n\nconst COMPUTER_SIZE_FORM = /^[a-z][a-z0-9-]{0,31}$/u;\n\n/**\n * Judges that the size is in the form every size name takes: 1 to 32 lowercase\n * letters, digits and hyphens, beginning with a letter. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateComputerSize(size: ComputerSize): void {\n if (size === \"\") throw new TypeError(\"computer size is required\");\n if (!COMPUTER_SIZE_FORM.test(size)) {\n throw new TypeError(\n `computer size ${JSON.stringify(size)} must be 1 to 32 lowercase letters, digits and hyphens, beginning with a letter`,\n );\n }\n}\n\n/**\n * The execution settings of a Computer: its OS image, its CPU and memory, its\n * network, its environment variables, its attached Secrets, its workload\n * identity, and its default shell. A create\n * states the whole document, and a field it leaves out takes IDYL's\n * default. An update changes the\n * settings field by field, as `UpdateComputerRequest` describes: a field it\n * leaves out keeps its value, and the image, which has no default once the\n * Computer exists, is only ever replaced.\n *\n * A change takes effect from the computer's next start and never disturbs a\n * command already running: a computer with nothing running starts on the\n * new settings at the next command, and one with sessions running keeps\n * running them on the settings it started with until they end. The shell is\n * the exception: it is chosen per session, so a change of it applies from\n * the next session and needs no start. Every change is an entry in the\n * Computer's journal holding the whole document after it.\n */\nexport interface ComputerExecutionSettings {\n /**\n * The isolation class the computer runs in, chosen when it is created:\n * `secure-container`, a container behind an application kernel, or `vm`, a\n * whole Linux machine its user administers. A computer that states none runs\n * in `secure-container`, whatever its subnet's default says. The class must\n * be one the subnet's runtime policy admits.\n */\n readonly isolation?: ComputerIsolationClass;\n /**\n * The OS image: an IDYL image by catalog name, or an image of the user's\n * own. It is chosen when the Computer is created; a create that states\n * none receives the catalog's default entry, stored by its name, so a read\n * shows the image a Computer runs.\n */\n readonly image?: ComputerExecutionSettingsImage;\n /**\n * The size the computer runs at, by name, such as `small`, which sets its\n * CPU and memory limits together. A document states `size`, or `cpu` and\n * `memory`, never both. A name the platform does not offer is refused when\n * the settings are written.\n */\n readonly size?: ComputerSize;\n /**\n * The CPU limit, such as `500m` or `2`. `undefined` takes IDYL's default\n * for the Subnet, as it stands each time the computer starts.\n */\n readonly cpu?: CpuQuantity;\n /**\n * The memory limit, such as `512Mi` or `4Gi`. `undefined` takes IDYL's\n * default for the Subnet, as it stands each time the computer starts.\n */\n readonly memory?: MemoryQuantity;\n /**\n * The network, held to the Micropod network profile\n * (`validateMicropodNetwork`): class `none`, `restricted-egress`, or\n * `internet`, one the Subnet's runtime policy admits. `undefined` gives the\n * Subnet's default network as it stands each time the computer starts,\n * with an `unrestricted` default narrowed to `internet`.\n */\n readonly network?: WorkloadNetwork;\n /**\n * Environment variables every process of the computer starts with, in\n * order, each session and command included. A variable overrides one of\n * the same name the image sets. Values are configuration, readable by\n * everyone who may read the Computer; they are not a place for secrets,\n * which `secrets` attaches.\n */\n readonly variables?: readonly ComputerEnvironmentVariable[];\n /**\n * The Vault Secrets the computer uses without holding them: IDYL adds each\n * one's value to the computer's requests to the origins it allows. Each is\n * attached through an environment variable that holds a placeholder in\n * place of the value.\n * See {@link ComputerSecretAttachment}.\n */\n readonly secrets?: readonly ComputerSecretAttachment[];\n /**\n * The workload identity the computer's processes exchange for a cloud\n * provider's short-lived credentials. See {@link ComputerIdentity}.\n */\n readonly identity?: ComputerIdentity;\n /**\n * The computer's default shell: the shell its terminals and interactive\n * sessions run when the session names none, as a clean absolute path\n * in the computer's image, such as `/usr/bin/zsh`. Whether the image\n * holds it is judged when a session starts, and a session whose shell the\n * image does not hold ends without starting. A change applies from the\n * next session. Commands are run by a POSIX shell whatever it says. `undefined` or empty runs `/bin/bash` when the image\n * holds it and `/bin/sh` otherwise, and none is written.\n */\n readonly shell?: string;\n}\n\n/**\n * Attaches one Vault Secret with an egress to a Computer: a Secret that\n * states a source and an egress. Every process of the computer finds a placeholder in\n * the environment variable `env`. The value never enters the computer: the\n * node's egress gateway puts it in place of the placeholder only in a request\n * to one of the Secret's origins, in the place its credential names.\n *\n * The placeholder is random, made when the Secret is attached, and the same\n * at every start of the computer. It exists only in the computer's\n * environment, and no read of the Computer returns it.\n *\n * Attaching needs permission on the Secret itself. The attachment holds the\n * Secret's ID. A deleted Secret keeps its ID for seven days: writing to its\n * name in that time restores the same Secret, with the new value as its\n * newest version, and the computers attached to it resume. Once it is purged,\n * or the seven days pass, a Secret written under the same name is another\n * Secret, with another ID, and no earlier attachment uses it. To stop a\n * computer using a Secret, detach it from that computer.\n *\n * On a computer whose network is `restricted-egress`, each of the Secret's\n * origins must already be covered by the allow list: attaching never opens a\n * destination. A change of the attachments applies from the computer's next\n * start.\n */\nexport interface ComputerSecretAttachment {\n /**\n * The environment variable that holds the placeholder: a name\n * {@link validateComputerEnvironmentVariableName} admits. Always written.\n */\n readonly env: string;\n /** The attached Secret. Always written. */\n readonly secret: ComputerSecretReference;\n}\n\n/**\n * The Secret an attachment uses: by ID, or by name when the attachment is\n * written. A name is resolved once, among the Secrets of the Computer's\n * Namespace and Subnet, when the attachment is written, and a read reports\n * the ID it resolved to. A reference states exactly one of `id` and `name`.\n */\nexport interface ComputerSecretReference {\n /** The Secret's ID. `undefined` or empty when `name` is stated. */\n readonly id?: ResourceId;\n /**\n * The Secret's name, resolved to its ID when the attachment is written.\n * `undefined` or empty when `id` is stated.\n */\n readonly name?: string;\n /**\n * Pins the attachment to one stored version of the Secret, at least 1:\n * the computer is sent that version's value, whatever versions are written\n * after it. `undefined` follows the Secret's current version. A Secret\n * whose source mints its values, such as a GitHub App, has no versions to\n * pin.\n */\n readonly version?: Integer;\n}\n\n/**\n * The workload identity of a Computer: the cloud credentials its processes\n * obtain without a stored key. The computer's processes ask the cloud\n * provider's token service for credentials as its standard SDKs do, and the\n * node's egress gateway answers that request with a token IDYL signs for\n * this Computer alone. The provider returns short-lived credentials for the\n * one role the identity names. Those credentials, and nothing longer-lived,\n * enter the computer. A change applies from the computer's next start.\n */\nexport interface ComputerIdentity {\n /** The AWS role the computer assumes. Required unless another provider is stated. */\n readonly aws?: ComputerAwsIdentity;\n}\n\n/**\n * The AWS IAM role a Computer assumes with its workload identity. The role's\n * trust policy decides which Computers may assume it, by the subject of\n * IDYL's token.\n */\nexport interface ComputerAwsIdentity {\n /**\n * The ARN of the IAM role,\n * `arn:<partition>:iam::<12-digit account>:role/<path and name>`, such as\n * `arn:aws:iam::123456789012:role/ci-push`. Always written.\n */\n readonly roleArn: string;\n}\n\n/** An isolation class a computer selects; open, as the platform may name more. */\nexport type ComputerIsolationClass =\n \"secure-container\" | \"vm\" | (string & Record<never, never>);\n\n/**\n * A shell an image holds, as the image's `/etc/shells` lists it and a\n * terminal offers it.\n */\nexport interface ImageShell {\n /**\n * The shell's file name, the final element of `path`, such as `zsh`.\n * Two shells of one image may share a name, and are told apart by\n * `path`. Always written.\n */\n readonly name: string;\n /**\n * Where the image holds the shell, a clean absolute path, such as\n * `/usr/bin/zsh`. A session that names it runs the shell under this path,\n * and so under its name: `/bin/sh` that is bash runs as sh. Always\n * written.\n */\n readonly path: string;\n}\n\n/** The most shells an image's list holds. */\nexport const MAX_IMAGE_SHELLS = 16;\n\n/** The wire shape of an image's shell. */\nexport const imageShellShape: Shape<ImageShell> = object<ImageShell>({\n name: always(string()),\n path: always(string()),\n});\n\n/**\n * Judges the path of a shell: present, without a NUL, carriage return or\n * line feed, and a clean absolute POSIX path other than `/`. Whether a\n * filesystem holds an executable there is judged where the shell starts.\n * Throws a `TypeError` stating the rule, which a caller prefixes with the\n * field it judged.\n */\nexport function validateShellPath(shell: string): void {\n if (shell.trim() === \"\") {\n throw new TypeError(\"is required\");\n }\n if (\n shell.includes(\"\\u0000\") ||\n shell.includes(\"\\r\") ||\n shell.includes(\"\\n\")\n ) {\n throw new TypeError(\"contains forbidden characters\");\n }\n if (shell === \"/\" || !isCleanAbsolutePath(shell)) {\n throw new TypeError(\"must be a clean absolute POSIX path\");\n }\n}\n\n/** Whether `path` is absolute and holds no empty, `.` or `..` segment. */\nfunction isCleanAbsolutePath(path: string): boolean {\n if (!path.startsWith(\"/\")) return false;\n return path\n .slice(1)\n .split(\"/\")\n .every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/**\n * Judges a list of an image's shells: at most {@link MAX_IMAGE_SHELLS}, each\n * path one {@link validateShellPath} admits, each name the path's final\n * element, and no path listed twice. Two paths may name one file, as\n * `/bin/sh` and `/bin/bash` do when sh is bash, since a shell started under\n * another name behaves as that name. Throws a `TypeError` naming the entry.\n */\nexport function validateImageShells(shells: readonly ImageShell[]): void {\n if (shells.length > MAX_IMAGE_SHELLS) {\n throw new TypeError(`must list at most ${String(MAX_IMAGE_SHELLS)} shells`);\n }\n const seen = new Map<string, number>();\n shells.forEach((shell, index) => {\n const entry = `[${String(index)}]`;\n try {\n validateShellPath(shell.path);\n } catch (cause) {\n throw new TypeError(`${entry}.path ${errorMessage(cause)}`, { cause });\n }\n if (shell.name !== shell.path.slice(shell.path.lastIndexOf(\"/\") + 1)) {\n throw new TypeError(\n `${entry}.name must be the final element of its path`,\n );\n }\n const previous = seen.get(shell.path);\n if (previous !== undefined) {\n throw new TypeError(`${entry}.path duplicates [${String(previous)}]`);\n }\n seen.set(shell.path, index);\n });\n}\n\n/** The wire shape of a computer image. */\nexport const computerExecutionSettingsImageShape: Shape<ComputerExecutionSettingsImage> =\n object<ComputerExecutionSettingsImage>({\n idyl: omitEmpty(string()),\n ref: omitEmpty(string()),\n });\n\n/** The wire shape of a environment variable. */\nexport const computerEnvironmentVariableShape: Shape<ComputerEnvironmentVariable> =\n object<ComputerEnvironmentVariable>({\n name: always(string()),\n value: always(string()),\n });\n\n/** The wire shape of the Secret an attachment names. */\nexport const computerSecretReferenceShape: Shape<ComputerSecretReference> =\n object<ComputerSecretReference>({\n id: omitEmpty(string<ResourceId>()),\n name: omitEmpty(string()),\n version: omitZero(integer({ unsigned: true, bits: 64 })),\n });\n\n/** The wire shape of a Secret attachment. */\nexport const computerSecretAttachmentShape: Shape<ComputerSecretAttachment> =\n object<ComputerSecretAttachment>({\n env: always(string()),\n secret: always(computerSecretReferenceShape),\n });\n\n/** The wire shape of a Computer's workload identity. */\nexport const computerIdentityShape: Shape<ComputerIdentity> =\n object<ComputerIdentity>({\n aws: pointer(\n object<ComputerAwsIdentity>({\n roleArn: always(string()),\n }),\n ),\n });\n\n/** The wire shape of a Computer's execution settings. */\nexport const computerExecutionSettingsShape: Shape<ComputerExecutionSettings> =\n object<ComputerExecutionSettings>({\n image: pointer(computerExecutionSettingsImageShape),\n isolation: omitEmpty(string<ComputerIsolationClass>()),\n size: omitEmpty(string()),\n cpu: omitZero(cpuQuantityShape),\n memory: omitZero(memoryQuantityShape),\n network: pointer(workloadNetworkShape),\n variables: omitEmpty(array(computerEnvironmentVariableShape)),\n secrets: omitEmpty(array(computerSecretAttachmentShape)),\n identity: pointer(computerIdentityShape),\n shell: omitEmpty(string()),\n });\n\n/**\n * The refusal {@link validateComputerExecutionSettings} throws. `field` is the path\n * of the refused field within the Computer spec, in its wire spelling, such\n * as `execution.variables[1].name`, and is the part a caller branches on or\n * reports; it is `execution` when the refusal concerns the settings as a\n * whole, as the size bound does. `rule` says what the field must be. The\n * message reads `<field>: <rule>`.\n */\nexport class ComputerExecutionSettingsError extends TypeError {\n readonly field: string;\n readonly rule: string;\n\n constructor(field: string, rule: string) {\n super(`${field}: ${rule}`);\n this.name = \"ComputerExecutionSettingsError\";\n this.field = field;\n this.rule = rule;\n }\n}\n\nconst INT64_MAX = 2n ** 63n - 1n;\nconst UINT64_MAX = 2n ** 64n - 1n;\nconst NANOCPUS_PER_MILLICORE = 1_000_000n;\n\n/**\n * Judges the settings and throws the first refusal as a\n * {@link ComputerExecutionSettingsError} naming the field:\n *\n * - the image, when stated, is one {@link validateComputerExecutionSettingsImage}\n * admits;\n * - the CPU and memory limits, when stated, are representable as a\n * Micropod's limits are (CPU in 64-bit signed nanoCPUs, memory in 64-bit\n * unsigned bytes);\n * - the network, when stated, is one `validateMicropodNetwork` admits;\n * - every variable name is well formed, unique, and does not begin with\n * {@link COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX}, and no value contains a NUL\n * byte;\n * - every Secret attachment is one {@link validateComputerSecretAttachment}\n * admits, and its variable is named by no other attachment and by no\n * variable;\n * - the identity, when stated, is one {@link validateComputerIdentity} admits,\n * and no variable or attachment names one of the variables IDYL sets for\n * it: `AWS_ROLE_ARN`, `AWS_ROLE_SESSION_NAME` and\n * `AWS_WEB_IDENTITY_TOKEN_FILE`;\n * - the shell, when stated, is one {@link validateShellPath} admits;\n * - the canonical encoding is at most\n * {@link MAX_COMPUTER_EXECUTION_SETTINGS_BYTES}.\n *\n * Whether the platform offers the size, whether the computer fits a host of\n * the Computer's Subnet, whether the Subnet admits its network class,\n * whether its catalog holds the image named, and whether each attached Secret\n * exists, may be attached by the writer, and has origins the computer's\n * network reaches, are the platform's decision.\n */\nexport function validateComputerExecutionSettings(\n computer: ComputerExecutionSettings,\n): void {\n if (computer.image !== undefined) {\n validateComputerExecutionSettingsImage(computer.image);\n }\n const isolation = computer.isolation ?? \"\";\n if (\n isolation !== \"\" &&\n isolation !== \"secure-container\" &&\n isolation !== \"vm\"\n ) {\n throw new ComputerExecutionSettingsError(\n \"execution.isolation\",\n \"must be secure-container or vm\",\n );\n }\n const size = computer.size ?? \"\";\n if (size !== \"\") {\n try {\n validateComputerSize(size);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\n \"execution.size\",\n errorMessage(cause),\n );\n }\n if (computer.cpu !== undefined || computer.memory !== undefined) {\n throw new ComputerExecutionSettingsError(\n \"execution.size\",\n \"must not be stated with cpu or memory\",\n );\n }\n }\n if (\n computer.cpu !== undefined &&\n millicoresExact(computer.cpu) * NANOCPUS_PER_MILLICORE > INT64_MAX\n ) {\n throw new ComputerExecutionSettingsError(\n \"execution.cpu\",\n \"must be representable in int64 nanoCPUs\",\n );\n }\n if (\n computer.memory !== undefined &&\n bytesExact(computer.memory) > UINT64_MAX\n ) {\n throw new ComputerExecutionSettingsError(\n \"execution.memory\",\n \"must be representable in uint64 bytes\",\n );\n }\n if (computer.network !== undefined) {\n const network = computer.network;\n try {\n validateMicropodNetwork(network);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\n \"execution.network\",\n errorMessage(cause),\n );\n }\n }\n validateComputerEnvironmentVariables(computer.variables ?? []);\n validateComputerSecretAttachments(\n computer.secrets ?? [],\n computer.variables ?? [],\n );\n if (computer.identity !== undefined) {\n validateComputerIdentity(computer.identity);\n validateIdentityVariables(computer.variables ?? [], computer.secrets ?? []);\n }\n const shell = computer.shell ?? \"\";\n if (shell !== \"\") {\n try {\n validateShellPath(shell);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\n \"execution.shell\",\n errorMessage(cause),\n );\n }\n }\n if (\n canonicalByteLength(computerExecutionSettingsShape.encode(computer)) >\n MAX_COMPUTER_EXECUTION_SETTINGS_BYTES\n ) {\n throw new ComputerExecutionSettingsError(\n \"execution\",\n `canonical encoding must be at most ${String(MAX_COMPUTER_EXECUTION_SETTINGS_BYTES)} bytes`,\n );\n }\n}\n\n/**\n * Judges the name of a environment variable: a letter or underscore, then\n * letters, digits, or underscores, not beginning with\n * {@link COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX}. Throws a `TypeError` stating\n * the rule.\n */\nexport function validateComputerEnvironmentVariableName(name: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/u.test(name)) {\n throw new TypeError(\"must match [a-zA-Z_][a-zA-Z0-9_]*\");\n }\n if (name.startsWith(COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX)) {\n throw new TypeError(\n `names beginning ${COMPUTER_ENVIRONMENT_VARIABLE_RESERVED_PREFIX} are reserved for IDYL`,\n );\n }\n}\n\nfunction validateComputerEnvironmentVariables(\n variables: readonly ComputerEnvironmentVariable[],\n): void {\n const seen = new Map<string, number>();\n variables.forEach((variable, index) => {\n const field = `execution.variables[${String(index)}]`;\n try {\n validateComputerEnvironmentVariableName(variable.name);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\n `${field}.name`,\n errorMessage(cause),\n );\n }\n const previous = seen.get(variable.name);\n if (previous !== undefined) {\n throw new ComputerExecutionSettingsError(\n `${field}.name`,\n `duplicates variables[${String(previous)}]`,\n );\n }\n seen.set(variable.name, index);\n if (variable.value.includes(\"\\u0000\")) {\n throw new ComputerExecutionSettingsError(\n `${field}.value`,\n \"must not contain a NUL byte\",\n );\n }\n });\n}\n\n/** The form of a Secret's name. */\nconst SECRET_NAME_FORM = /^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$/u;\n\n/**\n * Judges that the attachment names a well-formed variable and states exactly\n * one of a Secret ID in canonical form and a Secret name, throwing a\n * {@link ComputerExecutionSettingsError} whose `field` is relative to the\n * attachment, such as `env` or `secret.id`.\n */\nexport function validateComputerSecretAttachment(\n attachment: ComputerSecretAttachment,\n): void {\n try {\n validateComputerEnvironmentVariableName(attachment.env);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\"env\", errorMessage(cause));\n }\n const id = attachment.secret.id ?? \"\";\n const name = attachment.secret.name ?? \"\";\n if ((id === \"\") === (name === \"\")) {\n throw new ComputerExecutionSettingsError(\n \"secret\",\n \"must state exactly one of id and name\",\n );\n }\n if (id !== \"\") {\n if (!isResourceId(id)) {\n throw new ComputerExecutionSettingsError(\n \"secret.id\",\n \"resource ID must be a canonical UUID\",\n );\n }\n return;\n }\n if (name === \".\" || name === \"..\" || !SECRET_NAME_FORM.test(name)) {\n throw new ComputerExecutionSettingsError(\n \"secret.name\",\n `name ${JSON.stringify(name)} is invalid`,\n );\n }\n}\n\nfunction validateComputerSecretAttachments(\n attachments: readonly ComputerSecretAttachment[],\n variables: readonly ComputerEnvironmentVariable[],\n): void {\n const variableIndex = new Map<string, number>();\n variables.forEach((variable, index) => {\n if (!variableIndex.has(variable.name)) {\n variableIndex.set(variable.name, index);\n }\n });\n const seen = new Map<string, number>();\n attachments.forEach((attachment, index) => {\n const field = `execution.secrets[${String(index)}]`;\n try {\n validateComputerSecretAttachment(attachment);\n } catch (error) {\n if (!(error instanceof ComputerExecutionSettingsError)) throw error;\n throw new ComputerExecutionSettingsError(\n `${field}.${error.field}`,\n error.rule,\n );\n }\n const previous = seen.get(attachment.env);\n if (previous !== undefined) {\n throw new ComputerExecutionSettingsError(\n `${field}.env`,\n `duplicates secrets[${String(previous)}]`,\n );\n }\n const variable = variableIndex.get(attachment.env);\n if (variable !== undefined) {\n throw new ComputerExecutionSettingsError(\n `${field}.env`,\n `duplicates variables[${String(variable)}]`,\n );\n }\n seen.set(attachment.env, index);\n });\n}\n\n/** The variables IDYL sets for a computer with an AWS identity. */\nconst AWS_IDENTITY_VARIABLES: ReadonlySet<string> = new Set([\n \"AWS_ROLE_ARN\",\n \"AWS_ROLE_SESSION_NAME\",\n \"AWS_WEB_IDENTITY_TOKEN_FILE\",\n]);\n\nfunction validateIdentityVariables(\n variables: readonly ComputerEnvironmentVariable[],\n attachments: readonly ComputerSecretAttachment[],\n): void {\n const named = [\n ...variables.map((v, i) => [`variables[${String(i)}].name`, v.name]),\n ...attachments.map((a, i) => [`secrets[${String(i)}].env`, a.env]),\n ];\n for (const [field, name = \"\"] of named) {\n if (AWS_IDENTITY_VARIABLES.has(name)) {\n throw new ComputerExecutionSettingsError(\n `execution.${String(field)}`,\n `${name} is set by IDYL for a computer with an identity`,\n );\n }\n }\n}\n\n/** The form of an IAM role ARN. */\nconst AWS_ROLE_ARN_FORM =\n /^arn:aws(?:-cn|-us-gov)?:iam::[0-9]{12}:role\\/[A-Za-z0-9+=,.@_/-]{1,576}$/u;\n\n/**\n * Judges that the identity states a provider, and an AWS role ARN in IAM's\n * form, throwing a {@link ComputerExecutionSettingsError} naming the field.\n * Whether the role exists and trusts the Computer is AWS's decision.\n */\nexport function validateComputerIdentity(identity: ComputerIdentity): void {\n if (identity.aws === undefined) {\n throw new ComputerExecutionSettingsError(\n \"execution.identity\",\n \"must state aws\",\n );\n }\n if (!AWS_ROLE_ARN_FORM.test(identity.aws.roleArn)) {\n throw new ComputerExecutionSettingsError(\n \"execution.identity.aws.roleArn\",\n \"must be an IAM role ARN: arn:<partition>:iam::<account>:role/<name>\",\n );\n }\n}\n\n/**\n * Judges that the image states exactly one of `idyl` and `ref`, an IDYL\n * name in catalog form, and a reference without whitespace, throwing a\n * {@link ComputerExecutionSettingsError} naming the field.\n */\nexport function validateComputerExecutionSettingsImage(\n image: ComputerExecutionSettingsImage,\n): void {\n const idyl = image.idyl ?? \"\";\n const ref = image.ref ?? \"\";\n if ((idyl === \"\") === (ref === \"\")) {\n throw new ComputerExecutionSettingsError(\n \"execution.image\",\n \"must state exactly one of idyl and ref\",\n );\n }\n if (idyl !== \"\") {\n try {\n validateComputerImageName(idyl);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\n \"execution.image.idyl\",\n errorMessage(cause),\n );\n }\n return;\n }\n if (GO_SPACE.test(ref)) {\n throw new ComputerExecutionSettingsError(\n \"execution.image.ref\",\n \"must not contain whitespace\",\n );\n }\n}\n\n/** The white space Go's `unicode.IsSpace` reports, which a reference may not carry. */\nconst GO_SPACE =\n /[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]/u;\n\n/**\n * Whether `ref` is an own image referenced by a SHA-256 digest,\n * `<repository>@sha256:<64 lowercase hexadecimal digits>`, which never\n * changes.\n */\nexport function isComputerImageDigestReference(ref: string): boolean {\n const at = ref.indexOf(\"@sha256:\");\n return at >= 0 && /^[0-9a-f]{64}$/u.test(ref.slice(at + \"@sha256:\".length));\n}\n\n/**\n * Judges the form of an IDYL image catalog name: 1 to 63 lowercase\n * letters, digits, `.`, and `-`, beginning and ending with a letter or\n * digit. Whether a catalog holds the name is the platform's decision.\n * Throws a `TypeError` stating the rule.\n */\nexport function validateComputerImageName(name: string): void {\n if (!/^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/u.test(name)) {\n throw new TypeError(\n \"must be 1 to 63 lowercase letters, digits, '.', and '-', beginning and ending with a letter or digit\",\n );\n }\n}\n\n/**\n * The number of bytes the reference contract's JSON encoder writes for `value`: the\n * UTF-8 bytes of its JSON text, with `<`, `>`, `&`, U+2028, and U+2029\n * escaped as six-byte `\\uXXXX` sequences, as that encoder escapes them.\n */\nfunction canonicalByteLength(value: unknown): number {\n const text = stringifyJson(value as JsonValue);\n let length = new TextEncoder().encode(text).byteLength;\n for (const character of text) {\n if (character === \"<\" || character === \">\" || character === \"&\") {\n length += 5;\n } else if (character === \"
\" || character === \"
\") {\n length += 3;\n }\n }\n return length;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"./json.js\";\nimport { scalar, integerText, type Shape } from \"../internal/strictdecode.js\";\nimport {\n compareBytes,\n parseByteQuantity,\n unitBytes,\n type ByteUnit,\n} from \"./byte-quantity.js\";\n\n/**\n * The unit a {@link VolumeQuantity} is denominated in. Both the binary (IEC,\n * powers of 1024) family, `Ki`, `Mi`, `Gi`, and `Ti`, and the decimal (SI,\n * powers of 1000) family, `K`, `M`, `G`, and `T`, are supported; `B` is raw\n * bytes. The token of each unit is exactly the suffix {@link decodeVolume}\n * accepts for it.\n */\nexport type VolumeUnit = ByteUnit;\n\n/**\n * An amount of storage as a whole number in a declared unit, used to size\n * volumes and disks. It is the value form of the compact string a manifest\n * carries, `20Gi` or `100G`, which {@link decodeVolume} reads and\n * {@link formatVolume} writes; the wire never carries it as an object.\n *\n * Two quantities that name the same amount in different units are different\n * values: compare amounts with {@link compareVolume}, not by field. A\n * `value` of zero means no storage, which validators treat as a missing\n * size where one is required.\n */\nexport interface VolumeQuantity {\n readonly value: Integer;\n readonly unit: VolumeUnit;\n}\n\n/**\n * Bounds an acceptable amount of storage, inclusive at both ends. An end\n * left `undefined` is unconstrained.\n */\nexport interface VolumeQuantityRange {\n readonly min?: VolumeQuantity;\n readonly max?: VolumeQuantity;\n}\n\n/**\n * Parses a storage size string such as `20Gi`, `100G`, or `4096`. The value\n * is a whole non-negative number optionally followed by one of the\n * supported unit suffixes; no suffix means bytes. A fractional quantity is\n * refused rather than truncated, and the error names the exact whole-unit\n * spelling when one exists. Throws a `TypeError` for an unknown suffix,\n * malformed input, a byte count that would overflow 64 bits.\n */\nexport function decodeVolume(text: string): VolumeQuantity {\n return parseByteQuantity(\"volume\", text);\n}\n\n/**\n * Renders the quantity in the syntax {@link decodeVolume} accepts: value and\n * suffix for a unit-bearing quantity, and a bare number for a byte\n * quantity. Unlike memory, a byte count is not promoted to a larger unit.\n * The rendering is lossless: decoding it yields the same number of bytes.\n */\nexport function formatVolume(quantity: VolumeQuantity): string {\n if (quantity.unit === \"B\") return integerText(quantity.value);\n return `${integerText(quantity.value)}${quantity.unit}`;\n}\n\n/**\n * The quantity in bytes, the common unit for comparison. A byte count\n * beyond what a `number` holds exactly is returned as the nearest\n * representable value.\n */\nexport function volumeBytes(quantity: VolumeQuantity): number {\n return Number(volumeBytesExact(quantity));\n}\n\n/** Whether the quantity requests no storage, in whichever unit it is held. */\nexport function isZeroVolume(quantity: VolumeQuantity): boolean {\n return BigInt(quantity.value) === 0n;\n}\n\n/**\n * Orders two quantities by amount, so `4096Ki` and `4Mi` compare equal even\n * though their fields differ. Returns -1 when `left` is the smaller amount,\n * 0 when the two are equal, and 1 when `left` is the larger.\n */\nexport function compareVolume(\n left: VolumeQuantity,\n right: VolumeQuantity,\n): -1 | 0 | 1 {\n return compareBytes(volumeBytesExact(left), volumeBytesExact(right));\n}\n\n/**\n * The wire shape of a storage quantity: the compact string, or the bare\n * number a manifest converted from YAML carries for a byte count.\n */\nexport const volumeQuantityShape: Shape<VolumeQuantity> =\n scalar<VolumeQuantity>({\n decode: decodeVolume,\n encode: formatVolume,\n zero: () => ({ value: 0, unit: \"B\" }),\n isZero: isZeroVolume,\n acceptsNumber: true,\n });\n\n/** The exact byte count, for arithmetic that must not round. */\nexport function volumeBytesExact(quantity: VolumeQuantity): bigint {\n return BigInt(quantity.value) * unitBytes(quantity.unit);\n}\n\n/** Checks a known unit and exact unsigned 64-bit byte count; zero is valid and policy belongs to the caller. */\nexport function validateVolumeQuantity(quantity: VolumeQuantity): void {\n if (\n ![\"\", \"B\", \"Ki\", \"Mi\", \"Gi\", \"Ti\", \"K\", \"M\", \"G\", \"T\"].includes(\n quantity.unit,\n )\n )\n throw new TypeError(`unknown volume unit ${JSON.stringify(quantity.unit)}`);\n decodeVolume(formatVolume(quantity));\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseJson, type Integer, type JsonObject } from \"../resource/json.js\";\nimport {\n validateComputerSize,\n type ComputerSize,\n} from \"../resource/computer-execution-settings.js\";\nimport {\n cpuQuantityShape,\n isZeroCpu,\n type CpuQuantity,\n} from \"../resource/cpu.js\";\nimport {\n isZeroMemory,\n memoryQuantityShape,\n type MemoryQuantity,\n} from \"../resource/memory.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n isZeroVolume,\n volumeQuantityShape,\n type VolumeQuantity,\n} from \"../resource/volume.js\";\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\n\n/**\n * One size a Computer can run at, as the platform offers it. A read carries a\n * field newer than this SDK; {@link validateComputerSizeInfo} judges.\n */\nexport interface ComputerSizeInfo {\n /** The size's name, which a Computer's create and update state. */\n readonly name: ComputerSize;\n /** The size's name for display, such as `Small`. */\n readonly label: string;\n /** The CPU limit of a Computer of this size. */\n readonly cpu: CpuQuantity;\n /** The memory limit of a Computer of this size. */\n readonly memory: MemoryQuantity;\n /** The most a Computer of this size can store. */\n readonly disk: VolumeQuantity;\n /**\n * The most files, folders and links a Computer of this size holds. A save\n * or an upload that adds names past it fails with `SAVE_REASON_NAME_LIMIT`.\n * `undefined` when the size has no such limit.\n */\n readonly names?: Integer;\n /** Whether a Computer that states no size, CPU or memory runs at this size. Always written. */\n readonly default: boolean;\n}\n\nconst computerSizeInfoShape: Shape<ComputerSizeInfo> = object<ComputerSizeInfo>(\n {\n name: always(string()),\n label: always(string()),\n cpu: always(cpuQuantityShape),\n memory: always(memoryQuantityShape),\n disk: always(volumeQuantityShape),\n names: omitEmpty(integer({ unsigned: false, bits: 64 })),\n default: always(boolean()),\n },\n);\n\n/**\n * Every size a Computer can run at, smallest first, as `GET /v1/computer-sizes`\n * serves it. The read needs no credential.\n */\nexport interface ListComputerSizesResponse {\n /** Every size, smallest first. Always written, empty rather than omitted. */\n readonly items: readonly ComputerSizeInfo[];\n}\n\nconst listComputerSizesResponseShape: Shape<ListComputerSizesResponse> =\n object<ListComputerSizesResponse>({\n items: always(array(computerSizeInfoShape)),\n });\n\n/**\n * Judges the size: a name in identifier form, a label, a CPU, memory and\n * disk greater than zero, and a name limit that is not negative. Throws a\n * `TypeError`.\n */\nexport function validateComputerSizeInfo(size: ComputerSizeInfo): void {\n prefixed(\"name\", () => {\n validateComputerSize(size.name);\n });\n if (size.label === \"\") throw new TypeError(\"label is required\");\n if (isZeroCpu(size.cpu)) {\n throw new TypeError(\"cpu must be greater than zero\");\n }\n if (isZeroMemory(size.memory)) {\n throw new TypeError(\"memory must be greater than zero\");\n }\n if (isZeroVolume(size.disk)) {\n throw new TypeError(\"disk must be greater than zero\");\n }\n if (size.names !== undefined && BigInt(size.names) < 0n) {\n throw new TypeError(\"names must not be negative\");\n }\n}\n\n/**\n * Judges the list: valid sizes, each named once, and at most one default.\n * Throws a `TypeError`.\n */\nexport function validateListComputerSizesResponse(\n response: ListComputerSizesResponse,\n): void {\n const names = new Set<ComputerSize>();\n let hasDefault = false;\n response.items.forEach((item, index) => {\n const at = `items[${String(index)}]`;\n prefixed(at, () => {\n validateComputerSizeInfo(item);\n });\n if (names.has(item.name)) {\n throw new TypeError(\n `${at}: size ${JSON.stringify(item.name)} is listed twice`,\n );\n }\n names.add(item.name);\n if (item.default && hasDefault) {\n throw new TypeError(`${at}: only one size can be the default`);\n }\n hasDefault ||= item.default;\n });\n}\n\n/**\n * Reads the list as served, leniently. `document` is JSON text or a value\n * already parsed from JSON.\n */\nexport function decodeListComputerSizesResponse(\n document: unknown,\n): ListComputerSizesResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listComputerSizesResponseShape, \"lenient\");\n}\n\n/** Renders the list as the document the platform emits. */\nexport function encodeListComputerSizesResponse(\n response: ListComputerSizesResponse,\n): JsonObject {\n return listComputerSizesResponseShape.encode(response) as JsonObject;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { TransportError } from \"../errors.js\";\nimport { isInt64, numberOrBigInt } from \"./strictdecode.js\";\n/*\n * The judgement every list envelope receives before its items are handed\n * back. A response is read leniently and carried as it arrived; what is\n * judged is only what the SDK needs to hand back a usable page: `items` is\n * an array, absent or null reading as empty, and `totalCount` is an\n * integer, absent reading as zero.\n */\nimport type { ListEnvelope } from \"../api/types.js\";\nimport type { Integer } from \"../resource/json.js\";\n\n/**\n * Reads a list envelope, throwing an `Error` prefixed `invalid list\n * <plural> response` when it is not one. Each item is handed back as it\n * arrived; `judgeItem`, when given, is called with each item and its index\n * and throws for one the caller cannot use.\n */\nexport function listEnvelope<T, Count = Integer>(\n response: unknown,\n plural: string,\n judgeItem?: (item: unknown, index: number) => void,\n decodeCount?: (value: unknown) => Count,\n): ListEnvelope<T, Count> {\n const envelope = asRecord(response);\n const rawItems: unknown = envelope[\"items\"] ?? [];\n if (!Array.isArray(rawItems)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid list ${plural} response: items must be an array`,\n );\n }\n const items: readonly unknown[] = rawItems;\n const rawCount = envelope[\"totalCount\"] ?? 0;\n if (decodeCount === undefined && !isInt64(rawCount)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid list ${plural} response: totalCount must be an integer`,\n );\n }\n if (judgeItem !== undefined) {\n items.forEach((item: unknown, index) => {\n judgeItem(item, index);\n });\n }\n const snapshotCursor = envelope[\"snapshotCursor\"];\n const position = envelope[\"continue\"];\n return {\n items: items as readonly T[],\n totalCount:\n decodeCount === undefined\n ? (numberOrBigInt(BigInt(rawCount as Integer)) as Count)\n : decodeCount(envelope[\"totalCount\"]),\n ...(typeof snapshotCursor === \"string\" && snapshotCursor !== \"\"\n ? { snapshotCursor }\n : {}),\n ...(typeof position === \"string\" && position !== \"\"\n ? { continue: position }\n : {}),\n };\n}\n\n/** Whether `value` is a plain JSON object. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** `value` as a record, or an empty one when it is not an object. */\nexport function asRecord(value: unknown): Record<string, unknown> {\n return isRecord(value) ? value : {};\n}\n\n/**\n * A response envelope with the field `key` read through `decode`, the\n * lenient typed decoder of the kind it carries; everything else in the\n * envelope is carried as it arrived.\n */\nexport function readEnvelope<K extends string, T>(\n response: unknown,\n key: K,\n decode: (document: unknown) => T,\n): Record<string, unknown> & Record<K, T> {\n const envelope = asRecord(response);\n return {\n ...envelope,\n [key]: served(key, () => decode(envelope[key])),\n } as Record<string, unknown> & Record<K, T>;\n}\n\n/** A paged list whose items are read through `decode`, the lenient typed decoder of their kind. */\nexport function readList<T, Count = Integer>(\n response: unknown,\n plural: string,\n decode: (document: unknown) => T,\n decodeCount?: (value: unknown) => Count,\n): ListEnvelope<T, Count> {\n const page = listEnvelope<unknown, Count>(\n response,\n plural,\n undefined,\n decodeCount,\n );\n return {\n ...page,\n items: page.items.map((item) =>\n served(plural, () => {\n if (!isRecord(item)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid list ${plural} response: an item is not an object`,\n );\n }\n return decode(item);\n }),\n ),\n };\n}\n\n/**\n * Runs a decoder over served data. A document it cannot read at all is the\n * platform's fault, never the caller's, so it is an `invalid_response`\n * `TransportError` with a fixed sentence naming only the field.\n */\nexport function served<T>(field: string, decode: () => T): T {\n try {\n return decode();\n } catch (cause) {\n if (cause instanceof TransportError) throw cause;\n throw new TransportError(\"invalid_response\", `invalid ${field} response`, {\n cause,\n });\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n decodeListComputerSizesResponse,\n type ListComputerSizesResponse,\n} from \"../api/computer-size.js\";\nimport { COMPUTER_SIZES } from \"../internal/apipath.js\";\nimport type { ServiceState } from \"../internal/context.js\";\nimport { requireMeta } from \"../internal/endpoints.js\";\nimport { listEnvelope } from \"../internal/envelopes.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport type { RequestOptions } from \"../internal/transport.js\";\n\n/**\n * Reads every size a Computer can run at from the network's metadata endpoint,\n * anonymously: no credential is consulted and no Account is needed. The list\n * is returned as served; `validateListComputerSizesResponse` judges it.\n */\nexport async function listComputerSizes(\n state: ServiceState,\n request: RequestOptions = {},\n): Promise<ListComputerSizesResponse> {\n const response = await state.transport.anonymousJson<unknown>(\n \"GET\",\n requireMeta(state.endpoints.meta),\n COMPUTER_SIZES,\n signalOption(request.signal),\n );\n listEnvelope(response, \"computer sizes\");\n return decodeListComputerSizesResponse(response);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Sign-in, signup, and the identity exchanges. Starting sign-in is anonymous.\n * Every exchange proves possession of a key the caller holds: verifying a\n * code, redeeming a browser code and exchanging an access key prove the key\n * alone, and the tokens they issue are bound to it; every other exchange\n * presents a refresh token with a proof by the key it is bound to. The\n * service holds no credential of its own, and every token is opaque to it.\n */\nimport type {\n AuthorizeBrowserRequest,\n AuthorizeBrowserResponse,\n ExchangeBrowserRequest,\n} from \"../api/auth-browser.js\";\nimport type {\n ExchangeAccessKeyRequest,\n ResendAuthRequest,\n ResendAuthResponse,\n StartAuthRequest,\n StartAuthResponse,\n VerifyAuthRequest,\n VerifyAuthResponse,\n} from \"../api/auth.js\";\nimport type {\n ListProfilesResponse,\n ProfileTokenRequest,\n ProfileTokenResponse,\n} from \"../api/auth-profile.js\";\nimport type {\n SignupOffer,\n SignupRequest,\n SignupResponse,\n} from \"../api/signup.js\";\nimport {\n BROWSER_AUTHORIZE,\n BROWSER_EXCHANGE,\n LOGIN_RESEND,\n LOGIN_START,\n LOGIN_VERIFY,\n LOGOUT,\n SIGNUP,\n SIGNUP_OFFER,\n TOKEN_ACCESS_KEY,\n TOKEN_PROFILE,\n TOKEN_PROFILES,\n} from \"../internal/apipath.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport { Transport } from \"../internal/transport.js\";\nimport type { TransportOptions } from \"../internal/transport.js\";\nimport type { RequestOptions } from \"../request.js\";\n\n/** The endpoints sign-in addresses. */\nexport interface IdentityEndpoints {\n readonly identity: string;\n readonly api: string;\n}\n\n/**\n * A refresh token and the key it is bound to. Every exchange that presents\n * it proves possession of `key`.\n */\nexport interface RefreshPresentation {\n readonly refreshToken: string;\n readonly key: CryptoKeyPair;\n}\n\n/** The identity operations, as the reference contract defines them. */\nexport interface IdentityService {\n startAuth(\n request: StartAuthRequest,\n options?: RequestOptions,\n ): Promise<StartAuthResponse>;\n resendAuth(\n request: ResendAuthRequest,\n options?: RequestOptions,\n ): Promise<ResendAuthResponse>;\n verifyAuth(\n request: VerifyAuthRequest,\n key: CryptoKeyPair,\n options?: RequestOptions,\n ): Promise<VerifyAuthResponse>;\n getProfileAccessToken(\n refresh: RefreshPresentation,\n request: ProfileTokenRequest,\n options?: RequestOptions,\n ): Promise<ProfileTokenResponse>;\n listAssumableProfiles(\n refresh: RefreshPresentation,\n options?: RequestOptions,\n ): Promise<ListProfilesResponse>;\n logout(refresh: RefreshPresentation, options?: RequestOptions): Promise<void>;\n signup(\n refresh: RefreshPresentation,\n request: SignupRequest,\n options?: RequestOptions,\n ): Promise<SignupResponse>;\n getSignupOffer(\n refresh: RefreshPresentation,\n options?: RequestOptions,\n ): Promise<SignupOffer>;\n authorizeBrowser(\n refresh: RefreshPresentation,\n request: AuthorizeBrowserRequest,\n options?: RequestOptions,\n ): Promise<AuthorizeBrowserResponse>;\n exchangeBrowser(\n request: ExchangeBrowserRequest,\n key: CryptoKeyPair,\n options?: RequestOptions,\n ): Promise<ProfileTokenResponse>;\n exchangeAccessKey(\n request: ExchangeAccessKeyRequest,\n key: CryptoKeyPair,\n options?: RequestOptions,\n ): Promise<ProfileTokenResponse>;\n}\n\n/**\n * Builds the identity service over `endpoints`. `transportOptions` configure\n * the one transport every operation goes through; it holds no credential\n * source, so nothing but the presentation an exchange is given is ever\n * presented.\n */\nexport function identityService(\n endpoints: IdentityEndpoints,\n transportOptions: Omit<TransportOptions, \"credential\">,\n): IdentityService {\n const transport = new Transport(transportOptions);\n /**\n * The presentation of a refresh exchange, with the refresh token required;\n * the transport judges both members before anything is sent.\n */\n const presenting = (refresh: RefreshPresentation): RefreshPresentation => {\n if (\n typeof (refresh as unknown) !== \"object\" ||\n (refresh as unknown) === null\n ) {\n throw new TypeError(\"refresh credential is required\");\n }\n const refreshToken = refresh.refreshToken as string | undefined;\n return { refreshToken: refreshToken ?? \"\", key: refresh.key };\n };\n return Object.freeze({\n /** Requests a one-time authentication code. Anonymous. */\n async startAuth(request: StartAuthRequest, options: RequestOptions = {}) {\n return await transport.anonymousJson<StartAuthResponse>(\n \"POST\",\n endpoints.identity,\n LOGIN_START,\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Requests that the one-time authentication code be sent again. Like\n * `startAuth` it is anonymous, and its response carries no information\n * about whether the address belongs to an Account.\n */\n async resendAuth(request: ResendAuthRequest, options: RequestOptions = {}) {\n return await transport.anonymousJson<ResendAuthResponse>(\n \"POST\",\n endpoints.identity,\n LOGIN_RESEND,\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Verifies a one-time code with a proof by `key`, and returns a refresh\n * token bound to it.\n */\n async verifyAuth(\n request: VerifyAuthRequest,\n key: CryptoKeyPair,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<VerifyAuthResponse>(\n \"POST\",\n endpoints.identity,\n LOGIN_VERIFY,\n { key },\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Exchanges a refresh token for a profile access token bound to the\n * same key, and rotates the refresh token.\n */\n async getProfileAccessToken(\n refresh: RefreshPresentation,\n request: ProfileTokenRequest,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<ProfileTokenResponse>(\n \"POST\",\n endpoints.identity,\n TOKEN_PROFILE,\n presenting(refresh),\n { body: request, ...signalOption(options.signal) },\n );\n },\n /** Lists the profiles a refresh token may assume; it is not rotated. */\n async listAssumableProfiles(\n refresh: RefreshPresentation,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<ListProfilesResponse>(\n \"GET\",\n endpoints.identity,\n TOKEN_PROFILES,\n presenting(refresh),\n signalOption(options.signal),\n );\n },\n /** Ends the sign-in a refresh token belongs to. */\n async logout(refresh: RefreshPresentation, options: RequestOptions = {}) {\n await transport.exchangeJson<undefined>(\n \"POST\",\n endpoints.identity,\n LOGOUT,\n presenting(refresh),\n { response: \"none\", ...signalOption(options.signal) },\n );\n },\n /**\n * Creates the first Account for an authenticated identity. Throws a\n * `TypeError` before any request when the terms are not accepted.\n */\n async signup(\n refresh: RefreshPresentation,\n request: SignupRequest,\n options: RequestOptions = {},\n ) {\n if (!request.acceptedTerms) {\n throw new TypeError(\"terms must be accepted to create an account\");\n }\n return await transport.exchangeJson<SignupResponse>(\n \"POST\",\n endpoints.api,\n SIGNUP,\n presenting(refresh),\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Reads what an Account created now by the signed-in identity would start\n * with. It reserves nothing: `signup` makes the decision.\n */\n async getSignupOffer(\n refresh: RefreshPresentation,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<SignupOffer>(\n \"GET\",\n endpoints.api,\n SIGNUP_OFFER,\n presenting(refresh),\n signalOption(options.signal),\n );\n },\n /**\n * Issues a one-time code bound to a browser's S256 PKCE transaction and\n * key, and rotates the refresh token.\n */\n async authorizeBrowser(\n refresh: RefreshPresentation,\n request: AuthorizeBrowserRequest,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<AuthorizeBrowserResponse>(\n \"POST\",\n endpoints.identity,\n BROWSER_AUTHORIZE,\n presenting(refresh),\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Redeems a one-time code with a proof by `key`, the browser key the\n * code names, for an access token and a refresh token bound to it.\n */\n async exchangeBrowser(\n request: ExchangeBrowserRequest,\n key: CryptoKeyPair,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<ProfileTokenResponse>(\n \"POST\",\n endpoints.identity,\n BROWSER_EXCHANGE,\n { key },\n { body: request, ...signalOption(options.signal) },\n );\n },\n /**\n * Exchanges an access key for an access token with a proof by `key`,\n * the access key's own key, to which the token is bound.\n */\n async exchangeAccessKey(\n request: ExchangeAccessKeyRequest,\n key: CryptoKeyPair,\n options: RequestOptions = {},\n ) {\n return await transport.exchangeJson<ProfileTokenResponse>(\n \"POST\",\n endpoints.identity,\n TOKEN_ACCESS_KEY,\n { key },\n { body: request, ...signalOption(options.signal) },\n );\n },\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The access key file, the public format an access key is kept in, and the\n * credential source that exchanges one for access tokens. The file is one\n * JSON object:\n *\n * {\"type\":\"idyl-access-key\",\"network\":\"<network>\",\"accessKeyId\":\"<uuid>\",\n * \"account\":\"<12-digit Account ID>\",\"privateKey\":<private JWK>}\n *\n * where `privateKey` is an Ed25519 (RFC 8037) or ECDSA P-256 (RFC 7518)\n * private JSON Web Key. Every error names the problem and never any key\n * material.\n */\nimport type {\n Credential,\n CredentialContext,\n CredentialSource,\n} from \"../credential.js\";\nimport { TransportError } from \"../errors.js\";\nimport { abortable } from \"../internal/abort.js\";\nimport { coordinate, keyPairProblem } from \"../internal/dpop.js\";\nimport { validateNetworkDomain } from \"../internal/endpoints.js\";\nimport { parseText } from \"../internal/strictdecode.js\";\nimport { isAccountId } from \"../resource/id.js\";\nimport { isUuidId, parseAccessKeyId } from \"../resource/uuid-id.js\";\nimport type { AccessToken, Identity } from \"./identity.js\";\n\n/** The `type` every access key file carries. */\nconst ACCESS_KEY_FILE_TYPE = \"idyl-access-key\";\n\n/** The largest access key file read, in bytes. */\nconst MAX_ACCESS_KEY_FILE_BYTES = 4096;\n\n/** How long before its expiry an access key's token is replaced. */\nconst RENEW_BEFORE_MS = 5 * 60 * 1000;\n/** The least time between two background renewals of a valid token. */\nconst RENEW_RETRY_MS = 30 * 1000;\n/** How long before its expiry a token is no longer handed out. */\nconst VALID_MARGIN_MS = 30 * 1000;\n\n/** The refusal of any file that is not exactly one access key object. */\nconst NOT_A_FILE = \"access key file is not one access key JSON object\";\n\n/** The refusal of a private key that is not a valid, consistent key. */\nconst INVALID_KEY =\n \"access key file private key is not a valid Ed25519 or P-256 key\";\n\n/**\n * An access key as its holder keeps it: the key's ID, the network and\n * Account it belongs to, and its key pair. It is a credential: whoever\n * holds it acts as the key's principal. Keep its file where only its owner\n * can read it, and out of logs and source control.\n */\nexport interface AccessKeyFile {\n /** The IDYL network's API domain, the `network` a client is built with. */\n readonly network: string;\n /** The access key's ID, a lowercase canonical UUID: its record's `id`. */\n readonly accessKeyId: string;\n /** The twelve-digit ID of the Account the key acts in. */\n readonly account: string;\n /** The key pair; its private key is non-extractable unless it was imported extractable. */\n readonly key: CryptoKeyPair;\n}\n\n/** How {@link parseAccessKeyFile} imports the private key. */\nexport interface ParseAccessKeyFileOptions {\n /**\n * Imports the private key extractable, so {@link encodeAccessKeyFile} can\n * write it again. `undefined` imports it non-extractable, which is all a\n * credential needs.\n */\n readonly extractable?: boolean;\n}\n\n/** A private JSON Web Key in the members the file format admits. */\nexport interface PrivateJwk {\n readonly kty: \"OKP\" | \"EC\";\n readonly crv: \"Ed25519\" | \"P-256\";\n readonly x: string;\n readonly y?: string;\n readonly d: string;\n}\n\n/** The file's document, member for member. */\ninterface FileDocument {\n readonly type: typeof ACCESS_KEY_FILE_TYPE;\n readonly network: string;\n readonly accessKeyId: string;\n readonly account: string;\n readonly privateKey: PrivateJwk;\n}\n\n/**\n * Decodes an access key file strictly, at most 4096 bytes: one JSON object\n * with exactly the members of the format, of type `idyl-access-key`,\n * naming a network domain, a canonical access key ID and a twelve-digit\n * Account ID, and an Ed25519 or P-256 private key with matching public members.\n * The private key is imported non-extractable unless `options.extractable` is\n * set.\n *\n * @param text The access key file's text, exactly as given by\n * {@link CreatedAccessKey.keyFile}.\n * @throws {@link TypeError} the text is not a valid access key file; the\n * message names the problem and no key material\n */\nexport async function parseAccessKeyFile(\n text: string,\n options: ParseAccessKeyFileOptions = {},\n): Promise<AccessKeyFile> {\n return await fileOf(decodeFile(text), options.extractable === true);\n}\n\n/**\n * The credential source of an access key file's text, and the network the file\n * names. The file is judged now; its key is imported on the first request.\n * Throws a `TypeError` that names the problem and no key material.\n */\nexport function accessKeySource(\n text: string,\n identity: () => Identity,\n): { readonly network: string; readonly source: CredentialSource } {\n const document = decodeFile(text);\n let source: Promise<CredentialSource> | undefined;\n return {\n network: document.network,\n source: Object.freeze({\n async credential(context: CredentialContext): Promise<Credential> {\n source ??= fileOf(document, false).then((file) =>\n accessKeyCredentials(file, identity()),\n );\n return await (await source).credential(context);\n },\n }),\n };\n}\n\nfunction decodeFile(text: string): FileDocument {\n if (typeof text !== \"string\") {\n throw new TypeError(\"access key file must be text\");\n }\n if (new TextEncoder().encode(text).byteLength > MAX_ACCESS_KEY_FILE_BYTES) {\n throw new TypeError(\n `access key file exceeds ${String(MAX_ACCESS_KEY_FILE_BYTES)} bytes`,\n );\n }\n let parsed: unknown;\n try {\n parsed = parseText(text, \"strict\");\n } catch {\n // The parser's message may quote the text, which holds the key.\n throw new TypeError(NOT_A_FILE);\n }\n return documentOf(parsed);\n}\n\n/**\n * Encodes an access key file in the format {@link parseAccessKeyFile}\n * reads, members in the format's order. The private key must be\n * extractable, as a key {@link parseAccessKeyFile} imported with\n * `extractable` is.\n *\n * @param file The access key to encode.\n * @throws {@link TypeError} the private key is not extractable, the key\n * pair is not an Ed25519 or ECDSA P-256 pair, or a field is invalid\n */\nexport async function encodeAccessKeyFile(\n file: AccessKeyFile,\n): Promise<string> {\n const { network, accessKeyId, account, key } = file;\n const problem = keyPairProblem(key);\n if (problem !== undefined) {\n throw new TypeError(`access key file key ${problem}`);\n }\n if (!key.privateKey.extractable) {\n throw new TypeError(\"access key file private key is not extractable\");\n }\n let exported: JsonWebKey;\n try {\n exported = await crypto.subtle.exportKey(\"jwk\", key.privateKey);\n } catch {\n throw new TypeError(INVALID_KEY);\n }\n const { kty, crv, x, y, d } = exported;\n const document = documentOf({\n type: ACCESS_KEY_FILE_TYPE,\n network,\n accessKeyId,\n account,\n privateKey: kty === \"EC\" ? { kty, crv, x, y, d } : { kty, crv, x, d },\n });\n return encodeFile(document);\n}\n\n/** The file's text, members in the format's order. */\nexport function encodeFile(document: FileDocument): string {\n const { privateKey: k } = document;\n return JSON.stringify({\n type: document.type,\n network: document.network,\n accessKeyId: document.accessKeyId,\n account: document.account,\n privateKey:\n k.y === undefined\n ? { kty: k.kty, crv: k.crv, x: k.x, d: k.d }\n : { kty: k.kty, crv: k.crv, x: k.x, y: k.y, d: k.d },\n });\n}\n\n/** Judges a parsed value as the file's document, member for member. */\nfunction documentOf(value: unknown): FileDocument {\n const file = exactly(value, [\n \"type\",\n \"network\",\n \"accessKeyId\",\n \"account\",\n \"privateKey\",\n ]);\n if (file === undefined) throw new TypeError(NOT_A_FILE);\n if (file[\"type\"] !== ACCESS_KEY_FILE_TYPE) {\n throw new TypeError(\n `access key file type must be ${JSON.stringify(ACCESS_KEY_FILE_TYPE)}`,\n );\n }\n const { network, accessKeyId, account } = file;\n if (typeof network !== \"string\" || !isNetwork(network)) {\n throw new TypeError(\"access key file names no valid network\");\n }\n if (!isUuidId(accessKeyId)) {\n throw new TypeError(\n \"access key file access key ID must be a canonical UUID\",\n );\n }\n if (!isAccountId(account)) {\n throw new TypeError(\"access key file names no valid account\");\n }\n return {\n type: ACCESS_KEY_FILE_TYPE,\n network,\n accessKeyId,\n account,\n privateKey: privateJwk(file[\"privateKey\"]),\n };\n}\n\nfunction isNetwork(network: string): boolean {\n try {\n validateNetworkDomain(network);\n return true;\n } catch {\n return false;\n }\n}\n\n/** A private JWK of exactly the members its key type admits. */\nfunction privateJwk(value: unknown): PrivateJwk {\n const ed = exactly(value, [\"kty\", \"crv\", \"x\", \"d\"]);\n if (\n ed?.[\"kty\"] === \"OKP\" &&\n ed[\"crv\"] === \"Ed25519\" &&\n coordinate(ed[\"x\"]) &&\n coordinate(ed[\"d\"])\n ) {\n return { kty: \"OKP\", crv: \"Ed25519\", x: ed[\"x\"], d: ed[\"d\"] };\n }\n const ec = exactly(value, [\"kty\", \"crv\", \"x\", \"y\", \"d\"]);\n if (\n ec?.[\"kty\"] === \"EC\" &&\n ec[\"crv\"] === \"P-256\" &&\n coordinate(ec[\"x\"]) &&\n coordinate(ec[\"y\"]) &&\n coordinate(ec[\"d\"])\n ) {\n return { kty: \"EC\", crv: \"P-256\", x: ec[\"x\"], y: ec[\"y\"], d: ec[\"d\"] };\n }\n throw new TypeError(INVALID_KEY);\n}\n\n/** `value` as an object holding exactly `members`, or `undefined`. */\nfunction exactly(\n value: unknown,\n members: readonly string[],\n): Record<string, unknown> | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const keys = Object.keys(value);\n return keys.length === members.length &&\n members.every((member) => keys.includes(member))\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/**\n * Imports a judged document's key pair and proves the two halves belong\n * together: a message the private key signs verifies with the public key\n * its members name.\n */\nexport async function fileOf(\n document: FileDocument,\n extractable: boolean,\n): Promise<AccessKeyFile> {\n const { privateKey: jwk } = document;\n const algorithm =\n jwk.kty === \"OKP\"\n ? { name: \"Ed25519\" }\n : { name: \"ECDSA\", namedCurve: \"P-256\" };\n const signing =\n jwk.kty === \"OKP\"\n ? { name: \"Ed25519\" }\n : { name: \"ECDSA\", hash: \"SHA-256\" };\n const publicMembers: JsonWebKey =\n jwk.y === undefined\n ? { kty: jwk.kty, crv: jwk.crv, x: jwk.x }\n : { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };\n let key: CryptoKeyPair;\n try {\n const [privateKey, publicKey] = await Promise.all([\n crypto.subtle.importKey(\"jwk\", { ...jwk }, algorithm, extractable, [\n \"sign\",\n ]),\n crypto.subtle.importKey(\"jwk\", publicMembers, algorithm, true, [\n \"verify\",\n ]),\n ]);\n const probe = crypto.getRandomValues(new Uint8Array(32));\n const signature = await crypto.subtle.sign(signing, privateKey, probe);\n if (!(await crypto.subtle.verify(signing, publicKey, signature, probe))) {\n throw new TypeError(INVALID_KEY);\n }\n key = Object.freeze({ publicKey, privateKey });\n } catch {\n // A WebCrypto failure is reported as the one fixed sentence, never with\n // a cause that could describe the key.\n throw new TypeError(INVALID_KEY);\n }\n return Object.freeze({\n network: document.network,\n accessKeyId: document.accessKeyId,\n account: document.account,\n key,\n });\n}\n\n/** An access key's current token and its expiry, in milliseconds. */\ninterface HeldToken {\n readonly accessToken: string;\n readonly expiresAt: number;\n}\n\n/**\n * A {@link CredentialSource} for an access key. It exchanges the key at\n * `identity` for an access token bound to the same key on first use, and\n * hands that token out while it is valid. From five minutes before its\n * expiry the next token is exchanged in the background while the current\n * one is still handed out, so no request waits for a renewal; a request\n * waits only when there is no valid token, each under its own signal.\n * Exchanges are single-flight and bounded by the identity client's request\n * timeout rather than by any one caller. A failed background renewal is\n * tried again at most every 30 seconds while the token is valid; once it\n * has expired, a failed exchange rejects the requests that waited for it\n * and is tried again by the next.\n *\n * @param file The access key, in the form {@link parseAccessKeyFile} returns.\n * @param identity The identity of a client for the key's network, which\n * performs the exchanges.\n * @throws {@link TypeError} `file` is missing, names a malformed access key\n * ID or holds an unusable key pair, or `identity` is not a client's\n * identity\n */\nexport function accessKeyCredentials(\n file: AccessKeyFile,\n identity: Identity,\n): CredentialSource {\n if (typeof (file as unknown) !== \"object\" || (file as unknown) === null) {\n throw new TypeError(\"access key file is required\");\n }\n const accessKeyId = parseAccessKeyId(file.accessKeyId);\n const { key } = file;\n const problem = keyPairProblem(key);\n if (problem !== undefined) {\n throw new TypeError(`access key file key ${problem}`);\n }\n if (\n typeof (identity as Partial<Identity> | undefined)?.exchangeAccessKey !==\n \"function\"\n ) {\n throw new TypeError(\"identity is required: the client's identity\");\n }\n let current: HeldToken | undefined;\n let pending: Promise<HeldToken> | undefined;\n let nextRenewal = 0;\n const exchange = async (): Promise<HeldToken> => {\n const token: AccessToken = await identity.exchangeAccessKey(\n accessKeyId,\n key,\n );\n const expiresAt = Date.parse(token.expiresAt);\n if (\n !Number.isFinite(expiresAt) ||\n expiresAt <= Date.now() + VALID_MARGIN_MS\n ) {\n throw new TransportError(\n \"invalid_response\",\n \"access key exchange response has no valid expiry\",\n );\n }\n current = { accessToken: token.accessToken, expiresAt };\n return current;\n };\n const start = (): Promise<HeldToken> => {\n nextRenewal = Date.now() + RENEW_RETRY_MS;\n const exchanging = exchange().finally(() => {\n pending = undefined;\n });\n pending = exchanging;\n return exchanging;\n };\n return Object.freeze({\n async credential({ signal }: CredentialContext): Promise<Credential> {\n const now = Date.now();\n const held = current;\n if (held !== undefined && now + VALID_MARGIN_MS < held.expiresAt) {\n if (\n now + RENEW_BEFORE_MS >= held.expiresAt &&\n pending === undefined &&\n now >= nextRenewal\n ) {\n // A failed background renewal is retried by a later request.\n start().catch(() => undefined);\n }\n return { accessToken: held.accessToken, key };\n }\n const token = await abortable(pending ?? start(), signal);\n return { accessToken: token.accessToken, key };\n },\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The judgement a response envelope receives when a service hands back one\n * of its fields rather than the envelope itself, as the reference contract's identity\n * services do. The response is read leniently and carried as it arrived;\n * what is judged is only what the caller is handed: a collection is an\n * array, absent or null reading as empty, and an object is an object.\n */\nimport { TransportError } from \"../errors.js\";\nimport { isRecord } from \"./envelopes.js\";\n\n/**\n * The collection under `key` of the envelope `response`. An absent or null\n * collection reads as empty. Throws an `Error` prefixed\n * `invalid <label> response` when the envelope is not an object or the\n * collection is not an array.\n */\nexport function unwrapCollection(\n response: unknown,\n key: string,\n label: string,\n): readonly unknown[] {\n const value: unknown = envelope(response, label)[key] ?? [];\n if (!Array.isArray(value)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid ${label} response: ${key} must be an array`,\n );\n }\n return value;\n}\n\n/**\n * The object under `key` of the envelope `response`. Throws an `Error`\n * prefixed `invalid <label> response` when the envelope is not an object or\n * the field is absent or not an object.\n */\nexport function unwrapObject(\n response: unknown,\n key: string,\n label: string,\n): unknown {\n const value: unknown = envelope(response, label)[key];\n if (!isRecord(value)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid ${label} response: ${key} must be an object`,\n );\n }\n return value;\n}\n\nfunction envelope(response: unknown, label: string): Record<string, unknown> {\n if (!isRecord(response)) {\n throw new TransportError(\n \"invalid_response\",\n `invalid ${label} response: expected an object`,\n );\n }\n return response;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type {\n CreateAccessKeyRequest,\n CreateAccessKeyResponse,\n} from \"../api/iam.js\";\nimport type { AccessKey } from \"../api/iam-entities.js\";\nimport { ACCESS_KEYS, accessKey } from \"../internal/apipath.js\";\nimport type { ServiceState } from \"../internal/context.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport { unwrapCollection, unwrapObject } from \"../internal/unwrap.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport { parseAccessKeyId } from \"../resource/uuid-id.js\";\n\n/**\n * Access key operations for the calling person. The keys belong to whoever\n * the client's credential authenticates as, not to an Account path, so\n * every route is the same for every caller. Every `accessKeyId` is judged\n * with `parseAccessKeyId` before any request, so a malformed one throws a\n * `TypeError` and sends nothing.\n */\nexport interface AccessKeysService {\n /** The calling person's access key records. */\n list(options?: RequestOptions): Promise<readonly AccessKey[]>;\n /** Registers the public key the request names as an access key. */\n create(\n request: CreateAccessKeyRequest,\n options?: RequestOptions,\n ): Promise<AccessKey>;\n /** Revokes one access key. */\n revoke(accessKeyId: string, options?: RequestOptions): Promise<void>;\n}\n\n/** Builds the access key service. */\nexport function accessKeysService(state: ServiceState): AccessKeysService {\n const { transport, endpoints } = state;\n return Object.freeze({\n async list(options: RequestOptions = {}): Promise<readonly AccessKey[]> {\n const response = await transport.json<unknown>(\n \"GET\",\n endpoints.api,\n ACCESS_KEYS,\n signalOption(options.signal),\n );\n return unwrapCollection(\n response,\n \"accessKeys\",\n \"list access keys\",\n ) as readonly AccessKey[];\n },\n async create(\n request: CreateAccessKeyRequest,\n options: RequestOptions = {},\n ): Promise<AccessKey> {\n const response = await transport.json<CreateAccessKeyResponse>(\n \"POST\",\n endpoints.api,\n ACCESS_KEYS,\n { body: request, ...signalOption(options.signal) },\n );\n return unwrapObject(\n response,\n \"accessKey\",\n \"create access key\",\n ) as AccessKey;\n },\n async revoke(\n accessKeyId: string,\n options: RequestOptions = {},\n ): Promise<void> {\n await transport.json<undefined>(\n \"DELETE\",\n endpoints.api,\n accessKey(parseAccessKeyId(accessKeyId)),\n { response: \"none\", ...signalOption(options.signal) },\n );\n },\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * What every product on the client shares: the per-call options, the page a\n * listing returns, and the walk that turns pages into an async iterator.\n */\nimport { TransportError } from \"../errors.js\";\n\n/**\n * What a call accepts beyond its own arguments. `signal` cancels the call:\n * the credential lookup, the request and the body read stop, and the call\n * rejects with the signal's reason. Cancelling a call never deletes\n * anything.\n */\nexport interface CallOptions {\n /**\n * Cancels the call when it aborts: the call rejects with the signal's\n * reason. `undefined` lets the call run to its end.\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * One page of a listing. `continue` is present on every page but the last:\n * pass it back unchanged as the `continue` option to read the next page.\n * It is opaque and is valid only for its own listing.\n */\nexport interface Page<T> {\n /** The page's items, in the listing's order; empty when there are none. */\n readonly items: readonly T[];\n /**\n * The position of the next page, passed back as the `continue` option;\n * absent on the last page.\n */\n readonly continue?: string;\n}\n\n/** Walks a listing. */\nexport interface ListOptions extends CallOptions {\n /**\n * The most items to read per page. `undefined` takes the platform's page\n * size. Must be a positive integer.\n */\n readonly limit?: number;\n}\n\n/** Selects one page of a listing. */\nexport interface PageOptions extends CallOptions {\n /**\n * The most items to return. `undefined` takes the platform's page size.\n * Must be a positive integer.\n */\n readonly limit?: number;\n /** The `continue` of the previous page; `undefined` starts at the first. */\n readonly continue?: string;\n}\n\n/**\n * Walks a listing page by page, yielding each item in the platform's\n * order, until a page carries no `continue`. `signal` cancels the walk\n * between and during pages.\n */\nexport async function* walk<T>(\n page: (options: PageOptions) => Promise<Page<T>>,\n options: ListOptions = {},\n): AsyncGenerator<T, void, undefined> {\n requireLimit(options.limit);\n let next: string | undefined;\n for (;;) {\n const current = await page({\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n ...(next === undefined ? {} : { continue: next }),\n });\n yield* current.items;\n if (current.continue === undefined) return;\n if (current.continue === next) {\n throw new TransportError(\n \"invalid_response\",\n \"listing returned the position it was asked for\",\n );\n }\n next = current.continue;\n }\n}\n\n/**\n * Judges `limit` before any request: absent, or a positive safe integer.\n * Throws a `TypeError` naming the field.\n */\nexport function requireLimit(limit: number | undefined): number | undefined {\n if (limit === undefined) return undefined;\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new TypeError(\"limit must be a positive integer\");\n }\n return limit;\n}\n\n/**\n * Reads the `continue` of an offset-paged listing back into its offset.\n * Throws a `TypeError` when `value` is not a position this package issued.\n */\nexport function offsetOf(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (!/^(?:0|[1-9][0-9]{0,15})$/u.test(value)) {\n throw new TypeError(\"continue is not a position this listing issued\");\n }\n return Number(value);\n}\n\n/**\n * The `continue` of an offset-paged page: the offset after its items while\n * the platform reports more, absent on the last page.\n */\nexport function offsetContinue(\n offset: number,\n count: number,\n total: number | bigint,\n): string | undefined {\n const next = offset + count;\n return count > 0 && BigInt(next) < BigInt(total) ? String(next) : undefined;\n}\n\n/**\n * One page of an offset-paged listing. `limit` is judged and `continue` read\n * back into its offset before `read` sends anything; the served items become\n * public through `of`, and the page carries the next `continue` while the\n * platform reports more.\n */\nexport async function offsetPage<S, T>(\n options: PageOptions,\n read: (\n page: { readonly limit?: number; readonly offset?: number },\n call: { readonly signal?: AbortSignal },\n ) => Promise<{\n readonly items: readonly S[];\n readonly totalCount: number | bigint;\n }>,\n of: (served: S) => T,\n): Promise<Page<T>> {\n const limit = requireLimit(options.limit);\n const offset = offsetOf(options.continue) ?? 0;\n const page = await read(\n {\n ...(limit === undefined ? {} : { limit }),\n ...(offset === 0 ? {} : { offset }),\n },\n signalOf(options),\n );\n return pageOf(\n page.items.map(of),\n offsetContinue(offset, page.items.length, page.totalCount),\n );\n}\n\n/**\n * The kind of client a call states, recorded with what it changes or runs:\n * `sdk` when absent. Throws a `TypeError` for any other value.\n */\nexport function clientOf(\n client: \"sdk\" | \"console\" | \"cli\" | undefined,\n): \"sdk\" | \"console\" | \"cli\" {\n if (client === undefined) return \"sdk\";\n if (!([\"sdk\", \"console\", \"cli\"] as readonly string[]).includes(client)) {\n throw new TypeError('client must be \"sdk\", \"console\" or \"cli\"');\n }\n return client;\n}\n\n/** The `signal` of `options`, as a transport option. */\nexport function signalOf(options: CallOptions | undefined): {\n readonly signal?: AbortSignal;\n} {\n return options?.signal === undefined ? {} : { signal: options.signal };\n}\n\n/** Judges a required, non-blank string argument. */\nexport function requireText(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new TypeError(`${label} is required`);\n }\n return value;\n}\n\n/** A page of public items. */\nexport function pageOf<T>(\n items: readonly T[],\n next: string | undefined,\n): Page<T> {\n return Object.freeze({\n items: Object.freeze([...items]),\n ...(next === undefined ? {} : { continue: next }),\n });\n}\n\n/** The contract's page request for a public page selection. */\nexport function pageRequest(options: PageOptions): {\n readonly limit?: number;\n readonly continue?: string;\n} {\n const limit = requireLimit(options.limit);\n return {\n ...(limit === undefined ? {} : { limit }),\n ...(options.continue === undefined ? {} : { continue: options.continue }),\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { AccessKey as AccessKeyRecord } from \"../api/iam-entities.js\";\nimport { TransportError } from \"../errors.js\";\nimport type { ServiceState } from \"../internal/context.js\";\nimport { coordinate, keyProfile } from \"../internal/dpop.js\";\nimport { isUuidId } from \"../resource/uuid-id.js\";\nimport { accessKeysService } from \"../services/access-keys.js\";\nimport {\n encodeFile,\n fileOf,\n type AccessKeyFile,\n type PrivateJwk,\n} from \"./access-key-file.js\";\nimport { requireText, signalOf, type CallOptions } from \"./common.js\";\n\n/**\n * The record of an access key. It never carries the private key, which\n * IDYL never holds: `keyThumbprint` is the RFC 7638 thumbprint of the\n * public key IDYL keeps.\n */\nexport interface AccessKey {\n /**\n * The key's ID, a lowercase canonical UUID, which {@link AccessKeys.revoke}\n * takes.\n */\n readonly id: string;\n /** The key's name, as it was created. */\n readonly name: string;\n /** What the key is for; absent when it was created without one. */\n readonly description?: string;\n /** The RFC 7638 SHA-256 thumbprint of the key's public half, unpadded base64url. */\n readonly keyThumbprint: string;\n /** When it expires, as an RFC 3339 instant; absent for a key with no expiry. */\n readonly expiresAt?: string;\n /** When it was created, as an RFC 3339 instant. */\n readonly createdAt?: string;\n /** When it was last exchanged for an access token; absent until it has been. */\n readonly lastUsedAt?: string;\n /** When it was revoked; absent for a key in use. */\n readonly revokedAt?: string;\n}\n\n/**\n * A newly created access key: its record, and the access key file that\n * holds its private key. `keyFile` is the file's text, returned here and\n * never again: write it where only its owner can read it, and keep it out\n * of logs and source control. `file` is the same file ready for\n * `accessKeyCredentials`, its private key held non-extractable.\n */\nexport interface CreatedAccessKey {\n /** The key's record, as registered by IDYL. */\n readonly accessKey: AccessKey;\n /** The access key file's text, which holds the private key. */\n readonly keyFile: string;\n /** The same file, parsed, with its private key held non-extractable. */\n readonly file: AccessKeyFile;\n}\n\n/** Creates an access key. */\nexport interface CreateAccessKeyOptions extends CallOptions {\n /** The key's name: 1 to 128 characters. */\n readonly name: string;\n /** What the key is for, shown with its record; none when absent or empty. */\n readonly description?: string;\n /** When the key expires; a key with none never expires. */\n readonly expiresAt?: Date | string;\n}\n\n/**\n * The access keys of the person the client's credential authenticates as,\n * for programs and servers. An access key is an Ed25519 key pair whose\n * public half is registered with IDYL; whoever holds its private key\n * exchanges it for short-lived access tokens bound to it, which act as\n * that person, with their permissions, until the key expires or is\n * revoked. Every ID is judged before any request: a malformed one throws a\n * `TypeError` and sends nothing.\n *\n * @example\n * ```ts\n * import { writeFile } from \"node:fs/promises\";\n *\n * const { accessKey, keyFile } = await idyl.accessKeys.create({\n * name: \"ci\",\n * expiresAt: \"2027-01-01T00:00:00Z\",\n * });\n * await writeFile(\"ci.idyl-key\", keyFile, { mode: 0o600 });\n * console.log(accessKey.id);\n * ```\n */\nexport interface AccessKeys {\n /**\n * Creates an access key: generates an Ed25519 key pair with WebCrypto,\n * registers its public half, and returns the record and the key file.\n * The private key never leaves the runtime except in the returned file.\n *\n * @throws {@link TypeError} `name` is blank, `description` is not a\n * string, `expiresAt` is not a valid instant, or the client was built\n * from explicit endpoints without a `network`, which the key file names;\n * nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or the\n * response does not name the key that was registered\n */\n create(options: CreateAccessKeyOptions): Promise<CreatedAccessKey>;\n /**\n * Every access key, without any private key.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or the\n * response carries no key records\n */\n list(options?: CallOptions): Promise<readonly AccessKey[]>;\n /**\n * Revokes one access key. A revoked key is never exchanged again, and\n * tokens it obtained stop authorizing within the platform's\n * authorization cache lifetime.\n *\n * @param accessKeyId The key's `id`, a lowercase canonical UUID.\n * @throws {@link TypeError} `accessKeyId` is not a lowercase canonical\n * UUID; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n revoke(accessKeyId: string, options?: CallOptions): Promise<void>;\n}\n\n/** What creating an access key reads from its client. */\nexport interface AccessKeyHost {\n readonly state: ServiceState;\n /** The client's network domain; absent for a client built from endpoints alone. */\n readonly network: string | undefined;\n /** The Account the client's credential acts as. */\n account(options?: CallOptions): Promise<{ readonly id: string }>;\n}\n\n/** Builds the access keys of the person the client's credential authenticates as. */\nexport function accessKeys(host: AccessKeyHost): AccessKeys {\n const service = accessKeysService(host.state);\n return Object.freeze({\n async create(options: CreateAccessKeyOptions) {\n const { name, description, expiresAt } = options;\n requireText(name, \"access key name\");\n if (description !== undefined && typeof description !== \"string\") {\n throw new TypeError(\"description must be a string\");\n }\n const expiry = instant(expiresAt);\n const { network } = host;\n if (network === undefined) {\n throw new TypeError(\n \"network is required to create an access key file: the client was built from endpoints alone\",\n );\n }\n const account = (await host.account(signalOf(options))).id;\n // The private key is extractable only so it can be written into the\n // file below; the file handed back holds a non-extractable copy.\n const generated = await crypto.subtle.generateKey(\n { name: \"Ed25519\" },\n true,\n [\"sign\", \"verify\"],\n );\n const { jwk, thumbprint } = await keyProfile(generated.publicKey);\n const record = keyOf(\n await service.create(\n {\n name,\n ...(description === undefined || description === \"\"\n ? {}\n : { description }),\n publicKey: jwk,\n ...(expiry === undefined ? {} : { expiresAt: expiry }),\n },\n signalOf(options),\n ),\n );\n if (record.keyThumbprint !== thumbprint || !isUuidId(record.id)) {\n throw new TransportError(\n \"invalid_response\",\n \"access key response does not name the registered key\",\n );\n }\n const exported = await crypto.subtle.exportKey(\n \"jwk\",\n generated.privateKey,\n );\n const privateKey = privateJwkOf(exported);\n const document = {\n type: \"idyl-access-key\" as const,\n network,\n accessKeyId: record.id,\n account,\n privateKey,\n };\n return Object.freeze({\n accessKey: record,\n keyFile: encodeFile(document),\n file: await fileOf(document, false),\n });\n },\n async list(options?: CallOptions) {\n const records = await service.list(signalOf(options));\n return Object.freeze(records.map(keyOf));\n },\n async revoke(accessKeyId: string, options?: CallOptions) {\n await service.revoke(accessKeyId, signalOf(options));\n },\n });\n}\n\n/** The private members of a generated Ed25519 key's exported JWK. */\nfunction privateJwkOf(exported: JsonWebKey): PrivateJwk {\n const { x, d } = exported;\n if (!coordinate(x) || !coordinate(d)) {\n throw new TypeError(\"generated key could not be exported\");\n }\n return { kty: \"OKP\", crv: \"Ed25519\", x, d };\n}\n\n/** An expiry as the RFC 3339 instant the contract carries. */\nfunction instant(value: Date | string | undefined): string | undefined {\n if (value === undefined) return undefined;\n const time =\n value instanceof Date\n ? value.getTime()\n : typeof value === \"string\"\n ? Date.parse(value)\n : Number.NaN;\n if (Number.isNaN(time)) {\n throw new TypeError(\"expiresAt must be a valid instant\");\n }\n return new Date(time).toISOString();\n}\n\n/** The public view of a served access key record, judged as it is read. */\nfunction keyOf(record: AccessKeyRecord): AccessKey {\n if (\n typeof (record as unknown) !== \"object\" ||\n (record as unknown) === null ||\n typeof record.id !== \"string\" ||\n typeof record.name !== \"string\" ||\n typeof record.keyThumbprint !== \"string\"\n ) {\n throw new TransportError(\n \"invalid_response\",\n \"access key response carries no key record\",\n );\n }\n const optional = (key: keyof AccessKeyRecord) => {\n const value = record[key];\n return typeof value === \"string\" && value !== \"\" ? { [key]: value } : {};\n };\n return Object.freeze({\n id: record.id,\n name: record.name,\n ...optional(\"description\"),\n keyThumbprint: record.keyThumbprint,\n ...optional(\"expiresAt\"),\n ...optional(\"createdAt\"),\n ...optional(\"lastUsedAt\"),\n ...optional(\"revokedAt\"),\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { scalar, type Shape } from \"../internal/strictdecode.js\";\n\n/**\n * A span of time as a manifest states it, held to nanosecond precision:\n * whole `seconds` plus `nanoseconds` in the range −999 999 999 to\n * 999 999 999, both carrying the same sign. It is the value form of the Go\n * duration string a manifest carries, `15m` or `2h`, which\n * {@link parseDuration} reads and {@link formatDuration} writes; the wire\n * never carries it as a number.\n *\n * A duration whose two parts are both zero is unset, which validators treat\n * as missing where a duration is required.\n */\nexport interface Duration {\n readonly seconds: number;\n readonly nanoseconds: number;\n}\n\nconst NANOSECONDS_PER_SECOND = 1_000_000_000n;\nconst MAX_INT64 = (1n << 63n) - 1n;\n\n/** The units Go duration syntax accepts, each in nanoseconds. */\nconst UNITS: ReadonlyMap<string, bigint> = new Map([\n [\"ns\", 1n],\n [\"us\", 1_000n],\n [\"µs\", 1_000n],\n [\"μs\", 1_000n],\n [\"ms\", 1_000_000n],\n [\"s\", NANOSECONDS_PER_SECOND],\n [\"m\", 60n * NANOSECONDS_PER_SECOND],\n [\"h\", 3600n * NANOSECONDS_PER_SECOND],\n]);\n\n/**\n * Parses a Go duration string: a possibly signed sequence of decimal\n * numbers, each with an optional fraction and a unit suffix, such as `15m`,\n * `2h`, `1h30m`, or `1.5s`. The units are `ns`, `us` (or `µs`), `ms`, `s`,\n * `m`, and `h`; `0` alone is accepted without a unit. Throws a `TypeError`\n * for any other syntax, a missing or unknown unit, and a value that would\n * overflow a signed 64-bit nanosecond count.\n */\nexport function parseDuration(text: string): Duration {\n let rest = text;\n let negative = false;\n if (rest.startsWith(\"-\") || rest.startsWith(\"+\")) {\n negative = rest.startsWith(\"-\");\n rest = rest.slice(1);\n }\n if (rest === \"0\") return { seconds: 0, nanoseconds: 0 };\n if (rest === \"\") throw invalidDuration(text, undefined);\n\n let total = 0n;\n while (rest !== \"\") {\n const first = rest[0] ?? \"\";\n if (first !== \".\" && !isDigit(first))\n throw invalidDuration(text, undefined);\n\n const wholeDigits = leadingDigits(rest);\n rest = rest.slice(wholeDigits.length);\n const whole = wholeDigits === \"\" ? 0n : BigInt(wholeDigits);\n if (whole > 1n << 63n) throw invalidDuration(text, undefined);\n\n let fraction = 0n;\n let scale = 1;\n let fractionDigits = \"\";\n if (rest.startsWith(\".\")) {\n rest = rest.slice(1);\n fractionDigits = leadingDigits(rest);\n rest = rest.slice(fractionDigits.length);\n [fraction, scale] = leadingFraction(fractionDigits);\n }\n if (wholeDigits === \"\" && fractionDigits === \"\") {\n throw invalidDuration(text, undefined);\n }\n\n let unitLength = 0;\n while (unitLength < rest.length) {\n const character = rest[unitLength] ?? \"\";\n if (character === \".\" || isDigit(character)) break;\n unitLength += 1;\n }\n if (unitLength === 0) throw invalidDuration(text, \"missing unit\");\n const unitToken = rest.slice(0, unitLength);\n rest = rest.slice(unitLength);\n const unit = UNITS.get(unitToken);\n if (unit === undefined) {\n throw invalidDuration(text, `unknown unit ${JSON.stringify(unitToken)}`);\n }\n\n if (whole > (1n << 63n) / unit) throw invalidDuration(text, undefined);\n let value = whole * unit;\n if (fraction > 0n) {\n value += BigInt(Math.trunc(Number(fraction) * (Number(unit) / scale)));\n if (value > 1n << 63n) throw invalidDuration(text, undefined);\n }\n total += value;\n if (total > 1n << 63n) throw invalidDuration(text, undefined);\n }\n\n if (negative) return fromNanoseconds(-total);\n if (total > MAX_INT64) throw invalidDuration(text, undefined);\n return fromNanoseconds(total);\n}\n\nfunction leadingDigits(text: string): string {\n let length = 0;\n while (length < text.length && isDigit(text[length] ?? \"\")) length += 1;\n return text.slice(0, length);\n}\n\n/**\n * Reads the digits after a decimal point as a numerator and the power of ten\n * that scales it. Digits beyond what a 64-bit value holds are consumed but\n * do not change the result, as in Go's parser.\n */\nfunction leadingFraction(digits: string): [bigint, number] {\n let numerator = 0n;\n let scale = 1;\n let overflow = false;\n for (const digit of digits) {\n if (overflow) continue;\n if (numerator > MAX_INT64 / 10n) {\n overflow = true;\n continue;\n }\n const next = numerator * 10n + BigInt(digit);\n if (next > 1n << 63n) {\n overflow = true;\n continue;\n }\n numerator = next;\n scale *= 10;\n }\n return [numerator, scale];\n}\n\nfunction isDigit(character: string): boolean {\n return character >= \"0\" && character <= \"9\";\n}\n\nfunction invalidDuration(text: string, detail: string | undefined): TypeError {\n const quoted = JSON.stringify(text);\n return new TypeError(\n detail === undefined\n ? `invalid duration ${quoted}`\n : `invalid duration ${quoted}: ${detail}`,\n );\n}\n\nfunction fromNanoseconds(total: bigint): Duration {\n return {\n seconds: Number(total / NANOSECONDS_PER_SECOND),\n nanoseconds: Number(total % NANOSECONDS_PER_SECOND),\n };\n}\n\nfunction toNanoseconds(duration: Duration): bigint {\n return (\n BigInt(duration.seconds) * NANOSECONDS_PER_SECOND +\n BigInt(duration.nanoseconds)\n );\n}\n\n/**\n * Renders the duration in compact Go syntax: hours, minutes, and seconds\n * with trailing zero components trimmed, so two hours render as `2h` and\n * ninety minutes as `1h30m`; a duration under one second renders in the\n * largest of `ms`, `µs`, and `ns` that expresses it, with a fraction where\n * needed. Zero renders as `0s`. The result always re-parses through\n * {@link parseDuration} to the same value.\n */\nexport function formatDuration(duration: Duration): string {\n let out = goDurationString(toNanoseconds(duration));\n if (out.endsWith(\"m0s\")) out = `${out.slice(0, -3)}m`;\n if (out.endsWith(\"h0m\")) out = `${out.slice(0, -3)}h`;\n if (out === \"\" || out === \"-\") return \"0s\";\n return out;\n}\n\n/** Go's `time.Duration.String`, over a nanosecond count. */\nfunction goDurationString(total: bigint): string {\n const negative = total < 0n;\n let u = negative ? -total : total;\n let out: string;\n if (u < NANOSECONDS_PER_SECOND) {\n if (u === 0n) return \"0s\";\n let precision: number;\n let suffix: string;\n if (u < 1_000n) {\n precision = 0;\n suffix = \"ns\";\n } else if (u < 1_000_000n) {\n precision = 3;\n suffix = \"µs\";\n } else {\n precision = 6;\n suffix = \"ms\";\n }\n const [fraction, remaining] = formatFraction(u, precision);\n out = `${String(remaining)}${fraction}${suffix}`;\n } else {\n const [fraction, seconds] = formatFraction(u, 9);\n out = `${String(seconds % 60n)}${fraction}s`;\n u = seconds / 60n;\n if (u > 0n) {\n out = `${String(u % 60n)}m${out}`;\n u /= 60n;\n if (u > 0n) out = `${String(u)}h${out}`;\n }\n }\n return negative ? `-${out}` : out;\n}\n\n/**\n * Splits `value` into its fraction over `10^precision`, rendered with the\n * decimal point and trailing zeros omitted, and the whole part that remains.\n */\nfunction formatFraction(value: bigint, precision: number): [string, bigint] {\n let digits = \"\";\n let remaining = value;\n let print = false;\n for (let i = 0; i < precision; i += 1) {\n const digit = remaining % 10n;\n print = print || digit !== 0n;\n if (print) digits = `${String(digit)}${digits}`;\n remaining /= 10n;\n }\n return [print ? `.${digits}` : \"\", remaining];\n}\n\n/**\n * The duration in milliseconds, fractional when it holds sub-millisecond\n * precision.\n */\nexport function durationMilliseconds(duration: Duration): number {\n return duration.seconds * 1000 + duration.nanoseconds / 1_000_000;\n}\n\n/**\n * A duration of `milliseconds`, which must be a finite number of whole\n * nanoseconds; throws a `TypeError` otherwise.\n */\nexport function durationFromMilliseconds(milliseconds: number): Duration {\n const nanoseconds = milliseconds * 1_000_000;\n if (!Number.isFinite(nanoseconds) || !Number.isSafeInteger(nanoseconds)) {\n throw new TypeError(\n `invalid duration of ${String(milliseconds)} milliseconds: must be a whole number of nanoseconds`,\n );\n }\n return fromNanoseconds(BigInt(nanoseconds));\n}\n\n/**\n * The wire shape of a duration: the compact Go duration string. A number\n * is refused, as the reference contract refuses it, because a bare `30` names no unit.\n */\nexport const durationShape: Shape<Duration> = scalar<Duration>({\n decode: parseDuration,\n encode: formatDuration,\n zero: () => ({ seconds: 0, nanoseconds: 0 }),\n isZero: isZeroDuration,\n});\n\n/** Whether the duration is unset or explicitly zero. */\nexport function isZeroDuration(duration: Duration): boolean {\n return duration.seconds === 0 && duration.nanoseconds === 0;\n}\n\n/**\n * Orders two durations. Returns -1 when `left` is the shorter, 0 when the\n * two are equal, and 1 when `left` is the longer.\n */\nexport function compareDuration(left: Duration, right: Duration): -1 | 0 | 1 {\n const a = toNanoseconds(left);\n const b = toNanoseconds(right);\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport {\n always,\n boolean,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport {\n parseJournalEntryId,\n type JournalEntryId,\n} from \"../resource/uuid-id.js\";\n\n/** Live save progress or a retained outcome; unknown tokens are carried on read. */\nexport type ComputerCellSaveState =\n | \"pending\"\n | \"retrying\"\n | \"saved\"\n | \"unchanged\"\n | \"failed\"\n | \"off\"\n | \"forked\"\n | (string & Record<never, never>);\n/** Judges membership in this SDK's save-state vocabulary. */\nexport function validateComputerCellSaveState(\n state: ComputerCellSaveState,\n): void {\n switch (state) {\n case \"pending\":\n case \"retrying\":\n case \"saved\":\n case \"unchanged\":\n case \"failed\":\n case \"off\":\n case \"forked\":\n return;\n case \"\":\n throw new TypeError(\"cell save state is required\");\n default:\n throw new TypeError(`unknown cell save state ${JSON.stringify(state)}`);\n }\n}\n/**\n * Reports one save. `version` and `entry` are historical facts, not\n * ownership; `entryDeleted` reports that the covering entry no longer\n * exists although the cell was kept.\n */\nexport interface ComputerCellSave {\n readonly state: ComputerCellSaveState;\n readonly version?: Integer;\n readonly entry?: JournalEntryId;\n readonly entryDeleted?: boolean;\n readonly reason?: string;\n /** Seconds spent failing; zero remains a reported observation. */\n readonly failingSeconds?: Integer;\n /** The reported failing budget in seconds; zero remains explicit. */\n readonly failingBudgetSeconds?: Integer;\n}\n/** The canonical wire shape of a Cell save observation. */\nexport const computerCellSaveShape: Shape<ComputerCellSave> =\n object<ComputerCellSave>({\n state: always(string<ComputerCellSaveState>()),\n version: pointer(integer({ unsigned: false, bits: 64 })),\n entry: omitEmpty(string<JournalEntryId>()),\n entryDeleted: omitEmpty(boolean()),\n reason: omitEmpty(string()),\n failingSeconds: pointer(integer({ unsigned: false, bits: 64 })),\n failingBudgetSeconds: pointer(integer({ unsigned: false, bits: 64 })),\n });\n/** Checks state-selected identities and nonnegative count arithmetic. */\nexport function validateComputerCellSave(save: ComputerCellSave): void {\n validateComputerCellSaveState(save.state);\n for (const count of [\n save.version,\n save.failingSeconds,\n save.failingBudgetSeconds,\n ])\n if (count !== undefined && count < 0)\n throw new TypeError(\"save counts must be non-negative\");\n if (save.state === \"saved\" || save.state === \"unchanged\") {\n if (save.version === undefined)\n throw new TypeError(\"saved or unchanged requires version\");\n parseJournalEntryId(save.entry ?? \"\");\n } else if (\n save.version !== undefined ||\n (save.entry ?? \"\") !== \"\" ||\n save.entryDeleted\n )\n throw new TypeError(\"save version and entry require saved or unchanged\");\n if (save.state === \"failed\" && (save.reason ?? \"\") === \"\")\n throw new TypeError(\"failed save requires reason\");\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/** The fewest characters a notebook name may hold. */\nexport const MIN_COMPUTER_NOTEBOOK_NAME_BYTES = 3;\n\n/** The most characters a notebook name may hold. */\nexport const MAX_COMPUTER_NOTEBOOK_NAME_BYTES = 63;\n\n/**\n * Judges a notebook name: {@link MIN_COMPUTER_NOTEBOOK_NAME_BYTES} to\n * {@link MAX_COMPUTER_NOTEBOOK_NAME_BYTES} lowercase ASCII letters, digits,\n * or `-`, starting with a letter, the rule a Computer's name follows. A\n * notebook's name is unique within its Computer. Throws a `TypeError`.\n */\nexport function validateComputerNotebookName(name: string): void {\n if (name === \"\") throw new TypeError(\"notebook name is required\");\n if (name.length < MIN_COMPUTER_NOTEBOOK_NAME_BYTES) {\n throw new TypeError(\n `notebook name must be at least ${String(MIN_COMPUTER_NOTEBOOK_NAME_BYTES)} characters`,\n );\n }\n if (\n new TextEncoder().encode(name).byteLength > MAX_COMPUTER_NOTEBOOK_NAME_BYTES\n ) {\n throw new TypeError(\n `notebook name must not exceed ${String(MAX_COMPUTER_NOTEBOOK_NAME_BYTES)} characters`,\n );\n }\n for (let index = 0; index < name.length; index++) {\n const c = name.charCodeAt(index);\n if (c >= 0x61 && c <= 0x7a) continue;\n if ((c >= 0x30 && c <= 0x39) || c === 0x2d) {\n if (index === 0) {\n throw new TypeError(\"notebook name must start with a lowercase letter\");\n }\n continue;\n }\n throw new TypeError(\n \"notebook name must contain only lowercase letters, digits, or '-'\",\n );\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport type { Shape } from \"../internal/strictdecode.js\";\nimport {\n always,\n integer,\n object,\n omitEmpty,\n string,\n} from \"../internal/strictdecode.js\";\nimport {\n parseComputerSessionId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\n\n/**\n * What a Computer session stream runs, on the Computer's own endpoint:\n * `shell` an interactive shell, `exec` one command, `cell` a notebook cell,\n * `reattach` a session resumed after its stream was lost, `records` a\n * notebook's cell records read from the Computer's files, `files` listings\n * of the Computer's live folders, watched for changes, `ssh` one SSH\n * connection. A `files` session starts no process, saves nothing, never\n * wakes the Computer and never keeps it awake: a Computer that is not awake\n * refuses it with `COMPUTER_NOT_AWAKE`. An `ssh` session's stream carries\n * raw SSH bytes after its `opened` frame, and its SSH server, in the\n * Computer, starts the shells, commands and file transfers the connection's\n * channels ask for; an open SSH connection keeps the Computer awake as an\n * open terminal does, and it cannot be reattached. The union is open;\n * {@link validateComputerSessionMode} judges membership.\n */\nexport type ComputerSessionMode =\n | \"shell\"\n | \"exec\"\n | \"cell\"\n | \"reattach\"\n | \"records\"\n | \"files\"\n | \"ssh\"\n | (string & Record<never, never>);\n\n/** Judges that the mode is one this SDK names. Throws a `TypeError`. */\nexport function validateComputerSessionMode(mode: ComputerSessionMode): void {\n switch (mode) {\n case \"shell\":\n case \"exec\":\n case \"cell\":\n case \"reattach\":\n case \"records\":\n case \"files\":\n case \"ssh\":\n return;\n case \"\":\n throw new TypeError(\"mode is required\");\n default:\n throw new TypeError(\"unsupported mode\");\n }\n}\n\n/**\n * The endpoint arm of a Computer session create: the mode the grant admits,\n * and for a reattach the session it resumes. The command never travels\n * here; the client sends it in the session stream.\n */\nexport interface ComputerSessionEndpointRequest {\n readonly mode: ComputerSessionMode;\n /** The session a reattach resumes; only a reattach names one. */\n readonly session?: ComputerSessionId;\n}\n\nexport const computerSessionEndpointRequestShape: Shape<ComputerSessionEndpointRequest> =\n object<ComputerSessionEndpointRequest>({\n mode: always(string<ComputerSessionMode>()),\n session: omitEmpty(string<ComputerSessionId>()),\n });\n\n/**\n * Judges the endpoint arm: a mode this SDK names, and a session exactly\n * when the mode is `reattach`. Throws a `TypeError`.\n */\nexport function validateComputerSessionEndpointRequest(\n request: ComputerSessionEndpointRequest,\n): void {\n validateComputerSessionMode(request.mode);\n const session = request.session ?? \"\";\n if ((request.mode === \"reattach\") !== (session !== \"\")) {\n throw new TypeError(\n \"endpoint.session names the session a reattach resumes, and only a reattach names one\",\n );\n }\n if (session !== \"\") parseComputerSessionId(session);\n}\n\n/** Where an endpoint session's grant is installed: one sandbox on one machine. */\nexport interface ComputerSessionPlacement {\n /** The machine, as its identity names it. */\n readonly node: string;\n /** The host on the machine that holds the Computer's sandbox. */\n readonly hostPod: string;\n /** The sandbox's sequence on its host. */\n readonly sequence: Integer;\n}\n\nconst placementShape: Shape<ComputerSessionPlacement> =\n object<ComputerSessionPlacement>({\n node: always(string()),\n hostPod: always(string()),\n sequence: always(integer({ unsigned: false, bits: 64 })),\n });\n\n/**\n * An endpoint session's place, in its status from the moment it is ready:\n * the request ID its stream names, the mode, the Activation epoch and\n * runtime instance its grant names, and the sandbox it runs in. A client\n * sends the session's stream to the Computer's endpoint there, and checks\n * that the endpoint's certificate names this epoch.\n */\nexport interface ComputerSessionEndpoint {\n readonly requestId: string;\n readonly mode: ComputerSessionMode;\n readonly epoch: Integer;\n readonly runtimeInstance: string;\n readonly placement: ComputerSessionPlacement;\n}\n\nexport const computerSessionEndpointShape: Shape<ComputerSessionEndpoint> =\n object<ComputerSessionEndpoint>({\n requestId: always(string()),\n mode: always(string<ComputerSessionMode>()),\n epoch: always(integer({ unsigned: false, bits: 64 })),\n runtimeInstance: always(string()),\n placement: always(placementShape),\n });\n\n/**\n * Judges an endpoint session's place: a request ID, a mode this SDK names,\n * an epoch of at least 1, a runtime instance, and a placement naming its\n * machine, host and a sequence of at least 1. Throws a `TypeError`.\n */\nexport function validateComputerSessionEndpoint(\n endpoint: ComputerSessionEndpoint,\n): void {\n if (endpoint.requestId === \"\") {\n throw new TypeError(\"endpoint.requestId is required\");\n }\n validateComputerSessionMode(endpoint.mode);\n if (Number(endpoint.epoch) < 1) {\n throw new TypeError(\"endpoint.epoch must be at least 1\");\n }\n if (endpoint.runtimeInstance === \"\") {\n throw new TypeError(\"endpoint.runtimeInstance is required\");\n }\n if (endpoint.placement.node === \"\" || endpoint.placement.hostPod === \"\") {\n throw new TypeError(\"endpoint.placement names its node and host pod\");\n }\n if (Number(endpoint.placement.sequence) < 1) {\n throw new TypeError(\"endpoint.placement.sequence must be at least 1\");\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { validateShellPath } from \"../resource/computer-execution-settings.js\";\nimport {\n always,\n object,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { errorMessage } from \"../resource/validation.js\";\n\n/**\n * The session operation vocabulary of the session contract. A Computer\n * session is always `shell`, which runs an interactive shell or a command\n * with an explicit shell executable; the contract's other operations are\n * not offered for Computers. The union is open.\n */\nexport type WorkloadSessionOperation =\n \"exec\" | \"shell\" | \"logs\" | \"files\" | (string & Record<never, never>);\n\n/** Judges that the operation is one of the fixed set. Throws a `TypeError`. */\nexport function validateWorkloadSessionOperation(\n operation: WorkloadSessionOperation,\n): void {\n switch (operation) {\n case \"exec\":\n case \"shell\":\n case \"logs\":\n case \"files\":\n return;\n case \"\":\n throw new TypeError(\"operation is required\");\n default:\n throw new TypeError(\"unsupported operation\");\n }\n}\n\n/**\n * How a session's client attaches. A Computer session attaches with\n * `endpoint`: to the Computer's own session endpoint, over the client's\n * end-to-end encrypted Computer connection, and no other attachment is\n * offered for Computers. The union is open.\n */\nexport type WorkloadSessionAttachmentKind =\n \"endpoint\" | (string & Record<never, never>);\n\n/**\n * A shell request selects the exact shell executable. A command runs with\n * the same executable and `-c`.\n */\nexport interface WorkloadSessionShellRequest {\n readonly executable: string;\n}\n\n/** The wire shape of a shell arm. */\nexport const shellRequestShape: Shape<WorkloadSessionShellRequest> =\n object<WorkloadSessionShellRequest>({\n executable: always(string()),\n });\n\n/**\n * Judges a shell executable path as `validateShellPath` does, naming the\n * field `shell.executable`. Throws a `TypeError`.\n */\nexport function validateShellExecutable(executable: string): void {\n try {\n validateShellPath(executable);\n } catch (cause) {\n throw new TypeError(`shell.executable ${errorMessage(cause)}`, { cause });\n }\n}\n\n/** The terminal types a terminal profile may name. */\nconst TERMINAL_TYPES: ReadonlySet<string> = new Set([\n \"ansi\",\n \"linux\",\n \"screen\",\n \"screen-256color\",\n \"vt100\",\n \"xterm\",\n \"xterm-256color\",\n]);\n\n/**\n * The allowlisted terminal properties a session applies to its process.\n * There is no arbitrary environment: only these fixed properties cross the\n * session boundary. Dimensions are counts; `undefined` and zero state none.\n */\nexport interface WorkloadSessionTerminalProfile {\n readonly stdin?: boolean;\n /** One of `ansi`, `linux`, `screen`, `screen-256color`, `vt100`, `xterm` or `xterm-256color`. */\n readonly type: string;\n readonly rows?: number;\n readonly columns?: number;\n readonly pixelWidth?: number;\n readonly pixelHeight?: number;\n /**\n * `C`, `POSIX` or `C.UTF-8`, or 2 to 24 characters: two letters, then\n * letters, digits, `_`, `-` or `.`. `undefined` or empty states none.\n */\n readonly locale?: string;\n}\n\n/**\n * Judges a terminal profile: a type on the allowlist, non-negative rows and\n * columns stated together, non-negative pixel dimensions stated together\n * and only with character dimensions, and a well-formed locale. Throws a\n * `TypeError`.\n */\nexport function validateWorkloadSessionTerminalProfile(\n profile: WorkloadSessionTerminalProfile,\n): void {\n if (profile.type === \"\") throw new TypeError(\"terminal.type is required\");\n if (!TERMINAL_TYPES.has(profile.type)) {\n throw new TypeError(\"unsupported terminal.type\");\n }\n const rows = profile.rows ?? 0;\n const columns = profile.columns ?? 0;\n const pixelWidth = profile.pixelWidth ?? 0;\n const pixelHeight = profile.pixelHeight ?? 0;\n if (rows < 0 || columns < 0) {\n throw new TypeError(\"terminal rows and columns must be non-negative\");\n }\n if ((rows === 0) !== (columns === 0)) {\n throw new TypeError(\"terminal rows and columns must be provided together\");\n }\n if (pixelWidth < 0 || pixelHeight < 0) {\n throw new TypeError(\"terminal pixel dimensions must be non-negative\");\n }\n if ((pixelWidth === 0) !== (pixelHeight === 0)) {\n throw new TypeError(\"terminal pixel dimensions must be provided together\");\n }\n if (pixelWidth > 0 && rows === 0) {\n throw new TypeError(\n \"terminal character dimensions are required with pixel dimensions\",\n );\n }\n const locale = profile.locale ?? \"\";\n if (locale === \"\" || [\"C\", \"POSIX\", \"C.UTF-8\"].includes(locale)) return;\n if (!/^[A-Za-z]{2}[A-Za-z0-9_.-]{0,22}$/u.test(locale)) {\n throw new TypeError(\"terminal.locale is invalid\");\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { integer, explicitPointer } from \"../internal/strictdecode.js\";\nimport type { JournalEntryId } from \"../resource/uuid-id.js\";\nimport {\n always,\n decodeValue,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport type { ConditionReasonClass } from \"../resource/condition.js\";\nimport type { JsonObject } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n parseComputerId,\n parseComputerSessionId,\n parseJournalEntryId,\n type ComputerId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n computerCellSaveShape,\n validateComputerCellSave,\n type ComputerCellSave,\n} from \"./computer-cell-save.js\";\nimport { validateComputerNotebookName } from \"./computer-notebook-name.js\";\nimport {\n computerSessionEndpointRequestShape,\n computerSessionEndpointShape,\n validateComputerSessionEndpoint,\n validateComputerSessionEndpointRequest,\n} from \"./computer-session-endpoint.js\";\nimport type {\n ComputerSessionEndpoint,\n ComputerSessionEndpointRequest,\n} from \"./computer-session-endpoint.js\";\nimport {\n shellRequestShape,\n validateShellExecutable,\n validateWorkloadSessionOperation,\n type WorkloadSessionAttachmentKind,\n type WorkloadSessionOperation,\n type WorkloadSessionShellRequest,\n} from \"./workload-session.js\";\n\n/** The most characters a Computer session `idempotencyKey` may hold. */\nexport const MAX_COMPUTER_SESSION_IDEMPOTENCY_KEY_BYTES = 64;\n\n/**\n * How long a Computer session lives past its last successful renewal, or\n * past becoming ready before its first, in milliseconds: three minutes. A\n * session whose renewals stop ends about this long after the last one, with\n * reason `Expired`. See {@link ComputerSession}.\n */\nexport const COMPUTER_SESSION_LEASE_MS = 180_000;\n\n/**\n * How often a client renews a session it keeps, in milliseconds: one\n * minute. Three renewals fall within one {@link COMPUTER_SESSION_LEASE_MS},\n * so a session outlives one or two renewals lost in transit.\n */\nexport const COMPUTER_SESSION_RENEW_INTERVAL_MS = 60_000;\n\n/**\n * Creates one session in a Computer, run on the Computer's own session\n * endpoint. The create records the session's grant; the client opens the\n * session's stream on the endpoint, naming the create's `idempotencyKey` as\n * the stream's request ID, and the endpoint runs the session once its grant\n * is installed. A dormant Computer is woken to serve a session, except a\n * files stream, and the session counts toward the Computer's idle timeout\n * from its creation until it ends.\n *\n * Creating a session records it and answers at once with the\n * {@link ComputerSession}: `ready` when the Computer was awake or woke\n * quickly, and otherwise `pending` while the Computer wakes. Either answer\n * carries `status.endpoint` once the session is bound to the Activation\n * that will serve it, and the endpoint holds a stream until its grant is\n * installed, so a client opens the stream at once rather than waiting for\n * the session to be ready. No request is held open while the Computer\n * wakes.\n *\n * Every Computer session is operation `shell` with attachment `endpoint`,\n * and the route addresses the Computer, so there is no target or container\n * to name; any other operation or attachment is refused. `endpoint` states\n * the session's mode: an interactive `shell`, one command (`exec`), one\n * notebook `cell`, the resumption of a session whose stream was lost\n * (`reattach`), a read of a notebook's cell `records`, a listing of the\n * Computer's live `files`, or one SSH connection (`ssh`). A command, a\n * cell's script, and every byte of input travel only in the session's\n * stream, never in the request.\n *\n * An `ssh` session states no shell, no notebook and no session to resume;\n * its SSH connection's channels choose what runs. It cannot be reattached:\n * a reattach that names an `ssh` session is refused as an invalid request.\n *\n * ## Private sessions and notebooks\n *\n * A session that names no `notebook` is private: the platform keeps no\n * record of the command it runs, its input, its output, or its exit status.\n * Files the command changes persist through the Computer's saves.\n *\n * A cell and a records stream name a `notebook`, and no other mode does. A\n * cell is recorded as one cell of that notebook: its script, its output, its\n * exit status, and the file version saved after it. It runs with no\n * standard input and no terminal, so a notebook cell is always a single\n * command, never an interactive shell. A records stream reads the\n * notebook's cell records, their output included, from the Computer itself.\n * The notebook must exist in the Computer; a session naming one that does\n * not is refused with HTTP 404 and `NOTEBOOK_NOT_FOUND`. A\n * notebook runs one cell at a time: a cell created while another cell of\n * the same notebook runs waits in phase `pending` with reason\n * `NotebookBusy` until that cell ends.\n *\n * Logs and Files sessions, the exec operation, and every attachment\n * other than `endpoint` are not offered for Computers; a platform refuses\n * them with {@link ERROR_CODE_OPERATION_UNSUPPORTED} and\n * {@link ERROR_CODE_ATTACHMENT_UNSUPPORTED}.\n *\n * ## Retrying a create\n *\n * `idempotencyKey` is required: it is the request ID the session's stream\n * names, and it makes the create safe to retry.\n *\n * Two requests are the same request when every field other than the key is\n * equal: the operation, the shell, the attachment, the endpoint arm, the\n * notebook, and the client, where a request that states no client is the\n * same as one that states `unknown`.\n *\n * A key deduplicates within a window that opens with the first request\n * carrying it. Within the window, the same request under the same key\n * returns the session the first request created, with the same ID, in\n * whatever phase it has reached, and the command is never run a second\n * time; a different request under the same key is refused with HTTP 409 and\n * {@link ERROR_CODE_IDEMPOTENCY_KEY_MISMATCH}. A session that failed or was\n * cancelled is returned as it ended, so a request that should run after one\n * uses a new key. The window closes ten minutes after the session ends,\n * fails, or is cancelled. A retry never extends it, and neither does a\n * renewal. Once it closes, the key is free: the same request creates a new\n * session.\n */\nexport interface CreateComputerSessionRequest {\n /** Process-start version floor; absent is unstated and zero explicitly requires genesis. */\n readonly atLeastVersion?: Integer;\n readonly operation: WorkloadSessionOperation;\n /**\n * The shell the session runs, an executable of the Computer's image. A\n * session that names none runs, in mode `shell`, the Computer's default\n * shell (`ComputerExecutionSettings.shell`), or, when that states none,\n * `/bin/bash` when the image holds it and `/bin/sh` otherwise; a command\n * runs with `/bin/sh -c`. An interactive session whose shell the image\n * does not hold ends before the shell starts: the endpoint answers its\n * stream with the error `shell_not_found`, and nothing is written to its\n * terminal. `undefined` names none, and none is written.\n */\n readonly shell?: WorkloadSessionShellRequest;\n /** Always `endpoint`. */\n readonly attachment: WorkloadSessionAttachmentKind;\n /**\n * The session's endpoint arm: the mode its grant admits and, for a\n * reattach, the session it resumes. The command never travels here; the\n * client sends it in the session stream.\n */\n readonly endpoint?: ComputerSessionEndpointRequest;\n /**\n * The notebook of the Computer that a cell records into or a records\n * stream reads, as {@link validateComputerNotebookName} describes.\n * `undefined` or empty makes the session private: nothing it runs is\n * recorded, and none is written.\n */\n readonly notebook?: string;\n /**\n * 1 to {@link MAX_COMPUTER_SESSION_IDEMPOTENCY_KEY_BYTES} ASCII letters,\n * digits, `.`, `_`, or `-`: the request ID the session's stream names.\n * Required; a served spec without one reads as empty, which\n * {@link validateCreateComputerSessionRequest} refuses.\n */\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. A notebook cell records it, as\n * `unknown` when it is absent; it is informative and never authorizes\n * anything. `undefined` or empty states no client, and none is written.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/**\n * The kind of client that created a Computer session. It is informative:\n * the platform records what the request states and never authorizes or\n * routes on it.\n *\n * - `cli`: the `idyl` command-line client.\n * - `console`: the web console.\n * - `sdk`: a program through an IDYL SDK.\n * - `unknown`: a request that did not state its client.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerSessionClient}\n * judges membership.\n */\nexport type ComputerSessionClient =\n \"cli\" | \"console\" | \"sdk\" | \"unknown\" | (string & Record<never, never>);\n\n/**\n * Judges that the client is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateComputerSessionClient(\n client: ComputerSessionClient,\n): void {\n switch (client) {\n case \"cli\":\n case \"console\":\n case \"sdk\":\n case \"unknown\":\n return;\n case \"\":\n throw new TypeError(\"computer session client is required\");\n default:\n throw new TypeError(\n `unknown computer session client ${JSON.stringify(client)}`,\n );\n }\n}\n\n/**\n * Judges a client a request states, named `client` in a refusal: absent or\n * empty states none and passes, any other value must be one this SDK names.\n * Throws a `TypeError`.\n */\nexport function validateStatedClient(\n client: ComputerSessionClient | undefined,\n): void {\n const stated = client ?? \"\";\n if (stated === \"\") return;\n prefixed(\"client\", () => {\n validateComputerSessionClient(stated);\n });\n}\n\n/**\n * The wire shape of a create request: `operation` and `attachment` always\n * written, the shell and endpoint arms only when present, and `notebook`,\n * `idempotencyKey`, and `client` only when not empty.\n */\nexport const createComputerSessionRequestShape: Shape<CreateComputerSessionRequest> =\n object<CreateComputerSessionRequest>({\n atLeastVersion: explicitPointer(integer({ unsigned: false, bits: 64 })),\n operation: always(string<WorkloadSessionOperation>()),\n shell: pointer(shellRequestShape),\n attachment: always(string<WorkloadSessionAttachmentKind>()),\n endpoint: pointer(computerSessionEndpointRequestShape),\n notebook: omitEmpty(string()),\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n });\n\n/**\n * Judges the one offered operation and attachment pair, `shell` with\n * `endpoint`, the endpoint arm, a notebook exactly for a cell or a records\n * stream, the idempotency key's presence and form, and, when one is\n * stated, a client this SDK names. A refusal of the key names the rule and\n * never repeats the key. Throws a `TypeError`.\n */\nexport function validateCreateComputerSessionRequest(\n request: CreateComputerSessionRequest,\n): void {\n if (request.atLeastVersion !== undefined && request.atLeastVersion < 0)\n throw new TypeError(\"atLeastVersion must be non-negative\");\n validateWorkloadSessionOperation(request.operation);\n if (request.operation !== \"shell\") {\n throw new TypeError(\n `operation ${JSON.stringify(request.operation)} is not offered for Computer sessions`,\n );\n }\n if (request.shell !== undefined) {\n validateShellExecutable(request.shell.executable);\n }\n if (request.attachment === \"\") {\n throw new TypeError(\"attachment is required\");\n }\n if (request.attachment !== \"endpoint\") {\n throw new TypeError(\n `attachment ${JSON.stringify(request.attachment)} is not offered for Computer sessions`,\n );\n }\n validateEndpointAttachment(request);\n}\n\n/**\n * Judges a create of attachment `endpoint`: the endpoint arm, no shell for\n * an ssh session, a notebook exactly for a cell or a records stream, and\n * the idempotency key the session's stream names.\n */\nfunction validateEndpointAttachment(\n request: CreateComputerSessionRequest,\n): void {\n const endpoint = request.endpoint;\n if (endpoint === undefined) {\n throw new TypeError(\"an endpoint attachment requires the endpoint arm\");\n }\n prefixed(\"endpoint\", () => {\n validateComputerSessionEndpointRequest(endpoint);\n });\n if (endpoint.mode === \"ssh\" && request.shell !== undefined) {\n throw new TypeError(\n \"an ssh session states no shell: its channels choose what runs\",\n );\n }\n const notebookMode = endpoint.mode === \"cell\" || endpoint.mode === \"records\";\n const notebook = request.notebook ?? \"\";\n if (notebookMode !== (notebook !== \"\")) {\n throw new TypeError(\n \"a cell or a records stream names its notebook, and only those do\",\n );\n }\n if (notebook !== \"\") validateComputerNotebookName(notebook);\n if ((request.idempotencyKey ?? \"\") === \"\") {\n throw new TypeError(\n \"an endpoint attachment requires the idempotency key its stream names\",\n );\n }\n validateIdempotencyKey(request.idempotencyKey ?? \"\");\n validateStatedClient(request.client);\n}\n\nfunction validateIdempotencyKey(key: string): void {\n if (key === \"\") return;\n if (\n new TextEncoder().encode(key).byteLength >\n MAX_COMPUTER_SESSION_IDEMPOTENCY_KEY_BYTES\n ) {\n throw new TypeError(\n `idempotencyKey must not exceed ${String(MAX_COMPUTER_SESSION_IDEMPOTENCY_KEY_BYTES)} characters`,\n );\n }\n if (!/^[A-Za-z0-9._-]+$/u.test(key)) {\n throw new TypeError(\n \"idempotencyKey must contain only ASCII letters, digits, '.', '_', or '-'\",\n );\n }\n}\n\n/** Renders a create request as the document the route carries. */\nexport function encodeCreateComputerSessionRequest(\n request: CreateComputerSessionRequest,\n): JsonObject {\n createComputerSessionRequestShape.unknownFields(request, \"\");\n const value = createComputerSessionRequestShape.encode(request);\n decodeValue(value, createComputerSessionRequestShape, \"strict\");\n return value as JsonObject;\n}\n\n/**\n * Where a Computer session is in its life. A session is created `pending`,\n * becomes `ready` once it can be attached, `attached` once its process has\n * started, and `ended` once that process is over. It may instead `fail`\n * before it is ready, or be `cancelled` before it is attached. `ended`,\n * `failed`, and `cancelled` are final;\n * {@link isComputerSessionPhaseTerminal} reports them.\n *\n * - `pending`: the platform has recorded the session and is preparing it:\n * its Computer is waking, or capacity is being found for it. It counts\n * against the session limits while it waits.\n * - `ready`: the session can be attached: its grant is installed on the\n * endpoint its status carries.\n * - `attached`: the session's process has started. A session attaches once;\n * a second attachment is refused with\n * {@link ERROR_CODE_SESSION_ALREADY_ATTACHED}.\n * - `ended`: the session's process is over.\n * - `failed`: the session could not be made ready, and its reason says why.\n * - `cancelled`: the session was cancelled before it was attached: by its\n * creator, when it states no reason, or by the platform with\n * `ATTACH_TIMEOUT` when it was not attached in time.\n *\n * Every phase that is not final has a deadline the platform enforces, so a\n * session nobody attaches releases what it holds without the client's\n * help: a pending session that is not ready by\n * {@link ComputerSessionStatus.readyBy} fails with `WAKE_TIMEOUT`, a ready\n * session that is not attached by {@link ComputerSessionStatus.attachBy}\n * is cancelled with `ATTACH_TIMEOUT`, and an attached session that is not\n * renewed ends with `Expired` at {@link ComputerSessionStatus.expiresAt}.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerSessionPhase} judges\n * membership, and a caller treats an unknown phase as one it cannot attach\n * in.\n */\nexport type ComputerSessionPhase =\n | \"pending\"\n | \"ready\"\n | \"attached\"\n | \"ended\"\n | \"failed\"\n | \"cancelled\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the phase is one this SDK names. The empty string is reported\n * as missing: a served session always carries a phase. Throws a\n * `TypeError`.\n */\nexport function validateComputerSessionPhase(\n phase: ComputerSessionPhase,\n): void {\n switch (phase) {\n case \"pending\":\n case \"ready\":\n case \"attached\":\n case \"ended\":\n case \"failed\":\n case \"cancelled\":\n return;\n case \"\":\n throw new TypeError(\"computer session phase is required\");\n default:\n throw new TypeError(\n `unknown computer session phase ${JSON.stringify(phase)}`,\n );\n }\n}\n\n/**\n * Whether the phase is final: `ended`, `failed`, or `cancelled`. It is false\n * for a phase this SDK does not name.\n */\nexport function isComputerSessionPhaseTerminal(\n phase: ComputerSessionPhase,\n): boolean {\n return phase === \"ended\" || phase === \"failed\" || phase === \"cancelled\";\n}\n\n/**\n * Why a Computer session is in its phase, from a closed set of stable\n * codes a caller may branch on. A pending session carries the step it waits\n * on; a failed, cancelled, or ended session carries why it stopped. A\n * failure reason is spelled as the error code that refuses a create for the\n * same cause, so a client reads one code whether the platform refused the\n * session at once or failed it later.\n *\n * - `Waking`: a pending session whose Computer is starting.\n * - `WaitingForCapacity`: a pending session whose Computer waits for\n * capacity in its Subnet to run on.\n * - `NotebookBusy`: a pending notebook session that waits for the cell\n * before it in the same notebook to end.\n * - `PROFILE_FITS_NO_HOST`: a failed session whose Computer fits no host\n * eligible to run it. The session fails as soon as that is\n * known rather than waiting for its deadline.\n * - `WAKE_TIMEOUT`: a failed session whose Computer was not ready by\n * {@link ComputerSessionStatus.readyBy}. A new session may succeed.\n * - `EXECUTION_NOT_ENABLED`: a failed session whose Computer's Namespace\n * stopped having execution turned on in the Subnet while the session was\n * pending.\n * - `OUT_OF_USAGE`: a failed session whose Computer's Account had used its\n * month's allowance and its extra usage, as `ERROR_CODE_OUT_OF_USAGE`\n * describes. A new session can succeed once the Account buys extra\n * usage, upgrades, or starts its next period.\n * - `ISOLATION_CLASS_NOT_ADMITTED`: a failed session whose Computer runs in\n * an isolation class its Subnet no longer admits, so the Computer could\n * not start. Its files stay reachable and its settings writable. A new\n * session can succeed once the Computer's isolation class is one the\n * Subnet admits.\n * - `SIZE_NOT_IN_PLAN`: a failed session whose Computer runs at a size\n * larger than its Account's plan includes, as\n * `ERROR_CODE_SIZE_NOT_IN_PLAN` describes. A new session can succeed once\n * the Computer is resized to a size the plan includes, or the plan is\n * upgraded.\n * - `VCPU_LIMIT_REACHED`: a failed session whose wake would take the vCPU of\n * its Account's awake Computers past what its plan allows at once, as\n * `ERROR_CODE_VCPU_LIMIT_REACHED` describes. A new session can succeed once\n * another Computer is asleep, or the plan is upgraded.\n * - `mode-unavailable`: a failed session whose mode the endpoint serving\n * its Computer cannot serve. A pending or ready session fails with it\n * before anything runs. A new session may succeed, as on the Computer's\n * next Activation.\n * - `ATTACH_TIMEOUT`: a session the platform cancelled because it was not\n * attached by {@link ComputerSessionStatus.attachBy}.\n * - `Exited`: an ended session whose process ended.\n * - `Expired`: an ended session that reached\n * {@link ComputerSessionStatus.expiresAt}: its renewals stopped, or it\n * reached the maximum duration a Subnet or Account policy sets. Its\n * process was ended then. Idleness is never a reason: a session waiting\n * for input is kept for as long as it is renewed.\n * - `Released`: an ended session whose Computer's execution was released\n * or superseded while the session ran; its process was ended with it.\n * - `Revoked`: an ended session whose grant, the authorization it runs\n * under, was revoked, or whose renewal was refused because its creator no\n * longer holds the permission the session needs. Its process was ended at\n * once.\n * - `PutToSleep`: an ended session whose Computer was put to sleep on\n * request: its files were saved, then its process was ended and the\n * Computer's execution released.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerSessionReason}\n * judges membership, and {@link computerSessionReasonClass} says how to\n * read a reason without knowing it.\n */\nexport type ComputerSessionReason =\n | \"Waking\"\n | \"WaitingForCapacity\"\n | \"NotebookBusy\"\n | \"WaitingForDisk\"\n | \"NoViewCapableNode\"\n | \"WaitingForVersion\"\n | \"PROFILE_FITS_NO_HOST\"\n | \"WAKE_TIMEOUT\"\n | \"EXECUTION_NOT_ENABLED\"\n | \"OUT_OF_USAGE\"\n | \"ISOLATION_CLASS_NOT_ADMITTED\"\n | \"SIZE_NOT_IN_PLAN\"\n | \"VCPU_LIMIT_REACHED\"\n | \"mode-unavailable\"\n | \"ATTACH_TIMEOUT\"\n | \"Exited\"\n | \"Expired\"\n | \"Released\"\n | \"Revoked\"\n | \"PutToSleep\"\n | (string & Record<never, never>);\n\n/**\n * Every reason and its class, in the classes conditions use, as one table\n * so the set and its classification cannot disagree. For a reason that\n * stopped a session, the class says what a new session would meet:\n * `transient` when a new session may succeed as things stand, `blocked`\n * when something has to change first, and `settled` when the session simply\n * ran its course.\n */\nconst REASON_CLASSES: ReadonlyMap<string, ConditionReasonClass> = new Map([\n [\"Waking\", \"progressing\"],\n [\"WaitingForCapacity\", \"transient\"],\n [\"NotebookBusy\", \"progressing\"],\n [\"WaitingForDisk\", \"transient\"],\n [\"NoViewCapableNode\", \"transient\"],\n [\"WaitingForVersion\", \"progressing\"],\n [\"PROFILE_FITS_NO_HOST\", \"blocked\"],\n [\"WAKE_TIMEOUT\", \"transient\"],\n [\"EXECUTION_NOT_ENABLED\", \"blocked\"],\n [\"OUT_OF_USAGE\", \"blocked\"],\n [\"ISOLATION_CLASS_NOT_ADMITTED\", \"blocked\"],\n [\"SIZE_NOT_IN_PLAN\", \"blocked\"],\n [\"VCPU_LIMIT_REACHED\", \"blocked\"],\n [\"mode-unavailable\", \"transient\"],\n [\"ATTACH_TIMEOUT\", \"transient\"],\n [\"Exited\", \"settled\"],\n [\"Expired\", \"settled\"],\n [\"Released\", \"settled\"],\n [\"Revoked\", \"settled\"],\n [\"PutToSleep\", \"settled\"],\n]);\n\n/** The closed set of Computer session reasons, in a stable order. */\nexport function allComputerSessionReasons(): readonly ComputerSessionReason[] {\n return [...REASON_CLASSES.keys()];\n}\n\n/**\n * How a caller should read the reason: `progressing` or `transient` while a\n * session waits, and, for a session that stopped, `transient`, `blocked`,\n * or `settled` as {@link ComputerSessionReason} describes. `undefined` for\n * a reason outside the closed set, which a caller must treat as something\n * it does not understand rather than as anything in particular.\n */\nexport function computerSessionReasonClass(\n reason: ComputerSessionReason,\n): ConditionReasonClass | undefined {\n return REASON_CLASSES.get(reason);\n}\n\n/**\n * Judges that the reason is one this SDK names. The empty string is valid:\n * it is a session that states no reason. Throws a `TypeError`.\n */\nexport function validateComputerSessionReason(\n reason: ComputerSessionReason,\n): void {\n if (reason === \"\" || REASON_CLASSES.has(reason)) return;\n throw new TypeError(\n `unknown computer session reason ${JSON.stringify(reason)}`,\n );\n}\n\n/**\n * Where a Computer session is, and where its grant is installed once it is\n * bound. Instants are RFC 3339 strings.\n */\nexport interface ComputerSessionStatus {\n /**\n * The notebook cell that records a notebook session; process and save\n * facts live there. A private session has none.\n */\n readonly cell?: JournalEntryId;\n /**\n * The save that covers the session's end: the files its command left\n * behind. It appears once the session ends and progresses to a final\n * state: `saved` with the version it published, `unchanged` when nothing\n * changed, `failed` with its reason, or `off` when the Computer does not\n * save automatically. `entry` names the Computer history entry that owns\n * a published version. A client waits for the save by reading the session\n * until the state is final. `undefined` until the session ends.\n */\n readonly save?: ComputerCellSave;\n /** Where the session is in its life. Always written. */\n readonly phase: ComputerSessionPhase;\n /**\n * Why the session is in its phase. A failed or ended session always\n * states one. A pending session states one when the platform names the\n * step it waits on. A session the platform cancelled states\n * `ATTACH_TIMEOUT`, and one its creator cancelled states none. A ready or\n * attached session states none. `undefined` states no reason.\n */\n readonly reason?: ComputerSessionReason;\n /**\n * The instant by which the session must be ready: its creation plus the\n * Subnet's wake timeout. A session still pending then fails with\n * `WAKE_TIMEOUT`. Always written.\n */\n readonly readyBy: string;\n /**\n * The instant by which a ready session must be attached. A session not\n * attached by then is cancelled with `ATTACH_TIMEOUT`. It is written from\n * the moment the session is ready; `undefined` while pending.\n */\n readonly attachBy?: string;\n /**\n * The session's current lease deadline: its last successful renewal, or\n * the moment it became ready before its first, plus\n * {@link COMPUTER_SESSION_LEASE_MS}, bounded by the maximum session\n * duration a Subnet or Account policy sets, when one does. Without such a\n * policy nothing else bounds it. Each renewal moves it forward. A session\n * not renewed by then ends with `Expired`. It is written from the moment\n * the session is ready; `undefined` while pending.\n */\n readonly expiresAt?: string;\n /**\n * Where the session's grant is installed. It is present from the moment\n * the session is bound to the Activation that will serve it, which can be\n * while the session is still pending: the Computer is placed and\n * running, and its endpoint may still be starting. Once present it\n * does not change. A client may connect to it at once; the endpoint holds\n * a session's stream until the session's grant is installed. `undefined`\n * for a pending session not yet bound, and for a session that failed\n * before it was bound.\n */\n readonly endpoint?: ComputerSessionEndpoint;\n}\n\nconst computerSessionStatusShape: Shape<ComputerSessionStatus> =\n object<ComputerSessionStatus>({\n cell: omitEmpty(string<JournalEntryId>()),\n save: pointer(computerCellSaveShape),\n phase: always(string<ComputerSessionPhase>()),\n reason: omitEmpty(string<ComputerSessionReason>()),\n readyBy: always(timestampShape),\n attachBy: omitZero(timestampShape),\n expiresAt: omitZero(timestampShape),\n endpoint: pointer(computerSessionEndpointShape),\n });\n\n/**\n * One session of a Computer as the platform records it, from its creation\n * until it is deleted. The Computer's API serves it: creating a session\n * returns it at once, already ready when the Computer was awake or woke\n * within the create's short wait and otherwise pending; a read returns it as\n * it now is; and a cancel ends it. `id` names it on those routes and is\n * fixed at creation. `computer` is the ID of the Computer the session\n * belongs to, whether it was created by the Computer's name or by its ID; a\n * Computer's ID never changes, so a client that reads, renews and cancels\n * the session through the by-ID session routes of `computer` keeps reaching\n * it when the Computer is renamed while the session runs. `spec` is the\n * request that created it, as {@link CreateComputerSessionRequest}\n * describes. `status` reports where it is.\n *\n * A session is readable only by the identity that created it. A final\n * session is deleted once the window of its idempotency key closes, and a\n * read of it then reports HTTP 404.\n *\n * A session is a lease its client keeps by renewing it every\n * {@link COMPUTER_SESSION_RENEW_INTERVAL_MS} from the moment it is ready.\n * Each renewal checks the caller's permission on the Computer again,\n * exactly as creating the session does, and moves `status.expiresAt` to\n * {@link COMPUTER_SESSION_LEASE_MS} from then. A session ends at the\n * earliest of:\n *\n * - its renewals stopping: it ends about {@link COMPUTER_SESSION_LEASE_MS}\n * after the last one, with reason `Expired`;\n * - a refused renewal: it ends at once, with reason `Revoked`;\n * - its process ending, with reason `Exited`;\n * - the Computer's execution being released or superseded, with reason\n * `Released`; and\n * - a maximum duration, only where a Subnet or Account policy sets one,\n * with reason `Expired`.\n *\n * An idle session is not a lapse: a shell waiting for input is kept while\n * it is renewed. Renewing a session that is already final changes nothing\n * and is refused with HTTP 409 and {@link ERROR_CODE_SESSION_FINAL}.\n *\n * {@link decodeComputerSession} reads one leniently: a field, phase, or\n * reason newer than this SDK is carried rather than refused, the spec\n * included, and {@link validateComputerSession} judges the session against\n * this SDK's contract.\n */\nexport interface ComputerSession {\n readonly id: ComputerSessionId;\n readonly computer: ComputerId;\n readonly spec: CreateComputerSessionRequest;\n readonly status: ComputerSessionStatus;\n}\n\nconst computerSessionShape: Shape<ComputerSession> = object<ComputerSession>({\n id: always(string<ComputerSessionId>()),\n computer: always(string<ComputerId>()),\n spec: always(createComputerSessionRequestShape),\n status: always(computerSessionStatusShape),\n});\n\n/**\n * Reads a Computer session the platform served, leniently. `document` is\n * JSON text or a value already parsed from JSON; a string is parsed once,\n * as a response is. Unknown fields, phases, and reasons are carried, not\n * refused, and the spec is read the same way, although the create route\n * binds a request under its exact schema.\n */\nexport function decodeComputerSession(document: unknown): ComputerSession {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, computerSessionShape, \"lenient\");\n}\n\n/**\n * Renders a Computer session as the document the platform emits: `id`,\n * `computer`, `spec`, and the status's `phase` and `readyBy` always written, and every\n * other status field only when present.\n */\nexport function encodeComputerSession(session: ComputerSession): JsonObject {\n return computerSessionShape.encode(session) as JsonObject;\n}\n\n/**\n * Judges the session against this SDK's contract: a canonical ID and\n * Computer, a valid spec, a phase and reason this SDK names, a ready\n * deadline, and the fields each phase carries. A failed or ended session\n * states a reason. A ready, attached, or ended session carries its attach\n * deadline, its expiry, and its endpoint; a pending session carries neither\n * deadline nor expiry, though it may carry its endpoint once it is bound.\n * Throws a `TypeError`.\n */\nexport function validateComputerSession(session: ComputerSession): void {\n parseComputerSessionId(session.id);\n prefixed(\"computer\", () => {\n parseComputerId(session.computer);\n });\n prefixed(\"spec\", () => {\n validateCreateComputerSessionRequest(session.spec);\n });\n validateStatus(session.status);\n}\n\nfunction validateStatus(status: ComputerSessionStatus): void {\n const cell = status.cell ?? \"\";\n if (cell !== \"\") parseJournalEntryId(cell);\n if (status.save !== undefined) validateComputerCellSave(status.save);\n validateComputerSessionPhase(status.phase);\n const reason = status.reason ?? \"\";\n validateComputerSessionReason(reason);\n if (isZeroInstant(status.readyBy)) {\n throw new TypeError(\"status.readyBy is required\");\n }\n if (\n (status.phase === \"failed\" || status.phase === \"ended\") &&\n reason === \"\"\n ) {\n throw new TypeError(`status.reason is required in phase ${status.phase}`);\n }\n const hasAttachBy = !isZeroInstant(status.attachBy ?? \"\");\n const hasExpiresAt = !isZeroInstant(status.expiresAt ?? \"\");\n switch (status.phase) {\n case \"pending\":\n if (hasAttachBy || hasExpiresAt) {\n throw new TypeError(\n \"status.attachBy and status.expiresAt must be absent in phase pending\",\n );\n }\n break;\n case \"ready\":\n case \"attached\":\n case \"ended\":\n if (!hasAttachBy) {\n throw new TypeError(\n `status.attachBy is required in phase ${status.phase}`,\n );\n }\n if (!hasExpiresAt) {\n throw new TypeError(\n `status.expiresAt is required in phase ${status.phase}`,\n );\n }\n if (status.endpoint === undefined) {\n throw new TypeError(\n `status.endpoint is required in phase ${status.phase}`,\n );\n }\n break;\n default:\n break;\n }\n if (status.endpoint !== undefined) {\n validateComputerSessionEndpoint(status.endpoint);\n }\n}\n\n/** The instant the reference contract writes for a time it holds no value for. */\nconst ZERO_INSTANT_MS = Date.parse(\"0001-01-01T00:00:00Z\");\n\n/**\n * Whether an instant states no time: absent, or the zero instant the reference contract\n * writes for a time it holds no value for.\n */\nexport function isZeroInstant(instant: string): boolean {\n return instant === \"\" || Date.parse(instant) === ZERO_INSTANT_MS;\n}\n\n/**\n * Refuses a session because execution is not turned on for the Computer's\n * Namespace where the Computer lives. A session can be created once it is. A pending session that meets the same cause\n * fails with it as its reason.\n */\nexport const ERROR_CODE_EXECUTION_NOT_ENABLED = \"EXECUTION_NOT_ENABLED\";\n\n/** Refuses a session in a Computer that is terminating. */\nexport const ERROR_CODE_COMPUTER_TERMINATING = \"COMPUTER_TERMINATING\";\n\n/**\n * Names a session the capacity its Computer runs on can never serve,\n * because it fits no host eligible to provide it. The session\n * is refused, or failed with it as its reason, as soon as that is known,\n * rather than left waiting.\n */\nexport const ERROR_CODE_PROFILE_FITS_NO_HOST = \"PROFILE_FITS_NO_HOST\";\n\n/**\n * Names a session whose Computer was not ready by the session's\n * {@link ComputerSessionStatus.readyBy}; the session fails with it as its\n * reason. A new session may succeed. Under the same idempotency key the\n * create returns the failed session until the key's window closes, so a\n * retry that should run uses a new key.\n */\nexport const ERROR_CODE_WAKE_TIMEOUT = \"WAKE_TIMEOUT\";\n\n/**\n * Returned with HTTP 429 when a limit on concurrent sessions is reached. A\n * session can be created once one ends.\n */\nexport const ERROR_CODE_SESSION_BUDGET_EXCEEDED = \"SESSION_BUDGET_EXCEEDED\";\n\n/**\n * Refuses an attachment Computer sessions do not offer: any attachment\n * other than `endpoint`.\n */\nexport const ERROR_CODE_ATTACHMENT_UNSUPPORTED = \"ATTACHMENT_UNSUPPORTED\";\n\n/**\n * Refuses an operation Computer sessions do not offer, such as Logs and\n * Files.\n */\nexport const ERROR_CODE_OPERATION_UNSUPPORTED = \"OPERATION_UNSUPPORTED\";\n\n/**\n * Returned with HTTP 409 when a request reuses an idempotency key within\n * its window with a different request. See\n * {@link CreateComputerSessionRequest}.\n */\nexport const ERROR_CODE_IDEMPOTENCY_KEY_MISMATCH = \"IDEMPOTENCY_KEY_MISMATCH\";\n\n/**\n * Returned with HTTP 409 when a session that has already started its\n * process is attached again. A session runs its process once.\n */\nexport const ERROR_CODE_SESSION_ALREADY_ATTACHED = \"SESSION_ALREADY_ATTACHED\";\n\n/**\n * Returned with HTTP 409 when a session that is already ended, failed, or\n * cancelled is renewed. The renewal changes nothing; a read of the session\n * reports its phase and reason.\n */\nexport const ERROR_CODE_SESSION_FINAL = \"SESSION_FINAL\";\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * An Account pays for the Computers it runs through its billing: a plan,\n * which grants a monthly allowance of usage, and, on a paid plan, extra\n * usage bought on top of it. The Account's billing is one resource per\n * Account, `AccountBilling`, served by the global API. Changes that move\n * money are operation resources of their own: a plan change\n * (`BillingPlanChange`) and a purchase of extra usage (`BillingPurchase`).\n * Each create records the operation and answers within a short bounded\n * wait, already finished or still pending, and the caller reads it until it\n * is finished; no request is held open while Stripe takes a payment. Card\n * details, addresses, invoices and receipts are kept by Stripe and reached\n * through a portal session (`BillingPortalSession`); IDYL never receives\n * them.\n *\n * Billing is read when a client starts and in the background, never on a\n * Computer's wake, session or cell. A wake, a session or a resize that the\n * Account's billing refuses is refused by that call itself, with\n * `ERROR_CODE_OUT_OF_USAGE`, `ERROR_CODE_SIZE_NOT_IN_PLAN` or\n * `ERROR_CODE_VCPU_LIMIT_REACHED`, so nothing has to be checked first.\n *\n * Every amount of money is in US dollars, as a whole number of\n * micro-dollars (`MICROS_PER_DOLLAR` to the dollar), so amounts sum without\n * rounding. Amounts are never negative, and every amount field is always\n * written, since zero is a reading. Amounts are 64-bit integers on the wire: a value within\n * `Number.MAX_SAFE_INTEGER` reads as a number, a larger one as a bigint.\n */\nimport {\n validateComputerSize,\n type ComputerSize,\n} from \"../resource/computer-execution-settings.js\";\nimport {\n always,\n array,\n boolean,\n decodeValue,\n explicitPointer,\n integer,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { cpuQuantityShape, type CpuQuantity } from \"../resource/cpu.js\";\nimport { parseSubnetSlug } from \"../resource/id.js\";\nimport {\n memoryQuantityShape,\n type MemoryQuantity,\n} from \"../resource/memory.js\";\nimport {\n isZeroVolume,\n validateVolumeQuantity,\n volumeQuantityShape,\n type VolumeQuantity,\n} from \"../resource/volume.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport {\n compareDuration,\n durationShape,\n isZeroDuration,\n type Duration,\n} from \"../resource/duration.js\";\nimport type { Integer, JsonObject } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n parseBillingPlanChangeId,\n parseBillingPurchaseId,\n type BillingPlanChangeId,\n type BillingPurchaseId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n ERROR_CODE_ACTION_EXPIRED,\n ERROR_CODE_PAYMENT_DECLINED,\n ERROR_CODE_PAYMENT_DISPUTED,\n ERROR_CODE_PLAN_CHANGE_SUPERSEDED,\n ERROR_CODE_PLAN_CHANGE_UNAVAILABLE,\n} from \"./billing-errors.js\";\nimport { isZeroInstant } from \"./computer-session.js\";\nimport type { ListResponse } from \"./types.js\";\n\n/**\n * The number of micro-dollars in one US dollar: every billing amount is a\n * whole number of micro-dollars.\n */\nexport const MICROS_PER_DOLLAR = 1_000_000;\n\n/** The most bytes the `idempotencyKey` of a plan change or a purchase may take. */\nexport const MAX_BILLING_IDEMPOTENCY_KEY_BYTES = 64;\n\nconst MICROS_PER_DOLLAR_EXACT = BigInt(MICROS_PER_DOLLAR);\n\n/** The wire shape of every amount of money: a 64-bit integer of micro-dollars. */\nconst microsShape: Shape<Integer> = integer({ unsigned: false, bits: 64 });\n\nexport { validateComputerSize, type ComputerSize };\n\n/**\n * Identifies a plan. The plans an Account can be on are a catalog the\n * platform serves with every read of its billing\n * ({@link AccountBillingStatus.plans}), so a plan is an identifier rather\n * than a closed set. The tokens this SDK names are:\n *\n * - `trial`: the plan an Account starts on. It costs nothing, needs no\n * card and cannot be requested.\n * - `none`: no plan: an Account whose paid plan has ended. It costs nothing\n * and needs no card, and a plan change to it cancels a paid plan.\n * - `pro`: the first paid plan.\n * - `max`: the paid plan with five times Pro's allowance.\n * - `ultra`: the paid plan with 25 times Pro's allowance.\n */\nexport type BillingPlan =\n \"trial\" | \"none\" | \"pro\" | \"max\" | \"ultra\" | (string & Record<never, never>);\n\nconst BILLING_PLAN_FORM = /^[a-z][a-z0-9_]{0,62}$/u;\n\n/**\n * Judges that the plan is in the form every plan identifier takes: 1 to 63\n * lowercase letters, digits and underscores, beginning with a letter.\n * Whether the platform offers it is the platform's decision. Throws a\n * `TypeError`.\n */\nexport function validateBillingPlan(plan: BillingPlan): void {\n if (plan === \"\") throw new TypeError(\"billing plan is required\");\n if (!BILLING_PLAN_FORM.test(plan)) {\n throw new TypeError(\n `billing plan ${JSON.stringify(plan)} must be 1 to 63 lowercase letters, digits and underscores, beginning with a letter`,\n );\n }\n}\n\n/**\n * Whether auto-refill is on and how much each refill buys. A refill is an\n * extra usage purchase of kind `auto_refill`, made with the card the\n * Account pays with, at most one each time the balance reaches zero, and\n * never past the spend cap.\n */\nexport interface BillingAutoRefill {\n /** Whether auto-refill buys extra usage. Always written, `false` included. */\n readonly enabled: boolean;\n /**\n * What one refill buys: a positive whole number of dollars, in\n * micro-dollars. It is kept while auto-refill is off. Always written.\n */\n readonly amountMicros: Integer;\n}\n\n/** The wire shape of an auto-refill setting. */\nexport const billingAutoRefillShape: Shape<BillingAutoRefill> =\n object<BillingAutoRefill>({\n enabled: always(boolean()),\n amountMicros: always(microsShape),\n });\n\n/**\n * Judges the auto-refill: its amount is a positive whole number of dollars.\n * Throws a `TypeError`.\n */\nexport function validateBillingAutoRefill(autoRefill: BillingAutoRefill): void {\n validateDollarAmount(\"amountMicros\", autoRefill.amountMicros);\n}\n\n/** Refuses an amount that is not a positive whole number of dollars, which is how extra usage is sold. */\nfunction validateDollarAmount(field: string, micros: Integer): void {\n const exact = BigInt(micros);\n if (exact <= 0n || exact % MICROS_PER_DOLLAR_EXACT !== 0n) {\n throw new TypeError(`${field} must be a positive whole number of dollars`);\n }\n}\n\n/** Whether `micros` is below zero. */\nfunction isNegative(micros: Integer): boolean {\n return BigInt(micros) < 0n;\n}\n\n/** What an Account's owner sets for its extra usage. */\nexport interface AccountBillingSpec {\n /**\n * Buys extra usage when the Account's extra usage balance reaches zero.\n * It is off when an Account is created, with an amount of $20. The\n * platform turns it off on its own when a refill cannot be charged or a\n * payment is disputed, and says why in\n * {@link AccountBillingStatus.autoRefillStopped}. Always written.\n */\n readonly autoRefill: BillingAutoRefill;\n /**\n * The most the Account spends on extra usage in one period, counting\n * purchases paid and pending, whether the owner bought them or\n * auto-refill did; a purchase that would pass it is refused with\n * `ERROR_CODE_SPEND_CAP_REACHED`. `undefined` means no cap, which is how\n * an Account starts. Auto-refill can be on only while a cap is set\n * (`ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP`).\n */\n readonly spendCapMicros?: Integer;\n}\n\n/** The wire shape of an Account's billing settings. */\nexport const accountBillingSpecShape: Shape<AccountBillingSpec> =\n object<AccountBillingSpec>({\n autoRefill: always(billingAutoRefillShape),\n spendCapMicros: pointer(microsShape),\n });\n\n/**\n * Judges the spec: a valid auto-refill, a cap that is not negative, and a\n * cap set whenever auto-refill is on. Throws a `TypeError`.\n */\nexport function validateAccountBillingSpec(spec: AccountBillingSpec): void {\n prefixed(\"autoRefill\", () => {\n validateBillingAutoRefill(spec.autoRefill);\n });\n if (spec.spendCapMicros !== undefined && isNegative(spec.spendCapMicros)) {\n throw new TypeError(\"spendCapMicros must not be negative\");\n }\n if (spec.autoRefill.enabled && spec.spendCapMicros === undefined) {\n throw new TypeError(\n \"autoRefill can be enabled only with spendCapMicros set\",\n );\n }\n}\n\n/**\n * Whether an Account's Computers may wake.\n *\n * - `ok`: an Account whose Computers may wake: it has allowance or extra\n * usage left, or auto-refill can buy more.\n * - `out`: an Account that has used its month's allowance and its extra\n * usage, and that auto-refill cannot refill. Its wakes and session starts\n * are refused with `ERROR_CODE_OUT_OF_USAGE` and its awake Computers are\n * asked to sleep, their files kept. It is `ok` again after a purchase, an\n * upgrade or the start of its next period; its Computers are not woken by\n * that.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingStanding = \"ok\" | \"out\" | (string & Record<never, never>);\n\n/**\n * Judges that the standing is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateBillingStanding(standing: BillingStanding): void {\n switch (standing) {\n case \"ok\":\n case \"out\":\n return;\n case \"\":\n throw new TypeError(\"billing standing is required\");\n default:\n throw new TypeError(\n `unknown billing standing ${JSON.stringify(standing)}`,\n );\n }\n}\n\n/**\n * Whether a paid plan's latest renewal was paid.\n *\n * - `ok`: a renewal that was paid, or an Account on `trial` or `none`, whose periods need\n * no payment.\n * - `failed`: a renewal whose payment failed and is being retried by Stripe.\n * The period's allowance is granted only once it is paid. If the retries end\n * unpaid, the plan ends and the Account is on `none`.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingRenewalState =\n \"ok\" | \"failed\" | (string & Record<never, never>);\n\n/**\n * Judges that the state is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateBillingRenewalState(state: BillingRenewalState): void {\n switch (state) {\n case \"ok\":\n case \"failed\":\n return;\n case \"\":\n throw new TypeError(\"billing renewal state is required\");\n default:\n throw new TypeError(\n `unknown billing renewal state ${JSON.stringify(state)}`,\n );\n }\n}\n\n/**\n * Why the platform withheld the allowance of an Account's current period,\n * which is then zero.\n *\n * - `trial_one_per_person`: an unpaid allowance withheld because it is given\n * once per person: the verified sign-in email of the Account's owner\n * already holds it on another Account. The Account may still use a paid\n * plan, whose allowance is never withheld for this reason.\n * - `trials_closed`: an unpaid allowance withheld because IDYL offered no\n * trials when the Account was created. The Account may still use a paid\n * plan.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingAllowanceWithheld =\n \"trial_one_per_person\" | \"trials_closed\" | (string & Record<never, never>);\n\n/**\n * Judges that the reason is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateBillingAllowanceWithheld(\n reason: BillingAllowanceWithheld,\n): void {\n switch (reason) {\n case \"trial_one_per_person\":\n case \"trials_closed\":\n return;\n case \"\":\n throw new TypeError(\"billing allowance withheld reason is required\");\n default:\n throw new TypeError(\n `unknown billing allowance withheld reason ${JSON.stringify(reason)}`,\n );\n }\n}\n\n/**\n * Where an Account stands in its use of the platform. A client reads it to\n * tell an Account whose free usage has ended from a paying Account that has\n * used up its month, which a `standing` of `out` alone cannot.\n *\n * - `full`: an Account with nothing in its way but its usage: on a paid plan,\n * or on no plan with extra usage left to spend. A paid plan's month that is\n * used up reads `full`, with a `standing` of `out`.\n * - `trial`: an Account on its free trial, which ends at `periodEnd` or when\n * its allowance is used, whichever comes first.\n * - `ended`: an Account with no paid plan and nothing left to spend: its trial\n * ended or was withheld, or its paid plan ended and its extra usage is used.\n * - `deleting`: an Account whose retention has passed and whose files are being\n * deleted. The deletion cannot be stopped, and plan changes are refused until\n * it has finished. The Account then reads `ended`, with nothing stored, and\n * can choose a plan as usual.\n * Its standing is `out`, and no later period grants it anything. A paid plan\n * returns it to `full`.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingLifecycle =\n \"full\" | \"trial\" | \"ended\" | \"deleting\" | (string & Record<never, never>);\n\n/**\n * Judges that the lifecycle is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateBillingLifecycle(lifecycle: BillingLifecycle): void {\n switch (lifecycle) {\n case \"full\":\n case \"trial\":\n case \"ended\":\n case \"deleting\":\n return;\n case \"\":\n throw new TypeError(\"billing lifecycle is required\");\n default:\n throw new TypeError(\n `unknown billing lifecycle ${JSON.stringify(lifecycle)}`,\n );\n }\n}\n\n/**\n * What one awake hour of a size costs, before tax, and the size this rate\n * prices, stated as `ComputerSizeInfo` states it, so a reader of the Account's\n * billing needs no second request to show the size. `label`, `cpu`, `memory`,\n * `disk` and `default` are optional: a platform that leaves them out still\n * validates.\n */\nexport interface BillingSizeRate {\n /** The size. Always written. */\n readonly size: ComputerSize;\n /**\n * The price of one hour the Computer is awake at `size`, in\n * micro-dollars. A Computer is billed for the time it is awake at this\n * rate: half an hour costs half the rate. Zero is a rate. Always written.\n */\n readonly perHourMicros: Integer;\n /** The name a person reads for the size this rate prices, such as `Small`. */\n readonly label?: string;\n /** The CPU limit of a Computer of the size this rate prices. */\n readonly cpu?: CpuQuantity;\n /** The memory limit of a Computer of the size this rate prices. */\n readonly memory?: MemoryQuantity;\n /** The most a Computer of the size this rate prices can store. */\n readonly disk?: VolumeQuantity;\n /**\n * Whether the size this rate prices is the one a Computer that states no\n * size, CPU or memory runs at. `undefined` means it is not.\n */\n readonly default?: boolean;\n}\n\n/** The wire shape of the rate of one size. */\nexport const billingSizeRateShape: Shape<BillingSizeRate> =\n object<BillingSizeRate>({\n size: always(string()),\n perHourMicros: always(microsShape),\n label: omitEmpty(string()),\n cpu: omitZero(cpuQuantityShape),\n memory: omitZero(memoryQuantityShape),\n disk: omitZero(volumeQuantityShape),\n default: omitEmpty(boolean()),\n });\n\n/** The rates of one Subnet whose rate card differs from the platform's default. */\nexport interface BillingSubnetSizeRates {\n /**\n * The Subnet's canonical 12-digit slug, as a Computer names the Subnet it\n * lives in. Always written.\n */\n readonly subnet: string;\n /**\n * The Subnet's rate for each size, one entry per size, smallest first.\n * Always written, empty rather than omitted.\n */\n readonly sizeRates: readonly BillingSizeRate[];\n}\n\n/** The wire shape of one Subnet's rates. */\nexport const billingSubnetSizeRatesShape: Shape<BillingSubnetSizeRates> =\n object<BillingSubnetSizeRates>({\n subnet: always(string()),\n sizeRates: always(array(billingSizeRateShape)),\n });\n\n/**\n * Judges the Subnet's rates: a canonical slug, and rates as\n * {@link AccountBillingStatus.sizeRates} holds them. Throws a `TypeError`.\n */\nexport function validateBillingSubnetSizeRates(\n rates: BillingSubnetSizeRates,\n): void {\n prefixed(\"subnet\", () => {\n parseSubnetSlug(rates.subnet);\n });\n joined(\"sizeRates\", () => {\n validateSizeRates(rates.sizeRates);\n });\n}\n\n/**\n * Requires sizes in identifier form, each once, with rates that are not\n * negative. The platform states their order, smallest first. Its refusals begin\n * with the refused entry's index, for the caller to prefix with the field.\n */\nfunction validateSizeRates(rates: readonly BillingSizeRate[]): void {\n const seen = new Set<ComputerSize>();\n rates.forEach((rate, index) => {\n const at = `[${String(index)}]`;\n prefixed(`${at}: size`, () => {\n validateComputerSize(rate.size);\n });\n if (seen.has(rate.size)) {\n throw new TypeError(\n `${at}: size ${JSON.stringify(rate.size)} is listed twice`,\n );\n }\n seen.add(rate.size);\n if (isNegative(rate.perHourMicros)) {\n throw new TypeError(`${at}: perHourMicros must not be negative`);\n }\n });\n}\n\n/**\n * A change of plan that takes effect at the end of the current period: a\n * downgrade, or a cancellation, which is a change to `none`. When it takes\n * effect, the Account's awake Computers larger than `largestSize` are asked\n * to sleep, and each needs a size no larger than it, or an upgrade, before\n * it can wake again. A plan change to the plan in force undoes the pending\n * change.\n */\nexport interface BillingScheduledChange {\n /** The plan the Account changes to. Always written. */\n readonly plan: BillingPlan;\n /** When the change takes effect: the end of the current period. Always written. */\n readonly at: string;\n /** The largest size `plan` includes. Always written. */\n readonly largestSize: ComputerSize;\n}\n\n/** The wire shape of a scheduled change of plan. */\nexport const billingScheduledChangeShape: Shape<BillingScheduledChange> =\n object<BillingScheduledChange>({\n plan: always(string<BillingPlan>()),\n at: always(timestampShape),\n largestSize: always(string()),\n });\n\n/**\n * Judges the change: a plan in identifier form, an instant, and a size this\n * SDK names. Throws a `TypeError`.\n */\nexport function validateBillingScheduledChange(\n change: BillingScheduledChange,\n): void {\n prefixed(\"plan\", () => {\n validateBillingPlan(change.plan);\n });\n if (isZeroInstant(change.at)) throw new TypeError(\"at is required\");\n prefixed(\"largestSize\", () => {\n validateComputerSize(change.largestSize);\n });\n}\n\n/** Why and when the platform turned auto-refill off. */\nexport interface BillingAutoRefillStop {\n /**\n * `PAYMENT_DECLINED` when a refill could not be charged, or\n * `PAYMENT_DISPUTED` when a payment of the Account was disputed. Always\n * written.\n */\n readonly reason: string;\n /** When auto-refill was turned off. Always written. */\n readonly at: string;\n}\n\n/** The wire shape of an auto-refill stop. */\nexport const billingAutoRefillStopShape: Shape<BillingAutoRefillStop> =\n object<BillingAutoRefillStop>({\n reason: always(string()),\n at: always(timestampShape),\n });\n\n/**\n * Judges the stop: a reason this SDK names, and an instant. Throws a\n * `TypeError`.\n */\nexport function validateBillingAutoRefillStop(\n stop: BillingAutoRefillStop,\n): void {\n switch (stop.reason) {\n case ERROR_CODE_PAYMENT_DECLINED:\n case ERROR_CODE_PAYMENT_DISPUTED:\n break;\n case \"\":\n throw new TypeError(\"reason is required\");\n default:\n throw new TypeError(\n `unknown auto-refill stop reason ${JSON.stringify(stop.reason)}`,\n );\n }\n if (isZeroInstant(stop.at)) throw new TypeError(\"at is required\");\n}\n\n/** Names the smallest plan that includes a size. */\nexport interface BillingSizePlan {\n /** The size. Always written. */\n readonly size: ComputerSize;\n /** The smallest plan whose largest size is at least `size`. Always written. */\n readonly plan: BillingPlan;\n}\n\n/** The wire shape of a size and the smallest plan that includes it. */\nexport const billingSizePlanShape: Shape<BillingSizePlan> =\n object<BillingSizePlan>({\n size: always(string()),\n plan: always(string<BillingPlan>()),\n });\n\n/**\n * Judges the pair: a size and a plan in identifier form.\n * Throws a `TypeError`.\n */\nexport function validateBillingSizePlan(sizePlan: BillingSizePlan): void {\n prefixed(\"size\", () => {\n validateComputerSize(sizePlan.size);\n });\n prefixed(\"plan\", () => {\n validateBillingPlan(sizePlan.plan);\n });\n}\n\n/** A plan as it is offered. */\nexport interface BillingPlanOffer {\n /** Identifies the plan. Always written. */\n readonly plan: BillingPlan;\n /** The plan's name for display, such as `Max 5x`. Always written. */\n readonly name: string;\n /**\n * The plan's price for one month, before tax, which Stripe adds when it\n * charges, in micro-dollars. Zero for `trial` and `none`. Always written.\n */\n readonly priceMicros: Integer;\n /** The usage the plan grants each month, in micro-dollars. Always written. */\n readonly allowanceMicros: Integer;\n /** The largest size the plan includes. Always written. */\n readonly largestSize: ComputerSize;\n /**\n * The most data an Account on the plan stores across all its Computers,\n * saved history included, such as `400Gi`. A save or an upload that would\n * go past it fails with `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`. `undefined`\n * when the plan has no such limit.\n */\n readonly storedData?: VolumeQuantity;\n /**\n * The most vCPU an Account on the plan keeps awake at once, across all its\n * Computers. Asleep Computers count for nothing. A wake that would go past\n * it fails with `ERROR_CODE_VCPU_LIMIT_REACHED`. `undefined` when the plan\n * has no such limit.\n */\n readonly awakeVCPU?: Integer;\n /**\n * Whether an Account on the plan can buy extra usage and turn on\n * auto-refill. Always written.\n */\n readonly extraUsage: boolean;\n}\n\n/** The wire shape of a plan offer. */\nexport const billingPlanOfferShape: Shape<BillingPlanOffer> =\n object<BillingPlanOffer>({\n plan: always(string<BillingPlan>()),\n name: always(string()),\n priceMicros: always(microsShape),\n allowanceMicros: always(microsShape),\n largestSize: always(string()),\n storedData: omitZero(volumeQuantityShape),\n awakeVCPU: omitEmpty(integer({ unsigned: false, bits: 64 })),\n extraUsage: always(boolean()),\n });\n\n/**\n * Judges the offer: a plan in identifier form, a name, amounts and an awake\n * vCPU limit that are not negative, a size in identifier form, and a valid\n * stored-data limit when one is stated. Throws a `TypeError`.\n */\nexport function validateBillingPlanOffer(offer: BillingPlanOffer): void {\n prefixed(\"plan\", () => {\n validateBillingPlan(offer.plan);\n });\n if (offer.name === \"\") throw new TypeError(\"name is required\");\n if (isNegative(offer.priceMicros) || isNegative(offer.allowanceMicros)) {\n throw new TypeError(\"priceMicros and allowanceMicros must not be negative\");\n }\n if (offer.awakeVCPU !== undefined && isNegative(offer.awakeVCPU)) {\n throw new TypeError(\"awakeVCPU must not be negative\");\n }\n prefixed(\"largestSize\", () => {\n validateComputerSize(offer.largestSize);\n });\n validateStoredData(offer.storedData);\n}\n\n/**\n * Judges the terms on which an Account's files are kept: warnings only beside\n * a retention, each positive and shorter than it, longest first.\n */\nfunction validateFileRetention(\n retention: Duration | undefined,\n warnings: readonly Duration[] | undefined,\n): void {\n if (retention !== undefined && isBelowZero(retention)) {\n throw new TypeError(\"fileRetention must not be negative\");\n }\n if (warnings === undefined || warnings.length === 0) return;\n if (retention === undefined || isZeroDuration(retention)) {\n throw new TypeError(\"deletionWarnings need a fileRetention\");\n }\n let longest = retention;\n warnings.forEach((warning, index) => {\n if (\n isBelowZero(warning) ||\n isZeroDuration(warning) ||\n compareDuration(warning, longest) >= 0\n ) {\n throw new TypeError(\n `deletionWarnings[${String(index)}] must be positive and shorter than the one before it and fileRetention`,\n );\n }\n longest = warning;\n });\n}\n\n/** Whether the duration runs backwards. */\nfunction isBelowZero(duration: Duration): boolean {\n return compareDuration(duration, { seconds: 0, nanoseconds: 0 }) < 0;\n}\n\n/** Judges a stated limit on stored data: a valid quantity. */\nfunction validateStoredData(quantity: VolumeQuantity | undefined): void {\n if (quantity === undefined || isZeroVolume(quantity)) return;\n prefixed(\"storedData\", () => {\n validateVolumeQuantity(quantity);\n });\n}\n\n/**\n * An Account's billing as the platform reports it. Usage is counted as soon\n * as it is recorded, before it is settled, so the amounts are the ones the\n * Account's standing is judged on. Instants are RFC 3339 strings.\n */\nexport interface AccountBillingStatus {\n /** The plan in force. Always written. */\n readonly plan: BillingPlan;\n /**\n * The start of the current period, which is `[periodStart, periodEnd)`:\n * one month of the plan in force, or a trial's whole length. An upgrade\n * starts a new period at once. Always written.\n */\n readonly periodStart: string;\n /**\n * The end of the current period: when the allowance resets, a paid plan\n * renews and a trial ends. Always written.\n */\n readonly periodEnd: string;\n /**\n * The allowance granted for the current period: zero until a paid\n * period's renewal is paid, and zero when it was withheld\n * (`allowanceWithheld`). What is left of it when the period ends expires.\n * Always written.\n */\n readonly allowanceMicros: Integer;\n /**\n * Why the current period's allowance was withheld, when it was;\n * `undefined` otherwise. `allowanceMicros` is then zero.\n */\n readonly allowanceWithheld?: BillingAllowanceWithheld;\n /**\n * How much of `allowanceMicros` the period's usage has used, never more\n * than `allowanceMicros`. Usage beyond the allowance draws on the extra\n * usage balance. Always written.\n */\n readonly usedMicros: Integer;\n /**\n * The extra usage bought and not yet used. It never expires and is used\n * only once the allowance is used up. Always written.\n */\n readonly extraBalanceMicros: Integer;\n /**\n * The extra usage bought in the current period, purchases paid and\n * pending, which is what the spend cap counts. Always written.\n */\n readonly extraBoughtMicros: Integer;\n /** Whether the Account's Computers may wake. Always written. */\n readonly standing: BillingStanding;\n /** Where the Account stands in its use of the platform. Always written. */\n readonly lifecycle: BillingLifecycle;\n /** Whether the plan's latest renewal was paid. Always written. */\n readonly renewal: BillingRenewalState;\n /**\n * The largest size the plan in force includes. A wake or a resize of a\n * Computer to a larger size is refused with `ERROR_CODE_SIZE_NOT_IN_PLAN`.\n * Always written.\n */\n readonly largestSize: ComputerSize;\n /**\n * The most data the Account stores across all its Computers under the\n * plan in force, as {@link BillingPlanOffer.storedData} states it.\n * `undefined` when the plan has no such limit.\n */\n readonly storedData?: VolumeQuantity;\n /**\n * How long an Account keeps its files once it has no plan and nothing\n * left to spend, under the platform's default rate card in force now. The\n * files are deleted no earlier than that. An Account whose files are\n * already being kept this way keeps the terms it started with.\n * `undefined` when the rate card has no free trial.\n */\n readonly fileRetention?: Duration;\n /**\n * How long before its files are deleted each warning is sent to the\n * Account's owner, longest first, under the same rate card as\n * `fileRetention`. Each is shorter than `fileRetention`. `undefined` when\n * the rate card has no free trial.\n */\n readonly deletionWarnings?: readonly Duration[];\n /**\n * The plan the Account changes to at the end of the current period, when\n * a downgrade or a cancellation is scheduled; `undefined` when none is.\n */\n readonly scheduledChange?: BillingScheduledChange;\n /**\n * Why the platform turned auto-refill off on its own; `undefined` when it\n * did not. It is cleared when auto-refill is turned on again.\n */\n readonly autoRefillStopped?: BillingAutoRefillStop;\n /**\n * Whether Stripe holds invoices for the Account: it has paid at least\n * once. A portal session shows them. Always written.\n */\n readonly hasInvoices: boolean;\n /**\n * For each size some plan includes, the smallest plan that includes it,\n * smallest size first. Always written, empty rather than omitted.\n */\n readonly sizePlans: readonly BillingSizePlan[];\n /**\n * Every plan offered, cheapest first; it always lists the plan in force\n * and the plan of a scheduled change. Always written, empty rather than\n * omitted.\n */\n readonly plans: readonly BillingPlanOffer[];\n /**\n * What an awake hour of each size costs under the platform's default\n * rate card in force now: one entry per size, smallest first. A Computer\n * is charged its Subnet's rate, which is this one unless\n * `subnetSizeRates` names the Subnet. Always written, empty rather than\n * omitted.\n */\n readonly sizeRates: readonly BillingSizeRate[];\n /**\n * The Subnets the Account may use whose rate card in force now differs\n * from the default, each once, with its rates. A Subnet it does not list\n * charges `sizeRates`. Always written, empty rather than omitted, and\n * empty when every such Subnet charges the default.\n */\n readonly subnetSizeRates: readonly BillingSubnetSizeRates[];\n /**\n * The rate in force now for storing one GiB for one month, under the\n * platform's default rate card, before tax. Zero is a rate. Always written.\n */\n readonly storageMicrosPerGiBMonth: Integer;\n /**\n * The rate in force now for downloading one GiB, under the platform's default\n * rate card, before tax. Zero is a rate. Always written.\n */\n readonly downloadMicrosPerGiB: Integer;\n}\n\n/** The wire shape of an Account's billing status. */\nexport const accountBillingStatusShape: Shape<AccountBillingStatus> =\n object<AccountBillingStatus>({\n plan: always(string<BillingPlan>()),\n periodStart: always(timestampShape),\n periodEnd: always(timestampShape),\n allowanceMicros: always(microsShape),\n allowanceWithheld: omitEmpty(string<BillingAllowanceWithheld>()),\n usedMicros: always(microsShape),\n extraBalanceMicros: always(microsShape),\n extraBoughtMicros: always(microsShape),\n standing: always(string<BillingStanding>()),\n lifecycle: always(string<BillingLifecycle>()),\n renewal: always(string<BillingRenewalState>()),\n largestSize: always(string()),\n storedData: omitZero(volumeQuantityShape),\n fileRetention: omitZero(durationShape),\n deletionWarnings: omitEmpty(array(durationShape)),\n scheduledChange: pointer(billingScheduledChangeShape),\n autoRefillStopped: pointer(billingAutoRefillStopShape),\n hasInvoices: always(boolean()),\n sizePlans: always(array(billingSizePlanShape)),\n plans: always(array(billingPlanOfferShape)),\n sizeRates: always(array(billingSizeRateShape)),\n subnetSizeRates: always(array(billingSubnetSizeRatesShape)),\n storageMicrosPerGiBMonth: always(microsShape),\n downloadMicrosPerGiB: always(microsShape),\n });\n\n/**\n * Judges the status: a plan and sizes in identifier form; a standing, a\n * lifecycle and a renewal state this SDK names; a period whose end follows its\n * start; amounts and rates that are not negative, with no more used than\n * allowed; a withheld allowance with a\n * reason this SDK names and a zero amount; a valid stored-data limit when\n * one is stated; a valid scheduled change and auto-refill stop; sizes named\n * once each in `sizePlans`; plans listed once\n * each; the plan in force and the scheduled plan among `plans`; rates for\n * sizes in identifier form, each once, that are not negative; and Subnets named\n * by slug, each once. Throws a `TypeError`.\n */\nexport function validateAccountBillingStatus(\n status: AccountBillingStatus,\n): void {\n prefixed(\"plan\", () => {\n validateBillingPlan(status.plan);\n });\n if (\n isZeroInstant(status.periodStart) ||\n !(Date.parse(status.periodEnd) > Date.parse(status.periodStart))\n ) {\n throw new TypeError(\"periodEnd must follow periodStart\");\n }\n for (const [field, micros] of [\n [\"allowanceMicros\", status.allowanceMicros],\n [\"usedMicros\", status.usedMicros],\n [\"extraBalanceMicros\", status.extraBalanceMicros],\n [\"extraBoughtMicros\", status.extraBoughtMicros],\n [\"storageMicrosPerGiBMonth\", status.storageMicrosPerGiBMonth],\n [\"downloadMicrosPerGiB\", status.downloadMicrosPerGiB],\n ] as const) {\n if (isNegative(micros)) {\n throw new TypeError(`${field} must not be negative`);\n }\n }\n if (BigInt(status.usedMicros) > BigInt(status.allowanceMicros)) {\n throw new TypeError(\"usedMicros must not exceed allowanceMicros\");\n }\n const withheld = status.allowanceWithheld;\n if (withheld !== undefined) {\n prefixed(\"allowanceWithheld\", () => {\n validateBillingAllowanceWithheld(withheld);\n });\n if (BigInt(status.allowanceMicros) !== 0n) {\n throw new TypeError(\n \"allowanceMicros must be zero while allowanceWithheld is set\",\n );\n }\n }\n prefixed(\"standing\", () => {\n validateBillingStanding(status.standing);\n });\n prefixed(\"lifecycle\", () => {\n validateBillingLifecycle(status.lifecycle);\n });\n prefixed(\"renewal\", () => {\n validateBillingRenewalState(status.renewal);\n });\n prefixed(\"largestSize\", () => {\n validateComputerSize(status.largestSize);\n });\n validateStoredData(status.storedData);\n validateFileRetention(status.fileRetention, status.deletionWarnings);\n const scheduled = status.scheduledChange;\n if (scheduled !== undefined) {\n prefixed(\"scheduledChange\", () => {\n validateBillingScheduledChange(scheduled);\n });\n }\n const stopped = status.autoRefillStopped;\n if (stopped !== undefined) {\n prefixed(\"autoRefillStopped\", () => {\n validateBillingAutoRefillStop(stopped);\n });\n }\n const sizes = new Set<string>();\n status.sizePlans.forEach((sizePlan, index) => {\n const at = `sizePlans[${String(index)}]`;\n prefixed(at, () => {\n validateBillingSizePlan(sizePlan);\n });\n if (sizes.has(sizePlan.size)) {\n throw new TypeError(\n `${at}: size ${JSON.stringify(sizePlan.size)} is listed twice`,\n );\n }\n sizes.add(sizePlan.size);\n });\n const plans = new Set<string>();\n status.plans.forEach((offer, index) => {\n const at = `plans[${String(index)}]`;\n prefixed(at, () => {\n validateBillingPlanOffer(offer);\n });\n if (plans.has(offer.plan)) {\n throw new TypeError(\n `${at}: plan ${JSON.stringify(offer.plan)} is listed twice`,\n );\n }\n plans.add(offer.plan);\n });\n if (!plans.has(status.plan)) {\n throw new TypeError(\n `plans must list the plan in force, ${JSON.stringify(status.plan)}`,\n );\n }\n if (scheduled !== undefined && !plans.has(scheduled.plan)) {\n throw new TypeError(\n `plans must list the scheduled plan, ${JSON.stringify(scheduled.plan)}`,\n );\n }\n joined(\"sizeRates\", () => {\n validateSizeRates(status.sizeRates);\n });\n const subnets = new Set<string>();\n status.subnetSizeRates.forEach((rates, index) => {\n const at = `subnetSizeRates[${String(index)}]`;\n prefixed(at, () => {\n validateBillingSubnetSizeRates(rates);\n });\n if (subnets.has(rates.subnet)) {\n throw new TypeError(\n `${at}: subnet ${JSON.stringify(rates.subnet)} is listed twice`,\n );\n }\n subnets.add(rates.subnet);\n });\n}\n\n/**\n * An Account's billing: `spec` is what the Account's owner sets, and\n * `status` is what the platform reports. The global API serves one per\n * Account, at `/v1/accounts/{account}/billing`; it exists for every\n * Account, from sign-up onwards. The plan is changed through a\n * {@link BillingPlanChange} rather than through `spec`, because a change of\n * plan moves money.\n *\n * {@link decodeAccountBilling} reads one leniently: a field or value newer\n * than this SDK is carried rather than refused, and\n * {@link validateAccountBilling} judges the billing against this SDK's\n * contract.\n */\nexport interface AccountBilling {\n /** What the Account's owner sets. Always written. */\n readonly spec: AccountBillingSpec;\n /** What the platform reports. Always written. */\n readonly status: AccountBillingStatus;\n}\n\n/** The wire shape of an Account's billing. */\nexport const accountBillingShape: Shape<AccountBilling> =\n object<AccountBilling>({\n spec: always(accountBillingSpecShape),\n status: always(accountBillingStatusShape),\n });\n\n/**\n * Reads an Account's billing the platform served, leniently. `document` is\n * JSON text or a value already parsed from JSON; a string is parsed once,\n * as a response is. A field or token this SDK does not name is carried as\n * it arrived, and nothing is judged.\n */\nexport function decodeAccountBilling(document: unknown): AccountBilling {\n return decodeValue(parsed(document), accountBillingShape, \"lenient\");\n}\n\n/**\n * Renders an Account's billing as the document the platform emits: every\n * amount, flag and list always, the cap, the scheduled change and the\n * auto-refill stop only when present.\n */\nexport function encodeAccountBilling(billing: AccountBilling): JsonObject {\n return accountBillingShape.encode(billing) as JsonObject;\n}\n\n/**\n * Judges the billing against this SDK's contract: a valid spec and a valid\n * status. Throws a `TypeError`.\n */\nexport function validateAccountBilling(billing: AccountBilling): void {\n prefixed(\"spec\", () => {\n validateAccountBillingSpec(billing.spec);\n });\n prefixed(\"status\", () => {\n validateAccountBillingStatus(billing.status);\n });\n}\n\n/** Carries an Account's billing. */\nexport interface GetAccountBillingResponse {\n readonly billing: AccountBilling;\n}\n\n/** The wire shape of the billing read's response. */\nexport const getAccountBillingResponseShape: Shape<GetAccountBillingResponse> =\n object<GetAccountBillingResponse>({ billing: always(accountBillingShape) });\n\n/**\n * Changes an Account's billing settings field by field: a field it leaves\n * out keeps its value. `autoRefill` replaces the auto-refill setting whole.\n * `spendCapMicros` sets the spend cap, and `spendCapMicros` stated as\n * `null` removes it. The merged spec is judged as a whole: auto-refill on\n * with no cap is refused with `ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP`, and\n * auto-refill on for a plan without extra usage with\n * `ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN`. A refused update changes nothing.\n * Lowering the cap below what the period has bought already is allowed: it\n * refuses further purchases in the period.\n *\n * The encoding writes a field when it is stated, and `spendCapMicros` as\n * `null` when it is `null`. A strict read refuses an unknown or repeated\n * field and a `null` anywhere but `spendCapMicros`.\n */\nexport interface UpdateAccountBillingRequest {\n /** Replaces the auto-refill setting. */\n readonly autoRefill?: BillingAutoRefill;\n /**\n * Replaces the spend cap, which must not be negative, in micro-dollars;\n * `null` removes the spend cap.\n */\n readonly spendCapMicros?: Integer | null;\n}\n\n/** A 64-bit integer of micro-dollars, or `null`, which an update writes to remove a cap. */\nconst nullableMicrosShape: Shape<Integer | null> = {\n unknownFields: microsShape.unknownFields,\n decode: (value, path, mode, numberToken) =>\n value === null ? null : microsShape.decode(value, path, mode, numberToken),\n encode: (value) => (value === null ? null : microsShape.encode(value)),\n zero: () => null,\n isZero: (value) => value === null,\n isEmpty: (value) => value === null,\n};\n\n/**\n * The wire shape of a billing settings update: each stated field, with\n * `spendCapMicros` carried as `null` when it is, and a strict read refusing\n * `null` for `autoRefill`.\n */\nexport const updateAccountBillingRequestShape: Shape<UpdateAccountBillingRequest> =\n object<UpdateAccountBillingRequest>({\n autoRefill: explicitPointer(billingAutoRefillShape),\n spendCapMicros: { ...pointer(nullableMicrosShape), null: \"preserve\" },\n });\n\n/**\n * Judges the update: it states at least one field, the auto-refill amount\n * is a positive whole number of dollars, the cap is not negative, and\n * auto-refill is not turned on by the same update that removes the cap.\n * Whether the merged spec has a cap, and whether the plan includes extra\n * usage, are the platform's decision. Throws a `TypeError`.\n */\nexport function validateUpdateAccountBillingRequest(\n request: UpdateAccountBillingRequest,\n): void {\n const autoRefill = request.autoRefill;\n const cap = request.spendCapMicros;\n if (autoRefill === undefined && cap === undefined) {\n throw new TypeError(\"billing update states no field\");\n }\n if (autoRefill !== undefined) {\n prefixed(\"billing update: autoRefill\", () => {\n validateBillingAutoRefill(autoRefill);\n });\n }\n if (cap !== undefined && cap !== null && isNegative(cap)) {\n throw new TypeError(\"billing update: spendCapMicros must not be negative\");\n }\n if (autoRefill?.enabled === true && cap === null) {\n throw new TypeError(\n \"billing update: autoRefill can be enabled only with spendCapMicros set\",\n );\n }\n}\n\n/** Renders a billing settings update as the document the route carries. */\nexport function encodeUpdateAccountBillingRequest(\n request: UpdateAccountBillingRequest,\n): JsonObject {\n return updateAccountBillingRequestShape.encode(request) as JsonObject;\n}\n\n/** Returns the billing as the update left it. */\nexport interface UpdateAccountBillingResponse {\n readonly billing: AccountBilling;\n}\n\n/** The wire shape of the billing update's response. */\nexport const updateAccountBillingResponseShape: Shape<UpdateAccountBillingResponse> =\n object<UpdateAccountBillingResponse>({\n billing: always(accountBillingShape),\n });\n\n/**\n * What a {@link BillingAction} asks the user to do in Stripe.\n *\n * - `checkout`: a payment in Stripe Checkout, where the user enters a card\n * and billing details: the first paid plan, a paid plan after `trial` or `none`, and a\n * purchase on an Account with no saved card.\n * - `confirm_payment`: a payment of the saved card that the card's issuer\n * asks the user to authenticate, on Stripe's hosted invoice or payment\n * page.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingActionKind =\n \"checkout\" | \"confirm_payment\" | (string & Record<never, never>);\n\n/**\n * Judges that the kind is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateBillingActionKind(kind: BillingActionKind): void {\n switch (kind) {\n case \"checkout\":\n case \"confirm_payment\":\n return;\n case \"\":\n throw new TypeError(\"billing action kind is required\");\n default:\n throw new TypeError(\n `unknown billing action kind ${JSON.stringify(kind)}`,\n );\n }\n}\n\n/**\n * A payment the user completes on a page Stripe hosts, for an operation that\n * waits for that payment. A client opens `url` in the user's browser; Stripe\n * returns the user to IDYL when the payment is done or abandoned. The operation\n * finishes once Stripe confirms the payment, and fails with `ACTION_EXPIRED` if\n * the action expires first.\n */\nexport interface BillingAction {\n /** What the page asks of the user. Always written. */\n readonly kind: BillingActionKind;\n /**\n * The page, an absolute https URL. It grants the payment it is for to\n * whoever opens it, so it is shown only to the user who acts. Always\n * written.\n */\n readonly url: string;\n /** When the page stops accepting the payment. Always written. */\n readonly expiresAt: string;\n}\n\n/** The wire shape of a payment page. */\nexport const billingActionShape: Shape<BillingAction> = object<BillingAction>({\n kind: always(string<BillingActionKind>()),\n url: always(string()),\n expiresAt: always(timestampShape),\n});\n\n/**\n * Judges the action: a kind this SDK names, an absolute https URL with a\n * host and no user information, and an expiry. Throws a `TypeError`.\n */\nexport function validateBillingAction(action: BillingAction): void {\n prefixed(\"kind\", () => {\n validateBillingActionKind(action.kind);\n });\n validateHttpsUrl(\"url\", action.url);\n if (isZeroInstant(action.expiresAt)) {\n throw new TypeError(\"expiresAt is required\");\n }\n}\n\n/**\n * Refuses a page address that is not an absolute https URL with a host and\n * without user information, as `${field} must be ...`.\n */\nfunction validateHttpsUrl(field: string, raw: string): void {\n let parsedUrl: URL | undefined;\n try {\n parsedUrl = new URL(raw);\n } catch {\n parsedUrl = undefined;\n }\n if (\n parsedUrl?.protocol !== \"https:\" ||\n parsedUrl.host === \"\" ||\n parsedUrl.username !== \"\" ||\n parsedUrl.password !== \"\" ||\n /^[^:]*:\\/\\/[^/?#]*@/u.test(raw)\n ) {\n throw new TypeError(`${field} must be an absolute https URL with a host`);\n }\n}\n\n/**\n * Asks for an Account's plan to change. `idempotencyKey` makes an equal\n * retry within its window return the same change rather than make a second\n * one.\n */\nexport interface CreateBillingPlanChangeRequest {\n /**\n * The plan to change to: one {@link AccountBillingStatus.plans} lists, or\n * the plan in force to undo a scheduled change.\n */\n readonly plan: BillingPlan;\n /** At most {@link MAX_BILLING_IDEMPOTENCY_KEY_BYTES} bytes when stated. */\n readonly idempotencyKey?: string;\n}\n\n/** The wire shape of a plan change request. */\nexport const createBillingPlanChangeRequestShape: Shape<CreateBillingPlanChangeRequest> =\n object<CreateBillingPlanChangeRequest>({\n plan: always(string<BillingPlan>()),\n idempotencyKey: omitEmpty(string()),\n });\n\n/**\n * Judges the request: a plan in identifier form and a bounded key. Whether\n * the platform offers the plan is the platform's decision\n * (`ERROR_CODE_PLAN_NOT_OFFERED`). Throws a `TypeError`.\n */\nexport function validateCreateBillingPlanChangeRequest(\n request: CreateBillingPlanChangeRequest,\n): void {\n prefixed(\"plan\", () => {\n validateBillingPlan(request.plan);\n });\n validateBillingIdempotencyKey(request.idempotencyKey ?? \"\");\n}\n\n/** Renders a plan change request as the document the route carries. */\nexport function encodeCreateBillingPlanChangeRequest(\n request: CreateBillingPlanChangeRequest,\n): JsonObject {\n return createBillingPlanChangeRequestShape.encode(request) as JsonObject;\n}\n\nfunction validateBillingIdempotencyKey(key: string): void {\n if (\n new TextEncoder().encode(key).byteLength > MAX_BILLING_IDEMPOTENCY_KEY_BYTES\n ) {\n throw new TypeError(\n `idempotencyKey must be at most ${String(MAX_BILLING_IDEMPOTENCY_KEY_BYTES)} bytes`,\n );\n }\n}\n\n/**\n * Where a plan change is.\n *\n * - `pending`: a change being made, or one whose `action` waits for the\n * user in Stripe.\n * - `applied`: a change in force from `effectiveAt`.\n * - `scheduled`: a change that takes effect at `effectiveAt`, the end of\n * the current period, as {@link AccountBillingStatus.scheduledChange}\n * reports.\n * - `failed`: a change that was not made, with `reason`. The plan in force\n * is unchanged.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingPlanChangeState =\n | \"pending\"\n | \"applied\"\n | \"scheduled\"\n | \"failed\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the state is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateBillingPlanChangeState(\n state: BillingPlanChangeState,\n): void {\n switch (state) {\n case \"pending\":\n case \"applied\":\n case \"scheduled\":\n case \"failed\":\n return;\n case \"\":\n throw new TypeError(\"billing plan change state is required\");\n default:\n throw new TypeError(\n `unknown billing plan change state ${JSON.stringify(state)}`,\n );\n }\n}\n\n/**\n * Whether a plan change in `state` will not change state again: `applied`,\n * `scheduled` or `failed`. A state this SDK does not name is not final.\n *\n * @param state - The `state` of a {@link BillingPlanChange}.\n */\nexport function isBillingPlanChangeStateFinal(\n state: BillingPlanChangeState,\n): boolean {\n return state === \"applied\" || state === \"scheduled\" || state === \"failed\";\n}\n\n/**\n * A request to change an Account's plan, served at\n * `/v1/accounts/{account}/billing/plan-changes/{id}`. Creating one answers\n * within a short bounded wait, finished or pending, and the caller reads it\n * until its state is final. What a change does depends on the plan in force\n * and the plan it names:\n *\n * - From `trial` or `none` to a paid plan, the change waits for the user in Stripe\n * Checkout (`checkout`) and is applied once Stripe confirms the first\n * payment.\n * - To a plan with a higher price, it is an upgrade: it takes effect at\n * once, a new period starts with the new plan's whole allowance, what was\n * left of the old allowance expires, and Stripe charges the saved card the\n * new plan's price less a credit for the unused part of the old period. A\n * charge the card's issuer asks the user to authenticate waits for the\n * user (`confirm_payment`); a declined charge fails the change with\n * `PAYMENT_DECLINED` and leaves the plan as it was. An upgrade the\n * platform cannot make as priced fails with `PLAN_CHANGE_UNAVAILABLE`,\n * with nothing charged and the plan as it was.\n * - To a plan with a lower price, `none` included, it is scheduled for the\n * end of the current period, in place of any change scheduled before.\n * - To the plan in force, it undoes a scheduled change and is applied at\n * once; with nothing scheduled it changes nothing.\n *\n * An applied change also clears a scheduled one. A change made while\n * another is pending supersedes it: the earlier one fails with\n * `PLAN_CHANGE_SUPERSEDED`. A change is retained for a window after it is\n * final and then reads HTTP 404.\n *\n * {@link decodeBillingPlanChange} reads one leniently, and\n * {@link validateBillingPlanChange} judges it against this SDK's contract.\n */\nexport interface BillingPlanChange {\n /** Names the change. Always written. */\n readonly id: BillingPlanChangeId;\n /** The plan the change is to. Always written. */\n readonly plan: BillingPlan;\n /** Where the change is. Always written. */\n readonly state: BillingPlanChangeState;\n /**\n * Why a failed change was not made: `PAYMENT_DECLINED`,\n * `ACTION_EXPIRED`, `PLAN_CHANGE_SUPERSEDED` or\n * `PLAN_CHANGE_UNAVAILABLE`. Only a failed change carries one.\n */\n readonly reason?: string;\n /** The payment the user completes in Stripe, carried by a pending change that waits for one. */\n readonly action?: BillingAction;\n /**\n * When an applied change took effect, or when a scheduled change takes\n * effect; `undefined` while pending and once failed.\n */\n readonly effectiveAt?: string;\n}\n\n/** The wire shape of a plan change. */\nexport const billingPlanChangeShape: Shape<BillingPlanChange> =\n object<BillingPlanChange>({\n id: always(string<BillingPlanChangeId>()),\n plan: always(string<BillingPlan>()),\n state: always(string<BillingPlanChangeState>()),\n reason: omitEmpty(string()),\n action: pointer(billingActionShape),\n effectiveAt: omitZero(timestampShape),\n });\n\n/** Reads a plan change the platform served, leniently, as {@link decodeAccountBilling} reads billing. */\nexport function decodeBillingPlanChange(document: unknown): BillingPlanChange {\n return decodeValue(parsed(document), billingPlanChangeShape, \"lenient\");\n}\n\n/** Renders a plan change as the document the platform emits. */\nexport function encodeBillingPlanChange(change: BillingPlanChange): JsonObject {\n return billingPlanChangeShape.encode(change) as JsonObject;\n}\n\n/**\n * Judges the change: a canonical ID, a plan in identifier form, a state\n * this SDK names, and the fields each state carries. A failed change\n * states a reason this SDK names and nothing else does; only a pending\n * change carries an action; an applied or scheduled change carries\n * `effectiveAt` and no other state does. Throws a `TypeError`.\n */\nexport function validateBillingPlanChange(change: BillingPlanChange): void {\n parseBillingPlanChangeId(change.id);\n prefixed(\"plan\", () => {\n validateBillingPlan(change.plan);\n });\n validateBillingPlanChangeState(change.state);\n validateOperationReason(\n change.state === \"failed\",\n change.reason ?? \"\",\n ERROR_CODE_PAYMENT_DECLINED,\n ERROR_CODE_ACTION_EXPIRED,\n ERROR_CODE_PLAN_CHANGE_SUPERSEDED,\n ERROR_CODE_PLAN_CHANGE_UNAVAILABLE,\n );\n validatePendingAction(change.state === \"pending\", change.action);\n const effective = change.state === \"applied\" || change.state === \"scheduled\";\n if (effective === isZeroInstant(change.effectiveAt ?? \"\")) {\n throw new TypeError(\n `effectiveAt is required in states applied and scheduled and absent otherwise, not in state ${change.state}`,\n );\n }\n}\n\n/** Requires a reason from `named` exactly when failed. */\nfunction validateOperationReason(\n failed: boolean,\n reason: string,\n ...named: readonly string[]\n): void {\n if (!failed) {\n if (reason !== \"\") {\n throw new TypeError(\"reason is carried only once failed\");\n }\n return;\n }\n if (reason === \"\") throw new TypeError(\"reason is required once failed\");\n if (!named.includes(reason)) {\n throw new TypeError(`unknown failure reason ${JSON.stringify(reason)}`);\n }\n}\n\n/** Admits an action only while pending, and judges it. */\nfunction validatePendingAction(\n pending: boolean,\n action: BillingAction | undefined,\n): void {\n if (action === undefined) return;\n if (!pending) throw new TypeError(\"action is carried only while pending\");\n prefixed(\"action\", () => {\n validateBillingAction(action);\n });\n}\n\n/** Returns the change as it stood when the create's wait ended. */\nexport interface CreateBillingPlanChangeResponse {\n readonly planChange: BillingPlanChange;\n}\n\n/** The wire shape of the plan change create's response. */\nexport const createBillingPlanChangeResponseShape: Shape<CreateBillingPlanChangeResponse> =\n object<CreateBillingPlanChangeResponse>({\n planChange: always(billingPlanChangeShape),\n });\n\n/** Carries one plan change. */\nexport interface GetBillingPlanChangeResponse {\n readonly planChange: BillingPlanChange;\n}\n\n/** The wire shape of the plan change read's response. */\nexport const getBillingPlanChangeResponseShape: Shape<GetBillingPlanChangeResponse> =\n object<GetBillingPlanChangeResponse>({\n planChange: always(billingPlanChangeShape),\n });\n\n/**\n * Who made a purchase of extra usage.\n *\n * - `manual`: a purchase a user created.\n * - `auto_refill`: a purchase auto-refill made when the extra usage balance\n * reached zero.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingPurchaseKind =\n \"manual\" | \"auto_refill\" | (string & Record<never, never>);\n\n/**\n * Judges that the kind is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateBillingPurchaseKind(kind: BillingPurchaseKind): void {\n switch (kind) {\n case \"manual\":\n case \"auto_refill\":\n return;\n case \"\":\n throw new TypeError(\"billing purchase kind is required\");\n default:\n throw new TypeError(\n `unknown billing purchase kind ${JSON.stringify(kind)}`,\n );\n }\n}\n\n/**\n * Where a purchase is.\n *\n * - `pending`: a purchase being charged, or one whose `action` waits for\n * the user in Stripe. It counts against the spend cap.\n * - `paid`: a purchase Stripe confirmed: its amount is in the extra usage\n * balance.\n * - `failed`: a purchase that was not paid, with `reason`. Nothing was\n * charged, and it does not count against the cap.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string.\n */\nexport type BillingPurchaseState =\n \"pending\" | \"paid\" | \"failed\" | (string & Record<never, never>);\n\n/**\n * Judges that the state is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateBillingPurchaseState(\n state: BillingPurchaseState,\n): void {\n switch (state) {\n case \"pending\":\n case \"paid\":\n case \"failed\":\n return;\n case \"\":\n throw new TypeError(\"billing purchase state is required\");\n default:\n throw new TypeError(\n `unknown billing purchase state ${JSON.stringify(state)}`,\n );\n }\n}\n\n/**\n * Whether a purchase in `state` will not change state again: `paid` or\n * `failed`. A state this SDK does not name is not final.\n *\n * @param state - The `state` of a {@link BillingPurchase}.\n */\nexport function isBillingPurchaseStateFinal(\n state: BillingPurchaseState,\n): boolean {\n return state === \"paid\" || state === \"failed\";\n}\n\n/**\n * Asks to buy extra usage with the card the Account pays with.\n * `idempotencyKey` makes an equal retry within its window return the same\n * purchase rather than charge twice.\n *\n * Only an Account on a plan with extra usage can buy it\n * (`ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN`), and never past its spend cap\n * (`ERROR_CODE_SPEND_CAP_REACHED`). A refused create records nothing.\n */\nexport interface CreateBillingPurchaseRequest {\n /**\n * The extra usage to buy: a positive whole number of dollars, in\n * micro-dollars, before tax, which Stripe adds.\n */\n readonly amountMicros: Integer;\n /** At most {@link MAX_BILLING_IDEMPOTENCY_KEY_BYTES} bytes when stated. */\n readonly idempotencyKey?: string;\n}\n\n/** The wire shape of a purchase request. */\nexport const createBillingPurchaseRequestShape: Shape<CreateBillingPurchaseRequest> =\n object<CreateBillingPurchaseRequest>({\n amountMicros: always(microsShape),\n idempotencyKey: omitEmpty(string()),\n });\n\n/**\n * Judges the request: a positive whole number of dollars and a bounded key.\n * Throws a `TypeError`.\n */\nexport function validateCreateBillingPurchaseRequest(\n request: CreateBillingPurchaseRequest,\n): void {\n validateDollarAmount(\"amountMicros\", request.amountMicros);\n validateBillingIdempotencyKey(request.idempotencyKey ?? \"\");\n}\n\n/** Renders a purchase request as the document the route carries. */\nexport function encodeCreateBillingPurchaseRequest(\n request: CreateBillingPurchaseRequest,\n): JsonObject {\n return createBillingPurchaseRequestShape.encode(request) as JsonObject;\n}\n\n/**\n * A purchase of extra usage, served at\n * `/v1/accounts/{account}/billing/purchases/{id}`. Creating one answers\n * within a short bounded wait, finished or pending, and the caller reads it\n * until its state is final. A purchase on an Account with no saved card\n * waits for the user in Stripe Checkout (`checkout`); one the card's issuer\n * asks the user to authenticate goes there too. An auto-refill purchase is\n * charged with no user present, so a charge that needs the user fails it\n * with `PAYMENT_DECLINED` and turns auto-refill off.\n *\n * {@link decodeBillingPurchase} reads one leniently, and\n * {@link validateBillingPurchase} judges it against this SDK's contract.\n */\nexport interface BillingPurchase {\n /** Names the purchase. Always written. */\n readonly id: BillingPurchaseId;\n /** Who made the purchase. Always written. */\n readonly kind: BillingPurchaseKind;\n /** The extra usage bought, before tax, in micro-dollars. Always written. */\n readonly amountMicros: Integer;\n /** Where the purchase is. Always written. */\n readonly state: BillingPurchaseState;\n /**\n * Why a failed purchase was not paid: `PAYMENT_DECLINED` or\n * `ACTION_EXPIRED`. Only a failed purchase carries one.\n */\n readonly reason?: string;\n /** The payment the user completes in Stripe, carried by a pending purchase that waits for one. */\n readonly action?: BillingAction;\n /** When the purchase was recorded. Always written. */\n readonly createdAt: string;\n}\n\n/** The wire shape of a purchase. */\nexport const billingPurchaseShape: Shape<BillingPurchase> =\n object<BillingPurchase>({\n id: always(string<BillingPurchaseId>()),\n kind: always(string<BillingPurchaseKind>()),\n amountMicros: always(microsShape),\n state: always(string<BillingPurchaseState>()),\n reason: omitEmpty(string()),\n action: pointer(billingActionShape),\n createdAt: always(timestampShape),\n });\n\n/** Reads a purchase the platform served, leniently, as {@link decodeAccountBilling} reads billing. */\nexport function decodeBillingPurchase(document: unknown): BillingPurchase {\n return decodeValue(parsed(document), billingPurchaseShape, \"lenient\");\n}\n\n/** Renders a purchase as the document the platform emits. */\nexport function encodeBillingPurchase(purchase: BillingPurchase): JsonObject {\n return billingPurchaseShape.encode(purchase) as JsonObject;\n}\n\n/**\n * Judges the purchase: a canonical ID, a kind and a state this SDK names, a\n * positive whole number of dollars, a creation instant, and the fields each\n * state carries. A failed purchase states a reason this SDK names and\n * nothing else does; only a pending purchase carries an action. Throws a\n * `TypeError`.\n */\nexport function validateBillingPurchase(purchase: BillingPurchase): void {\n parseBillingPurchaseId(purchase.id);\n validateBillingPurchaseKind(purchase.kind);\n validateDollarAmount(\"amountMicros\", purchase.amountMicros);\n validateBillingPurchaseState(purchase.state);\n validateOperationReason(\n purchase.state === \"failed\",\n purchase.reason ?? \"\",\n ERROR_CODE_PAYMENT_DECLINED,\n ERROR_CODE_ACTION_EXPIRED,\n );\n validatePendingAction(purchase.state === \"pending\", purchase.action);\n if (isZeroInstant(purchase.createdAt)) {\n throw new TypeError(\"createdAt is required\");\n }\n}\n\n/** Returns the purchase as it stood when the create's wait ended. */\nexport interface CreateBillingPurchaseResponse {\n readonly purchase: BillingPurchase;\n}\n\n/** The wire shape of the purchase create's response. */\nexport const createBillingPurchaseResponseShape: Shape<CreateBillingPurchaseResponse> =\n object<CreateBillingPurchaseResponse>({\n purchase: always(billingPurchaseShape),\n });\n\n/** Carries one purchase. */\nexport interface GetBillingPurchaseResponse {\n readonly purchase: BillingPurchase;\n}\n\n/** The wire shape of the purchase read's response. */\nexport const getBillingPurchaseResponseShape: Shape<GetBillingPurchaseResponse> =\n object<GetBillingPurchaseResponse>({\n purchase: always(billingPurchaseShape),\n });\n\n/** One page of an Account's purchases of extra usage, newest first. */\nexport type ListBillingPurchasesResponse = ListResponse<BillingPurchase>;\n\n/** The wire shape of a page of purchases. */\nexport const listBillingPurchasesResponseShape: Shape<ListBillingPurchasesResponse> =\n object<ListBillingPurchasesResponse>({\n items: always(array(billingPurchaseShape)),\n totalCount: always(integer({ unsigned: false, bits: 64 })),\n snapshotCursor: omitEmpty(string()),\n continue: omitEmpty(string()),\n });\n\n/**\n * A session of Stripe's customer portal, where the user manages the\n * Account's card, billing address and tax IDs and reads its invoices and\n * receipts. Each create makes a new session; it is short-lived, so a client\n * opens `url` in the user's browser at once and creates another for a later\n * visit. Stripe returns the user to IDYL when they leave the portal. The\n * portal does not change plans: that is a {@link BillingPlanChange}.\n */\nexport interface BillingPortalSession {\n /**\n * The session's page, an absolute https URL. It signs whoever opens it in\n * to the Account's billing details, so it is shown only to the user who\n * asked for it. Always written.\n */\n readonly url: string;\n}\n\n/** The wire shape of a portal session. */\nexport const billingPortalSessionShape: Shape<BillingPortalSession> =\n object<BillingPortalSession>({ url: always(string()) });\n\n/**\n * Judges the session: an absolute https URL with a host and no user\n * information. Throws a `TypeError`.\n */\nexport function validateBillingPortalSession(\n session: BillingPortalSession,\n): void {\n validateHttpsUrl(\"url\", session.url);\n}\n\n/** Reads a portal session the platform served, leniently, as {@link decodeAccountBilling} reads billing. */\nexport function decodeBillingPortalSession(\n document: unknown,\n): BillingPortalSession {\n return decodeValue(parsed(document), billingPortalSessionShape, \"lenient\");\n}\n\n/** Renders a portal session as the document the platform emits. */\nexport function encodeBillingPortalSession(\n session: BillingPortalSession,\n): JsonObject {\n return billingPortalSessionShape.encode(session) as JsonObject;\n}\n\n/** Returns a new portal session. */\nexport interface CreateBillingPortalSessionResponse {\n readonly portalSession: BillingPortalSession;\n}\n\n/** The wire shape of the portal session create's response. */\nexport const createBillingPortalSessionResponseShape: Shape<CreateBillingPortalSessionResponse> =\n object<CreateBillingPortalSessionResponse>({\n portalSession: always(billingPortalSessionShape),\n });\n\n/** `document` parsed once when it is JSON text, and as given otherwise. */\nfunction parsed(document: unknown): unknown {\n return typeof document === \"string\" ? parseJson(document) : document;\n}\n\n/**\n * Runs `validate` and rethrows its `TypeError` with `prefix` joined to the\n * message without a separator, for refusals that begin with an index, as\n * `sizeRates[1]: ...`.\n */\nfunction joined(prefix: string, validate: () => void): void {\n try {\n validate();\n } catch (error) {\n if (error instanceof TypeError) {\n throw new TypeError(`${prefix}${error.message}`, { cause: error });\n }\n throw error;\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\nimport { integerEqual } from \"../internal/strictdecode.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport {\n parseJournalEntryId,\n parseStorageOperationId,\n} from \"../resource/uuid-id.js\";\nimport { validateForkState, validateVersionOrigin } from \"./storage-enums.js\";\nimport {\n type Shape,\n always,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n} from \"../internal/strictdecode.js\";\nimport { type JsonObject } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n type JournalEntryId,\n type StorageOperationId,\n} from \"../resource/uuid-id.js\";\nimport {\n type CommitState,\n type ForkState,\n type RestoreState,\n type VersionOrigin,\n} from \"./storage-enums.js\";\n\n/**\n * StorageUsage distinguishes the enforced on-disk measure, summed logical file\n * lengths and stored object bytes. Every count, including zero, is written.\n *\n * `names` is how many files, folders and links the newest saved version holds,\n * counted as the name limit of the Computer's size counts them\n * (`ComputerSizeInfo.names`). A save that adds names past that limit is refused\n * with `SAVE_REASON_NAME_LIMIT`. It is absent when no save has counted it yet;\n * the next save counts it.\n */\nexport interface StorageUsage {\n readonly referencedBytes: Integer;\n readonly logicalBytes: Integer;\n readonly storedBytes: Integer;\n readonly names?: Integer;\n}\n\n/** StorageStatus carries fork copying progress only when one was reported. */\nexport interface StorageStatus {\n readonly fork?: ForkProgress;\n}\n\n/** ForkProgress reports copying independently of historical ForkOf provenance. */\nexport interface ForkProgress {\n readonly state: ForkState;\n readonly copied: Integer;\n readonly total: Integer;\n}\n\n/** PageOptions selects a continuation page. Limit zero takes the route's default, and Continue is opaque and passed back verbatim. These options do not expose offset, filter or sort on routes that do not serve them. */\nexport interface PageOptions {\n readonly limit?: Integer;\n readonly continue?: string;\n}\n\n/** Version is a saved state owned by one journal entry. Number zero is genesis; numbers are never reused. Names are optional and unique within the resource. */\nexport interface Version {\n readonly number: Integer;\n readonly name?: string;\n readonly createdAt: string;\n readonly origin: VersionOrigin;\n /**\n * The immutable journal entry that owns this saved version. `undefined`\n * or empty means the owner was not reported. It conveys no execution\n * authority.\n */\n readonly entry?: JournalEntryId;\n readonly operation?: StorageOperationId;\n readonly parent?: Integer;\n readonly logicalBytes: Integer;\n}\n\n/** UpdateVersionRequest sets a unique name; an empty name removes it. */\nexport interface UpdateVersionRequest {\n readonly name: string;\n}\n\n/** CreateCommitRequest gives an optional retry identity to one explicit save. */\nexport interface CreateCommitRequest {\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. The journal entry it makes\n * records it, as `unknown` when it is absent; it is informative and never\n * authorizes anything.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/*\n * The reasons a save or an upload fails for size. Each is the `reason` of a\n * failed `Commit` or a failed `Upload`, and a save refused for one of them\n * leaves the Computer awake with its unsaved files. A `pending` sleep whose\n * save is refused for one carries it as `ComputerSleep.waitingFor` and asks\n * for a save again. Freeing files, or a sleep that discards unsaved changes,\n * lets the Computer sleep.\n */\n\n/**\n * A save or an upload that would take the data the Account stores past its\n * plan's limit (`BillingPlanOffer.storedData`). Saved history counts toward\n * it, and the total is measured hourly. A save that does not grow the\n * Computer's files is never refused with it, so an Account past its limit\n * can still delete files and save.\n */\nexport const SAVE_REASON_ACCOUNT_STORAGE_LIMIT = \"account-storage-limit\";\n\n/**\n * A save or an upload that would take the Computer's files more than 64 MiB\n * past its disk (`ComputerSizeInfo.disk`). The 64 MiB is room the Computer's\n * own bookkeeping can use once its disk is full, so a Computer that fills its\n * disk while nobody is there still saves and sleeps.\n */\nexport const SAVE_REASON_COMPUTER_SIZE = \"computer-size\";\n\n/**\n * A save or an upload that adds names past the most files, folders and links\n * the Computer's size holds (`ComputerSizeInfo.names`).\n */\nexport const SAVE_REASON_NAME_LIMIT = \"name-limit\";\n\n/** Whether `reason` is one of the reasons a save or an upload fails for size. */\nexport function isSaveSizeReason(reason: string | undefined): reason is string {\n return (\n reason === SAVE_REASON_ACCOUNT_STORAGE_LIMIT ||\n reason === SAVE_REASON_COMPUTER_SIZE ||\n reason === SAVE_REASON_NAME_LIMIT\n );\n}\n\n/** Commit reports a saved, unchanged or failed result. Version zero is retained with a pointer; pending work carries neither a final version nor a reason. */\nexport interface Commit {\n readonly id: StorageOperationId;\n readonly state: CommitState;\n readonly version?: Integer;\n readonly reason?: string;\n}\n\n/**\n * Restores a saved version, selected by `from` as a version number or\n * name. History only moves forward: the restore appends a `restore` entry\n * to the journal, owning a new version that holds the selected version's\n * files, and every entry before it is kept. A restore is undone by\n * restoring the version before it.\n *\n * On a Computer the restore also sets the execution settings to those in\n * force at the selected version's entry. They apply at the Computer's next\n * start, as every settings change does, and the restore entry's\n * `executionSettings` records them. Sessions running on the Computer\n * continue: the restored files reach the running machine as a published\n * upload does, replacing unsaved changes to the same paths.\n *\n * `idempotencyKey` makes an equal retry return the same restore.\n */\nexport interface CreateRestoreRequest {\n readonly from: string;\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. The journal entry it makes\n * records it, as `unknown` when it is absent; it is informative and never\n * authorizes anything.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/**\n * A restore's publication: `pending` until the new version is published,\n * then `published` with `version`, or `failed` with `reason`. Publication\n * is independent of the files' later delivery to a running machine and of\n * the restored execution settings, which apply at the Computer's next\n * start.\n */\nexport interface Restore {\n readonly id: StorageOperationId;\n readonly state: RestoreState;\n readonly version?: Integer;\n readonly reason?: string;\n}\n\n/** The canonical wire fields of StorageUsage. */\nexport const storageUsageFields = {\n referencedBytes: always(integer({ unsigned: true, bits: 64 })),\n logicalBytes: always(integer({ unsigned: true, bits: 64 })),\n storedBytes: always(integer({ unsigned: true, bits: 64 })),\n names: pointer(integer({ unsigned: true, bits: 64 })),\n};\n/** The canonical wire shape of StorageUsage. */\nexport const storageUsageShape: Shape<StorageUsage> =\n object<StorageUsage>(storageUsageFields);\n\n/** The canonical wire fields of ForkProgress. */\nexport const forkProgressFields = {\n state: always(string<ForkState>()),\n copied: always(integer({ unsigned: true, bits: 64 })),\n total: always(integer({ unsigned: true, bits: 64 })),\n};\n/** The canonical wire shape of ForkProgress. */\nexport const forkProgressShape: Shape<ForkProgress> =\n object<ForkProgress>(forkProgressFields);\n\n/** The canonical wire fields of PageOptions. */\nexport const pageOptionsFields = {\n limit: omitEmpty(integer({ unsigned: true, bits: 64 })),\n continue: omitEmpty(string()),\n};\n/** The canonical wire shape of PageOptions. */\nexport const pageOptionsShape: Shape<PageOptions> =\n object<PageOptions>(pageOptionsFields);\n\n/** The canonical wire fields of Version. */\nexport const versionFields = {\n number: always(integer({ unsigned: false, bits: 64 })),\n name: omitEmpty(string()),\n createdAt: always(timestampShape),\n origin: always(string<VersionOrigin>()),\n entry: omitEmpty(string<JournalEntryId>()),\n operation: omitEmpty(string<StorageOperationId>()),\n parent: pointer(integer({ unsigned: false, bits: 64 })),\n logicalBytes: always(integer({ unsigned: false, bits: 64 })),\n};\n/** The canonical wire shape of Version. */\nexport const versionShape: Shape<Version> = object<Version>(versionFields);\n\n/** The canonical wire fields of UpdateVersionRequest. */\nexport const updateVersionRequestFields = {\n name: always(string()),\n};\n/** The canonical wire shape of UpdateVersionRequest. */\nexport const updateVersionRequestShape: Shape<UpdateVersionRequest> =\n object<UpdateVersionRequest>(updateVersionRequestFields);\n\n/** The canonical wire fields of CreateCommitRequest. */\nexport const createCommitRequestFields = {\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n};\n/** The canonical wire shape of CreateCommitRequest. */\nexport const createCommitRequestShape: Shape<CreateCommitRequest> =\n object<CreateCommitRequest>(createCommitRequestFields);\n\n/** The canonical wire fields of Commit. */\nexport const commitFields = {\n id: always(string<StorageOperationId>()),\n state: always(string<CommitState>()),\n version: pointer(integer({ unsigned: false, bits: 64 })),\n reason: omitEmpty(string()),\n};\n/** The canonical wire shape of Commit. */\nexport const commitShape: Shape<Commit> = object<Commit>(commitFields);\n\n/** The canonical wire fields of CreateRestoreRequest. */\nexport const createRestoreRequestFields = {\n from: always(string()),\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n};\n/** The canonical wire shape of CreateRestoreRequest. */\nexport const createRestoreRequestShape: Shape<CreateRestoreRequest> =\n object<CreateRestoreRequest>(createRestoreRequestFields);\n\n/** The canonical wire fields of Restore. */\nexport const restoreFields = {\n id: always(string<StorageOperationId>()),\n state: always(string<RestoreState>()),\n version: pointer(integer({ unsigned: false, bits: 64 })),\n reason: omitEmpty(string()),\n};\n/** The canonical wire shape of Restore. */\nexport const restoreShape: Shape<Restore> = object<Restore>(restoreFields);\n\n/** The canonical wire fields of StorageStatus. */\nexport const storageStatusFields = {\n fork: pointer(forkProgressShape),\n};\n/** The canonical wire shape of StorageStatus. */\nexport const storageStatusShape: Shape<StorageStatus> =\n object<StorageStatus>(storageStatusFields);\n\n/** Reads a served Version leniently, carrying unknown fields and tokens. */\nexport function decodeVersion(document: unknown): Version {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n versionShape,\n \"lenient\",\n );\n}\n/** Renders Version with the public wire omission rules and explicit zero counts. */\nexport function encodeVersion(value: Version): JsonObject {\n return versionShape.encode(value) as JsonObject;\n}\n\n/** Reads a served Commit leniently, carrying unknown fields and tokens. */\nexport function decodeCommit(document: unknown): Commit {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n commitShape,\n \"lenient\",\n );\n}\n/** Renders Commit with the public wire omission rules and explicit zero counts. */\nexport function encodeCommit(value: Commit): JsonObject {\n return commitShape.encode(value) as JsonObject;\n}\n\n/** Reads a served Restore leniently, carrying unknown fields and tokens. */\nexport function decodeRestore(document: unknown): Restore {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n restoreShape,\n \"lenient\",\n );\n}\n/** Renders Restore with the public wire omission rules and explicit zero counts. */\nexport function encodeRestore(value: Restore): JsonObject {\n return restoreShape.encode(value) as JsonObject;\n}\n\n/** Checks fork state and progress arithmetic. */\nexport function validateForkProgress(progress: ForkProgress): void {\n validateForkState(progress.state);\n if (progress.copied > progress.total)\n throw new TypeError(\"fork copied exceeds total\");\n}\n/** Checks saved version counts, the reported owning entry and operation identities, and origin vocabulary. */\nexport function validateVersion(version: Version): void {\n if (\n version.number < 0 ||\n version.logicalBytes < 0 ||\n (version.parent !== undefined && version.parent < 0)\n )\n throw new TypeError(\"version counts must be non-negative\");\n if (integerEqual(version.number, 0) && version.parent !== undefined)\n throw new TypeError(\"genesis has no parent\");\n if ((version.entry ?? \"\") !== \"\") parseJournalEntryId(version.entry ?? \"\");\n if ((version.operation ?? \"\") !== \"\")\n parseStorageOperationId(version.operation ?? \"\");\n validateVersionOrigin(version.origin);\n}\n/**\n * Requires a selected restore version and a stated client this SDK names;\n * membership is resolved by the server.\n */\nexport function validateCreateRestoreRequest(\n request: CreateRestoreRequest,\n): void {\n if (request.from === \"\") throw new TypeError(\"restore from is required\");\n validateStatedClient(request.client);\n}\n\n/** Checks that a stated client is one this SDK names. */\nexport function validateCreateCommitRequest(\n request: CreateCommitRequest,\n): void {\n validateStatedClient(request.client);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport { isUint64, integerText } from \"./strictdecode.js\";\nimport type { FileReadOptions, FileListOptions } from \"../api/files.js\";\nimport type { WatchFilesOptions } from \"../api/file-status.js\";\nimport { pageOptionsShape, type PageOptions } from \"../api/storage.js\";\n/*\n * The query string a list request carries. Every list route shares one\n * encoding: each option is sent under its wire name only when it is set, and\n * the keys are written in sorted order so the same options always produce\n * the same string.\n *\n * The routes served by a Computer's API differ in how they name the place\n * the Computer lives in. A Namespace-scoped route states it as the `subnet`\n * parameter on every request; an account-wide route addresses it in the\n * path and never repeats it.\n *\n * A page size is a positive integer and an offset a non-negative one.\n * `undefined` is unset, a present value is sent, and a value no route could\n * honour is refused with a `TypeError` naming the option.\n */\nimport type { ListOptions } from \"../api/types.js\";\nimport type { JournalListOptions } from \"../api/journal.js\";\n\n/**\n * Encodes list options for a route on the global API. Returns the query\n * string beginning with `?`, or an empty string when nothing is set. Throws\n * a `TypeError` when `limit` is not a positive integer or `offset` is\n * not a non-negative integer.\n */\nexport function listQuery(options: ListOptions): string {\n return encode(queryValues(options, undefined));\n}\n\n/**\n * Encodes list options for a Namespace-scoped route served by a Computer's\n * API, which always states the resolved `subnet` explicitly.\n */\nexport function namespaceListQuery(\n options: ListOptions,\n subnet: string,\n): string {\n return encode(queryValues(options, subnet));\n}\n\n/**\n * Encodes list options for an account-wide route served by a Computer's\n * API, which addresses the resolved place in its path and does not repeat\n * it.\n */\nexport function accountListQuery(options: ListOptions): string {\n return encode(queryValues(options, undefined));\n}\n\n/**\n * Encodes the options of a Computer journal list, already judged: `limit`\n * when greater than zero and `continue` verbatim when set. Keys are written\n * in sorted order.\n */\nexport function computerJournalQuery(options: JournalListOptions): string {\n const values: [string, string][] = [];\n const limit = options.limit ?? 0;\n if (limit > 0) values.push([\"limit\", integerText(limit)]);\n const position = options.continue ?? \"\";\n if (position !== \"\") values.push([\"continue\", position]);\n return encode(values.sort(([a], [b]) => (a < b ? -1 : 1)));\n}\n\nfunction queryValues(\n options: ListOptions,\n subnet: string | undefined,\n): readonly (readonly [string, string])[] {\n const values: [string, string][] = [];\n const limit = pageValue(options.limit, \"limit\");\n if (limit !== undefined) values.push([\"limit\", limit]);\n const offset = pageValue(options.offset, \"offset\");\n if (offset !== undefined) values.push([\"offset\", offset]);\n if (options.filter !== undefined && options.filter !== \"\") {\n values.push([\"filter\", options.filter]);\n }\n if (options.sort !== undefined && options.sort !== \"\") {\n values.push([\"sort\", options.sort]);\n }\n if (subnet !== undefined && subnet !== \"\") values.push([\"subnet\", subnet]);\n values.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n return values;\n}\n\nfunction pageValue(\n value: Integer | undefined,\n key: string,\n): string | undefined {\n if (value === undefined) return undefined;\n if (key === \"limit\") {\n if (!isUint64(value) || value <= 0) {\n throw new TypeError(\"list limit must be a positive integer\");\n }\n } else if (!isUint64(value) || value < 0) {\n throw new TypeError(`list ${key} must be a non-negative integer`);\n }\n return integerText(value);\n}\n\nfunction encode(values: readonly (readonly [string, string])[]): string {\n if (values.length === 0) return \"\";\n const query = new URLSearchParams();\n for (const [key, value] of values) query.append(key, value);\n return `?${query.toString()}`;\n}\n\n/** Encodes only the continuation fields served by a page-only route. */\nexport function pageQuery(options: PageOptions): string {\n pageOptionsShape.unknownFields(options, \"\");\n const limit = options.limit ?? 0;\n if (!isUint64(limit) || limit < 0)\n throw new TypeError(\"limit must be a non-negative integer\");\n if (options.continue !== undefined && typeof options.continue !== \"string\")\n throw new TypeError(\"continue must be a string\");\n const query = new URLSearchParams();\n if (limit > 0) query.set(\"limit\", integerText(limit));\n if ((options.continue ?? \"\") !== \"\")\n query.set(\"continue\", options.continue ?? \"\");\n query.sort();\n return query.size === 0 ? \"\" : `?${query.toString()}`;\n}\n\n/**\n * The query of an image catalog read for one isolation class:\n * `?isolation=<class>`. The class is `secure-container` or `vm`, the classes\n * a Computer may select; any other value throws a `TypeError` before a\n * request is made.\n */\nexport function imageCatalogQuery(isolation: string): string {\n if (isolation !== \"secure-container\" && isolation !== \"vm\") {\n throw new TypeError(\n \"list images: isolation class must be secure-container or vm\",\n );\n }\n return `?${new URLSearchParams({ isolation }).toString()}`;\n}\n\n/** A saved file selector; exact byte spelling is retained in query fields. */\nexport function fileQuery(options: FileReadOptions): string {\n const query = new URLSearchParams();\n if (options.path !== undefined) query.set(\"path\", options.path);\n if (options.pathBase64 !== undefined)\n query.set(\"pathBase64\", options.pathBase64);\n if (options.version !== undefined && options.version !== \"\")\n query.set(\"version\", options.version);\n query.sort();\n const value = query.toString();\n return value === \"\" ? \"\" : `?${value}`;\n}\n/**\n * The query of a file watch: `path` or `pathBase64` when one is set, and\n * `after` when it is not empty.\n */\nexport function watchFilesQuery(options: WatchFilesOptions): string {\n const query = new URLSearchParams();\n if (options.path !== undefined) query.set(\"path\", options.path);\n if (options.pathBase64 !== undefined)\n query.set(\"pathBase64\", options.pathBase64);\n if (options.after !== undefined && options.after !== \"\")\n query.set(\"after\", options.after);\n query.sort();\n const value = query.toString();\n return value === \"\" ? \"\" : `?${value}`;\n}\n/** Saved files page by opaque positions and select a path and version. */\nexport function fileListQuery(options: FileListOptions): string {\n const query = new URLSearchParams(\n pageQuery({\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n ...(options.continue === undefined ? {} : { continue: options.continue }),\n }).slice(1),\n );\n for (const [key, value] of new URLSearchParams(fileQuery(options).slice(1)))\n query.set(key, value);\n query.sort();\n const value = query.toString();\n return value === \"\" ? \"\" : `?${value}`;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * An Account's billing is served by the global API under the Account's\n * path. Every request it sends is judged first: a body or an identifier\n * this SDK refuses throws a `TypeError` and sends nothing. Every response\n * is read leniently, through the kind's own decoder, and returned as its\n * envelope.\n */\nimport {\n decodeAccountBilling,\n decodeBillingPlanChange,\n decodeBillingPortalSession,\n decodeBillingPurchase,\n encodeCreateBillingPlanChangeRequest,\n encodeCreateBillingPurchaseRequest,\n encodeUpdateAccountBillingRequest,\n validateCreateBillingPlanChangeRequest,\n validateCreateBillingPurchaseRequest,\n validateUpdateAccountBillingRequest,\n type CreateBillingPlanChangeRequest,\n type CreateBillingPlanChangeResponse,\n type CreateBillingPortalSessionResponse,\n type CreateBillingPurchaseRequest,\n type CreateBillingPurchaseResponse,\n type GetAccountBillingResponse,\n type GetBillingPlanChangeResponse,\n type GetBillingPurchaseResponse,\n type ListBillingPurchasesResponse,\n type UpdateAccountBillingRequest,\n type UpdateAccountBillingResponse,\n} from \"../api/billing.js\";\nimport type { ListOptions } from \"../api/types.js\";\nimport { account, resourceWithin } from \"../internal/apipath.js\";\nimport type { ServiceState } from \"../internal/context.js\";\nimport { readEnvelope, readList } from \"../internal/envelopes.js\";\nimport { listQuery } from \"../internal/listquery.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport type { AccountId } from \"../resource/id.js\";\nimport {\n parseBillingPlanChangeId,\n parseBillingPurchaseId,\n} from \"../resource/uuid-id.js\";\n\n/**\n * The operations on one Account's billing, as `AccountBilling` describes:\n * its read and settings, its plan changes, its purchases of extra usage,\n * and its Stripe portal sessions. No Computer wake, session or cell needs a\n * billing call first: each answers a billing refusal itself.\n */\nexport interface BillingService {\n /** The Account's billing. */\n get(options?: RequestOptions): Promise<GetAccountBillingResponse>;\n /**\n * Changes the Account's billing settings field by field, as\n * `UpdateAccountBillingRequest` describes, and returns the billing as the\n * update left it. The request is judged with\n * `validateUpdateAccountBillingRequest` before it is sent, and sent with\n * `PATCH`; `spendCapMicros: null` removes the cap.\n */\n update(\n request: UpdateAccountBillingRequest,\n options?: RequestOptions,\n ): Promise<UpdateAccountBillingResponse>;\n /**\n * Asks for the Account's plan to change, as `BillingPlanChange`\n * describes. The answer is the change as it stood when the platform's\n * short wait ended: applied, scheduled or failed, or pending, in which\n * case its `action` may name a page the user completes in Stripe. The\n * request is judged with `validateCreateBillingPlanChangeRequest` before\n * it is sent.\n */\n createPlanChange(\n request: CreateBillingPlanChangeRequest,\n options?: RequestOptions,\n ): Promise<CreateBillingPlanChangeResponse>;\n /**\n * Reads one plan change of the Account. `planChangeId` must be a\n * canonical UUID; any other throws a `TypeError` and sends nothing. A\n * change past its retention window reads HTTP 404.\n */\n getPlanChange(\n planChangeId: string,\n options?: RequestOptions,\n ): Promise<GetBillingPlanChangeResponse>;\n /**\n * Opens a new session of Stripe's customer portal for the Account, as\n * `BillingPortalSession` describes. The session is short-lived: open its\n * URL at once.\n */\n createPortalSession(\n options?: RequestOptions,\n ): Promise<CreateBillingPortalSessionResponse>;\n /** The Account's purchases of extra usage. */\n readonly purchases: BillingPurchasesService;\n}\n\n/** The operations on one Account's purchases of extra usage. */\nexport interface BillingPurchasesService {\n /**\n * Buys extra usage, as `BillingPurchase` describes. The answer is the\n * purchase as it stood when the platform's short wait ended: paid or\n * failed, or pending, in which case its `action` may name a page the user\n * completes in Stripe. The request is judged with\n * `validateCreateBillingPurchaseRequest` before it is sent; a request\n * with an `idempotencyKey` is safe to retry.\n */\n create(\n request: CreateBillingPurchaseRequest,\n options?: RequestOptions,\n ): Promise<CreateBillingPurchaseResponse>;\n /**\n * Reads one purchase. `purchaseId` must be a canonical UUID; any other\n * throws a `TypeError` and sends nothing.\n */\n get(\n purchaseId: string,\n options?: RequestOptions,\n ): Promise<GetBillingPurchaseResponse>;\n /**\n * One page of the Account's purchases, newest first, auto-refill\n * purchases included. `options` is encoded as every list's is.\n */\n list(\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListBillingPurchasesResponse>;\n}\n\nconst BILLING = \"billing\";\nconst PURCHASES = \"purchases\";\n\n/** Builds the billing service for `accountId`. */\nexport function billingService(\n state: ServiceState,\n accountId: AccountId,\n): BillingService {\n const { transport, endpoints } = state;\n const billing = (suffix = \"\"): string =>\n account(accountId, suffix === \"\" ? BILLING : `${BILLING}/${suffix}`);\n return Object.freeze({\n async get(options: RequestOptions = {}) {\n return readEnvelope(\n await transport.json<unknown>(\n \"GET\",\n endpoints.api,\n billing(),\n signalOption(options.signal),\n ),\n \"billing\",\n decodeAccountBilling,\n );\n },\n async update(\n request: UpdateAccountBillingRequest,\n options: RequestOptions = {},\n ) {\n validateUpdateAccountBillingRequest(request);\n return readEnvelope(\n await transport.json<unknown>(\"PATCH\", endpoints.api, billing(), {\n body: encodeUpdateAccountBillingRequest(request),\n ...signalOption(options.signal),\n }),\n \"billing\",\n decodeAccountBilling,\n );\n },\n async createPlanChange(\n request: CreateBillingPlanChangeRequest,\n options: RequestOptions = {},\n ) {\n validateCreateBillingPlanChangeRequest(request);\n return readEnvelope(\n await transport.json<unknown>(\n \"POST\",\n endpoints.api,\n billing(\"plan-changes\"),\n {\n body: encodeCreateBillingPlanChangeRequest(request),\n ...signalOption(options.signal),\n },\n ),\n \"planChange\",\n decodeBillingPlanChange,\n );\n },\n async getPlanChange(planChangeId: string, options: RequestOptions = {}) {\n const id = parseBillingPlanChangeId(planChangeId);\n return readEnvelope(\n await transport.json<unknown>(\n \"GET\",\n endpoints.api,\n resourceWithin(billing(), \"plan-changes\", id),\n signalOption(options.signal),\n ),\n \"planChange\",\n decodeBillingPlanChange,\n );\n },\n async createPortalSession(options: RequestOptions = {}) {\n return readEnvelope(\n await transport.json<unknown>(\n \"POST\",\n endpoints.api,\n billing(\"portal-sessions\"),\n signalOption(options.signal),\n ),\n \"portalSession\",\n decodeBillingPortalSession,\n );\n },\n purchases: billingPurchasesService(state, billing()),\n } satisfies BillingService);\n}\n\n/** Builds the purchases service beneath the billing path `billing`. */\nfunction billingPurchasesService(\n state: ServiceState,\n billing: string,\n): BillingPurchasesService {\n const { transport, endpoints } = state;\n const collection = `${billing}/${PURCHASES}`;\n return Object.freeze({\n async create(\n request: CreateBillingPurchaseRequest,\n options: RequestOptions = {},\n ) {\n validateCreateBillingPurchaseRequest(request);\n return readEnvelope(\n await transport.json<unknown>(\"POST\", endpoints.api, collection, {\n body: encodeCreateBillingPurchaseRequest(request),\n ...signalOption(options.signal),\n }),\n \"purchase\",\n decodeBillingPurchase,\n );\n },\n async get(purchaseId: string, options: RequestOptions = {}) {\n const id = parseBillingPurchaseId(purchaseId);\n return readEnvelope(\n await transport.json<unknown>(\n \"GET\",\n endpoints.api,\n resourceWithin(billing, PURCHASES, id),\n signalOption(options.signal),\n ),\n \"purchase\",\n decodeBillingPurchase,\n );\n },\n async list(options: ListOptions = {}, request: RequestOptions = {}) {\n const query = listQuery(options);\n return readList(\n await transport.json<unknown>(\n \"GET\",\n endpoints.api,\n `${collection}${query}`,\n signalOption(request.signal),\n ),\n \"billing purchases\",\n decodeBillingPurchase,\n );\n },\n } satisfies BillingPurchasesService);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The public views of the records a Computer serves: its settings, its\n * history and its saved versions. Each is built\n * field by field from the served record, so a field the product does not\n * offer never reaches a caller.\n */\nimport type {\n ComputerAwake,\n ComputerSessionSummary,\n} from \"../api/computer-awake.js\";\nimport type { JournalEntry } from \"../api/journal.js\";\nimport type { Version as VersionRecord } from \"../api/storage.js\";\nimport type { ComputerEffectiveExecutionSettings } from \"../api/computer.js\";\nimport type {\n ComputerExecutionSettings,\n ComputerSecretAttachment,\n} from \"../resource/computer-execution-settings.js\";\nimport { formatCpu } from \"../resource/cpu.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { formatMemory } from \"../resource/memory.js\";\nimport { formatVolume } from \"../resource/volume.js\";\n\n/**\n * How a Computer runs: its image, CPU, memory, network class and what it\n * allows, environment variables, and default shell. A field that is absent\n * is not stated and takes IDYL's default.\n */\nexport interface ExecutionSettings {\n /** The image: an IDYL catalogue name such as `ubuntu-24.04`, or an image reference. */\n readonly image?: string;\n /** How it is isolated: `secure-container` or `vm`. Absent is `secure-container`. */\n readonly isolation?: string;\n /**\n * The size by name, such as `small`. Settings as stated hold it or `cpu` and\n * `memory`; the effective settings hold all three, with `disk`, and leave it\n * out while the limits are no size's.\n */\n readonly size?: string;\n /**\n * The name a person reads for `size`, such as `Small`, so a list row can show\n * it with no second request. Only the effective settings hold this field.\n */\n readonly sizeLabel?: string;\n /** The CPU limit, such as `500m` or `2`. */\n readonly cpu?: string;\n /** The memory limit, such as `512Mi` or `4Gi`. */\n readonly memory?: string;\n /**\n * The most the Computer can store, such as `20Gi`, as reported by IDYL. Only\n * the effective settings hold this field.\n */\n readonly disk?: string;\n /**\n * The network class: `internet` (the open internet, local networks\n * blocked), `restricted-egress` or `none`. A class this package does not name\n * is carried unchanged from IDYL's report.\n */\n readonly network?: string;\n /**\n * What a `restricted-egress` network allows: `dns`, and\n * `tcp:<port>:<hostname>` per destination.\n */\n readonly allow?: readonly string[];\n /** The environment variables every process starts with. */\n readonly env?: Readonly<Record<string, string>>;\n /**\n * The Secrets attached, by the environment variable each is attached\n * under: `secret` is the Secret's ID, and `version` the version an\n * attachment pins, absent when it follows the current one. Only the settings\n * as stated hold this field.\n */\n readonly secrets?: Readonly<\n Record<string, { readonly secret: string; readonly version?: number }>\n >;\n /**\n * The default shell its terminals run, such as `/usr/bin/zsh`. Absent\n * when none is stated: a terminal then runs `/bin/bash` when the image\n * has it and `/bin/sh` otherwise.\n */\n readonly shell?: string;\n}\n\n/**\n * One entry of a Computer's history, newest first. `kind` is `genesis`,\n * `execution-settings`, `upload`, `edit`, `restore`, `save`,\n * `fork-point`, `rename`, `wake` or `sleep`, or one this package does not\n * name. `version` is\n * the saved version the entry owns, when it owns one. `creator` names who\n * caused it, absent when IDYL made it on its own.\n */\nexport interface HistoryEntry {\n /** The entry's ID, which a fork can start from. */\n readonly id: string;\n /** What the entry records, as the description of {@link HistoryEntry} lists. */\n readonly kind: string;\n /** When IDYL admitted the entry, as an RFC 3339 instant. */\n readonly admittedAt: string;\n /** The saved version the entry owns, when it owns one. */\n readonly version?: number;\n /** Who caused it; absent when IDYL made it on its own. */\n readonly creator?: string;\n /**\n * The kind of client that made it, such as `console`, `cli` or `sdk`, or\n * `unknown` when its request named none. Present on every entry a\n * request caused; absent on an entry IDYL made on its own. It is\n * informative and grants nothing.\n */\n readonly client?: string;\n /** What caused a `save` entry. */\n readonly save?: { readonly trigger: string };\n /** The settings after an `execution-settings` or `restore` entry. */\n readonly settings?: ExecutionSettings;\n /**\n * The image patch an `execution-settings` entry records: IDYL started the\n * Computer on a newer patch level of its catalog image, named by `image`,\n * moving `from` one patch level `to` another, such as `2026.10.13` to\n * `2026.10.24`. Such an entry is IDYL's own and names no creator or\n * client. Absent on every other entry.\n */\n readonly imagePatch?: {\n readonly image: string;\n readonly from: string;\n readonly to: string;\n };\n /** The names before and after a `rename` entry. */\n readonly rename?: { readonly from: string; readonly to: string };\n /**\n * Why a `sleep` entry's Computer slept: `reason` is `request`, `idle`,\n * `no-execution`, `settings`, `restore`, `node-drain`, `out-of-usage`,\n * `plan-size` or `powered-off`, when a program in the Computer shut its\n * machine down; `idleTimeout` is the timeout in force on an idle sleep;\n * `discardedUnsavedChanges` is true when the sleep was asked to discard\n * unsaved changes and released the Computer without saving them.\n */\n readonly sleep?: {\n readonly reason?: string;\n readonly idleTimeout?: string;\n readonly discardedUnsavedChanges: boolean;\n };\n /**\n * What started a `wake` entry's Computer: `session` is the kind of session,\n * `terminal`, `command` or `ssh`, or a kind this package does not name.\n * Absent on a wake request.\n */\n readonly wake?: { readonly session: string };\n /**\n * Why a `restart` entry's execution started again: `reason` is `node-lost`,\n * `failed`, when the Computer's machine or container failed, or `replaced`.\n */\n readonly restart?: { readonly reason: string };\n}\n\n/** One thing keeping a Computer awake. */\nexport interface AwakeHold {\n /**\n * What it is: `session`, `keep-awake`, `starting-session`,\n * `settings-restart`, or a kind this package does not name. A\n * `settings-restart` keeps nothing awake: the Computer sleeps once no session\n * holds it awake.\n */\n readonly kind: string;\n /** How many sessions it names; zero on a hold that names none. */\n readonly count: number;\n}\n\n/**\n * Why a Computer is awake and when it sleeps, at the time of the read. A\n * Computer counting down states `sleepsAt` and `sleepsIn`; count down from\n * `sleepsIn`, which needs no agreement between this machine's clock and IDYL's,\n * and read the Computer again to follow a change made elsewhere.\n */\nexport interface Awake {\n /** When its current execution started, as an RFC 3339 instant. */\n readonly since: string;\n /** What keeps it awake at the read; empty while it counts down. */\n readonly holds: readonly AwakeHold[];\n /** When it sleeps by IDYL's clock, as an RFC 3339 instant. */\n readonly sleepsAt?: string;\n /**\n * Whole seconds until `sleepsAt`, from the read; zero once that time has\n * passed.\n */\n readonly sleepsIn?: number;\n}\n\n/**\n * One open session of a Computer, as seen by anyone who may read the Computer.\n * It carries no command, output or credential, and it grants nothing.\n */\nexport interface OpenSession {\n /** The session's ID. */\n readonly id: string;\n /**\n * `terminal`, `command`, `ssh` (an SSH connection), or a kind this\n * package does not name.\n */\n readonly kind: string;\n /** The kind of client that opened it, or `unknown`. It is informative. */\n readonly client: string;\n /** The identity that opened the session. */\n readonly openedBy: string;\n /** When it was accepted, as an RFC 3339 instant. */\n readonly openedAt: string;\n /** Whether the caller who read the list opened the session. */\n readonly yours: boolean;\n}\n\n/** One saved version of a Computer's files. */\nexport interface Version {\n /** The version's number; zero is the empty first version. */\n readonly number: number;\n /** The name it was given, if any. */\n readonly name?: string;\n /** When it was saved, as an RFC 3339 instant. */\n readonly createdAt: string;\n /** What made it: `genesis`, `commit`, `upload`, `restore` or `fork-point`. */\n readonly origin: string;\n /** The history entry that owns this version. */\n readonly entry?: string;\n /** The version it was made from. */\n readonly parent?: number;\n /** The size of its files, in bytes. */\n readonly bytes: number;\n}\n\n/** An integer the platform served, as a number. */\nexport function numberOf(value: Integer): number {\n return typeof value === \"bigint\" ? Number(value) : value;\n}\n\n/** An optional integer the platform served, as a number. */\nexport function optionalNumber(value: Integer | undefined): number | undefined {\n return value === undefined ? undefined : numberOf(value);\n}\n\n/** Copies `value` into `target` under `key` when it is present. */\nfunction present<K extends string, V>(\n key: K,\n value: V | undefined,\n): Readonly<Partial<Record<K, V>>> {\n return (value === undefined ? {} : { [key]: value }) as Readonly<\n Partial<Record<K, V>>\n >;\n}\n\n/**\n * A served quantity or duration in its spelling. The lenient reader\n * carries a value its codec refused as it arrived, so a string is shown as\n * it is, and anything else that cannot be spelled is left out rather than\n * failing the whole record.\n */\nexport function spelled<T>(\n value: T | undefined,\n format: (value: T) => string,\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return format(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The `secrets` field of the settings as stated; a read that carries no\n * list, or what the lenient reader kept of one it could not read, has none.\n */\nfunction attachmentsOf(\n settings: ComputerExecutionSettings | ComputerEffectiveExecutionSettings,\n): Pick<ExecutionSettings, \"secrets\"> {\n const stated: unknown = \"secrets\" in settings ? settings.secrets : undefined;\n return Array.isArray(stated)\n ? { secrets: attachedOf(stated as readonly ComputerSecretAttachment[]) }\n : {};\n}\n\n/**\n * The public view of Secret attachments, by variable. A read names each\n * Secret by ID; a name is shown only where IDYL reported one in its place.\n */\nfunction attachedOf(\n attachments: readonly ComputerSecretAttachment[],\n): Readonly<\n Record<string, { readonly secret: string; readonly version?: number }>\n> {\n const attached: Record<\n string,\n { readonly secret: string; readonly version?: number }\n > = {};\n for (const { env, secret } of attachments) {\n attached[env] = Object.freeze({\n secret: secret.id ?? secret.name ?? \"\",\n ...(secret.version === undefined\n ? {}\n : { version: numberOf(secret.version) }),\n });\n }\n return Object.freeze(attached);\n}\n\n/** The public view of execution settings. */\nexport function settingsOf(\n settings:\n ComputerExecutionSettings | ComputerEffectiveExecutionSettings | undefined,\n): ExecutionSettings {\n if (settings === undefined) return Object.freeze({});\n const env: Record<string, string> = {};\n for (const variable of settings.variables ?? []) {\n env[variable.name] = variable.value;\n }\n return Object.freeze({\n ...present(\"image\", settings.image?.idyl ?? settings.image?.ref),\n ...present(\"size\", settings.size === \"\" ? undefined : settings.size),\n ...(\"sizeLabel\" in settings && settings.sizeLabel !== \"\"\n ? present(\"sizeLabel\", settings.sizeLabel)\n : {}),\n ...present(\"cpu\", spelled(settings.cpu, formatCpu)),\n ...present(\"memory\", spelled(settings.memory, formatMemory)),\n ...(\"disk\" in settings\n ? present(\"disk\", spelled(settings.disk, formatVolume))\n : {}),\n ...present(\"network\", settings.network?.class),\n ...present(\n \"allow\",\n settings.network?.egress?.allow === undefined\n ? undefined\n : Object.freeze([...settings.network.egress.allow]),\n ),\n ...(settings.variables === undefined ? {} : { env: Object.freeze(env) }),\n ...attachmentsOf(settings),\n ...(\"isolation\" in settings\n ? present(\n \"isolation\",\n settings.isolation === \"\" ? undefined : settings.isolation,\n )\n : {}),\n ...present(\"shell\", settings.shell === \"\" ? undefined : settings.shell),\n });\n}\n\n/** The public view of a history entry. */\nexport function historyEntryOf(entry: JournalEntry): HistoryEntry {\n return Object.freeze({\n id: entry.id,\n kind: entry.kind,\n admittedAt: entry.admittedAt,\n ...present(\"version\", optionalNumber(entry.version)),\n ...present(\"creator\", entry.creator),\n ...present(\n \"client\",\n entry.client ?? entry.cell?.client ?? entry.executionSettings?.client,\n ),\n ...present(\n \"save\",\n entry.save === undefined\n ? undefined\n : Object.freeze({ trigger: entry.save.trigger }),\n ),\n ...present(\n \"settings\",\n entry.executionSettings === undefined\n ? undefined\n : settingsOf(entry.executionSettings.settings),\n ),\n ...present(\n \"imagePatch\",\n entry.executionSettings?.imagePatch === undefined\n ? undefined\n : Object.freeze({\n image: entry.executionSettings.imagePatch.name,\n from: entry.executionSettings.imagePatch.from.patch,\n to: entry.executionSettings.imagePatch.to.patch,\n }),\n ),\n ...present(\n \"rename\",\n entry.rename === undefined\n ? undefined\n : Object.freeze({ from: entry.rename.from, to: entry.rename.to }),\n ),\n ...present(\n \"sleep\",\n entry.sleep === undefined\n ? undefined\n : Object.freeze({\n ...present(\"reason\", entry.sleep.reason),\n ...present(\"idleTimeout\", entry.sleep.idleTimeout),\n discardedUnsavedChanges:\n entry.sleep.discardedUnsavedChanges === true,\n }),\n ),\n ...present(\n \"wake\",\n entry.wake === undefined\n ? undefined\n : Object.freeze({ session: entry.wake.session }),\n ),\n ...present(\n \"restart\",\n entry.restart === undefined\n ? undefined\n : Object.freeze({ reason: entry.restart.reason }),\n ),\n });\n}\n\n/** The public view of why a Computer is awake. */\nexport function awakeOf(awake: ComputerAwake): Awake {\n return Object.freeze({\n since: awake.since,\n holds: Object.freeze(\n awake.holds.map((hold) =>\n Object.freeze({ kind: hold.kind, count: numberOf(hold.count) }),\n ),\n ),\n ...present(\"sleepsAt\", awake.sleepsAt),\n ...present(\"sleepsIn\", optionalNumber(awake.sleepsIn)),\n });\n}\n\n/** The public view of an open session. */\nexport function openSessionOf(session: ComputerSessionSummary): OpenSession {\n return Object.freeze({\n id: session.id,\n kind: session.kind,\n client: session.client,\n openedBy: session.openedBy,\n openedAt: session.openedAt,\n yours: session.yours,\n });\n}\n\n/** The public view of a saved version. */\nexport function versionOf(version: VersionRecord): Version {\n return Object.freeze({\n number: numberOf(version.number),\n ...present(\"name\", version.name),\n createdAt: version.createdAt,\n origin: version.origin,\n ...present(\"entry\", version.entry),\n ...present(\"parent\", optionalNumber(version.parent)),\n bytes: numberOf(version.logicalBytes),\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * An Account's billing: its plan, its usage and settings, its plan changes,\n * its purchases of extra usage and its Stripe portal sessions. Each public\n * view is built field by field from the served record, so a field the\n * product does not offer never reaches a caller.\n */\nimport type {\n AccountBilling as AccountBillingRecord,\n BillingAction as BillingActionRecord,\n BillingActionKind,\n BillingAllowanceWithheld,\n BillingPlan,\n BillingPlanChange as BillingPlanChangeRecord,\n BillingPlanChangeState,\n BillingPortalSession as BillingPortalSessionRecord,\n BillingPurchase as BillingPurchaseRecord,\n BillingPurchaseKind,\n BillingPurchaseState,\n BillingLifecycle,\n BillingRenewalState,\n BillingStanding,\n ComputerSize,\n} from \"../api/billing.js\";\nimport {\n validateCreateBillingPlanChangeRequest,\n validateCreateBillingPurchaseRequest,\n validateUpdateAccountBillingRequest,\n} from \"../api/billing.js\";\nimport { TransportError } from \"../errors.js\";\nimport { formatCpu, type CpuQuantity } from \"../resource/cpu.js\";\nimport { formatMemory, type MemoryQuantity } from \"../resource/memory.js\";\nimport { formatVolume, type VolumeQuantity } from \"../resource/volume.js\";\nimport {\n durationMilliseconds,\n isZeroDuration,\n type Duration,\n} from \"../resource/duration.js\";\nimport {\n parseBillingPlanChangeId,\n parseBillingPurchaseId,\n} from \"../resource/uuid-id.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { isRecord } from \"../internal/envelopes.js\";\nimport { billingService, type BillingService } from \"../services/billing.js\";\nimport {\n offsetContinue,\n offsetOf,\n pageOf,\n requireLimit,\n signalOf,\n walk,\n type CallOptions,\n type ListOptions,\n type Page,\n type PageOptions,\n} from \"./common.js\";\nimport { spelled } from \"./records.js\";\n\nexport type {\n BillingActionKind,\n BillingAllowanceWithheld,\n BillingPlan,\n BillingPlanChangeState,\n BillingPurchaseKind,\n BillingPurchaseState,\n BillingLifecycle,\n BillingRenewalState,\n BillingStanding,\n ComputerSize,\n};\nexport {\n MICROS_PER_DOLLAR,\n isBillingPlanChangeStateFinal,\n isBillingPurchaseStateFinal,\n} from \"../api/billing.js\";\n\n/**\n * Whether auto-refill is on and how much each refill buys. A refill is an\n * extra usage purchase of kind `auto_refill`, made with the card the\n * Account pays with, at most one each time the balance reaches zero, and\n * never past the spend cap.\n */\nexport interface BillingAutoRefill {\n /** Whether auto-refill buys extra usage. */\n readonly enabled: boolean;\n /**\n * What one refill buys: a positive whole number of dollars, in\n * micro-dollars. It is kept while auto-refill is off.\n */\n readonly amountMicros: number;\n}\n\n/** What an Account's owner sets for its extra usage. */\nexport interface AccountBillingSpec {\n /**\n * Buys extra usage when the Account's extra usage balance reaches zero.\n * It is off when an Account is created. IDYL turns it off on its own\n * when a refill cannot be charged or a payment is disputed, and says why\n * in {@link AccountBillingStatus.autoRefillStopped}.\n */\n readonly autoRefill: BillingAutoRefill;\n /**\n * The most the Account spends on extra usage in one period, counting\n * purchases paid and pending, whether the owner bought them or\n * auto-refill did; a purchase that would pass it is refused with\n * `ERROR_CODE_SPEND_CAP_REACHED`. `undefined` means no cap, which is how\n * an Account starts. Auto-refill can be on only while a cap is set.\n */\n readonly spendCapMicros?: number;\n}\n\n/**\n * What one awake hour of a size costs, before tax, and the size this rate\n * prices, so a page can show the size with no second request. IDYL may leave out\n * every field but `size` and `perHourMicros`.\n */\nexport interface BillingSizeRate {\n /** The size this rate prices. */\n readonly size: ComputerSize;\n /**\n * The price of one hour a Computer is awake at `size`, in micro-dollars.\n * A Computer is billed for the time it is awake at this rate: half an\n * hour costs half the rate. Zero is a rate.\n */\n readonly perHourMicros: number;\n /** The name to show a person for the size, such as `Small`. */\n readonly label?: string;\n /** The CPU limit of a Computer of the size, such as `2`. */\n readonly cpu?: string;\n /** The memory limit of a Computer of the size, such as `4Gi`. */\n readonly memory?: string;\n /** The most a Computer of the size can store, such as `20Gi`. */\n readonly disk?: string;\n /** `true` when a Computer that states no size, CPU or memory runs at the size. */\n readonly default?: boolean;\n}\n\n/**\n * A change of plan that takes effect at the end of the current period: a\n * downgrade, or a cancellation, which is a change to `none`. When it takes\n * effect, the Account's awake Computers larger than `largestSize` are asked\n * to sleep, and each needs a size no larger than it, or an upgrade, before\n * it can wake again. A plan change to the plan in force undoes the pending\n * change.\n */\nexport interface BillingScheduledChange {\n /** The plan the Account changes to. */\n readonly plan: BillingPlan;\n /** When the change takes effect, the end of the current period, as an RFC 3339 instant. */\n readonly at: string;\n /** The largest size `plan` includes. */\n readonly largestSize: ComputerSize;\n}\n\n/** Why and when IDYL turned auto-refill off. */\nexport interface BillingAutoRefillStop {\n /**\n * `ERROR_CODE_PAYMENT_DECLINED` when a refill could not be charged, or\n * `ERROR_CODE_PAYMENT_DISPUTED` when a payment of the Account was\n * disputed.\n */\n readonly reason: string;\n /** When auto-refill was turned off, as an RFC 3339 instant. */\n readonly at: string;\n}\n\n/** Names the smallest plan that includes a size. */\nexport interface BillingSizePlan {\n /** A size some plan includes. */\n readonly size: ComputerSize;\n /** The smallest plan whose largest size is at least `size`. */\n readonly plan: BillingPlan;\n}\n\n/** A plan as it is offered. */\nexport interface BillingPlanOffer {\n /** The plan's identifier, in the form a plan change uses. */\n readonly plan: BillingPlan;\n /** The plan's name for display, such as `Max 5x`. */\n readonly name: string;\n /**\n * The plan's price for one month, before tax, which Stripe adds when it\n * charges, in micro-dollars. Zero for `trial` and `none`.\n */\n readonly priceMicros: number;\n /** The usage the plan grants each month, in micro-dollars. */\n readonly allowanceMicros: number;\n /** The largest size the plan includes. */\n readonly largestSize: ComputerSize;\n /**\n * The most data an Account on the plan stores across all its Computers,\n * saved history included, such as `400Gi` or `2Ti`. A save or an upload\n * that would go past it fails with `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`.\n * `undefined` when the plan has no such limit.\n */\n readonly storedData?: string;\n /**\n * The most vCPU an Account on the plan keeps awake at once, across all its\n * Computers. Asleep Computers count for nothing. A wake that would go past\n * it fails with `ERROR_CODE_VCPU_LIMIT_REACHED`. `undefined` when the plan\n * has no such limit.\n */\n readonly awakeVCPU?: number;\n /** Whether an Account on the plan can buy extra usage and turn on auto-refill. */\n readonly extraUsage: boolean;\n}\n\n/**\n * An Account's billing, as reported by IDYL. Usage is counted the moment it is\n * recorded, before it is settled, so the amounts are the ones the Account's\n * standing is judged on. Instants are RFC 3339 strings.\n */\nexport interface AccountBillingStatus {\n /** The plan in force. */\n readonly plan: BillingPlan;\n /**\n * The start of the current period, which is `[periodStart, periodEnd)`:\n * one month of the plan in force, or a trial's whole length. An upgrade\n * starts a fresh period at once.\n */\n readonly periodStart: string;\n /** The end of the current period: when the allowance resets, a paid plan renews and a trial ends. */\n readonly periodEnd: string;\n /**\n * The allowance granted for the current period: zero until a paid\n * period's renewal is paid, and zero when it was withheld\n * (`allowanceWithheld`). What is left of it when the period ends expires.\n */\n readonly allowanceMicros: number;\n /**\n * Why the current period's allowance was withheld, when it was;\n * `undefined` otherwise. `trial_one_per_person` is an unpaid allowance\n * withheld because it is given once per person and the verified sign-in\n * email of the Account's owner already holds it on another Account.\n * `trials_closed` is one withheld because IDYL offered no trials when the\n * Account was created. A paid plan's allowance is never withheld for\n * either reason.\n */\n readonly allowanceWithheld?: BillingAllowanceWithheld;\n /**\n * How much of `allowanceMicros` the period's usage has used, never more\n * than `allowanceMicros`. Usage beyond the allowance draws on the extra\n * usage balance.\n */\n readonly usedMicros: number;\n /**\n * The extra usage bought and unused. It never expires and is used only\n * once the allowance is used up.\n */\n readonly extraBalanceMicros: number;\n /**\n * The extra usage bought in the current period, purchases paid and\n * pending, which is what the spend cap counts.\n */\n readonly extraBoughtMicros: number;\n /**\n * Whether the Account's Computers may wake: `ok`, or `out` when the\n * allowance and the extra usage are used and auto-refill cannot buy\n * more. An `out` Account's wakes and session starts are refused with\n * `ERROR_CODE_OUT_OF_USAGE` and its awake Computers are asked to sleep,\n * their files kept. It is `ok` again after a purchase, an upgrade or the\n * start of its next period; its Computers are not woken by that.\n */\n readonly standing: BillingStanding;\n /**\n * Where the Account stands in its use of the platform: `full`, `trial`\n * while its free trial runs, or `ended` with no paid plan and nothing left\n * to spend. It tells an Account whose free usage has ended from a paying\n * Account that has used up its month, which a `standing` of `out` alone\n * cannot.\n */\n readonly lifecycle: BillingLifecycle;\n /**\n * Whether the plan's latest renewal was paid: `ok`, or `failed` while\n * Stripe retries a payment that failed. The period's allowance is granted\n * only once it is paid; if the retries end unpaid, the plan ends and the\n * Account is on `none`.\n */\n readonly renewal: BillingRenewalState;\n /**\n * The largest size the plan in force includes. A wake or a resize of a\n * Computer to a larger size is refused with `ERROR_CODE_SIZE_NOT_IN_PLAN`.\n */\n readonly largestSize: ComputerSize;\n /**\n * The most data the Account stores across all its Computers under the\n * plan in force, saved history included, such as `400Gi`. `undefined`\n * when the plan has no such limit.\n */\n readonly storedData?: string;\n /**\n * How long, in milliseconds, an Account keeps its files once it has no\n * plan and nothing left to spend, under the default rate card in force.\n * The files are deleted no earlier than that. An Account whose files\n * are already being kept this way keeps the terms it started with.\n * `undefined` when the rate card has no free trial.\n */\n readonly fileRetentionMs?: number;\n /**\n * How long, in milliseconds, before its files are deleted each warning is\n * sent to the Account's owner, longest first. `undefined` when the rate\n * card has no free trial.\n */\n readonly deletionWarningsMs?: readonly number[];\n /**\n * The plan the Account changes to at the end of the current period, when\n * a downgrade or a cancellation is scheduled; `undefined` when none is.\n */\n readonly scheduledChange?: BillingScheduledChange;\n /**\n * Why IDYL turned auto-refill off on its own; `undefined` when it did\n * not. It is cleared when auto-refill is turned on again.\n */\n readonly autoRefillStopped?: BillingAutoRefillStop;\n /** Whether Stripe holds invoices for the Account. A portal session shows them. */\n readonly hasInvoices: boolean;\n /**\n * For each size some plan includes, the smallest plan that includes it,\n * smallest size first.\n */\n readonly sizePlans: readonly BillingSizePlan[];\n /**\n * Every plan offered, cheapest first; it always lists the plan in force\n * and the plan of a scheduled change.\n */\n readonly plans: readonly BillingPlanOffer[];\n /**\n * What an awake hour of each size costs the Account's Computers under the\n * rate card in force: one entry per size, smallest first.\n */\n readonly sizeRates: readonly BillingSizeRate[];\n /**\n * The rate in force for storing one GiB for one month, in micro-dollars,\n * before tax. Zero is a rate.\n */\n readonly storageMicrosPerGiBMonth: number;\n /**\n * The rate in force for downloading one GiB, in micro-dollars, before\n * tax. Zero is a rate.\n */\n readonly downloadMicrosPerGiB: number;\n}\n\n/**\n * An Account's billing: `spec` is what the Account's owner sets, and\n * `status` is what IDYL reports. Every Account has one, from sign-up onwards.\n * A plan change, not `spec`, moves the Account to another plan.\n *\n * Every amount of money is in US dollars, as a whole number of\n * micro-dollars (`MICROS_PER_DOLLAR` to the dollar), so amounts sum without\n * rounding. Amounts are never negative.\n */\nexport interface AccountBilling {\n /** What the Account's owner sets: auto-refill and the spend cap. */\n readonly spec: AccountBillingSpec;\n /** What IDYL reports: the plan, the period, usage, standing and rates. */\n readonly status: AccountBillingStatus;\n}\n\n/**\n * A payment the user completes on a page Stripe hosts, for an operation that\n * waits for that payment. Open `url` in the user's browser; Stripe returns the\n * user to IDYL when the payment is done or abandoned. The operation finishes\n * once Stripe confirms the payment, and fails with `ERROR_CODE_ACTION_EXPIRED`\n * if the action expires first.\n */\nexport interface BillingAction {\n /**\n * `checkout`, a payment in Stripe Checkout where the user enters a card\n * and billing details, or `confirm_payment`, a payment of the saved card\n * that the card's issuer asks the user to authenticate.\n */\n readonly kind: BillingActionKind;\n /**\n * The page, an absolute https URL. It grants the payment it is for to\n * whoever opens it, so show it only to the user who acts.\n */\n readonly url: string;\n /** When the page stops accepting the payment, as an RFC 3339 instant. */\n readonly expiresAt: string;\n}\n\n/**\n * A request to change an Account's plan. Creating one answers within a\n * short bounded wait, finished or pending, and the caller reads it until\n * `isBillingPlanChangeStateFinal` says its state is final. What a change\n * does depends on the plan in force and the plan it names:\n *\n * - From `trial` or `none` to a paid plan, the change waits for the user in Stripe\n * Checkout and is applied once Stripe confirms the first payment.\n * - To a plan with a higher price, it is an upgrade: it takes effect at\n * once, a fresh period starts with the higher plan's whole allowance, what\n * was left of the old allowance expires, and Stripe charges the saved card\n * the higher plan's price less a credit for the unused part of the old\n * period. A\n * charge the card's issuer asks the user to authenticate waits for the\n * user; a declined charge fails the change with\n * `ERROR_CODE_PAYMENT_DECLINED` and leaves the plan as it was. An\n * upgrade the platform cannot make as priced fails with\n * `ERROR_CODE_PLAN_CHANGE_UNAVAILABLE`, with nothing charged and the plan\n * as it was.\n * - To a plan with a lower price, `none` included, it is scheduled for the\n * end of the current period, in place of any change scheduled before.\n * - To the plan in force, it undoes a scheduled change and is applied at\n * once; with nothing scheduled it changes nothing.\n *\n * A change made while another is pending supersedes it: the earlier one\n * fails with `ERROR_CODE_PLAN_CHANGE_SUPERSEDED`. A change is kept for a\n * while after it is final, and then reads HTTP 404.\n */\nexport interface BillingPlanChange {\n /** The change's ID, a canonical UUID, which `getPlanChange` reads. */\n readonly id: string;\n /** The plan the change is to. */\n readonly plan: BillingPlan;\n /** `pending`, `applied`, `scheduled` or `failed`. */\n readonly state: BillingPlanChangeState;\n /**\n * Why a failed change was not made: `ERROR_CODE_PAYMENT_DECLINED`,\n * `ERROR_CODE_ACTION_EXPIRED`, `ERROR_CODE_PLAN_CHANGE_SUPERSEDED` or\n * `ERROR_CODE_PLAN_CHANGE_UNAVAILABLE`.\n * Only a failed change carries one.\n */\n readonly reason?: string;\n /** The payment the user completes in Stripe, carried by a pending change that waits for one. */\n readonly action?: BillingAction;\n /**\n * When an applied change took effect, or when a scheduled change takes\n * effect; `undefined` while pending and once failed.\n */\n readonly effectiveAt?: string;\n}\n\n/**\n * A purchase of extra usage. Creating one answers within a short bounded\n * wait, finished or pending, and the caller reads it until\n * `isBillingPurchaseStateFinal` says its state is final. A purchase on an\n * Account with no saved card waits for the user in Stripe Checkout; one the\n * card's issuer asks the user to authenticate goes there too. An\n * auto-refill purchase is charged with no user present, so a charge that\n * needs the user fails it with `ERROR_CODE_PAYMENT_DECLINED` and turns\n * auto-refill off.\n */\nexport interface BillingPurchase {\n /** The purchase's ID, a canonical UUID, which `purchases.get` reads. */\n readonly id: string;\n /** `manual`, a purchase a user created, or `auto_refill`. */\n readonly kind: BillingPurchaseKind;\n /** The extra usage bought, before tax, in micro-dollars. */\n readonly amountMicros: number;\n /**\n * `pending`, which counts against the spend cap; `paid`, whose amount is\n * in the extra usage balance; or `failed`, which charged nothing and does\n * not count against the cap.\n */\n readonly state: BillingPurchaseState;\n /**\n * Why a failed purchase was not paid: `ERROR_CODE_PAYMENT_DECLINED` or\n * `ERROR_CODE_ACTION_EXPIRED`. Only a failed purchase carries one.\n */\n readonly reason?: string;\n /** The payment the user completes in Stripe, carried by a pending purchase that waits for one. */\n readonly action?: BillingAction;\n /** When the purchase was recorded, as an RFC 3339 instant. */\n readonly createdAt: string;\n}\n\n/**\n * A session of Stripe's customer portal, where the user manages the\n * Account's card, billing address and tax IDs and reads its invoices and\n * receipts. It is short-lived: open `url` in the user's browser at once and\n * create another for a later visit. The portal does not change plans.\n */\nexport interface BillingPortalSession {\n /**\n * The session's page, an absolute https URL. It signs whoever opens it in to\n * the Account's billing details, so show it only to the user who asked.\n */\n readonly url: string;\n}\n\n/**\n * Changes an Account's billing settings field by field: a field left out\n * keeps its value. The merged settings are judged as a whole: auto-refill\n * on with no cap is refused with `ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP`,\n * and auto-refill on for a plan without extra usage with\n * `ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN`. A refused update changes nothing.\n * Lowering the cap below what the period has bought already is allowed: it\n * refuses further purchases in the period.\n */\nexport interface UpdateBillingOptions extends CallOptions {\n /** Replaces the auto-refill setting whole. */\n readonly autoRefill?: BillingAutoRefill;\n /**\n * Replaces the spend cap, which must not be negative, in micro-dollars;\n * `null` removes the cap.\n */\n readonly spendCapMicros?: number | null;\n}\n\n/** Asks for the Account's plan to change. */\nexport interface CreatePlanChangeOptions extends CallOptions {\n /**\n * The plan to change to: one {@link AccountBillingStatus.plans} lists, or\n * the plan in force to undo a scheduled change.\n */\n readonly plan: BillingPlan;\n /**\n * Makes an equal retry within its window return the same change rather\n * than make a second one. At most 64 bytes.\n */\n readonly idempotencyKey?: string;\n}\n\n/**\n * Buys extra usage with the card the Account pays with. Only an Account on\n * a plan with extra usage can buy it (`ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN`),\n * and never past its spend cap (`ERROR_CODE_SPEND_CAP_REACHED`). A refused\n * purchase records nothing.\n */\nexport interface CreatePurchaseOptions extends CallOptions {\n /**\n * The extra usage to buy: a positive whole number of dollars, in\n * micro-dollars, before tax, which Stripe adds.\n */\n readonly amountMicros: number;\n /**\n * Makes an equal retry within its window return the same purchase rather\n * than charge twice. At most 64 bytes.\n */\n readonly idempotencyKey?: string;\n}\n\n/** The Account's purchases of extra usage, newest first, auto-refill purchases included. */\nexport interface BillingPurchases {\n /**\n * Buys extra usage. The answer is the purchase as it stood when IDYL's\n * short wait ended: paid or failed, or pending, in which case its\n * `action` may name a page the user completes in Stripe.\n *\n * @throws {@link TypeError} `amountMicros` is not a positive whole number\n * of dollars in micro-dollars, or `idempotencyKey` is not a string of at\n * most 64 bytes, before any request is sent\n * @throws {@link ApiError} IDYL refuses the purchase, such as with\n * `ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN` or `ERROR_CODE_SPEND_CAP_REACHED`;\n * a refused purchase records nothing\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n create(options: CreatePurchaseOptions): Promise<BillingPurchase>;\n /**\n * Reads one purchase.\n *\n * @param purchaseId - The purchase's `id`.\n * @throws {@link TypeError} `purchaseId` is not a canonical UUID, before\n * any request is sent\n * @throws {@link ApiError} IDYL refuses the read, such as with status 404\n * for a purchase the Account does not hold\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n get(purchaseId: string, options?: CallOptions): Promise<BillingPurchase>;\n /**\n * Every purchase, page by page.\n *\n * @throws {@link TypeError} `limit` is not a positive integer\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n list(options?: ListOptions): AsyncIterable<BillingPurchase>;\n /**\n * One page of the purchases.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, or\n * `continue` is not one a page of this listing returned, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n listPage(options?: PageOptions): Promise<Page<BillingPurchase>>;\n}\n\n/**\n * The billing of the Account the client's credential acts as. Read it when\n * a program starts and in the background: no wake, session or command\n * needs a billing read first, since each answers a billing refusal itself\n * (`isOutOfUsage`, `sizeNotInPlan`). Every request is judged before it is\n * sent: an invalid option or a malformed ID throws a `TypeError` and sends\n * nothing.\n *\n * @example\n * ```ts\n * import { MICROS_PER_DOLLAR } from \"@idyl-sh/sdk\";\n *\n * const { status } = await idyl.billing.get();\n * const left = (status.allowanceMicros - status.usedMicros) / MICROS_PER_DOLLAR;\n * console.log(`${status.plan}: $${left.toFixed(2)} of allowance left`);\n * console.log(`resets ${status.periodEnd}, standing ${status.standing}`);\n * ```\n */\nexport interface Billing {\n /**\n * The Account's billing.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n get(options?: CallOptions): Promise<AccountBilling>;\n /**\n * Changes the Account's billing settings and returns the billing that\n * results.\n *\n * @throws {@link TypeError} the update states no field, or a field is\n * invalid, before any request is sent\n * @throws {@link ApiError} IDYL refuses the settings, such as with\n * `ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP` or\n * `ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN`; a refused update changes\n * nothing\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n update(options: UpdateBillingOptions): Promise<AccountBilling>;\n /**\n * Asks for the Account's plan to change. The answer is the change as it\n * stood when IDYL's short wait ended: applied, scheduled or failed, or\n * pending, in which case its `action` may name a page the user completes\n * in Stripe.\n *\n * @throws {@link TypeError} `plan` is not in the form of a plan, or\n * `idempotencyKey` is not a string of at most 64 bytes, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the change, such as with\n * `ERROR_CODE_PLAN_NOT_OFFERED`\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n createPlanChange(\n options: CreatePlanChangeOptions,\n ): Promise<BillingPlanChange>;\n /**\n * Reads one plan change of the Account.\n *\n * @param planChangeId - The plan change's `id`.\n * @throws {@link TypeError} `planChangeId` is not a canonical UUID, before\n * any request is sent\n * @throws {@link ApiError} IDYL refuses the read, such as with status 404\n * for a change it does not keep\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n getPlanChange(\n planChangeId: string,\n options?: CallOptions,\n ): Promise<BillingPlanChange>;\n /**\n * Opens a session of Stripe's customer portal for the Account.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer cannot be read\n */\n createPortalSession(options?: CallOptions): Promise<BillingPortalSession>;\n /** The Account's purchases of extra usage. */\n readonly purchases: BillingPurchases;\n}\n\n/** Builds the billing of the Account the client's credential acts as. */\nexport function billing(\n context: (options?: CallOptions) => Promise<PlacementContext>,\n): Billing {\n const service = async (\n options: CallOptions | undefined,\n ): Promise<{\n readonly context: PlacementContext;\n readonly service: BillingService;\n }> => {\n const resolved = await context(options);\n return {\n context: resolved,\n service: billingService(resolved.state, resolved.scope.accountId),\n };\n };\n const listPage = async (\n options: PageOptions = {},\n ): Promise<Page<BillingPurchase>> => {\n const limit = requireLimit(options.limit);\n const offset = offsetOf(options.continue) ?? 0;\n const page = await (\n await service(options)\n ).service.purchases.list(\n {\n ...(limit === undefined ? {} : { limit }),\n ...(offset === 0 ? {} : { offset }),\n },\n signalOf(options),\n );\n return pageOf(\n page.items.map(purchaseOf),\n offsetContinue(offset, page.items.length, page.totalCount),\n );\n };\n return Object.freeze({\n async get(options: CallOptions = {}) {\n const resolved = await service(options);\n const { billing: record } = await resolved.service.get(signalOf(options));\n return await billingOf(record, resolved.context, options);\n },\n async update(options: UpdateBillingOptions) {\n const request = updateRequest(options);\n validateUpdateAccountBillingRequest(request);\n const resolved = await service(options);\n const { billing: record } = await resolved.service.update(\n request,\n signalOf(options),\n );\n return await billingOf(record, resolved.context, options);\n },\n async createPlanChange(options: CreatePlanChangeOptions) {\n if (typeof (options.plan as unknown) !== \"string\") {\n throw new TypeError(\"plan must be a string\");\n }\n const request = {\n plan: options.plan,\n ...keyOption(options.idempotencyKey),\n };\n validateCreateBillingPlanChangeRequest(request);\n const { planChange } = await (\n await service(options)\n ).service.createPlanChange(request, signalOf(options));\n return planChangeOf(planChange);\n },\n async getPlanChange(planChangeId: string, options: CallOptions = {}) {\n const id = parseBillingPlanChangeId(planChangeId);\n const { planChange } = await (\n await service(options)\n ).service.getPlanChange(id, signalOf(options));\n return planChangeOf(planChange);\n },\n async createPortalSession(options: CallOptions = {}) {\n const { portalSession } = await (\n await service(options)\n ).service.createPortalSession(signalOf(options));\n return portalSessionOf(portalSession);\n },\n purchases: Object.freeze({\n async create(options: CreatePurchaseOptions) {\n const request = {\n amountMicros: requireMicros(options.amountMicros, \"amountMicros\"),\n ...keyOption(options.idempotencyKey),\n };\n validateCreateBillingPurchaseRequest(request);\n const { purchase } = await (\n await service(options)\n ).service.purchases.create(request, signalOf(options));\n return purchaseOf(purchase);\n },\n async get(purchaseId: string, options: CallOptions = {}) {\n const id = parseBillingPurchaseId(purchaseId);\n const { purchase } = await (\n await service(options)\n ).service.purchases.get(id, signalOf(options));\n return purchaseOf(purchase);\n },\n list: (options: ListOptions = {}) => walk(listPage, options),\n listPage,\n }),\n });\n}\n\n/**\n * The settings update an option set states, its numbers judged as whole\n * numbers of micro-dollars before the update's own validation judges it.\n */\nfunction updateRequest(options: UpdateBillingOptions): {\n readonly autoRefill?: {\n readonly enabled: boolean;\n readonly amountMicros: number;\n };\n readonly spendCapMicros?: number | null;\n} {\n const { autoRefill, spendCapMicros } = options;\n if (\n autoRefill !== undefined &&\n (typeof (autoRefill as unknown) !== \"object\" ||\n (autoRefill as unknown) === null ||\n typeof (autoRefill.enabled as unknown) !== \"boolean\")\n ) {\n throw new TypeError(\n \"autoRefill must be an object with a boolean enabled and an amountMicros\",\n );\n }\n return {\n ...(autoRefill === undefined\n ? {}\n : {\n autoRefill: {\n enabled: autoRefill.enabled,\n amountMicros: requireMicros(\n autoRefill.amountMicros,\n \"autoRefill.amountMicros\",\n ),\n },\n }),\n ...(spendCapMicros === undefined\n ? {}\n : {\n spendCapMicros:\n spendCapMicros === null\n ? null\n : requireMicros(spendCapMicros, \"spendCapMicros\"),\n }),\n };\n}\n\n/** Judges an amount a caller states: a safe integer of micro-dollars. */\nfunction requireMicros(value: unknown, field: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n throw new TypeError(`${field} must be a whole number of micro-dollars`);\n }\n return value;\n}\n\n/** The idempotency key a caller states, as the request's own field. */\nfunction keyOption(key: unknown): { readonly idempotencyKey?: string } {\n if (key === undefined) return {};\n if (typeof key !== \"string\") {\n throw new TypeError(\"idempotencyKey must be a string\");\n }\n return { idempotencyKey: key };\n}\n\n/**\n * The public view of a served billing. The rates are the ones the\n * Account's Computers are charged: those of the place they live in when\n * its rate card differs from the default, read through the client's\n * placement only then, and the default rates otherwise.\n */\nasync function billingOf(\n record: AccountBillingRecord,\n context: PlacementContext,\n options: CallOptions,\n): Promise<AccountBilling> {\n const spec = objectOf(record.spec);\n const status = objectOf(record.status);\n const autoRefill = objectOf(spec[\"autoRefill\"]);\n const cap = spec[\"spendCapMicros\"];\n const scheduled = status[\"scheduledChange\"];\n const stopped = status[\"autoRefillStopped\"];\n const withheld = status[\"allowanceWithheld\"];\n return Object.freeze({\n spec: Object.freeze({\n autoRefill: Object.freeze({\n enabled: autoRefill[\"enabled\"] === true,\n amountMicros: micros(autoRefill[\"amountMicros\"]),\n }),\n ...(cap === undefined || cap === null\n ? {}\n : { spendCapMicros: micros(cap) }),\n }),\n status: Object.freeze({\n plan: text(status[\"plan\"]),\n periodStart: text(status[\"periodStart\"]),\n periodEnd: text(status[\"periodEnd\"]),\n allowanceMicros: micros(status[\"allowanceMicros\"]),\n ...(typeof withheld === \"string\" && withheld !== \"\"\n ? { allowanceWithheld: withheld }\n : {}),\n usedMicros: micros(status[\"usedMicros\"]),\n extraBalanceMicros: micros(status[\"extraBalanceMicros\"]),\n extraBoughtMicros: micros(status[\"extraBoughtMicros\"]),\n standing: text(status[\"standing\"]),\n lifecycle: text(status[\"lifecycle\"]),\n renewal: text(status[\"renewal\"]),\n largestSize: text(status[\"largestSize\"]),\n ...quantityText(\n \"storedData\",\n status[\"storedData\"] as VolumeQuantity | undefined,\n formatVolume,\n ),\n ...fileTerms(status),\n ...(isRecord(scheduled)\n ? {\n scheduledChange: Object.freeze({\n plan: text(scheduled[\"plan\"]),\n at: text(scheduled[\"at\"]),\n largestSize: text(scheduled[\"largestSize\"]),\n }),\n }\n : {}),\n ...(isRecord(stopped)\n ? {\n autoRefillStopped: Object.freeze({\n reason: text(stopped[\"reason\"]),\n at: text(stopped[\"at\"]),\n }),\n }\n : {}),\n hasInvoices: status[\"hasInvoices\"] === true,\n sizePlans: listOf(status[\"sizePlans\"], (item) =>\n Object.freeze({ size: text(item[\"size\"]), plan: text(item[\"plan\"]) }),\n ),\n plans: listOf(status[\"plans\"], (item) =>\n Object.freeze({\n plan: text(item[\"plan\"]),\n name: text(item[\"name\"]),\n priceMicros: micros(item[\"priceMicros\"]),\n allowanceMicros: micros(item[\"allowanceMicros\"]),\n largestSize: text(item[\"largestSize\"]),\n ...quantityText(\n \"storedData\",\n item[\"storedData\"] as VolumeQuantity | undefined,\n formatVolume,\n ),\n ...count(\"awakeVCPU\", item[\"awakeVCPU\"]),\n extraUsage: item[\"extraUsage\"] === true,\n }),\n ),\n sizeRates: await chargedRates(record, context, options),\n storageMicrosPerGiBMonth: micros(status[\"storageMicrosPerGiBMonth\"]),\n downloadMicrosPerGiB: micros(status[\"downloadMicrosPerGiB\"]),\n }),\n });\n}\n\n/**\n * The rates the Account's Computers are charged. The billing read names\n * the default rates and, apart, the rates of every place the Account may\n * use whose rate card differs; only when it names any is the client's one\n * place resolved to choose among them.\n */\nasync function chargedRates(\n record: AccountBillingRecord,\n context: PlacementContext,\n options: CallOptions,\n): Promise<readonly BillingSizeRate[]> {\n const status = objectOf(record.status);\n const overrides = status[\"subnetSizeRates\"];\n let rates: unknown = status[\"sizeRates\"];\n if (Array.isArray(overrides) && overrides.length > 0) {\n const { subnet } = await context.placement.resolve(\n context.scope.accountId,\n signalOf(options),\n );\n const own = (overrides as readonly unknown[]).find(\n (entry) => isRecord(entry) && entry[\"subnet\"] === subnet,\n );\n if (isRecord(own)) rates = own[\"sizeRates\"];\n }\n return listOf(rates, (item: Record<string, unknown>) =>\n Object.freeze({\n size: text(item[\"size\"]),\n perHourMicros: micros(item[\"perHourMicros\"]),\n ...optionalText(item, \"label\"),\n ...quantityText(\"cpu\", item[\"cpu\"] as CpuQuantity | undefined, formatCpu),\n ...quantityText(\n \"memory\",\n item[\"memory\"] as MemoryQuantity | undefined,\n formatMemory,\n ),\n ...quantityText(\n \"disk\",\n item[\"disk\"] as VolumeQuantity | undefined,\n formatVolume,\n ),\n ...(item[\"default\"] === true ? { default: true } : {}),\n } satisfies BillingSizeRate),\n );\n}\n\n/** The public view of a served plan change. */\nfunction planChangeOf(record: BillingPlanChangeRecord): BillingPlanChange {\n const change = objectOf(record);\n return Object.freeze({\n id: text(change[\"id\"]),\n plan: text(change[\"plan\"]),\n state: text(change[\"state\"]),\n ...optionalText(change, \"reason\"),\n ...actionOption(change[\"action\"]),\n ...optionalText(change, \"effectiveAt\"),\n });\n}\n\n/** The public view of a served purchase. */\nfunction purchaseOf(record: BillingPurchaseRecord): BillingPurchase {\n const purchase = objectOf(record);\n return Object.freeze({\n id: text(purchase[\"id\"]),\n kind: text(purchase[\"kind\"]),\n amountMicros: micros(purchase[\"amountMicros\"]),\n state: text(purchase[\"state\"]),\n ...optionalText(purchase, \"reason\"),\n ...actionOption(purchase[\"action\"]),\n createdAt: text(purchase[\"createdAt\"]),\n });\n}\n\n/** The public view of a served portal session. */\nfunction portalSessionOf(\n record: BillingPortalSessionRecord,\n): BillingPortalSession {\n return Object.freeze({ url: text(objectOf(record)[\"url\"]) });\n}\n\n/** A served payment page, when one is carried. */\nfunction actionOption(value: unknown): { readonly action?: BillingAction } {\n if (!isRecord(value)) return {};\n const action = value as Partial<Record<keyof BillingActionRecord, unknown>>;\n return {\n action: Object.freeze({\n kind: text(action.kind),\n url: text(action.url),\n expiresAt: text(action.expiresAt),\n }),\n };\n}\n\n/**\n * A served field that must be an object, such as a billing's `spec`; a\n * response without one cannot be read.\n */\nfunction objectOf(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new TransportError(\n \"invalid_response\",\n \"billing response carries no object where one is required\",\n );\n }\n return value;\n}\n\n/** A served list of objects, each through `view`; anything else reads as empty. */\nfunction listOf<T>(\n value: unknown,\n view: (item: Record<string, unknown>) => T,\n): readonly T[] {\n if (!Array.isArray(value)) return Object.freeze([]);\n return Object.freeze(\n value\n .filter((item): item is Record<string, unknown> => isRecord(item))\n .map(view),\n );\n}\n\n/** A served string, or the empty string when it is absent or not a string. */\nfunction text(value: unknown): string {\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** A served optional quantity in its spelling, present only when it has one. */\nfunction quantityText<K extends string, T>(\n key: K,\n value: T | undefined,\n format: (value: T) => string,\n): Readonly<Partial<Record<K, string>>> {\n const spelling = spelled(value, format);\n return (spelling === undefined ? {} : { [key]: spelling }) as Readonly<\n Partial<Record<K, string>>\n >;\n}\n\n/** A served optional count, present only when it is a positive safe integer. */\nfunction count<K extends string>(\n key: K,\n value: unknown,\n): Readonly<Partial<Record<K, number>>> {\n return (\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0\n ? { [key]: value }\n : {}\n ) as Readonly<Partial<Record<K, number>>>;\n}\n\n/**\n * The served terms on which the Account's files are kept, in milliseconds,\n * present only when the status states a retention.\n */\nfunction fileTerms(status: Record<string, unknown>): {\n readonly fileRetentionMs?: number;\n readonly deletionWarningsMs?: readonly number[];\n} {\n const retention = status[\"fileRetention\"] as Duration | undefined;\n if (retention === undefined || isZeroDuration(retention)) return {};\n const warnings = (status[\"deletionWarnings\"] ?? []) as readonly Duration[];\n return {\n fileRetentionMs: durationMilliseconds(retention),\n deletionWarningsMs: Object.freeze(warnings.map(durationMilliseconds)),\n };\n}\n\n/** A served optional string, present only when it is a non-empty string. */\nfunction optionalText<K extends string>(\n record: Record<string, unknown>,\n key: K,\n): Readonly<Partial<Record<K, string>>> {\n const value = record[key];\n return (\n typeof value === \"string\" && value !== \"\" ? { [key]: value } : {}\n ) as Readonly<Partial<Record<K, string>>>;\n}\n\n/**\n * A served amount of micro-dollars. An amount that is not a whole number\n * within `Number.MAX_SAFE_INTEGER` cannot be shown as the number it is, so\n * the response is refused rather than read as another amount.\n */\nfunction micros(value: unknown): number {\n if (typeof value === \"number\" && Number.isSafeInteger(value)) return value;\n if (value === undefined) return 0;\n throw new TransportError(\n \"invalid_response\",\n \"billing response carries an amount that is not a safe whole number\",\n );\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { integerEqual } from \"../internal/strictdecode.js\";\nimport type { Integer } from \"../resource/json.js\";\n/*\n * A wait is a client-side loop over reads, and the loop is the same for\n * every kind: read the object, evaluate the condition against it, stop on\n * met or failed, otherwise read again. What differs per kind is the\n * evaluation, and it is published here as a pure function per kind so that\n * every client, in every language, reaches the same verdict from the same\n * object. A service that waits delegates to its kind's evaluator; there is\n * never a second reading of the same state.\n *\n * Absence is the caller's judgement for every deleted wait: a read that\n * reports the resource gone is the condition met, and an object that can\n * still be read is pending whatever its phase.\n */\nimport type {\n Namespace,\n NamespaceResourceCount,\n NamespaceTermination,\n} from \"./namespace.js\";\nimport type { Computer } from \"./computer.js\";\nimport {\n computerSessionReasonClass,\n type ComputerSession,\n} from \"./computer-session.js\";\n\n/**\n * A lifecycle condition a wait can hold for. It is one vocabulary for every\n * kind a wait can address; which conditions a kind supports is the kind's\n * own contract, stated by its evaluator.\n *\n * - `ready`: a Computer session can be attached.\n * - `deleted`: the API no longer returns the resource; while the resource\n * is still observable the evaluation stays pending.\n */\nexport type WaitCondition = \"ready\" | \"deleted\";\n\n/**\n * The verdict of evaluating a condition against one object.\n *\n * - `pending`: not yet satisfied; further observation may satisfy it.\n * - `met`: satisfied; the wait ends successfully.\n * - `failed`: the object can no longer satisfy the condition, or the\n * condition is unsupported for the kind; the wait ends unsuccessfully.\n */\nexport type WaitState = \"pending\" | \"met\" | \"failed\";\n\n/** The pure evaluation of a condition against one object. */\nexport interface WaitEvaluation {\n readonly state: WaitState;\n /** Prose for a person; never a contract, never parsed. */\n readonly message: string;\n}\n\n/**\n * Evaluates a condition against a served Namespace. Only `deleted` applies,\n * and a Namespace that can still be read has not been deleted, so every\n * phase is pending: an active Namespace says it is not terminating, a\n * terminating one names what still holds finalization back, and a phase\n * this SDK does not name is reported as it arrived. Absence is the caller's\n * judgement, as it is for every deleted wait: a read that reports 404 is\n * the condition met.\n */\nexport function evaluateNamespaceWait(\n namespace: Namespace,\n condition: WaitCondition,\n): WaitEvaluation {\n switch (condition) {\n case \"deleted\":\n switch (namespace.phase) {\n case \"active\":\n return pending(`namespace ${namespace.name} is not terminating`);\n case \"terminating\":\n return pending(\n `namespace ${namespace.name} is terminating: ${namespaceHoldouts(namespace.termination)}`,\n );\n default:\n return pending(\n `namespace ${namespace.name} still exists in phase ${JSON.stringify(namespace.phase)}`,\n );\n }\n default:\n return unsupportedCondition(\"Namespace\", condition);\n }\n}\n\n/**\n * Evaluates a condition against a served Computer. Only `deleted` applies:\n * every phase is pending while the Computer can still be read, a\n * terminating one awaits finalization, and absence is the caller's\n * judgement from a read that reports 404.\n */\nexport function evaluateComputerWait(\n computer: Computer,\n condition: WaitCondition,\n): WaitEvaluation {\n switch (condition) {\n case \"deleted\":\n switch (computer.phase) {\n case \"active\":\n return pending(`computer ${computer.name} is not terminating`);\n case \"terminating\":\n return pending(\n `computer ${computer.name} is terminating: ${AWAITING_FINALIZATION}`,\n );\n default:\n return pending(\n `computer ${computer.name} still exists in phase ${JSON.stringify(computer.phase)}`,\n );\n }\n default:\n return unsupportedCondition(\"Computer\", condition);\n }\n}\n\n/**\n * Evaluates a condition against a served Computer session. Only `ready`\n * applies. A ready session meets it; a pending session, and one in a phase\n * this SDK does not name, is pending; a session that is attached already,\n * or that ended, failed, or was cancelled, can no longer become ready and\n * fails it. The message appends the session's reason in parentheses when it\n * states one this SDK names.\n */\nexport function evaluateComputerSessionWait(\n session: ComputerSession,\n condition: WaitCondition,\n): WaitEvaluation {\n if (condition !== \"ready\") {\n return unsupportedCondition(\"ComputerSession\", condition);\n }\n const stated = session.status.reason ?? \"\";\n const reason =\n computerSessionReasonClass(stated) === undefined ? \"\" : ` (${stated})`;\n switch (session.status.phase) {\n case \"ready\":\n return met(\"computer session is ready\");\n case \"pending\":\n return pending(`computer session is pending${reason}`);\n case \"attached\":\n return failure(\"computer session is already attached\");\n case \"ended\":\n return failed(`computer session has ended${reason}`);\n case \"failed\":\n return failed(`computer session failed${reason}`);\n case \"cancelled\":\n return failed(`computer session was cancelled${reason}`);\n default:\n return pending(\n \"computer session is in a phase this version does not name\",\n );\n }\n}\n\n/**\n * The holdout message for a terminating object that nothing holds back any\n * more: the platform has drained it and has not yet finalized it.\n */\nconst AWAITING_FINALIZATION = \"awaiting finalization\";\n\n/**\n * Names what keeps a terminating Namespace from finalizing, in the\n * platform's order: the Computers still to finalize, then each zone that\n * has not acknowledged or still reports live resources.\n */\nfunction namespaceHoldouts(\n termination: NamespaceTermination | undefined,\n): string {\n if (termination === undefined) return AWAITING_FINALIZATION;\n const holdouts: string[] = [];\n if (termination.computersRemaining > 0) {\n holdouts.push(\n `${countNoun(termination.computersRemaining, \"computer\")} remaining`,\n );\n }\n for (const zone of termination.zones) {\n if (!zone.acknowledged) {\n holdouts.push(`${zone.zone} unacknowledged`);\n continue;\n }\n const remaining = remainingByKind(zone.remaining);\n if (remaining !== \"\") holdouts.push(`${zone.zone}: ${remaining}`);\n }\n return holdouts.length === 0 ? AWAITING_FINALIZATION : holdouts.join(\"; \");\n}\n\n/**\n * Renders the kinds a zone still holds, as `<kind> 2, <kind> 1`, leaving out\n * kinds it reports at zero.\n */\nfunction remainingByKind(counts: readonly NamespaceResourceCount[]): string {\n return counts\n .filter((count) => count.count > 0)\n .map((count) => `${count.kind} ${String(count.count)}`)\n .join(\", \");\n}\n\n/** Renders a count with its noun, pluralized with a trailing `s`. */\nfunction countNoun(count: Integer, noun: string): string {\n return integerEqual(count, 1) ? `1 ${noun}` : `${String(count)} ${noun}s`;\n}\n\n/**\n * The one verdict for a condition a kind does not have, whichever kind\n * vocabulary names the kind.\n */\nfunction unsupportedCondition(\n kind: string,\n condition: WaitCondition,\n): WaitEvaluation {\n return failed(\n `condition ${JSON.stringify(condition)} is not supported for ${kind}`,\n );\n}\n\nfunction pending(message: string): WaitEvaluation {\n return { state: \"pending\", message };\n}\n\nfunction met(message: string): WaitEvaluation {\n return { state: \"met\", message };\n}\n\nfunction failed(message: string): WaitEvaluation {\n return { state: \"failed\", message };\n}\n\nfunction failure(message: string): WaitEvaluation {\n return { state: \"failed\", message };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/**\n * How long a Computer keeps its execution after its last session ends.\n * Every session counts, exec and shell alike, from its creation until it\n * ends. When the timeout passes with no session, the platform releases the\n * compute held for the Computer and the Computer becomes dormant; its\n * durable state is retained, and the next session wakes it.\n *\n * The value is {@link IDLE_TIMEOUT_NEVER}, or a whole number followed by one\n * unit, `s` for seconds, `m` for minutes or `h` for hours, written without a\n * sign or leading zeros and totaling at least {@link MIN_IDLE_TIMEOUT_MS}:\n * `0s`, `90s`, `5m` and `2h` are timeouts. Zero releases execution as soon\n * as it is idle; never is spelled out. A value larger than a signed\n * 64-bit nanosecond count can hold, about 292 years, is refused.\n *\n * The platform states a Computer's timeout canonically, as a whole number\n * of seconds with `s` or as `never`, so a Computer declared with `5m` reads\n * back as `300s`. {@link parseIdleTimeout} returns the same canonical\n * spelling.\n *\n * The type is a string and has no codec of its own: the wire carries any\n * token it is given, and {@link validateIdleTimeout} judges it.\n */\nexport type IdleTimeout = string;\n\n/**\n * The timeout that keeps a Computer awake: it is never released for being\n * idle, its execution is held, and billed, until a caller puts it to sleep\n * with `computer.sleep()` or deletes it. Processes left running in the\n * background keep running until then.\n */\nexport const IDLE_TIMEOUT_NEVER: IdleTimeout = \"never\";\n\n/** The timeout of a Computer that states none. */\nexport const DEFAULT_IDLE_TIMEOUT: IdleTimeout = \"300s\";\n\n/** The shortest finite idle timeout, in milliseconds: zero. */\nexport const MIN_IDLE_TIMEOUT_MS = 0;\n\nconst MIN_IDLE_TIMEOUT_SECONDS = 0n;\n\n/** The largest whole number of seconds a signed 64-bit nanosecond count holds. */\nconst MAX_IDLE_TIMEOUT_SECONDS = ((1n << 63n) - 1n) / 1_000_000_000n;\n\nconst UNIT_SECONDS: ReadonlyMap<string, bigint> = new Map([\n [\"s\", 1n],\n [\"m\", 60n],\n [\"h\", 3600n],\n]);\n\n/**\n * Validates `raw` and returns it in the canonical spelling the platform\n * states: `never`, or the whole number of seconds followed by `s`. Throws a\n * `TypeError` with the sentence {@link validateIdleTimeout} would throw.\n */\nexport function parseIdleTimeout(raw: string): IdleTimeout {\n const seconds = idleTimeoutSeconds(raw);\n return seconds === undefined ? IDLE_TIMEOUT_NEVER : `${String(seconds)}s`;\n}\n\n/**\n * The canonical idle timeout of `milliseconds`, which must be a whole\n * number of seconds and at least {@link MIN_IDLE_TIMEOUT_MS}. Throws a\n * `TypeError` otherwise.\n */\nexport function idleTimeoutFromMilliseconds(milliseconds: number): IdleTimeout {\n if (!Number.isSafeInteger(milliseconds) || milliseconds % 1000 !== 0) {\n throw new TypeError(\"idle timeout must be a whole number of seconds\");\n }\n if (milliseconds < MIN_IDLE_TIMEOUT_MS) {\n throw new TypeError(\"idle timeout must be non-negative\");\n }\n return `${String(milliseconds / 1000)}s`;\n}\n\n/**\n * Judges that the timeout is `never` or a finite timeout in the grammar\n * {@link IdleTimeout} documents. The empty string is reported as missing.\n * Refusals are fixed sentences and never repeat the value. Throws a\n * `TypeError`.\n */\nexport function validateIdleTimeout(timeout: IdleTimeout): void {\n idleTimeoutSeconds(timeout);\n}\n\n/** Whether the timeout is {@link IDLE_TIMEOUT_NEVER}. */\nexport function isIdleTimeoutNever(timeout: IdleTimeout): boolean {\n return timeout === IDLE_TIMEOUT_NEVER;\n}\n\n/**\n * The length of a finite timeout in milliseconds. `never` has no length and\n * is refused, as is a value {@link validateIdleTimeout} refuses; both throw\n * a `TypeError`. A timeout longer than `Number.MAX_SAFE_INTEGER`\n * milliseconds is returned rounded to the nearest representable number.\n */\nexport function idleTimeoutMilliseconds(timeout: IdleTimeout): number {\n const seconds = idleTimeoutSeconds(timeout);\n if (seconds === undefined) {\n throw new TypeError(\"idle timeout never has no duration\");\n }\n return Number(seconds * 1000n);\n}\n\n/**\n * Judges `raw` against the grammar and returns the timeout in seconds, or\n * `undefined` for never.\n */\nfunction idleTimeoutSeconds(raw: string): bigint | undefined {\n if (raw === \"\") throw new TypeError(\"idle timeout is required\");\n if (raw === IDLE_TIMEOUT_NEVER) return undefined;\n const digits = raw.slice(0, -1);\n const multiplier = UNIT_SECONDS.get(raw.slice(-1));\n if (\n multiplier === undefined ||\n !/^[0-9]+$/u.test(digits) ||\n (digits.length > 1 && digits.startsWith(\"0\"))\n ) {\n throw new TypeError(\n 'idle timeout must be \"never\" or a whole number followed by s, m, or h, such as \"300s\", \"5m\", or \"1h\"',\n );\n }\n const value = BigInt(digits);\n if (value > MAX_IDLE_TIMEOUT_SECONDS / multiplier) {\n throw new TypeError(\"idle timeout is longer than a duration can represent\");\n }\n const seconds = value * multiplier;\n if (seconds < MIN_IDLE_TIMEOUT_SECONDS) {\n throw new TypeError(\"idle timeout must be non-negative\");\n }\n return seconds;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/** Computer list selection through `ListOptions.filter`. */\nexport type ComputerOwnerFilter =\n \"unowned\" | \"all\" | (string & Record<never, never>);\n\n/**\n * Accepts the default and the named selectors; ordinary scope\n * authorization is still required. Throws a `TypeError`.\n */\nexport function validateComputerOwnerFilter(value: ComputerOwnerFilter): void {\n if (value === \"\" || value === \"unowned\" || value === \"all\") return;\n throw new TypeError(\"invalid computer owner filter\");\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\nimport { integerText, isUint64 } from \"../internal/strictdecode.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { encodeBase64, decodeBase64 } from \"../resource/base64.js\";\nimport { isWellFormed, prefixed } from \"../resource/validation.js\";\nimport {\n type Shape,\n always,\n array,\n decodeValue,\n integer,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n} from \"../internal/strictdecode.js\";\nimport { type JsonObject } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport { type StorageOperationId } from \"../resource/uuid-id.js\";\nimport { type PageOptions, pageOptionsFields } from \"./storage.js\";\nimport type { FileStatus } from \"./file-status.js\";\n\n/**\n * The length of every piece of a file but its last. A file of `size` bytes has\n * `size / FILE_PIECE_BYTES` pieces, rounded up, and an empty file has none.\n */\nexport const FILE_PIECE_BYTES = 4 * 1024 * 1024;\n\n/** The length of one piece hash in a pieces list. */\nexport const FILE_PIECE_HASH_BYTES = 32;\n\n/** The PAX record that states a regular file's tag in a saved tree archive. */\nexport const ARCHIVE_TAG_RECORD = \"comment\";\n\n/** FilePath preserves a relative POSIX path as UTF-8 or standard padded base64, exactly one. A pointer to an empty Path explicitly addresses the root. Existing byte names may be read or deleted without normalization. */\nexport interface FilePath {\n readonly path?: string;\n readonly pathBase64?: string;\n}\n\n/**\n * FileEntry is one saved child, preserving names and symlink targets as exact UTF-8 or padded base64. Size is the logical file length, not the size measure. Mode contains permission bits only; zero sizes are written.\n *\n * `sha256` is the SHA-256 of a file's bytes and `tag` its public content hash, the value `fileTagOfPieces` computes. Either may be absent from a listing where stating it would take more than the listing reads. A read's `ETag` always states the tag.\n *\n * `status` says whether the entry's content is safe in the store, and `statusReason` why it is not when `status` is `conflict` or `failed`. A listing of the latest saved version states it on every entry. A listing of a named version omits it, since every entry of a saved version is in the store.\n */\nexport interface FileEntry {\n readonly name?: string;\n readonly nameBase64?: string;\n readonly type: FileEntryType;\n readonly mode: number;\n readonly size: Integer;\n readonly sha256?: string;\n readonly tag?: string;\n readonly target?: string;\n readonly targetBase64?: string;\n readonly status?: FileStatus;\n readonly statusReason?: string;\n}\n\n/** FileListOptions selects children of a saved path, or save-first with update permission. Version omitted means the latest saved version. */\nexport interface FileListOptions extends PageOptions, FilePath {\n readonly version?: string;\n}\n\n/** FileReadOptions selects saved content or a POSIX archive. Save-first reads exactly the version returned by its save, reported in Idyl-Saved-Version. */\nexport interface FileReadOptions extends FilePath {\n readonly version?: string;\n}\n\n/**\n * CreateFileDownloadLinkRequest names one saved file or directory at one version, for a link that a browser or another program without credentials can read. Version omitted means the latest saved version, and the link stays on the version it resolved to.\n */\nexport interface CreateFileDownloadLinkRequest extends FilePath {\n readonly version?: string;\n}\n\n/**\n * FileDownloadLink is a read-only address of one saved file or directory at one version. Whoever holds `url` can read those bytes until `expiresAt`, with no other credential, so it is handled as a secret. A directory is served as a POSIX tar archive. The link answers range requests, so a browser's download manager can resume it. Its bytes count as the Account's downloads.\n */\nexport interface FileDownloadLink {\n readonly url: string;\n readonly expiresAt: string;\n readonly version: Integer;\n}\n\n/** ContentFacts is what a read of saved content would serve: its strong entity tag, its length in bytes, and the saved version it belongs to. */\nexport interface ContentFacts {\n readonly etag: string;\n readonly size: number;\n readonly version: Integer;\n}\n\n/** ContentRange asks for `length` bytes from `offset` of the bytes `etag` names. */\nexport interface ContentRange {\n readonly offset: number;\n readonly length: number;\n readonly etag: string;\n}\n\n/** CreateUploadRequest chooses a base version; undefined uses the current files head. An equal `idempotencyKey` retry returns its recorded outcome without a new effect. */\nexport interface CreateUploadRequest {\n readonly base?: Integer;\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. The journal entry it makes\n * records it, as `unknown` when it is absent; it is informative and never\n * authorizes anything.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/**\n * UploadDelivery reports the running writer's application of a published\n * upload. `reason` states why the last attempt failed while `state` is\n * `retrying`, and why the delivery ended while it is `failed`.\n *\n * `replacedCount` counts the delivered paths that met the running\n * Computer's unsaved work, and `replaced` names the first 100 of them in\n * byte order of their path; the replaced paths listing pages through all of\n * them. Both are reported once `state` is `applied`. A publish to a running\n * Computer answers once the writer applied the upload or its delivery\n * failed, waiting at most 10 seconds; past that wait `state` is `pending`\n * or `retrying` and the writer receives the upload later, in publication\n * order.\n */\nexport interface UploadDelivery {\n readonly state: DeliveryState;\n readonly replacedCount: Integer;\n readonly replaced?: readonly UploadReplacedPath[];\n readonly reason?: string;\n}\n\n/**\n * UploadReplacedPath is one delivered path that met unsaved work on the\n * running Computer. When `landedAt` is set, both copies are kept: the\n * Computer's own copy keeps the path and the uploaded copy is at\n * `landedAt`, in the same folder. When it is absent, the uploaded copy\n * replaced the Computer's copy at the path.\n */\nexport interface UploadReplacedPath extends FilePath {\n readonly landedAt?: FilePath;\n}\n\n/** Upload reports staging activity, its terminal outcome and optional delivery. While bytes arrive there is no elapsed transfer limit; inactivity is measured by the server, independently of the caller's context deadline. */\nexport interface Upload {\n readonly id: StorageOperationId;\n readonly state: UploadState;\n readonly base: Integer;\n readonly lastActivityAt?: string;\n readonly idleExpiresAt?: string;\n readonly version?: Integer;\n readonly delivery?: UploadDelivery;\n readonly reason?: string;\n}\n\n/** UploadFileOptions identifies one sequenced file stream. Resume verifies the accepted prefix from byte zero before sending further bounded parts. */\nexport interface UploadFileOptions extends FilePath {\n readonly mode: number;\n readonly seq: Integer;\n}\n\n/** UploadArchiveOptions streams a POSIX tar rooted at Path. Each archive entry is validated by the server; the SDK retains one bounded part without unpacking the stream. */\nexport interface UploadArchiveOptions extends FilePath {\n readonly seq: Integer;\n}\n\n/** FileRename moves an existing byte path to a new UTF-8 NFC path. */\nexport interface FileRename {\n readonly from: FilePath;\n readonly to: FilePath;\n}\n\n/** UploadChangesRequest records one ordered page of deletes and renames. */\nexport interface UploadChangesRequest {\n readonly seq: Integer;\n readonly delete?: readonly FilePath[];\n readonly rename?: readonly FileRename[];\n}\n\n/** UploadChangeReceipt records atomic acceptance and the server-computed payload fingerprint. A repeated sequence with different content is refused. */\nexport interface UploadChangeReceipt {\n readonly seq: Integer;\n readonly fingerprint: string;\n}\n\n/** PublishUploadRequest gives publication an optional retained retry identity. */\nexport interface PublishUploadRequest {\n readonly idempotencyKey?: string;\n}\n\n/** Supported file entry type tokens; responses also carry newer tokens. */\nexport type FileEntryType =\n \"file\" | \"dir\" | \"symlink\" | (string & Record<never, never>);\n/** Judges file entry type membership without rejecting newer values on read. */\nexport function validateFileEntryType(value: FileEntryType): void {\n if ([\"file\", \"dir\", \"symlink\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"file entry type is required\");\n throw new TypeError(`unknown file entry type ${JSON.stringify(value)}`);\n}\n\n/** Supported upload state tokens; responses also carry newer tokens. */\nexport type UploadState =\n | \"open\"\n | \"published\"\n | \"cancelled\"\n | \"expired\"\n | \"conflict\"\n | \"failed\"\n | (string & Record<never, never>);\n/** Judges upload state membership without rejecting newer values on read. */\nexport function validateUploadState(value: UploadState): void {\n if (\n [\n \"open\",\n \"published\",\n \"cancelled\",\n \"expired\",\n \"conflict\",\n \"failed\",\n ].includes(value)\n )\n return;\n if (value === \"\") throw new TypeError(\"upload state is required\");\n throw new TypeError(`unknown upload state ${JSON.stringify(value)}`);\n}\n\n/** Supported delivery state tokens; responses also carry newer tokens. */\nexport type DeliveryState =\n \"pending\" | \"applied\" | \"retrying\" | (string & Record<never, never>);\n/** Judges delivery state membership without rejecting newer values on read. */\nexport function validateDeliveryState(value: DeliveryState): void {\n if ([\"pending\", \"applied\", \"retrying\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"delivery state is required\");\n throw new TypeError(`unknown delivery state ${JSON.stringify(value)}`);\n}\n\n/** The canonical wire fields of FilePath. */\nexport const filePathFields = {\n path: pointer(string()),\n pathBase64: pointer(string()),\n};\n/** The canonical wire shape of FilePath. */\nexport const filePathShape: Shape<FilePath> = object<FilePath>(filePathFields);\n\n/** The canonical wire fields of FileEntry. */\nexport const fileEntryFields = {\n name: pointer(string()),\n nameBase64: pointer(string()),\n type: always(string<FileEntryType>()),\n mode: always(integer({ unsigned: true, bits: 32 })),\n size: always(integer({ unsigned: true, bits: 64 })),\n sha256: omitEmpty(string()),\n tag: omitEmpty(string()),\n target: pointer(string()),\n targetBase64: pointer(string()),\n status: omitEmpty(string<FileStatus>()),\n statusReason: omitEmpty(string()),\n};\n/** The canonical wire shape of FileEntry. */\nexport const fileEntryShape: Shape<FileEntry> =\n object<FileEntry>(fileEntryFields);\n\n/** The canonical wire shape of CreateFileDownloadLinkRequest. */\nexport const createFileDownloadLinkRequestShape: Shape<CreateFileDownloadLinkRequest> =\n object<CreateFileDownloadLinkRequest>({\n ...filePathFields,\n version: omitEmpty(string()),\n });\n\n/** The canonical wire shape of FileDownloadLink. */\nexport const fileDownloadLinkShape: Shape<FileDownloadLink> =\n object<FileDownloadLink>({\n url: always(string()),\n expiresAt: always(timestampShape),\n version: always(integer({ unsigned: false, bits: 64 })),\n });\n\n/** The canonical wire fields of CreateUploadRequest. */\nexport const createUploadRequestFields = {\n base: pointer(integer({ unsigned: false, bits: 64 })),\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n};\n/** The canonical wire shape of CreateUploadRequest. */\nexport const createUploadRequestShape: Shape<CreateUploadRequest> =\n object<CreateUploadRequest>(createUploadRequestFields);\n\n/** The canonical wire fields of UploadReplacedPath. */\nexport const uploadReplacedPathFields = {\n ...filePathFields,\n landedAt: pointer(filePathShape),\n};\n/** The canonical wire shape of UploadReplacedPath. */\nexport const uploadReplacedPathShape: Shape<UploadReplacedPath> =\n object<UploadReplacedPath>(uploadReplacedPathFields);\n\n/** The canonical wire fields of UploadDelivery. */\nexport const uploadDeliveryFields = {\n state: always(string<DeliveryState>()),\n replacedCount: always(integer({ unsigned: true, bits: 64 })),\n replaced: omitEmpty(array(uploadReplacedPathShape)),\n reason: omitEmpty(string()),\n};\n/** The canonical wire shape of UploadDelivery. */\nexport const uploadDeliveryShape: Shape<UploadDelivery> =\n object<UploadDelivery>(uploadDeliveryFields);\n\n/** The canonical wire fields of UploadChangeReceipt. */\nexport const uploadChangeReceiptFields = {\n seq: always(integer({ unsigned: true, bits: 64 })),\n fingerprint: always(string()),\n};\n/** The canonical wire shape of UploadChangeReceipt. */\nexport const uploadChangeReceiptShape: Shape<UploadChangeReceipt> =\n object<UploadChangeReceipt>(uploadChangeReceiptFields);\n\n/** The canonical wire fields of PublishUploadRequest. */\nexport const publishUploadRequestFields = {\n idempotencyKey: omitEmpty(string()),\n};\n/** The canonical wire shape of PublishUploadRequest. */\nexport const publishUploadRequestShape: Shape<PublishUploadRequest> =\n object<PublishUploadRequest>(publishUploadRequestFields);\n\n/** The canonical wire fields of FileListOptions. */\nexport const fileListOptionsFields = {\n ...pageOptionsFields,\n ...filePathFields,\n version: omitEmpty(string()),\n};\n/** The canonical wire shape of FileListOptions. */\nexport const fileListOptionsShape: Shape<FileListOptions> =\n object<FileListOptions>(fileListOptionsFields);\n\n/** The canonical wire fields of FileReadOptions. */\nexport const fileReadOptionsFields = {\n ...filePathFields,\n version: omitEmpty(string()),\n};\n/** The canonical wire shape of FileReadOptions. */\nexport const fileReadOptionsShape: Shape<FileReadOptions> =\n object<FileReadOptions>(fileReadOptionsFields);\n\n/** The canonical wire fields of Upload. */\nexport const uploadFields = {\n id: always(string<StorageOperationId>()),\n state: always(string<UploadState>()),\n base: always(integer({ unsigned: false, bits: 64 })),\n lastActivityAt: omitZero(timestampShape),\n idleExpiresAt: omitZero(timestampShape),\n version: pointer(integer({ unsigned: false, bits: 64 })),\n delivery: pointer(uploadDeliveryShape),\n reason: omitEmpty(string()),\n};\n/** The canonical wire shape of Upload. */\nexport const uploadShape: Shape<Upload> = object<Upload>(uploadFields);\n\n/** The canonical wire fields of UploadFileOptions. */\nexport const uploadFileOptionsFields = {\n ...filePathFields,\n mode: always(integer({ unsigned: true, bits: 32 })),\n seq: always(integer({ unsigned: true, bits: 64 })),\n};\n/** The canonical wire shape of UploadFileOptions. */\nexport const uploadFileOptionsShape: Shape<UploadFileOptions> =\n object<UploadFileOptions>(uploadFileOptionsFields);\n\n/** The canonical wire fields of UploadArchiveOptions. */\nexport const uploadArchiveOptionsFields = {\n ...filePathFields,\n seq: always(integer({ unsigned: true, bits: 64 })),\n};\n/** The canonical wire shape of UploadArchiveOptions. */\nexport const uploadArchiveOptionsShape: Shape<UploadArchiveOptions> =\n object<UploadArchiveOptions>(uploadArchiveOptionsFields);\n\n/** The canonical wire fields of FileRename. */\nexport const fileRenameFields = {\n from: always(filePathShape),\n to: always(filePathShape),\n};\n/** The canonical wire shape of FileRename. */\nexport const fileRenameShape: Shape<FileRename> =\n object<FileRename>(fileRenameFields);\n\n/** The canonical wire fields of UploadChangesRequest. */\nexport const uploadChangesRequestFields = {\n seq: always(integer({ unsigned: true, bits: 64 })),\n delete: omitEmpty(array(filePathShape)),\n rename: omitEmpty(array(fileRenameShape)),\n};\n/** The canonical wire shape of UploadChangesRequest. */\nexport const uploadChangesRequestShape: Shape<UploadChangesRequest> =\n object<UploadChangesRequest>(uploadChangesRequestFields);\n\n/** Reads a served FileEntry leniently, carrying unknown fields and tokens. */\nexport function decodeFileEntry(document: unknown): FileEntry {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n fileEntryShape,\n \"lenient\",\n );\n}\n/** Renders FileEntry with the public wire omission rules and explicit zero counts. */\nexport function encodeFileEntry(value: FileEntry): JsonObject {\n return fileEntryShape.encode(value) as JsonObject;\n}\n\n/** Reads a served Upload leniently, carrying unknown fields and tokens. */\nexport function decodeUpload(document: unknown): Upload {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n uploadShape,\n \"lenient\",\n );\n}\n/** Renders Upload with the public wire omission rules and explicit zero counts. */\nexport function encodeUpload(value: Upload): JsonObject {\n return uploadShape.encode(value) as JsonObject;\n}\n\n/** Copies path bytes into their lossless UTF-8 or canonical padded-base64 representation. */\nexport function newFilePath(bytes: Uint8Array): FilePath {\n try {\n return {\n path: new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n bytes,\n ),\n };\n } catch {\n return { pathBase64: encodeBase64(bytes) };\n }\n}\n/** Checks an existing relative POSIX path and returns independently owned bytes. */\nexport function filePathBytes(path: FilePath): Uint8Array {\n if ((path.path !== undefined) === (path.pathBase64 !== undefined))\n throw new TypeError(\"exactly one path or pathBase64 is required\");\n let bytes: Uint8Array;\n if (path.path !== undefined) {\n if (!isWellFormed(path.path))\n throw new TypeError(\"path must be UTF-8; use pathBase64 for byte names\");\n bytes = new TextEncoder().encode(path.path);\n } else {\n const base64 = path.pathBase64 ?? \"\";\n if (base64.length > 5460)\n throw new TypeError(\"path exceeds the Linux path bound\");\n try {\n bytes = decodeBase64(base64);\n } catch {\n throw new TypeError(\"pathBase64 must be canonical padded base64\");\n }\n if (encodeBase64(bytes) !== base64)\n throw new TypeError(\"pathBase64 must be canonical padded base64\");\n }\n if (bytes.length > 4095)\n throw new TypeError(\"path exceeds the Linux path bound\");\n if (bytes.includes(0) || bytes[0] === 47)\n throw new TypeError(\"path must be relative and contain no NUL\");\n if (bytes.length !== 0) {\n let start = 0;\n for (let index = 0; index <= bytes.length; index += 1) {\n if (index !== bytes.length && bytes[index] !== 47) continue;\n const length = index - start;\n if (\n length === 0 ||\n length > 255 ||\n (length === 1 && bytes[start] === 46) ||\n (length === 2 && bytes[start] === 46 && bytes[start + 1] === 46)\n )\n throw new TypeError(\"path has an invalid Linux component\");\n start = index + 1;\n }\n }\n return bytes;\n}\n/** Checks an existing path without imposing new-name normalization. */\nexport function validateFilePath(path: FilePath): void {\n filePathBytes(path);\n}\n/** Refuses authority-owned runtime paths while retaining existing byte names. */\nexport function validateFilePathMutation(path: FilePath): void {\n const bytes = filePathBytes(path);\n const text = new TextDecoder(\"utf-8\", { ignoreBOM: true }).decode(bytes);\n if (text === \".runtime\" || text.startsWith(\".runtime/\"))\n throw new TypeError(\"path names authority-owned runtime state\");\n}\n/** Requires UTF-8 NFC for new names without normalizing their bytes. */\nexport function validateFilePathCreate(path: FilePath): void {\n validateFilePathMutation(path);\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(\n filePathBytes(path),\n );\n } catch {\n throw new TypeError(\"new path names must be UTF-8 NFC\");\n }\n if (text.normalize(\"NFC\") !== text)\n throw new TypeError(\"new path names must be UTF-8 NFC\");\n}\n/** Checks a listed saved byte path; version resolution remains a server decision. */\nexport function validateFileListOptions(options: FileListOptions): void {\n if (options.version !== undefined)\n fileListOptionsFields.version.shape.decode(options.version, \"version\");\n validateFilePath(options);\n}\n/** Checks an existing byte path for content or archive reads. */\nexport function validateFileReadOptions(options: FileReadOptions): void {\n if (options.version !== undefined)\n fileReadOptionsFields.version.shape.decode(options.version, \"version\");\n validateFilePath(options);\n}\n/** Checks the path, and refuses a save, which a link must not start. */\nexport function validateCreateFileDownloadLinkRequest(\n request: CreateFileDownloadLinkRequest,\n): void {\n if (request.version === \"save-first\")\n throw new TypeError(\"a download link cannot save first\");\n validateFilePath(request);\n}\n/** Checks a requested upload base and a stated client before submission. */\nexport function validateCreateUploadRequest(\n request: CreateUploadRequest,\n): void {\n if (request.base !== undefined && request.base < 0)\n throw new TypeError(\"upload base must be non-negative\");\n validateStatedClient(request.client);\n}\n/** Checks a new file's byte path, permission bits and positive sequence. */\nexport function validateUploadFileOptions(options: UploadFileOptions): void {\n if (!isUint64(options.seq) || options.seq <= 0)\n throw new TypeError(\"upload sequence must be positive\");\n uploadFileOptionsFields.mode.shape.decode(options.mode, \"mode\");\n if (options.mode > 0o777)\n throw new TypeError(\"mode contains non-permission bits\");\n validateFilePathCreate(options);\n if (filePathBytes(options).length === 0)\n throw new TypeError(\"file path must not be the root\");\n}\n/** Checks an archive prefix and positive sequence without buffering or unpacking the stream. */\nexport function validateUploadArchiveOptions(\n options: UploadArchiveOptions,\n): void {\n if (!isUint64(options.seq) || options.seq <= 0)\n throw new TypeError(\"upload sequence must be positive\");\n validateFilePathCreate(options);\n}\n/** Checks ordered delete/rename operands; conflicts remain server decisions. */\nexport function validateUploadChangesRequest(\n request: UploadChangesRequest,\n): void {\n if (!isUint64(request.seq) || request.seq <= 0)\n throw new TypeError(\"upload sequence must be positive\");\n (request.delete ?? []).forEach((path, index) => {\n prefixed(`delete[${String(index)}]`, () => {\n validateFilePathMutation(path);\n });\n });\n (request.rename ?? []).forEach((path, index) => {\n prefixed(`rename[${String(index)}].from`, () => {\n validateFilePathMutation(path.from);\n });\n prefixed(`rename[${String(index)}].to`, () => {\n validateFilePathCreate(path.to);\n });\n });\n}\n/** Owns one raw streaming response; version zero remains distinct from an unreported version. */\nexport interface StoredContent {\n readonly body: ReadableStream<Uint8Array>;\n readonly etag: string;\n readonly version?: Integer;\n /** Releases the body without changing the remote resource. */\n close(): Promise<void>;\n}\n\n/**\n * A file's tag, its public content hash, from its piece hashes laid end to end\n * in order. A file of one piece has the SHA-256 of its bytes, which is that\n * piece's hash. An empty file has the SHA-256 of no bytes. A file of several\n * pieces has the SHA-256 of its piece hashes, which no tool hashing the file's\n * bytes computes.\n *\n * A tag covers content, not length, so a large file and a small file holding\n * the bytes of its piece hashes share a tag. Their lengths differ, and a length\n * fixes a file's number of pieces, so a tag and a length together identify the\n * bytes: see `fileEtag`.\n */\nexport async function fileTagOfPieces(\n pieceHashes: Uint8Array<ArrayBuffer>,\n): Promise<string> {\n return hexOf(\n pieceHashes.length === FILE_PIECE_HASH_BYTES\n ? pieceHashes\n : new Uint8Array(await crypto.subtle.digest(\"SHA-256\", pieceHashes)),\n );\n}\n\n/** Bytes in lowercase hexadecimal, the spelling of a tag. */\nexport function hexOf(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\n \"\",\n );\n}\n\n/**\n * A saved file's strong entity tag, the tag and the length together. Two files\n * with one entity tag hold the same bytes, and the entity tag is the same in\n * every version that holds them. `tag` must be lowercase hexadecimal.\n */\nexport function fileEtag(tag: string, size: Integer): string {\n return `\"${tag}-${integerText(size)}\"`;\n}\n\n/**\n * Reads an entity tag `fileEtag` wrote, and returns `undefined` for any other\n * value, or a length beyond 2^53 - 1, which no `number` states exactly. A tree\n * archive's entity tag is not one, and has no parts to read.\n */\nexport function parseFileEtag(\n etag: string,\n): { readonly tag: string; readonly size: number } | undefined {\n const match = /^\"([0-9a-f]{64})-(0|[1-9][0-9]*)\"$/u.exec(etag);\n if (match === null) return undefined;\n const size = Number(match[2]);\n return Number.isSafeInteger(size) ? { tag: match[1] ?? \"\", size } : undefined;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport type { StorageOperationId } from \"../resource/uuid-id.js\";\nimport {\n always,\n decodeValue,\n integer,\n integerText,\n isUint64,\n jsonObject,\n numberOrBigInt,\n object,\n omitEmpty,\n omitZero,\n pointer,\n scalar,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport {\n filePathFields,\n uploadChangeReceiptShape,\n validateUploadArchiveOptions,\n validateUploadFileOptions,\n type FilePath,\n type UploadChangeReceipt,\n} from \"./files.js\";\nimport type { ErrorResponse } from \"./types.js\";\n\n/** Selects one file or POSIX tar stream within an Upload sequence. */\nexport type UploadTransferKind =\n \"file\" | \"archive\" | (string & Record<never, never>);\n/** Reports durable receipt and ingestion; newer tokens remain readable. */\nexport type UploadTransferState =\n | \"receiving\"\n | \"processing\"\n | \"complete\"\n | \"failed\"\n | (string & Record<never, never>);\n/** Reserves an Upload sequence. Equal sequence, kind, path and mode retries return the same transfer. */\nexport interface CreateUploadTransferRequest extends FilePath {\n readonly seq: Integer;\n readonly kind: UploadTransferKind;\n readonly mode?: number;\n}\n/** Records a contiguous plaintext prefix. Completion carries one accepted change receipt and does not publish the parent Upload. */\nexport interface UploadTransfer {\n readonly id: StorageOperationId;\n readonly seq: Integer;\n readonly state: UploadTransferState;\n readonly nextOffset: Integer;\n readonly prefixSHA256: string;\n readonly maxPartBytes: Integer;\n readonly receipt?: UploadChangeReceipt;\n readonly failure?: ErrorResponse;\n}\n/** Seals the exact length and digest. Equal retries retain the outcome; processing is polled until ingestion completes. */\nexport interface CompleteUploadTransferRequest {\n readonly length: Integer;\n readonly sha256: string;\n}\n\n/** Requires a supported stream kind before submission. */\nexport function validateUploadTransferKind(value: UploadTransferKind): void {\n if (value !== \"file\" && value !== \"archive\")\n throw new TypeError(\"unknown upload transfer kind\");\n}\n/** Requires a recognized lifecycle state before acting on a response. */\nexport function validateUploadTransferState(value: UploadTransferState): void {\n if (![\"receiving\", \"processing\", \"complete\", \"failed\"].includes(value))\n throw new TypeError(\"unknown upload transfer state\");\n}\n/** Tests the canonical lowercase hexadecimal spelling, without hashing bytes. */\nexport function validUploadSHA256(value: string): boolean {\n return typeof value === \"string\" && /^[0-9a-f]{64}$/u.test(value);\n}\n/** Checks the same path, permissions and sequence as its file or archive stream. */\nexport function validateCreateUploadTransferRequest(\n request: CreateUploadTransferRequest,\n): void {\n validateUploadTransferKind(request.kind);\n if (request.kind === \"file\")\n validateUploadFileOptions({ ...request, mode: request.mode ?? 0 });\n else {\n if (request.mode !== undefined && request.mode !== 0)\n throw new TypeError(\"archive transfer has no file mode\");\n validateUploadArchiveOptions(request);\n }\n}\n/** Requires an exact uint64 byte length and canonical SHA-256 spelling. */\nexport function validateCompleteUploadTransferRequest(\n request: CompleteUploadTransferRequest,\n): void {\n if (!isUint64(request.length))\n throw new TypeError(\"upload length must fit uint64\");\n if (!validUploadSHA256(request.sha256))\n throw new TypeError(\n \"upload SHA-256 must be 64 lowercase hexadecimal digits\",\n );\n}\n\n// Byte counts are exact unsigned decimal JSON strings, including zero.\nconst byteCountShape: Shape<Integer> = scalar({\n decode(value) {\n if (\n !/^(?:0|[1-9][0-9]*)$/u.test(value) ||\n BigInt(value) > 18446744073709551615n\n )\n throw new TypeError(\"upload byte count must fit uint64\");\n return numberOrBigInt(BigInt(value));\n },\n encode(value) {\n if (!isUint64(value))\n throw new TypeError(\"upload byte count must fit uint64\");\n return integerText(value);\n },\n zero: () => 0,\n isZero: (value) => value === 0 || value === 0n,\n});\nconst failureShape: Shape<ErrorResponse> = object<ErrorResponse>({\n error: always(string()),\n code: omitEmpty(string()),\n details: omitEmpty(jsonObject()),\n});\n/** The canonical creation request shape. */\nexport const createUploadTransferRequestShape: Shape<CreateUploadTransferRequest> =\n object({\n ...filePathFields,\n seq: always(integer({ unsigned: true, bits: 64 })),\n kind: always(string<UploadTransferKind>()),\n mode: omitZero(integer({ unsigned: true, bits: 32 })),\n });\n/** The canonical transfer response shape, preserving exact byte counts. */\nconst transferShape: Shape<UploadTransfer> = object({\n id: always(string<StorageOperationId>()),\n seq: always(integer({ unsigned: true, bits: 64 })),\n state: always(string<UploadTransferState>()),\n nextOffset: always(byteCountShape),\n prefixSHA256: always(string()),\n maxPartBytes: always(byteCountShape),\n receipt: pointer(uploadChangeReceiptShape),\n failure: pointer(failureShape),\n});\n// Prefix offsets and budgets drive source reads and allocations. They must\n// retain their exact decimal-string wire form even on a lenient observation.\nexport const uploadTransferShape: Shape<UploadTransfer> = {\n ...transferShape,\n decode(value, path, mode) {\n const result = transferShape.decode(value, path, mode);\n const raw = value as Record<string, unknown>;\n return {\n ...result,\n nextOffset: byteCountShape.decode(\n raw[\"nextOffset\"],\n `${path}.nextOffset`,\n ),\n maxPartBytes: byteCountShape.decode(\n raw[\"maxPartBytes\"],\n `${path}.maxPartBytes`,\n ),\n };\n },\n};\n/** The canonical completion request shape. */\nexport const completeUploadTransferRequestShape: Shape<CompleteUploadTransferRequest> =\n object({\n length: always(byteCountShape),\n sha256: always(string()),\n });\n/** Reads a transfer while accepting newer fields and tokens. */\nexport function decodeUploadTransfer(value: unknown): UploadTransfer {\n return decodeValue(value, uploadTransferShape, \"lenient\");\n}\n/** Writes canonical transfer JSON, including exact decimal byte strings. */\nexport function encodeUploadTransfer(value: UploadTransfer): unknown {\n return uploadTransferShape.encode(value);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * SHA-256 as FIPS 180-4 defines it, computed synchronously so that a\n * validator can judge a digest where it judges everything else. The package\n * declares no dependency and a browser's digest is asynchronous, so the\n * function is written out here.\n */\n\nconst ROUND_CONSTANTS = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nconst INITIAL_STATE = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n];\n\nfunction rotateRight(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits));\n}\n\n/** Incremental SHA-256 with one partial block retained between updates. */\nexport class Sha256 {\n readonly #state = Uint32Array.from(INITIAL_STATE);\n readonly #schedule = new Uint32Array(64);\n readonly #tail = new Uint8Array(64);\n #tailLength = 0;\n #length = 0n;\n\n update(data: Uint8Array): void {\n this.#length += BigInt(data.byteLength);\n let offset = 0;\n if (this.#tailLength !== 0) {\n const copied = Math.min(64 - this.#tailLength, data.byteLength);\n this.#tail.set(data.subarray(0, copied), this.#tailLength);\n this.#tailLength += copied;\n offset = copied;\n if (this.#tailLength === 64) {\n compress(this.#state, this.#tail, this.#schedule);\n this.#tailLength = 0;\n }\n }\n while (offset + 64 <= data.byteLength) {\n compress(this.#state, data.subarray(offset, offset + 64), this.#schedule);\n offset += 64;\n }\n if (offset < data.byteLength) {\n this.#tail.set(data.subarray(offset), this.#tailLength);\n this.#tailLength += data.byteLength - offset;\n }\n }\n\n /** Reads the current digest without sealing or changing the hash. */\n hex(): string {\n const state = this.#state.slice();\n const padded = new Uint8Array(this.#tailLength < 56 ? 64 : 128);\n padded.set(this.#tail.subarray(0, this.#tailLength));\n padded[this.#tailLength] = 0x80;\n new DataView(padded.buffer).setBigUint64(\n padded.byteLength - 8,\n BigInt.asUintN(64, this.#length * 8n),\n );\n for (let offset = 0; offset < padded.byteLength; offset += 64)\n compress(state, padded.subarray(offset, offset + 64), this.#schedule);\n return Array.from(state, (word) => word.toString(16).padStart(8, \"0\")).join(\n \"\",\n );\n }\n}\n\n/** The SHA-256 of `data`, as 64 lowercase hexadecimal digits. */\nexport function sha256Hex(data: Uint8Array): string {\n const hash = new Sha256();\n hash.update(data);\n return hash.hex();\n}\n\nfunction compress(\n state: Uint32Array,\n data: Uint8Array,\n schedule: Uint32Array,\n): void {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n for (let t = 0; t < 16; t += 1) {\n schedule[t] = view.getUint32(t * 4);\n }\n for (let t = 16; t < 64; t += 1) {\n const w15 = schedule[t - 15] ?? 0;\n const w2 = schedule[t - 2] ?? 0;\n const sigma0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ (w15 >>> 3);\n const sigma1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ (w2 >>> 10);\n schedule[t] =\n ((schedule[t - 16] ?? 0) + sigma0 + (schedule[t - 7] ?? 0) + sigma1) >>>\n 0;\n }\n let a = state[0] ?? 0;\n let b = state[1] ?? 0;\n let c = state[2] ?? 0;\n let d = state[3] ?? 0;\n let e = state[4] ?? 0;\n let f = state[5] ?? 0;\n let g = state[6] ?? 0;\n let h = state[7] ?? 0;\n for (let t = 0; t < 64; t += 1) {\n const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);\n const choose = (e & f) ^ (~e & g);\n const temp1 =\n (h + sum1 + choose + (ROUND_CONSTANTS[t] ?? 0) + (schedule[t] ?? 0)) >>>\n 0;\n const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const temp2 = (sum0 + majority) >>> 0;\n h = g;\n g = f;\n f = e;\n e = (d + temp1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) >>> 0;\n }\n state[0] = ((state[0] ?? 0) + a) >>> 0;\n state[1] = ((state[1] ?? 0) + b) >>> 0;\n state[2] = ((state[2] ?? 0) + c) >>> 0;\n state[3] = ((state[3] ?? 0) + d) >>> 0;\n state[4] = ((state[4] ?? 0) + e) >>> 0;\n state[5] = ((state[5] ?? 0) + f) >>> 0;\n state[6] = ((state[6] ?? 0) + g) >>> 0;\n state[7] = ((state[7] ?? 0) + h) >>> 0;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n ApiError,\n UploadTransferFailedError,\n TransportError,\n} from \"../errors.js\";\nimport { Sha256, sha256Hex } from \"../resource/sha256.js\";\nimport { parseStorageOperationId } from \"../resource/uuid-id.js\";\nimport { integerEqual, isUint64 } from \"./strictdecode.js\";\nimport { abortable, delay } from \"./abort.js\";\nimport { isFetchFailure } from \"./transport.js\";\nimport {\n validUploadSHA256,\n validateUploadTransferState,\n type CreateUploadTransferRequest,\n type UploadTransfer,\n type CompleteUploadTransferRequest,\n} from \"../api/upload-transfer.js\";\nimport type { UploadChangeReceipt } from \"../api/files.js\";\n\nexport interface UploadTransferCalls {\n create(request: CreateUploadTransferRequest): Promise<UploadTransfer>;\n get(id: string): Promise<UploadTransfer>;\n part(\n id: string,\n offset: bigint,\n digest: string,\n body: Uint8Array,\n ): Promise<UploadTransfer>;\n complete(\n id: string,\n request: CompleteUploadTransferRequest,\n ): Promise<UploadTransfer>;\n}\nexport function checkUploadTransfer(\n value: UploadTransfer,\n id?: string,\n seq?: number | bigint,\n): UploadTransfer {\n parseStorageOperationId(value.id);\n if (id !== undefined && value.id !== id)\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer response names a different identity\",\n );\n if (!isUint64(value.nextOffset) || !isUint64(value.maxPartBytes))\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer response has invalid byte counts\",\n );\n if (\n !isUint64(value.seq) ||\n value.seq <= 0 ||\n (seq !== undefined && !integerEqual(value.seq, seq)) ||\n (value.receipt !== undefined && !integerEqual(value.receipt.seq, value.seq))\n )\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer response names a different sequence\",\n );\n return value;\n}\nfunction retryable(error: unknown, signal: AbortSignal): boolean {\n if (signal.aborted) return false;\n if (error instanceof ApiError)\n return error.status === 408 || error.status === 429 || error.status >= 500;\n return isFetchFailure(error);\n}\nasync function retry<T>(\n call: () => Promise<T>,\n signal: AbortSignal,\n): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n signal.throwIfAborted();\n try {\n return await call();\n } catch (error) {\n if (attempt === 2 || !retryable(error, signal)) throw error;\n await delay(\n Math.max(\n (attempt + 1) * 100,\n error instanceof ApiError ? (error.retryAfterMs ?? 0) : 0,\n ),\n signal,\n );\n }\n }\n}\nfunction progress(\n value: UploadTransfer,\n id: string,\n seq: number | bigint,\n offset: bigint,\n digest: string,\n): void {\n checkUploadTransfer(value, id, seq);\n validateUploadTransferState(value.state);\n if (value.state === \"failed\") throw new UploadTransferFailedError(value);\n if (BigInt(value.nextOffset) !== offset || value.prefixSHA256 !== digest)\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer progress differs from the verified source prefix\",\n );\n if (value.maxPartBytes <= 0)\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer response has a zero part budget\",\n );\n if (value.state === \"complete\" && value.receipt === undefined)\n throw new TransportError(\n \"invalid_response\",\n \"completed upload transfer has no change receipt\",\n );\n}\nconst MAX_PART_BYTES = 4 * 1024 * 1024;\nconst UINT64_MAX = 18446744073709551615n;\n\n/**\n * Retains one bounded part and verifies every accepted prefix against the\n * source from byte zero. `accepted` receives the byte count the platform\n * holds after the verified prefix and after each accepted part; an exception\n * it throws ends the upload with that exception.\n */\nexport async function uploadStream(\n request: CreateUploadTransferRequest,\n body: ReadableStream<Uint8Array>,\n calls: UploadTransferCalls,\n signal: AbortSignal,\n accepted?: (bytes: bigint) => void,\n): Promise<UploadChangeReceipt> {\n let value = await retry(() => calls.create(request), signal);\n checkUploadTransfer(value, undefined, request.seq);\n validateUploadTransferState(value.state);\n if (value.state === \"failed\") throw new UploadTransferFailedError(value);\n if (!validUploadSHA256(value.prefixSHA256) || value.maxPartBytes <= 0)\n throw new TransportError(\n \"invalid_response\",\n \"upload transfer has invalid prefix metadata\",\n );\n const id = value.id;\n const reader = body.getReader();\n let pending: Uint8Array = new Uint8Array(0);\n let eof = false;\n const onAbort = (): void => {\n void reader.cancel(signal.reason).catch(() => undefined);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n async function readPart(length: number): Promise<Uint8Array> {\n const part = new Uint8Array(length);\n let filled = 0;\n while (filled < length) {\n signal.throwIfAborted();\n if (pending.byteLength === 0) {\n if (eof) break;\n const read = await abortable(reader.read(), signal);\n if (read.done) {\n eof = true;\n break;\n }\n if (!(read.value instanceof Uint8Array))\n throw new TypeError(\"upload source must yield Uint8Array chunks\");\n pending = read.value;\n }\n const copied = Math.min(length - filled, pending.byteLength);\n part.set(pending.subarray(0, copied), filled);\n pending = pending.subarray(copied);\n filled += copied;\n }\n return part.subarray(0, filled);\n }\n function sourceEnded(): boolean {\n return eof;\n }\n function budget(): number {\n return Number(\n BigInt(value.maxPartBytes) < BigInt(MAX_PART_BYTES)\n ? BigInt(value.maxPartBytes)\n : BigInt(MAX_PART_BYTES),\n );\n }\n try {\n signal.throwIfAborted();\n const hash = new Sha256();\n let offset = BigInt(value.nextOffset);\n for (let remaining = offset; remaining !== 0n;) {\n const size = Number(\n remaining < BigInt(budget()) ? remaining : BigInt(budget()),\n );\n const part = await readPart(size);\n if (part.byteLength !== size)\n throw new TypeError(\n \"source is shorter than the accepted upload prefix\",\n );\n hash.update(part);\n remaining -= BigInt(part.byteLength);\n }\n progress(value, id, request.seq, offset, hash.hex());\n accepted?.(offset);\n for (;;) {\n const part = await readPart(budget());\n if (part.byteLength !== 0) {\n if (value.state !== \"receiving\")\n throw new TypeError(\n \"source is longer than the sealed upload transfer\",\n );\n const next = offset + BigInt(part.byteLength);\n if (next > UINT64_MAX)\n throw new TypeError(\"upload stream length overflows uint64\");\n const before = hash.hex();\n hash.update(part);\n const after = hash.hex();\n const digest = sha256Hex(part);\n value = await retry(async () => {\n try {\n return await calls.part(id, offset, digest, part);\n } catch (error) {\n if (retryable(error, signal)) {\n let observed: UploadTransfer | undefined;\n try {\n observed = await calls.get(id);\n } catch (readError) {\n if (!retryable(readError, signal)) throw readError;\n }\n if (observed !== undefined) {\n if (BigInt(observed.nextOffset) === next) {\n progress(observed, id, request.seq, next, after);\n return observed;\n }\n progress(observed, id, request.seq, offset, before);\n }\n }\n throw error;\n }\n }, signal);\n progress(value, id, request.seq, next, after);\n offset = next;\n accepted?.(offset);\n }\n if (sourceEnded()) break;\n }\n if (value.state === \"complete\") return receipt(value);\n const sealed = { length: offset, sha256: hash.hex() };\n value = await retry(() => calls.complete(id, sealed), signal);\n for (;;) {\n progress(value, id, request.seq, offset, sealed.sha256);\n if (value.state === \"complete\") return receipt(value);\n if (value.state !== \"processing\")\n throw new TransportError(\n \"invalid_response\",\n \"sealed upload transfer did not enter processing\",\n );\n await delay(1000, signal);\n value = await retry(() => calls.get(id), signal);\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n reader.releaseLock();\n }\n}\n\nfunction receipt(value: UploadTransfer): UploadChangeReceipt {\n if (value.receipt === undefined)\n throw new TransportError(\n \"invalid_response\",\n \"completed upload transfer has no change receipt\",\n );\n return value.receipt;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n type FileEntry,\n type FileEntryType,\n type FilePath,\n filePathFields,\n filePathShape,\n validateFilePath,\n} from \"./files.js\";\nimport {\n type Shape,\n always,\n array,\n boolean,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n} from \"../internal/strictdecode.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\n\n/**\n * FileStatus says whether a file's content is safe in the store. A file's name\n * and status reach every client as soon as the name changes on a running\n * Computer; its content follows with the Computer's next save.\n *\n * - `synced`: content that is safe in the store.\n * - `syncing`: a name that exists on a running Computer whose content no\n * saved version holds yet.\n * - `conflict`: a name where two changes collided and both copies were kept;\n * its `statusReason` is `kept-both`.\n * - `failed`: content the Computer's save cannot finish; its `statusReason`\n * is the failing save's reason, as its commit reports it.\n *\n * Responses also carry newer tokens.\n */\nexport type FileStatus =\n | \"synced\"\n | \"syncing\"\n | \"conflict\"\n | \"failed\"\n | (string & Record<never, never>);\n/** Judges file status membership without making decoding strict. */\nexport function validateFileStatus(value: FileStatus): void {\n if ([\"synced\", \"syncing\", \"conflict\", \"failed\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"file status is required\");\n throw new TypeError(`unknown file status ${JSON.stringify(value)}`);\n}\n\n/**\n * FileListResponse is one page of a saved directory listing.\n *\n * `syncing` is stated when the listing reads the latest saved version: `true`\n * while the files' owner is a running Computer holding changes no saved\n * version holds yet, including changes written in place to files the listing\n * shows as `synced`, and `false` otherwise. When the service cannot tell, it\n * states `true`. It is `undefined` on a listing of a named version. `store`\n * is present on such a listing while the running Computer's reads wait for\n * the store.\n */\nexport interface FileListResponse {\n readonly items: readonly FileEntry[];\n readonly totalCount: Integer;\n readonly continue?: string;\n readonly syncing?: boolean;\n readonly store?: FileStoreWait;\n}\n\n/**\n * WatchFilesOptions selects the folder a file watch follows, the root when no\n * path is set, and `after`, the `cursor` of the answer the caller holds. An\n * absent or empty `after` asks for the current status at once.\n */\nexport interface WatchFilesOptions extends FilePath {\n readonly after?: string;\n}\n\n/**\n * WatchFilesResponse is one answer of a file watch: the whole current status\n * of the watched folder and everything below it, and the versions published\n * since the answer `after` named.\n *\n * A watch answers at once when the status or the published versions moved\n * past `after`. Otherwise the service holds the request until one does, for\n * at most 10 seconds, and then answers with the same `cursor`. A client\n * follows a folder by asking again with each answer's `cursor`; a request\n * held open is not a stream, and nothing is lost between two requests.\n *\n * `changes` lists every name below the folder that changed on a running\n * Computer since its last saved version, in byte order of path; it is the\n * whole set, not what changed since `after`. `published` lists the versions\n * published since `after`, oldest first, such as a save, an upload or a\n * restore. `relist` says that `after` is older than the service still\n * remembers, so the caller lists the folder again instead of applying\n * `published`. `syncing` has {@link FileListResponse}'s meaning. `store` is\n * present while the Computer's reads wait for the store.\n */\nexport interface WatchFilesResponse {\n readonly cursor: string;\n readonly syncing: boolean;\n readonly changes: readonly FileChange[];\n readonly published: readonly FilePublication[];\n readonly relist?: boolean;\n readonly store?: FileStoreWait;\n}\n\n/**\n * FileChangeKind says what changed at a {@link FileChange}'s path.\n *\n * - `changed`: a name created, replaced or moved to its path. `type`, `size`\n * and `modified` are read from the file when its change is reported.\n * - `removed`: a saved name the running Computer no longer holds.\n * - `many`: a folder holding more changed names than are listed one by one.\n * The empty path names the whole tree. The caller lists the folder to see\n * them.\n *\n * Responses also carry newer tokens.\n */\nexport type FileChangeKind =\n \"changed\" | \"removed\" | \"many\" | (string & Record<never, never>);\n/** Judges file change kind membership without making decoding strict. */\nexport function validateFileChangeKind(value: FileChangeKind): void {\n if ([\"changed\", \"removed\", \"many\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"file change is required\");\n throw new TypeError(`unknown file change ${JSON.stringify(value)}`);\n}\n\n/**\n * FileChange is one changed path of a file watch, relative to the root of the\n * files, not to the watched folder. `status` is `syncing`, `conflict` or\n * `failed`, with `statusReason` as on a {@link FileEntry}. `size` is in\n * bytes, and `modified` is an RFC 3339 timestamp.\n */\nexport interface FileChange extends FilePath {\n readonly change: FileChangeKind;\n readonly type?: FileEntryType;\n readonly size?: Integer;\n readonly modified?: string;\n readonly status: FileStatus;\n readonly statusReason?: string;\n}\n\n/**\n * FilePublication is one version published to the files. `paths` lists the\n * paths it changed, relative to the root of the files, when the service knows\n * them; `more` says it changed more than it lists, so the caller lists the\n * folders it shows again.\n */\nexport interface FilePublication {\n readonly version: Integer;\n readonly paths: readonly FilePath[];\n readonly more?: boolean;\n}\n\n/**\n * FileStoreWaitState says how a running Computer's reads wait for the store.\n *\n * - `waiting`: a read that has waited for the store for at least five\n * seconds and is still trying.\n * - `unreachable`: a Computer whose first reads of files fail at once,\n * because one read waited out its bound. One read is tried again every 30\n * seconds, and its success ends this state.\n *\n * Responses also carry newer tokens.\n */\nexport type FileStoreWaitState =\n \"waiting\" | \"unreachable\" | (string & Record<never, never>);\n/** Judges file store wait state membership without making decoding strict. */\nexport function validateFileStoreWaitState(value: FileStoreWaitState): void {\n if ([\"waiting\", \"unreachable\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"file store wait state is required\");\n throw new TypeError(`unknown file store wait state ${JSON.stringify(value)}`);\n}\n\n/**\n * FileStoreWait says a running Computer's reads wait for the store. `cause`\n * is `store` for a store that does not answer, and `connection` for a\n * Computer whose machine cannot reach the service to be let into the store.\n * `since` is when the wait began, as an RFC 3339 timestamp, and `waiting`\n * counts the reads waiting now. `fillDone` and `fillTotal` are the bytes the\n * largest waiting file has and needs, both zero when they are not known.\n */\nexport interface FileStoreWait {\n readonly state: FileStoreWaitState;\n readonly cause: string;\n readonly since: string;\n readonly waiting: Integer;\n readonly fillDone: Integer;\n readonly fillTotal: Integer;\n}\n\n/** The canonical wire fields of WatchFilesOptions. */\nexport const watchFilesOptionsFields = {\n ...filePathFields,\n after: omitEmpty(string()),\n};\n/** The canonical wire shape of WatchFilesOptions. */\nexport const watchFilesOptionsShape: Shape<WatchFilesOptions> =\n object<WatchFilesOptions>(watchFilesOptionsFields);\n\n/** The canonical wire shape of FileChange. */\nexport const fileChangeShape: Shape<FileChange> = object<FileChange>({\n ...filePathFields,\n change: always(string<FileChangeKind>()),\n type: omitEmpty(string<FileEntryType>()),\n size: omitEmpty(integer({ unsigned: true, bits: 64 })),\n modified: pointer(timestampShape),\n status: always(string<FileStatus>()),\n statusReason: omitEmpty(string()),\n});\n\n/** The canonical wire shape of FilePublication. */\nexport const filePublicationShape: Shape<FilePublication> =\n object<FilePublication>({\n version: always(integer({ unsigned: false, bits: 64 })),\n paths: always(array(filePathShape)),\n more: omitEmpty(boolean()),\n });\n\n/** The canonical wire shape of FileStoreWait. */\nexport const fileStoreWaitShape: Shape<FileStoreWait> = object<FileStoreWait>({\n state: always(string<FileStoreWaitState>()),\n cause: always(string()),\n since: always(timestampShape),\n waiting: always(integer({ unsigned: true, bits: 64 })),\n fillDone: always(integer({ unsigned: true, bits: 64 })),\n fillTotal: always(integer({ unsigned: true, bits: 64 })),\n});\n\n/** The canonical wire shape of WatchFilesResponse. */\nexport const watchFilesResponseShape: Shape<WatchFilesResponse> =\n object<WatchFilesResponse>({\n cursor: always(string()),\n syncing: always(boolean()),\n changes: always(array(fileChangeShape)),\n published: always(array(filePublicationShape)),\n relist: omitEmpty(boolean()),\n store: pointer(fileStoreWaitShape),\n });\n\n/** Checks the byte path of a file watch when one is set. */\nexport function validateWatchFilesOptions(options: WatchFilesOptions): void {\n if (options.path === undefined && options.pathBase64 === undefined) return;\n validateFilePath(options);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Placement resolution. A Computer lives in the place IDYL assigns its\n * Account, and that place's public API serves it. Every Computer operation\n * resolves it through the client's one placement source, judged at the bar\n * the operation needs, and builds the Namespace scope every Namespace-scoped\n * route is built from.\n */\nimport type { NamespaceScope } from \"../api/types.js\";\nimport type { SubnetSlug } from \"../resource/id.js\";\nimport type { PlacementContext } from \"./context.js\";\n\n/** How a resolution is to be judged. */\nexport interface ResolvePlacementOptions {\n /**\n * Requires the client to have a Namespace. `undefined` requires one; an\n * account-wide operation passes `false`.\n */\n readonly requireNamespace?: boolean;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Where a Computer operation is sent and what it is stamped with.\n *\n * `subnet` is the canonical slug of the place the Computer lives in and\n * `endpoint` the origin of its public API; `zone` is the trust scope\n * discovery names for the place, empty when it names none. `scope` is the\n * Namespace address\n * every Namespace-scoped route is built from; its `namespace` is empty when\n * the resolution did not require one.\n */\nexport interface ResolvedPlacement {\n readonly subnet: SubnetSlug;\n readonly endpoint: string;\n readonly zone: string;\n readonly scope: NamespaceScope;\n}\n\n/**\n * Resolves the client's placement to the API that serves it. Throws a\n * `TypeError` when a Namespace is required and the client has none, before\n * any request.\n */\nexport async function resolvePlacement(\n context: PlacementContext,\n options: ResolvePlacementOptions = {},\n): Promise<ResolvedPlacement> {\n const requireNamespace = options.requireNamespace ?? true;\n const namespace = context.scope.namespace ?? \"\";\n if (requireNamespace && namespace.trim() === \"\") {\n throw new TypeError(\"namespace is required\");\n }\n const assigned = await context.placement.resolve(context.scope.accountId, {\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n });\n return {\n subnet: assigned.subnet,\n endpoint: assigned.endpoint,\n zone: assigned.zone,\n scope: { accountId: context.scope.accountId, namespace },\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { TransportError } from \"../errors.js\";\nimport * as transfers from \"../api/upload-transfer.js\";\nimport {\n checkUploadTransfer,\n uploadStream,\n} from \"../internal/storage-upload.js\";\nimport { sha256Hex } from \"../resource/sha256.js\";\nimport { isUint64 } from \"../internal/strictdecode.js\";\nimport { integerEqual } from \"../internal/strictdecode.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport * as storage from \"../api/storage.js\";\nimport * as files from \"../api/files.js\";\nimport * as fileStatus from \"../api/file-status.js\";\nimport type { ListResponse, NamespaceScope } from \"../api/types.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport {\n namespaceResource,\n computerById,\n storageChild,\n} from \"../internal/apipath.js\";\nimport {\n fileQuery,\n pageQuery,\n fileListQuery,\n watchFilesQuery,\n} from \"../internal/listquery.js\";\nimport { asRecord, readList } from \"../internal/envelopes.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport {\n decodeValue,\n isInt64,\n integerText,\n numberOrBigInt,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport {\n parseComputerId,\n parseStorageOperationId,\n} from \"../resource/uuid-id.js\";\nimport type { RequestOptions } from \"../request.js\";\n\n/**\n * What a file or archive upload accepts beyond a call's options: `accepted`\n * receives the byte count the platform holds after each accepted part.\n */\nexport interface UploadRequestOptions extends RequestOptions {\n readonly accepted?: (bytes: bigint) => void;\n}\n\n/** Which read of saved content: one file's bytes, or a tree's POSIX tar archive. */\nexport type ContentKind = \"file\" | \"archive\";\n\n/** The route and media type of each kind of content read. */\nconst CONTENT_ROUTES = {\n file: { suffix: \"files/content\", accept: \"application/octet-stream\" },\n archive: { suffix: \"files/archive\", accept: \"application/x-tar\" },\n} as const;\n\n/** Saved-state operations of a Computer's files. */\nexport interface StorageMethods {\n /** Reads saved versions newest first; pass `continue` back unchanged to resume the listing. */\n listVersions(\n address: string,\n options?: storage.PageOptions,\n requestOptions?: RequestOptions,\n ): Promise<ListResponse<storage.Version>>;\n /** Reads one saved version by number or name, without changing the current files. Addresses the resource by stable identity. */\n getVersionById(\n address: string,\n version: string,\n requestOptions?: RequestOptions,\n ): Promise<storage.Version>;\n /** Reads saved versions newest first; pass `continue` back unchanged to resume the listing. Addresses the resource by stable identity. */\n listVersionsById(\n address: string,\n options?: storage.PageOptions,\n requestOptions?: RequestOptions,\n ): Promise<ListResponse<storage.Version>>;\n /** Names a saved version by its non-negative number; empty removes the name. */\n updateVersion(\n address: string,\n number: Integer,\n request: storage.UpdateVersionRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Version>;\n /** Names a saved version by its non-negative number; empty removes the name. Addresses the resource by stable identity. */\n updateVersionById(\n address: string,\n number: Integer,\n request: storage.UpdateVersionRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Version>;\n /** Saves the files or records unchanged; an idempotency key retains the effect. */\n createCommit(\n address: string,\n request: storage.CreateCommitRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Commit>;\n /** Saves the files or records unchanged; an idempotency key retains the effect. Addresses the resource by stable identity. */\n createCommitById(\n address: string,\n request: storage.CreateCommitRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Commit>;\n /** Reads the recorded save outcome; nonterminal means it continues. */\n getCommit(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<storage.Commit>;\n /** Reads the recorded save outcome; nonterminal means it continues. Addresses the resource by stable identity. */\n getCommitById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<storage.Commit>;\n /**\n * Appends a `restore` entry owning a new version with the selected\n * version's files, keeping every earlier entry. On a Computer it also\n * restores the execution settings in force at that version's entry, which\n * apply at the Computer's next start; running sessions continue. See\n * {@link storage.CreateRestoreRequest}.\n */\n createRestore(\n address: string,\n request: storage.CreateRestoreRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Restore>;\n /** Restores a saved version as {@link StorageMethods.createRestore} does. Addresses the resource by stable identity. */\n createRestoreById(\n address: string,\n request: storage.CreateRestoreRequest,\n requestOptions?: RequestOptions,\n ): Promise<storage.Restore>;\n /** Reads a retained restore outcome by stable operation identity. */\n getRestore(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<storage.Restore>;\n /** Reads a retained restore outcome by stable operation identity. Addresses the resource by stable identity. */\n getRestoreById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<storage.Restore>;\n /** Reads saved children with byte-safe names; omitted version selects the saved head, whose listing states each entry's status and whether the files are syncing. */\n listFiles(\n address: string,\n options: files.FileListOptions,\n requestOptions?: RequestOptions,\n ): Promise<fileStatus.FileListResponse>;\n /** Reads saved children with byte-safe names; omitted version selects the saved head, whose listing states each entry's status and whether the files are syncing. Addresses the resource by stable identity. */\n listFilesById(\n address: string,\n options: files.FileListOptions,\n requestOptions?: RequestOptions,\n ): Promise<fileStatus.FileListResponse>;\n /**\n * Asks once for the status of a folder of the files, as\n * {@link fileStatus.WatchFilesResponse} describes: at once when it moved\n * past `options.after`, otherwise after the service held the request for at\n * most 10 seconds. An answer that names no cursor cannot be followed and is\n * refused as an invalid response.\n */\n watchFiles(\n address: string,\n options: fileStatus.WatchFilesOptions,\n requestOptions?: RequestOptions,\n ): Promise<fileStatus.WatchFilesResponse>;\n /** Asks once for the status of a folder of the files, as {@link StorageMethods.watchFiles} does. Addresses the resource by stable identity. */\n watchFilesById(\n address: string,\n options: fileStatus.WatchFilesOptions,\n requestOptions?: RequestOptions,\n ): Promise<fileStatus.WatchFilesResponse>;\n /** Opens staging on a saved base; omitted base selects the current head. */\n createUpload(\n address: string,\n request: files.CreateUploadRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Opens staging on a saved base; omitted base selects the current head. Addresses the resource by stable identity. */\n createUploadById(\n address: string,\n request: files.CreateUploadRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Reads upload activity, terminal outcome and optional delivery. */\n getUpload(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Reads upload activity, terminal outcome and optional delivery. Addresses the resource by stable identity. */\n getUploadById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Ends open staging so it cannot publish, preserving terminal outcome arbitration. */\n cancelUpload(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Ends open staging so it cannot publish, preserving terminal outcome arbitration. Addresses the resource by stable identity. */\n cancelUploadById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Publishes accepted changes as one version, preserving the server conflict outcome. */\n publishUpload(\n address: string,\n operation: string,\n request: files.PublishUploadRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Publishes accepted changes as one version, preserving the server conflict outcome. Addresses the resource by stable identity. */\n publishUploadById(\n address: string,\n operation: string,\n request: files.PublishUploadRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.Upload>;\n /** Submits one sequenced page of deletes and renames, checking its receipt sequence. */\n uploadChanges(\n address: string,\n operation: string,\n request: files.UploadChangesRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n /** Submits one sequenced page of deletes and renames, checking its receipt sequence. Addresses the resource by stable identity. */\n uploadChangesById(\n address: string,\n operation: string,\n request: files.UploadChangesRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n /** Reads the byte paths replaced when publication was delivered to the running writer, each with where the uploaded copy landed when both copies are kept. */\n listUploadReplaced(\n address: string,\n operation: string,\n options?: storage.PageOptions,\n requestOptions?: RequestOptions,\n ): Promise<ListResponse<files.UploadReplacedPath>>;\n /** Reads the byte paths replaced when publication was delivered to the running writer, each with where the uploaded copy landed when both copies are kept. Addresses the resource by stable identity. */\n listUploadReplacedById(\n address: string,\n operation: string,\n options?: storage.PageOptions,\n requestOptions?: RequestOptions,\n ): Promise<ListResponse<files.UploadReplacedPath>>;\n /** Asks what a read of a saved file or tree would serve, reading no content. Addresses the resource by stable identity. */\n headContentById(\n address: string,\n kind: ContentKind,\n options: files.FileReadOptions,\n requestOptions?: RequestOptions,\n ): Promise<files.ContentFacts>;\n /** Opens one range of the bytes an entity tag names, or `undefined`, with the response discarded unread, when the answer is anything but exactly that range of those bytes. Addresses the resource by stable identity. */\n readContentRangeById(\n address: string,\n kind: ContentKind,\n options: files.FileReadOptions,\n range: files.ContentRange,\n requestOptions?: RequestOptions,\n ): Promise<files.StoredContent | undefined>;\n /** Opens a saved file's raw 32-byte piece hashes in order, with the file's entity tag; close the returned content. Addresses the resource by stable identity. */\n readFilePiecesById(\n address: string,\n options: files.FileReadOptions,\n requestOptions?: RequestOptions,\n ): Promise<files.StoredContent>;\n /** Creates a link that reads one saved file or directory at one version with no other credential; the link is handled as a secret. Addresses the resource by stable identity. */\n createFileDownloadLinkById(\n address: string,\n request: files.CreateFileDownloadLinkRequest,\n requestOptions?: RequestOptions,\n ): Promise<files.FileDownloadLink>;\n /** Reserves one immutable Upload sequence; equal retries return its transfer. */\n createUploadTransfer(\n address: string,\n operation: string,\n request: transfers.CreateUploadTransferRequest,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Reserves one immutable Upload sequence; equal retries return its transfer. Addresses the resource by stable identity. */\n createUploadTransferById(\n address: string,\n operation: string,\n request: transfers.CreateUploadTransferRequest,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Reads the durable accepted prefix and ingestion outcome. */\n getUploadTransfer(\n address: string,\n operation: string,\n transfer: string,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Reads the durable accepted prefix and ingestion outcome. Addresses the resource by stable identity. */\n getUploadTransferById(\n address: string,\n operation: string,\n transfer: string,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Sends one nonempty bounded part at its exact offset; equal bytes replay safely. */\n uploadTransferPart(\n address: string,\n operation: string,\n transfer: string,\n offset: Integer,\n sha256: string,\n body: Uint8Array,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Sends one nonempty bounded part at its exact offset; equal bytes replay safely. Addresses the resource by stable identity. */\n uploadTransferPartById(\n address: string,\n operation: string,\n transfer: string,\n offset: Integer,\n sha256: string,\n body: Uint8Array,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Seals exact length and digest without publishing the parent Upload. */\n completeUploadTransfer(\n address: string,\n operation: string,\n transfer: string,\n request: transfers.CompleteUploadTransferRequest,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Seals exact length and digest without publishing the parent Upload. Addresses the resource by stable identity. */\n completeUploadTransferById(\n address: string,\n operation: string,\n transfer: string,\n request: transfers.CompleteUploadTransferRequest,\n requestOptions?: RequestOptions,\n ): Promise<transfers.UploadTransfer>;\n /** Sends bounded parts and verifies accepted bytes from the source beginning on resume. */\n uploadFile(\n address: string,\n operation: string,\n options: files.UploadFileOptions,\n body: ReadableStream<Uint8Array>,\n requestOptions?: UploadRequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n /** Sends bounded parts and verifies accepted bytes from the source beginning on resume. Addresses the resource by stable identity. */\n uploadFileById(\n address: string,\n operation: string,\n options: files.UploadFileOptions,\n body: ReadableStream<Uint8Array>,\n requestOptions?: UploadRequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n /** Sends a POSIX tar in bounded parts; the server validates entries and resume verifies the accepted prefix. */\n uploadArchive(\n address: string,\n operation: string,\n options: files.UploadArchiveOptions,\n body: ReadableStream<Uint8Array>,\n requestOptions?: UploadRequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n /** Sends a POSIX tar in bounded parts; the server validates entries and resume verifies the accepted prefix. Addresses the resource by stable identity. */\n uploadArchiveById(\n address: string,\n operation: string,\n options: files.UploadArchiveOptions,\n body: ReadableStream<Uint8Array>,\n requestOptions?: UploadRequestOptions,\n ): Promise<files.UploadChangeReceipt>;\n}\n\n/**\n * The wire form of a submission: refused with a `TypeError` for a field its\n * shape does not declare or a value `validate` refuses, and otherwise\n * encoded and read back strictly, so nothing is sent that the strict\n * decoder would refuse.\n */\nexport function submission<T>(\n value: T,\n shape: Shape<T>,\n validate?: (value: T) => void,\n): unknown {\n shape.unknownFields(value, \"\");\n validate?.(value);\n const encoded = shape.encode(value);\n decodeValue(encoded, shape, \"strict\");\n return encoded;\n}\n\n/**\n * `result`, when it names the operation that was read; a response naming\n * another is refused as an invalid response.\n */\nexport function sameOperation<T extends { readonly id: string }>(\n result: T,\n operation: string,\n): T {\n if (result.id !== operation)\n throw new TransportError(\n \"invalid_response\",\n \"operation response names a different identity\",\n );\n return result;\n}\n\ntype ResourcePath = (scope: NamespaceScope) => string;\n/** Composes canonical storage operations with one existing placement/credential transport. */\nexport function storageMethods(\n context: PlacementContext,\n family: \"computers\",\n): StorageMethods {\n function resourcePath(address: string, byId: boolean): ResourcePath {\n if (byId) {\n const id = parseComputerId(address);\n return (scope) => computerById(scope, id);\n }\n requireNonBlank(address, \"computer name\");\n return (scope) => namespaceResource(scope, family, address);\n }\n async function exchange<T>(\n path: ResourcePath,\n method: string,\n collection: string,\n shape: Shape<T>,\n requestOptions: RequestOptions,\n member?: string,\n suffix = \"\",\n query = \"\",\n body?: unknown,\n ): Promise<T> {\n const resolved = await resolvePlacement(\n context,\n signalOption(requestOptions.signal),\n );\n const value = await context.state.transport.json<unknown>(\n method,\n resolved.endpoint,\n storageChild(path(resolved.scope), collection, member, suffix) + query,\n {\n ...signalOption(requestOptions.signal),\n ...(body === undefined ? {} : { body }),\n },\n );\n return decodeValue(value, shape, \"lenient\");\n }\n /** The response of a read of one storage child, as it arrived. */\n async function served(\n path: ResourcePath,\n collection: string,\n query: string,\n options: RequestOptions,\n member?: string,\n suffix = \"\",\n ): Promise<unknown> {\n const resolved = await resolvePlacement(\n context,\n signalOption(options.signal),\n );\n return await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n storageChild(path(resolved.scope), collection, member, suffix) + query,\n signalOption(options.signal),\n );\n }\n async function list<T>(\n path: ResourcePath,\n collection: string,\n decode: (value: unknown) => T,\n query: string,\n options: RequestOptions,\n member?: string,\n suffix = \"\",\n ): Promise<ListResponse<T>> {\n return readList(\n await served(path, collection, query, options, member, suffix),\n collection,\n decode,\n );\n }\n /** One page of saved children, with whether the files are syncing and the wait for the store when the listing states them. */\n async function listFiles(\n path: ResourcePath,\n options: files.FileListOptions,\n requestOptions: RequestOptions,\n ): Promise<fileStatus.FileListResponse> {\n submission(\n options,\n files.fileListOptionsShape,\n files.validateFileListOptions,\n );\n const value = await served(\n path,\n \"files\",\n fileListQuery(options),\n requestOptions,\n );\n const {\n items,\n totalCount,\n continue: next,\n } = readList(value, \"files\", files.decodeFileEntry);\n const { syncing, store } = asRecord(value);\n return {\n items,\n totalCount,\n ...(next === undefined ? {} : { continue: next }),\n ...(typeof syncing === \"boolean\" ? { syncing } : {}),\n ...(store === undefined || store === null\n ? {}\n : {\n store: decodeValue(store, fileStatus.fileStoreWaitShape, \"lenient\"),\n }),\n };\n }\n /** One answer of a file watch, refused when it names no cursor to ask again with. */\n async function watchFiles(\n path: ResourcePath,\n options: fileStatus.WatchFilesOptions,\n requestOptions: RequestOptions,\n ): Promise<fileStatus.WatchFilesResponse> {\n submission(\n options,\n fileStatus.watchFilesOptionsShape,\n fileStatus.validateWatchFilesOptions,\n );\n const answer = await exchange(\n path,\n \"GET\",\n \"files/watch\",\n fileStatus.watchFilesResponseShape,\n requestOptions,\n undefined,\n \"\",\n watchFilesQuery(options),\n );\n if (answer.cursor === \"\")\n throw new TransportError(\n \"invalid_response\",\n \"file watch answer names no cursor\",\n );\n return answer;\n }\n /** Where one content read goes, its options judged before any request. */\n async function contentTarget(\n path: ResourcePath,\n suffix: string,\n options: files.FileReadOptions,\n requestOptions: RequestOptions,\n ): Promise<{ readonly endpoint: string; readonly target: string }> {\n submission(\n options,\n files.fileReadOptionsShape,\n files.validateFileReadOptions,\n );\n const resolved = await resolvePlacement(\n context,\n signalOption(requestOptions.signal),\n );\n return {\n endpoint: resolved.endpoint,\n target: storageChild(path(resolved.scope), suffix) + fileQuery(options),\n };\n }\n async function read(\n path: ResourcePath,\n suffix: string,\n options: files.FileReadOptions,\n requestOptions: RequestOptions,\n accept: string,\n ): Promise<files.StoredContent> {\n const { endpoint, target } = await contentTarget(\n path,\n suffix,\n options,\n requestOptions,\n );\n return await storedContent(\n await context.state.transport.openContent(\n endpoint,\n target,\n accept,\n requestOptions.signal,\n ),\n );\n }\n async function readRange(\n path: ResourcePath,\n kind: ContentKind,\n options: files.FileReadOptions,\n range: files.ContentRange,\n requestOptions: RequestOptions,\n ): Promise<files.StoredContent | undefined> {\n const { suffix, accept } = CONTENT_ROUTES[kind];\n const { endpoint, target } = await contentTarget(\n path,\n suffix,\n options,\n requestOptions,\n );\n const response = await context.state.transport.openContent(\n endpoint,\n target,\n accept,\n requestOptions.signal,\n {\n range: `bytes=${String(range.offset)}-${String(range.offset + range.length - 1)}`,\n \"if-range\": range.etag,\n },\n );\n if (!servesRange(response, range)) {\n await response.body?.cancel();\n return undefined;\n }\n return await storedContent(response);\n }\n async function head(\n path: ResourcePath,\n kind: ContentKind,\n options: files.FileReadOptions,\n requestOptions: RequestOptions,\n ): Promise<files.ContentFacts> {\n const { endpoint, target } = await contentTarget(\n path,\n CONTENT_ROUTES[kind].suffix,\n options,\n requestOptions,\n );\n const response = await context.state.transport.openContent(\n endpoint,\n target,\n \"*/*\",\n requestOptions.signal,\n undefined,\n \"HEAD\",\n );\n const version = await savedVersion(response);\n const etag = response.headers.get(\"ETag\");\n const length = response.headers.get(\"Content-Length\");\n if (\n version === undefined ||\n etag === null ||\n length === null ||\n !/^[0-9]+$/u.test(length)\n )\n throw new TransportError(\n \"invalid_response\",\n \"content response does not state its length, entity tag and version\",\n );\n return { etag, size: Number(length), version };\n }\n async function createTransfer(\n path: ResourcePath,\n operation: string,\n creation: transfers.CreateUploadTransferRequest,\n options: RequestOptions,\n ): Promise<transfers.UploadTransfer> {\n const id = parseStorageOperationId(operation);\n const body = submission(\n creation,\n transfers.createUploadTransferRequestShape,\n transfers.validateCreateUploadTransferRequest,\n );\n const result = await exchange<transfers.UploadTransfer>(\n path,\n \"POST\",\n \"uploads\",\n transfers.uploadTransferShape,\n options,\n id,\n \"transfers\",\n \"\",\n body,\n );\n return checkUploadTransfer(result, undefined, creation.seq);\n }\n async function getTransfer(\n path: ResourcePath,\n operation: string,\n transfer: string,\n options: RequestOptions,\n ): Promise<transfers.UploadTransfer> {\n const id = parseStorageOperationId(operation);\n const child = parseStorageOperationId(transfer);\n return checkUploadTransfer(\n await exchange(\n path,\n \"GET\",\n \"uploads\",\n transfers.uploadTransferShape,\n options,\n id,\n `transfers/${child}`,\n ),\n child,\n );\n }\n async function partTransfer(\n path: ResourcePath,\n operation: string,\n transfer: string,\n offset: Integer,\n digest: string,\n body: Uint8Array,\n options: RequestOptions,\n ): Promise<transfers.UploadTransfer> {\n const id = parseStorageOperationId(operation);\n const child = parseStorageOperationId(transfer);\n if (\n !isUint64(offset) ||\n !(body instanceof Uint8Array) ||\n body.byteLength === 0 ||\n BigInt(offset) + BigInt(body.byteLength) > 18446744073709551615n\n )\n throw new TypeError(\n \"upload part must be nonempty and its end must fit uint64\",\n );\n if (!transfers.validUploadSHA256(digest) || sha256Hex(body) !== digest)\n throw new TypeError(\"upload part SHA-256 differs from its bytes\");\n const resolved = await resolvePlacement(\n context,\n signalOption(options.signal),\n );\n // A part is already in memory, so it is sent as bytes: a streaming\n // request body is not supported by every browser.\n const content = new Uint8Array(body);\n const wire = await context.state.transport.sendContent(\n resolved.endpoint,\n storageChild(\n path(resolved.scope),\n \"uploads\",\n id,\n `transfers/${child}/parts/${integerText(offset)}`,\n ) + `?sha256=${digest}`,\n \"application/octet-stream\",\n content,\n options.signal,\n );\n return checkUploadTransfer(transfers.decodeUploadTransfer(wire), child);\n }\n async function completeTransfer(\n path: ResourcePath,\n operation: string,\n transfer: string,\n completion: transfers.CompleteUploadTransferRequest,\n options: RequestOptions,\n ): Promise<transfers.UploadTransfer> {\n const id = parseStorageOperationId(operation);\n const child = parseStorageOperationId(transfer);\n const body = submission(\n completion,\n transfers.completeUploadTransferRequestShape,\n transfers.validateCompleteUploadTransferRequest,\n );\n return checkUploadTransfer(\n await exchange(\n path,\n \"POST\",\n \"uploads\",\n transfers.uploadTransferShape,\n options,\n id,\n `transfers/${child}/complete`,\n \"\",\n body,\n ),\n child,\n );\n }\n async function streamUpload(\n path: ResourcePath,\n operation: string,\n options: files.UploadArchiveOptions | files.UploadFileOptions,\n body: ReadableStream<Uint8Array>,\n requestOptions: UploadRequestOptions,\n archive: boolean,\n ): Promise<files.UploadChangeReceipt> {\n requireContentStream(body);\n parseStorageOperationId(operation);\n if (archive)\n submission(\n options,\n files.uploadArchiveOptionsShape,\n files.validateUploadArchiveOptions,\n );\n else\n submission(\n options as files.UploadFileOptions,\n files.uploadFileOptionsShape,\n files.validateUploadFileOptions,\n );\n const creation: transfers.CreateUploadTransferRequest = {\n ...options,\n kind: archive ? \"archive\" : \"file\",\n };\n return await uploadStream(\n creation,\n body,\n {\n create: (value) =>\n createTransfer(path, operation, value, requestOptions),\n get: (id) => getTransfer(path, operation, id, requestOptions),\n part: (id, offset, digest, content) =>\n partTransfer(\n path,\n operation,\n id,\n offset,\n digest,\n content,\n requestOptions,\n ),\n complete: (id, value) =>\n completeTransfer(path, operation, id, value, requestOptions),\n },\n requestOptions.signal ?? new AbortController().signal,\n requestOptions.accepted,\n );\n }\n return {\n async createUploadTransfer(address, operation, creation, options = {}) {\n return await createTransfer(\n resourcePath(address, false),\n operation,\n creation,\n options,\n );\n },\n async createUploadTransferById(address, operation, creation, options = {}) {\n return await createTransfer(\n resourcePath(address, true),\n operation,\n creation,\n options,\n );\n },\n async getUploadTransfer(address, operation, transfer, options = {}) {\n return await getTransfer(\n resourcePath(address, false),\n operation,\n transfer,\n options,\n );\n },\n async getUploadTransferById(address, operation, transfer, options = {}) {\n return await getTransfer(\n resourcePath(address, true),\n operation,\n transfer,\n options,\n );\n },\n async uploadTransferPart(\n address,\n operation,\n transfer,\n offset,\n digest,\n body,\n options = {},\n ) {\n return await partTransfer(\n resourcePath(address, false),\n operation,\n transfer,\n offset,\n digest,\n body,\n options,\n );\n },\n async uploadTransferPartById(\n address,\n operation,\n transfer,\n offset,\n digest,\n body,\n options = {},\n ) {\n return await partTransfer(\n resourcePath(address, true),\n operation,\n transfer,\n offset,\n digest,\n body,\n options,\n );\n },\n async completeUploadTransfer(\n address,\n operation,\n transfer,\n completion,\n options = {},\n ) {\n return await completeTransfer(\n resourcePath(address, false),\n operation,\n transfer,\n completion,\n options,\n );\n },\n async completeUploadTransferById(\n address,\n operation,\n transfer,\n completion,\n options = {},\n ) {\n return await completeTransfer(\n resourcePath(address, true),\n operation,\n transfer,\n completion,\n options,\n );\n },\n async listVersions(address, options = {}, requestOptions = {}) {\n const path = resourcePath(address, false);\n submission(options, storage.pageOptionsShape);\n return await list(\n path,\n \"versions\",\n storage.decodeVersion,\n pageQuery(options),\n requestOptions,\n );\n },\n async getVersionById(address, version, requestOptions = {}) {\n requireNonBlank(version, \"version\");\n return await exchange(\n resourcePath(address, true),\n \"GET\",\n \"versions\",\n storage.versionShape,\n requestOptions,\n version,\n );\n },\n async listVersionsById(address, options = {}, requestOptions = {}) {\n const path = resourcePath(address, true);\n submission(options, storage.pageOptionsShape);\n return await list(\n path,\n \"versions\",\n storage.decodeVersion,\n pageQuery(options),\n requestOptions,\n );\n },\n async updateVersion(address, number, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n if (!isInt64(number) || number < 0)\n throw new TypeError(\"version must be a non-negative integer\");\n return await exchange(\n path,\n \"PATCH\",\n \"versions\",\n storage.versionShape,\n requestOptions,\n integerText(number),\n \"\",\n \"\",\n submission(request, storage.updateVersionRequestShape),\n );\n },\n async updateVersionById(address, number, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n if (!isInt64(number) || number < 0)\n throw new TypeError(\"version must be a non-negative integer\");\n return await exchange(\n path,\n \"PATCH\",\n \"versions\",\n storage.versionShape,\n requestOptions,\n integerText(number),\n \"\",\n \"\",\n submission(request, storage.updateVersionRequestShape),\n );\n },\n async createCommit(address, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n const result = await exchange(\n path,\n \"POST\",\n \"commits\",\n storage.commitShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(request, storage.createCommitRequestShape),\n );\n return result;\n },\n async createCommitById(address, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n const result = await exchange(\n path,\n \"POST\",\n \"commits\",\n storage.commitShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(request, storage.createCommitRequestShape),\n );\n return result;\n },\n async getCommit(address, operation, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"commits\",\n storage.commitShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async getCommitById(address, operation, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"commits\",\n storage.commitShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async createRestore(address, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n const result = await exchange(\n path,\n \"POST\",\n \"restores\",\n storage.restoreShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(\n request,\n storage.createRestoreRequestShape,\n storage.validateCreateRestoreRequest,\n ),\n );\n return result;\n },\n async createRestoreById(address, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n const result = await exchange(\n path,\n \"POST\",\n \"restores\",\n storage.restoreShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(\n request,\n storage.createRestoreRequestShape,\n storage.validateCreateRestoreRequest,\n ),\n );\n return result;\n },\n async getRestore(address, operation, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"restores\",\n storage.restoreShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async getRestoreById(address, operation, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"restores\",\n storage.restoreShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async listFiles(address, options, requestOptions = {}) {\n return await listFiles(\n resourcePath(address, false),\n options,\n requestOptions,\n );\n },\n async listFilesById(address, options, requestOptions = {}) {\n return await listFiles(\n resourcePath(address, true),\n options,\n requestOptions,\n );\n },\n async watchFiles(address, options, requestOptions = {}) {\n return await watchFiles(\n resourcePath(address, false),\n options,\n requestOptions,\n );\n },\n async watchFilesById(address, options, requestOptions = {}) {\n return await watchFiles(\n resourcePath(address, true),\n options,\n requestOptions,\n );\n },\n async createUpload(address, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(\n request,\n files.createUploadRequestShape,\n files.validateCreateUploadRequest,\n ),\n );\n return result;\n },\n async createUploadById(address, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n undefined,\n \"\",\n \"\",\n submission(\n request,\n files.createUploadRequestShape,\n files.validateCreateUploadRequest,\n ),\n );\n return result;\n },\n async getUpload(address, operation, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async getUploadById(address, operation, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"GET\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async cancelUpload(address, operation, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"DELETE\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async cancelUploadById(address, operation, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"DELETE\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"\",\n \"\",\n undefined,\n );\n return sameOperation(result, id);\n },\n async publishUpload(address, operation, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"publish\",\n \"\",\n submission(request, files.publishUploadRequestShape),\n );\n return sameOperation(result, id);\n },\n async publishUploadById(address, operation, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadShape,\n requestOptions,\n id,\n \"publish\",\n \"\",\n submission(request, files.publishUploadRequestShape),\n );\n return sameOperation(result, id);\n },\n async uploadChanges(address, operation, request, requestOptions = {}) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadChangeReceiptShape,\n requestOptions,\n id,\n \"changes\",\n \"\",\n submission(\n request,\n files.uploadChangesRequestShape,\n files.validateUploadChangesRequest,\n ),\n );\n if (!integerEqual(result.seq, request.seq))\n throw new TransportError(\n \"invalid_response\",\n \"change receipt names a different sequence\",\n );\n return result;\n },\n async uploadChangesById(address, operation, request, requestOptions = {}) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n const result = await exchange(\n path,\n \"POST\",\n \"uploads\",\n files.uploadChangeReceiptShape,\n requestOptions,\n id,\n \"changes\",\n \"\",\n submission(\n request,\n files.uploadChangesRequestShape,\n files.validateUploadChangesRequest,\n ),\n );\n if (!integerEqual(result.seq, request.seq))\n throw new TransportError(\n \"invalid_response\",\n \"change receipt names a different sequence\",\n );\n return result;\n },\n async listUploadReplaced(\n address,\n operation,\n options = {},\n requestOptions = {},\n ) {\n const path = resourcePath(address, false);\n const id = parseStorageOperationId(operation);\n return await list(\n path,\n \"uploads\",\n (value) => decodeValue(value, files.uploadReplacedPathShape, \"lenient\"),\n pageQuery(options),\n requestOptions,\n id,\n \"replaced\",\n );\n },\n async listUploadReplacedById(\n address,\n operation,\n options = {},\n requestOptions = {},\n ) {\n const path = resourcePath(address, true);\n const id = parseStorageOperationId(operation);\n return await list(\n path,\n \"uploads\",\n (value) => decodeValue(value, files.uploadReplacedPathShape, \"lenient\"),\n pageQuery(options),\n requestOptions,\n id,\n \"replaced\",\n );\n },\n async headContentById(address, kind, options, requestOptions = {}) {\n return await head(\n resourcePath(address, true),\n kind,\n options,\n requestOptions,\n );\n },\n async readContentRangeById(\n address,\n kind,\n options,\n range,\n requestOptions = {},\n ) {\n return await readRange(\n resourcePath(address, true),\n kind,\n options,\n range,\n requestOptions,\n );\n },\n async readFilePiecesById(address, options, requestOptions = {}) {\n return await read(\n resourcePath(address, true),\n \"files/pieces\",\n options,\n requestOptions,\n \"application/octet-stream\",\n );\n },\n async createFileDownloadLinkById(address, request, requestOptions = {}) {\n const body = submission(\n request,\n files.createFileDownloadLinkRequestShape,\n files.validateCreateFileDownloadLinkRequest,\n );\n return await exchange(\n resourcePath(address, true),\n \"POST\",\n \"files\",\n files.fileDownloadLinkShape,\n requestOptions,\n \"download-link\",\n \"\",\n \"\",\n body,\n );\n },\n async uploadFile(address, operation, options, body, requestOptions = {}) {\n const path = resourcePath(address, false);\n return await streamUpload(\n path,\n operation,\n options,\n body,\n requestOptions,\n false,\n );\n },\n async uploadFileById(\n address,\n operation,\n options,\n body,\n requestOptions = {},\n ) {\n const path = resourcePath(address, true);\n return await streamUpload(\n path,\n operation,\n options,\n body,\n requestOptions,\n false,\n );\n },\n async uploadArchive(\n address,\n operation,\n options,\n body,\n requestOptions = {},\n ) {\n const path = resourcePath(address, false);\n return await streamUpload(\n path,\n operation,\n options,\n body,\n requestOptions,\n true,\n );\n },\n async uploadArchiveById(\n address,\n operation,\n options,\n body,\n requestOptions = {},\n ) {\n const path = resourcePath(address, true);\n return await streamUpload(\n path,\n operation,\n options,\n body,\n requestOptions,\n true,\n );\n },\n };\n}\n\n/** The saved version a content response states, if it states one. */\nasync function savedVersion(response: Response): Promise<Integer | undefined> {\n const raw = response.headers.get(\"Idyl-Saved-Version\");\n if (raw === null) return undefined;\n if (\n !/^[+-]?[0-9]+$/u.test(raw) ||\n !isInt64(BigInt(raw)) ||\n BigInt(raw) < 0n\n ) {\n await response.body?.cancel();\n throw new TransportError(\n \"invalid_response\",\n \"content response has an invalid saved version\",\n );\n }\n return numberOrBigInt(BigInt(raw));\n}\n\n/** Whether a response is exactly `range` of the bytes its entity tag names. */\nfunction servesRange(response: Response, range: files.ContentRange): boolean {\n const served = /^bytes ([0-9]+)-([0-9]+)\\/[0-9]+$/u.exec(\n response.headers.get(\"Content-Range\") ?? \"\",\n );\n return (\n response.status === 206 &&\n response.headers.get(\"ETag\") === range.etag &&\n Number(served?.[1]) === range.offset &&\n Number(served?.[2]) === range.offset + range.length - 1\n );\n}\n\n/** Takes ownership of a content response's body as one closeable stream. */\nasync function storedContent(response: Response): Promise<files.StoredContent> {\n const version = await savedVersion(response);\n if (response.body === null)\n throw new TransportError(\n \"invalid_response\",\n \"content response has no body\",\n );\n const reader = response.body.getReader();\n let closed = false;\n async function close(): Promise<void> {\n if (closed) return;\n closed = true;\n try {\n await reader.cancel();\n } finally {\n reader.releaseLock();\n }\n }\n const body = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n if (closed) {\n controller.close();\n return;\n }\n try {\n const value = await reader.read();\n if (value.done) {\n closed = true;\n reader.releaseLock();\n controller.close();\n } else controller.enqueue(value.value);\n } catch (error) {\n closed = true;\n reader.releaseLock();\n controller.error(error);\n }\n },\n async cancel() {\n await close();\n },\n },\n { highWaterMark: 0 },\n );\n return {\n body,\n etag: response.headers.get(\"ETag\") ?? \"\",\n ...(version === undefined ? {} : { version }),\n close,\n };\n}\n\nfunction requireContentStream(\n value: unknown,\n): asserts value is ReadableStream<Uint8Array> {\n if (\n value === null ||\n typeof value !== \"object\" ||\n typeof (value as { getReader?: unknown }).getReader !== \"function\"\n )\n throw new TypeError(\"content stream is required\");\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * A Computer is awake while its execution runs and asleep while only its\n * saved files remain. It wakes by itself when a session needs it and sleeps\n * by itself after its idle timeout. A wake (ComputerWake) and a sleep\n * (ComputerSleep) do the same on request. Each is an operation resource:\n * creating one records it and answers at once, pending or already finished,\n * and the caller reads it until it is finished. No request is held open\n * while a Computer wakes or sleeps; the platform owns every deadline.\n *\n * Both need computer:update on the Namespace that owns the Computer. A wake\n * and a sleep of one Computer take effect in the order they were created:\n * each waits for the earlier pending operations of the other kind to finish.\n */\nimport {\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\nimport {\n type Shape,\n always,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n} from \"../internal/strictdecode.js\";\nimport { parseJson, type Integer, type JsonObject } from \"../resource/json.js\";\nimport type { ComputerOperationId } from \"../resource/uuid-id.js\";\n\n/**\n * Asks for a Computer to be woken. `idempotencyKey` makes an equal retry\n * return the same wake.\n */\nexport interface CreateComputerWakeRequest {\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. The journal entry it makes\n * records it, as `unknown` when it is absent; it is informative and never\n * authorizes anything.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/**\n * A request to wake a Computer: start its execution with no session open.\n * A wake of an asleep Computer is `pending` until its execution has started\n * and is then `awake`; a wake of an awake Computer is `awake` at once.\n * Either way the Computer then stays awake for its idle timeout, counted\n * from the wake, and goes to sleep as it does after its last session.\n *\n * A `failed` wake carries `reason`, spelled as the error code that fails a\n * session for the same cause: `WAKE_TIMEOUT`, `PROFILE_FITS_NO_HOST`,\n * `INSUFFICIENT_CAPACITY`, `INSUFFICIENT_DISK`, `EXECUTION_NOT_ENABLED`,\n * `IMAGE_NOT_IN_CATALOG`, `NETWORK_CLASS_NOT_ADMITTED`,\n * `ISOLATION_CLASS_NOT_ADMITTED`, `VERSION_DAMAGED`, `OUT_OF_USAGE`,\n * `SIZE_NOT_IN_PLAN` or `VCPU_LIMIT_REACHED`. A pending or\n * awake wake carries no reason.\n *\n * A pending wake that cannot be placed yet, for a cause that can clear with no\n * change by the caller, carries `waitingFor`. It is spelled as the `reason`\n * the wake fails with if the cause holds until its deadline:\n * `INSUFFICIENT_CAPACITY` when no machine has room, `INSUFFICIENT_DISK` when\n * none has the disk, or `PROFILE_FITS_NO_HOST` when none can run it. The wake\n * keeps trying until then. `waitingFor` is absent once the Computer has a\n * place, and on an awake or failed wake.\n *\n * A wake that found the Computer asleep is recorded in its journal as a\n * `wake` entry.\n */\nexport interface ComputerWake {\n readonly id: ComputerOperationId;\n readonly state: ComputerWakeState;\n readonly reason?: string;\n readonly waitingFor?: string;\n}\n\n/**\n * Asks for a Computer to be put to sleep. `idempotencyKey` makes an equal\n * retry return the same sleep.\n */\nexport interface CreateComputerSleepRequest {\n readonly idempotencyKey?: string;\n /**\n * The kind of client sending the request. The journal entry it makes\n * records it, as `unknown` when it is absent; it is informative and never\n * authorizes anything.\n */\n readonly client?: ComputerSessionClient;\n /**\n * Puts the Computer to sleep without saving it: every change made since\n * its last saved version is discarded, and the sleep records no version.\n * Asked while a sleep of the Computer is pending, it ends that sleep's wait\n * for a save that has not published, such as one that keeps failing, and\n * the Computer goes to sleep with its unsaved changes discarded. The\n * journal's `sleep` entry records the discard (`JournalEntrySleep`).\n * `false` or absent saves the Computer first.\n */\n readonly discardUnsavedChanges?: boolean;\n /**\n * Puts the Computer to sleep as a machine that loses its power: its\n * programs are not ended or shut down before the save, the save holds what\n * they had written to the Computer's files when it was taken, and they are\n * then stopped without a shutdown. What a program synchronized to its\n * files before the save was taken is kept; what it held only in memory is\n * not. It is for a Computer whose programs or shutdown do not finish. The\n * journal's `sleep` entry records it (`JournalEntrySleep.forced`). `false`\n * or absent ends the Computer's programs before the save. It is never set\n * with `discardUnsavedChanges`.\n */\n readonly force?: boolean;\n}\n\n/**\n * A request to put a Computer to sleep. A sleep of an awake Computer first\n * saves its files, as an explicit save does, unless its `autoSave` is false\n * or the request asked to discard unsaved changes\n * (`CreateComputerSleepRequest.discardUnsavedChanges`): its unsaved changes\n * are then discarded and the sleep records no version. A save that fails is\n * asked for again until one publishes, and the Computer stays awake with its\n * changes meanwhile; IDYL never discards them because saving failed. It then\n * ends every open session, then releases its execution as its idle timeout\n * does: background processes stop. An ended session reads the reason\n * `PutToSleep`. While a sleep is pending, a new session waits\n * for it and then wakes the Computer again.\n *\n * `version` is the version the sleep's save recorded, present once the save\n * is known, version zero included. A sleep of an asleep Computer is\n * `asleep` at once, with no version and no save, as is a sleep of one whose\n * `autoSave` is false.\n *\n * A `failed` sleep carries `reason`: {@link COMPUTER_SLEEP_REASON_SAVE_FAILED}\n * when the save failed, in which case the Computer stays awake and its\n * sessions continue, or {@link COMPUTER_SLEEP_REASON_TIMEOUT} when the\n * Computer could not be released in time, in which case it stays awake and\n * goes to sleep after its idle timeout.\n *\n * A `pending` sleep whose last save was refused at a storage limit carries\n * `waitingFor`, spelled as that save's reason: `account-storage-limit`,\n * `computer-size` or `name-limit` (`SAVE_REASON_ACCOUNT_STORAGE_LIMIT`,\n * `SAVE_REASON_COMPUTER_SIZE`, `SAVE_REASON_NAME_LIMIT`). The Computer stays\n * awake with its unsaved files, and the sleep asks for a save again, after a\n * back-off, until one is saved. Two answers end the wait, each one call: deleting files, through the\n * files API or on the Computer, so that the next save passes; or a sleep with\n * `CreateComputerSleepRequest.discardUnsavedChanges`, which discards the\n * unsaved changes and puts the Computer to sleep at its last saved version.\n * `waitingFor` is absent once a save is saved, before any save failed, after a\n * save that failed for another reason, and on an asleep or failed sleep.\n *\n * A sleep that released the Computer is recorded in its journal as a\n * `sleep` entry.\n */\nexport interface ComputerSleep {\n readonly id: ComputerOperationId;\n readonly state: ComputerSleepState;\n readonly version?: Integer;\n readonly reason?: string;\n readonly waitingFor?: string;\n}\n\n/**\n * A sleep whose save of the Computer's files failed. Nothing was ended and\n * the Computer stays awake.\n */\nexport const COMPUTER_SLEEP_REASON_SAVE_FAILED = \"SAVE_FAILED\";\n\n/**\n * A sleep whose Computer could not be released before the sleep's\n * deadline, as when saves at the end of its sessions kept failing.\n */\nexport const COMPUTER_SLEEP_REASON_TIMEOUT = \"SLEEP_TIMEOUT\";\n\n/**\n * Where a wake is: `pending` until the Computer has started, then `awake`,\n * or `failed` when it could not be started. `pending` is the only state\n * that changes. Reads also carry newer tokens.\n */\nexport type ComputerWakeState =\n \"pending\" | \"awake\" | \"failed\" | (string & Record<never, never>);\n\n/** Judges computer wake state membership without making decoding strict. */\nexport function validateComputerWakeState(value: ComputerWakeState): void {\n if ([\"pending\", \"awake\", \"failed\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"computer wake state is required\");\n throw new TypeError(`unknown computer wake state ${JSON.stringify(value)}`);\n}\n\n/**\n * Where a sleep is: `pending` while it saves, ends sessions or releases the\n * Computer, then `asleep`, or `failed` when it left the Computer awake.\n * `pending` is the only state that changes. Reads also carry newer tokens.\n */\nexport type ComputerSleepState =\n \"pending\" | \"asleep\" | \"failed\" | (string & Record<never, never>);\n\n/** Judges computer sleep state membership without making decoding strict. */\nexport function validateComputerSleepState(value: ComputerSleepState): void {\n if ([\"pending\", \"asleep\", \"failed\"].includes(value)) return;\n if (value === \"\") throw new TypeError(\"computer sleep state is required\");\n throw new TypeError(`unknown computer sleep state ${JSON.stringify(value)}`);\n}\n\n/** The canonical wire fields of CreateComputerWakeRequest. */\nexport const createComputerWakeRequestFields = {\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n};\n/** The canonical wire shape of CreateComputerWakeRequest. */\nexport const createComputerWakeRequestShape: Shape<CreateComputerWakeRequest> =\n object<CreateComputerWakeRequest>(createComputerWakeRequestFields);\n\n/** Checks that a stated client is one this SDK names. */\nexport function validateCreateComputerWakeRequest(\n request: CreateComputerWakeRequest,\n): void {\n validateStatedClient(request.client);\n}\n\n/** The canonical wire fields of ComputerWake. */\nexport const computerWakeFields = {\n id: always(string<ComputerOperationId>()),\n state: always(string<ComputerWakeState>()),\n reason: omitEmpty(string()),\n waitingFor: omitEmpty(string()),\n};\n/** The canonical wire shape of ComputerWake. */\nexport const computerWakeShape: Shape<ComputerWake> =\n object<ComputerWake>(computerWakeFields);\n\n/** The canonical wire fields of CreateComputerSleepRequest. */\nexport const createComputerSleepRequestFields = {\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n discardUnsavedChanges: omitEmpty(boolean()),\n force: omitEmpty(boolean()),\n};\n/** The canonical wire shape of CreateComputerSleepRequest. */\nexport const createComputerSleepRequestShape: Shape<CreateComputerSleepRequest> =\n object<CreateComputerSleepRequest>(createComputerSleepRequestFields);\n\n/**\n * Checks that a stated client is one this SDK names, and that a sleep does\n * not both discard and force.\n */\nexport function validateCreateComputerSleepRequest(\n request: CreateComputerSleepRequest,\n): void {\n validateStatedClient(request.client);\n if (request.force === true && request.discardUnsavedChanges === true) {\n throw new TypeError(\"force and discardUnsavedChanges cannot both be set\");\n }\n}\n\n/** The canonical wire fields of ComputerSleep. */\nexport const computerSleepFields = {\n id: always(string<ComputerOperationId>()),\n state: always(string<ComputerSleepState>()),\n version: pointer(integer({ unsigned: false, bits: 64 })),\n reason: omitEmpty(string()),\n waitingFor: omitEmpty(string()),\n};\n/** The canonical wire shape of ComputerSleep. */\nexport const computerSleepShape: Shape<ComputerSleep> =\n object<ComputerSleep>(computerSleepFields);\n\n/** Reads a served ComputerWake leniently, carrying unknown fields and tokens. */\nexport function decodeComputerWake(document: unknown): ComputerWake {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n computerWakeShape,\n \"lenient\",\n );\n}\n/** Renders ComputerWake with the public wire omission rules. */\nexport function encodeComputerWake(value: ComputerWake): JsonObject {\n return computerWakeShape.encode(value) as JsonObject;\n}\n\n/** Reads a served ComputerSleep leniently, carrying unknown fields and tokens. */\nexport function decodeComputerSleep(document: unknown): ComputerSleep {\n return decodeValue(\n typeof document === \"string\" ? parseJson(document) : document,\n computerSleepShape,\n \"lenient\",\n );\n}\n/** Renders ComputerSleep with the public wire omission rules, version zero included. */\nexport function encodeComputerSleep(value: ComputerSleep): JsonObject {\n return computerSleepShape.encode(value) as JsonObject;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport * as operations from \"../api/computer-operations.js\";\nimport type { NamespaceScope } from \"../api/types.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport {\n computerById,\n namespaceResource,\n storageChild,\n} from \"../internal/apipath.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport { decodeValue, type Shape } from \"../internal/strictdecode.js\";\nimport {\n parseComputerId,\n parseComputerOperationId,\n} from \"../resource/uuid-id.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport { sameOperation, submission } from \"./storage.js\";\n\n/**\n * Wakes and sleeps of a Computer, each an operation resource as\n * {@link operations.ComputerWake} and {@link operations.ComputerSleep}\n * describe. A create answers at once, pending or finished; the caller reads\n * the operation until its state is no longer `pending`. Every call\n * addresses the Computer either by name or, in its `ById` form, by its\n * stable ID, and needs `computer:update`. A read whose answer names another\n * operation is refused with a `TransportError` (`invalid_response`).\n */\nexport interface ComputerOperationMethods {\n /**\n * Asks for the Computer addressed by name to be woken. The answer is\n * `awake` at once when the Computer is already awake, and otherwise\n * `pending` until its execution has started.\n */\n createWake(\n address: string,\n request: operations.CreateComputerWakeRequest,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerWake>;\n /** Asks for the Computer addressed by its stable ID to be woken, as {@link ComputerOperationMethods.createWake} does. */\n createWakeById(\n address: string,\n request: operations.CreateComputerWakeRequest,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerWake>;\n /** Reads a wake of the Computer addressed by name. */\n getWake(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerWake>;\n /** Reads a wake of the Computer addressed by its stable ID. */\n getWakeById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerWake>;\n /**\n * Asks for the Computer addressed by name to be put to sleep. The answer\n * is `asleep` at once when the Computer is already asleep, and otherwise\n * `pending` until its files have been saved, its sessions ended and its\n * execution released.\n */\n createSleep(\n address: string,\n request: operations.CreateComputerSleepRequest,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerSleep>;\n /** Asks for the Computer addressed by its stable ID to be put to sleep, as {@link ComputerOperationMethods.createSleep} does. */\n createSleepById(\n address: string,\n request: operations.CreateComputerSleepRequest,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerSleep>;\n /** Reads a sleep of the Computer addressed by name. */\n getSleep(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerSleep>;\n /** Reads a sleep of the Computer addressed by its stable ID. */\n getSleepById(\n address: string,\n operation: string,\n requestOptions?: RequestOptions,\n ): Promise<operations.ComputerSleep>;\n}\n\ntype ComputerPath = (scope: NamespaceScope) => string;\n\n/** Composes the wake and sleep routes on the client's placement and transport. */\nexport function computerOperationMethods(\n context: PlacementContext,\n): ComputerOperationMethods {\n function computerPath(address: string, byId: boolean): ComputerPath {\n if (byId) {\n const id = parseComputerId(address);\n return (scope) => computerById(scope, id);\n }\n requireNonBlank(address, \"computer name\");\n return (scope) => namespaceResource(scope, \"computers\", address);\n }\n async function exchange<T>(\n path: ComputerPath,\n method: \"GET\" | \"POST\",\n collection: \"wakes\" | \"sleeps\",\n shape: Shape<T>,\n requestOptions: RequestOptions,\n member?: string,\n body?: unknown,\n ): Promise<T> {\n const resolved = await resolvePlacement(\n context,\n signalOption(requestOptions.signal),\n );\n const value = await context.state.transport.json<unknown>(\n method,\n resolved.endpoint,\n storageChild(path(resolved.scope), collection, member),\n {\n ...signalOption(requestOptions.signal),\n ...(body === undefined ? {} : { body }),\n },\n );\n return decodeValue(value, shape, \"lenient\");\n }\n async function createWake(\n path: ComputerPath,\n request: operations.CreateComputerWakeRequest,\n requestOptions: RequestOptions,\n ): Promise<operations.ComputerWake> {\n const body = submission(request, operations.createComputerWakeRequestShape);\n return await exchange(\n path,\n \"POST\",\n \"wakes\",\n operations.computerWakeShape,\n requestOptions,\n undefined,\n body,\n );\n }\n async function getWake(\n path: ComputerPath,\n operation: string,\n requestOptions: RequestOptions,\n ): Promise<operations.ComputerWake> {\n const id = parseComputerOperationId(operation);\n return sameOperation(\n await exchange(\n path,\n \"GET\",\n \"wakes\",\n operations.computerWakeShape,\n requestOptions,\n id,\n ),\n id,\n );\n }\n async function createSleep(\n path: ComputerPath,\n request: operations.CreateComputerSleepRequest,\n requestOptions: RequestOptions,\n ): Promise<operations.ComputerSleep> {\n const body = submission(\n request,\n operations.createComputerSleepRequestShape,\n );\n return await exchange(\n path,\n \"POST\",\n \"sleeps\",\n operations.computerSleepShape,\n requestOptions,\n undefined,\n body,\n );\n }\n async function getSleep(\n path: ComputerPath,\n operation: string,\n requestOptions: RequestOptions,\n ): Promise<operations.ComputerSleep> {\n const id = parseComputerOperationId(operation);\n return sameOperation(\n await exchange(\n path,\n \"GET\",\n \"sleeps\",\n operations.computerSleepShape,\n requestOptions,\n id,\n ),\n id,\n );\n }\n return {\n async createWake(address, request, requestOptions = {}) {\n return await createWake(\n computerPath(address, false),\n request,\n requestOptions,\n );\n },\n async createWakeById(address, request, requestOptions = {}) {\n return await createWake(\n computerPath(address, true),\n request,\n requestOptions,\n );\n },\n async getWake(address, operation, requestOptions = {}) {\n return await getWake(\n computerPath(address, false),\n operation,\n requestOptions,\n );\n },\n async getWakeById(address, operation, requestOptions = {}) {\n return await getWake(\n computerPath(address, true),\n operation,\n requestOptions,\n );\n },\n async createSleep(address, request, requestOptions = {}) {\n return await createSleep(\n computerPath(address, false),\n request,\n requestOptions,\n );\n },\n async createSleepById(address, request, requestOptions = {}) {\n return await createSleep(\n computerPath(address, true),\n request,\n requestOptions,\n );\n },\n async getSleep(address, operation, requestOptions = {}) {\n return await getSleep(\n computerPath(address, false),\n operation,\n requestOptions,\n );\n },\n async getSleepById(address, operation, requestOptions = {}) {\n return await getSleep(\n computerPath(address, true),\n operation,\n requestOptions,\n );\n },\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { isUint64 } from \"../internal/strictdecode.js\";\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n parseComputerSessionId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport { validateComputerNotebookName } from \"./computer-notebook-name.js\";\nimport {\n isZeroInstant,\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\n\n/**\n * What a hold on an awake Computer is.\n *\n * - `session`: one or more open sessions: terminals, commands, notebook\n * cells and SSH connections. An open session holds the Computer while it\n * stays open, whether or not anything is typed or running in it; an SSH\n * connection holds it as a terminal does, for as long as the connection\n * is open, even with no channel open. A stream that only reads the\n * Computer's files or a notebook's records is not a session here.\n * - `keep-awake`: an idle timeout of never: the Computer sleeps only when it\n * is asked to.\n * - `starting-session`: one or more sessions accepted and not yet started.\n * - `settings-restart`: a Computer running on execution settings older than\n * those in force. It keeps nothing awake: the Computer sleeps as soon as\n * no session holds it, whatever its idle timeout, so that its next start\n * uses the settings in force.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerAwakeHoldKind} judges\n * membership, and a caller shows a hold of a kind it does not know as\n * something keeping the Computer awake that it cannot describe.\n */\nexport type ComputerAwakeHoldKind =\n | \"session\"\n | \"keep-awake\"\n | \"starting-session\"\n | \"settings-restart\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the kind is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateComputerAwakeHoldKind(\n kind: ComputerAwakeHoldKind,\n): void {\n switch (kind) {\n case \"session\":\n case \"keep-awake\":\n case \"starting-session\":\n case \"settings-restart\":\n return;\n case \"\":\n throw new TypeError(\"computer awake hold kind is required\");\n default:\n throw new TypeError(`unknown computer awake hold kind \"${kind}\"`);\n }\n}\n\n/** One reason an awake Computer has not started counting down to sleep. */\nexport interface ComputerAwakeHold {\n /** What the hold is. */\n readonly kind: ComputerAwakeHoldKind;\n /**\n * How many sessions the hold names: at least one on a `session` or\n * `starting-session` hold, and zero on any other. Always written.\n */\n readonly count: Integer;\n}\n\n/**\n * Why a Computer is awake and when it will sleep, as of the read that\n * reported it. It is the same rule that puts the Computer to sleep, so the\n * time it states is one the platform keeps.\n *\n * When `holds` names nothing but `settings-restart`, or nothing at all, the\n * Computer is counting down: `sleepsAt` and `sleepsIn` are present. A\n * Computer past its time reads `sleepsIn` zero until it has saved and gone to\n * sleep. While a session or Keep awake holds the Computer, both are absent,\n * because nothing it can state says when it will sleep.\n *\n * A caller counting down starts from `sleepsIn`, which needs no agreement\n * between the caller's clock and the platform's, and reads the Computer again\n * to follow a change made elsewhere.\n */\nexport interface ComputerAwake {\n /** When the Computer's current execution started, as an RFC 3339 instant. */\n readonly since: string;\n /**\n * What is keeping the Computer awake now, each kind at most once. Always\n * written, empty when the Computer is counting down.\n */\n readonly holds: readonly ComputerAwakeHold[];\n /**\n * When the Computer sleeps by the platform's clock, as an RFC 3339 instant.\n * Present exactly when `sleepsIn` is.\n */\n readonly sleepsAt?: string;\n /**\n * How long until `sleepsAt`, in whole seconds from the read that reported\n * it. It is never negative. Present exactly when `sleepsAt` is.\n */\n readonly sleepsIn?: Integer;\n}\n\nconst computerAwakeHoldShape: Shape<ComputerAwakeHold> =\n object<ComputerAwakeHold>({\n kind: always(string<ComputerAwakeHoldKind>()),\n count: always(integer({ unsigned: false, bits: 64 })),\n });\n\n/** The wire shape of {@link ComputerAwake}. */\nexport const computerAwakeShape: Shape<ComputerAwake> = object<ComputerAwake>({\n since: always(timestampShape),\n holds: always(array(computerAwakeHoldShape)),\n sleepsAt: pointer(timestampShape),\n sleepsIn: pointer(integer({ unsigned: false, bits: 64 })),\n});\n\n/**\n * Reads an awake state leniently: a field or kind newer than this SDK is\n * carried rather than refused, and {@link validateComputerAwake} judges it.\n */\nexport function decodeComputerAwake(document: unknown): ComputerAwake {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, computerAwakeShape, \"lenient\");\n}\n\n/**\n * Judges the value against this SDK's contract: a start time, holds that are\n * valid and name each kind once, and a sleep time stated whole. Throws a\n * `TypeError`.\n */\nexport function validateComputerAwake(awake: ComputerAwake): void {\n if (isZeroInstant(awake.since)) throw new TypeError(\"since is required\");\n const seen = new Set<string>();\n awake.holds.forEach((hold, index) => {\n prefixed(`holds[${String(index)}]`, () => {\n validateComputerAwakeHoldKind(hold.kind);\n const counted =\n hold.kind === \"session\" || hold.kind === \"starting-session\";\n if (counted && Number(hold.count) < 1) {\n throw new TypeError(\n `a ${hold.kind} hold must count at least one session`,\n );\n }\n if (!counted && Number(hold.count) !== 0) {\n throw new TypeError(`a ${hold.kind} hold counts no sessions`);\n }\n if (seen.has(hold.kind)) {\n throw new TypeError(`${hold.kind} is repeated`);\n }\n seen.add(hold.kind);\n });\n });\n if ((awake.sleepsAt === undefined) !== (awake.sleepsIn === undefined)) {\n throw new TypeError(\"sleepsAt and sleepsIn must be set together\");\n }\n if (awake.sleepsIn !== undefined && !isUint64(awake.sleepsIn)) {\n throw new TypeError(\"sleepsIn must not be negative\");\n }\n}\n\n/**\n * What an open session of a Computer is, in the words a person uses for it:\n * `terminal`, an interactive shell on a terminal; `command`, one command;\n * `notebook-cell`, one notebook cell; or `ssh`, one SSH connection, a\n * session of mode `ssh`, shown to people as \"SSH connection\". An SSH\n * connection's channels are part of it, not sessions of their own.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerSessionKind} judges\n * membership, and a caller shows a session of a kind it does not know as a\n * session it cannot describe.\n */\nexport type ComputerSessionKind =\n | \"terminal\"\n | \"command\"\n | \"notebook-cell\"\n | \"ssh\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the kind is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateComputerSessionKind(kind: ComputerSessionKind): void {\n switch (kind) {\n case \"terminal\":\n case \"command\":\n case \"notebook-cell\":\n case \"ssh\":\n return;\n case \"\":\n throw new TypeError(\"computer session kind is required\");\n default:\n throw new TypeError(`unknown computer session kind \"${kind}\"`);\n }\n}\n\n/**\n * One open session of a Computer, as anyone who may read the Computer sees\n * it: what kind of session it is, which client opened it, who opened it and\n * when. It carries no command, output, attachment or credential, and it\n * grants nothing: a session is read, renewed and ended only by the identity\n * that created it.\n */\nexport interface ComputerSessionSummary {\n /** Names the session. */\n readonly id: ComputerSessionId;\n /** What the session is. */\n readonly kind: ComputerSessionKind;\n /** The notebook the cell runs in, by its current name; only on a notebook cell. */\n readonly notebook?: string;\n /**\n * The kind of client that opened the session, or `unknown` when its request\n * stated none. It is informative and grants nothing.\n */\n readonly client: ComputerSessionClient;\n /** The identity that opened the session, as `JournalEntry.creator` names it. */\n readonly openedBy: string;\n /** When the platform accepted the session, by its own clock, as an RFC 3339 instant. */\n readonly openedAt: string;\n /** True when the caller who read the list opened the session. Always written. */\n readonly yours: boolean;\n}\n\nconst computerSessionSummaryShape: Shape<ComputerSessionSummary> =\n object<ComputerSessionSummary>({\n id: always(string<ComputerSessionId>()),\n kind: always(string<ComputerSessionKind>()),\n notebook: omitEmpty(string()),\n client: always(string<ComputerSessionClient>()),\n openedBy: always(string()),\n openedAt: always(timestampShape),\n yours: always(boolean()),\n });\n\n/**\n * Judges the summary against this SDK's contract: a canonical ID, a kind and\n * a client this SDK names, who and when, and a notebook exactly on a notebook\n * cell. Throws a `TypeError`.\n */\nexport function validateComputerSessionSummary(\n summary: ComputerSessionSummary,\n): void {\n parseComputerSessionId(summary.id);\n validateComputerSessionKind(summary.kind);\n prefixed(\"client\", () => {\n if (summary.client === \"\") {\n throw new TypeError(\"computer session client is required\");\n }\n });\n validateStatedClient(summary.client);\n if (summary.openedBy === \"\") throw new TypeError(\"openedBy is required\");\n if (isZeroInstant(summary.openedAt)) {\n throw new TypeError(\"openedAt is required\");\n }\n const notebook = summary.notebook ?? \"\";\n if ((summary.kind === \"notebook-cell\") !== (notebook !== \"\")) {\n throw new TypeError(\"notebook must be set exactly on a notebook cell\");\n }\n if (notebook !== \"\") {\n prefixed(\"notebook\", () => {\n validateComputerNotebookName(notebook);\n });\n }\n}\n\n/**\n * Every open session of a Computer, oldest first. The Computer's session\n * limit bounds it, so it is not paged.\n */\nexport interface ListComputerSessionsResponse {\n /** The open sessions. Always written, empty when none is open. */\n readonly items: readonly ComputerSessionSummary[];\n}\n\nconst listComputerSessionsResponseShape: Shape<ListComputerSessionsResponse> =\n object<ListComputerSessionsResponse>({\n items: always(array(computerSessionSummaryShape)),\n });\n\n/**\n * Reads a session list leniently: a field or kind newer than this SDK is\n * carried rather than refused, and {@link validateComputerSessionSummary}\n * judges each session.\n */\nexport function decodeListComputerSessionsResponse(\n document: unknown,\n): ListComputerSessionsResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listComputerSessionsResponseShape, \"lenient\");\n}\n\n/** Renders a session list as the document the platform emits. */\nexport function encodeListComputerSessionsResponse(\n page: ListComputerSessionsResponse,\n): unknown {\n return listComputerSessionsResponseShape.encode(page);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n always,\n integer,\n object,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\n\n/**\n * Work being recovered into a Computer: files kept after the session that\n * wrote them ended without saving them, on their way to a new version.\n * The platform publishes that version by itself; no caller action is needed\n * or offered. Once it is published, the version's save entry carries the\n * trigger `recovery` and the Computer reports no recovery. Where a newer\n * version changed a path the recovered work also changed, the newer file\n * stays and the recovered one is written beside it under the name\n * `<stem>.recovered-v<N><ext>`, N being the recovered version's number, so\n * nothing newer is ever overwritten.\n */\nexport interface ComputerRecovery {\n /** How many files hold recovered changes. Always written. */\n readonly files: Integer;\n /** The total size of those files, in bytes. Always written. */\n readonly bytes: Integer;\n /**\n * When the platform learned of the recovered work, as an RFC 3339\n * timestamp. Always written.\n */\n readonly since: string;\n}\n\n/** The wire shape of a Computer's recovery. */\nexport const computerRecoveryShape: Shape<ComputerRecovery> =\n object<ComputerRecovery>({\n files: always(integer({ unsigned: false, bits: 64 })),\n bytes: always(integer({ unsigned: false, bits: 64 })),\n since: always(timestampShape),\n });\n\n/**\n * Judges the recovery: counts that are not negative and a `since` that is\n * set. Throws a `TypeError`.\n */\nexport function validateComputerRecovery(recovery: ComputerRecovery): void {\n if (BigInt(recovery.files) < 0n || BigInt(recovery.bytes) < 0n) {\n throw new TypeError(\"recovery counts must be non-negative\");\n }\n if (recovery.since === \"\") {\n throw new TypeError(\"recovery since is required\");\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"./json.js\";\nimport {\n always,\n integer,\n object,\n omitEmpty,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport {\n parseJournalEntryId,\n parseComputerId,\n type JournalEntryId,\n type ComputerId,\n} from \"./uuid-id.js\";\nimport { prefixed } from \"./validation.js\";\n\n/** Names one Computer in the request's Account and Namespace. */\nexport interface StorageResourceReference {\n /** Stable Computer identity. */\n readonly computer?: ComputerId;\n}\n/** The inline wire fields shared by resource ownership and historical references. */\nexport const storageResourceReferenceFields = {\n computer: omitEmpty(string<ComputerId>()),\n};\n/** The canonical wire shape of one resource reference. */\nexport const storageResourceReferenceShape: Shape<StorageResourceReference> =\n object<StorageResourceReference>(storageResourceReferenceFields);\n/** Requires one canonical source identity; authorization remains a server check. */\nexport function validateStorageResourceReference(\n reference: StorageResourceReference,\n): void {\n const computer = reference.computer ?? \"\";\n if (computer === \"\") throw new TypeError(\"computer is required\");\n parseComputerId(computer);\n}\n/**\n * Fixes the source journal entry a create operation copies. Later changes\n * to the source do not change the new resource's history.\n */\nexport interface ForkReference {\n readonly source: StorageResourceReference;\n /**\n * The source entry the fork starts at: an entry of the source's journal.\n */\n readonly entry: JournalEntryId;\n}\n/** The wire shape of an immutable fork point. */\nexport const forkReferenceShape: Shape<ForkReference> = object<ForkReference>({\n source: always(storageResourceReferenceShape),\n entry: always(string<JournalEntryId>()),\n});\n/** Checks source and entry identities without reading or authorizing the source. */\nexport function validateForkReference(reference: ForkReference): void {\n prefixed(\"source\", () => {\n validateStorageResourceReference(reference.source);\n });\n prefixed(\"entry\", () => {\n parseJournalEntryId(reference.entry);\n });\n}\n/** Historical fork provenance; version zero is reported genesis, distinct from a create's entry target. */\nexport interface VersionRef extends StorageResourceReference {\n readonly version: Integer;\n}\n/** The wire shape of historical resource/version provenance. */\nexport const versionRefShape: Shape<VersionRef> = object<VersionRef>({\n ...storageResourceReferenceFields,\n version: always(integer({ unsigned: false, bits: 64 })),\n});\n/** Checks resource identity and nonnegative version number. */\nexport function validateVersionRef(reference: VersionRef): void {\n validateStorageResourceReference(reference);\n if (reference.version < 0)\n throw new TypeError(\"version must be non-negative\");\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n compareDuration,\n durationShape,\n formatDuration,\n type Duration,\n} from \"./duration.js\";\nimport {} from \"./storage.js\";\nimport { boolean } from \"../internal/strictdecode.js\";\nimport {\n object,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\n\nimport { validateIdleTimeout, type IdleTimeout } from \"./idle-timeout.js\";\n\nimport {\n validateComputerExecutionSettings,\n computerExecutionSettingsShape,\n type ComputerExecutionSettings,\n} from \"./computer-execution-settings.js\";\n\nimport { prefixed } from \"./validation.js\";\n\n/** The shortest `saveQuiet` a Computer accepts: one second. */\nconst MIN_COMPUTER_SAVE_QUIET: Duration = { seconds: 1, nanoseconds: 0 };\n/** The longest `saveQuiet` a Computer accepts: ten minutes. */\nconst MAX_COMPUTER_SAVE_QUIET: Duration = { seconds: 600, nanoseconds: 0 };\n/** The shortest `saveMaxInterval` a Computer accepts: ten seconds. */\nconst MIN_COMPUTER_SAVE_MAX_INTERVAL: Duration = {\n seconds: 10,\n nanoseconds: 0,\n};\n/** The longest `saveMaxInterval` a Computer accepts: one hour. */\nconst MAX_COMPUTER_SAVE_MAX_INTERVAL: Duration = {\n seconds: 3_600,\n nanoseconds: 0,\n};\n\n/**\n * How a Computer runs. Every field is optional, and a spec that states\n * nothing is written as `{}` rather than omitted, keeping the manifest\n * envelope of kind, metadata, and spec.\n */\nexport interface ComputerSpec {\n /**\n * Whether the Computer saves its workspace on its own: after changes, when\n * each session ends, and at release. `false` saves only on demand and at\n * release, and a session then reports its save as `off`. An explicit\n * `false` remains stated. `undefined` takes the default, `true`.\n */\n readonly autoSave?: boolean;\n /**\n * How long writes to the workspace must have been quiet before a\n * change-driven save runs: a duration from `1s` to `10m`. `undefined`\n * takes the default, `10s`.\n */\n readonly saveQuiet?: Duration;\n /**\n * The longest time between saves while writes continue and a session is\n * open, so continuous writes are never left unsaved for longer: a\n * duration from `10s` to `1h`, and at least `saveQuiet`. The platform\n * judges it against the `saveQuiet` in force, its default included.\n * `undefined` takes the default, `2m`.\n */\n readonly saveMaxInterval?: Duration;\n /** Nonnegative failing-save budget, with zero preserved; omission uses server policy. */\n readonly saveWindow?: Duration;\n /**\n * How long the Computer keeps its execution after its last session\n * ends: `never`, or a whole number followed by `s`, `m`, or `h`, at least\n * `0s`. The platform states it canonically in seconds, so `5m` reads\n * back as `300s`. `undefined` takes the default, `300s`. See\n * {@link IdleTimeout}.\n */\n readonly idleTimeout?: IdleTimeout;\n /**\n * The execution settings of a Computer: its OS image, size or CPU and\n * memory, network, and environment variables. A create states the whole document, and a field\n * it leaves out takes IDYL's default; an update changes it field by field.\n * A served Computer states the image it runs, unless its Subnet offered no\n * image when it was created.\n * See {@link ComputerExecutionSettings}.\n */\n readonly execution?: ComputerExecutionSettings;\n}\n\nexport const computerSpecShape: Shape<ComputerSpec> = object<ComputerSpec>({\n idleTimeout: pointer(string()),\n autoSave: pointer(boolean()),\n saveQuiet: pointer(durationShape),\n saveMaxInterval: pointer(durationShape),\n saveWindow: pointer(durationShape),\n execution: pointer(computerExecutionSettingsShape),\n});\n\n/**\n * Judges every field the spec states. A spec that states nothing is valid:\n * the platform applies the defaults. `saveMaxInterval` is judged against\n * `saveQuiet` only when both are stated; the platform judges the pair in\n * force. Throws a `TypeError` naming the field,\n * such as `idleTimeout: idle timeout must be non-negative`; a refusal of the\n * computer is a `ComputerExecutionSettingsError` naming the field.\n */\nexport function validateComputerSpec(spec: ComputerSpec): void {\n if (spec.idleTimeout !== undefined) {\n prefixed(\"idleTimeout\", () => {\n validateIdleTimeout(spec.idleTimeout ?? \"\");\n });\n }\n validateComputerSaveSettings(spec.saveQuiet, spec.saveMaxInterval);\n if (\n spec.saveWindow !== undefined &&\n compareDuration(spec.saveWindow, { seconds: 0, nanoseconds: 0 }) < 0\n )\n throw new TypeError(\"saveWindow must be non-negative\");\n if (spec.execution !== undefined)\n validateComputerExecutionSettings(spec.execution);\n}\n\n/**\n * Judges the change-driven save settings a spec or an update states: each\n * within its range, and the interval at least the quiet time when both are\n * stated.\n */\nfunction validateComputerSaveSettings(\n quiet: Duration | undefined,\n interval: Duration | undefined,\n): void {\n if (\n quiet !== undefined &&\n (compareDuration(quiet, MIN_COMPUTER_SAVE_QUIET) < 0 ||\n compareDuration(quiet, MAX_COMPUTER_SAVE_QUIET) > 0)\n ) {\n throw new TypeError(\n `saveQuiet must be from ${formatDuration(MIN_COMPUTER_SAVE_QUIET)} to ${formatDuration(MAX_COMPUTER_SAVE_QUIET)}`,\n );\n }\n if (interval === undefined) return;\n if (\n compareDuration(interval, MIN_COMPUTER_SAVE_MAX_INTERVAL) < 0 ||\n compareDuration(interval, MAX_COMPUTER_SAVE_MAX_INTERVAL) > 0\n ) {\n throw new TypeError(\n `saveMaxInterval must be from ${formatDuration(MIN_COMPUTER_SAVE_MAX_INTERVAL)} to ${formatDuration(MAX_COMPUTER_SAVE_MAX_INTERVAL)}`,\n );\n }\n if (quiet !== undefined && compareDuration(interval, quiet) < 0) {\n throw new TypeError(\"saveMaxInterval must be at least saveQuiet\");\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { parseJson } from \"../resource/json.js\";\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport type { JsonObject } from \"../resource/json.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n isComputerImageDigestReference,\n validateComputerImageName,\n type ComputerIsolationClass,\n} from \"../resource/computer-execution-settings.js\";\nimport type { ListResponse } from \"./types.js\";\n\n/** The operating system of an IDYL image catalog entry and its version. */\nexport interface ComputerImageOs {\n /** The OS, such as `ubuntu`, `debian`, or `alpine`. */\n readonly name: string;\n /** The OS version, such as `24.04` or `12`. */\n readonly version: string;\n}\n\n/**\n * One entry of the IDYL image catalog of a Subnet: an OS image IDYL\n * publishes for Computers, which a Computer chooses by `name` as\n * `ComputerExecutionSettingsImage.idyl`. IDYL keeps each entry patched: a patch\n * gives the entry a new pinned `image` and a later `patch` for the same OS\n * and versions, and a Computer on the entry runs it from its next start.\n * Another OS or version is another entry with another name.\n *\n * The catalog is read-only and served by the Subnet's API. A read decodes\n * leniently, and {@link validateComputerImage} judges the entry against\n * this SDK's contract.\n */\nexport interface ComputerImage {\n /** The entry's stable catalog name, what a Computer's settings store, such as `ubuntu-24.04`. */\n readonly name: string;\n /** The entry's name for a person, such as `Python 3.12 on Ubuntu 24.04`. */\n readonly displayName: string;\n /** What the image holds beyond its OS, such as `pip, numpy, pandas`. */\n readonly description?: string;\n /** The operating system the image runs, which a patch never changes. */\n readonly os: ComputerImageOs;\n /** Whether the image is built for a computer with a GPU. Always written. */\n readonly gpu: boolean;\n /** The entry's current pinned image, by digest: what a start on the entry runs now. */\n readonly image: string;\n /** The entry's current patch level, such as `2026.10.12` or `2026.10.12.2`. See {@link validateComputerImagePatch}. */\n readonly patch: string;\n /** Whether a create that states no image receives this entry; at most one entry is the default. Always written. */\n readonly default: boolean;\n /**\n * The isolation class the entry serves: a Computer in that class, and no\n * other, may name it. Each entry serves one class. `undefined` is\n * `secure-container`, and none is written.\n */\n readonly isolation?: ComputerIsolationClass;\n}\n\nconst computerImageShape: Shape<ComputerImage> = object<ComputerImage>({\n name: always(string()),\n displayName: always(string()),\n description: omitEmpty(string()),\n os: always(\n object<ComputerImageOs>({\n name: always(string()),\n version: always(string()),\n }),\n ),\n gpu: always(boolean()),\n image: always(string()),\n patch: always(string()),\n default: always(boolean()),\n isolation: omitEmpty(string<ComputerIsolationClass>()),\n});\n\n/**\n * The IDYL image catalog of one Subnet, served whole on one page. Without a\n * query it lists the entries a Computer in `secure-container` may name.\n * With the query `isolation`, naming an isolation class a Computer may\n * select, it lists the entries a Computer in that class may name, each\n * stating the class, and is empty when the Subnet's runtime policy does not\n * admit the class, so a client offers a class exactly when its list is not\n * empty. The route takes no other options.\n */\nexport type ListComputerImagesResponse = ListResponse<ComputerImage>;\n\nconst listComputerImagesResponseShape: Shape<ListComputerImagesResponse> =\n object<ListComputerImagesResponse>({\n items: always(array(computerImageShape)),\n totalCount: always(integer({ unsigned: false, bits: 64 })),\n snapshotCursor: omitEmpty(string()),\n continue: omitEmpty(string()),\n });\n\n/** Reads one catalog entry the platform served, leniently. `document` is JSON text or a parsed value. */\nexport function decodeComputerImage(document: unknown): ComputerImage {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, computerImageShape, \"lenient\");\n}\n\n/** Renders a catalog entry as the document the platform emits. */\nexport function encodeComputerImage(image: ComputerImage): JsonObject {\n return computerImageShape.encode(image) as JsonObject;\n}\n\n/** Reads a catalog the platform served, leniently. */\nexport function decodeListComputerImagesResponse(\n document: unknown,\n): ListComputerImagesResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listComputerImagesResponseShape, \"lenient\");\n}\n\n/** Renders a catalog as the document the platform emits. */\nexport function encodeListComputerImagesResponse(\n response: ListComputerImagesResponse,\n): JsonObject {\n return listComputerImagesResponseShape.encode(response) as JsonObject;\n}\n\n/**\n * Judges the entry against this SDK's contract: a name in catalog form, a\n * display name, an OS and its version, an image pinned by digest, a patch\n * level in its form, and an isolation class a Computer may select,\n * `secure-container` or `vm`, when one is stated. Throws a `TypeError`.\n */\nexport function validateComputerImage(image: ComputerImage): void {\n prefixed(\"name\", () => {\n validateComputerImageName(image.name);\n });\n if (image.displayName === \"\") {\n throw new TypeError(\"displayName is required\");\n }\n if (image.os.name === \"\" || image.os.version === \"\") {\n throw new TypeError(\"os.name and os.version are required\");\n }\n if (!isComputerImageDigestReference(image.image)) {\n throw new TypeError(\"image must be pinned by a sha256 digest\");\n }\n prefixed(\"patch\", () => {\n validateComputerImagePatch(image.patch);\n });\n const isolation = image.isolation ?? \"\";\n if (\n isolation !== \"\" &&\n isolation !== \"secure-container\" &&\n isolation !== \"vm\"\n ) {\n throw new TypeError(\"isolation: must be secure-container or vm\");\n }\n}\n\n/** A patch level read into its date and its sequence number that day. */\ninterface PatchLevel {\n readonly date: number;\n readonly n: number;\n}\n\nfunction parsePatchLevel(patch: string): PatchLevel {\n const match =\n /^([0-9]{4})\\.([0-9]{2})\\.([0-9]{2})(?:\\.([1-9][0-9]{0,8}))?$/u.exec(patch);\n if (match === null) {\n throw new TypeError(\"must be YYYY.MM.DD with an optional .N\");\n }\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n // Date.UTC reads years 0 through 99 as 1900 through 1999, so the year is\n // set on its own.\n const date = new Date(0);\n date.setUTCFullYear(year, month - 1, day);\n if (\n date.getUTCFullYear() !== year ||\n date.getUTCMonth() !== month - 1 ||\n date.getUTCDate() !== day\n ) {\n throw new TypeError(\"must name a calendar date\");\n }\n return {\n date: date.getTime(),\n n: match[4] === undefined ? 0 : Number(match[4]),\n };\n}\n\n/**\n * Judges the form of a catalog entry's patch level: a date, `YYYY.MM.DD`,\n * optionally followed by `.N` for the N-th patch published that day, N a\n * positive whole number without leading zeros. Levels order by date, then\n * by N, a level without N first. Throws a `TypeError` stating the rule.\n */\nexport function validateComputerImagePatch(patch: string): void {\n parsePatchLevel(patch);\n}\n\n/** Orders two valid patch levels by date, then by N: negative, zero, or positive. */\nexport function compareComputerImagePatch(left: string, right: string): number {\n const a = parsePatchLevel(left);\n const b = parsePatchLevel(right);\n if (a.date !== b.date) return a.date < b.date ? -1 : 1;\n if (a.n !== b.n) return a.n < b.n ? -1 : 1;\n return 0;\n}\n\n/**\n * The image a Computer's execution environment runs, as a read reports it: for an IDYL\n * image, the catalog entry's name, display name, and description with the\n * patch level and pinned image of the start `started` says; for an own\n * image, the reference as given.\n */\nexport interface ComputerExecutionSettingsImageStatus {\n /** The IDYL image's catalog name; absent for an own image. */\n readonly name?: string;\n /** The catalog entry's name for a person; absent for an own image. */\n readonly displayName?: string;\n /** What the IDYL image holds beyond its OS. */\n readonly description?: string;\n /**\n * The patch level of the IDYL image: the one the Computer last started\n * on when `started` is true, and the one its next start would use when it\n * is false.\n */\n readonly patch?: string;\n /** The pinned image, by digest, of that patch level. */\n readonly image?: string;\n /**\n * Present exactly for an IDYL image: true when `patch` and `image` are\n * those the Computer last started on, false before it has started on the\n * entry it names.\n */\n readonly started?: boolean;\n /** The own image's reference, as the settings state it; absent for an IDYL image. */\n readonly ref?: string;\n}\n\n/** The wire shape of a Computer's image status. */\nexport const computerExecutionSettingsImageStatusShape: Shape<ComputerExecutionSettingsImageStatus> =\n object<ComputerExecutionSettingsImageStatus>({\n name: omitEmpty(string()),\n displayName: omitEmpty(string()),\n description: omitEmpty(string()),\n patch: omitEmpty(string()),\n image: omitEmpty(string()),\n started: pointer(boolean()),\n ref: omitEmpty(string()),\n });\n\n/**\n * Judges the status against this SDK's contract: exactly one of `name` and\n * `ref`; for an IDYL image a display name, a patch level in its form, an\n * image pinned by digest, and `started`; for an own image nothing else.\n * Throws a `TypeError`.\n */\nexport function validateComputerExecutionSettingsImageStatus(\n status: ComputerExecutionSettingsImageStatus,\n): void {\n const name = status.name ?? \"\";\n const ref = status.ref ?? \"\";\n if ((name === \"\") === (ref === \"\")) {\n throw new TypeError(\"image must state exactly one of name and ref\");\n }\n if (ref !== \"\") {\n if (\n (status.displayName ?? \"\") !== \"\" ||\n (status.description ?? \"\") !== \"\" ||\n (status.patch ?? \"\") !== \"\" ||\n (status.image ?? \"\") !== \"\" ||\n status.started !== undefined\n ) {\n throw new TypeError(\"image of an own image carries only ref\");\n }\n return;\n }\n if ((status.displayName ?? \"\") === \"\") {\n throw new TypeError(\"image.displayName is required for an IDYL image\");\n }\n prefixed(\"image.patch\", () => {\n validateComputerImagePatch(status.patch ?? \"\");\n });\n if (!isComputerImageDigestReference(status.image ?? \"\")) {\n throw new TypeError(\"image.image must be pinned by a sha256 digest\");\n }\n if (status.started === undefined) {\n throw new TypeError(\"image.started is required for an IDYL image\");\n }\n}\n\n/**\n * Returned with HTTP 422 when a create or an update names an IDYL image the\n * catalog of the Computer's Subnet does not hold. The details name the\n * image under `name`. The request changes nothing; `listImages` reads the\n * catalog.\n */\nexport const ERROR_CODE_IMAGE_NOT_IN_CATALOG = \"IMAGE_NOT_IN_CATALOG\";\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { computerAwakeShape, type ComputerAwake } from \"./computer-awake.js\";\nimport {\n computerRecoveryShape,\n type ComputerRecovery,\n} from \"./computer-recovery.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport { durationShape, type Duration } from \"../resource/duration.js\";\nimport {\n forkReferenceShape,\n versionRefShape,\n validateForkReference,\n type ForkReference,\n type VersionRef,\n} from \"../resource/storage.js\";\nimport {\n volumeQuantityShape,\n type VolumeQuantity,\n} from \"../resource/volume.js\";\nimport {\n storageStatusShape,\n storageUsageShape,\n type StorageStatus,\n type StorageUsage,\n} from \"./storage.js\";\nimport {\n always,\n array,\n boolean,\n fieldPath,\n decodeValue,\n integer,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport {\n parseAccountId,\n parseSubnetSlug,\n type AccountId,\n} from \"../resource/id.js\";\nimport { StrictDecodeError } from \"../resource/decode-error.js\";\nimport {\n cpuQuantityShape,\n isZeroCpu,\n type CpuQuantity,\n} from \"../resource/cpu.js\";\nimport {\n validateIdleTimeout,\n type IdleTimeout,\n} from \"../resource/idle-timeout.js\";\nimport type { JsonObject, JsonValue } from \"../resource/json.js\";\nimport {\n isZeroMemory,\n memoryQuantityShape,\n type MemoryQuantity,\n} from \"../resource/memory.js\";\nimport {\n workloadNetworkShape,\n type WorkloadNetwork,\n} from \"../resource/workload-network.js\";\nimport { publicIdShape, timestampShape } from \"../resource/shapes.js\";\nimport {\n isComputerId,\n type NamespaceId,\n type ComputerId,\n type JournalEntryId,\n} from \"../resource/uuid-id.js\";\nimport {\n errorMessage,\n pathPrefixed,\n prefixed,\n} from \"../resource/validation.js\";\nimport {\n validateComputerSpec,\n computerSpecShape,\n type ComputerSpec,\n} from \"../resource/computer.js\";\nimport type { ListResponse } from \"./types.js\";\nimport {\n computerExecutionSettingsImageStatusShape,\n type ComputerExecutionSettingsImageStatus,\n} from \"./computer-image.js\";\nimport {\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\nimport {\n ComputerExecutionSettingsError,\n validateComputerExecutionSettings,\n validateComputerEnvironmentVariableName,\n computerExecutionSettingsImageShape,\n computerEnvironmentVariableShape,\n computerSecretAttachmentShape,\n computerIdentityShape,\n type ComputerIdentity,\n type ComputerSecretAttachment,\n imageShellShape,\n validateComputerSize,\n type ComputerExecutionSettings,\n type ComputerSize,\n type ComputerExecutionSettingsImage,\n type ComputerEnvironmentVariable,\n type ComputerIsolationClass,\n type ImageShell,\n} from \"../resource/computer-execution-settings.js\";\n\n/**\n * The lifecycle state of a Computer.\n *\n * - `active`: in service; it resolves, and its operations are accepted\n * subject to authorization.\n * - `terminating`: deletion has been accepted and not yet finalized. It\n * still resolves, and reads and deletes are accepted.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerPhase} judges\n * membership.\n */\nexport type ComputerPhase =\n \"active\" | \"terminating\" | (string & Record<never, never>);\n\n/**\n * Judges that the phase is one this SDK names. The empty string is reported\n * as missing: a served Computer always carries a phase. Throws a\n * `TypeError`.\n */\nexport function validateComputerPhase(phase: ComputerPhase): void {\n switch (phase) {\n case \"active\":\n case \"terminating\":\n return;\n case \"\":\n throw new TypeError(\"computer phase is required\");\n default:\n throw new TypeError(`unknown computer phase ${JSON.stringify(phase)}`);\n }\n}\n\n/**\n * Whether anything is executing on a Computer's behalf. It is independent\n * of the phase, which reports the Computer's lifecycle: an active Computer\n * may be dormant, and execution is reported, not requested.\n *\n * - `dormant`: nothing is executing. The Computer's durable state is\n * retained and no compute is held for it.\n * - `running`: execution is in progress.\n * - `waiting`: execution is suspended until something it waits on happens.\n * No compute is held for it while it waits.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerExecution} judges\n * membership, and a caller treats an unknown value as neither dormant nor\n * running.\n */\nexport type ComputerExecution =\n \"dormant\" | \"running\" | \"waiting\" | (string & Record<never, never>);\n\n/**\n * Judges that the execution state is one this SDK names. The empty string\n * is reported as missing: a served Computer always carries one. Throws a\n * `TypeError`.\n */\nexport function validateComputerExecution(execution: ComputerExecution): void {\n switch (execution) {\n case \"dormant\":\n case \"running\":\n case \"waiting\":\n return;\n case \"\":\n throw new TypeError(\"computer execution is required\");\n default:\n throw new TypeError(\n `unknown computer execution ${JSON.stringify(execution)}`,\n );\n }\n}\n\n/**\n * What a Computer's next start uses, as a read reports it. `size`, `cpu`,\n * `memory` and `disk` are stated together, where `ComputerExecutionSettings`\n * states `size` or `cpu` and `memory`, because this is the outcome of those\n * settings rather than a statement of them. No write accepts it, since writing\n * it back would fix the defaults it resolved. A size newer than this SDK is\n * carried.\n */\nexport interface ComputerEffectiveExecutionSettings {\n /** The OS image the settings name; absent while they name none. */\n readonly image?: ComputerExecutionSettingsImage;\n /**\n * The name of the size whose CPU and memory the computer's limits are. Absent\n * while they are no size's, and while the platform runs no execution for the\n * Computer's Subnet.\n */\n readonly size?: ComputerSize;\n /**\n * The name a person reads for `size`, `ComputerSizeInfo.label`, such as\n * `Small`, so a reader can show it with no second request. Absent while\n * `size` is.\n */\n readonly sizeLabel?: string;\n /** The CPU limit; absent while the platform runs no execution for the Computer's Subnet. */\n readonly cpu?: CpuQuantity;\n /** The memory limit; absent while the platform runs no execution for the Computer's Subnet. */\n readonly memory?: MemoryQuantity;\n /**\n * The most the Computer can store. The Computer holds it apart from its\n * current size, so it is what the platform recorded for the Computer. Absent\n * while the platform reports none.\n */\n readonly disk?: VolumeQuantity;\n /** The network the computer runs with, the Subnet's default resolved; absent while none can be resolved. */\n readonly network?: WorkloadNetwork;\n /** The environment variables the settings state, in order. */\n readonly variables?: readonly ComputerEnvironmentVariable[];\n /** The default shell the settings state; absent while they state none. */\n readonly shell?: string;\n}\n\nconst computerEffectiveExecutionSettingsShape: Shape<ComputerEffectiveExecutionSettings> =\n object<ComputerEffectiveExecutionSettings>({\n image: pointer(computerExecutionSettingsImageShape),\n size: omitEmpty(string()),\n sizeLabel: omitEmpty(string()),\n cpu: omitZero(cpuQuantityShape),\n memory: omitZero(memoryQuantityShape),\n disk: omitZero(volumeQuantityShape),\n network: pointer(workloadNetworkShape),\n variables: omitEmpty(array(computerEnvironmentVariableShape)),\n shell: omitEmpty(string()),\n });\n\n/**\n * The state of a Computer's execution settings: which revision is in force,\n * the journal entry that recorded it, whether the computer still runs on an\n * earlier one, and what the computer's next start uses.\n */\nexport interface ComputerExecutionSettingsStatus {\n /**\n * Counts the changes to the execution settings: zero before the first,\n * then one more with each. Always written, since zero is a reading.\n */\n readonly revision: Integer;\n /**\n * The journal entry that recorded the settings in force: of kind\n * `execution-settings`, or `restore` when a restore set them. Absent while\n * the Computer has recorded no settings.\n */\n readonly entry?: JournalEntryId;\n /**\n * Whether the computer is running, for the sessions that run on it, on\n * settings older than `revision`. The settings in force take effect once\n * those sessions end. Always written.\n */\n readonly pending: boolean;\n /**\n * What the computer's next start uses: the stated settings with every\n * field they leave out filled in with the default it resolves to now, the\n * network the Subnet's default included, and the size with its CPU, memory\n * and disk stated together. Always written.\n */\n readonly effective: ComputerEffectiveExecutionSettings;\n /**\n * The image the computer runs, with the patch level of an IDYL image;\n * absent while the settings state no image.\n */\n readonly image?: ComputerExecutionSettingsImageStatus;\n /**\n * The shells the computer's image held when the computer last started,\n * read from the image's `/etc/shells`: each listed path the image holds as\n * an executable, once per file and name, without login-refusing and\n * restricted shells, with `/bin/bash` and `/bin/sh` added when the image\n * holds them, at most `MAX_IMAGE_SHELLS`, in the file's order. A start\n * whose list could not be read keeps the list before it. Absent before\n * the computer first starts; the image may have changed since, so a shell\n * listed here is offered, not promised.\n */\n readonly shells?: readonly ImageShell[];\n /**\n * The largest size the Computer's Subnet can run now: the largest size\n * whose CPU and memory, with the runtime's own allowance, fit a ready host\n * of the Subnet. A create or a change of the settings at a larger size is\n * refused with {@link ERROR_CODE_COMPUTER_DOES_NOT_FIT}; every size up to\n * it is accepted. Absent while the Subnet has\n * no ready host, and no size is then refused for want of a host that fits\n * it. `validateComputerSize` judges its form.\n */\n readonly largestSize?: ComputerSize;\n}\n\nconst computerExecutionSettingsStatusShape: Shape<ComputerExecutionSettingsStatus> =\n object<ComputerExecutionSettingsStatus>({\n revision: always(integer({ unsigned: false, bits: 64 })),\n entry: omitEmpty(string<JournalEntryId>()),\n pending: always(boolean()),\n effective: always(computerEffectiveExecutionSettingsShape),\n image: pointer(computerExecutionSettingsImageStatusShape),\n shells: omitEmpty(array(imageShellShape)),\n largestSize: omitEmpty(string()),\n });\n\n/**\n * A Computer as the platform serves it: one durable logical computer,\n * owned by a Namespace and living in one Subnet. It retains its state\n * independently of any execution.\n *\n * A Computer is addressed by Subnet, Namespace, and name together: `name`\n * is unique among the live Computers of its Namespace in its Subnet, so\n * equal names in two Subnets of one Namespace are two Computers. `name`\n * changes when the Computer is renamed ({@link UpdateComputerRequest});\n * the name it had is free at once for another Computer, as a name is once\n * its holder has been finalized. `id` is the stable identity the by-ID\n * routes address, and never changes: a caller that must keep reaching one\n * Computer across renames holds its ID. `namespaceId` is the stable\n * identity of the owning Namespace.\n *\n * `subnet` is the canonical twelve-digit slug of the Subnet the Computer\n * lives in. It is chosen at creation and never changes: a Computer needed\n * in another Subnet is created there as a new Computer. The Subnet's API\n * serves the Computer.\n *\n * `phase` is the lifecycle state: `active` while the Computer is in\n * service, and `terminating` from the moment a delete is accepted until the\n * platform finalizes the release. `terminatingAt` is the instant the delete\n * was recorded, the same instant the delete response reported as\n * `deletedAt`, and is present only while terminating. A finalized Computer\n * resolves 404.\n *\n * `execution` reports whether anything is executing on the Computer's\n * behalf. `headVersion` is the number of the Computer's committed version:\n * it starts at zero, the empty genesis version, and is always written,\n * since zero is a reading rather than an absence.\n *\n * `spec` states how the Computer runs. Its idle timeout is written in the\n * canonical spelling, a whole number of seconds with `s` or `never`; a\n * Computer that states none runs with `DEFAULT_IDLE_TIMEOUT`. Its `spec.execution`\n * holds the settings as stated; `executionSettings` reports which revision of them is in\n * force, what the computer's next start uses, and the image it runs.\n */\nexport interface Computer {\n /** Usage observations when reported; present objects retain all zero counts. */\n readonly usage?: StorageUsage;\n /**\n * Work on its way into the Computer as a new version, after the session\n * that wrote it ended without saving it. A read of one Computer reports\n * it until the version is published; it is absent from every other\n * response.\n */\n readonly recovery?: ComputerRecovery;\n /** Historical saved-state provenance, independent of ongoing copying. */\n readonly forkOf?: VersionRef;\n /** Copying progress only when reported. */\n readonly status?: StorageStatus;\n readonly id: ComputerId;\n readonly accountId: AccountId;\n readonly namespaceId: NamespaceId;\n readonly namespace: string;\n readonly subnet: string;\n readonly name: string;\n readonly phase: ComputerPhase;\n readonly execution: ComputerExecution;\n readonly headVersion: Integer;\n /** How the Computer runs; always written. */\n readonly spec: ComputerSpec;\n /** The state of the Computer's execution settings; absent from a platform that does not report it. */\n readonly executionSettings?: ComputerExecutionSettingsStatus;\n /** When the platform created the Computer, as an RFC 3339 instant. */\n readonly createdAt: string;\n /** When the platform last updated the Computer, as an RFC 3339 instant. */\n readonly updatedAt: string;\n /** When the delete was recorded, as an RFC 3339 instant; present only while terminating. */\n readonly terminatingAt?: string;\n /**\n * When the Computer last woke or went to sleep, as an RFC 3339 instant:\n * while it runs, when it woke. List responses report it; it is absent from\n * a read of one Computer and for a Computer that has never run.\n */\n readonly lastUsedAt?: string;\n /**\n * Why the Computer is awake and when it will sleep. A read of one Computer\n * reports it while `execution` is `running`. It is absent from every other\n * response, so its absence from a list says nothing about the Computer.\n */\n readonly awake?: ComputerAwake;\n /**\n * Whether a running Computer is on its way to sleep: a sleep was asked for,\n * or its idle time has run out. `execution` stays `running` while it saves\n * and until it is released. A read of one Computer and a list both report\n * it, so every reader states the same thing. A session opened before an idle\n * sleep is released clears it, because the Computer then stays awake.\n * `undefined` means it is not going to sleep.\n */\n readonly goingToSleep?: boolean;\n}\n\nconst computerShape: Shape<Computer> = object<Computer>({\n id: always(string<ComputerId>()),\n accountId: always(publicIdShape(parseAccountId)),\n namespaceId: always(string<NamespaceId>()),\n namespace: always(string()),\n subnet: always(string()),\n name: always(string()),\n phase: always(string<ComputerPhase>()),\n execution: always(string<ComputerExecution>()),\n headVersion: always(integer({ unsigned: false, bits: 64 })),\n spec: always(computerSpecShape),\n usage: pointer(storageUsageShape),\n recovery: pointer(computerRecoveryShape),\n forkOf: pointer(versionRefShape),\n status: pointer(storageStatusShape),\n executionSettings: pointer(computerExecutionSettingsStatusShape),\n awake: pointer(computerAwakeShape),\n goingToSleep: omitEmpty(boolean()),\n createdAt: always(timestampShape),\n updatedAt: always(timestampShape),\n terminatingAt: pointer(timestampShape),\n lastUsedAt: pointer(timestampShape),\n});\n\n/**\n * Renders a served Computer as the document the platform emits: `phase`,\n * `execution`, `headVersion`, and `spec` are always written, zero and `{}`\n * included, and `terminatingAt` only when present.\n */\nexport function encodeComputer(computer: Computer): JsonObject {\n return computerShape.encode(computer) as JsonObject;\n}\n\n/**\n * Reads a Computer the platform served, leniently. `document` is JSON text\n * or a value already parsed from JSON; a string is parsed once, as a\n * response is. A field this SDK does not declare is carried as it arrived,\n * a value the shape cannot read is carried as it arrived, and a missing\n * field reads as its zero value, as the reference contract reads it. Nothing is judged;\n * `validateComputerPhase` and `validateComputerExecution` judge the\n * result.\n */\nexport function decodeComputer(document: unknown): Computer {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, computerShape, \"lenient\");\n}\n\n/**\n * Creates one Computer in the addressed Namespace. `name` must be 3 to 63\n * characters in the platform's computer-name format and unique among the\n * live Computers of the Namespace in the Subnet; `by-id` is reserved, and a\n * name in the form of a Computer ID is refused, so a name is never mistaken\n * for an ID by a tool that accepts either. The name can be changed later\n * ({@link UpdateComputerRequest}). `subnet` is the canonical twelve-digit\n * slug of the Subnet the Computer will live in, and never changes; the Computers service stamps the client's resolved Subnet when\n * it is `undefined`. `spec` states how the Computer runs; every field is\n * optional, and a spec that states nothing is not written, so the request\n * is then the name and the Subnet alone. The platform refuses a request\n * naming a field it does not define rather than ignoring it.\n *\n * The Computer's OS image is chosen at creation: the image `spec.execution`\n * states, or, when it states none, the default entry of the Subnet's IDYL\n * image catalog, stored by its name. The Computer records its first\n * execution settings, whatever the request stated, as the first entry of its\n * journal. An IDYL image the catalog does not hold is refused with\n * `ERROR_CODE_IMAGE_NOT_IN_CATALOG`, a computer whose isolation class the\n * Subnet does not admit with `ERROR_CODE_ISOLATION_CLASS_NOT_ADMITTED`, one\n * whose network class it does not admit with\n * `ERROR_CODE_NETWORK_CLASS_NOT_ADMITTED`, and one that fits no host of the\n * Subnet with\n * {@link ERROR_CODE_COMPUTER_DOES_NOT_FIT}; either way nothing is created.\n */\nexport interface CreateComputerRequest {\n /** Exact source history point copied at creation; source authority remains a server decision. */\n readonly forkOf?: ForkReference;\n /**\n * Asks for a Computer that saves only `/workspace`: its system files\n * outside `/workspace`, such as installed packages, users and `/etc`, start\n * from its image at each wake. `undefined` or `false`, the default, saves\n * the whole system. A fork is held to the same rule whatever its source\n * saves: a fork that states nothing saves the whole system, starting from\n * the source's system files when the source saved them and from its\n * image's otherwise, and a fork that asks for `/workspace` only carries\n * none of the source's system files. `false` is not written.\n */\n readonly workspaceOnly?: boolean;\n /** Equal retries retain the recorded creation outcome in the caller's scope. */\n readonly idempotencyKey?: string;\n readonly name: string;\n readonly subnet?: string;\n readonly spec?: ComputerSpec;\n /**\n * The kind of client sending the request. The execution settings' journal\n * entry records it, as `unknown` when it is absent; it is informative and\n * never authorizes anything. `undefined` or empty states no client, and\n * none is written.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/**\n * The wire shape of a create request: `name` and `subnet` always written,\n * `spec` only when it states a field.\n */\nexport const createComputerRequestShape: Shape<CreateComputerRequest> =\n object<CreateComputerRequest>({\n name: always(string()),\n subnet: omitEmpty(string()),\n spec: omitZero(computerSpecShape),\n forkOf: pointer(forkReferenceShape),\n workspaceOnly: omitEmpty(boolean()),\n idempotencyKey: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n });\n\n/**\n * Judges what can be judged without the platform: a name is present and not\n * in the form of a Computer ID, the Subnet is a canonical slug, and every spec field stated is valid. The\n * name's format and uniqueness, and whether the Subnet accepts the\n * Computer, are the platform's decision. A stated `workspaceOnly` must be\n * a boolean, and a stated client one this SDK names. Throws a `TypeError`, a spec field named as\n * `computer spec.idleTimeout: ...`.\n */\nexport function validateCreateComputerRequest(\n request: CreateComputerRequest,\n): void {\n validateComputerName(request.name);\n const subnet = request.subnet ?? \"\";\n if (subnet === \"\") {\n throw new TypeError(\"computer subnet is required\");\n }\n prefixed(\"computer subnet\", () => {\n parseSubnetSlug(subnet);\n });\n pathPrefixed(\"computer spec\", () => {\n validateComputerSpec(request.spec ?? {});\n });\n if (request.forkOf !== undefined) validateForkReference(request.forkOf);\n if (\n request.workspaceOnly !== undefined &&\n typeof request.workspaceOnly !== \"boolean\"\n ) {\n throw new TypeError(\"workspaceOnly must be a boolean\");\n }\n validateStatedClient(request.client);\n}\n\n/**\n * Judges what of a Computer name can be judged without the platform: it is\n * present, and it is not in the form of a Computer ID.\n */\nfunction validateComputerName(name: string): void {\n if (name.trim() === \"\") {\n throw new TypeError(\"computer name is required\");\n }\n if (isComputerId(name)) {\n throw new TypeError(\n \"computer name must not be in the form of a computer ID\",\n );\n }\n}\n\n/**\n * Changes one live Computer field by field: each field the request states\n * is changed and every field it leaves out keeps the value it has, so a\n * caller states only what it changes and never reads the Computer first.\n * The platform refuses a request naming a field it does not define rather\n * than ignoring it.\n *\n * `name` renames the Computer, at once. The new name is held to the rules a\n * create's name is held to, and a name a live Computer of the same\n * Namespace holds in the same Subnet is refused with HTTP 409, as a\n * create's is; when a rename and a create race for one name, one of them\n * wins. A rename to the name the Computer has changes nothing. A\n * terminating Computer is refused with HTTP 409 and\n * `ERROR_CODE_COMPUTER_TERMINATING`. Any other rename is recorded as one `rename` entry in the\n * Computer's journal. The Computer's ID, files, history and sessions are\n * unchanged: a session addressed by the Computer's ID keeps working, and a\n * request that names the old name is answered as for a Computer that does\n * not exist.\n *\n * `idleTimeout` takes effect at once, from `never` to a finite timeout and\n * back alike, and is measured from when the Computer last became idle, so a\n * Computer already idle for longer than a shortened timeout is released.\n * The idle timeout is not part of the execution settings, so it is not\n * recorded in the Computer's journal.\n *\n * The other fields change the execution settings, and the platform merges\n * them into the settings in force: `image`, `isolation`, `cpu`, `memory`,\n * `network`, and `shell` replace the setting of the same name; `size` replaces the CPU and\n * memory together with those of the size it names, and is never stated with\n * either; `cpu`, `memory`, and\n * `network` stated as `null` return to IDYL's default for the Subnet, as it\n * stands each time the computer starts, and `shell` stated as `null`\n * returns to the default shell rule; `setVariables` sets each variable it\n * names and `removeVariables` removes each one it names; `setSecrets`\n * attaches each Secret it states and `removeSecrets` detaches each one it\n * names, by the variable of the attachment; `identity` replaces the workload\n * identity, and stated as `null` removes it. The image has no\n * default, so it is only ever replaced. Changes that leave the settings as\n * they were record nothing. Any other change is recorded as one entry in the\n * Computer's journal, holding the whole settings after it, and takes effect\n * from the computer's next start: at once when nothing runs on it, and,\n * while sessions run, once the last of them ends, without disturbing them;\n * `ComputerExecutionSettingsStatus.pending` reports the wait. A change of the\n * shell alone applies from the next session and leaves `pending` as it was.\n * The merged settings are judged as a create's are: an IDYL image the\n * catalog does not hold for the isolation class is refused with\n * `ERROR_CODE_IMAGE_NOT_IN_CATALOG`, an isolation class the Subnet does not\n * admit with `ERROR_CODE_ISOLATION_CLASS_NOT_ADMITTED`, a network class it\n * does not admit with `ERROR_CODE_NETWORK_CLASS_NOT_ADMITTED`, and a size the\n * platform does not\n * offer or settings that fit no host of the Subnet with\n * {@link ERROR_CODE_COMPUTER_DOES_NOT_FIT}; a refused update\n * changes nothing, its idle timeout included.\n *\n * Only the fields a request states reach the wire, in a fixed order, a\n * setting returned to its default as `null`.\n */\nexport interface UpdateComputerRequest {\n /** The Computer's new name. */\n readonly name?: string;\n /**\n * Replaces whether the Computer saves on its own, an explicit `false`\n * included, as `ComputerSpec.autoSave` states it.\n */\n readonly autoSave?: boolean;\n /**\n * Replaces how long writes must be quiet before a change-driven save,\n * within the range `ComputerSpec.saveQuiet` states.\n */\n readonly saveQuiet?: Duration;\n /**\n * Replaces the longest time between saves while writes continue, within\n * the range `ComputerSpec.saveMaxInterval` states. The platform judges it\n * against the `saveQuiet` the update leaves in force.\n */\n readonly saveMaxInterval?: Duration;\n /** Nonnegative failing-save budget, including explicit zero. */\n readonly saveWindow?: Duration;\n /**\n * Replaces the idle timeout, in the spelling `ComputerSpec` states;\n * `never` keeps the Computer awake until it is put to sleep.\n */\n readonly idleTimeout?: IdleTimeout;\n /** Replaces the computer's OS image: an IDYL image by catalog name, or one of the caller's own. */\n readonly image?: ComputerExecutionSettingsImage;\n /**\n * Replaces the isolation class the computer runs in, as\n * `ComputerExecutionSettings.isolation` states it: `secure-container` or\n * `vm`. An IDYL image serves one isolation class, so an update that\n * changes the class and states no image gives the computer the catalog's\n * default image for the new class, and an IDYL image stated beside it\n * must serve the new class. The files under `/workspace` carry over.\n * `undefined` or empty leaves the class as it is, and none is written; it\n * is never `null`.\n */\n readonly isolation?: ComputerIsolationClass;\n /**\n * Replaces the CPU and memory limits with those of the size it names, such\n * as `small`. It is never stated with `cpu` or `memory`, not even as `null`,\n * and it is never `null` itself: `cpu` and `memory` stated as `null` return a\n * size to the default.\n */\n readonly size?: ComputerSize;\n /**\n * Replaces the CPU limit, which must be greater than zero, such as `500m`\n * or `2`; `null` returns it to IDYL's default for the Subnet.\n */\n readonly cpu?: CpuQuantity | null;\n /**\n * Replaces the memory limit, which must be greater than zero, such as\n * `512Mi` or `4Gi`; `null` returns it to IDYL's default for the Subnet.\n */\n readonly memory?: MemoryQuantity | null;\n /**\n * Replaces the network, held to the Micropod network profile\n * (`validateMicropodNetwork`); an allow list is part of the network it is\n * stated in, so it is replaced with it. `null` returns to the Subnet's\n * default network.\n */\n readonly network?: WorkloadNetwork | null;\n /**\n * Replaces the computer's default shell, as\n * `ComputerExecutionSettings.shell` states it, such as `/usr/bin/zsh`; it\n * must not be empty. `null` returns it to the rule a computer stating no\n * shell follows.\n */\n readonly shell?: string | null;\n /**\n * Sets environment variables by name: one the settings already hold takes the\n * new value in its place, and one they do not is added after the others,\n * in the order stated. Names are unique within the list.\n */\n readonly setVariables?: readonly ComputerEnvironmentVariable[];\n /**\n * Removes environment variables by name. A name the settings do not hold\n * changes nothing. Names are unique within the list, and a name is never\n * both set and removed.\n */\n readonly removeVariables?: readonly string[];\n /**\n * Attaches Secrets by variable name, as {@link ComputerSecretAttachment}\n * describes: an attachment whose variable the settings already attach\n * replaces it, and one they do not is added after the others, in the order\n * stated. Variables are unique within the list.\n */\n readonly setSecrets?: readonly ComputerSecretAttachment[];\n /**\n * Detaches Secrets by the name of the variable that holds their\n * placeholder. A name the settings do not attach changes nothing. Names\n * are unique within the list, and a name is never both set and removed.\n */\n readonly removeSecrets?: readonly string[];\n /**\n * Replaces the computer's workload identity, as\n * `ComputerExecutionSettings.identity` states it; `null` removes it.\n */\n readonly identity?: ComputerIdentity | null;\n /**\n * The kind of client sending the request. The execution settings' journal\n * entry records it, as `unknown` when it is absent; it is informative and\n * never authorizes anything. `undefined` or empty states no client, and\n * none is written.\n */\n readonly client?: ComputerSessionClient;\n}\n\n/** The fields of an update, in the order the wire writes them, with their shapes. */\nconst UPDATE_FIELDS: readonly (readonly [\n keyof UpdateComputerRequest,\n Shape<unknown>,\n])[] = [\n [\"name\", string() as Shape<unknown>],\n [\"idleTimeout\", string() as Shape<unknown>],\n [\"autoSave\", boolean() as Shape<unknown>],\n [\"saveQuiet\", durationShape as Shape<unknown>],\n [\"saveMaxInterval\", durationShape as Shape<unknown>],\n [\"saveWindow\", durationShape as Shape<unknown>],\n [\"image\", computerExecutionSettingsImageShape as Shape<unknown>],\n [\"isolation\", string<ComputerIsolationClass>() as Shape<unknown>],\n [\"size\", string() as Shape<unknown>],\n [\"cpu\", cpuQuantityShape as Shape<unknown>],\n [\"memory\", memoryQuantityShape as Shape<unknown>],\n [\"network\", workloadNetworkShape as Shape<unknown>],\n [\"shell\", string() as Shape<unknown>],\n [\"setVariables\", array(computerEnvironmentVariableShape) as Shape<unknown>],\n [\"removeVariables\", array(string()) as Shape<unknown>],\n [\"setSecrets\", array(computerSecretAttachmentShape) as Shape<unknown>],\n [\"removeSecrets\", array(string()) as Shape<unknown>],\n [\"identity\", computerIdentityShape as Shape<unknown>],\n [\"client\", string<ComputerSessionClient>() as Shape<unknown>],\n];\n\n/** The settings an update may return to their default by stating `null`. */\nconst RESETTABLE: ReadonlySet<string> = new Set([\n \"cpu\",\n \"memory\",\n \"network\",\n \"shell\",\n \"identity\",\n]);\n\n/** The fields an update writes only when they are not empty. */\nconst OMITTED_WHEN_EMPTY: ReadonlySet<string> = new Set([\n \"isolation\",\n \"setVariables\",\n \"removeVariables\",\n \"setSecrets\",\n \"removeSecrets\",\n \"client\",\n]);\n\n/**\n * The wire shape of an update request. It writes each field the request\n * states, in the order the interface declares them: `cpu`, `memory`,\n * `network`, `shell`, and `identity` as `null` when they are, and `isolation`,\n * `setVariables`, `removeVariables`, `setSecrets`, `removeSecrets`, and\n * `client` only when not empty.\n * A read carries `null` for the five settings that `null` resets and\n * refuses it for every other field when strict.\n */\nexport const updateComputerRequestShape: Shape<UpdateComputerRequest> = {\n unknownFields: (value, path) => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return;\n }\n const record = value as Readonly<Record<string, unknown>>;\n for (const key of Object.keys(record).sort()) {\n const field = UPDATE_FIELDS.find(([name]) => name === key);\n if (field === undefined) {\n throw new StrictDecodeError({\n reason: \"unknown_field\",\n path: fieldPath(path, key),\n message: `unknown field ${JSON.stringify(fieldPath(path, key))}`,\n });\n }\n if (record[key] !== null) {\n field[1].unknownFields(record[key], fieldPath(path, key));\n }\n }\n },\n decode: (value, path, mode) => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new StrictDecodeError({\n reason: \"wrong_type\",\n path,\n message: \"document must be an object\",\n });\n }\n const record = value as Readonly<Record<string, unknown>>;\n const decoded: Record<string, unknown> = {};\n for (const key of Object.keys(record)) {\n const raw = record[key];\n const field = UPDATE_FIELDS.find(([name]) => name === key);\n if (field === undefined) {\n if (mode === \"lenient\") decoded[key] = raw;\n continue;\n }\n if (raw === null) {\n if (RESETTABLE.has(key)) {\n decoded[key] = null;\n } else if (mode !== \"lenient\") {\n throw new StrictDecodeError({\n reason: \"invalid_value\",\n path: fieldPath(path, key),\n message: `${fieldPath(path, key)} must not be null`,\n });\n }\n continue;\n }\n decoded[key] = field[1].decode(raw, fieldPath(path, key), mode);\n }\n return decoded;\n },\n encode: (request) => {\n const record = request as Readonly<Record<string, unknown>>;\n const encoded: Record<string, JsonValue> = {};\n for (const [name, shape] of UPDATE_FIELDS) {\n const item = record[name];\n if (item === undefined) continue;\n if (item === null) {\n if (RESETTABLE.has(name)) encoded[name] = null;\n continue;\n }\n if (OMITTED_WHEN_EMPTY.has(name) && shape.isEmpty(item)) continue;\n encoded[name] = shape.encode(item);\n }\n return encoded;\n },\n zero: () => ({}),\n isZero: (request) => Object.keys(request).length === 0,\n isEmpty: () => false,\n};\n\n/** Renders an update request as the document the route carries. */\nexport function encodeUpdateComputerRequest(\n request: UpdateComputerRequest,\n): JsonObject {\n return updateComputerRequestShape.encode(request) as JsonObject;\n}\n\n/** Whether the update changes the execution settings. */\nfunction statesComputer(request: UpdateComputerRequest): boolean {\n return (\n request.image !== undefined ||\n (request.isolation ?? \"\") !== \"\" ||\n request.size !== undefined ||\n request.cpu !== undefined ||\n request.memory !== undefined ||\n request.network !== undefined ||\n request.shell !== undefined ||\n (request.setVariables ?? []).length > 0 ||\n (request.removeVariables ?? []).length > 0 ||\n (request.setSecrets ?? []).length > 0 ||\n (request.removeSecrets ?? []).length > 0 ||\n request.identity !== undefined\n );\n}\n\n/**\n * Requires the update to state at least one field, since one that states\n * none would change nothing, and judges every field it states:\n *\n * - the name is present and not in the form of a Computer ID, as a\n * create's is;\n * - the idle timeout is one `validateIdleTimeout` admits;\n * - the image, isolation class, size, CPU, memory, network, shell,\n * variables to set, and Secret attachments to set are what\n * `validateComputerExecutionSettings` admits, a stated CPU or memory greater than\n * zero, a stated shell not empty, and a stated size in identifier form with no\n * CPU or memory beside it, not even as `null`;\n * - every variable to remove is a well-formed name, stated once, and not\n * also set, and so is every Secret attachment to remove;\n * - the client, when stated, is one this SDK names.\n *\n * Every refusal reads `computer update: ...`. A refused computer field\n * carries, as its `cause`, a `ComputerExecutionSettingsError` whose `field` is the\n * path within this request, such as `cpu` or `setVariables[1].name`.\n * Whether the platform offers the size, whether the merged settings fit a host\n * of the Subnet, whether the Subnet admits their isolation and network classes,\n * and whether its catalog holds the image named for the class, are the\n * platform's decision. Throws a\n * `TypeError`.\n */\nexport function validateUpdateComputerRequest(\n request: UpdateComputerRequest,\n): void {\n if (\n request.name === undefined &&\n request.idleTimeout === undefined &&\n request.autoSave === undefined &&\n request.saveQuiet === undefined &&\n request.saveMaxInterval === undefined &&\n request.saveWindow === undefined &&\n !statesComputer(request)\n ) {\n throw new TypeError(\"computer update states no field\");\n }\n prefixed(\"computer update\", () => {\n if (request.name !== undefined) validateComputerName(request.name);\n if (request.idleTimeout !== undefined) {\n const idleTimeout = request.idleTimeout;\n prefixed(\"idleTimeout\", () => {\n validateIdleTimeout(idleTimeout);\n });\n }\n validateComputerSpec({\n ...(request.autoSave === undefined ? {} : { autoSave: request.autoSave }),\n ...(request.saveQuiet === undefined\n ? {}\n : { saveQuiet: request.saveQuiet }),\n ...(request.saveMaxInterval === undefined\n ? {}\n : { saveMaxInterval: request.saveMaxInterval }),\n ...(request.saveWindow === undefined\n ? {}\n : { saveWindow: request.saveWindow }),\n });\n validateUpdateComputer(request);\n validateStatedClient(request.client);\n });\n}\n\nfunction validateUpdateComputer(request: UpdateComputerRequest): void {\n if (request.size !== undefined) {\n try {\n validateComputerSize(request.size);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(\"size\", errorMessage(cause));\n }\n if (request.cpu !== undefined || request.memory !== undefined) {\n throw new ComputerExecutionSettingsError(\n \"size\",\n \"must not be stated with cpu or memory\",\n );\n }\n }\n if (\n request.cpu !== undefined &&\n request.cpu !== null &&\n isZeroCpu(request.cpu)\n ) {\n throw new ComputerExecutionSettingsError(\n \"cpu\",\n \"must be greater than zero; null returns it to the default\",\n );\n }\n if (\n request.memory !== undefined &&\n request.memory !== null &&\n isZeroMemory(request.memory)\n ) {\n throw new ComputerExecutionSettingsError(\n \"memory\",\n \"must be greater than zero; null returns it to the default\",\n );\n }\n if (request.shell === \"\") {\n throw new ComputerExecutionSettingsError(\n \"shell\",\n \"must not be empty; null returns it to the default\",\n );\n }\n // The settings an update states are a part of the settings it leaves in\n // force, so the rules and the size bound that hold for the whole hold for\n // the part.\n const stated: ComputerExecutionSettings = {\n ...(request.image === undefined ? {} : { image: request.image }),\n ...(request.isolation === undefined\n ? {}\n : { isolation: request.isolation }),\n ...(request.size === undefined ? {} : { size: request.size }),\n ...(request.cpu === undefined || request.cpu === null\n ? {}\n : { cpu: request.cpu }),\n ...(request.memory === undefined || request.memory === null\n ? {}\n : { memory: request.memory }),\n ...(request.network === undefined || request.network === null\n ? {}\n : { network: request.network }),\n ...(request.shell === undefined || request.shell === null\n ? {}\n : { shell: request.shell }),\n ...(request.setVariables === undefined\n ? {}\n : { variables: request.setVariables }),\n ...(request.setSecrets === undefined\n ? {}\n : { secrets: request.setSecrets }),\n ...(request.identity === undefined || request.identity === null\n ? {}\n : { identity: request.identity }),\n };\n try {\n validateComputerExecutionSettings(stated);\n } catch (error) {\n if (!(error instanceof ComputerExecutionSettingsError)) throw error;\n throw new ComputerExecutionSettingsError(\n updateComputerField(error.field),\n error.rule,\n );\n }\n validateRemovedNames(\n \"removeVariables\",\n request.removeVariables ?? [],\n new Set((request.setVariables ?? []).map((variable) => variable.name)),\n \"names a variable setVariables also sets\",\n );\n validateRemovedNames(\n \"removeSecrets\",\n request.removeSecrets ?? [],\n new Set((request.setSecrets ?? []).map((attachment) => attachment.env)),\n \"names a variable setSecrets also sets\",\n );\n}\n\n/**\n * Judges the names an update removes from the list field `list`: each a\n * well-formed variable name, stated once, and not among the names the same\n * update sets.\n */\nfunction validateRemovedNames(\n list: string,\n names: readonly string[],\n set: ReadonlySet<string>,\n setRefusal: string,\n): void {\n const removed = new Map<string, number>();\n names.forEach((name, index) => {\n const field = `${list}[${String(index)}]`;\n try {\n validateComputerEnvironmentVariableName(name);\n } catch (cause) {\n throw new ComputerExecutionSettingsError(field, errorMessage(cause));\n }\n const previous = removed.get(name);\n if (previous !== undefined) {\n throw new ComputerExecutionSettingsError(\n field,\n `duplicates ${list}[${String(previous)}]`,\n );\n }\n if (set.has(name)) {\n throw new ComputerExecutionSettingsError(field, setRefusal);\n }\n removed.set(name, index);\n });\n}\n\n/**\n * Maps the path of a settings field, as `validateComputerExecutionSettings` names\n * it, to the path of the update field that stated it.\n */\nfunction updateComputerField(field: string): string {\n const path = field.replace(/^execution\\.?/u, \"\");\n if (path.startsWith(\"variables\")) {\n return `setVariables${path.slice(\"variables\".length)}`;\n }\n if (path.startsWith(\"secrets\")) {\n return `setSecrets${path.slice(\"secrets\".length)}`;\n }\n return path === \"\" ? \"execution\" : path;\n}\n\n/**\n * Returned with HTTP 422 when a computer's CPU and memory, with the\n * runtime's own allowance, fit no host of the Computer's Subnet, so it\n * could never start. The details state the largest size that fits a host\n * of the Subnet now, the size `ComputerExecutionSettingsStatus.largestSize`\n * reports, as its CPU and memory under `maxCPU` and `maxMemory`, in the\n * quantity spelling. The request changes nothing.\n */\nexport const ERROR_CODE_COMPUTER_DOES_NOT_FIT = \"COMPUTER_DOES_NOT_FIT\";\n\n/** The Computer as the update left it, its spec in canonical spelling. */\nexport interface UpdateComputerResponse {\n readonly computer: Computer;\n}\n\n/** The wire shape of an update response: the Computer under `computer`. */\nexport const updateComputerResponseShape: Shape<UpdateComputerResponse> =\n object<UpdateComputerResponse>({\n computer: always(computerShape),\n });\n\n/** The newly recorded Computer, including its server-assigned ID. */\nexport interface CreateComputerResponse {\n readonly computer: Computer;\n}\n\n/** One Computer, addressed by name or by ID. */\nexport interface GetComputerResponse {\n readonly computer: Computer;\n}\n\n/**\n * One page of Computers in one Subnet: those of one Namespace, or of every\n * Namespace the caller may list. Each Computer carries its own Namespace\n * and Subnet.\n */\nexport type ListComputersResponse = ListResponse<Computer>;\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * Requests a Namespace-scoped service sends to the API that serves the\n * Account's Computers. The client's placement is resolved once per\n * operation, and an account-wide list needs no Namespace. The resolved\n * endpoint is where the request goes; the resolved place and scope are what\n * its path is built from.\n *\n * `ZoneCollection` is the shape of a collection that is created into, read,\n * changed, and deleted by name, and listed within a Namespace or across the\n * Account, each resource travelling under its own envelope key. It is read\n * through the kind's lenient decoder, so what the platform adds survives the\n * read; the rest of every envelope is carried as it arrived.\n *\n * A Computer names the place it lives in on every response, and only that\n * place's API serves it. Its collection refuses a response in which any\n * Computer names a place other than the one the request addressed, or none,\n * so a caller never holds a Computer another place answered for. Every path\n * is built in `apipath`, every list query encoded in `listquery`, and every\n * envelope read here.\n */\nimport { TransportError } from \"../errors.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport type {\n DeleteResponse,\n ListOptions,\n ListResponse,\n} from \"../api/types.js\";\nimport { accountSubnet, namespace, namespaceResource } from \"./apipath.js\";\nimport type { PlacementContext } from \"./context.js\";\nimport { readEnvelope, readList } from \"./envelopes.js\";\nimport { requireNonBlank } from \"./options.js\";\nimport { accountListQuery, namespaceListQuery } from \"./listquery.js\";\nimport { resolvePlacement } from \"./routing.js\";\nimport type { ResolvedPlacement, ResolvePlacementOptions } from \"./routing.js\";\n\n/** What one request to a Subnet's API carries beyond its method and path. */\nexport interface ZoneRequestOptions {\n readonly body?: unknown;\n readonly headers?: Readonly<Record<string, string>>;\n readonly maxRequestBodyBytes?: number;\n readonly safeErrorCode?: (code: string) => boolean;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Resolves the client's placement under `resolve` and sends one request to\n * the Subnet API that serves it. `path` is built from the resolution, so an\n * account-wide route always addresses the Subnet the request is sent to.\n */\nexport async function sendToZone<T>(\n context: PlacementContext,\n method: string,\n path: (resolved: ResolvedPlacement) => string,\n resolve: Omit<ResolvePlacementOptions, \"signal\">,\n options: ZoneRequestOptions = {},\n): Promise<T> {\n return (await exchange(context, method, path, resolve, options))\n .response as T;\n}\n\n/**\n * Throws unless every place in `served` is `addressed`. The message names\n * the kind only: where a Computer lives is never part of a message, and the\n * place a response named is server-controlled and is never repeated.\n */\nfunction requireServedSubnet(\n label: string,\n addressed: string,\n served: readonly string[],\n): void {\n if (served.some((subnet) => subnet !== addressed)) {\n throw new TransportError(\n \"invalid_response\",\n `${label} response names a placement other than the one addressed`,\n );\n }\n}\n\n/**\n * {@link sendToZone}, handing back the resolution the request was sent\n * under with the response. `options.bodyFor`, when present, builds the body\n * from the resolution in place of `options.body`, and may throw to refuse\n * the request before it is sent.\n */\nasync function exchange(\n context: PlacementContext,\n method: string,\n path: (resolved: ResolvedPlacement) => string,\n resolve: Omit<ResolvePlacementOptions, \"signal\">,\n options: ExchangeOptions = {},\n): Promise<Exchanged> {\n const resolved = await resolvePlacement(context, {\n ...resolve,\n ...signalOption(options.signal),\n });\n const body =\n options.bodyFor === undefined ? options.body : options.bodyFor(resolved);\n const response = await context.state.transport.json<unknown>(\n method,\n resolved.endpoint,\n path(resolved),\n {\n ...(body === undefined ? {} : { body }),\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n ...(options.maxRequestBodyBytes === undefined\n ? {}\n : { maxRequestBodyBytes: options.maxRequestBodyBytes }),\n ...(options.safeErrorCode === undefined\n ? {}\n : { safeErrorCode: options.safeErrorCode }),\n ...signalOption(options.signal),\n },\n );\n return { resolved, response };\n}\n\n/** What {@link exchange} carries: a body may be built from the resolution. */\ninterface ExchangeOptions extends ZoneRequestOptions {\n readonly bodyFor?: (resolved: ResolvedPlacement) => unknown;\n}\n\n/** A response envelope carrying one resource under `K`. */\nexport type Envelope<K extends string, T> = Readonly<Record<K, T>>;\n\n/** How one kind's collection is addressed, encoded, and read. */\nexport interface ZoneCollectionSpec<K extends string, T> {\n /** The collection path segment, such as `computers`. */\n readonly plural: string;\n /** The envelope key requests and responses wrap the resource in. */\n readonly key: K;\n /** The singular noun used in messages, such as `computer`. */\n readonly label: string;\n /** Reads a resource the platform reported, leniently. */\n readonly decode: (value: unknown) => T;\n /**\n * The Subnet a served resource names, for a kind that lives in one Subnet.\n * When present, every response carrying resources is refused unless each\n * of them names the Subnet the request addressed. `undefined` checks\n * nothing.\n */\n readonly subnetOf?: (value: T) => string;\n}\n\n/** One kind's Namespace-scoped collection on the client's resolved Subnet. */\nexport class ZoneCollection<K extends string, T> {\n readonly #context: PlacementContext;\n readonly #spec: ZoneCollectionSpec<K, T>;\n\n constructor(context: PlacementContext, spec: ZoneCollectionSpec<K, T>) {\n this.#context = context;\n this.#spec = spec;\n }\n\n /**\n * Creates a resource in the Namespace from the request body `body`\n * builds for the resolved placement. `body`\n * may throw to refuse the request before anything is sent.\n */\n async submit(\n body: (resolved: ResolvedPlacement) => unknown,\n signal?: AbortSignal,\n ): Promise<Envelope<K, T>> {\n return this.#envelope(\n await exchange(\n this.#context,\n \"POST\",\n (resolved) => namespace(resolved.scope, this.#spec.plural),\n {},\n { bodyFor: body, ...signalOption(signal) },\n ),\n );\n }\n\n /** Reads the named resource. Throws a `TypeError` when `name` is blank. */\n async get(name: string, signal?: AbortSignal): Promise<Envelope<K, T>> {\n this.#requireName(name);\n return await this.read(\n (resolved) => this.#resourcePath(resolved, name),\n signal,\n );\n }\n\n /** Reads the one resource `path` addresses on the resolved Subnet. */\n async read(\n path: (resolved: ResolvedPlacement) => string,\n signal?: AbortSignal,\n ): Promise<Envelope<K, T>> {\n return this.#envelope(\n await exchange(this.#context, \"GET\", path, {}, signalOption(signal)),\n );\n }\n\n /**\n * Applies a partial change, `body`, to the named resource with a PATCH\n * and reads back the resource as the change left it. Throws a\n * `TypeError` when `name` is blank.\n */\n async patch(\n name: string,\n body: unknown,\n signal?: AbortSignal,\n ): Promise<Envelope<K, T>> {\n this.#requireName(name);\n return await this.change(\n (resolved) => this.#resourcePath(resolved, name),\n body,\n signal,\n );\n }\n\n /**\n * Applies a partial change, `body`, with a PATCH of the one resource\n * `path` addresses on the resolved Subnet, and reads back the resource\n * as the change left it.\n */\n async change(\n path: (resolved: ResolvedPlacement) => string,\n body: unknown,\n signal?: AbortSignal,\n ): Promise<Envelope<K, T>> {\n return this.#envelope(\n await exchange(\n this.#context,\n \"PATCH\",\n path,\n {},\n { body, ...signalOption(signal) },\n ),\n );\n }\n\n /**\n * Asks the platform to remove the named resource and returns its answer.\n * Throws a `TypeError` when `name` is blank.\n */\n async delete(name: string, signal?: AbortSignal): Promise<DeleteResponse> {\n this.#requireName(name);\n return await this.remove(\n (resolved) => this.#resourcePath(resolved, name),\n signal,\n );\n }\n\n /**\n * Asks the platform to remove the one resource `path` addresses on the\n * resolved Subnet and returns its answer.\n */\n async remove(\n path: (resolved: ResolvedPlacement) => string,\n signal?: AbortSignal,\n ): Promise<DeleteResponse> {\n return await sendToZone<DeleteResponse>(\n this.#context,\n \"DELETE\",\n path,\n {},\n signalOption(signal),\n );\n }\n\n /** One page of the collection within the Namespace. */\n async list(\n options: ListOptions,\n signal?: AbortSignal,\n ): Promise<ListResponse<T>> {\n return this.#page(\n await exchange(\n this.#context,\n \"GET\",\n (resolved) =>\n namespace(resolved.scope, this.#spec.plural) +\n namespaceListQuery(options, resolved.subnet),\n {},\n signalOption(signal),\n ),\n );\n }\n\n /**\n * One page of the collection across every Namespace in the Account, in\n * the client's Subnet. The client's Namespace is not consulted: the path\n * addresses the Account and the Subnet directly, and each item carries\n * its own Namespace.\n */\n async listAllNamespaces(\n options: ListOptions,\n signal?: AbortSignal,\n ): Promise<ListResponse<T>> {\n return this.#page(\n await exchange(\n this.#context,\n \"GET\",\n (resolved) =>\n accountSubnet(\n resolved.scope.accountId,\n resolved.subnet,\n this.#spec.plural,\n ) + accountListQuery(options),\n { requireNamespace: false },\n signalOption(signal),\n ),\n );\n }\n\n #envelope(exchanged: Exchanged): Envelope<K, T> {\n const envelope = readEnvelope(\n exchanged.response,\n this.#spec.key,\n this.#spec.decode,\n );\n this.#requireServed(exchanged.resolved, [envelope[this.#spec.key]]);\n return envelope;\n }\n\n #page(exchanged: Exchanged): ListResponse<T> {\n const page = readList(\n exchanged.response,\n this.#spec.plural,\n this.#spec.decode,\n );\n this.#requireServed(exchanged.resolved, page.items);\n return page;\n }\n\n #requireServed(resolved: ResolvedPlacement, served: readonly T[]): void {\n const subnetOf = this.#spec.subnetOf;\n if (subnetOf === undefined) return;\n requireServedSubnet(\n this.#spec.label,\n resolved.subnet,\n served.map(subnetOf),\n );\n }\n\n #requireName(name: string): void {\n requireNonBlank(name, `${this.#spec.label} name`);\n }\n\n #resourcePath(resolved: ResolvedPlacement, name: string): string {\n return namespaceResource(resolved.scope, this.#spec.plural, name);\n }\n}\n\n/** A response with the resolution its request was sent under. */\ninterface Exchanged {\n readonly resolved: ResolvedPlacement;\n readonly response: unknown;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { signalOption } from \"./internal/options.js\";\nimport type { WaitEvaluation } from \"./api/wait.js\";\nimport { isNotFound } from \"./errors.js\";\nimport { abortReason, delay, managedSignal } from \"./internal/abort.js\";\n\n/**\n * Controls polling for a lifecycle condition.\n *\n * `timeoutMs` bounds the whole wait; `undefined` allows 600000, ten\n * minutes. An explicit `0` judges the condition exactly once and returns\n * without waiting: the wait judges the state it starts from (a fresh read\n * for a service wait, and one read for a deletion wait), resolves with it when it meets the condition,\n * rejects with the wait's terminal error when it can no longer meet it, and\n * otherwise rejects with a `TimeoutError` `DOMException`, exactly as a wait\n * that ran out of time. `pollIntervalMs` is the pause between reads;\n * `undefined` polls every 1 000. Both are milliseconds; `timeoutMs` must be\n * zero or greater and `pollIntervalMs` greater than zero when given. A wait\n * that exhausts its timeout rejects with a `TimeoutError` `DOMException`;\n * one cancelled through `signal` rejects with the signal's reason. Neither\n * outcome deletes anything.\n */\nexport interface WaitOptions {\n readonly timeoutMs?: number;\n readonly pollIntervalMs?: number;\n readonly signal?: AbortSignal;\n}\n\n/** The wait timeout applied when the options set none, in milliseconds. */\nexport const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;\n\n/** The poll interval applied when the options set none, in milliseconds. */\nexport const DEFAULT_WAIT_POLL_INTERVAL_MS = 1_000;\n\n/** A wait's settings with the defaults applied. */\nexport interface NormalizedWait {\n readonly timeoutMs: number;\n readonly pollIntervalMs: number;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Applies the defaults and holds each value to the contract, throwing a\n * `TypeError` naming the field that is not a finite number of milliseconds\n * in range: zero or greater for `timeoutMs`, where zero means a single\n * judgement, and greater than zero for `pollIntervalMs`. It runs before any\n * network call so a wait that could never succeed is refused before it\n * creates anything.\n */\nexport function normalizeWaitOptions(options: WaitOptions): NormalizedWait {\n const timeoutMs = milliseconds(\n options.timeoutMs,\n DEFAULT_WAIT_TIMEOUT_MS,\n \"wait timeoutMs\",\n 0,\n );\n const pollIntervalMs = milliseconds(\n options.pollIntervalMs,\n DEFAULT_WAIT_POLL_INTERVAL_MS,\n \"wait pollIntervalMs\",\n 1,\n );\n return {\n timeoutMs,\n pollIntervalMs,\n ...signalOption(options.signal),\n };\n}\n\n/**\n * What one poll needs: a snapshot already in hand, judged before any\n * request; a read of the object under the wait's signal, reporting\n * `undefined` when the object is gone; the judgement of one snapshot; the\n * timeout sentence for the bound applied; and, for a wait whose pauses\n * follow a schedule of their own, the pause before each read.\n */\nexport interface PollTarget<T> {\n readonly initial?: T;\n readonly read: (signal: AbortSignal) => Promise<T | undefined>;\n /** Whether `current` meets the condition; throws to end the wait with a terminal failure. */\n readonly met: (current: T) => boolean;\n readonly timeoutMessage: (timeoutMs: number) => string;\n /**\n * The pause before read number `attempt`, counted from zero over the\n * reads that follow an observation, in milliseconds. It is consulted\n * just before each pause, so it may reflect what the previous read\n * reported. `undefined` pauses for the wait's poll interval every time.\n */\n readonly delay?: (attempt: number) => number;\n}\n\n/**\n * The one polling loop every wait runs. A snapshot in hand is judged\n * first; otherwise, and after every pause, of the poll interval or of the\n * target's own schedule, the object is read again and judged, until `met`\n * reports the condition or `read` reports the object gone, in which case\n * `undefined` is returned. A zero timeout judges once: the snapshot in\n * hand, or without one a single read, and a pending judgement throws as an\n * exhausted timeout does. An exhausted timeout throws a `TimeoutError`\n * `DOMException`; cancellation throws the signal's reason; a failure `met`\n * or `read` throws propagates. The listener and timer the wait holds are\n * released however it ends, and nothing is deleted.\n */\nexport async function pollUntil<T>(\n options: WaitOptions,\n target: PollTarget<T>,\n): Promise<T | undefined> {\n const wait = normalizeWaitOptions(options);\n if (wait.timeoutMs === 0) return await judgeOnce(wait, target);\n const managed = managedSignal(\n wait.signal,\n wait.timeoutMs,\n target.timeoutMessage(wait.timeoutMs),\n );\n try {\n let current = target.initial;\n let observed = current !== undefined;\n for (let attempt = 0; ;) {\n if (current !== undefined && target.met(current)) return current;\n if (observed) {\n const pause = target.delay?.(attempt) ?? wait.pollIntervalMs;\n attempt += 1;\n await delay(pause, managed.signal);\n }\n current = await target.read(managed.signal);\n observed = true;\n if (current === undefined) return undefined;\n }\n } finally {\n managed.cleanup();\n }\n}\n\n/**\n * The single judgement a zero timeout asks for: the snapshot in hand, or\n * without one a single read under the caller's signal. A pending judgement\n * throws the caller's cancellation reason when the signal has aborted, and\n * otherwise the `TimeoutError` `DOMException` an exhausted timeout throws.\n */\nasync function judgeOnce<T>(\n wait: NormalizedWait,\n target: PollTarget<T>,\n): Promise<T | undefined> {\n const managed = managedSignal(wait.signal, undefined, \"\");\n try {\n let current = target.initial;\n if (current === undefined) {\n current = await target.read(managed.signal);\n if (current === undefined) return undefined;\n }\n if (target.met(current)) return current;\n if (managed.signal.aborted) throw abortReason(managed.signal);\n throw new DOMException(target.timeoutMessage(0), \"TimeoutError\");\n } finally {\n managed.cleanup();\n }\n}\n\n/** What the deletion wait needs to read one object and judge it. */\nexport interface DeletionTarget<T> {\n readonly kind: string;\n readonly name: string;\n readonly read: (signal: AbortSignal) => Promise<T>;\n readonly evaluate: (current: T) => WaitEvaluation;\n}\n\n/**\n * Polls until the object is gone: the evaluator reports `deleted` met, or a\n * read answers 404, which is the caller's judgement that absence is the\n * condition. Every other verdict is pending; a served object that can be\n * read has not been deleted. It reads at once and then after each pause of\n * the poll interval, never judging a snapshot in hand, so it answers without\n * a one-interval delay and a timeout shorter than the poll interval still\n * makes one read; a zero timeout makes exactly one. It resolves with the\n * last read judged pending, the object as it was last seen, and with\n * `undefined` when none was. Timeout, cancellation, and release behave as\n * in {@link pollUntil}.\n */\nexport async function waitForDeletion<T>(\n options: WaitOptions,\n target: DeletionTarget<T>,\n): Promise<T | undefined> {\n let last: T | undefined;\n await pollUntil<T>(options, {\n read: async (signal) => {\n try {\n return await target.read(signal);\n } catch (error) {\n if (isNotFound(error)) return undefined;\n throw error;\n }\n },\n met: (current) => {\n if (target.evaluate(current).state === \"met\") return true;\n last = current;\n return false;\n },\n timeoutMessage: (timeoutMs) =>\n `wait for ${target.kind.toLowerCase()} ${JSON.stringify(target.name)} deletion exceeded ${String(timeoutMs)} ms`,\n });\n return last;\n}\n\n/**\n * `value`, or `fallback` when it is `undefined`. `floor` is `0` for a value\n * that may be zero and `1` for one that must be greater than zero; any\n * other value throws a `TypeError` naming `label`.\n */\nfunction milliseconds(\n value: number | undefined,\n fallback: number,\n label: string,\n floor: 0 | 1,\n): number {\n if (value === undefined) return fallback;\n const inRange = floor === 0 ? value >= 0 : value > 0;\n if (typeof value !== \"number\" || !Number.isFinite(value) || !inRange) {\n throw new TypeError(\n floor === 0\n ? `${label} must be zero or greater`\n : `${label} must be greater than zero`,\n );\n }\n return value;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport {\n storageResourceReferenceFields,\n validateStorageResourceReference,\n type StorageResourceReference,\n} from \"../resource/storage.js\";\nimport {\n validateComputerCellSave,\n computerCellSaveShape,\n type ComputerCellSave,\n} from \"./computer-cell-save.js\";\nimport { validateComputerNotebookName } from \"./computer-notebook-name.js\";\nimport {\n always,\n array,\n boolean,\n fieldPath,\n integer,\n object,\n omitEmpty,\n omitZero,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { StrictDecodeError } from \"../resource/decode-error.js\";\nimport type { JsonObject, JsonValue } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n parseJournalEntryId,\n parseComputerSessionId,\n type JournalEntryId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n isZeroInstant,\n validateComputerSessionClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\n\n/**\n * The most command bytes a Cell carries in a journal list: the bytes of an\n * exec command's arguments taken together. A listed command longer than\n * this is cut and marked truncated; reading the entry on its own returns\n * the whole command.\n */\nexport const MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES = 4 << 10;\n\n/**\n * How a Cell's session ran its process. It describes the session, and is\n * distinct from the kind of the journal entry that holds the Cell.\n *\n * - `exec`: a command run directly, with or without a terminal.\n * Its command is the `exec` member.\n * - `endpoint-cell`: a notebook cell run over the Computer's own session\n * endpoint. Its command travels end to end encrypted to the Computer,\n * which alone records it, so the Cell's command carries no member.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerCellMode} judges\n * membership.\n */\nexport type ComputerCellMode =\n \"exec\" | \"endpoint-cell\" | (string & Record<never, never>);\n\n/**\n * Where a Cell is. A Cell is `running` from the moment its session is\n * permitted to start until its process is known to be over, and then\n * `ended`. A session that never ran its process is an `error` Cell from the\n * start, and a permitted session whose process failed to start becomes one.\n * `ended` and `error` are final.\n *\n * The union is open; {@link validateComputerCellState} judges membership.\n */\nexport type ComputerCellState =\n \"running\" | \"ended\" | \"error\" | (string & Record<never, never>);\n\n/**\n * Why a Cell's session never ran its process.\n *\n * - `fits-no-host`: the Computer fits no host eligible to run it in its\n * Subnet.\n * - `execution-not-enabled`: the Computer's Namespace stopped having\n * execution turned on in the Subnet before the session started.\n * - `wake-timeout`: the Computer was not ready by the session's ready\n * deadline.\n * - `out-of-usage`: the Computer's Account had used its month's allowance\n * and its extra usage, as session reason `OUT_OF_USAGE` describes.\n * - `isolation-class-not-admitted`: the Computer runs in an isolation class\n * its Subnet no longer admits, as session reason\n * `ISOLATION_CLASS_NOT_ADMITTED` describes.\n * - `size-not-in-plan`: the Computer runs at a size larger than its\n * Account's plan includes, as session reason `SIZE_NOT_IN_PLAN`\n * describes.\n * - `vcpu-limit-reached`: the wake would take the vCPU of the Account's awake\n * Computers past what its plan allows at once, as session reason\n * `VCPU_LIMIT_REACHED` describes.\n * - `attach-timeout`: a ready session was not attached by its attach\n * deadline.\n * - `cancelled`: the session was cancelled before it started.\n * - `revoked`: the session's authorization was revoked before it started,\n * as when a newer execution of the Computer superseded the one it was\n * granted on.\n * - `released`: the Computer's execution was released before the session\n * started.\n * - `expired`: the session reached its expiry before it started.\n * - `ended`: the platform ended the session before it started.\n * - `start-failed`: the session was permitted to start but its process\n * failed to start. The Cell keeps its place in the journal and its\n * recording.\n * - `put-to-sleep`: the session's Computer was put to sleep on request\n * before the session started.\n *\n * The union is open; {@link validateComputerCellErrorReason} judges\n * membership.\n */\nexport type ComputerCellErrorReason =\n | \"fits-no-host\"\n | \"execution-not-enabled\"\n | \"wake-timeout\"\n | \"out-of-usage\"\n | \"isolation-class-not-admitted\"\n | \"size-not-in-plan\"\n | \"vcpu-limit-reached\"\n | \"attach-timeout\"\n | \"cancelled\"\n | \"revoked\"\n | \"released\"\n | \"expired\"\n | \"ended\"\n | \"start-failed\"\n | \"put-to-sleep\"\n | (string & Record<never, never>);\n\n/**\n * Whether the machine that ran a Cell's session recorded its facts.\n *\n * - `recorded`: the machine records the session: its start, its end, and its\n * output byte counts arrive as the machine reports them.\n * - `not-recorded`: the session ran on a machine or path that does not record\n * sessions. The Cell shows who ran what and when it was admitted; its\n * process facts stay unknown.\n * - `lost`: the machine could not record the session, or its record never\n * reached the platform before the Cell was closed.\n *\n * The union is open; {@link validateComputerCellRecording} judges\n * membership.\n */\nexport type ComputerCellRecording =\n \"recorded\" | \"not-recorded\" | \"lost\" | (string & Record<never, never>);\n\n/**\n * How a Cell's process ended.\n *\n * - `exited`: the process exited on its own account; its exit code is\n * reported when the machine observed it.\n * - `signaled`: the process was ended by a signal, which is reported when\n * the machine observed it.\n * - `unknown`: the process's end was not observed. Nothing about it is\n * invented.\n *\n * The union is open; {@link validateComputerCellProcessOutcome} judges\n * membership.\n */\nexport type ComputerCellProcessOutcome =\n | \"exited\"\n | \"signaled\"\n | \"unknown\"\n | \"start-unknown\"\n | (string & Record<never, never>);\n\n/**\n * What ended a Cell's session, which is distinct from how its process\n * ended: a session ended at its deadline can still have a process that\n * exited with a code.\n *\n * - `exited`: the session ended because its process ended.\n * - `deadline`: the time the session was permitted to run lapsed.\n * - `client-disconnected`: the session's client disconnected.\n * - `runtime-error`: the runtime that ran the session failed.\n * - `node-restarted`: the IDYL software on the machine that ran the\n * session restarted.\n * - `forked`: the Cell was copied into a fork of its Computer while it was\n * still running; the copy is closed with this termination and an unknown\n * outcome.\n * - `unknown`: the session's end was not reported: the platform closed the\n * Cell when the session could no longer be running.\n * - `interrupted`: an explicit execution fence ended the work. An already\n * observed process exit or signal remains unchanged.\n * - `put-to-sleep`: the session ended because its Computer was put to sleep\n * on request. An already observed process exit or signal remains\n * unchanged.\n *\n * The union is open; {@link validateComputerCellTermination} judges\n * membership.\n */\nexport type ComputerCellTermination =\n | \"exited\"\n | \"deadline\"\n | \"client-disconnected\"\n | \"runtime-error\"\n | \"node-restarted\"\n | \"forked\"\n | \"unknown\"\n | \"interrupted\"\n | \"put-to-sleep\"\n | (string & Record<never, never>);\n\n/**\n * Retained output facts: none when no checkpoint is kept, empty for zero-byte\n * retained output, complete for the whole output, truncated for a retained\n * prefix and partial when its tail was not checkpointed. Availability at\n * read time is a distinct observation. Unknown tokens remain carried on read.\n */\nexport type ComputerCellOutputStored =\n | \"none\"\n | \"empty\"\n | \"complete\"\n | \"truncated\"\n | \"partial\"\n | (string & Record<never, never>);\n\n/** A closed vocabulary's judgement: membership, the empty string reported as missing. */\nfunction vocabulary(\n label: string,\n members: readonly string[],\n): (value: string) => void {\n return (value) => {\n if (members.includes(value)) return;\n if (value === \"\") throw new TypeError(`${label} is required`);\n throw new TypeError(`unknown ${label} ${JSON.stringify(value)}`);\n };\n}\n\n/** Judges that the mode is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellMode: (mode: ComputerCellMode) => void =\n vocabulary(\"computer cell mode\", [\"exec\", \"endpoint-cell\"]);\n\n/** Judges that the state is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellState: (state: ComputerCellState) => void =\n vocabulary(\"computer cell state\", [\"running\", \"ended\", \"error\"]);\n\n/** Judges that the error reason is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellErrorReason: (\n reason: ComputerCellErrorReason,\n) => void = vocabulary(\"computer cell error reason\", [\n \"fits-no-host\",\n \"execution-not-enabled\",\n \"wake-timeout\",\n \"out-of-usage\",\n \"isolation-class-not-admitted\",\n \"size-not-in-plan\",\n \"vcpu-limit-reached\",\n \"attach-timeout\",\n \"cancelled\",\n \"revoked\",\n \"released\",\n \"expired\",\n \"ended\",\n \"start-failed\",\n \"put-to-sleep\",\n]);\n\n/** Judges that the recording is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellRecording: (\n recording: ComputerCellRecording,\n) => void = vocabulary(\"computer cell recording\", [\n \"recorded\",\n \"not-recorded\",\n \"lost\",\n]);\n\n/** Judges that the process outcome is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellProcessOutcome: (\n outcome: ComputerCellProcessOutcome,\n) => void = vocabulary(\"computer cell process outcome\", [\n \"exited\",\n \"signaled\",\n \"unknown\",\n \"start-unknown\",\n]);\n\n/** Judges that the termination is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellTermination: (\n termination: ComputerCellTermination,\n) => void = vocabulary(\"computer cell termination\", [\n \"exited\",\n \"deadline\",\n \"client-disconnected\",\n \"runtime-error\",\n \"node-restarted\",\n \"forked\",\n \"unknown\",\n \"interrupted\",\n \"put-to-sleep\",\n]);\n\n/** Judges that the output-stored value is one this SDK names. Throws a `TypeError`. */\nexport const validateComputerCellOutputStored: (\n stored: ComputerCellOutputStored,\n) => void = vocabulary(\"computer cell output stored\", [\n \"none\",\n \"empty\",\n \"complete\",\n \"truncated\",\n \"partial\",\n]);\n\n/** The command an exec session ran: the argument vector its request stated. */\nexport interface ComputerCellExecCommand {\n /** The command and its arguments. Always written. */\n readonly argv: readonly string[];\n /**\n * Whether `argv` is cut, as a journal list carries it: its leading\n * arguments, the last of them possibly shortened, holding at most\n * {@link MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES} bytes together. Reading\n * the entry on its own returns the whole vector.\n */\n readonly truncated?: boolean;\n}\n\n/**\n * What a Cell's session ran. A Cell of mode `exec` carries its command in\n * `exec`; an endpoint cell carries no member, because the Computer alone\n * records its command.\n *\n * A read carries a member this SDK does not name rather than refusing it,\n * as a further property of the command, and encodes it again unchanged, so\n * a Cell read and written back loses nothing;\n * {@link computerCellCommandUnknownMembers} names such members, and\n * validation refuses a command carrying one.\n */\nexport interface ComputerCellCommand {\n readonly exec?: ComputerCellExecCommand;\n}\n\nconst execCommandShape: Shape<ComputerCellExecCommand> =\n object<ComputerCellExecCommand>({\n argv: always(array(string())),\n truncated: omitEmpty(boolean()),\n });\n\n/** The members this SDK names, in the order they are written. */\nconst COMMAND_MEMBERS: readonly [keyof ComputerCellCommand, Shape<unknown>][] =\n [[\"exec\", execCommandShape as Shape<unknown>]];\n\n/**\n * The names, in lexical order, of the members a read carried that this SDK\n * does not name. It is empty for a command this SDK can describe.\n */\nexport function computerCellCommandUnknownMembers(\n command: ComputerCellCommand,\n): readonly string[] {\n const record = command as Readonly<Record<string, unknown>>;\n return Object.keys(record)\n .filter(\n (name) =>\n !COMMAND_MEMBERS.some(([known]) => known === name) &&\n record[name] !== undefined &&\n record[name] !== null,\n )\n .sort();\n}\n\n/**\n * A command is read as a reader of the journal routes reads it: the members\n * this SDK names are decoded, any other member is carried as it arrived, and\n * a member written as null is absent. It is written with the named members\n * first, then every carried member, unchanged.\n */\nconst commandShape: Shape<ComputerCellCommand> = {\n unknownFields: () => undefined,\n decode: (value, path, mode) => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n if (mode === \"lenient\") return value as ComputerCellCommand;\n throw new StrictDecodeError({\n reason: \"wrong_type\",\n path,\n message: `${path}: expected an object`,\n });\n }\n const members = value as Readonly<Record<string, unknown>>;\n const decoded: Record<string, unknown> = {};\n for (const name of Object.keys(members)) {\n const raw = members[name];\n if (raw === null || raw === undefined) continue;\n const known = COMMAND_MEMBERS.find(([member]) => member === name);\n decoded[name] =\n known === undefined\n ? raw\n : known[1].decode(raw, fieldPath(path, name), mode);\n }\n return decoded;\n },\n encode: (command) => {\n const record = command as Readonly<Record<string, unknown>>;\n const encoded: Record<string, JsonValue> = {};\n for (const [name, shape] of COMMAND_MEMBERS) {\n const member = record[name];\n if (member !== undefined) encoded[name] = shape.encode(member);\n }\n for (const name of computerCellCommandUnknownMembers(command)) {\n encoded[name] = record[name] as JsonValue;\n }\n return encoded;\n },\n zero: () => ({}),\n isZero: (command) => Object.keys(command).length === 0,\n isEmpty: () => false,\n};\n\n/** Why a Cell's session never ran its process. */\nexport interface ComputerCellError {\n /** The cause, from a closed set a caller may branch on. Always written. */\n readonly reason: ComputerCellErrorReason;\n}\n\n/** How a Cell's process ended, as the machine observed it. */\nexport interface ComputerCellProcess {\n /** How the process ended. Always written. */\n readonly outcome: ComputerCellProcessOutcome;\n /**\n * The process's exit code, reported only with outcome `exited` and only\n * when the machine observed it; zero is a reading.\n */\n readonly exitCode?: Integer;\n /**\n * The signal that ended the process, as the machine reports it; reported\n * only with outcome `signaled` and only when the machine observed it.\n */\n readonly signal?: string;\n}\n\n/**\n * How much output a Cell's session wrote and what of it the platform keeps.\n * The counts are of the bytes the process wrote, before any framing; a\n * session with a terminal writes one stream, counted as standard output.\n */\nexport interface ComputerCellOutput {\n /** Bytes written to standard output; zero is a reading, `undefined` until reported. */\n readonly stdoutBytes?: Integer;\n /** Bytes written to standard error; zero is a reading, `undefined` until reported. */\n readonly stderrBytes?: Integer;\n /** What of the output is kept. Always written. */\n readonly stored: ComputerCellOutputStored;\n}\n\n/**\n * One recorded command in a Computer: who ran what, from which client, how\n * it ran, when it started and ended, how it ended, and how much output it\n * wrote. A notebook records the commands of the sessions that name it. Every\n * notebook session is one Cell, whatever the client, including one that\n * never ran its process, which is an error Cell holding its command and the\n * reason. A private session, one that names no notebook, is never a Cell.\n *\n * Anyone who may read the Computer may read the Cells of its journal,\n * whoever created them; a notebook's Cells are read through the notebook.\n * The material a session attaches with is never part of a Cell. Standard\n * input and keystrokes are never recorded.\n *\n * The process facts are reported by the machine that ran the session, are\n * filled in as they arrive, and never change once known. An unknown fact is\n * absent, never invented. Instants are RFC 3339 strings.\n *\n * A read decodes leniently: a field, a token, or a command member newer\n * than this SDK is carried rather than refused, and\n * {@link validateComputerCell} judges the Cell against this SDK's\n * contract.\n */\nexport interface ComputerCell extends StorageResourceReference {\n /** Applied version observed at process start; absent is unreported and zero is genesis. */\n readonly ranAt?: Integer;\n /** Reported save progress or a retained outcome. */\n readonly save?: ComputerCellSave;\n /** The ID of the journal entry that holds the Cell. */\n readonly id: JournalEntryId;\n /** The user Computer session, absent on copies. Historical origin metadata may retain its identity without a live session binding. */\n readonly session?: ComputerSessionId;\n /**\n * The notebook the Cell belongs to. `undefined` on a Cell of the\n * Computer's own history.\n */\n readonly notebook?: string;\n /** The admitting identity: the creator of the session. */\n readonly creator: string;\n /** The kind of client the session's request stated, or `unknown`; informative. */\n readonly client: ComputerSessionClient;\n /** How the session ran its process; it selects the member of `command` that carries it. */\n readonly mode: ComputerCellMode;\n /** Whether the session ran its process with a terminal. Always written. */\n readonly terminal: boolean;\n /** What the session ran. */\n readonly command: ComputerCellCommand;\n /** Where the Cell is. */\n readonly state: ComputerCellState;\n /** Why the session never ran its process; present exactly in state `error`. */\n readonly error?: ComputerCellError;\n /**\n * Whether the machine recorded the session; present on every Cell whose\n * session was permitted to start, and absent on an error Cell whose\n * session never was.\n */\n readonly recording?: ComputerCellRecording;\n /** When the session's process started, as the machine observed it; `undefined` until reported. */\n readonly startedAt?: string;\n /** When the session's process ended or failed to start, as the machine observed it; `undefined` until reported. */\n readonly endedAt?: string;\n /** How the session's process ended; `undefined` until known. */\n readonly process?: ComputerCellProcess;\n /** What ended the session; `undefined` until known. */\n readonly termination?: ComputerCellTermination;\n /** How much output the session wrote, and what of it is kept. */\n readonly output: ComputerCellOutput;\n}\n\n/** The wire shape of a Cell. */\nexport const computerCellShape: Shape<ComputerCell> = object<ComputerCell>({\n id: always(string<JournalEntryId>()),\n session: omitEmpty(string<ComputerSessionId>()),\n notebook: omitEmpty(string()),\n ...storageResourceReferenceFields,\n ranAt: pointer(integer({ unsigned: false, bits: 64 })),\n save: pointer(computerCellSaveShape),\n creator: always(string()),\n client: always(string<ComputerSessionClient>()),\n mode: always(string<ComputerCellMode>()),\n terminal: always(boolean()),\n command: always(commandShape),\n state: always(string<ComputerCellState>()),\n error: pointer(\n object<ComputerCellError>({\n reason: always(string<ComputerCellErrorReason>()),\n }),\n ),\n recording: omitEmpty(string<ComputerCellRecording>()),\n startedAt: omitZero(timestampShape),\n endedAt: omitZero(timestampShape),\n process: pointer(\n object<ComputerCellProcess>({\n outcome: always(string<ComputerCellProcessOutcome>()),\n exitCode: pointer(integer({ unsigned: false, bits: 64 })),\n signal: omitEmpty(string()),\n }),\n ),\n termination: omitEmpty(string<ComputerCellTermination>()),\n output: always(\n object<ComputerCellOutput>({\n stdoutBytes: pointer(integer({ unsigned: false, bits: 64 })),\n stderrBytes: pointer(integer({ unsigned: false, bits: 64 })),\n stored: always(string<ComputerCellOutputStored>()),\n }),\n ),\n});\n\n/** Renders a Cell as the document the platform emits. */\nexport function encodeComputerCell(cell: ComputerCell): JsonObject {\n return computerCellShape.encode(cell) as JsonObject;\n}\n\n/**\n * Judges the command against this SDK's contract: no member this SDK does\n * not name, and an `exec` member that follows its own rules. Throws a\n * `TypeError`.\n */\nexport function validateComputerCellCommand(\n command: ComputerCellCommand,\n): void {\n const unknown = computerCellCommandUnknownMembers(command);\n if (unknown.length > 0) {\n throw new TypeError(\n `command member ${JSON.stringify(unknown[0])} is not one this version names`,\n );\n }\n if (command.exec === undefined) {\n throw new TypeError(\"command.exec is required\");\n }\n validateExecCommand(command.exec);\n}\n\nfunction validateExecCommand(command: ComputerCellExecCommand): void {\n if (command.argv.length === 0) {\n throw new TypeError(\"command.exec.argv is required\");\n }\n if (command.truncated !== true) return;\n const encoder = new TextEncoder();\n const total = command.argv.reduce(\n (sum, argument) => sum + encoder.encode(argument).byteLength,\n 0,\n );\n if (total > MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES) {\n throw new TypeError(\n `command.exec.argv must not exceed ${String(MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES)} bytes when truncated`,\n );\n }\n}\n\n/**\n * Judges the Cell against this SDK's contract: canonical IDs, a creator, a\n * client, mode, state, and command this SDK names, an `exec` command on an\n * exec Cell and none on an endpoint cell, an error exactly on an error\n * Cell, a recording on every Cell that is not an error Cell, no end on a\n * running Cell, and process, termination, and output facts this SDK names.\n * Throws a `TypeError`.\n */\nexport function validateComputerCell(cell: ComputerCell): void {\n if (cell.ranAt !== undefined && cell.ranAt < 0)\n throw new TypeError(\"ranAt must be non-negative\");\n const notebook = cell.notebook ?? \"\";\n if (notebook !== \"\") validateComputerNotebookName(notebook);\n if (cell.save !== undefined) validateComputerCellSave(cell.save);\n parseJournalEntryId(cell.id);\n const session = cell.session ?? \"\";\n if (session !== \"\") {\n prefixed(\"session\", () => {\n parseComputerSessionId(session);\n });\n }\n prefixed(\"owner\", () => {\n validateStorageResourceReference(cell);\n });\n if (cell.creator === \"\") throw new TypeError(\"creator is required\");\n validateComputerSessionClient(cell.client);\n validateComputerCellMode(cell.mode);\n validateModeCommand(cell);\n validateComputerCellState(cell.state);\n validateState(cell);\n const startedAt = cell.startedAt ?? \"\";\n const endedAt = cell.endedAt ?? \"\";\n if (\n !isZeroInstant(startedAt) &&\n !isZeroInstant(endedAt) &&\n Date.parse(endedAt) < Date.parse(startedAt)\n ) {\n throw new TypeError(\"endedAt must not be before startedAt\");\n }\n if (cell.process !== undefined) validateProcess(cell.process);\n const termination = cell.termination ?? \"\";\n if (termination !== \"\") validateComputerCellTermination(termination);\n validateOutput(cell.output);\n}\n\n/**\n * Judges the command against a mode already accepted: an endpoint cell\n * carries no member, and an exec Cell carries a valid `exec`.\n */\nfunction validateModeCommand(cell: ComputerCell): void {\n if (cell.mode === \"endpoint-cell\") {\n if (\n COMMAND_MEMBERS.some(([name]) => cell.command[name] !== undefined) ||\n computerCellCommandUnknownMembers(cell.command).length > 0\n ) {\n throw new TypeError(\n \"an endpoint cell carries no command: the Computer alone records it\",\n );\n }\n return;\n }\n validateComputerCellCommand(cell.command);\n}\n\nfunction validateState(cell: ComputerCell): void {\n if (cell.state === \"error\") {\n if (cell.error === undefined) {\n throw new TypeError(\"error is required in state error\");\n }\n const reason = cell.error.reason;\n prefixed(\"error.reason\", () => {\n validateComputerCellErrorReason(reason);\n });\n } else if (cell.error !== undefined) {\n throw new TypeError(`error must be absent in state ${cell.state}`);\n }\n const recording = cell.recording ?? \"\";\n if (recording === \"\") {\n if (cell.state !== \"error\") {\n throw new TypeError(`recording is required in state ${cell.state}`);\n }\n } else {\n validateComputerCellRecording(recording);\n }\n if (\n cell.state === \"running\" &&\n (!isZeroInstant(cell.endedAt ?? \"\") ||\n cell.process !== undefined ||\n (cell.termination ?? \"\") !== \"\")\n ) {\n throw new TypeError(\n \"endedAt, process, and termination must be absent in state running\",\n );\n }\n}\n\nfunction validateProcess(process: ComputerCellProcess): void {\n prefixed(\"process.outcome\", () => {\n validateComputerCellProcessOutcome(process.outcome);\n });\n if (process.exitCode !== undefined && process.outcome !== \"exited\") {\n throw new TypeError(\n `process.exitCode must be absent with outcome ${process.outcome}`,\n );\n }\n if ((process.signal ?? \"\") !== \"\" && process.outcome !== \"signaled\") {\n throw new TypeError(\n `process.signal must be absent with outcome ${process.outcome}`,\n );\n }\n}\n\nfunction validateOutput(output: ComputerCellOutput): void {\n if (output.stdoutBytes !== undefined && output.stdoutBytes < 0) {\n throw new TypeError(\"output.stdoutBytes must be non-negative\");\n }\n if (output.stderrBytes !== undefined && output.stderrBytes < 0) {\n throw new TypeError(\"output.stderrBytes must be non-negative\");\n }\n prefixed(\"output.stored\", () => {\n validateComputerCellOutputStored(output.stored);\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { Integer } from \"../resource/json.js\";\nimport {\n always,\n array,\n boolean,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport {\n isComputerImageDigestReference,\n validateComputerExecutionSettings,\n validateComputerEnvironmentVariableName,\n computerExecutionSettingsShape,\n type ComputerExecutionSettings,\n} from \"../resource/computer-execution-settings.js\";\nimport { errorMessage } from \"../resource/validation.js\";\nimport {\n compareComputerImagePatch,\n validateComputerImagePatch,\n} from \"./computer-image.js\";\nimport {\n validateComputerSessionClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\n\n/**\n * The most bytes of variable values an execution-settings change carries in a journal\n * list, its variables' values taken together. A change whose values are\n * longer has them cut and is marked truncated; reading the entry on its own\n * returns them whole.\n */\nexport const MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES = 4 << 10;\n\n/** The changed path of a change of the OS image. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_IMAGE = \"image\";\n/**\n * The changed path of a change of the isolation class, by which a Computer\n * moves between `secure-container` and `vm`.\n */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_ISOLATION = \"isolation\";\n/** The changed path of a change of the CPU limit. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_CPU = \"cpu\";\n/** The changed path of a change of the memory limit. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_MEMORY = \"memory\";\n/** The changed path of a change of the network. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_NETWORK = \"network\";\n/** The changed path of a change of the default shell. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_SHELL = \"shell\";\n/**\n * The prefix of the changed path of a variable that was added, changed, or\n * removed, as in `variables.LOG_LEVEL`.\n */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_VARIABLE_PREFIX = \"variables.\";\n/**\n * The prefix of the changed path of a Secret attachment that was added,\n * changed, or removed, named by its variable, as in `secrets.GITHUB_TOKEN`.\n */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_SECRET_PREFIX = \"secrets.\";\n/** The changed path of a change of the workload identity. */\nexport const COMPUTER_EXECUTION_SETTINGS_CHANGED_IDENTITY = \"identity\";\n\n/**\n * What made an execution-settings entry.\n *\n * - `settings`: a write of the settings, by the creator the change names, a\n * create included.\n * - `image-patch`: IDYL's: the Computer started on a newer patch level of\n * the IDYL image its settings name. The settings, and their revision, are\n * those in force before it.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateComputerExecutionSettingsChangeCause}\n * judges membership, and a caller shows an entry of a cause it does not\n * know as an execution-settings change it cannot describe.\n */\nexport type ComputerExecutionSettingsChangeCause =\n \"settings\" | \"image-patch\" | (string & Record<never, never>);\n\n/**\n * Judges that the cause is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateComputerExecutionSettingsChangeCause(\n cause: ComputerExecutionSettingsChangeCause,\n): void {\n switch (cause) {\n case \"settings\":\n case \"image-patch\":\n return;\n case \"\":\n throw new TypeError(\n \"computer execution-settings change cause is required\",\n );\n default:\n throw new TypeError(\n `unknown computer execution-settings change cause ${JSON.stringify(cause)}`,\n );\n }\n}\n\n/** One patch level of an IDYL image and its pinned image. */\nexport interface ComputerExecutionSettingsImagePatchLevel {\n /** The patch level. See `validateComputerImagePatch`. */\n readonly patch: string;\n /** The pinned image of the patch level, by digest. */\n readonly image: string;\n}\n\n/**\n * A patch IDYL applied to the IDYL image a Computer's settings name: the\n * catalog entry and the patch levels the Computer's starts moved between.\n */\nexport interface ComputerExecutionSettingsImagePatch {\n /** The catalog name of the IDYL image. */\n readonly name: string;\n /** The patch level the Computer last started on before. */\n readonly from: ComputerExecutionSettingsImagePatchLevel;\n /** The patch level the Computer started on. */\n readonly to: ComputerExecutionSettingsImagePatchLevel;\n}\n\n/**\n * One entry of a Computer's journal about its execution settings: the whole\n * settings after the entry, the revision in force, and its cause. A change of the\n * settings names what it changed and who made it from which client; it is\n * recorded when the Computer is created, whenever a write states settings\n * that differ from those in force, and on the restore entry of a restore\n * that changes them to those of the restored point. An image patch names\n * the IDYL image and the patch levels it moved between; IDYL records it\n * when the Computer starts on a newer patch level. Neither a change nor a\n * patch changes the Computer's files; a restore changes them through the\n * version its entry owns.\n *\n * Anyone who may read the Computer may read every change, variable values\n * included. A read decodes leniently, and\n * {@link validateComputerExecutionSettingsChange} judges the change against this\n * SDK's contract.\n */\nexport interface ComputerExecutionSettingsChange {\n /** What made the entry. */\n readonly cause: ComputerExecutionSettingsChangeCause;\n /**\n * The whole execution settings after the entry, as stated. In a journal\n * list its variable values are bounded and `truncated` is set when they\n * were cut.\n */\n readonly settings: ComputerExecutionSettings;\n /**\n * The revision of the execution settings in force after the entry, the\n * `ComputerExecutionSettingsStatus.revision` a read reports: the one a change of\n * the settings made, the first being revision one, and the one an image\n * patch left unchanged.\n */\n readonly revision: Integer;\n /**\n * What a change of the settings changed against the settings before it,\n * each path once: `image`, `cpu`, `memory`, `network`, or `variables.`\n * and a variable's name. The first change, recorded when the Computer is\n * created, is made against IDYL's defaults. Empty for an image patch.\n * Always written.\n */\n readonly changed: readonly string[];\n /** The patch IDYL applied; present exactly when `cause` is `image-patch`. */\n readonly imagePatch?: ComputerExecutionSettingsImagePatch;\n /** The identity that made a change of the settings; absent on an image patch. */\n readonly creator?: string;\n /**\n * The kind of client a change of the settings' request stated, or\n * `unknown` when it stated none; informative, and absent on an image\n * patch.\n */\n readonly client?: ComputerSessionClient;\n /**\n * Whether the variable values are cut, as a journal list carries them:\n * each variable keeps its name, and the values, in order, hold at most\n * {@link MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES} bytes together, the\n * last of them possibly shortened and those after it empty.\n */\n readonly truncated?: boolean;\n}\n\nconst imagePatchLevelShape: Shape<ComputerExecutionSettingsImagePatchLevel> =\n object<ComputerExecutionSettingsImagePatchLevel>({\n patch: always(string()),\n image: always(string()),\n });\n\n/** The wire shape of an execution-settings change. */\nexport const computerExecutionSettingsChangeShape: Shape<ComputerExecutionSettingsChange> =\n object<ComputerExecutionSettingsChange>({\n cause: always(string<ComputerExecutionSettingsChangeCause>()),\n settings: always(computerExecutionSettingsShape),\n revision: always(integer({ unsigned: false, bits: 64 })),\n changed: always(array(string())),\n imagePatch: pointer(\n object<ComputerExecutionSettingsImagePatch>({\n name: always(string()),\n from: always(imagePatchLevelShape),\n to: always(imagePatchLevelShape),\n }),\n ),\n creator: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n truncated: omitEmpty(boolean()),\n });\n\n/**\n * Judges the change against this SDK's contract: a cause this SDK names,\n * valid settings, a positive revision, and, when truncated, variable values\n * within {@link MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES}. A change of\n * the settings names at least one changed path, each one this SDK names and\n * none repeated, a creator, and a client this SDK names, and no image\n * patch. An image patch names no changed path, creator, or client; its\n * settings name the IDYL image it patched; and it moves from one patch level\n * to a later one. Throws a `TypeError`.\n */\nexport function validateComputerExecutionSettingsChange(\n change: ComputerExecutionSettingsChange,\n): void {\n validateComputerExecutionSettingsChangeCause(change.cause);\n validateComputerExecutionSettings(change.settings);\n if (change.revision < 1) {\n throw new TypeError(\"revision must be positive\");\n }\n if (change.cause === \"image-patch\") {\n validateImagePatch(change);\n } else {\n validateSettingsChange(change);\n }\n if (change.truncated === true) {\n const encoder = new TextEncoder();\n const total = (change.settings.variables ?? []).reduce(\n (sum, variable) => sum + encoder.encode(variable.value).byteLength,\n 0,\n );\n if (total > MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES) {\n throw new TypeError(\n `settings.variables values must not exceed ${String(MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES)} bytes when truncated`,\n );\n }\n }\n}\n\nfunction validateSettingsChange(change: ComputerExecutionSettingsChange): void {\n if (change.imagePatch !== undefined) {\n throw new TypeError(\n \"imagePatch must be absent on a change of the settings\",\n );\n }\n if (change.changed.length === 0) {\n throw new TypeError(\"changed must name at least one path\");\n }\n change.changed.forEach((path, index) => {\n prefixed(`changed[${String(index)}]`, () => {\n validateChangedPath(path);\n });\n const previous = change.changed.indexOf(path);\n if (previous < index) {\n throw new TypeError(\n `changed[${String(index)}] duplicates changed[${String(previous)}]`,\n );\n }\n });\n if ((change.creator ?? \"\") === \"\") {\n throw new TypeError(\"creator is required\");\n }\n validateComputerSessionClient(change.client ?? \"\");\n}\n\nfunction validateImagePatch(change: ComputerExecutionSettingsChange): void {\n const patch = change.imagePatch;\n if (patch === undefined) {\n throw new TypeError(\"imagePatch is required on an image patch\");\n }\n if (\n change.changed.length !== 0 ||\n (change.creator ?? \"\") !== \"\" ||\n (change.client ?? \"\") !== \"\"\n ) {\n throw new TypeError(\n \"changed, creator, and client must be absent on an image patch\",\n );\n }\n if (\n change.settings.image === undefined ||\n (change.settings.image.idyl ?? \"\") !== patch.name\n ) {\n throw new TypeError(\n \"imagePatch.name must be the IDYL image the settings name\",\n );\n }\n validatePatchLevel(patch.from, \"from\");\n validatePatchLevel(patch.to, \"to\");\n if (compareComputerImagePatch(patch.to.patch, patch.from.patch) <= 0) {\n throw new TypeError(\n \"imagePatch.to.patch must be later than imagePatch.from.patch\",\n );\n }\n}\n\nfunction validatePatchLevel(\n level: ComputerExecutionSettingsImagePatchLevel,\n field: string,\n): void {\n prefixed(`imagePatch.${field}.patch`, () => {\n validateComputerImagePatch(level.patch);\n });\n if (!isComputerImageDigestReference(level.image)) {\n throw new TypeError(\n `imagePatch.${field}.image must be pinned by a sha256 digest`,\n );\n }\n}\n\nfunction validateChangedPath(path: string): void {\n switch (path) {\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_IMAGE:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_ISOLATION:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_CPU:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_MEMORY:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_NETWORK:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_SHELL:\n case COMPUTER_EXECUTION_SETTINGS_CHANGED_IDENTITY:\n return;\n default:\n break;\n }\n for (const prefix of [\n COMPUTER_EXECUTION_SETTINGS_CHANGED_VARIABLE_PREFIX,\n COMPUTER_EXECUTION_SETTINGS_CHANGED_SECRET_PREFIX,\n ]) {\n if (!path.startsWith(prefix)) continue;\n try {\n validateComputerEnvironmentVariableName(path.slice(prefix.length));\n } catch (cause) {\n throw new TypeError(\n `${JSON.stringify(path)} does not name a variable: ${errorMessage(cause)}`,\n { cause },\n );\n }\n return;\n }\n throw new TypeError(\n `unknown execution settings path ${JSON.stringify(path)}`,\n );\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { integerEqual } from \"../internal/strictdecode.js\";\nimport { isUint64 } from \"../internal/strictdecode.js\";\nimport { validateComputerNotebookName } from \"./computer-notebook-name.js\";\nimport {\n validateComputerSessionKind,\n type ComputerSessionKind,\n} from \"./computer-awake.js\";\nimport { parseJson } from \"../resource/json.js\";\nimport type { Integer } from \"../resource/json.js\";\nimport type { PageOptions } from \"./storage.js\";\nimport {\n storageResourceReferenceShape,\n validateForkReference,\n type ForkReference,\n} from \"../resource/storage.js\";\nimport {\n parseComputerSessionId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport type { JsonObject } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n parseJournalEntryId,\n type JournalEntryId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\nimport type { ListResponse } from \"./types.js\";\nimport {\n validateComputerCell,\n computerCellShape,\n type ComputerCell,\n} from \"./computer-cell.js\";\nimport {\n isZeroInstant,\n validateStatedClient,\n type ComputerSessionClient,\n} from \"./computer-session.js\";\nimport {\n validateComputerExecutionSettingsChange,\n computerExecutionSettingsChangeShape,\n type ComputerExecutionSettingsChange,\n} from \"./computer-execution-settings.js\";\n\n/** The largest page a journal list returns, and the largest `limit` a request may state. */\nexport const MAX_JOURNAL_PAGE_SIZE = 200;\n\n/**\n * What a journal entry records.\n *\n * - `genesis`: the first entry of every journal: sequence number zero,\n * recording nothing. It is not counted in any count.\n * - `cell`: an entry that records one command run in the Computer outside\n * any notebook, such as a copied Cell. Its `cell` carries the detail. A\n * command run in a notebook is a cell of that notebook, listed with it,\n * and a private session records nothing.\n * - `execution-settings`: an entry that records one change to the Computer's\n * execution settings. Its `executionSettings` carries the whole settings after the\n * change.\n * - `upload`: an entry that owns a file-change version once its publication\n * succeeds.\n * - `edit`: an entry that owns a file-change version once its publication\n * succeeds.\n * - `restore`: an entry that owns a restored version. On a Computer whose\n * restore changed its execution settings, its `executionSettings` records\n * the settings the restore set.\n * - `save`: an entry that records a save and owns its published version.\n * Its `save` says what caused it.\n * - `fork-point`: an entry that records the copied starting point of a\n * fork.\n * - `rename`: an entry that records a change of the Computer's name. Its\n * `rename` carries the name before and after, and its `creator` who\n * renamed it. It owns no version: the Computer's files and identity are\n * unchanged.\n * - `wake`: an entry that records the Computer woken on request from sleep.\n * Its `creator` is who woke it. It owns no version and carries no detail.\n * A wake that found the Computer awake records nothing.\n * - `sleep`: an entry that records the Computer put to sleep on request:\n * its execution released after its files were saved and its sessions\n * ended. Its `creator` is who put it to sleep. It owns no version; the\n * save the sleep made is its own `save` entry. Its `sleep` detail is\n * present when the sleep discarded unsaved changes on request. A sleep\n * that found the Computer asleep records nothing.\n * - `restart`: an entry that records the Computer's execution started again\n * without the Computer going to sleep, on the same files and history. IDYL\n * makes a restart on its own, so it names no `creator`. Its `restart` detail\n * says why. The sessions open at the restart ended with it. It owns no\n * version.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateJournalEntryKind}\n * judges membership, and a caller shows an entry of a kind it does not know\n * as one it cannot describe.\n */\nexport type JournalEntryKind =\n | \"genesis\"\n | \"cell\"\n | \"execution-settings\"\n | \"upload\"\n | \"edit\"\n | \"restore\"\n | \"save\"\n | \"fork-point\"\n | \"rename\"\n | \"wake\"\n | \"sleep\"\n | \"restart\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the kind is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateJournalEntryKind(kind: JournalEntryKind): void {\n switch (kind) {\n case \"genesis\":\n case \"cell\":\n case \"execution-settings\":\n case \"upload\":\n case \"edit\":\n case \"restore\":\n case \"save\":\n case \"fork-point\":\n case \"rename\":\n case \"wake\":\n case \"sleep\":\n case \"restart\":\n return;\n case \"\":\n throw new TypeError(\"journal entry kind is required\");\n default:\n throw new TypeError(`unknown journal entry kind ${JSON.stringify(kind)}`);\n }\n}\n\n/**\n * What caused a save entry.\n *\n * - `session-end`: a save made when a session ended, capturing the files it\n * left behind.\n * - `change`: a save IDYL made on its own because the files changed: once\n * writes had been quiet for the Computer's `saveQuiet`, or once its\n * `saveMaxInterval` had passed while writes went on. One such save can hold the changes of\n * several people, so it names no `creator`.\n * - `request`: a save a caller asked for with a commit.\n * - `release`: the save IDYL made when the execution holding the files was\n * released.\n * - `recovery`: a save of work kept after the session that wrote it ended\n * without saving it. It names no `creator`.\n *\n * The union is open: a token the platform reports that this SDK does not\n * know is carried as a string; {@link validateJournalSaveTrigger} judges\n * membership, and a caller shows a save of a trigger it does not know as a\n * save it cannot explain.\n */\nexport type JournalSaveTrigger =\n | \"session-end\"\n | \"change\"\n | \"request\"\n | \"release\"\n | \"recovery\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the trigger is one this SDK names. The empty string is\n * reported as missing. Throws a `TypeError`.\n */\nexport function validateJournalSaveTrigger(trigger: JournalSaveTrigger): void {\n switch (trigger) {\n case \"session-end\":\n case \"change\":\n case \"request\":\n case \"release\":\n case \"recovery\":\n return;\n case \"\":\n throw new TypeError(\"save trigger is required\");\n default:\n throw new TypeError(`unknown save trigger ${JSON.stringify(trigger)}`);\n }\n}\n\n/**\n * What caused a save entry, and, for a save made when a session ended,\n * which session and which notebook cell. The links are historical: the\n * session or notebook they name may since have been deleted, and they grant\n * no access to it.\n */\nexport interface JournalEntrySave {\n /** What caused the save. */\n readonly trigger: JournalSaveTrigger;\n /**\n * The notebook whose cell caused the save, set together with `cell`;\n * only on a `session-end` save.\n */\n readonly notebook?: string;\n /**\n * The notebook cell whose end caused the save, set together with\n * `notebook`; only on a `session-end` save.\n */\n readonly cell?: JournalEntryId;\n /** The session whose end caused the save; only on a `session-end` save. */\n readonly session?: ComputerSessionId;\n}\n\nconst journalEntrySaveShape: Shape<JournalEntrySave> = object<JournalEntrySave>(\n {\n trigger: always(string<JournalSaveTrigger>()),\n notebook: omitEmpty(string()),\n cell: omitEmpty(string<JournalEntryId>()),\n session: omitEmpty(string<ComputerSessionId>()),\n },\n);\n\n/**\n * Judges the save against this SDK's contract: a trigger this SDK names, a\n * notebook and a cell stated together and well formed, a well-formed\n * session, and links only on a `session-end` save. Throws a `TypeError`.\n */\nexport function validateJournalEntrySave(save: JournalEntrySave): void {\n validateJournalSaveTrigger(save.trigger);\n const notebook = save.notebook ?? \"\";\n const cell = save.cell ?? \"\";\n const session = save.session ?? \"\";\n if ((notebook !== \"\") !== (cell !== \"\")) {\n throw new TypeError(\"notebook and cell must be set together\");\n }\n if (notebook !== \"\") {\n prefixed(\"notebook\", () => {\n validateComputerNotebookName(notebook);\n });\n prefixed(\"cell\", () => {\n parseJournalEntryId(cell);\n });\n }\n if (session !== \"\") {\n prefixed(\"session\", () => {\n parseComputerSessionId(session);\n });\n }\n if (save.trigger !== \"session-end\" && (notebook !== \"\" || session !== \"\")) {\n throw new TypeError(\n `a ${save.trigger} save names no notebook, cell, or session`,\n );\n }\n}\n\n/** Original provenance retained by copies of any journal entry kind; it conveys no source-read or execution authority. */\nexport interface JournalEntryOrigin extends ForkReference {\n /** Recorded original Computer session, when known; historical and only on Cell origins. */\n readonly session?: ComputerSessionId;\n}\n/** Checks recorded identities without requiring or authorizing source existence. */\nexport function validateJournalEntryOrigin(origin: JournalEntryOrigin): void {\n validateForkReference(origin);\n if ((origin.session ?? \"\") !== \"\")\n prefixed(\"session\", () => {\n parseComputerSessionId(origin.session ?? \"\");\n });\n}\nconst journalEntryOriginShape: Shape<JournalEntryOrigin> =\n object<JournalEntryOrigin>({\n source: always(storageResourceReferenceShape),\n entry: always(string<JournalEntryId>()),\n session: omitEmpty(string<ComputerSessionId>()),\n });\n\n/**\n * The change of name a `rename` entry records. Both names are the\n * Computer's names at the time; neither is a reference that resolves to the\n * Computer later, since the name it had may since have been given to\n * another Computer.\n */\nexport interface JournalEntryRename {\n /** The name the Computer had before the rename. */\n readonly from: string;\n /** The name the rename gave the Computer. */\n readonly to: string;\n}\n\nconst journalEntryRenameShape: Shape<JournalEntryRename> =\n object<JournalEntryRename>({\n from: always(string()),\n to: always(string()),\n });\n\n/**\n * Requires both names, and requires them to differ: a rename to the name a\n * Computer already has records nothing. Throws a `TypeError`.\n */\nexport function validateJournalEntryRename(rename: JournalEntryRename): void {\n if (rename.from === \"\" || rename.to === \"\") {\n throw new TypeError(\"from and to are required\");\n }\n if (rename.from === rename.to) {\n throw new TypeError(\"from and to must differ\");\n }\n}\n\n/**\n * One entry of a Computer's journal: the history of what was\n * done to that resource, one list that only grows forward. An entry is\n * placed when it is admitted, so a running Cell keeps its place while it\n * runs, and entries are never moved, rewritten, or removed. Restoring an\n * earlier version appends a restore entry rather than returning to it.\n *\n * Entries are numbered per journal in the order they were admitted,\n * starting at genesis. A Computer's execution-settings changes share that\n * journal with the entries that own saved versions. Every entry names who caused it, except one IDYL made on its\n * own.\n *\n * {@link decodeJournalEntry} reads one leniently: a field or kind\n * newer than this SDK is carried rather than refused, and\n * {@link validateJournalEntry} judges the entry against this SDK's\n * contract.\n */\nexport interface JournalEntry {\n /** Saved version owned by this entry; zero is genesis, absent until published. */\n readonly version?: Integer;\n /** Original source and entry; later copies and source deletion retain it unchanged. */\n readonly origin?: JournalEntryOrigin;\n /** Names the entry on the journal routes; it never changes. */\n readonly id: JournalEntryId;\n /**\n * The entry's sequence number: zero for genesis, then increasing in the\n * order entries were admitted. Two entries of one resource never share\n * one. Always written.\n */\n readonly seq: Integer;\n /** What the entry records. */\n readonly kind: JournalEntryKind;\n /** When the platform admitted the entry, by its own clock, as an RFC 3339 instant. */\n readonly admittedAt: string;\n /**\n * The identity that caused the entry: who saved, uploaded, restored,\n * changed the settings, renamed, or forked. `undefined` only on an entry IDYL made\n * on its own, such as genesis, a change-driven save, a release save, or an\n * image patch. It is informative and grants nothing.\n */\n readonly creator?: string;\n /**\n * The kind of client whose request caused the entry, or `unknown` when\n * that request stated none. `undefined` on an entry IDYL made on its own.\n * It is informative and grants nothing.\n */\n readonly client?: ComputerSessionClient;\n /**\n * The session the entry records, present exactly when `kind` is `cell`.\n * In a journal list it carries its command bounded by\n * `MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES`; reading the entry on its own\n * returns the whole command.\n */\n readonly cell?: ComputerCell;\n /**\n * The execution settings the entry records. Present when `kind` is\n * `execution-settings`, and on the `restore` entry of a Computer whose\n * restore changed its settings, where it is the settings the restore set:\n * those in force at the restored version's entry, applied at the\n * Computer's next start. Absent on every other entry. In a journal list\n * its variable values are bounded by\n * `MAX_COMPUTER_EXECUTION_SETTINGS_LISTED_VARIABLE_BYTES`; reading the\n * entry on its own returns them whole.\n */\n readonly executionSettings?: ComputerExecutionSettingsChange;\n /** What caused a save, present exactly when `kind` is `save`. */\n readonly save?: JournalEntrySave;\n /** The change of name, present exactly when `kind` is `rename`. */\n readonly rename?: JournalEntryRename;\n /**\n * Why the Computer slept and what the sleep did beyond releasing it. It is\n * present only when `kind` is `sleep`.\n */\n readonly sleep?: JournalEntrySleep;\n /**\n * What kind of session started the Computer. It is present only when `kind`\n * is `wake`, and absent on a wake request and on a start IDYL made on its\n * own.\n */\n readonly wake?: JournalEntryWake;\n /** Why the execution started again, present exactly when `kind` is `restart`. */\n readonly restart?: JournalEntryRestart;\n}\n\n/**\n * Why a Computer went to sleep: `request`, a caller asked; `idle`, it reached\n * its idle timeout with nothing holding it; `no-execution`, its execution had\n * stopped and nothing was waiting to start it again; `settings`, so that its\n * next start uses new execution settings; `restore`, a restore set earlier\n * execution settings; `node-drain`, the machine it ran on was being drained; `out-of-usage`,\n * the Account ran out of usage; `plan-size`, its size is above what the\n * Account's plan includes; or `powered-off`, a program in it shut its machine\n * down, and IDYL saved and released it as on a sleep a caller asks for.\n *\n * The union is open: a caller shows a sleep of a reason it does not know as a\n * sleep it cannot explain.\n */\nexport type JournalSleepReason =\n | \"request\"\n | \"idle\"\n | \"no-execution\"\n | \"settings\"\n | \"restore\"\n | \"node-drain\"\n | \"out-of-usage\"\n | \"plan-size\"\n | \"powered-off\"\n | (string & Record<never, never>);\n\n/**\n * Judges that the reason is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateJournalSleepReason(reason: JournalSleepReason): void {\n switch (reason) {\n case \"request\":\n case \"idle\":\n case \"no-execution\":\n case \"settings\":\n case \"restore\":\n case \"node-drain\":\n case \"out-of-usage\":\n case \"plan-size\":\n case \"powered-off\":\n return;\n case \"\":\n throw new TypeError(\"sleep reason is required\");\n default:\n throw new TypeError(`unknown sleep reason \"${reason}\"`);\n }\n}\n\n/**\n * Why a Computer's execution started again: `node-lost`, the machine it ran on\n * was lost; `failed`, its machine or container failed and its execution ended\n * on its own; or `replaced`, its execution was replaced for any other reason.\n *\n * The union is open: a caller shows a restart of a reason it does not know as\n * a restart it cannot explain.\n */\nexport type JournalRestartReason =\n \"node-lost\" | \"failed\" | \"replaced\" | (string & Record<never, never>);\n\n/**\n * Judges that the reason is one this SDK names. The empty string is reported\n * as missing. Throws a `TypeError`.\n */\nexport function validateJournalRestartReason(\n reason: JournalRestartReason,\n): void {\n switch (reason) {\n case \"node-lost\":\n case \"failed\":\n case \"replaced\":\n return;\n case \"\":\n throw new TypeError(\"restart reason is required\");\n default:\n throw new TypeError(`unknown restart reason \"${reason}\"`);\n }\n}\n\n/** The detail of a `wake` entry a session caused. */\nexport interface JournalEntryWake {\n /** The kind of session that started the Computer. */\n readonly session: ComputerSessionKind;\n}\n\n/** The detail of a `restart` entry. */\nexport interface JournalEntryRestart {\n /** Why the Computer's execution started again. */\n readonly reason: JournalRestartReason;\n}\n\n/**\n * The detail of a `sleep` entry. Its presence alone says nothing about\n * unsaved changes: only `discardedUnsavedChanges` does.\n */\nexport interface JournalEntrySleep {\n /** Why the Computer slept. */\n readonly reason?: JournalSleepReason;\n /**\n * The idle timeout in force when the Computer slept, in its canonical\n * spelling; only with `idle`.\n */\n readonly idleTimeout?: string;\n /**\n * True when the sleep was asked to discard the Computer's unsaved changes\n * (`CreateComputerSleepRequest.discardUnsavedChanges`) and released it\n * without saving them.\n */\n readonly discardedUnsavedChanges?: boolean;\n /**\n * True when the sleep was asked to force\n * (`CreateComputerSleepRequest.force`): its save holds what the Computer's\n * programs had written when it was taken, and they were then stopped\n * without a shutdown.\n */\n readonly forced?: boolean;\n}\n\nconst journalEntrySleepShape: Shape<JournalEntrySleep> =\n object<JournalEntrySleep>({\n reason: omitEmpty(string<JournalSleepReason>()),\n idleTimeout: omitEmpty(string()),\n discardedUnsavedChanges: omitEmpty(boolean()),\n forced: omitEmpty(boolean()),\n });\n\nconst journalEntryWakeShape: Shape<JournalEntryWake> = object<JournalEntryWake>(\n {\n session: always(string<ComputerSessionKind>()),\n },\n);\n\nconst journalEntryRestartShape: Shape<JournalEntryRestart> =\n object<JournalEntryRestart>({\n reason: always(string<JournalRestartReason>()),\n });\n\nconst journalEntryShape: Shape<JournalEntry> = object<JournalEntry>({\n version: pointer(integer({ unsigned: false, bits: 64 })),\n id: always(string<JournalEntryId>()),\n seq: always(integer({ unsigned: false, bits: 64 })),\n kind: always(string<JournalEntryKind>()),\n admittedAt: always(timestampShape),\n creator: omitEmpty(string()),\n client: omitEmpty(string<ComputerSessionClient>()),\n origin: pointer(journalEntryOriginShape),\n cell: pointer(computerCellShape),\n executionSettings: pointer(computerExecutionSettingsChangeShape),\n save: pointer(journalEntrySaveShape),\n rename: pointer(journalEntryRenameShape),\n sleep: pointer(journalEntrySleepShape),\n wake: pointer(journalEntryWakeShape),\n restart: pointer(journalEntryRestartShape),\n});\n\n/** Judges the reasons a wake, a sleep or a restart entry carries. */\nfunction validateReasons(entry: JournalEntry): void {\n const { wake, sleep, restart } = entry;\n if (wake !== undefined) {\n prefixed(\"wake\", () => {\n validateComputerSessionKind(wake.session);\n });\n }\n if (sleep !== undefined) {\n prefixed(\"sleep\", () => {\n const reason = sleep.reason ?? \"\";\n if (reason !== \"\") validateJournalSleepReason(reason);\n if ((sleep.idleTimeout ?? \"\") !== \"\" && reason !== \"idle\") {\n throw new TypeError(\n `idleTimeout must be absent on a \"${reason}\" sleep`,\n );\n }\n if (sleep.forced === true && sleep.discardedUnsavedChanges === true) {\n throw new TypeError(\"a sleep cannot both discard and force\");\n }\n });\n }\n if (entry.kind === \"restart\") {\n if (restart === undefined) {\n throw new TypeError(\"restart is required on a restart entry\");\n }\n prefixed(\"restart\", () => {\n validateJournalRestartReason(restart.reason);\n });\n }\n}\n\n/**\n * One page of a resource's journal, newest entry first. `totalCount` is\n * the number of entries other than genesis, read when the listing's first\n * page was, so the whole listing returns `totalCount` entries and then\n * genesis; entries admitted after the first page are not listed by its\n * continuation. `continue` is the position the next page starts from,\n * absent on the last page.\n */\nexport type ListJournalResponse = ListResponse<JournalEntry>;\n\nconst listJournalResponseShape: Shape<ListJournalResponse> =\n object<ListJournalResponse>({\n items: always(array(journalEntryShape)),\n totalCount: always(integer({ unsigned: false, bits: 64 })),\n snapshotCursor: omitEmpty(string()),\n continue: omitEmpty(string()),\n });\n\n/**\n * Reads a journal entry the platform served, leniently. `document` is JSON\n * text or a value already parsed from JSON; a string is parsed once, as a\n * response is. A field, kind, token, or command member this SDK does not\n * name is carried as it arrived, and nothing is judged.\n */\nexport function decodeJournalEntry(document: unknown): JournalEntry {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, journalEntryShape, \"lenient\");\n}\n\n/** Renders a journal entry as the document the platform emits. */\nexport function encodeJournalEntry(entry: JournalEntry): JsonObject {\n return journalEntryShape.encode(entry) as JsonObject;\n}\n\n/**\n * Reads a journal page the platform served, leniently, as\n * {@link decodeJournalEntry} reads each entry.\n */\nexport function decodeJournalPage(document: unknown): ListJournalResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listJournalResponseShape, \"lenient\");\n}\n\n/**\n * Renders a journal page as the document the platform emits: `items` and\n * `totalCount` always, `continue` only on a page that is not the last.\n */\nexport function encodeJournalPage(page: ListJournalResponse): JsonObject {\n return listJournalResponseShape.encode(page) as JsonObject;\n}\n\n/**\n * Judges the entry against this SDK's contract: a canonical ID, a kind this\n * SDK names, an admission time, and the shape the kind gives it. Genesis has\n * sequence number zero and carries no Cell, execution settings, save, or\n * rename. Every other entry has a positive sequence number. A Cell entry has\n * a valid Cell whose ID is the entry's; an execution-settings entry has\n * valid execution settings; a restore entry may carry valid execution\n * settings; a save entry has a valid save; a rename entry has a valid rename\n * and owns no version; a sleep entry may carry a valid sleep detail; a wake\n * entry may carry a valid wake detail; a restart entry has a valid restart\n * detail and owns no version; no entry carries one its kind does not. A\n * copied Cell has no live session and is not running. Historical origin\n * sessions are permitted only on Cell\n * entries. Throws a `TypeError`.\n */\nexport function validateJournalEntry(entry: JournalEntry): void {\n parseJournalEntryId(entry.id);\n validateJournalEntryKind(entry.kind);\n if (isZeroInstant(entry.admittedAt)) {\n throw new TypeError(\"admittedAt is required\");\n }\n if (entry.version !== undefined && entry.version < 0)\n throw new TypeError(\"version must be non-negative\");\n validateStatedClient(entry.client);\n const origin = entry.origin;\n if (origin !== undefined) {\n prefixed(\"origin\", () => {\n validateJournalEntryOrigin(origin);\n });\n if (entry.kind !== \"cell\" && (origin.session ?? \"\") !== \"\")\n throw new TypeError(\"origin.session must be absent on a non-cell entry\");\n }\n if (entry.sleep !== undefined && entry.kind !== \"sleep\")\n throw new TypeError(`sleep must be absent on a ${entry.kind} entry`);\n if (entry.wake !== undefined && entry.kind !== \"wake\")\n throw new TypeError(`wake must be absent on a ${entry.kind} entry`);\n if (entry.restart !== undefined && entry.kind !== \"restart\")\n throw new TypeError(`restart must be absent on a ${entry.kind} entry`);\n if (entry.kind === \"genesis\") {\n if (!integerEqual(entry.seq, 0)) {\n throw new TypeError(\"genesis must have seq 0\");\n }\n if (\n entry.cell !== undefined ||\n entry.executionSettings !== undefined ||\n entry.save !== undefined ||\n entry.rename !== undefined\n ) {\n throw new TypeError(\n \"genesis must have no cell, executionSettings, save, or rename\",\n );\n }\n return;\n }\n if (entry.rename !== undefined && entry.kind !== \"rename\") {\n throw new TypeError(`rename must be absent on a ${entry.kind} entry`);\n }\n if (entry.seq < 1) {\n throw new TypeError(`a ${entry.kind} entry must have a positive seq`);\n }\n switch (entry.kind) {\n case \"cell\":\n validateCellEntry(entry);\n return;\n case \"execution-settings\": {\n if (entry.version !== undefined)\n throw new TypeError(\"execution-settings entries own no version\");\n const executionSettings = entry.executionSettings;\n if (executionSettings === undefined) {\n throw new TypeError(\n \"executionSettings is required on an execution-settings entry\",\n );\n }\n if (entry.cell !== undefined) {\n throw new TypeError(\n \"cell must be absent on an execution-settings entry\",\n );\n }\n if (entry.save !== undefined) {\n throw new TypeError(\n \"save must be absent on an execution-settings entry\",\n );\n }\n prefixed(\"executionSettings\", () => {\n validateComputerExecutionSettingsChange(executionSettings);\n });\n return;\n }\n case \"save\": {\n if (entry.cell !== undefined || entry.executionSettings !== undefined) {\n throw new TypeError(\n \"cell and executionSettings must be absent on a save entry\",\n );\n }\n const save = entry.save;\n if (save === undefined) {\n throw new TypeError(\"save is required on a save entry\");\n }\n prefixed(\"save\", () => {\n validateJournalEntrySave(save);\n });\n return;\n }\n case \"restore\": {\n if (entry.cell !== undefined || entry.save !== undefined) {\n throw new TypeError(\"cell and save must be absent on a restore entry\");\n }\n const executionSettings = entry.executionSettings;\n if (executionSettings !== undefined) {\n prefixed(\"executionSettings\", () => {\n validateComputerExecutionSettingsChange(executionSettings);\n });\n }\n return;\n }\n case \"rename\": {\n if (entry.version !== undefined)\n throw new TypeError(\"rename entries own no version\");\n if (\n entry.cell !== undefined ||\n entry.executionSettings !== undefined ||\n entry.save !== undefined\n ) {\n throw new TypeError(\n \"cell, executionSettings, and save must be absent on a rename entry\",\n );\n }\n const rename = entry.rename;\n if (rename === undefined) {\n throw new TypeError(\"rename is required on a rename entry\");\n }\n prefixed(\"rename\", () => {\n validateJournalEntryRename(rename);\n });\n return;\n }\n case \"wake\":\n case \"sleep\":\n case \"restart\":\n if (entry.version !== undefined)\n throw new TypeError(`${entry.kind} entries own no version`);\n if (\n entry.cell !== undefined ||\n entry.executionSettings !== undefined ||\n entry.save !== undefined\n ) {\n throw new TypeError(\n `cell, executionSettings, and save must be absent on a ${entry.kind} entry`,\n );\n }\n validateReasons(entry);\n return;\n default:\n if (\n entry.cell !== undefined ||\n entry.executionSettings !== undefined ||\n entry.save !== undefined\n ) {\n throw new TypeError(\n \"cell, executionSettings, and save must be absent on a version entry\",\n );\n }\n }\n}\n\n/**\n * Judges a Cell entry: it owns no version and carries a valid Cell whose ID\n * is the entry's, a copy carrying no live session.\n */\nfunction validateCellEntry(entry: JournalEntry): void {\n if (entry.version !== undefined)\n throw new TypeError(\"a cell owns no version\");\n if (entry.executionSettings !== undefined) {\n throw new TypeError(\"executionSettings must be absent on a cell entry\");\n }\n if (entry.save !== undefined) {\n throw new TypeError(\"save must be absent on a cell entry\");\n }\n const cell = entry.cell;\n if (cell === undefined) {\n throw new TypeError(\"cell is required on a cell entry\");\n }\n if (cell.id !== entry.id) {\n throw new TypeError(\"cell.id does not match the entry id\");\n }\n prefixed(\"cell\", () => {\n validateComputerCell(cell);\n });\n if (entry.origin !== undefined) {\n if ((cell.session ?? \"\") !== \"\")\n throw new TypeError(\"cell.session must be absent on a copied entry\");\n if (cell.state === \"running\")\n throw new TypeError(\"a copied cell must not be running\");\n }\n}\n\n/**\n * Reads a resource's journal a page at a time, newest entry first, ending\n * with genesis. The journal list takes these options rather than\n * `ListOptions`: it pages by an opaque position, never by offset, and\n * refuses offset, filter, and sort with {@link ERROR_CODE_INVALID_QUERY}.\n */\nexport type JournalListOptions = PageOptions;\n\n/**\n * Judges that the options state a listing the route serves: a `limit` that\n * is a non-negative integer within {@link MAX_JOURNAL_PAGE_SIZE}. Throws a\n * `TypeError`.\n */\nexport function validateJournalListOptions(options: JournalListOptions): void {\n const limit = options.limit ?? 0;\n if (!isUint64(limit) || limit < 0) {\n throw new TypeError(\"limit must be a non-negative integer\");\n }\n if (limit > MAX_JOURNAL_PAGE_SIZE) {\n throw new TypeError(\n `limit must be at most ${String(MAX_JOURNAL_PAGE_SIZE)}`,\n );\n }\n}\n\n/**\n * Returned with HTTP 400 when a request states a query parameter its route\n * does not serve, such as offset, filter, or sort on the journal list, or a\n * value it cannot read.\n */\nexport const ERROR_CODE_INVALID_QUERY = \"INVALID_QUERY\";\n\n/**\n * Returned with HTTP 400 when a continue position was not issued by the\n * listing it is passed to: malformed, or issued for another resource. The\n * listing starts again without it.\n */\nexport const ERROR_CODE_INVALID_CONTINUE = \"INVALID_CONTINUE\";\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * A Computer's journal is its history. A private session records no\n * entry. Anyone who may read the Computer may read its whole journal,\n * including entries other identities caused. Every journal call addresses\n * the Computer by name or by its stable identity, as the session calls do,\n * on the Subnet the client's placement resolves to.\n */\nimport { TransportError } from \"../errors.js\";\nimport type { NamespaceScope } from \"../api/types.js\";\nimport {\n decodeJournalEntry,\n decodeJournalPage,\n validateJournalListOptions,\n type ListJournalResponse,\n type JournalEntry,\n type JournalListOptions,\n} from \"../api/journal.js\";\nimport { computerJournal, computerJournalById } from \"../internal/apipath.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { listEnvelope } from \"../internal/envelopes.js\";\nimport { computerJournalQuery } from \"../internal/listquery.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport {\n parseComputerId,\n parseJournalEntryId,\n type JournalEntryId,\n} from \"../resource/uuid-id.js\";\n\n/**\n * One Computer's journal, built from the scope the resolution named; with\n * `entryId`, one entry of it.\n */\nexport type JournalPath = (\n scope: NamespaceScope,\n entryId?: JournalEntryId,\n) => string;\n\n/**\n * The journal of the Computer addressed by name. Throws a `TypeError` when\n * `name` is blank.\n */\nexport function journalByName(name: string): JournalPath {\n requireNonBlank(name, \"computer name\");\n return (scope, entryId) => computerJournal(scope, name, entryId);\n}\n\n/**\n * The journal of the Computer addressed by its stable identity. Throws a\n * `TypeError` when `id` is not a canonical UUID.\n */\nexport function journalById(id: string): JournalPath {\n const computerId = parseComputerId(id);\n return (scope, entryId) => computerJournalById(scope, computerId, entryId);\n}\n\n/**\n * Reads one page of the journal. The options are judged before any request\n * is sent, and the page is read leniently once its envelope is one.\n */\nexport async function listJournal(\n context: PlacementContext,\n journal: JournalPath,\n options: JournalListOptions,\n signal: AbortSignal | undefined,\n label = \"computer journal\",\n): Promise<ListJournalResponse> {\n validateJournalListOptions(options);\n const resolved = await resolvePlacement(context, signalOption(signal));\n const response = await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n `${journal(resolved.scope)}${computerJournalQuery(options)}`,\n signalOption(signal),\n );\n listEnvelope(response, label);\n return decodeJournalPage(response);\n}\n\n/**\n * Reads one entry of the journal. A response naming another entry is\n * refused.\n */\nexport async function getJournalEntry(\n context: PlacementContext,\n journal: JournalPath,\n entryId: string,\n signal: AbortSignal | undefined,\n label = \"computer journal\",\n): Promise<JournalEntry> {\n const id = parseJournalEntryId(entryId);\n const resolved = await resolvePlacement(context, signalOption(signal));\n const entry = decodeJournalEntry(\n await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n journal(resolved.scope, id),\n signalOption(signal),\n ),\n );\n if (entry.id !== id) {\n throw new TransportError(\n \"invalid_response\",\n `read ${label} entry response names a different entry`,\n );\n }\n return entry;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n object,\n omitEmpty,\n pointer,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { parseJson, type Integer } from \"../resource/json.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport { validateComputerEnvironmentVariableName } from \"../resource/computer-execution-settings.js\";\nimport {\n isComputerId,\n isResourceId,\n type ComputerId,\n type ResourceId,\n} from \"../resource/uuid-id.js\";\nimport { errorMessage } from \"../resource/validation.js\";\n\n/**\n * Whether an attachment's value can be sent: `healthy`, `expiring` within\n * seven days, or `broken`. Open, as the platform may name more; the\n * validator judges membership.\n */\nexport type ComputerSecretAttachmentHealth =\n \"healthy\" | \"expiring\" | \"broken\" | (string & Record<never, never>);\n\n/**\n * Why an attachment is not healthy. `expiring` goes with the health of that\n * name; every other reason goes with `broken`:\n *\n * - `secret_deleted`: the attached Secret was deleted; writing to its name\n * within seven days of the delete restores it, and the attachment resumes;\n * - `secret_not_found`: no Secret with the attachment's ID exists in the\n * Computer's Namespace and Subnet;\n * - `not_attached`: the attachment came with a fork's or a restore's\n * settings and was never attached to this Computer;\n * - `no_egress`: the Secret no longer states a source and an egress;\n * - `expired`: the value has expired;\n * - `source_failed`: the Secret's source cannot produce a value.\n *\n * Open, as the platform may name more; the validator judges membership.\n */\nexport type ComputerSecretAttachmentReason =\n | \"secret_deleted\"\n | \"secret_not_found\"\n | \"not_attached\"\n | \"no_egress\"\n | \"expiring\"\n | \"expired\"\n | \"source_failed\"\n | (string & Record<never, never>);\n\n/** The state of one Secret attachment of a Computer. */\nexport interface ComputerSecretAttachmentStatus {\n /** The environment variable that holds the placeholder. Always written. */\n readonly env: string;\n /** The ID of the Secret the attachment holds. Always written. */\n readonly secret: ResourceId;\n /** Whether the attachment's value can be sent. Always written. */\n readonly health: ComputerSecretAttachmentHealth;\n /** Why the health is not `healthy`; `undefined` when it is. */\n readonly reason?: ComputerSecretAttachmentReason;\n /**\n * When the value the attachment sends stops being valid, an RFC 3339\n * time; `undefined` while no expiry is known.\n */\n readonly expiresAt?: string;\n}\n\n/**\n * The state of each Secret attachment of a Computer, one item per attachment\n * in its execution settings in force, in their order. It is read on its own\n * route when asked for; a Computer read never carries it.\n */\nexport interface ListComputerSecretAttachmentsResponse {\n /** One status per attachment. Always written, empty when none. */\n readonly items: readonly ComputerSecretAttachmentStatus[];\n}\n\nconst computerSecretAttachmentStatusShape: Shape<ComputerSecretAttachmentStatus> =\n object<ComputerSecretAttachmentStatus>({\n env: always(string()),\n secret: always(string<ResourceId>()),\n health: always(string<ComputerSecretAttachmentHealth>()),\n reason: omitEmpty(string<ComputerSecretAttachmentReason>()),\n expiresAt: pointer(timestampShape),\n });\n\nconst listComputerSecretAttachmentsResponseShape: Shape<ListComputerSecretAttachmentsResponse> =\n object<ListComputerSecretAttachmentsResponse>({\n items: always(array(computerSecretAttachmentStatusShape)),\n });\n\n/**\n * Reads an attachment-state list leniently: a field, health or reason newer\n * than this SDK is carried rather than refused, and\n * {@link validateListComputerSecretAttachmentsResponse} judges it.\n */\nexport function decodeListComputerSecretAttachmentsResponse(\n document: unknown,\n): ListComputerSecretAttachmentsResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(\n value,\n listComputerSecretAttachmentsResponseShape,\n \"lenient\",\n );\n}\n\n/** Renders an attachment-state list as the document the platform emits. */\nexport function encodeListComputerSecretAttachmentsResponse(\n page: ListComputerSecretAttachmentsResponse,\n): unknown {\n return listComputerSecretAttachmentsResponseShape.encode(page);\n}\n\nconst BROKEN_REASONS: ReadonlySet<string> = new Set([\n \"secret_deleted\",\n \"secret_not_found\",\n \"not_attached\",\n \"no_egress\",\n \"expired\",\n \"source_failed\",\n]);\n\n/**\n * Judges one attachment's state: a well-formed variable, a Secret ID in\n * canonical form, a health this SDK names, and a reason exactly when the\n * health is not `healthy`: `expiring` with the health of that name, any\n * other reason with `broken`. Throws a `TypeError`.\n */\nexport function validateComputerSecretAttachmentStatus(\n status: ComputerSecretAttachmentStatus,\n): void {\n try {\n validateComputerEnvironmentVariableName(status.env);\n } catch (cause) {\n throw new TypeError(`env: ${errorMessage(cause)}`, { cause });\n }\n if (!isResourceId(status.secret)) {\n throw new TypeError(\"secret: resource ID must be a canonical UUID\");\n }\n const reason = status.reason ?? \"\";\n switch (status.health) {\n case \"healthy\":\n if (reason !== \"\") {\n throw new TypeError(\"reason must be absent when healthy\");\n }\n return;\n case \"expiring\":\n if (reason !== \"expiring\") {\n throw new TypeError(\"reason must be expiring when expiring\");\n }\n return;\n case \"broken\":\n if (reason === \"\") throw new TypeError(\"reason is required when broken\");\n if (!BROKEN_REASONS.has(reason)) {\n throw new TypeError(\n `unknown attachment reason ${JSON.stringify(reason)}`,\n );\n }\n return;\n case \"\":\n throw new TypeError(\"health is required\");\n default:\n throw new TypeError(\n `unknown attachment health ${JSON.stringify(status.health)}`,\n );\n }\n}\n\n/**\n * Judges every item with {@link validateComputerSecretAttachmentStatus}, and\n * that no variable is listed twice. Throws a `TypeError` naming the item.\n */\nexport function validateListComputerSecretAttachmentsResponse(\n page: ListComputerSecretAttachmentsResponse,\n): void {\n const seen = new Map<string, number>();\n page.items.forEach((item, index) => {\n try {\n validateComputerSecretAttachmentStatus(item);\n } catch (cause) {\n throw new TypeError(`items[${String(index)}]: ${errorMessage(cause)}`, {\n cause,\n });\n }\n const previous = seen.get(item.env);\n if (previous !== undefined) {\n throw new TypeError(\n `items[${String(index)}].env duplicates items[${String(previous)}]`,\n );\n }\n seen.set(item.env, index);\n });\n}\n\n/**\n * One attachment of a Secret in one Computer's execution settings: which\n * Computer, through which variable, whether it is attached there, and\n * whether it is pinned to a version.\n */\nexport interface ComputerSecretUse {\n /** The stable ID of the Computer that holds the attachment. Always written. */\n readonly computer: ComputerId;\n /** The Computer's name within its Namespace and Subnet. Always written. */\n readonly computerName: string;\n /** The environment variable that holds the placeholder. Always written. */\n readonly env: string;\n /**\n * Whether the attachment was attached to this Computer by a caller who\n * held `vaultsecret:reference` on the Secret. An attachment that came with\n * the settings of a fork or a restore, and was never attached here, reads\n * `false`: its value is not sent, and its health reads `not_attached`,\n * until it is attached here. Always written.\n */\n readonly attached: boolean;\n /**\n * The version of the Secret the attachment is pinned to. `undefined` when\n * the attachment follows the Secret's current version, so a rotation\n * reaches it; a pinned attachment keeps its version.\n */\n readonly version?: Integer;\n}\n\n/**\n * Every attachment of one Secret in the execution settings of the Computers\n * the caller may read: one item per attachment that holds the Secret's ID,\n * ordered by Computer name and then by variable.\n *\n * It lists the settings in force, which a Computer applies from its next\n * start, so sleeping and awake Computers are listed alike; an awake Computer\n * keeps the attachments it started with until it next starts. It is read at\n * one moment, and one response holds every item, so it is not paged.\n * Computers the caller may not read are left out. The Secret itself is not\n * read: an ID that no readable Computer attaches reads as no items, whether\n * or not a Secret has it.\n */\nexport interface ListComputersBySecretResponse {\n /** One item per attachment. Always written, empty when none. */\n readonly items: readonly ComputerSecretUse[];\n}\n\nconst computerSecretUseShape: Shape<ComputerSecretUse> =\n object<ComputerSecretUse>({\n computer: always(string<ComputerId>()),\n computerName: always(string()),\n env: always(string()),\n attached: always(boolean()),\n version: omitEmpty(integer({ unsigned: true, bits: 64 })),\n });\n\nconst listComputersBySecretResponseShape: Shape<ListComputersBySecretResponse> =\n object<ListComputersBySecretResponse>({\n items: always(array(computerSecretUseShape)),\n });\n\n/**\n * Reads the attachments of a Secret leniently: a field newer than this SDK\n * is carried rather than refused, and\n * {@link validateListComputersBySecretResponse} judges it.\n */\nexport function decodeListComputersBySecretResponse(\n document: unknown,\n): ListComputersBySecretResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listComputersBySecretResponseShape, \"lenient\");\n}\n\n/** Renders the attachments of a Secret as the document the platform emits. */\nexport function encodeListComputersBySecretResponse(\n page: ListComputersBySecretResponse,\n): unknown {\n return listComputersBySecretResponseShape.encode(page);\n}\n\n/**\n * Judges one attachment of a Secret: a Computer ID in canonical form, a\n * Computer name, and a well-formed variable. Throws a `TypeError`.\n */\nexport function validateComputerSecretUse(use: ComputerSecretUse): void {\n if (!isComputerId(use.computer)) {\n throw new TypeError(\"computer: computer ID must be a canonical UUID\");\n }\n if (use.computerName === \"\") {\n throw new TypeError(\"computerName is required\");\n }\n try {\n validateComputerEnvironmentVariableName(use.env);\n } catch (cause) {\n throw new TypeError(`env: ${errorMessage(cause)}`, { cause });\n }\n}\n\n/**\n * Judges every item with {@link validateComputerSecretUse}, and that no\n * Computer lists one variable twice; one Computer may attach the Secret\n * through two variables. Throws a `TypeError` naming the item.\n */\nexport function validateListComputersBySecretResponse(\n page: ListComputersBySecretResponse,\n): void {\n const seen = new Map<string, number>();\n page.items.forEach((item, index) => {\n try {\n validateComputerSecretUse(item);\n } catch (cause) {\n throw new TypeError(`items[${String(index)}]: ${errorMessage(cause)}`, {\n cause,\n });\n }\n const key = `${item.computer} ${item.env}`;\n const previous = seen.get(key);\n if (previous !== undefined) {\n throw new TypeError(\n `items[${String(index)}] duplicates items[${String(previous)}]`,\n );\n }\n seen.set(key, index);\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The reads of a Namespace's Computers by the Secrets they attach: the\n * state of each attachment of one Computer, and every attachment of one\n * Secret across the Computers the caller may read. Both are read when asked\n * for, on the API that serves the Computers; neither reads a Secret's value,\n * and no Computer read carries them.\n */\nimport {\n decodeListComputerSecretAttachmentsResponse,\n decodeListComputersBySecretResponse,\n type ListComputerSecretAttachmentsResponse,\n type ListComputersBySecretResponse,\n} from \"../api/computer-secrets.js\";\nimport type { NamespaceScope } from \"../api/types.js\";\nimport { computersBySecret } from \"../internal/apipath.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { served } from \"../internal/envelopes.js\";\nimport { signalOption } from \"../internal/options.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport { parseResourceId } from \"../resource/uuid-id.js\";\n\n/** Reads the attachment states of the Computer `path` addresses. */\nexport async function listSecretAttachments(\n context: PlacementContext,\n path: (scope: NamespaceScope) => string,\n signal: AbortSignal | undefined,\n): Promise<ListComputerSecretAttachmentsResponse> {\n const resolved = await resolvePlacement(context, signalOption(signal));\n const response = await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n path(resolved.scope),\n signalOption(signal),\n );\n return served(\"computer secrets\", () =>\n decodeListComputerSecretAttachmentsResponse(response),\n );\n}\n\n/**\n * Reads every attachment of the Secret with ID `secretId` across the\n * Namespace's Computers. Throws a `TypeError` before any request when the\n * ID is not a canonical UUID.\n */\nexport async function listComputersBySecret(\n context: PlacementContext,\n secretId: string,\n signal: AbortSignal | undefined,\n): Promise<ListComputersBySecretResponse> {\n const id = parseResourceId(secretId);\n const resolved = await resolvePlacement(context, signalOption(signal));\n const response = await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n computersBySecret(resolved.scope, id),\n signalOption(signal),\n );\n return served(\"computers by secret\", () =>\n decodeListComputersBySecretResponse(response),\n );\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The session routes of a Computer: create, read, cancel and renew. A\n * session runs on the Computer's own session endpoint, over the client's\n * Computer connection; these routes record its grant and keep its lease. A\n * create answers at once, and no request is held open while the Computer\n * wakes.\n *\n * Every call addresses the Computer either by name or by its stable\n * identity, and every request of one call addresses the Subnet its single\n * placement resolution named.\n */\nimport type { NamespaceScope } from \"../api/types.js\";\nimport {\n decodeListComputerSessionsResponse,\n type ListComputerSessionsResponse,\n} from \"../api/computer-awake.js\";\nimport {\n ERROR_CODE_SESSION_FINAL,\n decodeComputerSession,\n encodeCreateComputerSessionRequest,\n isComputerSessionPhaseTerminal,\n validateCreateComputerSessionRequest,\n type CreateComputerSessionRequest,\n type ComputerSession,\n} from \"../api/computer-session.js\";\nimport { ApiError, TransportError, isApiCode } from \"../errors.js\";\nimport { computerSessions, computerSessionsById } from \"../internal/apipath.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport {\n resolvePlacement,\n type ResolvedPlacement,\n} from \"../internal/routing.js\";\nimport {\n parseComputerId,\n parseComputerSessionId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport { prefixed } from \"../resource/validation.js\";\n\n/**\n * One Computer's session collection, built from the scope the resolution\n * named; with `sessionId`, one session in it.\n */\ntype SessionCollection = (\n scope: NamespaceScope,\n sessionId?: ComputerSessionId,\n) => string;\n\n/**\n * The session collection of the Computer addressed by name. Throws a\n * `TypeError` when `name` is blank.\n */\nexport function sessionsByName(name: string): SessionCollection {\n requireNonBlank(name, \"computer name\");\n return (scope, sessionId) => computerSessions(scope, name, sessionId);\n}\n\n/**\n * The session collection of the Computer addressed by its stable identity.\n * Throws a `TypeError` when `id` is not a canonical UUID.\n */\nexport function sessionsById(id: string): SessionCollection {\n const computerId = parseComputerId(id);\n return (scope, sessionId) =>\n computerSessionsById(scope, computerId, sessionId);\n}\n\n/**\n * Creates a session in the collection on a fresh resolution and returns it\n * as the platform answered. The request is judged before anything is sent,\n * and a response that does not carry a canonical session ID and its\n * Computer's ID is refused.\n */\nexport async function createSession(\n context: PlacementContext,\n collection: SessionCollection,\n request: CreateComputerSessionRequest,\n signal: AbortSignal | undefined,\n): Promise<ComputerSession> {\n prefixed(\"create computer session request is invalid\", () => {\n validateCreateComputerSessionRequest(request);\n encodeCreateComputerSessionRequest(request);\n });\n const resolved = await resolvePlacement(context, signalOption(signal));\n const value = await context.state.transport.json<unknown>(\n \"POST\",\n resolved.endpoint,\n collection(resolved.scope),\n {\n body: encodeCreateComputerSessionRequest(request),\n ...signalOption(signal),\n },\n );\n const session = servedSession(value);\n try {\n parseComputerSessionId(session.id);\n parseComputerId(session.computer);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n \"create computer session response is invalid\",\n { cause },\n );\n }\n return session;\n}\n\n/**\n * A served session, read leniently. A session the package cannot read is\n * the platform's failure, never the caller's, so it is an\n * `invalid_response` `TransportError`.\n */\nfunction servedSession(value: unknown): ComputerSession {\n try {\n return decodeComputerSession(value);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n \"computer session response is invalid\",\n { cause },\n );\n }\n}\n\n/**\n * Reads one session of the collection, as it now is, on a fresh\n * resolution. A response naming another session is refused.\n */\nexport async function getSession(\n context: PlacementContext,\n collection: SessionCollection,\n sessionId: string,\n signal: AbortSignal | undefined,\n): Promise<ComputerSession> {\n const id = parseComputerSessionId(sessionId);\n const resolved = await resolvePlacement(context, signalOption(signal));\n const value = await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n collection(resolved.scope, id),\n signalOption(signal),\n );\n return sameSession(servedSession(value), id, \"read\");\n}\n\n/**\n * Lists the open sessions of the collection's Computer on a fresh\n * resolution, as anyone who may read the Computer sees them.\n */\nexport async function listSessions(\n context: PlacementContext,\n collection: SessionCollection,\n signal: AbortSignal | undefined,\n): Promise<ListComputerSessionsResponse> {\n const resolved = await resolvePlacement(context, signalOption(signal));\n return decodeListComputerSessionsResponse(\n await context.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n collection(resolved.scope),\n signalOption(signal),\n ),\n );\n}\n\n/** Cancels one session of the collection on a fresh resolution. */\nexport async function cancelSession(\n context: PlacementContext,\n collection: SessionCollection,\n sessionId: string,\n signal: AbortSignal | undefined,\n): Promise<void> {\n const id = parseComputerSessionId(sessionId);\n const resolved = await resolvePlacement(context, signalOption(signal));\n await context.state.transport.json<undefined>(\n \"DELETE\",\n resolved.endpoint,\n collection(resolved.scope, id),\n { response: \"none\", ...signalOption(signal) },\n );\n}\n\n/**\n * Renews one session of the collection on a fresh resolution, with a POST\n * that has no body, and returns the session as the renewal left it. A\n * response naming another session is refused.\n */\nexport async function renewSession(\n context: PlacementContext,\n collection: SessionCollection,\n sessionId: string,\n signal: AbortSignal | undefined,\n): Promise<ComputerSession> {\n const id = parseComputerSessionId(sessionId);\n const resolved = await resolvePlacement(context, signalOption(signal));\n return await renewAt(context, resolved, collection, id, signal);\n}\n\n/**\n * Renews several sessions of the collection on one placement resolution:\n * each session is renewed by its own POST to its renew route, all at once,\n * and no session's failure keeps the others from being sent.\n *\n * Resolves to the sessions that renewing again cannot keep, so the caller\n * stops renewing them: an ID that is not a canonical UUID, which is never\n * sent; a renewal answered with HTTP 404, the session or its Computer not\n * found; a renewal refused with HTTP 409 and `SESSION_FINAL`; and a renewal\n * that answers the session in a final phase. Every other failure, such as a\n * network failure, HTTP 429 or a server error, leaves its session out of\n * the result, to be renewed again. Placement is resolved only when an ID\n * is valid, and the call rejects only when that resolution fails.\n */\nexport async function renewSessions(\n context: PlacementContext,\n collection: SessionCollection,\n sessionIds: readonly string[],\n): Promise<string[]> {\n const over: string[] = [];\n const ids: ComputerSessionId[] = [];\n for (const sessionId of sessionIds) {\n try {\n ids.push(parseComputerSessionId(sessionId));\n } catch {\n over.push(sessionId);\n }\n }\n if (ids.length === 0) return over;\n const resolved = await resolvePlacement(context);\n const outcomes = await Promise.allSettled(\n ids.map((id) => renewAt(context, resolved, collection, id, undefined)),\n );\n outcomes.forEach((outcome, index) => {\n const id = ids[index];\n if (id === undefined) return;\n if (\n outcome.status === \"fulfilled\"\n ? isComputerSessionPhaseTerminal(outcome.value.status.phase)\n : sessionOver(outcome.reason)\n ) {\n over.push(id);\n }\n });\n return over;\n}\n\n/**\n * Whether a renewal's failure says the session can never be renewed: HTTP\n * 404, or HTTP 409 with `SESSION_FINAL`.\n */\nfunction sessionOver(error: unknown): boolean {\n return (\n (error instanceof ApiError && error.status === 404) ||\n (isApiCode(error, ERROR_CODE_SESSION_FINAL) && error.status === 409)\n );\n}\n\n/**\n * Renews one session of the collection on `resolved` with a POST that has\n * no body. A response naming another session is refused.\n */\nasync function renewAt(\n context: PlacementContext,\n resolved: ResolvedPlacement,\n collection: SessionCollection,\n id: ComputerSessionId,\n signal: AbortSignal | undefined,\n): Promise<ComputerSession> {\n const value = await context.state.transport.json<unknown>(\n \"POST\",\n resolved.endpoint,\n `${collection(resolved.scope, id)}/renew`,\n signalOption(signal),\n );\n return sameSession(servedSession(value), id, \"renew\");\n}\n\n/** `session`, refused when it is not the session `id` the call addressed. */\nfunction sameSession(\n session: ComputerSession,\n id: ComputerSessionId,\n call: \"read\" | \"renew\",\n): ComputerSession {\n if (session.id !== id) {\n throw new TransportError(\n \"invalid_response\",\n `${call} computer session response names a different session`,\n );\n }\n return session;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { validateComputerOwnerFilter } from \"../api/computer-owner.js\";\nimport { storageMethods, type StorageMethods } from \"./storage.js\";\nimport {\n computerOperationMethods,\n type ComputerOperationMethods,\n} from \"./computer-operations.js\";\nimport type { DeleteResponse, ListOptions } from \"../api/types.js\";\nimport { evaluateComputerWait } from \"../api/wait.js\";\nimport {\n createComputerRequestShape,\n decodeComputer,\n encodeUpdateComputerRequest,\n validateCreateComputerRequest,\n validateUpdateComputerRequest,\n} from \"../api/computer.js\";\nimport type { ListComputerSessionsResponse } from \"../api/computer-awake.js\";\nimport type {\n ListComputerSecretAttachmentsResponse,\n ListComputersBySecretResponse,\n} from \"../api/computer-secrets.js\";\nimport type {\n CreateComputerRequest,\n CreateComputerResponse,\n GetComputerResponse,\n ListComputersResponse,\n UpdateComputerRequest,\n UpdateComputerResponse,\n Computer,\n} from \"../api/computer.js\";\nimport {\n accountSubnet,\n computerById,\n computerSecrets,\n computerSecretsById,\n} from \"../internal/apipath.js\";\nimport { listEnvelope } from \"../internal/envelopes.js\";\nimport { imageCatalogQuery } from \"../internal/listquery.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport {\n decodeListComputerImagesResponse,\n type ListComputerImagesResponse,\n} from \"../api/computer-image.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport { ZoneCollection } from \"../internal/zone.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport type { AccountId } from \"../resource/id.js\";\nimport { parseComputerId } from \"../resource/uuid-id.js\";\nimport type { ComputerIsolationClass } from \"../resource/computer-execution-settings.js\";\nimport { waitForDeletion } from \"../wait.js\";\nimport type { WaitOptions } from \"../wait.js\";\nimport type {\n CreateComputerSessionRequest,\n ComputerSession,\n} from \"../api/computer-session.js\";\nimport type {\n ListJournalResponse,\n JournalEntry,\n JournalListOptions,\n} from \"../api/journal.js\";\nimport {\n getJournalEntry,\n journalById,\n journalByName,\n listJournal,\n} from \"./computer-journal.js\";\nimport {\n listComputersBySecret,\n listSecretAttachments,\n} from \"./computer-secrets.js\";\nimport {\n cancelSession,\n createSession,\n getSession,\n listSessions,\n renewSession,\n sessionsById,\n sessionsByName,\n} from \"./computer-sessions.js\";\n\n/**\n * The durable Computers of one Namespace, in the place IDYL assigned the\n * Account. A Computer lives in the place it was created in, and that\n * place's API serves it: every operation is sent to the API the client's\n * placement resolves to, and a response in which a Computer names any other\n * place is refused with an `Error`. A Computer is addressed by place,\n * Namespace, and name together.\n *\n * Requests and responses are the `api` envelopes verbatim, the served\n * Computer read through `decodeComputer`. A service that addresses no\n * Namespace serves only {@link ComputersService.listAllNamespaces}; its\n * Namespace-scoped operations throw a `TypeError` saying a Namespace is\n * required.\n *\n * A Computer's sessions are resources: a create records a session's grant\n * and answers at once, `ready` when the Computer was awake and otherwise\n * `pending` while it wakes, carrying the endpoint its grant is installed on\n * once the session is bound. The session itself runs on that endpoint, over\n * the client's Computer connection. No request is held open while the\n * Computer wakes. Every session operation addresses the Computer either by\n * name or, in its `ById` form, by the Computer's stable identity. A name is\n * free to reuse once its previous holder has been finalized, so a caller\n * holding an ID keeps reaching the Computer it names, and the session it\n * created there, through the `ById` forms. Sessions are read through\n * `decodeComputerSession`.\n */\nexport interface ComputersService\n extends StorageMethods, ComputerOperationMethods {\n /**\n * Records a Computer in the Namespace, in the client's resolved place.\n * The place is stamped onto the request; a request naming a different\n * one is refused with a `TypeError` before anything is sent. The\n * response carries the server-assigned ID. A name already held by a live\n * Computer of the Namespace there is refused with HTTP 409, and a\n * terminating Namespace refuses the creation with HTTP 409 and\n * `ERROR_CODE_NAMESPACE_TERMINATING`, which `isApiCode` classifies.\n * An `idempotencyKey`, when supplied, identifies equal creation retries;\n * the server retains their recorded outcome.\n *\n * The request is judged with\n * `validateCreateComputerRequest` before anything is sent, and a spec\n * that states no field is not written. Throws a `TypeError` when the name\n * is blank or the request is invalid.\n */\n create(\n request: CreateComputerRequest,\n options?: RequestOptions,\n ): Promise<CreateComputerResponse>;\n /** Reads a Computer by name. Throws a `TypeError` when `name` is blank. */\n get(name: string, options?: RequestOptions): Promise<GetComputerResponse>;\n /**\n * Reads a Computer by its stable identity. A name is free to reuse once\n * its previous holder has been finalized, so a caller holding an ID reads\n * the Computer it names here. Throws a `TypeError` when `id` is not a\n * canonical UUID.\n */\n getById(id: string, options?: RequestOptions): Promise<GetComputerResponse>;\n /**\n * Changes the Computer addressed by name field by field, as\n * {@link UpdateComputerRequest} describes, with a PATCH of the Computer,\n * and returns the Computer as the update left it. The request is judged\n * with `validateUpdateComputerRequest` before it is sent, so an update\n * that states no field, or an invalid one, throws a `TypeError` and sends\n * nothing. Throws a `TypeError` when `name` is blank.\n */\n update(\n name: string,\n request: UpdateComputerRequest,\n options?: RequestOptions,\n ): Promise<UpdateComputerResponse>;\n /**\n * Changes the Computer addressed by its stable identity, exactly as\n * {@link ComputersService.update} does by name. A name is free to reuse\n * once its previous holder has been finalized, so a caller holding an ID\n * never updates a later Computer that took the name. Throws a `TypeError`\n * when `id` is not a canonical UUID or the request is invalid.\n */\n updateById(\n id: string,\n request: UpdateComputerRequest,\n options?: RequestOptions,\n ): Promise<UpdateComputerResponse>;\n /**\n * Starts releasing a Computer addressed by name. The platform records it\n * as terminating and answers 202 with `accepted` set and `deletedAt`\n * stamped, then releases what the Computer holds and finalizes on its\n * own. Nothing else in the Namespace is touched. Deleting a Computer that\n * is already terminating is accepted again with the same `deletedAt`.\n * Once finalized, the Computer resolves 404 and its name may be reused.\n *\n * A caller that needs the Computer gone follows with\n * {@link ComputersService.waitUntilDeleted}. Throws a `TypeError` when\n * `name` is blank.\n */\n delete(name: string, options?: RequestOptions): Promise<DeleteResponse>;\n /**\n * Starts releasing a Computer addressed by its stable identity, with the\n * answer {@link ComputersService.delete} describes. Throws a `TypeError`\n * when `id` is not a canonical UUID.\n */\n deleteById(id: string, options?: RequestOptions): Promise<DeleteResponse>;\n /**\n * One page of the Computers in the Namespace, in the client's resolved\n * place. Filter selects ownership: empty or `unowned`, or `all`.\n */\n list(\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListComputersResponse>;\n /**\n * One page of Computers across every Namespace the caller is authorized\n * to list in the Account, in the resolved Subnet. The service's Namespace\n * does not narrow the result: each Computer carries its own Namespace,\n * `totalCount` counts the account-wide authorized result, and the\n * platform orders by Namespace name and then Computer name so paging is\n * stable and equal names in different Namespaces stay distinct.\n */\n listAllNamespaces(\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListComputersResponse>;\n /**\n * Reads the Computer back by name until it resolves 404, judging each\n * read with `evaluateComputerWait`. It resolves once the Computer is\n * gone; an exhausted timeout rejects with a `TimeoutError` `DOMException`,\n * cancellation with the signal's reason, and any other read failure with\n * its error. Nothing is deleted. Throws a `TypeError` when `name` is\n * blank.\n */\n waitUntilDeleted(name: string, options?: WaitOptions): Promise<void>;\n /**\n * The IDYL image catalog of the resolved Subnet: the images a Computer\n * there may name as `ComputerExecutionSettingsImage.idyl`, each with its current\n * patch level, and the default a create that states no image receives.\n * The catalog is served whole, on one page, read leniently and judged\n * entry by entry with `validateComputerImage` only when a caller asks.\n * The service's Namespace does not narrow it, so a service that addresses\n * no Namespace serves it too.\n */\n listImages(request?: RequestOptions): Promise<ListComputerImagesResponse>;\n /**\n * The IDYL images of the resolved Subnet's catalog that a Computer in\n * `isolation` may name, each stating the class. The list is empty when\n * the Subnet does not admit the class, so a caller offers the class\n * exactly when it is not. `isolation` is `secure-container` or `vm`; any\n * other value throws a `TypeError` before a request is made. Read and\n * scoped as {@link listImages} is.\n */\n listImagesFor(\n isolation: ComputerIsolationClass,\n request?: RequestOptions,\n ): Promise<ListComputerImagesResponse>;\n /**\n * Creates a session in the Computer addressed by name and returns it as\n * the platform answered: ready, or pending while the Computer wakes,\n * carrying its endpoint once it is bound. It neither waits nor opens the\n * session's stream. The request is judged with\n * `validateCreateComputerSessionRequest` before it is sent.\n *\n * A create the platform refuses at once, such as one whose Namespace has\n * no execution in the Subnet or one over a session limit, rejects with an\n * `ApiError` carrying its code, which `isApiCode` classifies against the\n * `ERROR_CODE_*` constants. A request may be retried after a lost\n * response under the same `idempotencyKey`, within the window\n * `CreateComputerSessionRequest` documents, and returns the same session.\n * Throws a `TypeError` when `name` is blank or the request is invalid.\n */\n createSession(\n name: string,\n request: CreateComputerSessionRequest,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Creates a session in the Computer addressed by its stable identity, as\n * {@link ComputersService.createSession} does. The session is read,\n * renewed, and cancelled by the same identity with the other `ById`\n * forms. Throws a `TypeError` when `id` is not a canonical UUID.\n */\n createSessionById(\n id: string,\n request: CreateComputerSessionRequest,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Reads a session of the Computer addressed by name, as it now is. Only\n * the identity that created a session may read it. A session that ended\n * is readable until the window of its idempotency key closes; after that,\n * and for an ID the Computer never issued, the read rejects with HTTP\n * 404, which `isNotFound` classifies. Throws a `TypeError` when `name` is\n * blank or `sessionId` is not a canonical UUID.\n */\n getSession(\n name: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Reads a session of the Computer addressed by its stable identity, as\n * {@link ComputersService.getSession} does.\n */\n getSessionById(\n computerId: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Lists every open session of the Computer addressed by name, oldest\n * first, as anyone who may read the Computer sees them: kind, client, who\n * and when, never content. {@link ComputersService.getSession} reads a\n * session in full, and only for its creator. A Computer that is asleep\n * lists none. Throws a `TypeError` when `name` is blank.\n */\n listSessions(\n name: string,\n options?: RequestOptions,\n ): Promise<ListComputerSessionsResponse>;\n /**\n * Lists every open session of the Computer addressed by its stable\n * identity, as {@link ComputersService.listSessions} does.\n */\n listSessionsById(\n id: string,\n options?: RequestOptions,\n ): Promise<ListComputerSessionsResponse>;\n /**\n * The state of each Secret attachment of the Computer addressed by name:\n * one item per attachment in its execution settings in force, in their\n * order, saying whether the attached Secret's value can be sent and, when\n * it cannot, why. Anyone who may read the Computer may also read this state.\n * Throws a `TypeError` when `name` is blank.\n */\n listSecrets(\n name: string,\n options?: RequestOptions,\n ): Promise<ListComputerSecretAttachmentsResponse>;\n /**\n * The state of each Secret attachment of the Computer addressed by its\n * stable identity, as {@link ComputersService.listSecrets} reads it.\n */\n listSecretsById(\n id: string,\n options?: RequestOptions,\n ): Promise<ListComputerSecretAttachmentsResponse>;\n /**\n * Every attachment of the Secret with ID `secretId` in the execution\n * settings of the Namespace's Computers that the caller may read,\n * sleeping Computers included: for each, the Computer, the variable,\n * whether it is attached there, and the version it is pinned to, if any.\n * A Computer the caller may not read is left out. Throws a `TypeError`\n * before any request when `secretId` is not a canonical UUID.\n */\n listBySecret(\n secretId: string,\n options?: RequestOptions,\n ): Promise<ListComputersBySecretResponse>;\n /**\n * Cancels a session of the Computer addressed by name: one whose stream\n * no endpoint has started. Once a stream may have started, the session\n * is left to end by its deadlines, or ended through its stream.\n * Cancelling a session that is already final changes nothing. A session\n * its creator cancels states no reason. Throws a `TypeError` when `name`\n * is blank or `sessionId` is not a canonical UUID.\n */\n cancelSession(\n name: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * Cancels a session of the Computer addressed by its stable identity, as\n * {@link ComputersService.cancelSession} does and under the same rule.\n */\n cancelSessionById(\n computerId: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<void>;\n /**\n * Renews the lease of a session of the Computer addressed by name, with a\n * POST that has no body, and returns the session as the renewal left it,\n * its `status.expiresAt` the new lease deadline. A session is kept by\n * renewing it every `COMPUTER_SESSION_RENEW_INTERVAL_MS`, as\n * `ComputerSession` describes.\n *\n * The platform checks the caller's permission on the Computer again,\n * exactly as a create does. A refused renewal ends the session at once\n * with reason `Revoked` and rejects with an `ApiError`. Renewing a session\n * that is already final changes nothing and rejects with an `ApiError`\n * carrying HTTP 409 and `ERROR_CODE_SESSION_FINAL`. Throws a `TypeError`\n * when `name` is blank or `sessionId` is not a canonical UUID.\n */\n renewSession(\n name: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Renews a session of the Computer addressed by its stable identity, as\n * {@link ComputersService.renewSession} does.\n */\n renewSessionById(\n computerId: string,\n sessionId: string,\n options?: RequestOptions,\n ): Promise<ComputerSession>;\n /**\n * Returns one page of the journal of the Computer addressed by name,\n * newest entry first, as `JournalListOptions` describes. Pass the\n * page's `continue` back in the options to read the next page; a page\n * without one is the last. Each listed Cell carries its command bounded\n * by `MAX_COMPUTER_CELL_LISTED_COMMAND_BYTES`;\n * {@link ComputersService.getJournalEntry} returns the whole command.\n * The journal is one list that only grows forward, and each entry names\n * its `creator` unless IDYL made it on its own. A private session records\n * no entry. Anyone who may read the\n * Computer may read its whole journal, including entries other identities\n * caused.\n *\n * Options the route does not serve are refused with a `TypeError` before\n * any request is sent. A continue position the platform cannot use\n * rejects with `ERROR_CODE_INVALID_CONTINUE`, and the listing starts again\n * without it. Throws a `TypeError` when `name` is blank.\n */\n listJournal(\n name: string,\n options?: JournalListOptions,\n request?: RequestOptions,\n ): Promise<ListJournalResponse>;\n /**\n * Returns one page of the journal of the Computer addressed by its\n * stable identity, as {@link ComputersService.listJournal} does.\n */\n listJournalById(\n id: string,\n options?: JournalListOptions,\n request?: RequestOptions,\n ): Promise<ListJournalResponse>;\n /**\n * Reads one entry of the journal of the Computer addressed by name. A\n * Cell entry carries its whole command. An entry the Computer's journal\n * does not hold rejects with HTTP 404, which `isNotFound` classifies.\n * Throws a `TypeError` when `name` is blank or `entryId` is not a\n * canonical UUID.\n */\n getJournalEntry(\n name: string,\n entryId: string,\n request?: RequestOptions,\n ): Promise<JournalEntry>;\n /**\n * Reads one entry of the journal of the Computer addressed by its stable\n * identity, as {@link ComputersService.getJournalEntry} does.\n */\n getJournalEntryById(\n computerId: string,\n entryId: string,\n request?: RequestOptions,\n ): Promise<JournalEntry>;\n}\n\n/**\n * Builds the Computer service for `namespaceName` within `accountId`, on\n * the placement `context` holds. With `namespaceName` undefined the service\n * addresses no Namespace.\n */\nexport function computersService(\n context: PlacementContext,\n accountId: AccountId,\n namespaceName: string | undefined,\n): ComputersService {\n const addressed: PlacementContext = {\n state: context.state,\n scope: {\n accountId,\n ...(namespaceName === undefined ? {} : { namespace: namespaceName }),\n },\n placement: context.placement,\n };\n const collection = new ZoneCollection(addressed, {\n plural: \"computers\",\n key: \"computer\",\n label: \"computer\",\n decode: decodeComputer,\n subnetOf: (computer) => computer.subnet,\n });\n /** Reads the resolved Subnet's image catalog with the query given. */\n const listImages = async (\n query: string,\n request: RequestOptions,\n ): Promise<ListComputerImagesResponse> => {\n const resolved = await resolvePlacement(addressed, {\n requireNamespace: false,\n ...signalOption(request.signal),\n });\n const response = await addressed.state.transport.json<unknown>(\n \"GET\",\n resolved.endpoint,\n accountSubnet(accountId, resolved.subnet, \"computer-images\") + query,\n signalOption(request.signal),\n );\n listEnvelope(response, \"computer images\");\n return decodeListComputerImagesResponse(response);\n };\n const service: ComputersService = {\n ...storageMethods(context, \"computers\"),\n ...computerOperationMethods(context),\n async create(request, options = {}) {\n createComputerRequestShape.unknownFields(request, \"\");\n requireNonBlank(request.name, \"computer name\");\n requireScope(namespaceName);\n return await collection.submit((resolved) => {\n if (\n request.subnet !== undefined &&\n request.subnet !== \"\" &&\n request.subnet !== resolved.subnet\n ) {\n throw new TypeError(\n \"computer subnet does not match resolved placement subnet\",\n );\n }\n const body: CreateComputerRequest = {\n name: request.name,\n subnet: resolved.subnet,\n ...(request.spec === undefined ? {} : { spec: request.spec }),\n ...(request.client === undefined ? {} : { client: request.client }),\n ...(request.forkOf === undefined ? {} : { forkOf: request.forkOf }),\n ...(request.workspaceOnly === undefined\n ? {}\n : { workspaceOnly: request.workspaceOnly }),\n ...(request.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: request.idempotencyKey }),\n };\n validateCreateComputerRequest(body);\n return createComputerRequestShape.encode(body);\n }, options.signal);\n },\n async get(name, options = {}) {\n requireNonBlank(name, \"computer name\");\n requireScope(namespaceName);\n return await collection.get(name, options.signal);\n },\n async getById(id, options = {}) {\n const computerId = parseComputerId(id);\n requireScope(namespaceName);\n return await collection.read(\n (resolved) => computerById(resolved.scope, computerId),\n options.signal,\n );\n },\n async update(name, request, options = {}) {\n requireNonBlank(name, \"computer name\");\n validateUpdateComputerRequest(request);\n requireScope(namespaceName);\n return await collection.patch(\n name,\n encodeUpdateComputerRequest(request),\n options.signal,\n );\n },\n async updateById(id, request, options = {}) {\n const computerId = parseComputerId(id);\n validateUpdateComputerRequest(request);\n requireScope(namespaceName);\n return await collection.change(\n (resolved) => computerById(resolved.scope, computerId),\n encodeUpdateComputerRequest(request),\n options.signal,\n );\n },\n async delete(name, options = {}) {\n requireNonBlank(name, \"computer name\");\n requireScope(namespaceName);\n return await collection.delete(name, options.signal);\n },\n async deleteById(id, options = {}) {\n const computerId = parseComputerId(id);\n requireScope(namespaceName);\n return await collection.remove(\n (resolved) => computerById(resolved.scope, computerId),\n options.signal,\n );\n },\n async list(options = {}, request = {}) {\n validateComputerOwnerFilter(options.filter ?? \"\");\n requireScope(namespaceName);\n return await collection.list(options, request.signal);\n },\n async listAllNamespaces(options = {}, request = {}) {\n validateComputerOwnerFilter(options.filter ?? \"\");\n return await collection.listAllNamespaces(options, request.signal);\n },\n async listImages(request = {}) {\n return await listImages(\"\", request);\n },\n async listImagesFor(isolation, request = {}) {\n return await listImages(imageCatalogQuery(isolation), request);\n },\n async waitUntilDeleted(name, options = {}) {\n requireNonBlank(name, \"computer name\");\n requireScope(namespaceName);\n await waitForDeletion<Computer>(options, {\n kind: \"Computer\",\n name,\n read: async (signal) => (await service.get(name, { signal })).computer,\n evaluate: (computer) => evaluateComputerWait(computer, \"deleted\"),\n });\n },\n async createSession(name, request, options = {}) {\n const sessions = sessionsByName(name);\n requireScope(namespaceName);\n return await createSession(addressed, sessions, request, options.signal);\n },\n async createSessionById(id, request, options = {}) {\n const sessions = sessionsById(id);\n requireScope(namespaceName);\n return await createSession(addressed, sessions, request, options.signal);\n },\n async getSession(name, sessionId, options = {}) {\n const sessions = sessionsByName(name);\n requireScope(namespaceName);\n return await getSession(addressed, sessions, sessionId, options.signal);\n },\n async getSessionById(computerId, sessionId, options = {}) {\n const sessions = sessionsById(computerId);\n requireScope(namespaceName);\n return await getSession(addressed, sessions, sessionId, options.signal);\n },\n async listSessions(name, options = {}) {\n const sessions = sessionsByName(name);\n requireScope(namespaceName);\n return await listSessions(addressed, sessions, options.signal);\n },\n async listSessionsById(id, options = {}) {\n const sessions = sessionsById(id);\n requireScope(namespaceName);\n return await listSessions(addressed, sessions, options.signal);\n },\n async listSecrets(name, options = {}) {\n requireNonBlank(name, \"computer name\");\n requireScope(namespaceName);\n return await listSecretAttachments(\n addressed,\n (scope) => computerSecrets(scope, name),\n options.signal,\n );\n },\n async listSecretsById(id, options = {}) {\n const computerId = parseComputerId(id);\n requireScope(namespaceName);\n return await listSecretAttachments(\n addressed,\n (scope) => computerSecretsById(scope, computerId),\n options.signal,\n );\n },\n async listBySecret(secretId, options = {}) {\n requireScope(namespaceName);\n return await listComputersBySecret(addressed, secretId, options.signal);\n },\n async cancelSession(name, sessionId, options = {}) {\n const sessions = sessionsByName(name);\n requireScope(namespaceName);\n await cancelSession(addressed, sessions, sessionId, options.signal);\n },\n async cancelSessionById(computerId, sessionId, options = {}) {\n const sessions = sessionsById(computerId);\n requireScope(namespaceName);\n await cancelSession(addressed, sessions, sessionId, options.signal);\n },\n async renewSession(name, sessionId, options = {}) {\n const sessions = sessionsByName(name);\n requireScope(namespaceName);\n return await renewSession(addressed, sessions, sessionId, options.signal);\n },\n async renewSessionById(computerId, sessionId, options = {}) {\n const sessions = sessionsById(computerId);\n requireScope(namespaceName);\n return await renewSession(addressed, sessions, sessionId, options.signal);\n },\n async listJournal(name, options = {}, request = {}) {\n const journal = journalByName(name);\n requireScope(namespaceName);\n return await listJournal(addressed, journal, options, request.signal);\n },\n async listJournalById(id, options = {}, request = {}) {\n const journal = journalById(id);\n requireScope(namespaceName);\n return await listJournal(addressed, journal, options, request.signal);\n },\n async getJournalEntry(name, entryId, request = {}) {\n const journal = journalByName(name);\n requireScope(namespaceName);\n return await getJournalEntry(addressed, journal, entryId, request.signal);\n },\n async getJournalEntryById(computerId, entryId, request = {}) {\n const journal = journalById(computerId);\n requireScope(namespaceName);\n return await getJournalEntry(addressed, journal, entryId, request.signal);\n },\n };\n return Object.freeze(service);\n}\n\nfunction requireScope(namespaceName: string | undefined): string {\n if (namespaceName === undefined || namespaceName.trim() === \"\") {\n throw new TypeError(\"namespace is required\");\n }\n return namespaceName;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The Vault management routes' bounds and error vocabulary. A management\n * request carries secret material, so its body is bounded before it is\n * sent and an error it receives relays the platform's message only under a\n * code this vocabulary names.\n */\nimport {\n always,\n array,\n boolean,\n decodeValue,\n integer,\n isUint64,\n numberOrBigInt,\n object,\n omitEmpty,\n omitZero,\n string,\n type Shape,\n} from \"../internal/strictdecode.js\";\nimport { parseJson, type Integer } from \"../resource/json.js\";\nimport {\n secretSpecShape,\n type RedactedSecret,\n type SecretSpec,\n} from \"../resource/secret.js\";\nimport { timestampShape } from \"../resource/shapes.js\";\nimport {\n isComputerId,\n isResourceId,\n isUuidId,\n type ComputerId,\n type ResourceId,\n} from \"../resource/uuid-id.js\";\nimport { errorMessage } from \"../resource/validation.js\";\nimport type { ListResponse } from \"./types.js\";\n\n/**\n * The most bytes the encoded JSON body of one Vault management request may\n * take. It bounds the encoded body, not the value it carries.\n */\nexport const MAX_VAULT_MANAGEMENT_REQUEST_BODY_BYTES = 2 * 1024 * 1024;\n\n/**\n * The stable codes a Vault refusal carries. Each is safe to show: none\n * discloses whether an unrelated resource exists.\n */\nexport const VAULT_ERROR_CODES: readonly string[] = Object.freeze([\n \"VAULT_POLICY_DISABLED\",\n \"VAULT_RESOURCE_NOT_FOUND\",\n \"VAULT_VERSION_NOT_FOUND\",\n \"VAULT_KEY_NOT_FOUND\",\n \"VAULT_KIND_MISMATCH\",\n \"VAULT_RESOURCE_VERSION_CONFLICT\",\n \"VAULT_RESOURCE_DELETED\",\n \"VAULT_ACTIVE_BINDINGS\",\n \"VAULT_RUNTIME_CAPABILITY_MISSING\",\n \"VAULT_NODE_NOT_AUTHORIZED\",\n \"VAULT_ASSIGNMENT_STALE\",\n \"VAULT_PROJECTION_NOT_AUTHORIZED\",\n \"VAULT_PROJECTION_INVALID\",\n \"VAULT_AUTHORITY_UNAVAILABLE\",\n \"VAULT_STORAGE_UNAVAILABLE\",\n \"VAULT_ENCRYPTION_UNAVAILABLE\",\n \"VAULT_DECRYPTION_UNAVAILABLE\",\n \"VAULT_CERTIFICATE_INVALID\",\n \"VAULT_PAYLOAD_LIMIT_EXCEEDED\",\n \"VAULT_RESOURCE_LIMIT_EXCEEDED\",\n \"VAULT_DELIVERY_FAILED\",\n]);\n\nconst vaultErrorCodes: ReadonlySet<string> = new Set(VAULT_ERROR_CODES);\n\n/** Whether `code` is one of {@link VAULT_ERROR_CODES}. */\nexport function isVaultErrorCode(code: string): boolean {\n return vaultErrorCodes.has(code);\n}\n\n/**\n * The request header naming a caller-chosen key that makes a rotation safe\n * to retry: repeating the same key cannot append a second version.\n */\nexport const VAULT_HEADER_IDEMPOTENCY_KEY = \"Idempotency-Key\";\n\n/**\n * The request header carrying the strong resource-version ETag a rotation\n * is conditioned on: a stale value fails the rotation with\n * `VAULT_RESOURCE_VERSION_CONFLICT` instead of losing a concurrent change.\n */\nexport const VAULT_HEADER_IF_MATCH = \"If-Match\";\n\n/**\n * The page of redacted Secrets a list returns. `totalCount` counts every\n * Secret of the Namespace in the addressed Subnet. No item carries a value.\n */\nexport type ListVaultSecretsResponse = ListResponse<RedactedSecret>;\n\n/**\n * Appends one version to a Secret. Concurrency and idempotency travel only\n * in the `If-Match` and `Idempotency-Key` headers, never in the body.\n */\nexport interface RotateVaultSecretRequest {\n /** The new version's content, judged as a write. Always written. */\n readonly spec: SecretSpec;\n}\n\n/**\n * Permanently removes every version of a Vault resource. `confirm` must be\n * {@link VAULT_PURGE_CONFIRMATION}; any other value is refused with\n * `VAULT_PROJECTION_INVALID`. `force` purges a resource that live bindings\n * still hold; without it such a purge is refused with\n * `VAULT_ACTIVE_BINDINGS`.\n */\nexport interface PurgeVaultResourceRequest {\n /** Always written. */\n readonly confirm: string;\n /** `undefined` reads as `false`. */\n readonly force?: boolean;\n}\n\n/**\n * The word a purge states as its explicit confirmation. A purge cannot be\n * undone: no later write restores the resource or its ID.\n */\nexport const VAULT_PURGE_CONFIRMATION = \"purge\";\n\n/** Whether a purge was accepted and, once it has completed, when. */\nexport interface PurgeVaultResourceResponse {\n /** Always written. */\n readonly accepted: boolean;\n /** When the purge completed, an RFC 3339 time; `undefined` until it has. */\n readonly purgedAt?: string;\n}\n\n/** One stored version of a Vault resource, as metadata only. */\nexport interface VaultVersionMetadata {\n /** The version number, from 1. Always written. */\n readonly version: Integer;\n /** When the version was written, an RFC 3339 time. */\n readonly createdAt?: string;\n /** Whether it is the resource's current version. Always written. */\n readonly current: boolean;\n}\n\n/** The page of a Vault resource's versions a version list returns. */\nexport type ListVaultVersionsResponse = ListResponse<VaultVersionMetadata>;\n\n/**\n * The two headers every rotation carries; both are required. They travel\n * only as headers, never in a request body.\n */\nexport interface VaultRotateOptions {\n /**\n * A caller-chosen key, unique to one intended rotation, sent as\n * {@link VAULT_HEADER_IDEMPOTENCY_KEY}. Retrying with the same key cannot\n * append a second version.\n */\n readonly idempotencyKey: string;\n /**\n * The strong ETag of the resource version the rotation expects, such as\n * `\"4\"`, sent as {@link VAULT_HEADER_IF_MATCH};\n * {@link formatVaultResourceVersionETag} builds it.\n */\n readonly ifMatch: string;\n}\n\n/**\n * Judges a rotation's headers: a key with no surrounding whitespace and no\n * line break, and an `If-Match` that\n * {@link parseVaultResourceVersionETag} admits. Throws a `TypeError`.\n */\nexport function validateVaultRotateOptions(options: VaultRotateOptions): void {\n const { idempotencyKey, ifMatch } = options;\n if (idempotencyKey.trim() === \"\") {\n throw new TypeError(`${VAULT_HEADER_IDEMPOTENCY_KEY} header is required`);\n }\n if (idempotencyKey.trim() !== idempotencyKey) {\n throw new TypeError(\n `${VAULT_HEADER_IDEMPOTENCY_KEY} header must not contain surrounding whitespace`,\n );\n }\n if (ifMatch.trim() === \"\") {\n throw new TypeError(`${VAULT_HEADER_IF_MATCH} header is required`);\n }\n if (/[\\r\\n]/u.test(idempotencyKey)) {\n throw new TypeError(\n `${VAULT_HEADER_IDEMPOTENCY_KEY} header contains invalid characters`,\n );\n }\n if (/[\\r\\n]/u.test(ifMatch)) {\n throw new TypeError(\n `${VAULT_HEADER_IF_MATCH} header contains invalid characters`,\n );\n }\n try {\n parseVaultResourceVersionETag(ifMatch);\n } catch (cause) {\n throw new TypeError(\n `${VAULT_HEADER_IF_MATCH} header: ${errorMessage(cause)}`,\n { cause },\n );\n }\n}\n\n/**\n * The canonical strong ETag of a resource version, such as `\"4\"`, which a\n * rotation's `If-Match` states. Throws a `TypeError` when the version is\n * not a positive integer.\n */\nexport function formatVaultResourceVersionETag(\n resourceVersion: Integer,\n): string {\n const version = isUint64(resourceVersion) ? BigInt(resourceVersion) : 0n;\n if (version === 0n) {\n throw new TypeError(\"resource version must be greater than zero\");\n }\n return `\"${version.toString()}\"`;\n}\n\n/**\n * Reads a strong ETag in its one canonical form, a quoted positive decimal\n * with no leading zero, as the resource version it states. A weak, wildcard,\n * unquoted, zero or otherwise non-canonical value is refused with a\n * `TypeError`.\n */\nexport function parseVaultResourceVersionETag(value: string): Integer {\n if (value.length < 3 || !value.startsWith('\"') || !value.endsWith('\"')) {\n throw new TypeError(\"must be a strong quoted decimal ETag\");\n }\n const decimal = value.slice(1, -1);\n if (!/^[1-9][0-9]*$/u.test(decimal) || BigInt(decimal) >= 1n << 64n) {\n throw new TypeError(\n \"must contain a canonical positive decimal resource version\",\n );\n }\n return numberOrBigInt(BigInt(decimal));\n}\n\nconst vaultVersionMetadataShape: Shape<VaultVersionMetadata> =\n object<VaultVersionMetadata>({\n version: always(integer({ unsigned: true, bits: 64 })),\n createdAt: omitZero(timestampShape),\n current: always(boolean()),\n });\n\n/**\n * Reads one version's metadata leniently: a field newer than this package\n * is carried rather than refused.\n */\nexport function decodeVaultVersionMetadata(\n document: unknown,\n): VaultVersionMetadata {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, vaultVersionMetadataShape, \"lenient\");\n}\n\nconst purgeVaultResourceRequestShape: Shape<PurgeVaultResourceRequest> =\n object<PurgeVaultResourceRequest>({\n confirm: always(string()),\n force: omitEmpty(boolean()),\n });\n\n/** Renders a purge request as the document the route reads. */\nexport function encodePurgeVaultResourceRequest(\n request: PurgeVaultResourceRequest,\n): unknown {\n return purgeVaultResourceRequestShape.encode(request);\n}\n\nconst rotateVaultSecretRequestShape: Shape<RotateVaultSecretRequest> =\n object<RotateVaultSecretRequest>({\n spec: always(secretSpecShape),\n });\n\n/** Renders a rotation request as the document the route reads. */\nexport function encodeRotateVaultSecretRequest(\n request: RotateVaultSecretRequest,\n): unknown {\n return rotateVaultSecretRequestShape.encode(request);\n}\n\n/**\n * Whether a decryption opened its value: `opened`; `refused`, the key\n * service refused, for example because the session was not entitled to the\n * value; or `failed`, Vault's request received no answer from the key\n * service, so whether the value was opened is not known to Vault, and the key\n * service's report of the same request replaces it. Open, as the platform\n * may name more; {@link validateVaultDecryption} judges membership.\n */\nexport type VaultDecryptionOutcome =\n \"opened\" | \"refused\" | \"failed\" | (string & Record<never, never>);\n\n/**\n * Who reported a decryption: `vault`, Vault reported it and the key\n * service's report has not arrived; `kms`, only the key service reported\n * it, so Vault's code did not; or `both`. Open, as the platform may name\n * more; {@link validateVaultDecryption} judges membership.\n */\nexport type VaultDecryptionReportedBy =\n \"vault\" | \"kms\" | \"both\" | (string & Record<never, never>);\n\n/** The most bytes {@link VaultDecryption.activation} holds. */\nexport const MAX_VAULT_DECRYPTION_ACTIVATION_BYTES = 64;\n\n/** The most bytes {@link VaultDecryption.kmsRequestId} holds. */\nexport const MAX_VAULT_DECRYPTION_KMS_REQUEST_ID_BYTES = 128;\n\n/**\n * One decryption of a stored Secret or TLSCertificate value: the record IDYL\n * keeps for the Account of every time the key that seals Vault values was\n * asked to open one. It never carries the value.\n *\n * Vault reports a decryption when it opens a value for a Computer or Pod\n * that is starting, and the key service's own log reports every decryption;\n * the two reports of one decryption share `kmsRequestId` and are one record.\n * A record only the key service reported names the value, the version and\n * the activation the key service saw, and no Computer, Pod or machine. Records\n * are kept for 90 days and removed with the Account.\n */\nexport interface VaultDecryption {\n /** When the decryption was made, an RFC 3339 time. Always written. */\n readonly at: string;\n /** `Secret` or `TLSCertificate`: the kind whose value was opened. Always written. */\n readonly kind: string;\n /** The opened resource's ID. Always written. */\n readonly resourceId: ResourceId;\n /**\n * The resource's name within its Namespace and Subnet when the value was\n * opened. A resource deleted and created again under the name has another\n * `resourceId`. Always written.\n */\n readonly name: string;\n /** The stored version whose value was opened, from 1. Always written. */\n readonly version: Integer;\n /** The canonical slug of the Subnet the resource resides in. Always written. */\n readonly subnet: string;\n /**\n * The Computer the value was opened for; `undefined` for a Pod's\n * decryption and for a record only the key service reported.\n */\n readonly computerId?: ComputerId;\n /**\n * The Pod instance the value was opened for; `undefined` for a Computer's\n * decryption and for a record only the key service reported.\n */\n readonly podId?: string;\n /**\n * The start the value was opened for: a Computer's activation or a Pod's\n * assignment; `undefined` when it was opened under no start's session.\n */\n readonly activation?: string;\n /**\n * The ID of the machine the value was released to; `undefined` for a\n * record only the key service reported.\n */\n readonly nodeId?: string;\n /** Whether the value was opened. Always written. */\n readonly outcome: VaultDecryptionOutcome;\n /** Who reported the decryption. Always written. */\n readonly reportedBy: VaultDecryptionReportedBy;\n /**\n * The key service's ID of the request; `undefined` only when Vault's\n * request received no answer that named one.\n */\n readonly kmsRequestId?: string;\n}\n\n/**\n * One page of decryption records, newest first. `totalCount` counts every\n * record of the listing, so a page that holds fewer is followed by another.\n */\nexport type ListVaultDecryptionsResponse = ListResponse<VaultDecryption>;\n\nconst vaultDecryptionShape: Shape<VaultDecryption> = object<VaultDecryption>({\n at: always(timestampShape),\n kind: always(string()),\n resourceId: always(string<ResourceId>()),\n name: always(string()),\n version: always(integer({ unsigned: true, bits: 64 })),\n subnet: always(string()),\n computerId: omitEmpty(string<ComputerId>()),\n podId: omitEmpty(string()),\n activation: omitEmpty(string()),\n nodeId: omitEmpty(string()),\n outcome: always(string<VaultDecryptionOutcome>()),\n reportedBy: always(string<VaultDecryptionReportedBy>()),\n kmsRequestId: omitEmpty(string()),\n});\n\nconst listVaultDecryptionsResponseShape: Shape<ListVaultDecryptionsResponse> =\n object<ListVaultDecryptionsResponse>({\n items: always(array(vaultDecryptionShape)),\n totalCount: always(integer({ unsigned: false, bits: 64 })),\n snapshotCursor: omitEmpty(string()),\n continue: omitEmpty(string()),\n });\n\n/**\n * Reads one decryption record leniently: a field, outcome or reporter newer\n * than this SDK is carried rather than refused, and\n * {@link validateVaultDecryption} judges it. `document` is JSON text or a\n * parsed value.\n */\nexport function decodeVaultDecryption(document: unknown): VaultDecryption {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, vaultDecryptionShape, \"lenient\");\n}\n\n/** Renders a decryption record as the document the platform emits. */\nexport function encodeVaultDecryption(record: VaultDecryption): unknown {\n return vaultDecryptionShape.encode(record);\n}\n\n/** Reads a page of decryption records leniently. */\nexport function decodeListVaultDecryptionsResponse(\n document: unknown,\n): ListVaultDecryptionsResponse {\n const value: unknown =\n typeof document === \"string\" ? parseJson(document) : document;\n return decodeValue(value, listVaultDecryptionsResponseShape, \"lenient\");\n}\n\n/** Renders a page of decryption records as the document the platform emits. */\nexport function encodeListVaultDecryptionsResponse(\n page: ListVaultDecryptionsResponse,\n): unknown {\n return listVaultDecryptionsResponseShape.encode(page);\n}\n\n/** A machine ID: the unpadded base64url spelling of a 32-byte Ed25519 key. */\nconst NODE_ID = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u;\n\n/**\n * Judges a decryption record's own shape, as the reference contract does:\n * a time; a kind of `Secret` or `TLSCertificate`; a canonical resource ID; a\n * name; a version from 1; a Subnet; at most one of a Computer and a Pod, each\n * a canonical ID; an activation and a key service request ID within their\n * bounds; a well-formed machine ID; an outcome and a reporter this SDK names;\n * and a key service request ID whenever the key service reported it. It does\n * not judge whether the named resource, Computer, Pod or machine still exists.\n * Throws a `TypeError`.\n */\nexport function validateVaultDecryption(record: VaultDecryption): void {\n if (record.at === \"\") throw new TypeError(\"vault decryption at is required\");\n if (record.kind !== \"Secret\" && record.kind !== \"TLSCertificate\") {\n throw new TypeError(\n record.kind === \"\"\n ? \"vault decryption kind is required\"\n : `unknown vault decryption kind ${JSON.stringify(record.kind)}`,\n );\n }\n if (!isResourceId(record.resourceId)) {\n throw new TypeError(\"vault decryption resourceId must be a canonical UUID\");\n }\n if (record.name === \"\") {\n throw new TypeError(\"vault decryption name is required\");\n }\n if (BigInt(record.version) < 1n) {\n throw new TypeError(\"vault decryption version must be at least 1\");\n }\n if (record.subnet === \"\") {\n throw new TypeError(\"vault decryption subnet is required\");\n }\n const computerId = record.computerId ?? \"\";\n const podId = record.podId ?? \"\";\n if (computerId !== \"\" && podId !== \"\") {\n throw new TypeError(\"vault decryption names a Computer and a Pod\");\n }\n if (computerId !== \"\" && !isComputerId(computerId)) {\n throw new TypeError(\"vault decryption computerId must be a canonical UUID\");\n }\n if (podId !== \"\" && !isUuidId(podId)) {\n throw new TypeError(\"vault decryption podId must be a canonical UUID\");\n }\n if (\n utf8Length(record.activation ?? \"\") > MAX_VAULT_DECRYPTION_ACTIVATION_BYTES\n ) {\n throw new TypeError(\n `vault decryption activation exceeds ${String(MAX_VAULT_DECRYPTION_ACTIVATION_BYTES)} bytes`,\n );\n }\n const nodeId = record.nodeId ?? \"\";\n if (nodeId !== \"\" && !NODE_ID.test(nodeId)) {\n throw new TypeError(\"vault decryption nodeId is malformed\");\n }\n switch (record.outcome) {\n case \"opened\":\n case \"refused\":\n case \"failed\":\n break;\n case \"\":\n throw new TypeError(\"vault decryption outcome is required\");\n default:\n throw new TypeError(\n `unknown vault decryption outcome ${JSON.stringify(record.outcome)}`,\n );\n }\n switch (record.reportedBy) {\n case \"vault\":\n case \"kms\":\n case \"both\":\n break;\n case \"\":\n throw new TypeError(\"vault decryption reportedBy is required\");\n default:\n throw new TypeError(\n `unknown vault decryption reportedBy ${JSON.stringify(record.reportedBy)}`,\n );\n }\n const requestId = record.kmsRequestId ?? \"\";\n if (utf8Length(requestId) > MAX_VAULT_DECRYPTION_KMS_REQUEST_ID_BYTES) {\n throw new TypeError(\n `vault decryption kmsRequestId exceeds ${String(MAX_VAULT_DECRYPTION_KMS_REQUEST_ID_BYTES)} bytes`,\n );\n }\n if (requestId === \"\" && record.reportedBy !== \"vault\") {\n throw new TypeError(\n \"vault decryption kmsRequestId is required when the key service reported it\",\n );\n }\n}\n\n/**\n * Judges every record with {@link validateVaultDecryption}. Throws a\n * `TypeError` naming the item.\n */\nexport function validateListVaultDecryptionsResponse(\n page: ListVaultDecryptionsResponse,\n): void {\n page.items.forEach((record, index) => {\n try {\n validateVaultDecryption(record);\n } catch (cause) {\n throw new TypeError(`items[${String(index)}]: ${errorMessage(cause)}`, {\n cause,\n });\n }\n });\n}\n\nfunction utf8Length(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The Vault Secrets of one Namespace, on the API that serves the client's\n * Computers. A Secret lives in one Namespace and one Subnet; the Subnet is\n * the one the client's placement resolves, which is the Subnet its\n * Computers live in, so a Secret written here can be attached to them.\n *\n * Every route carries secret material, so a request body is bounded before\n * it is sent and a refusal relays the platform's message only under a\n * Vault code. Every response is redacted: no read returns a value.\n */\nimport { TransportError } from \"../errors.js\";\nimport {\n decodeVaultDecryption,\n decodeVaultVersionMetadata,\n encodePurgeVaultResourceRequest,\n encodeRotateVaultSecretRequest,\n isVaultErrorCode,\n MAX_VAULT_MANAGEMENT_REQUEST_BODY_BYTES,\n validateVaultRotateOptions,\n VAULT_HEADER_IDEMPOTENCY_KEY,\n VAULT_HEADER_IF_MATCH,\n type ListVaultDecryptionsResponse,\n type ListVaultSecretsResponse,\n type ListVaultVersionsResponse,\n type PurgeVaultResourceRequest,\n type PurgeVaultResourceResponse,\n type RotateVaultSecretRequest,\n type VaultRotateOptions,\n} from \"../api/vault.js\";\nimport type { DeleteResponse, ListOptions } from \"../api/types.js\";\nimport {\n namespace,\n namespaceResource,\n vaultDecryptionsOfComputer,\n} from \"../internal/apipath.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { readList } from \"../internal/envelopes.js\";\nimport { listQuery } from \"../internal/listquery.js\";\nimport { requireNonBlank, signalOption } from \"../internal/options.js\";\nimport {\n resolvePlacement,\n type ResolvedPlacement,\n} from \"../internal/routing.js\";\nimport type { RequestOptions } from \"../request.js\";\nimport {\n decodeRedactedSecret,\n secretShape,\n validateSecret,\n validateSecretSpec,\n validateVaultReferenceName,\n type RedactedSecret,\n type Secret,\n} from \"../resource/secret.js\";\n\n/** The Secrets of the Namespace a client addresses. */\nexport interface VaultSecretsService {\n /**\n * Validates `secret` and creates it under its name, returning its\n * redacted form. The Namespace and Subnet are the addressed ones: a\n * document that states another is a `TypeError`, and one that states\n * none takes them. Writing the same content again returns the Secret it\n * created; writing other content under a name in use is refused with\n * `VAULT_RESOURCE_VERSION_CONFLICT`. Writing to the name of a Secret\n * deleted within seven days restores that Secret, with its ID.\n */\n put(secret: Secret, options?: RequestOptions): Promise<RedactedSecret>;\n /** The redacted form of the named Secret. */\n get(name: string, options?: RequestOptions): Promise<RedactedSecret>;\n /**\n * One page of the Namespace's Secrets in the addressed Subnet, redacted,\n * in the platform's order by name. `limit` and `offset` page it; a\n * Secret of another Namespace or Subnet in the page is refused with a\n * `TransportError`.\n */\n list(\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListVaultSecretsResponse>;\n /**\n * Appends a version to the named Secret and makes it current, returning\n * the redacted Secret. `spec` is judged as a write, and states the same\n * form as the Secret: a source and an egress, or keyed data. `options`\n * carries the two required headers: the `If-Match` of the resource\n * version the rotation expects, which refuses a stale one with\n * `VAULT_RESOURCE_VERSION_CONFLICT`, and an idempotency key that makes a\n * retry return the version it appended rather than append another.\n * Throws a `TypeError` before any request when either is invalid.\n */\n rotate(\n name: string,\n request: RotateVaultSecretRequest,\n options: VaultRotateOptions,\n call?: RequestOptions,\n ): Promise<RedactedSecret>;\n /**\n * Permanently removes every version of the named Secret. It cannot be\n * restored, and an attachment that names its ID reads\n * `secret_not_found` from then on. `request.confirm` states the explicit\n * confirmation; `force` purges a Secret that live bindings still hold.\n */\n purge(\n name: string,\n request: PurgeVaultResourceRequest,\n options?: RequestOptions,\n ): Promise<PurgeVaultResourceResponse>;\n /**\n * One page of the named Secret's versions, as metadata only. `limit` and\n * `offset` page it.\n */\n listVersions(\n name: string,\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListVaultVersionsResponse>;\n /**\n * One page of the record of every decryption of the named Secret's\n * values, newest first. The record names the Secret by name, so it holds\n * decryptions made before the Secret was deleted and created again.\n * `limit` and `offset` page it; a record of another Subnet in the page is\n * refused with a `TransportError`.\n */\n listDecryptions(\n name: string,\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListVaultDecryptionsResponse>;\n /**\n * One page of the record of every Secret value opened for the Computer\n * with this stable ID, newest first, on its own route under the\n * Namespace's vault path: a Computer read, a listing and a wake never\n * carry it. `limit` and `offset` page it; a record of another Subnet in\n * the page is refused with a `TransportError`.\n */\n listComputerDecryptions(\n computerId: string,\n options?: ListOptions,\n request?: RequestOptions,\n ): Promise<ListVaultDecryptionsResponse>;\n /**\n * Deletes the named Secret. It can be restored for seven days by writing\n * to its name, and the Computers attached to it resume when it is.\n */\n delete(name: string, options?: RequestOptions): Promise<DeleteResponse>;\n}\n\nconst COLLECTION = \"vault/secrets\";\n\n/** Builds the Secrets service of the Namespace `context` addresses. */\nexport function vaultSecretsService(\n context: PlacementContext,\n): VaultSecretsService {\n const send = async (\n method: string,\n path: (resolved: ResolvedPlacement) => string,\n request: RequestOptions,\n body?: (resolved: ResolvedPlacement) => unknown,\n headers?: Readonly<Record<string, string>>,\n ): Promise<{ resolved: ResolvedPlacement; response: unknown }> => {\n const resolved = await resolvePlacement(context, {\n ...signalOption(request.signal),\n });\n const encoded = body?.(resolved);\n const response = await context.state.transport.json<unknown>(\n method,\n resolved.endpoint,\n path(resolved),\n {\n ...(encoded === undefined ? {} : { body: encoded }),\n ...(headers === undefined ? {} : { headers }),\n maxRequestBodyBytes: MAX_VAULT_MANAGEMENT_REQUEST_BODY_BYTES,\n safeErrorCode: isVaultErrorCode,\n ...signalOption(request.signal),\n },\n );\n return { resolved, response };\n };\n /** The path of the named Secret, with `suffix` appended. */\n const secretPath =\n (name: string, suffix = \"\") =>\n (resolved: ResolvedPlacement): string =>\n namespaceResource(resolved.scope, COLLECTION, name) + suffix;\n const read = async (\n method: string,\n name: string,\n request: RequestOptions,\n body?: (resolved: ResolvedPlacement) => unknown,\n suffix = \"\",\n headers?: Readonly<Record<string, string>>,\n ): Promise<RedactedSecret> => {\n const { resolved, response } = await send(\n method,\n secretPath(name, suffix),\n request,\n body,\n headers,\n );\n const secret = decodeRedactedSecret(response);\n if (!isAddressed(secret, resolved) || secret.metadata.name !== name) {\n throw new TransportError(\n \"invalid_response\",\n \"secret response names a secret other than the one addressed\",\n );\n }\n return secret;\n };\n /**\n * One page of decryption records at `path`. A record that names a Subnet\n * other than the addressed one, which the routes never serve, is refused.\n */\n const decryptions = async (\n path: (resolved: ResolvedPlacement) => string,\n request: RequestOptions,\n ): Promise<ListVaultDecryptionsResponse> => {\n const { resolved, response } = await send(\"GET\", path, request);\n const page = readList(response, \"decryptions\", decodeVaultDecryption);\n if (!page.items.every((record) => record.subnet === resolved.subnet)) {\n throw new TransportError(\n \"invalid_response\",\n \"decryption list names a record outside the addressed subnet\",\n );\n }\n return page;\n };\n return {\n async put(secret, options = {}) {\n const name = requireNonBlank(secret.metadata.name, \"secret name\");\n // The name and the spec are judged before placement is resolved, so\n // a refusal arrives before anything is read or sent.\n validateVaultReferenceName(\"metadata.name\", name);\n validateSecretSpec(secret.spec);\n return await read(\"PUT\", name, options, (resolved) => {\n const stated = secret.metadata;\n if (stated.subnet !== \"\" && stated.subnet !== resolved.subnet) {\n throw new TypeError(\n \"secret subnet does not match resolved placement subnet\",\n );\n }\n const namespace = stated.namespace ?? \"\";\n if (namespace !== \"\" && namespace !== resolved.scope.namespace) {\n throw new TypeError(\n \"secret namespace is not the addressed namespace\",\n );\n }\n const document: Secret = {\n ...secret,\n metadata: {\n ...stated,\n namespace: resolved.scope.namespace,\n subnet: resolved.subnet,\n },\n };\n validateSecret(document);\n return secretShape.encode(document);\n });\n },\n async get(name, options = {}) {\n return await read(\"GET\", requireNonBlank(name, \"secret name\"), options);\n },\n async list(options = {}, request = {}) {\n const query = listQuery(options);\n const { resolved, response } = await send(\n \"GET\",\n (placed) => namespace(placed.scope, COLLECTION) + query,\n request,\n );\n const page = readList(response, \"secrets\", decodeRedactedSecret);\n if (!page.items.every((secret) => isAddressed(secret, resolved))) {\n throw new TransportError(\n \"invalid_response\",\n \"secret list names a secret outside the addressed namespace\",\n );\n }\n return page;\n },\n async rotate(name, request, options, call = {}) {\n const secretName = requireNonBlank(name, \"secret name\");\n validateVaultRotateOptions(options);\n validateSecretSpec(request.spec);\n return await read(\n \"POST\",\n secretName,\n call,\n () => encodeRotateVaultSecretRequest(request),\n \":rotate\",\n {\n [VAULT_HEADER_IDEMPOTENCY_KEY]: options.idempotencyKey,\n [VAULT_HEADER_IF_MATCH]: options.ifMatch,\n },\n );\n },\n async purge(name, request, options = {}) {\n const secretName = requireNonBlank(name, \"secret name\");\n const { response } = await send(\n \"POST\",\n secretPath(secretName, \":purge\"),\n options,\n () => encodePurgeVaultResourceRequest(request),\n );\n const record =\n typeof response === \"object\" && response !== null\n ? (response as Readonly<Record<string, unknown>>)\n : {};\n const { purgedAt } = record;\n return {\n accepted: record[\"accepted\"] === true,\n ...(typeof purgedAt === \"string\" ? { purgedAt } : {}),\n };\n },\n async listVersions(name, options = {}, request = {}) {\n const secretName = requireNonBlank(name, \"secret name\");\n const query = listQuery(options);\n const { response } = await send(\n \"GET\",\n secretPath(secretName, `/versions${query}`),\n request,\n );\n return readList(response, \"secret versions\", decodeVaultVersionMetadata);\n },\n async listDecryptions(name, options = {}, request = {}) {\n const secretName = requireNonBlank(name, \"secret name\");\n return await decryptions(\n secretPath(secretName, `/decryptions${listQuery(options)}`),\n request,\n );\n },\n async listComputerDecryptions(computerId, options = {}, request = {}) {\n const id = requireNonBlank(computerId, \"computer ID\");\n return await decryptions(\n (resolved) =>\n vaultDecryptionsOfComputer(resolved.scope, id) + listQuery(options),\n request,\n );\n },\n async delete(name, options = {}) {\n const { response } = await send(\n \"DELETE\",\n secretPath(requireNonBlank(name, \"secret name\")),\n options,\n );\n const record =\n typeof response === \"object\" && response !== null\n ? (response as Readonly<Record<string, unknown>>)\n : {};\n const { deletedAt } = record;\n return {\n accepted: record[\"accepted\"] === true,\n ...(typeof deletedAt === \"string\" ? { deletedAt } : {}),\n };\n },\n };\n}\n\n/**\n * Whether a served Secret names the addressed Subnet and Namespace; one\n * that states no Namespace is read as the addressed one.\n */\nfunction isAddressed(\n secret: RedactedSecret,\n resolved: ResolvedPlacement,\n): boolean {\n return (\n typeof (secret as unknown) === \"object\" &&\n (secret.metadata as unknown) !== undefined &&\n secret.metadata.subnet === resolved.subnet &&\n (secret.metadata.namespace ?? resolved.scope.namespace) ===\n resolved.scope.namespace\n );\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The record of decryptions: one entry for each time IDYL opened a Secret's\n * stored value. The public type is built from the served record field by\n * field; no entry carries a value.\n */\nimport type { VaultDecryption } from \"../api/vault.js\";\nimport { numberOf } from \"./records.js\";\n\n/**\n * One time IDYL opened a Secret's stored value, as the record reports the\n * decryption.\n * Vault, which keeps the sealed values, and the key service that seals them\n * each report every decryption, so the record holds a decryption whether or\n * not Vault's code reported the decryption. IDYL keeps each entry for 90\n * days.\n *\n * A Computer's start opens the values it attaches, and a later use can\n * open a value again.\n */\nexport interface Decryption {\n /** When the value was opened, as an RFC 3339 instant. */\n readonly at: string;\n /**\n * The kind of the opened resource: `Secret`, or \"TLSCertificate\" for a TLS\n * certificate a Pod mounts.\n */\n readonly kind: string;\n /** The opened resource's ID, a canonical UUID. */\n readonly resourceId: string;\n /**\n * The resource's name when the value was opened. A Secret deleted and\n * created again under the name has another `resourceId`.\n */\n readonly name: string;\n /** The version whose value was opened, from 1. */\n readonly version: number;\n /**\n * The Computer the value was opened for. Absent for a Pod's decryption and\n * for one only the key service reported.\n */\n readonly computerId?: string;\n /**\n * The Pod the value was opened for, by its instance ID. Absent for a\n * Computer's decryption and for one only the key service reported.\n */\n readonly podId?: string;\n /**\n * The start the value was opened for: a Computer's activation or a Pod's\n * assignment. Absent when it was opened under no start.\n */\n readonly activation?: string;\n /**\n * `opened`; `refused`, the key service refused to open it; or `failed`,\n * Vault's request received no answer, so whether it was opened is not\n * known until the key service's report of the request arrives. An outcome\n * this package does not name is carried unchanged from IDYL's report.\n */\n readonly outcome:\n \"opened\" | \"refused\" | \"failed\" | (string & Record<never, never>);\n /**\n * Who reported the decryption: `vault`, `kms` for the key service alone,\n * which means Vault's code did not report it, or `both`. A reporter this\n * package does not name is carried unchanged from IDYL's report.\n */\n readonly reportedBy:\n \"vault\" | \"kms\" | \"both\" | (string & Record<never, never>);\n /**\n * The key service's ID of the request, which names the same decryption in\n * the key service's own log. Absent only when Vault's request received no\n * answer that named one.\n */\n readonly kmsRequestId?: string;\n}\n\n/** The fields of a served record the public type carries. */\nconst FIELDS = [\n \"at\",\n \"kind\",\n \"resourceId\",\n \"name\",\n \"computerId\",\n \"podId\",\n \"activation\",\n \"outcome\",\n \"reportedBy\",\n \"kmsRequestId\",\n] as const;\n\n/**\n * The public view of one served decryption record, read leniently: an\n * outcome or a reporter this package does not name is carried, and a field\n * the public type does not declare is left out.\n */\nexport function decryptionOf(served: VaultDecryption): Decryption {\n const view: Record<string, unknown> = {};\n for (const field of FIELDS) {\n if (served[field] !== undefined) view[field] = served[field];\n }\n view[\"version\"] = numberOf(served.version);\n return Object.freeze(view) as unknown as Decryption;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * One download: a single stream over a saved file or tree that survives\n * breaks inside itself. The content is resolved once, every read is pinned to\n * that version and entity tag, and a cut asks for the rest from where the\n * stream stopped. A file is checked piece by piece as it arrives, so a break\n * costs only the piece in progress and no unchecked byte reaches the caller.\n * An archive has no piece list: it resumes by offset, and each file's tag\n * rides inside it in a PAX record for whoever unpacks it.\n */\nimport { ERROR_CODE_DOWNLOAD_LIMIT_REACHED } from \"../api/billing-errors.js\";\nimport {\n FILE_PIECE_BYTES,\n FILE_PIECE_HASH_BYTES,\n fileTagOfPieces,\n hexOf,\n parseFileEtag,\n type ContentFacts,\n type FileReadOptions,\n type StoredContent,\n} from \"../api/files.js\";\nimport { ERROR_CODE_VERSION_NOT_FOUND } from \"../api/storage-errors.js\";\nimport { ApiError, TransportError } from \"../errors.js\";\nimport { abortable, delay } from \"../internal/abort.js\";\nimport { bodyFailure } from \"../internal/transport.js\";\nimport type { ComputersService } from \"../services/computers.js\";\nimport type { CallOptions } from \"./common.js\";\nimport { numberOf } from \"./records.js\";\n\n/** A stream that delivers nothing for this long is cut. */\nconst SILENT_STREAM_MS = 30_000;\n/** The first wait after a failed read, doubled up to `LAST_RETRY_WAIT_MS`. */\nconst FIRST_RETRY_WAIT_MS = 1_000;\nconst LAST_RETRY_WAIT_MS = 30_000;\n/** A download that gains no byte for this long while asked for one stops. */\nconst NO_GAIN_LIMIT_MS = 15 * 60_000;\n\n/** How far a download has come: bytes handed over, of the content's length. */\nexport interface DownloadProgress {\n /** Bytes handed to the reader so far; for a file, only checked bytes. */\n readonly done: number;\n /** The content's whole length in bytes. */\n readonly total: number;\n}\n\n/** Downloads a file or a directory. */\nexport interface DownloadOptions extends CallOptions {\n /** Downloads the directory `path` names as a POSIX tar archive. */\n readonly archive?: boolean;\n /**\n * The saved version to read, by number or name; the latest when absent.\n * A named version that stops being kept ends the download. The latest,\n * when it stops being kept, is asked for once more: the download goes on\n * if the content is the same, and otherwise ends.\n */\n readonly version?: number | string;\n /**\n * Called with `{ done: 0, total }` when reading starts and again as bytes\n * are handed to the reader, in order, one call at a time. A file counts\n * only bytes that have been checked. A throw ends the stream with that\n * error.\n */\n readonly onProgress?: (progress: DownloadProgress) => void;\n}\n\n/**\n * A downloaded file or archive, read the way a `fetch` response is read:\n * once, by one of `stream`, `bytes`, `text`, `json` or `blob`. It is\n * streamed one piece at a time, never buffered beyond the piece in progress,\n * at most 4 MiB, until a reader asks for the whole body. Nothing is connected\n * until the first read, so a body never read needs no cleanup; a stream\n * abandoned partway should be cancelled with `cancel()`.\n *\n * The stream survives breaks. A cut, a silent connection (30 s) or a server\n * error is retried from the byte the stream reached, waiting 1 s doubling to\n * 30 s with half of it random, or as long as `Retry-After` asks. It ends\n * with an error after 15 minutes of being read without gaining a byte, and\n * at once on a refusal another try cannot change: an `ApiError` such as\n * status 401, 403 or 404, or `DOWNLOAD_LIMIT_REACHED`. A saved version that\n * stops being kept ends it with `VERSION_NOT_FOUND`, or with a\n * `TransportError` with code `invalid_response` when the answer shows\n * different bytes, since bytes already handed over cannot be taken back. The\n * caller's `signal` ends it at any point with the signal's reason.\n *\n * A file's bytes are checked against its tag as they arrive, so none reaches\n * the reader unchecked. An archive is checked by whoever unpacks it, against\n * the `comment` PAX record each file carries.\n */\nexport interface FileBody {\n /** The saved version resolved for the content when the download started. */\n readonly version: number;\n /** The content's strong entity tag: for a file, its tag and length. */\n readonly etag: string;\n /** The content's length in bytes. */\n readonly size: number;\n /** Whether the body has been read. */\n readonly bodyUsed: boolean;\n /**\n * The content as a stream of bytes, read one piece at a time as the\n * stream is pulled. Cancelling the stream ends the download. A download\n * that ends with an error errors the stream with it, as the type\n * describes.\n *\n * @throws {@link TypeError} the body has already been read\n */\n stream(): ReadableStream<Uint8Array>;\n /**\n * The whole content as bytes.\n *\n * @throws {@link TypeError} the body has already been read\n * @throws {@link ApiError} the download ends on a refusal another try\n * cannot change, such as `VERSION_NOT_FOUND` or `DOWNLOAD_LIMIT_REACHED`\n * @throws {@link TransportError} the download gains no byte for 15\n * minutes, or the content it reads is replaced\n */\n bytes(): Promise<Uint8Array>;\n /**\n * The content decoded as UTF-8.\n *\n * @throws {@link TypeError} the body has already been read\n * @throws {@link ApiError} the download ends on a refusal another try\n * cannot change, such as `VERSION_NOT_FOUND` or `DOWNLOAD_LIMIT_REACHED`\n * @throws {@link TransportError} the download gains no byte for 15\n * minutes, or the content it reads is replaced\n */\n text(): Promise<string>;\n /**\n * The content parsed as JSON.\n *\n * @throws {@link TypeError} the body has already been read\n * @throws {@link ApiError} the download ends on a refusal another try\n * cannot change, such as `VERSION_NOT_FOUND` or `DOWNLOAD_LIMIT_REACHED`\n * @throws {@link TransportError} the download gains no byte for 15\n * minutes, or the content it reads is replaced\n * @throws SyntaxError the content is not JSON\n */\n json(): Promise<unknown>;\n /**\n * The whole content as a `Blob`.\n *\n * @throws {@link TypeError} the body has already been read\n * @throws {@link ApiError} the download ends on a refusal another try\n * cannot change, such as `VERSION_NOT_FOUND` or `DOWNLOAD_LIMIT_REACHED`\n * @throws {@link TransportError} the download gains no byte for 15\n * minutes, or the content it reads is replaced\n */\n blob(): Promise<Blob>;\n}\n\n/** What one download reads. */\nexport interface DownloadRequest extends CallOptions {\n /** The path, already held to the workspace. */\n readonly path: string;\n readonly archive: boolean;\n /** The version the caller named, by number or name. */\n readonly version?: string;\n readonly onProgress?: ((progress: DownloadProgress) => void) | undefined;\n}\n\n/** The time a download keeps: its clock, its waits and its silence timer. */\nexport interface DownloadPacing {\n now(): number;\n /** A number from 0 up to 1, the random part of a wait. */\n random(): number;\n wait(milliseconds: number, signal: AbortSignal): Promise<void>;\n /** Runs `run` after `milliseconds`; the function returned cancels it. */\n after(milliseconds: number, run: () => void): () => void;\n}\n\nconst systemPacing: DownloadPacing = {\n now: Date.now,\n random: Math.random,\n wait: delay,\n after(milliseconds, run) {\n const timer = setTimeout(run, milliseconds);\n return () => {\n clearTimeout(timer);\n };\n },\n};\n\n/** A read that broke: a cut, a silent stream, a short body or wrong bytes. */\nclass BrokenRead extends Error {}\n\n/** An answer that shows the version or bytes being read are not served. */\nconst CONTENT_MOVED = new Error();\n\n/** One request's body, read under the silence limit. */\ninterface OpenRead {\n read(): Promise<ReadableStreamReadResult<Uint8Array>>;\n end(): void;\n}\n\n/**\n * Resolves the content with `HEAD`, rejecting on a refusal, and returns its\n * body. No content is requested until the body is first read.\n */\nexport async function openDownload(\n service: ComputersService,\n computerId: string,\n request: DownloadRequest,\n pacing: DownloadPacing = systemPacing,\n): Promise<FileBody> {\n const { path, archive, signal, onProgress } = request;\n const kind = archive ? \"archive\" : \"file\";\n // The version every read names; empty asks for the latest.\n let pinned = request.version ?? \"\";\n const named = pinned !== \"\";\n const readOptions = (): FileReadOptions => ({ path, version: pinned });\n\n const cancelled = new AbortController();\n const stop = AbortSignal.any(\n signal === undefined ? [cancelled.signal] : [signal, cancelled.signal],\n );\n\n /** One request's abort: the download's, or its own when it goes silent. */\n const requestScope = () => {\n const controller = new AbortController();\n const scoped = AbortSignal.any([stop, controller.signal]);\n const end = (): void => {\n controller.abort(new BrokenRead());\n };\n return {\n signal: scoped,\n end,\n async watched<T>(work: Promise<T>): Promise<T> {\n work.catch(() => undefined);\n const cancel = pacing.after(SILENT_STREAM_MS, end);\n try {\n return await abortable(work, scoped);\n } finally {\n cancel();\n }\n },\n };\n };\n\n /** Opens one request, or fails as moved when it answers `undefined`. */\n const open = async (\n send: (signal: AbortSignal) => Promise<StoredContent | undefined>,\n ): Promise<OpenRead> => {\n const scope = requestScope();\n try {\n const content = await scope.watched(send(scope.signal));\n if (content === undefined) {\n throw CONTENT_MOVED;\n }\n const reader = content.body.getReader();\n return {\n read: async () => {\n try {\n return await scope.watched(reader.read());\n } catch (error) {\n throw new BrokenRead(undefined, { cause: error });\n }\n },\n end: () => {\n reader.cancel().catch(() => undefined);\n scope.end();\n },\n };\n } catch (error) {\n scope.end();\n throw error;\n }\n };\n\n const resolveHead = async (): Promise<ContentFacts> => {\n const scope = requestScope();\n return await scope.watched(\n service.headContentById(computerId, kind, readOptions(), {\n signal: scope.signal,\n }),\n );\n };\n\n let etag = \"\";\n let size = 0;\n let current: OpenRead | undefined;\n let rest: Uint8Array | undefined;\n const dropRead = (): void => {\n current?.end();\n current = undefined;\n rest = undefined;\n };\n\n /**\n * Runs `work` until it succeeds. It stops at once on an answer another try\n * cannot change, and after `NO_GAIN_LIMIT_MS`. The limit is measured from\n * this call, so time a reader spends away from the stream does not count.\n */\n const gaining = async <T>(work: () => Promise<T>): Promise<T> => {\n const since = pacing.now();\n let wait = FIRST_RETRY_WAIT_MS;\n let followed = false;\n for (;;) {\n try {\n return await work();\n } catch (error) {\n dropRead();\n if (stop.aborted) throw stop.reason;\n if (\n error === CONTENT_MOVED ||\n (error instanceof ApiError &&\n error.code === ERROR_CODE_VERSION_NOT_FOUND)\n ) {\n // Only the latest is followed, once in each stretch without a gain.\n if (named || followed) throw movedFailure(error);\n followed = true;\n pinned = \"\";\n const facts = await gaining(resolveHead);\n if (facts.etag !== etag) {\n throw movedFailure(error);\n }\n pinned = String(facts.version);\n continue;\n }\n if (!retryable(error)) throw error;\n if (pacing.now() - since >= NO_GAIN_LIMIT_MS) {\n throw bodyFailure(\"download stalled for 15 minutes\", error);\n }\n await pacing.wait(\n Math.max(\n (wait * (1 + pacing.random())) / 2,\n (error as ApiError).retryAfterMs ?? 0,\n ),\n stop,\n );\n wait = Math.min(wait * 2, LAST_RETRY_WAIT_MS);\n }\n }\n };\n\n const facts = await gaining(resolveHead);\n etag = facts.etag;\n size = facts.size;\n const stated = archive ? undefined : parseFileEtag(etag);\n if (!archive && stated?.size !== size) {\n throw new TransportError(\n \"invalid_response\",\n \"content response does not state its length, entity tag and version\",\n );\n }\n const tag = stated?.tag ?? \"\";\n pinned = String(facts.version);\n\n let offset = 0;\n const openRest = async (): Promise<OpenRead> =>\n await open(\n async (signal) =>\n await service.readContentRangeById(\n computerId,\n kind,\n readOptions(),\n { offset, length: size - offset, etag },\n { signal },\n ),\n );\n\n /** Fills `buffer` from `read`, keeping what arrived beyond it for the next. */\n const fill = async (read: OpenRead, buffer: Uint8Array): Promise<void> => {\n let filled = 0;\n while (filled < buffer.length) {\n let chunk = rest;\n rest = undefined;\n if (chunk === undefined) {\n const { done, value } = await read.read();\n if (done) throw new BrokenRead();\n chunk = value;\n }\n const taken = Math.min(chunk.length, buffer.length - filled);\n buffer.set(chunk.subarray(0, taken), filled);\n filled += taken;\n if (taken < chunk.length) rest = chunk.subarray(taken);\n }\n };\n\n let hashes: string | undefined;\n /** The file's piece hashes in hexadecimal, read once and checked against its tag. */\n const pieceHashes = async (): Promise<string> => {\n if (hashes !== undefined) return hashes;\n const count = Math.ceil(size / FILE_PIECE_BYTES);\n if (count === 1) return tag;\n const list = new Uint8Array(count * FILE_PIECE_HASH_BYTES);\n const read = await open(async (signal) => {\n const content = await service.readFilePiecesById(\n computerId,\n readOptions(),\n { signal },\n );\n if (content.etag === etag) return content;\n await content.close();\n return undefined;\n });\n try {\n await fill(read, list);\n } finally {\n read.end();\n rest = undefined;\n }\n if ((await fileTagOfPieces(list)) !== tag) throw new BrokenRead();\n hashes = hexOf(list);\n return hashes;\n };\n\n /** The next piece, whole and checked; a piece is a new buffer it hands over. */\n const nextPiece = async (): Promise<Uint8Array> => {\n const expected = await pieceHashes();\n const read = (current ??= await openRest());\n const piece = new Uint8Array(Math.min(FILE_PIECE_BYTES, size - offset));\n await fill(read, piece);\n const at = (offset / FILE_PIECE_BYTES) * 2 * FILE_PIECE_HASH_BYTES;\n const digest = await crypto.subtle.digest(\"SHA-256\", piece);\n if (!expected.startsWith(hexOf(new Uint8Array(digest)), at)) {\n throw new BrokenRead();\n }\n return piece;\n };\n\n /** The next bytes of an archive, as they arrive. */\n const nextChunk = async (): Promise<Uint8Array> => {\n const read = (current ??= await openRest());\n const { done, value } = await read.read();\n if (done) throw new BrokenRead();\n return value.subarray(0, size - offset);\n };\n\n let started = false;\n const source = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n stop.throwIfAborted();\n if (!started) {\n started = true;\n onProgress?.({ done: 0, total: size });\n }\n if (offset < size) {\n const bytes = await gaining(archive ? nextChunk : nextPiece);\n offset += bytes.length;\n controller.enqueue(bytes);\n onProgress?.({ done: offset, total: size });\n }\n if (offset === size) {\n dropRead();\n controller.close();\n }\n } catch (error) {\n dropRead();\n controller.error(error);\n }\n },\n cancel(reason) {\n dropRead();\n cancelled.abort(reason);\n },\n },\n { highWaterMark: 0 },\n );\n return fileBody(source, { version: numberOf(facts.version), etag, size });\n}\n\n/** Whether another try can change a failed read's outcome. */\nfunction retryable(error: unknown): boolean {\n if (error instanceof ApiError) {\n return (\n error.code !== ERROR_CODE_DOWNLOAD_LIMIT_REACHED &&\n (error.status === 429 || error.status >= 500)\n );\n }\n if (error instanceof TransportError) {\n return error.code === \"network_error\" || error.code === \"timeout\";\n }\n return error instanceof BrokenRead;\n}\n\n/** What a caller sees when the content being read cannot be followed. */\nfunction movedFailure(error: unknown): unknown {\n return error instanceof ApiError\n ? error\n : new TransportError(\n \"invalid_response\",\n \"saved content changed during the read\",\n );\n}\n\n/** A body read once, the way a `fetch` response is. */\nfunction fileBody(\n source: ReadableStream<Uint8Array>,\n facts: Pick<FileBody, \"version\" | \"etag\" | \"size\">,\n): FileBody {\n let used = false;\n const take = (): ReadableStream<Uint8Array> => {\n if (used) throw new TypeError(\"the body has already been read\");\n used = true;\n return source;\n };\n const response = (): Response => new Response(take());\n return Object.freeze({\n ...facts,\n get bodyUsed() {\n return used;\n },\n stream: take,\n bytes: async () => new Uint8Array(await response().arrayBuffer()),\n text: async () => await response().text(),\n json: async (): Promise<unknown> => await response().json(),\n blob: async () => await response().blob(),\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * A Computer's workspace as a remote filesystem of saved versions. Moving\n * bytes between the caller and the Computer is `upload` and `download`;\n * managing what is there is `list`, `createFolder`, `move` and `remove`,\n * and `watch` follows a folder's status as its names change.\n * Each change is one upload operation: opened on the current files, sent,\n * published as one version, and read until it settles. A download is one\n * resumable, checked stream, read by `./download.ts`, and `downloadLink`\n * hands the same bytes to something that holds no credential.\n */\nimport type { WatchFilesResponse } from \"../api/file-status.js\";\nimport type {\n FileEntry as FileEntryRecord,\n FilePath,\n Upload,\n} from \"../api/files.js\";\nimport { ERROR_CODE_UPLOAD_CONFLICT } from \"../api/storage-errors.js\";\nimport { isSaveSizeReason } from \"../api/storage.js\";\nimport {\n ERROR_CODE_UPLOAD_CANCELLED,\n ERROR_CODE_UPLOAD_EXPIRED,\n} from \"../api/storage-errors.js\";\nimport {\n ApiError,\n isNotFound,\n TransportError,\n UploadTransferFailedError,\n} from \"../errors.js\";\nimport { delay } from \"../internal/abort.js\";\nimport type { ComputersService } from \"../services/computers.js\";\nimport type { UploadRequestOptions } from \"../services/storage.js\";\nimport { pollUntil } from \"../wait.js\";\nimport {\n clientOf,\n signalOf,\n walk,\n type CallOptions,\n type Page,\n} from \"./common.js\";\nimport { serviceOf, type HandleState } from \"./computer.js\";\nimport {\n openDownload,\n type DownloadOptions,\n type FileBody,\n} from \"./download.js\";\nimport { numberOf, optionalNumber } from \"./records.js\";\n\n/**\n * What an upload sends: text (as UTF-8), bytes, a `Blob` or `File`, or a\n * stream of bytes. In Node.js, `await fs.openAsBlob(path)` uploads a local\n * file; the package itself reads no local disk.\n */\nexport type FileData =\n string | Uint8Array | ArrayBuffer | Blob | ReadableStream<Uint8Array>;\n\n/** Uploads files. */\nexport interface UploadOptions extends CallOptions {\n /**\n * The permission bits of an uploaded file, such as `0o755`; `0o644` when\n * absent. Not for an archive, whose entries carry their own.\n */\n readonly mode?: number;\n /**\n * Treats the data as a POSIX tar archive and unpacks it into the\n * directory `path` names; `false` when absent.\n */\n readonly archive?: boolean;\n /**\n * Makes the upload safe to repeat: a repeat with the same key returns\n * the version the first published.\n */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the upload, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Receives the progress of each file's bytes: once when its transfer\n * starts, and again each time the platform accepts a part of at most\n * 4 MiB. It is called synchronously, in order, and an exception it throws\n * ends the upload with that exception. Every file's bytes are accepted\n * before the upload publishes its version.\n */\n readonly onProgress?: (progress: UploadProgress) => void;\n}\n\n/**\n * How much of one uploaded file the platform holds. The bytes are kept\n * across a retried part, so `sent` only grows.\n */\nexport interface UploadProgress {\n /** The path, relative to the workspace; for an archive, its directory. */\n readonly path: string;\n /** Bytes the platform has accepted of this path's data. */\n readonly sent: number;\n /**\n * The data's whole length in bytes, absent when it is a `ReadableStream`,\n * whose length is known only once it ends.\n */\n readonly size?: number;\n}\n\n/** Moves or removes files. */\nexport interface ChangeOptions extends CallOptions {\n /** Makes the change safe to repeat, as an upload's key does. */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the change, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n}\n\n/** Creates a download link. */\nexport interface DownloadLinkOptions extends CallOptions {\n /**\n * The saved version the link reads, by number or name; the latest when\n * absent. The link stays on the version it resolved to.\n */\n readonly version?: number | string;\n}\n\n/**\n * A read-only address of one saved file or directory at one version, for a\n * browser or another program that holds no credential. Whoever holds `url`\n * can read those bytes until `expiresAt`, with nothing else, so it is handled\n * as a secret: not logged, and not given to anyone who should not have the\n * bytes. A directory is served as a POSIX tar archive. The link answers range\n * requests, so a browser's download manager can resume it, and its bytes count\n * as the Account's downloads.\n */\nexport interface DownloadLink {\n /**\n * The link: an `https:` URL that carries its own authority, read with a\n * plain `GET` and no credential.\n */\n readonly url: string;\n /** When the link stops working, as an RFC 3339 timestamp. */\n readonly expiresAt: string;\n /** The saved version the link reads. */\n readonly version: number;\n}\n\n/** Lists a directory. */\nexport interface ListFilesOptions extends CallOptions {\n /** Lists every directory below as well, depth first. */\n readonly recursive?: boolean;\n /** The saved version to read, by number or name; the latest when absent. */\n readonly version?: number | string;\n}\n\n/**\n * Whether a file's content is safe in the store: `synced` once a saved\n * version holds it; `syncing` for a name on a running Computer whose content\n * no saved version holds yet; `conflict` where two changes collided and both\n * copies were kept; `failed` for content the Computer's save cannot finish.\n * Newer values are carried as they arrive.\n */\nexport type FileStatus =\n | \"synced\"\n | \"syncing\"\n | \"conflict\"\n | \"failed\"\n | (string & Record<never, never>);\n\n/** One entry of a listing. */\nexport interface FileEntry {\n /** Its path relative to the workspace. */\n readonly path: string;\n /** `file`, `dir` or `symlink`. */\n readonly type: \"file\" | \"dir\" | \"symlink\" | (string & Record<never, never>);\n /** Its size in bytes. */\n readonly size: number;\n /** Its permission bits. */\n readonly mode: number;\n /**\n * A file's public content hash, the tag in its entity tag. Absent from a\n * listing where stating it would take more than the listing reads.\n */\n readonly tag?: string;\n /** A symlink's target. */\n readonly target?: string;\n /**\n * Whether its content is safe in the store. A listing of the latest\n * version states it on every entry; a listing of a named version, which a\n * recursive listing reads throughout, leaves it absent, since everything\n * a saved version holds is in the store.\n */\n readonly status?: FileStatus;\n /**\n * Why its content is not safe: `kept-both` for a `conflict`, and the\n * failing save's reason for `failed`.\n */\n readonly statusReason?: string;\n}\n\n/**\n * One answer of `watch`: the whole current status of the watched folder and\n * everything below it, and the versions published since the answer before.\n */\nexport interface FolderStatus {\n /**\n * Whether the files hold changes no saved version holds yet, including\n * changes written in place to files a listing shows as `synced`. It is\n * `true` while a running Computer holds such changes, and when the\n * platform cannot tell.\n */\n readonly syncing: boolean;\n /**\n * Every name below the folder that differs on the running Computer from\n * its last saved version, in byte order of path. It is the whole set each\n * time, not the difference from the answer before.\n */\n readonly changes: readonly FileChange[];\n /** The versions published since the answer before, oldest first. */\n readonly published: readonly FilePublication[];\n /**\n * Whether more was published since the answer before than the platform\n * still remembers, so the folder is listed again instead of applying\n * `published`.\n */\n readonly relist: boolean;\n /** Present while the running Computer's reads wait for the store. */\n readonly store?: FileStoreWait;\n}\n\n/** One name of a {@link FolderStatus} that differs from the last saved version. */\nexport interface FileChange {\n /** Its path relative to the workspace, not to the watched folder. */\n readonly path: string;\n /**\n * `changed` for a name created, replaced or moved to its path; `removed`\n * for a saved name the running Computer does not hold; `many` for a\n * folder holding more differing names than are listed one by one, the\n * workspace itself when `path` is empty, whose names a listing shows.\n */\n readonly change:\n \"changed\" | \"removed\" | \"many\" | (string & Record<never, never>);\n /** `file`, `dir` or `symlink`, on a `changed` name. */\n readonly type?: FileEntry[\"type\"];\n /** Its size in bytes, on a `changed` name. */\n readonly size?: number;\n /** When it was last modified, as an RFC 3339 timestamp, when stated. */\n readonly modified?: string;\n /** `syncing`, `conflict` or `failed`. */\n readonly status: FileStatus;\n /** Why, as on a {@link FileEntry}. */\n readonly statusReason?: string;\n}\n\n/** One version published to the files, such as a save, an upload or a restore. */\nexport interface FilePublication {\n /** The saved version it published. */\n readonly version: number;\n /** The paths it wrote or removed, relative to the workspace, when they are known. */\n readonly paths: readonly string[];\n /**\n * Whether it touched more than `paths` lists, so the folders shown are\n * listed again.\n */\n readonly more: boolean;\n}\n\n/** How a running Computer's reads wait for the store. */\nexport interface FileStoreWait {\n /**\n * `waiting` for a read that has waited at least five seconds and is still\n * trying; `unreachable` for a Computer whose first reads of files fail at\n * once, with one read tried again every 30 seconds until one succeeds.\n */\n readonly state: \"waiting\" | \"unreachable\" | (string & Record<never, never>);\n /**\n * `store` for a store that does not answer, `connection` for a Computer\n * whose machine cannot reach the platform to be let into the store.\n */\n readonly cause: \"store\" | \"connection\" | (string & Record<never, never>);\n /** When the wait began, as an RFC 3339 timestamp. */\n readonly since: string;\n /** How many reads are waiting. */\n readonly waiting: number;\n /** The bytes the largest waiting file has. */\n readonly fillDone: number;\n /** The bytes the largest waiting file needs. */\n readonly fillTotal: number;\n}\n\n/**\n * What an upload published, and how the running Computer received the upload.\n */\nexport interface Uploaded {\n /** The saved version the upload published. */\n readonly version: number;\n /**\n * How the running Computer received the upload; absent when no Computer\n * was running, since the next wake starts from the saved version.\n */\n readonly delivery?: Delivery;\n}\n\n/**\n * An upload's delivery to the running Computer. The upload resolves once\n * the Computer applied it (`applied`) or the delivery ended (`failed`,\n * with its `reason`), waiting at most 10 seconds after it is saved. Past\n * that wait the state is `pending` or `retrying`: the upload is saved, and\n * the Computer receives it later, in order.\n */\nexport interface Delivery {\n /** `pending`, `applied`, `retrying` or `failed`. */\n readonly state:\n | \"pending\"\n | \"applied\"\n | \"retrying\"\n | \"failed\"\n | (string & Record<never, never>);\n /** Why the last attempt failed, or why the delivery ended. */\n readonly reason?: string;\n /** How many uploaded paths met unsaved work on the running Computer. */\n readonly replacedCount: number;\n /** The first 100 of those paths, in byte order. */\n readonly replaced: readonly ReplacedPath[];\n}\n\n/**\n * An uploaded path that met unsaved work on the running Computer. When\n * `landedAt` is set, both copies are kept: the Computer's own copy keeps\n * `path` and the uploaded copy is at `landedAt`. When it is absent, the\n * upload replaced the Computer's copy at `path`.\n */\nexport interface ReplacedPath {\n /** The path, relative to the workspace. */\n readonly path: string;\n /** Where the uploaded copy is, relative to the workspace. */\n readonly landedAt?: string;\n}\n\n/**\n * A Computer's workspace, the files at `/workspace`, as saved versions.\n *\n * Paths are relative to the workspace with `/` as the separator; an\n * absolute path, or one that would leave the workspace, is refused with a\n * `TypeError` before any request. Each `upload`, `move` or `remove`\n * publishes one saved version however many files it touches and resolves\n * with that version; `upload` also says how the running Computer received the\n * files. `download` reads a saved version. On a running Computer, a name a\n * program creates, moves or removes reaches `list` and `watch` at once with the\n * status `syncing`, and reads `synced` once it is saved, about ten seconds\n * after writes go quiet, at the end of a command, or on `computer.save()`; its\n * content follows with that save.\n *\n * A change that ends without publishing, because another change to the same\n * files was published first or it expired, rejects with an `ApiError`\n * (status 409) carrying its outcome's code, such as `UPLOAD_CONFLICT`. One\n * that fails for size carries its reason as the code:\n * `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`, `SAVE_REASON_COMPUTER_SIZE` or\n * `SAVE_REASON_NAME_LIMIT`.\n *\n * @example\n * ```ts\n * await computer.files.upload(\"data/input.csv\", \"id,score\\n1,0.9\\n\");\n *\n * for await (const entry of computer.files.list(\"data\")) {\n * console.log(entry.path, entry.size);\n * }\n *\n * const results = await computer.files.download(\"results.json\");\n * console.log(await results.json());\n * ```\n */\nexport interface Files {\n /**\n * Uploads one file, or a tar archive into a directory with `archive`.\n *\n * @param path - The file's path, relative to the workspace; with\n * `archive`, the directory the archive unpacks into, the workspace\n * itself when empty.\n * @param data - The file's content, or the archive.\n * @throws {@link TypeError} the path, the data or an option is invalid, or\n * `mode` is stated with `archive`, before any request is sent\n * @throws {@link ApiError} IDYL refuses the upload or one of its parts, or\n * the upload ends without publishing (status 409, with the outcome's\n * code, such as `UPLOAD_CONFLICT`, or the size reason that stopped the\n * upload)\n * @throws {@link TransportError} a request does not complete\n */\n upload(\n path: string,\n data: FileData,\n options?: UploadOptions,\n ): Promise<Uploaded>;\n /**\n * Uploads many files, by path, as one version.\n *\n * @param files - Each file's content by its path, relative to the\n * workspace.\n * @throws {@link TypeError} `files` names no file, a path, a file's data\n * or an option is invalid, or `archive` is stated, before any request\n * is sent\n * @throws {@link ApiError} IDYL refuses the upload or one of its parts, or\n * the upload ends without publishing (status 409, with the outcome's\n * code, such as `UPLOAD_CONFLICT`, or the size reason that stopped the\n * upload)\n * @throws {@link TransportError} a request does not complete\n */\n upload(\n files: Readonly<Record<string, FileData>>,\n options?: UploadOptions,\n ): Promise<Uploaded>;\n /**\n * Downloads a file, or a directory as a tar archive with `archive`, as a\n * body that resumes across breaks and hands a file's bytes over only once\n * they are checked; see {@link FileBody}. It resolves once the content is\n * resolved, and reads no bytes until the body is read.\n *\n * @param path - The file's path, relative to the workspace; with\n * `archive`, the directory's, the workspace itself when empty.\n * @throws {@link TypeError} the path or an option is invalid, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses to resolve the content, such as\n * with status 404 for a path or version it does not hold, or\n * `DOWNLOAD_LIMIT_REACHED`\n * @throws {@link TransportError} the content cannot be resolved after\n * 15 minutes of retries, or its answer cannot be used\n */\n download(path: string, options?: DownloadOptions): Promise<FileBody>;\n /**\n * Creates a link that reads a saved file or directory, the workspace itself\n * when `path` is empty, with no other credential. Whoever holds its `url`\n * can read those bytes until it expires, so it is handled as a secret. A\n * `version` of `save-first` is refused with a `TypeError`.\n *\n * @param path - The file's or directory's path, relative to the\n * workspace; empty for the workspace itself.\n * @throws {@link TypeError} the path or `version` is invalid, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the link, such as with status 404\n * for a path or version it does not hold\n * @throws {@link TransportError} the request does not complete\n */\n downloadLink(\n path: string,\n options?: DownloadLinkOptions,\n ): Promise<DownloadLink>;\n /**\n * The entries of a directory, the workspace itself when `path` is absent.\n * Pages are read as the iteration asks for them.\n *\n * @param path - The directory's path, relative to the workspace; empty or\n * absent for the workspace itself.\n * @throws {@link TypeError} the path or `version` is invalid, when the\n * iteration starts and before any request is sent\n * @throws {@link ApiError} IDYL refuses a page, such as with status 404\n * for a directory or version it does not hold\n * @throws {@link TransportError} a request does not complete\n */\n list(path?: string, options?: ListFilesOptions): AsyncIterable<FileEntry>;\n /**\n * Follows a folder, the workspace itself when `path` is absent. The first\n * answer is the folder's current status, whether the files are `syncing`\n * included, and each later one is an answer in which the status or the\n * published versions moved.\n *\n * Each answer is one request that the platform holds for at most 10\n * seconds when nothing moved, asked again with the cursor of the answer\n * before, so nothing is missed between two answers and one request is\n * open at a time. Watching never wakes a Computer: one that is asleep has\n * no changes on their way, and its answers move only when a version is\n * published. A request that fails for a timeout, a rate limit, a server\n * error or the network is asked again after 500 ms doubling to 30 s, half\n * of it random, or as long as `Retry-After` asks; any other refusal ends\n * the iteration with that error. It runs until the consumer stops\n * iterating, which leaves no request or timer behind, or until `signal`\n * aborts, which rejects with the signal's reason.\n *\n * @param path - The folder's path, relative to the workspace; empty or\n * absent for the workspace itself.\n * @throws {@link TypeError} the path is invalid, when the iteration starts\n * and before any request is sent\n * @throws {@link ApiError} IDYL refuses a request with a status other than\n * 408, 429 or 5xx, which are asked again\n * @throws {@link TransportError} a request does not complete for a reason\n * other than the network or a timeout, which are asked again\n */\n watch(path?: string, options?: CallOptions): AsyncIterable<FolderStatus>;\n /**\n * Creates an empty folder in a folder that exists, as one saved version.\n * A name already taken, by a folder or a file, is an `ApiError` with\n * status 409, and a missing parent folder one with status 404, each\n * before anything is sent. The name is judged on the version the upload\n * is based on, so a change to the same path published after that version\n * ends the upload in conflict (`UPLOAD_CONFLICT`) rather than being\n * replaced.\n *\n * @param path - The folder to create, relative to the workspace.\n * @returns the saved version that holds the folder\n * @throws {@link TypeError} the path is invalid, before any request is\n * sent\n * @throws {@link ApiError} the name is taken (status 409), the parent\n * folder is missing (status 404), IDYL refuses the change, or it ends\n * without publishing (status 409, with the outcome's code)\n * @throws {@link TransportError} a request does not complete\n */\n createFolder(path: string, options?: ChangeOptions): Promise<number>;\n /**\n * Moves, which also renames, a file or directory.\n *\n * @param from - The path to move, relative to the workspace.\n * @param to - Its path after the move, relative to the workspace.\n * @returns the saved version that holds the move\n * @throws {@link TypeError} a path is invalid, before any request is sent\n * @throws {@link ApiError} IDYL refuses the move, or it ends without\n * publishing (status 409, with the outcome's code)\n * @throws {@link TransportError} a request does not complete\n */\n move(from: string, to: string, options?: ChangeOptions): Promise<number>;\n /**\n * Removes files and directories.\n *\n * @param paths - The path, or the paths, to remove, relative to the\n * workspace.\n * @returns the saved version that holds the removal\n * @throws {@link TypeError} `paths` names no path or a path is invalid,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the removal, or it ends without\n * publishing (status 409, with the outcome's code)\n * @throws {@link TransportError} a request does not complete\n */\n remove(\n paths: string | readonly string[],\n options?: ChangeOptions,\n ): Promise<number>;\n}\n\n/** The interval between reads while an upload settles. */\nconst SETTLE_POLL_MS = 500;\n\n/** The first bound of the wait before a failed watch request is asked again. */\nconst FIRST_WATCH_RETRY_MS = 500;\n/** The bound every wait before a failed watch request is asked again stays under. */\nconst LAST_WATCH_RETRY_MS = 30_000;\n\n/** Builds the files of the Computer `computerId`. */\nexport function files(state: HandleState, computerId: string): Files {\n /*\n * `check`, when given, judges the open upload's base version before\n * anything is sent; when it throws, the upload is cancelled. A repeat of\n * an idempotent upload returns the recorded outcome unjudged.\n */\n const publish = async (\n options: UploadOptions | ChangeOptions,\n send: (service: ComputersService, operation: string) => Promise<void>,\n check?: (service: ComputersService, base: string) => Promise<void>,\n ): Promise<Uploaded> => {\n const service = await serviceOf(state, options);\n const key =\n options.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: options.idempotencyKey };\n const created = await service.createUploadById(\n computerId,\n { ...key, client: clientOf(options.client) },\n signalOf(options),\n );\n let result = created;\n if (created.state === \"open\") {\n if (check !== undefined) {\n try {\n await check(service, String(numberOf(created.base)));\n } catch (error) {\n await service\n .cancelUploadById(computerId, created.id, signalOf(options))\n .catch(() => undefined);\n throw error;\n }\n }\n try {\n await send(service, created.id);\n } catch (error) {\n throw transferFailure(error);\n }\n result = await service.publishUploadById(\n computerId,\n created.id,\n key,\n signalOf(options),\n );\n }\n const settled =\n (await pollUntil(\n { ...signalOf(options), pollIntervalMs: SETTLE_POLL_MS },\n {\n initial: result,\n read: async (signal) =>\n await service.getUploadById(computerId, created.id, { signal }),\n met: (upload) =>\n [\n \"published\",\n \"conflict\",\n \"expired\",\n \"cancelled\",\n \"failed\",\n ].includes(upload.state),\n timeoutMessage: (ms) =>\n `upload did not settle within ${String(ms)} ms`,\n },\n )) ?? result;\n const version = optionalNumber(settled.version);\n if (settled.state !== \"published\" || version === undefined) {\n throw unpublished(settled);\n }\n const delivery = settled.delivery;\n return Object.freeze({\n version,\n ...(delivery === undefined\n ? {}\n : {\n delivery: Object.freeze({\n state: delivery.state,\n ...(delivery.reason === undefined\n ? {}\n : { reason: delivery.reason }),\n replacedCount: numberOf(delivery.replacedCount),\n replaced: Object.freeze(\n (delivery.replaced ?? []).map((p) =>\n Object.freeze({\n path: pathText(p),\n ...(p.landedAt === undefined\n ? {}\n : { landedAt: pathText(p.landedAt) }),\n }),\n ),\n ),\n }),\n }),\n });\n };\n /** A change's saved version. */\n const change = async (...args: Parameters<typeof publish>): Promise<number> =>\n (await publish(...args)).version;\n\n async function upload(\n target: string | Readonly<Record<string, FileData>>,\n dataOrOptions?: FileData | UploadOptions,\n maybeOptions?: UploadOptions,\n ): Promise<Uploaded> {\n if (typeof target === \"string\") {\n const options = maybeOptions ?? {};\n const archive = options.archive === true;\n const path = workspacePath(target, archive ? \"a directory\" : undefined);\n const data = dataOrOptions as FileData;\n const body = bytesOf(data);\n const transfer = transferOf(options, path, data);\n if (archive) {\n if (options.mode !== undefined) {\n throw new TypeError(\"mode does not apply to an archive\");\n }\n return await publish(options, async (service, operation) => {\n await service.uploadArchiveById(\n computerId,\n operation,\n { path, seq: 1 },\n body,\n transfer,\n );\n });\n }\n const mode = fileMode(options.mode);\n return await publish(options, async (service, operation) => {\n await service.uploadFileById(\n computerId,\n operation,\n { path, mode, seq: 1 },\n body,\n transfer,\n );\n });\n }\n if (typeof target !== \"object\" || (target as unknown) === null) {\n throw new TypeError(\"files must be a path or an object of paths\");\n }\n const options = (dataOrOptions ?? {}) as UploadOptions;\n if (options.archive === true) {\n throw new TypeError(\"archive takes one path and one archive\");\n }\n const mode = fileMode(options.mode);\n const entries = Object.entries(target).map(([name, data]) => {\n const path = workspacePath(name);\n return [path, bytesOf(data), transferOf(options, path, data)] as const;\n });\n if (entries.length === 0) throw new TypeError(\"files must name a file\");\n return await publish(options, async (service, operation) => {\n let seq = 0;\n for (const [path, body, transfer] of entries) {\n seq += 1;\n await service.uploadFileById(\n computerId,\n operation,\n { path, mode, seq },\n body,\n transfer,\n );\n }\n });\n }\n\n /** One page of a directory, each entry with whether its name addresses it. */\n const listPage = async (\n path: string,\n version: string | undefined,\n options: CallOptions & { readonly continue?: string },\n ): Promise<Page<Listed>> => {\n const service = await serviceOf(state, options);\n const page = await service.listFilesById(\n computerId,\n {\n path,\n ...(version === undefined ? {} : { version }),\n ...(options.continue === undefined\n ? {}\n : { continue: options.continue }),\n },\n signalOf(options),\n );\n return Object.freeze({\n items: page.items.map((entry) => listed(path, entry)),\n ...(page.continue === undefined ? {} : { continue: page.continue }),\n });\n };\n\n async function* walkDirectory(\n path: string,\n version: string | undefined,\n options: ListFilesOptions,\n ): AsyncGenerator<FileEntry, void, undefined> {\n for await (const { entry, addressable } of walk(\n (page) => listPage(path, version, page),\n signalOf(options),\n )) {\n yield entry;\n if (options.recursive === true && entry.type === \"dir\" && addressable) {\n yield* walkDirectory(entry.path, version, options);\n }\n }\n }\n\n async function* list(\n path = \"\",\n options: ListFilesOptions = {},\n ): AsyncGenerator<FileEntry, void, undefined> {\n const directory = workspacePath(path, \"the workspace\");\n let version = versionOption(options.version).version;\n // A recursive walk reads one saved version throughout, so a save while\n // it walks cannot mix two.\n if (options.recursive === true && version === undefined) {\n const service = await serviceOf(state, options);\n const { computer } = await service.getById(computerId, signalOf(options));\n version = String(numberOf(computer.headVersion));\n }\n yield* walkDirectory(directory, version, options);\n }\n\n async function* watch(\n path = \"\",\n options: CallOptions = {},\n ): AsyncGenerator<FolderStatus, void, undefined> {\n const directory = workspacePath(path, \"the workspace\");\n const signal = options.signal ?? new AbortController().signal;\n const service = await serviceOf(state, options);\n let after = \"\";\n for (let failures = 0; ;) {\n let answer: WatchFilesResponse;\n try {\n answer = await service.watchFilesById(\n computerId,\n {\n ...(directory === \"\" ? {} : { path: directory }),\n ...(after === \"\" ? {} : { after }),\n },\n { signal },\n );\n } catch (error) {\n if (signal.aborted || !retryable(error)) throw error;\n await delay(watchRetryDelay(failures, error), signal);\n failures += 1;\n continue;\n }\n failures = 0;\n if (answer.cursor === after) continue;\n after = answer.cursor;\n yield folderStatus(answer);\n }\n }\n\n /** Whether the folder `directory` holds `name` in the saved `version`. */\n const holds = async (\n service: ComputersService,\n directory: string,\n name: string,\n version: string,\n options: CallOptions,\n ): Promise<boolean> => {\n let next: string | undefined;\n do {\n const page = await service.listFilesById(\n computerId,\n {\n path: directory,\n version,\n ...(next === undefined ? {} : { continue: next }),\n },\n signalOf(options),\n );\n if (page.items.some((entry) => entry.name === name)) return true;\n next = page.continue;\n } while (next !== undefined);\n return false;\n };\n\n return Object.freeze({\n upload,\n async createFolder(path: string, options: ChangeOptions = {}) {\n const target = workspacePath(path);\n const cut = target.lastIndexOf(\"/\");\n const parent = cut < 0 ? \"\" : target.slice(0, cut);\n const name = target.slice(cut + 1);\n const archive = folderArchive(name);\n return await change(\n options,\n async (service, operation) => {\n await service.uploadArchiveById(\n computerId,\n operation,\n { path: parent, seq: 1 },\n bytesOf(archive),\n signalOf(options),\n );\n },\n async (service, base) => {\n let taken: boolean;\n try {\n taken = await holds(service, parent, name, base, options);\n } catch (error) {\n if (!isNotFound(error)) throw error;\n throw new ApiError({\n status: 404,\n message: `folder ${parent} does not exist`,\n cause: error,\n });\n }\n if (taken) {\n throw new ApiError({\n status: 409,\n message: `${target} already exists`,\n });\n }\n },\n );\n },\n async download(path: string, options: DownloadOptions = {}) {\n const archive = options.archive === true;\n const target = workspacePath(path, archive ? \"the workspace\" : undefined);\n const version = versionOption(options.version);\n const service = await serviceOf(state, options);\n return await openDownload(service, computerId, {\n path: target,\n archive,\n ...version,\n ...signalOf(options),\n onProgress: options.onProgress,\n });\n },\n async downloadLink(path: string, options: DownloadLinkOptions = {}) {\n const target = workspacePath(path, \"the workspace\");\n const version = versionOption(options.version);\n const service = await serviceOf(state, options);\n const link = await service.createFileDownloadLinkById(\n computerId,\n { path: target, ...version },\n signalOf(options),\n );\n return Object.freeze({\n url: link.url,\n expiresAt: link.expiresAt,\n version: numberOf(link.version),\n });\n },\n list,\n watch,\n async move(from: string, to: string, options: ChangeOptions = {}) {\n const source = workspacePath(from);\n const destination = workspacePath(to);\n return await change(options, async (service, operation) => {\n await service.uploadChangesById(\n computerId,\n operation,\n {\n seq: 1,\n rename: [{ from: { path: source }, to: { path: destination } }],\n },\n signalOf(options),\n );\n });\n },\n async remove(\n paths: string | readonly string[],\n options: ChangeOptions = {},\n ) {\n const listed = (typeof paths === \"string\" ? [paths] : [...paths]).map(\n (path) => workspacePath(path),\n );\n if (listed.length === 0) throw new TypeError(\"paths must name a path\");\n return await change(options, async (service, operation) => {\n await service.uploadChangesById(\n computerId,\n operation,\n { seq: 1, delete: listed.map((path) => ({ path })) },\n signalOf(options),\n );\n });\n },\n });\n}\n\n/**\n * Holds a path to the workspace: relative, `/`-separated, with no empty,\n * `.` or `..` segment and no NUL. `root`, when given, admits the empty\n * path as the workspace itself and names it in the refusal.\n */\nfunction workspacePath(path: unknown, root?: string): string {\n if (typeof path !== \"string\") throw new TypeError(\"path must be a string\");\n if (path === \"\") {\n if (root !== undefined) return \"\";\n throw new TypeError(\"path is required\");\n }\n if (path.startsWith(\"/\")) {\n throw new TypeError(\"path must be relative to the workspace, not absolute\");\n }\n if (path.includes(\"\\0\")) throw new TypeError(\"path must not contain NUL\");\n for (const segment of path.split(\"/\")) {\n if (segment === \"\" || segment === \".\" || segment === \"..\") {\n throw new TypeError(\n \"path must stay within the workspace, with no empty, '.' or '..' segment\",\n );\n }\n }\n return path;\n}\n\n/** The size of a tar block. */\nconst BLOCK = 512;\n\n/**\n * A POSIX tar archive holding one empty directory, `name`, with\n * permission bits 0755. A name too long for the ustar name field is\n * carried by a pax extended header.\n */\nfunction folderArchive(name: string): Uint8Array {\n const encoder = new TextEncoder();\n const entry = encoder.encode(`${name}/`);\n const blocks: Uint8Array[] = [];\n if (entry.length > 100) {\n const record = paxRecord(\"path\", `${name}/`);\n blocks.push(tarHeader(encoder.encode(\"PaxHeader\"), \"x\", record.length));\n blocks.push(padded(record));\n blocks.push(tarHeader(entry.slice(0, 100), \"5\", 0));\n } else {\n blocks.push(tarHeader(entry, \"5\", 0));\n }\n blocks.push(new Uint8Array(2 * BLOCK));\n const archive = new Uint8Array(\n blocks.reduce((total, block) => total + block.length, 0),\n );\n let offset = 0;\n for (const block of blocks) {\n archive.set(block, offset);\n offset += block.length;\n }\n return archive;\n}\n\n/** One ustar header block. */\nfunction tarHeader(name: Uint8Array, type: string, size: number): Uint8Array {\n const header = new Uint8Array(BLOCK);\n const ascii = (offset: number, text: string): void => {\n for (let i = 0; i < text.length; i += 1) {\n header[offset + i] = text.charCodeAt(i);\n }\n };\n const octal = (offset: number, width: number, value: number): void => {\n ascii(offset, value.toString(8).padStart(width - 1, \"0\"));\n };\n header.set(name, 0);\n octal(100, 8, type === \"5\" ? 0o755 : 0o644);\n octal(108, 8, 0);\n octal(116, 8, 0);\n octal(124, 12, size);\n octal(136, 12, 0);\n ascii(156, type);\n ascii(257, \"ustar\\0\");\n ascii(263, \"00\");\n ascii(148, \" \".repeat(8));\n const sum = header.reduce((total, byte) => total + byte, 0);\n ascii(148, `${sum.toString(8).padStart(6, \"0\")}\\0 `);\n return header;\n}\n\n/** One pax record, `<length> <key>=<value>\\n`, its length counting itself. */\nfunction paxRecord(key: string, value: string): Uint8Array {\n const body = new TextEncoder().encode(` ${key}=${value}\\n`);\n let length = body.length + 1;\n while (String(length).length + body.length !== length) length += 1;\n const record = new Uint8Array(length);\n record.set(new TextEncoder().encode(String(length)), 0);\n record.set(body, String(length).length);\n return record;\n}\n\n/** `data` zero-padded to a whole number of blocks. */\nfunction padded(data: Uint8Array): Uint8Array {\n const block = new Uint8Array(Math.ceil(data.length / BLOCK) * BLOCK);\n block.set(data);\n return block;\n}\n\nfunction fileMode(mode: number | undefined): number {\n if (mode === undefined) return 0o644;\n if (!Number.isInteger(mode) || mode < 0 || mode > 0o7777) {\n throw new TypeError(\"mode must be permission bits from 0 to 0o7777\");\n }\n return mode;\n}\n\nfunction versionOption(version: number | string | undefined): {\n readonly version?: string;\n} {\n if (version === undefined) return {};\n if (typeof version === \"number\") {\n if (!Number.isSafeInteger(version) || version < 0) {\n throw new TypeError(\"version must be a non-negative integer or a name\");\n }\n return { version: String(version) };\n }\n if (typeof version !== \"string\" || version.trim() === \"\") {\n throw new TypeError(\"version must be a non-negative integer or a name\");\n }\n return { version };\n}\n\n/** Upload data as a stream of bytes, judged before any request. */\n/** The byte length of upload data, when it is known before it is read. */\nfunction sizeOf(data: unknown): number | undefined {\n if (typeof data === \"string\") return new TextEncoder().encode(data).length;\n if (data instanceof Uint8Array || data instanceof ArrayBuffer) {\n return data.byteLength;\n }\n if (typeof Blob !== \"undefined\" && data instanceof Blob) return data.size;\n return undefined;\n}\n\n/** One file's transfer options: the call's signal and its progress. */\nfunction transferOf(\n options: UploadOptions,\n path: string,\n data: unknown,\n): UploadRequestOptions {\n const { onProgress } = options;\n if (onProgress === undefined) return signalOf(options);\n const size = sizeOf(data);\n return {\n ...signalOf(options),\n accepted: (bytes) => {\n onProgress(\n Object.freeze({\n path,\n sent: Number(bytes),\n ...(size === undefined ? {} : { size }),\n }),\n );\n },\n };\n}\n\nfunction bytesOf(data: unknown): ReadableStream<Uint8Array> {\n if (typeof data === \"string\") return new Blob([data]).stream();\n if (data instanceof Uint8Array || data instanceof ArrayBuffer) {\n return new Blob([new Uint8Array(data)]).stream();\n }\n if (typeof Blob !== \"undefined\" && data instanceof Blob) return data.stream();\n if (data instanceof ReadableStream) {\n return data as ReadableStream<Uint8Array>;\n }\n throw new TypeError(\n \"data must be a string, bytes, a Blob or File, or a ReadableStream\",\n );\n}\n\n/** A listed entry, and whether its name addresses it. */\ninterface Listed {\n readonly entry: FileEntry;\n readonly addressable: boolean;\n}\n\n/** Bytes in standard base64, decoded as UTF-8 with replacement characters. */\nfunction decodedText(base64: string | undefined): string {\n return new TextDecoder().decode(\n Uint8Array.from(atob(base64 ?? \"\"), (c) => c.charCodeAt(0)),\n );\n}\n\n/** A reported path as text; one that is not UTF-8 has replacement characters. */\nfunction pathText(p: FilePath): string {\n return p.path ?? decodedText(p.pathBase64);\n}\n\n/**\n * A listed entry, its path joined to the directory listed. A name that is\n * not UTF-8 is shown decoded with replacement characters; it cannot\n * address the entry, so a recursive walk does not descend into it.\n */\nfunction listed(directory: string, entry: FileEntryRecord): Listed {\n const addressable = entry.name !== undefined;\n const name = entry.name ?? decodedText(entry.nameBase64);\n return {\n entry: Object.freeze({\n path: directory === \"\" ? name : `${directory}/${name}`,\n type: entry.type,\n size: numberOf(entry.size),\n mode: entry.mode,\n ...(entry.tag === undefined ? {} : { tag: entry.tag }),\n ...(entry.target === undefined ? {} : { target: entry.target }),\n ...(entry.status === undefined || entry.status === \"\"\n ? {}\n : { status: entry.status }),\n ...(entry.statusReason === undefined\n ? {}\n : { statusReason: entry.statusReason }),\n }),\n addressable,\n };\n}\n\n/** A watch answer as the public view of the folder's status. */\nfunction folderStatus({\n syncing,\n changes,\n published,\n relist,\n store,\n}: WatchFilesResponse): FolderStatus {\n return Object.freeze({\n syncing,\n changes: Object.freeze(\n changes.map((change) =>\n Object.freeze({\n path: pathText(change),\n change: change.change,\n ...(change.type === undefined || change.type === \"\"\n ? {}\n : { type: change.type }),\n ...(change.change === \"changed\" || change.size !== undefined\n ? { size: numberOf(change.size ?? 0) }\n : {}),\n ...(change.modified === undefined\n ? {}\n : { modified: change.modified }),\n status: change.status,\n ...(change.statusReason === undefined\n ? {}\n : { statusReason: change.statusReason }),\n }),\n ),\n ),\n published: Object.freeze(\n published.map(({ version, paths, more }) =>\n Object.freeze({\n version: numberOf(version),\n paths: Object.freeze(paths.map(pathText)),\n more: more === true,\n }),\n ),\n ),\n relist: relist === true,\n ...(store === undefined\n ? {}\n : {\n store: Object.freeze({\n state: store.state,\n cause: store.cause,\n since: store.since,\n waiting: numberOf(store.waiting),\n fillDone: numberOf(store.fillDone),\n fillTotal: numberOf(store.fillTotal),\n }),\n }),\n });\n}\n\n/** Whether asking a failed watch request again can change its outcome. */\nfunction retryable(error: unknown): boolean {\n if (error instanceof ApiError) {\n return error.status === 408 || error.status === 429 || error.status >= 500;\n }\n return (\n error instanceof TransportError &&\n (error.code === \"network_error\" || error.code === \"timeout\")\n );\n}\n\n/**\n * The wait before failed watch request number `failures`, counted from zero\n * since the last answer: drawn from the upper half of a bound that starts at\n * {@link FIRST_WATCH_RETRY_MS} and doubles up to {@link LAST_WATCH_RETRY_MS},\n * and raised to the `Retry-After` the refusal asked for, never past that\n * bound's ceiling.\n */\nfunction watchRetryDelay(failures: number, error: unknown): number {\n const bound = Math.min(\n FIRST_WATCH_RETRY_MS * 2 ** failures,\n LAST_WATCH_RETRY_MS,\n );\n const drawn = bound / 2 + Math.random() * (bound / 2);\n const asked = error instanceof ApiError ? (error.retryAfterMs ?? 0) : 0;\n return asked > drawn ? Math.min(asked, LAST_WATCH_RETRY_MS) : drawn;\n}\n\n/**\n * An upload that ended without publishing, as the `ApiError` a refusal of\n * it would be: status 409 and the outcome's code, or, for an upload that\n * failed for size, its reason.\n */\nfunction unpublished(upload: Upload): ApiError {\n const code =\n upload.state === \"conflict\"\n ? ERROR_CODE_UPLOAD_CONFLICT\n : upload.state === \"expired\"\n ? ERROR_CODE_UPLOAD_EXPIRED\n : upload.state === \"cancelled\"\n ? ERROR_CODE_UPLOAD_CANCELLED\n : upload.state === \"failed\" && isSaveSizeReason(upload.reason)\n ? upload.reason\n : undefined;\n return new ApiError({\n status: 409,\n ...(code === undefined ? {} : { code }),\n message: upload.reason ?? `upload ended ${upload.state}`,\n });\n}\n\n/** A transfer the platform refused, as the `ApiError` it is. */\nfunction transferFailure(error: unknown): unknown {\n if (!(error instanceof UploadTransferFailedError)) return error;\n const code = error.transfer.failure?.code;\n return new ApiError({\n status: 409,\n ...(code === undefined || code === \"\" ? {} : { code }),\n message: \"upload transfer failed\",\n cause: error,\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The Secrets a Computer can attach: each holds one value that IDYL adds to\n * the Computer's requests to the origins the Secret allows, so the value\n * never enters the Computer. A Namespace can also hold keyed Secrets, which\n * a Pod mounts as files; every read reports them too, and a Computer cannot\n * use one. The public types are built from the redacted document field by\n * field; no read carries a value.\n */\nimport type {\n ComputerSecretAttachmentStatus,\n ComputerSecretUse as ServedComputerSecretUse,\n} from \"../api/computer-secrets.js\";\nimport {\n formatVaultResourceVersionETag,\n validateVaultRotateOptions,\n VAULT_PURGE_CONFIRMATION,\n type VaultVersionMetadata,\n} from \"../api/vault.js\";\nimport { TransportError } from \"../errors.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport {\n validateRedactedSecret,\n validateSecretSpec,\n validateVaultReferenceName,\n type RedactedSecret,\n type SecretSource as SecretSourceDocument,\n type SecretEgressCredential as RedactedSecretCredential,\n type SecretKeyMetadata,\n type SecretSpec,\n} from \"../resource/secret.js\";\nimport { parseTimestamp } from \"../resource/shapes.js\";\nimport { errorMessage } from \"../resource/validation.js\";\nimport { vaultSecretsService } from \"../services/vault-secrets.js\";\nimport {\n offsetPage,\n requireLimit,\n requireText,\n signalOf,\n walk,\n type CallOptions,\n type ListOptions,\n type Page,\n type PageOptions,\n} from \"./common.js\";\nimport { decryptionOf, type Decryption } from \"./decryptions.js\";\nimport { numberOf } from \"./records.js\";\n\n/**\n * The place in a request a Secret's value fills. A placeholder anywhere\n * else in a request is sent as written.\n *\n * - `basic-password` is the password of HTTP Basic authentication, filled\n * when the whole password is the placeholder; the user name is sent as\n * written.\n * - `header` is the header `header` names, such as `PRIVATE-TOKEN`, filled\n * when its whole value is the placeholder.\n * - `authorization-token` is the token of an `Authorization` header in the\n * scheme `scheme` names: `Bearer`, as most API clients send an API key or\n * an access token, or `token`, as the GitHub CLI sends a GitHub token. It\n * is filled when the request carries exactly one `Authorization` header\n * whose value is the scheme, compared without regard to case, then one or\n * more spaces, then a token that is wholly the placeholder. A request with\n * two `Authorization` headers, another scheme, or the placeholder inside\n * a longer token is sent as written.\n */\nexport type SecretCredential =\n | { readonly type: \"basic-password\" }\n | { readonly type: \"header\"; readonly header: string }\n | {\n readonly type: \"authorization-token\";\n readonly scheme: \"Bearer\" | \"token\";\n };\n\n/**\n * Where a Secret's value comes from, as a read reports it: a stored `value`\n * of `sizeBytes` bytes, with the `expiresAt` its writer stated; a\n * `github-app` installation whose tokens IDYL mints; or, for a keyed Secret\n * that a Pod mounts as files, its `keys`. No read carries a value or the\n * App's private key.\n */\nexport type SecretSource =\n | {\n readonly type: \"value\";\n readonly sizeBytes: number;\n readonly expiresAt?: string;\n }\n | {\n readonly type: \"github-app\";\n readonly appId: number;\n readonly installationId: number;\n }\n | {\n readonly type: \"keys\";\n readonly keys: readonly SecretKey[];\n };\n\n/** One key of a keyed Secret, without its value. */\nexport interface SecretKey {\n /** The key's name, which is the file name a Pod mounts it as. */\n readonly name: string;\n /** The length of the key's value, in bytes. */\n readonly sizeBytes: number;\n}\n\n/** A Secret, as reported by every read. */\nexport interface Secret {\n /** The Secret's ID, a canonical UUID, held by a Computer's attachment. */\n readonly id: string;\n /** The Secret's name, unique within its Namespace. */\n readonly name: string;\n /** The Namespace the Secret lives in. */\n readonly namespace: string;\n /**\n * The HTTPS origins that receive the value, as they were written. Empty\n * for a keyed Secret, whose values go to no origin.\n */\n readonly origins: readonly string[];\n /**\n * The place in a request the value fills. Absent for a keyed Secret, which\n * a Computer cannot use.\n */\n readonly credential?: SecretCredential;\n /** Where the value comes from, without the value itself. */\n readonly source: SecretSource;\n /** The current version, from 1; an attachment can pin one. */\n readonly version: number;\n /**\n * The Secret's resource version, from 1, which every write advances. A\n * rotation states the one it expects, and is refused if the Secret was\n * written since.\n */\n readonly resourceVersion: number;\n /**\n * `active`, or `tombstone` once deleted. A state this package does not name\n * is carried unchanged from IDYL's report.\n */\n readonly state: string;\n /**\n * `healthy`; `expiring` within seven days of the value's expiry; `expired`;\n * or `source_failed` when a GitHub App's last token mint failed. Absent\n * when IDYL reports none.\n */\n readonly health?: string;\n /** When it was created, as an RFC 3339 instant. */\n readonly createdAt?: string;\n /** When it was last written, as an RFC 3339 instant. */\n readonly updatedAt?: string;\n}\n\n/**\n * What a version of a Secret holds: exactly one source, `value` or\n * `githubApp`, the `origins` that receive its value, and the `credential`\n * the value fills.\n */\nexport interface SecretContentOptions extends CallOptions {\n /**\n * A value to store: printable ASCII, at most 8 KiB, with no line break.\n * It is write-only: no read returns it, and it never enters a Computer.\n */\n readonly value?: string;\n /**\n * When the stored value stops being valid, as an RFC 3339 instant. The\n * Secret's health turns to `expiring` seven days before it, and a value\n * past it is never sent. Only with `value`.\n */\n readonly expiresAt?: string;\n /**\n * A GitHub App installation whose installation tokens IDYL mints as the\n * value, each lasting one hour. `privateKey` is a private key of the App\n * in the PEM form GitHub downloads; it is write-only and stays in IDYL.\n */\n readonly githubApp?: {\n readonly appId: number;\n readonly installationId: number;\n readonly privateKey: string;\n };\n /**\n * The HTTPS origins that receive the value, 1 to 16, each\n * `https://<host>`, such as `https://api.example.com`, on port 443: an\n * origin may write `:443`, and any other port is refused with `origin must\n * use port 443`, because the value is added only to requests on port 443.\n * A wildcard is the whole leftmost label, `https://*.example.com`, and covers\n * every name below that label. The value goes to no other origin, and each\n * origin can read it, so name only the API hosts that need the value.\n */\n readonly origins: readonly string[];\n /** The place in a request the value fills. */\n readonly credential: SecretCredential;\n}\n\n/** Creates a Secret, with the content of its first version. */\nexport interface CreateSecretOptions extends SecretContentOptions {\n /**\n * The Secret's name, unique within the Namespace: 1 to 63 lowercase\n * letters, digits, `.`, `_` and `-`, beginning and ending with a letter\n * or a digit.\n */\n readonly name: string;\n}\n\n/**\n * Rotates a Secret: the content of the version the rotation appends, which\n * states a source and an egress as the Secret does, and the two guards\n * every rotation carries.\n */\nexport interface RotateSecretOptions extends SecretContentOptions {\n /**\n * The {@link Secret.resourceVersion} the rotation expects, from a read of\n * the Secret. A Secret written since is not rotated, and the call\n * rejects with an `ApiError` whose code is\n * `VAULT_RESOURCE_VERSION_CONFLICT`.\n */\n readonly resourceVersion: number;\n /**\n * A key you choose, unique to this one intended rotation, such as a UUID.\n * Retrying with the same key returns the version the first attempt\n * appended rather than appending another, so a rotation whose outcome is\n * unknown can be retried safely. It has no surrounding whitespace and no\n * line break.\n */\n readonly idempotencyKey: string;\n}\n\n/**\n * Purges a Secret. A purge cannot be undone, so it states its confirmation\n * explicitly.\n */\nexport interface PurgeSecretOptions extends CallOptions {\n /** The confirmation: always the word `purge`. */\n readonly confirm: \"purge\";\n /**\n * Purges a Secret that Pods still hold. Without it, such a purge is\n * refused with an `ApiError` whose code is `VAULT_ACTIVE_BINDINGS`.\n */\n readonly force?: boolean;\n}\n\n/** The outcome of a purge. */\nexport interface SecretPurge {\n /** Whether IDYL accepted the purge. */\n readonly accepted: boolean;\n /** When the purge completed, as an RFC 3339 instant; absent until it has. */\n readonly purgedAt?: string;\n}\n\n/** Selects the versions of a Secret a read returns. */\nexport interface SecretVersionsOptions extends CallOptions {\n /**\n * The most versions to return, newest first. `undefined` takes the\n * platform's default. Must be a positive integer.\n */\n readonly limit?: number;\n}\n\n/** One stored version of a Secret. No version carries its value. */\nexport interface SecretVersion {\n /** The version number, from 1. */\n readonly version: number;\n /** Whether it is the Secret's current version. */\n readonly current: boolean;\n /** When it was written, as an RFC 3339 instant. */\n readonly createdAt?: string;\n}\n\n/**\n * The Namespace's Secrets. A Secret lives where the client's Computers\n * live, and a Computer attaches it by name or ID through its `secrets`\n * setting. Writing a Secret, and reading one, needs the permission to do so\n * on the Namespace; a refusal rejects with an `ApiError` that carries\n * IDYL's stable code, such as `VAULT_POLICY_DISABLED` where Secrets are not\n * enabled.\n *\n * @example\n * ```ts\n * await idyl.secrets.create({\n * name: \"github-token\",\n * value: process.env.GITHUB_TOKEN!,\n * origins: [\"https://api.github.com\"],\n * credential: { type: \"authorization-token\", scheme: \"Bearer\" },\n * });\n *\n * const computer = await idyl.computers.get(\"research\");\n * await computer.update({ secrets: { GITHUB_TOKEN: \"github-token\" } });\n * ```\n */\nexport interface Secrets {\n /**\n * Creates a Secret and returns it in the form a read reports. Creating the\n * same Secret again returns it; other content under a name in use is refused\n * with `VAULT_RESOURCE_VERSION_CONFLICT`. Creating a Secret under the name of\n * one deleted within seven days restores that Secret, with its ID, and the\n * Computers attached to it resume. No error message ever contains the value\n * or the key.\n *\n * @throws {@link TypeError} an option is invalid, naming the field,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the Secret, such as\n * `VAULT_RESOURCE_VERSION_CONFLICT` for other content under a name in\n * use, or `VAULT_POLICY_DISABLED`\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid Secret\n */\n create(options: CreateSecretOptions): Promise<Secret>;\n /**\n * The Secret with this name.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, before any request is sent\n * @throws {@link ApiError} the Namespace holds no Secret of this name\n * (status 404), or IDYL refuses the read\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid Secret\n */\n get(name: string, options?: CallOptions): Promise<Secret>;\n /**\n * Every Secret of the Namespace, by name, page by page. No item carries a\n * value.\n *\n * @throws {@link TypeError} `limit` is not a positive integer\n * @throws {@link ApiError} IDYL refuses the request; it carries IDYL's\n * stable code, such as `VAULT_POLICY_DISABLED`\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid Secret\n */\n list(options?: ListOptions): AsyncIterable<Secret>;\n /**\n * One page of the Namespace's Secrets, by name.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, or\n * `continue` is not one a page of this listing returned, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the request; it carries IDYL's\n * stable code, such as `VAULT_POLICY_DISABLED`\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid Secret\n */\n listPage(options?: PageOptions): Promise<Page<Secret>>;\n /**\n * Appends a version to the Secret with this name and makes it current,\n * returning the Secret. The version states a source and an egress as the\n * first did; its origins and credential may differ from the last.\n * Attachments that follow the current version send its value from their\n * next request; an attachment pinned to a version keeps its version. A\n * Secret whose source is a GitHub App mints its own tokens and keeps no\n * versions to pin.\n *\n * The rotation is conditioned on `resourceVersion` and made safe to retry\n * by `idempotencyKey`. No error message ever contains the value or the\n * key.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty or an option is invalid,\n * naming the field, before any request is sent\n * @throws {@link ApiError} IDYL refuses the rotation, such as\n * `VAULT_RESOURCE_VERSION_CONFLICT` when the Secret was written since\n * `resourceVersion`, or status 404 for a name the Namespace does not\n * hold\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid Secret\n */\n rotate(name: string, options: RotateSecretOptions): Promise<Secret>;\n /**\n * Removes the Secret with this name and every version of it, permanently.\n * Unlike `delete`, it cannot be restored, and creating a Secret of its\n * name later creates another Secret with another ID; attachments that\n * named the purged Secret read `secret_not_found`. `confirm` must be\n * `purge`.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, `confirm` is not `purge`, or\n * `force` is not a boolean, before any request is sent\n * @throws {@link ApiError} IDYL refuses the purge, such as\n * `VAULT_ACTIVE_BINDINGS` for a Secret Pods still hold without `force`\n * @throws {@link TransportError} the request does not complete\n */\n purge(name: string, options: PurgeSecretOptions): Promise<SecretPurge>;\n /**\n * The stored versions of the Secret with this name, newest first: the\n * newest `limit` of them, or the platform's default count when `limit`\n * is absent. The current version is the first.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, or `limit` is not a positive\n * integer, before any request is sent\n * @throws {@link ApiError} IDYL refuses the read, such as with status 404\n * for a name the Namespace does not hold\n * @throws {@link TransportError} the request does not complete\n */\n versions(\n name: string,\n options?: SecretVersionsOptions,\n ): Promise<readonly SecretVersion[]>;\n /**\n * Every time IDYL opened a value of the Secret with this name, newest\n * first, page by page: when, which version, the Computer or Pod it was\n * opened for, the outcome and who reported the decryption. The record names\n * the Secret by name, so it holds decryptions made before the Secret was\n * deleted and created again. No entry carries a value. It is read only\n * when asked for, never on a Computer's wake, terminal or cell.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, or `limit` is not a positive\n * integer, before any request is sent\n * @throws {@link ApiError} IDYL refuses a page's request\n * @throws {@link TransportError} a page's request does not complete, or\n * its answer is not a valid decryption\n */\n decryptions(name: string, options?: ListOptions): AsyncIterable<Decryption>;\n /**\n * One page of the record of every time IDYL opened a value of the Secret\n * with this name, newest first.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, `limit` is not a positive\n * integer, or `continue` is not one a page of this listing returned,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid decryption\n */\n decryptionsPage(\n name: string,\n options?: PageOptions,\n ): Promise<Page<Decryption>>;\n /**\n * Deletes the Secret with this name. For seven days, creating a Secret of\n * its name restores it, with its ID. To stop one Computer using a Secret,\n * detach it from that Computer instead.\n *\n * @param name - The Secret's name.\n * @throws {@link TypeError} `name` is empty, before any request is sent\n * @throws {@link ApiError} IDYL refuses the delete, such as with status\n * 404 for a name the Namespace does not hold\n * @throws {@link TransportError} the request does not complete\n */\n delete(name: string, options?: CallOptions): Promise<void>;\n}\n\n/** Builds the Secrets of the Namespace the client's context addresses. */\nexport function secrets(\n context: (options?: CallOptions) => Promise<PlacementContext>,\n): Secrets {\n const service = async (options: CallOptions | undefined) =>\n vaultSecretsService(await context(signalOf(options)));\n const listPage = async (options: PageOptions = {}): Promise<Page<Secret>> =>\n await offsetPage(\n options,\n async (page, call) => await (await service(options)).list(page, call),\n secretOf,\n );\n const decryptionsPage = async (\n name: string,\n options: PageOptions = {},\n ): Promise<Page<Decryption>> => {\n const secretName = requireText(name, \"secret name\");\n return await offsetPage(\n options,\n async (page, call) =>\n await (await service(options)).listDecryptions(secretName, page, call),\n decryptionOf,\n );\n };\n return Object.freeze({\n async create(options: CreateSecretOptions) {\n const name = requireText(options.name, \"secret name\");\n const document = {\n kind: \"Secret\",\n metadata: { name, subnet: \"\" },\n spec: specOf(options),\n };\n // Judged before the client's context is read, so a refusal arrives\n // before anything is sent.\n validateVaultReferenceName(\"metadata.name\", name);\n validateSecretSpec(document.spec);\n const served = await (\n await service(options)\n ).put(document, signalOf(options));\n return secretOf(served);\n },\n list: (options: ListOptions = {}) => walk(listPage, options),\n listPage,\n async rotate(name: string, options: RotateSecretOptions) {\n const secretName = requireText(name, \"secret name\");\n const spec = specOf(options);\n const guards = {\n idempotencyKey: idempotencyKeyOf(options.idempotencyKey),\n ifMatch: formatVaultResourceVersionETag(\n positive(options.resourceVersion, \"resourceVersion\"),\n ),\n };\n // Judged before the client's context is read, so a refusal arrives\n // before anything is sent.\n validateSecretSpec(spec);\n validateVaultRotateOptions(guards);\n const served = await (\n await service(options)\n ).rotate(secretName, { spec }, guards, signalOf(options));\n return secretOf(served);\n },\n async purge(name: string, options: PurgeSecretOptions) {\n const secretName = requireText(name, \"secret name\");\n if ((options.confirm as unknown) !== VAULT_PURGE_CONFIRMATION) {\n throw new TypeError('confirm must be \"purge\"');\n }\n if (\n options.force !== undefined &&\n typeof (options.force as unknown) !== \"boolean\"\n ) {\n throw new TypeError(\"force must be a boolean\");\n }\n const outcome = await (\n await service(options)\n ).purge(\n secretName,\n {\n confirm: VAULT_PURGE_CONFIRMATION,\n ...(options.force === true ? { force: true } : {}),\n },\n signalOf(options),\n );\n return Object.freeze({\n accepted: outcome.accepted,\n ...(outcome.purgedAt === undefined\n ? {}\n : { purgedAt: outcome.purgedAt }),\n });\n },\n async versions(name: string, options: SecretVersionsOptions = {}) {\n const secretName = requireText(name, \"secret name\");\n const limit = requireLimit(options.limit);\n const { items } = await (\n await service(options)\n ).listVersions(\n secretName,\n limit === undefined ? {} : { limit },\n signalOf(options),\n );\n return Object.freeze(items.map(versionOf));\n },\n async get(name: string, options: CallOptions = {}) {\n const secretName = requireText(name, \"secret name\");\n const served = await (\n await service(options)\n ).get(secretName, signalOf(options));\n return secretOf(served);\n },\n decryptions: (name: string, options: ListOptions = {}) => {\n const secretName = requireText(name, \"secret name\");\n return walk((page) => decryptionsPage(secretName, page), options);\n },\n decryptionsPage,\n async delete(name: string, options: CallOptions = {}) {\n const secretName = requireText(name, \"secret name\");\n await (await service(options)).delete(secretName, signalOf(options));\n },\n });\n}\n\n/** The spec of a Secret version a create or a rotation states. */\nfunction specOf(options: SecretContentOptions): SecretSpec {\n return {\n source: sourceOf(options),\n egress: {\n origins: originsOf(options.origins),\n credential: credentialOf(options.credential),\n },\n };\n}\n\n/** Judges an idempotency key before it becomes a header. */\nfunction idempotencyKeyOf(key: unknown): string {\n if (typeof key !== \"string\" || key.trim() === \"\") {\n throw new TypeError(\"idempotencyKey is required\");\n }\n if (key.trim() !== key || /[\\r\\n]/u.test(key)) {\n throw new TypeError(\n \"idempotencyKey must have no surrounding whitespace and no line break\",\n );\n }\n return key;\n}\n\nfunction sourceOf(options: SecretContentOptions): SecretSourceDocument {\n const { value, expiresAt, githubApp } = options;\n if ((value === undefined) === (githubApp === undefined)) {\n throw new TypeError(\"state exactly one of value and githubApp\");\n }\n if (githubApp !== undefined) {\n if (expiresAt !== undefined) {\n throw new TypeError(\"expiresAt is stated only with value\");\n }\n if (\n typeof (githubApp as unknown) !== \"object\" ||\n (githubApp as unknown) === null\n ) {\n throw new TypeError(\"githubApp must be an object\");\n }\n if (typeof (githubApp.privateKey as unknown) !== \"string\") {\n throw new TypeError(\"githubApp.privateKey must be a string\");\n }\n return {\n githubApp: {\n appId: positive(githubApp.appId, \"githubApp.appId\"),\n installationId: positive(\n githubApp.installationId,\n \"githubApp.installationId\",\n ),\n privateKey: githubApp.privateKey,\n },\n };\n }\n if (typeof value !== \"string\") {\n throw new TypeError(\"value must be a string\");\n }\n if (expiresAt === undefined) return { value };\n try {\n return { value, expiresAt: parseTimestamp(expiresAt) };\n } catch (cause) {\n throw new TypeError(`expiresAt: ${errorMessage(cause)}`, { cause });\n }\n}\n\nfunction positive(value: unknown, label: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n throw new TypeError(`${label} must be a positive integer`);\n }\n return value;\n}\n\nfunction originsOf(origins: unknown): string[] {\n if (!Array.isArray(origins)) {\n throw new TypeError(\"origins must be an array of origins\");\n }\n return origins.map((origin: unknown, index) => {\n if (typeof origin !== \"string\") {\n throw new TypeError(`origins[${String(index)}] must be a string`);\n }\n return origin;\n });\n}\n\nfunction credentialOf(credential: unknown): SecretCredential {\n if (typeof credential !== \"object\" || credential === null) {\n throw new TypeError(\n 'credential must be { type: \"basic-password\" }, { type: \"header\", header } or { type: \"authorization-token\", scheme }',\n );\n }\n const { type, header, scheme } = credential as {\n readonly type?: unknown;\n readonly header?: unknown;\n readonly scheme?: unknown;\n };\n if (typeof type !== \"string\") {\n throw new TypeError(\"credential.type must be a string\");\n }\n if (header !== undefined && typeof header !== \"string\") {\n throw new TypeError(\"credential.header must be a string\");\n }\n if (scheme !== undefined && typeof scheme !== \"string\") {\n throw new TypeError(\"credential.scheme must be a string\");\n }\n // Only the fields the contract names are sent. A type this package does\n // not name, a scheme it does not name, or a field where none belongs, is\n // carried for the contract's validator to refuse with its own sentence.\n return {\n type,\n ...(header === undefined ? {} : { header }),\n ...(scheme === undefined ? {} : { scheme }),\n } as SecretCredential;\n}\n\n/** The public view of a served Secret, judged as it is read. */\nfunction secretOf(served: RedactedSecret): Secret {\n try {\n validateRedactedSecret(served);\n } catch (cause) {\n throw new TransportError(\n \"invalid_response\",\n `secret response is not a valid secret: ${errorMessage(cause)}`,\n { cause },\n );\n }\n const { metadata, spec, status } = served;\n const { source, egress } = spec;\n if (metadata.id === undefined) {\n throw new TransportError(\"invalid_response\", \"secret response names no ID\");\n }\n // The validator admits a source exactly with an egress, and keys exactly\n // without either, so a Secret with no source is a keyed one.\n return Object.freeze({\n id: metadata.id,\n name: metadata.name,\n namespace: metadata.namespace ?? \"\",\n origins: Object.freeze([...(egress?.origins ?? [])]),\n ...(egress === undefined\n ? {}\n : { credential: credentialInfoOf(egress.credential) }),\n source:\n source === undefined ? keysInfoOf(spec.keys ?? []) : sourceInfoOf(source),\n version: numberOf(spec.currentVersion),\n resourceVersion: numberOf(status.resourceVersion),\n state: status.state,\n ...(status.health === undefined || status.health === \"\"\n ? {}\n : { health: status.health }),\n ...(metadata.createdAt === undefined\n ? {}\n : { createdAt: metadata.createdAt }),\n ...(metadata.updatedAt === undefined\n ? {}\n : { updatedAt: metadata.updatedAt }),\n });\n}\n\nfunction sourceInfoOf(\n source: NonNullable<RedactedSecret[\"spec\"][\"source\"]>,\n): SecretSource {\n if (source.githubApp !== undefined) {\n return Object.freeze({\n type: \"github-app\",\n appId: numberOf(source.githubApp.appId),\n installationId: numberOf(source.githubApp.installationId),\n });\n }\n const value = source.value ?? { sizeBytes: 0 };\n return Object.freeze({\n type: \"value\",\n sizeBytes: numberOf(value.sizeBytes),\n ...(value.expiresAt === undefined ? {} : { expiresAt: value.expiresAt }),\n });\n}\n\n/** The public view of a keyed Secret's keys. */\nfunction keysInfoOf(keys: readonly SecretKeyMetadata[]): SecretSource {\n return Object.freeze({\n type: \"keys\",\n keys: Object.freeze(\n keys.map((key) =>\n Object.freeze({\n name: key.name,\n sizeBytes: numberOf(key.sizeBytes ?? 0),\n }),\n ),\n ),\n });\n}\n\n/** The public view of a served credential, which the read has judged. */\nfunction credentialInfoOf(\n credential: RedactedSecretCredential,\n): SecretCredential {\n switch (credential.type) {\n case \"header\":\n return Object.freeze({\n type: \"header\",\n header: credential.header ?? \"\",\n });\n case \"authorization-token\":\n return Object.freeze({\n type: \"authorization-token\",\n scheme: credential.scheme === \"token\" ? \"token\" : \"Bearer\",\n });\n default:\n return Object.freeze({ type: \"basic-password\" });\n }\n}\n\n/** The public view of one served version. */\nfunction versionOf(version: VaultVersionMetadata): SecretVersion {\n return Object.freeze({\n version: numberOf(version.version),\n current: version.current,\n ...(version.createdAt === undefined\n ? {}\n : { createdAt: version.createdAt }),\n });\n}\n\n/**\n * The state of one Secret attachment of a Computer, judged against the\n * version the attachment uses: its current version, or the one it is\n * pinned to.\n */\nexport interface SecretAttachmentStatus {\n /** The environment variable that holds the placeholder. */\n readonly env: string;\n /** The ID of the attached Secret. */\n readonly secret: string;\n /**\n * `healthy`; `expiring`, within seven days of the value's expiry; or\n * `broken`, when the value is not sent. A health this package does not name\n * is carried unchanged from IDYL's report.\n */\n readonly health: string;\n /**\n * Why the health is not `healthy`: `expiring` with that health, and with\n * `broken` one of `secret_deleted` (deleted; creating a Secret of its\n * name within seven days restores it), `secret_not_found` (no Secret has\n * the ID), `not_attached` (it came with a fork's or a restore's settings\n * and was never attached to this Computer; attaching it again sends it),\n * `no_egress`, `expired` or `source_failed`. Absent when healthy.\n */\n readonly reason?: string;\n /**\n * When the value the attachment sends stops being valid, as an RFC 3339\n * instant; absent while none is known.\n */\n readonly expiresAt?: string;\n}\n\n/**\n * One attachment of a Secret in one Computer's settings, as read by\n * `computers.listBySecret`.\n */\nexport interface ComputerSecretUse {\n /** The ID of the Computer that holds the attachment. */\n readonly computer: string;\n /** The Computer's name. */\n readonly computerName: string;\n /** The environment variable that holds the placeholder. */\n readonly env: string;\n /**\n * Whether the attachment was attached to this Computer by someone allowed\n * to use the Secret. An attachment that came with a fork's or a restore's\n * settings and was never attached here is `false`: its value is not sent\n * until it is attached here.\n */\n readonly attached: boolean;\n /**\n * The version the attachment is pinned to; absent when it follows the\n * Secret's current version, and so receives each rotation.\n */\n readonly version?: number;\n}\n\n/** The public view of one served attachment state. */\nexport function secretAttachmentStatusOf(\n status: ComputerSecretAttachmentStatus,\n): SecretAttachmentStatus {\n return Object.freeze({\n env: status.env,\n secret: status.secret,\n health: status.health,\n ...(status.reason === undefined ? {} : { reason: status.reason }),\n ...(status.expiresAt === undefined ? {} : { expiresAt: status.expiresAt }),\n });\n}\n\n/** The public view of one served attachment of a Secret. */\nexport function computerSecretUseOf(\n use: ServedComputerSecretUse,\n): ComputerSecretUse {\n return Object.freeze({\n computer: use.computer,\n computerName: use.computerName,\n env: use.env,\n attached: use.attached,\n ...(use.version === undefined ? {} : { version: numberOf(use.version) }),\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * A Computer's settings as callers state them, in the plain spellings the\n * product uses, and their translation into the contract's create spec and\n * update request. Every field is judged before any request and a refusal\n * names it.\n */\nimport {\n validateUpdateComputerRequest,\n type UpdateComputerRequest,\n} from \"../api/computer.js\";\nimport {\n validateComputerSpec,\n type ComputerSpec,\n} from \"../resource/computer.js\";\nimport type {\n ComputerEnvironmentVariable,\n ComputerSecretAttachment,\n} from \"../resource/computer-execution-settings.js\";\nimport { isResourceId } from \"../resource/uuid-id.js\";\nimport type { WorkloadNetwork } from \"../resource/workload-network.js\";\nimport { decodeCpu } from \"../resource/cpu.js\";\nimport { parseDuration } from \"../resource/duration.js\";\nimport { parseIdleTimeout } from \"../resource/idle-timeout.js\";\nimport { decodeMemory } from \"../resource/memory.js\";\nimport { errorMessage } from \"../resource/validation.js\";\nimport { clientOf, type CallOptions } from \"./common.js\";\n\n/**\n * A Secret a Computer attaches: `secret` is its name or its ID, and\n * `version` pins one stored version, from 1; without it the attachment\n * follows the Secret's current version. A Secret whose source is a GitHub\n * App has no versions to pin.\n */\nexport interface SecretAttachment {\n /** The Secret's name or its ID. */\n readonly secret: string;\n /** The stored version to pin, from 1; absent to follow the current version. */\n readonly version?: number;\n}\n\n/** The settings a create may state; each one left out takes IDYL's default. */\nexport interface ComputerSettingsOptions {\n /**\n * The image: a catalogue name such as `ubuntu-24.04` (see\n * `idyl.computers.images()`), or the reference of your own public image\n * such as `ghcr.io/example/toolbox:1.4`. A value with `/`, `:` or `@` is\n * a reference; a catalogue name never has one.\n */\n readonly image?: string;\n /**\n * How the Computer is isolated: `secure-container` (the default), a\n * container behind an application kernel, or `vm`, a whole Linux machine\n * you administer. `idyl.computers.images({ isolation })` lists the images\n * of a class, and is empty for a class that is not offered. An\n * `update` can change it later.\n */\n readonly isolation?: \"secure-container\" | \"vm\";\n /**\n * The size by name, such as `small`, which sets its CPU, memory and disk.\n * `idyl.computers.sizes()` lists the sizes. It is never stated with `cpu` or\n * `memory`.\n */\n readonly size?: string;\n /** The CPU limit, such as `500m` or `2`. */\n readonly cpu?: string;\n /** The memory limit, such as `512Mi` or `4Gi`. */\n readonly memory?: string;\n /**\n * The network class: `internet` (the default: the open internet, local\n * networks blocked), `none`, or `restricted-egress`.\n */\n readonly network?: string;\n /**\n * What a `restricted-egress` network allows: `dns` for name lookups, and\n * `<tcp|udp>:<port>:<destination>` for each destination, where a destination\n * is a hostname, a wildcard such as `*.example.com`, an IPv4 address or an\n * IPv4 range, such as `tcp:443:pypi.org`. Only with\n * `network: \"restricted-egress\"`; without it, such a network reaches\n * nothing.\n */\n readonly allow?: readonly string[];\n /** Environment variables every process starts with. */\n readonly env?: Readonly<Record<string, string>>;\n /**\n * The Secrets the Computer uses without holding them, by the environment\n * variable each is attached under: a Secret's name or ID, or a\n * {@link SecretAttachment}. A canonical UUID is read as an ID, anything\n * else as a name, which IDYL resolves once, among the Secrets of the\n * Computer's Namespace, and keeps as the ID. The variable holds a\n * placeholder, and IDYL puts the Secret's value in its place in the\n * Computer's requests to the origins the Secret allows. A variable is\n * never both in `env` and here. On a `restricted-egress` network, `allow`\n * must already reach each of the Secret's origins.\n */\n readonly secrets?: Readonly<Record<string, string | SecretAttachment>>;\n /**\n * The default shell its terminals run, an absolute path in the image\n * such as `/usr/bin/zsh`. When absent, a terminal runs `/bin/bash` when\n * the image has it and `/bin/sh` otherwise. A terminal whose shell the\n * image does not have ends at once with the ending `shell_not_found`.\n */\n readonly shell?: string;\n /**\n * How long the Computer keeps running after its last command or\n * terminal ends: `never`, or a whole number followed by `s`, `m` or `h`.\n */\n readonly idleTimeout?: string;\n /** Whether the Computer saves its files on its own. `true` by default. */\n readonly autoSave?: boolean;\n /** How long writes must be quiet before an automatic save, from `1s` to `10m`. */\n readonly saveQuiet?: string;\n /** The longest time between saves while writes continue, from `10s` to `1h`. */\n readonly saveMaxInterval?: string;\n}\n\n/**\n * Updates a Computer field by field; a field left out keeps its value. A\n * change of the execution settings (everything but `name`, `idleTimeout`\n * and the save settings) applies from the Computer's next start.\n */\nexport interface UpdateComputerOptions extends CallOptions {\n /**\n * The kind of client making the change, recorded with a change of the\n * execution settings in the Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Renames the Computer. The old name is free at once and stops reaching\n * it, while its ID, files, history and running commands stay as they are.\n */\n readonly name?: string;\n /** The image, as on create. */\n readonly image?: string;\n /**\n * Moves the Computer to another isolation class, `secure-container` or\n * `vm`, from its next start; its files under `/workspace` carry over.\n * Each image serves one class: without `image`, the Computer takes the\n * default image of the class it moves to, and an `image` stated beside\n * it must be one of that class (`idyl.computers.images({ isolation })`).\n * A class not offered where the Computer lives is refused with\n * `ERROR_CODE_ISOLATION_CLASS_NOT_ADMITTED`.\n */\n readonly isolation?: \"secure-container\" | \"vm\";\n /**\n * The size by name, as on create, which replaces the CPU and memory\n * together; never stated with `cpu` or `memory`.\n */\n readonly size?: string;\n /** The CPU limit, such as `500m` or `2`; `null` returns to IDYL's default. */\n readonly cpu?: string | null;\n /** The memory limit, such as `512Mi` or `4Gi`; `null` returns to IDYL's default. */\n readonly memory?: string | null;\n /**\n * The network class, as on create; `null` returns to IDYL's default,\n * `internet`.\n */\n readonly network?: string | null;\n /**\n * What a `restricted-egress` network allows, as on create; it is stated\n * with `network: \"restricted-egress\"` and replaces the whole list.\n */\n readonly allow?: readonly string[];\n /**\n * Environment variables to set, by name; an entry set to `null` removes\n * that variable, and variables left out keep their values.\n */\n readonly env?: Readonly<Record<string, string | null>>;\n /**\n * Attaches Secrets, as on create, by variable; an entry set to `null`\n * detaches the Secret attached under that variable. The others keep their\n * attachments.\n */\n readonly secrets?: Readonly<Record<string, string | SecretAttachment | null>>;\n /**\n * The default shell, as on create; `null` returns to `/bin/bash` when the\n * image has it and `/bin/sh` otherwise. Unlike the other execution\n * settings, an update of it applies from the next terminal and needs no\n * start.\n */\n readonly shell?: string | null;\n /**\n * How long the Computer keeps running after its last command or\n * terminal ends, as on create; it takes effect at once.\n */\n readonly idleTimeout?: string;\n /** Whether the Computer saves its files on its own; it takes effect at once. */\n readonly autoSave?: boolean;\n /** How long writes must be quiet before an automatic save, from `1s` to `10m`. */\n readonly saveQuiet?: string;\n /** The longest time between saves while writes continue, from `10s` to `1h`. */\n readonly saveMaxInterval?: string;\n}\n\n/** The create spec the options state. */\nexport function settingsRequest(\n options: ComputerSettingsOptions,\n): ComputerSpec {\n const execution = {\n ...field(\"image\", options.image, image),\n ...field(\"size\", options.size, text),\n ...field(\"cpu\", options.cpu, (cpu) => decodeCpu(text(cpu))),\n ...field(\"memory\", options.memory, (memory) => decodeMemory(text(memory))),\n ...field(\"isolation\", options.isolation, text),\n ...networkField(options.network, options.allow),\n ...(options.env === undefined\n ? {}\n : { variables: variables(\"env\", options.env) }),\n ...(options.secrets === undefined\n ? {}\n : { secrets: attachments(objectOf(\"secrets\", options.secrets)) }),\n ...field(\"shell\", options.shell, text),\n };\n const spec: ComputerSpec = {\n ...(Object.keys(execution).length === 0 ? {} : { execution }),\n ...saveSettings(options),\n };\n judged(() => {\n validateComputerSpec(spec);\n });\n return spec;\n}\n\n/** The update request the options state. */\nexport function updateRequest(\n options: UpdateComputerOptions,\n): UpdateComputerRequest {\n const set: Record<string, string> = {};\n const remove: string[] = [];\n for (const [name, value] of Object.entries(options.env ?? {})) {\n if (value === null) remove.push(name);\n else set[name] = value;\n }\n const attach: Record<string, unknown> = {};\n const detach: string[] = [];\n for (const [name, value] of Object.entries(\n objectOf(\"secrets\", options.secrets ?? {}),\n )) {\n if (value === null) detach.push(name);\n else attach[name] = value;\n }\n const request: UpdateComputerRequest = {\n ...field(\"name\", options.name, text),\n ...field(\"image\", options.image, image),\n ...field(\"isolation\", options.isolation, text),\n ...field(\"size\", options.size, text),\n ...nullable(\"cpu\", options.cpu, (cpu) => decodeCpu(text(cpu))),\n ...nullable(\"memory\", options.memory, (memory) =>\n decodeMemory(text(memory)),\n ),\n ...(options.network === null && options.allow === undefined\n ? { network: null }\n : networkField(options.network ?? undefined, options.allow)),\n ...(Object.keys(set).length === 0\n ? {}\n : { setVariables: variables(\"env\", set) }),\n ...(remove.length === 0 ? {} : { removeVariables: remove }),\n ...(Object.keys(attach).length === 0\n ? {}\n : { setSecrets: attachments(attach) }),\n ...(detach.length === 0 ? {} : { removeSecrets: detach }),\n ...nullable(\"shell\", options.shell, text),\n ...saveSettings(options),\n };\n if (Object.keys(request).length === 0) {\n throw new TypeError(\"update states no field\");\n }\n const stated: UpdateComputerRequest = {\n ...request,\n client: clientOf(options.client),\n };\n judged(() => {\n validateUpdateComputerRequest(stated);\n });\n return stated;\n}\n\n/** The idle timeout and save settings the options state. */\nfunction saveSettings(\n options: Pick<\n ComputerSettingsOptions,\n \"idleTimeout\" | \"autoSave\" | \"saveQuiet\" | \"saveMaxInterval\"\n >,\n): ComputerSpec {\n if (options.autoSave !== undefined && typeof options.autoSave !== \"boolean\") {\n throw new TypeError(\"autoSave must be a boolean\");\n }\n return {\n ...field(\"idleTimeout\", options.idleTimeout, (timeout) =>\n parseIdleTimeout(text(timeout)),\n ),\n ...(options.autoSave === undefined ? {} : { autoSave: options.autoSave }),\n ...field(\"saveQuiet\", options.saveQuiet, (quiet) =>\n parseDuration(text(quiet)),\n ),\n ...field(\"saveMaxInterval\", options.saveMaxInterval, (interval) =>\n parseDuration(text(interval)),\n ),\n };\n}\n\n/**\n * `{ [key]: parse(value) }` when `value` is stated, and nothing otherwise.\n * A refusal is a `TypeError` naming the field.\n */\nfunction field<K extends string, T>(\n key: K,\n value: unknown,\n parse: (value: unknown) => T,\n): Readonly<Partial<Record<K, T>>> {\n if (value === undefined) return {} as Readonly<Partial<Record<K, T>>>;\n try {\n return { [key]: parse(value) } as Readonly<Partial<Record<K, T>>>;\n } catch (cause) {\n throw new TypeError(`${key}: ${errorMessage(cause)}`, { cause });\n }\n}\n\n/** As {@link field}, with `null` returning the setting to its default. */\nfunction nullable<K extends string, T>(\n key: K,\n value: unknown,\n parse: (value: unknown) => T,\n): Readonly<Partial<Record<K, T | null>>> {\n if (value === null)\n return { [key]: null } as Readonly<Partial<Record<K, null>>>;\n return field(key, value, parse);\n}\n\n/**\n * An image as stated: a reference when it has `/`, `:` or `@`, which a\n * catalogue name never has, and a catalogue name otherwise.\n */\nfunction image(value: unknown): { idyl: string } | { ref: string } {\n const stated = text(value);\n return /[/:@]/u.test(stated) ? { ref: stated } : { idyl: stated };\n}\n\n/**\n * The network block the class and allow list state. An allow list belongs\n * to a `restricted-egress` network and is refused with any other class or\n * none; local networks stay denied while it is set.\n */\nfunction networkField(\n network: unknown,\n allow: unknown,\n): { network?: WorkloadNetwork } {\n if (allow === undefined) {\n return field(\"network\", network, (value) => ({ class: text(value) }));\n }\n if (network !== \"restricted-egress\") {\n throw new TypeError(\n 'allow: only a network of class \"restricted-egress\" has an allow list; state network: \"restricted-egress\" with it',\n );\n }\n if (!Array.isArray(allow)) {\n throw new TypeError(\"allow: must be an array of rules\");\n }\n const rules = allow.map((rule, index) => {\n if (typeof rule !== \"string\") {\n throw new TypeError(`allow[${String(index)}]: must be a string`);\n }\n return rule;\n });\n return {\n network: {\n class: \"restricted-egress\",\n ...(rules.length === 0\n ? {}\n : { egress: { allow: rules, denyLocalNetworks: true } }),\n },\n };\n}\n\nfunction text(value: unknown): string {\n if (typeof value !== \"string\") throw new TypeError(\"must be a string\");\n return value;\n}\n\n/** Environment variables in the order stated, each judged by the contract. */\nfunction variables(\n key: string,\n env: Readonly<Record<string, unknown>>,\n): ComputerEnvironmentVariable[] {\n if (typeof env !== \"object\" || Array.isArray(env)) {\n throw new TypeError(`${key} must be an object of names and values`);\n }\n return Object.entries(env).map(([name, value]) => {\n if (typeof value !== \"string\") {\n throw new TypeError(`${key}.${name} must be a string`);\n }\n return { name, value };\n });\n}\n\nfunction objectOf(\n key: string,\n value: unknown,\n): Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${key} must be an object of variables`);\n }\n return value as Readonly<Record<string, unknown>>;\n}\n\n/**\n * Secret attachments in the order stated. A canonical UUID names a Secret\n * by ID and anything else by name; the contract's validator judges each.\n */\nfunction attachments(\n stated: Readonly<Record<string, unknown>>,\n): ComputerSecretAttachment[] {\n return Object.entries(stated).map(([env, value]) => {\n const attachment: unknown =\n typeof value === \"string\" ? { secret: value } : value;\n if (typeof attachment !== \"object\" || attachment === null) {\n throw new TypeError(\n `secrets.${env} must be a Secret name or ID, or { secret, version }`,\n );\n }\n const { secret, version } = attachment as {\n readonly secret?: unknown;\n readonly version?: unknown;\n };\n if (typeof secret !== \"string\") {\n throw new TypeError(`secrets.${env}.secret must be a string`);\n }\n if (\n version !== undefined &&\n (typeof version !== \"number\" ||\n !Number.isSafeInteger(version) ||\n version < 1)\n ) {\n throw new TypeError(`secrets.${env}.version must be a positive integer`);\n }\n return {\n env,\n secret: {\n ...(isResourceId(secret) ? { id: secret } : { name: secret }),\n ...(version === undefined ? {} : { version }),\n },\n };\n });\n}\n\n/**\n * Runs the contract's own judgement of settings before any request, so a\n * refusal arrives before anything is read or sent, worded for a Computer.\n */\nfunction judged(check: () => void): void {\n try {\n check();\n } catch (error) {\n if (!(error instanceof TypeError)) throw error;\n throw new TypeError(\n error.message\n .replace(/^computer spec\\.(?:execution\\.)?/u, \"\")\n .replaceAll(\"a Micropod\", \"a Computer\")\n .replace(\", unrestricted)\", \")\")\n .replaceAll(\"the Micropod network profile\", \"a Computer's network\"),\n { cause: error },\n );\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport { decodeBase64, encodeBase64 } from \"../resource/base64.js\";\n\n/**\n * The one SSH host key algorithm a session endpoint uses, and the type name\n * OpenSSH writes before the key.\n */\nconst HOST_KEY_TYPE = \"ssh-ed25519\";\n\n/** The bytes of {@link HOST_KEY_TYPE}, as the key's wire encoding names it. */\nconst HOST_KEY_TYPE_BYTES = new TextEncoder().encode(HOST_KEY_TYPE);\n\n/** The length of an Ed25519 public key, in bytes. */\nconst ED25519_PUBLIC_KEY_BYTES = 32;\n\n/**\n * Judges an endpoint's SSH host key as the `opened` frame of an `ssh`\n * session stream carries it: exactly one OpenSSH public key line,\n * `ssh-ed25519 ` followed by the standard base64, with padding, of the key\n * in SSH's wire encoding (the string `ssh-ed25519`, then the 32-byte\n * Ed25519 public key, each with its four-byte big-endian length), and\n * nothing else: no comment, no other whitespace and no line ending. The\n * base64 must be the one canonical spelling of those 51 bytes: its\n * re-encoding must equal it byte for byte, so no character carries stray\n * bits and no carriage return or line feed hides inside it. The type name\n * inside the wire encoding is compared byte for byte, so no byte-order mark\n * or other byte precedes it. The refusal names the rule and never repeats\n * the line. Throws a `TypeError`.\n */\nexport function validateComputerSessionHostKey(line: string): void {\n const prefix = `${HOST_KEY_TYPE} `;\n if (!line.startsWith(prefix)) {\n throw new TypeError(\"a host key is an ssh-ed25519 public key line\");\n }\n const encoded = line.slice(prefix.length);\n let blob: Uint8Array;\n try {\n blob = decodeBase64(encoded);\n } catch (cause) {\n throw new TypeError(\"a host key's key is canonical standard base64\", {\n cause,\n });\n }\n if (encodeBase64(blob) !== encoded) {\n throw new TypeError(\"a host key's key is canonical standard base64\");\n }\n const name = cutSshString(blob, 0);\n if (name === undefined || !sameBytes(name.value, HOST_KEY_TYPE_BYTES)) {\n throw new TypeError(\"a host key's key names ssh-ed25519\");\n }\n const key = cutSshString(blob, name.next);\n if (\n key?.value.byteLength !== ED25519_PUBLIC_KEY_BYTES ||\n key.next !== blob.byteLength\n ) {\n throw new TypeError(\n `a host key's key is one ${String(ED25519_PUBLIC_KEY_BYTES)}-byte Ed25519 public key and nothing else`,\n );\n }\n}\n\n/** Whether `a` and `b` hold the same bytes. */\nfunction sameBytes(a: Uint8Array, b: Uint8Array): boolean {\n return a.byteLength === b.byteLength && a.every((byte, at) => byte === b[at]);\n}\n\n/**\n * Reads one SSH wire string, a four-byte big-endian length and that many\n * bytes, at `offset` of `blob`: its bytes and the offset after it, or\n * `undefined` when `blob` holds less than it declares.\n */\nfunction cutSshString(\n blob: Uint8Array,\n offset: number,\n): { readonly value: Uint8Array; readonly next: number } | undefined {\n if (blob.byteLength - offset < 4) return undefined;\n const length = new DataView(\n blob.buffer,\n blob.byteOffset + offset,\n 4,\n ).getUint32(0);\n const start = offset + 4;\n if (length > blob.byteLength - start) return undefined;\n return { value: blob.subarray(start, start + length), next: start + length };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// `workload-session/json-v2`: the frames of one session stream on a\n// Computer connection, as the reference contract defines them. A frame is a\n// big-endian uint32 length, then that many bytes of JSON whose first member\n// names the frame's type. Byte fields are standard base64. A client encodes\n// its frames in the published member order and reads the endpoint's\n// frames leniently: an unknown member is ignored, and a frame of an unknown\n// type is returned as such for the caller to judge.\n\nimport { validateComputerSessionHostKey } from \"../api/computer-session-host-key.js\";\nimport { decodeBase64, encodeBase64 } from \"../resource/base64.js\";\n\n/** The profile every `open` names. */\nexport const SESSION_STREAM_PROFILE = \"workload-session/json-v2\";\n/** The largest frame on a session stream, in bytes. */\nexport const MAX_FRAME_BYTES = 64 << 10;\n/** The largest payload of one stdin, stdout or stderr frame, in bytes. */\nexport const MAX_DATA_BYTES = 32 << 10;\n\n/**\n * The additions a client asks for in `open.features`: `save-result`, the\n * save that covers an exec, after its exit; `reattach`, a session that\n * survives the loss of its stream; and `raw-after-opened`, raw bytes in\n * both directions from the byte after `opened`, the one feature of an `ssh`\n * stream, which no other mode takes.\n */\nexport type SessionFeature = \"save-result\" | \"reattach\" | \"raw-after-opened\";\n\n/**\n * What a session stream runs. An `ssh` stream carries one SSH connection:\n * its `opened` frame is the last frame in either direction, and from the\n * byte after it both directions carry raw SSH bytes.\n */\nexport type SessionMode = \"shell\" | \"exec\" | \"reattach\" | \"files\" | \"ssh\";\n\n/**\n * A terminal's size in character cells: `cols` and `rows` are whole\n * numbers from 1 to 10000 each.\n */\nexport interface TerminalSize {\n /** The width, in character cells. */\n readonly cols: number;\n /** The height, in character cells. */\n readonly rows: number;\n}\n\n/** A session stream's first frame. */\nexport interface OpenFrame {\n readonly requestID: string;\n readonly mode: SessionMode;\n readonly shell?: string;\n readonly command?: readonly string[];\n readonly tty: boolean;\n readonly size?: TerminalSize;\n readonly term?: string;\n readonly locale?: string;\n readonly session?: string;\n readonly cursor?: number;\n readonly features?: readonly SessionFeature[];\n}\n\n/** A frame the client sends. */\nexport type ClientFrame =\n | ({ readonly type: \"open\" } & OpenFrame)\n | { readonly type: \"stdin\"; readonly data: Uint8Array }\n | { readonly type: \"resize\"; readonly size: TerminalSize }\n | { readonly type: \"close_input\" }\n | { readonly type: \"end\" }\n | { readonly type: \"watch\"; readonly path: string }\n | { readonly type: \"unwatch\"; readonly path: string };\n\n/**\n * What a folder entry is: `file`, `dir`, `symlink`, or `other` (a fifo, a\n * socket or a device). The union is open: an endpoint may name a newer\n * type, which a reader shows as it would `other`.\n */\nexport type FolderEntryType =\n \"file\" | \"dir\" | \"symlink\" | \"other\" | (string & Record<never, never>);\n\n/** One entry of a folder on a Computer's live disk. */\nexport interface FolderEntry {\n /** The entry's name within its folder. */\n readonly name: string;\n /** What the entry is: a file, a folder, a symlink or another kind. */\n readonly type: FolderEntryType;\n /** The size in bytes; 0 for a folder. */\n readonly size: number;\n /** The permission bits (`st_mode & 0o7777`). */\n readonly mode: number;\n /** The modification time, in milliseconds since the Unix epoch. */\n readonly modified: number;\n /** Where a symlink points, as stored; only a symlink has one. */\n readonly target?: string;\n}\n\n/**\n * Why a watched folder could not be listed: `not_found` (it is missing or\n * was removed or moved away; it stays watched and is listed again if it\n * reappears), `not_folder` (the path names a file, a symlink or another\n * entry), `denied` (the Computer's user cannot read it), `too_many` (the\n * stream already watches the most folders it may; the watch was not\n * taken). The union is open for later reasons.\n */\nexport type FolderProblem =\n | \"not_found\"\n | \"not_folder\"\n | \"denied\"\n | \"too_many\"\n | (string & Record<never, never>);\n\n/** A frame the endpoint sends, as read. */\nexport type EndpointFrame =\n | {\n readonly type: \"opened\";\n readonly session: string;\n readonly shell?: string;\n readonly cursor?: number;\n readonly dropped?: boolean;\n /**\n * The SSH host key of the endpoint serving an `ssh` stream, one\n * `ssh-ed25519 <base64>` line; only an `ssh` stream's `opened`\n * carries one, and it always does.\n */\n readonly hostKey?: string;\n }\n | { readonly type: \"stdout\" | \"stderr\"; readonly data: Uint8Array }\n | { readonly type: \"exit\"; readonly code?: number; readonly signal?: string }\n | {\n readonly type: \"saved\";\n readonly outcome: string;\n readonly revision?: number;\n readonly reason?: string;\n }\n | { readonly type: \"error\"; readonly code: string; readonly message?: string }\n | {\n readonly type: \"listing\";\n /** The folder, relative to `/workspace`; `\"\"` is the root. */\n readonly path: string;\n /** This frame's entries, ordered by name in byte order. */\n readonly entries: readonly FolderEntry[];\n /** Whether more frames of the same pass follow. */\n readonly more: boolean;\n readonly problem?: FolderProblem;\n /** Present and true when the folder holds more entries than a pass lists. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"unknown\"; readonly frameType: string };\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** The JSON text of `frame`, members in the published order. */\nexport function frameJson(frame: ClientFrame): string {\n switch (frame.type) {\n case \"open\": {\n const o: Record<string, unknown> = {\n type: \"open\",\n profile: SESSION_STREAM_PROFILE,\n requestID: frame.requestID,\n mode: frame.mode,\n };\n if (frame.shell !== undefined) o[\"shell\"] = frame.shell;\n if (frame.command !== undefined && frame.command.length > 0) {\n o[\"command\"] = frame.command;\n }\n o[\"tty\"] = frame.tty;\n if (frame.size !== undefined) {\n o[\"size\"] = { cols: frame.size.cols, rows: frame.size.rows };\n }\n if (frame.term !== undefined) o[\"term\"] = frame.term;\n if (frame.locale !== undefined) o[\"locale\"] = frame.locale;\n if (frame.session !== undefined) o[\"session\"] = frame.session;\n if (frame.cursor !== undefined) o[\"cursor\"] = frame.cursor;\n if (frame.features !== undefined && frame.features.length > 0) {\n o[\"features\"] = frame.features;\n }\n return JSON.stringify(o);\n }\n case \"stdin\":\n return JSON.stringify({ type: \"stdin\", data: encodeBase64(frame.data) });\n case \"resize\":\n return JSON.stringify({\n type: \"resize\",\n size: { cols: frame.size.cols, rows: frame.size.rows },\n });\n case \"close_input\":\n case \"end\":\n return JSON.stringify({ type: frame.type });\n case \"watch\":\n case \"unwatch\":\n return JSON.stringify({ type: frame.type, path: frame.path });\n }\n}\n\n/**\n * The bytes of `frame` on the stream: its length, then its JSON. Throws a\n * `RangeError` for a frame larger than {@link MAX_FRAME_BYTES}.\n */\nexport function encodeFrame(frame: ClientFrame): Uint8Array {\n const body = encoder.encode(frameJson(frame));\n if (body.length > MAX_FRAME_BYTES) {\n throw new RangeError(\"session frame exceeds the frame size limit\");\n }\n const out = new Uint8Array(4 + body.length);\n new DataView(out.buffer).setUint32(0, body.length);\n out.set(body, 4);\n return out;\n}\n\n/** Frames of stdin for `data`, each within {@link MAX_DATA_BYTES}. */\nexport function stdinFrames(data: Uint8Array): Uint8Array[] {\n const frames: Uint8Array[] = [];\n for (let at = 0; at < data.length; at += MAX_DATA_BYTES) {\n frames.push(\n encodeFrame({\n type: \"stdin\",\n data: data.subarray(at, at + MAX_DATA_BYTES),\n }),\n );\n }\n return frames;\n}\n\n/**\n * A session frame that cannot be read: one longer than the frame bound, not\n * UTF-8 JSON, not an object, or with a field of the wrong form. The stream it\n * arrived on ends, and the session's `output` fails with the same error. The\n * message is a fixed sentence naming the rule; it never carries the frame's\n * bytes.\n */\nexport class FrameError extends Error {\n /**\n * Builds the error. The package builds every `FrameError` a session's\n * output errors with.\n *\n * @param message a fixed sentence naming the rule the frame breaks\n * @param options `cause`, the underlying failure, when there is one\n */\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"FrameError\";\n }\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction integer(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isSafeInteger(value)\n ? value\n : undefined;\n}\n\nfunction bytes(value: unknown): Uint8Array {\n if (typeof value !== \"string\") {\n throw new FrameError(\"session frame data is not base64 text\");\n }\n try {\n return decodeBase64(value);\n } catch (cause) {\n throw new FrameError(\"session frame data is not base64 text\", { cause });\n }\n}\n\n/** Reads one entry of a `listing` frame. An entry must be an object. */\nfunction folderEntry(value: unknown): FolderEntry {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new FrameError(\"session frame listing entry is not an object\");\n }\n const e = value as Record<string, unknown>;\n const target = text(e[\"target\"]);\n return {\n name: text(e[\"name\"]) ?? \"\",\n type: text(e[\"type\"]) ?? \"\",\n size: integer(e[\"size\"]) ?? 0,\n mode: integer(e[\"mode\"]) ?? 0,\n modified: integer(e[\"modified\"]) ?? 0,\n ...(target === undefined ? {} : { target }),\n };\n}\n\n/** An `opened` frame, as read. */\nexport type OpenedFrame = Extract<EndpointFrame, { readonly type: \"opened\" }>;\n\n/**\n * Judges an `opened` frame as the answer to an open of `mode`: an `ssh`\n * stream's carries its session and host key and nothing else, and every\n * other mode's carries no host key. Throws a `TypeError`.\n */\nexport function validateOpenedFor(\n opened: OpenedFrame,\n mode: SessionMode,\n): void {\n if (mode !== \"ssh\") {\n if (opened.hostKey !== undefined) {\n throw new TypeError(\"only an ssh stream's opened carries a host key\");\n }\n return;\n }\n if (opened.hostKey === undefined) {\n throw new TypeError(\"an ssh stream's opened carries its host key\");\n }\n if (\n opened.shell !== undefined ||\n opened.cursor !== undefined ||\n opened.dropped !== undefined\n ) {\n throw new TypeError(\n \"an ssh stream's opened carries its session and host key alone\",\n );\n }\n}\n\n/**\n * Reads one endpoint frame from its JSON text, leniently. A host key an\n * `opened` frame carries must be text, absent or null when there is none,\n * and one `ssh-ed25519` public key line, as `validateComputerSessionHostKey`\n * judges it.\n */\nexport function readFrame(json: string): EndpointFrame {\n let value: unknown;\n try {\n value = JSON.parse(json);\n } catch (cause) {\n throw new FrameError(\"session frame is not JSON\", { cause });\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new FrameError(\"session frame is not an object\");\n }\n const f = value as Record<string, unknown>;\n const type = text(f[\"type\"]) ?? \"\";\n switch (type) {\n case \"opened\": {\n const shell = text(f[\"shell\"]);\n const cursor = integer(f[\"cursor\"]);\n const member = f[\"hostKey\"];\n if (\n member !== undefined &&\n member !== null &&\n typeof member !== \"string\"\n ) {\n throw new FrameError(\"session frame host key is not text\");\n }\n const hostKey = member ?? \"\";\n if (hostKey !== \"\") {\n try {\n validateComputerSessionHostKey(hostKey);\n } catch (cause) {\n throw new FrameError(\n \"session frame host key is not one ssh-ed25519 public key line\",\n { cause },\n );\n }\n }\n return {\n type,\n session: text(f[\"session\"]) ?? \"\",\n ...(shell === undefined ? {} : { shell }),\n ...(cursor === undefined ? {} : { cursor }),\n ...(f[\"dropped\"] === true ? { dropped: true } : {}),\n ...(hostKey === \"\" ? {} : { hostKey }),\n };\n }\n case \"stdout\":\n case \"stderr\":\n return { type, data: bytes(f[\"data\"]) };\n case \"exit\": {\n const code = integer(f[\"code\"]);\n const signal = text(f[\"signal\"]);\n return {\n type,\n ...(code === undefined ? {} : { code }),\n ...(signal === undefined ? {} : { signal }),\n };\n }\n case \"saved\": {\n const revision = integer(f[\"revision\"]);\n const reason = text(f[\"reason\"]);\n return {\n type,\n outcome: text(f[\"outcome\"]) ?? \"\",\n ...(revision === undefined ? {} : { revision }),\n ...(reason === undefined ? {} : { reason }),\n };\n }\n case \"error\": {\n const message = text(f[\"message\"]);\n return {\n type,\n code: text(f[\"code\"]) ?? \"\",\n ...(message === undefined ? {} : { message }),\n };\n }\n case \"listing\": {\n const problem = text(f[\"problem\"]);\n return {\n type,\n path: text(f[\"path\"]) ?? \"\",\n entries: Array.isArray(f[\"entries\"])\n ? f[\"entries\"].map(folderEntry)\n : [],\n more: f[\"more\"] === true,\n ...(problem === undefined || problem === \"\" ? {} : { problem }),\n ...(f[\"truncated\"] === true ? { truncated: true } : {}),\n };\n }\n default:\n return { type: \"unknown\", frameType: type };\n }\n}\n\n/**\n * Splits a session stream's bytes into frames as they arrive. A frame that\n * declares more than {@link MAX_FRAME_BYTES} is refused before it is\n * buffered.\n */\nexport class FrameReader {\n #buffer = new Uint8Array(0);\n\n /** Takes in bytes and returns every complete frame. */\n push(chunk: Uint8Array): EndpointFrame[] {\n const joined = new Uint8Array(this.#buffer.length + chunk.length);\n joined.set(this.#buffer);\n joined.set(chunk, this.#buffer.length);\n const frames: EndpointFrame[] = [];\n let at = 0;\n for (;;) {\n if (joined.length - at < 4) break;\n const length = new DataView(\n joined.buffer,\n joined.byteOffset + at,\n 4,\n ).getUint32(0);\n if (length > MAX_FRAME_BYTES) {\n throw new FrameError(\"session frame exceeds the frame size limit\");\n }\n if (joined.length - at - 4 < length) break;\n let json: string;\n try {\n json = decoder.decode(joined.subarray(at + 4, at + 4 + length));\n } catch (cause) {\n throw new FrameError(\"session frame is not UTF-8\", { cause });\n }\n frames.push(readFrame(json));\n at += 4 + length;\n }\n this.#buffer = joined.slice(at);\n return frames;\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// A `files` session: the client names the folders it watches, and the\n// endpoint lists each one from the Computer's live disk, then lists it\n// again shortly after it changes. A listing arrives as a pass of one or\n// more `listing` frames; the session hands the caller whole passes.\n\nimport { isWellFormed } from \"../resource/validation.js\";\nimport { FrameError, encodeFrame } from \"./frames.js\";\nimport type { EndpointFrame, FolderEntry, FolderProblem } from \"./frames.js\";\n\n/** The longest folder path a `files` session takes, in UTF-8 bytes. */\nconst MAX_PATH_BYTES = 4096;\n/** The longest path segment a `files` session takes, in UTF-8 bytes. */\nconst MAX_SEGMENT_BYTES = 255;\n/** The most entries one pass lists. */\nconst MAX_PASS_ENTRIES = 10_000;\n\nconst utf8 = new TextEncoder();\n\n/** One whole listing of a watched folder, replacing any earlier one. */\nexport interface FolderListing {\n /** The folder, relative to `/workspace`; `\"\"` is the root. */\n readonly path: string;\n /**\n * The folder's entries, ordered by name in byte order. Empty when\n * `problem` is present. The root's listing never names `.runtime`.\n */\n readonly entries: readonly FolderEntry[];\n /** Why the folder could not be listed; absent when it was. */\n readonly problem?: FolderProblem;\n /**\n * Present and true when the folder holds more entries than one pass\n * lists: `entries` are the first 10,000 by name.\n */\n readonly truncated?: boolean;\n}\n\n/** What a `files` session calls as listings arrive. */\nexport interface FilesSessionHandlers {\n /**\n * Called with each whole pass of a watched folder, in the order the\n * endpoint sent them. A pass for a folder unwatched since is not\n * delivered. An exception it throws does not end the session.\n */\n onListing(listing: FolderListing): void;\n}\n\n/**\n * How a `files` session ended:\n *\n * - `closed`: closed by the caller.\n * - `ended`: the endpoint ended the stream, as when the session's grant\n * ends or the Computer stops.\n * - `broken`: the connection to the Computer was lost.\n * - `error`: the endpoint ended the stream with an error frame; `code` is\n * its stable code.\n * - `failed`: the session could not be opened or read; `error` is why. A\n * refused create is an `ApiError`, a `ComputerNotAwakeError` when the\n * Computer is not awake.\n */\nexport type FilesSessionEnding =\n | { readonly reason: \"closed\" }\n | { readonly reason: \"ended\" }\n | { readonly reason: \"broken\" }\n | { readonly reason: \"error\"; readonly code: string }\n | { readonly reason: \"failed\"; readonly error: unknown };\n\n/**\n * A `files` session on a Computer: listings of the folders it watches,\n * from the Computer's live disk. It starts no process, saves nothing,\n * never wakes the Computer and never keeps it awake. It is renewed with\n * the connector's other sessions until it ends.\n */\nexport interface ComputerFilesSession {\n /** Resolves once, with how the session ended. It never rejects. */\n readonly ended: Promise<FilesSessionEnding>;\n /**\n * Watches the folder at `path`, relative to `/workspace` (`\"\"` is the root),\n * and asks for a pass of that folder. Watching a folder already watched asks\n * for a fresh pass. A session watches at most 32 folders; a further watch is\n * answered with the problem `too_many`. A path the endpoint takes is segments\n * joined by `/`, no leading or trailing `/`, no empty, `.` or `..` segment,\n * well-formed text, at most 4096 bytes in UTF-8 and at most 255 bytes per\n * segment. Does nothing once the session has ended.\n *\n * @param path the folder, relative to `/workspace`\n * @throws TypeError `path` is not one the endpoint takes; nothing is sent\n */\n watch(path: string): void;\n /**\n * Stops watching the folder at `path`. Unwatching a folder not watched\n * does nothing.\n *\n * @param path the folder, relative to `/workspace`\n * @throws TypeError `path` is one {@link ComputerFilesSession.watch}\n * refuses; nothing is sent\n */\n unwatch(path: string): void;\n /** Ends the session on purpose. */\n close(): void;\n}\n\n/** The session stream a `files` session reads and writes. */\nexport interface FilesStream {\n readonly output: ReadableStream<EndpointFrame | { readonly type: \"broken\" }>;\n /** Sends one encoded frame, unless the stream has ended. */\n sendFrame(frame: Uint8Array): void;\n /** Finishes the stream and stops renewing its session. */\n close(): void;\n}\n\n/**\n * Judges a folder path as a `files` session takes it. Throws a\n * `TypeError`.\n */\nexport function validateFolderPath(path: string): void {\n if (typeof path !== \"string\") {\n throw new TypeError(\"folder path must be a string\");\n }\n if (path === \"\") return;\n if (!isWellFormed(path)) {\n throw new TypeError(\"folder path is not well-formed text\");\n }\n if (utf8.encode(path).length > MAX_PATH_BYTES) {\n throw new TypeError(\n `folder path must not exceed ${String(MAX_PATH_BYTES)} bytes`,\n );\n }\n for (const segment of path.split(\"/\")) {\n if (segment === \"\") {\n throw new TypeError(\n \"folder path must not start or end with / or hold an empty segment\",\n );\n }\n if (segment === \".\" || segment === \"..\") {\n throw new TypeError(\"folder path must not hold a . or .. segment\");\n }\n if (utf8.encode(segment).length > MAX_SEGMENT_BYTES) {\n throw new TypeError(\n `folder path segment must not exceed ${String(MAX_SEGMENT_BYTES)} bytes`,\n );\n }\n }\n}\n\n/**\n * Gathers `listing` frames into whole passes. A pass is every frame for\n * one path up to and including the first whose `more` is false.\n */\nexport class ListingPasses {\n readonly #open = new Map<string, FolderEntry[]>();\n\n /**\n * Takes one `listing` frame; returns the pass it completes, if any.\n * Throws a {@link FrameError} for a pass longer than the endpoint may\n * send.\n */\n push(\n frame: Extract<EndpointFrame, { type: \"listing\" }>,\n ): FolderListing | undefined {\n const entries = this.#open.get(frame.path) ?? [];\n if (entries.length + frame.entries.length > MAX_PASS_ENTRIES) {\n this.#open.delete(frame.path);\n throw new FrameError(\"session frame listing exceeds the pass bound\");\n }\n entries.push(...frame.entries);\n if (frame.more) {\n this.#open.set(frame.path, entries);\n return undefined;\n }\n this.#open.delete(frame.path);\n return Object.freeze({\n path: frame.path,\n entries: Object.freeze(entries),\n ...(frame.problem === undefined ? {} : { problem: frame.problem }),\n ...(frame.truncated === true ? { truncated: true } : {}),\n });\n }\n\n /** Drops any unfinished pass of `path`. */\n drop(path: string): void {\n this.#open.delete(path);\n }\n}\n\n/** Runs a `files` session over `stream`. */\nexport function filesSession(\n stream: FilesStream,\n handlers: FilesSessionHandlers,\n): ComputerFilesSession {\n const watched = new Set<string>();\n const passes = new ListingPasses();\n let over = false;\n let settle: (ending: FilesSessionEnding) => void = () => undefined;\n const ended = new Promise<FilesSessionEnding>((resolve) => {\n settle = resolve;\n });\n const finish = (ending: FilesSessionEnding): void => {\n if (over) return;\n over = true;\n watched.clear();\n stream.close();\n settle(ending);\n };\n const deliver = (listing: FolderListing): void => {\n try {\n handlers.onListing(listing);\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n };\n void (async () => {\n const reader = stream.output.getReader();\n let ending: FilesSessionEnding | undefined;\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n if (value.type === \"listing\") {\n if (!watched.has(value.path)) {\n passes.drop(value.path);\n continue;\n }\n const listing = passes.push(value);\n if (listing !== undefined) deliver(listing);\n } else if (value.type === \"error\") {\n ending ??= { reason: \"error\", code: value.code };\n } else if (value.type === \"broken\") {\n ending ??= { reason: \"broken\" };\n }\n }\n } catch (error) {\n ending ??= { reason: \"failed\", error };\n }\n finish(ending ?? { reason: \"ended\" });\n })();\n return {\n ended,\n watch(path) {\n validateFolderPath(path);\n if (over) return;\n watched.add(path);\n stream.sendFrame(encodeFrame({ type: \"watch\", path }));\n },\n unwatch(path) {\n validateFolderPath(path);\n if (over || !watched.delete(path)) return;\n passes.drop(path);\n stream.sendFrame(encodeFrame({ type: \"unwatch\", path }));\n },\n close() {\n if (over) return;\n stream.sendFrame(encodeFrame({ type: \"end\" }));\n finish({ reason: \"closed\" });\n },\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// The signed session trust of a Zone, as the reference contract defines it:\n// which roots sign Computer endpoint and client certificates, and where\n// the Zone's data edge is and how it is authenticated. A client trusts it\n// only when a Network trust key it pins, or a successor that key signed,\n// signed it, and refuses another Network or Zone, a bundle outside its\n// validity, and a version lower than the highest it has accepted.\n\nimport { decodeBase64 } from \"../resource/base64.js\";\n\n/** The payload type of a session trust bundle. */\nexport const SESSION_TRUST_TYPE = \"idyl-session-trust/1\";\n/** The payload type of a trust key statement. */\nexport const TRUST_KEY_TYPE = \"idyl-trust-key/1\";\n/** The role whose keys sign session trust. */\nexport const NETWORK_TRUST_ROLE = \"network-trust\";\n\n/** A Network trust key the client pins: its ID and raw Ed25519 public key. */\nexport interface TrustKey {\n /** The key's ID, as published by the Network. */\n readonly keyId: string;\n /** The raw 32-byte Ed25519 public key. */\n readonly publicKey: Uint8Array;\n}\n\n/** The sentence a bundle for another Network or trust scope is refused with. */\nconst TRUST_SCOPE = \"trust document names another network, zone or role\";\n\n/** A signed document as served: its payload and its signatures, base64. */\nexport interface SignedTrustDocument {\n readonly payload: string;\n readonly signatures: readonly {\n readonly keyId: string;\n readonly signature: string;\n }[];\n}\n\n/** The session trust route's answer. */\nexport interface SessionTrustResponse {\n readonly bundle: SignedTrustDocument;\n readonly keys?: readonly SignedTrustDocument[];\n}\n\n/** A verified session trust bundle. */\nexport interface SessionTrust {\n readonly network: string;\n readonly zone: string;\n readonly version: number;\n readonly expiresAtMs: number;\n /** DER roots of Computer endpoint and client certificates. */\n readonly podRoots: readonly Uint8Array[];\n /**\n * The data edge: its `host:port`, exact SPIFFE ID and DER roots, and the\n * `wss://` URL of its browser listener when the Zone names one.\n */\n readonly dataFabric: {\n readonly endpoint: string;\n readonly serverId: string;\n readonly serverRoots: readonly Uint8Array[];\n readonly browserEndpoint?: string;\n };\n}\n\n/** What a bundle must satisfy. */\nexport interface SessionTrustPolicy {\n readonly network: string;\n readonly zone?: string;\n readonly keys: readonly TrustKey[];\n /** The highest version accepted before; a lower one is refused. */\n readonly minVersion: number;\n readonly nowMs: number;\n}\n\n/**\n * The Network's signed session trust was refused: no pinned key, nor a\n * successor one signed, signed it; it names another Network or another\n * trust scope than the client's placement chose; it lies outside its\n * validity or lacks a part a connection needs; its version is lower than\n * the highest the client has accepted for that Network and scope, a\n * rollback; or the trust floor that keeps that version could not be read\n * or written, which `cause` carries. The connector's `ready` rejects with this\n * error, and so does every session waiting on `ready`. The message is a fixed\n * sentence naming the rule.\n */\nexport class SessionTrustError extends Error {\n /**\n * Builds the error. A {@link TrustFloor} of the caller's own rejects with\n * one to refuse a rollback.\n *\n * @param message a fixed sentence naming the rule the bundle breaks\n * @param options `cause`, the underlying failure, when there is one\n */\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"SessionTrustError\";\n }\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** `bytes` in a buffer of its own, as WebCrypto takes them. */\nfunction owned(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const out = new Uint8Array(bytes.length);\n out.set(bytes);\n return out;\n}\n\n/** The bytes a signature covers: the type, a newline, the payload. */\nfunction signedMessage(\n type: string,\n payload: Uint8Array,\n): Uint8Array<ArrayBuffer> {\n const prefix = encoder.encode(`${type}\\n`);\n const out = new Uint8Array(prefix.length + payload.length);\n out.set(prefix);\n out.set(payload, prefix.length);\n return out;\n}\n\nasync function verifiedBy(\n type: string,\n document: SignedTrustDocument,\n keys: ReadonlyMap<string, Uint8Array>,\n): Promise<Uint8Array | undefined> {\n const payload = decodeBase64(document.payload);\n const message = signedMessage(type, payload);\n for (const signature of document.signatures) {\n const publicKey = keys.get(signature.keyId);\n if (publicKey === undefined) continue;\n const key = await crypto.subtle.importKey(\n \"raw\",\n owned(publicKey),\n { name: \"Ed25519\" },\n false,\n [\"verify\"],\n );\n if (\n await crypto.subtle.verify(\n { name: \"Ed25519\" },\n key,\n owned(decodeBase64(signature.signature)),\n message,\n )\n ) {\n return payload;\n }\n }\n return undefined;\n}\n\nfunction json(payload: Uint8Array, what: string): Record<string, unknown> {\n let value: unknown;\n try {\n value = JSON.parse(decoder.decode(payload));\n } catch (cause) {\n throw new SessionTrustError(`${what} is not JSON`, { cause });\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new SessionTrustError(`${what} is not an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction pemCertificates(pem: string): Uint8Array[] {\n const out: Uint8Array[] = [];\n const re =\n /-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\\s]+)-----END CERTIFICATE-----/g;\n for (const match of pem.matchAll(re)) {\n out.push(decodeBase64((match[1] ?? \"\").replace(/\\s+/g, \"\")));\n }\n return out;\n}\n\n/** A `wss://` URL with a host and a path, and nothing else. */\nfunction isBrowserEndpoint(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n return (\n url.protocol === \"wss:\" &&\n url.hostname !== \"\" &&\n url.pathname.length > 1 &&\n url.username === \"\" &&\n url.password === \"\" &&\n url.search === \"\" &&\n url.hash === \"\"\n );\n}\n\n/**\n * Verifies a Zone's session trust under `policy` and returns it. Throws a\n * {@link SessionTrustError} naming the rule a bundle breaks.\n */\nexport async function verifySessionTrust(\n response: SessionTrustResponse,\n policy: SessionTrustPolicy,\n): Promise<SessionTrust> {\n const trusted = new Map<string, Uint8Array>(\n policy.keys.map((k) => [k.keyId, k.publicKey]),\n );\n // Successor keys, each announced by a key already trusted.\n for (const statement of response.keys ?? []) {\n const payload = await verifiedBy(TRUST_KEY_TYPE, statement, trusted);\n if (payload === undefined) continue;\n const s = json(payload, \"trust key statement\");\n if (\n s[\"type\"] !== TRUST_KEY_TYPE ||\n s[\"network\"] !== policy.network ||\n s[\"role\"] !== NETWORK_TRUST_ROLE ||\n typeof s[\"keyId\"] !== \"string\" ||\n typeof s[\"publicKey\"] !== \"string\" ||\n typeof s[\"notBefore\"] !== \"string\" ||\n Date.parse(s[\"notBefore\"]) > policy.nowMs\n ) {\n continue;\n }\n trusted.set(s[\"keyId\"], decodeBase64(s[\"publicKey\"]));\n }\n const payload = await verifiedBy(\n SESSION_TRUST_TYPE,\n response.bundle,\n trusted,\n );\n if (payload === undefined) {\n throw new SessionTrustError(\n \"session trust is not signed by a trusted Network key\",\n );\n }\n const b = json(payload, \"session trust\");\n if (b[\"type\"] !== SESSION_TRUST_TYPE) {\n throw new SessionTrustError(\"session trust has another type\");\n }\n if (b[\"network\"] !== policy.network) {\n throw new SessionTrustError(TRUST_SCOPE);\n }\n const zone = b[\"zone\"];\n if (typeof zone !== \"string\" || zone === \"\") {\n throw new SessionTrustError(\"session trust names no Zone\");\n }\n if (policy.zone !== undefined && zone !== policy.zone) {\n throw new SessionTrustError(TRUST_SCOPE);\n }\n const version = b[\"version\"];\n if (typeof version !== \"number\" || !Number.isSafeInteger(version)) {\n throw new SessionTrustError(\"session trust has no version\");\n }\n if (version < policy.minVersion) {\n throw new SessionTrustError(\n \"session trust bundle is older than one already accepted\",\n );\n }\n const issuedAt = Date.parse(String(b[\"issuedAt\"]));\n const expiresAt = Date.parse(String(b[\"expiresAt\"]));\n if (\n Number.isNaN(issuedAt) ||\n Number.isNaN(expiresAt) ||\n policy.nowMs < issuedAt ||\n policy.nowMs >= expiresAt\n ) {\n throw new SessionTrustError(\"session trust is outside its validity\");\n }\n const pod = b[\"pod\"] as { generations?: unknown } | undefined;\n const podRoots = (Array.isArray(pod?.generations) ? pod.generations : [])\n .map((g: unknown) => (g as { certificateDer?: unknown }).certificateDer)\n .filter((der): der is string => typeof der === \"string\")\n .map((der) => decodeBase64(der));\n if (podRoots.length === 0) {\n throw new SessionTrustError(\"session trust names no Pod roots\");\n }\n const fabric = b[\"dataFabric\"] as Record<string, unknown> | undefined;\n const endpoint = fabric?.[\"endpoint\"];\n const serverId = fabric?.[\"serverId\"];\n const roots = fabric?.[\"serverRoots\"];\n const serverRoots = pemCertificates(typeof roots === \"string\" ? roots : \"\");\n if (\n typeof endpoint !== \"string\" ||\n typeof serverId !== \"string\" ||\n serverRoots.length === 0\n ) {\n throw new SessionTrustError(\"session trust names no data edge\");\n }\n const browser = fabric?.[\"browserEndpoint\"];\n if (browser !== undefined && !isBrowserEndpoint(browser)) {\n throw new SessionTrustError(\n \"session trust names a browser endpoint that is not a wss URL\",\n );\n }\n return {\n network: policy.network,\n zone,\n version,\n expiresAtMs: expiresAt,\n podRoots,\n dataFabric: {\n endpoint,\n serverId,\n serverRoots,\n ...(browser === undefined ? {} : { browserEndpoint: browser }),\n },\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// The highest session trust version a client has accepted, per Network and\n// trust scope. A connector refuses a bundle older than it, so a validly\n// signed but rolled-back bundle is never accepted again once a newer one\n// has been.\n\nimport { SessionTrustError } from \"./trust.js\";\n\n/** The sentence a floor refuses an older version with. */\nexport const TRUST_ROLLBACK =\n \"session trust bundle is older than one already accepted\";\n\n/**\n * Where a client keeps the highest session trust version it has accepted\n * for each Network and trust scope. `scope` is the opaque name the client's\n * placement gives the sessions a bundle governs; a floor keeps it as given,\n * without interpretation.\n */\nexport interface TrustFloor {\n /**\n * Accepts `version` for `network` and `scope` as one atomic step: rejects\n * with a `SessionTrustError` when it is lower than the version kept, and\n * otherwise keeps it when it is higher; an equal version changes nothing.\n * Any other rejection means the floor could not be read or written, and a\n * connector refuses the bundle for that reason.\n *\n * @param network the Network the bundle names, as a domain\n * @param scope the trust scope the bundle governs, kept as given\n * @param version the bundle's version\n * @throws {@link SessionTrustError} `version` is lower than the version\n * kept\n */\n accept(network: string, scope: string, version: number): Promise<void>;\n}\n\n/** The database a browser keeps its trust floors in. */\nconst DATABASE = \"idyl-session-trust\";\n/** Its one store: one record per Network and trust scope. */\nconst STORE = \"floors\";\n\ninterface FloorRecord {\n readonly network: string;\n readonly scope: string;\n readonly version: number;\n}\n\n/**\n * A trust floor held in memory, for the life of the page or process that\n * holds it.\n */\nexport function memoryTrustFloor(): TrustFloor {\n const floors = new Map<string, number>();\n return {\n accept(network, scope, version) {\n const key = `${network}\\n${scope}`;\n const kept = floors.get(key) ?? 0;\n if (version < kept) {\n return Promise.reject(new SessionTrustError(TRUST_ROLLBACK));\n }\n if (version > kept) floors.set(key, version);\n return Promise.resolve();\n },\n };\n}\n\n/**\n * A trust floor kept in IndexedDB, in database `idyl-session-trust`, store\n * `floors`, one record per Network and trust scope; each `accept` is one\n * readwrite transaction, so two pages accepting at once never lower each\n * other. The page's `memory` floor records every version the page accepts\n * as well, so the page never accepts below a version it has accepted,\n * whatever the database later holds.\n *\n * The database is opened when the floor is made, at whatever version it\n * has, so a page never locks out another that made it at a newer version,\n * and opened again when it is closed under the floor, as when site data is\n * cleared, or asked to make way for a newer version. An open that another\n * page blocks waits for it. A factory whose `open` throws before the page\n * has ever opened the database, as some private windows' does, leaves the\n * floor to `memory` for the life of the page; once the database has\n * opened, an `open` that throws rejects. Any other failure to open, read or\n * write rejects, and the next `accept` opens the database again. A stored\n * record that is not a whole, non-negative version rejects too: nothing is\n * assumed in its place.\n */\nexport function indexedDbTrustFloor(\n factory: IDBFactory,\n memory: TrustFloor,\n): TrustFloor {\n let opened: Promise<IDBDatabase | undefined> | undefined;\n let everOpened = false;\n const database = (): Promise<IDBDatabase | undefined> => {\n if (opened === undefined) {\n const opening = openDatabase(factory, everOpened, () => {\n if (opened === opening) opened = undefined;\n });\n opened = opening;\n opening.then(\n (db) => {\n if (db !== undefined) everOpened = true;\n },\n () => {\n if (opened === opening) opened = undefined;\n },\n );\n }\n return opened;\n };\n void database().catch(() => undefined);\n return {\n async accept(network, scope, version) {\n await memory.accept(network, scope, version);\n for (let attempt = 0; ; attempt += 1) {\n const current = database();\n const db = await current;\n if (db === undefined) return;\n try {\n await acceptIn(db, network, scope, version);\n return;\n } catch (error) {\n // A database closed under the floor is opened again once, unless\n // a concurrent accept already opened it again.\n if (attempt > 0 || !closed(error)) throw error;\n if (opened === current) opened = undefined;\n }\n }\n },\n };\n}\n\nfunction closed(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"InvalidStateError\";\n}\n\n/** Accepts `version` in one readwrite transaction of `db`. */\nfunction acceptIn(\n db: IDBDatabase,\n network: string,\n scope: string,\n version: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let refusal: Error | undefined;\n const transaction = db.transaction(STORE, \"readwrite\");\n const store = transaction.objectStore(STORE);\n const request = store.get([network, scope]) as IDBRequest<unknown>;\n request.onsuccess = () => {\n const kept = keptVersion(request.result);\n if (kept === undefined) {\n refusal = new Error(\"trust floor record is malformed\");\n } else if (version < kept) {\n refusal = new SessionTrustError(TRUST_ROLLBACK);\n } else if (version > kept) {\n store.put({ network, scope, version } satisfies FloorRecord);\n }\n };\n transaction.oncomplete = () => {\n if (refusal === undefined) resolve();\n else reject(refusal);\n };\n transaction.onerror = () => {\n reject(transaction.error ?? new Error(\"trust floor transaction failed\"));\n };\n transaction.onabort = transaction.onerror;\n });\n}\n\n/**\n * The version a stored record keeps: 0 for none, and `undefined` for a\n * record that is not a whole, non-negative version.\n */\nfunction keptVersion(record: unknown): number | undefined {\n if (record === undefined) return 0;\n const version =\n typeof record === \"object\" && record !== null\n ? (record as { version?: unknown }).version\n : undefined;\n return typeof version === \"number\" &&\n Number.isSafeInteger(version) &&\n version >= 0\n ? version\n : undefined;\n}\n\n/**\n * Opens the database at whatever version it has, and, when it holds no\n * floor store, opens it once more at the next version to create it. Calls\n * `lost` when the opened database is closed or asked to make way for a\n * newer version. Resolves with `undefined` when `open` throws and the page\n * has never opened the database; rejects when it throws after, or when\n * the open fails. A blocked open keeps waiting.\n */\nasync function openDatabase(\n factory: IDBFactory,\n everOpened: boolean,\n lost: () => void,\n): Promise<IDBDatabase | undefined> {\n const db = await openAt(factory, undefined, everOpened);\n if (db === undefined || db.objectStoreNames.contains(STORE)) {\n if (db !== undefined) watch(db, lost);\n return db;\n }\n const next = db.version + 1;\n db.close();\n const upgraded = await openAt(factory, next, true);\n if (upgraded !== undefined) watch(upgraded, lost);\n return upgraded;\n}\n\nfunction watch(db: IDBDatabase, lost: () => void): void {\n db.onversionchange = () => {\n db.close();\n lost();\n };\n db.onclose = lost;\n}\n\n/**\n * One `open` of the database, at `version` when one is given, creating the\n * floor store in an upgrade that lacks it.\n */\nfunction openAt(\n factory: IDBFactory,\n version: number | undefined,\n strict: boolean,\n): Promise<IDBDatabase | undefined> {\n return new Promise((resolve, reject) => {\n let request: IDBOpenDBRequest;\n try {\n request =\n version === undefined\n ? factory.open(DATABASE)\n : factory.open(DATABASE, version);\n } catch (error) {\n if (strict)\n reject(error instanceof Error ? error : new Error(String(error)));\n else resolve(undefined);\n return;\n }\n let settled = false;\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE, { keyPath: [\"network\", \"scope\"] });\n }\n };\n request.onsuccess = () => {\n const db = request.result;\n if (settled) {\n db.close();\n return;\n }\n settled = true;\n resolve(db);\n };\n request.onerror = () => {\n settled = true;\n reject(request.error ?? new Error(\"trust floor database cannot open\"));\n };\n });\n}\n\n/** The page's default floor, made by the first connector that needs it. */\nlet pageFloor: TrustFloor | undefined;\n\n/**\n * The trust floor a connector uses when it is given none: one per page,\n * shared by every connector of the page, kept in IndexedDB where the\n * runtime offers it and in memory where it does not.\n */\nexport function defaultTrustFloor(): TrustFloor {\n if (pageFloor === undefined) {\n const memory = memoryTrustFloor();\n const factory = (globalThis as { indexedDB?: IDBFactory }).indexedDB;\n pageFloor =\n factory === undefined ? memory : indexedDbTrustFloor(factory, memory);\n }\n return pageFloor;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// The page's side of Computer connections. It owns the access credential's\n// requests (the client certificate, the Zone's session trust, session\n// creates and renewals) and the session frames; its Worker owns the client\n// certificate's key and every TLS connection. A session is opened by\n// sending its create and its stream at the same time, named by one request\n// ID, so nothing waits for the create unless the Computer's place or\n// Activation is not yet known. The create answers with the place once the\n// session is bound to the Activation that will serve it, while the session\n// may still be pending, so the connection's handshake overlaps the end of\n// the Computer's wake. The platform holds a session pending and unbound\n// while the Computer's previous Activation is released, as just after the\n// Computer went to sleep; only such an answer is read again, until the\n// session is bound.\n\nimport {\n isComputerSessionPhaseTerminal,\n isZeroInstant,\n validateComputerSessionReason,\n validateCreateComputerSessionRequest,\n type ComputerSession as ServedSession,\n type ComputerSessionClient,\n type CreateComputerSessionRequest,\n} from \"../api/computer-session.js\";\nimport { validateWorkloadSessionTerminalProfile } from \"../api/workload-session.js\";\nimport { ApiError, TransportError } from \"../errors.js\";\nimport {\n isComputerSessionId,\n type ComputerSessionId,\n} from \"../resource/uuid-id.js\";\nimport { pollUntil } from \"../wait.js\";\nimport type { ComputerSessionEndpoint } from \"../api/computer-session-endpoint.js\";\nimport {\n FrameError,\n FrameReader,\n encodeFrame,\n stdinFrames,\n validateOpenedFor,\n} from \"./frames.js\";\nimport { filesSession } from \"./files.js\";\nimport type { ComputerFilesSession, FilesSessionHandlers } from \"./files.js\";\nimport type {\n EndpointFrame,\n OpenFrame,\n SessionFeature,\n SessionMode,\n TerminalSize,\n} from \"./frames.js\";\nimport type { PageToWorker, WorkerToPage } from \"./messages.js\";\nimport { SessionTrustError, verifySessionTrust } from \"./trust.js\";\nimport { defaultTrustFloor, type TrustFloor } from \"./trust-floor.js\";\nimport type { SessionTrust, SessionTrustResponse, TrustKey } from \"./trust.js\";\n\n/**\n * The Worker a connector runs its connections through: a dedicated Worker\n * whose module called `serveComputerConnections`, or the `worker` that\n * `connectInThisThread` returns. The messages between them belong to the\n * connection and are opaque to the caller.\n */\nexport interface WorkerPort {\n /**\n * Sends a message to the Worker, as `Worker.postMessage` does.\n *\n * @param message a request of the connection's own protocol\n * @param transfer the buffers whose ownership passes to the Worker\n */\n postMessage(message: PageToWorker, transfer?: Transferable[]): void;\n /**\n * Calls `listener` with each message the Worker sends, as\n * `Worker.addEventListener` does.\n *\n * @param type always `message`\n * @param listener called with each message, in the order the Worker sent\n * them\n */\n addEventListener(\n type: \"message\",\n listener: (event: MessageEvent<WorkerToPage>) => void,\n ): void;\n}\n\n/** The client certificate the platform issued for the Worker's key. */\nexport interface IssuedCertificate {\n /** DER, leaf first. */\n readonly chain: readonly Uint8Array[];\n /** The dock admission lease, exactly as issued. */\n readonly admissionLease: Uint8Array;\n readonly notAfterMs: number;\n}\n\n/**\n * A session trust response and the trust scope the client's own placement\n * names, which the bundle must name too: the client, not the bundle,\n * chooses the scope it is held to.\n */\nexport interface PlacedSessionTrust {\n readonly scope: string;\n readonly response: SessionTrustResponse;\n}\n\n/** The platform requests the connector makes, with the page's credential. */\nexport interface ConnectorApi {\n /** Issues a client certificate for a DER certificate request. */\n certify(request: Uint8Array): Promise<IssuedCertificate>;\n /**\n * The session trust of the Zone that serves the Account, with that Zone\n * as the client's placement names it.\n */\n sessionTrust(): Promise<PlacedSessionTrust>;\n /** Creates a session of a Computer. */\n createSession(\n computer: string,\n request: CreateComputerSessionRequest,\n ): Promise<ServedSession>;\n /**\n * Reads one session of a Computer as it now is. A response naming\n * another session is refused.\n */\n readSession(\n computer: string,\n session: string,\n signal: AbortSignal,\n ): Promise<ServedSession>;\n /**\n * Renews the named sessions of a Computer, each on its own renew route.\n * Resolves to those that renewing again cannot keep: the platform does\n * not know them or holds them as final. A session left out failed only\n * for now, such as on a network failure or a server error.\n */\n renewSessions(\n computer: string,\n sessions: readonly string[],\n ): Promise<readonly string[]>;\n /** Cancels one session of a Computer; cancelling an ended one is a no-op. */\n cancelSession(computer: string, session: string): Promise<void>;\n}\n\n/**\n * Where a Computer's sessions were last placed, kept across page loads so\n * the first session after a reload need not wait for its create. The value\n * is opaque to the caller and is never authority: a stale one costs one\n * fast refusal.\n */\nexport interface PlacementMemory {\n /**\n * The value `save` last kept for a Computer, or `undefined` when it kept\n * none.\n *\n * @param computer the Computer's ID\n */\n load(computer: string): string | undefined;\n /**\n * Keeps `value` for a Computer, in place of any value kept before.\n *\n * @param computer the Computer's ID\n * @param value the opaque value to keep, exactly as given\n */\n save(computer: string, value: string): void;\n}\n\n/** What a connector needs. */\nexport interface ComputerConnectorOptions {\n readonly worker: WorkerPort;\n /** The compiled Computer connection module. */\n readonly module: WebAssembly.Module;\n readonly network: string;\n /** The Network trust keys this client pins. */\n readonly trustKeys: readonly TrustKey[];\n /** The Account the page acts as, read once when the connector starts. */\n readonly account: () => Promise<string>;\n readonly api: ConnectorApi;\n readonly placements?: PlacementMemory;\n /** The kind of client every session create states; `sdk` when absent. */\n readonly client?: ComputerSessionClient;\n /** The edge's browser listener; derived from the Zone when absent. */\n readonly edgeUrl?: (zone: string) => string;\n /** The renewal interval of open sessions, in milliseconds. */\n readonly renewEveryMs?: number;\n /**\n * Where the highest accepted session trust version is kept per Network\n * and Zone; when absent, the page's IndexedDB floor, or its memory where\n * IndexedDB is absent or its `open` throws.\n */\n readonly trustFloor?: TrustFloor;\n}\n\n/** What one session stream runs. */\nexport interface SessionOpen {\n /**\n * What the stream runs: `shell`, an interactive shell on a terminal; or\n * `exec`, one command.\n */\n readonly mode: \"shell\" | \"exec\";\n /**\n * The shell a `shell` session runs, as a clean absolute path; when\n * absent, the Computer chooses.\n */\n readonly shell?: string;\n /**\n * An `exec` session's command and its arguments: 1 to 1024 arguments of\n * at most 32 KiB together, the first naming the program.\n */\n readonly command?: readonly string[];\n /**\n * Whether the session runs on a terminal. A `shell` session always does;\n * `false` when absent.\n */\n readonly tty?: boolean;\n /** The terminal's size; stated when, and only when, `tty` is `true`. */\n readonly size?: TerminalSize;\n /**\n * The terminal type, such as `xterm-256color`; stated when, and only\n * when, `tty` is `true`.\n */\n readonly term?: string;\n /** The terminal's locale, such as `C.UTF-8`; only a terminal session states one. */\n readonly locale?: string;\n}\n\n/** What any session stream the connector opens runs. */\ntype StreamOpen = Omit<SessionOpen, \"mode\"> & {\n readonly mode: SessionOpen[\"mode\"] | \"files\";\n};\n\n/** The most arguments an exec's command holds. */\nconst MAX_COMMAND_ARGS = 1024;\n/** The most bytes an exec's command holds. */\nconst MAX_COMMAND_BYTES = 32 << 10;\n\n/** The largest terminal dimension, in character cells. */\nconst MAX_TERMINAL_DIMENSION = 10_000;\n\n/**\n * Judges an open's stream before its create or its stream is sent, as the\n * endpoint judges its open frame: a terminal states its size, 1 to 10000\n * cells each way, and a type and locale\n * `validateWorkloadSessionTerminalProfile` admits, and only a terminal\n * does; a shell runs on a terminal, names no command, and names its shell,\n * when it does, by a clean absolute path; and an exec names its command\n * alone, 1 to 1024 arguments of at most 32 KiB together, the first naming\n * its program. An `ssh` stream is refused: it carries raw bytes after\n * `opened` and opens with OpenSSH. Throws a `TypeError`.\n */\nexport function validateSessionOpen(open: StreamOpen): void {\n const mode: string = open.mode;\n if (mode === \"ssh\") {\n throw new TypeError(\n \"an ssh session carries raw bytes after opened and opens with OpenSSH\",\n );\n }\n const tty = open.tty ?? false;\n const command = open.command ?? [];\n const shell = open.shell ?? \"\";\n if (tty !== (open.size !== undefined)) {\n throw new TypeError(\n \"a terminal session states its size, and only a terminal session does\",\n );\n }\n if (open.size !== undefined) validateTerminalSize(open.size);\n if (\n tty !== ((open.term ?? \"\") !== \"\") ||\n (!tty && (open.locale ?? \"\") !== \"\")\n ) {\n throw new TypeError(\n \"a terminal session names its terminal type, and only a terminal session names a terminal\",\n );\n }\n if (tty) {\n validateWorkloadSessionTerminalProfile({\n type: open.term ?? \"\",\n ...(open.locale === undefined ? {} : { locale: open.locale }),\n });\n }\n switch (open.mode) {\n case \"shell\":\n if (!tty || command.length > 0) {\n throw new TypeError(\n \"a shell session runs on a terminal and names no command\",\n );\n }\n if (shell !== \"\" && !isCleanAbsolutePath(shell)) {\n throw new TypeError(\n `shell ${JSON.stringify(shell)} is not a clean absolute path`,\n );\n }\n break;\n case \"exec\":\n if (shell !== \"\") {\n throw new TypeError(\"an exec names its command alone\");\n }\n validateCommand(command);\n break;\n case \"files\":\n if (tty || shell !== \"\" || command.length > 0) {\n throw new TypeError(\"a files stream names nothing else\");\n }\n break;\n default:\n throw new TypeError(\"unsupported mode\");\n }\n}\n\nconst utf8 = new TextEncoder();\n\nfunction validateTerminalSize(size: TerminalSize): void {\n const inBounds = (dimension: number): boolean =>\n Number.isSafeInteger(dimension) &&\n dimension >= 1 &&\n dimension <= MAX_TERMINAL_DIMENSION;\n if (!inBounds(size.cols) || !inBounds(size.rows)) {\n throw new TypeError(\n `terminal size ${String(size.cols)}x${String(size.rows)} is outside 1 to ${String(MAX_TERMINAL_DIMENSION)}`,\n );\n }\n}\n\n/**\n * Whether `path` is absolute, holds no NUL, and is already in its clean\n * form: no empty, `.` or `..` segment and no trailing slash, except the\n * root `/` itself.\n */\nfunction isCleanAbsolutePath(path: string): boolean {\n if (!path.startsWith(\"/\") || path.includes(\"\\0\")) return false;\n if (path === \"/\") return true;\n return path\n .slice(1)\n .split(\"/\")\n .every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\nfunction validateCommand(command: readonly string[]): void {\n if (command.length === 0 || command.length > MAX_COMMAND_ARGS) {\n throw new TypeError(\n `an exec's command must hold 1 to ${String(MAX_COMMAND_ARGS)} arguments`,\n );\n }\n let total = 0;\n for (const argument of command) {\n total += utf8.encode(argument).length;\n if (argument.includes(\"\\0\")) {\n throw new TypeError(\"an exec's command holds a NUL\");\n }\n }\n if (command[0] === \"\" || total > MAX_COMMAND_BYTES) {\n throw new TypeError(\n `an exec's command names its program and is at most ${String(MAX_COMMAND_BYTES)} bytes`,\n );\n }\n}\n\n/**\n * The features an open asks for, by mode: an exec asks for its save result\n * after exit. The endpoint refuses a feature its mode does not take: a shell\n * takes no save result, and a files stream takes no feature.\n */\nfunction featuresFor(mode: StreamOpen[\"mode\"]): readonly SessionFeature[] {\n return mode === \"exec\" ? [\"save-result\"] : [];\n}\nconst RENEW_EVERY_MS = 60_000;\nconst KEEPALIVE_MS = 20_000;\n/**\n * The least time an open reads a session its create answered pending\n * without its endpoint before it gives up on the session being bound, and\n * the bound when no answer states the session's `readyBy`, in milliseconds.\n */\nconst BIND_WAIT_MS = 30_000;\n/**\n * How long past a pending session's `readyBy` an open still reads it, in\n * milliseconds: the platform fails the session at `readyBy`, and the grace\n * covers its sweep and the clocks of this host and the platform\n * disagreeing, so the open normally reads the session failed.\n */\nconst READY_BY_GRACE_MS = 30_000;\n/**\n * The first pause before a read of an unbound session, and the longest:\n * each pause doubles up to it. Milliseconds.\n */\nconst BIND_BACKOFF_MS = 100;\nconst BIND_BACKOFF_MAX_MS = 1_000;\n\n/** A request to the Worker, before its `ref`. */\ntype Request = PageToWorker extends infer T\n ? T extends { readonly ref: number }\n ? Omit<T, \"ref\">\n : never\n : never;\n\ninterface Pending {\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: Error) => void;\n}\n\ninterface Docked {\n readonly dock: number;\n readonly trust: SessionTrust;\n readonly chain: readonly Uint8Array[];\n}\n\ninterface Connection {\n readonly handle: number;\n readonly dock: number;\n readonly node: string;\n readonly established: Promise<number>;\n readonly streams: Map<number, SessionStream>;\n readonly listener: (m: WorkerToPage) => void;\n}\n\n/**\n * One page's end-to-end encrypted connections to the Account's Computers.\n * Each session's bytes are readable only by the page and the Computer.\n */\nexport interface ComputerConnector {\n /**\n * Starts the Worker, obtains the page's client certificate and the\n * Network's signed trust, and connects. Call it when the page loads: a\n * session waits for it, and none of it happens when a session opens. A\n * call after a failure starts again.\n *\n * @throws {@link SessionTrustError} the Network's session trust fails\n * verification or is older than the trust floor, or the floor cannot\n * be read or written\n * @throws {@link ApiError} IDYL refuses the client certificate or the\n * session trust\n * @throws {@link TransportError} a request to IDYL does not complete\n * @throws Error the connection to the Network's edge ends while it is\n * made\n */\n ready(): Promise<void>;\n /**\n * Gets ready to open sessions on a Computer at once, where it was last\n * placed. It sends nothing for a Computer whose place it does not know,\n * and a failure only leaves the next session to connect.\n *\n * @param computer the Computer's ID\n */\n prepare(computer: string): void;\n /**\n * Opens a session on the Computer `computer` (its ID). Resolves once its\n * stream is open; its output, exit and save result arrive on the\n * stream's `output`. An `opened` that does not answer the open's mode,\n * as one carrying an SSH host key does for any mode but `ssh`, errors the\n * output with a `FrameError`, finishes the stream, and stops the\n * session's renewals, leaving it to its lease. An `ssh` session's stream carries raw SSH bytes\n * after `opened`, not frames, so the connector never opens one: OpenSSH\n * does. An open of mode `ssh` or `reattach` rejects with a `TypeError`\n * before anything is sent, so it neither wakes nor reaches the Computer.\n *\n * @param computer the Computer's ID\n * @throws TypeError `open` is not one the endpoint takes; nothing is sent\n * @throws {@link ComputerSessionEndedError} the session ended before it\n * opened\n * @throws {@link ApiError} IDYL refuses the session, such as with\n * `OUT_OF_USAGE`\n * @throws {@link TransportError} a request to IDYL does not complete\n * @throws {@link SessionTrustError} the connector cannot get ready, as\n * {@link ComputerConnector.ready} rejects\n * @throws DOMException a `TimeoutError` when IDYL does not bind the\n * session to the Computer by its ready-by time, or an `AbortError` when\n * `close` is called first\n * @throws Error the connection to the Computer or to the Network's edge\n * ends before the stream opens\n */\n open(computer: string, open: SessionOpen): Promise<ComputerSessionStream>;\n /**\n * Opens a `files` session on the Computer `computer` (its ID): listings\n * of the folders it watches, from the Computer's live disk, delivered to\n * `handlers`. Resolves once its stream is open; it watches nothing until\n * the caller calls `watch`. A Computer that is not awake refuses the\n * session with a `ComputerNotAwakeError` and is neither woken nor kept\n * awake: the returned promise rejects with that error, or, when the stream\n * was opened before the refusal arrived, the session ends `failed` with the\n * same error.\n *\n * @param computer the Computer's ID\n * @throws {@link ComputerNotAwakeError} the Computer is not awake\n * @throws {@link ApiError} IDYL refuses the session for another reason\n * @throws {@link TransportError} a request to IDYL does not complete\n * @throws {@link SessionTrustError} the connector cannot get ready, as\n * {@link ComputerConnector.ready} rejects\n * @throws Error the connection to the Computer or to the Network's edge\n * ends before the stream opens\n */\n openFiles(\n computer: string,\n handlers: FilesSessionHandlers,\n ): Promise<ComputerFilesSession>;\n /** Ends every connection. */\n close(): void;\n}\n\n/** Builds a connector. */\nexport function computerConnector(\n options: ComputerConnectorOptions,\n): ComputerConnector {\n return new Connector(options);\n}\n\nclass Connector implements ComputerConnector {\n readonly #o: ComputerConnectorOptions;\n readonly #floor: TrustFloor;\n readonly #pending = new Map<number, Pending>();\n readonly #listeners = new Set<(m: WorkerToPage) => void>();\n readonly #lanes = new Map<string, Promise<number>>();\n readonly #connections = new Map<string, Promise<Connection>>();\n readonly #known = new Map<string, ComputerSessionEndpoint>();\n readonly #sessions = new Map<string, Set<string>>();\n // Recent events, so a wait that starts after its request was sent still\n // sees an event the Worker sent with the reply.\n readonly #log: { readonly seq: number; readonly message: WorkerToPage }[] =\n [];\n #seq = 0;\n #ref = 1;\n #account = \"\";\n // The Worker's certificate request, once the Worker has started. The\n // Worker's key outlives every dock.\n #started: Promise<Uint8Array> | undefined;\n // The dock in use. It is dropped when the dock ends or fails to dock, so\n // the next session docks again.\n #ready: Promise<Docked> | undefined;\n // The edge's earliest time to dock again, from the last dock's end.\n #notBeforeMs = 0;\n #renewer: ReturnType<typeof setInterval> | undefined;\n // Aborted by close, which ends every read of an unbound session.\n #closing = new AbortController();\n\n constructor(options: ComputerConnectorOptions) {\n this.#o = options;\n // The default floor opens its database now, at page load, so a dock's\n // floor read is one transaction.\n this.#floor = options.trustFloor ?? defaultTrustFloor();\n options.worker.addEventListener(\"message\", (event) => {\n const message = event.data;\n if (message.type === \"reply\") {\n const pending = this.#pending.get(message.ref);\n if (pending === undefined) return;\n this.#pending.delete(message.ref);\n if (message.error === undefined) pending.resolve(message.value);\n else pending.reject(new Error(message.error));\n return;\n }\n this.#log.push({ seq: ++this.#seq, message });\n if (this.#log.length > 256) this.#log.shift();\n for (const listener of [...this.#listeners]) listener(message);\n });\n }\n\n /**\n * Starts the Worker, obtains the client certificate and the Zone's\n * trust, and docks. Call it at page load; every other method waits for\n * it, and nothing here happens on a click unless the dock has ended.\n */\n ready(): Promise<void> {\n return this.#state().then(() => undefined);\n }\n\n #state(): Promise<Docked> {\n if (this.#ready === undefined) {\n const ready = this.#dock();\n this.#ready = ready;\n ready.catch(() => {\n if (this.#ready === ready) this.#ready = undefined;\n });\n }\n return this.#ready;\n }\n\n /**\n * Gets ready to open sessions on `computer` at once: the lane to its last\n * known place and, when it is awake there, the connection to it.\n */\n prepare(computer: string): void {\n const known = this.#known.get(computer) ?? this.#recall(computer);\n if (known === undefined) return;\n this.#known.set(computer, known);\n void this.#connection(computer, known).catch(() => undefined);\n }\n\n /**\n * Opens a session on `computer`. Resolves once its stream is open; the\n * session's output, exit and save result arrive on its `output`.\n */\n open(computer: string, open: SessionOpen): Promise<ComputerSessionStream> {\n return this.#open(computer, open);\n }\n\n /**\n * Opens a `files` session on `computer`. Resolves once its stream is\n * open; its listings arrive on `handlers`.\n */\n async openFiles(\n computer: string,\n handlers: FilesSessionHandlers,\n ): Promise<ComputerFilesSession> {\n return filesSession(\n await this.#open(computer, { mode: \"files\" }),\n handlers,\n );\n }\n\n async #open(computer: string, open: StreamOpen): Promise<SessionStream> {\n // The stream and the create are judged before anything is sent, so a\n // refused open neither wakes the Computer nor reaches it.\n validateSessionOpen(open);\n const requestID = crypto.randomUUID();\n const request: CreateComputerSessionRequest = {\n operation: \"shell\",\n attachment: \"endpoint\",\n endpoint: { mode: open.mode },\n idempotencyKey: requestID,\n client: this.#o.client ?? \"sdk\",\n };\n validateCreateComputerSessionRequest(request);\n await this.ready();\n const created = this.#o.api.createSession(computer, request);\n // A pending answer bound to its Activation carries its endpoint as a\n // ready one does; the endpoint holds the stream until the grant is\n // installed, so either is connected to at once. Only a pending answer\n // without its endpoint is read again, until the session is bound.\n const placed = (session: ServedSession): ComputerSessionEndpoint => {\n const endpoint = session.status.endpoint;\n if (endpoint === undefined) {\n const phase = session.status.phase;\n if (isEndedPhase(phase)) {\n throw new ComputerSessionEndedError({\n session: session.id,\n phase,\n ...(session.status.reason === undefined\n ? {}\n : { reason: session.status.reason }),\n });\n }\n throw new Error(\"the session was created without its endpoint\");\n }\n this.#remember(computer, endpoint);\n this.#track(computer, session.id);\n return endpoint;\n };\n const answered = created.then((session) =>\n unbound(session)\n ? this.#bound(computer, session).then(placed)\n : placed(session),\n );\n answered.catch(() => undefined);\n // The client connects where it last saw the Computer; with no place\n // known it waits for the create. The endpoint's certificate must name\n // an Activation epoch at least the one known, so a command never\n // reaches an earlier Activation.\n const known =\n this.#known.get(computer) ?? this.#recall(computer) ?? (await answered);\n let connection: Connection;\n try {\n connection = await this.#connection(computer, known);\n await connection.established;\n } catch (first) {\n // The place the client knew is stale: the create says where it is.\n const endpoint = await answered;\n if (sameEndpoint(endpoint, known)) throw first;\n connection = await this.#connection(computer, endpoint, true);\n await connection.established;\n }\n const session = await this.#stream(computer, connection, requestID, open);\n created.then(\n (served) => {\n session.served(served.id);\n },\n (error: unknown) => {\n session.fail(error);\n },\n );\n // A stream sent before the answer is ended at once by a session that\n // ended before it opened, as a refused create ends it.\n answered.catch((error: unknown) => {\n if (error instanceof ComputerSessionEndedError) session.fail(error);\n });\n return session;\n }\n\n /**\n * Reads `session`, which its create answered pending without its\n * endpoint, until it is bound or in another phase, and resolves to it\n * then. The platform holds a session unbound while the Computer's\n * previous Activation is released, as after the Computer went to sleep,\n * and while the Computer's wake runs, as while its files are fetched; it\n * fails a session still pending at the session's `readyBy`, which moves\n * forward while the wake makes progress. The reads therefore go on until\n * the latest `readyBy` read has passed by {@link READY_BY_GRACE_MS}, and\n * never end before {@link BIND_WAIT_MS}, which is also the bound when no\n * answer states a `readyBy`. They pause from {@link BIND_BACKOFF_MS},\n * doubling to {@link BIND_BACKOFF_MAX_MS}; a read that meets a network\n * failure, HTTP 429 or a server error is tried again at the next pause,\n * and any other refusal rejects at once. A session still unbound once the\n * bound passed rejects with a `TimeoutError` `DOMException`, and `close`\n * ends the reads at once with an `AbortError`.\n */\n async #bound(\n computer: string,\n session: ServedSession,\n ): Promise<ServedSession> {\n const started = Date.now();\n let current = session;\n let readyBy = instant(session.status.readyBy);\n let until = boundBy(readyBy, started);\n for (;;) {\n try {\n await pollUntil<ServedSession>(\n {\n timeoutMs: Math.max(0, until - Date.now()),\n signal: this.#closing.signal,\n },\n {\n initial: current,\n read: async (signal) => {\n try {\n current = await this.#o.api.readSession(\n computer,\n session.id,\n signal,\n );\n } catch (error) {\n if (signal.aborted || !passing(error)) throw error;\n }\n return current;\n },\n met: (read) => !unbound(read),\n timeoutMessage: () =>\n readyBy === undefined\n ? `computer session ${session.id} was not bound to an Activation within ${String(BIND_WAIT_MS)} ms`\n : `computer session ${session.id} was not bound to an Activation by its ready-by time ${rfc3339Seconds(readyBy)}`,\n delay: (attempt) =>\n Math.max(\n 0,\n Math.min(\n BIND_BACKOFF_MS * 2 ** attempt,\n BIND_BACKOFF_MAX_MS,\n until - Date.now(),\n ),\n ),\n },\n );\n return current;\n } catch (error) {\n // A wait that ran out goes on only when a read moved the session's\n // readyBy, and with it the bound, forward.\n if (!(error instanceof DOMException) || error.name !== \"TimeoutError\")\n throw error;\n const moved = instant(current.status.readyBy);\n if (moved === undefined || (readyBy !== undefined && moved <= readyBy))\n throw error;\n readyBy = moved;\n const next = boundBy(readyBy, started);\n if (next <= until) throw error;\n until = next;\n }\n }\n }\n\n /** Ends every connection and the dock. */\n close(): void {\n if (this.#renewer !== undefined) clearInterval(this.#renewer);\n this.#closing.abort();\n this.#closing = new AbortController();\n void this.#ready?.then(({ dock }) =>\n this.#request({ type: \"close-dock\", dock }),\n );\n }\n\n /** Starts the Worker once; resolves to its certificate request. */\n #start(): Promise<Uint8Array> {\n if (this.#started === undefined) {\n const started = (async () => {\n const key = new Promise<Uint8Array>((resolve) => {\n const listener = (m: WorkerToPage): void => {\n if (m.type === \"key\") {\n this.#listeners.delete(listener);\n resolve(m.certificateRequest);\n }\n };\n this.#listeners.add(listener);\n });\n this.#account = await this.#o.account();\n await this.#request({ type: \"start\", module: this.#o.module });\n return key;\n })();\n this.#started = started;\n started.catch(() => {\n if (this.#started === started) this.#started = undefined;\n });\n }\n return this.#started;\n }\n\n /**\n * Holds a verified bundle to the trust floor of its Network and the Zone\n * the client's placement chose, which the bundle was verified to name:\n * an older version is refused, and a newer one raises the floor, in one\n * atomic step. A floor that cannot be read or written refuses the bundle:\n * a rollback is never accepted because the floor was out of reach.\n */\n async #holdToFloor(verified: SessionTrust): Promise<void> {\n try {\n await this.#floor.accept(\n verified.network,\n verified.zone,\n verified.version,\n );\n } catch (error) {\n if (error instanceof SessionTrustError) throw error;\n throw new SessionTrustError(\"session trust floor is unavailable\", {\n cause: error,\n });\n }\n }\n\n /**\n * Obtains a client certificate and the Zone's trust, and docks. Each dock\n * is admitted with a certificate issued for it.\n */\n async #dock(): Promise<Docked> {\n // The trust is fetched, verified and held to the floor while the client\n // certificate is requested, so neither waits for the other.\n const trust = this.#o.api.sessionTrust().then(async (placed) => {\n if (placed.scope === \"\") {\n throw new SessionTrustError(\n \"the client's placement names no session trust scope\",\n );\n }\n const verified = await verifySessionTrust(placed.response, {\n network: this.#o.network,\n zone: placed.scope,\n keys: this.#o.trustKeys,\n minVersion: 0,\n nowMs: Date.now(),\n });\n await this.#holdToFloor(verified);\n return verified;\n });\n trust.catch(() => undefined);\n const wait = this.#notBeforeMs - Date.now();\n if (wait > 0) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n const certificate = await this.#o.api.certify(await this.#start());\n const verified = await trust;\n const docked = this.#event(\n (m) => m.type === \"docked\" || m.type === \"dock-ended\",\n );\n const dock = (await this.#request({\n type: \"dock\",\n url:\n this.#o.edgeUrl?.(verified.zone) ??\n verified.dataFabric.browserEndpoint ??\n `wss://edge.${verified.zone}.zone.${this.#o.network}/hyperplane/fallback/1`,\n serverName: verified.dataFabric.endpoint.replace(/:\\d+$/, \"\"),\n edgeId: verified.dataFabric.serverId,\n edgeRoots: verified.dataFabric.serverRoots,\n chain: certificate.chain,\n lease: certificate.admissionLease,\n keepaliveMs: KEEPALIVE_MS,\n })) as number;\n const outcome = await docked;\n if (outcome.type === \"dock-ended\") {\n this.#ended(outcome);\n throw new Error(`the dock ended: ${outcome.reason}`);\n }\n const ending = (m: WorkerToPage): void => {\n if (m.type !== \"dock-ended\" || m.dock !== dock) return;\n this.#listeners.delete(ending);\n this.#ended(m);\n };\n this.#listeners.add(ending);\n this.#renewer ??= setInterval(() => {\n this.#renew();\n }, this.#o.renewEveryMs ?? RENEW_EVERY_MS);\n return { dock, trust: verified, chain: certificate.chain };\n }\n\n /**\n * Forgets a dock that ended, its lanes and its Computer connections, and\n * ends their streams as broken: the Worker no longer holds any of them.\n * The next session docks again, no earlier than the edge asked.\n */\n #ended(m: Extract<WorkerToPage, { type: \"dock-ended\" }>): void {\n if (m.retryAfterMs !== undefined) {\n this.#notBeforeMs = Date.now() + m.retryAfterMs;\n }\n const ready = this.#ready;\n void ready?.then(\n ({ dock }) => {\n if (dock === m.dock && this.#ready === ready) this.#ready = undefined;\n },\n () => undefined,\n );\n for (const key of [...this.#lanes.keys()]) {\n if (key.startsWith(`${String(m.dock)} `)) this.#lanes.delete(key);\n }\n for (const [computer, opened] of [...this.#connections]) {\n void opened.then(\n (connection) => {\n if (connection.dock !== m.dock) return;\n this.#listeners.delete(connection.listener);\n for (const s of connection.streams.values()) s.ended(true);\n connection.streams.clear();\n if (this.#connections.get(computer) === opened) {\n this.#connections.delete(computer);\n }\n },\n () => undefined,\n );\n }\n }\n\n #remember(computer: string, endpoint: ComputerSessionEndpoint): void {\n this.#known.set(computer, endpoint);\n this.#o.placements?.save(computer, JSON.stringify(endpoint));\n }\n\n #recall(computer: string): ComputerSessionEndpoint | undefined {\n const text = this.#o.placements?.load(computer);\n if (text === undefined) return undefined;\n try {\n const value = JSON.parse(text) as ComputerSessionEndpoint;\n return typeof value.placement.hostPod === \"string\" ? value : undefined;\n } catch {\n return undefined;\n }\n }\n\n #track(computer: string, session: string): void {\n let set = this.#sessions.get(computer);\n if (set === undefined) {\n set = new Set();\n this.#sessions.set(computer, set);\n }\n set.add(session);\n }\n\n /**\n * Renews every session the page holds. A session the platform does not\n * know or holds as final is never renewed again; its stream is left to\n * the endpoint, which ends it when its permit runs out, so output still\n * on the way, such as a command's exit and save result, is not cut off. A\n * session whose renewal failed for any other reason is renewed at the\n * next interval.\n */\n #renew(): void {\n for (const [computer, sessions] of this.#sessions) {\n if (sessions.size === 0) continue;\n void this.#o.api.renewSessions(computer, [...sessions]).then(\n (over) => {\n for (const session of over) sessions.delete(session);\n },\n () => undefined,\n );\n }\n }\n\n async #lane(node: string): Promise<number> {\n const { dock, trust } = await this.#state();\n const principal = `spiffe://${trust.zone}.zone.${this.#o.network}/node/${node}/data-dock`;\n // Lanes are the dock's: keyed by it, so a later dock opens its own.\n const key = `${String(dock)} ${principal}`;\n let lane = this.#lanes.get(key);\n if (lane === undefined) {\n lane = (async () => {\n const since = this.#mark();\n const handle = (await this.#request({\n type: \"open-lane\",\n dock,\n principal,\n })) as number;\n // The lane ends with its dock, which the Worker reports only once.\n const outcome = await this.#event(\n (m) =>\n onDock(m, dock) &&\n (((m.type === \"lane-ready\" || m.type === \"lane-ended\") &&\n m.lane === handle) ||\n m.type === \"dock-ended\"),\n since,\n );\n if (outcome.type === \"lane-ended\" || outcome.type === \"dock-ended\") {\n throw new Error(\n `the lane to the Computer's machine ended: ${outcome.reason}`,\n );\n }\n return handle;\n })();\n this.#lanes.set(key, lane);\n lane.catch(() => this.#lanes.delete(key));\n }\n return lane;\n }\n\n #connection(\n computer: string,\n at: ComputerSessionEndpoint,\n fresh = false,\n ): Promise<Connection> {\n const current = this.#connections.get(computer);\n if (current !== undefined && !fresh) return current;\n const opened = (async () => {\n const { dock, trust, chain } = await this.#state();\n const lane = await this.#lane(at.placement.node);\n const since = this.#mark();\n const handle = (await this.#request({\n type: \"open-computer\",\n dock,\n lane,\n hostPod: at.placement.hostPod,\n sequence: String(at.placement.sequence),\n epoch: String(at.epoch),\n roots: trust.podRoots,\n chain,\n trustDomain: `${trust.zone}.zone.${this.#o.network}`,\n account: this.#account,\n computer: computer,\n minEpoch: String(at.epoch),\n })) as number;\n const streams = new Map<number, SessionStream>();\n const established = this.#event(\n (m) =>\n onDock(m, dock) &&\n (((m.type === \"computer-established\" ||\n m.type === \"computer-ended\") &&\n m.computer === handle) ||\n m.type === \"dock-ended\"),\n since,\n ).then((m) => {\n if (m.type === \"computer-ended\" || m.type === \"dock-ended\") {\n throw new Error(`the Computer connection ended: ${m.reason}`);\n }\n return Number(m.type === \"computer-established\" ? m.epoch : 0);\n });\n // A connection readied ahead may end unawaited (the Computer left\n // its place); a session that waits on it still sees why.\n established.catch(() => undefined);\n // A handle is unique only within its dock.\n const listener = (m: WorkerToPage): void => {\n if (!onDock(m, dock)) return;\n if (m.type === \"data\" && m.computer === handle) {\n streams.get(m.stream)?.receive(m.bytes);\n } else if (m.type === \"stream-ended\" && m.computer === handle) {\n streams.get(m.stream)?.ended(m.broken);\n streams.delete(m.stream);\n } else if (m.type === \"computer-ended\" && m.computer === handle) {\n this.#listeners.delete(listener);\n for (const s of streams.values()) s.ended(true);\n streams.clear();\n if (this.#connections.get(computer) === opened) {\n this.#connections.delete(computer);\n }\n }\n };\n const connection: Connection = {\n handle,\n dock,\n node: at.placement.node,\n established,\n streams,\n listener,\n };\n this.#listeners.add(listener);\n return connection;\n })();\n this.#connections.set(computer, opened);\n opened.catch(() => {\n if (this.#connections.get(computer) === opened)\n this.#connections.delete(computer);\n });\n return opened;\n }\n\n async #stream(\n computer: string,\n connection: Connection,\n requestID: string,\n open: StreamOpen,\n ): Promise<SessionStream> {\n const { dock } = await this.#state();\n const stream = (await this.#request({\n type: \"open-stream\",\n dock,\n computer: connection.handle,\n })) as number;\n const send = (bytes: Uint8Array): void => {\n void this.#request(\n { type: \"write\", dock, computer: connection.handle, stream, bytes },\n [bytes.buffer],\n ).catch(() => undefined);\n };\n const session = new SessionStream(\n requestID,\n open.mode,\n send,\n () => {\n void this.#request({\n type: \"finish\",\n dock,\n computer: connection.handle,\n stream,\n }).catch(() => undefined);\n },\n () => {\n this.#sessions.get(computer)?.delete(session.id ?? \"\");\n },\n (id) => {\n // A cancel that fails leaves the session to its attach\n // deadline; the stream's error is what the caller acts on.\n this.#sessions.get(computer)?.delete(id);\n void this.#o.api.cancelSession(computer, id).catch(() => undefined);\n },\n );\n connection.streams.set(stream, session);\n const frame: OpenFrame = {\n requestID,\n mode: open.mode,\n tty: open.tty ?? false,\n features: featuresFor(open.mode),\n ...(open.shell === undefined ? {} : { shell: open.shell }),\n ...(open.command === undefined ? {} : { command: open.command }),\n ...(open.size === undefined ? {} : { size: open.size }),\n ...(open.term === undefined ? {} : { term: open.term }),\n ...(open.locale === undefined ? {} : { locale: open.locale }),\n };\n send(encodeFrame({ type: \"open\", ...frame }));\n return session;\n }\n\n #request(request: Request, transfer: Transferable[] = []): Promise<unknown> {\n const ref = this.#ref++;\n return new Promise((resolve, reject) => {\n this.#pending.set(ref, { resolve, reject });\n this.#o.worker.postMessage({ ...request, ref }, transfer);\n });\n }\n\n /** The event count so far, to wait from with {@link #event}. */\n #mark(): number {\n return this.#seq;\n }\n\n /** The first event after `since` that `match` accepts. */\n #event<T extends WorkerToPage>(\n match: (m: WorkerToPage) => boolean,\n since: number = this.#seq,\n ): Promise<T> {\n const seen = this.#log.find((e) => e.seq > since && match(e.message));\n if (seen !== undefined) return Promise.resolve(seen.message as T);\n return new Promise((resolve) => {\n const listener = (m: WorkerToPage): void => {\n if (!match(m)) return;\n this.#listeners.delete(listener);\n resolve(m as T);\n };\n this.#listeners.add(listener);\n });\n }\n}\n\n/**\n * Whether the platform holds `session` pending and not yet bound to the\n * Activation that will serve it: it names no endpoint.\n */\nfunction unbound(session: ServedSession): boolean {\n return (\n session.status.phase === \"pending\" && session.status.endpoint === undefined\n );\n}\n\n/**\n * The instant `timestamp` names, in milliseconds since the epoch, or\n * `undefined` for the zero instant or a timestamp that names none.\n */\nfunction instant(timestamp: string): number | undefined {\n if (isZeroInstant(timestamp)) return undefined;\n const ms = Date.parse(timestamp);\n return Number.isNaN(ms) ? undefined : ms;\n}\n\n/**\n * When the reads of an unbound session first read at `started` stop:\n * {@link READY_BY_GRACE_MS} after `readyBy`, the latest `readyBy` the\n * platform stated for it, and never before {@link BIND_WAIT_MS} has\n * passed, which is also the bound when the platform stated none.\n */\nfunction boundBy(readyBy: number | undefined, started: number): number {\n const least = started + BIND_WAIT_MS;\n return readyBy === undefined\n ? least\n : Math.max(least, readyBy + READY_BY_GRACE_MS);\n}\n\n/** `ms` as an RFC 3339 UTC timestamp to the second, as the reference contract writes one. */\nfunction rfc3339Seconds(ms: number): string {\n return new Date(Math.floor(ms / 1_000) * 1_000)\n .toISOString()\n .replace(\".000Z\", \"Z\");\n}\n\n/**\n * Whether a read failed only in passing, so the same read may succeed: no\n * answer arrived, the request timed out, or the platform answered HTTP 429\n * or a server error.\n */\nfunction passing(error: unknown): boolean {\n if (error instanceof TransportError) {\n return error.code === \"network_error\" || error.code === \"timeout\";\n }\n return (\n error instanceof ApiError && (error.status === 429 || error.status >= 500)\n );\n}\n\n/** Whether the Worker's event `m` is about the dock `dock`. */\nfunction onDock(m: WorkerToPage, dock: number): boolean {\n return \"dock\" in m && m.dock === dock;\n}\n\nfunction sameEndpoint(\n a: ComputerSessionEndpoint,\n b: ComputerSessionEndpoint,\n): boolean {\n return (\n a.epoch === b.epoch &&\n a.placement.node === b.placement.node &&\n a.placement.hostPod === b.placement.hostPod &&\n a.placement.sequence === b.placement.sequence\n );\n}\n\n/**\n * A session that ended before it opened: its create answered it in a final\n * phase (`ended`, `failed`, or `cancelled`) without the endpoint its stream\n * opens on, so no endpoint served the session and nothing ran. A session whose\n * Computer was put to sleep before it started is answered `cancelled`. `phase`\n * and `reason` are what a caller branches on; the message is for people. The\n * open rejects with it when it waited for the create's answer, and a stream\n * already sent fails with it the moment the answer arrives.\n */\nexport class ComputerSessionEndedError extends Error {\n /** The session's ID, as answered by the create. */\n readonly session: ComputerSessionId;\n /** The final phase the session is in: `ended`, `failed` or `cancelled`. */\n readonly phase: EndedPhase;\n /**\n * The session's reason code, such as `ATTACH_TIMEOUT` or `WAKE_TIMEOUT`,\n * as the platform sent it; `undefined` when the session states none.\n */\n declare readonly reason?: string;\n\n /**\n * The message names the session when its ID is canonical, the phase when\n * it is final, and the reason when this SDK names it; no other text the\n * platform sent is echoed.\n *\n * @param options the session's ID, final phase and reason, as the create\n * answered them\n */\n constructor(options: {\n readonly session: ComputerSessionId;\n readonly phase: EndedPhase;\n readonly reason?: string;\n }) {\n super(endedMessage(options));\n this.name = \"ComputerSessionEndedError\";\n this.session = options.session;\n this.phase = options.phase;\n if (options.reason !== undefined) this.reason = options.reason;\n }\n}\n\n/** The final phases a session ends in. */\ntype EndedPhase = \"ended\" | \"failed\" | \"cancelled\";\n\n/** Whether `phase` is a final phase. */\nfunction isEndedPhase(phase: string): phase is EndedPhase {\n return isComputerSessionPhaseTerminal(phase);\n}\n\nfunction endedMessage(options: {\n readonly session: string;\n readonly phase: string;\n readonly reason?: string;\n}): string {\n const session = isComputerSessionId(options.session)\n ? `the Computer session ${options.session}`\n : \"the Computer session\";\n const phase = isEndedPhase(options.phase)\n ? options.phase\n : \"in a final phase\";\n const reason = options.reason ?? \"\";\n if (reason !== \"\" && knownReason(reason)) {\n return `${session} ended before it opened: ${phase} (${reason})`;\n }\n return `${session} ended before it opened: ${phase}`;\n}\n\nfunction knownReason(reason: string): boolean {\n try {\n validateComputerSessionReason(reason);\n return true;\n } catch {\n return false;\n }\n}\n\n/** What a session's output carries: the endpoint's frames, as read. */\nexport type SessionOutput = EndpointFrame | { readonly type: \"broken\" };\n\n/** One session on a Computer connection. */\nexport interface ComputerSessionStream {\n /** The request ID the session's grant and stream name. */\n readonly requestId: string;\n /** The endpoint's frames, in order; it closes after the stream ends. */\n readonly output: ReadableStream<SessionOutput>;\n /** The session's ID, once its create has answered. */\n readonly id: string | undefined;\n /**\n * Sends input to the process, in order.\n *\n * @param data the bytes to send to its standard input\n */\n write(data: Uint8Array): void;\n /**\n * Sets the terminal's size, 1 to 10000 cells each way.\n *\n * @param size the terminal's size in character cells\n * @throws TypeError `size` is outside those bounds; nothing is sent\n */\n resize(size: TerminalSize): void;\n /** Ends the input; the process sees end of file. */\n closeInput(): void;\n /** Ends the session on purpose. */\n close(): void;\n}\n\n/**\n * The error codes an endpoint answers an open with only before it asks the\n * machine the Computer runs on to start the session: a session whose stream opens with one of them\n * never started, and its request ID is used once, so it never will.\n */\nconst UNSTARTED_CODES: ReadonlySet<string> = new Set([\n \"invalid_request\",\n \"unsupported\",\n \"busy\",\n \"not_granted\",\n]);\n\nclass SessionStream implements ComputerSessionStream {\n /** The request ID the session's grant and stream name. */\n readonly requestId: string;\n /** The endpoint's frames, in order; it closes after the stream ends. */\n readonly output: ReadableStream<SessionOutput>;\n /** The mode the stream's open names, which its `opened` must answer. */\n readonly #mode: SessionMode;\n #id: string | undefined;\n readonly #send: (bytes: Uint8Array) => void;\n readonly #finish: () => void;\n readonly #forget: () => void;\n readonly #abandon: (id: string) => void;\n readonly #reader = new FrameReader();\n #controller!: ReadableStreamDefaultController<SessionOutput>;\n // The output is closed or errored.\n #done = false;\n // The Worker's stream is finished by the page or ended by the Worker.\n #released = false;\n // The page closed the session: it is no longer renewed.\n #closed = false;\n // A frame of the stream arrived.\n #answered = false;\n // The endpoint refused the open before the session started.\n #unstarted = false;\n // The unstarted session was cancelled.\n #abandoned = false;\n\n /**\n * `abandon` cancels the session by its ID, once, when the endpoint\n * refused its open before it started; it runs as soon as both the\n * refusal and the create's answer are in.\n */\n constructor(\n requestId: string,\n mode: SessionMode,\n send: (bytes: Uint8Array) => void,\n finish: () => void,\n forget: () => void,\n abandon: (id: string) => void,\n ) {\n this.requestId = requestId;\n this.#mode = mode;\n this.#send = send;\n this.#finish = finish;\n this.#forget = forget;\n this.#abandon = abandon;\n this.output = new ReadableStream<SessionOutput>({\n start: (controller) => {\n this.#controller = controller;\n },\n // A reader that cancels ends the output: nothing more may reach it.\n cancel: () => {\n this.#done = true;\n },\n });\n }\n\n /** The session's ID, once its create has answered. */\n get id(): string | undefined {\n return this.#id;\n }\n\n /** Sends input. */\n write(data: Uint8Array): void {\n for (const frame of stdinFrames(data)) this.#send(frame);\n }\n\n /** Sets the terminal's size. */\n resize(size: TerminalSize): void {\n validateTerminalSize(size);\n this.#send(encodeFrame({ type: \"resize\", size }));\n }\n\n /** Ends the input; the process sees end of file. */\n closeInput(): void {\n this.#send(encodeFrame({ type: \"close_input\" }));\n }\n\n /**\n * Ends the session on purpose: its stream is finished, unless it has\n * ended, and the session is no longer renewed.\n */\n close(): void {\n this.#closed = true;\n this.#release();\n this.#forget();\n }\n\n /** @internal Sends one encoded frame, unless the stream has ended. */\n sendFrame(frame: Uint8Array): void {\n if (!this.#released) this.#send(frame);\n }\n\n /** Finishes the Worker's stream once. */\n #release(): void {\n if (this.#released) return;\n this.#released = true;\n this.#finish();\n }\n\n /** @internal The session's create answered. */\n served(id: string): void {\n this.#id = id;\n // A session closed before its create answered is not renewed.\n if (this.#closed) this.#forget();\n this.#abandonUnstarted();\n }\n\n /**\n * Judges the stream's first frame: whether the session never started,\n * and that an `opened` answers the open's mode. Throws a `FrameError`\n * for an `opened` that does not.\n */\n #first(frame: SessionOutput): void {\n if (this.#answered) return;\n this.#answered = true;\n if (frame.type === \"opened\") {\n try {\n validateOpenedFor(frame, this.#mode);\n } catch (cause) {\n // The session is no longer renewed, as a session closed on\n // purpose is not; its lease ends it.\n this.#closed = true;\n this.#forget();\n throw new FrameError(\n \"the endpoint's opened does not answer the stream's mode\",\n { cause },\n );\n }\n }\n if (frame.type === \"error\" && UNSTARTED_CODES.has(frame.code)) {\n this.#unstarted = true;\n this.#abandonUnstarted();\n }\n }\n\n /** Cancels a session that never started, once its ID is known. */\n #abandonUnstarted(): void {\n if (!this.#unstarted || this.#abandoned || this.#id === undefined) return;\n this.#abandoned = true;\n this.#abandon(this.#id);\n }\n\n /** @internal The session's create failed. */\n fail(error: unknown): void {\n if (this.#done) return;\n this.#done = true;\n this.#controller.error(error);\n }\n\n /** @internal Bytes of the stream arrived. */\n receive(bytes: Uint8Array): void {\n if (this.#done) return;\n try {\n for (const frame of this.#reader.push(bytes)) {\n this.#first(frame);\n this.#controller.enqueue(frame);\n }\n } catch (error) {\n if (error instanceof FrameError) {\n this.fail(error);\n this.#release();\n return;\n }\n throw error;\n }\n }\n\n /** @internal The stream ended. */\n ended(broken: boolean): void {\n this.#released = true;\n if (this.#done) return;\n this.#done = true;\n if (broken) this.#controller.enqueue({ type: \"broken\" });\n this.#controller.close();\n }\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { ComputerConnector } from \"../computer-connection/connector.js\";\nimport type { ThreadConnection } from \"../computer-connection/in-thread.js\";\nimport type { TrustKey } from \"../computer-connection/trust.js\";\nimport { isBrowserDocument } from \"../internal/browser.js\";\n\n/**\n * How long a connector the client started for itself stays open with no\n * command running, in milliseconds. Commands in a row share one connection;\n * a program with nothing left to do exits this soon after its last command,\n * because an open connection keeps a Node.js process alive.\n */\nconst IDLE_CLOSE_MS = 1_000;\n\n/** What a connector runs on, as the client built or was given it. */\nexport interface ConnectorParts {\n readonly worker: ThreadConnection[\"worker\"];\n readonly module: WebAssembly.Module;\n readonly network: string;\n readonly trustKeys: readonly TrustKey[];\n}\n\n/** A connector in use. */\nexport interface ConnectionHold {\n readonly connector: ComputerConnector;\n /** Ends this use. Calling it again changes nothing. */\n readonly release: () => void;\n}\n\n/** The connectors of one client. */\nexport interface Connections {\n /** The Network and trust keys of the client, for a connector it builds. */\n readonly network: string | undefined;\n readonly trustKeys: readonly TrustKey[] | undefined;\n /**\n * Keeps `connector`, built by the application, as the one every later\n * command runs on. Its life is the application's. Returns `connector`.\n */\n adopt(connector: ComputerConnector): ComputerConnector;\n /** A use of the adopted connector, or of one started for it. */\n hold(): Promise<ConnectionHold>;\n /** Runs `work` on the connector of a {@link hold}, released when it ends. */\n use<T>(work: (connector: ComputerConnector) => Promise<T>): Promise<T>;\n}\n\n/** What {@link connections} builds from. */\nexport interface ConnectionsOptions {\n readonly network: string | undefined;\n readonly trustKeys: readonly TrustKey[] | undefined;\n readonly build: (parts: ConnectorParts) => ComputerConnector;\n /** Serves a connection in this thread. */\n readonly connect?: () => Promise<ThreadConnection>;\n}\n\nasync function connectFromPackage(): Promise<ThreadConnection> {\n // The connection and its WebAssembly load only for a program that runs a\n // command, and never count against the client's own size.\n const { connectInThisThread } =\n await import(\"@idyl-sh/sdk/computer-connection\");\n return await connectInThisThread();\n}\n\n/**\n * The connectors of one client. A browser page holds its connection in a\n * dedicated Worker, which only the application can start, so a page builds\n * its connector and adopts it. Any other program needs none of that: the\n * client starts a connector on the first command, in the program's own\n * thread, and closes it once no command has run for a moment.\n */\nexport function connections(options: ConnectionsOptions): Connections {\n const { network, trustKeys, build } = options;\n const connect = options.connect ?? connectFromPackage;\n let adopted: ComputerConnector | undefined;\n let started: Promise<ComputerConnector> | undefined;\n let running = 0;\n let idle: ReturnType<typeof setTimeout> | undefined;\n\n const start = (): Promise<ComputerConnector> => {\n if (isBrowserDocument()) {\n throw new TypeError(\n \"a page runs commands through a connector of its own: build one with idyl.computers.connector first\",\n );\n }\n if (network === undefined) {\n throw new TypeError(\n \"a client built from endpoints alone names no network to run commands on\",\n );\n }\n if (trustKeys === undefined || trustKeys.length === 0) {\n throw new TypeError(\n `no trust keys are known for the network ${network}: state trustKeys on the client`,\n );\n }\n const starting = connect().then(({ worker, module }) =>\n build({ worker, module, network, trustKeys }),\n );\n starting.catch(() => {\n if (started === starting) started = undefined;\n });\n return starting;\n };\n\n const end = (): void => {\n running -= 1;\n if (running > 0) return;\n idle = setTimeout(() => {\n idle = undefined;\n const closing = started;\n started = undefined;\n void closing?.then(\n (connector) => {\n connector.close();\n },\n () => undefined,\n );\n }, IDLE_CLOSE_MS);\n };\n\n const hold = async (): Promise<ConnectionHold> => {\n if (adopted !== undefined) {\n return { connector: adopted, release: () => undefined };\n }\n if (idle !== undefined) clearTimeout(idle);\n idle = undefined;\n running += 1;\n let held = true;\n const release = (): void => {\n if (held) end();\n held = false;\n };\n try {\n started ??= start();\n return { connector: await started, release };\n } catch (error) {\n release();\n throw error;\n }\n };\n\n return Object.freeze({\n network,\n trustKeys,\n adopt(connector: ComputerConnector) {\n adopted = connector;\n return connector;\n },\n hold,\n async use<T>(work: (connector: ComputerConnector) => Promise<T>) {\n const { connector, release } = await hold();\n try {\n return await work(connector);\n } finally {\n release();\n }\n },\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { ComputerSession } from \"../api/computer-session.js\";\nimport type {\n ComputerConnector,\n ComputerSessionStream,\n SessionOpen,\n} from \"../computer-connection/connector.js\";\nimport {\n CommandSaveError,\n CommandSessionError,\n ExitError,\n type CommandOutput,\n} from \"../errors.js\";\nimport { abortable, delay } from \"../internal/abort.js\";\nimport type { CallOptions } from \"./common.js\";\nimport { optionalNumber } from \"./records.js\";\n\n/** The most output of one stream a command keeps, in bytes. */\nconst MAX_OUTPUT_BYTES = 16 * 1024 * 1024;\n\n/**\n * How long a command that reported no save result waits for its session to\n * state one, in milliseconds. A read of the session is repeated until then.\n */\nconst SAVE_WAIT_MS = 30_000;\n/** The interval between those reads, in milliseconds. */\nconst SAVE_POLL_MS = 250;\n\nconst NEVER_ABORTED = new AbortController().signal;\n\n/** Runs a command. */\nexport interface ExecOptions extends CallOptions {\n /**\n * Ends the command when aborted: the session closes and the call rejects\n * with the signal's reason.\n */\n readonly signal?: AbortSignal;\n}\n\n/** What became of the files a command wrote. */\nexport type CommandSave =\n /** Its changes are saved, as the version `version`. */\n | \"published\"\n /** There was nothing to save. */\n | \"unchanged\"\n /** The Computer does not save automatically; nothing was saved. */\n | \"off\"\n /** The outcome could not be read. Its save remains the platform's to finish. */\n | \"unconfirmed\";\n\n/** A command that ran to its end, with exit code 0, and whose save did not fail. */\nexport interface ExecResult extends CommandOutput {\n /** Always 0: any other exit rejects with {@link ExitError}. */\n readonly exitCode: 0;\n /** What became of the files the command wrote. */\n readonly save: CommandSave;\n /** The saved version its changes became, when `save` is `published`. */\n readonly version?: number;\n}\n\n/**\n * The argument list of a command: a string runs through `/bin/sh -c`, so its\n * pipes, quotes and variables work; a list runs its program as given. Throws a\n * `TypeError` for an empty string; the session open judges a list.\n */\nexport function commandOf(command: string | readonly string[]): string[] {\n if (typeof command === \"string\") {\n if (command.trim() === \"\") throw new TypeError(\"command is required\");\n return [\"/bin/sh\", \"-c\", command];\n }\n if (!Array.isArray(command)) {\n throw new TypeError(\"command must be a string or a list of arguments\");\n }\n return [...(command as readonly string[])];\n}\n\n/** One stream's output, held up to its bound. */\nclass Collected {\n readonly #decoder = new TextDecoder();\n #text = \"\";\n #bytes = 0;\n\n /** Adds `data`; returns whether the stream is still within its bound. */\n add(data: Uint8Array): boolean {\n this.#bytes += data.byteLength;\n if (this.#bytes > MAX_OUTPUT_BYTES) return false;\n this.#text += this.#decoder.decode(data, { stream: true });\n return true;\n }\n\n get text(): string {\n return this.#text + this.#decoder.decode();\n }\n}\n\n/** What is known of a session's save. */\ninterface SaveState {\n readonly outcome: string;\n readonly revision?: number;\n readonly reason?: string;\n}\n\ntype SaveRead = (\n session: string,\n signal: AbortSignal | undefined,\n) => Promise<ComputerSession>;\n\n/**\n * Opens a session on `computer`. A session that opens only after `signal`\n * aborted is closed, since the caller has already left.\n */\nexport async function openSession(\n connector: ComputerConnector,\n computer: string,\n open: SessionOpen,\n signal: AbortSignal | undefined,\n): Promise<ComputerSessionStream> {\n signal?.throwIfAborted();\n const opening = connector.open(computer, open);\n return await bounded(opening, signal).catch((error: unknown) => {\n opening.then(\n (late) => {\n late.close();\n },\n () => undefined,\n );\n throw error;\n });\n}\n\n/**\n * Runs the command `open` names on the Computer `computer` and\n * returns once it has ended and its changes are saved, so a read of the files\n * after it sees what it wrote. The session is closed however the call ends.\n */\nexport async function runCommand(\n connector: ComputerConnector,\n computer: string,\n open: SessionOpen,\n readSession: SaveRead,\n signal: AbortSignal | undefined,\n): Promise<ExecResult> {\n const session = await openSession(connector, computer, open, signal);\n const stdout = new Collected();\n const stderr = new Collected();\n const output = (): CommandOutput => ({\n stdout: stdout.text,\n stderr: stderr.text,\n });\n const reader = session.output.getReader();\n let id = session.id;\n let exit: { readonly code?: number; readonly signal?: string } | undefined;\n let saved:\n | {\n readonly outcome: string;\n readonly revision?: number;\n readonly reason?: string;\n }\n | undefined;\n try {\n for (;;) {\n const { done, value: frame } = await bounded(reader.read(), signal);\n if (done) break;\n switch (frame.type) {\n case \"opened\":\n id = frame.session;\n break;\n case \"stdout\":\n case \"stderr\":\n if (!(frame.type === \"stdout\" ? stdout : stderr).add(frame.data)) {\n throw new CommandSessionError(\"output_too_large\", output());\n }\n break;\n case \"exit\":\n exit = frame;\n break;\n case \"saved\":\n saved = frame;\n break;\n case \"error\":\n throw new CommandSessionError(frame.code, output());\n case \"broken\":\n if (exit === undefined) {\n throw new CommandSessionError(\"broken\", output());\n }\n break;\n default:\n break;\n }\n }\n if (exit === undefined) {\n throw new CommandSessionError(\"no_exit\", output());\n }\n const state: SaveState =\n saved ?? (await sessionSave(id, readSession, signal));\n if (state.outcome === \"failed\") {\n throw new CommandSaveError(state.reason, exit.code, output());\n }\n if (exit.code !== 0 || exit.signal !== undefined) {\n throw new ExitError(exit.code, exit.signal, output());\n }\n return Object.freeze({\n exitCode: 0,\n ...output(),\n save: saveOf(state.outcome),\n ...(state.revision === undefined ? {} : { version: state.revision }),\n });\n } finally {\n session.close();\n void reader.cancel().catch(() => undefined);\n }\n}\n\nfunction saveOf(outcome: string): CommandSave {\n return outcome === \"published\" || outcome === \"unchanged\" || outcome === \"off\"\n ? outcome\n : \"unconfirmed\";\n}\n\n/**\n * The save of a session that sent no save result, as the platform records it.\n * Reads that fail are repeated within the bound; a save that stays unknown is\n * `unconfirmed`, and the command's own outcome stands.\n */\nasync function sessionSave(\n session: string | undefined,\n read: SaveRead,\n signal: AbortSignal | undefined,\n): Promise<SaveState> {\n if (session === undefined) return { outcome: \"unconfirmed\" };\n const deadline = Date.now() + SAVE_WAIT_MS;\n for (;;) {\n try {\n const { status } = await read(session, signal);\n const save = status.save;\n switch (save?.state) {\n case \"saved\": {\n const version = optionalNumber(save.version);\n return {\n outcome: \"published\",\n ...(version === undefined ? {} : { revision: version }),\n };\n }\n case \"unchanged\":\n case \"off\":\n return { outcome: save.state };\n case \"failed\":\n return {\n outcome: \"failed\",\n ...(save.reason === undefined ? {} : { reason: save.reason }),\n };\n default:\n break;\n }\n } catch (error) {\n if (signal?.aborted === true) throw error;\n }\n if (Date.now() >= deadline) return { outcome: \"unconfirmed\" };\n await delay(SAVE_POLL_MS, signal ?? NEVER_ABORTED);\n }\n}\n\nasync function bounded<T>(\n work: Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n return signal === undefined ? await work : await abortable(work, signal);\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type {\n ComputerSessionStream,\n SessionOutput,\n} from \"../computer-connection/connector.js\";\nimport type { TerminalSize } from \"../computer-connection/frames.js\";\nimport type { CallOptions } from \"./common.js\";\nimport type { ConnectionHold } from \"./connections.js\";\nimport { openSession } from \"./exec.js\";\n\n/** The size a terminal opens at when its options state none. */\nconst DEFAULT_SIZE: TerminalSize = { cols: 80, rows: 24 };\n/** The terminal type a terminal opens with when its options state none. */\nconst DEFAULT_TERM = \"xterm-256color\";\n\n/** Opens a terminal. */\nexport interface TerminalOptions extends CallOptions {\n /** Its size, 1 to 10000 cells each way; 80 by 24 when absent. */\n readonly size?: TerminalSize;\n /** Its terminal type; `xterm-256color` when absent. */\n readonly term?: string;\n /**\n * The shell to run, an absolute path in the image; the Computer's default\n * shell when absent.\n */\n readonly shell?: string;\n}\n\n/**\n * Opens a terminal on `computer`, holding the connection `hold` gave until the\n * terminal has ended or is closed.\n */\nexport async function openTerminal(\n hold: ConnectionHold,\n computer: string,\n options: TerminalOptions,\n): Promise<ComputerSessionStream> {\n let session: ComputerSessionStream;\n try {\n session = await openSession(\n hold.connector,\n computer,\n {\n mode: \"shell\",\n tty: true,\n size: options.size ?? DEFAULT_SIZE,\n term: options.term ?? DEFAULT_TERM,\n ...(options.shell === undefined ? {} : { shell: options.shell }),\n },\n options.signal,\n );\n } catch (error) {\n hold.release();\n throw error;\n }\n const reader = session.output.getReader();\n const end = (): void => {\n session.close();\n hold.release();\n };\n const output = new ReadableStream<SessionOutput>(\n {\n async pull(controller) {\n const { done, value } = await reader.read().catch((error: unknown) => {\n end();\n throw error;\n });\n if (done) {\n end();\n controller.close();\n return;\n }\n controller.enqueue(value);\n // A shell that exited has nothing more to say, and its stream may stay\n // open until it is closed.\n if (value.type === \"exit\") {\n end();\n controller.close();\n void reader.cancel().catch(() => undefined);\n }\n },\n async cancel(reason) {\n end();\n await reader.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n return Object.freeze({\n requestId: session.requestId,\n output,\n get id() {\n return session.id;\n },\n write: (data: Uint8Array) => {\n session.write(data);\n },\n resize: (size: TerminalSize) => {\n session.resize(size);\n },\n closeInput: () => {\n session.closeInput();\n },\n close: end,\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n// The platform requests of Computer connections, on the Subnet API that\n// serves the Account: the client certificate for the connection's key, the\n// signed session trust, endpoint session creates, reads and\n// cancels, and their renewal, each session on its own renew route.\n// Each request carries the client's credential and its proof.\n\nimport type { PlacementContext } from \"../internal/context.js\";\nimport { accountSubnet } from \"../internal/apipath.js\";\nimport { resolvePlacement } from \"../internal/routing.js\";\nimport { TransportError } from \"../errors.js\";\nimport { decodeBase64, encodeBase64 } from \"../resource/base64.js\";\nimport type {\n ConnectorApi,\n IssuedCertificate,\n PlacedSessionTrust,\n} from \"../computer-connection/connector.js\";\nimport type { SessionTrustResponse } from \"../computer-connection/trust.js\";\nimport {\n cancelSession,\n createSession,\n getSession,\n renewSessions,\n sessionsById,\n} from \"./computer-sessions.js\";\n\n/** The connector's platform requests in `context`. */\nexport function computerEndpointApi(\n context: () => Promise<PlacementContext>,\n): ConnectorApi {\n return {\n async certify(request: Uint8Array): Promise<IssuedCertificate> {\n const c = await context();\n const resolved = await resolvePlacement(c);\n const answer = await c.state.transport.json<unknown>(\n \"POST\",\n resolved.endpoint,\n accountSubnet(\n c.scope.accountId,\n resolved.subnet,\n \"client-certificates\",\n ),\n { body: { csr: encodeBase64(request) } },\n );\n return issued(answer);\n },\n async sessionTrust(): Promise<PlacedSessionTrust> {\n const c = await context();\n const resolved = await resolvePlacement(c);\n const response = await c.state.transport.json<SessionTrustResponse>(\n \"GET\",\n resolved.endpoint,\n \"/v1/session-trust\",\n );\n return { scope: resolved.zone, response };\n },\n async createSession(computer, request) {\n return await createSession(\n await context(),\n sessionsById(computer),\n request,\n undefined,\n );\n },\n async readSession(computer, session, signal) {\n return await getSession(\n await context(),\n sessionsById(computer),\n session,\n signal,\n );\n },\n async renewSessions(computer, sessions) {\n return await renewSessions(\n await context(),\n sessionsById(computer),\n sessions,\n );\n },\n async cancelSession(computer, session) {\n await cancelSession(\n await context(),\n sessionsById(computer),\n session,\n undefined,\n );\n },\n };\n}\n\n/**\n * Reads the client certificate answer: the chain (base64 DER, leaf first),\n * the admission lease and the expiry.\n */\nfunction issued(answer: unknown): IssuedCertificate {\n const a = (\n typeof answer === \"object\" && answer !== null ? answer : {}\n ) as Record<string, unknown>;\n const chain = a[\"chain\"];\n const lease = a[\"admissionLease\"];\n const notAfter =\n typeof a[\"notAfter\"] === \"string\" ? Date.parse(a[\"notAfter\"]) : Number.NaN;\n if (\n !Array.isArray(chain) ||\n chain.length === 0 ||\n !chain.every((c) => typeof c === \"string\") ||\n typeof lease !== \"string\" ||\n Number.isNaN(notAfter)\n ) {\n throw new TransportError(\n \"invalid_response\",\n \"client certificate response is invalid\",\n );\n }\n return {\n chain: chain.map((c: string) => decodeBase64(c)),\n admissionLease: decodeBase64(lease),\n notAfterMs: notAfter,\n };\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type {\n ComputerSleep,\n ComputerWake,\n} from \"../api/computer-operations.js\";\nimport type { ComputerSize } from \"../api/billing.js\";\nimport type { Computer as ComputerRecord } from \"../api/computer.js\";\nimport type { ListComputerSizesResponse } from \"../api/computer-size.js\";\nimport { isSaveSizeReason } from \"../api/storage.js\";\nimport { formatCpu } from \"../resource/cpu.js\";\nimport { formatMemory } from \"../resource/memory.js\";\nimport { evaluateComputerWait } from \"../api/wait.js\";\nimport { ApiError, TransportError } from \"../errors.js\";\nimport type { PlacementContext } from \"../internal/context.js\";\nimport type { AccountId } from \"../resource/id.js\";\nimport { formatDuration } from \"../resource/duration.js\";\nimport { DEFAULT_IDLE_TIMEOUT } from \"../resource/idle-timeout.js\";\nimport { formatVolume } from \"../resource/volume.js\";\nimport {\n isJournalEntryId,\n isResourceId,\n parseJournalEntryId,\n type JournalEntryId,\n} from \"../resource/uuid-id.js\";\nimport { imageCatalogQuery } from \"../internal/listquery.js\";\nimport { computersService } from \"../services/computers.js\";\nimport { vaultSecretsService } from \"../services/vault-secrets.js\";\nimport type { ComputersService } from \"../services/computers.js\";\nimport {\n normalizeWaitOptions,\n pollUntil,\n waitForDeletion,\n type WaitOptions,\n} from \"../wait.js\";\nimport {\n clientOf,\n offsetPage,\n pageOf,\n pageRequest,\n requireLimit,\n signalOf,\n walk,\n type CallOptions,\n type ListOptions,\n type Page,\n type PageOptions,\n} from \"./common.js\";\nimport {\n awakeOf,\n historyEntryOf,\n numberOf,\n openSessionOf,\n optionalNumber,\n settingsOf,\n spelled,\n versionOf,\n type Awake,\n type ExecutionSettings,\n type HistoryEntry,\n type OpenSession,\n type Version,\n} from \"./records.js\";\nimport { decryptionOf, type Decryption } from \"./decryptions.js\";\nimport { files, type Files } from \"./files.js\";\nimport {\n computerSecretUseOf,\n secretAttachmentStatusOf,\n type ComputerSecretUse,\n type SecretAttachmentStatus,\n} from \"./secrets.js\";\nimport { settingsRequest, updateRequest } from \"./settings.js\";\nimport { computerConnector } from \"../computer-connection/connector.js\";\nimport { connections, type Connections } from \"./connections.js\";\nimport { openTerminal, type TerminalOptions } from \"./terminal.js\";\nimport {\n commandOf,\n runCommand,\n type ExecOptions,\n type ExecResult,\n} from \"./exec.js\";\nimport type {\n ComputerConnector,\n ComputerSessionStream,\n} from \"../computer-connection/connector.js\";\nimport type {\n PlacementMemory,\n WorkerPort,\n} from \"../computer-connection/connector.js\";\nimport type { TrustKey } from \"../computer-connection/trust.js\";\nimport type { TrustFloor } from \"../computer-connection/trust-floor.js\";\nimport { computerEndpointApi } from \"../services/computer-endpoint-sessions.js\";\nimport type {\n ComputerSettingsOptions,\n UpdateComputerOptions,\n} from \"./settings.js\";\n\n/**\n * A Computer as it was when it was read: an immutable snapshot. Read the\n * Computer again for its current state.\n */\nexport interface ComputerInfo {\n /**\n * The stable identifier. A name changes when the Computer is renamed and\n * may be reused once freed; an ID never changes and is never reused.\n */\n readonly id: string;\n /**\n * The Computer's name, unique among the live Computers of its Namespace. A\n * rename changes it; the ID stays.\n */\n readonly name: string;\n /**\n * `active` in service, or `terminating` from the moment a delete is accepted\n * until IDYL has released the Computer.\n */\n readonly phase: \"active\" | \"terminating\" | (string & Record<never, never>);\n /**\n * Whether anything executes for it: `dormant` (nothing runs and no\n * compute is held), `running`, or `waiting`.\n */\n readonly execution:\n \"dormant\" | \"running\" | \"waiting\" | (string & Record<never, never>);\n /** The newest saved version of its files; zero is the empty first version. */\n readonly version: number;\n /** The execution settings as stated. */\n readonly settings: ExecutionSettings;\n /**\n * The settings its next start uses: those stated, with every default\n * filled in. For display; absent when IDYL does not report them.\n */\n readonly effectiveSettings?: ExecutionSettings;\n /**\n * Whether it is still running on earlier settings, which it leaves once\n * the commands running on them end.\n */\n readonly settingsPending: boolean;\n /**\n * The shells its image held when it last started, as the image's\n * `/etc/shells` lists them, at most 16, for a terminal to offer. Absent\n * before it first starts. Its image may hold other shells at its next\n * start, so a shell listed here is offered, not promised.\n */\n readonly shells?: readonly ImageShell[];\n /**\n * The largest size it can run at when it was read: the largest size that fits\n * a machine ready for the Computer. A create or a change at a larger size is\n * refused with `COMPUTER_DOES_NOT_FIT`; every size up to it is accepted.\n * Absent while no machine is ready for the Computer, or when IDYL reports no\n * value.\n */\n readonly largestSize?: ComputerSize;\n /**\n * How long it keeps running after its last command or terminal ends:\n * whole seconds such as `300s`, or `never`.\n */\n readonly idleTimeout: string;\n /** Whether it saves its files on its own; `true` unless turned off. */\n readonly autoSave: boolean;\n /** How long writes must be quiet before an automatic save, such as `10s`, when stated. */\n readonly saveQuiet?: string;\n /** The longest time between saves while writes continue, such as `2m`, when stated. */\n readonly saveMaxInterval?: string;\n /**\n * How much its files use, in bytes, as IDYL reports it, and how many files,\n * folders and links its newest saved version holds, once a save has counted\n * them.\n */\n readonly usage?: {\n readonly logicalBytes: number;\n readonly storedBytes: number;\n readonly names?: number;\n };\n /** The Computer and saved version it was forked from. */\n readonly forkOf?: { readonly computerId?: string; readonly version: number };\n /**\n * The copy a fork makes: `copying`, then `done` or `failed`, with how\n * much of the `total` is `copied`. Absent when IDYL reports no value.\n */\n readonly fork?: {\n readonly state:\n \"copying\" | \"done\" | \"failed\" | (string & Record<never, never>);\n readonly copied: number;\n readonly total: number;\n };\n /** When it was created, as an RFC 3339 instant. */\n readonly createdAt: string;\n /** When it was last modified, as an RFC 3339 instant. */\n readonly updatedAt: string;\n /** When its delete was recorded; present only while terminating. */\n readonly terminatingAt?: string;\n /**\n * When it last woke or went to sleep, as an RFC 3339 instant: while it\n * runs, when it woke. A list reports it; it is absent from a read of one\n * Computer and for a Computer that has never run.\n */\n readonly lastUsedAt?: string;\n /**\n * Why it is awake and when it will sleep. A read of one Computer reports it\n * while it runs; it is absent from a list, so its absence there says\n * nothing about the Computer.\n */\n readonly awake?: Awake;\n /**\n * Whether it is on its way to sleep while it still runs: a sleep was asked\n * for, or its idle time has run out, and it may still be saving. A read of\n * one Computer and a list both report it; absent means it is not. A session\n * opened before an idle sleep is released clears `goingToSleep`.\n */\n readonly goingToSleep?: boolean;\n}\n\n/** A shell a Computer's image holds. */\nexport interface ImageShell {\n /** The shell's file name, such as `zsh`; two shells may share one. */\n readonly name: string;\n /** Where the image holds it, such as `/usr/bin/zsh`; what a terminal names. */\n readonly path: string;\n}\n\n/** Creates a Computer. */\nexport interface CreateComputerOptions\n extends ComputerSettingsOptions, CallOptions {\n /**\n * 3 to 63 characters in IDYL's Computer name format, unique among the\n * Account's live Computers.\n */\n readonly name: string;\n /**\n * Makes a create safe to repeat: a repeat with the same key returns the\n * Computer the first created.\n */\n readonly idempotencyKey?: string;\n /**\n * The kind of client creating it, recorded with its first execution\n * settings in its history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Makes a Computer that saves only `/workspace`: its system files outside\n * `/workspace`, such as installed packages, users and `/etc`, start from\n * its image at each wake. Absent or `false`, it saves its whole system.\n */\n readonly workspaceOnly?: boolean;\n}\n\n/** Forks a Computer. */\nexport interface ForkOptions extends CallOptions {\n /**\n * The fork's name: 3 to 63 characters in IDYL's Computer name format,\n * unique among the Account's live Computers.\n */\n readonly name: string;\n /**\n * Where to fork from: a history entry's ID, such as a version's `entry`; a\n * saved version's number or name; or, left out, the newest saved version.\n * Stating `undefined` is a `TypeError`, so a value read from a record that\n * holds none is never forked from somewhere else.\n */\n readonly from?: string | number;\n /** Makes the fork safe to repeat, as a create's key does. */\n readonly idempotencyKey?: string;\n /**\n * Makes a fork that saves only `/workspace` and carries none of this\n * Computer's system files. Absent or `false`, the fork saves its whole\n * system, whatever this Computer saves.\n */\n readonly workspaceOnly?: boolean;\n /**\n * How long to wait for the copy, in milliseconds; ten minutes when\n * absent. A wait that runs out rejects with a `TimeoutError`\n * `DOMException`; the fork goes on.\n */\n readonly timeoutMs?: number;\n}\n\n/** Deletes a Computer. */\nexport interface DeleteComputerOptions extends CallOptions {\n /**\n * Waits until the Computer is gone, not only until its delete is\n * accepted. `false` when absent.\n */\n readonly wait?: boolean;\n /**\n * How long to wait, in milliseconds, with `wait`; ten minutes when\n * absent. A wait that runs out rejects with a `TimeoutError`\n * `DOMException`; the delete goes on.\n */\n readonly timeoutMs?: number;\n}\n\n/** Saves a Computer's files. */\nexport interface SaveOptions extends CallOptions {\n /**\n * How long to wait for the outcome, in milliseconds; ten minutes when\n * absent. A wait that runs out rejects with a `TimeoutError`\n * `DOMException`; the save goes on.\n */\n readonly timeoutMs?: number;\n /** Makes the save safe to repeat: a repeat with the same key returns its outcome. */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the save, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n}\n\n/** A save's outcome. */\nexport interface SaveResult {\n /**\n * `saved` when the save published a version, or `unchanged` when the\n * files held nothing the last saved version lacks.\n */\n readonly state: \"saved\" | \"unchanged\" | (string & Record<never, never>);\n /**\n * The version the save published, or with `unchanged` the Computer's\n * newest saved version.\n */\n readonly version: number;\n}\n\n/** Wakes a Computer. */\nexport interface WakeOptions extends CallOptions {\n /**\n * How long to wait for the Computer to be awake, in milliseconds; ten\n * minutes when absent. A wait that runs out rejects with a `TimeoutError`\n * `DOMException`; the wake goes on.\n */\n readonly timeoutMs?: number;\n /** Makes the wake safe to repeat: a repeat with the same key returns its outcome. */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the wake, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Called when the wake starts waiting for a cause that can clear by itself,\n * with the code it fails with if the cause holds, such as\n * `ERROR_CODE_INSUFFICIENT_CAPACITY`, and with `undefined` when it stops\n * waiting. It is called only when that changes, as the wake is read. The wake\n * goes on trying whatever it does, and a callback that throws rejects the\n * wait; the wake itself goes on.\n */\n readonly onWaiting?: (waitingFor: string | undefined) => void;\n}\n\n/** A finished wake: the Computer is `awake`. */\nexport interface WakeResult {\n /** `awake`. */\n readonly state: \"awake\" | (string & Record<never, never>);\n}\n\n/** Puts a Computer to sleep. */\nexport interface SleepOptions extends CallOptions {\n /**\n * How long to wait for the Computer to be asleep, in milliseconds; ten\n * minutes when absent. A wait that runs out rejects with a `TimeoutError`\n * `DOMException`; the sleep goes on.\n */\n readonly timeoutMs?: number;\n /** Makes the sleep safe to repeat: a repeat with the same key returns its outcome. */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the sleep, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Puts the Computer to sleep without saving it: every change to its files\n * since its last saved version is lost, and the sleep saves no version.\n * Saved versions and history are untouched, and the Computer wakes later\n * at its last saved version. Asked while another sleep of the Computer is\n * waiting for a save that has not published, such as one that keeps\n * failing, it ends that wait. The sleep's history entry records the\n * discard. `false` or absent saves the files first.\n */\n readonly discardUnsavedChanges?: boolean;\n /**\n * Called when the sleep starts waiting at a storage limit that refused its\n * save, with that save's reason, such as\n * `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`, and with `undefined` when it stops\n * waiting. It is called only when that changes, as the sleep is read. The\n * sleep goes on asking for a save whatever it does: deleting files, or a\n * sleep with `discardUnsavedChanges`, ends the wait. A callback that throws\n * rejects the wait; the sleep itself goes on.\n */\n readonly onWaiting?: (waitingFor: string | undefined) => void;\n}\n\n/** A finished sleep: the Computer is `asleep`. */\nexport interface SleepResult {\n /** `asleep`. */\n readonly state: \"asleep\" | (string & Record<never, never>);\n /**\n * The version the sleep's save recorded; absent when the Computer was\n * already asleep, or the sleep discarded unsaved changes, and nothing was\n * saved.\n */\n readonly version?: number;\n}\n\n/** Restores a saved version. */\nexport interface RestoreOptions extends CallOptions {\n /**\n * How long to wait for the restored files to be published, in\n * milliseconds; ten minutes when absent. A wait that runs out rejects\n * with a `TimeoutError` `DOMException`; the restore goes on.\n */\n readonly timeoutMs?: number;\n /** Makes the restore safe to repeat. */\n readonly idempotencyKey?: string;\n /**\n * The kind of client making the restore, recorded with its entry in the\n * Computer's history. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n}\n\n/** A published restore. */\nexport interface RestoreResult {\n /** `published`. */\n readonly state: \"published\" | (string & Record<never, never>);\n /** The version the restore published, which holds the restored files. */\n readonly version: number;\n}\n\n/** What a handle shares with the handles derived from it. */\nexport interface HandleState {\n /** The client's view, once its Account is known. */\n readonly context: (options?: CallOptions) => Promise<PlacementContext>;\n /** The Namespace the handle's Computer lives in. */\n readonly namespace: string;\n /** The connectors commands run on. */\n readonly connections: Connections;\n}\n\ninterface Internals {\n readonly state: HandleState;\n readonly record: ComputerRecord;\n readonly snapshot: ComputerInfo;\n}\n\nconst internals = new WeakMap<Computer, Internals>();\n\n/** The interval between reads while a save, restore, fork, wake, sleep or delete settles. */\nconst SETTLE_POLL_MS = 500;\n\n/** How long a fork whose copy reports no progress is read before it counts as copied. */\nconst FORK_GRACE_MS = 5_000;\n\n/**\n * The wait of an operation that settles on the platform, judged before\n * anything is sent: a `timeoutMs` that is not a non-negative number is a\n * `TypeError` naming it.\n */\nfunction settleOptions(\n options: CallOptions & { readonly timeoutMs?: number },\n): WaitOptions {\n const wait: WaitOptions = {\n ...signalOf(options),\n pollIntervalMs: SETTLE_POLL_MS,\n ...(options.timeoutMs === undefined\n ? {}\n : { timeoutMs: options.timeoutMs }),\n };\n try {\n normalizeWaitOptions(wait);\n } catch (cause) {\n throw new TypeError(\n \"timeoutMs must be a non-negative number of milliseconds\",\n { cause },\n );\n }\n return wait;\n}\n\n/**\n * One Computer. A handle holds an immutable snapshot, read when the handle\n * was made, and addresses its Computer by its stable ID, so it keeps\n * reaching its Computer across a rename, and a name reused after a rename\n * or a delete never reaches another Computer. Its methods do the work:\n * `update`, `delete`, `save`, `wake`, `sleep`, `history`, `versions`,\n * `exec`, `terminal`, `restore` and `fork`. A {@link ComputerConnector},\n * addressed by its `id`, opens any other session, such as a live files listing.\n *\n * Get one from `idyl.computers`.\n *\n * @example\n * ```ts\n * const computer = await idyl.computers.get(\"research\");\n *\n * await computer.files.upload(\"data.csv\", \"id,score\\n1,0.9\\n\");\n * const { stdout } = await computer.exec(\"wc -l data.csv\");\n *\n * const { version } = await computer.save();\n * const trial = await computer.fork({ name: \"research-trial\", from: version });\n * ```\n */\nexport class Computer {\n private constructor() {\n throw new TypeError(\"a Computer is obtained from idyl.computers\");\n }\n\n /** The Computer as it was when this handle was made. */\n get snapshot(): ComputerInfo {\n return internalsOf(this).snapshot;\n }\n\n /** The Computer's stable identifier. */\n get id(): string {\n return internalsOf(this).snapshot.id;\n }\n\n /** The Computer's name. */\n get name(): string {\n return internalsOf(this).snapshot.name;\n }\n\n /**\n * The Computer's workspace as saved versions: `upload`, `download`,\n * `list`, `move` and `remove`.\n */\n get files(): Files {\n const { state, record } = internalsOf(this);\n return files(state, record.id);\n }\n\n /**\n * Updates the Computer field by field and returns a handle with its\n * updated snapshot. Execution settings take effect from its next start,\n * without disturbing commands already running; `settingsPending` reports\n * the wait. A rename, the idle timeout and the save settings take effect\n * at once; this handle keeps its earlier snapshot, and sessions already\n * running are unaffected by a rename.\n *\n * @throws {@link TypeError} the update states nothing or a field is\n * invalid, naming the field, before any request is sent\n * @throws {@link ApiError} IDYL refuses the update, such as for a name\n * another Computer holds or a size the plan does not include\n * @throws {@link TransportError} the request does not complete, or the\n * answer names another Account or Namespace\n */\n async update(options: UpdateComputerOptions): Promise<Computer> {\n const { state, record } = internalsOf(this);\n const request = updateRequest(options);\n const service = await serviceOf(state, options);\n const { computer } = await service.updateById(\n record.id,\n request,\n signalOf(options),\n );\n return await handleOf(state, computer, options);\n }\n\n /**\n * Deletes the Computer: its files and history are released.\n * The delete is accepted at once and completes on its own; `wait` waits\n * until the Computer is gone.\n *\n * @throws {@link TypeError} `timeoutMs` is not a non-negative number,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the delete\n * @throws {@link TransportError} a request does not complete\n * @throws DOMException a `TimeoutError`: with `wait`, the Computer is\n * not gone within `timeoutMs`; the delete goes on\n */\n async delete(options: DeleteComputerOptions = {}): Promise<void> {\n const { state, record } = internalsOf(this);\n const wait = settleOptions(options);\n const service = await serviceOf(state, options);\n await service.deleteById(record.id, signalOf(options));\n if (options.wait !== true) return;\n await waitForDeletion(wait, {\n kind: \"Computer\",\n name: record.name,\n read: async (signal) =>\n (await service.getById(record.id, { signal })).computer,\n evaluate: (computer) => evaluateComputerWait(computer, \"deleted\"),\n });\n }\n\n /**\n * Saves the Computer's files and waits for the outcome. A save that finds\n * nothing to save reports `unchanged` with the newest saved version. A\n * save refused for size leaves the Computer awake with its unsaved files;\n * freeing files, or a sleep that discards unsaved changes, lets it sleep.\n *\n * @throws {@link TypeError} `timeoutMs` is not a non-negative number,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the save, or the save fails: status\n * 409 with the reason as `detail`, and for a save refused for size the\n * reason as `code` too, `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`,\n * `SAVE_REASON_COMPUTER_SIZE` or `SAVE_REASON_NAME_LIMIT`\n * @throws {@link TransportError} a request does not complete\n * @throws DOMException a `TimeoutError`: the save does not finish\n * within `timeoutMs`; the save goes on\n */\n async save(options: SaveOptions = {}): Promise<SaveResult> {\n const { state, record } = internalsOf(this);\n const wait = settleOptions(options);\n const service = await serviceOf(state, options);\n const created = await service.createCommitById(\n record.id,\n {\n ...(options.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: options.idempotencyKey }),\n client: clientOf(options.client),\n },\n signalOf(options),\n );\n const settled =\n (await pollUntil(wait, {\n initial: created,\n read: async (signal) =>\n await service.getCommitById(record.id, created.id, { signal }),\n met: (commit) =>\n [\"saved\", \"unchanged\", \"failed\"].includes(commit.state),\n timeoutMessage: (ms) => `save did not finish within ${String(ms)} ms`,\n })) ?? created;\n if (settled.state === \"failed\" || settled.version === undefined) {\n throw outcomeRefused(\n \"save\",\n settled.state,\n settled.reason,\n isSaveSizeReason(settled.reason),\n );\n }\n return Object.freeze({\n state: settled.state,\n version: numberOf(settled.version),\n });\n }\n\n /**\n * Wakes the Computer: starts its execution with no command running, and\n * waits until it is awake. A Computer that is already awake is awake at\n * once. Either way it then stays awake for its idle timeout, counted from\n * the wake, and goes to sleep as it does after its last command. Commands\n * wake a Computer on their own; a wake starts it ahead of them.\n *\n * @throws {@link TypeError} `timeoutMs` is not a non-negative number,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the wake, or the wake fails:\n * status 409 whose `code` and `detail` are the reason, the code that would\n * fail a command for the same cause, such as\n * `ERROR_CODE_INSUFFICIENT_CAPACITY` or `ERROR_CODE_WAKE_TIMEOUT`\n * @throws {@link TransportError} a request does not complete\n * @throws DOMException a `TimeoutError`: the Computer is not awake\n * within `timeoutMs`; the wake goes on\n */\n async wake(options: WakeOptions = {}): Promise<WakeResult> {\n const { state, record } = internalsOf(this);\n const wait = settleOptions(options);\n const service = await serviceOf(state, options);\n const created = await service.createWakeById(\n record.id,\n {\n ...(options.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: options.idempotencyKey }),\n client: clientOf(options.client),\n },\n signalOf(options),\n );\n let waitingFor: string | undefined;\n const observed = (wake: ComputerWake): ComputerWake => {\n if (wake.waitingFor !== waitingFor) {\n waitingFor = wake.waitingFor;\n options.onWaiting?.(waitingFor);\n }\n return wake;\n };\n const settled =\n (await pollUntil(wait, {\n initial: observed(created),\n read: async (signal) =>\n observed(\n await service.getWakeById(record.id, created.id, { signal }),\n ),\n met: (wake) => [\"awake\", \"failed\"].includes(wake.state),\n timeoutMessage: (ms) => `wake did not finish within ${String(ms)} ms`,\n })) ?? created;\n if (settled.state !== \"awake\") {\n throw outcomeRefused(\"wake\", settled.state, settled.reason, true);\n }\n return Object.freeze({ state: settled.state });\n }\n\n /**\n * Puts the Computer to sleep and waits until it is asleep. Its files are\n * saved first, as `save` does, unless `discardUnsavedChanges` asks to\n * discard the changes since its last saved version; then every command\n * and terminal still running is ended and its execution is\n * released, so background processes stop. A Computer that is already\n * asleep is asleep at once, with nothing saved. The next command wakes it\n * again.\n *\n * @throws {@link TypeError} `timeoutMs` is not a non-negative number,\n * before any request is sent\n * @throws {@link ApiError} IDYL refuses the sleep, or the sleep fails:\n * status 409 whose `code` and `detail` are the reason,\n * `ERROR_CODE_SAVE_FAILED` when the save failed and nothing was ended, or\n * `ERROR_CODE_SLEEP_TIMEOUT` when the Computer could not be released in\n * time and goes to sleep after its idle timeout instead\n * @throws {@link TransportError} a request does not complete\n * @throws DOMException a `TimeoutError`: the Computer is not asleep\n * within `timeoutMs`; the sleep goes on\n */\n async sleep(options: SleepOptions = {}): Promise<SleepResult> {\n const { state, record } = internalsOf(this);\n const wait = settleOptions(options);\n const service = await serviceOf(state, options);\n const created = await service.createSleepById(\n record.id,\n {\n ...(options.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: options.idempotencyKey }),\n client: clientOf(options.client),\n ...(options.discardUnsavedChanges === true\n ? { discardUnsavedChanges: true }\n : {}),\n },\n signalOf(options),\n );\n let waitingFor: string | undefined;\n const observed = (sleep: ComputerSleep): ComputerSleep => {\n if (sleep.waitingFor !== waitingFor) {\n waitingFor = sleep.waitingFor;\n options.onWaiting?.(waitingFor);\n }\n return sleep;\n };\n const settled =\n (await pollUntil(wait, {\n initial: observed(created),\n read: async (signal) =>\n observed(\n await service.getSleepById(record.id, created.id, { signal }),\n ),\n met: (sleep) => [\"asleep\", \"failed\"].includes(sleep.state),\n timeoutMessage: (ms) => `sleep did not finish within ${String(ms)} ms`,\n })) ?? created;\n if (settled.state !== \"asleep\") {\n throw outcomeRefused(\"sleep\", settled.state, settled.reason, true);\n }\n const version = optionalNumber(settled.version);\n return Object.freeze({\n state: settled.state,\n ...(version === undefined ? {} : { version }),\n });\n }\n\n /**\n * The Computer's history, newest entry first, page by page. Anyone who\n * may read the Computer may read its whole history.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses a page's request\n * @throws {@link TransportError} a page's request does not complete\n */\n history(options: ListOptions = {}): AsyncIterable<HistoryEntry> {\n return walk((page) => this.historyPage(page), options);\n }\n\n /**\n * One page of the Computer's history, newest entry first.\n *\n * @throws {@link TypeError} `limit` is not a positive integer\n * @throws {@link ApiError} IDYL refuses the request, such as a `continue`\n * this listing did not issue\n * @throws {@link TransportError} the request does not complete\n */\n async historyPage(options: PageOptions = {}): Promise<Page<HistoryEntry>> {\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const page = await service.listJournalById(\n record.id,\n pageRequest(options),\n signalOf(options),\n );\n return pageOf(page.items.map(historyEntryOf), page.continue);\n }\n\n /**\n * The Computer's open sessions, oldest first, as anyone who may read the\n * Computer sees them: kind, client, who and when, never content. A Computer\n * that is asleep has none.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n async sessions(options: CallOptions = {}): Promise<readonly OpenSession[]> {\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const { items } = await service.listSessionsById(\n record.id,\n signalOf(options),\n );\n return Object.freeze(items.map(openSessionOf));\n }\n\n /**\n * The state of each of the Computer's Secret attachments, in the order of\n * its settings in force: whether the attached Secret's value can be sent,\n * judged against the version the attachment uses, and when it cannot,\n * why. It is read when asked for, from IDYL, and never wakes the\n * Computer. Anyone who may read the Computer may also read this state.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n async secrets(\n options: CallOptions = {},\n ): Promise<readonly SecretAttachmentStatus[]> {\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const { items } = await service.listSecretsById(\n record.id,\n signalOf(options),\n );\n return Object.freeze(items.map(secretAttachmentStatusOf));\n }\n\n /**\n * Every Secret value IDYL opened for the Computer, newest first, page by\n * page: when, which Secret and version, the start it was opened for, the\n * outcome and who reported the decryption. The record names the Computer\n * by its ID, so a Computer of the same name created after a delete has a\n * record of its own. A decryption only the key service reported names no\n * Computer and is in the Secret's record alone, `idyl.secrets.decryptions`.\n * No entry carries a value. The record is read only when asked for: a\n * Computer read, a listing and a wake never carry the record.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses a page's request\n * @throws {@link TransportError} a page's request does not complete, or\n * its answer is not a valid decryption\n */\n decryptions(options: ListOptions = {}): AsyncIterable<Decryption> {\n return walk((page) => this.decryptionsPage(page), options);\n }\n\n /**\n * One page of the record of every Secret value IDYL opened for the\n * Computer, newest first.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, or\n * `continue` is not one a page of this listing returned, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or its\n * answer is not a valid decryption\n */\n async decryptionsPage(options: PageOptions = {}): Promise<Page<Decryption>> {\n const { state, record } = internalsOf(this);\n return await offsetPage(\n options,\n async (page, call) =>\n await vaultSecretsService(\n await state.context(call),\n ).listComputerDecryptions(record.id, page, call),\n decryptionOf,\n );\n }\n\n /**\n * The Computer's saved versions, newest first, page by page.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses a page's request\n * @throws {@link TransportError} a page's request does not complete\n */\n versions(options: ListOptions = {}): AsyncIterable<Version> {\n return walk((page) => this.versionsPage(page), options);\n }\n\n /**\n * One page of the Computer's saved versions, newest first.\n *\n * @throws {@link TypeError} `limit` is not a positive integer\n * @throws {@link ApiError} IDYL refuses the request, such as a `continue`\n * this listing did not issue\n * @throws {@link TransportError} the request does not complete\n */\n async versionsPage(options: PageOptions = {}): Promise<Page<Version>> {\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const page = await service.listVersionsById(\n record.id,\n pageRequest(options),\n signalOf(options),\n );\n return pageOf(page.items.map(versionOf), page.continue);\n }\n\n /**\n * One saved version, by number or by name.\n *\n * @param version the version's number, a non-negative integer, or the\n * name it was given with `nameVersion`\n * @throws {@link TypeError} `version` is neither a non-negative integer\n * nor a non-empty name, before any request is sent\n * @throws {@link ApiError} IDYL refuses the request, such as for a version\n * the Computer does not have\n * @throws {@link TransportError} the request does not complete\n */\n async version(\n version: number | string,\n options: CallOptions = {},\n ): Promise<Version> {\n const selector = versionSelector(version);\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n return versionOf(\n await service.getVersionById(record.id, selector, signalOf(options)),\n );\n }\n\n /**\n * Reads the Computer again and returns a handle with its current\n * snapshot. This handle's `snapshot` stays as it was.\n *\n * @throws {@link ApiError} IDYL refuses the read, such as for a Computer\n * that is gone (status 404)\n * @throws {@link TransportError} the request does not complete\n */\n async refresh(options: CallOptions = {}): Promise<Computer> {\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const { computer } = await service.getById(record.id, signalOf(options));\n return await handleOf(state, computer, options);\n }\n\n /**\n * Opens a terminal: a shell in the Computer, its output on `output`, its\n * input through `write`. A Computer that is asleep wakes. It runs until its\n * shell exits or it is closed, and it holds the client's connection open\n * until then, so a program closes it, or reads it to its end, before it can\n * exit. A browser page first builds its connector with\n * `idyl.computers.connector`.\n *\n * @throws {@link TypeError} the client has no connector to run it on: a\n * browser page that has not built one with `idyl.computers.connector`,\n * or a client with no network or trust keys\n * @throws {@link ApiError} IDYL refuses the session, such as\n * `ERROR_CODE_INSUFFICIENT_CAPACITY` or `ERROR_CODE_SESSION_BUDGET_EXCEEDED`\n * @throws {@link ComputerSessionEndedError} the session ended before it\n * ran, such as when the Computer was put to sleep\n * @throws {@link SessionTrustError} the network's session trust is refused\n * @throws {@link TransportError} a request does not complete\n */\n async terminal(\n options: TerminalOptions = {},\n ): Promise<ComputerSessionStream> {\n const { state, record } = internalsOf(this);\n return await openTerminal(\n await state.connections.hold(),\n record.id,\n options,\n );\n }\n\n /**\n * Runs a command in the Computer and returns once it has ended and its\n * changes are saved, so a read of the files after it sees what it wrote. A\n * Computer that is asleep wakes. A string runs through `/bin/sh -c`, so its\n * pipes, quotes and variables work; a list runs its program as given. It\n * starts in `/workspace`.\n *\n * Each stream keeps at most 16 MiB. For more, or for output as it arrives,\n * open a session on a {@link ComputerConnector}.\n *\n * A browser page first builds its connector with `idyl.computers.connector`.\n * Any other program needs nothing more: the client connects on the first\n * command and closes the connection a moment after the last.\n *\n * @param command a shell command line, run through `/bin/sh -c`, or a\n * program and its arguments, run as given\n * @throws {@link ExitError} the command exits other than with 0; it\n * carries the exit code and the output\n * @throws {@link CommandSaveError} the command ended but its changes could\n * not be saved; it carries the output\n * @throws {@link CommandSessionError} the session failed before the\n * command's end was known, or a stream passed 16 MiB; it carries the\n * output so far\n * @throws {@link TypeError} `command` is empty, or the client has no\n * connector to run it on: a\n * browser page that has not built one with `idyl.computers.connector`,\n * or a client with no network or trust keys\n * @throws {@link ApiError} IDYL refuses the session, such as\n * `ERROR_CODE_INSUFFICIENT_CAPACITY` or `ERROR_CODE_SESSION_BUDGET_EXCEEDED`\n * @throws {@link ComputerSessionEndedError} the session ended before it\n * ran, such as when the Computer was put to sleep\n * @throws {@link SessionTrustError} the network's session trust is refused\n * @throws {@link TransportError} a request does not complete\n */\n async exec(\n command: string | readonly string[],\n options: ExecOptions = {},\n ): Promise<ExecResult> {\n const argv = commandOf(command);\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n return await state.connections.use((connector) =>\n runCommand(\n connector,\n record.id,\n { mode: \"exec\", command: argv },\n (session, signal) =>\n service.getSessionById(\n record.id,\n session,\n signal === undefined ? {} : { signal },\n ),\n options.signal,\n ),\n );\n }\n\n /**\n * Names a saved version, so `restore` can select it by name; an empty\n * name removes the name.\n *\n * @param version the version's number\n * @param name the name to give it, or `\"\"` to remove its name\n * @throws {@link TypeError} `version` is not a non-negative integer, or\n * `name` is not a string, before any request is sent\n * @throws {@link ApiError} IDYL refuses the request, such as for a version\n * the Computer does not have\n * @throws {@link TransportError} the request does not complete\n */\n async nameVersion(\n version: number,\n name: string,\n options: CallOptions = {},\n ): Promise<Version> {\n if (!Number.isSafeInteger(version) || version < 0) {\n throw new TypeError(\"version must be a non-negative integer\");\n }\n if (typeof name !== \"string\") throw new TypeError(\"name must be a string\");\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n return versionOf(\n await service.updateVersionById(\n record.id,\n version,\n { name },\n signalOf(options),\n ),\n );\n }\n\n /**\n * Restores the files and execution settings of a saved version, by\n * number or by name, and waits until the restored files are published as\n * a further version. History only moves forward: the restore is an entry\n * of its own and every earlier one is kept. The settings apply at the\n * next start; commands already running continue, and the next session\n * sees the restored files.\n *\n * @param version the number of the version to restore, or its name\n * @throws {@link TypeError} `version` is neither a non-negative integer\n * nor a non-empty name, or `timeoutMs` is invalid, before any request is\n * sent\n * @throws {@link ApiError} IDYL refuses the restore, or the restore fails:\n * status 409 whose `detail` says why\n * @throws {@link TransportError} a request does not complete\n * @throws DOMException a `TimeoutError`: the restored files are not\n * published within `timeoutMs`; the restore goes on\n */\n async restore(\n version: number | string,\n options: RestoreOptions = {},\n ): Promise<RestoreResult> {\n const from = versionSelector(version);\n const { state, record } = internalsOf(this);\n const wait = settleOptions(options);\n const service = await serviceOf(state, options);\n const created = await service.createRestoreById(\n record.id,\n {\n from,\n ...(options.idempotencyKey === undefined\n ? {}\n : { idempotencyKey: options.idempotencyKey }),\n client: clientOf(options.client),\n },\n signalOf(options),\n );\n const settled =\n (await pollUntil(wait, {\n initial: created,\n read: async (signal) =>\n await service.getRestoreById(record.id, created.id, { signal }),\n met: (restore) => [\"published\", \"failed\"].includes(restore.state),\n timeoutMessage: (ms) =>\n `restore did not finish within ${String(ms)} ms`,\n })) ?? created;\n const published = optionalNumber(settled.version);\n if (settled.state !== \"published\" || published === undefined) {\n throw outcomeRefused(\"restore\", settled.state, settled.reason);\n }\n return Object.freeze({ state: settled.state, version: published });\n }\n\n /**\n * Creates a Computer from a point in this Computer's history, by default\n * its newest saved version, and waits until its copy has finished. The fork\n * has that point's files and settings and a history of its own; unsaved\n * changes are left out. Check `snapshot.fork?.state` on the returned handle:\n * `failed` means the copy did not complete.\n *\n * @throws {@link TypeError} `name` is empty, `from` is stated as\n * `undefined`, `timeoutMs` is invalid, or the Computer has no saved\n * version to fork from\n * @throws {@link ApiError} IDYL refuses the fork, such as for a name\n * another Computer holds or a version the Computer does not have\n * @throws {@link TransportError} a request does not complete, or the\n * answer names another Account or Namespace\n * @throws DOMException a `TimeoutError`: the copy does not finish\n * within `timeoutMs`; the fork goes on\n */\n async fork(options: ForkOptions): Promise<Computer> {\n const { name, idempotencyKey, workspaceOnly } = options;\n const stated = (options as { readonly from?: unknown }).from;\n if (\"from\" in options && (stated === undefined || stated === \"\")) {\n throw new TypeError(\n \"from names no history entry or version; leave it out to fork from the newest saved version\",\n );\n }\n const forkName = requireName(name);\n const wait = settleOptions(options);\n const { state, record } = internalsOf(this);\n const service = await serviceOf(state, options);\n const entry = await forkPoint(service, record.id, options);\n const { computer } = await service.create(\n {\n name: forkName,\n forkOf: { source: { computer: record.id }, entry },\n ...(workspaceOnly === undefined ? {} : { workspaceOnly }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n },\n signalOf(options),\n );\n // The copy is finished once it reports `done` or `failed`. A Computer\n // that reports no copy at all is read for a short while, in case the\n // copy appears late, and then taken as copied.\n const unreported = Date.now() + FORK_GRACE_MS;\n const settled =\n (await pollUntil(wait, {\n initial: computer,\n read: async (signal) =>\n (await service.getById(computer.id, { signal })).computer,\n met: (current) => {\n const copy = current.status?.fork?.state;\n return copy === undefined\n ? Date.now() >= unreported\n : copy === \"done\" || copy === \"failed\";\n },\n timeoutMessage: (ms) => `fork did not finish within ${String(ms)} ms`,\n })) ?? computer;\n return await handleOf(state, settled, options);\n }\n}\n\n/** The history entry a fork of the Computer `id` starts from. */\nasync function forkPoint(\n service: ComputersService,\n id: string,\n options: ForkOptions,\n): Promise<JournalEntryId> {\n const { from } = options;\n if (typeof from === \"string\" && isJournalEntryId(from)) {\n return parseJournalEntryId(from);\n }\n const version =\n from === undefined\n ? (await service.listVersionsById(id, { limit: 1 }, signalOf(options)))\n .items[0]\n : await service.getVersionById(\n id,\n versionSelector(from),\n signalOf(options),\n );\n if (version?.entry === undefined) {\n throw new TypeError(\"the Computer has no saved version to fork from\");\n }\n return parseJournalEntryId(version.entry);\n}\n\n/** The handle state of `computer`; it is how the other client modules reach it. */\nexport function handleStateOf(computer: Computer): {\n readonly state: HandleState;\n readonly id: string;\n} {\n const { state, record } = internalsOf(computer);\n return { state, id: record.id };\n}\n\n/** The Computers service of the handle's Namespace. */\nexport async function serviceOf(\n state: HandleState,\n options: CallOptions | undefined,\n): Promise<ComputersService> {\n const context = await state.context(signalOf(options));\n return computersService(context, context.scope.accountId, state.namespace);\n}\n\n/**\n * A handle for `record`, judged against the client's Account: a served\n * Computer of another Account, or of another Namespace, is never handed\n * back.\n */\nexport async function handleOf(\n state: HandleState,\n record: ComputerRecord,\n options: CallOptions | undefined,\n): Promise<Computer> {\n const context = await state.context(signalOf(options));\n return handleFor(state, record, context.scope.accountId);\n}\n\n/** A handle for `record`, judged against `accountId` and the Namespace. */\nexport function handleFor(\n state: HandleState,\n record: ComputerRecord,\n accountId: AccountId,\n): Computer {\n if (record.accountId !== accountId || record.namespace !== state.namespace) {\n throw new TransportError(\n \"invalid_response\",\n \"computer response names a different account or namespace\",\n );\n }\n const computer = Object.create(Computer.prototype) as Computer;\n internals.set(\n computer,\n Object.freeze({ state, record, snapshot: computerInfoOf(record) }),\n );\n return Object.freeze(computer);\n}\n\nfunction internalsOf(computer: Computer): Internals {\n const value = internals.get(computer);\n if (value === undefined) {\n throw new TypeError(\"receiver is not a Computer handle\");\n }\n return value;\n}\n\n/** The public snapshot of a served Computer. */\nexport function computerInfoOf(record: ComputerRecord): ComputerInfo {\n const { spec, executionSettings, usage, forkOf, status } = record;\n const fork = status?.fork;\n return Object.freeze({\n id: record.id,\n name: record.name,\n phase: record.phase,\n execution: record.execution,\n version: numberOf(record.headVersion),\n settings: settingsOf(spec.execution),\n ...(executionSettings === undefined\n ? {}\n : { effectiveSettings: settingsOf(executionSettings.effective) }),\n settingsPending: executionSettings?.pending === true,\n ...(executionSettings?.shells === undefined\n ? {}\n : {\n shells: Object.freeze(\n executionSettings.shells.map(({ name, path }) =>\n Object.freeze({ name, path }),\n ),\n ),\n }),\n ...(executionSettings?.largestSize === undefined ||\n executionSettings.largestSize === \"\"\n ? {}\n : { largestSize: executionSettings.largestSize }),\n idleTimeout: spec.idleTimeout ?? DEFAULT_IDLE_TIMEOUT,\n autoSave: spec.autoSave !== false,\n ...optional(\"saveQuiet\", spelled(spec.saveQuiet, formatDuration)),\n ...optional(\n \"saveMaxInterval\",\n spelled(spec.saveMaxInterval, formatDuration),\n ),\n ...(usage === undefined\n ? {}\n : {\n usage: Object.freeze({\n logicalBytes: numberOf(usage.logicalBytes),\n storedBytes: numberOf(usage.storedBytes),\n ...(usage.names === undefined\n ? {}\n : { names: numberOf(usage.names) }),\n }),\n }),\n ...(forkOf === undefined\n ? {}\n : {\n forkOf: Object.freeze({\n ...(forkOf.computer === undefined\n ? {}\n : { computerId: forkOf.computer }),\n version: numberOf(forkOf.version),\n }),\n }),\n ...(fork === undefined\n ? {}\n : {\n fork: Object.freeze({\n state: fork.state,\n copied: numberOf(fork.copied),\n total: numberOf(fork.total),\n }),\n }),\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n ...(record.terminatingAt === undefined\n ? {}\n : { terminatingAt: record.terminatingAt }),\n ...(record.lastUsedAt === undefined\n ? {}\n : { lastUsedAt: record.lastUsedAt }),\n ...(record.goingToSleep === true ? { goingToSleep: true } : {}),\n ...(record.awake === undefined ? {} : { awake: awakeOf(record.awake) }),\n });\n}\n\n/** The image catalogue entry a Computer can start from. */\nexport interface ComputerImage {\n /** The name a create or update states, such as `ubuntu-24.04`. */\n readonly name: string;\n /** The name to show a person, such as `Ubuntu 24.04`. */\n readonly displayName: string;\n /** A sentence on what the image holds; absent when the catalogue states none. */\n readonly description?: string;\n /** The operating system the image runs: its name and its version. */\n readonly os: { readonly name: string; readonly version: string };\n /** Whether the image carries GPU support. */\n readonly gpu: boolean;\n /** Its current patch level. */\n readonly patch: string;\n /**\n * Whether a create in the image's isolation class that states no image\n * receives this image.\n */\n readonly default: boolean;\n /**\n * The isolation class the image serves, `secure-container` or `vm`: only a\n * Computer in that class runs the image.\n */\n readonly isolation:\n \"secure-container\" | \"vm\" | (string & Record<never, never>);\n}\n\n/** Which images `images` lists. */\nexport interface ImagesOptions extends CallOptions {\n /**\n * The isolation class whose images to list, `secure-container` or `vm`.\n * The list of a class not offered where the Account's Computers live is\n * empty, so a class is offered exactly when its list is not. When absent, the\n * `secure-container` images are listed.\n */\n readonly isolation?: \"secure-container\" | \"vm\";\n}\n\n/** One size a Computer can run at, as offered by IDYL. */\nexport interface ComputerSizeInfo {\n /** The name `create` and `update` state, such as `small`. */\n readonly name: ComputerSize;\n /** The name to show a person, such as `Small`. */\n readonly label: string;\n /** The CPU limit, such as `2`. */\n readonly cpu: string;\n /** The memory limit, such as `4Gi`. */\n readonly memory: string;\n /** The most a Computer of this size can store, such as `20Gi`. */\n readonly disk: string;\n /**\n * The most files, folders and links a Computer of this size holds, such\n * as `2000000`. A save or an upload that adds names past it fails with\n * `SAVE_REASON_NAME_LIMIT`. `undefined` when the size has no such limit.\n */\n readonly names?: number;\n /** Whether a Computer that states no size, CPU or memory runs at this size. */\n readonly default: boolean;\n}\n\n/**\n * The Computers of the client's Namespace: `idyl.computers`.\n *\n * @example\n * ```ts\n * const computer = await idyl.computers.create({\n * name: \"research\",\n * image: \"ubuntu-24.04\",\n * });\n *\n * const same = await idyl.computers.get(\"research\");\n *\n * for await (const each of idyl.computers.list()) {\n * console.log(each.name, each.snapshot.execution);\n * }\n * ```\n */\nexport interface Computers {\n /**\n * Creates a Computer and returns its handle. Every setting is optional;\n * one left out takes IDYL's default, the image the catalogue's default.\n *\n * @throws {@link TypeError} an option is invalid, naming the field, before\n * any request is sent\n * @throws {@link ApiError} IDYL refuses the create, such as for a name\n * another Computer holds, or with `ERROR_CODE_IMAGE_NOT_IN_CATALOG` or\n * `ERROR_CODE_SIZE_NOT_IN_PLAN`\n * @throws {@link TransportError} the request does not complete, or the\n * answer names another Account or Namespace\n */\n create(options: CreateComputerOptions): Promise<Computer>;\n /**\n * The Computer with this name.\n *\n * @param name the Computer's name\n * @throws {@link TypeError} `name` is empty, before any request is sent\n * @throws {@link ApiError} IDYL refuses the read, such as for a name the\n * Namespace does not hold (status 404)\n * @throws {@link TransportError} the request does not complete, or the\n * answer names another Account or Namespace\n */\n get(name: string, options?: CallOptions): Promise<Computer>;\n /**\n * Every Computer of the Account, page by page, as handles. Each holds the\n * snapshot the listing read and acts on its Computer without reading it\n * again, as a handle from `get` does.\n *\n * @throws {@link TypeError} `limit` is not a positive integer\n * @throws {@link ApiError} IDYL refuses a page's request\n * @throws {@link TransportError} a page's request does not complete, or a\n * listed Computer belongs to another Account or Namespace\n */\n list(options?: ListOptions): AsyncIterable<Computer>;\n /**\n * One page of the Account's Computers, as handles.\n *\n * @throws {@link TypeError} `limit` is not a positive integer, or\n * `continue` is not a position this listing issued, before any request is\n * sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or a\n * listed Computer belongs to another Account or Namespace\n */\n listPage(options?: PageOptions): Promise<Page<Computer>>;\n /**\n * Every attachment of the Secret with this ID across the Namespace's\n * Computers that you may read, asleep or awake, ordered by Computer name\n * and then by variable: which Computer, through which variable, whether\n * it is attached there, and the version it is pinned to, if any. It lists\n * the settings each Computer applies from its next start. It is read at\n * one moment and is not paged, and it reads no Secret: an ID no Computer\n * you may read attaches reads as none.\n *\n * @param secretId a Secret's `id`, a canonical UUID\n * @throws {@link TypeError} `secretId` is not a canonical UUID, before any\n * request is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n listBySecret(\n secretId: string,\n options?: CallOptions,\n ): Promise<readonly ComputerSecretUse[]>;\n /**\n * The image catalogue a Computer can start from, for one isolation class:\n * `secure-container` unless `isolation` names another. Empty for a class\n * that is not offered.\n *\n * @throws {@link TypeError} `isolation` names no isolation class, before\n * any request is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n images(options?: ImagesOptions): Promise<readonly ComputerImage[]>;\n /**\n * The sizes a Computer can run at, smallest first, as IDYL offers them. The\n * read needs no credential and no Account.\n *\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n sizes(options?: CallOptions): Promise<readonly ComputerSizeInfo[]>;\n /**\n * A connector for the Account's Computers: the one way a command, a\n * terminal or a live files listing runs in a Computer.\n * Each session is end-to-end encrypted between the page and the\n * Computer, run by `options.worker`: a Worker that called\n * `serveComputerConnections` from `@idyl-sh/sdk/computer-connection`.\n * Nothing is sent until {@link ComputerConnector.ready} or a session.\n * `Computer.exec` runs on the connector built last, which stays open until\n * it is closed.\n *\n * @throws {@link TypeError} neither the options nor the client name a\n * network, or neither states trust keys\n */\n connector(options: ConnectorOptions): ComputerConnector;\n}\n\n/** What a Computer connector needs beyond the client. */\nexport interface ConnectorOptions {\n /** The Worker that runs the connections. */\n readonly worker: WorkerPort;\n /** `@idyl-sh/sdk/computer-connection.wasm`, compiled. */\n readonly module: WebAssembly.Module;\n /** The Network the client is configured for, as a domain; the client's when absent. */\n readonly network?: string;\n /** The Network trust keys the page pins; the client's when absent. */\n readonly trustKeys?: readonly TrustKey[];\n /** Where Computers were last placed, kept across page loads. */\n readonly placements?: PlacementMemory;\n /**\n * The kind of client every session create states. `sdk` when absent.\n */\n readonly client?: \"sdk\" | \"console\" | \"cli\";\n /**\n * Where the connector keeps the highest session trust version it has\n * accepted per Network and trust scope, and refuses an older bundle. When\n * absent, the page's one default floor: IndexedDB where the runtime\n * offers it, and memory for the life of the page where IndexedDB is\n * absent or its `open` throws before the page ever opened it; any other\n * storage failure refuses the bundle.\n */\n readonly trustFloor?: TrustFloor;\n}\n\n/** Builds the Computers of `namespace`. */\nexport function computers(\n context: (options?: CallOptions) => Promise<PlacementContext>,\n namespace: string,\n readSizes: (options?: CallOptions) => Promise<ListComputerSizesResponse>,\n network: {\n readonly network: string | undefined;\n readonly trustKeys: readonly TrustKey[] | undefined;\n },\n): Computers {\n const buildConnector = (\n options: ConnectorOptions & {\n readonly network: string;\n readonly trustKeys: readonly TrustKey[];\n },\n ): ComputerConnector =>\n computerConnector({\n worker: options.worker,\n module: options.module,\n network: options.network,\n trustKeys: options.trustKeys,\n ...(options.placements === undefined\n ? {}\n : { placements: options.placements }),\n client: clientOf(options.client),\n ...(options.trustFloor === undefined\n ? {}\n : { trustFloor: options.trustFloor }),\n account: async () => (await context()).scope.accountId,\n api: computerEndpointApi(() => context()),\n });\n const commands = connections({\n network: network.network,\n trustKeys: network.trustKeys,\n build: buildConnector,\n });\n const fresh = (): HandleState => ({\n context,\n namespace,\n connections: commands,\n });\n const service = async (options?: CallOptions) =>\n await serviceOf(fresh(), options);\n const listPage = async (\n options: PageOptions = {},\n ): Promise<Page<Computer>> => {\n const limit = requireLimit(options.limit);\n const offset = offsetOf(options.continue);\n const state = fresh();\n const page = await (\n await serviceOf(state, options)\n ).list(\n {\n ...(limit === undefined ? {} : { limit }),\n ...(offset === 0 ? {} : { offset }),\n },\n signalOf(options),\n );\n const handles = await Promise.all(\n page.items.map((record) => handleOf(state, record, options)),\n );\n const next = offset + page.items.length;\n return pageOf(\n handles,\n page.items.length > 0 && BigInt(next) < BigInt(page.totalCount)\n ? String(next)\n : undefined,\n );\n };\n return Object.freeze({\n async create(options: CreateComputerOptions) {\n const state = fresh();\n const name = requireName(options.name);\n const spec = settingsRequest(options);\n const client = clientOf(options.client);\n const { idempotencyKey, workspaceOnly } = options;\n const { computer } = await (\n await serviceOf(state, options)\n ).create(\n {\n name,\n ...(Object.keys(spec).length === 0 ? {} : { spec }),\n ...(workspaceOnly === undefined ? {} : { workspaceOnly }),\n ...(idempotencyKey === undefined ? {} : { idempotencyKey }),\n client,\n },\n signalOf(options),\n );\n return await handleOf(state, computer, options);\n },\n async get(name: string, options: CallOptions = {}) {\n const state = fresh();\n const computerName = requireName(name);\n const service = await serviceOf(state, options);\n const { computer } = await service.get(computerName, signalOf(options));\n return await handleOf(state, computer, options);\n },\n list: (options: ListOptions = {}) => walk(listPage, options),\n listPage,\n async listBySecret(secretId: string, options: CallOptions = {}) {\n // Judged before the client's context is read, so a refusal arrives\n // before anything is sent.\n if (!isResourceId(secretId)) {\n throw new TypeError(\"secret ID must be a canonical UUID\");\n }\n const { items } = await (\n await service(options)\n ).listBySecret(secretId, signalOf(options));\n return Object.freeze(items.map(computerSecretUseOf));\n },\n connector(options: ConnectorOptions) {\n const stated = options.network ?? commands.network;\n const keys = options.trustKeys ?? commands.trustKeys;\n if (stated === undefined) {\n throw new TypeError(\"network is required: the client names none\");\n }\n if (keys === undefined) {\n throw new TypeError(\"trustKeys is required: the client states none\");\n }\n return commands.adopt(\n buildConnector({ ...options, network: stated, trustKeys: keys }),\n );\n },\n async images(options: ImagesOptions = {}) {\n const { isolation } = options;\n // A class no Computer may select is refused before the client's\n // context, which may read the network, is resolved.\n if (isolation !== undefined) imageCatalogQuery(isolation);\n const computers = await service(options);\n const catalogue = await (isolation === undefined\n ? computers.listImages(signalOf(options))\n : computers.listImagesFor(isolation, signalOf(options)));\n return Object.freeze(\n catalogue.items.map((image) =>\n Object.freeze({\n name: image.name,\n displayName: image.displayName,\n ...(image.description === undefined\n ? {}\n : { description: image.description }),\n os: Object.freeze({\n name: image.os.name,\n version: image.os.version,\n }),\n gpu: image.gpu,\n patch: image.patch,\n default: image.default,\n isolation: image.isolation ?? \"secure-container\",\n }),\n ),\n );\n },\n async sizes(options: CallOptions = {}) {\n const { items } = await readSizes(options);\n return Object.freeze(\n items.map((size) =>\n Object.freeze({\n name: size.name,\n label: size.label,\n cpu: formatCpu(size.cpu),\n memory: formatMemory(size.memory),\n disk: formatVolume(size.disk),\n ...(size.names === undefined\n ? {}\n : { names: numberOf(size.names) }),\n default: size.default,\n }),\n ),\n );\n },\n });\n}\n\nfunction offsetOf(value: string | undefined): number {\n if (value === undefined) return 0;\n if (!/^(?:0|[1-9][0-9]{0,15})$/u.test(value)) {\n throw new TypeError(\"continue is not a position this listing issued\");\n }\n return Number(value);\n}\n\nfunction requireName(name: unknown): string {\n if (typeof name !== \"string\" || name.trim() === \"\") {\n throw new TypeError(\"computer name is required\");\n }\n return name;\n}\n\n/** A saved version selected by number or by name, as the contract spells it. */\nfunction versionSelector(version: number | string): string {\n if (typeof version === \"number\") {\n if (!Number.isSafeInteger(version) || version < 0) {\n throw new TypeError(\"version must be a non-negative integer or a name\");\n }\n return String(version);\n }\n if (typeof version !== \"string\" || version.trim() === \"\") {\n throw new TypeError(\"version must be a non-negative integer or a name\");\n }\n return version;\n}\n\n/**\n * An operation that ended without the outcome asked for, as the `ApiError`\n * a refusal of it would be: status 409, the platform's reason as `detail`.\n * An operation whose reasons are stable codes also carries its reason as\n * `code`.\n */\nfunction outcomeRefused(\n operation: string,\n state: string,\n reason: string | undefined,\n coded = false,\n): ApiError {\n return new ApiError({\n status: 409,\n message: reason ?? `${operation} ended ${state}`,\n ...(coded && reason !== undefined ? { code: reason } : {}),\n });\n}\n\nfunction optional<K extends string>(\n key: K,\n value: string | undefined,\n): Readonly<Partial<Record<K, string>>> {\n return (value === undefined ? {} : { [key]: value }) as Readonly<\n Partial<Record<K, string>>\n >;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { BillingAllowanceWithheld } from \"../api/billing.js\";\nimport type { ProfileTokenRequest } from \"../api/auth-profile.js\";\nimport type { SignInReader } from \"../api/auth.js\";\nimport { TransportError } from \"../errors.js\";\nimport { parseAccountId } from \"../resource/id.js\";\nimport { parseAccessKeyId, parseProfileId } from \"../resource/uuid-id.js\";\nimport type { IdentityService } from \"../services/identity.js\";\nimport { requireText, signalOf, type CallOptions } from \"./common.js\";\n\n/**\n * A profile a person can act as: one Account and the permissions the profile\n * grants there. `orgId` and `org` are present when the Account belongs to an\n * organization.\n */\nexport interface Profile {\n /** The Account's twelve-digit ID. */\n readonly accountId: string;\n /** The Account's name. */\n readonly accountName: string;\n /** The Account's contact address. */\n readonly accountEmail: string;\n /** The organization's twelve-digit ID; absent for an Account outside one. */\n readonly orgId?: string;\n /** The organization's name; absent for an Account outside one. */\n readonly org?: string;\n /** The profile's ID, a lowercase canonical UUID. */\n readonly profileId: string;\n /** The profile's name. */\n readonly profileName: string;\n}\n\n/**\n * Starts a sign-in or sends another code. `timeZone` and `locale` say how\n * the person signing in reads dates and times, so that IDYL's emails can\n * show them that way: the email carrying the code uses them at once, and a\n * verified sign-in keeps them for later emails. None of the fields is\n * authority: a value the server cannot use is ignored, never refused, and an\n * empty one is not sent. Code running on a server sets them from the\n * person's own browser or device, never from the server's.\n */\nexport interface SignInOptions extends CallOptions {\n /**\n * An IANA tz database name, such as `Europe/Berlin`, or a fixed offset from\n * UTC, such as `+05:30`.\n */\n readonly timeZone?: string;\n /** A BCP 47 language tag, such as `de-DE`. */\n readonly locale?: string;\n /**\n * The `User-Agent` of the browser asking for the code, set by a server\n * that starts a sign-in on a browser's behalf, so the email can say which\n * browser asked. The server reads a known browser and operating system from\n * it and shows nothing else. The value is not kept.\n */\n readonly userAgent?: string;\n}\n\n/**\n * A refresh token and the key it is bound to. Every exchange that presents\n * the token proves possession of `key`; the token alone is useless. The\n * exchanges that mint a token, {@link Identity.accessToken} and\n * {@link Identity.authorizeBrowser}, retire the refresh token they present\n * and return its successor, which the holder keeps in its place. A retired\n * token presented again with its key is answered with a fresh successor, so\n * concurrent exchanges by one holder all succeed.\n */\nexport interface RefreshCredential {\n /** The refresh token, presented as issued and never inspected. */\n readonly refreshToken: string;\n /** The key pair the token is bound to, which signs each exchange's proof. */\n readonly key: CryptoKeyPair;\n}\n\n/**\n * The result of a verified sign-in code. `refreshToken` is bound to the key\n * whose proof the verification carried and is presented with it, as a\n * {@link RefreshCredential}, by every later exchange; `expiresAt` is its\n * RFC 3339 expiry. `profiles` lists the profiles the person can act as,\n * when the platform included them, and `accessToken` is present, bound to\n * the same key, when a default profile could be assumed at once.\n *\n * A refresh token is a long-lived credential. Where it is kept is the\n * application's decision; it is useless without its key, and a browser\n * page keeps that key non-extractable.\n */\nexport interface SignIn {\n /** The refresh token, bound to the verifying key. */\n readonly refreshToken: string;\n /** When the refresh token expires, as an RFC 3339 instant. */\n readonly expiresAt: string;\n /** The profiles the person can act as; absent when the platform did not list them. */\n readonly profiles?: readonly Profile[];\n /** An access token for the default profile; absent when none could be assumed at once. */\n readonly accessToken?: string;\n}\n\n/**\n * Chooses the profile a refresh token is exchanged for. The Account is named\n * by `account` (its name, as `org/account`) or by `accountId`, and the\n * profile by `profile` (its name) or by `profileId`. With nothing set, the\n * platform chooses the person's default profile.\n */\nexport interface ProfileSelector {\n /** The Account's name, as `org/account`. */\n readonly account?: string;\n /** The Account's twelve-digit ID. */\n readonly accountId?: string;\n /** The profile's name. */\n readonly profile?: string;\n /** The profile's ID, a lowercase canonical UUID. */\n readonly profileId?: string;\n}\n\n/**\n * A short-lived access token for one Account and profile, and what it acts\n * as. It is bound to the key whose proof obtained it: present it with that\n * key as a `Credential`. `expiresAt` is its RFC 3339 expiry.\n *\n * `refreshToken` is present when the exchange rotated or issued one: the\n * successor of the refresh token {@link Identity.accessToken} presented,\n * which replaces it, or the refresh token {@link Identity.exchangeBrowser}\n * issues bound to the browser's key. `refreshExpiresAt` is its expiry. An\n * access key's exchange names no profile, so its `profileId` and `profileName`\n * are empty.\n */\nexport interface AccessToken {\n /** The access token, bound to the key whose proof obtained the token. */\n readonly accessToken: string;\n /** When the access token expires, as an RFC 3339 instant. */\n readonly expiresAt: string;\n /** The refresh token the exchange rotated or issued; absent when it did neither. */\n readonly refreshToken?: string;\n /**\n * When `refreshToken` expires, as an RFC 3339 instant; absent when\n * `refreshToken` is absent.\n */\n readonly refreshExpiresAt?: string;\n /** The twelve-digit ID of the Account the token acts in. */\n readonly accountId: string;\n /** The name of the Account the token acts in. */\n readonly accountName: string;\n /** The organization's twelve-digit ID; absent for an Account outside one. */\n readonly orgId?: string;\n /** The organization's name; absent for an Account outside one. */\n readonly org?: string;\n /** The profile's ID; empty for an access key's token. */\n readonly profileId: string;\n /** The profile's name; empty for an access key's token. */\n readonly profileName: string;\n}\n\n/** Creates the first Account of a signed-in person. */\nexport interface SignUpRequest {\n /** Must be `true`: the person accepts the terms of service. */\n readonly acceptedTerms: boolean;\n /** The Account's display name; the platform chooses one when absent. */\n readonly displayName?: string;\n}\n\n/**\n * What an Account the signed-in person creates would start with. The\n * decision is made when the Account is created, and reading this reserves\n * nothing.\n */\nexport interface SignUpOffer {\n /** Whether the Account would start on a free trial. */\n readonly trial: boolean;\n /**\n * Why it would not, when a trial is withheld: `trial_one_per_person` when\n * the person already has one, or `trials_closed`. `undefined` when a trial\n * is offered or when none is offered to anyone.\n */\n readonly trialWithheld?: BillingAllowanceWithheld;\n}\n\n/**\n * What sign-up created: the Account and the owner profile the person can\n * assume at once.\n */\nexport interface SignUp {\n /** The Account created: its twelve-digit ID and its display name. */\n readonly account: { readonly id: string; readonly displayName: string };\n /** The owner profile of the Account, which the person can assume. */\n readonly profile: {\n readonly accountId: string;\n readonly accountName: string;\n readonly profileId: string;\n readonly profileName: string;\n };\n}\n\n/**\n * A browser authorization: a registered client, its exact redirect URI, a\n * state value of 32 random bytes encoded as unpadded base64url, the S256\n * PKCE challenge of a verifier the page keeps, and `dpopJkt`, the\n * thumbprint of the page's own key (see `keyThumbprint`). `profile` must\n * name the Account and profile by `accountId` and `profileId`.\n */\nexport interface BrowserAuthorizationRequest {\n /** The registered client's ID. */\n readonly clientId: string;\n /** The redirect URI, exactly as registered by the client. */\n readonly redirectUri: string;\n /** 32 random bytes as unpadded base64url, which the page checks on return. */\n readonly state: string;\n /** The RFC 7636 S256 challenge of the verifier the page keeps. */\n readonly codeChallenge: string;\n /**\n * The RFC 7638 thumbprint of the page's key, as returned by `keyThumbprint`.\n */\n readonly dpopJkt: string;\n /** The Account and profile the page acts as, named by `accountId` and `profileId`. */\n readonly profile: ProfileSelector;\n}\n\n/**\n * A short-lived, single-use code, redeemable only with a proof by the key\n * the authorization named, and the successor of the refresh token the\n * authorization presented, which the successor replaces. `expiresAt` is the\n * code's expiry and `refreshExpiresAt` the successor's.\n */\nexport interface BrowserAuthorization {\n /** The single-use code the page redeems. */\n readonly code: string;\n /** When the code expires, as an RFC 3339 instant. */\n readonly expiresAt: string;\n /** The successor of the refresh token the authorization presented. */\n readonly refreshToken: string;\n /** When the successor expires, as an RFC 3339 instant. */\n readonly refreshExpiresAt: string;\n}\n\n/** Redeems a browser authorization code with its transaction and verifier. */\nexport interface BrowserExchangeRequest {\n /** The code {@link Identity.authorizeBrowser} issued. */\n readonly code: string;\n /** The client ID the authorization named. */\n readonly clientId: string;\n /** The redirect URI the authorization named. */\n readonly redirectUri: string;\n /** The state the authorization named. */\n readonly state: string;\n /** The RFC 7636 verifier whose S256 challenge the authorization carried. */\n readonly codeVerifier: string;\n}\n\n/**\n * Sign-in for people and access keys: email codes, sign-up, the profiles a\n * person can act as, access tokens, the browser handoff, access key\n * exchanges and sign-out.\n *\n * Every token IDYL issues is bound to a key its holder keeps. Verifying a\n * code, redeeming a browser code and exchanging an access key prove a key\n * and bind the tokens they issue to it; every other call presents a\n * {@link RefreshCredential} for that one request only. Starting sign-in is\n * anonymous. None of them consults the client's `credential`. No token is\n * kept, inspected or logged, and no message carries one.\n *\n * @example\n * ```ts\n * const key = await crypto.subtle.generateKey({ name: \"Ed25519\" }, false, [\n * \"sign\",\n * \"verify\",\n * ]);\n * await idyl.identity.startSignIn(\"ada@example.com\");\n * const { refreshToken } = await idyl.identity.verifyCode(\n * \"ada@example.com\",\n * \"123456\",\n * key,\n * );\n * const token = await idyl.identity.accessToken({ refreshToken, key });\n * ```\n */\nexport interface Identity {\n /**\n * Sends a six-digit sign-in code to `email`. The answer is the same\n * whether or not the address belongs to anyone.\n *\n * @param email The address to send the code to.\n * @throws {@link TypeError} `email` is blank; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n startSignIn(email: string, options?: SignInOptions): Promise<void>;\n /**\n * Sends another sign-in code, answering as {@link Identity.startSignIn} does.\n *\n * @param email The address the sign-in was started for.\n * @throws {@link TypeError} `email` is blank; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n resendCode(email: string, options?: SignInOptions): Promise<void>;\n /**\n * Verifies a sign-in code with a proof by `key`, the client's key, and\n * returns a refresh token bound to that key.\n *\n * @param email The address the code was sent to.\n * @param code The six-digit code from the email.\n * @param key The Ed25519 or ECDSA P-256 key pair the tokens are bound to;\n * its private key may be non-extractable.\n * @throws {@link TypeError} `email` or `code` is blank, or `key` cannot\n * sign; nothing is sent\n * @throws {@link ApiError} the code is wrong or expired, or IDYL refuses\n * the request\n * @throws {@link TransportError} the request does not complete, or the\n * response carries no refresh token or expiry\n */\n verifyCode(\n email: string,\n code: string,\n key: CryptoKeyPair,\n options?: CallOptions,\n ): Promise<SignIn>;\n /**\n * Creates the first Account of a signed-in person who has none.\n *\n * @param refresh The person's refresh token and its key.\n * @param request The acceptance of the terms and the Account's name.\n * @throws {@link TypeError} `acceptedTerms` is not `true`, or the refresh\n * credential cannot be presented; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n signUp(\n refresh: RefreshCredential,\n request: SignUpRequest,\n options?: CallOptions,\n ): Promise<SignUp>;\n /**\n * Reads what an Account the signed-in person creates would start with.\n * It reserves nothing: `signUp` makes the decision.\n *\n * @param refresh The person's refresh token and its key.\n * @throws {@link TypeError} the refresh credential is missing, its token is\n * empty or its key cannot sign; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n signUpOffer(\n refresh: RefreshCredential,\n options?: CallOptions,\n ): Promise<SignUpOffer>;\n /**\n * The profiles a refresh token's person can act as; the token is not\n * rotated.\n *\n * @param refresh The person's refresh token and its key.\n * @throws {@link TypeError} the refresh credential is missing, its token is\n * empty or its key cannot sign; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n profiles(\n refresh: RefreshCredential,\n options?: CallOptions,\n ): Promise<readonly Profile[]>;\n /**\n * Exchanges a refresh token for a short-lived access token for one\n * Account and profile, bound to the same key; with no selector, for the\n * default profile. The refresh token is rotated: the result's\n * `refreshToken` is its successor.\n *\n * @param refresh The person's refresh token and its key.\n * @param profile The Account and profile to act as; the default profile\n * when absent.\n * @throws {@link TypeError} `accountId` or `profileId` is malformed, or the\n * refresh credential cannot be presented; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or the\n * response carries no access token or expiry\n */\n accessToken(\n refresh: RefreshCredential,\n profile?: ProfileSelector,\n options?: CallOptions,\n ): Promise<AccessToken>;\n /**\n * Issues a single-use code that hands a browser page its own tokens:\n * bound to a registered client, its exact redirect URI, the state, an\n * S256 PKCE challenge and the page's key thumbprint, `dpopJkt`. The page\n * redeems it with {@link Identity.exchangeBrowser} and its key. The\n * refresh token is rotated: the result's `refreshToken` is its successor.\n *\n * @param refresh The person's refresh token and its key.\n * @param request The page's client, transaction and key thumbprint.\n * @throws {@link TypeError} a field of `request` is blank, `dpopJkt` is not\n * a SHA-256 key thumbprint, a profile ID is malformed, or the refresh\n * credential cannot be presented; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or the\n * response lacks the code, the successor or an expiry\n */\n authorizeBrowser(\n refresh: RefreshCredential,\n request: BrowserAuthorizationRequest,\n options?: CallOptions,\n ): Promise<BrowserAuthorization>;\n /**\n * Redeems a browser authorization code with its verifier and a proof by\n * `key`, the key the authorization named, for an access token and a\n * refresh token of a sign-in of the page's own, both bound to `key`.\n *\n * @param request The code, the transaction it was issued for, and the\n * verifier.\n * @param key The page's key pair, whose thumbprint the authorization named.\n * @throws {@link TypeError} a field of `request` is blank, or `key` cannot\n * sign; nothing is sent\n * @throws {@link ApiError} IDYL refuses the code, such as one already\n * redeemed or expired\n * @throws {@link TransportError} the request does not complete, or the\n * response carries no access token or expiry\n */\n exchangeBrowser(\n request: BrowserExchangeRequest,\n key: CryptoKeyPair,\n options?: CallOptions,\n ): Promise<AccessToken>;\n /**\n * Exchanges an access key for an access token. `key` is the access key's\n * key pair: the request's proof, signed by it, is the assertion, and the\n * token is bound to the same key. The token acts as the key's principal\n * in the key's Account and expires within an hour, never after the key\n * does; `accessKeyCredentials` keeps such a token fresh.\n *\n * @param accessKeyId The access key's ID, a lowercase canonical UUID.\n * @param key The access key's key pair.\n * @throws {@link TypeError} `accessKeyId` is not a lowercase canonical UUID,\n * or `key` cannot sign; nothing is sent\n * @throws {@link ApiError} IDYL refuses the exchange, such as for a revoked\n * or expired key\n * @throws {@link TransportError} the request does not complete, or the\n * response carries no access token or expiry\n */\n exchangeAccessKey(\n accessKeyId: string,\n key: CryptoKeyPair,\n options?: CallOptions,\n ): Promise<AccessToken>;\n /**\n * Ends the sign-in a refresh token belongs to: it and every token rotated\n * from the same sign-in are refused from then on.\n *\n * @param refresh The refresh token of the sign-in to end, and its key.\n * @throws {@link TypeError} the refresh credential is missing, its token is\n * empty or its key cannot sign; nothing is sent\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete\n */\n signOut(refresh: RefreshCredential, options?: CallOptions): Promise<void>;\n}\n\n/** Builds the sign-in surface over the identity service. */\nexport function identity(service: () => IdentityService): Identity {\n return Object.freeze({\n async startSignIn(email: string, options?: SignInOptions) {\n await service().startAuth(\n { email: requireText(email, \"email\"), ...readerOf(options) },\n signalOf(options),\n );\n },\n async resendCode(email: string, options?: SignInOptions) {\n await service().resendAuth(\n { email: requireText(email, \"email\"), ...readerOf(options) },\n signalOf(options),\n );\n },\n async verifyCode(\n email: string,\n code: string,\n key: CryptoKeyPair,\n options?: CallOptions,\n ) {\n return signInOf(\n await service().verifyAuth(\n {\n email: requireText(email, \"email\"),\n code: requireText(code, \"code\"),\n },\n key,\n signalOf(options),\n ),\n );\n },\n async signUp(\n refresh: RefreshCredential,\n request: SignUpRequest,\n options?: CallOptions,\n ) {\n const { acceptedTerms, displayName } = request;\n if ((acceptedTerms as unknown) !== true) {\n throw new TypeError(\"terms must be accepted to create an account\");\n }\n return signUpOf(\n await service().signup(\n refresh,\n {\n acceptedTerms,\n ...(displayName === undefined ? {} : { displayName }),\n },\n signalOf(options),\n ),\n );\n },\n async signUpOffer(refresh: RefreshCredential, options?: CallOptions) {\n const { trial, trialWithheld } = await service().getSignupOffer(\n refresh,\n signalOf(options),\n );\n return Object.freeze({\n trial: (trial as unknown) === true,\n ...(typeof trialWithheld === \"string\" && trialWithheld !== \"\"\n ? { trialWithheld }\n : {}),\n });\n },\n async profiles(refresh: RefreshCredential, options?: CallOptions) {\n const { profiles } = await service().listAssumableProfiles(\n refresh,\n signalOf(options),\n );\n const listed: unknown = profiles;\n return Object.freeze(\n (Array.isArray(listed) ? profiles : []).map(profileOf),\n );\n },\n async accessToken(\n refresh: RefreshCredential,\n profile: ProfileSelector = {},\n options?: CallOptions,\n ) {\n return accessTokenOf(\n await service().getProfileAccessToken(\n refresh,\n selector(profile),\n signalOf(options),\n ),\n );\n },\n async authorizeBrowser(\n refresh: RefreshCredential,\n request: BrowserAuthorizationRequest,\n options?: CallOptions,\n ) {\n const { clientId, redirectUri, state, codeChallenge, dpopJkt, profile } =\n request;\n if (!/^[A-Za-z0-9_-]{43}$/u.test(requireText(dpopJkt, \"dpopJkt\"))) {\n throw new TypeError(\"dpopJkt must be a SHA-256 key thumbprint\");\n }\n const authorized = await service().authorizeBrowser(\n refresh,\n {\n clientId: requireText(clientId, \"clientId\"),\n redirectUri: requireText(redirectUri, \"redirectUri\"),\n state: requireText(state, \"state\"),\n codeChallenge: requireText(codeChallenge, \"codeChallenge\"),\n dpopJkt,\n profile: selector(profile),\n },\n signalOf(options),\n );\n const label = \"browser authorization\";\n return Object.freeze({\n code: field(authorized, \"code\", label),\n expiresAt: field(authorized, \"expiresAt\", label),\n refreshToken: field(authorized, \"refreshToken\", label),\n refreshExpiresAt: field(authorized, \"refreshExpiresAt\", label),\n });\n },\n async exchangeBrowser(\n request: BrowserExchangeRequest,\n key: CryptoKeyPair,\n options?: CallOptions,\n ) {\n const { code, clientId, redirectUri, state, codeVerifier } = request;\n const exchanged = await service().exchangeBrowser(\n {\n code: requireText(code, \"code\"),\n clientId: requireText(clientId, \"clientId\"),\n redirectUri: requireText(redirectUri, \"redirectUri\"),\n state: requireText(state, \"state\"),\n codeVerifier: requireText(codeVerifier, \"codeVerifier\"),\n },\n key,\n signalOf(options),\n );\n return accessTokenOf(exchanged);\n },\n async exchangeAccessKey(\n accessKeyId: string,\n key: CryptoKeyPair,\n options?: CallOptions,\n ) {\n return accessTokenOf(\n await service().exchangeAccessKey(\n { accessKeyId: parseAccessKeyId(accessKeyId) },\n key,\n signalOf(options),\n ),\n );\n },\n async signOut(refresh: RefreshCredential, options?: CallOptions) {\n await service().logout(refresh, signalOf(options));\n },\n });\n}\n/**\n * The declared fields of a profile selector and nothing else, judged as\n * the contract's identifiers before any request.\n */\nfunction selector(profile: ProfileSelector): ProfileTokenRequest {\n const { account, accountId, profile: name, profileId } = profile;\n return {\n ...(account === undefined ? {} : { account }),\n ...(accountId === undefined\n ? {}\n : { accountId: parseAccountId(accountId) }),\n ...(name === undefined ? {} : { profile: name }),\n ...(profileId === undefined\n ? {}\n : { profileId: parseProfileId(profileId) }),\n };\n}\n\n/**\n * The reader fields of sign-in options and nothing else: each non-empty\n * string is sent, and an empty or missing one is left out, as the server\n * reads it as not known.\n */\nfunction readerOf(options: SignInOptions | undefined): SignInReader {\n const reader: { timeZone?: string; locale?: string; userAgent?: string } = {};\n for (const key of [\"timeZone\", \"locale\", \"userAgent\"] as const) {\n const value: unknown = options?.[key];\n if (typeof value === \"string\" && value !== \"\") reader[key] = value;\n }\n return reader;\n}\n\n/**\n * A credential field of a served sign-in record: a non-empty string, or the\n * record is unusable, an `invalid_response` `TransportError` naming only the\n * record and the field. Only fields a caller cannot proceed without are\n * held to this; every other field is read leniently, so a record the\n * platform has acted on is never refused for a display value.\n */\nfunction field(record: unknown, key: string, label: string): string {\n const value = text(record, key);\n if (value === \"\") {\n throw new TransportError(\n \"invalid_response\",\n `${label} response has no ${key}`,\n );\n }\n return value;\n}\n\n/** A display field of a served record: its string, or empty. */\nfunction text(record: unknown, key: string): string {\n const value =\n typeof record === \"object\" && record !== null\n ? (record as Record<string, unknown>)[key]\n : undefined;\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** An optional string of a served record, carried only when it is one. */\nfunction optional<K extends string>(\n record: unknown,\n key: K,\n): Readonly<Partial<Record<K, string>>> {\n const value = text(record, key);\n return (value === \"\" ? {} : { [key]: value }) as Readonly<\n Partial<Record<K, string>>\n >;\n}\n\nfunction profileOf(record: unknown): Profile {\n return Object.freeze({\n accountId: text(record, \"accountId\"),\n accountName: text(record, \"accountName\"),\n accountEmail: text(record, \"accountEmail\"),\n ...optional(record, \"orgId\"),\n ...optional(record, \"org\"),\n profileId: text(record, \"profileId\"),\n profileName: text(record, \"profileName\"),\n });\n}\n\nfunction accessTokenOf(record: unknown): AccessToken {\n return Object.freeze({\n accessToken: field(record, \"accessToken\", \"access token\"),\n expiresAt: field(record, \"expiresAt\", \"access token\"),\n ...optional(record, \"refreshToken\"),\n ...optional(record, \"refreshExpiresAt\"),\n accountId: text(record, \"accountId\"),\n accountName: text(record, \"accountName\"),\n ...optional(record, \"orgId\"),\n ...optional(record, \"org\"),\n profileId: text(record, \"profileId\"),\n profileName: text(record, \"profileName\"),\n });\n}\n\nfunction signInOf(record: unknown): SignIn {\n const profiles = (record as { profiles?: unknown } | null)?.profiles;\n return Object.freeze({\n refreshToken: field(record, \"refreshToken\", \"sign-in\"),\n expiresAt: field(record, \"expiresAt\", \"sign-in\"),\n ...(Array.isArray(profiles)\n ? { profiles: Object.freeze(profiles.map(profileOf)) }\n : {}),\n ...optional(record, \"accessToken\"),\n });\n}\n\n/**\n * The record of a sign-up, read leniently throughout: the Account exists\n * once the platform answered, so nothing in the answer is reason to fail.\n */\nfunction signUpOf(record: unknown): SignUp {\n const parts = (record ?? {}) as Record<string, unknown>;\n const { account, profile } = parts;\n return Object.freeze({\n account: Object.freeze({\n id: text(account, \"id\"),\n displayName: text(account, \"displayName\"),\n }),\n profile: Object.freeze({\n accountId: text(profile, \"accountId\"),\n accountName: text(profile, \"accountName\"),\n profileId: text(profile, \"profileId\"),\n profileName: text(profile, \"profileName\"),\n }),\n });\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { TrustKey } from \"../computer-connection/trust.js\";\nimport { decodeBase64 } from \"../resource/base64.js\";\n\n/**\n * The Network trust keys this package pins, by Network: each key's ID, the\n * RFC 7638 thumbprint of its Ed25519 JWK, and its raw public key as\n * standard base64. They are public keys, kept in source so that anyone can\n * read which keys a release trusts. A successor key needs no new release:\n * a Network announces it in a statement a pinned key signs.\n */\nconst PINNED: ReadonlyMap<\n string,\n readonly { readonly keyId: string; readonly publicKey: string }[]\n> = new Map([\n [\n \"idyl.sh\",\n [\n {\n keyId: \"vZZ-WibhORIZdMICCA6lPBTqrmOlsAl3mxASYfOOQ-I\",\n publicKey: \"/+hVsiFC1uACHFnyv/LzB1mx+sl9vQO0ogTRog12B40=\",\n },\n ],\n ],\n]);\n\n/**\n * The trust keys this package pins for `network`, as fresh copies a caller\n * may keep, or `undefined` when it pins none for that Network.\n */\nexport function pinnedTrustKeys(network: string): TrustKey[] | undefined {\n return PINNED.get(network)?.map(({ keyId, publicKey }) => ({\n keyId,\n publicKey: decodeBase64(publicKey),\n }));\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\nimport type { CurrentAccountResponse } from \"../api/auth.js\";\nimport type { TrustKey } from \"../computer-connection/trust.js\";\nimport type { CredentialSource } from \"../credential.js\";\nimport { TransportError } from \"../errors.js\";\nimport { abortable } from \"../internal/abort.js\";\nimport type { PlacementContext, ServiceState } from \"../internal/context.js\";\nimport { ProofClock } from \"../internal/dpop.js\";\nimport { resolveEndpointSet } from \"../internal/endpoints.js\";\nimport {\n networkPlacement,\n type PlacementSource,\n} from \"../internal/placement.js\";\nimport { Transport, type TransportOptions } from \"../internal/transport.js\";\nimport { DEFAULT_USER_AGENT } from \"../internal/version.js\";\nimport { isAccountId, type AccountId } from \"../resource/id.js\";\nimport { validateVaultReferenceName } from \"../resource/secret.js\";\nimport { deleteAccount, getCurrentAccount } from \"../services/account.js\";\nimport { listComputerSizes } from \"../services/computer-sizes.js\";\nimport { identityService } from \"../services/identity.js\";\nimport { accessKeySource } from \"./access-key-file.js\";\nimport { accessKeys, type AccessKeys } from \"./access-keys.js\";\nimport { billing, type Billing } from \"./billing.js\";\nimport { signalOf, type CallOptions } from \"./common.js\";\nimport { computers, type Computers } from \"./computer.js\";\nimport { identity, type Identity } from \"./identity.js\";\nimport { pinnedTrustKeys } from \"./network-trust.js\";\nimport { secrets, type Secrets } from \"./secrets.js\";\n\n/** The network a client addresses when its options name none. */\nconst DEFAULT_NETWORK = \"idyl.sh\";\n\n/** The Namespace a client addresses when its options name none. */\nconst DEFAULT_NAMESPACE = \"default\";\n\n/** Explicit origins for the public endpoints, each `https://host[:port]`. */\nexport interface Endpoints {\n /** The API that serves Accounts, Computers, Secrets and billing. */\n readonly api?: string;\n /** The identity service that signs people in and issues tokens. */\n readonly identity?: string;\n /** The public metadata service, which lists the sizes a Computer can run at. */\n readonly meta?: string;\n}\n\n/**\n * Configures an {@link Idyl} client. Everything the client uses is in these\n * options: it reads no environment variable and no file, holds no default\n * credential, and discovers no private endpoint.\n */\nexport interface IdylOptions {\n /**\n * An access key: the text of its key file, as it was given when the key\n * was created. The client takes its network from the file, and exchanges\n * the key for access tokens as `accessKeyCredentials` does. Stating it with\n * `credential`, or with a `network` other than the file's, is a `TypeError`,\n * and so is `undefined`, as from an environment variable that is not set.\n */\n readonly accessKey?: string | undefined;\n /**\n * Supplies the access token and key of every authenticated request,\n * consulted for each one: `accessKeyCredentials` for an access key,\n * `staticCredential` for a fixed token, or a source of the\n * application's own. Without it, the client signs people in through\n * {@link Idyl.identity}, lists the sizes a Computer can run at through\n * `computers.sizes()`, and refuses every other call with a `TypeError`\n * before anything is sent. Neither one consults `credential`.\n */\n readonly credential?: CredentialSource;\n /**\n * The IDYL network's public API domain, such as `idyl.sh`, from\n * which the endpoints derive. Defaults to `idyl.sh`.\n */\n readonly network?: string;\n /**\n * The Namespace of the Account that `computers` and `secrets` address,\n * such as `team-a`: 1 to 63 lowercase letters, digits, `.`, `_` and `-`,\n * beginning and ending with a letter or a digit. Defaults to `default`,\n * the Namespace every Account has. Another Namespace takes another\n * client.\n */\n readonly namespace?: string;\n /**\n * The trust keys of the network, which commands and terminals verify the\n * network's session trust against. Defaults to the keys this package\n * pins for the network, which it does for `idyl.sh`; any other network\n * needs its keys stated here.\n */\n readonly trustKeys?: readonly TrustKey[];\n /**\n * Explicit endpoints, for tests. With `network`, they override the\n * endpoints derived from it; without it, all three must be given.\n */\n readonly endpoints?: Endpoints;\n /**\n * Performs every request, called with no receiver exactly as\n * `fetch(url, init)` is. TLS, proxy and dialing behaviour belong to that\n * function. Defaults to the runtime's `fetch`.\n */\n readonly fetch?: typeof globalThis.fetch;\n /**\n * Permits `http:` endpoints. Cleartext exposes tokens and proofs to the\n * network path, so it is for local development only.\n */\n readonly allowHttp?: boolean;\n /**\n * Appended to the package's own `User-Agent`, to name the application.\n * In a browser page the browser owns that header and may ignore the value.\n */\n readonly userAgent?: string;\n}\n\n/** The Account a client's credential acts as. */\nexport interface Account {\n /** The Account's twelve-digit identifier. */\n readonly id: string;\n /** The Account's email address; empty when IDYL reports none. */\n readonly email: string;\n /** The Account's display name; empty when IDYL reports none. */\n readonly displayName: string;\n}\n\n/** What deleting an Account returns. */\nexport interface DeleteAccountResult {\n /** Whether IDYL accepted the deletion. */\n readonly accepted: boolean;\n}\n\n/**\n * The IDYL client. It holds what every product shares: the credential\n * source, the Account it acts as, and the connection. Each product is one of\n * its properties.\n *\n * The Account is the one the credential acts as, read once, on first use,\n * and kept for the life of the client; another Account takes another\n * client. A client is safe to share across concurrent calls.\n *\n * @example\n * ```ts\n * import { Idyl } from \"@idyl-sh/sdk\";\n *\n * const idyl = new Idyl({ accessKey: process.env.IDYL_ACCESS_KEY });\n * const computer = await idyl.computers.create({ name: \"eval\" });\n * ```\n */\nexport class Idyl {\n readonly #state: ServiceState;\n readonly #identity: Identity;\n readonly #accessKeys: AccessKeys;\n readonly #billing: Billing;\n readonly #computers: Computers;\n readonly #secrets: Secrets;\n readonly #namespace: string;\n readonly #placement: PlacementSource;\n #account: Promise<Account> | undefined;\n #context: PlacementContext | undefined;\n\n /**\n * Builds a client. Nothing is sent until a call is made.\n *\n * @param options The client's configuration; every option is optional.\n * @throws {@link TypeError} an option is invalid; the message names the\n * first invalid option\n */\n constructor(options: IdylOptions = {}) {\n if (\n typeof (options as unknown) !== \"object\" ||\n (options as unknown) === null\n ) {\n throw new TypeError(\"options must be an object\");\n }\n if (options.accessKey !== undefined && options.credential !== undefined) {\n throw new TypeError(\"state accessKey or credential, not both\");\n }\n if (\"accessKey\" in options && options.accessKey === undefined) {\n throw new TypeError(\n \"accessKey is undefined: the variable that should hold it is not set\",\n );\n }\n const access =\n options.accessKey === undefined\n ? undefined\n : accessKeySource(options.accessKey, () => this.#identity);\n if (\n access !== undefined &&\n options.network !== undefined &&\n options.network !== access.network\n ) {\n throw new TypeError(\"network is not the network the access key names\");\n }\n const namespace = options.namespace ?? DEFAULT_NAMESPACE;\n if (typeof (namespace as unknown) !== \"string\") {\n throw new TypeError(\"namespace must be a string\");\n }\n validateVaultReferenceName(\"namespace\", namespace);\n this.#namespace = namespace;\n const credential = access?.source ?? options.credential;\n const allowHttp = options.allowHttp ?? false;\n if (typeof allowHttp !== \"boolean\") {\n throw new TypeError(\"allowHttp must be a boolean\");\n }\n // Explicit endpoints without a network stand alone: nothing is filled\n // in from the production network, so a credential meant for another\n // deployment is never sent there.\n const explicit = options.endpoints;\n const stated = options.network ?? access?.network;\n const standalone = explicit !== undefined && stated === undefined;\n if (standalone) {\n for (const key of [\"api\", \"identity\", \"meta\"] as const) {\n if (explicit[key] === undefined) {\n throw new TypeError(\n `endpoints.${key} is required when endpoints are given without network`,\n );\n }\n }\n }\n const network = standalone ? undefined : (stated ?? DEFAULT_NETWORK);\n const endpoints = resolveEndpointSet(network, explicit, allowHttp, \"API\");\n // One clock for every transport of the client, so a proof states the\n // API's time whichever transport learned it.\n const transportOptions: Omit<TransportOptions, \"credential\"> = {\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n ...userAgentOption(options.userAgent),\n allowHttp,\n clock: new ProofClock(),\n };\n const transport = new Transport({\n ...credentialOption(credential),\n ...transportOptions,\n });\n this.#state = Object.freeze({\n endpoints,\n scheme: new URL(endpoints.api).protocol === \"http:\" ? \"http:\" : \"https:\",\n transport,\n });\n this.#placement = networkPlacement(this.#state);\n const identityEndpoints = {\n identity: requireEndpoint(endpoints.identity, \"identity\"),\n api: endpoints.api,\n };\n let service: ReturnType<typeof identityService> | undefined;\n this.#identity = identity(\n () => (service ??= identityService(identityEndpoints, transportOptions)),\n );\n this.#computers = computers(\n (call) => this.#contextOf(call),\n namespace,\n (call) => listComputerSizes(this.#state, signalOf(call ?? {})),\n {\n network,\n trustKeys:\n options.trustKeys ??\n (network === undefined ? undefined : pinnedTrustKeys(network)),\n },\n );\n this.#secrets = secrets((call) => this.#contextOf(call));\n this.#billing = billing((call) => this.#contextOf(call));\n this.#accessKeys = accessKeys({\n state: this.#state,\n network,\n account: (call) => this.account(call),\n });\n }\n\n /**\n * The Account the credential acts as. It is read once, on first use; a\n * read that fails is not kept, so the next call reads again.\n *\n * @throws {@link TypeError} the client has no credential, or its\n * credential source returns one that cannot be presented\n * @throws {@link ApiError} IDYL refuses the request\n * @throws {@link TransportError} the request does not complete, or the\n * response names no valid Account\n */\n async account(options?: CallOptions): Promise<Account> {\n const read = (this.#account ??= getCurrentAccount(this.#state)\n .then(accountOf)\n .catch((error: unknown) => {\n this.#account = undefined;\n throw error;\n }));\n return options?.signal === undefined\n ? await read\n : await abortable(read, options.signal);\n }\n\n /**\n * The Computers of the client's Namespace: create, get, list, the image\n * catalogue and the sizes.\n */\n get computers(): Computers {\n return this.#computers;\n }\n\n /**\n * The Secrets of the client's Namespace, whose values IDYL adds to a\n * Computer's requests to the origins each allows: create, get and delete.\n */\n get secrets(): Secrets {\n return this.#secrets;\n }\n\n /** The Namespace the client addresses. */\n get namespace(): string {\n return this.#namespace;\n }\n\n /**\n * Sign-in for people and access keys: email codes, sign-up, profiles,\n * access tokens and access key exchanges.\n */\n get identity(): Identity {\n return this.#identity;\n }\n\n /** Access keys for programs and servers: create, list and revoke. */\n get accessKeys(): AccessKeys {\n return this.#accessKeys;\n }\n\n /**\n * The Account's billing: its plan, usage and settings, its plan changes,\n * its purchases of extra usage and its Stripe portal sessions.\n */\n get billing(): Billing {\n return this.#billing;\n }\n\n /**\n * Deletes the Account the credential acts as. `accepted` is `true` when\n * IDYL accepted the deletion.\n *\n * @throws {@link TypeError} the client has no credential, or its\n * credential source returns one that cannot be presented\n * @throws {@link ApiError} IDYL refuses the deletion, for example of a\n * credential without the permission to delete the Account; nothing is\n * deleted\n * @throws {@link TransportError} the request does not complete, or the\n * response is not an object\n */\n async deleteAccount(options?: CallOptions): Promise<DeleteAccountResult> {\n const accountId = parseAccount(await this.account(signalOf(options)));\n const response: unknown = await deleteAccount(\n this.#state,\n accountId,\n signalOf(options),\n );\n if (typeof response !== \"object\" || response === null) {\n throw new TransportError(\n \"invalid_response\",\n \"account deletion response is not an object\",\n );\n }\n const { accepted } = response as { readonly accepted?: unknown };\n return Object.freeze({ accepted: accepted === true });\n }\n\n /** The services' view of this client, once the Account is known. */\n async #contextOf(options?: CallOptions): Promise<PlacementContext> {\n const accountId = parseAccount(await this.account(signalOf(options)));\n if (this.#context?.scope.accountId !== accountId) {\n this.#context = Object.freeze({\n state: this.#state,\n scope: Object.freeze({ accountId, namespace: this.#namespace }),\n placement: this.#placement,\n });\n }\n return this.#context;\n }\n}\n\nfunction credentialOption(\n credential: unknown,\n): Pick<TransportOptions, \"credential\"> {\n if (credential === undefined) return {};\n if (\n typeof credential !== \"object\" ||\n credential === null ||\n typeof (credential as Partial<CredentialSource>).credential !== \"function\"\n ) {\n throw new TypeError(\n \"credential must be a CredentialSource, such as staticCredential or accessKeyCredentials returns\",\n );\n }\n return { credential: credential as CredentialSource };\n}\n\nfunction userAgentOption(\n userAgent: unknown,\n): Pick<TransportOptions, \"userAgent\"> {\n if (userAgent === undefined) return {};\n if (typeof userAgent !== \"string\" || /[\\r\\n]/u.test(userAgent)) {\n throw new TypeError(\"userAgent must be a single-line string\");\n }\n const trimmed = userAgent.trim();\n return trimmed === \"\"\n ? {}\n : { userAgent: `${DEFAULT_USER_AGENT} ${trimmed}` };\n}\n\nfunction requireEndpoint(value: string | undefined, label: string): string {\n if (value === undefined) {\n throw new TypeError(`${label} endpoint is required`);\n }\n return value;\n}\n\n/** The public view of the current-account response, judged as it is read. */\nfunction accountOf(response: CurrentAccountResponse): Account {\n if (typeof response !== \"object\" || !isAccountId(response.id)) {\n throw new TransportError(\n \"invalid_response\",\n \"current account response names no valid account\",\n );\n }\n return Object.freeze({\n id: response.id,\n email: typeof response.email === \"string\" ? response.email : \"\",\n displayName:\n typeof response.displayName === \"string\" ? response.displayName : \"\",\n });\n}\n\nfunction parseAccount(account: Account): AccountId {\n return account.id as AccountId;\n}\n","// Copyright 2026 Idyl Labs. SPDX-License-Identifier: Apache-2.0\n\n/*\n * The stable codes an `ApiError` carries that a caller of this package may\n * branch on. Match them with `isApiCode(error, code)`, never on a message.\n */\n\nimport {\n SAVE_REASON_ACCOUNT_STORAGE_LIMIT,\n SAVE_REASON_COMPUTER_SIZE,\n SAVE_REASON_NAME_LIMIT,\n} from \"../api/storage.js\";\n\n/**\n * Execution is not turned on for the Computer, so it runs no command. A\n * command runs once execution is turned on.\n */\nexport const ERROR_CODE_EXECUTION_NOT_ENABLED = \"EXECUTION_NOT_ENABLED\";\n\n/**\n * A `files` session asked of a Computer that is not awake (HTTP 409). The\n * Computer is neither woken nor kept awake; its saved files are listed\n * instead. It is always a `ComputerNotAwakeError`.\n */\nexport const ERROR_CODE_COMPUTER_NOT_AWAKE = \"COMPUTER_NOT_AWAKE\";\n\n/** A command or terminal in a Computer that is being deleted. */\nexport const ERROR_CODE_COMPUTER_TERMINATING = \"COMPUTER_TERMINATING\";\n\n/**\n * The Computer's CPU and memory fit no machine that could run it, so it\n * cannot start until an update gives it a size that fits.\n */\nexport const ERROR_CODE_PROFILE_FITS_NO_HOST = \"PROFILE_FITS_NO_HOST\";\n\n/**\n * The Computer was not ready in time for a command. A later attempt may\n * succeed.\n */\nexport const ERROR_CODE_WAKE_TIMEOUT = \"WAKE_TIMEOUT\";\n\n/**\n * A limit on concurrent commands and terminals is reached (HTTP 429).\n * Another can start once one of them ends.\n */\nexport const ERROR_CODE_SESSION_BUDGET_EXCEEDED = \"SESSION_BUDGET_EXCEEDED\";\n\n/**\n * No machine that could run the Computer has the CPU and memory free for it\n * when the request arrives. Unlike `ERROR_CODE_PROFILE_FITS_NO_HOST`, a\n * later attempt can succeed once capacity is released.\n */\nexport const ERROR_CODE_INSUFFICIENT_CAPACITY = \"INSUFFICIENT_CAPACITY\";\n\n/**\n * No machine that could run the Computer has the disk space its files\n * need. A later attempt can succeed once space is freed.\n */\nexport const ERROR_CODE_INSUFFICIENT_DISK = \"INSUFFICIENT_DISK\";\n\n/**\n * The saved version the Computer starts from is damaged: its stored content\n * failed its integrity checks. Restoring another saved version lets it\n * start.\n */\nexport const ERROR_CODE_VERSION_DAMAGED = \"VERSION_DAMAGED\";\n\n/**\n * A sleep whose save of the Computer's files failed. Nothing was ended and\n * the Computer stays awake.\n */\nexport const ERROR_CODE_SAVE_FAILED = \"SAVE_FAILED\";\n\n/**\n * A sleep whose Computer could not be released in time. It stays awake and\n * goes to sleep after its idle timeout.\n */\nexport const ERROR_CODE_SLEEP_TIMEOUT = \"SLEEP_TIMEOUT\";\n\n/** A renewal of a session that has already ended (HTTP 409). */\nexport const ERROR_CODE_SESSION_FINAL = \"SESSION_FINAL\";\n\n/**\n * A create or update names an image the catalogue does not hold (HTTP\n * 422); `idyl.computers.images()` lists the catalogue.\n */\nexport const ERROR_CODE_IMAGE_NOT_IN_CATALOG = \"IMAGE_NOT_IN_CATALOG\";\n\n/**\n * The CPU and memory asked for fit no machine that could run the Computer\n * (HTTP 422). The details state the largest size that fits one at the time\n * of the request, the size the snapshot's `largestSize` names, as its CPU\n * and memory under `maxCPU` and `maxMemory`.\n */\nexport const ERROR_CODE_COMPUTER_DOES_NOT_FIT = \"COMPUTER_DOES_NOT_FIT\";\n\n/**\n * A network class the Account may not use (HTTP 403). The details name the\n * refused class under `class` and the admitted ones under `allowed`.\n */\nexport const ERROR_CODE_NETWORK_CLASS_NOT_ADMITTED =\n \"NETWORK_CLASS_NOT_ADMITTED\";\n\n/**\n * An isolation class not offered where the Computer lives (HTTP 403), on a\n * create or on an update that moves the Computer to another class; a wake\n * or command of a Computer whose class is withdrawn there fails with it\n * too. The\n * details name the refused class under `isolation.class` and the offered\n * ones under `allowedIsolationClasses`. `idyl.computers.images({ isolation })`\n * is empty for a class that is not offered.\n */\nexport const ERROR_CODE_ISOLATION_CLASS_NOT_ADMITTED =\n \"ISOLATION_CLASS_NOT_ADMITTED\";\n\n/**\n * This release of the package is below the minimum the API supports (HTTP\n * 426). The details name the minimum and latest versions.\n */\nexport const ERROR_CODE_CLIENT_UPGRADE_REQUIRED = \"CLIENT_UPGRADE_REQUIRED\";\n\n/**\n * A disk size smaller than what the Computer's files already use, or a\n * change of its CPU and memory to a size whose disk cannot hold them (HTTP\n * 409). Earlier versions do not count. `sizeBelowUsage` reads its details:\n * the bytes the files use, the bytes the size holds, and, for a change of\n * size, the size named. Freeing space lets the change through.\n */\nexport const ERROR_CODE_SIZE_BELOW_USAGE = \"SIZE_BELOW_USAGE\";\n\n/** A disk size above the largest the Account may use. */\nexport const ERROR_CODE_SIZE_ABOVE_CAP = \"SIZE_ABOVE_CAP\";\n\n/** A saved version, by number or name, the Computer does not have. */\nexport const ERROR_CODE_VERSION_NOT_FOUND = \"VERSION_NOT_FOUND\";\n\n/** A fork whose source could not reach a point to copy from; try again. */\nexport const ERROR_CODE_FORK_NOT_QUIESCENT = \"FORK_NOT_QUIESCENT\";\n\n/** A path the workspace cannot hold, or one that is reserved. */\nexport const ERROR_CODE_PATH_INVALID = \"PATH_INVALID\";\n\n/** A file name a call writes that is not in Unicode normalization form C. */\nexport const ERROR_CODE_NAME_NOT_NFC = \"NAME_NOT_NFC\";\n\n/**\n * The Account's storage is not open, so its saved files can be neither read\n * nor written.\n */\nexport const ERROR_CODE_STORAGE_NOT_OPEN = \"STORAGE_NOT_OPEN\";\n\n/** The files were modified while the call ran; read again and retry. */\nexport const ERROR_CODE_HEAD_MOVED = \"HEAD_MOVED\";\n\n/** Files a call writes were modified by someone else first. */\nexport const ERROR_CODE_UPLOAD_CONFLICT = \"UPLOAD_CONFLICT\";\n\n/** A files change that went quiet for too long, so it cannot publish. */\nexport const ERROR_CODE_UPLOAD_EXPIRED = \"UPLOAD_EXPIRED\";\n\n/** A files change that was cancelled, so it cannot publish. */\nexport const ERROR_CODE_UPLOAD_CANCELLED = \"UPLOAD_CANCELLED\";\n\n/**\n * A `continue` position the listing did not issue; list again with no position.\n */\nexport const ERROR_CODE_INVALID_CONTINUE = \"INVALID_CONTINUE\";\n\n/**\n * The Account has used its month's allowance and its extra usage, and\n * auto-refill cannot buy more (HTTP 402). It refuses a session at once,\n * and a wake or a session that fails later for the same cause carries it as\n * its reason. A purchase, an upgrade or the start of the Account's next\n * period lets its Computers wake again; `isOutOfUsage` recognises this error.\n */\nexport const ERROR_CODE_OUT_OF_USAGE = \"OUT_OF_USAGE\";\n\n/**\n * A wake, or a change of a Computer's CPU and memory to a larger size,\n * names a size larger than the Account's plan includes (HTTP 402). A change to\n * a size no larger than the Computer's own is never refused with this error.\n * `sizeNotInPlan` reads its details: the size refused, the plan's largest size,\n * and the smallest plan that includes the size.\n */\nexport const ERROR_CODE_SIZE_NOT_IN_PLAN = \"SIZE_NOT_IN_PLAN\";\n\n/**\n * A wake would take the vCPU of the Account's awake Computers past what its\n * plan allows at once. It fails a wake and a pending session, which carry it as\n * their reason, and it carries no details. Computers already awake keep running.\n * Putting another Computer to sleep, or upgrading to a plan with a higher limit,\n * lets the Computer wake. The count can briefly lag a change, so a wake just\n * after a sleep can fail with it and succeed when asked again.\n */\nexport const ERROR_CODE_VCPU_LIMIT_REACHED = \"VCPU_LIMIT_REACHED\";\n\n/**\n * An Account on a free trial or on no plan has downloaded as much of its saved\n * files as one window allows (HTTP 429, with `Retry-After`). The details carry\n * `limitBytes` and `usedBytes`. A paid plan has no limit, and the next window\n * opens when `Retry-After` has passed.\n */\nexport const ERROR_CODE_DOWNLOAD_LIMIT_REACHED = \"DOWNLOAD_LIMIT_REACHED\";\n\n/**\n * Why a plan change or a purchase failed: the card was declined, or could\n * not be charged without the user, as an auto-refill cannot. The plan in\n * force is unchanged and nothing was charged. It is also why auto-refill\n * was turned off. A portal session replaces the card.\n */\nexport const ERROR_CODE_PAYMENT_DECLINED = \"PAYMENT_DECLINED\";\n\n/** Why auto-refill was turned off when a payment of the Account was disputed. */\nexport const ERROR_CODE_PAYMENT_DISPUTED = \"PAYMENT_DISPUTED\";\n\n/**\n * Why a plan change or a purchase failed: its payment page expired before\n * the user completed the payment. Nothing was charged.\n */\nexport const ERROR_CODE_ACTION_EXPIRED = \"ACTION_EXPIRED\";\n\n/**\n * Why a pending plan change failed: it was replaced by a later plan change of\n * the Account. No charge was made.\n */\nexport const ERROR_CODE_PLAN_CHANGE_SUPERSEDED = \"PLAN_CHANGE_SUPERSEDED\";\n\n/**\n * Why an upgrade failed: the platform could not make it as priced. The\n * plan in force is unchanged and nothing was charged; the same change can\n * be made again later.\n */\nexport const ERROR_CODE_PLAN_CHANGE_UNAVAILABLE = \"PLAN_CHANGE_UNAVAILABLE\";\n\n/** A plan change names a plan that is not offered (HTTP 422). */\nexport const ERROR_CODE_PLAN_NOT_OFFERED = \"PLAN_NOT_OFFERED\";\n\n/**\n * A purchase of extra usage, or an update that turns auto-refill on, on a\n * plan that does not include extra usage (HTTP 402). An upgrade to a plan\n * that includes it lets the Account buy.\n */\nexport const ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN = \"EXTRA_USAGE_NOT_IN_PLAN\";\n\n/**\n * A purchase of extra usage that would take what the current period has\n * bought, purchases paid and pending, past the Account's spend cap (HTTP\n * 409). `spendCapReached` reads its details: the cap and what the period\n * has bought.\n */\nexport const ERROR_CODE_SPEND_CAP_REACHED = \"SPEND_CAP_REACHED\";\n\n/**\n * An update that would leave auto-refill on with no spend cap set (HTTP\n * 422): auto-refill never buys without a cap.\n */\nexport const ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP =\n \"AUTO_REFILL_NEEDS_SPEND_CAP\";\n\n/*\n * A save or an upload refused for size carries its reason as its code:\n * `SAVE_REASON_ACCOUNT_STORAGE_LIMIT`, `SAVE_REASON_COMPUTER_SIZE` or\n * `SAVE_REASON_NAME_LIMIT`, defined beside the save and upload contracts.\n */\nexport {\n SAVE_REASON_ACCOUNT_STORAGE_LIMIT,\n SAVE_REASON_COMPUTER_SIZE,\n SAVE_REASON_NAME_LIMIT,\n};\n\n/**\n * The code an `ApiError` carries. It is an open union: the platform may add\n * codes, which arrive as their own strings.\n */\nexport type ApiErrorCode =\n | typeof ERROR_CODE_EXECUTION_NOT_ENABLED\n | typeof ERROR_CODE_COMPUTER_TERMINATING\n | typeof ERROR_CODE_PROFILE_FITS_NO_HOST\n | typeof ERROR_CODE_WAKE_TIMEOUT\n | typeof ERROR_CODE_SESSION_BUDGET_EXCEEDED\n | typeof ERROR_CODE_INSUFFICIENT_CAPACITY\n | typeof ERROR_CODE_INSUFFICIENT_DISK\n | typeof ERROR_CODE_VERSION_DAMAGED\n | typeof ERROR_CODE_SAVE_FAILED\n | typeof ERROR_CODE_SLEEP_TIMEOUT\n | typeof ERROR_CODE_SESSION_FINAL\n | typeof ERROR_CODE_IMAGE_NOT_IN_CATALOG\n | typeof ERROR_CODE_COMPUTER_DOES_NOT_FIT\n | typeof ERROR_CODE_NETWORK_CLASS_NOT_ADMITTED\n | typeof ERROR_CODE_ISOLATION_CLASS_NOT_ADMITTED\n | typeof ERROR_CODE_CLIENT_UPGRADE_REQUIRED\n | typeof ERROR_CODE_SIZE_BELOW_USAGE\n | typeof ERROR_CODE_SIZE_ABOVE_CAP\n | typeof ERROR_CODE_VERSION_NOT_FOUND\n | typeof ERROR_CODE_FORK_NOT_QUIESCENT\n | typeof ERROR_CODE_PATH_INVALID\n | typeof ERROR_CODE_NAME_NOT_NFC\n | typeof ERROR_CODE_STORAGE_NOT_OPEN\n | typeof ERROR_CODE_HEAD_MOVED\n | typeof ERROR_CODE_UPLOAD_CONFLICT\n | typeof ERROR_CODE_UPLOAD_EXPIRED\n | typeof ERROR_CODE_UPLOAD_CANCELLED\n | typeof ERROR_CODE_INVALID_CONTINUE\n | typeof ERROR_CODE_OUT_OF_USAGE\n | typeof ERROR_CODE_SIZE_NOT_IN_PLAN\n | typeof ERROR_CODE_VCPU_LIMIT_REACHED\n | typeof ERROR_CODE_DOWNLOAD_LIMIT_REACHED\n | typeof ERROR_CODE_PAYMENT_DECLINED\n | typeof ERROR_CODE_PAYMENT_DISPUTED\n | typeof ERROR_CODE_ACTION_EXPIRED\n | typeof ERROR_CODE_PLAN_CHANGE_SUPERSEDED\n | typeof ERROR_CODE_PLAN_CHANGE_UNAVAILABLE\n | typeof ERROR_CODE_PLAN_NOT_OFFERED\n | typeof ERROR_CODE_EXTRA_USAGE_NOT_IN_PLAN\n | typeof ERROR_CODE_SPEND_CAP_REACHED\n | typeof ERROR_CODE_AUTO_REFILL_NEEDS_SPEND_CAP\n | typeof SAVE_REASON_ACCOUNT_STORAGE_LIMIT\n | typeof SAVE_REASON_COMPUTER_SIZE\n | typeof SAVE_REASON_NAME_LIMIT\n | (string & Record<never, never>);\n"]}
|