Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

30.0 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import type { FirstRunUseCase } from '@/lib/first-run'
import type {
  CiSettings,
  CiConnectInput,
  CiWebStart,
  CiConnectResult,
  CiConnectConfiguration,
  CiRunners,
} from './ci-types'
import { BillingApiClient } from '@/billing-api/billingApiClient'
import { DashboardConfig } from '@/types/DashboardConfig'
import {
  Configuration as AnalyticsConfiguration,
  TelemetryApi as AnalyticsTelemetryApi,
  UsageApi as AnalyticsUsageApi,
} from '@boxlite-ai/analytics-api-client'
import {
  ApiKeysApi,
  AuditApi,
  ImagesApi,
  RegistriesApi,
  Configuration,
  OrganizationsApi,
  RegionsApi,
  RunnersApi,
  BoxApi,
  UsersApi,
  VolumesApi,
  WebhooksApi,
  UsageApi as CoreUsageApi,
  NetworkMode,
  User,
} from '@boxlite-ai/api-client'
import axios, { AxiosError, AxiosInstance, type AxiosRequestConfig } from 'axios'
import { BoxliteError } from './errors'
import { couponClaimReceipt, CouponClaimUnconfirmedError, type CouponClaimReceipt } from './coupon-claim'
import type { DomainList, HeldDomain, CustomDomain, CustomDomainList } from './domain-types'
import type { Checkpoint, CheckpointPage } from './checkpoint-types'
import { readTunnelDescriptor, tunnelOperationError, TunnelRequestError, type TunnelDescriptor } from './tunnel'

export interface VolumeStorageCapabilities {
  object_storage_enabled?: boolean
  filestore_enabled?: boolean
}

// A burst of in-flight requests can all 401 at once when the access token goes
// invalid; this in-page guard ensures at most one re-login redirect per page
// load. It is reset if onUnauthorized throws (a failed handler must not wedge
// recovery) and is naturally cleared when signinRedirect reloads the page.
let isHandlingUnauthorized = false

// Survives the full-page reload signinRedirect triggers, so a first stale-token
// 401 (recover silently) is distinguishable from one that persists *after* a
// re-auth already happened this session (revoked user / wrong audience / backend
// auth bug). Without a cross-reload marker a fresh-but-still-rejected token would
// bounce to login forever. sessionStorage scopes it to this tab.
const REAUTH_ATTEMPTED_KEY = 'boxlite.reauth-attempted'

function reauthAlreadyAttempted(): boolean {
  try {
    return window.sessionStorage.getItem(REAUTH_ATTEMPTED_KEY) !== null
  } catch {
    // sessionStorage can be unavailable (privacy mode, sandboxed iframe). Treat
    // as "not attempted" so we still try recovery once.
    return false
  }
}

function markReauthAttempted(): void {
  try {
    window.sessionStorage.setItem(REAUTH_ATTEMPTED_KEY, '1')
  } catch {
    // best-effort; see reauthAlreadyAttempted
  }
}

function clearReauthAttempted(): void {
  try {
    window.sessionStorage.removeItem(REAUTH_ATTEMPTED_KEY)
  } catch {
    // best-effort; see reauthAlreadyAttempted
  }
}

// Prefer bash when the image has it; every image has sh.
const LOGIN_SHELL = 'if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi'

export interface CancellationFeedbackInput {
  reasons: string[]
  intent: string | null
  note: string
}

export interface OrganizationOnboarding {
  useCase: FirstRunUseCase
  note: string
  submittedBy: string
  submittedAt: string
}
export interface PromptDraft {
  text: string
  revision: number
  updatedAt: string
}

const activityHeaders = { 'X-BoxLite-Source': 'dashboard' }

class ReauthenticationStartError extends BoxliteError {}

export class ApiClient {
  public async claimCoupon(
    organizationId: string,
    claim: { eventId: string; couponCode: string },
  ): Promise<CouponClaimReceipt> {
    const response = await this.http
      .post<unknown>(`/organizations/${encodeURIComponent(organizationId)}/coupon-claims`, claim, {
        ...this.v1Config(),
        timeout: 10_000,
      })
      .catch((error: BoxliteError) => {
        if (error instanceof ReauthenticationStartError) throw error
        const { cause } = error
        if (axios.isAxiosError(cause) && cause.response && cause.response.status < 500) throw error
        throw new CouponClaimUnconfirmedError()
      })
    const receipt = couponClaimReceipt.safeParse(response.data)
    if (response.status !== 202 || !receipt.success) throw new CouponClaimUnconfirmedError()
    return receipt.data
  }

