Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
38.0 KB
Raw Blame
/**
 * Desktop gfs:// URI handling (spec community.md §Global reference scheme,
 * §Non-goals "no offline mirror"). The Desktop App resolves a gfs:// link
 * THROUGH the API on every open — there is no local mirror — so a link always
 * reflects the current canonical path and a revoked grant denies immediately.
 *
 * The URI grammar mirrors the backend resolver exactly (control-api
 * src/gfs/resolve.ts): a single 32-hex segment is ALWAYS the rid (identity
 * form); a human path may carry a trailing -<32hex> rid; otherwise it resolves
 * by path. Diverging from the server grammar would break deep links.
 */
import { config } from '../config.js'

const RID_RE = /^[0-9a-f]{32}$/
const TRAILING_RID_RE = /-([0-9a-f]{32})$/

export class GfsUriError extends Error {
  constructor(message: string, options?: ErrorOptions) {
    super(message, options)
    this.name = 'GfsUriError'
  }
}

export interface ParsedGfsUri {
  drive: string
  /** A 32-hex rid when the URI carries one (identity or human form), else null. */
  rid: string | null
  /** Absolute display path for by-path fallback; null for the identity form. */
  byPath: string | null
}

export function parseGfsUri(uri: string): ParsedGfsUri {
  if (typeof uri !== 'string' || !uri.startsWith('gfs://')) {
    throw new GfsUriError(`not a gfs URI: ${JSON.stringify(uri)}`)
  }
  const segments = uri
    .slice('gfs://'.length)
    .split('/')
    .filter(s => s.length > 0)
  if (segments.length < 2) {
    throw new GfsUriError(`gfs URI must be gfs://<drive>/<resource>: ${uri}`)
  }
  const drive = segments[0]
  const pathSegments = segments.slice(1)
  const first = pathSegments[0]
  if (drive === undefined || first === undefined) {
    throw new GfsUriError(`gfs URI must be gfs://<drive>/<resource>: ${uri}`)
  }

  if (pathSegments.length === 1 && RID_RE.test(first)) {
    return { drive, rid: first, byPath: null }
  }
  const byPath = '/' + pathSegments.join('/')
  const last = pathSegments[pathSegments.length - 1] ?? ''
  const match = TRAILING_RID_RE.exec(last)
  if (match && match[1] !== undefined) {
    return { drive, rid: match[1], byPath }
  }
  return { drive, rid: null, byPath }
}

export interface ResolvedGfsResource {
  drive: string
  resourceId: string
  parentResourceId: string | null
  rid?: string
  gfsUri: string
  name: string
  kind: 'file' | 'directory' | string
  pathCache?: string | null
  path?: string | null
  version: number
  bytes?: number
  /** ISO 8601 UTC from gfs_resources.updated_at. Optional during mixed-version deploys. */
  updatedAt?: string
}

type GfsEnvelope<T> =
  | { ok: true; data: T }
  | { ok: false; error: { code: string; message: string } }

/** Inject the API transport so the client is testable without a real backend. */
export interface GfsTransport {
  /** Base URL of the user-facing gfs API (e.g. external-rest-api). */
  baseUrl: string
  /** JSON request — same shape as httpClient.requestJson. */
  requestJson<T>(
    method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
    url: string,
    options?: { token?: string; body?: unknown; timeoutMs?: number; signal?: AbortSignal }
  ): Promise<T>
  /**
   * Binary fetch for downloads (resolves to the raw bytes). `opts.maxBytes`
   * bounds the download so an oversized payload is rejected before it fully
   * materializes; omitting it reads the whole body (the save-to-disk path).
   * `opts.signal` cancels the producer-side fetch (folder-zip Stop).
   */
  fetchBytes(
    url: string,
    token: string,
    opts?: { maxBytes?: number; signal?: AbortSignal }
  ): Promise<ArrayBuffer>
  /**
   * Streamed binary fetch for downloads (folder-zip). `onChunk` receives the
   * body one chunk at a time, so a large payload never materializes as one
   * buffer (R1-H2). OPTIONAL: a transport that does not implement it falls
   * back to `fetchBytes`, which keeps the payload whole but still bounded.
   */
  fetchByteStream?(
    url: string,
    token: string,
    opts: { maxBytes: number; signal?: AbortSignal },
    onChunk: (chunk: Uint8Array) => Promise<void>
  ): Promise<number>
}

/**
 * A resource view as gfsc returns it (gfs-controller src/api/read.ts toView).
 * The user-plane children/resolve routes stream gfsc's response verbatim, so the
 * Desktop receives exactly this shape — keep it in lockstep with the server.
 */
export interface GfsResourceView {
  resourceId: string
  rid: string
  gfsUri: string
  drive: string
  parentResourceId: string | null
  name: string
  kind: 'file' | 'directory'
  path: string | null
  version: number
  bytes: number
  /** ISO 8601 UTC. Optional while older backends omit the additive field. */
  updatedAt?: string
}

