@folsom/fuse 0.41.0 → 0.42.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/dist/index.d.ts CHANGED
@@ -628,6 +628,8 @@ declare const State: {
628
628
  readonly Running: "running";
629
629
  readonly Draining: "draining";
630
630
  readonly Destroying: "destroying";
631
+ /** A destroy that ran out of retries. The environment may still exist on its host; destroy it again to retry. */
632
+ readonly DestroyFailed: "destroy_failed";
631
633
  readonly Destroyed: "destroyed";
632
634
  readonly Failed: "failed";
633
635
  };
@@ -1654,7 +1656,7 @@ declare class FuseClient {
1654
1656
  withActor(actor: ActorLabel): FuseClient;
1655
1657
  }
1656
1658
 
1657
- declare const VERSION = "0.41.0";
1659
+ declare const VERSION = "0.42.0";
1658
1660
 
1659
1661
  /** Stable, machine-readable error codes returned by the server. */
1660
1662
  declare const ErrorCode: {
package/dist/index.js CHANGED
@@ -422,6 +422,8 @@ var State = {
422
422
  Running: "running",
423
423
  Draining: "draining",
424
424
  Destroying: "destroying",
425
+ /** A destroy that ran out of retries. The environment may still exist on its host; destroy it again to retry. */
426
+ DestroyFailed: "destroy_failed",
425
427
  Destroyed: "destroyed",
426
428
  Failed: "failed"
427
429
  };
@@ -1419,7 +1421,7 @@ var ApiKeysService = class {
1419
1421
  };
1420
1422
 
1421
1423
  // src/version.ts
1422
- var VERSION = "0.41.0";
1424
+ var VERSION = "0.42.0";
1423
1425
 
1424
1426
  // src/client.ts
1425
1427
  var FuseClient = class _FuseClient {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/transport.ts","../src/types.ts","../src/validate.ts","../src/events.ts","../src/interventions.ts","../src/gates.ts","../src/takeover.ts","../src/environments.ts","../src/snapshots.ts","../src/hosts.ts","../src/apiKeys.ts","../src/version.ts","../src/client.ts"],"names":["REQUEST_ID_HEADER","MAX_PAGE_LIMIT"],"mappings":";AAMA,IAAM,iBAAA,GAAoB,cAAA;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IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,MAAM,SAAA,GAAY,IAAI,SAAA,CAAU;AAAA,MAC9B,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,SAAA,EAAW,OAAA,CAAQ,SAAA,IAAa,CAAA,QAAA,EAAW,OAAO,CAAA,CAAA;AAAA,MAClD,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,YAAY,OAAA,CAAQ,UAAA;AAAA,MACpB,QAAQ,OAAA,CAAQ;AAAA,KACjB,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,GAAe,IAAI,mBAAA,CAAoB,SAAS,CAAA;AACrD,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,gBAAA,CAAiB,SAAS,CAAA;AAC/C,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,YAAA,CAAa,SAAS,CAAA;AACvC,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,cAAA,CAAe,SAAS,CAAA;AAC3C,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAI,oBAAA,CAAqB,SAAS,CAAA;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,KAAA,EAA+B;AACvC,IAAA,OAAO,IAAI,WAAA,CAAW,EAAE,GAAG,IAAA,CAAK,OAAA,EAAS,OAAO,CAAA;AAAA,EAClD;AACF","file":"index.js","sourcesContent":["// Error types for the Fuse SDK, mirroring sdks/go/errors.go: a structured\n// FuseApiError for non-2xx responses plus code-checking helpers, and a\n// FuseError for transport/configuration failures.\n\nimport type { Intervention } from \"./types.js\";\n\nconst REQUEST_ID_HEADER = \"X-Request-ID\";\n\n/** Stable, machine-readable error codes returned by the server. */\nexport const ErrorCode = {\n NotFound: \"not_found\",\n Conflict: \"conflict\",\n InvalidArgument: \"invalid_argument\",\n Unavailable: \"unavailable\",\n Internal: \"internal\",\n Unauthorized: \"unauthorized\",\n Forbidden: \"forbidden\",\n Locked: \"locked\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nconst STATUS_TEXT: Record<number, string> = {\n 400: \"bad request\",\n 401: \"unauthorized\",\n 403: \"forbidden\",\n 404: \"not found\",\n 409: \"conflict\",\n 423: \"locked\",\n 500: \"internal server error\",\n 502: \"bad gateway\",\n 503: \"service unavailable\",\n};\n\nfunction statusText(status: number): string {\n return STATUS_TEXT[status] ?? `status ${status}`;\n}\n\nexport interface FuseApiErrorInit {\n status: number;\n code?: string;\n message?: string;\n details?: Record<string, string>;\n requestId?: string;\n body?: string;\n}\n\nfunction formatMessage(init: FuseApiErrorInit): string {\n const parts: string[] = [`status=${init.status}`];\n if (init.code) parts.push(`code=${init.code}`);\n if (init.message) parts.push(init.message);\n else parts.push(statusText(init.status));\n if (init.requestId) parts.push(`request_id=${init.requestId}`);\n return \"fuse api error: \" + parts.join(\", \");\n}\n\n/** FuseApiError is a non-2xx response from the server. */\nexport class FuseApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly details?: Record<string, string>;\n readonly requestId?: string;\n /** Raw response body, when available. */\n readonly body?: string;\n\n constructor(init: FuseApiErrorInit) {\n super(formatMessage(init));\n this.name = \"FuseApiError\";\n this.status = init.status;\n this.code = init.code ?? \"\";\n this.details = init.details;\n this.requestId = init.requestId;\n this.body = init.body;\n // Restore the prototype chain so `instanceof` works after transpilation.\n Object.setPrototypeOf(this, FuseApiError.prototype);\n }\n}\n\n/** Reasons a forbidden error carries in details.reason. */\nexport const ForbiddenReason = {\n MissingScope: \"missing_scope\",\n EnvScope: \"env_scope\",\n SelfApproval: \"self_approval\",\n ActorRequired: \"actor_required\",\n ActorMismatch: \"actor_mismatch\",\n ActorNotAllowed: \"actor_not_allowed\",\n MintEscalation: \"mint_escalation\",\n /** A hitl deny gate (or the exec allowlist in deny mode) refused the\n * action. The message is the gate's reason; details.gate names the gate. */\n HitlDenied: \"hitl_denied\",\n} as const;\n\nexport type ForbiddenReason = (typeof ForbiddenReason)[keyof typeof ForbiddenReason];\n\n/**\n * ForbiddenError is a 403 forbidden response: the caller is authenticated\n * but not allowed. `reason` is one of ForbiddenReason (empty when the server\n * sent none) and `scope` names the missing scope for missing_scope.\n */\nexport class ForbiddenError extends FuseApiError {\n readonly reason: string;\n readonly scope?: string;\n\n constructor(init: FuseApiErrorInit) {\n super(init);\n this.name = \"ForbiddenError\";\n this.reason = init.details?.reason ?? \"\";\n this.scope = init.details?.scope;\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * LockedError is a 423 locked response: a human holds the environment (a\n * takeover) or an ask-mode stall is pending, so agent exec and computer calls\n * are refused. exec and computer wait it out by default; this surfaces only\n * when waiting is off. Wait on `interventionId` with interventions.wait.\n */\nexport class LockedError extends FuseApiError {\n readonly interventionId: string;\n /** \"takeover\" or \"stall\". */\n readonly kind: string;\n\n constructor(init: FuseApiErrorInit) {\n super(init);\n this.name = \"LockedError\";\n this.interventionId = init.details?.intervention_id ?? \"\";\n this.kind = init.details?.kind ?? \"\";\n Object.setPrototypeOf(this, LockedError.prototype);\n }\n}\n\n/** isLocked reports whether err is a 423 locked api error. */\nexport function isLocked(err: unknown): err is LockedError {\n return err instanceof LockedError;\n}\n\n/** FuseError is a transport, configuration, or decoding failure (not an API error). */\nexport class FuseError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"FuseError\";\n Object.setPrototypeOf(this, FuseError.prototype);\n }\n}\n\n/**\n * PendingInterventionError is thrown instead of waiting when a hitl gate held\n * the call and waiting is off (exec's `wait: false` or the client's\n * `hitlNoWait`). Wait on `intervention.id` with interventions.wait; the\n * outcome is on its result.\n */\nexport class PendingInterventionError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `held by hitl gate ${intervention.gate ?? \"\"}: waiting on intervention ${intervention.id}`,\n );\n this.name = \"PendingInterventionError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, PendingInterventionError.prototype);\n }\n}\n\n/**\n * InterventionRejectedError is a held call a human rejected, or that expired\n * or was cancelled without approval. `intervention.decision.reason` is for\n * the agent to read and replan on.\n */\nexport class InterventionRejectedError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `intervention ${intervention.id} ${intervention.state}: ${intervention.decision?.reason ?? \"\"}`,\n );\n this.name = \"InterventionRejectedError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, InterventionRejectedError.prototype);\n }\n}\n\n/** HeldActionError is an approved held action fuse could not perform. */\nexport class HeldActionError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `approved action of intervention ${intervention.id} failed: ${intervention.result?.error ?? \"\"}`,\n );\n this.name = \"HeldActionError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, HeldActionError.prototype);\n }\n}\n\n/** isFuseApiError is a type guard for FuseApiError. */\nexport function isFuseApiError(err: unknown): err is FuseApiError {\n return err instanceof FuseApiError;\n}\n\nfunction hasCode(err: unknown, code: string): boolean {\n return isFuseApiError(err) && err.code === code;\n}\n\n/** isNotFound reports whether err is a not_found api error. */\nexport function isNotFound(err: unknown): boolean {\n return hasCode(err, ErrorCode.NotFound);\n}\n\n/** isConflict reports whether err is a conflict api error. */\nexport function isConflict(err: unknown): boolean {\n return hasCode(err, ErrorCode.Conflict);\n}\n\n/** isUnauthorized reports whether err is an unauthorized api error. */\nexport function isUnauthorized(err: unknown): boolean {\n return hasCode(err, ErrorCode.Unauthorized);\n}\n\n/** isForbidden reports whether err is a forbidden api error. */\nexport function isForbidden(err: unknown): err is ForbiddenError {\n return err instanceof ForbiddenError;\n}\n\n/** isHitlDenied reports whether err is an action a hitl gate denied. */\nexport function isHitlDenied(err: unknown): err is ForbiddenError {\n return isForbidden(err) && err.reason === ForbiddenReason.HitlDenied;\n}\n\n/** isInvalidArgument reports whether err is an invalid_argument api error. */\nexport function isInvalidArgument(err: unknown): boolean {\n return hasCode(err, ErrorCode.InvalidArgument);\n}\n\n/** isUnavailable reports whether err is an unavailable api error. */\nexport function isUnavailable(err: unknown): boolean {\n return hasCode(err, ErrorCode.Unavailable);\n}\n\ninterface ErrorEnvelope {\n error?: {\n code?: string;\n message?: string;\n details?: Record<string, string>;\n };\n}\n\nfunction parseApiError(\n status: number,\n requestId: string | undefined,\n body: string,\n): FuseApiError {\n if (body) {\n try {\n const env = JSON.parse(body) as ErrorEnvelope;\n const e = env?.error;\n if (e && (e.code || e.message)) {\n const init = {\n status,\n code: e.code,\n message: e.message,\n details: e.details,\n requestId,\n body,\n };\n if (e.code === ErrorCode.Forbidden) return new ForbiddenError(init);\n if (e.code === ErrorCode.Locked) return new LockedError(init);\n return new FuseApiError(init);\n }\n } catch {\n // fall through to the status-text error below\n }\n }\n return new FuseApiError({ status, message: statusText(status), requestId, body });\n}\n\n/**\n * errorFromResponse builds a FuseApiError from a non-2xx Response, parsing the\n * `{\"error\":{code,message,details}}` envelope and reading the X-Request-ID\n * response header for correlation.\n */\nexport async function errorFromResponse(res: Response): Promise<FuseApiError> {\n const requestId = res.headers.get(REQUEST_ID_HEADER) ?? undefined;\n let body = \"\";\n try {\n body = await res.text();\n } catch (err) {\n return new FuseApiError({\n status: res.status,\n message: `read error body: ${String(err)}`,\n requestId,\n });\n }\n return parseApiError(res.status, requestId, body);\n}\n","// The transport layer: builds requests (URL, headers, auth, X-Request-ID,\n// JSON body), applies an optional client-default timeout, executes fetch, and\n// turns non-2xx responses into FuseApiError. Mirrors the transport in\n// sdks/go/environments.go. SSE streams use stream() which deliberately applies\n// no timeout (the Go SDK uses a separate Timeout:0 client for events).\n\nimport { FuseError, errorFromResponse } from \"./errors.js\";\nimport type { ActorLabel, Intervention } from \"./types.js\";\n\nconst REQUEST_ID_HEADER = \"X-Request-ID\";\nconst ACTOR_HEADER = \"Fuse-Actor\";\nconst ACTOR_NAME_HEADER = \"Fuse-Actor-Name\";\n\n/** A minimal fetch signature, satisfied by the global fetch and most polyfills. */\nexport type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/** Per-call options accepted by every service method. */\nexport interface CallOptions {\n /** Abort the request (and, for events, the stream). */\n signal?: AbortSignal;\n}\n\nexport interface TransportConfig {\n baseUrl: string;\n token?: string;\n fetch?: FetchLike;\n userAgent?: string;\n requestId?: () => string;\n timeoutMs?: number;\n headers?: Record<string, string>;\n actor?: ActorLabel;\n hitlNoWait?: boolean;\n onHeld?: (held: Intervention) => void;\n}\n\n/** Gated is the answer to a call a hitl gate may hold: the action's own\n * response body, or the held intervention of a 202. */\nexport type Gated<T> = { held: Intervention } | { held?: undefined; value: T };\n\ntype Query = Record<string, string | undefined>;\n\ninterface RequestSpec {\n query?: Query;\n body?: unknown;\n signal?: AbortSignal;\n}\n\n/** Combine zero or more AbortSignals into one, without relying on AbortSignal.any (Node 20+). */\nfunction combineSignals(signals: Array<AbortSignal | undefined>): {\n signal?: AbortSignal;\n cleanup: () => void;\n} {\n const active = signals.filter((s): s is AbortSignal => s != null);\n if (active.length === 0) return { cleanup: () => {} };\n if (active.length === 1) return { signal: active[0], cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbort = (event: Event) => {\n const target = event.target as AbortSignal;\n controller.abort(target.reason);\n cleanup();\n };\n const cleanup = () => {\n for (const s of active) s.removeEventListener(\"abort\", onAbort);\n };\n for (const s of active) {\n if (s.aborted) {\n controller.abort(s.reason);\n cleanup();\n return { signal: controller.signal, cleanup: () => {} };\n }\n s.addEventListener(\"abort\", onAbort);\n }\n return { signal: controller.signal, cleanup };\n}\n\nexport class Transport {\n private readonly baseUrl: URL;\n private readonly token?: string;\n private readonly fetchImpl: FetchLike;\n private readonly userAgent?: string;\n private readonly requestId?: () => string;\n private readonly timeoutMs?: number;\n private readonly defaultHeaders?: Record<string, string>;\n private readonly actor?: ActorLabel;\n /** The client's hitl wait options. */\n readonly hitlNoWait: boolean;\n readonly onHeld?: (held: Intervention) => void;\n\n constructor(cfg: TransportConfig) {\n if (!cfg.baseUrl) {\n throw new FuseError(\"base url is required\");\n }\n let parsed: URL;\n try {\n parsed = new URL(cfg.baseUrl);\n } catch {\n throw new FuseError(\"base url is invalid\");\n }\n this.baseUrl = parsed;\n this.token = cfg.token;\n this.userAgent = cfg.userAgent;\n this.requestId = cfg.requestId;\n this.timeoutMs = cfg.timeoutMs;\n this.defaultHeaders = cfg.headers;\n this.actor = cfg.actor;\n this.hitlNoWait = cfg.hitlNoWait ?? false;\n this.onHeld = cfg.onHeld;\n\n const provided = cfg.fetch;\n if (provided) {\n this.fetchImpl = provided;\n } else if (typeof globalThis.fetch === \"function\") {\n this.fetchImpl = globalThis.fetch.bind(globalThis) as FetchLike;\n } else {\n throw new FuseError(\n \"global fetch is not available; pass a fetch implementation via the `fetch` option (Node 18+ required)\",\n );\n }\n }\n\n /** Perform a request and decode a JSON response body. */\n async json<T>(method: string, path: string, spec: RequestSpec = {}): Promise<T> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n return await this.decodeJson<T>(res);\n } finally {\n cleanup();\n }\n }\n\n /**\n * Perform a call a hitl gate may hold. A 202 answers with the held\n * intervention; anything else 2xx with the action's own (possibly empty)\n * body.\n */\n async gated<T>(\n method: string,\n path: string,\n spec: RequestSpec = {},\n ): Promise<Gated<T>> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n if (res.status === 202) return { held: await this.decodeHeld(res) };\n return { value: await this.decodeJson<T>(res) };\n } finally {\n cleanup();\n }\n }\n\n /** Like noContent for a call a hitl gate may hold: it resolves to the held\n * intervention of a 202, or undefined when the action itself answered. */\n async gatedNoContent(\n method: string,\n path: string,\n spec: RequestSpec = {},\n ): Promise<Intervention | undefined> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n if (res.status === 202) return await this.decodeHeld(res);\n await res.body?.cancel().catch(() => {});\n return undefined;\n } finally {\n cleanup();\n }\n }\n\n /** Perform a request and return the response body as text. */\n async text(method: string, path: string, spec: RequestSpec = {}): Promise<string> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n return await res.text();\n } finally {\n cleanup();\n }\n }\n private async decodeHeld(res: Response): Promise<Intervention> {\n const body = await this.decodeJson<{ intervention?: Intervention }>(res);\n if (!body?.intervention?.id) throw new FuseError(\"decode held response\");\n return body.intervention;\n }\n\n /** Perform a request that returns no body (e.g. 204 actions). */\n async noContent(method: string, path: string, spec: RequestSpec = {}): Promise<void> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n // Release the connection even if the server sent a body.\n await res.body?.cancel().catch(() => {});\n } finally {\n cleanup();\n }\n }\n\n /**\n * Open a long-lived stream (SSE). Applies NO timeout — only the caller's\n * signal cancels it — and checks the status eagerly so connect-time errors\n * (404/401/...) surface as a FuseApiError before any iteration.\n */\n async stream(\n path: string,\n query: Query | undefined,\n signal?: AbortSignal,\n ): Promise<Response> {\n const res = await this.execute(\n \"GET\",\n path,\n { query, signal },\n signal,\n \"text/event-stream\",\n );\n if (!res.ok) throw await errorFromResponse(res);\n return res;\n }\n\n private async execute(\n method: string,\n path: string,\n spec: RequestSpec,\n signal: AbortSignal | undefined,\n accept?: string,\n ): Promise<Response> {\n const url = this.buildUrl(path, spec.query);\n const hasBody = spec.body !== undefined && spec.body !== null;\n const headers = this.buildHeaders(hasBody, accept);\n const init: RequestInit = { method, headers };\n if (hasBody) init.body = JSON.stringify(spec.body);\n if (signal) init.signal = signal;\n\n try {\n return await this.fetchImpl(url, init);\n } catch (err) {\n // A caller- or timeout-initiated abort propagates as-is; everything else\n // is wrapped so consumers get a consistent FuseError with a cause.\n if (signal?.aborted) throw err;\n throw new FuseError(`request failed: ${method} ${url}`, { cause: err });\n }\n }\n\n private buildUrl(path: string, query?: Query): string {\n const p = path.startsWith(\"/\") ? path : \"/\" + path;\n const u = new URL(p, this.baseUrl);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== \"\") u.searchParams.set(key, value);\n }\n }\n return u.toString();\n }\n\n private buildHeaders(hasBody: boolean, accept?: string): Record<string, string> {\n const headers: Record<string, string> = { ...(this.defaultHeaders ?? {}) };\n if (hasBody) headers[\"Content-Type\"] = \"application/json\";\n if (this.token) headers[\"Authorization\"] = `Bearer ${this.token}`;\n if (this.userAgent) headers[\"User-Agent\"] = this.userAgent;\n if (this.requestId) {\n const id = this.requestId();\n if (id) headers[REQUEST_ID_HEADER] = id;\n }\n if (accept) headers[\"Accept\"] = accept;\n if (this.actor?.id) {\n headers[ACTOR_HEADER] = this.actor.id;\n if (this.actor.name) headers[ACTOR_NAME_HEADER] = this.actor.name;\n }\n return headers;\n }\n\n private async decodeJson<T>(res: Response): Promise<T> {\n const text = await res.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new FuseError(\"decode response body\", { cause: err });\n }\n }\n\n private withTimeout(callerSignal?: AbortSignal): {\n signal?: AbortSignal;\n cleanup: () => void;\n } {\n const signals: Array<AbortSignal | undefined> = [callerSignal];\n if (this.timeoutMs && this.timeoutMs > 0) {\n signals.push(AbortSignal.timeout(this.timeoutMs));\n }\n return combineSignals(signals);\n }\n}\n","// Wire types for the Fuse API. Field names match the JSON sent on the wire\n// (snake_case), so request/response bodies pass through JSON.stringify /\n// JSON.parse untouched — a faithful 1:1 mirror of the Go SDK's struct tags\n// (see sdks/go/types.go). List *options* (see each service) use camelCase\n// keys and are translated to snake_case query params by the service.\n\n/** Spec is the hardware/runtime spec for a microVM. */\nexport interface Spec {\n cpus?: number;\n ram_mb?: number;\n storage_gb?: number;\n gpus?: number;\n gpu_kind?: string;\n /** Requests fractional GPU allocation: a MIG profile in mig-parted\n * vocabulary (e.g. \"1g.10gb\"). When set, gpus counts MIG instances of this\n * profile rather than whole devices. */\n gpu_profile?: string;\n region?: string;\n /** Restricts scheduling to hosts of this CPU architecture (\"amd64\",\n * \"arm64\"). Omitted means any host. */\n arch?: string;\n max_runtime_seconds?: number;\n /** Destroys the environment after this many seconds with no exec and no\n * attach session. Omitted or 0 means no idle expiry. Unlike\n * max_runtime_seconds (a ceiling measured from create), this is measured\n * from the last exec or attach. */\n idle_timeout_seconds?: number;\n image?: string;\n /** Pins the environment to an exact host id (the Fusefile's\n * placement.host). The pinned host still has to be active, run the right\n * backend, and fit the request. */\n host_id?: string;\n /** Placement label selectors (the Fusefile's placement.labels): every pair\n * must match the target host's declared labels. */\n labels?: Record<string, string>;\n /** Back guest memory with 2M pages. The host must have them reserved; only\n * an environment created with this can be migrated lazily. */\n huge_pages?: boolean;\n}\n\n/** ExposeSpec requests that a guest port be published at boot. */\nexport interface ExposeSpec {\n port: number;\n as?: string;\n /** Transport to publish on: \"tcp\" (the default) or \"udp\". Typed as a plain\n * string rather than a union so a server that grows a third transport does\n * not turn into a compile error here. The host agent installs a separate\n * forwarding rule per transport, so a service speaking both needs two\n * entries. */\n protocol?: string;\n}\n\n/** Endpoint is a published port with its externally reachable URL. */\nexport interface Endpoint {\n as?: string;\n url: string;\n /** The transport this endpoint was actually published on, which is not\n * always what was asked for: an agent too old to know about the field\n * publishes tcp and answers with this omitted. */\n protocol?: string;\n port: number;\n}\n\n/** HealthcheckHttp is an HTTP GET against a port inside the guest. The probe\n * runs in-guest, so the port needs no matching ExposeSpec. */\nexport interface HealthcheckHttp {\n port: number;\n /** Request path, which must start with a slash. Defaults to \"/\". */\n path?: string;\n}\n\n/**\n * HealthcheckSpec is the environment-level readiness probe (the Fusefile's\n * `healthcheck:` block). Exactly one of http and exec must be set; the server\n * rejects a request that sets both or neither.\n *\n * It is not the per-service compose healthcheck that can appear inside a\n * manifest: that one governs a single container and never reaches the control\n * plane. This one is evaluated by the guest agent over the environment as a\n * whole and its verdict comes back on EnvironmentInfo.health.\n *\n * Every duration is in seconds, and 0 means \"omitted, use the guest agent's\n * default\". The server substitutes no defaults of its own, because the probe\n * executes in the guest.\n */\nexport interface HealthcheckSpec {\n http?: HealthcheckHttp;\n /** An argv run inside the guest. Exit status 0 passes. */\n exec?: string[];\n /** Seconds between attempts. 0 for the guest agent default (10s). */\n interval_seconds?: number;\n /** Bound on one attempt, in seconds. 0 for the guest agent default (2s).\n * Attempts run one at a time, so a value above interval_seconds is\n * rejected rather than silently stretching the interval. */\n timeout_seconds?: number;\n /** Consecutive failures that flip the verdict to failing. 0 for the guest\n * agent default (3). */\n retries?: number;\n /** Grace window from the first attempt during which failures are not\n * counted. It ends for good once the probe passes once. */\n start_period_seconds?: number;\n}\n\n/**\n * DesktopSpec is the geometry of the environment's graphical session (the\n * Fusefile's `desktop:` block). It requires an image that carries the desktop\n * stack; on any other image the declaration is inert and the computer surface\n * reports the display as absent.\n *\n * width and height are required, 320 to 3840 each: a guessed dimension would\n * silently shift every coordinate a computer-use model emits.\n */\nexport interface DesktopSpec {\n /** Display width in pixels. */\n width: number;\n /** Display height in pixels. */\n height: number;\n /** Window manager to run: \"mutter\", \"xfwm4\" or \"openbox\". Omit to keep the\n * image's baked default. A string rather than a union so a server that\n * grows a window manager does not turn into a compile error here. */\n wm?: string;\n}\n\n/**\n * ComputerAction is one computer-use action, in the same shape Anthropic's\n * computer tool emits as tool_use input, so translating a tool_use block into\n * a call is mechanical. Only action is required; which other fields apply\n * depends on the action, and the guest agent enforces the full schema.\n */\nexport interface ComputerAction {\n /** The action to perform, e.g. \"screenshot\", \"left_click\", \"type\", \"key\",\n * \"scroll\", \"zoom\". */\n action: string;\n /** [x, y] target for pointer actions. */\n coordinate?: number[];\n /** [x, y] origin for left_click_drag. */\n start_coordinate?: number[];\n /** The payload for type, the keysym combo for key/hold_key, or modifiers\n * held during a click action. */\n text?: string;\n /** [x1, y1, x2, y2] crop for zoom. */\n region?: number[];\n /** Seconds for hold_key and wait, capped guest-side at 100. */\n duration?: number;\n scroll_direction?: \"up\" | \"down\" | \"left\" | \"right\";\n /** Wheel clicks for scroll, 1 to 100. */\n scroll_amount?: number;\n}\n\n/**\n * ComputerResult is the guest's answer to one action. screenshot is a base64\n * PNG, present on every action that implies one; for zoom it is the cropped\n * region at full resolution.\n */\nexport interface ComputerResult {\n output?: string;\n screenshot?: string;\n}\n\n/**\n * ComputerDisplay reports the environment's display: whether it is up and at\n * what geometry, so a caller can populate display_width_px /\n * display_height_px in its computer tool definition without hardcoding them.\n */\nexport interface ComputerDisplay {\n display?: string;\n up: boolean;\n /** Live display width in pixels, 0 when the display is down. */\n width: number;\n /** Live display height in pixels, 0 when the display is down. */\n height: number;\n /** The window manager actually running, which can differ from\n * DesktopSpec.wm when the image does not carry the one asked for. */\n wm?: string;\n /** Why the display is down, when it is. */\n error?: string;\n}\n\n/** ToolResultImageSource is a Messages-API base64 image source. */\nexport interface ToolResultImageSource {\n type: \"base64\";\n media_type: \"image/png\";\n data: string;\n}\n\n/**\n * ToolResultBlock is one content block of a Messages API tool_result. The\n * field names match the Messages API, so the blocks can be sent back verbatim\n * as the tool_result content.\n */\nexport interface ToolResultBlock {\n type: \"text\" | \"image\";\n text?: string;\n source?: ToolResultImageSource;\n}\n\n/**\n * ComputerToolResult is what goes back to Claude for one computer tool_use:\n * the content blocks and whether they describe an error. Map it onto the\n * tool_result block for the tool_use's id and the loop is closed.\n */\nexport interface ComputerToolResult {\n content: ToolResultBlock[];\n is_error?: boolean;\n}\n\n/**\n * Health is the last verdict of an environment's healthcheck.\n *\n * It is deliberately not folded into EnvironmentInfo.state: that vocabulary is\n * a closed set clients reason about, and an unhealthy environment is still a\n * running one. Nothing tears an environment down for a failing probe.\n */\nexport interface Health {\n /** \"starting\", \"passing\" or \"failing\". */\n state: string;\n /** When the probe entered this state. */\n since?: string;\n /** Consecutive failed attempts. Zero while passing. */\n failures?: number;\n /** The last attempt's failure detail. Empty while passing. */\n message?: string;\n}\n\n/**\n * EgressSpec routes the environment's outbound traffic. Omit it (or omit\n * mode) for direct egress, which is what every request written before this\n * field existed meant. Every field is a plain string rather than a union so a\n * server that grows a new mode or provider does not turn into a compile error\n * here.\n */\nexport interface EgressSpec {\n /** \"direct\" (the default) or \"proxy\". */\n mode?: string;\n /** Proxy backend, required when mode is \"proxy\" (\"cloudflare-warp\",\n * \"wireguard\", or \"mock\" for local development). */\n provider?: string;\n /** \"socks5\" (the default for proxy) or \"http\". */\n protocol?: string;\n /** Name of an entry in the request's secrets holding the provider's\n * credential, for a provider that takes one: \"wireguard\" reads a base64\n * wg-quick config. The value goes to the host's egress backend only and is\n * left out of the secrets the guest receives. */\n secret?: string;\n}\n\n/**\n * EgressStatus is how the environment's outbound traffic is actually routed.\n * mode is always set; provider, protocol and endpoint are present only for\n * proxy egress. endpoint is a host-local address, never a credential.\n */\nexport interface EgressStatus {\n mode: string;\n provider?: string;\n protocol?: string;\n endpoint?: string;\n /** the endpoint's last probe verdict; proxy only. */\n health?: EgressHealth;\n}\n\n/**\n * EgressHealth is the proxy endpoint's last probe verdict. state is\n * \"unknown\" until the first probe, then \"healthy\" or \"unhealthy\"; typed as a\n * plain string so a server that grows a state does not turn into a compile\n * error here. reason is the backend-level failure, empty while healthy.\n */\nexport interface EgressHealth {\n state: string;\n reason?: string;\n checked_at?: string;\n}\n\n/** CreateRequest is the body for environments.create. */\nexport interface CreateRequest {\n task_id: string;\n spec?: Spec;\n manifest_inline?: string;\n secrets?: Record<string, string>;\n startup_script?: string;\n /**\n * Guest files written before the startup script runs, keyed by absolute\n * guest path with base64-encoded content. What a Fusefile's `copy` block\n * compiles to. Paths under /fuse are rejected, the total decoded size is\n * capped at 512 KiB, and permissions are not carried.\n */\n files?: Record<string, string>;\n gateway_url?: string;\n gateway_token?: string;\n expose?: ExposeSpec[];\n /** Environment-level readiness probe. Omit it for an environment with no\n * probe, in which case EnvironmentInfo.health is never populated. It is not\n * evaluated inside create: the call returns as soon as the VM is up, and\n * the verdict arrives on later reads. */\n healthcheck?: HealthcheckSpec;\n /** Routes the environment's outbound traffic. Omit it for direct egress. */\n egress?: EgressSpec;\n /** Graphical session geometry. Omit it for an environment with no desktop,\n * in which case a desktop image keeps its baked default geometry. */\n desktop?: DesktopSpec;\n /** Human-in-the-loop policy. Omit it for an environment that cannot raise\n * interventions. */\n hitl?: HitlSpec;\n}\n\n/** EnvironmentInfo is the server's view of a single microVM. */\nexport interface EnvironmentInfo {\n id: string;\n state: string;\n task_id: string;\n host_id?: string;\n url: string;\n spec: Spec;\n created_at: string;\n updated_at: string;\n error?: string;\n endpoints?: Endpoint[];\n /** Last verdict of the environment-level healthcheck. Absent when the\n * environment declared no healthcheck, and absent until the first verdict\n * has been read back from the guest. The server refreshes it on its\n * reconcile tick (30s by default), so it lags the guest by up to a tick. */\n health?: Health;\n /** How outbound traffic is actually routed. Absent only from a server that\n * predates the field; treat that as direct. */\n egress?: EgressStatus;\n}\n\n/** ForkOptions is the optional body for environments.fork. */\nexport interface ForkOptions {\n reuse_snapshot_id?: string;\n comment?: string;\n}\n\n/** MigrateOptions is the optional body for environments.migrate. */\nexport interface MigrateOptions {\n /**\n * Host to migrate to. Empty means the orchestrator picks a host other than\n * the source, preferring the environment's checkpoint standby; if no other\n * host can take it the call fails with 503 and the source keeps running.\n */\n target_host_id?: string;\n /**\n * Resume the guest from its memory on the target, so processes survive the\n * move, instead of cold-booting it. It never falls back to a cold\n * migration: a target that cannot resume the guest answers\n * 409 and the source keeps running.\n */\n live?: boolean;\n /**\n * Resume the guest before its memory has arrived and page it in from the\n * source afterwards. Requires live and an environment created with\n * huge_pages; until the vm.memory_resident event the guest still depends on\n * the source host.\n */\n lazy?: boolean;\n}\n\n/** ExecRequest is the body for environments.exec. Exactly one of cmd or shell must be set. */\nexport interface ExecRequest {\n /**\n * The argv to run in the guest, e.g. [\"ls\", \"-l\"]. Argv needs no quoting\n * rules and cannot be turned into an injection by interpolating a value, so\n * prefer it.\n */\n cmd?: string[];\n\n /**\n * Runs the string under `sh -lc`. Use it only for what argv cannot express:\n * pipelines, redirects, and globs.\n */\n shell?: string;\n\n /**\n * Bounds the command inside the guest. Zero or unset takes the server\n * default; the server clamps anything above its ceiling.\n */\n timeout_ms?: number;\n\n /**\n * Wait for a human when a hitl gate holds the exec (202), or when a\n * human holds the environment (423, a takeover or a pending stall), then\n * run (the default). false throws a PendingInterventionError or a\n * LockedError at once instead. Not sent on the wire.\n */\n wait?: boolean;\n\n /**\n * Called with the pending intervention when a gate holds the exec, before\n * waiting on it. It overrides the client's onHeld. Not sent on the wire.\n */\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * ExecResult is the outcome of a guest command.\n *\n * A non-zero exit_code is a successful call: the command ran and failed. Only a\n * thrown error means the command could not be run at all.\n */\nexport interface ExecResult {\n exit_code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Event is one item from environments.events. It matches the server's SSE\n * wire payload. Stream-level failures are thrown from the async iterator\n * rather than delivered as an in-band event.\n */\nexport interface Event {\n id: string;\n /** Event kind: \"state\" (an omitted kind means \"state\") or \"step\". */\n event: string;\n vm_id: string;\n state: string;\n url?: string;\n error?: string;\n updated_at: string;\n /** index of the setup step, 1-based. step events only. */\n index?: number;\n /** total number of setup steps. step events only. */\n total?: number;\n /** layer cache key for the step. step events only. */\n key?: string;\n /** whether the step was served from the layer cache. step events only. */\n cached?: boolean;\n /** why the step missed the cache. step events only. */\n miss_reason?: string;\n /** what changed, e.g. the input paths. step events only. */\n miss_detail?: string[];\n /** wall-clock duration of the step in milliseconds. step events only. */\n duration_ms?: number;\n /** exit code of the step. step events only. */\n exit_code?: number;\n}\n\n/** SnapshotRequest is the optional body for snapshots.create. */\nexport interface SnapshotRequest {\n comment?: string;\n mode?: string;\n retention_seconds?: number;\n metadata?: Record<string, string>;\n export_ref?: string;\n export_status?: string;\n /** Labels this snapshot as the artifact of one cacheable setup step, which is\n * what makes it findable by recipe rather than by its random id. Empty for an\n * ordinary snapshot. The scope it is filed under comes from how the caller\n * authenticated and is not settable here. */\n layer_key?: string;\n /** Capture the guest's memory and vCPU state alongside the rootfs, so\n * restoring resumes the guest instead of cold-booting it. Omitted or false\n * takes a disk-only snapshot, which is the default and the fallback.\n *\n * It costs the environment's full configured memory in bytes on every\n * create, pauses the guest for the length of the capture, and produces an\n * artifact pinned to the host that took it. It also cannot seed a new\n * environment: `fork` and `CreateRequest.seed_snapshot_id` read only a\n * snapshot's rootfs, and a live snapshot's rootfs is captured without\n * quiescing the guest filesystem, so it is consistent only alongside the\n * memory image. Both reject a live snapshot with a 409 conflict.\n *\n * Against a backend with no live-snapshot support this is a 501\n * `unimplemented`, not a conflict.\n *\n * It is a request, not a guarantee: read `Snapshot.kind` to find out what\n * was actually written. */\n live?: boolean;\n}\n\n/** ResolveSnapshotResponse is the wire envelope for a layer lookup. Internal:\n * resolve() returns Snapshot | null so the found flag never reaches callers. */\nexport interface ResolveSnapshotResponse {\n found: boolean;\n snapshot?: Snapshot;\n}\n\n/** SnapshotExport is an optional exported snapshot artifact. */\nexport interface SnapshotExport {\n destination: string;\n status?: string;\n requested_at?: string;\n updated_at?: string;\n last_error?: string;\n}\n\n/** Snapshot is a persisted snapshot record. */\nexport interface Snapshot {\n id: string;\n vm_id: string;\n task_id?: string;\n tenant_id?: string;\n parent_snapshot_id?: string;\n mode?: string;\n state?: string;\n comment?: string;\n /** The content-addressed cache key of the setup step this artifact was\n * taken after. Absent on anything that is not a build layer, and an empty\n * key never matches a lookup. */\n layer_key?: string;\n /** CPU architecture, in GOARCH vocabulary (\"amd64\", \"arm64\"), of the host\n * that actually built the artifact rather than of whoever asked for it. A\n * rootfs is not portable across architectures, so this is a real constraint\n * on whether the artifact can be booted; it is deliberately not folded into\n * layer_key, so a lookup has to filter on it separately. */\n arch?: string;\n /** Hex sha256 of the artifact rootfs. It verifies that a given copy of\n * those bytes is intact, and nothing more: it is not a cross-build\n * identity, because two builds of the same recipe produce different rootfs\n * bytes (timestamps, inode ordering, package caches). It can never be used\n * as a cache key. The live snapshot a migrate takes in its final pause on\n * an xfs or btrfs host is the exception: its digest is a sha256 of its\n * per-block hash table, not of the rootfs file. */\n digest?: string;\n /** Whether this artifact is the rootfs alone (`\"disk\"`), or the rootfs plus\n * the guest's memory and vCPU state (`\"live\"`). Restoring a disk snapshot\n * cold-boots the guest; restoring a live one resumes it.\n *\n * It is what the host agent reports it actually wrote, not what was\n * requested. A host running an agent too old to know about live snapshots\n * answers `live: true` with a disk snapshot, and this then says `\"disk\"`.\n * Branch on it rather than on your own request.\n *\n * Typed loosely rather than as a `\"disk\" | \"live\"` union so a server that\n * grows a third kind does not turn into a compile error here. A server that\n * predates live snapshots omits it entirely; treat undefined as `\"disk\"`. */\n kind?: string;\n size_bytes?: number;\n created_at: string;\n updated_at?: string;\n retention_until?: string;\n last_error?: string;\n export_ref?: string;\n exports?: SnapshotExport[];\n}\n\n/** HostCapacity is a host's resource envelope. */\nexport interface HostCapacity {\n cpus: number;\n ram_mb: number;\n storage_gb: number;\n vm_count: number;\n /** The host's CPU architecture in GOARCH vocabulary (\"amd64\", \"arm64\").\n * Omitted means amd64 (hosts registered before arch existed). */\n arch?: string;\n gpus?: number;\n gpu_kind?: string;\n /** The firecracker release the host agent reports it runs (\"v1.17.0\").\n * Probed at registration (a declared value is ignored) and only set on\n * capacity. Live migration needs both hosts on the same release. Omitted\n * on qemu hosts and older agents. */\n firecracker?: string;\n /** The firecracker release the host's fc-agent.py pins. Differs from\n * firecracker when the host has not run fc-update since the pin moved. */\n firecracker_pinned?: string;\n /** Fractional GPU capacity: MIG instance count by profile name (e.g.\n * {\"1g.10gb\": 4}). Like gpus, it requires backend \"qemu\". When the host\n * reports per-instance MIG inventory (mig_instances), this map is a derived\n * summary; otherwise it is the scheduling unit. */\n mig_profiles?: Record<string, number>;\n /** Per-instance MIG inventory probed from the host agent (one entry per\n * carved MIG GPU instance). When non-empty, the orchestrator binds specific\n * instance uuids to VMs instead of decrementing a count. Strictly additive:\n * a host that reports no instances falls back to mig_profiles. Only\n * populated on capacity (not allocated) for qemu hosts. */\n mig_instances?: MIGInstance[];\n /** The set of MIG instance uuids currently bound to VMs. Populated only on\n * allocated, and only for hosts that report per-instance MIG inventory. */\n mig_instance_uuids?: string[];\n /** Per-device GPU detail probed from the host agent, carried alongside the\n * scalar gpus/gpu_kind counters. Only populated on capacity (not\n * allocated) for qemu hosts. */\n gpu_devices?: GPUDevice[];\n}\n\n/** GPUDevice is the per-device detail probed for a single GPU. Every field is\n * best-effort and omitted when the host agent could not determine it. */\nexport interface GPUDevice {\n uuid?: string;\n model?: string;\n pci_bus_id?: string;\n memory_mb?: number;\n driver_version?: string;\n cuda_version?: string;\n compute_cap?: string;\n mig_capable?: boolean;\n mig_mode?: string;\n iommu_group?: string;\n}\n\n/** MIGInstance is one carved MIG GPU instance probed from the host agent. The\n * orchestrator binds a specific instance uuid to a VM so it knows which\n * instance went to which VM. */\nexport interface MIGInstance {\n uuid?: string;\n profile?: string;\n kind?: string;\n parent_gpu_uuid?: string;\n}\n\n/** RegisterHostRequest is the body for hosts.register. */\nexport interface RegisterHostRequest {\n id: string;\n url: string;\n token?: string;\n region?: string;\n backend?: string;\n /** Operator-declared key/value pairs matched against a spec's placement\n * label selectors. Never probed from the host agent. */\n labels?: Record<string, string>;\n capacity?: HostCapacity;\n}\n\n/** Host is the server's view of a registered host. */\nexport interface Host {\n id: string;\n url: string;\n region?: string;\n state: string;\n backend?: string;\n labels?: Record<string, string>;\n capacity: HostCapacity;\n allocated: HostCapacity;\n last_seen: string;\n created_at: string;\n updated_at: string;\n /** Non-fatal registration notices (e.g. declared capacity exceeding the\n * probed value). Only ever populated on the response to hosts.register. */\n warnings?: string[];\n}\n\n/**\n * APIKey is a key's metadata. The raw secret appears only in\n * CreatedAPIKey.key, returned once at creation.\n */\nexport interface APIKey {\n id: string;\n label?: string;\n created_at: string;\n last_used_at?: string;\n revoked_at?: string;\n /** The hitl scopes the key holds. Absent for a full-access key. */\n scopes?: string[];\n /** The environment a scoped key is limited to (and its forks). */\n env_id?: string;\n /** RFC 3339 timestamp. Scoped keys always expire. */\n expires_at?: string;\n /** The actor the key is pinned to, if any. */\n actor?: ActorLabel;\n created_by?: string;\n}\n\n/** ActorLabel is an actor as a caller names it: an opaque id (at most 128\n * bytes) and an optional display name. */\nexport interface ActorLabel {\n id: string;\n name?: string;\n}\n\n/** Hitl scopes a key can be minted with. */\nexport const HitlScope = {\n Read: \"hitl:read\",\n Decide: \"hitl:decide\",\n Secret: \"hitl:secret\",\n Takeover: \"hitl:takeover\",\n ActAs: \"hitl:act-as\",\n} as const;\n\nexport type HitlScope = (typeof HitlScope)[keyof typeof HitlScope];\n\n/**\n * CreatedAPIKey is returned by apiKeys.create. `key` is the raw secret and is\n * unrecoverable after this response.\n */\nexport interface CreatedAPIKey extends APIKey {\n key: string;\n}\n\n/** Lifecycle states for EnvironmentInfo.state and Event.state. */\nexport const State = {\n Provisioning: \"provisioning\",\n Running: \"running\",\n Draining: \"draining\",\n Destroying: \"destroying\",\n Destroyed: \"destroyed\",\n Failed: \"failed\",\n} as const;\n\nexport type State = (typeof State)[keyof typeof State];\n\n/** isTerminalState reports whether state is a terminal lifecycle state. */\nexport function isTerminalState(state: string): boolean {\n return state === State.Destroyed || state === State.Failed;\n}\n\n/**\n * Verdicts carried in Health.state. Separate from State on purpose: a failing\n * probe reports, it does not move the environment anywhere new.\n */\nexport const HealthState = {\n /** The probe has not passed yet and is still inside its start period, so\n * failures are not being counted. */\n Starting: \"starting\",\n /** The most recent attempt succeeded. */\n Passing: \"passing\",\n /** The probe failed its configured retries in a row after the start period\n * ended. */\n Failing: \"failing\",\n} as const;\n\nexport type HealthState = (typeof HealthState)[keyof typeof HealthState];\n\n/** HitlSpec is the human-in-the-loop policy an environment is created with. */\nexport interface HitlSpec {\n /** Default deadline for every intervention, 10 to 86400. Omitted means 600. */\n timeout_seconds?: number;\n /** \"reject\" (the default) or \"allow\". */\n on_timeout?: string;\n /** The request kinds the agent may raise. */\n requests: HitlRequests;\n /** Refuse decisions made without a pinned or asserted actor. */\n require_actor?: boolean;\n /** Webhooks told about every intervention and audit event. */\n notify?: HitlWebhook[];\n /** Gates hold, record or deny exec, lifecycle and computer actions, and\n * raise stall and expiry signals. */\n gates?: HitlGate[];\n /** Allowlist mode for exec. */\n exec?: HitlExecPolicy;\n}\n\n/** HitlGate is one enforced gate. */\nexport interface HitlGate {\n name: string;\n /** HitlKind.Exec, HitlKind.Lifecycle, HitlKind.Computer, HitlKind.Stall\n * or HitlKind.Expiry. */\n on: string;\n match: HitlGateMatch;\n /** One of GateMode; ask is the default. */\n mode?: string;\n /** The default reach of an approval: \"once\", \"env\" or \"ttl:<duration>\". */\n grant?: string;\n timeout_seconds?: number;\n /** Returned on a deny and shown to the human on an ask. */\n reason?: string;\n /** A webhook asked allow, deny or ask before a human sees an ask gate's\n * action. A failure or timeout means ask. */\n decide?: HitlDecider;\n}\n\n/** HitlDecider is a gate's decider. secret names an entry in the create\n * request's secrets; its value signs each call (Fuse-Signature). */\nexport interface HitlDecider {\n url: string;\n secret: string;\n}\n\n/** HitlGateMatch selects the actions a gate applies to. Every field set must\n * match. */\nexport interface HitlGateMatch {\n /** Matches the basename of argv[0] after env, sudo, nice, timeout, xargs,\n * nohup and stdbuf are stripped. */\n program?: string[];\n /** Matches when these appear in argv in this order. */\n args?: string[];\n /** Matches any opaque shell exec. */\n shell?: boolean;\n /** Matches lifecycle actions (one of LifecycleAction) or, on a computer\n * gate, computer action names (\"type\", \"key\", \"left_click\", ...). */\n action?: string[];\n /** Matches a computer \"type\" whose text contains any entry, ignoring\n * case. */\n text_contains?: string[];\n /** Raises a stall after this many consecutive non-zero exec exits\n * (on: \"stall\"). */\n failures?: number;\n /** Raises a stall after this long with no exec or computer call\n * (on: \"stall\"). */\n quiet_seconds?: number;\n /** Raises an expiry this long before the idle_timeout or max_runtime reap\n * (on: \"expiry\"). */\n before_seconds?: number;\n}\n\n/** HitlExecPolicy is allowlist mode for exec: a program not in allow is held\n * with default (\"ask\" or \"deny\"), interpreters and shells included. */\nexport interface HitlExecPolicy {\n default: string;\n allow: string[];\n}\n\n/** ExecPayload is a held exec. */\nexport interface ExecPayload {\n argv: string[];\n shell?: string;\n timeout_ms?: number;\n}\n\n/** ComputerPayload is a held computer action. input is the body as sent. */\nexport interface ComputerPayload {\n action: string;\n text?: string;\n input: unknown;\n}\n\n/** DeciderNote is what a gate's decider said when it sent an action on to a\n * human: verdict \"ask\" with its reason, or the error fuse fell through on. */\nexport interface DeciderNote {\n /** One of DeciderVerdict. */\n verdict: string;\n reason?: string;\n error?: string;\n}\n\n/** InterventionReview is a review request. content is the file as fuse read\n * it at request time when path is set. */\nexport interface InterventionReview {\n path?: string;\n content: string;\n /** One of ReviewFormat. */\n format: string;\n message?: string;\n truncated?: boolean;\n}\n\n/** LifecyclePayload is a held environment action. */\nexport interface LifecyclePayload {\n /** One of LifecycleAction. */\n action: string;\n}\n\n/** InterventionResult is what running an approved gated action produced. */\nexport interface InterventionResult {\n exec?: ExecResult;\n computer?: ComputerResult;\n env_id?: string;\n snapshot_id?: string;\n error?: string;\n /** RFC 3339 timestamp. */\n finished_at: string;\n}\n\n/** HitlWebhook is one hitl.notify target. `secret` names an entry of the\n * create request's secrets; its value signs each delivery with HMAC-SHA256\n * in the Fuse-Signature header. */\nexport interface HitlWebhook {\n url: string;\n secret: string;\n}\n\n/** HitlRequests declares the allowed request kinds. Present means allowed;\n * set ask (to {}) to allow asks. */\nexport interface HitlRequests {\n ask?: HitlAskRequests;\n secret?: HitlSecretRequests;\n takeover?: HitlTakeoverRequests;\n review?: HitlReviewRequests;\n}\n\n/** HitlReviewRequests configures review requests. Present means allowed. */\nexport type HitlReviewRequests = Record<string, never>;\n\n/** HitlSecretRequests declares where a secret may land. The agent names one\n * of these targets; it can never choose a path or variable of its own. */\nexport interface HitlSecretRequests {\n targets: HitlSecretTarget[];\n}\n\n/** HitlSecretTarget is one declared destination: exactly one of env (a\n * variable later execs see) or file (an absolute guest path, written 0600).\n * label is what the human is shown first. */\nexport interface HitlSecretTarget {\n env?: string;\n file?: string;\n label: string;\n}\n\n/** HitlTakeoverRequests declares the ways a human may take over: \"terminal\"\n * and \"desktop\" (which needs a desktop block). Empty means terminal. */\nexport interface HitlTakeoverRequests {\n via?: string[];\n}\n\n/** HitlAskRequests configures ask requests. Present means allowed. */\nexport type HitlAskRequests = Record<string, never>;\n\n/** Actor is who raised or decided an intervention: \"master\", \"key:<id>\", or\n * \"system\" for fuse itself (expiry, cancel on destroy). */\nexport interface Actor {\n id: string;\n name?: string;\n /** \"key\", \"system\" or \"decider\". */\n source: string;\n key_id?: string;\n}\n\n/** InterventionPayload is what was asked, attempted or noticed: a question\n * for an ask, the held exec or lifecycle action for a gate, a secret or\n * takeover request, or a signal. */\nexport interface InterventionPayload {\n question?: string;\n choices?: string[];\n exec?: ExecPayload;\n lifecycle?: LifecyclePayload;\n /** Set for a secret request only. */\n secret?: InterventionSecret;\n /** Set for a takeover only. */\n takeover?: InterventionTakeover;\n /** What fuse saw, for a stall or expiry. */\n signal?: InterventionSignal;\n /** The held computer action. */\n computer?: ComputerPayload;\n /** What is up for review. */\n review?: InterventionReview;\n /** The gate decider's note on an action it escalated. */\n decider?: DeciderNote;\n}\n\n/** InterventionSecret is a secret request. label comes from the Fusefile and\n * is what a human should read first; message is the agent's own text. The\n * value is never part of any intervention. */\nexport interface InterventionSecret {\n target: string;\n label: string;\n message?: string;\n}\n\n/** InterventionTakeover is a takeover. holder and started_at are set while a\n * human holds the environment, which is also when the agent's exec and\n * computer calls get 423. */\nexport interface InterventionTakeover {\n via: string;\n reason?: string;\n holder?: Actor;\n /** RFC 3339 timestamp. */\n started_at?: string;\n}\n\n/** InterventionSignal is what fuse noticed on its own. A stall carries the\n * failure run or the quiet time; an expiry carries the reaper due and when,\n * and once approved the time the environment is kept until. */\nexport interface InterventionSignal {\n failures?: number;\n last_exit_code?: number;\n quiet_seconds?: number;\n /** \"idle_timeout\" or \"max_runtime\". */\n reaper?: string;\n /** RFC 3339 timestamp. */\n reap_at?: string;\n /** RFC 3339 timestamp. */\n extended_until?: string;\n}\n\n/** InterventionDecision is how an intervention resolved. An expired one\n * carries the on_timeout outcome and a cancelled one a reject. */\nexport interface InterventionDecision {\n /** \"approve\" or \"reject\". */\n outcome: string;\n answer?: string;\n reason?: string;\n decided_by: Actor;\n decided_at: string;\n /** The argv the approver replaced a held exec's with. */\n edited_argv?: string[];\n /** The text the approver replaced a held type's with. */\n edited_text?: string;\n /** How far an approval of a gated action reaches. */\n grant?: string;\n}\n\n/** Intervention is one request for a human. */\nexport interface Intervention {\n id: string;\n env_id: string;\n kind: string;\n /** Names the gate that raised it; absent for a request. */\n gate?: string;\n /** The gate's mode (one of GateMode). notify and deny records are born\n * terminal. */\n mode?: string;\n /** One of InterventionState. */\n state: string;\n payload: InterventionPayload;\n triggered_by: Actor;\n /** RFC 3339 timestamp. */\n deadline: string;\n on_timeout: string;\n /** Set on every terminal intervention. */\n decision?: InterventionDecision;\n /** Set once an approved gated action has been performed. */\n result?: InterventionResult;\n created_at: string;\n updated_at: string;\n}\n\n/** AuditEntry is one row of the hash-chained hitl audit log. It holds who\n * did what and when, never intervention content. Hashes are hex. */\nexport interface AuditEntry {\n seq: number;\n /** One of AuditEvent. */\n event: string;\n intervention_id?: string;\n env_id?: string;\n actor: Actor;\n remote_addr?: string;\n /** Links a takeover_session row to its cast; fetch it with\n * interventions.getRecording. */\n recording_id?: string;\n /** RFC 3339 timestamp. */\n at: string;\n prev_hash: string;\n hash: string;\n}\n\n/** Audit log events. */\nexport const AuditEvent = {\n Raised: \"raised\",\n Decided: \"decided\",\n Expired: \"expired\",\n Cancelled: \"cancelled\",\n InviteMinted: \"invite_minted\",\n InviteUsed: \"invite_used\",\n GrantCreated: \"grant_created\",\n GrantUsed: \"grant_used\",\n SecretAnswered: \"secret_answered\",\n TakeoverStarted: \"takeover_started\",\n TakeoverEnded: \"takeover_ended\",\n TakeoverSession: \"takeover_session\",\n} as const;\n\nexport type AuditEvent = (typeof AuditEvent)[keyof typeof AuditEvent];\n\n/** Intervention kinds: ask is a request, exec and lifecycle are the gate\n * surfaces. */\nexport const HitlKind = {\n Ask: \"ask\",\n Exec: \"exec\",\n Lifecycle: \"lifecycle\",\n Computer: \"computer\",\n Review: \"review\",\n Secret: \"secret\",\n Takeover: \"takeover\",\n Stall: \"stall\",\n Expiry: \"expiry\",\n} as const;\n\nexport type HitlKind = (typeof HitlKind)[keyof typeof HitlKind];\n\n/** Gate modes. */\nexport const GateMode = {\n Ask: \"ask\",\n Notify: \"notify\",\n Deny: \"deny\",\n} as const;\n\nexport type GateMode = (typeof GateMode)[keyof typeof GateMode];\n\n/** Decider verdicts. */\nexport const DeciderVerdict = {\n Allow: \"allow\",\n Deny: \"deny\",\n Ask: \"ask\",\n} as const;\n\nexport type DeciderVerdict = (typeof DeciderVerdict)[keyof typeof DeciderVerdict];\n\n/** The actor source a decider's decision records. */\nexport const ACTOR_SOURCE_DECIDER = \"decider\";\n\n/** Review formats. */\nexport const ReviewFormat = {\n Text: \"text\",\n Diff: \"diff\",\n} as const;\n\nexport type ReviewFormat = (typeof ReviewFormat)[keyof typeof ReviewFormat];\n\n/** Takeover modes: terminal gives the human a shell, desktop the live\n * desktop view (it needs a desktop block). */\nexport const TakeoverVia = {\n Terminal: \"terminal\",\n Desktop: \"desktop\",\n} as const;\n\nexport type TakeoverVia = (typeof TakeoverVia)[keyof typeof TakeoverVia];\n\n/** Lifecycle actions a gate can hold. */\nexport const LifecycleAction = {\n Destroy: \"destroy\",\n Fork: \"fork\",\n Migrate: \"migrate\",\n Drain: \"drain\",\n Snapshot: \"snapshot\",\n RotateToken: \"rotate-token\",\n} as const;\n\nexport type LifecycleAction = (typeof LifecycleAction)[keyof typeof LifecycleAction];\n\n/** The gate name the exec allowlist reports. */\nexport const ALLOWLIST_GATE = \"exec.allowlist\";\n\n/** Intervention states. pending is the only non-terminal one. */\nexport const InterventionState = {\n Pending: \"pending\",\n Approved: \"approved\",\n Rejected: \"rejected\",\n Expired: \"expired\",\n Cancelled: \"cancelled\",\n} as const;\n\nexport type InterventionState =\n (typeof InterventionState)[keyof typeof InterventionState];\n\n/** Intervention outcomes. Every terminal intervention carries one. */\nexport const InterventionOutcome = {\n Approve: \"approve\",\n Reject: \"reject\",\n} as const;\n\nexport type InterventionOutcome =\n (typeof InterventionOutcome)[keyof typeof InterventionOutcome];\n\n/** isInterventionTerminal reports whether the intervention is resolved. */\nexport function isInterventionTerminal(i: Intervention | undefined): boolean {\n return !!i && !!i.state && i.state !== InterventionState.Pending;\n}\n\n/** isInterventionApproved reports whether the intervention resolved as\n * approve, which includes an expiry under on_timeout: allow. */\nexport function isInterventionApproved(i: Intervention | undefined): boolean {\n return i?.decision?.outcome === InterventionOutcome.Approve;\n}\n\n/** isInterventionSettled reports whether a caller has its final answer:\n * resolved, and for an approved gated action that fuse performs, performed\n * (with the outcome on result). */\nexport function isInterventionSettled(i: Intervention | undefined): boolean {\n if (!i || !isInterventionTerminal(i)) return false;\n // a decider's allow lets the caller perform the action itself.\n if (i.decision?.decided_by?.source === ACTOR_SOURCE_DECIDER) return true;\n const runs =\n i.mode === GateMode.Ask &&\n (!!i.payload?.exec || !!i.payload?.lifecycle || !!i.payload?.computer);\n return !runs || !isInterventionApproved(i) || !!i.result;\n}\n","import { FuseError } from \"./errors.js\";\n\n/**\n * requireArg throws a FuseError when a required path argument is missing,\n * mirroring the Go SDK's \"<thing> is required\" guards.\n */\nexport function requireArg(value: string | undefined | null, name: string): string {\n if (!value) {\n throw new FuseError(`${name} is required`);\n }\n return value;\n}\n","// SSE event streaming, porting the state machine in sdks/go/events.go to an\n// async iterator. The stream is opened (and its status checked) eagerly; the\n// returned AsyncIterable yields each Event and ends after a terminal-state\n// event (destroyed/failed) or on clean EOF. Stream-level failures are thrown\n// from the iterator. Caller abort is treated as normal termination.\n\nimport type { Transport } from \"./transport.js\";\nimport { FuseError } from \"./errors.js\";\nimport { type Event, isTerminalState } from \"./types.js\";\n\nconst DATA_PREFIX = \"data:\";\n\n/** Open the SSE stream for an environment and return an async-iterable of events. */\nexport async function streamEvents(\n t: Transport,\n vmId: string,\n signal?: AbortSignal,\n): Promise<AsyncIterable<Event>> {\n const path = `/v1/environments/${encodeURIComponent(vmId)}/events`;\n const res = await t.stream(path, undefined, signal);\n return parseEventStream(res, signal);\n}\n\nfunction parseEventStream(res: Response, signal?: AbortSignal): AsyncIterable<Event> {\n return {\n async *[Symbol.asyncIterator](): AsyncGenerator<Event> {\n const body = res.body;\n if (!body) return;\n\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n let data = \"\";\n let hasData = false;\n\n try {\n while (true) {\n let chunk;\n try {\n chunk = await reader.read();\n } catch (err) {\n // Caller-initiated abort is a clean end, not an error.\n if (signal?.aborted) return;\n throw new FuseError(\"event stream read failed\", { cause: err });\n }\n if (chunk.done) {\n // Clean EOF with no terminal state: just end (matches Go).\n return;\n }\n\n buffer += decoder.decode(chunk.value, { stream: true });\n\n let nl: number;\n while ((nl = buffer.indexOf(\"\\n\")) >= 0) {\n let line = buffer.slice(0, nl);\n buffer = buffer.slice(nl + 1);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1); // tolerate CRLF\n\n if (line === \"\") {\n // Blank line terminates the current event.\n if (!hasData) continue;\n const payload = data;\n data = \"\";\n hasData = false;\n\n let event: Event;\n try {\n event = JSON.parse(payload) as Event;\n } catch (err) {\n throw new FuseError(\"decode event\", { cause: err });\n }\n yield event;\n if (isTerminalState(event.state)) return;\n } else if (line.startsWith(\":\")) {\n // Comment / keepalive line — skip.\n continue;\n } else if (line.startsWith(DATA_PREFIX)) {\n // Strip the prefix and a single optional leading space; multiple\n // data: lines concatenate without a separator (matches server).\n let p = line.slice(DATA_PREFIX.length);\n if (p.startsWith(\" \")) p = p.slice(1);\n data += p;\n hasData = true;\n }\n // Other fields (id:, event:, ...) are ignored.\n }\n }\n } finally {\n // Release the underlying socket if the consumer breaks early.\n try {\n await reader.cancel();\n } catch {\n // ignore\n }\n }\n },\n };\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport { isInterventionSettled, type AuditEntry, type Intervention } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** The server's max page size; list() requests this internally. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** How long one long-poll asks the server to hold. It stays well under a\n * typical client timeout; the server caps it at 50s. */\nconst WAIT_POLL = \"30s\";\n\n/** Filters (and pagination) for interventions.list / interventions.listPage. */\nexport interface ListInterventionsOptions {\n /** Only interventions raised by this environment. */\n envId?: string;\n /** One of InterventionState. */\n state?: string;\n /** Only interventions raised or decided by this actor id. */\n actor?: string;\n /** Page size. Only consulted by listPage; list() always walks every page. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface InterventionList {\n interventions: Intervention[];\n next_cursor?: string;\n}\n\n/** One page of interventions.listPage, plus the cursor to fetch the next one. */\nexport interface InterventionPage {\n interventions: Intervention[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** Filters (and pagination) for interventions.audit / interventions.auditPage. */\nexport interface AuditOptions {\n /** Only rows for this environment. */\n envId?: string;\n /** Only rows for this actor id. */\n actor?: string;\n /** An RFC 3339 time, or a duration like \"24h\" meaning that long ago. */\n since?: string;\n /** Page size. Only consulted by auditPage; audit() always walks every page. */\n limit?: number;\n /** Opaque cursor from a previous auditPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface AuditList {\n entries: AuditEntry[];\n next_cursor?: string;\n}\n\n/** One page of interventions.auditPage, plus the cursor to fetch the next one. */\nexport interface AuditPage {\n entries: AuditEntry[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** Body for interventions.approve: an answer to an ask, or an approval of a\n * held exec or lifecycle action. */\nexport interface ApproveOptions {\n /** An ask needs an answer (one of its choices, when it has any). */\n answer?: string;\n reason?: string;\n /** Replaces a held exec's argv. It is re-checked against the deny gates,\n * and cannot be combined with grant. */\n editedArgv?: string[];\n /** Replaces a held computer \"type\" action's text. It is re-checked against\n * the deny gates, and cannot be combined with grant. */\n editedText?: string;\n /** \"once\", \"env\" or \"ttl:<duration>\"; unset takes the gate's default. */\n grant?: string;\n /** How long approving an expiry keeps the environment alive. Zero or unset\n * is one more full window of the reaper that was due. */\n extendSeconds?: number;\n}\n\n/** Body for interventions.reject. */\nexport interface RejectOptions {\n /** Fed back to the agent; the server fills one in when empty. */\n reason?: string;\n}\n\n/** InterventionsService reads and decides hitl interventions. */\nexport class InterventionsService {\n constructor(private readonly t: Transport) {}\n\n /** List every intervention matching options, oldest first, walking every\n * page. */\n async list(\n options: ListInterventionsOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention[]> {\n const out: Intervention[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.interventions);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of interventions matching options. */\n async listPage(\n options: ListInterventionsOptions = {},\n opts: CallOptions = {},\n ): Promise<InterventionPage> {\n const out = await this.t.json<InterventionList>(\"GET\", \"/v1/interventions\", {\n query: {\n env: options.envId,\n state: options.state,\n actor: options.actor,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { interventions: out.interventions ?? [], nextCursor: out.next_cursor };\n }\n\n /** List every hitl audit row matching options, oldest first, walking every\n * page. */\n async audit(options: AuditOptions = {}, opts: CallOptions = {}): Promise<AuditEntry[]> {\n const out: AuditEntry[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.auditPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.entries);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of the hitl audit log matching options. */\n async auditPage(\n options: AuditOptions = {},\n opts: CallOptions = {},\n ): Promise<AuditPage> {\n const out = await this.t.json<AuditList>(\"GET\", \"/v1/hitl/audit\", {\n query: {\n env: options.envId,\n actor: options.actor,\n since: options.since,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { entries: out.entries ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a takeover session's recording (an AuditEntry's recording_id):\n * asciinema v2 cast text for a terminal session, json (an input-action log\n * plus screenshots) for a desktop one. Needs the hitl:read scope. */\n async getRecording(recordingId: string, opts: CallOptions = {}): Promise<string> {\n requireArg(recordingId, \"recording id\");\n return this.t.text(\"GET\", `/v1/hitl/recordings/${encodeURIComponent(recordingId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Fetch one intervention without waiting. */\n async get(id: string, opts: CallOptions = {}): Promise<Intervention> {\n return getIntervention(this.t, id, undefined, opts);\n }\n\n /**\n * Block until the intervention settles: resolved, and for an approved gated\n * action, performed, with the outcome on result. Every intervention has a deadline,\n * so this always returns eventually. A dropped connection or an\n * orchestrator restart is survived by polling again; the server, not the\n * connection, holds the state. Pass `opts.signal` to stop early.\n */\n async wait(id: string, opts: CallOptions = {}): Promise<Intervention> {\n return waitIntervention(this.t, id, opts);\n }\n\n /** Resolve a pending intervention as approved. For a held exec or\n * lifecycle action, the orchestrator then performs it (optionally with\n * body.editedArgv, or granting repeats with body.grant); wait on the id for\n * its result. Requires the master token. */\n async approve(\n id: string,\n body: ApproveOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n return this.decide(id, \"approve\", body, opts);\n }\n\n /** Resolve a pending intervention as rejected. Requires the master token. */\n async reject(\n id: string,\n body: RejectOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n return this.decide(id, \"reject\", { reason: body.reason }, opts);\n }\n\n /**\n * Answer a pending secret request. The value is written into the guest at\n * the declared target and dropped; fuse never stores, logs or returns it.\n * Needs the hitl:secret scope.\n */\n async answerSecret(\n id: string,\n value: string,\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/interventions/${encodeURIComponent(id)}`,\n { query: { action: \"secret\" }, body: { value }, signal: opts.signal },\n );\n }\n\n private async decide(\n id: string,\n action: string,\n body: ApproveOptions,\n opts: CallOptions,\n ): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/interventions/${encodeURIComponent(id)}`,\n {\n query: { action },\n body: {\n answer: body.answer || undefined,\n reason: body.reason || undefined,\n edited_argv: body.editedArgv?.length ? body.editedArgv : undefined,\n edited_text: body.editedText,\n grant: body.grant || undefined,\n extend_seconds: body.extendSeconds || undefined,\n },\n signal: opts.signal,\n },\n );\n }\n}\n\n/** waitIntervention long-polls until the intervention is settled. A wait can\n * time out on an approved gated action that has not run yet, so the loop\n * checks settled, not terminal. */\nexport async function waitIntervention(\n t: Transport,\n id: string,\n opts: CallOptions = {},\n): Promise<Intervention> {\n for (;;) {\n const i = await getIntervention(t, id, WAIT_POLL, opts);\n if (isInterventionSettled(i)) return i;\n opts.signal?.throwIfAborted();\n }\n}\n\nfunction getIntervention(\n t: Transport,\n id: string,\n wait: string | undefined,\n opts: CallOptions,\n): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return t.json<Intervention>(\"GET\", `/v1/interventions/${encodeURIComponent(id)}`, {\n query: { wait },\n signal: opts.signal,\n });\n}\n","// hitl gates: waiting out a call a gate held, mirroring sdks/go/gates.go.\n\nimport type { CallOptions, Transport } from \"./transport.js\";\nimport { isInterventionApproved, type Intervention } from \"./types.js\";\nimport {\n HeldActionError,\n InterventionRejectedError,\n PendingInterventionError,\n} from \"./errors.js\";\nimport { waitIntervention } from \"./interventions.js\";\n\n/** Per-call overrides of the client's hitl wait options. */\nexport interface HeldOptions {\n /** false throws a PendingInterventionError instead of waiting. */\n wait?: boolean;\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * settleHeld waits out a held call: it reports the hold, waits until the\n * intervention settles, and turns anything but a successful run into an\n * error. Only opts.signal bounds the wait; every intervention has a\n * deadline, so it always ends.\n */\nexport async function settleHeld(\n t: Transport,\n held: Intervention,\n o: HeldOptions,\n opts: CallOptions,\n): Promise<Intervention> {\n const onHeld = o.onHeld ?? t.onHeld;\n onHeld?.(held);\n if (o.wait === false || t.hitlNoWait) throw new PendingInterventionError(held);\n const i = await waitIntervention(t, held.id, opts);\n if (!isInterventionApproved(i)) throw new InterventionRejectedError(i);\n if (i.result?.error) throw new HeldActionError(i);\n return i;\n}\n","// hitl takeover lock: waiting out a 423 on exec and computer calls, mirroring\n// sdks/go. while a human holds the environment (or an ask-mode stall is\n// pending) those calls are refused; by default the sdk waits for the\n// intervention to settle and retries, so agent code needs no changes.\n\nimport type { CallOptions, Transport } from \"./transport.js\";\nimport type { Intervention } from \"./types.js\";\nimport { isLocked } from \"./errors.js\";\nimport { waitIntervention } from \"./interventions.js\";\n\n/** Per-call options for calls a takeover can lock or a gate can hold\n * (computer actions). */\nexport interface LockedCallOptions extends CallOptions {\n /** Wait out a takeover or a pending stall, and a gate's hold (the\n * default). false throws a LockedError or a PendingInterventionError at\n * once instead. */\n wait?: boolean;\n /** Called with the pending intervention when a gate holds the action,\n * before waiting on it. It overrides the client's onHeld. */\n onHeld?: (held: Intervention) => void;\n}\n\n/** Body for environments.takeover. */\nexport interface TakeoverOptions {\n /** How to take over: TakeoverVia.Terminal (the default) or\n * TakeoverVia.Desktop. */\n via?: string;\n /** Recorded when no agent request is pending to claim. */\n reason?: string;\n}\n\n/** Body for environments.release. */\nexport interface ReleaseOptions {\n /** Handed back to the agent as the takeover's answer. */\n note?: string;\n}\n\n/**\n * retryLocked runs call, and on a 423 waits until the named intervention is\n * no longer pending, then runs it again. a fresh 423 waits again. the server\n * bounds every lock by the intervention deadline; opts.signal stops early.\n */\nexport async function retryLocked<T>(\n t: Transport,\n call: () => Promise<T>,\n wait: boolean | undefined,\n opts: CallOptions,\n): Promise<T> {\n for (;;) {\n try {\n return await call();\n } catch (err) {\n if (wait === false || !isLocked(err) || !err.interventionId) throw err;\n await waitIntervention(t, err.interventionId, opts);\n opts.signal?.throwIfAborted();\n }\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type {\n ComputerAction,\n ComputerDisplay,\n ComputerResult,\n ComputerToolResult,\n CreateRequest,\n EnvironmentInfo,\n Event,\n ExecRequest,\n ExecResult,\n ForkOptions,\n Intervention,\n MigrateOptions,\n ToolResultBlock,\n} from \"./types.js\";\nimport { HitlKind, isInterventionApproved } from \"./types.js\";\nimport {\n FuseError,\n InterventionRejectedError,\n isFuseApiError,\n isHitlDenied,\n} from \"./errors.js\";\nimport { requireArg } from \"./validate.js\";\nimport { streamEvents } from \"./events.js\";\nimport { waitIntervention } from \"./interventions.js\";\nimport { settleHeld } from \"./gates.js\";\nimport {\n retryLocked,\n type LockedCallOptions,\n type ReleaseOptions,\n type TakeoverOptions,\n} from \"./takeover.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Filters (and pagination) for environments.list / environments.listPage. */\nexport interface ListEnvironmentsOptions {\n taskId?: string;\n state?: string;\n hostId?: string;\n /** Page size (server default 50, max 200). Only consulted by listPage —\n * list() always walks every page, so it ignores this and requests the\n * server's max page size. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface EnvironmentList {\n environments: EnvironmentInfo[];\n next_cursor?: string;\n}\n\n/** One page of environments.listPage, plus the cursor to fetch the next one. */\nexport interface EnvironmentPage {\n environments: EnvironmentInfo[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** What environments.requestHuman sends. */\nexport interface HumanRequest {\n /** The request kind: \"ask\" (the default), \"secret\", \"takeover\" or\n * \"review\". */\n kind?: string;\n /** What the human is asked (ask). */\n question?: string;\n /** Restricts the answer to one of these (ask). */\n choices?: string[];\n /** A declared secret target: its env name or file path (secret). */\n target?: string;\n /** The agent's text shown under the target's label (secret), or with the\n * content up for review (review). */\n message?: string;\n /** How the human takes over: \"terminal\" or \"desktop\" (takeover). */\n via?: string;\n /** Why the agent wants a human to take over (takeover). */\n reason?: string;\n /** An absolute guest file to review; exclusive with content (review). */\n path?: string;\n /** Inline text or a diff to review (review). */\n content?: string;\n /** ReviewFormat.Text or ReviewFormat.Diff; unset guesses (review). */\n format?: string;\n /** Shortens the policy's deadline. It can never extend it. */\n timeoutSeconds?: number;\n /** Wait for a decision (the default). false returns the pending\n * intervention at once; wait on it later with interventions.wait. */\n wait?: boolean;\n}\n\n/** What environments.requestReview sends: exactly one of path and content. */\nexport interface ReviewRequest {\n /** An absolute guest file; fuse reads it at request time. */\n path?: string;\n /** Inline text or a diff. */\n content?: string;\n /** ReviewFormat.Text or ReviewFormat.Diff; unset guesses. */\n format?: string;\n message?: string;\n timeoutSeconds?: number;\n /** Wait for the verdict (the default). false returns at once with the\n * pending intervention and approved false. */\n wait?: boolean;\n}\n\n/** ReviewResult is a finished review. comments are the reviewer's, on\n * either outcome. */\nexport interface ReviewResult {\n approved: boolean;\n comments: string;\n intervention: Intervention;\n}\n\n/** EnvironmentsService manages microVM lifecycle. */\nexport class EnvironmentsService {\n constructor(private readonly t: Transport) {}\n\n /** List tracked environments, optionally filtered. Transparently walks\n * every result page. For explicit single-page control (e.g. a cursor from\n * a previous call), use listPage. */\n async list(\n options: ListEnvironmentsOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo[]> {\n const out: EnvironmentInfo[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.environments);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of tracked environments, optionally filtered. */\n async listPage(\n options: ListEnvironmentsOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentPage> {\n const out = await this.t.json<EnvironmentList>(\"GET\", \"/v1/environments\", {\n query: {\n task_id: options.taskId,\n state: options.state,\n host_id: options.hostId,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { environments: out.environments ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a single environment by VM id. */\n async get(vmId: string, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n return this.t.json<EnvironmentInfo>(\n \"GET\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { signal: opts.signal },\n );\n }\n\n /** Provision a new environment. Blocks until running or creation fails. */\n async create(body: CreateRequest, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n return this.t.json<EnvironmentInfo>(\"POST\", \"/v1/environments\", {\n body,\n signal: opts.signal,\n });\n }\n\n /** Fork an environment into a new one; returns the new environment. When a\n * hitl gate holds the fork, it waits for the decision and returns the\n * environment the orchestrator then forked. */\n async fork(\n vmId: string,\n body: ForkOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"fork\" }, body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n return this.heldEnvironment(out.held, opts);\n }\n\n /**\n * Migrate an environment to another host; returns the new environment. The\n * source is drained and destroyed once the new one is running.\n */\n async migrate(\n vmId: string,\n body: MigrateOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"migrate\" }, body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n return this.heldEnvironment(out.held, opts);\n }\n\n /** heldEnvironment waits out a held fork or migrate and returns the\n * environment it produced. */\n private async heldEnvironment(\n held: Intervention,\n opts: CallOptions,\n ): Promise<EnvironmentInfo> {\n const i = await settleHeld(this.t, held, {}, opts);\n if (!i.result?.env_id) {\n throw new FuseError(`intervention ${i.id} settled without an environment`);\n }\n return this.get(i.result.env_id, opts);\n }\n\n /**\n * Run a command inside a running environment's guest and return its exit code\n * with stdout and stderr kept separate.\n *\n * A non-zero exit_code is resolved, not thrown: the command ran and failed.\n * A thrown error means the command could not be run at all.\n *\n * Exec requires the master token.\n *\n * When a hitl gate holds the exec, exec waits for the decision (bounded\n * only by `opts.signal`); the orchestrator runs the approved (possibly\n * edited) argv and exec returns its result. A rejection throws an\n * InterventionRejectedError, a deny gate an error isHitlDenied matches.\n * `wait: false` throws a PendingInterventionError at once instead.\n *\n * While a human holds a takeover (or an ask-mode stall is pending) the\n * server answers 423; exec waits for that intervention to settle and runs\n * the command then. `wait: false` throws a LockedError at once instead.\n *\n * @example\n * const out = await client.environments.exec(id, { cmd: [\"ls\", \"-l\"] });\n * if (out.exit_code !== 0) console.error(out.stderr);\n */\n async exec(\n vmId: string,\n body: ExecRequest,\n opts: CallOptions = {},\n ): Promise<ExecResult> {\n requireArg(vmId, \"vm id\");\n const hasCmd = (body.cmd?.length ?? 0) > 0;\n const hasShell = (body.shell ?? \"\") !== \"\";\n if (!hasCmd && !hasShell) {\n throw new FuseError(\"one of cmd or shell is required\");\n }\n if (hasCmd && hasShell) {\n throw new FuseError(\"cmd and shell are mutually exclusive\");\n }\n const { wait, onHeld, ...wire } = body;\n // a 423 (a human holds the environment) waits and retries; a 202 (a gate\n // holds this exec) waits for the decision and its run.\n const out = await retryLocked(\n this.t,\n () =>\n this.t.gated<ExecResult>(\"POST\", `/v1/environments/${encodeURIComponent(vmId)}`, {\n query: { action: \"exec\" },\n body: wire,\n signal: opts.signal,\n }),\n wait,\n opts,\n );\n if (!out.held) return out.value;\n const i = await settleHeld(this.t, out.held, { wait, onHeld }, opts);\n if (!i.result?.exec) {\n throw new FuseError(`intervention ${i.id} settled without an exec result`);\n }\n return i.result.exec;\n }\n\n /**\n * Relay one computer-use action to the environment's desktop and return the\n * result, usually carrying a base64 PNG screenshot. Requires an environment\n * booted from a desktop image; on any other image the server answers 503\n * with a reason.\n *\n * Like exec, it waits out a takeover or a pending stall (a 423) and then\n * acts; `opts.wait: false` throws a LockedError at once instead. When a\n * computer gate holds the action (a 202), it waits for the decision and\n * returns what the orchestrator got performing it (with the human's edited\n * text, if any); a rejection throws an InterventionRejectedError, and\n * `opts.wait: false` throws a PendingInterventionError at once instead.\n *\n * @example\n * const res = await client.environments.computer(id, {\n * action: \"left_click\",\n * coordinate: [512, 384],\n * });\n */\n async computer(\n vmId: string,\n action: ComputerAction,\n opts: LockedCallOptions = {},\n ): Promise<ComputerResult> {\n requireArg(vmId, \"vm id\");\n requireArg(action?.action, \"action\");\n return this.postComputer(vmId, action, opts);\n }\n\n /**\n * Execute one computer tool_use against the environment and shape the\n * answer for the Messages API: the tool_use block's `input` goes in\n * verbatim (it is already the wire shape the computer endpoint takes), and\n * content blocks for the tool_result come out.\n *\n * An action the environment refuses (a malformed coordinate, a display\n * that is not up) resolves to `is_error` content rather than throwing: the\n * agent loop should feed it to the model, which is the party that can\n * correct it. So does a hitl deny gate or a human rejecting a held action. A throw is reserved for failures the model cannot fix —\n * transport, auth, an unknown environment.\n *\n * @example\n * for (const block of msg.content) {\n * if (block.type === \"tool_use\" && block.name === \"computer\") {\n * const result = await client.environments.computerToolResult(id, block.input);\n * toolResults.push({ type: \"tool_result\", tool_use_id: block.id, ...result });\n * }\n * }\n */\n async computerToolResult(\n vmId: string,\n input: unknown,\n opts: LockedCallOptions = {},\n ): Promise<ComputerToolResult> {\n requireArg(vmId, \"vm id\");\n const action = (input as { action?: string } | null)?.action ?? \"\";\n if (action === \"\") {\n return {\n is_error: true,\n content: [{ type: \"text\", text: \"tool input names no action\" }],\n };\n }\n let res: ComputerResult;\n try {\n res = await this.postComputer(vmId, input, opts);\n } catch (err) {\n if (\n isFuseApiError(err) &&\n (err.status === 400 ||\n err.status === 409 ||\n err.status === 503 ||\n isHitlDenied(err))\n ) {\n return {\n is_error: true,\n content: [{ type: \"text\", text: err.message || \"the computer action failed\" }],\n };\n }\n if (err instanceof InterventionRejectedError) {\n return {\n is_error: true,\n content: [\n { type: \"text\", text: `a human rejected this action: ${err.message}` },\n ],\n };\n }\n throw err;\n }\n const content: ToolResultBlock[] = [];\n if (res.output) content.push({ type: \"text\", text: res.output });\n if (res.screenshot) {\n content.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: \"image/png\",\n data: res.screenshot,\n },\n });\n }\n if (content.length === 0) content.push({ type: \"text\", text: \"done\" });\n return { content };\n }\n\n private async postComputer(\n vmId: string,\n body: unknown,\n opts: LockedCallOptions,\n ): Promise<ComputerResult> {\n // a 423 (a human holds the environment) waits and retries; a 202 (a gate\n // holds this action) waits for the decision and its run.\n const out = await retryLocked(\n this.t,\n () =>\n this.t.gated<ComputerResult>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}/computer`,\n { body, signal: opts.signal },\n ),\n opts.wait,\n opts,\n );\n if (!out.held) return out.value;\n const i = await settleHeld(\n this.t,\n out.held,\n { wait: opts.wait, onHeld: opts.onHeld },\n opts,\n );\n if (!i.result?.computer) {\n throw new FuseError(`intervention ${i.id} settled without a computer result`);\n }\n return i.result.computer;\n }\n\n /**\n * Ask a human for something the environment's hitl policy declares. By\n * default it waits (by long-polling) until the intervention resolves\n * (answered, rejected, expired or cancelled); read the result off the\n * returned intervention's decision. Pass `wait: false` to get the pending\n * handle instead. Pass `opts.signal` to stop waiting early.\n *\n * @example\n * const res = await client.environments.requestHuman(id, {\n * question: \"deploy to prod?\",\n * choices: [\"yes\", \"no\"],\n * });\n * if (isInterventionApproved(res)) console.log(res.decision?.answer);\n */\n async requestHuman(\n vmId: string,\n req: HumanRequest,\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n const pending = await this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"request\" },\n body: {\n kind: req.kind || \"ask\",\n question: req.question || undefined,\n choices: req.choices,\n target: req.target || undefined,\n message: req.message || undefined,\n via: req.via || undefined,\n reason: req.reason || undefined,\n path: req.path || undefined,\n content: req.content || undefined,\n format: req.format || undefined,\n timeout_seconds: req.timeoutSeconds || undefined,\n },\n signal: opts.signal,\n },\n );\n if (req.wait === false) return pending;\n return waitIntervention(this.t, pending.id, opts);\n }\n\n /**\n * Submit a guest file or a text/diff blob for a human to approve or reject\n * with comments, and wait for the verdict. Needs hitl.requests.review.\n * With `wait: false` it returns at once with the pending intervention and\n * approved false.\n *\n * @example\n * const r = await client.environments.requestReview(id, {\n * content: diff,\n * format: ReviewFormat.Diff,\n * });\n * if (!r.approved) console.log(r.comments);\n */\n async requestReview(\n vmId: string,\n req: ReviewRequest,\n opts: CallOptions = {},\n ): Promise<ReviewResult> {\n const i = await this.requestHuman(\n vmId,\n {\n kind: HitlKind.Review,\n path: req.path,\n content: req.content,\n format: req.format,\n message: req.message,\n timeoutSeconds: req.timeoutSeconds,\n wait: req.wait,\n },\n opts,\n );\n return {\n approved: isInterventionApproved(i),\n comments: i.decision?.reason ?? \"\",\n intervention: i,\n };\n }\n\n /**\n * Take over the environment as a human: claims the agent's pending\n * takeover request if there is one, else opens a new one. While held, the\n * agent's exec and computer calls wait. Returns the held intervention.\n * Needs the hitl:takeover scope; a conflict when someone else holds it.\n */\n async takeover(\n vmId: string,\n body: TakeoverOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"takeover\" },\n body: { via: body.via || undefined, reason: body.reason || undefined },\n signal: opts.signal,\n },\n );\n }\n\n /**\n * End a takeover and hand the environment back to the agent. The note is\n * the takeover's answer. Returns the approved intervention; a conflict when\n * nothing is held.\n */\n async release(\n vmId: string,\n body: ReleaseOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"release\" },\n body: { note: body.note || undefined },\n signal: opts.signal,\n },\n );\n }\n\n /** Report whether the environment has a live display and at what geometry.\n * up is false with a reason on an image with no desktop. */\n async computerDisplay(vmId: string, opts: CallOptions = {}): Promise<ComputerDisplay> {\n requireArg(vmId, \"vm id\");\n return this.t.json<ComputerDisplay>(\n \"GET\",\n `/v1/environments/${encodeURIComponent(vmId)}/computer`,\n { signal: opts.signal },\n );\n }\n\n /**\n * Phase-1 only: quiesces the guest workload and moves the environment to\n * \"draining\" so you can inspect its output, but does not destroy it. Call\n * destroy() afterward to remove it. A drained environment left\n * undestroyed keeps running (and billing) until the orchestrator's\n * draining timeout (5m30s by default) passes, and then the orchestrator\n * destroys it.\n */\n async drain(vmId: string, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"drain\" }, signal: opts.signal },\n );\n if (!out.held) return out.value;\n await settleHeld(this.t, out.held, {}, opts);\n return this.get(vmId, opts);\n }\n\n /** Rotate the per-VM credentials and push them to the guest. */\n async rotateToken(vmId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(vmId, \"vm id\");\n const held = await this.t.gatedNoContent(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"rotate-token\" }, signal: opts.signal },\n );\n if (held) await settleHeld(this.t, held, {}, opts);\n }\n\n /** Forcefully destroy an environment. Idempotent. When a hitl gate holds\n * the destroy, it waits for the decision. */\n async destroy(vmId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(vmId, \"vm id\");\n const held = await this.t.gatedNoContent(\n \"DELETE\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { signal: opts.signal },\n );\n if (held) await settleHeld(this.t, held, {}, opts);\n }\n\n /**\n * Open the SSE event stream for an environment. The returned promise rejects\n * with a FuseApiError on a connect-time failure (e.g. not_found); on success\n * it resolves to an AsyncIterable that yields each Event and ends after a\n * terminal-state event. Pass `opts.signal` to cancel; there is no built-in\n * timeout on the stream.\n *\n * @example\n * for await (const ev of await client.environments.events(id)) {\n * console.log(ev.state);\n * }\n */\n async events(vmId: string, opts: CallOptions = {}): Promise<AsyncIterable<Event>> {\n requireArg(vmId, \"vm id\");\n return streamEvents(this.t, vmId, opts.signal);\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { ResolveSnapshotResponse, Snapshot, SnapshotRequest } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\nimport { FuseError } from \"./errors.js\";\nimport { settleHeld } from \"./gates.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Filters (and pagination) for snapshots.list / snapshots.listPage. */\nexport interface ListSnapshotsOptions {\n vmId?: string;\n taskId?: string;\n tenantId?: string;\n state?: string;\n /** Narrows to the build layers taken after one setup step. Unset means \"do\n * not filter\", never \"match artifacts with no layer key\". */\n layerKey?: string;\n /** Narrows to artifacts built on one architecture, in GOARCH vocabulary\n * (\"amd64\", \"arm64\"). It is a separate filter from layerKey rather than\n * part of it because a rootfs is not portable across architectures, so a\n * layer lookup that does not constrain arch can be served bytes it cannot\n * boot. */\n arch?: string;\n /** Page size (server default 50, max 200). Only consulted by listPage —\n * list() always walks every page, so it ignores this and requests the\n * server's max page size. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface SnapshotList {\n snapshots: Snapshot[];\n next_cursor?: string;\n}\n\n/** One page of snapshots.listPage, plus the cursor to fetch the next one. */\nexport interface SnapshotPage {\n snapshots: Snapshot[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** SnapshotsService manages microVM snapshots. */\nexport class SnapshotsService {\n constructor(private readonly t: Transport) {}\n\n /** Create a snapshot of a running environment.\n *\n * An empty body takes a disk snapshot, the rootfs and nothing else; pass\n * `{ live: true }` to capture the guest's memory and vCPU state as well.\n *\n * The returned `snapshot.kind` reports what was actually written, which can\n * be `\"disk\"` even for a `live: true` request that reached a host too old to\n * honour it. A caller that depends on the memory being there should check\n * it. `live: true` against a backend with no live-snapshot support throws a\n * 501 `unimplemented`, not a conflict.\n *\n * When a hitl gate holds the snapshot, create waits for the decision and\n * returns the snapshot the orchestrator then took. */\n async create(\n vmId: string,\n body: SnapshotRequest = {},\n opts: CallOptions = {},\n ): Promise<Snapshot> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<Snapshot>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}/snapshots`,\n { body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n const i = await settleHeld(this.t, out.held, {}, opts);\n if (!i.result?.snapshot_id) {\n throw new FuseError(`intervention ${i.id} settled without a snapshot`);\n }\n return this.get(i.result.snapshot_id, opts);\n }\n\n /** List snapshots, optionally filtered. Transparently walks every result\n * page. For explicit single-page control (e.g. a cursor from a previous\n * call), use listPage. */\n async list(\n options: ListSnapshotsOptions = {},\n opts: CallOptions = {},\n ): Promise<Snapshot[]> {\n const out: Snapshot[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.snapshots);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of snapshots, optionally filtered. */\n async listPage(\n options: ListSnapshotsOptions = {},\n opts: CallOptions = {},\n ): Promise<SnapshotPage> {\n const out = await this.t.json<SnapshotList>(\"GET\", \"/v1/snapshots\", {\n query: {\n vm_id: options.vmId,\n task_id: options.taskId,\n tenant_id: options.tenantId,\n state: options.state,\n layer_key: options.layerKey,\n arch: options.arch,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { snapshots: out.snapshots ?? [], nextCursor: out.next_cursor };\n }\n\n /**\n * Resolve one layer cache key and architecture to the newest ready build\n * artifact, or null when there is none.\n *\n * A miss is not an error and never rejects: a cold cache is the normal state\n * of a first build, and modelling it as a failure would make every caller\n * wrap this in a try/catch to discover nothing was wrong.\n *\n * arch is required rather than defaulted. An ext4 rootfs is not portable\n * across architectures, so resolving without one could hand back an artifact\n * the caller cannot boot, at the exact moment it believes it got a hit.\n *\n * The scope searched comes from how the client authenticated; there is\n * deliberately no tenant parameter.\n */\n async resolve(\n layerKey: string,\n arch: string,\n opts: CallOptions = {},\n ): Promise<Snapshot | null> {\n requireArg(layerKey, \"layer key\");\n requireArg(arch, \"arch\");\n const out = await this.t.json<ResolveSnapshotResponse>(\n \"GET\",\n \"/v1/snapshots/resolve\",\n { query: { layer_key: layerKey, arch }, signal: opts.signal },\n );\n return out.found && out.snapshot ? out.snapshot : null;\n }\n\n /** Fetch a single snapshot by id. */\n async get(snapshotId: string, opts: CallOptions = {}): Promise<Snapshot> {\n requireArg(snapshotId, \"snapshot id\");\n return this.t.json<Snapshot>(\n \"GET\",\n `/v1/snapshots/${encodeURIComponent(snapshotId)}`,\n { signal: opts.signal },\n );\n }\n\n /** Delete a snapshot. Idempotent; the snapshot must be a leaf. */\n async delete(snapshotId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(snapshotId, \"snapshot id\");\n await this.t.noContent(\"DELETE\", `/v1/snapshots/${encodeURIComponent(snapshotId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Restore an environment from a snapshot. */\n async restore(snapshotId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(snapshotId, \"snapshot id\");\n await this.t.noContent(\"POST\", `/v1/snapshots/${encodeURIComponent(snapshotId)}`, {\n query: { action: \"restore\" },\n signal: opts.signal,\n });\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { Host, RegisterHostRequest } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Pagination for hosts.listPage. */\nexport interface ListHostsOptions {\n /** Page size (server default 50, max 200). */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface HostList {\n hosts: Host[];\n next_cursor?: string;\n}\n\n/** One page of hosts.listPage, plus the cursor to fetch the next one. */\nexport interface HostPage {\n hosts: Host[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** HostsService manages registered Firecracker hosts. */\nexport class HostsService {\n constructor(private readonly t: Transport) {}\n\n /** Register (or re-register) a host. Idempotent on id. */\n async register(body: RegisterHostRequest, opts: CallOptions = {}): Promise<Host> {\n return this.t.json<Host>(\"POST\", \"/v1/hosts\", { body, signal: opts.signal });\n }\n\n /** List registered hosts. Transparently walks every result page. For\n * explicit single-page control (e.g. a cursor from a previous call), use\n * listPage. */\n async list(opts: CallOptions = {}): Promise<Host[]> {\n const out: Host[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listPage({ limit: MAX_PAGE_LIMIT, cursor }, opts);\n out.push(...page.hosts);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of registered hosts. */\n async listPage(\n options: ListHostsOptions = {},\n opts: CallOptions = {},\n ): Promise<HostPage> {\n const out = await this.t.json<HostList>(\"GET\", \"/v1/hosts\", {\n query: {\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { hosts: out.hosts ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a single host by id. */\n async get(hostId: string, opts: CallOptions = {}): Promise<Host> {\n requireArg(hostId, \"host id\");\n return this.t.json<Host>(\"GET\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Mark a host unschedulable; existing VMs keep running. */\n async cordon(hostId: string, opts: CallOptions = {}): Promise<void> {\n await this.action(hostId, \"cordon\", opts);\n }\n\n /** Return a cordoned host to active scheduling. */\n async uncordon(hostId: string, opts: CallOptions = {}): Promise<void> {\n await this.action(hostId, \"uncordon\", opts);\n }\n\n /** Remove a host. The host must have no running VMs. */\n async deregister(hostId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(hostId, \"host id\");\n await this.t.noContent(\"DELETE\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n signal: opts.signal,\n });\n }\n\n private async action(hostId: string, action: string, opts: CallOptions): Promise<void> {\n requireArg(hostId, \"host id\");\n await this.t.noContent(\"POST\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n query: { action },\n signal: opts.signal,\n });\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { ActorLabel, APIKey, CreatedAPIKey } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** Options for apiKeys.create. Naming scopes mints a key limited to the hitl\n * routes; it must expire (ttlSeconds, at most 86400). */\nexport interface CreateApiKeyOptions {\n label?: string;\n /** One or more of HitlScope. Omit for a full-access key. */\n scopes?: string[];\n /** Limit a scoped key to this environment and its forks. */\n envId?: string;\n /** Lifetime in seconds. */\n ttlSeconds?: number;\n /** Pin the key to this actor. */\n actor?: ActorLabel;\n}\n\ninterface APIKeyList {\n api_keys: APIKey[];\n}\n\n/**\n * ApiKeysService manages revocable API keys. These endpoints require the\n * master token; the server enforces this.\n */\nexport class ApiKeysService {\n constructor(private readonly t: Transport) {}\n\n /**\n * Issue a new API key. Pass a label, or options for a scoped key. The raw\n * secret is returned once in `key` and is unrecoverable afterward.\n */\n async create(\n labelOrOptions?: string | CreateApiKeyOptions,\n opts: CallOptions = {},\n ): Promise<CreatedAPIKey> {\n const o: CreateApiKeyOptions =\n typeof labelOrOptions === \"string\"\n ? { label: labelOrOptions }\n : (labelOrOptions ?? {});\n return this.t.json<CreatedAPIKey>(\"POST\", \"/v1/api-keys\", {\n body: {\n label: o.label || undefined,\n scopes: o.scopes,\n env_id: o.envId || undefined,\n ttl_seconds: o.ttlSeconds || undefined,\n actor: o.actor,\n },\n signal: opts.signal,\n });\n }\n\n /** List API key metadata. */\n async list(opts: CallOptions = {}): Promise<APIKey[]> {\n const out = await this.t.json<APIKeyList>(\"GET\", \"/v1/api-keys\", {\n signal: opts.signal,\n });\n return out.api_keys ?? [];\n }\n\n /** Revoke the API key with the given id. */\n async revoke(id: string, opts: CallOptions = {}): Promise<void> {\n requireArg(id, \"id\");\n await this.t.noContent(\"DELETE\", `/v1/api-keys/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n}\n","// generated by scripts/gen-version.mjs. do not edit.\nexport const VERSION = \"0.41.0\";\n","import { Transport, type FetchLike } from \"./transport.js\";\nimport { EnvironmentsService } from \"./environments.js\";\nimport { SnapshotsService } from \"./snapshots.js\";\nimport { HostsService } from \"./hosts.js\";\nimport { ApiKeysService } from \"./apiKeys.js\";\nimport { InterventionsService } from \"./interventions.js\";\nimport { VERSION } from \"./version.js\";\nimport type { ActorLabel, Intervention } from \"./types.js\";\n\n/** Options for constructing a FuseClient. */\nexport interface FuseClientOptions {\n /** Base URL of the Fuse control plane, e.g. \"https://fuse.example.com\". Required. */\n baseUrl: string;\n /** Bearer token (master token or an API key). Omit for unauthenticated endpoints. */\n token?: string;\n /** Custom fetch implementation. Defaults to the global fetch (Node 18+). */\n fetch?: FetchLike;\n /** User-Agent header. Defaults to \"fuse-ts/<version>\". Ignored by browsers. */\n userAgent?: string;\n /** Generator for the X-Request-ID header, called once per request. Empty results are omitted. */\n requestId?: () => string;\n /** Default per-request timeout in milliseconds. Does NOT apply to events() streams. */\n timeoutMs?: number;\n /** Extra default headers merged into every request. */\n headers?: Record<string, string>;\n /** The human this client acts for, sent as the Fuse-Actor and\n * Fuse-Actor-Name headers on every request. */\n actor?: ActorLabel;\n /** Make every hitl-gated call throw a PendingInterventionError at once\n * instead of waiting for the human. exec's `wait: false` does the same for\n * one exec. */\n hitlNoWait?: boolean;\n /** Called with the pending intervention whenever a gate holds a call,\n * before the call waits on it. exec's `onHeld` overrides it. */\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * FuseClient is the entry point for the Fuse API. It groups the resource\n * services that share a single transport.\n *\n * @example\n * const client = new FuseClient({ baseUrl: \"https://fuse.example.com\", token });\n * const env = await client.environments.create({ task_id: \"task-1\" });\n */\nexport class FuseClient {\n readonly environments: EnvironmentsService;\n readonly snapshots: SnapshotsService;\n readonly hosts: HostsService;\n readonly apiKeys: ApiKeysService;\n readonly interventions: InterventionsService;\n private readonly options: FuseClientOptions;\n\n constructor(options: FuseClientOptions) {\n this.options = options;\n const transport = new Transport({\n baseUrl: options.baseUrl,\n token: options.token,\n fetch: options.fetch,\n userAgent: options.userAgent ?? `fuse-ts/${VERSION}`,\n requestId: options.requestId,\n timeoutMs: options.timeoutMs,\n headers: options.headers,\n actor: options.actor,\n hitlNoWait: options.hitlNoWait,\n onHeld: options.onHeld,\n });\n this.environments = new EnvironmentsService(transport);\n this.snapshots = new SnapshotsService(transport);\n this.hosts = new HostsService(transport);\n this.apiKeys = new ApiKeysService(transport);\n this.interventions = new InterventionsService(transport);\n }\n\n /**\n * withActor returns a copy of this client, with the same options otherwise,\n * that sends `actor` as the Fuse-Actor headers. This client is unchanged.\n */\n withActor(actor: ActorLabel): FuseClient {\n return new FuseClient({ ...this.options, actor });\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/transport.ts","../src/types.ts","../src/validate.ts","../src/events.ts","../src/interventions.ts","../src/gates.ts","../src/takeover.ts","../src/environments.ts","../src/snapshots.ts","../src/hosts.ts","../src/apiKeys.ts","../src/version.ts","../src/client.ts"],"names":["REQUEST_ID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A,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,aAAA;AAAA,EACQ,OAAA;AAAA,EAEjB,YAAY,OAAA,EAA4B;AACtC,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,MAAM,SAAA,GAAY,IAAI,SAAA,CAAU;AAAA,MAC9B,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,SAAA,EAAW,OAAA,CAAQ,SAAA,IAAa,CAAA,QAAA,EAAW,OAAO,CAAA,CAAA;AAAA,MAClD,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,WAAW,OAAA,CAAQ,SAAA;AAAA,MACnB,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,YAAY,OAAA,CAAQ,UAAA;AAAA,MACpB,QAAQ,OAAA,CAAQ;AAAA,KACjB,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,GAAe,IAAI,mBAAA,CAAoB,SAAS,CAAA;AACrD,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,gBAAA,CAAiB,SAAS,CAAA;AAC/C,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAI,YAAA,CAAa,SAAS,CAAA;AACvC,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,cAAA,CAAe,SAAS,CAAA;AAC3C,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAI,oBAAA,CAAqB,SAAS,CAAA;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,KAAA,EAA+B;AACvC,IAAA,OAAO,IAAI,WAAA,CAAW,EAAE,GAAG,IAAA,CAAK,OAAA,EAAS,OAAO,CAAA;AAAA,EAClD;AACF","file":"index.js","sourcesContent":["// Error types for the Fuse SDK, mirroring sdks/go/errors.go: a structured\n// FuseApiError for non-2xx responses plus code-checking helpers, and a\n// FuseError for transport/configuration failures.\n\nimport type { Intervention } from \"./types.js\";\n\nconst REQUEST_ID_HEADER = \"X-Request-ID\";\n\n/** Stable, machine-readable error codes returned by the server. */\nexport const ErrorCode = {\n NotFound: \"not_found\",\n Conflict: \"conflict\",\n InvalidArgument: \"invalid_argument\",\n Unavailable: \"unavailable\",\n Internal: \"internal\",\n Unauthorized: \"unauthorized\",\n Forbidden: \"forbidden\",\n Locked: \"locked\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nconst STATUS_TEXT: Record<number, string> = {\n 400: \"bad request\",\n 401: \"unauthorized\",\n 403: \"forbidden\",\n 404: \"not found\",\n 409: \"conflict\",\n 423: \"locked\",\n 500: \"internal server error\",\n 502: \"bad gateway\",\n 503: \"service unavailable\",\n};\n\nfunction statusText(status: number): string {\n return STATUS_TEXT[status] ?? `status ${status}`;\n}\n\nexport interface FuseApiErrorInit {\n status: number;\n code?: string;\n message?: string;\n details?: Record<string, string>;\n requestId?: string;\n body?: string;\n}\n\nfunction formatMessage(init: FuseApiErrorInit): string {\n const parts: string[] = [`status=${init.status}`];\n if (init.code) parts.push(`code=${init.code}`);\n if (init.message) parts.push(init.message);\n else parts.push(statusText(init.status));\n if (init.requestId) parts.push(`request_id=${init.requestId}`);\n return \"fuse api error: \" + parts.join(\", \");\n}\n\n/** FuseApiError is a non-2xx response from the server. */\nexport class FuseApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly details?: Record<string, string>;\n readonly requestId?: string;\n /** Raw response body, when available. */\n readonly body?: string;\n\n constructor(init: FuseApiErrorInit) {\n super(formatMessage(init));\n this.name = \"FuseApiError\";\n this.status = init.status;\n this.code = init.code ?? \"\";\n this.details = init.details;\n this.requestId = init.requestId;\n this.body = init.body;\n // Restore the prototype chain so `instanceof` works after transpilation.\n Object.setPrototypeOf(this, FuseApiError.prototype);\n }\n}\n\n/** Reasons a forbidden error carries in details.reason. */\nexport const ForbiddenReason = {\n MissingScope: \"missing_scope\",\n EnvScope: \"env_scope\",\n SelfApproval: \"self_approval\",\n ActorRequired: \"actor_required\",\n ActorMismatch: \"actor_mismatch\",\n ActorNotAllowed: \"actor_not_allowed\",\n MintEscalation: \"mint_escalation\",\n /** A hitl deny gate (or the exec allowlist in deny mode) refused the\n * action. The message is the gate's reason; details.gate names the gate. */\n HitlDenied: \"hitl_denied\",\n} as const;\n\nexport type ForbiddenReason = (typeof ForbiddenReason)[keyof typeof ForbiddenReason];\n\n/**\n * ForbiddenError is a 403 forbidden response: the caller is authenticated\n * but not allowed. `reason` is one of ForbiddenReason (empty when the server\n * sent none) and `scope` names the missing scope for missing_scope.\n */\nexport class ForbiddenError extends FuseApiError {\n readonly reason: string;\n readonly scope?: string;\n\n constructor(init: FuseApiErrorInit) {\n super(init);\n this.name = \"ForbiddenError\";\n this.reason = init.details?.reason ?? \"\";\n this.scope = init.details?.scope;\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * LockedError is a 423 locked response: a human holds the environment (a\n * takeover) or an ask-mode stall is pending, so agent exec and computer calls\n * are refused. exec and computer wait it out by default; this surfaces only\n * when waiting is off. Wait on `interventionId` with interventions.wait.\n */\nexport class LockedError extends FuseApiError {\n readonly interventionId: string;\n /** \"takeover\" or \"stall\". */\n readonly kind: string;\n\n constructor(init: FuseApiErrorInit) {\n super(init);\n this.name = \"LockedError\";\n this.interventionId = init.details?.intervention_id ?? \"\";\n this.kind = init.details?.kind ?? \"\";\n Object.setPrototypeOf(this, LockedError.prototype);\n }\n}\n\n/** isLocked reports whether err is a 423 locked api error. */\nexport function isLocked(err: unknown): err is LockedError {\n return err instanceof LockedError;\n}\n\n/** FuseError is a transport, configuration, or decoding failure (not an API error). */\nexport class FuseError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"FuseError\";\n Object.setPrototypeOf(this, FuseError.prototype);\n }\n}\n\n/**\n * PendingInterventionError is thrown instead of waiting when a hitl gate held\n * the call and waiting is off (exec's `wait: false` or the client's\n * `hitlNoWait`). Wait on `intervention.id` with interventions.wait; the\n * outcome is on its result.\n */\nexport class PendingInterventionError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `held by hitl gate ${intervention.gate ?? \"\"}: waiting on intervention ${intervention.id}`,\n );\n this.name = \"PendingInterventionError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, PendingInterventionError.prototype);\n }\n}\n\n/**\n * InterventionRejectedError is a held call a human rejected, or that expired\n * or was cancelled without approval. `intervention.decision.reason` is for\n * the agent to read and replan on.\n */\nexport class InterventionRejectedError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `intervention ${intervention.id} ${intervention.state}: ${intervention.decision?.reason ?? \"\"}`,\n );\n this.name = \"InterventionRejectedError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, InterventionRejectedError.prototype);\n }\n}\n\n/** HeldActionError is an approved held action fuse could not perform. */\nexport class HeldActionError extends Error {\n readonly intervention: Intervention;\n\n constructor(intervention: Intervention) {\n super(\n `approved action of intervention ${intervention.id} failed: ${intervention.result?.error ?? \"\"}`,\n );\n this.name = \"HeldActionError\";\n this.intervention = intervention;\n Object.setPrototypeOf(this, HeldActionError.prototype);\n }\n}\n\n/** isFuseApiError is a type guard for FuseApiError. */\nexport function isFuseApiError(err: unknown): err is FuseApiError {\n return err instanceof FuseApiError;\n}\n\nfunction hasCode(err: unknown, code: string): boolean {\n return isFuseApiError(err) && err.code === code;\n}\n\n/** isNotFound reports whether err is a not_found api error. */\nexport function isNotFound(err: unknown): boolean {\n return hasCode(err, ErrorCode.NotFound);\n}\n\n/** isConflict reports whether err is a conflict api error. */\nexport function isConflict(err: unknown): boolean {\n return hasCode(err, ErrorCode.Conflict);\n}\n\n/** isUnauthorized reports whether err is an unauthorized api error. */\nexport function isUnauthorized(err: unknown): boolean {\n return hasCode(err, ErrorCode.Unauthorized);\n}\n\n/** isForbidden reports whether err is a forbidden api error. */\nexport function isForbidden(err: unknown): err is ForbiddenError {\n return err instanceof ForbiddenError;\n}\n\n/** isHitlDenied reports whether err is an action a hitl gate denied. */\nexport function isHitlDenied(err: unknown): err is ForbiddenError {\n return isForbidden(err) && err.reason === ForbiddenReason.HitlDenied;\n}\n\n/** isInvalidArgument reports whether err is an invalid_argument api error. */\nexport function isInvalidArgument(err: unknown): boolean {\n return hasCode(err, ErrorCode.InvalidArgument);\n}\n\n/** isUnavailable reports whether err is an unavailable api error. */\nexport function isUnavailable(err: unknown): boolean {\n return hasCode(err, ErrorCode.Unavailable);\n}\n\ninterface ErrorEnvelope {\n error?: {\n code?: string;\n message?: string;\n details?: Record<string, string>;\n };\n}\n\nfunction parseApiError(\n status: number,\n requestId: string | undefined,\n body: string,\n): FuseApiError {\n if (body) {\n try {\n const env = JSON.parse(body) as ErrorEnvelope;\n const e = env?.error;\n if (e && (e.code || e.message)) {\n const init = {\n status,\n code: e.code,\n message: e.message,\n details: e.details,\n requestId,\n body,\n };\n if (e.code === ErrorCode.Forbidden) return new ForbiddenError(init);\n if (e.code === ErrorCode.Locked) return new LockedError(init);\n return new FuseApiError(init);\n }\n } catch {\n // fall through to the status-text error below\n }\n }\n return new FuseApiError({ status, message: statusText(status), requestId, body });\n}\n\n/**\n * errorFromResponse builds a FuseApiError from a non-2xx Response, parsing the\n * `{\"error\":{code,message,details}}` envelope and reading the X-Request-ID\n * response header for correlation.\n */\nexport async function errorFromResponse(res: Response): Promise<FuseApiError> {\n const requestId = res.headers.get(REQUEST_ID_HEADER) ?? undefined;\n let body = \"\";\n try {\n body = await res.text();\n } catch (err) {\n return new FuseApiError({\n status: res.status,\n message: `read error body: ${String(err)}`,\n requestId,\n });\n }\n return parseApiError(res.status, requestId, body);\n}\n","// The transport layer: builds requests (URL, headers, auth, X-Request-ID,\n// JSON body), applies an optional client-default timeout, executes fetch, and\n// turns non-2xx responses into FuseApiError. Mirrors the transport in\n// sdks/go/environments.go. SSE streams use stream() which deliberately applies\n// no timeout (the Go SDK uses a separate Timeout:0 client for events).\n\nimport { FuseError, errorFromResponse } from \"./errors.js\";\nimport type { ActorLabel, Intervention } from \"./types.js\";\n\nconst REQUEST_ID_HEADER = \"X-Request-ID\";\nconst ACTOR_HEADER = \"Fuse-Actor\";\nconst ACTOR_NAME_HEADER = \"Fuse-Actor-Name\";\n\n/** A minimal fetch signature, satisfied by the global fetch and most polyfills. */\nexport type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/** Per-call options accepted by every service method. */\nexport interface CallOptions {\n /** Abort the request (and, for events, the stream). */\n signal?: AbortSignal;\n}\n\nexport interface TransportConfig {\n baseUrl: string;\n token?: string;\n fetch?: FetchLike;\n userAgent?: string;\n requestId?: () => string;\n timeoutMs?: number;\n headers?: Record<string, string>;\n actor?: ActorLabel;\n hitlNoWait?: boolean;\n onHeld?: (held: Intervention) => void;\n}\n\n/** Gated is the answer to a call a hitl gate may hold: the action's own\n * response body, or the held intervention of a 202. */\nexport type Gated<T> = { held: Intervention } | { held?: undefined; value: T };\n\ntype Query = Record<string, string | undefined>;\n\ninterface RequestSpec {\n query?: Query;\n body?: unknown;\n signal?: AbortSignal;\n}\n\n/** Combine zero or more AbortSignals into one, without relying on AbortSignal.any (Node 20+). */\nfunction combineSignals(signals: Array<AbortSignal | undefined>): {\n signal?: AbortSignal;\n cleanup: () => void;\n} {\n const active = signals.filter((s): s is AbortSignal => s != null);\n if (active.length === 0) return { cleanup: () => {} };\n if (active.length === 1) return { signal: active[0], cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbort = (event: Event) => {\n const target = event.target as AbortSignal;\n controller.abort(target.reason);\n cleanup();\n };\n const cleanup = () => {\n for (const s of active) s.removeEventListener(\"abort\", onAbort);\n };\n for (const s of active) {\n if (s.aborted) {\n controller.abort(s.reason);\n cleanup();\n return { signal: controller.signal, cleanup: () => {} };\n }\n s.addEventListener(\"abort\", onAbort);\n }\n return { signal: controller.signal, cleanup };\n}\n\nexport class Transport {\n private readonly baseUrl: URL;\n private readonly token?: string;\n private readonly fetchImpl: FetchLike;\n private readonly userAgent?: string;\n private readonly requestId?: () => string;\n private readonly timeoutMs?: number;\n private readonly defaultHeaders?: Record<string, string>;\n private readonly actor?: ActorLabel;\n /** The client's hitl wait options. */\n readonly hitlNoWait: boolean;\n readonly onHeld?: (held: Intervention) => void;\n\n constructor(cfg: TransportConfig) {\n if (!cfg.baseUrl) {\n throw new FuseError(\"base url is required\");\n }\n let parsed: URL;\n try {\n parsed = new URL(cfg.baseUrl);\n } catch {\n throw new FuseError(\"base url is invalid\");\n }\n this.baseUrl = parsed;\n this.token = cfg.token;\n this.userAgent = cfg.userAgent;\n this.requestId = cfg.requestId;\n this.timeoutMs = cfg.timeoutMs;\n this.defaultHeaders = cfg.headers;\n this.actor = cfg.actor;\n this.hitlNoWait = cfg.hitlNoWait ?? false;\n this.onHeld = cfg.onHeld;\n\n const provided = cfg.fetch;\n if (provided) {\n this.fetchImpl = provided;\n } else if (typeof globalThis.fetch === \"function\") {\n this.fetchImpl = globalThis.fetch.bind(globalThis) as FetchLike;\n } else {\n throw new FuseError(\n \"global fetch is not available; pass a fetch implementation via the `fetch` option (Node 18+ required)\",\n );\n }\n }\n\n /** Perform a request and decode a JSON response body. */\n async json<T>(method: string, path: string, spec: RequestSpec = {}): Promise<T> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n return await this.decodeJson<T>(res);\n } finally {\n cleanup();\n }\n }\n\n /**\n * Perform a call a hitl gate may hold. A 202 answers with the held\n * intervention; anything else 2xx with the action's own (possibly empty)\n * body.\n */\n async gated<T>(\n method: string,\n path: string,\n spec: RequestSpec = {},\n ): Promise<Gated<T>> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n if (res.status === 202) return { held: await this.decodeHeld(res) };\n return { value: await this.decodeJson<T>(res) };\n } finally {\n cleanup();\n }\n }\n\n /** Like noContent for a call a hitl gate may hold: it resolves to the held\n * intervention of a 202, or undefined when the action itself answered. */\n async gatedNoContent(\n method: string,\n path: string,\n spec: RequestSpec = {},\n ): Promise<Intervention | undefined> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n if (res.status === 202) return await this.decodeHeld(res);\n await res.body?.cancel().catch(() => {});\n return undefined;\n } finally {\n cleanup();\n }\n }\n\n /** Perform a request and return the response body as text. */\n async text(method: string, path: string, spec: RequestSpec = {}): Promise<string> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n return await res.text();\n } finally {\n cleanup();\n }\n }\n private async decodeHeld(res: Response): Promise<Intervention> {\n const body = await this.decodeJson<{ intervention?: Intervention }>(res);\n if (!body?.intervention?.id) throw new FuseError(\"decode held response\");\n return body.intervention;\n }\n\n /** Perform a request that returns no body (e.g. 204 actions). */\n async noContent(method: string, path: string, spec: RequestSpec = {}): Promise<void> {\n const { signal: combined, cleanup } = this.withTimeout(spec.signal);\n try {\n const res = await this.execute(method, path, spec, combined);\n if (!res.ok) throw await errorFromResponse(res);\n // Release the connection even if the server sent a body.\n await res.body?.cancel().catch(() => {});\n } finally {\n cleanup();\n }\n }\n\n /**\n * Open a long-lived stream (SSE). Applies NO timeout — only the caller's\n * signal cancels it — and checks the status eagerly so connect-time errors\n * (404/401/...) surface as a FuseApiError before any iteration.\n */\n async stream(\n path: string,\n query: Query | undefined,\n signal?: AbortSignal,\n ): Promise<Response> {\n const res = await this.execute(\n \"GET\",\n path,\n { query, signal },\n signal,\n \"text/event-stream\",\n );\n if (!res.ok) throw await errorFromResponse(res);\n return res;\n }\n\n private async execute(\n method: string,\n path: string,\n spec: RequestSpec,\n signal: AbortSignal | undefined,\n accept?: string,\n ): Promise<Response> {\n const url = this.buildUrl(path, spec.query);\n const hasBody = spec.body !== undefined && spec.body !== null;\n const headers = this.buildHeaders(hasBody, accept);\n const init: RequestInit = { method, headers };\n if (hasBody) init.body = JSON.stringify(spec.body);\n if (signal) init.signal = signal;\n\n try {\n return await this.fetchImpl(url, init);\n } catch (err) {\n // A caller- or timeout-initiated abort propagates as-is; everything else\n // is wrapped so consumers get a consistent FuseError with a cause.\n if (signal?.aborted) throw err;\n throw new FuseError(`request failed: ${method} ${url}`, { cause: err });\n }\n }\n\n private buildUrl(path: string, query?: Query): string {\n const p = path.startsWith(\"/\") ? path : \"/\" + path;\n const u = new URL(p, this.baseUrl);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== \"\") u.searchParams.set(key, value);\n }\n }\n return u.toString();\n }\n\n private buildHeaders(hasBody: boolean, accept?: string): Record<string, string> {\n const headers: Record<string, string> = { ...(this.defaultHeaders ?? {}) };\n if (hasBody) headers[\"Content-Type\"] = \"application/json\";\n if (this.token) headers[\"Authorization\"] = `Bearer ${this.token}`;\n if (this.userAgent) headers[\"User-Agent\"] = this.userAgent;\n if (this.requestId) {\n const id = this.requestId();\n if (id) headers[REQUEST_ID_HEADER] = id;\n }\n if (accept) headers[\"Accept\"] = accept;\n if (this.actor?.id) {\n headers[ACTOR_HEADER] = this.actor.id;\n if (this.actor.name) headers[ACTOR_NAME_HEADER] = this.actor.name;\n }\n return headers;\n }\n\n private async decodeJson<T>(res: Response): Promise<T> {\n const text = await res.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new FuseError(\"decode response body\", { cause: err });\n }\n }\n\n private withTimeout(callerSignal?: AbortSignal): {\n signal?: AbortSignal;\n cleanup: () => void;\n } {\n const signals: Array<AbortSignal | undefined> = [callerSignal];\n if (this.timeoutMs && this.timeoutMs > 0) {\n signals.push(AbortSignal.timeout(this.timeoutMs));\n }\n return combineSignals(signals);\n }\n}\n","// Wire types for the Fuse API. Field names match the JSON sent on the wire\n// (snake_case), so request/response bodies pass through JSON.stringify /\n// JSON.parse untouched — a faithful 1:1 mirror of the Go SDK's struct tags\n// (see sdks/go/types.go). List *options* (see each service) use camelCase\n// keys and are translated to snake_case query params by the service.\n\n/** Spec is the hardware/runtime spec for a microVM. */\nexport interface Spec {\n cpus?: number;\n ram_mb?: number;\n storage_gb?: number;\n gpus?: number;\n gpu_kind?: string;\n /** Requests fractional GPU allocation: a MIG profile in mig-parted\n * vocabulary (e.g. \"1g.10gb\"). When set, gpus counts MIG instances of this\n * profile rather than whole devices. */\n gpu_profile?: string;\n region?: string;\n /** Restricts scheduling to hosts of this CPU architecture (\"amd64\",\n * \"arm64\"). Omitted means any host. */\n arch?: string;\n max_runtime_seconds?: number;\n /** Destroys the environment after this many seconds with no exec and no\n * attach session. Omitted or 0 means no idle expiry. Unlike\n * max_runtime_seconds (a ceiling measured from create), this is measured\n * from the last exec or attach. */\n idle_timeout_seconds?: number;\n image?: string;\n /** Pins the environment to an exact host id (the Fusefile's\n * placement.host). The pinned host still has to be active, run the right\n * backend, and fit the request. */\n host_id?: string;\n /** Placement label selectors (the Fusefile's placement.labels): every pair\n * must match the target host's declared labels. */\n labels?: Record<string, string>;\n /** Back guest memory with 2M pages. The host must have them reserved; only\n * an environment created with this can be migrated lazily. */\n huge_pages?: boolean;\n}\n\n/** ExposeSpec requests that a guest port be published at boot. */\nexport interface ExposeSpec {\n port: number;\n as?: string;\n /** Transport to publish on: \"tcp\" (the default) or \"udp\". Typed as a plain\n * string rather than a union so a server that grows a third transport does\n * not turn into a compile error here. The host agent installs a separate\n * forwarding rule per transport, so a service speaking both needs two\n * entries. */\n protocol?: string;\n}\n\n/** Endpoint is a published port with its externally reachable URL. */\nexport interface Endpoint {\n as?: string;\n url: string;\n /** The transport this endpoint was actually published on, which is not\n * always what was asked for: an agent too old to know about the field\n * publishes tcp and answers with this omitted. */\n protocol?: string;\n port: number;\n}\n\n/** HealthcheckHttp is an HTTP GET against a port inside the guest. The probe\n * runs in-guest, so the port needs no matching ExposeSpec. */\nexport interface HealthcheckHttp {\n port: number;\n /** Request path, which must start with a slash. Defaults to \"/\". */\n path?: string;\n}\n\n/**\n * HealthcheckSpec is the environment-level readiness probe (the Fusefile's\n * `healthcheck:` block). Exactly one of http and exec must be set; the server\n * rejects a request that sets both or neither.\n *\n * It is not the per-service compose healthcheck that can appear inside a\n * manifest: that one governs a single container and never reaches the control\n * plane. This one is evaluated by the guest agent over the environment as a\n * whole and its verdict comes back on EnvironmentInfo.health.\n *\n * Every duration is in seconds, and 0 means \"omitted, use the guest agent's\n * default\". The server substitutes no defaults of its own, because the probe\n * executes in the guest.\n */\nexport interface HealthcheckSpec {\n http?: HealthcheckHttp;\n /** An argv run inside the guest. Exit status 0 passes. */\n exec?: string[];\n /** Seconds between attempts. 0 for the guest agent default (10s). */\n interval_seconds?: number;\n /** Bound on one attempt, in seconds. 0 for the guest agent default (2s).\n * Attempts run one at a time, so a value above interval_seconds is\n * rejected rather than silently stretching the interval. */\n timeout_seconds?: number;\n /** Consecutive failures that flip the verdict to failing. 0 for the guest\n * agent default (3). */\n retries?: number;\n /** Grace window from the first attempt during which failures are not\n * counted. It ends for good once the probe passes once. */\n start_period_seconds?: number;\n}\n\n/**\n * DesktopSpec is the geometry of the environment's graphical session (the\n * Fusefile's `desktop:` block). It requires an image that carries the desktop\n * stack; on any other image the declaration is inert and the computer surface\n * reports the display as absent.\n *\n * width and height are required, 320 to 3840 each: a guessed dimension would\n * silently shift every coordinate a computer-use model emits.\n */\nexport interface DesktopSpec {\n /** Display width in pixels. */\n width: number;\n /** Display height in pixels. */\n height: number;\n /** Window manager to run: \"mutter\", \"xfwm4\" or \"openbox\". Omit to keep the\n * image's baked default. A string rather than a union so a server that\n * grows a window manager does not turn into a compile error here. */\n wm?: string;\n}\n\n/**\n * ComputerAction is one computer-use action, in the same shape Anthropic's\n * computer tool emits as tool_use input, so translating a tool_use block into\n * a call is mechanical. Only action is required; which other fields apply\n * depends on the action, and the guest agent enforces the full schema.\n */\nexport interface ComputerAction {\n /** The action to perform, e.g. \"screenshot\", \"left_click\", \"type\", \"key\",\n * \"scroll\", \"zoom\". */\n action: string;\n /** [x, y] target for pointer actions. */\n coordinate?: number[];\n /** [x, y] origin for left_click_drag. */\n start_coordinate?: number[];\n /** The payload for type, the keysym combo for key/hold_key, or modifiers\n * held during a click action. */\n text?: string;\n /** [x1, y1, x2, y2] crop for zoom. */\n region?: number[];\n /** Seconds for hold_key and wait, capped guest-side at 100. */\n duration?: number;\n scroll_direction?: \"up\" | \"down\" | \"left\" | \"right\";\n /** Wheel clicks for scroll, 1 to 100. */\n scroll_amount?: number;\n}\n\n/**\n * ComputerResult is the guest's answer to one action. screenshot is a base64\n * PNG, present on every action that implies one; for zoom it is the cropped\n * region at full resolution.\n */\nexport interface ComputerResult {\n output?: string;\n screenshot?: string;\n}\n\n/**\n * ComputerDisplay reports the environment's display: whether it is up and at\n * what geometry, so a caller can populate display_width_px /\n * display_height_px in its computer tool definition without hardcoding them.\n */\nexport interface ComputerDisplay {\n display?: string;\n up: boolean;\n /** Live display width in pixels, 0 when the display is down. */\n width: number;\n /** Live display height in pixels, 0 when the display is down. */\n height: number;\n /** The window manager actually running, which can differ from\n * DesktopSpec.wm when the image does not carry the one asked for. */\n wm?: string;\n /** Why the display is down, when it is. */\n error?: string;\n}\n\n/** ToolResultImageSource is a Messages-API base64 image source. */\nexport interface ToolResultImageSource {\n type: \"base64\";\n media_type: \"image/png\";\n data: string;\n}\n\n/**\n * ToolResultBlock is one content block of a Messages API tool_result. The\n * field names match the Messages API, so the blocks can be sent back verbatim\n * as the tool_result content.\n */\nexport interface ToolResultBlock {\n type: \"text\" | \"image\";\n text?: string;\n source?: ToolResultImageSource;\n}\n\n/**\n * ComputerToolResult is what goes back to Claude for one computer tool_use:\n * the content blocks and whether they describe an error. Map it onto the\n * tool_result block for the tool_use's id and the loop is closed.\n */\nexport interface ComputerToolResult {\n content: ToolResultBlock[];\n is_error?: boolean;\n}\n\n/**\n * Health is the last verdict of an environment's healthcheck.\n *\n * It is deliberately not folded into EnvironmentInfo.state: that vocabulary is\n * a closed set clients reason about, and an unhealthy environment is still a\n * running one. Nothing tears an environment down for a failing probe.\n */\nexport interface Health {\n /** \"starting\", \"passing\" or \"failing\". */\n state: string;\n /** When the probe entered this state. */\n since?: string;\n /** Consecutive failed attempts. Zero while passing. */\n failures?: number;\n /** The last attempt's failure detail. Empty while passing. */\n message?: string;\n}\n\n/**\n * EgressSpec routes the environment's outbound traffic. Omit it (or omit\n * mode) for direct egress, which is what every request written before this\n * field existed meant. Every field is a plain string rather than a union so a\n * server that grows a new mode or provider does not turn into a compile error\n * here.\n */\nexport interface EgressSpec {\n /** \"direct\" (the default) or \"proxy\". */\n mode?: string;\n /** Proxy backend, required when mode is \"proxy\" (\"cloudflare-warp\",\n * \"wireguard\", or \"mock\" for local development). */\n provider?: string;\n /** \"socks5\" (the default for proxy) or \"http\". */\n protocol?: string;\n /** Name of an entry in the request's secrets holding the provider's\n * credential, for a provider that takes one: \"wireguard\" reads a base64\n * wg-quick config. The value goes to the host's egress backend only and is\n * left out of the secrets the guest receives. */\n secret?: string;\n}\n\n/**\n * EgressStatus is how the environment's outbound traffic is actually routed.\n * mode is always set; provider, protocol and endpoint are present only for\n * proxy egress. endpoint is a host-local address, never a credential.\n */\nexport interface EgressStatus {\n mode: string;\n provider?: string;\n protocol?: string;\n endpoint?: string;\n /** the endpoint's last probe verdict; proxy only. */\n health?: EgressHealth;\n}\n\n/**\n * EgressHealth is the proxy endpoint's last probe verdict. state is\n * \"unknown\" until the first probe, then \"healthy\" or \"unhealthy\"; typed as a\n * plain string so a server that grows a state does not turn into a compile\n * error here. reason is the backend-level failure, empty while healthy.\n */\nexport interface EgressHealth {\n state: string;\n reason?: string;\n checked_at?: string;\n}\n\n/** CreateRequest is the body for environments.create. */\nexport interface CreateRequest {\n task_id: string;\n spec?: Spec;\n manifest_inline?: string;\n secrets?: Record<string, string>;\n startup_script?: string;\n /**\n * Guest files written before the startup script runs, keyed by absolute\n * guest path with base64-encoded content. What a Fusefile's `copy` block\n * compiles to. Paths under /fuse are rejected, the total decoded size is\n * capped at 512 KiB, and permissions are not carried.\n */\n files?: Record<string, string>;\n gateway_url?: string;\n gateway_token?: string;\n expose?: ExposeSpec[];\n /** Environment-level readiness probe. Omit it for an environment with no\n * probe, in which case EnvironmentInfo.health is never populated. It is not\n * evaluated inside create: the call returns as soon as the VM is up, and\n * the verdict arrives on later reads. */\n healthcheck?: HealthcheckSpec;\n /** Routes the environment's outbound traffic. Omit it for direct egress. */\n egress?: EgressSpec;\n /** Graphical session geometry. Omit it for an environment with no desktop,\n * in which case a desktop image keeps its baked default geometry. */\n desktop?: DesktopSpec;\n /** Human-in-the-loop policy. Omit it for an environment that cannot raise\n * interventions. */\n hitl?: HitlSpec;\n}\n\n/** EnvironmentInfo is the server's view of a single microVM. */\nexport interface EnvironmentInfo {\n id: string;\n state: string;\n task_id: string;\n host_id?: string;\n url: string;\n spec: Spec;\n created_at: string;\n updated_at: string;\n error?: string;\n endpoints?: Endpoint[];\n /** Last verdict of the environment-level healthcheck. Absent when the\n * environment declared no healthcheck, and absent until the first verdict\n * has been read back from the guest. The server refreshes it on its\n * reconcile tick (30s by default), so it lags the guest by up to a tick. */\n health?: Health;\n /** How outbound traffic is actually routed. Absent only from a server that\n * predates the field; treat that as direct. */\n egress?: EgressStatus;\n}\n\n/** ForkOptions is the optional body for environments.fork. */\nexport interface ForkOptions {\n reuse_snapshot_id?: string;\n comment?: string;\n}\n\n/** MigrateOptions is the optional body for environments.migrate. */\nexport interface MigrateOptions {\n /**\n * Host to migrate to. Empty means the orchestrator picks a host other than\n * the source, preferring the environment's checkpoint standby; if no other\n * host can take it the call fails with 503 and the source keeps running.\n */\n target_host_id?: string;\n /**\n * Resume the guest from its memory on the target, so processes survive the\n * move, instead of cold-booting it. It never falls back to a cold\n * migration: a target that cannot resume the guest answers\n * 409 and the source keeps running.\n */\n live?: boolean;\n /**\n * Resume the guest before its memory has arrived and page it in from the\n * source afterwards. Requires live and an environment created with\n * huge_pages; until the vm.memory_resident event the guest still depends on\n * the source host.\n */\n lazy?: boolean;\n}\n\n/** ExecRequest is the body for environments.exec. Exactly one of cmd or shell must be set. */\nexport interface ExecRequest {\n /**\n * The argv to run in the guest, e.g. [\"ls\", \"-l\"]. Argv needs no quoting\n * rules and cannot be turned into an injection by interpolating a value, so\n * prefer it.\n */\n cmd?: string[];\n\n /**\n * Runs the string under `sh -lc`. Use it only for what argv cannot express:\n * pipelines, redirects, and globs.\n */\n shell?: string;\n\n /**\n * Bounds the command inside the guest. Zero or unset takes the server\n * default; the server clamps anything above its ceiling.\n */\n timeout_ms?: number;\n\n /**\n * Wait for a human when a hitl gate holds the exec (202), or when a\n * human holds the environment (423, a takeover or a pending stall), then\n * run (the default). false throws a PendingInterventionError or a\n * LockedError at once instead. Not sent on the wire.\n */\n wait?: boolean;\n\n /**\n * Called with the pending intervention when a gate holds the exec, before\n * waiting on it. It overrides the client's onHeld. Not sent on the wire.\n */\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * ExecResult is the outcome of a guest command.\n *\n * A non-zero exit_code is a successful call: the command ran and failed. Only a\n * thrown error means the command could not be run at all.\n */\nexport interface ExecResult {\n exit_code: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Event is one item from environments.events. It matches the server's SSE\n * wire payload. Stream-level failures are thrown from the async iterator\n * rather than delivered as an in-band event.\n */\nexport interface Event {\n id: string;\n /** Event kind: \"state\" (an omitted kind means \"state\") or \"step\". */\n event: string;\n vm_id: string;\n state: string;\n url?: string;\n error?: string;\n updated_at: string;\n /** index of the setup step, 1-based. step events only. */\n index?: number;\n /** total number of setup steps. step events only. */\n total?: number;\n /** layer cache key for the step. step events only. */\n key?: string;\n /** whether the step was served from the layer cache. step events only. */\n cached?: boolean;\n /** why the step missed the cache. step events only. */\n miss_reason?: string;\n /** what changed, e.g. the input paths. step events only. */\n miss_detail?: string[];\n /** wall-clock duration of the step in milliseconds. step events only. */\n duration_ms?: number;\n /** exit code of the step. step events only. */\n exit_code?: number;\n}\n\n/** SnapshotRequest is the optional body for snapshots.create. */\nexport interface SnapshotRequest {\n comment?: string;\n mode?: string;\n retention_seconds?: number;\n metadata?: Record<string, string>;\n export_ref?: string;\n export_status?: string;\n /** Labels this snapshot as the artifact of one cacheable setup step, which is\n * what makes it findable by recipe rather than by its random id. Empty for an\n * ordinary snapshot. The scope it is filed under comes from how the caller\n * authenticated and is not settable here. */\n layer_key?: string;\n /** Capture the guest's memory and vCPU state alongside the rootfs, so\n * restoring resumes the guest instead of cold-booting it. Omitted or false\n * takes a disk-only snapshot, which is the default and the fallback.\n *\n * It costs the environment's full configured memory in bytes on every\n * create, pauses the guest for the length of the capture, and produces an\n * artifact pinned to the host that took it. It also cannot seed a new\n * environment: `fork` and `CreateRequest.seed_snapshot_id` read only a\n * snapshot's rootfs, and a live snapshot's rootfs is captured without\n * quiescing the guest filesystem, so it is consistent only alongside the\n * memory image. Both reject a live snapshot with a 409 conflict.\n *\n * Against a backend with no live-snapshot support this is a 501\n * `unimplemented`, not a conflict.\n *\n * It is a request, not a guarantee: read `Snapshot.kind` to find out what\n * was actually written. */\n live?: boolean;\n}\n\n/** ResolveSnapshotResponse is the wire envelope for a layer lookup. Internal:\n * resolve() returns Snapshot | null so the found flag never reaches callers. */\nexport interface ResolveSnapshotResponse {\n found: boolean;\n snapshot?: Snapshot;\n}\n\n/** SnapshotExport is an optional exported snapshot artifact. */\nexport interface SnapshotExport {\n destination: string;\n status?: string;\n requested_at?: string;\n updated_at?: string;\n last_error?: string;\n}\n\n/** Snapshot is a persisted snapshot record. */\nexport interface Snapshot {\n id: string;\n vm_id: string;\n task_id?: string;\n tenant_id?: string;\n parent_snapshot_id?: string;\n mode?: string;\n state?: string;\n comment?: string;\n /** The content-addressed cache key of the setup step this artifact was\n * taken after. Absent on anything that is not a build layer, and an empty\n * key never matches a lookup. */\n layer_key?: string;\n /** CPU architecture, in GOARCH vocabulary (\"amd64\", \"arm64\"), of the host\n * that actually built the artifact rather than of whoever asked for it. A\n * rootfs is not portable across architectures, so this is a real constraint\n * on whether the artifact can be booted; it is deliberately not folded into\n * layer_key, so a lookup has to filter on it separately. */\n arch?: string;\n /** Hex sha256 of the artifact rootfs. It verifies that a given copy of\n * those bytes is intact, and nothing more: it is not a cross-build\n * identity, because two builds of the same recipe produce different rootfs\n * bytes (timestamps, inode ordering, package caches). It can never be used\n * as a cache key. The live snapshot a migrate takes in its final pause on\n * an xfs or btrfs host is the exception: its digest is a sha256 of its\n * per-block hash table, not of the rootfs file. */\n digest?: string;\n /** Whether this artifact is the rootfs alone (`\"disk\"`), or the rootfs plus\n * the guest's memory and vCPU state (`\"live\"`). Restoring a disk snapshot\n * cold-boots the guest; restoring a live one resumes it.\n *\n * It is what the host agent reports it actually wrote, not what was\n * requested. A host running an agent too old to know about live snapshots\n * answers `live: true` with a disk snapshot, and this then says `\"disk\"`.\n * Branch on it rather than on your own request.\n *\n * Typed loosely rather than as a `\"disk\" | \"live\"` union so a server that\n * grows a third kind does not turn into a compile error here. A server that\n * predates live snapshots omits it entirely; treat undefined as `\"disk\"`. */\n kind?: string;\n size_bytes?: number;\n created_at: string;\n updated_at?: string;\n retention_until?: string;\n last_error?: string;\n export_ref?: string;\n exports?: SnapshotExport[];\n}\n\n/** HostCapacity is a host's resource envelope. */\nexport interface HostCapacity {\n cpus: number;\n ram_mb: number;\n storage_gb: number;\n vm_count: number;\n /** The host's CPU architecture in GOARCH vocabulary (\"amd64\", \"arm64\").\n * Omitted means amd64 (hosts registered before arch existed). */\n arch?: string;\n gpus?: number;\n gpu_kind?: string;\n /** The firecracker release the host agent reports it runs (\"v1.17.0\").\n * Probed at registration (a declared value is ignored) and only set on\n * capacity. Live migration needs both hosts on the same release. Omitted\n * on qemu hosts and older agents. */\n firecracker?: string;\n /** The firecracker release the host's fc-agent.py pins. Differs from\n * firecracker when the host has not run fc-update since the pin moved. */\n firecracker_pinned?: string;\n /** Fractional GPU capacity: MIG instance count by profile name (e.g.\n * {\"1g.10gb\": 4}). Like gpus, it requires backend \"qemu\". When the host\n * reports per-instance MIG inventory (mig_instances), this map is a derived\n * summary; otherwise it is the scheduling unit. */\n mig_profiles?: Record<string, number>;\n /** Per-instance MIG inventory probed from the host agent (one entry per\n * carved MIG GPU instance). When non-empty, the orchestrator binds specific\n * instance uuids to VMs instead of decrementing a count. Strictly additive:\n * a host that reports no instances falls back to mig_profiles. Only\n * populated on capacity (not allocated) for qemu hosts. */\n mig_instances?: MIGInstance[];\n /** The set of MIG instance uuids currently bound to VMs. Populated only on\n * allocated, and only for hosts that report per-instance MIG inventory. */\n mig_instance_uuids?: string[];\n /** Per-device GPU detail probed from the host agent, carried alongside the\n * scalar gpus/gpu_kind counters. Only populated on capacity (not\n * allocated) for qemu hosts. */\n gpu_devices?: GPUDevice[];\n}\n\n/** GPUDevice is the per-device detail probed for a single GPU. Every field is\n * best-effort and omitted when the host agent could not determine it. */\nexport interface GPUDevice {\n uuid?: string;\n model?: string;\n pci_bus_id?: string;\n memory_mb?: number;\n driver_version?: string;\n cuda_version?: string;\n compute_cap?: string;\n mig_capable?: boolean;\n mig_mode?: string;\n iommu_group?: string;\n}\n\n/** MIGInstance is one carved MIG GPU instance probed from the host agent. The\n * orchestrator binds a specific instance uuid to a VM so it knows which\n * instance went to which VM. */\nexport interface MIGInstance {\n uuid?: string;\n profile?: string;\n kind?: string;\n parent_gpu_uuid?: string;\n}\n\n/** RegisterHostRequest is the body for hosts.register. */\nexport interface RegisterHostRequest {\n id: string;\n url: string;\n token?: string;\n region?: string;\n backend?: string;\n /** Operator-declared key/value pairs matched against a spec's placement\n * label selectors. Never probed from the host agent. */\n labels?: Record<string, string>;\n capacity?: HostCapacity;\n}\n\n/** Host is the server's view of a registered host. */\nexport interface Host {\n id: string;\n url: string;\n region?: string;\n state: string;\n backend?: string;\n labels?: Record<string, string>;\n capacity: HostCapacity;\n allocated: HostCapacity;\n last_seen: string;\n created_at: string;\n updated_at: string;\n /** Non-fatal registration notices (e.g. declared capacity exceeding the\n * probed value). Only ever populated on the response to hosts.register. */\n warnings?: string[];\n}\n\n/**\n * APIKey is a key's metadata. The raw secret appears only in\n * CreatedAPIKey.key, returned once at creation.\n */\nexport interface APIKey {\n id: string;\n label?: string;\n created_at: string;\n last_used_at?: string;\n revoked_at?: string;\n /** The hitl scopes the key holds. Absent for a full-access key. */\n scopes?: string[];\n /** The environment a scoped key is limited to (and its forks). */\n env_id?: string;\n /** RFC 3339 timestamp. Scoped keys always expire. */\n expires_at?: string;\n /** The actor the key is pinned to, if any. */\n actor?: ActorLabel;\n created_by?: string;\n}\n\n/** ActorLabel is an actor as a caller names it: an opaque id (at most 128\n * bytes) and an optional display name. */\nexport interface ActorLabel {\n id: string;\n name?: string;\n}\n\n/** Hitl scopes a key can be minted with. */\nexport const HitlScope = {\n Read: \"hitl:read\",\n Decide: \"hitl:decide\",\n Secret: \"hitl:secret\",\n Takeover: \"hitl:takeover\",\n ActAs: \"hitl:act-as\",\n} as const;\n\nexport type HitlScope = (typeof HitlScope)[keyof typeof HitlScope];\n\n/**\n * CreatedAPIKey is returned by apiKeys.create. `key` is the raw secret and is\n * unrecoverable after this response.\n */\nexport interface CreatedAPIKey extends APIKey {\n key: string;\n}\n\n/** Lifecycle states for EnvironmentInfo.state and Event.state. */\nexport const State = {\n Provisioning: \"provisioning\",\n Running: \"running\",\n Draining: \"draining\",\n Destroying: \"destroying\",\n /** A destroy that ran out of retries. The environment may still exist on its host; destroy it again to retry. */\n DestroyFailed: \"destroy_failed\",\n Destroyed: \"destroyed\",\n Failed: \"failed\",\n} as const;\n\nexport type State = (typeof State)[keyof typeof State];\n\n/** isTerminalState reports whether state is a terminal lifecycle state. */\nexport function isTerminalState(state: string): boolean {\n return state === State.Destroyed || state === State.Failed;\n}\n\n/**\n * Verdicts carried in Health.state. Separate from State on purpose: a failing\n * probe reports, it does not move the environment anywhere new.\n */\nexport const HealthState = {\n /** The probe has not passed yet and is still inside its start period, so\n * failures are not being counted. */\n Starting: \"starting\",\n /** The most recent attempt succeeded. */\n Passing: \"passing\",\n /** The probe failed its configured retries in a row after the start period\n * ended. */\n Failing: \"failing\",\n} as const;\n\nexport type HealthState = (typeof HealthState)[keyof typeof HealthState];\n\n/** HitlSpec is the human-in-the-loop policy an environment is created with. */\nexport interface HitlSpec {\n /** Default deadline for every intervention, 10 to 86400. Omitted means 600. */\n timeout_seconds?: number;\n /** \"reject\" (the default) or \"allow\". */\n on_timeout?: string;\n /** The request kinds the agent may raise. */\n requests: HitlRequests;\n /** Refuse decisions made without a pinned or asserted actor. */\n require_actor?: boolean;\n /** Webhooks told about every intervention and audit event. */\n notify?: HitlWebhook[];\n /** Gates hold, record or deny exec, lifecycle and computer actions, and\n * raise stall and expiry signals. */\n gates?: HitlGate[];\n /** Allowlist mode for exec. */\n exec?: HitlExecPolicy;\n}\n\n/** HitlGate is one enforced gate. */\nexport interface HitlGate {\n name: string;\n /** HitlKind.Exec, HitlKind.Lifecycle, HitlKind.Computer, HitlKind.Stall\n * or HitlKind.Expiry. */\n on: string;\n match: HitlGateMatch;\n /** One of GateMode; ask is the default. */\n mode?: string;\n /** The default reach of an approval: \"once\", \"env\" or \"ttl:<duration>\". */\n grant?: string;\n timeout_seconds?: number;\n /** Returned on a deny and shown to the human on an ask. */\n reason?: string;\n /** A webhook asked allow, deny or ask before a human sees an ask gate's\n * action. A failure or timeout means ask. */\n decide?: HitlDecider;\n}\n\n/** HitlDecider is a gate's decider. secret names an entry in the create\n * request's secrets; its value signs each call (Fuse-Signature). */\nexport interface HitlDecider {\n url: string;\n secret: string;\n}\n\n/** HitlGateMatch selects the actions a gate applies to. Every field set must\n * match. */\nexport interface HitlGateMatch {\n /** Matches the basename of argv[0] after env, sudo, nice, timeout, xargs,\n * nohup and stdbuf are stripped. */\n program?: string[];\n /** Matches when these appear in argv in this order. */\n args?: string[];\n /** Matches any opaque shell exec. */\n shell?: boolean;\n /** Matches lifecycle actions (one of LifecycleAction) or, on a computer\n * gate, computer action names (\"type\", \"key\", \"left_click\", ...). */\n action?: string[];\n /** Matches a computer \"type\" whose text contains any entry, ignoring\n * case. */\n text_contains?: string[];\n /** Raises a stall after this many consecutive non-zero exec exits\n * (on: \"stall\"). */\n failures?: number;\n /** Raises a stall after this long with no exec or computer call\n * (on: \"stall\"). */\n quiet_seconds?: number;\n /** Raises an expiry this long before the idle_timeout or max_runtime reap\n * (on: \"expiry\"). */\n before_seconds?: number;\n}\n\n/** HitlExecPolicy is allowlist mode for exec: a program not in allow is held\n * with default (\"ask\" or \"deny\"), interpreters and shells included. */\nexport interface HitlExecPolicy {\n default: string;\n allow: string[];\n}\n\n/** ExecPayload is a held exec. */\nexport interface ExecPayload {\n argv: string[];\n shell?: string;\n timeout_ms?: number;\n}\n\n/** ComputerPayload is a held computer action. input is the body as sent. */\nexport interface ComputerPayload {\n action: string;\n text?: string;\n input: unknown;\n}\n\n/** DeciderNote is what a gate's decider said when it sent an action on to a\n * human: verdict \"ask\" with its reason, or the error fuse fell through on. */\nexport interface DeciderNote {\n /** One of DeciderVerdict. */\n verdict: string;\n reason?: string;\n error?: string;\n}\n\n/** InterventionReview is a review request. content is the file as fuse read\n * it at request time when path is set. */\nexport interface InterventionReview {\n path?: string;\n content: string;\n /** One of ReviewFormat. */\n format: string;\n message?: string;\n truncated?: boolean;\n}\n\n/** LifecyclePayload is a held environment action. */\nexport interface LifecyclePayload {\n /** One of LifecycleAction. */\n action: string;\n}\n\n/** InterventionResult is what running an approved gated action produced. */\nexport interface InterventionResult {\n exec?: ExecResult;\n computer?: ComputerResult;\n env_id?: string;\n snapshot_id?: string;\n error?: string;\n /** RFC 3339 timestamp. */\n finished_at: string;\n}\n\n/** HitlWebhook is one hitl.notify target. `secret` names an entry of the\n * create request's secrets; its value signs each delivery with HMAC-SHA256\n * in the Fuse-Signature header. */\nexport interface HitlWebhook {\n url: string;\n secret: string;\n}\n\n/** HitlRequests declares the allowed request kinds. Present means allowed;\n * set ask (to {}) to allow asks. */\nexport interface HitlRequests {\n ask?: HitlAskRequests;\n secret?: HitlSecretRequests;\n takeover?: HitlTakeoverRequests;\n review?: HitlReviewRequests;\n}\n\n/** HitlReviewRequests configures review requests. Present means allowed. */\nexport type HitlReviewRequests = Record<string, never>;\n\n/** HitlSecretRequests declares where a secret may land. The agent names one\n * of these targets; it can never choose a path or variable of its own. */\nexport interface HitlSecretRequests {\n targets: HitlSecretTarget[];\n}\n\n/** HitlSecretTarget is one declared destination: exactly one of env (a\n * variable later execs see) or file (an absolute guest path, written 0600).\n * label is what the human is shown first. */\nexport interface HitlSecretTarget {\n env?: string;\n file?: string;\n label: string;\n}\n\n/** HitlTakeoverRequests declares the ways a human may take over: \"terminal\"\n * and \"desktop\" (which needs a desktop block). Empty means terminal. */\nexport interface HitlTakeoverRequests {\n via?: string[];\n}\n\n/** HitlAskRequests configures ask requests. Present means allowed. */\nexport type HitlAskRequests = Record<string, never>;\n\n/** Actor is who raised or decided an intervention: \"master\", \"key:<id>\", or\n * \"system\" for fuse itself (expiry, cancel on destroy). */\nexport interface Actor {\n id: string;\n name?: string;\n /** \"key\", \"system\" or \"decider\". */\n source: string;\n key_id?: string;\n}\n\n/** InterventionPayload is what was asked, attempted or noticed: a question\n * for an ask, the held exec or lifecycle action for a gate, a secret or\n * takeover request, or a signal. */\nexport interface InterventionPayload {\n question?: string;\n choices?: string[];\n exec?: ExecPayload;\n lifecycle?: LifecyclePayload;\n /** Set for a secret request only. */\n secret?: InterventionSecret;\n /** Set for a takeover only. */\n takeover?: InterventionTakeover;\n /** What fuse saw, for a stall or expiry. */\n signal?: InterventionSignal;\n /** The held computer action. */\n computer?: ComputerPayload;\n /** What is up for review. */\n review?: InterventionReview;\n /** The gate decider's note on an action it escalated. */\n decider?: DeciderNote;\n}\n\n/** InterventionSecret is a secret request. label comes from the Fusefile and\n * is what a human should read first; message is the agent's own text. The\n * value is never part of any intervention. */\nexport interface InterventionSecret {\n target: string;\n label: string;\n message?: string;\n}\n\n/** InterventionTakeover is a takeover. holder and started_at are set while a\n * human holds the environment, which is also when the agent's exec and\n * computer calls get 423. */\nexport interface InterventionTakeover {\n via: string;\n reason?: string;\n holder?: Actor;\n /** RFC 3339 timestamp. */\n started_at?: string;\n}\n\n/** InterventionSignal is what fuse noticed on its own. A stall carries the\n * failure run or the quiet time; an expiry carries the reaper due and when,\n * and once approved the time the environment is kept until. */\nexport interface InterventionSignal {\n failures?: number;\n last_exit_code?: number;\n quiet_seconds?: number;\n /** \"idle_timeout\" or \"max_runtime\". */\n reaper?: string;\n /** RFC 3339 timestamp. */\n reap_at?: string;\n /** RFC 3339 timestamp. */\n extended_until?: string;\n}\n\n/** InterventionDecision is how an intervention resolved. An expired one\n * carries the on_timeout outcome and a cancelled one a reject. */\nexport interface InterventionDecision {\n /** \"approve\" or \"reject\". */\n outcome: string;\n answer?: string;\n reason?: string;\n decided_by: Actor;\n decided_at: string;\n /** The argv the approver replaced a held exec's with. */\n edited_argv?: string[];\n /** The text the approver replaced a held type's with. */\n edited_text?: string;\n /** How far an approval of a gated action reaches. */\n grant?: string;\n}\n\n/** Intervention is one request for a human. */\nexport interface Intervention {\n id: string;\n env_id: string;\n kind: string;\n /** Names the gate that raised it; absent for a request. */\n gate?: string;\n /** The gate's mode (one of GateMode). notify and deny records are born\n * terminal. */\n mode?: string;\n /** One of InterventionState. */\n state: string;\n payload: InterventionPayload;\n triggered_by: Actor;\n /** RFC 3339 timestamp. */\n deadline: string;\n on_timeout: string;\n /** Set on every terminal intervention. */\n decision?: InterventionDecision;\n /** Set once an approved gated action has been performed. */\n result?: InterventionResult;\n created_at: string;\n updated_at: string;\n}\n\n/** AuditEntry is one row of the hash-chained hitl audit log. It holds who\n * did what and when, never intervention content. Hashes are hex. */\nexport interface AuditEntry {\n seq: number;\n /** One of AuditEvent. */\n event: string;\n intervention_id?: string;\n env_id?: string;\n actor: Actor;\n remote_addr?: string;\n /** Links a takeover_session row to its cast; fetch it with\n * interventions.getRecording. */\n recording_id?: string;\n /** RFC 3339 timestamp. */\n at: string;\n prev_hash: string;\n hash: string;\n}\n\n/** Audit log events. */\nexport const AuditEvent = {\n Raised: \"raised\",\n Decided: \"decided\",\n Expired: \"expired\",\n Cancelled: \"cancelled\",\n InviteMinted: \"invite_minted\",\n InviteUsed: \"invite_used\",\n GrantCreated: \"grant_created\",\n GrantUsed: \"grant_used\",\n SecretAnswered: \"secret_answered\",\n TakeoverStarted: \"takeover_started\",\n TakeoverEnded: \"takeover_ended\",\n TakeoverSession: \"takeover_session\",\n} as const;\n\nexport type AuditEvent = (typeof AuditEvent)[keyof typeof AuditEvent];\n\n/** Intervention kinds: ask is a request, exec and lifecycle are the gate\n * surfaces. */\nexport const HitlKind = {\n Ask: \"ask\",\n Exec: \"exec\",\n Lifecycle: \"lifecycle\",\n Computer: \"computer\",\n Review: \"review\",\n Secret: \"secret\",\n Takeover: \"takeover\",\n Stall: \"stall\",\n Expiry: \"expiry\",\n} as const;\n\nexport type HitlKind = (typeof HitlKind)[keyof typeof HitlKind];\n\n/** Gate modes. */\nexport const GateMode = {\n Ask: \"ask\",\n Notify: \"notify\",\n Deny: \"deny\",\n} as const;\n\nexport type GateMode = (typeof GateMode)[keyof typeof GateMode];\n\n/** Decider verdicts. */\nexport const DeciderVerdict = {\n Allow: \"allow\",\n Deny: \"deny\",\n Ask: \"ask\",\n} as const;\n\nexport type DeciderVerdict = (typeof DeciderVerdict)[keyof typeof DeciderVerdict];\n\n/** The actor source a decider's decision records. */\nexport const ACTOR_SOURCE_DECIDER = \"decider\";\n\n/** Review formats. */\nexport const ReviewFormat = {\n Text: \"text\",\n Diff: \"diff\",\n} as const;\n\nexport type ReviewFormat = (typeof ReviewFormat)[keyof typeof ReviewFormat];\n\n/** Takeover modes: terminal gives the human a shell, desktop the live\n * desktop view (it needs a desktop block). */\nexport const TakeoverVia = {\n Terminal: \"terminal\",\n Desktop: \"desktop\",\n} as const;\n\nexport type TakeoverVia = (typeof TakeoverVia)[keyof typeof TakeoverVia];\n\n/** Lifecycle actions a gate can hold. */\nexport const LifecycleAction = {\n Destroy: \"destroy\",\n Fork: \"fork\",\n Migrate: \"migrate\",\n Drain: \"drain\",\n Snapshot: \"snapshot\",\n RotateToken: \"rotate-token\",\n} as const;\n\nexport type LifecycleAction = (typeof LifecycleAction)[keyof typeof LifecycleAction];\n\n/** The gate name the exec allowlist reports. */\nexport const ALLOWLIST_GATE = \"exec.allowlist\";\n\n/** Intervention states. pending is the only non-terminal one. */\nexport const InterventionState = {\n Pending: \"pending\",\n Approved: \"approved\",\n Rejected: \"rejected\",\n Expired: \"expired\",\n Cancelled: \"cancelled\",\n} as const;\n\nexport type InterventionState =\n (typeof InterventionState)[keyof typeof InterventionState];\n\n/** Intervention outcomes. Every terminal intervention carries one. */\nexport const InterventionOutcome = {\n Approve: \"approve\",\n Reject: \"reject\",\n} as const;\n\nexport type InterventionOutcome =\n (typeof InterventionOutcome)[keyof typeof InterventionOutcome];\n\n/** isInterventionTerminal reports whether the intervention is resolved. */\nexport function isInterventionTerminal(i: Intervention | undefined): boolean {\n return !!i && !!i.state && i.state !== InterventionState.Pending;\n}\n\n/** isInterventionApproved reports whether the intervention resolved as\n * approve, which includes an expiry under on_timeout: allow. */\nexport function isInterventionApproved(i: Intervention | undefined): boolean {\n return i?.decision?.outcome === InterventionOutcome.Approve;\n}\n\n/** isInterventionSettled reports whether a caller has its final answer:\n * resolved, and for an approved gated action that fuse performs, performed\n * (with the outcome on result). */\nexport function isInterventionSettled(i: Intervention | undefined): boolean {\n if (!i || !isInterventionTerminal(i)) return false;\n // a decider's allow lets the caller perform the action itself.\n if (i.decision?.decided_by?.source === ACTOR_SOURCE_DECIDER) return true;\n const runs =\n i.mode === GateMode.Ask &&\n (!!i.payload?.exec || !!i.payload?.lifecycle || !!i.payload?.computer);\n return !runs || !isInterventionApproved(i) || !!i.result;\n}\n","import { FuseError } from \"./errors.js\";\n\n/**\n * requireArg throws a FuseError when a required path argument is missing,\n * mirroring the Go SDK's \"<thing> is required\" guards.\n */\nexport function requireArg(value: string | undefined | null, name: string): string {\n if (!value) {\n throw new FuseError(`${name} is required`);\n }\n return value;\n}\n","// SSE event streaming, porting the state machine in sdks/go/events.go to an\n// async iterator. The stream is opened (and its status checked) eagerly; the\n// returned AsyncIterable yields each Event and ends after a terminal-state\n// event (destroyed/failed) or on clean EOF. Stream-level failures are thrown\n// from the iterator. Caller abort is treated as normal termination.\n\nimport type { Transport } from \"./transport.js\";\nimport { FuseError } from \"./errors.js\";\nimport { type Event, isTerminalState } from \"./types.js\";\n\nconst DATA_PREFIX = \"data:\";\n\n/** Open the SSE stream for an environment and return an async-iterable of events. */\nexport async function streamEvents(\n t: Transport,\n vmId: string,\n signal?: AbortSignal,\n): Promise<AsyncIterable<Event>> {\n const path = `/v1/environments/${encodeURIComponent(vmId)}/events`;\n const res = await t.stream(path, undefined, signal);\n return parseEventStream(res, signal);\n}\n\nfunction parseEventStream(res: Response, signal?: AbortSignal): AsyncIterable<Event> {\n return {\n async *[Symbol.asyncIterator](): AsyncGenerator<Event> {\n const body = res.body;\n if (!body) return;\n\n const reader = body.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n let buffer = \"\";\n let data = \"\";\n let hasData = false;\n\n try {\n while (true) {\n let chunk;\n try {\n chunk = await reader.read();\n } catch (err) {\n // Caller-initiated abort is a clean end, not an error.\n if (signal?.aborted) return;\n throw new FuseError(\"event stream read failed\", { cause: err });\n }\n if (chunk.done) {\n // Clean EOF with no terminal state: just end (matches Go).\n return;\n }\n\n buffer += decoder.decode(chunk.value, { stream: true });\n\n let nl: number;\n while ((nl = buffer.indexOf(\"\\n\")) >= 0) {\n let line = buffer.slice(0, nl);\n buffer = buffer.slice(nl + 1);\n if (line.endsWith(\"\\r\")) line = line.slice(0, -1); // tolerate CRLF\n\n if (line === \"\") {\n // Blank line terminates the current event.\n if (!hasData) continue;\n const payload = data;\n data = \"\";\n hasData = false;\n\n let event: Event;\n try {\n event = JSON.parse(payload) as Event;\n } catch (err) {\n throw new FuseError(\"decode event\", { cause: err });\n }\n yield event;\n if (isTerminalState(event.state)) return;\n } else if (line.startsWith(\":\")) {\n // Comment / keepalive line — skip.\n continue;\n } else if (line.startsWith(DATA_PREFIX)) {\n // Strip the prefix and a single optional leading space; multiple\n // data: lines concatenate without a separator (matches server).\n let p = line.slice(DATA_PREFIX.length);\n if (p.startsWith(\" \")) p = p.slice(1);\n data += p;\n hasData = true;\n }\n // Other fields (id:, event:, ...) are ignored.\n }\n }\n } finally {\n // Release the underlying socket if the consumer breaks early.\n try {\n await reader.cancel();\n } catch {\n // ignore\n }\n }\n },\n };\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport { isInterventionSettled, type AuditEntry, type Intervention } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** The server's max page size; list() requests this internally. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** How long one long-poll asks the server to hold. It stays well under a\n * typical client timeout; the server caps it at 50s. */\nconst WAIT_POLL = \"30s\";\n\n/** Filters (and pagination) for interventions.list / interventions.listPage. */\nexport interface ListInterventionsOptions {\n /** Only interventions raised by this environment. */\n envId?: string;\n /** One of InterventionState. */\n state?: string;\n /** Only interventions raised or decided by this actor id. */\n actor?: string;\n /** Page size. Only consulted by listPage; list() always walks every page. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface InterventionList {\n interventions: Intervention[];\n next_cursor?: string;\n}\n\n/** One page of interventions.listPage, plus the cursor to fetch the next one. */\nexport interface InterventionPage {\n interventions: Intervention[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** Filters (and pagination) for interventions.audit / interventions.auditPage. */\nexport interface AuditOptions {\n /** Only rows for this environment. */\n envId?: string;\n /** Only rows for this actor id. */\n actor?: string;\n /** An RFC 3339 time, or a duration like \"24h\" meaning that long ago. */\n since?: string;\n /** Page size. Only consulted by auditPage; audit() always walks every page. */\n limit?: number;\n /** Opaque cursor from a previous auditPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface AuditList {\n entries: AuditEntry[];\n next_cursor?: string;\n}\n\n/** One page of interventions.auditPage, plus the cursor to fetch the next one. */\nexport interface AuditPage {\n entries: AuditEntry[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** Body for interventions.approve: an answer to an ask, or an approval of a\n * held exec or lifecycle action. */\nexport interface ApproveOptions {\n /** An ask needs an answer (one of its choices, when it has any). */\n answer?: string;\n reason?: string;\n /** Replaces a held exec's argv. It is re-checked against the deny gates,\n * and cannot be combined with grant. */\n editedArgv?: string[];\n /** Replaces a held computer \"type\" action's text. It is re-checked against\n * the deny gates, and cannot be combined with grant. */\n editedText?: string;\n /** \"once\", \"env\" or \"ttl:<duration>\"; unset takes the gate's default. */\n grant?: string;\n /** How long approving an expiry keeps the environment alive. Zero or unset\n * is one more full window of the reaper that was due. */\n extendSeconds?: number;\n}\n\n/** Body for interventions.reject. */\nexport interface RejectOptions {\n /** Fed back to the agent; the server fills one in when empty. */\n reason?: string;\n}\n\n/** InterventionsService reads and decides hitl interventions. */\nexport class InterventionsService {\n constructor(private readonly t: Transport) {}\n\n /** List every intervention matching options, oldest first, walking every\n * page. */\n async list(\n options: ListInterventionsOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention[]> {\n const out: Intervention[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.interventions);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of interventions matching options. */\n async listPage(\n options: ListInterventionsOptions = {},\n opts: CallOptions = {},\n ): Promise<InterventionPage> {\n const out = await this.t.json<InterventionList>(\"GET\", \"/v1/interventions\", {\n query: {\n env: options.envId,\n state: options.state,\n actor: options.actor,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { interventions: out.interventions ?? [], nextCursor: out.next_cursor };\n }\n\n /** List every hitl audit row matching options, oldest first, walking every\n * page. */\n async audit(options: AuditOptions = {}, opts: CallOptions = {}): Promise<AuditEntry[]> {\n const out: AuditEntry[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.auditPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.entries);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of the hitl audit log matching options. */\n async auditPage(\n options: AuditOptions = {},\n opts: CallOptions = {},\n ): Promise<AuditPage> {\n const out = await this.t.json<AuditList>(\"GET\", \"/v1/hitl/audit\", {\n query: {\n env: options.envId,\n actor: options.actor,\n since: options.since,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { entries: out.entries ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a takeover session's recording (an AuditEntry's recording_id):\n * asciinema v2 cast text for a terminal session, json (an input-action log\n * plus screenshots) for a desktop one. Needs the hitl:read scope. */\n async getRecording(recordingId: string, opts: CallOptions = {}): Promise<string> {\n requireArg(recordingId, \"recording id\");\n return this.t.text(\"GET\", `/v1/hitl/recordings/${encodeURIComponent(recordingId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Fetch one intervention without waiting. */\n async get(id: string, opts: CallOptions = {}): Promise<Intervention> {\n return getIntervention(this.t, id, undefined, opts);\n }\n\n /**\n * Block until the intervention settles: resolved, and for an approved gated\n * action, performed, with the outcome on result. Every intervention has a deadline,\n * so this always returns eventually. A dropped connection or an\n * orchestrator restart is survived by polling again; the server, not the\n * connection, holds the state. Pass `opts.signal` to stop early.\n */\n async wait(id: string, opts: CallOptions = {}): Promise<Intervention> {\n return waitIntervention(this.t, id, opts);\n }\n\n /** Resolve a pending intervention as approved. For a held exec or\n * lifecycle action, the orchestrator then performs it (optionally with\n * body.editedArgv, or granting repeats with body.grant); wait on the id for\n * its result. Requires the master token. */\n async approve(\n id: string,\n body: ApproveOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n return this.decide(id, \"approve\", body, opts);\n }\n\n /** Resolve a pending intervention as rejected. Requires the master token. */\n async reject(\n id: string,\n body: RejectOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n return this.decide(id, \"reject\", { reason: body.reason }, opts);\n }\n\n /**\n * Answer a pending secret request. The value is written into the guest at\n * the declared target and dropped; fuse never stores, logs or returns it.\n * Needs the hitl:secret scope.\n */\n async answerSecret(\n id: string,\n value: string,\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/interventions/${encodeURIComponent(id)}`,\n { query: { action: \"secret\" }, body: { value }, signal: opts.signal },\n );\n }\n\n private async decide(\n id: string,\n action: string,\n body: ApproveOptions,\n opts: CallOptions,\n ): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/interventions/${encodeURIComponent(id)}`,\n {\n query: { action },\n body: {\n answer: body.answer || undefined,\n reason: body.reason || undefined,\n edited_argv: body.editedArgv?.length ? body.editedArgv : undefined,\n edited_text: body.editedText,\n grant: body.grant || undefined,\n extend_seconds: body.extendSeconds || undefined,\n },\n signal: opts.signal,\n },\n );\n }\n}\n\n/** waitIntervention long-polls until the intervention is settled. A wait can\n * time out on an approved gated action that has not run yet, so the loop\n * checks settled, not terminal. */\nexport async function waitIntervention(\n t: Transport,\n id: string,\n opts: CallOptions = {},\n): Promise<Intervention> {\n for (;;) {\n const i = await getIntervention(t, id, WAIT_POLL, opts);\n if (isInterventionSettled(i)) return i;\n opts.signal?.throwIfAborted();\n }\n}\n\nfunction getIntervention(\n t: Transport,\n id: string,\n wait: string | undefined,\n opts: CallOptions,\n): Promise<Intervention> {\n requireArg(id, \"intervention id\");\n return t.json<Intervention>(\"GET\", `/v1/interventions/${encodeURIComponent(id)}`, {\n query: { wait },\n signal: opts.signal,\n });\n}\n","// hitl gates: waiting out a call a gate held, mirroring sdks/go/gates.go.\n\nimport type { CallOptions, Transport } from \"./transport.js\";\nimport { isInterventionApproved, type Intervention } from \"./types.js\";\nimport {\n HeldActionError,\n InterventionRejectedError,\n PendingInterventionError,\n} from \"./errors.js\";\nimport { waitIntervention } from \"./interventions.js\";\n\n/** Per-call overrides of the client's hitl wait options. */\nexport interface HeldOptions {\n /** false throws a PendingInterventionError instead of waiting. */\n wait?: boolean;\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * settleHeld waits out a held call: it reports the hold, waits until the\n * intervention settles, and turns anything but a successful run into an\n * error. Only opts.signal bounds the wait; every intervention has a\n * deadline, so it always ends.\n */\nexport async function settleHeld(\n t: Transport,\n held: Intervention,\n o: HeldOptions,\n opts: CallOptions,\n): Promise<Intervention> {\n const onHeld = o.onHeld ?? t.onHeld;\n onHeld?.(held);\n if (o.wait === false || t.hitlNoWait) throw new PendingInterventionError(held);\n const i = await waitIntervention(t, held.id, opts);\n if (!isInterventionApproved(i)) throw new InterventionRejectedError(i);\n if (i.result?.error) throw new HeldActionError(i);\n return i;\n}\n","// hitl takeover lock: waiting out a 423 on exec and computer calls, mirroring\n// sdks/go. while a human holds the environment (or an ask-mode stall is\n// pending) those calls are refused; by default the sdk waits for the\n// intervention to settle and retries, so agent code needs no changes.\n\nimport type { CallOptions, Transport } from \"./transport.js\";\nimport type { Intervention } from \"./types.js\";\nimport { isLocked } from \"./errors.js\";\nimport { waitIntervention } from \"./interventions.js\";\n\n/** Per-call options for calls a takeover can lock or a gate can hold\n * (computer actions). */\nexport interface LockedCallOptions extends CallOptions {\n /** Wait out a takeover or a pending stall, and a gate's hold (the\n * default). false throws a LockedError or a PendingInterventionError at\n * once instead. */\n wait?: boolean;\n /** Called with the pending intervention when a gate holds the action,\n * before waiting on it. It overrides the client's onHeld. */\n onHeld?: (held: Intervention) => void;\n}\n\n/** Body for environments.takeover. */\nexport interface TakeoverOptions {\n /** How to take over: TakeoverVia.Terminal (the default) or\n * TakeoverVia.Desktop. */\n via?: string;\n /** Recorded when no agent request is pending to claim. */\n reason?: string;\n}\n\n/** Body for environments.release. */\nexport interface ReleaseOptions {\n /** Handed back to the agent as the takeover's answer. */\n note?: string;\n}\n\n/**\n * retryLocked runs call, and on a 423 waits until the named intervention is\n * no longer pending, then runs it again. a fresh 423 waits again. the server\n * bounds every lock by the intervention deadline; opts.signal stops early.\n */\nexport async function retryLocked<T>(\n t: Transport,\n call: () => Promise<T>,\n wait: boolean | undefined,\n opts: CallOptions,\n): Promise<T> {\n for (;;) {\n try {\n return await call();\n } catch (err) {\n if (wait === false || !isLocked(err) || !err.interventionId) throw err;\n await waitIntervention(t, err.interventionId, opts);\n opts.signal?.throwIfAborted();\n }\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type {\n ComputerAction,\n ComputerDisplay,\n ComputerResult,\n ComputerToolResult,\n CreateRequest,\n EnvironmentInfo,\n Event,\n ExecRequest,\n ExecResult,\n ForkOptions,\n Intervention,\n MigrateOptions,\n ToolResultBlock,\n} from \"./types.js\";\nimport { HitlKind, isInterventionApproved } from \"./types.js\";\nimport {\n FuseError,\n InterventionRejectedError,\n isFuseApiError,\n isHitlDenied,\n} from \"./errors.js\";\nimport { requireArg } from \"./validate.js\";\nimport { streamEvents } from \"./events.js\";\nimport { waitIntervention } from \"./interventions.js\";\nimport { settleHeld } from \"./gates.js\";\nimport {\n retryLocked,\n type LockedCallOptions,\n type ReleaseOptions,\n type TakeoverOptions,\n} from \"./takeover.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Filters (and pagination) for environments.list / environments.listPage. */\nexport interface ListEnvironmentsOptions {\n taskId?: string;\n state?: string;\n hostId?: string;\n /** Page size (server default 50, max 200). Only consulted by listPage —\n * list() always walks every page, so it ignores this and requests the\n * server's max page size. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface EnvironmentList {\n environments: EnvironmentInfo[];\n next_cursor?: string;\n}\n\n/** One page of environments.listPage, plus the cursor to fetch the next one. */\nexport interface EnvironmentPage {\n environments: EnvironmentInfo[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** What environments.requestHuman sends. */\nexport interface HumanRequest {\n /** The request kind: \"ask\" (the default), \"secret\", \"takeover\" or\n * \"review\". */\n kind?: string;\n /** What the human is asked (ask). */\n question?: string;\n /** Restricts the answer to one of these (ask). */\n choices?: string[];\n /** A declared secret target: its env name or file path (secret). */\n target?: string;\n /** The agent's text shown under the target's label (secret), or with the\n * content up for review (review). */\n message?: string;\n /** How the human takes over: \"terminal\" or \"desktop\" (takeover). */\n via?: string;\n /** Why the agent wants a human to take over (takeover). */\n reason?: string;\n /** An absolute guest file to review; exclusive with content (review). */\n path?: string;\n /** Inline text or a diff to review (review). */\n content?: string;\n /** ReviewFormat.Text or ReviewFormat.Diff; unset guesses (review). */\n format?: string;\n /** Shortens the policy's deadline. It can never extend it. */\n timeoutSeconds?: number;\n /** Wait for a decision (the default). false returns the pending\n * intervention at once; wait on it later with interventions.wait. */\n wait?: boolean;\n}\n\n/** What environments.requestReview sends: exactly one of path and content. */\nexport interface ReviewRequest {\n /** An absolute guest file; fuse reads it at request time. */\n path?: string;\n /** Inline text or a diff. */\n content?: string;\n /** ReviewFormat.Text or ReviewFormat.Diff; unset guesses. */\n format?: string;\n message?: string;\n timeoutSeconds?: number;\n /** Wait for the verdict (the default). false returns at once with the\n * pending intervention and approved false. */\n wait?: boolean;\n}\n\n/** ReviewResult is a finished review. comments are the reviewer's, on\n * either outcome. */\nexport interface ReviewResult {\n approved: boolean;\n comments: string;\n intervention: Intervention;\n}\n\n/** EnvironmentsService manages microVM lifecycle. */\nexport class EnvironmentsService {\n constructor(private readonly t: Transport) {}\n\n /** List tracked environments, optionally filtered. Transparently walks\n * every result page. For explicit single-page control (e.g. a cursor from\n * a previous call), use listPage. */\n async list(\n options: ListEnvironmentsOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo[]> {\n const out: EnvironmentInfo[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.environments);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of tracked environments, optionally filtered. */\n async listPage(\n options: ListEnvironmentsOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentPage> {\n const out = await this.t.json<EnvironmentList>(\"GET\", \"/v1/environments\", {\n query: {\n task_id: options.taskId,\n state: options.state,\n host_id: options.hostId,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { environments: out.environments ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a single environment by VM id. */\n async get(vmId: string, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n return this.t.json<EnvironmentInfo>(\n \"GET\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { signal: opts.signal },\n );\n }\n\n /** Provision a new environment. Blocks until running or creation fails. */\n async create(body: CreateRequest, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n return this.t.json<EnvironmentInfo>(\"POST\", \"/v1/environments\", {\n body,\n signal: opts.signal,\n });\n }\n\n /** Fork an environment into a new one; returns the new environment. When a\n * hitl gate holds the fork, it waits for the decision and returns the\n * environment the orchestrator then forked. */\n async fork(\n vmId: string,\n body: ForkOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"fork\" }, body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n return this.heldEnvironment(out.held, opts);\n }\n\n /**\n * Migrate an environment to another host; returns the new environment. The\n * source is drained and destroyed once the new one is running.\n */\n async migrate(\n vmId: string,\n body: MigrateOptions = {},\n opts: CallOptions = {},\n ): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"migrate\" }, body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n return this.heldEnvironment(out.held, opts);\n }\n\n /** heldEnvironment waits out a held fork or migrate and returns the\n * environment it produced. */\n private async heldEnvironment(\n held: Intervention,\n opts: CallOptions,\n ): Promise<EnvironmentInfo> {\n const i = await settleHeld(this.t, held, {}, opts);\n if (!i.result?.env_id) {\n throw new FuseError(`intervention ${i.id} settled without an environment`);\n }\n return this.get(i.result.env_id, opts);\n }\n\n /**\n * Run a command inside a running environment's guest and return its exit code\n * with stdout and stderr kept separate.\n *\n * A non-zero exit_code is resolved, not thrown: the command ran and failed.\n * A thrown error means the command could not be run at all.\n *\n * Exec requires the master token.\n *\n * When a hitl gate holds the exec, exec waits for the decision (bounded\n * only by `opts.signal`); the orchestrator runs the approved (possibly\n * edited) argv and exec returns its result. A rejection throws an\n * InterventionRejectedError, a deny gate an error isHitlDenied matches.\n * `wait: false` throws a PendingInterventionError at once instead.\n *\n * While a human holds a takeover (or an ask-mode stall is pending) the\n * server answers 423; exec waits for that intervention to settle and runs\n * the command then. `wait: false` throws a LockedError at once instead.\n *\n * @example\n * const out = await client.environments.exec(id, { cmd: [\"ls\", \"-l\"] });\n * if (out.exit_code !== 0) console.error(out.stderr);\n */\n async exec(\n vmId: string,\n body: ExecRequest,\n opts: CallOptions = {},\n ): Promise<ExecResult> {\n requireArg(vmId, \"vm id\");\n const hasCmd = (body.cmd?.length ?? 0) > 0;\n const hasShell = (body.shell ?? \"\") !== \"\";\n if (!hasCmd && !hasShell) {\n throw new FuseError(\"one of cmd or shell is required\");\n }\n if (hasCmd && hasShell) {\n throw new FuseError(\"cmd and shell are mutually exclusive\");\n }\n const { wait, onHeld, ...wire } = body;\n // a 423 (a human holds the environment) waits and retries; a 202 (a gate\n // holds this exec) waits for the decision and its run.\n const out = await retryLocked(\n this.t,\n () =>\n this.t.gated<ExecResult>(\"POST\", `/v1/environments/${encodeURIComponent(vmId)}`, {\n query: { action: \"exec\" },\n body: wire,\n signal: opts.signal,\n }),\n wait,\n opts,\n );\n if (!out.held) return out.value;\n const i = await settleHeld(this.t, out.held, { wait, onHeld }, opts);\n if (!i.result?.exec) {\n throw new FuseError(`intervention ${i.id} settled without an exec result`);\n }\n return i.result.exec;\n }\n\n /**\n * Relay one computer-use action to the environment's desktop and return the\n * result, usually carrying a base64 PNG screenshot. Requires an environment\n * booted from a desktop image; on any other image the server answers 503\n * with a reason.\n *\n * Like exec, it waits out a takeover or a pending stall (a 423) and then\n * acts; `opts.wait: false` throws a LockedError at once instead. When a\n * computer gate holds the action (a 202), it waits for the decision and\n * returns what the orchestrator got performing it (with the human's edited\n * text, if any); a rejection throws an InterventionRejectedError, and\n * `opts.wait: false` throws a PendingInterventionError at once instead.\n *\n * @example\n * const res = await client.environments.computer(id, {\n * action: \"left_click\",\n * coordinate: [512, 384],\n * });\n */\n async computer(\n vmId: string,\n action: ComputerAction,\n opts: LockedCallOptions = {},\n ): Promise<ComputerResult> {\n requireArg(vmId, \"vm id\");\n requireArg(action?.action, \"action\");\n return this.postComputer(vmId, action, opts);\n }\n\n /**\n * Execute one computer tool_use against the environment and shape the\n * answer for the Messages API: the tool_use block's `input` goes in\n * verbatim (it is already the wire shape the computer endpoint takes), and\n * content blocks for the tool_result come out.\n *\n * An action the environment refuses (a malformed coordinate, a display\n * that is not up) resolves to `is_error` content rather than throwing: the\n * agent loop should feed it to the model, which is the party that can\n * correct it. So does a hitl deny gate or a human rejecting a held action. A throw is reserved for failures the model cannot fix —\n * transport, auth, an unknown environment.\n *\n * @example\n * for (const block of msg.content) {\n * if (block.type === \"tool_use\" && block.name === \"computer\") {\n * const result = await client.environments.computerToolResult(id, block.input);\n * toolResults.push({ type: \"tool_result\", tool_use_id: block.id, ...result });\n * }\n * }\n */\n async computerToolResult(\n vmId: string,\n input: unknown,\n opts: LockedCallOptions = {},\n ): Promise<ComputerToolResult> {\n requireArg(vmId, \"vm id\");\n const action = (input as { action?: string } | null)?.action ?? \"\";\n if (action === \"\") {\n return {\n is_error: true,\n content: [{ type: \"text\", text: \"tool input names no action\" }],\n };\n }\n let res: ComputerResult;\n try {\n res = await this.postComputer(vmId, input, opts);\n } catch (err) {\n if (\n isFuseApiError(err) &&\n (err.status === 400 ||\n err.status === 409 ||\n err.status === 503 ||\n isHitlDenied(err))\n ) {\n return {\n is_error: true,\n content: [{ type: \"text\", text: err.message || \"the computer action failed\" }],\n };\n }\n if (err instanceof InterventionRejectedError) {\n return {\n is_error: true,\n content: [\n { type: \"text\", text: `a human rejected this action: ${err.message}` },\n ],\n };\n }\n throw err;\n }\n const content: ToolResultBlock[] = [];\n if (res.output) content.push({ type: \"text\", text: res.output });\n if (res.screenshot) {\n content.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: \"image/png\",\n data: res.screenshot,\n },\n });\n }\n if (content.length === 0) content.push({ type: \"text\", text: \"done\" });\n return { content };\n }\n\n private async postComputer(\n vmId: string,\n body: unknown,\n opts: LockedCallOptions,\n ): Promise<ComputerResult> {\n // a 423 (a human holds the environment) waits and retries; a 202 (a gate\n // holds this action) waits for the decision and its run.\n const out = await retryLocked(\n this.t,\n () =>\n this.t.gated<ComputerResult>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}/computer`,\n { body, signal: opts.signal },\n ),\n opts.wait,\n opts,\n );\n if (!out.held) return out.value;\n const i = await settleHeld(\n this.t,\n out.held,\n { wait: opts.wait, onHeld: opts.onHeld },\n opts,\n );\n if (!i.result?.computer) {\n throw new FuseError(`intervention ${i.id} settled without a computer result`);\n }\n return i.result.computer;\n }\n\n /**\n * Ask a human for something the environment's hitl policy declares. By\n * default it waits (by long-polling) until the intervention resolves\n * (answered, rejected, expired or cancelled); read the result off the\n * returned intervention's decision. Pass `wait: false` to get the pending\n * handle instead. Pass `opts.signal` to stop waiting early.\n *\n * @example\n * const res = await client.environments.requestHuman(id, {\n * question: \"deploy to prod?\",\n * choices: [\"yes\", \"no\"],\n * });\n * if (isInterventionApproved(res)) console.log(res.decision?.answer);\n */\n async requestHuman(\n vmId: string,\n req: HumanRequest,\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n const pending = await this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"request\" },\n body: {\n kind: req.kind || \"ask\",\n question: req.question || undefined,\n choices: req.choices,\n target: req.target || undefined,\n message: req.message || undefined,\n via: req.via || undefined,\n reason: req.reason || undefined,\n path: req.path || undefined,\n content: req.content || undefined,\n format: req.format || undefined,\n timeout_seconds: req.timeoutSeconds || undefined,\n },\n signal: opts.signal,\n },\n );\n if (req.wait === false) return pending;\n return waitIntervention(this.t, pending.id, opts);\n }\n\n /**\n * Submit a guest file or a text/diff blob for a human to approve or reject\n * with comments, and wait for the verdict. Needs hitl.requests.review.\n * With `wait: false` it returns at once with the pending intervention and\n * approved false.\n *\n * @example\n * const r = await client.environments.requestReview(id, {\n * content: diff,\n * format: ReviewFormat.Diff,\n * });\n * if (!r.approved) console.log(r.comments);\n */\n async requestReview(\n vmId: string,\n req: ReviewRequest,\n opts: CallOptions = {},\n ): Promise<ReviewResult> {\n const i = await this.requestHuman(\n vmId,\n {\n kind: HitlKind.Review,\n path: req.path,\n content: req.content,\n format: req.format,\n message: req.message,\n timeoutSeconds: req.timeoutSeconds,\n wait: req.wait,\n },\n opts,\n );\n return {\n approved: isInterventionApproved(i),\n comments: i.decision?.reason ?? \"\",\n intervention: i,\n };\n }\n\n /**\n * Take over the environment as a human: claims the agent's pending\n * takeover request if there is one, else opens a new one. While held, the\n * agent's exec and computer calls wait. Returns the held intervention.\n * Needs the hitl:takeover scope; a conflict when someone else holds it.\n */\n async takeover(\n vmId: string,\n body: TakeoverOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"takeover\" },\n body: { via: body.via || undefined, reason: body.reason || undefined },\n signal: opts.signal,\n },\n );\n }\n\n /**\n * End a takeover and hand the environment back to the agent. The note is\n * the takeover's answer. Returns the approved intervention; a conflict when\n * nothing is held.\n */\n async release(\n vmId: string,\n body: ReleaseOptions = {},\n opts: CallOptions = {},\n ): Promise<Intervention> {\n requireArg(vmId, \"vm id\");\n return this.t.json<Intervention>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n {\n query: { action: \"release\" },\n body: { note: body.note || undefined },\n signal: opts.signal,\n },\n );\n }\n\n /** Report whether the environment has a live display and at what geometry.\n * up is false with a reason on an image with no desktop. */\n async computerDisplay(vmId: string, opts: CallOptions = {}): Promise<ComputerDisplay> {\n requireArg(vmId, \"vm id\");\n return this.t.json<ComputerDisplay>(\n \"GET\",\n `/v1/environments/${encodeURIComponent(vmId)}/computer`,\n { signal: opts.signal },\n );\n }\n\n /**\n * Phase-1 only: quiesces the guest workload and moves the environment to\n * \"draining\" so you can inspect its output, but does not destroy it. Call\n * destroy() afterward to remove it. A drained environment left\n * undestroyed keeps running (and billing) until the orchestrator's\n * draining timeout (5m30s by default) passes, and then the orchestrator\n * destroys it.\n */\n async drain(vmId: string, opts: CallOptions = {}): Promise<EnvironmentInfo> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<EnvironmentInfo>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"drain\" }, signal: opts.signal },\n );\n if (!out.held) return out.value;\n await settleHeld(this.t, out.held, {}, opts);\n return this.get(vmId, opts);\n }\n\n /** Rotate the per-VM credentials and push them to the guest. */\n async rotateToken(vmId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(vmId, \"vm id\");\n const held = await this.t.gatedNoContent(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { query: { action: \"rotate-token\" }, signal: opts.signal },\n );\n if (held) await settleHeld(this.t, held, {}, opts);\n }\n\n /** Forcefully destroy an environment. Idempotent. When a hitl gate holds\n * the destroy, it waits for the decision. */\n async destroy(vmId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(vmId, \"vm id\");\n const held = await this.t.gatedNoContent(\n \"DELETE\",\n `/v1/environments/${encodeURIComponent(vmId)}`,\n { signal: opts.signal },\n );\n if (held) await settleHeld(this.t, held, {}, opts);\n }\n\n /**\n * Open the SSE event stream for an environment. The returned promise rejects\n * with a FuseApiError on a connect-time failure (e.g. not_found); on success\n * it resolves to an AsyncIterable that yields each Event and ends after a\n * terminal-state event. Pass `opts.signal` to cancel; there is no built-in\n * timeout on the stream.\n *\n * @example\n * for await (const ev of await client.environments.events(id)) {\n * console.log(ev.state);\n * }\n */\n async events(vmId: string, opts: CallOptions = {}): Promise<AsyncIterable<Event>> {\n requireArg(vmId, \"vm id\");\n return streamEvents(this.t, vmId, opts.signal);\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { ResolveSnapshotResponse, Snapshot, SnapshotRequest } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\nimport { FuseError } from \"./errors.js\";\nimport { settleHeld } from \"./gates.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Filters (and pagination) for snapshots.list / snapshots.listPage. */\nexport interface ListSnapshotsOptions {\n vmId?: string;\n taskId?: string;\n tenantId?: string;\n state?: string;\n /** Narrows to the build layers taken after one setup step. Unset means \"do\n * not filter\", never \"match artifacts with no layer key\". */\n layerKey?: string;\n /** Narrows to artifacts built on one architecture, in GOARCH vocabulary\n * (\"amd64\", \"arm64\"). It is a separate filter from layerKey rather than\n * part of it because a rootfs is not portable across architectures, so a\n * layer lookup that does not constrain arch can be served bytes it cannot\n * boot. */\n arch?: string;\n /** Page size (server default 50, max 200). Only consulted by listPage —\n * list() always walks every page, so it ignores this and requests the\n * server's max page size. */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface SnapshotList {\n snapshots: Snapshot[];\n next_cursor?: string;\n}\n\n/** One page of snapshots.listPage, plus the cursor to fetch the next one. */\nexport interface SnapshotPage {\n snapshots: Snapshot[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** SnapshotsService manages microVM snapshots. */\nexport class SnapshotsService {\n constructor(private readonly t: Transport) {}\n\n /** Create a snapshot of a running environment.\n *\n * An empty body takes a disk snapshot, the rootfs and nothing else; pass\n * `{ live: true }` to capture the guest's memory and vCPU state as well.\n *\n * The returned `snapshot.kind` reports what was actually written, which can\n * be `\"disk\"` even for a `live: true` request that reached a host too old to\n * honour it. A caller that depends on the memory being there should check\n * it. `live: true` against a backend with no live-snapshot support throws a\n * 501 `unimplemented`, not a conflict.\n *\n * When a hitl gate holds the snapshot, create waits for the decision and\n * returns the snapshot the orchestrator then took. */\n async create(\n vmId: string,\n body: SnapshotRequest = {},\n opts: CallOptions = {},\n ): Promise<Snapshot> {\n requireArg(vmId, \"vm id\");\n const out = await this.t.gated<Snapshot>(\n \"POST\",\n `/v1/environments/${encodeURIComponent(vmId)}/snapshots`,\n { body, signal: opts.signal },\n );\n if (!out.held) return out.value;\n const i = await settleHeld(this.t, out.held, {}, opts);\n if (!i.result?.snapshot_id) {\n throw new FuseError(`intervention ${i.id} settled without a snapshot`);\n }\n return this.get(i.result.snapshot_id, opts);\n }\n\n /** List snapshots, optionally filtered. Transparently walks every result\n * page. For explicit single-page control (e.g. a cursor from a previous\n * call), use listPage. */\n async list(\n options: ListSnapshotsOptions = {},\n opts: CallOptions = {},\n ): Promise<Snapshot[]> {\n const out: Snapshot[] = [];\n let cursor = options.cursor;\n for (;;) {\n const page = await this.listPage(\n { ...options, limit: MAX_PAGE_LIMIT, cursor },\n opts,\n );\n out.push(...page.snapshots);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of snapshots, optionally filtered. */\n async listPage(\n options: ListSnapshotsOptions = {},\n opts: CallOptions = {},\n ): Promise<SnapshotPage> {\n const out = await this.t.json<SnapshotList>(\"GET\", \"/v1/snapshots\", {\n query: {\n vm_id: options.vmId,\n task_id: options.taskId,\n tenant_id: options.tenantId,\n state: options.state,\n layer_key: options.layerKey,\n arch: options.arch,\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { snapshots: out.snapshots ?? [], nextCursor: out.next_cursor };\n }\n\n /**\n * Resolve one layer cache key and architecture to the newest ready build\n * artifact, or null when there is none.\n *\n * A miss is not an error and never rejects: a cold cache is the normal state\n * of a first build, and modelling it as a failure would make every caller\n * wrap this in a try/catch to discover nothing was wrong.\n *\n * arch is required rather than defaulted. An ext4 rootfs is not portable\n * across architectures, so resolving without one could hand back an artifact\n * the caller cannot boot, at the exact moment it believes it got a hit.\n *\n * The scope searched comes from how the client authenticated; there is\n * deliberately no tenant parameter.\n */\n async resolve(\n layerKey: string,\n arch: string,\n opts: CallOptions = {},\n ): Promise<Snapshot | null> {\n requireArg(layerKey, \"layer key\");\n requireArg(arch, \"arch\");\n const out = await this.t.json<ResolveSnapshotResponse>(\n \"GET\",\n \"/v1/snapshots/resolve\",\n { query: { layer_key: layerKey, arch }, signal: opts.signal },\n );\n return out.found && out.snapshot ? out.snapshot : null;\n }\n\n /** Fetch a single snapshot by id. */\n async get(snapshotId: string, opts: CallOptions = {}): Promise<Snapshot> {\n requireArg(snapshotId, \"snapshot id\");\n return this.t.json<Snapshot>(\n \"GET\",\n `/v1/snapshots/${encodeURIComponent(snapshotId)}`,\n { signal: opts.signal },\n );\n }\n\n /** Delete a snapshot. Idempotent; the snapshot must be a leaf. */\n async delete(snapshotId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(snapshotId, \"snapshot id\");\n await this.t.noContent(\"DELETE\", `/v1/snapshots/${encodeURIComponent(snapshotId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Restore an environment from a snapshot. */\n async restore(snapshotId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(snapshotId, \"snapshot id\");\n await this.t.noContent(\"POST\", `/v1/snapshots/${encodeURIComponent(snapshotId)}`, {\n query: { action: \"restore\" },\n signal: opts.signal,\n });\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { Host, RegisterHostRequest } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** The server's max page size; list() requests this internally so it walks\n * every page in as few round trips as possible. */\nconst MAX_PAGE_LIMIT = 200;\n\n/** Pagination for hosts.listPage. */\nexport interface ListHostsOptions {\n /** Page size (server default 50, max 200). */\n limit?: number;\n /** Opaque cursor from a previous listPage() call's nextCursor. */\n cursor?: string;\n}\n\ninterface HostList {\n hosts: Host[];\n next_cursor?: string;\n}\n\n/** One page of hosts.listPage, plus the cursor to fetch the next one. */\nexport interface HostPage {\n hosts: Host[];\n /** Empty/undefined once there are no more results. */\n nextCursor?: string;\n}\n\n/** HostsService manages registered Firecracker hosts. */\nexport class HostsService {\n constructor(private readonly t: Transport) {}\n\n /** Register (or re-register) a host. Idempotent on id. */\n async register(body: RegisterHostRequest, opts: CallOptions = {}): Promise<Host> {\n return this.t.json<Host>(\"POST\", \"/v1/hosts\", { body, signal: opts.signal });\n }\n\n /** List registered hosts. Transparently walks every result page. For\n * explicit single-page control (e.g. a cursor from a previous call), use\n * listPage. */\n async list(opts: CallOptions = {}): Promise<Host[]> {\n const out: Host[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page = await this.listPage({ limit: MAX_PAGE_LIMIT, cursor }, opts);\n out.push(...page.hosts);\n if (!page.nextCursor) break;\n cursor = page.nextCursor;\n }\n return out;\n }\n\n /** List one page of registered hosts. */\n async listPage(\n options: ListHostsOptions = {},\n opts: CallOptions = {},\n ): Promise<HostPage> {\n const out = await this.t.json<HostList>(\"GET\", \"/v1/hosts\", {\n query: {\n limit: options.limit ? String(options.limit) : undefined,\n cursor: options.cursor,\n },\n signal: opts.signal,\n });\n return { hosts: out.hosts ?? [], nextCursor: out.next_cursor };\n }\n\n /** Fetch a single host by id. */\n async get(hostId: string, opts: CallOptions = {}): Promise<Host> {\n requireArg(hostId, \"host id\");\n return this.t.json<Host>(\"GET\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n signal: opts.signal,\n });\n }\n\n /** Mark a host unschedulable; existing VMs keep running. */\n async cordon(hostId: string, opts: CallOptions = {}): Promise<void> {\n await this.action(hostId, \"cordon\", opts);\n }\n\n /** Return a cordoned host to active scheduling. */\n async uncordon(hostId: string, opts: CallOptions = {}): Promise<void> {\n await this.action(hostId, \"uncordon\", opts);\n }\n\n /** Remove a host. The host must have no running VMs. */\n async deregister(hostId: string, opts: CallOptions = {}): Promise<void> {\n requireArg(hostId, \"host id\");\n await this.t.noContent(\"DELETE\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n signal: opts.signal,\n });\n }\n\n private async action(hostId: string, action: string, opts: CallOptions): Promise<void> {\n requireArg(hostId, \"host id\");\n await this.t.noContent(\"POST\", `/v1/hosts/${encodeURIComponent(hostId)}`, {\n query: { action },\n signal: opts.signal,\n });\n }\n}\n","import type { CallOptions, Transport } from \"./transport.js\";\nimport type { ActorLabel, APIKey, CreatedAPIKey } from \"./types.js\";\nimport { requireArg } from \"./validate.js\";\n\n/** Options for apiKeys.create. Naming scopes mints a key limited to the hitl\n * routes; it must expire (ttlSeconds, at most 86400). */\nexport interface CreateApiKeyOptions {\n label?: string;\n /** One or more of HitlScope. Omit for a full-access key. */\n scopes?: string[];\n /** Limit a scoped key to this environment and its forks. */\n envId?: string;\n /** Lifetime in seconds. */\n ttlSeconds?: number;\n /** Pin the key to this actor. */\n actor?: ActorLabel;\n}\n\ninterface APIKeyList {\n api_keys: APIKey[];\n}\n\n/**\n * ApiKeysService manages revocable API keys. These endpoints require the\n * master token; the server enforces this.\n */\nexport class ApiKeysService {\n constructor(private readonly t: Transport) {}\n\n /**\n * Issue a new API key. Pass a label, or options for a scoped key. The raw\n * secret is returned once in `key` and is unrecoverable afterward.\n */\n async create(\n labelOrOptions?: string | CreateApiKeyOptions,\n opts: CallOptions = {},\n ): Promise<CreatedAPIKey> {\n const o: CreateApiKeyOptions =\n typeof labelOrOptions === \"string\"\n ? { label: labelOrOptions }\n : (labelOrOptions ?? {});\n return this.t.json<CreatedAPIKey>(\"POST\", \"/v1/api-keys\", {\n body: {\n label: o.label || undefined,\n scopes: o.scopes,\n env_id: o.envId || undefined,\n ttl_seconds: o.ttlSeconds || undefined,\n actor: o.actor,\n },\n signal: opts.signal,\n });\n }\n\n /** List API key metadata. */\n async list(opts: CallOptions = {}): Promise<APIKey[]> {\n const out = await this.t.json<APIKeyList>(\"GET\", \"/v1/api-keys\", {\n signal: opts.signal,\n });\n return out.api_keys ?? [];\n }\n\n /** Revoke the API key with the given id. */\n async revoke(id: string, opts: CallOptions = {}): Promise<void> {\n requireArg(id, \"id\");\n await this.t.noContent(\"DELETE\", `/v1/api-keys/${encodeURIComponent(id)}`, {\n signal: opts.signal,\n });\n }\n}\n","// generated by scripts/gen-version.mjs. do not edit.\nexport const VERSION = \"0.42.0\";\n","import { Transport, type FetchLike } from \"./transport.js\";\nimport { EnvironmentsService } from \"./environments.js\";\nimport { SnapshotsService } from \"./snapshots.js\";\nimport { HostsService } from \"./hosts.js\";\nimport { ApiKeysService } from \"./apiKeys.js\";\nimport { InterventionsService } from \"./interventions.js\";\nimport { VERSION } from \"./version.js\";\nimport type { ActorLabel, Intervention } from \"./types.js\";\n\n/** Options for constructing a FuseClient. */\nexport interface FuseClientOptions {\n /** Base URL of the Fuse control plane, e.g. \"https://fuse.example.com\". Required. */\n baseUrl: string;\n /** Bearer token (master token or an API key). Omit for unauthenticated endpoints. */\n token?: string;\n /** Custom fetch implementation. Defaults to the global fetch (Node 18+). */\n fetch?: FetchLike;\n /** User-Agent header. Defaults to \"fuse-ts/<version>\". Ignored by browsers. */\n userAgent?: string;\n /** Generator for the X-Request-ID header, called once per request. Empty results are omitted. */\n requestId?: () => string;\n /** Default per-request timeout in milliseconds. Does NOT apply to events() streams. */\n timeoutMs?: number;\n /** Extra default headers merged into every request. */\n headers?: Record<string, string>;\n /** The human this client acts for, sent as the Fuse-Actor and\n * Fuse-Actor-Name headers on every request. */\n actor?: ActorLabel;\n /** Make every hitl-gated call throw a PendingInterventionError at once\n * instead of waiting for the human. exec's `wait: false` does the same for\n * one exec. */\n hitlNoWait?: boolean;\n /** Called with the pending intervention whenever a gate holds a call,\n * before the call waits on it. exec's `onHeld` overrides it. */\n onHeld?: (held: Intervention) => void;\n}\n\n/**\n * FuseClient is the entry point for the Fuse API. It groups the resource\n * services that share a single transport.\n *\n * @example\n * const client = new FuseClient({ baseUrl: \"https://fuse.example.com\", token });\n * const env = await client.environments.create({ task_id: \"task-1\" });\n */\nexport class FuseClient {\n readonly environments: EnvironmentsService;\n readonly snapshots: SnapshotsService;\n readonly hosts: HostsService;\n readonly apiKeys: ApiKeysService;\n readonly interventions: InterventionsService;\n private readonly options: FuseClientOptions;\n\n constructor(options: FuseClientOptions) {\n this.options = options;\n const transport = new Transport({\n baseUrl: options.baseUrl,\n token: options.token,\n fetch: options.fetch,\n userAgent: options.userAgent ?? `fuse-ts/${VERSION}`,\n requestId: options.requestId,\n timeoutMs: options.timeoutMs,\n headers: options.headers,\n actor: options.actor,\n hitlNoWait: options.hitlNoWait,\n onHeld: options.onHeld,\n });\n this.environments = new EnvironmentsService(transport);\n this.snapshots = new SnapshotsService(transport);\n this.hosts = new HostsService(transport);\n this.apiKeys = new ApiKeysService(transport);\n this.interventions = new InterventionsService(transport);\n }\n\n /**\n * withActor returns a copy of this client, with the same options otherwise,\n * that sends `actor` as the Fuse-Actor headers. This client is unchanged.\n */\n withActor(actor: ActorLabel): FuseClient {\n return new FuseClient({ ...this.options, actor });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@folsom/fuse",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "TypeScript SDK for the Fuse microVM control plane",
5
5
  "license": "MIT",
6
6
  "author": "andrewn6",