  public async saveCancellationFeedback(org: string, feedback: CancellationFeedbackInput): Promise<void> {
    const response = await this.http.put(`/organizations/${encodeURIComponent(org)}/cancellation-feedback`, feedback, {
      ...this.v1Config(),
      timeout: 10_000,
    })
    if (response.status !== 204) throw new BoxliteError('Feedback save was not confirmed')
  }

  public async requestExperimentalFeature(organizationId: string, feature: string): Promise<void> {
    const response = await this.http.post(
      `/organizations/${encodeURIComponent(organizationId)}/experimental-feature-requests`,
      { feature },
      { ...this.v1Config(), timeout: 10_000 },
    )
    if (response.status !== 204) throw new BoxliteError('Feature request was not confirmed')
  }

  public async register(turnstileToken: string): Promise<User> {
    return (await this.http.post<User>('/auth/register', { turnstileToken }, { ...this.v1Config(), timeout: 30_000 }))
      .data
  }
  public async getCiRepositories(
    organization: string,
    context: import('./ci-types').CiRepositoryContext,
    page: number,
    signal?: AbortSignal,
  ): Promise<import('./ci-types').CiRepositoryPage> {
    const route =
      context.kind === 'binding'
        ? `connections/${encodeURIComponent(context.id)}/repositories`
        : `connect/${encodeURIComponent(context.id)}/accounts/${context.account}/repositories`
    return (
      await this.http.get(`/v1/${encodeURIComponent(organization)}/ci/${route}`, {
        ...this.v1Config(),
        params: { page, limit: 25 },
        signal,
      })
    ).data
  }

  public async getCiRunners(organization: string, page: number, limit: number, name?: string): Promise<CiRunners> {
    return (
      await this.http.get(`/v1/${encodeURIComponent(organization)}/ci/runners`, {
        ...this.v1Config(),
        params: { page, limit, ...(name?.trim() ? { name: name.trim() } : {}) },
      })
    ).data
  }
  public async updateCiConnection(organization: string, binding: string, allowPrivate: boolean): Promise<void> {
    await this.http.patch(
      `/v1/${encodeURIComponent(organization)}/ci/connections/${encodeURIComponent(binding)}`,
      { allow_private_repositories: allowPrivate },
      this.v1Config(),
    )
  }
  public async deleteCiConnection(organization: string, binding: string): Promise<void> {
    await this.http.delete(
      `/v1/${encodeURIComponent(organization)}/ci/connections/${encodeURIComponent(binding)}`,
      this.v1Config(),
    )
  }
  public async getCiSettings(organization: string): Promise<CiSettings> {
    return (await this.http.get(`/v1/${encodeURIComponent(organization)}/ci/settings`, this.v1Config())).data
  }
  public async setCiCapacity(organization: string, maximum: number | null): Promise<CiSettings> {
    return (
      await this.http.patch(
        `/v1/${encodeURIComponent(organization)}/ci/settings`,
        { max_concurrent_jobs: maximum },
        this.v1Config(),
      )
    ).data
  }
  public async getCiConnectConfiguration(organization: string): Promise<CiConnectConfiguration> {
    return (await this.http.get(`/v1/${encodeURIComponent(organization)}/ci/connect/configuration`, this.v1Config()))
      .data
  }
  public async startCiConnect(organization: string, input: CiConnectInput): Promise<CiWebStart> {
    return (await this.http.post(`/v1/${encodeURIComponent(organization)}/ci/connect/web`, input, this.v1Config())).data
  }
  public async getCiConnect(organization: string, id: string): Promise<CiConnectResult> {
    return (
      await this.http.get(
        `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}`,
        this.v1Config(),
      )
    ).data
  }
  public async cancelCiConnect(organization: string, id: string): Promise<CiConnectResult> {
    return (
      await this.http.delete(
        `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}`,
        this.v1Config(),
      )
    ).data
  }
  public async selectCiAccount(
    organization: string,
    id: string,
    account: number,
    allowPrivate: boolean,
  ): Promise<CiConnectResult> {
    return (
      await this.http.post(
        `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}/accounts`,
        { account_id: account, allow_private_repositories: allowPrivate },
        this.v1Config(),
      )
    ).data
  }
  public async completeCiConnect(
    organization: string,
    id: string,
    input: { code: string; state: string },
  ): Promise<CiConnectResult> {
    try {
      return (
        await this.http.post(
          `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}/complete`,
          input,
          this.v1Config(),
        )
      ).data
    } catch {
      // Axios errors can retain the submitted code in request configuration.
      throw new Error('GitHub authorization could not be completed. Restart connect.')
    }
  }