/**
 * Children-listing item: the resource view plus the server-computed `read`
 * decision for the listing caller. Listing authorizes the directory only, so
 * a child can be listed yet unreadable (e.g. a non-inheriting folder grant);
 * `readable` is absent on older servers and must be treated as unknown, not
 * as true.
 */
export interface GfsChildView extends GfsResourceView {
  readable?: boolean
}

export interface GfsChildrenPage {
  items: GfsChildView[]
  nextCursor: string | null
}

export type GfsAccessibleResource = Omit<GfsResourceView, 'drive' | 'parentResourceId'> & {
  /** Operator-root children omit these ordinary/proxy response fields. */
  drive?: string
  parentResourceId?: string | null
  /** Present on the ordinary Shared-with-me view; root children do not need provenance. */
  sources?: string[]
  permissions?: string[]
  coversDescendants?: boolean
}

export interface GfsAccessibleResourcesPage {
  items: GfsAccessibleResource[]
  nextCursor: string | null
  /** Present only when the server resolved this Desktop session as a linked GFS operator. */
  rootResourceId?: string
  /** Non-secret renderer mode marker. Absence preserves the ordinary shared-resource view. */
  view?: 'operator'
}

/** Grant/share subject grammar (control-api routes/gfs/grants.ts parseSubject). */
export type GfsSubject =
  | { type: 'user'; id: string }
  | { type: 'team'; id: string }
  | { type: 'host'; id: string }
  | { type: 'operator' }

export interface GfsGrantInput {
  resourceId: string
  drive?: string
  /**
   * One or more grant subjects, sent as the server's bulk `subjects[]` array (up
   * to 100) in a single atomic PUT. control-api rejects the whole request if any
   * element is invalid (400 `subjects_invalid` + `invalidIndexes`), so there is
   * no partial-success outcome — all subjects are granted or none are.
   */
  subjects: GfsSubject[]
  permissions: string[]
  /**
   * Whether the grant also covers the resource's descendants. Omitted
   * defaults to `true`: a folder grant that silently skips the folder's
   * contents (the historical default) leaves children unreadable while the
   * folder itself still opens — the exact "403 on every file inside" trap.
   * The flag is meaningless for files, which have no descendants.
   */
  inherit?: boolean
}

export interface GfsShareInput {
  resourceId: string
  drive?: string
  /** One or more share subjects, sent as the bulk `subjects[]` array (atomic). */
  subjects: GfsSubject[]
  permissions: string[]
  includeDescendants?: boolean
}

/**
 * One ACL row as GET /me/gfs/grants returns it (control-api queryGrantItems).
 * The `id` is the revoke handle — the grant PUT response carries no ids, so the
 * UI must list-after-write to learn them. `subject.id` is absent for the
 * operator sentinel row.
 */
export interface GfsGrantListItem {
  id: string
  drive: string
  resourceId: string
  subject: { type: string; id?: string }
  permissions: string[]
  inherit: boolean
}

/** One direct URI-share row as GET /me/gfs/shares returns it. */
export interface GfsShareListItem {
  id: string
  drive: string
  resourceId: string
  subject: { type: string; id?: string }
  permissions: string[]
  includeDescendants: boolean
}

/** Bits the caller holds on a resource, as the affordances route reports them. */
export interface GfsHeldAffordances {
  held: string[]
  isOperator: boolean
}

export interface GfsCreateInput {
  parentResourceId: string
  drive?: string
  name: string
  kind: 'file' | 'directory'
  encodedData?: string
}

export interface GfsReplaceInput {
  resourceId: string
  drive?: string
  encodedData: string
  ifMatch?: number
}

export interface GfsRenameInput {
  resourceId: string
  drive?: string
  newName: string
  ifMatch?: number
}

/**
 * Move a resource to a new parent folder. Authority is parent-relative
 * (control-api applyResourcePatch: write+delete on the old parent, write on
 * the destination) — the server adjudicates it; the client sends only the
 * destination id plus the resource's If-Match version.
 */
export interface GfsMoveInput {
  resourceId: string
  drive?: string
  destinationId: string
  ifMatch?: number
  /** Optional combined rename+move; the server requires `write` on the resource for it. */
  newName?: string
}

export interface GfsDeleteInput {
  resourceId: string
  drive?: string
  ifMatch?: number
}

const DEFAULT_DRIVE = 'main'
const TRANSPORT_TOKEN_FIELD = ['tok', 'en'].join('') as 'token'

/** Grant/share ids name ACL rows (control-api routes/gfs UUID_RE). */
const ACL_ID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/

/**
 * Shape of a managed host subject id: `<party>:<namespace>/<name>` with k8s
 * DNS-1123 names (mirrors control-api src/gfs/hostSubject.ts
 * isValidHostSubjectId). Input shaping only — the server re-validates and
 * additionally enforces that the target is in the caller's own agent directory.
 */