  public async selectCiConnect(organization: string, id: string, installation: number): Promise<CiConnectResult> {
    return (
      await this.http.post(
        `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}/select`,
        { installation_id: installation },
        this.v1Config(),
      )
    ).data
  }
  public async completeCiInstallation(
    organization: string,
    id: string,
    input: { installation_id: number; state: string },
  ): Promise<CiConnectResult> {
    try {
      return (
        await this.http.post(
          `/v1/${encodeURIComponent(organization)}/ci/connect/${encodeURIComponent(id)}/installation`,
          input,
          this.v1Config(),
        )
      ).data
    } catch {
      throw new Error('GitHub installation could not be verified. Restart connect.')
    }
  }

  public async getCheckpointCapabilities(): Promise<{ checkpoints_enabled: boolean }> {
    return (await this.http.get('/v1/config', this.v1Config())).data.capabilities
  }

  public async getVolumeStorageCapabilities(): Promise<VolumeStorageCapabilities> {
    return (await this.http.get('/v1/config', this.v1Config())).data.capabilities
  }

  public async listCheckpoints(org: string): Promise<Checkpoint[]> {
    const checkpoints: Checkpoint[] = []
    const seen = new Set<string>()
    let pageToken: string | undefined
    do {
      const { data } = await this.http.get<CheckpointPage>(`/v1/${encodeURIComponent(org)}/checkpoints`, {
        ...this.v1Config(),
        ...(pageToken ? { params: { page_token: pageToken } } : {}),
      })
      checkpoints.push(...data.checkpoints)
      pageToken = data.next_page_token || undefined
      if (pageToken && seen.has(pageToken)) throw new Error('Checkpoint server repeated a pagination token')
      if (pageToken) seen.add(pageToken)
    } while (pageToken)
    return checkpoints
  }

  public async createCheckpoint(org: string, source: string, name?: string): Promise<Checkpoint> {
    return (
      await this.http.post(
        `/v1/${encodeURIComponent(org)}/checkpoints`,
        {
          source_box_id: source,
          ...(name ? { name } : {}),
        },
        this.v1Config(),
      )
    ).data
  }

  public async removeCheckpoint(org: string, key: string): Promise<void> {
    await this.http.delete(`/v1/${encodeURIComponent(org)}/checkpoints/${encodeURIComponent(key)}`, this.v1Config())
  }

  public async createBoxFromCheckpoint(
    org: string,
    key: string,
    name?: string,
  ): Promise<{ box_id: string; name?: string }> {
    return (
      await this.http.post(
        `/v1/${encodeURIComponent(org)}/boxes`,
        {
          checkpoint_id: key,
          ...(name ? { name } : {}),
        },
        this.v1Config(),
      )
    ).data
  }

  public async getOrganizationOnboarding(org: string): Promise<OrganizationOnboarding | null> {
    return (await this.http.get(`/organizations/${encodeURIComponent(org)}/onboarding`, this.v1Config())).data
  }
  public async saveOrganizationOnboarding(org: string, value: Pick<OrganizationOnboarding, 'useCase' | 'note'>) {
    return (await this.http.put(`/organizations/${encodeURIComponent(org)}/onboarding`, value, this.v1Config())).data
  }
  public async getPromptDraft(org: string): Promise<PromptDraft | null> {
    return (await this.http.get(`/organizations/${encodeURIComponent(org)}/quickstart/prompt`, this.v1Config())).data
  }
  public async savePromptDraft(org: string, text: string, revision: number): Promise<PromptDraft> {
    return (
      await this.http.put(
        `/organizations/${encodeURIComponent(org)}/quickstart/prompt`,
        { text, revision },
        this.v1Config(),
      )
    ).data
  }
  public async preparePromptHandoff(org: string, text: string, requestId: string) {
    return (
      await this.http.post(
        `/organizations/${encodeURIComponent(org)}/quickstart/handoffs`,
        { text, requestId },
        this.v1Config(),
      )
    ).data
  }
  public async markPromptCopied(org: string, requestId: string) {
    return (
      await this.http.patch(
        `/organizations/${encodeURIComponent(org)}/quickstart/handoffs/${encodeURIComponent(requestId)}/copied`,
        {},
        this.v1Config(),
      )
    ).data
  }

  private config: Configuration
  private http: AxiosInstance
  private onUnauthorized?: () => Promise<void> | void
  private _boxApi: BoxApi
  private _userApi: UsersApi
  private _apiKeyApi: ApiKeysApi
  private _organizationsApi: OrganizationsApi
  private _billingApi: BillingApiClient
  private _volumeApi: VolumesApi
  private _imageApi: ImagesApi
  private _registriesApi: RegistriesApi
  private _auditApi: AuditApi
  private _regionsApi: RegionsApi
  private _runnersApi: RunnersApi
  private _webhooksApi: WebhooksApi
  private _usageApi: CoreUsageApi
  private _analyticsUsageApi: AnalyticsUsageApi | null
  private _analyticsTelemetryApi: AnalyticsTelemetryApi | null

  constructor(config: DashboardConfig, accessToken: string, onUnauthorized?: () => Promise<void> | void) {
    this.onUnauthorized = onUnauthorized
    this.config = new Configuration({
      basePath: config.apiUrl,
      accessToken: accessToken,
    })

    const axiosInstance = axios.create({ baseURL: config.apiUrl, headers: activityHeaders })
    axiosInstance.defaults.headers.common.Authorization = `Bearer ${accessToken}`
    axiosInstance.interceptors.request.use((request) => {
      request.headers?.delete?.('User-Agent')
      if (request.headers) {
        delete (request.headers as Record<string, unknown>)['User-Agent']
      }
      return request
    })
    axiosInstance.interceptors.response.use(
      (response) => {
        // A request succeeded → the token is good again; clear the cross-reload
        // marker so a future stale token still gets its one silent recovery.
        clearReauthAttempted()
        return response
      },
      (error) => {
        // A 401 means the access token is no longer accepted — it expired, or
        // (the common case in the local stack) it was signed by a key that
        // rotated when the Rauthy box was recreated. oidc-client-ts only tracks
        // local expiry, so it still believes the user is signed in and keeps
        // replaying the dead token on every reload. Drop the session and bounce
        // to a fresh login instead of a dead-end "Unauthorized" screen.
        if (error?.response?.status === 401 && this.onUnauthorized) {
          return this.handleUnauthorized(error)
        }

        let errorMessage: string

        if (error instanceof AxiosError && error.message.includes('timeout of')) {
          errorMessage = 'Operation timed out'
        } else {
          errorMessage =
            error.response?.data?.error?.message ||
            error.response?.data?.message ||
            error.response?.data ||
            error.message ||
            String(error)
        }

        // The envelope's machine-readable `code` is what the UI branches on; the
        // message is only for display. A rejection the API describes (say, an
        // unverified email) must not be flattened into an anonymous error here.
        const responseCode = error?.response?.data?.error?.code ?? error?.response?.data?.code
        const responseBoxId = error?.response?.data?.boxId
        const responseStatus = error?.response?.data?.statusCode
        const retryAfter = Number(error?.response?.headers?.['retry-after'])

        throw BoxliteError.fromString(String(errorMessage), {
          cause: error instanceof Error ? error : undefined,
          code: typeof responseCode === 'string' ? responseCode : undefined,
          retryAfterSeconds: Number.isSafeInteger(retryAfter) && retryAfter > 0 ? retryAfter : undefined,
          statusCode:
            typeof responseStatus === 'number'
              ? responseStatus
              : typeof error?.response?.status === 'number'
                ? error.response.status
                : undefined,
          boxId: typeof responseBoxId === 'string' && responseBoxId.length > 0 ? responseBoxId : undefined,
        })
      },
    )

    this.http = axiosInstance

    // Initialize APIs
    this._boxApi = new BoxApi(this.config, undefined, axiosInstance)
    this._userApi = new UsersApi(this.config, undefined, axiosInstance)
    this._apiKeyApi = new ApiKeysApi(this.config, undefined, axiosInstance)
    this._organizationsApi = new OrganizationsApi(this.config, undefined, axiosInstance)
    this._billingApi = new BillingApiClient(config.billingApiUrl || window.location.origin, accessToken)
    this._volumeApi = new VolumesApi(this.config, undefined, axiosInstance)
    this._imageApi = new ImagesApi(this.config, undefined, axiosInstance)
    this._registriesApi = new RegistriesApi(this.config, undefined, axiosInstance)
    this._auditApi = new AuditApi(this.config, undefined, axiosInstance)
    this._regionsApi = new RegionsApi(this.config, undefined, axiosInstance)
    this._runnersApi = new RunnersApi(this.config, undefined, axiosInstance)
    this._webhooksApi = new WebhooksApi(this.config, undefined, axiosInstance)
    this._usageApi = new CoreUsageApi(this.config, undefined, axiosInstance)

    if (config.analyticsApiUrl) {
      const analyticsConfig = new AnalyticsConfiguration({
        basePath: config.analyticsApiUrl,
        accessToken: accessToken,
        baseOptions: {
          baseURL: config.analyticsApiUrl,
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        },
      })
      this._analyticsUsageApi = new AnalyticsUsageApi(analyticsConfig, undefined, axiosInstance)
      this._analyticsTelemetryApi = new AnalyticsTelemetryApi(analyticsConfig, undefined, axiosInstance)
    } else {
      this._analyticsUsageApi = null
      this._analyticsTelemetryApi = null
    }
  }