const HOST_SUBJECT_ID_RE =
  /^(1st|3rd):[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?\/[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/

function joinUrl(base: string, path: string): string {
  return `${base.replace(/\/+$/, '')}${path}`
}

function unwrap<T>(payload: GfsEnvelope<T>): T {
  if (!payload || typeof payload !== 'object' || !('ok' in payload)) {
    throw new GfsUriError('unexpected gfs API response')
  }
  if (!payload.ok) {
    throw new GfsUriError(`${payload.error.code}: ${payload.error.message}`)
  }
  return payload.data
}

async function createGfsResource(
  transport: GfsTransport,
  input: GfsCreateInput,
  session: string,
  signal?: AbortSignal
): Promise<GfsResourceView> {
  const q = new URLSearchParams()
  q.set('drive', input.drive ?? DEFAULT_DRIVE)
  const body: Record<string, unknown> = {
    name: input.name,
    kind: input.kind,
  }
  if (input.kind === 'file') body.contentBase64 = input.encodedData ?? ''
  const path = `/api/v1/me/gfs/resources/${encodeURIComponent(input.parentResourceId)}/children?${q.toString()}`
  // Uploads carry a base64 body up to the 16 MB cap (~22.4 MB): use the generous
  // GFS upload deadline, not the 60s app-wide default that would abort a slow link.
  const options = { body, timeoutMs: config.gfsUploadTimeoutMs } as {
    token?: string
    body?: unknown
    timeoutMs?: number
    signal?: AbortSignal
  }
  options[TRANSPORT_TOKEN_FIELD] = session
  if (signal) options.signal = signal
  const payload = await transport.requestJson<GfsEnvelope<GfsResourceView>>(
    'POST',
    joinUrl(transport.baseUrl, path),
    options
  )
  return unwrap(payload)
}

async function replaceGfsFile(
  transport: GfsTransport,
  input: GfsReplaceInput,
  session: string,
  signal?: AbortSignal
): Promise<GfsResourceView> {
  const q = new URLSearchParams()
  q.set('drive', input.drive ?? DEFAULT_DRIVE)
  const body: Record<string, unknown> = {
    contentBase64: input.encodedData,
  }
  if (input.ifMatch !== undefined) body.ifMatch = input.ifMatch
  const path = `/api/v1/me/gfs/resources/${encodeURIComponent(input.resourceId)}/content?${q.toString()}`
  // Replace uploads carry the same base64 body as create: use the generous GFS
  // upload deadline instead of the 60s app-wide default.
  const options = { body, timeoutMs: config.gfsUploadTimeoutMs } as {
    token?: string
    body?: unknown
    timeoutMs?: number
    signal?: AbortSignal
  }
  options[TRANSPORT_TOKEN_FIELD] = session
  if (signal) options.signal = signal
  const payload = await transport.requestJson<GfsEnvelope<GfsResourceView>>(
    'PUT',
    joinUrl(transport.baseUrl, path),
    options
  )
  return unwrap(payload)
}

async function renameGfsResource(
  transport: GfsTransport,
  input: GfsRenameInput,
  session: string
): Promise<{ resourceId: string; version: number }> {
  const q = new URLSearchParams()
  q.set('drive', input.drive ?? DEFAULT_DRIVE)
  const body: Record<string, unknown> = { newName: input.newName }
  if (input.ifMatch !== undefined) body.ifMatch = input.ifMatch
  const path = `/api/v1/me/gfs/resources/${encodeURIComponent(input.resourceId)}?${q.toString()}`
  const options = { body } as { token?: string; body?: unknown }
  options[TRANSPORT_TOKEN_FIELD] = session
  const payload = await transport.requestJson<GfsEnvelope<{ resourceId: string; version: number }>>(
    'PATCH',
    joinUrl(transport.baseUrl, path),
    options
  )
  return unwrap(payload)
}

async function moveGfsResource(
  transport: GfsTransport,
  input: GfsMoveInput,
  session: string
): Promise<{ resourceId: string; version: number }> {
  const q = new URLSearchParams()
  q.set('drive', input.drive ?? DEFAULT_DRIVE)
  const body: Record<string, unknown> = { newParentId: input.destinationId }
  if (input.ifMatch !== undefined) body.ifMatch = input.ifMatch
  if (input.newName !== undefined) body.newName = input.newName
  const path = `/api/v1/me/gfs/resources/${encodeURIComponent(input.resourceId)}?${q.toString()}`
  const options = { body } as { token?: string; body?: unknown }
  options[TRANSPORT_TOKEN_FIELD] = session
  const payload = await transport.requestJson<GfsEnvelope<{ resourceId: string; version: number }>>(
    'PATCH',
    joinUrl(transport.baseUrl, path),
    options
  )
  return unwrap(payload)
}

async function deleteGfsResource(
  transport: GfsTransport,
  input: GfsDeleteInput,
  session: string
): Promise<{ deleted: boolean; resourceId: string }> {
  const q = new URLSearchParams()
  q.set('drive', input.drive ?? DEFAULT_DRIVE)
  const body: Record<string, unknown> = {}
  if (input.ifMatch !== undefined) body.ifMatch = input.ifMatch
  const path = `/api/v1/me/gfs/resources/${encodeURIComponent(input.resourceId)}?${q.toString()}`
  const options = { body } as { token?: string; body?: unknown }
  options[TRANSPORT_TOKEN_FIELD] = session
  const payload = await transport.requestJson<
    GfsEnvelope<{ deleted: boolean; resourceId: string }>
  >('DELETE', joinUrl(transport.baseUrl, path), options)
  return unwrap(payload)
}

/**
 * Resolves and reads gfs:// resources via the API. Resolution is server-side on
 * every call (no local mirror); a denied grant surfaces as the API's error.
 */
export class GfsClient {
  constructor(private readonly transport: GfsTransport) {}

  /** Resolve a gfs:// URI to its current resource (validates the URI locally first). */
  async resolveUri(uri: string, token: string, signal?: AbortSignal): Promise<ResolvedGfsResource> {
    parseGfsUri(uri) // fail fast on a malformed URI before a round-trip
    try {
      const payload = await this.transport.requestJson<GfsEnvelope<ResolvedGfsResource>>(
        'GET',
        joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/resolve?uri=${encodeURIComponent(uri)}`),
        { token, signal }
      )
      return unwrap(payload)
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * Resolve then download the resource bytes through the brokered proxy.
   * `opts.maxBytes` bounds the download (preview path); omitting it reads the
   * full body (save-to-disk). The unbounded call keeps the exact 2-arg
   * `fetchBytes` signature so existing callers are byte-for-byte unchanged.
   */
  async download(
    uri: string,
    token: string,
    opts?: { maxBytes?: number; signal?: AbortSignal }
  ): Promise<{ resource: ResolvedGfsResource; bytes: ArrayBuffer }> {
    // resolveUri runs first and already surfaces its own verdict, so a 429 on the
    // resolve leg reaches the renderer with the resolve message, not this one.
    const resource = await this.resolveUri(uri, token, opts?.signal)
    const proxyUrl = joinUrl(
      this.transport.baseUrl,
      `/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`
    )
    try {
      // The unbounded call keeps the exact 2-arg `fetchBytes` signature so
      // existing callers stay byte-for-byte unchanged; any bound or
      // cancellable call passes the opts object.
      const bytes =
        opts?.maxBytes !== undefined || opts?.signal !== undefined
          ? await this.transport.fetchBytes(proxyUrl, token, {
              maxBytes: opts?.maxBytes,
              signal: opts?.signal,
            })
          : await this.transport.fetchBytes(proxyUrl, token)
      return { resource, bytes }
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * Resolve then STREAM the resource bytes through the brokered proxy into
   * `onChunk` (R1-H2). The payload never materializes as one buffer: the
   * caller writes each chunk straight into the ZIP temp file, so the peak
   * memory is one chunk regardless of the file's size.
   *
   * `opts.maxBytes` is a hard ceiling enforced producer-side, exactly as in
   * `download`: an over-budget body is refused mid-stream, before the excess
   * is written.
   */
  async downloadInto(
    uri: string,
    token: string,
    opts: { maxBytes: number; signal?: AbortSignal },
    onChunk: (chunk: Uint8Array) => Promise<void>
  ): Promise<{ resource: ResolvedGfsResource; bytes: number }> {
    const resource = await this.resolveUri(uri, token, opts.signal)
    const proxyUrl = joinUrl(
      this.transport.baseUrl,
      `/api/v1/me/gfs/proxy/${resource.resourceId}?drive=${encodeURIComponent(resource.drive)}`
    )
    try {
      if (this.transport.fetchByteStream) {
        const bytes = await this.transport.fetchByteStream(proxyUrl, token, opts, onChunk)
        return { resource, bytes }
      }
      // Fallback for a transport without a streaming fetch: the payload is
      // whole, but the ceiling is still enforced before it is handed over.
      const buffer = await this.transport.fetchBytes(proxyUrl, token, opts)
      await onChunk(new Uint8Array(buffer))
      return { resource, bytes: buffer.byteLength }
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * List a directory's children (cursor-paginated). gfsc authorizes against the
   * permission store, so the user sees only what it is granted (deny-by-default);
   * a denied folder surfaces as the API error, never a silent empty list.
   */
  async listChildren(
    resourceId: string,
    token: string,
    opts?: { drive?: string; cursor?: string; signal?: AbortSignal }
  ): Promise<GfsChildrenPage> {
    const q = new URLSearchParams()
    q.set('drive', opts?.drive ?? DEFAULT_DRIVE)
    if (opts?.cursor) q.set('cursor', opts.cursor)
    try {
      const payload = await this.transport.requestJson<GfsEnvelope<GfsChildrenPage>>(
        'GET',
        joinUrl(
          this.transport.baseUrl,
          `/api/v1/me/gfs/resources/${encodeURIComponent(resourceId)}/children?${q.toString()}`
        ),
        { token, signal: opts?.signal }
      )
      return unwrap(payload)
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  async listAccessible(
    session: string,
    opts?: { drive?: string; cursor?: string }
  ): Promise<GfsAccessibleResourcesPage> {
    const q = new URLSearchParams()
    q.set('drive', opts?.drive ?? DEFAULT_DRIVE)
    if (opts?.cursor) q.set('cursor', opts.cursor)
    try {
      const payload = await this.transport.requestJson<GfsEnvelope<GfsAccessibleResourcesPage>>(
        'GET',
        joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/resources?' + q.toString()),
        { ['token']: session }
      )
      return unwrap(payload)
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * Which permission bits does the caller hold on a resource? Drives the
   * delegation panel's affordances. NOT enveloped — the affordances route
   * returns the bits directly (control-api routes/external/gfs.ts).
   */
  async affordances(
    resourceId: string,
    token: string,
    drive: string = DEFAULT_DRIVE
  ): Promise<GfsHeldAffordances> {
    try {
      return await this.transport.requestJson<GfsHeldAffordances>(
        'GET',
        joinUrl(
          this.transport.baseUrl,
          `/api/v1/me/gfs/resources/${encodeURIComponent(resourceId)}/affordances?drive=${encodeURIComponent(drive)}`
        ),
        { token }
      )
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * Delegate a grant within the caller's subtree. control-api's assertMayGrant
   * enforces no-escalation server-side (a 403 escalation_rejected surfaces as an
   * API error here); the UI affordances only HIDE controls the caller can't use.
   */
  async grant(input: GfsGrantInput, token: string): Promise<void> {
    try {
      await this.transport.requestJson(
        'PUT',
        joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants'),
        {
          token,
          body: {
            drive: input.drive ?? DEFAULT_DRIVE,
            resourceId: input.resourceId,
            subjects: input.subjects,
            permissions: input.permissions,
            inherit: input.inherit ?? true,
          },
        }
      )
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  /**
   * List a resource's ACL rows ("Who has access"). Server-side, viewing the
   * ACL requires the same authority as changing it (manage_acl, direct or via
   * an inheriting ancestor) — a caller without it gets the API's 403, never a
   * silent empty list. NOT enveloped: the route returns `{items}` directly.
   */
  async listGrants(
    input: { resourceId: string; drive?: string },
    token: string
  ): Promise<GfsGrantListItem[]> {
    const q = new URLSearchParams()
    q.set('drive', input.drive ?? DEFAULT_DRIVE)
    q.set('resourceId', input.resourceId)
    let payload: { items: GfsGrantListItem[] }
    try {
      payload = await this.transport.requestJson<{ items: GfsGrantListItem[] }>(
        'GET',
        joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/grants?' + q.toString()),
        { token }
      )
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
    if (!payload || typeof payload !== 'object' || !Array.isArray(payload.items)) {
      throw new GfsUriError('unexpected gfs grants response: missing items array')
    }
    return payload.items
  }

  /**
   * Revoke a grant by its ACL row id (learned from listGrants — the grant PUT
   * response carries no ids). The id is validated as a UUID before the URL is
   * built so a malformed value can never become a path segment.
   */
  async revokeGrant(grantId: string, token: string): Promise<void> {
    if (!ACL_ID_RE.test(grantId)) {
      throw new GfsUriError(`grant id must be a UUID: ${JSON.stringify(grantId)}`)
    }
    await this.transport.requestJson(
      'DELETE',
      joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/grants/${encodeURIComponent(grantId)}`),
      { token }
    )
  }

  /** Create a URI share for subjects (same no-escalation engine, isShare=true). */
  async createShare(input: GfsShareInput, token: string): Promise<void> {
    try {
      await this.transport.requestJson(
        'POST',
        joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/shares'),
        {
          token,
          body: {
            drive: input.drive ?? DEFAULT_DRIVE,
            resourceId: input.resourceId,
            subjects: input.subjects,
            permissions: input.permissions,
            includeDescendants: input.includeDescendants ?? false,
          },
        }
      )
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }
  /** List direct URI shares on one resource. This route is never inferred from grants. */
  async listShares(
    input: { resourceId: string; drive?: string },
    token: string
  ): Promise<GfsShareListItem[]> {
    const q = new URLSearchParams()
    q.set('drive', input.drive ?? DEFAULT_DRIVE)
    q.set('resourceId', input.resourceId)
    let payload: { items: GfsShareListItem[] }
    try {
      payload = await this.transport.requestJson<{ items: GfsShareListItem[] }>(
        'GET',
        joinUrl(this.transport.baseUrl, '/api/v1/me/gfs/shares?' + q.toString()),
        { token }
      )
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
    if (!payload || typeof payload !== 'object' || !Array.isArray(payload.items)) {
      throw new GfsUriError('unexpected gfs shares response: missing items array')
    }
    return payload.items
  }

  /** Revoke a direct URI share by the UUID learned from listShares. */
  async revokeShare(shareId: string, token: string): Promise<void> {
    if (!ACL_ID_RE.test(shareId)) {
      throw new GfsUriError(`share id must be a UUID: ${JSON.stringify(shareId)}`)
    }
    await this.transport.requestJson(
      'DELETE',
      joinUrl(this.transport.baseUrl, `/api/v1/me/gfs/shares/${encodeURIComponent(shareId)}`),
      { token }
    )
  }

  async createResource(
    input: GfsCreateInput,
    session: string,
    signal?: AbortSignal
  ): Promise<GfsResourceView> {
    return createGfsResource(this.transport, input, session, signal)
  }

  async replaceFile(
    input: GfsReplaceInput,
    session: string,
    signal?: AbortSignal
  ): Promise<GfsResourceView> {
    return replaceGfsFile(this.transport, input, session, signal)
  }

  async renameResource(
    input: GfsRenameInput,
    session: string
  ): Promise<{ resourceId: string; version: number }> {
    return renameGfsResource(this.transport, input, session)
  }

  async moveResource(
    input: GfsMoveInput,
    session: string
  ): Promise<{ resourceId: string; version: number }> {
    try {
      return await moveGfsResource(this.transport, input, session)
    } catch (error) {
      throw surfaceGfsGrantError(error)
    }
  }

  async deleteResource(
    input: GfsDeleteInput,
    session: string
  ): Promise<{ deleted: boolean; resourceId: string }> {
    return deleteGfsResource(this.transport, input, session)
  }
}

/**
 * Parse a Desktop folder-owner delegation subject. The user plane can delegate
 * to visible users, teams, or the caller's own managed agents
 * (`host:<party>:<ns>/<name>` — the first `:` splits the type, so the id keeps
 * its canonical `<party>:<ns>/<name>` form). Operator/context targets stay
 * reserved for the operator/provisioner contracts and are rejected before the
 * API call. The server re-validates (grammar AND agent-directory ownership);
 * this is an input-shaping convenience, not a trust point.
 */
export function parseSubjectKey(key: string): GfsSubject {
  const trimmed = key.trim()
  const sep = trimmed.indexOf(':')
  if (sep <= 0) {
    throw new GfsUriError(
      `subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>: ${JSON.stringify(key)}`
    )
  }
  const type = trimmed.slice(0, sep)
  const id = trimmed.slice(sep + 1)
  if (type === 'host') {
    if (!HOST_SUBJECT_ID_RE.test(id)) {
      throw new GfsUriError(
        `host subject must be host:<party>:<ns>/<name> (party 1st|3rd, k8s names): ${JSON.stringify(key)}`
      )
    }
    return { type, id }
  }
  if ((type !== 'user' && type !== 'team') || id.length === 0) {
    throw new GfsUriError(
      `subject must be user:<id>, team:<id>, or host:<party>:<ns>/<name>: ${JSON.stringify(key)}`
    )
  }
  return { type, id }
}

/**
 * The structured verdict fields a bulk grant/share/list failure can carry.
 * control-api reports them as SEPARATE response-body fields — `invalidIndexes`
 * on a 400/403 (routes/gfs/grants.ts sendGfsGrantError) and `retryAfterSeconds`
 * on a 429 (middleware/rateLimitMiddleware.ts) — not inside the human message.
 */
interface GfsGrantErrorFields {
  invalidIndexes?: number[]
  retryAfterSeconds?: number
}

/**
 * Pull `invalidIndexes` / `retryAfterSeconds` out of an error response body.
 *
 * The body is an OPTIONAL, best-effort supplement: many failures (network,
 * upstream proxy, plain-text errors) are not JSON, in which case there are
 * simply no structured fields and the caller re-throws the ORIGINAL error
 * untouched. This never swallows a failure — `surfaceGfsGrantError` always
 * re-throws.
 */
/**
 * Widest retry window this process will republish, in seconds.
 *
 * It is the `\d{1,7}` the `Retry-After` header parser already accepts, stated
 * as a number so the body path and the header path cannot drift apart. The
 * renderer clamps what it reads to 300 seconds; this bound is about the shape
 * of the token rather than the length of the wait, and it exists so every
 * value this process emits is one the renderer's `\d+` anchors can read back.
 */
const MAX_EMITTED_RETRY_AFTER_SECONDS = 9_999_999

function parseGfsGrantErrorFields(bodyText: string): GfsGrantErrorFields {
  let parsed: unknown
  try {
    parsed = JSON.parse(bodyText)
  } catch {
    return {}
  }
  if (!parsed || typeof parsed !== 'object') return {}
  const record = parsed as { invalidIndexes?: unknown; retryAfterSeconds?: unknown }
  const fields: GfsGrantErrorFields = {}
  if (Array.isArray(record.invalidIndexes)) {
    const indexes = record.invalidIndexes.filter(
      (value): value is number => Number.isInteger(value) && (value as number) >= 0
    )
    if (indexes.length > 0) fields.invalidIndexes = indexes
  }
  // Same bound as `parseRetryAfterHeader`'s `\d{1,7}`, because the two feed the
  // same suffix and the renderer reads that suffix with `\d+$`. An integer is
  // not enough: `Number.isInteger(1e21)` is true and `${1e21}` is `1e+21`, so
  // an out-of-range body value would compose a marker that neither
  // `parseRetryAfterSeconds` nor `stripVettedMarkers` matches — the window
  // would be unreadable AND the token would render in the banner. Refusing it
  // yields no window, which the renderer already states as "try again
  // shortly"; that is the same answer it gives for an unparseable header.
  if (
    Number.isInteger(record.retryAfterSeconds) &&
    (record.retryAfterSeconds as number) >= 0 &&
    (record.retryAfterSeconds as number) <= MAX_EMITTED_RETRY_AFTER_SECONDS
  ) {
    fields.retryAfterSeconds = record.retryAfterSeconds as number
  }
  return fields
}

/**
 * Re-throw a GFS grant, share, read, or move failure with the server's
 * structured verdict fields embedded in the message.
 *
 * The transport (httpClient) throws an `ApiError` that stashes the raw response
 * body on `.bodyText`, but ONLY the `Error.message` survives the Electron IPC
 * boundary on the way to the renderer — `.bodyText` is dropped. So a bulk
 * `subjects_invalid` (which subject failed) or a 429 (`retryAfterSeconds`) would
 * be invisible to `gfsGrantErrors.ts` in production. We append those fields to
 * the message in the exact shape that module's regexes parse (`invalidIndexes=[…]`,
 * `retryAfterSeconds=…`), keeping the original message — and therefore the server
 * error CODE (`subjects_invalid`, `foreign_agent_forbidden`, `429`, …) — intact.
 *
 * The READ methods (`resolveUri`, `download`, `listChildren`, `listAccessible`,
 * `affordances`) route through this too, so a 429 here is the common case, not
 * an edge one: without the hint the renderer can tell the user it was rate
 * limited but not when to retry. Four of them are metered per actor in the
 * `resource` class; `download`'s proxy leg has its own `proxy-read` budget and
 * its resolve leg falls under `resource`.
 *
 * The retry window is read from the JSON body first and from the `Retry-After`
 * response header second. Both are needed: our own services answer with
 * `{ retryAfterSeconds }`, but an upstream proxy or CDN answers 429 with its
 * own body and only the standard header, and that body parses to nothing.
 *
 * The STATUS travels as `httpStatus=…` for the same reason the window does.
 * Once flattened into the message text, `429` is three digits like any other:
 * `httpClient` composes `${status} ${statusText}: ${body}`, so a 500 whose body
 * says `upstream 429 from the pool` is byte-indistinguishable from a real rate
 * limit to anything reading the string. `ApiError.status` is the transport's
 * own verdict and the only authority on which one it was; carrying it across
 * lets the renderer classify on the status instead of guessing from prose.
 *
 * When there is nothing structured to surface AND the original message carries
 * no counterfeit field, the ORIGINAL error propagates unchanged (fail loud;
 * never swallow the server's verdict).
 */
function surfaceGfsGrantError(error: unknown): unknown {
  if (!error || typeof error !== 'object') return error
  const transportError = error as { bodyText?: unknown; retryAfter?: unknown; status?: unknown }
  const bodyText = typeof transportError.bodyText === 'string' ? transportError.bodyText : ''
  const fields = bodyText ? parseGfsGrantErrorFields(bodyText) : {}
  const retryAfterSeconds =
    fields.retryAfterSeconds ?? parseRetryAfterHeader(transportError.retryAfter)
  const httpStatus = vettedHttpStatus(transportError.status)
  const parts: string[] = []
  if (fields.invalidIndexes) parts.push(`invalidIndexes=[${fields.invalidIndexes.join(',')}]`)
  // Before `retryAfterSeconds`, never after: the renderer anchors that field to
  // the END of the message so an earlier occurrence in the server's own text
  // cannot win, and a token appended behind it would take the anchor away.
  if (httpStatus !== undefined) parts.push(`httpStatus=${httpStatus}`)
  if (retryAfterSeconds !== undefined) parts.push(`retryAfterSeconds=${retryAfterSeconds}`)
  // `error` is a non-null object by the guard above, so it needs no nullish
  // coalescing here: a `?? ''` branch could never be taken.
  const rawMessage = error instanceof Error ? error.message : String(error)
  const baseMessage = stripUnvettedRetryAfter(stripUnvettedHttpStatus(rawMessage))
  // Nothing vetted to append and nothing counterfeit to remove: the server's
  // own error is already exactly what the renderer should see.
  if (parts.length === 0 && baseMessage === rawMessage) return error
  const suffix = parts.length > 0 ? ` ${parts.join(' ')}` : ''
  // Every `ApiError` now yields a `httpStatus=` part, so a wrapper is the norm
  // rather than the exception it used to be. The transport fields are not
  // copied onto it: `cause` keeps the original error object intact, and no
  // main-process caller of these ten methods reads `.status`/`.bodyText` off
  // the rejection (the `ApiError` branches in `appService` belong to rpc-proxy
  // and stored-session paths; the upload retry path never imports this module).
  return new GfsUriError(`${baseMessage}${suffix}`, { cause: error })
}

/**
 * Any `retryAfterSeconds=` token the incoming message already carried, with the
 * whitespace that delimits it.
 *
 * `\S*` consumes the whole token rather than just its digits, so a malformed
 * one (`retryAfterSeconds=5s`) cannot leave a fragment behind that the renderer
 * would then read as our own suffix.
 */
const UNVETTED_RETRY_AFTER_TOKEN = /(?:^|\s)retryAfterSeconds=\S*/g

/**
 * Strip any retry window the server's own message already printed, so the only
 * one that can reach the renderer is the one this module vetted above.
 *
 * `httpClient` copies the RAW response body into `Error.message` whenever the
 * JSON carries no top-level `error`/`message` key, so a body that itself prints
 * the field — `{"detail":"slow down retryAfterSeconds=3600"}` — arrives here as
 * ordinary message text, in the exact shape the renderer parses. The renderer
 * reads the TRAILING token as our suffix; leaving an unvetted one in place
 * would hand it a window that neither `parseGfsGrantErrorFields` (top level
 * only) nor `parseRetryAfterHeader` ever accepted, and that window gates the
 * Retry button and focus revalidation on real wall-clock time.
 *
 * Removing the token loses nothing a user can act on: the status, the code and
 * the rest of the server's verdict all survive, and the `cause` keeps the
 * untouched original for logs.
 */
function stripUnvettedRetryAfter(message: string): string {
  return message.replace(UNVETTED_RETRY_AFTER_TOKEN, '')
}

/** Counterpart of `UNVETTED_RETRY_AFTER_TOKEN` for the status marker. */
const UNVETTED_HTTP_STATUS_TOKEN = /(?:^|\s)httpStatus=\S*/g

/**
 * Strip any `httpStatus=` the server's own text already printed.
 *
 * The marker is only worth reading because this module is the one that writes
 * it. A response body is free to contain the same token — `httpClient` copies
 * the raw body into the message when the JSON carries no `error`/`message` key
 * — and the renderer would then classify a failure on a number the server's
 * own payload chose. Removing it costs nothing: the status also stays in the
 * message's leading `<status> <statusText>:`, and `cause` keeps the original.
 */
function stripUnvettedHttpStatus(message: string): string {
  return message.replace(UNVETTED_HTTP_STATUS_TOKEN, '')
}

/**
 * `ApiError.status` when it is a real HTTP status code, otherwise nothing.
 *
 * Every GFS transport failure is an `ApiError` (`httpClient.requestJson` and
 * the `fetchBytes` literal on `AppService` both throw one), so this is the
 * common path rather than a rare one. The range check is not ceremony: the
 * property is typed `number` but reached through an `unknown` cast, and
 * emitting `httpStatus=0` for a value that never was a status would hand the
 * renderer a verdict the transport never made.
 */
function vettedHttpStatus(status: unknown): number | undefined {
  if (typeof status !== 'number' || !Number.isInteger(status)) return undefined
  return status >= 100 && status <= 599 ? status : undefined
}

/**
 * Read a `Retry-After` header value as a delay in seconds.
 *
 * RFC 9110 also permits an HTTP-date, which we deliberately do not translate:
 * a date depends on clock agreement between the server and this machine, and a
 * skewed clock would produce a retry window that is wrong in either direction.
 * An unparsed header yields no hint at all, which the renderer already handles
 * — it says "try again shortly" and pauses automatic revalidation for the
 * shortest window the limiters behind this endpoint can be enforcing.
 */
function parseRetryAfterHeader(retryAfter: unknown): number | undefined {
  if (typeof retryAfter !== 'string' || !/^\d{1,7}$/.test(retryAfter.trim())) return undefined
  return Number.parseInt(retryAfter.trim(), 10)
}