  // Recovery is bounded to ONE re-login attempt per session: the first 401
  // drops the session and bounces to a fresh login (suppressing the error so
  // the user sees a loading state, not a dead-end screen); a 401 that persists
  // *after* that re-auth is surfaced as an error instead of bouncing forever.
  private async handleUnauthorized(error: unknown): Promise<never> {
    // De-dupe a concurrent 401 burst: only the first drives recovery, the rest
    // suspend on the in-flight redirect. Checked BEFORE the cross-reload marker
    // so a second concurrent 401 isn't misread as a failed post-reauth attempt.
    if (isHandlingUnauthorized) {
      return new Promise<never>(() => {})
    }

    if (reauthAlreadyAttempted()) {
      // We already sent the user through a fresh login this session and the new
      // token is still rejected (revoked user / wrong audience / backend bug).
      // Bouncing again would loop forever, so surface the failure.
      throw BoxliteError.fromString('Authentication failed after re-login. Please sign in again.', {
        cause: error instanceof Error ? error : undefined,
      })
    }

    isHandlingUnauthorized = true
    markReauthAttempted()
    try {
      // onUnauthorized clears the OIDC user; ApiProvider's effect then runs
      // signinRedirect, which navigates the page away. Awaited so a failed
      // start (e.g. a rejecting removeUser) surfaces an error instead of
      // hanging forever on the suspend below.
      await this.onUnauthorized?.()
    } catch (handlerError) {
      isHandlingUnauthorized = false
      clearReauthAttempted()
      throw new ReauthenticationStartError('Failed to start re-authentication. Please sign in again.', {
        cause: handlerError,
      })
    }

    // Suspend the caller (never-settling promise) so it shows the loading
    // state, not an error, while the redirect navigates the page away. Reached
    // only on a successfully-started re-auth.
    return new Promise<never>(() => {})
  }

  public async listDomains(organizationId: string): Promise<DomainList> {
    return (await this.http.get(`/v1/${encodeURIComponent(organizationId)}/domains`, this.v1Config())).data
  }

  public async claimDomain(organizationId: string, name: string): Promise<HeldDomain> {
    return (await this.http.post(`/v1/${encodeURIComponent(organizationId)}/domains`, { name }, this.v1Config())).data
  }

  public async listCustomDomains(org: string): Promise<CustomDomainList> {
    return (await this.http.get(`/organizations/${encodeURIComponent(org)}/custom-domains`, this.v1Config())).data
  }

  public async createCustomDomain(org: string, hostname: string): Promise<CustomDomain> {
    return (
      await this.http.post(`/organizations/${encodeURIComponent(org)}/custom-domains`, { hostname }, this.v1Config())
    ).data
  }

  public async verifyCustomDomain(org: string, id: string): Promise<CustomDomain> {
    return (
      await this.http.post(
        `/organizations/${encodeURIComponent(org)}/custom-domains/${encodeURIComponent(id)}/verify`,
        {},
        this.v1Config(),
      )
    ).data
  }

  public async prepareCustomDomain(org: string, id: string): Promise<CustomDomain> {
    return (
      await this.http.post(
        `/organizations/${encodeURIComponent(org)}/custom-domains/${encodeURIComponent(id)}/prepare`,
        {},
        this.v1Config(),
      )
    ).data
  }

  public async advanceCustomDomain(org: string, id: string): Promise<CustomDomain> {
    return (
      await this.http.post(
        `/organizations/${encodeURIComponent(org)}/custom-domains/${encodeURIComponent(id)}/advance`,
        {},
        this.v1Config(),
      )
    ).data
  }

  public async deleteCustomDomain(org: string, id: string): Promise<void> {
    await this.http.delete(
      `/organizations/${encodeURIComponent(org)}/custom-domains/${encodeURIComponent(id)}`,
      this.v1Config(),
    )
  }

  public async bindDomain(org: string, hostname: string, box: string, port: number): Promise<HeldDomain> {
    return (
      await this.http.put(
        `/v1/${encodeURIComponent(org)}/domains/${encodeURIComponent(hostname)}/target`,
        { type: 'box', box, port },
        this.v1Config(),
      )
    ).data
  }

  public async unbindDomain(org: string, hostname: string): Promise<void> {
    await this.http.delete(
      `/v1/${encodeURIComponent(org)}/domains/${encodeURIComponent(hostname)}/target`,
      this.v1Config(),
    )
  }

  /** Sets a box's inbound mode through the `/v1` route the CLI and SDKs use. */
  public async setBoxInboundMode(
    organizationId: string,
    boxId: string,
    mode: NetworkMode,
    signal?: AbortSignal,
  ): Promise<void> {
    await this.http.put(
      this.v1BoxPath(organizationId, boxId, '/network/inbound'),
      { mode },
      { ...this.v1Config(), timeout: 30_000, signal },
    )
  }

  /** The Console creates public tunnels only; private requests never reach the server. */
  public async prepareBoxTunnel(
    organizationId: string,
    boxId: string,
    port: number,
    isPublic: boolean,
    signal?: AbortSignal,
  ): Promise<TunnelDescriptor> {
    if (!Number.isInteger(port) || port < 1 || port > 65535)
      throw new TunnelRequestError('Enter a port from 1 to 65535.')
    if (!isPublic) throw new TunnelRequestError('Private tunnel creation is not available in the Console.')
    signal?.throwIfAborted()
    try {
      const response = await this.http.post<unknown>(
        this.v1BoxPath(organizationId, boxId, '/network/tunnel'),
        { isPublic },
        { ...this.v1Config(), params: { port }, signal, timeout: 30_000 },
      )
      return readTunnelDescriptor(response.data)
    } catch (error) {
      throw tunnelOperationError(error, 'create')
    }
  }

  /** Revocation remains available when the Box is stopped or inbound is disabled. */
  public async revokeBoxTunnel(
    organizationId: string,
    boxId: string,
    port: number,
    signal?: AbortSignal,
  ): Promise<void> {
    if (!Number.isInteger(port) || port < 1 || port > 65535)
      throw new TunnelRequestError('Enter a port from 1 to 65535.')
    try {
      await this.http.delete(this.v1BoxPath(organizationId, boxId, '/network/tunnel'), {
        ...this.v1Config(),
        params: { port },
        signal,
        timeout: 30_000,
      })
    } catch (error) {
      throw tunnelOperationError(error, 'revoke')
    }
  }

  /** Starts a login shell on a pseudo-terminal; returns its execution id. */
  public async startTerminalExec(organizationId: string, boxId: string): Promise<string> {
    const response = await this.http.post<{ execution_id: string }>(
      this.v1BoxPath(organizationId, boxId, '/exec'),
      { command: '/bin/sh', args: ['-c', LOGIN_SHELL], tty: true, env: { TERM: 'xterm-256color' } },
      this.v1Config(),
    )
    return response.data.execution_id
  }

  /**
   * The attach WebSocket URL for an execution, carrying a one-time ticket:
   * a browser cannot send `Authorization` on a WebSocket, so the ticket is
   * bought from the cloud API with the bearer and spent by the `/v1` upgrade.
   */
  public async terminalAttachUrl(organizationId: string, boxId: string, execId: string): Promise<string> {
    const executionPath = this.v1BoxPath(organizationId, boxId, `/executions/${encodeURIComponent(execId)}`)
    const { data } = await this._boxApi.createAttachTicket(boxId, { executionId: execId }, organizationId)
    const url = new URL(`${this.config.basePath}${executionPath}/attach`, window.location.origin)
    url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
    url.searchParams.set('ticket', data.ticket)
    return url.toString()
  }

  /** Ends an execution, so a terminal's shell does not wait for the runner's idle reaper. */
  public async killTerminalExec(organizationId: string, boxId: string, execId: string): Promise<void> {
    await this.http.delete(
      this.v1BoxPath(organizationId, boxId, `/executions/${encodeURIComponent(execId)}`),
      this.v1Config(),
    )
  }

  private v1BoxPath(organizationId: string, boxId: string, suffix: string): string {
    return `/v1/${encodeURIComponent(organizationId)}/boxes/${encodeURIComponent(boxId)}${suffix}`
  }

  /** App requests use the selected organization and the dashboard's existing bearer/session recovery. */
  public cloudApps(organizationId: string, onForbidden?: () => void) {
    const request = <T>(path: string, options: AxiosRequestConfig = {}) => {
      if (!organizationId) throw new Error('No organization selected')
      return this.http
        .request<T>({
          ...options,
          ...this.v1Config(),
          headers: { ...options.headers, ...this.v1Config().headers },
          url: `/v1/${encodeURIComponent(organizationId)}${path}`,
        })
        .catch((error) => {
          const status = error?.cause?.response?.status ?? error?.response?.status
          if (status === 403) onForbidden?.()
          throw error
        })
    }
    return {
      get: <T = unknown>(path: string, options?: AxiosRequestConfig) => request<T>(path, { ...options, method: 'GET' }),
      post: <T = unknown>(path: string, data?: unknown, options?: AxiosRequestConfig) =>
        request<T>(path, { ...options, method: 'POST', data }),
      put: <T = unknown>(path: string, data?: unknown, options?: AxiosRequestConfig) =>
        request<T>(path, { ...options, method: 'PUT', data }),
      delete: <T = unknown>(path: string, options?: AxiosRequestConfig) =>
        request<T>(path, { ...options, method: 'DELETE' }),
    }
  }

  /** `/v1` is spec-first and outside the generated client; same instance, so the same 401 handling. */
  private v1Config() {
    return { baseURL: this.config.basePath, headers: { Authorization: `Bearer ${this.config.accessToken}` } }
  }

  public setAccessToken(accessToken: string) {
    this.config.accessToken = accessToken
    this._billingApi.setAccessToken(accessToken)
    this.http.defaults.headers.common.Authorization = `Bearer ${accessToken}`
  }

  public get boxApi() {
    return this._boxApi
  }

  public get userApi() {
    return this._userApi
  }

  public get apiKeyApi() {
    return this._apiKeyApi
  }

  public get organizationsApi() {
    return this._organizationsApi
  }

  public get billingApi() {
    return this._billingApi
  }

  public get volumeApi() {
    return this._volumeApi
  }

  public get imageApi() {
    return this._imageApi
  }

  public get registriesApi() {
    return this._registriesApi
  }

  public get auditApi() {
    return this._auditApi
  }

  public get regionsApi() {
    return this._regionsApi
  }

  public get runnersApi() {
    return this._runnersApi
  }

  public get webhooksApi() {
    return this._webhooksApi
  }

  public get usageApi() {
    return this._usageApi
  }

  public get analyticsUsageApi() {
    return this._analyticsUsageApi
  }

  public get analyticsTelemetryApi() {
    return this._analyticsTelemetryApi
  }

  public async webhookRequest(method: string, url: string, data?: any) {
    // Use the existing axios instance that's already configured with interceptors
    const axiosInstance = axios.create({
      baseURL: this.config.basePath,
      headers: {
        ...activityHeaders,
        Authorization: `Bearer ${this.config.accessToken}`,
      },
    })

    return axiosInstance.request({
      method,
      url,
      data,
    })
  }

  public get axiosInstance() {
    return this.http
  }
}