{"version":3,"file":"cli.mjs","names":["computeExpiresAt","loadYaml"],"sources":["../src/core/errors.ts","../src/core/credentials.ts","../src/core/browser.ts","../src/core/help.ts","../src/core/http.ts","../src/core/tokens.ts","../src/core/utils.ts","../src/commands/auth.ts","../src/commands/config.ts","../src/commands/dev.ts","../src/commands/dashboard.ts","../src/core/sse.ts","../src/commands/stream.ts","../src/commands/prompt.ts","../src/core/version.ts","../src/commands/version.ts","../src/core/output.ts","../src/cli.ts"],"sourcesContent":["export enum ExitCode {\n  Success = 0,\n  InternalError = 1,\n  InvalidArguments = 2,\n  AuthRequired = 3,\n  Forbidden = 4,\n  NotFound = 5,\n  Conflict = 6,\n  RateLimited = 7,\n  UpstreamError = 8,\n  NetworkError = 9,\n}\n\nexport interface CliErrorOptions {\n  hint?: string;\n  details?: unknown;\n  status?: number;\n  cause?: unknown;\n}\n\nexport class CliError extends Error {\n  readonly code: string;\n  readonly exitCode: ExitCode;\n  readonly hint?: string;\n  readonly details?: unknown;\n  readonly status?: number;\n\n  constructor(code: string, message: string, exitCode: ExitCode, options: CliErrorOptions = {}) {\n    super(message, { cause: options.cause });\n    this.name = \"CliError\";\n    this.code = code;\n    this.exitCode = exitCode;\n    this.hint = options.hint;\n    this.details = options.details;\n    this.status = options.status;\n  }\n}\n\nexport function isCliError(error: unknown): error is CliError {\n  return error instanceof CliError;\n}\n\nexport function toCliError(error: unknown): CliError {\n  if (error instanceof CliError) {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return new CliError(\"INTERNAL\", error.message, ExitCode.InternalError, {\n      cause: error,\n    });\n  }\n\n  return new CliError(\"INTERNAL\", \"Unknown error\", ExitCode.InternalError, {\n    details: error,\n  });\n}\n\nexport function mapHttpStatusToExitCode(status: number): ExitCode {\n  if (status === 400) {\n    return ExitCode.InvalidArguments;\n  }\n  if (status === 401) {\n    return ExitCode.AuthRequired;\n  }\n  if (status === 403) {\n    return ExitCode.Forbidden;\n  }\n  if (status === 404) {\n    return ExitCode.NotFound;\n  }\n  if (status === 409) {\n    return ExitCode.Conflict;\n  }\n  if (status === 429) {\n    return ExitCode.RateLimited;\n  }\n  if (status >= 500) {\n    return ExitCode.UpstreamError;\n  }\n  return ExitCode.InternalError;\n}\n\nexport function fromHttpStatus(\n  status: number,\n  message: string,\n  options: Omit<CliErrorOptions, \"status\"> = {},\n): CliError {\n  return new CliError(\n    `HTTP_${status}`,\n    message,\n    mapHttpStatusToExitCode(status),\n    {\n      ...options,\n      status,\n    },\n  );\n}\n","import { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { CliError, ExitCode } from \"./errors\";\n\nexport const DEFAULT_DASHBOARD_BASE_URL = \"https://streams.loro.dev\";\nexport const DEFAULT_GATEWAY_BASE_URL = \"https://streams-api.loro.dev\";\n\nexport type AccessTokenAudience = \"dashboard\" | \"gateway\";\n\nexport interface StoredAccessToken {\n  token: string;\n  expiresAt?: string;\n}\n\nexport interface StoredAuth {\n  type: \"refresh_token\";\n  refreshToken: string;\n  accessTokens?: Partial<Record<AccessTokenAudience, StoredAccessToken>>;\n}\n\nexport interface LoroProfile {\n  dashboardBaseUrl: string;\n  gatewayBaseUrl: string;\n  activeOrgId?: string;\n  auth?: StoredAuth;\n}\n\nexport interface CredentialsFile {\n  version: 1;\n  currentProfile: string;\n  profiles: Record<string, LoroProfile>;\n}\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** Where an effective base URL came from, so errors can say what to change. */\nexport type BaseUrlSource =\n  | { kind: \"profile\"; profile: string; field: \"dashboardBaseUrl\" | \"gatewayBaseUrl\" }\n  | { kind: \"env\"; name: \"LORO_DASHBOARD_URL\" | \"LORO_GATEWAY_URL\" }\n  | { kind: \"flag\"; name: string };\n\nfunction describeSource(source: BaseUrlSource): string {\n  switch (source.kind) {\n    case \"profile\":\n      return `profile \"${source.profile}\" ${source.field}`;\n    case \"env\":\n      return `environment variable ${source.name}`;\n    case \"flag\":\n      return source.name;\n  }\n}\n\nfunction fixHint(source: BaseUrlSource): string {\n  const optIn = \"or set LORO_ALLOW_INSECURE_HTTP=1 if this host is on a trusted network\";\n  switch (source.kind) {\n    case \"profile\": {\n      const flag = source.field === \"dashboardBaseUrl\" ? \"--dashboard-url\" : \"--gateway-url\";\n      return `Run \\`loro config set --profile ${source.profile} ${flag} https://...\\`, ${optIn}.`;\n    }\n    case \"env\":\n      return `Set ${source.name} to an https:// URL (or unset it), ${optIn}.`;\n    case \"flag\":\n      return `Pass an https:// URL to ${source.name}, ${optIn}.`;\n  }\n}\n\n/**\n * Refresh tokens, access tokens and API keys are only sent over https, or over\n * plain http to loopback (local dev). `LORO_ALLOW_INSECURE_HTTP=1` is the\n * explicit opt-in for other plain-http hosts (e.g. a LAN dev stack).\n *\n * Call this immediately before sending credentials, with the effective URL\n * actually used. Loading/inspecting configuration never applies it, so a\n * stored plain-http profile can always be listed, repaired or logged out.\n */\nexport function assertCredentialTransport(url: string, source: BaseUrlSource): void {\n  let parsed: URL;\n  try {\n    parsed = new URL(url);\n  } catch {\n    throw new CliError(\n      \"INVALID_URL\",\n      `Invalid URL ${JSON.stringify(url)} from ${describeSource(source)}`,\n      ExitCode.InvalidArguments,\n      { hint: fixHint(source) },\n    );\n  }\n  if (parsed.protocol === \"https:\") return;\n  if (parsed.protocol === \"http:\") {\n    if (LOOPBACK_HOSTS.has(parsed.hostname) || process.env.LORO_ALLOW_INSECURE_HTTP === \"1\") {\n      return;\n    }\n    throw new CliError(\n      \"INSECURE_URL\",\n      `Refusing to send credentials over plain http to ${parsed.host} (from ${describeSource(source)})`,\n      ExitCode.InvalidArguments,\n      { hint: fixHint(source) },\n    );\n  }\n  throw new CliError(\n    \"INVALID_URL\",\n    `Unsupported URL scheme ${parsed.protocol} from ${describeSource(source)}`,\n    ExitCode.InvalidArguments,\n    { hint: fixHint(source) },\n  );\n}\n\n/** Effective dashboard/gateway URL source for a profile after env overrides. */\nexport function profileUrlSource(\n  profileName: string,\n  target: \"dashboard\" | \"gateway\",\n): BaseUrlSource {\n  const envName = target === \"dashboard\" ? \"LORO_DASHBOARD_URL\" : \"LORO_GATEWAY_URL\";\n  if (process.env[envName]) {\n    return { kind: \"env\", name: envName };\n  }\n  return {\n    kind: \"profile\",\n    profile: profileName,\n    field: target === \"dashboard\" ? \"dashboardBaseUrl\" : \"gatewayBaseUrl\",\n  };\n}\n\n/** Lenient form used when reading stored profiles and env overrides. */\nfunction trimBaseUrl(url: string): string {\n  const trimmed = url.trim();\n  if (trimmed.length === 0) {\n    throw new CliError(\"INVALID_URL\", \"Base URL cannot be empty\", ExitCode.InvalidArguments);\n  }\n  return trimmed.endsWith(\"/\") ? trimmed.slice(0, -1) : trimmed;\n}\n\n/**\n * Validate a base URL supplied as new input (`config set`, `--host`):\n * non-empty, parseable, http(s), trailing slash removed. Transport policy is\n * separate (`assertCredentialTransport`).\n */\nexport function normalizeBaseUrl(url: string): string {\n  const normalized = trimBaseUrl(url);\n  let parsed: URL;\n  try {\n    parsed = new URL(normalized);\n  } catch {\n    throw new CliError(\"INVALID_URL\", `Invalid base URL: ${normalized}`, ExitCode.InvalidArguments);\n  }\n  if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n    throw new CliError(\n      \"INVALID_URL\",\n      `Base URL must use http:// or https://: ${normalized}`,\n      ExitCode.InvalidArguments,\n    );\n  }\n  return normalized;\n}\n\nexport function defaultProfile(): LoroProfile {\n  return {\n    dashboardBaseUrl: DEFAULT_DASHBOARD_BASE_URL,\n    gatewayBaseUrl: DEFAULT_GATEWAY_BASE_URL,\n  };\n}\n\nexport function defaultCredentials(): CredentialsFile {\n  return {\n    version: 1,\n    currentProfile: \"default\",\n    profiles: {\n      default: defaultProfile(),\n    },\n  };\n}\n\nexport function getCredentialsPath(): string {\n  if (process.platform === \"win32\") {\n    const appData = process.env.APPDATA;\n    if (!appData) {\n      throw new CliError(\n        \"CONFIG_PATH_ERROR\",\n        \"APPDATA is not set on Windows\",\n        ExitCode.InternalError,\n      );\n    }\n    return join(appData, \"loro\", \"credentials.json\");\n  }\n\n  const xdgConfigHome = process.env.XDG_CONFIG_HOME;\n  if (xdgConfigHome && xdgConfigHome.length > 0) {\n    return join(xdgConfigHome, \"loro\", \"credentials.json\");\n  }\n\n  return join(homedir(), \".config\", \"loro\", \"credentials.json\");\n}\n\nfunction coerceStringField(\n  value: unknown,\n  fieldName: string,\n  required: boolean,\n): string | undefined {\n  if (value == null) {\n    if (required) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        `credentials.${fieldName} is required`,\n        ExitCode.InvalidArguments,\n      );\n    }\n    return undefined;\n  }\n\n  if (typeof value !== \"string\") {\n    throw new CliError(\n      \"INVALID_CREDENTIALS\",\n      `credentials.${fieldName} must be a string`,\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return value;\n}\n\nfunction parseProfile(input: unknown): LoroProfile {\n  if (typeof input !== \"object\" || input === null) {\n    throw new CliError(\n      \"INVALID_CREDENTIALS\",\n      \"Invalid profile entry in credentials file\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const record = input as Record<string, unknown>;\n  const dashboardBaseUrl = trimBaseUrl(\n    coerceStringField(record.dashboardBaseUrl, \"dashboardBaseUrl\", true)!,\n  );\n  const gatewayBaseUrl = trimBaseUrl(\n    coerceStringField(record.gatewayBaseUrl, \"gatewayBaseUrl\", true)!,\n  );\n\n  const profile: LoroProfile = {\n    dashboardBaseUrl,\n    gatewayBaseUrl,\n  };\n\n  const activeOrgId = coerceStringField(record.activeOrgId, \"activeOrgId\", false);\n  if (activeOrgId) {\n    profile.activeOrgId = activeOrgId;\n  }\n\n  if (record.auth != null) {\n    if (typeof record.auth !== \"object\") {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"credentials.auth must be an object\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const auth = record.auth as Record<string, unknown>;\n    const type = coerceStringField(auth.type, \"auth.type\", true);\n    if (type !== \"refresh_token\") {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        `Unsupported auth type: ${type}`,\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const refreshToken = coerceStringField(auth.refreshToken, \"auth.refreshToken\", true)!;\n    const accessTokens: Partial<Record<AccessTokenAudience, StoredAccessToken>> = {};\n\n    const accessTokensRaw = auth.accessTokens;\n    if (accessTokensRaw != null) {\n      if (typeof accessTokensRaw !== \"object\") {\n        throw new CliError(\n          \"INVALID_CREDENTIALS\",\n          \"credentials.auth.accessTokens must be an object\",\n          ExitCode.InvalidArguments,\n        );\n      }\n\n      const accessTokensRecord = accessTokensRaw as Record<string, unknown>;\n      const parseAudienceEntry = (audience: AccessTokenAudience): void => {\n        const rawEntry = accessTokensRecord[audience];\n        if (rawEntry == null) {\n          return;\n        }\n        if (typeof rawEntry !== \"object\") {\n          throw new CliError(\n            \"INVALID_CREDENTIALS\",\n            `credentials.auth.accessTokens.${audience} must be an object`,\n            ExitCode.InvalidArguments,\n          );\n        }\n        const entry = rawEntry as Record<string, unknown>;\n        const token = coerceStringField(\n          entry.token,\n          `auth.accessTokens.${audience}.token`,\n          true,\n        )!;\n        const expiresAt = coerceStringField(\n          entry.expiresAt,\n          `auth.accessTokens.${audience}.expiresAt`,\n          false,\n        );\n        accessTokens[audience] = {\n          token,\n          expiresAt,\n        };\n      };\n\n      parseAudienceEntry(\"dashboard\");\n      parseAudienceEntry(\"gateway\");\n    }\n\n    // Backward compatibility with legacy single-token shape.\n    const legacyAccessToken = coerceStringField(auth.accessToken, \"auth.accessToken\", false);\n    if (legacyAccessToken) {\n      const rawLegacyAudience = coerceStringField(\n        auth.accessTokenAudience,\n        \"auth.accessTokenAudience\",\n        false,\n      );\n      if (\n        rawLegacyAudience != null &&\n        rawLegacyAudience !== \"dashboard\" &&\n        rawLegacyAudience !== \"gateway\"\n      ) {\n        throw new CliError(\n          \"INVALID_CREDENTIALS\",\n          \"credentials.auth.accessTokenAudience must be one of: dashboard, gateway\",\n          ExitCode.InvalidArguments,\n        );\n      }\n      const legacyAudience: AccessTokenAudience = rawLegacyAudience ?? \"dashboard\";\n      if (!accessTokens[legacyAudience]) {\n        accessTokens[legacyAudience] = {\n          token: legacyAccessToken,\n          expiresAt: coerceStringField(auth.expiresAt, \"auth.expiresAt\", false),\n        };\n      }\n    }\n\n    profile.auth = {\n      type: \"refresh_token\",\n      refreshToken,\n      accessTokens: Object.keys(accessTokens).length > 0 ? accessTokens : undefined,\n    };\n  }\n\n  return profile;\n}\n\nexport async function loadCredentials(): Promise<CredentialsFile> {\n  const path = getCredentialsPath();\n\n  try {\n    const raw = await readFile(path, \"utf8\");\n    const parsed = JSON.parse(raw) as unknown;\n\n    if (typeof parsed !== \"object\" || parsed === null) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"Credentials file must contain an object\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const record = parsed as Record<string, unknown>;\n    const version = record.version;\n\n    if (version !== 1) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"Unsupported credentials version\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const currentProfile = coerceStringField(record.currentProfile, \"currentProfile\", true)!;\n    const profilesRaw = record.profiles;\n\n    if (typeof profilesRaw !== \"object\" || profilesRaw === null) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"credentials.profiles must be an object\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const profiles: Record<string, LoroProfile> = {};\n    for (const [name, value] of Object.entries(profilesRaw)) {\n      profiles[name] = parseProfile(value);\n    }\n\n    if (Object.keys(profiles).length === 0) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"credentials.profiles cannot be empty\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    if (!profiles[currentProfile]) {\n      throw new CliError(\n        \"INVALID_CREDENTIALS\",\n        \"currentProfile points to a missing profile\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    return {\n      version: 1,\n      currentProfile,\n      profiles,\n    };\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return defaultCredentials();\n    }\n\n    if (error instanceof CliError) {\n      throw error;\n    }\n\n    throw new CliError(\n      \"INVALID_CREDENTIALS\",\n      \"Failed to read credentials file\",\n      ExitCode.InvalidArguments,\n      { cause: error },\n    );\n  }\n}\n\nexport async function saveCredentials(credentials: CredentialsFile): Promise<void> {\n  const path = getCredentialsPath();\n  const dir = dirname(path);\n  await mkdir(dir, { recursive: true, mode: 0o700 });\n  // `mode` applies at creation, so a new file is never briefly world-readable;\n  // the chmod calls tighten files/directories created by older CLI versions.\n  await writeFile(path, `${JSON.stringify(credentials, null, 2)}\\n`, {\n    encoding: \"utf8\",\n    mode: 0o600,\n  });\n\n  if (process.platform !== \"win32\") {\n    await chmod(dir, 0o700);\n    await chmod(path, 0o600);\n  }\n}\n\nexport function ensureProfile(credentials: CredentialsFile, profileName?: string): LoroProfile {\n  const name = profileName ?? credentials.currentProfile;\n\n  if (!credentials.profiles[name]) {\n    credentials.profiles[name] = defaultProfile();\n  }\n\n  return credentials.profiles[name];\n}\n\nexport function resolveProfileName(credentials: CredentialsFile, profileName?: string): string {\n  return profileName ?? credentials.currentProfile;\n}\n\nexport function applyEnvOverrides(profile: LoroProfile): LoroProfile {\n  const dashboardFromEnv = process.env.LORO_DASHBOARD_URL;\n  const gatewayFromEnv = process.env.LORO_GATEWAY_URL;\n\n  return {\n    ...profile,\n    dashboardBaseUrl: dashboardFromEnv\n      ? trimBaseUrl(dashboardFromEnv)\n      : profile.dashboardBaseUrl,\n    gatewayBaseUrl: gatewayFromEnv\n      ? trimBaseUrl(gatewayFromEnv)\n      : profile.gatewayBaseUrl,\n  };\n}\n","import { spawn } from \"node:child_process\";\n\nfunction trySpawn(command: string, args: string[]): Promise<boolean> {\n  return new Promise((resolve) => {\n    const child = spawn(command, args, {\n      stdio: \"ignore\",\n      detached: true,\n    });\n\n    child.on(\"error\", () => resolve(false));\n    child.on(\"spawn\", () => {\n      child.unref();\n      resolve(true);\n    });\n  });\n}\n\n/**\n * The URL comes from the dashboard response (`verification_url`), so treat it\n * as untrusted: only http(s) targets are opened, and never through a shell.\n * `cmd /c start` re-parses its arguments, so a `&` in the URL would run a\n * second command; `rundll32 url.dll,FileProtocolHandler` takes it verbatim.\n */\nexport async function openBrowser(url: string): Promise<boolean> {\n  let target: string;\n  try {\n    const parsed = new URL(url);\n    if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n      return false;\n    }\n    target = parsed.href;\n  } catch {\n    return false;\n  }\n\n  if (process.platform === \"darwin\") {\n    return trySpawn(\"open\", [target]);\n  }\n\n  if (process.platform === \"win32\") {\n    return trySpawn(\"rundll32\", [\"url.dll,FileProtocolHandler\", target]);\n  }\n\n  return trySpawn(\"xdg-open\", [target]);\n}\n","export interface HelpEntry {\n  name: string;\n  description: string;\n}\n\nexport interface HelpDoc {\n  title: string;\n  summary?: string[];\n  usage?: string[];\n  commands?: HelpEntry[];\n  arguments?: HelpEntry[];\n  options?: HelpEntry[];\n  sections?: Array<{\n    title: string;\n    lines: string[];\n  }>;\n  examples?: string[];\n  tips?: string[];\n  seeAlso?: string[];\n}\n\nfunction renderEntrySection(title: string, entries: HelpEntry[]): string[] {\n  if (entries.length === 0) {\n    return [];\n  }\n\n  const width = entries.reduce((max, entry) => Math.max(max, entry.name.length), 0);\n  return [\n    \"\",\n    `${title}:`,\n    ...entries.map((entry) => `  ${entry.name.padEnd(width)}  ${entry.description}`),\n  ];\n}\n\nfunction renderBulletSection(title: string, lines: string[]): string[] {\n  if (lines.length === 0) {\n    return [];\n  }\n\n  return [\"\", `${title}:`, ...lines.map((line) => `  - ${line}`)];\n}\n\nexport function renderHelp(doc: HelpDoc): string {\n  const lines: string[] = [doc.title];\n\n  if (doc.summary && doc.summary.length > 0) {\n    lines.push(\"\", ...doc.summary);\n  }\n\n  if (doc.usage && doc.usage.length > 0) {\n    lines.push(\"\", \"Usage:\", ...doc.usage.map((line) => `  ${line}`));\n  }\n\n  lines.push(...renderEntrySection(\"Commands\", doc.commands ?? []));\n  lines.push(...renderEntrySection(\"Arguments\", doc.arguments ?? []));\n  lines.push(...renderEntrySection(\"Options\", doc.options ?? []));\n  for (const section of doc.sections ?? []) {\n    if (section.lines.length === 0) {\n      continue;\n    }\n    lines.push(\"\", `${section.title}:`, ...section.lines.map((line) => `  ${line}`));\n  }\n  lines.push(...renderBulletSection(\"Examples\", doc.examples ?? []));\n  lines.push(...renderBulletSection(\"Tips\", doc.tips ?? []));\n  lines.push(...renderBulletSection(\"See also\", doc.seeAlso ?? []));\n\n  return lines.join(\"\\n\");\n}\n\nexport function isHelpToken(value: string | undefined): boolean {\n  return value === \"help\" || value === \"--help\";\n}\n\nexport function hasHelpFlag(args: string[]): boolean {\n  return args.includes(\"--help\");\n}\n","import { CliError, ExitCode, fromHttpStatus } from \"./errors\";\n\nexport interface HttpRequestOptions {\n  baseUrl: string;\n  path: string;\n  method?: string;\n  headers?: Record<string, string>;\n  query?: Record<string, string | number | boolean | undefined>;\n  body?: unknown;\n  signal?: AbortSignal;\n}\n\nexport interface HttpResponse<T = unknown> {\n  url: string;\n  status: number;\n  ok: boolean;\n  headers: Headers;\n  data?: T;\n  rawText: string;\n}\n\nfunction buildUrl(\n  baseUrl: string,\n  path: string,\n  query?: Record<string, string | number | boolean | undefined>,\n): URL {\n  const normalizedBase = baseUrl.endsWith(\"/\") ? baseUrl : `${baseUrl}/`;\n  const normalizedPath = path.startsWith(\"/\") ? path.slice(1) : path;\n  const url = new URL(normalizedPath, normalizedBase);\n\n  if (query) {\n    for (const [key, value] of Object.entries(query)) {\n      if (value == null) {\n        continue;\n      }\n      url.searchParams.set(key, String(value));\n    }\n  }\n\n  return url;\n}\n\nfunction parseBody(body: unknown): { rawBody: BodyInit | undefined; headers: Record<string, string> } {\n  if (body == null) {\n    return {\n      rawBody: undefined,\n      headers: {},\n    };\n  }\n\n  if (\n    typeof body === \"string\" ||\n    body instanceof ArrayBuffer ||\n    ArrayBuffer.isView(body) ||\n    body instanceof Blob ||\n    body instanceof URLSearchParams ||\n    body instanceof FormData\n  ) {\n    return {\n      rawBody: body as BodyInit,\n      headers: {},\n    };\n  }\n\n  return {\n    rawBody: JSON.stringify(body),\n    headers: {\n      \"content-type\": \"application/json\",\n    },\n  };\n}\n\nfunction tryParseJson<T>(text: string): T | undefined {\n  if (text.trim().length === 0) {\n    return undefined;\n  }\n\n  try {\n    return JSON.parse(text) as T;\n  } catch {\n    return undefined;\n  }\n}\n\nexport async function httpRequest<T = unknown>(opts: HttpRequestOptions): Promise<HttpResponse<T>> {\n  const url = buildUrl(opts.baseUrl, opts.path, opts.query);\n  const parsedBody = parseBody(opts.body);\n\n  const headers = {\n    accept: \"application/json\",\n    ...parsedBody.headers,\n    ...opts.headers,\n  };\n\n  let response: Response;\n  try {\n    response = await fetch(url, {\n      method: opts.method ?? \"GET\",\n      headers,\n      body: parsedBody.rawBody,\n      signal: opts.signal,\n    });\n  } catch (error) {\n    throw new CliError(\"NETWORK_ERROR\", `Failed to request ${url.toString()}`, ExitCode.NetworkError, {\n      cause: error,\n    });\n  }\n\n  const rawText = await response.text();\n  const data = tryParseJson<T>(rawText);\n\n  return {\n    url: url.toString(),\n    status: response.status,\n    ok: response.ok,\n    headers: response.headers,\n    data,\n    rawText,\n  };\n}\n\nfunction deriveErrorMessage<T>(response: HttpResponse<T>, defaultMessage: string): string {\n  if (response.status >= 500) {\n    return `${defaultMessage}: HTTP ${response.status}`;\n  }\n\n  const data = response.data as Record<string, unknown> | undefined;\n  const messageFromJson =\n    data && typeof data.error === \"string\"\n      ? data.error\n      : data && typeof data.message === \"string\"\n        ? data.message\n        : undefined;\n\n  const messageFromText = response.rawText.trim().length > 0 ? response.rawText.trim() : undefined;\n  const detail = messageFromJson ?? messageFromText;\n\n  if (!detail) {\n    return defaultMessage;\n  }\n\n  return `${defaultMessage}: ${detail}`;\n}\n\nexport function ensureHttpOk<T>(\n  response: HttpResponse<T>,\n  defaultMessage: string,\n  hint?: string,\n): HttpResponse<T> {\n  if (response.ok) {\n    return response;\n  }\n\n  throw fromHttpStatus(response.status, deriveErrorMessage(response, defaultMessage), {\n    hint,\n    details: response.data ?? response.rawText,\n  });\n}\n","import {\n  applyEnvOverrides,\n  assertCredentialTransport,\n  profileUrlSource,\n  ensureProfile,\n  loadCredentials,\n  resolveProfileName,\n  saveCredentials,\n  type CredentialsFile,\n  type LoroProfile,\n  type StoredAuth,\n  type AccessTokenAudience,\n} from \"./credentials\";\nimport { CliError, ExitCode } from \"./errors\";\nimport { ensureHttpOk, httpRequest } from \"./http\";\n\ninterface RefreshResponse {\n  access_token?: string;\n  refresh_token?: string;\n  expires_in?: number;\n}\n\nexport interface AccessTokenResult {\n  token: string;\n  expiresAt?: string;\n  profileName: string;\n  profile: LoroProfile;\n  credentials: CredentialsFile;\n}\n\nfunction isTokenFresh(expiresAt?: string): boolean {\n  if (!expiresAt) {\n    return false;\n  }\n\n  const expiresAtMs = Date.parse(expiresAt);\n  if (Number.isNaN(expiresAtMs)) {\n    return false;\n  }\n\n  const refreshSkewMs = 30_000;\n  return expiresAtMs - refreshSkewMs > Date.now();\n}\n\nfunction computeExpiresAt(expiresInSeconds: number | undefined): string | undefined {\n  if (typeof expiresInSeconds !== \"number\" || !Number.isFinite(expiresInSeconds)) {\n    return undefined;\n  }\n  const now = Date.now();\n  return new Date(now + expiresInSeconds * 1000).toISOString();\n}\n\nfunction requireRefreshAuth(profile: LoroProfile): StoredAuth {\n  if (profile.auth?.type === \"refresh_token\" && profile.auth.refreshToken) {\n    return profile.auth;\n  }\n\n  throw new CliError(\n    \"AUTH_REQUIRED\",\n    \"Please run `loro auth login` first.\",\n    ExitCode.AuthRequired,\n    {\n      hint: \"loro auth login --host https://streams.loro.dev\",\n    },\n  );\n}\n\nexport async function ensureAccessToken(options: {\n  profileName?: string;\n  audience?: AccessTokenAudience;\n} = {}): Promise<AccessTokenResult> {\n  const requestedAudience: AccessTokenAudience = options.audience ?? \"dashboard\";\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, options.profileName);\n  const mutableProfile = ensureProfile(credentials, profileName);\n  const profile = applyEnvOverrides(mutableProfile);\n  // Every authenticated command passes through here before a token is sent.\n  // The refresh token always goes to the dashboard; a gateway-audience token\n  // is then sent to the gateway. Only those effective URLs are checked, so an\n  // unrelated plain-http URL elsewhere in the profile does not block commands.\n  assertCredentialTransport(profile.dashboardBaseUrl, profileUrlSource(profileName, \"dashboard\"));\n  if (requestedAudience === \"gateway\") {\n    assertCredentialTransport(profile.gatewayBaseUrl, profileUrlSource(profileName, \"gateway\"));\n  }\n  const auth = requireRefreshAuth(mutableProfile);\n  const cachedAccessToken = auth.accessTokens?.[requestedAudience];\n  if (cachedAccessToken && isTokenFresh(cachedAccessToken.expiresAt)) {\n    return {\n      token: cachedAccessToken.token,\n      expiresAt: cachedAccessToken.expiresAt,\n      profileName,\n      profile,\n      credentials,\n    };\n  }\n\n  const refreshResponse = await httpRequest<RefreshResponse>({\n    baseUrl: profile.dashboardBaseUrl,\n    path: \"/api/auth/cli/refresh\",\n    method: \"POST\",\n    body: {\n      refresh_token: auth.refreshToken,\n      audience: requestedAudience,\n    },\n  });\n\n  ensureHttpOk(refreshResponse, \"Failed to refresh CLI access token\", \"Run `loro auth login` again.\");\n\n  const payload = refreshResponse.data;\n  if (!payload || typeof payload.access_token !== \"string\") {\n    throw new CliError(\n      \"AUTH_REFRESH_FAILED\",\n      \"Dashboard returned an invalid refresh response.\",\n      ExitCode.UpstreamError,\n    );\n  }\n\n  const refreshedToken = payload.access_token;\n  const refreshedRefreshToken =\n    typeof payload.refresh_token === \"string\" && payload.refresh_token.length > 0\n      ? payload.refresh_token\n      : auth.refreshToken;\n  const refreshedExpiresAt = computeExpiresAt(payload.expires_in);\n\n  const nextAccessTokens = {\n    ...(auth.accessTokens ?? {}),\n    [requestedAudience]: {\n      token: refreshedToken,\n      expiresAt: refreshedExpiresAt,\n    },\n  };\n\n  mutableProfile.auth = {\n    type: \"refresh_token\",\n    refreshToken: refreshedRefreshToken,\n    accessTokens: nextAccessTokens,\n  };\n\n  await saveCredentials(credentials);\n\n  return {\n    token: refreshedToken,\n    expiresAt: refreshedExpiresAt,\n    profileName,\n    profile,\n    credentials,\n  };\n}\n","export function sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => {\n    setTimeout(resolve, ms);\n  });\n}\n\nexport function parsePositiveInteger(\n  value: string | undefined,\n  fieldName: string,\n): number | undefined {\n  if (value == null) {\n    return undefined;\n  }\n\n  if (!/^\\d+$/.test(value)) {\n    throw new Error(`${fieldName} must be a positive integer`);\n  }\n\n  const numeric = Number(value);\n  if (!Number.isSafeInteger(numeric) || numeric <= 0) {\n    throw new Error(`${fieldName} must be a positive integer`);\n  }\n\n  return numeric;\n}\n","import { parseArgs } from \"node:util\";\nimport {\n  assertCredentialTransport,\n  ensureProfile,\n  loadCredentials,\n  normalizeBaseUrl,\n  resolveProfileName,\n  saveCredentials,\n} from \"../core/credentials\";\nimport { openBrowser } from \"../core/browser\";\nimport { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport { ensureHttpOk, httpRequest } from \"../core/http\";\nimport { ensureAccessToken } from \"../core/tokens\";\nimport type { CommandContext, CommandOutput } from \"../core/types\";\nimport { sleep } from \"../core/utils\";\n\ninterface CliStartResponse {\n  device_code?: string;\n  user_code?: string;\n  verification_url?: string;\n  expires_at?: string;\n  interval_sec?: number;\n}\n\ninterface CliPollResponse {\n  access_token?: string;\n  refresh_token?: string;\n  expires_in?: number;\n  organization_id?: string;\n  user?: unknown;\n  error?: string;\n  status?: string;\n}\n\nfunction authHelp(): string {\n  return renderHelp({\n    title: \"loro auth\",\n    summary: [\n      \"Authenticate the CLI against the dashboard, inspect the current identity, mint short-lived access tokens, and choose the active organization.\",\n      \"Dashboard and gateway access tokens are audience-scoped. Pick the audience that matches the API surface you will call.\",\n    ],\n    usage: [\n      \"loro auth <subcommand> [options]\",\n      \"loro auth <subcommand> --help\",\n    ],\n    commands: [\n      {\n        name: \"login\",\n        description: \"Start the device-like browser flow and persist refresh/access tokens in the local profile.\",\n      },\n      {\n        name: \"logout\",\n        description: \"Remove stored auth from the local profile and best-effort revoke the refresh token server-side.\",\n      },\n      {\n        name: \"whoami\",\n        description: \"Show the current dashboard identity, active org, and effective base URLs.\",\n      },\n      {\n        name: \"token\",\n        description: \"Print a short-lived access token for the requested audience (`gateway` by default).\",\n      },\n      {\n        name: \"use-org\",\n        description: \"Switch the active organization used by later dashboard commands and key creation flows.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile instead of the current default profile.\",\n      },\n      {\n        name: \"--json\",\n        description: \"Return machine-readable envelopes. Useful when another tool needs token expiry metadata.\",\n      },\n    ],\n    examples: [\n      \"loro auth login --host https://streams.loro.dev\",\n      \"loro auth whoami\",\n      \"loro auth token --audience gateway\",\n      \"loro auth use-org org_123\",\n    ],\n    tips: [\n      \"`login` fetches dashboard credentials. `loro stream` and `loro bucket` commands will mint or refresh a gateway token from those stored credentials as needed.\",\n      \"Run `loro dashboard organizations list` before `use-org` when you do not remember the org id.\",\n      \"Use `loro auth token --audience dashboard --json` when you need both the token and `expiresAt` in a script.\",\n    ],\n    seeAlso: [\n      \"loro dashboard organizations --help\",\n      \"loro config --help\",\n    ],\n  });\n}\n\nfunction loginHelp(): string {\n  return renderHelp({\n    title: \"loro auth login\",\n    summary: [\n      \"Start the dashboard device flow, optionally open the browser automatically, and persist the resulting refresh token in the selected local profile.\",\n      \"If the dashboard returns an organization during login, the CLI also stores it as the profile's active org.\",\n    ],\n    usage: [\"loro auth login [--host <url>] [--profile <name>] [--no-browser]\"],\n    options: [\n      {\n        name: \"--host <url>\",\n        description: \"Override the dashboard base URL for this login and persist it into the selected profile.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Store the login under a named local profile.\",\n      },\n      {\n        name: \"--no-browser\",\n        description: \"Do not attempt to open the verification URL automatically; print it only.\",\n      },\n    ],\n    examples: [\n      \"loro auth login\",\n      \"loro auth login --host https://streams.loro.dev\",\n      \"loro auth login --profile staging --no-browser\",\n    ],\n    tips: [\n      \"Use `--no-browser` for SSH sessions, remote terminals, or CI-like environments where opening a browser is not possible.\",\n      \"After login, verify identity and org context with `loro auth whoami`.\",\n    ],\n    seeAlso: [\"loro auth whoami\", \"loro config set --help\"],\n  });\n}\n\nfunction logoutHelp(): string {\n  return renderHelp({\n    title: \"loro auth logout\",\n    summary: [\n      \"Remove stored auth from the selected profile. If the profile has a refresh token, the CLI also attempts a best-effort revoke request.\",\n    ],\n    usage: [\"loro auth logout [--profile <name>]\"],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Log out a specific local profile instead of the current one.\",\n      },\n    ],\n    examples: [\"loro auth logout\", \"loro auth logout --profile staging\"],\n    tips: [\n      \"This only clears local CLI auth for the selected profile; it does not delete the profile's saved base URLs or active org id.\",\n    ],\n    seeAlso: [\"loro auth login\", \"loro config get\"],\n  });\n}\n\nfunction whoamiHelp(): string {\n  return renderHelp({\n    title: \"loro auth whoami\",\n    summary: [\n      \"Show which dashboard user and organization the CLI will act as, plus the dashboard and gateway base URLs resolved from the current profile.\",\n    ],\n    usage: [\"loro auth whoami [--profile <name>]\"],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Inspect a specific local profile.\",\n      },\n    ],\n    examples: [\"loro auth whoami\", \"loro auth whoami --profile prod\"],\n    tips: [\n      \"Use this before member management, API key creation, or quota/billing inspection to avoid operating on the wrong org.\",\n    ],\n    seeAlso: [\"loro auth use-org --help\", \"loro dashboard organizations list\"],\n  });\n}\n\nfunction tokenHelp(): string {\n  return renderHelp({\n    title: \"loro auth token\",\n    summary: [\n      \"Print a short-lived access token for either the dashboard or the gateway. The CLI refreshes it from the stored refresh token when necessary.\",\n    ],\n    usage: [\"loro auth token [--profile <name>] [--audience gateway|dashboard]\"],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Mint the token from a specific local profile.\",\n      },\n      {\n        name: \"--audience <name>\",\n        description: \"Choose `gateway` for `loro stream`/`loro bucket` or direct data-plane calls, or `dashboard` for control-plane APIs. Default: `gateway`.\",\n      },\n    ],\n    examples: [\n      \"loro auth token\",\n      \"loro auth token --audience dashboard\",\n      \"loro auth token --audience gateway --json\",\n    ],\n    tips: [\n      \"Without `--json`, the command prints only the raw token so it can be piped directly into other tools.\",\n      \"Use `dashboard` tokens for `/api/dashboard/*` and `gateway` tokens for `/ds/*`.\",\n    ],\n    seeAlso: [\"loro dashboard api-key token --help\", \"loro stream --help\"],\n  });\n}\n\nfunction useOrgHelp(): string {\n  return renderHelp({\n    title: \"loro auth use-org\",\n    summary: [\n      \"Set the active organization in the selected profile and also ask the dashboard to activate that org for the current human session.\",\n      \"Later dashboard commands automatically send this org id in the `x-loro-org-id` header when needed.\",\n    ],\n    usage: [\"loro auth use-org <org-id> [--profile <name>]\"],\n    arguments: [\n      {\n        name: \"<org-id>\",\n        description: \"The exact organization id returned by `loro dashboard organizations list`.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Update a specific local profile instead of the current one.\",\n      },\n    ],\n    examples: [\"loro auth use-org org_123\", \"loro auth use-org org_prod --profile prod\"],\n    tips: [\n      \"Run `loro auth whoami` after switching if you want to confirm both the saved org id and the effective base URLs.\",\n    ],\n    seeAlso: [\"loro dashboard organizations list\", \"loro auth whoami\"],\n  });\n}\n\nfunction parseAudience(value: string | undefined): \"gateway\" | \"dashboard\" {\n  if (!value || value === \"gateway\") {\n    return \"gateway\";\n  }\n  if (value === \"dashboard\") {\n    return \"dashboard\";\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--audience must be one of: gateway, dashboard\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction computeExpiresAt(expiresInSeconds: number | undefined): string | undefined {\n  if (typeof expiresInSeconds !== \"number\" || !Number.isFinite(expiresInSeconds)) {\n    return undefined;\n  }\n  return new Date(Date.now() + expiresInSeconds * 1000).toISOString();\n}\n\nfunction requireStringField(\n  value: unknown,\n  fieldName: string,\n  errorCode: ExitCode = ExitCode.UpstreamError,\n): string {\n  if (typeof value !== \"string\" || value.length === 0) {\n    throw new CliError(\n      \"INVALID_UPSTREAM_RESPONSE\",\n      `Expected field \\`${fieldName}\\` in response payload.`,\n      errorCode,\n    );\n  }\n  return value;\n}\n\nfunction extractPollError(payload: CliPollResponse | undefined): string | undefined {\n  if (!payload) {\n    return undefined;\n  }\n\n  if (typeof payload.error === \"string\") {\n    return payload.error;\n  }\n\n  if (typeof payload.status === \"string\" && payload.status !== \"ok\") {\n    return payload.status;\n  }\n\n  return undefined;\n}\n\nasync function runLogin(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: loginHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      host: { type: \"string\" },\n      profile: { type: \"string\" },\n      \"no-browser\": { type: \"boolean\", default: false },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"`loro auth login` does not accept positional arguments.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, parsed.values.profile);\n  const profile = ensureProfile(credentials, profileName);\n\n  if (parsed.values.host) {\n    profile.dashboardBaseUrl = normalizeBaseUrl(parsed.values.host);\n  }\n  // The device flow returns a long-lived refresh token from this host. Login\n  // uses the stored profile URL (not env overrides), so name that source.\n  assertCredentialTransport(\n    profile.dashboardBaseUrl,\n    parsed.values.host\n      ? { kind: \"flag\", name: \"--host\" }\n      : { kind: \"profile\", profile: profileName, field: \"dashboardBaseUrl\" },\n  );\n\n  const startResponse = await httpRequest<CliStartResponse>({\n    baseUrl: profile.dashboardBaseUrl,\n    path: \"/api/auth/cli/start\",\n    method: \"POST\",\n    body: {\n      provider: \"github\",\n    },\n  });\n\n  if (startResponse.status === 404) {\n    throw new CliError(\n      \"AUTH_FLOW_UNAVAILABLE\",\n      \"CLI OAuth device flow is not enabled in this deployment.\",\n      ExitCode.NotFound,\n      {\n        hint: \"Deploy dashboard endpoints: /api/auth/cli/start|poll|refresh|revoke|whoami\",\n      },\n    );\n  }\n\n  ensureHttpOk(startResponse, \"Failed to start OAuth device flow\");\n\n  const startPayload = startResponse.data;\n  const deviceCode = requireStringField(startPayload?.device_code, \"device_code\");\n  const verificationUrl = requireStringField(startPayload?.verification_url, \"verification_url\");\n\n  const userCode = requireStringField(startPayload?.user_code, \"user_code\");\n  const expiresAt =\n    typeof startPayload?.expires_at === \"string\"\n      ? Date.parse(startPayload.expires_at)\n      : Date.now() + 10 * 60_000;\n  const deadlineMs = Number.isFinite(expiresAt) ? expiresAt : Date.now() + 10 * 60_000;\n\n  let intervalMs =\n    typeof startPayload?.interval_sec === \"number\" && startPayload.interval_sec > 0\n      ? startPayload.interval_sec * 1000\n      : 2_000;\n\n  if (!context.json) {\n    process.stderr.write(`Open this URL to continue login: ${verificationUrl}\\n`);\n    process.stderr.write(`Verification code: ${userCode}\\n`);\n  }\n\n  if (!parsed.values[\"no-browser\"]) {\n    const opened = await openBrowser(verificationUrl);\n    if (!opened && !context.json) {\n      process.stderr.write(\"Failed to open browser automatically. Open the URL manually.\\n\");\n    }\n  }\n\n  while (Date.now() < deadlineMs) {\n    await sleep(intervalMs);\n\n    const pollResponse = await httpRequest<CliPollResponse>({\n      baseUrl: profile.dashboardBaseUrl,\n      path: \"/api/auth/cli/poll\",\n      method: \"POST\",\n      body: {\n        device_code: deviceCode,\n      },\n    });\n\n    const pollPayload = pollResponse.data;\n\n    if (\n      pollResponse.ok &&\n      typeof pollPayload?.access_token === \"string\" &&\n      typeof pollPayload?.refresh_token === \"string\"\n    ) {\n      profile.auth = {\n        type: \"refresh_token\",\n        refreshToken: pollPayload.refresh_token,\n        accessTokens: {\n          dashboard: {\n            token: pollPayload.access_token,\n            expiresAt: computeExpiresAt(pollPayload.expires_in),\n          },\n        },\n      };\n\n      if (typeof pollPayload.organization_id === \"string\" && pollPayload.organization_id.length > 0) {\n        profile.activeOrgId = pollPayload.organization_id;\n      }\n\n      credentials.currentProfile = profileName;\n      await saveCredentials(credentials);\n\n      return {\n        text: `Login successful. profile=${profileName}`,\n        data: {\n          profile: profileName,\n          dashboardBaseUrl: profile.dashboardBaseUrl,\n          activeOrgId: profile.activeOrgId,\n          accessTokenExpiresAt: profile.auth.accessTokens?.dashboard?.expiresAt,\n          user: pollPayload.user,\n        },\n      };\n    }\n\n    const pollError = extractPollError(pollPayload);\n\n    if (pollResponse.status === 202 || pollError === \"authorization_pending\" || pollError === \"pending\") {\n      continue;\n    }\n\n    if (pollError === \"slow_down\") {\n      intervalMs += 1_000;\n      continue;\n    }\n\n    if (pollError === \"expired_token\") {\n      throw new CliError(\n        \"AUTH_TIMEOUT\",\n        \"OAuth device flow expired before authorization completed.\",\n        ExitCode.AuthRequired,\n      );\n    }\n\n    if (pollResponse.status === 404) {\n      throw new CliError(\n        \"AUTH_FLOW_UNAVAILABLE\",\n        \"CLI OAuth poll endpoint is not enabled in this deployment.\",\n        ExitCode.NotFound,\n      );\n    }\n\n    ensureHttpOk(pollResponse, \"Failed while polling OAuth device flow\");\n  }\n\n  throw new CliError(\n    \"AUTH_TIMEOUT\",\n    \"OAuth device flow timed out before authorization completed.\",\n    ExitCode.AuthRequired,\n    {\n      hint: \"Run `loro auth login` again.\",\n    },\n  );\n}\n\nasync function runLogout(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: logoutHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"`loro auth logout` does not accept positional arguments.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, parsed.values.profile);\n  const profile = ensureProfile(credentials, profileName);\n\n  // Logout must always work: clear local credentials, and only attempt the\n  // best-effort remote revoke when the refresh token may be sent there.\n  if (\n    profile.auth?.type === \"refresh_token\"\n    && isCredentialTransportAllowed(profile.dashboardBaseUrl, profileName)\n  ) {\n    await httpRequest({\n      baseUrl: profile.dashboardBaseUrl,\n      path: \"/api/auth/cli/revoke\",\n      method: \"POST\",\n      body: {\n        refresh_token: profile.auth.refreshToken,\n      },\n    }).catch(() => {\n      // Best effort revoke.\n    });\n  }\n\n  delete profile.auth;\n  await saveCredentials(credentials);\n\n  return {\n    text: `Logged out profile ${profileName}`,\n    data: {\n      profile: profileName,\n      loggedOut: true,\n    },\n  };\n}\n\nasync function runWhoami(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: whoamiHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"`loro auth whoami` does not accept positional arguments.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const access = await ensureAccessToken({\n    profileName: parsed.values.profile,\n    audience: \"dashboard\",\n  });\n\n  const headers: Record<string, string> = {\n    authorization: `Bearer ${access.token}`,\n  };\n\n  const whoamiResponse = await httpRequest<Record<string, unknown>>({\n    baseUrl: access.profile.dashboardBaseUrl,\n    path: \"/api/auth/cli/whoami\",\n    method: \"GET\",\n    headers,\n  });\n\n  if (whoamiResponse.status === 404) {\n    throw new CliError(\n      \"AUTH_FLOW_UNAVAILABLE\",\n      \"CLI whoami endpoint is not enabled in this deployment.\",\n      ExitCode.NotFound,\n      {\n        hint: \"Deploy /api/auth/cli/whoami or upgrade dashboard service.\",\n      },\n    );\n  }\n\n  ensureHttpOk(whoamiResponse, \"Failed to fetch current identity\");\n\n  const payload = whoamiResponse.data ?? {};\n  const user = payload.user as Record<string, unknown> | undefined;\n  const organization = payload.organization as Record<string, unknown> | undefined;\n\n  const userEmail = typeof user?.email === \"string\" ? user.email : \"n/a\";\n  const userName = typeof user?.name === \"string\" ? user.name : \"n/a\";\n  const orgId =\n    (typeof organization?.id === \"string\" && organization.id) ||\n    access.profile.activeOrgId ||\n    \"n/a\";\n\n  return {\n    text: [\n      `profile: ${access.profileName}`,\n      `user: ${userName} <${userEmail}>`,\n      `activeOrgId: ${orgId}`,\n      `dashboardBaseUrl: ${access.profile.dashboardBaseUrl}`,\n      `gatewayBaseUrl: ${access.profile.gatewayBaseUrl}`,\n    ].join(\"\\n\"),\n    data: {\n      profile: access.profileName,\n      activeOrgId: orgId,\n      dashboardBaseUrl: access.profile.dashboardBaseUrl,\n      gatewayBaseUrl: access.profile.gatewayBaseUrl,\n      user,\n      organization,\n    },\n  };\n}\n\nasync function runToken(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: tokenHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n      audience: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"`loro auth token` does not accept positional arguments.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const audience = parseAudience(parsed.values.audience);\n  const access = await ensureAccessToken({\n    profileName: parsed.values.profile,\n    audience,\n  });\n\n  if (!context.json) {\n    return {\n      text: access.token,\n      data: {\n        token: access.token,\n        expiresAt: access.expiresAt,\n        audience,\n      },\n    };\n  }\n\n  return {\n    data: {\n      token: access.token,\n      expiresAt: access.expiresAt,\n      audience,\n    },\n  };\n}\n\nasync function runUseOrg(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: useOrgHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length !== 1) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Usage: loro auth use-org <org-id> [--profile <name>]\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const orgId = parsed.positionals[0];\n  if (!orgId || orgId.trim().length === 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"org-id cannot be empty\", ExitCode.InvalidArguments);\n  }\n\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, parsed.values.profile);\n  const profile = ensureProfile(credentials, profileName);\n\n  const access = await ensureAccessToken({\n    profileName,\n    audience: \"dashboard\",\n  });\n\n  const activateResponse = await httpRequest<Record<string, unknown>>({\n    // Same effective URL (env overrides applied) that ensureAccessToken\n    // validated and obtained the token from.\n    baseUrl: access.profile.dashboardBaseUrl,\n    path: \"/api/dashboard/organizations/activate\",\n    method: \"POST\",\n    headers: {\n      authorization: `Bearer ${access.token}`,\n    },\n    body: {\n      organization_id: orgId,\n    },\n  });\n\n  ensureHttpOk(\n    activateResponse,\n    `Failed to switch active organization to ${orgId}`,\n    \"Use `loro dashboard organizations list` to inspect available organizations.\",\n  );\n\n  profile.activeOrgId = orgId;\n\n  await saveCredentials(credentials);\n\n  return {\n    text: `Active organization set to ${orgId} (profile=${profileName})`,\n    data: {\n      profile: profileName,\n      activeOrgId: orgId,\n    },\n  };\n}\n\n\n/** Logout still clears local credentials; it only skips the remote revoke. */\nfunction isCredentialTransportAllowed(url: string, profileName: string): boolean {\n  try {\n    assertCredentialTransport(url, { kind: \"profile\", profile: profileName, field: \"dashboardBaseUrl\" });\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function runAuthCommand(\n  args: string[],\n  context: CommandContext,\n): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: authHelp() };\n  }\n\n  const [subcommand, ...rest] = args;\n\n  if (subcommand === \"login\") {\n    return runLogin(rest, context);\n  }\n  if (subcommand === \"logout\") {\n    return runLogout(rest);\n  }\n  if (subcommand === \"whoami\") {\n    return runWhoami(rest);\n  }\n  if (subcommand === \"token\") {\n    return runToken(rest, context);\n  }\n  if (subcommand === \"use-org\") {\n    return runUseOrg(rest);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `Unknown auth subcommand: ${subcommand}`,\n    ExitCode.InvalidArguments,\n    {\n      hint: authHelp(),\n    },\n  );\n}\n","import { parseArgs } from \"node:util\";\nimport {\n  applyEnvOverrides,\n  assertCredentialTransport,\n  ensureProfile,\n  loadCredentials,\n  normalizeBaseUrl,\n  resolveProfileName,\n  saveCredentials,\n  type LoroProfile,\n} from \"../core/credentials\";\nimport { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport type { CommandOutput } from \"../core/types\";\n\nfunction configHelp(): string {\n  return renderHelp({\n    title: \"loro config\",\n    summary: [\n      \"Inspect or update local profile defaults such as dashboard and gateway base URLs.\",\n      \"Saved profile values live in the credentials file, but runtime environment variables can still override them.\",\n    ],\n    usage: [\n      \"loro config <subcommand> [options]\",\n      \"loro config <subcommand> --help\",\n    ],\n    commands: [\n      {\n        name: \"get\",\n        description: \"Show the effective profile configuration, including env-var overrides and whether auth exists.\",\n      },\n      {\n        name: \"set\",\n        description: \"Persist dashboard and/or gateway base URLs for a profile.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Operate on a named local profile.\",\n      },\n    ],\n    examples: [\n      \"loro config get\",\n      \"loro config set --dashboard-url https://streams.loro.dev --gateway-url https://streams-api.loro.dev\",\n      \"loro config set --profile staging --gateway-url https://sync-staging.example.com\",\n    ],\n    tips: [\n      \"`loro config get` applies `LORO_DASHBOARD_URL` and `LORO_GATEWAY_URL` overrides before printing values.\",\n      \"`loro auth login --host <url>` is a convenient way to set the dashboard URL while authenticating.\",\n    ],\n    seeAlso: [\"loro auth login --help\", \"loro auth whoami\"],\n  });\n}\n\nfunction configGetHelp(): string {\n  return renderHelp({\n    title: \"loro config get\",\n    summary: [\n      \"Print the effective configuration for a local profile: dashboard URL, gateway URL, active org id, and whether auth is stored.\",\n    ],\n    usage: [\"loro config get [--profile <name>]\"],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Inspect a specific profile instead of the current default.\",\n      },\n    ],\n    examples: [\"loro config get\", \"loro config get --profile staging\"],\n    tips: [\n      \"The printed URLs already include `LORO_DASHBOARD_URL` / `LORO_GATEWAY_URL` runtime overrides if those env vars are set.\",\n    ],\n    seeAlso: [\"loro config set --help\", \"loro auth whoami\"],\n  });\n}\n\nfunction configSetHelp(): string {\n  return renderHelp({\n    title: \"loro config set\",\n    summary: [\n      \"Persist one or both base URLs for a local profile. At least one of `--dashboard-url` or `--gateway-url` is required.\",\n    ],\n    usage: [\n      \"loro config set [--profile <name>] [--dashboard-url <url>] [--gateway-url <url>]\",\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Write into a named local profile.\",\n      },\n      {\n        name: \"--dashboard-url <url>\",\n        description: \"Persist the dashboard base URL used by `auth` and `dashboard` commands.\",\n      },\n      {\n        name: \"--gateway-url <url>\",\n        description: \"Persist the gateway base URL used by `ds` commands.\",\n      },\n    ],\n    examples: [\n      \"loro config set --dashboard-url https://streams.loro.dev\",\n      \"loro config set --gateway-url https://streams-api.loro.dev\",\n      \"loro config set --profile prod --dashboard-url https://deploy.example.com --gateway-url https://sync.example.com\",\n    ],\n    tips: [\n      \"This command updates stored defaults only. `LORO_DASHBOARD_URL` and `LORO_GATEWAY_URL` can still override them at runtime.\",\n      \"URLs are normalized so trailing `/` is removed before saving.\",\n    ],\n    seeAlso: [\"loro config get\", \"loro auth login --help\"],\n  });\n}\n\nasync function runGet(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: configGetHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, parsed.values.profile);\n  const profile = applyEnvOverrides(ensureProfile(credentials, profileName));\n\n  return {\n    text: [\n      `profile: ${profileName}`,\n      `dashboardBaseUrl: ${profile.dashboardBaseUrl}`,\n      `gatewayBaseUrl: ${profile.gatewayBaseUrl}`,\n      `activeOrgId: ${profile.activeOrgId ?? \"n/a\"}`,\n      `hasAuth: ${profile.auth ? \"yes\" : \"no\"}`,\n    ].join(\"\\n\"),\n    data: publicProfileData(profileName, profile),\n  };\n}\n\nasync function runSet(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: configSetHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n      \"dashboard-url\": { type: \"string\" },\n      \"gateway-url\": { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const dashboardUrl = parsed.values[\"dashboard-url\"];\n  const gatewayUrl = parsed.values[\"gateway-url\"];\n\n  if (!dashboardUrl && !gatewayUrl) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"At least one of --dashboard-url or --gateway-url is required\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, parsed.values.profile);\n  const profile = ensureProfile(credentials, profileName);\n\n  // Validate only what is being written; other stored values may predate the\n  // transport policy and stay editable.\n  if (dashboardUrl) {\n    profile.dashboardBaseUrl = normalizeBaseUrl(dashboardUrl);\n    assertCredentialTransport(profile.dashboardBaseUrl, { kind: \"flag\", name: \"--dashboard-url\" });\n  }\n  if (gatewayUrl) {\n    profile.gatewayBaseUrl = normalizeBaseUrl(gatewayUrl);\n    assertCredentialTransport(profile.gatewayBaseUrl, { kind: \"flag\", name: \"--gateway-url\" });\n  }\n\n  await saveCredentials(credentials);\n\n  return {\n    text: [\n      \"Config updated:\",\n      `- profile: ${profileName}`,\n      `- dashboardBaseUrl: ${profile.dashboardBaseUrl}`,\n      `- gatewayBaseUrl: ${profile.gatewayBaseUrl}`,\n    ].join(\"\\n\"),\n    data: publicProfileData(profileName, profile),\n  };\n}\n\n/**\n * Structured (`--json`) view of a profile. Never includes `auth`: the stored\n * refresh token is long-lived and agents/CI routinely log `--json` output.\n */\nfunction publicProfileData(profileName: string, profile: LoroProfile) {\n  return {\n    profile: profileName,\n    dashboardBaseUrl: profile.dashboardBaseUrl,\n    gatewayBaseUrl: profile.gatewayBaseUrl,\n    ...(profile.activeOrgId === undefined ? {} : { activeOrgId: profile.activeOrgId }),\n    hasAuth: Boolean(profile.auth),\n  };\n}\n\nexport async function runConfigCommand(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: configHelp() };\n  }\n\n  const [subcommand, ...rest] = args;\n  if (subcommand === \"get\") {\n    return runGet(rest);\n  }\n  if (subcommand === \"set\") {\n    return runSet(rest);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `Unknown config subcommand: ${subcommand}`,\n    ExitCode.InvalidArguments,\n    {\n      hint: configHelp(),\n    },\n  );\n}\n","import { startDevServer, type RunningDevServer } from \"@loro-dev/sqlite-riverrun\";\nimport { parseArgs } from \"node:util\";\nimport { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, renderHelp } from \"../core/help\";\nimport type { CommandContext, CommandOutput } from \"../core/types\";\n\ninterface DevCommandDeps {\n  startDevServer: typeof startDevServer;\n  writeStdout: (value: string) => void;\n}\n\nconst defaultDeps: DevCommandDeps = {\n  startDevServer,\n  writeStdout: (value) => {\n    process.stdout.write(value);\n  },\n};\n\nfunction devHelp(): string {\n  return renderHelp({\n    title: \"loro dev\",\n    summary: [\n      \"Start a local single-node Durable Streams dev server backed by SQLite and WAL.\",\n      \"The Rust SQLite runtime defaults to local development without auth and supports explicit buckets and CRDT protocol workflows.\",\n    ],\n    usage: [\n      \"loro dev --db-path <path> [--host <host>] [--port <port>] [--verbose]\",\n      \"loro dev --help\",\n    ],\n    options: [\n      {\n        name: \"--db-path <path>\",\n        description: \"SQLite database path to open or create. Required.\",\n      },\n      {\n        name: \"--host <host>\",\n        description: \"Host interface to bind. Defaults to 127.0.0.1.\",\n      },\n      {\n        name: \"--port <port>\",\n        description: \"TCP port to bind. Defaults to 8787. Use 0 to request an ephemeral port.\",\n      },\n      {\n        name: \"--protocol <auto|h2c|http1>\",\n        description: \"Wire protocol to serve. Defaults to auto (HTTP/1.1 WebSocket and H2C on one port).\",\n      },\n      {\n        name: \"--verbose\",\n        description: \"Enable verbose runtime logging from the local server implementation.\",\n      },\n    ],\n    examples: [\n      \"loro dev --db-path ./data/dev.sqlite\",\n      \"loro dev --host 127.0.0.1 --port 8787 --db-path ./tmp/loro-dev.sqlite\",\n      \"loro dev --port 0 --db-path /tmp/loro-dev.sqlite --json\",\n    ],\n    tips: [\n      \"This command does not switch your active CLI profile; point clients at the printed base URL explicitly.\",\n      \"The SQLite file uses WAL mode so repeated restarts keep durable local state while supporting concurrent reads.\",\n    ],\n    seeAlso: [\n      \"loro stream --help\",\n      \"plans/20260312-sqlite-riverrun-dev-design.md\",\n    ],\n  });\n}\n\nfunction formatStartup(server: RunningDevServer, json: boolean): string {\n  if (json) {\n    return `${JSON.stringify(\n      {\n        ok: true,\n        data: {\n          baseUrl: server.baseUrl,\n          host: server.host,\n          port: server.port,\n          protocol: server.protocol,\n          dbPath: server.dbPath,\n          dataDir: server.dataDir,\n          sqliteJournalMode: server.sqliteJournalMode,\n        },\n        meta: { version: \"0.1\" },\n      },\n      null,\n      2,\n    )}\\n`;\n  }\n\n  return [\n    \"Local Loro Streams dev server started:\",\n    `baseUrl: ${server.baseUrl}`,\n    `host: ${server.host}`,\n    `port: ${server.port}`,\n    `protocol: ${server.protocol}`,\n    `dbPath: ${server.dbPath}`,\n    `dataDir: ${server.dataDir}`,\n    `sqliteJournalMode: ${server.sqliteJournalMode}`,\n  ].join(\"\\n\") + \"\\n\";\n}\n\nexport async function runDevCommand(\n  args: string[],\n  context: CommandContext,\n  deps: DevCommandDeps = defaultDeps,\n): Promise<CommandOutput> {\n  if (args.length === 0 || hasHelpFlag(args)) {\n    return { text: devHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      \"db-path\": { type: \"string\" },\n      host: { type: \"string\" },\n      port: { type: \"string\" },\n      protocol: { type: \"string\" },\n      verbose: { type: \"boolean\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const dbPath = parsed.values[\"db-path\"];\n  if (!dbPath) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--db-path is required\",\n      ExitCode.InvalidArguments,\n      { hint: \"loro dev --db-path ./data/dev.sqlite\" },\n    );\n  }\n\n  const portValue = parsed.values.port;\n  const port = portValue == null ? 8787 : Number.parseInt(portValue, 10);\n  if (!Number.isInteger(port) || port < 0 || port > 65535) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Invalid --port value\", ExitCode.InvalidArguments);\n  }\n  const protocol = parsed.values.protocol;\n  if (protocol != null && protocol !== \"auto\" && protocol !== \"h2c\" && protocol !== \"http1\") {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Invalid --protocol value\", ExitCode.InvalidArguments);\n  }\n\n  const server = await deps.startDevServer({\n    dbPath,\n    host: parsed.values.host,\n    port,\n    protocol,\n    verbose: parsed.values.verbose ?? false,\n  });\n\n  deps.writeStdout(formatStartup(server, context.json));\n\n  const onSignal = () => {\n    void server.close();\n  };\n\n  process.once(\"SIGINT\", onSignal);\n  process.once(\"SIGTERM\", onSignal);\n\n  try {\n    await server.closed;\n  } finally {\n    process.off(\"SIGINT\", onSignal);\n    process.off(\"SIGTERM\", onSignal);\n  }\n\n  return { suppressFinalOutput: true };\n}\n","import { parseArgs } from \"node:util\";\nimport {\n  applyEnvOverrides,\n  assertCredentialTransport,\n  profileUrlSource,\n  ensureProfile,\n  loadCredentials,\n  resolveProfileName,\n  saveCredentials,\n} from \"../core/credentials\";\nimport { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport { ensureHttpOk, httpRequest } from \"../core/http\";\nimport { ensureAccessToken } from \"../core/tokens\";\nimport type { CommandOutput } from \"../core/types\";\n\ninterface RequestOptions {\n  profile?: string;\n  path: string;\n  method?: string;\n  query?: Record<string, string | number | boolean | undefined>;\n  body?: unknown;\n}\n\nasync function dashboardRequest<T = unknown>(opts: RequestOptions) {\n  const access = await ensureAccessToken({\n    profileName: opts.profile,\n    audience: \"dashboard\",\n  });\n\n  const headers: Record<string, string> = {\n    authorization: `Bearer ${access.token}`,\n  };\n\n  if (access.profile.activeOrgId) {\n    headers[\"x-loro-org-id\"] = access.profile.activeOrgId;\n  }\n\n  const response = await httpRequest<T>({\n    baseUrl: access.profile.dashboardBaseUrl,\n    path: opts.path,\n    method: opts.method,\n    headers,\n    query: opts.query,\n    body: opts.body,\n  });\n\n  return {\n    response,\n    access,\n  };\n}\n\nfunction dashboardHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard\",\n    summary: [\n      \"Call dashboard control-plane APIs for organization administration, billing/quota inspection, bucket inventory, and API key lifecycle management.\",\n      \"Most subcommands require a dashboard access token from `loro auth login` and use the active org stored in the selected profile.\",\n    ],\n    usage: [\n      \"loro dashboard <resource> <action> [options]\",\n      \"loro dashboard <resource> --help\",\n      \"loro dashboard <resource> <action> --help\",\n    ],\n    commands: [\n      {\n        name: \"buckets\",\n        description: \"List buckets visible to the current org in the dashboard/control-plane view.\",\n      },\n      {\n        name: \"usage\",\n        description: \"Inspect aggregated usage counters for a time window.\",\n      },\n      {\n        name: \"quota\",\n        description: \"Read the current org quota and billing state.\",\n      },\n      {\n        name: \"storage\",\n        description: \"Read storage snapshot history for the current org.\",\n      },\n      {\n        name: \"organizations\",\n        description: \"List available orgs or switch the active org context.\",\n      },\n      {\n        name: \"members\",\n        description: \"List, invite, or remove organization members.\",\n      },\n      {\n        name: \"api-key\",\n        description: \"Create, inspect, revoke, verify, or exchange API keys for data-plane JWTs.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile for auth, base URL resolution, and org context.\",\n      },\n      {\n        name: \"--json\",\n        description: \"Return machine-readable data for scripting and agent workflows.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard organizations list\",\n      \"loro dashboard organizations activate --id org_123\",\n      \"loro dashboard members invite --email new@example.com --role member\",\n      \"loro dashboard api-key create --name agent-key --bucket demo\",\n      \"loro dashboard usage get --from 2026-03-01T00:00:00.000Z --to 2026-03-02T00:00:00.000Z\",\n    ],\n    tips: [\n      \"If a command behaves as if it is in the wrong org, run `loro auth whoami` or `loro dashboard organizations list` before retrying.\",\n      \"`api-key verify` and `api-key token` do not require a logged-in dashboard session, but they still use the profile to decide which dashboard base URL to call.\",\n    ],\n    seeAlso: [\n      \"loro auth --help\",\n      \"loro dashboard api-key --help\",\n      \"loro dashboard members --help\",\n      \"loro dashboard organizations --help\",\n    ],\n  });\n}\n\nfunction bucketsHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard buckets\",\n    summary: [\n      \"Browse bucket inventory from the dashboard's org-scoped view. This is useful for admin/audit tasks, not for reading stream payloads.\",\n    ],\n    usage: [\n      \"loro dashboard buckets list [--profile <name>]\",\n      \"loro dashboard buckets list --help\",\n    ],\n    commands: [\n      {\n        name: \"list\",\n        description: \"List buckets with current byte usage and stream counts.\",\n      },\n    ],\n    seeAlso: [\"loro dashboard buckets list --help\", \"loro bucket --help\"],\n  });\n}\n\nfunction bucketsListHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard buckets list\",\n    summary: [\n      \"List buckets visible to the active org and print a compact summary of current bytes and stream counts.\",\n    ],\n    usage: [\"loro dashboard buckets list [--profile <name>]\"],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile for dashboard auth and org context.\",\n      },\n    ],\n    examples: [\"loro dashboard buckets list\", \"loro dashboard buckets list --profile prod\"],\n    tips: [\n      \"Use `loro bucket get <bucket>` when you need the data-plane view of an individual bucket rather than the dashboard inventory list.\",\n    ],\n  });\n}\n\nfunction usageHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard usage\",\n    summary: [\n      \"Inspect aggregated usage records for the active org. This is a reporting view rather than a raw event log.\",\n    ],\n    usage: [\n      \"loro dashboard usage get [--from <iso>] [--to <iso>] [--profile <name>]\",\n      \"loro dashboard usage get --help\",\n    ],\n    commands: [\n      {\n        name: \"get\",\n        description: \"Return usage counters for the requested time window.\",\n      },\n    ],\n    seeAlso: [\"loro dashboard usage get --help\", \"loro dashboard quota get --help\"],\n  });\n}\n\nfunction usageGetHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard usage get\",\n    summary: [\n      \"Fetch aggregated usage rows for the active org. Results are grouped by operation and include request/response byte counts.\",\n    ],\n    usage: [\"loro dashboard usage get [--from <iso>] [--to <iso>] [--profile <name>]\"],\n    options: [\n      {\n        name: \"--from <iso>\",\n        description: \"ISO-8601 lower bound, rounded down to a UTC hour.\",\n      },\n      {\n        name: \"--to <iso>\",\n        description: \"Exclusive ISO-8601 upper bound, rounded up to a UTC hour.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard usage get\",\n      \"loro dashboard usage get --from 2026-03-01T00:00:00.000Z --to 2026-03-31T23:59:59.999Z\",\n    ],\n    tips: [\n      \"When omitted, `--from` and `--to` let the server choose its default reporting window.\",\n    ],\n  });\n}\n\nfunction quotaHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard quota\",\n    summary: [\"Inspect the current org quota and billing-related suspension state.\"],\n    usage: [\n      \"loro dashboard quota get [--profile <name>]\",\n      \"loro dashboard quota get --help\",\n    ],\n    commands: [{ name: \"get\", description: \"Return the current quota record for the active org.\" }],\n    seeAlso: [\"loro dashboard quota get --help\", \"loro dashboard storage get --help\"],\n  });\n}\n\nfunction quotaGetHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard quota get\",\n    summary: [\n      \"Fetch the active org's quota configuration, billing balance, and suspension status.\",\n    ],\n    usage: [\"loro dashboard quota get [--profile <name>]\"],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard quota get\"],\n  });\n}\n\nfunction storageHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard storage\",\n    summary: [\n      \"Inspect historical storage snapshots for the active org. This is useful for trend analysis and reclaim planning.\",\n    ],\n    usage: [\n      \"loro dashboard storage get [--profile <name>]\",\n      \"loro dashboard storage get --help\",\n    ],\n    commands: [\n      {\n        name: \"get\",\n        description: \"Return sampled storage totals and reclaimable bytes.\",\n      },\n    ],\n    seeAlso: [\"loro dashboard storage get --help\", \"loro dashboard usage get --help\"],\n  });\n}\n\nfunction storageGetHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard storage get\",\n    summary: [\n      \"Fetch the sampled storage series for the active org, including total and reclaimable bytes.\",\n    ],\n    usage: [\"loro dashboard storage get [--profile <name>]\"],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard storage get\"],\n  });\n}\n\nfunction organizationsHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard organizations\",\n    summary: [\n      \"List organizations the current user can access or switch which organization the CLI treats as active.\",\n    ],\n    usage: [\n      \"loro dashboard organizations <action> [options]\",\n      \"loro dashboard organizations <action> --help\",\n    ],\n    commands: [\n      {\n        name: \"list\",\n        description: \"List organizations visible to the current user and show the currently active org id.\",\n      },\n      {\n        name: \"activate\",\n        description: \"Switch the active org for the selected profile and the current dashboard session.\",\n      },\n    ],\n    seeAlso: [\"loro dashboard organizations list --help\", \"loro dashboard organizations activate --help\"],\n  });\n}\n\nfunction organizationsListHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard organizations list\",\n    summary: [\n      \"List organizations visible to the current dashboard identity and print the currently active org id.\",\n    ],\n    usage: [\"loro dashboard organizations list [--profile <name>]\"],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard organizations list\"],\n    tips: [\n      \"Use the returned `id` value with `loro dashboard organizations activate --id <org-id>` or `loro auth use-org <org-id>`.\",\n    ],\n  });\n}\n\nfunction organizationsActivateHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard organizations activate\",\n    summary: [\n      \"Set the active org for later dashboard commands and persist it in the selected local profile.\",\n    ],\n    usage: [\"loro dashboard organizations activate --id <org-id> [--profile <name>]\"],\n    options: [\n      { name: \"--id <org-id>\", description: \"Organization id to activate. Required.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard organizations activate --id org_123\"],\n    tips: [\n      \"This command updates local state. `loro auth use-org` offers the same outcome under the `auth` command group if you prefer to stay in the auth flow.\",\n    ],\n    seeAlso: [\"loro auth use-org --help\", \"loro dashboard organizations list\"],\n  });\n}\n\nfunction membersHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard members\",\n    summary: [\n      \"Manage organization membership for the active org or an explicitly selected org.\",\n    ],\n    usage: [\n      \"loro dashboard members <action> [options]\",\n      \"loro dashboard members <action> --help\",\n    ],\n    commands: [\n      {\n        name: \"list\",\n        description: \"List current members for an org.\",\n      },\n      {\n        name: \"invite\",\n        description: \"Create a new member invitation with the requested role.\",\n      },\n      {\n        name: \"remove\",\n        description: \"Remove a member by member id or email.\",\n      },\n    ],\n    seeAlso: [\n      \"loro dashboard members list --help\",\n      \"loro dashboard members invite --help\",\n      \"loro dashboard members remove --help\",\n    ],\n  });\n}\n\nfunction membersListHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard members list\",\n    summary: [\"List members for the active org, or for an explicitly chosen organization id.\"],\n    usage: [\n      \"loro dashboard members list [--organization-id <org-id>] [--profile <name>]\",\n    ],\n    options: [\n      {\n        name: \"--organization-id <org-id>\",\n        description: \"Override the active org for this request only.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard members list\",\n      \"loro dashboard members list --organization-id org_123\",\n    ],\n  });\n}\n\nfunction membersInviteHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard members invite\",\n    summary: [\n      \"Create a membership invitation for a user email in the active org or an explicitly chosen org.\",\n    ],\n    usage: [\n      \"loro dashboard members invite --email <email> --role <member|admin|owner> [--organization-id <org-id>] [--profile <name>]\",\n    ],\n    options: [\n      { name: \"--email <email>\", description: \"Invitee email address. Required.\" },\n      {\n        name: \"--role <role>\",\n        description: \"Role to assign on acceptance. Must be one of `member`, `admin`, or `owner`.\",\n      },\n      {\n        name: \"--organization-id <org-id>\",\n        description: \"Override the active org for this request only.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard members invite --email new@example.com --role member\",\n      \"loro dashboard members invite --email admin@example.com --role admin --organization-id org_123\",\n    ],\n    tips: [\n      \"Use `owner` sparingly; it is normally reserved for org administrators.\",\n    ],\n  });\n}\n\nfunction membersRemoveHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard members remove\",\n    summary: [\n      \"Remove an org member by member id or email. This operates on the active org unless an override is provided.\",\n    ],\n    usage: [\n      \"loro dashboard members remove --member-id-or-email <value> [--organization-id <org-id>] [--profile <name>]\",\n    ],\n    options: [\n      {\n        name: \"--member-id-or-email <value>\",\n        description: \"Exact member identifier or email. Required.\",\n      },\n      {\n        name: \"--organization-id <org-id>\",\n        description: \"Override the active org for this request only.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard members remove --member-id-or-email user_123\",\n      \"loro dashboard members remove --member-id-or-email dev@example.com\",\n    ],\n  });\n}\n\nfunction apiKeyHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key\",\n    summary: [\n      \"Manage API keys for service or agent access. Most actions require a logged-in dashboard session, while `verify` and `token` work directly with an API key.\",\n    ],\n    usage: [\n      \"loro dashboard api-key <action> [options]\",\n      \"loro dashboard api-key <action> --help\",\n    ],\n    commands: [\n      {\n        name: \"create\",\n        description: \"Create a new long-lived API key. The raw secret is returned only once.\",\n      },\n      {\n        name: \"list\",\n        description: \"List API keys for the active org, including previews for audit and rotation planning.\",\n      },\n      {\n        name: \"revoke\",\n        description: \"Revoke an API key immediately by id.\",\n      },\n      {\n        name: \"verify\",\n        description: \"Validate an API key and inspect its resolved permissions without needing a human session.\",\n      },\n      {\n        name: \"token\",\n        description: \"Exchange an API key for a short-lived JWT that can call the gateway/data plane.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard api-key create --name agent-key --bucket demo\",\n      \"loro dashboard api-key list\",\n      \"loro dashboard api-key token --key <api-key>\",\n    ],\n    tips: [\n      \"Prefer `token` when a workload needs a short-lived JWT and should not send the raw API key to the gateway directly.\",\n      \"Store the `key` from `create` immediately; later `list` only returns previews.\",\n    ],\n    seeAlso: [\n      \"loro dashboard api-key create --help\",\n      \"loro dashboard api-key token --help\",\n      \"loro auth token --help\",\n    ],\n  });\n}\n\nfunction apiKeyCreateHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key create\",\n    summary: [\n      \"Create a new long-lived API key scoped to one existing bucket in the active org.\",\n    ],\n    usage: [\n      \"loro dashboard api-key create --name <name> --bucket <bucket> [--expires-in <sec>] [--profile <name>]\",\n    ],\n    options: [\n      { name: \"--name <name>\", description: \"Human-readable label for the key. Required.\" },\n      {\n        name: \"--bucket <bucket>\",\n        description: \"Existing bucket id to grant this key. Required.\",\n      },\n      {\n        name: \"--expires-in <sec>\",\n        description: \"Optional lifetime in seconds. Omit for the server's default key lifetime.\",\n      },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile.\",\n      },\n    ],\n    sections: [\n      {\n        title: \"Generated Permissions\",\n        lines: [\n          \"The server checks that the bucket exists in the authenticated org before creating the key.\",\n          \"The key is stored as an exact-bucket gateway scope for the selected bucket.\",\n          \"Allowed operations: bucket-get, stream-read, stream-head, stream-bootstrap-read, stream-snapshot-read, stream-create, stream-append, stream-snapshot-write.\",\n          \"Destructive operations such as bucket-delete, stream-delete, stream-close, and stream-snapshot-delete are not granted.\",\n          \"The old `--permissions` / `buckets` JSON syntax is deprecated and rejected by the server.\",\n        ],\n      },\n    ],\n    examples: [\n      \"loro dashboard api-key create --name agent-key --bucket demo\",\n      \"loro dashboard api-key create --name ci-key --bucket prod-data --expires-in 3600\",\n    ],\n    tips: [\n      \"The response includes both `id` and the raw `key`. The raw key is the secret; save it immediately because it is not shown again later.\",\n      \"Run `loro dashboard api-key token --key <api-key>` to exchange the API key for a short-lived gateway JWT.\",\n    ],\n  });\n}\n\nfunction apiKeyListHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key list\",\n    summary: [\n      \"List API keys for the active org with stable ids and redacted previews.\",\n    ],\n    usage: [\"loro dashboard api-key list [--profile <name>]\"],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard api-key list\"],\n  });\n}\n\nfunction apiKeyRevokeHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key revoke\",\n    summary: [\n      \"Revoke an API key immediately by id. Use this for emergency invalidation or rotation cleanup.\",\n    ],\n    usage: [\"loro dashboard api-key revoke --id <id> [--profile <name>]\"],\n    options: [\n      { name: \"--id <id>\", description: \"API key id to revoke. Required.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\"loro dashboard api-key revoke --id key_123\"],\n  });\n}\n\nfunction apiKeyVerifyHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key verify\",\n    summary: [\n      \"Validate an API key and inspect its resolved permissions. This endpoint does not require a logged-in dashboard session.\",\n    ],\n    usage: [\"loro dashboard api-key verify --key <api-key> [--profile <name>]\"],\n    options: [\n      { name: \"--key <api-key>\", description: \"Raw API key secret to verify. Required.\" },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific profile only to choose the dashboard base URL.\",\n      },\n    ],\n    examples: [\"loro dashboard api-key verify --key lk_test_abc\"],\n    tips: [\n      \"Use this before `token` if you are unsure whether a key belongs to the expected org or carries the expected scope.\",\n    ],\n  });\n}\n\nfunction apiKeyTokenHelp(): string {\n  return renderHelp({\n    title: \"loro dashboard api-key token\",\n    summary: [\n      \"Exchange an API key for a short-lived JWT suitable for gateway/data-plane calls.\",\n    ],\n    usage: [\"loro dashboard api-key token --key <api-key> [--profile <name>]\"],\n    options: [\n      { name: \"--key <api-key>\", description: \"Raw API key secret to exchange. Required.\" },\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific profile only to choose the dashboard base URL.\",\n      },\n    ],\n    examples: [\n      \"loro dashboard api-key token --key lk_test_abc\",\n      \"loro dashboard api-key token --key lk_test_abc --json\",\n    ],\n    tips: [\n      \"The returned JWT is short-lived. Refresh it again with the same API key when it expires.\",\n      \"Use this instead of embedding human dashboard tokens into services.\",\n    ],\n    seeAlso: [\"loro auth token --help\", \"loro stream --help\"],\n  });\n}\n\nfunction formatBuckets(payload: Record<string, unknown>): string {\n  const buckets = Array.isArray(payload.buckets) ? payload.buckets : [];\n\n  if (buckets.length === 0) {\n    return \"No buckets found.\";\n  }\n\n  const lines = [\"Buckets:\"];\n  for (const item of buckets) {\n    const bucket = item as Record<string, unknown>;\n    lines.push(\n      `- ${String(bucket.bucket_id ?? \"unknown\")} bytes=${String(bucket.current_bytes ?? 0)} streams=${String(bucket.stream_count ?? 0)}`,\n    );\n  }\n\n  return lines.join(\"\\n\");\n}\n\nfunction formatUsage(payload: Record<string, unknown>): string {\n  const usage = Array.isArray(payload.usage) ? payload.usage : [];\n  const lines = [usage.length === 0 ? \"No usage entries found.\" : \"Usage:\"];\n  if (payload.granularity === \"hour\") {\n    lines.push(\n      `UTC hours: [${String(payload.effective_from ?? \"unbounded\")}, ${String(payload.effective_to ?? \"unbounded\")})`,\n    );\n  }\n  for (const item of usage) {\n    const row = item as Record<string, unknown>;\n    lines.push(\n      `- ${String(row.operation ?? \"unknown\")} count=${String(row.request_count ?? 0)} reqBytes=${String(row.request_bytes ?? 0)} respBytes=${String(row.response_bytes ?? 0)}`,\n    );\n  }\n\n  return lines.join(\"\\n\");\n}\n\nfunction formatQuota(payload: Record<string, unknown>): string {\n  const quota = payload.quota as Record<string, unknown> | null | undefined;\n\n  if (!quota) {\n    return \"No quota configured.\";\n  }\n\n  return [\n    \"Quota:\",\n    `- maxStorageBytes: ${String(quota.max_storage_bytes ?? \"n/a\")}`,\n    `- maxOpsPerMonth: ${String(quota.max_ops_per_month ?? \"n/a\")}`,\n    `- billingBalance: ${String(quota.billing_balance ?? \"n/a\")}`,\n    `- suspended: ${String(quota.suspended ?? false)}`,\n    `- updatedAt: ${String(quota.updated_at ?? \"n/a\")}`,\n  ].join(\"\\n\");\n}\n\nfunction formatStorage(payload: Record<string, unknown>): string {\n  const entries = Array.isArray(payload.storage) ? payload.storage : [];\n\n  if (entries.length === 0) {\n    return \"No storage snapshots found.\";\n  }\n\n  const lines = [\"Storage snapshots:\"];\n  for (const item of entries) {\n    const row = item as Record<string, unknown>;\n    lines.push(\n      `- ${String(row.sampled_at ?? \"unknown\")} total=${String(row.total_bytes ?? 0)} reclaimable=${String(row.reclaimable_bytes ?? 0)}`,\n    );\n  }\n\n  return lines.join(\"\\n\");\n}\n\nfunction parseExpiresIn(raw: string | undefined): number | undefined {\n  if (!raw) {\n    return undefined;\n  }\n\n  if (!/^\\d+$/.test(raw)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--expires-in must be a positive integer\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const value = Number(raw);\n  if (!Number.isSafeInteger(value) || value <= 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--expires-in must be a positive integer\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return value;\n}\n\nfunction parseMemberRole(raw: string | undefined): \"member\" | \"admin\" | \"owner\" {\n  if (raw === \"member\" || raw === \"admin\" || raw === \"owner\") {\n    return raw;\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--role must be one of: member, admin, owner\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nasync function resolveDashboardBaseUrl(profileName?: string): Promise<string> {\n  const credentials = await loadCredentials();\n  const resolvedProfileName = resolveProfileName(credentials, profileName);\n  const profile = applyEnvOverrides(ensureProfile(credentials, resolvedProfileName));\n  assertCredentialTransport(\n    profile.dashboardBaseUrl,\n    profileUrlSource(resolvedProfileName, \"dashboard\"),\n  );\n  return profile.dashboardBaseUrl;\n}\n\nfunction requireApiKey(value: string | undefined, optionName: string): string {\n  if (!value || value.trim().length === 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      `${optionName} is required`,\n      ExitCode.InvalidArguments,\n    );\n  }\n  return value.trim();\n}\n\nasync function runBuckets(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: bucketsHelp() };\n  }\n\n  const [action, ...rest] = args;\n  if (action !== \"list\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Unknown dashboard buckets action\",\n      ExitCode.InvalidArguments,\n      {\n        hint: bucketsHelp(),\n      },\n    );\n  }\n\n  if (hasHelpFlag(rest)) {\n    return { text: bucketsListHelp() };\n  }\n\n  const parsed = parseArgs({\n    args: rest,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/dashboard/buckets\",\n  });\n\n  ensureHttpOk(response, \"Failed to list buckets\");\n  const payload = response.data ?? {};\n\n  return {\n    text: formatBuckets(payload),\n    data: payload,\n  };\n}\n\nasync function runUsage(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: usageHelp() };\n  }\n\n  const [action, ...rest] = args;\n  if (action !== \"get\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Unknown dashboard usage action\",\n      ExitCode.InvalidArguments,\n      {\n        hint: usageHelp(),\n      },\n    );\n  }\n\n  if (hasHelpFlag(rest)) {\n    return { text: usageGetHelp() };\n  }\n\n  const parsed = parseArgs({\n    args: rest,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      from: { type: \"string\" },\n      to: { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/dashboard/usage\",\n    query: {\n      granularity: \"hour\",\n      from: parsed.values.from,\n      to: parsed.values.to,\n    },\n  });\n\n  ensureHttpOk(response, \"Failed to get usage\");\n  const payload = response.data ?? {};\n\n  return {\n    text: formatUsage(payload),\n    data: payload,\n  };\n}\n\nasync function runQuota(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: quotaHelp() };\n  }\n\n  const [action, ...rest] = args;\n  if (action !== \"get\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Unknown dashboard quota action\",\n      ExitCode.InvalidArguments,\n      {\n        hint: quotaHelp(),\n      },\n    );\n  }\n\n  if (hasHelpFlag(rest)) {\n    return { text: quotaGetHelp() };\n  }\n\n  const parsed = parseArgs({\n    args: rest,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/dashboard/quota\",\n  });\n\n  ensureHttpOk(response, \"Failed to get quota\");\n  const payload = response.data ?? {};\n\n  return {\n    text: formatQuota(payload),\n    data: payload,\n  };\n}\n\nasync function runStorage(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: storageHelp() };\n  }\n\n  const [action, ...rest] = args;\n  if (action !== \"get\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Unknown dashboard storage action\",\n      ExitCode.InvalidArguments,\n      {\n        hint: storageHelp(),\n      },\n    );\n  }\n\n  if (hasHelpFlag(rest)) {\n    return { text: storageGetHelp() };\n  }\n\n  const parsed = parseArgs({\n    args: rest,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/dashboard/storage\",\n  });\n\n  ensureHttpOk(response, \"Failed to get storage snapshots\");\n  const payload = response.data ?? {};\n\n  return {\n    text: formatStorage(payload),\n    data: payload,\n  };\n}\n\nasync function runOrganizations(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: organizationsHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"list\") {\n    if (hasHelpFlag(rest)) {\n      return { text: organizationsListHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length > 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n    }\n\n    const { response } = await dashboardRequest<Record<string, unknown>>({\n      profile: parsed.values.profile,\n      path: \"/api/dashboard/organizations\",\n    });\n\n    ensureHttpOk(response, \"Failed to list organizations\");\n    const payload = response.data ?? {};\n    const organizations = Array.isArray(payload.organizations) ? payload.organizations : [];\n    const activeOrganizationId =\n      typeof payload.active_organization_id === \"string\" ? payload.active_organization_id : \"n/a\";\n\n    const lines = organizations.length > 0 ? [\"Organizations:\"] : [\"No organizations found.\"];\n    for (const item of organizations) {\n      const organization = item as Record<string, unknown>;\n      lines.push(\n        `- ${String(organization.id ?? \"unknown\")} ${String(organization.name ?? \"(unnamed)\")} slug=${String(organization.slug ?? \"n/a\")}`,\n      );\n    }\n    lines.push(`activeOrganizationId: ${activeOrganizationId}`);\n\n    return {\n      text: lines.join(\"\\n\"),\n      data: payload,\n    };\n  }\n\n  if (action === \"activate\") {\n    if (hasHelpFlag(rest)) {\n      return { text: organizationsActivateHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        id: { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length > 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n    }\n\n    const id = parsed.values.id;\n    if (!id || id.trim().length === 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"--id is required\", ExitCode.InvalidArguments);\n    }\n    const normalizedId = id.trim();\n\n    const { response } = await dashboardRequest<Record<string, unknown>>({\n      profile: parsed.values.profile,\n      path: \"/api/dashboard/organizations/activate\",\n      method: \"POST\",\n      body: {\n        organization_id: normalizedId,\n      },\n    });\n\n    ensureHttpOk(response, \"Failed to activate organization\");\n    const payload = response.data ?? {};\n\n    const credentials = await loadCredentials();\n    const profileName = resolveProfileName(credentials, parsed.values.profile);\n    const profile = ensureProfile(credentials, profileName);\n    profile.activeOrgId = normalizedId;\n    await saveCredentials(credentials);\n\n    return {\n      text: `Active organization switched to ${normalizedId} (profile=${profileName})`,\n      data: payload,\n    };\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown dashboard organizations action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: organizationsHelp(),\n    },\n  );\n}\n\nasync function runMembers(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: membersHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"list\") {\n    if (hasHelpFlag(rest)) {\n      return { text: membersListHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        \"organization-id\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length > 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n    }\n\n    const { response } = await dashboardRequest<Record<string, unknown>>({\n      profile: parsed.values.profile,\n      path: \"/api/dashboard/members\",\n      query: {\n        organization_id: parsed.values[\"organization-id\"],\n      },\n    });\n\n    ensureHttpOk(response, \"Failed to list members\");\n    const payload = response.data ?? {};\n    const members = Array.isArray(payload.members) ? payload.members : [];\n\n    const lines = members.length > 0 ? [\"Members:\"] : [\"No members found.\"];\n    for (const item of members) {\n      const member = item as Record<string, unknown>;\n      const user = member.user as Record<string, unknown> | undefined;\n      lines.push(\n        `- ${String(member.userId ?? \"unknown\")} ${String(user?.email ?? \"n/a\")} role=${String(member.role ?? \"n/a\")}`,\n      );\n    }\n    lines.push(`total: ${String(payload.total ?? members.length)}`);\n\n    return {\n      text: lines.join(\"\\n\"),\n      data: payload,\n    };\n  }\n\n  if (action === \"invite\") {\n    if (hasHelpFlag(rest)) {\n      return { text: membersInviteHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        email: { type: \"string\" },\n        role: { type: \"string\" },\n        \"organization-id\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length > 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n    }\n\n    const email = parsed.values.email?.trim();\n    if (!email) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"--email is required\", ExitCode.InvalidArguments);\n    }\n    const role = parseMemberRole(parsed.values.role);\n\n    const body: Record<string, unknown> = {\n      email,\n      role,\n    };\n    const organizationId = parsed.values[\"organization-id\"]?.trim();\n    if (organizationId) {\n      body.organization_id = organizationId;\n    }\n\n    const { response } = await dashboardRequest<Record<string, unknown>>({\n      profile: parsed.values.profile,\n      path: \"/api/dashboard/members/invite\",\n      method: \"POST\",\n      body,\n    });\n\n    ensureHttpOk(response, \"Failed to invite member\");\n    const payload = response.data ?? {};\n    const invitation = payload.invitation as Record<string, unknown> | undefined;\n\n    return {\n      text: [\n        \"Member invitation created:\",\n        `- id: ${String(invitation?.id ?? \"n/a\")}`,\n        `- email: ${String(invitation?.email ?? email)}`,\n        `- role: ${String(invitation?.role ?? role)}`,\n      ].join(\"\\n\"),\n      data: payload,\n    };\n  }\n\n  if (action === \"remove\") {\n    if (hasHelpFlag(rest)) {\n      return { text: membersRemoveHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        \"member-id-or-email\": { type: \"string\" },\n        \"organization-id\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length > 0) {\n      throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n    }\n\n    const memberIdOrEmail = parsed.values[\"member-id-or-email\"]?.trim();\n    if (!memberIdOrEmail) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"--member-id-or-email is required\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const body: Record<string, unknown> = {\n      member_id_or_email: memberIdOrEmail,\n    };\n    const organizationId = parsed.values[\"organization-id\"]?.trim();\n    if (organizationId) {\n      body.organization_id = organizationId;\n    }\n\n    const { response } = await dashboardRequest<Record<string, unknown>>({\n      profile: parsed.values.profile,\n      path: \"/api/dashboard/members/remove\",\n      method: \"POST\",\n      body,\n    });\n\n    ensureHttpOk(response, \"Failed to remove member\");\n    const payload = response.data ?? {};\n\n    return {\n      text: `Member removed: ${memberIdOrEmail}`,\n      data: payload,\n    };\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown dashboard members action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: membersHelp(),\n    },\n  );\n}\n\nasync function runApiKeyCreate(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: apiKeyCreateHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      name: { type: \"string\" },\n      bucket: { type: \"string\" },\n      \"expires-in\": { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const name = parsed.values.name;\n  const bucket = parsed.values.bucket?.trim();\n\n  if (!name) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"--name is required\", ExitCode.InvalidArguments);\n  }\n  if (!bucket) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"--bucket is required\", ExitCode.InvalidArguments);\n  }\n  const expiresInSeconds = parseExpiresIn(parsed.values[\"expires-in\"]);\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/auth/api-key\",\n    method: \"POST\",\n    body: {\n      name,\n      bucket,\n      expiresInSeconds,\n    },\n  });\n\n  ensureHttpOk(response, \"Failed to create API key\");\n  const payload = response.data ?? {};\n\n  return {\n    text: [\n      \"API key created:\",\n      `- id: ${String(payload.id ?? \"n/a\")}`,\n      `- key: ${String(payload.key ?? \"n/a\")}`,\n    ].join(\"\\n\"),\n    data: payload,\n  };\n}\n\nasync function runApiKeyList(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: apiKeyListHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/auth/api-key/list\",\n  });\n\n  ensureHttpOk(response, \"Failed to list API keys\");\n  const payload = response.data ?? {};\n  const keys = Array.isArray(payload.keys) ? payload.keys : [];\n\n  const lines = keys.length > 0 ? [\"API keys:\"] : [\"No API keys found.\"];\n  for (const item of keys) {\n    const key = item as Record<string, unknown>;\n    lines.push(\n      `- ${String(key.id ?? \"unknown\")} ${String(key.name ?? \"(unnamed)\")} ${String(key.keyPreview ?? \"\")}`,\n    );\n  }\n\n  return {\n    text: lines.join(\"\\n\"),\n    data: payload,\n  };\n}\n\nasync function runApiKeyRevoke(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: apiKeyRevokeHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      id: { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const id = parsed.values.id;\n  if (!id) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"--id is required\", ExitCode.InvalidArguments);\n  }\n\n  const { response } = await dashboardRequest<Record<string, unknown>>({\n    profile: parsed.values.profile,\n    path: \"/api/auth/api-key/revoke\",\n    method: \"POST\",\n    body: { id },\n  });\n\n  ensureHttpOk(response, \"Failed to revoke API key\");\n  const payload = response.data ?? {};\n\n  return {\n    text: `API key revoked: ${id}`,\n    data: payload,\n  };\n}\n\nasync function runApiKeyVerify(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: apiKeyVerifyHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      key: { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const key = requireApiKey(parsed.values.key, \"--key\");\n  const dashboardBaseUrl = await resolveDashboardBaseUrl(parsed.values.profile);\n\n  const response = await httpRequest<Record<string, unknown>>({\n    baseUrl: dashboardBaseUrl,\n    path: \"/api/auth/api-key/verify\",\n    method: \"POST\",\n    body: { key },\n  });\n\n  ensureHttpOk(response, \"Failed to verify API key\");\n  const payload = response.data ?? {};\n\n  return {\n    text: [\n      \"API key verified:\",\n      `- valid: ${String(payload.valid ?? false)}`,\n      `- name: ${String(payload.name ?? \"n/a\")}`,\n      `- referenceId: ${String(payload.referenceId ?? \"n/a\")}`,\n      `- permissions: ${JSON.stringify(payload.permissions ?? {})}`,\n    ].join(\"\\n\"),\n    data: payload,\n  };\n}\n\nasync function runApiKeyToken(args: string[]): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: apiKeyTokenHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      key: { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments);\n  }\n\n  const key = requireApiKey(parsed.values.key, \"--key\");\n  const dashboardBaseUrl = await resolveDashboardBaseUrl(parsed.values.profile);\n\n  const response = await httpRequest<Record<string, unknown>>({\n    baseUrl: dashboardBaseUrl,\n    path: \"/api/auth/api-key/token\",\n    method: \"POST\",\n    headers: {\n      authorization: `Bearer ${key}`,\n    },\n  });\n\n  ensureHttpOk(response, \"Failed to exchange API key for JWT\");\n  const payload = response.data ?? {};\n\n  return {\n    text: [\n      \"JWT issued from API key:\",\n      `- expiresIn: ${String(payload.expires_in ?? \"n/a\")}`,\n      `- token: ${String(payload.token ?? \"n/a\")}`,\n    ].join(\"\\n\"),\n    data: payload,\n  };\n}\n\nasync function runApiKey(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: apiKeyHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"create\") {\n    return runApiKeyCreate(rest);\n  }\n  if (action === \"list\") {\n    return runApiKeyList(rest);\n  }\n  if (action === \"revoke\") {\n    return runApiKeyRevoke(rest);\n  }\n  if (action === \"verify\") {\n    return runApiKeyVerify(rest);\n  }\n  if (action === \"token\") {\n    return runApiKeyToken(rest);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown dashboard api-key action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: apiKeyHelp(),\n    },\n  );\n}\n\nexport async function runDashboardCommand(args: string[]): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: dashboardHelp() };\n  }\n\n  const [resource, ...rest] = args;\n\n  if (resource === \"buckets\") {\n    return runBuckets(rest);\n  }\n  if (resource === \"usage\") {\n    return runUsage(rest);\n  }\n  if (resource === \"quota\") {\n    return runQuota(rest);\n  }\n  if (resource === \"storage\") {\n    return runStorage(rest);\n  }\n  if (resource === \"organizations\") {\n    return runOrganizations(rest);\n  }\n  if (resource === \"members\") {\n    return runMembers(rest);\n  }\n  if (resource === \"api-key\") {\n    return runApiKey(rest);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `Unknown dashboard resource: ${resource}`,\n    ExitCode.InvalidArguments,\n    {\n      hint: dashboardHelp(),\n    },\n  );\n}\n","export interface SseEvent {\n  event: string;\n  data: string;\n}\n\nexport async function consumeSseStream(\n  stream: ReadableStream<Uint8Array>,\n  onEvent: (event: SseEvent) => void | Promise<void>,\n): Promise<void> {\n  const reader = stream.getReader();\n  const decoder = new TextDecoder();\n\n  let buffer = \"\";\n  let eventType = \"message\";\n  let dataLines: string[] = [];\n\n  const dispatch = async (): Promise<void> => {\n    if (dataLines.length === 0) {\n      eventType = \"message\";\n      return;\n    }\n\n    const payload = dataLines.join(\"\\n\");\n    dataLines = [];\n\n    await onEvent({\n      event: eventType,\n      data: payload,\n    });\n\n    eventType = \"message\";\n  };\n\n  try {\n    while (true) {\n      const { value, done } = await reader.read();\n      if (done) {\n        break;\n      }\n\n      buffer += decoder.decode(value, { stream: true });\n\n      while (true) {\n        const newlineIndex = buffer.indexOf(\"\\n\");\n        if (newlineIndex < 0) {\n          break;\n        }\n\n        const line = buffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n        buffer = buffer.slice(newlineIndex + 1);\n\n        if (line.length === 0) {\n          await dispatch();\n          continue;\n        }\n\n        if (line.startsWith(\":\")) {\n          continue;\n        }\n\n        const separatorIndex = line.indexOf(\":\");\n        const field = separatorIndex >= 0 ? line.slice(0, separatorIndex) : line;\n        const valuePart =\n          separatorIndex >= 0\n            ? line.slice(separatorIndex + 1).replace(/^ /, \"\")\n            : \"\";\n\n        if (field === \"event\") {\n          eventType = valuePart || \"message\";\n        } else if (field === \"data\") {\n          dataLines.push(valuePart);\n        }\n      }\n    }\n\n    buffer += decoder.decode();\n    if (buffer.length > 0) {\n      const line = buffer.replace(/\\r$/, \"\");\n      if (line.startsWith(\"data:\")) {\n        dataLines.push(line.slice(5).replace(/^ /, \"\"));\n      }\n    }\n\n    await dispatch();\n  } catch (error) {\n    await reader.cancel().catch(() => undefined);\n    throw error;\n  } finally {\n    reader.releaseLock();\n  }\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { parseArgs } from \"node:util\";\nimport {\n  StreamsClient,\n  createStreamPart,\n  type BootstrapOutput as StreamsBootstrapOutput,\n  type StreamError,\n  type StreamOperationMeta,\n  type StreamPart,\n} from \"@loro-dev/streams-client\";\nimport { consumeSseStream } from \"../core/sse\";\nimport { CliError, ExitCode, fromHttpStatus } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport { ensureAccessToken } from \"../core/tokens\";\nimport type { CommandContext, CommandOutput } from \"../core/types\";\nimport { sleep } from \"../core/utils\";\n\nclass StopWatchError extends Error {\n  constructor() {\n    super(\"watch stopped\");\n  }\n}\n\ntype OutputFormat = \"text\" | \"jsonl\";\ntype LiveMode = \"none\" | \"sse\";\ntype ReadBodyFraming = \"json-array\" | \"binary\" | \"raw\";\ntype MessageKind = \"json\" | \"binary\";\ntype MessageRenderMode = \"auto\" | \"utf8\" | \"hex\" | \"base64\" | \"json\";\ntype ReadFramingMode = \"auto\" | \"raw\" | \"binary\";\ntype AppendFramingMode = \"auto\" | \"raw\" | \"binary\";\n\nconst BINARY_CONTENT_TYPE = \"application/octet-stream\";\nconst JSON_CONTENT_TYPE = \"application/json\";\nconst UTF8_DECODER = new TextDecoder(\"utf-8\");\nconst UTF8_ENCODER = new TextEncoder();\nconst EMPTY_BYTES = new Uint8Array();\nconst SAFE_WATCH_CONTROL_FIELDS = [\n  \"streamNextOffset\",\n  \"stream_next_offset\",\n  \"nextOffset\",\n  \"streamCursor\",\n  \"stream_cursor\",\n  \"streamUpToDate\",\n  \"stream_up_to_date\",\n  \"streamClosed\",\n  \"stream_closed\",\n] as const;\n\ninterface WatchState {\n  emittedEvents: number;\n  nextOffset: string;\n}\n\ninterface RequestBodyResult {\n  body?: Uint8Array;\n  source: \"none\" | \"inline\" | \"file\";\n}\n\ninterface GatewayResponseData {\n  request: {\n    method: string;\n    url: string;\n  };\n  response: {\n    status: number;\n    statusText: string;\n    headers: Record<string, string>;\n  };\n  contentType: string | null;\n  rawBody: Uint8Array;\n}\n\ninterface DsResponseData {\n  request: {\n    method: string;\n    url: string;\n  };\n  response: {\n    status: number;\n    statusText: string;\n    headers: Record<string, string>;\n  };\n  body: {\n    kind: \"empty\" | \"text\" | \"binary\";\n    bytes: number;\n    preview: string;\n    text?: string;\n    sha256?: string;\n    truncated?: boolean;\n  };\n}\n\ninterface DecodedMessage {\n  id: string;\n  index: number;\n  kind: MessageKind;\n  length: number;\n  bytes: Uint8Array;\n  value?: unknown;\n}\n\ninterface DecodedReadBody {\n  framing: ReadBodyFraming;\n  messages: DecodedMessage[];\n}\n\ninterface RenderedMessage {\n  id: string;\n  index: number;\n  kind: MessageKind;\n  length: number;\n  data: string;\n  truncated: boolean;\n}\n\ninterface StreamReadData {\n  request: {\n    method: string;\n    url: string;\n  };\n  response: {\n    status: number;\n    statusText: string;\n    headers: Record<string, string>;\n  };\n  body: {\n    kind: \"messages\";\n    bytes: number;\n    contentType: string | null;\n    framing: ReadBodyFraming;\n    messageCount: number;\n  };\n  messages: RenderedMessage[];\n}\n\ninterface StreamInspectData extends StreamReadData {\n  message: RenderedMessage;\n}\n\nfunction bucketHelp(): string {\n  return renderHelp({\n    title: \"loro bucket\",\n    summary: [\n      \"Manage bucket lifecycle in the gateway/data-plane API.\",\n    ],\n    usage: [\n      \"loro bucket <action> <bucket> [options]\",\n      \"loro bucket <action> --help\",\n    ],\n    commands: [\n      { name: \"create\", description: \"Create a bucket if it does not already exist.\" },\n      { name: \"get\", description: \"Inspect a bucket and print the HTTP/header summary returned by the gateway.\" },\n      { name: \"delete\", description: \"Delete a bucket from the data plane.\" },\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier. Empty names are rejected.\" },\n    ],\n    seeAlso: [\n      \"loro bucket create --help\",\n      \"loro bucket get --help\",\n      \"loro bucket delete --help\",\n      \"loro dashboard buckets list\",\n      \"loro stream --help\",\n    ],\n  });\n}\n\nfunction bucketActionHelp(action: \"create\" | \"get\" | \"delete\"): string {\n  const actionDescriptions = {\n    create: \"Create a bucket in the data plane.\",\n    get: \"Inspect a bucket in the data plane.\",\n    delete: \"Delete a bucket in the data plane.\",\n  } as const;\n\n  return renderHelp({\n    title: `loro bucket ${action}`,\n    summary: [actionDescriptions[action]],\n    usage: [`loro bucket ${action} <bucket> [--profile <name>]`],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier to operate on.\" },\n    ],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [`loro bucket ${action} demo`],\n  });\n}\n\nfunction streamHelp(): string {\n  return renderHelp({\n    title: \"loro stream\",\n    summary: [\n      \"Operate on durable streams: lifecycle management, append, read, live tail, message inspection, recovery, and snapshots.\",\n      \"This command group uses gateway tokens. The CLI obtains or refreshes them from your stored auth profile automatically.\",\n    ],\n    usage: [\n      \"loro stream <action> ...\",\n      \"loro stream <action> --help\",\n    ],\n    commands: [\n      { name: \"create\", description: \"Create a stream and optionally set its content type.\" },\n      { name: \"append\", description: \"Append one payload to a stream, with raw or binary framing.\" },\n      { name: \"read\", description: \"Read stream contents once, with framing-aware decoding and optional SSE mode.\" },\n      { name: \"watch\", description: \"Agent-friendly live tail with optional reconnect and max-event limits.\" },\n      { name: \"inspect\", description: \"Inspect one decoded message by its index within the current read window.\" },\n      { name: \"head\", description: \"Fetch stream headers only, without the body.\" },\n      { name: \"delete\", description: \"Delete a stream.\" },\n      { name: \"close\", description: \"Close a stream without deleting history. Appends may be rejected afterwards.\" },\n      { name: \"bootstrap\", description: \"Run the server-defined recovery/bootstrap endpoint once, then continue with ordinary reads.\" },\n      { name: \"snapshot\", description: \"Read or write stream snapshots keyed by a stream offset.\" },\n    ],\n    options: [\n      {\n        name: \"--profile <name>\",\n        description: \"Use a specific local profile for gateway base URL and auth.\",\n      },\n      {\n        name: \"--json\",\n        description: \"Return structured data for non-streaming commands. Streaming commands still emit event lines directly.\",\n      },\n    ],\n    examples: [\n      \"loro stream create demo s1 --content-type application/json\",\n      \"loro stream append demo s1 --data '{\\\"type\\\":\\\"update\\\"}'\",\n      \"loro stream read demo s1 --format jsonl\",\n      \"loro stream watch demo s1 --from now --format jsonl --reconnect\",\n    ],\n    tips: [\n      \"Use `loro stream watch` when you want a long-running tail with reconnect behavior and bounded output for CI or agents.\",\n      \"Use `loro stream read` when you want a one-shot read window with framing-aware message decoding.\",\n      \"Offsets are opaque. Persist and replay them exactly as returned by the server.\",\n    ],\n    seeAlso: [\n      \"loro stream read --help\",\n      \"loro stream append --help\",\n      \"loro stream watch --help\",\n      \"loro stream snapshot --help\",\n      \"loro bucket --help\",\n      \"loro prompt durable-stream\",\n    ],\n  });\n}\n\nfunction streamCreateHelp(): string {\n  return renderHelp({\n    title: \"loro stream create\",\n    summary: [\n      \"Create a stream inside a bucket. Set `--content-type` explicitly when you want predictable append/read behavior.\",\n    ],\n    usage: [\"loro stream create <bucket> <stream> [--content-type <type>] [--profile <name>]\"],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier inside the bucket.\" },\n    ],\n    options: [\n      {\n        name: \"--content-type <type>\",\n        description: \"Persist the stream content type. Common choices: `application/json` or `application/octet-stream`.\",\n      },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream create demo s1 --content-type application/json\",\n      `loro stream create demo s1 --content-type ${BINARY_CONTENT_TYPE}`,\n    ],\n    tips: [\n      \"Choose the content type before appending data; `append --framing auto` uses it to infer how payloads should be wrapped.\",\n    ],\n  });\n}\n\nfunction streamAppendHelp(): string {\n  return renderHelp({\n    title: \"loro stream append\",\n    summary: [\n      \"Append one payload to a stream from either inline text or a file. The CLI can send raw bytes or wrap the payload with binary framing.\",\n    ],\n    usage: [\n      \"loro stream append <bucket> <stream> [--data <text>|--data-file <path>] [--content-type <type>] [--framing auto|raw|binary] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--data <text>\", description: \"Inline payload text.\" },\n      { name: \"--data-file <path>\", description: \"Read the payload bytes from a file.\" },\n      {\n        name: \"--content-type <type>\",\n        description: \"Override the request content type. If omitted with `--framing auto`, the CLI resolves the stream content type via `HEAD`.\",\n      },\n      {\n        name: \"--framing <mode>\",\n        description: \"Choose `raw`, `binary`, or `auto`. `auto` inspects the stream content type and picks the wrapping strategy.\",\n      },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream append demo s1 --data '{\\\"type\\\":\\\"update\\\"}'\",\n      \"loro stream append demo s1 --data-file ./update.bin --framing binary\",\n      \"loro stream append demo s1 --data hello --framing raw --content-type text/plain\",\n    ],\n    tips: [\n      \"Use exactly one of `--data` or `--data-file`.\",\n      \"When the stream content type is JSON and inline `--data` is not valid JSON, the CLI auto-stringifies it so the request still becomes valid JSON.\",\n      `Binary framing uses the content type \\`${BINARY_CONTENT_TYPE}\\` and preserves per-message boundaries.`,\n    ],\n    seeAlso: [\"loro stream read --help\", \"loro stream inspect --help\"],\n  });\n}\n\nfunction streamReadHelp(): string {\n  return renderHelp({\n    title: \"loro stream read\",\n    summary: [\n      \"Read a stream once and decode the response into message records. You can also switch to direct SSE mode with `--live sse`.\",\n    ],\n    usage: [\n      \"loro stream read <bucket> <stream> [--offset <token>] [--live sse|none] [--format text|jsonl] [--framing auto|raw|binary] [--data-format auto|utf8|hex|base64|json] [--preview-bytes <n>] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--offset <token>\", description: \"Start reading from an explicit offset. Omit it to let the server start from the beginning. In SSE mode the default becomes `now`.\" },\n      { name: \"--live <mode>\", description: \"Use `none` for a one-shot HTTP read or `sse` for a direct SSE tail.\" },\n      { name: \"--format <mode>\", description: \"Human-readable `text` or one-message-per-line `jsonl` output.\" },\n      { name: \"--framing <mode>\", description: \"How to decode message boundaries: `auto`, `raw`, or `binary`.\" },\n      { name: \"--data-format <mode>\", description: \"Render each decoded message as `auto`, `utf8`, `hex`, `base64`, or `json`.\" },\n      { name: \"--preview-bytes <n>\", description: \"Truncate message previews after `n` bytes. Default: 32.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream read demo s1\",\n      \"loro stream read demo s1 --format jsonl --data-format json\",\n      \"loro stream read demo s1 --offset 123 --framing binary --preview-bytes 256\",\n      \"loro stream read demo s1 --live sse --format jsonl\",\n    ],\n    tips: [\n      \"Use `--format jsonl` when another tool needs one structured message per line.\",\n      \"When framing resolves to `raw`, the server did not provide stable message boundaries. Switch the stream to JSON or binary framing if you need per-message inspection.\",\n      \"Use `loro stream watch` instead of `--live sse` when you want reconnect support or a bounded event count.\",\n    ],\n    seeAlso: [\"loro stream watch --help\", \"loro stream inspect --help\"],\n  });\n}\n\nfunction streamInspectHelp(): string {\n  return renderHelp({\n    title: \"loro stream inspect\",\n    summary: [\n      \"Inspect one decoded message from the current read window. The `<message-id>` is the zero-based message index after decoding the response body.\",\n    ],\n    usage: [\n      \"loro stream inspect <bucket> <stream> <message-id> [--offset <token>] [--framing auto|raw|binary] [--data-format auto|utf8|hex|base64|json] [--preview-bytes <n>] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n      { name: \"<message-id>\", description: \"Zero-based message index within the current decoded read window.\" },\n    ],\n    options: [\n      { name: \"--offset <token>\", description: \"Start the read window from an explicit offset before selecting the message index.\" },\n      { name: \"--framing <mode>\", description: \"How to decode message boundaries: `auto`, `raw`, or `binary`.\" },\n      { name: \"--data-format <mode>\", description: \"Render the selected message as `auto`, `utf8`, `hex`, `base64`, or `json`.\" },\n      { name: \"--preview-bytes <n>\", description: \"Truncate the rendered preview after `n` bytes. Default: 4096.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream inspect demo s1 0\",\n      \"loro stream inspect demo s1 3 --offset 123 --data-format hex\",\n    ],\n    tips: [\n      \"If the requested index does not exist in the current read window, the command fails with 404-like semantics.\",\n      \"For raw framing, message index 0 usually means the entire response body because no internal message boundaries are available.\",\n    ],\n    seeAlso: [\"loro stream read --help\"],\n  });\n}\n\nfunction streamHeadHelp(): string {\n  return renderHelp({\n    title: \"loro stream head\",\n    summary: [\"Fetch stream headers only. This is useful for checking offsets or metadata without transferring the body.\"],\n    usage: [\"loro stream head <bucket> <stream> [--profile <name>]\"],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [{ name: \"--profile <name>\", description: \"Use a specific local profile.\" }],\n    examples: [\"loro stream head demo s1\"],\n  });\n}\n\nfunction streamDeleteHelp(): string {\n  return renderHelp({\n    title: \"loro stream delete\",\n    summary: [\"Delete a stream and its stored data.\"],\n    usage: [\"loro stream delete <bucket> <stream> [--profile <name>]\"],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [{ name: \"--profile <name>\", description: \"Use a specific local profile.\" }],\n    examples: [\"loro stream delete demo s1\"],\n  });\n}\n\nfunction streamCloseHelp(): string {\n  return renderHelp({\n    title: \"loro stream close\",\n    summary: [\n      \"Transition a stream from open to closed without deleting historical data. This sends `POST` to the stream URL with `Stream-Closed: true` and an empty body.\",\n    ],\n    usage: [\"loro stream close <bucket> <stream> [--profile <name>]\"],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [{ name: \"--profile <name>\", description: \"Use a specific local profile.\" }],\n    examples: [\"loro stream close demo s1\"],\n    seeAlso: [\"loro stream head --help\", \"loro stream delete --help\"],\n  });\n}\n\nfunction streamBootstrapHelp(): string {\n  return renderHelp({\n    title: \"loro stream bootstrap\",\n    summary: [\n      \"Run the bootstrap/recovery endpoint for a stream. This is typically used after retention gaps or `410 Gone` responses.\",\n    ],\n    usage: [\n      \"loro stream bootstrap <bucket> <stream> [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream bootstrap demo s1\",\n    ],\n    tips: [\n      \"Reach for this when the server tells you your previous offset is no longer valid because of retention or compaction.\",\n      \"To keep tailing after bootstrap, continue with `loro stream read --live sse` from the returned `Stream-Next-Offset`.\",\n    ],\n    seeAlso: [\"loro stream read --help\", \"loro stream watch --help\"],\n  });\n}\n\nfunction streamSnapshotHelp(): string {\n  return renderHelp({\n    title: \"loro stream snapshot\",\n    summary: [\n      \"Read or write snapshots associated with a stream offset. Snapshots are useful for fast rehydration before replaying later updates.\",\n    ],\n    usage: [\n      \"loro stream snapshot <action> ...\",\n      \"loro stream snapshot <action> --help\",\n    ],\n    commands: [\n      { name: \"read\", description: \"Read the latest snapshot or a snapshot at a specific offset.\" },\n      { name: \"write\", description: \"Write a snapshot payload for a specific stream offset.\" },\n    ],\n    seeAlso: [\n      \"loro stream snapshot read --help\",\n      \"loro stream snapshot write --help\",\n      \"loro stream bootstrap --help\",\n    ],\n  });\n}\n\nfunction streamSnapshotReadHelp(): string {\n  return renderHelp({\n    title: \"loro stream snapshot read\",\n    summary: [\n      \"Read the latest snapshot or the snapshot stored at a specific offset. `--latest` returns a friendly empty result instead of an error when no snapshot exists yet.\",\n    ],\n    usage: [\n      \"loro stream snapshot read <bucket> <stream> [--at <offset>|--latest] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--at <offset>\", description: \"Read the snapshot stored for an explicit offset.\" },\n      { name: \"--latest\", description: \"Read the latest snapshot for the stream.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream snapshot read demo s1 --latest\",\n      \"loro stream snapshot read demo s1 --at 123\",\n    ],\n    tips: [\n      \"Use exactly one of `--at` or `--latest`.\",\n    ],\n  });\n}\n\nfunction streamSnapshotWriteHelp(): string {\n  return renderHelp({\n    title: \"loro stream snapshot write\",\n    summary: [\n      \"Write a snapshot payload for a specific stream offset using bytes read from a file.\",\n    ],\n    usage: [\n      \"loro stream snapshot write <bucket> <stream> --at <offset> --data-file <path> [--content-type <type>] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--at <offset>\", description: \"Offset the snapshot corresponds to. Required.\" },\n      { name: \"--data-file <path>\", description: \"Read the snapshot bytes from a file. Required.\" },\n      { name: \"--content-type <type>\", description: \"Optional request content type for the snapshot payload.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream snapshot write demo s1 --at 123 --data-file ./snapshot.bin\",\n      \"loro stream snapshot write demo s1 --at 123 --data-file ./snapshot.json --content-type application/json\",\n    ],\n    tips: [\n      \"Snapshots do not replace the append-only log. They are a checkpoint that should be paired with later replay from the returned stream offsets.\",\n    ],\n  });\n}\n\nfunction watchHelp(): string {\n  return renderHelp({\n    title: \"loro stream watch\",\n    summary: [\n      \"Open an SSE watch on a stream and emit compact text lines or JSONL events. This command is designed for long-running tails, CI smoke tests, and agent loops.\",\n    ],\n    usage: [\n      \"loro stream watch <bucket> <stream> [--from now|-1|<offset>] [--format text|jsonl] [--reconnect] [--max-events <n>] [--profile <name>]\",\n    ],\n    arguments: [\n      { name: \"<bucket>\", description: \"Bucket identifier.\" },\n      { name: \"<stream>\", description: \"Stream identifier.\" },\n    ],\n    options: [\n      { name: \"--from <offset>\", description: \"Start from `now`, `-1` (stream beginning), or an explicit offset token. Default: `now`.\" },\n      { name: \"--format <mode>\", description: \"Emit compact `text` lines or one JSON object per line (`jsonl`).\" },\n      { name: \"--reconnect\", description: \"Reconnect automatically and continue from the last observed next offset.\" },\n      { name: \"--max-events <n>\", description: \"Stop cleanly after `n` events. Useful in CI and scripts.\" },\n      { name: \"--profile <name>\", description: \"Use a specific local profile.\" },\n    ],\n    examples: [\n      \"loro stream watch demo s1\",\n      \"loro stream watch demo s1 --from -1 --format jsonl\",\n      \"loro stream watch demo s1 --reconnect --max-events 10\",\n    ],\n    tips: [\n      \"Unlike `--json` on non-streaming commands, watch output is streamed directly and does not use the envelope format.\",\n      \"Use `--reconnect` when the server or CDN closes idle SSE connections and you want tailing to continue automatically.\",\n    ],\n    seeAlso: [\"loro stream read --help\", \"loro stream bootstrap --help\"],\n  });\n}\n\nfunction parseMaxEvents(value: string | undefined): number | undefined {\n  if (!value) {\n    return undefined;\n  }\n\n  if (!/^\\d+$/.test(value)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--max-events must be a positive integer\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const parsed = Number(value);\n  if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--max-events must be a positive integer\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return parsed;\n}\n\nfunction parsePreviewBytes(value: string | undefined, optionName: string, fallback: number): number {\n  if (!value) {\n    return fallback;\n  }\n  if (!/^\\d+$/.test(value)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      `${optionName} must be a positive integer`,\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const parsed = Number(value);\n  if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      `${optionName} must be a positive integer`,\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return parsed;\n}\n\nfunction parseOutputFormat(raw: string | undefined, optionName: string): OutputFormat {\n  if (!raw || raw === \"text\") {\n    return \"text\";\n  }\n  if (raw === \"jsonl\") {\n    return \"jsonl\";\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `${optionName} must be one of: text, jsonl`,\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction parseMessageRenderMode(raw: string | undefined): MessageRenderMode {\n  if (!raw || raw === \"auto\") {\n    return \"auto\";\n  }\n\n  if (raw === \"utf8\" || raw === \"hex\" || raw === \"base64\" || raw === \"json\") {\n    return raw;\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--data-format must be one of: auto, utf8, hex, base64, json\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction parseMessageId(raw: string): number {\n  if (!/^\\d+$/.test(raw)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"<message-id> must be a non-negative integer\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const parsed = Number(raw);\n  if (!Number.isSafeInteger(parsed)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"<message-id> is out of range\",\n      ExitCode.InvalidArguments,\n    );\n  }\n  return parsed;\n}\n\nfunction parseReadFramingMode(raw: string | undefined): ReadFramingMode {\n  if (!raw || raw === \"auto\") {\n    return \"auto\";\n  }\n  if (raw === \"raw\" || raw === \"binary\") {\n    return raw;\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--framing must be one of: auto, raw, binary\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction parseAppendFramingMode(raw: string | undefined): AppendFramingMode {\n  if (!raw || raw === \"auto\") {\n    return \"auto\";\n  }\n  if (raw === \"raw\") {\n    return \"raw\";\n  }\n  if (raw === \"binary\") {\n    return \"binary\";\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--framing must be one of: auto, raw, binary\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction parseLiveMode(raw: string | undefined): LiveMode {\n  if (!raw || raw === \"none\") {\n    return \"none\";\n  }\n  if (raw === \"sse\") {\n    return \"sse\";\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--live must be one of: none, sse\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction baseContentType(contentType: string | null): string {\n  return contentType?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nfunction isJsonContentType(contentType: string | null): boolean {\n  return baseContentType(contentType) === \"application/json\";\n}\n\nfunction isBinaryContentType(contentType: string | null): boolean {\n  return baseContentType(contentType) === BINARY_CONTENT_TYPE;\n}\n\nfunction safeJsonParse(value: string): unknown {\n  try {\n    return JSON.parse(value) as unknown;\n  } catch {\n    return value;\n  }\n}\n\nfunction extractNextOffset(value: unknown): string | undefined {\n  if (typeof value !== \"object\" || value === null) {\n    return undefined;\n  }\n\n  const record = value as Record<string, unknown>;\n\n  if (typeof record.streamNextOffset === \"string\" && record.streamNextOffset.length > 0) {\n    return record.streamNextOffset;\n  }\n\n  if (typeof record.stream_next_offset === \"string\" && record.stream_next_offset.length > 0) {\n    return record.stream_next_offset;\n  }\n\n  if (typeof record.nextOffset === \"string\" && record.nextOffset.length > 0) {\n    return record.nextOffset;\n  }\n\n  return undefined;\n}\n\nfunction sanitizeWatchEventData(eventType: string, parsedData: unknown): unknown {\n  if (eventType !== \"control\" || typeof parsedData !== \"object\" || parsedData === null) {\n    return parsedData;\n  }\n\n  const record = parsedData as Record<string, unknown>;\n  const sanitized: Record<string, unknown> = {};\n  for (const key of SAFE_WATCH_CONTROL_FIELDS) {\n    if (record[key] !== undefined) {\n      sanitized[key] = record[key];\n    }\n  }\n  return sanitized;\n}\n\nfunction renderTextEvent(eventType: string, parsedData: unknown): string {\n  const sanitizedData = sanitizeWatchEventData(eventType, parsedData);\n\n  if (eventType === \"control\" && typeof sanitizedData === \"object\" && sanitizedData !== null) {\n    const record = sanitizedData as Record<string, unknown>;\n    return `[control] nextOffset=${String(record.streamNextOffset ?? record.stream_next_offset ?? \"n/a\")} cursor=${String(record.streamCursor ?? record.stream_cursor ?? \"n/a\")}`;\n  }\n\n  if (typeof sanitizedData === \"string\") {\n    return `[${eventType}] ${sanitizedData}`;\n  }\n\n  return `[${eventType}] ${JSON.stringify(sanitizedData)}`;\n}\n\nfunction renderJsonlEvent(eventType: string, parsedData: unknown): string {\n  const sanitizedData = sanitizeWatchEventData(eventType, parsedData);\n  return JSON.stringify({\n    event: eventType,\n    data: sanitizedData,\n    receivedAt: new Date().toISOString(),\n  });\n}\n\nfunction emitWatchSummary(context: CommandContext, message: string): void {\n  if (!context.json) {\n    process.stderr.write(`${message}\\n`);\n  }\n}\n\nfunction encodePathPart(value: string, label: string): string {\n  const trimmed = value.trim();\n  if (!trimmed) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      `${label} cannot be empty`,\n      ExitCode.InvalidArguments,\n    );\n  }\n  if (trimmed === \".\" || trimmed === \"..\" || trimmed.includes(\"/\")) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      `${label} cannot be a path separator or dot segment`,\n      ExitCode.InvalidArguments,\n    );\n  }\n  return encodeURIComponent(trimmed);\n}\n\n/**\n * Resolves a gateway request path against the configured gateway base URL.\n *\n * The path is resolved *relative* to the base so a gateway path prefix such as\n * `https://gateway.example/proxy` survives. A root-absolute\n * `new URL(\"/ds/...\", base)` silently discards that prefix.\n */\nfunction gatewayRequestUrl(gatewayBaseUrl: string, path: string): URL {\n  return new URL(path.replace(/^\\/+/, \"\"), `${gatewayBaseUrl.replace(/\\/+$/g, \"\")}/`);\n}\n\nfunction isTextContentType(contentType: string | null): boolean {\n  if (!contentType) {\n    return true;\n  }\n\n  const normalized = contentType.toLowerCase();\n  return (\n    normalized.startsWith(\"text/\") ||\n    normalized.startsWith(\"application/json\") ||\n    normalized.startsWith(\"application/problem+json\") ||\n    normalized.startsWith(\"application/xml\")\n  );\n}\n\nfunction extractHeaderSummary(headers: Headers): Record<string, string> {\n  const summary: Record<string, string> = {};\n\n  const preferredHeaders = [\n    \"stream-next-offset\",\n    \"stream-snapshot-offset\",\n    \"stream-cursor\",\n    \"stream-up-to-date\",\n    \"stream-closed\",\n    \"stream-snapshot-content-type\",\n    \"stream-sse-data-encoding\",\n    \"producer-epoch\",\n    \"producer-seq\",\n    \"producer-expected-seq\",\n    \"producer-received-seq\",\n    \"etag\",\n    \"location\",\n    \"content-type\",\n    \"cache-control\",\n    \"content-length\",\n  ];\n\n  for (const key of preferredHeaders) {\n    const value = headers.get(key);\n    if (value) {\n      summary[key] = value;\n    }\n  }\n\n  return summary;\n}\n\nfunction trimPreview(text: string, maxChars = 4096): { text: string; truncated: boolean } {\n  if (text.length <= maxChars) {\n    return { text, truncated: false };\n  }\n\n  return {\n    text: `${text.slice(0, maxChars)}\\n...[truncated ${text.length - maxChars} chars]`,\n    truncated: true,\n  };\n}\n\nfunction formatHeaderLines(headers: Record<string, string>): string[] {\n  const entries = Object.entries(headers);\n  if (entries.length === 0) {\n    return [\"(none)\"];\n  }\n\n  return entries.map(([key, value]) => `${key}: ${value}`);\n}\n\nfunction formatDsResponseText(data: DsResponseData): string {\n  const lines: string[] = [];\n  lines.push(`HTTP ${data.response.status} ${data.response.statusText}`);\n  lines.push(`Request: ${data.request.method} ${data.request.url}`);\n  lines.push(\"Headers:\");\n  for (const line of formatHeaderLines(data.response.headers)) {\n    lines.push(`- ${line}`);\n  }\n\n  lines.push(`Body (${data.body.kind}, ${data.body.bytes} bytes):`);\n  lines.push(data.body.preview);\n  return lines.join(\"\\n\");\n}\n\nfunction decodeBodyText(bytes: Uint8Array): string {\n  return UTF8_DECODER.decode(bytes);\n}\n\nfunction bodyPreview(\n  method: string,\n  contentType: string | null,\n  rawBody: Uint8Array,\n): DsResponseData[\"body\"] {\n  if (method === \"HEAD\" || rawBody.length === 0) {\n    return {\n      kind: \"empty\",\n      bytes: rawBody.length,\n      preview: \"(empty)\",\n    };\n  }\n\n  if (isTextContentType(contentType)) {\n    const text = decodeBodyText(rawBody);\n    const { text: preview, truncated } = trimPreview(text);\n    return {\n      kind: \"text\",\n      bytes: rawBody.length,\n      preview,\n      text,\n      truncated,\n    };\n  }\n\n  const sha256 = createHash(\"sha256\").update(rawBody).digest(\"hex\");\n  return {\n    kind: \"binary\",\n    bytes: rawBody.length,\n    preview: `<binary ${rawBody.length} bytes, sha256=${sha256}>`,\n    sha256,\n  };\n}\n\nasync function readBodyFromOptions(options: {\n  data?: string;\n  dataFile?: string;\n  required: boolean;\n}): Promise<RequestBodyResult> {\n  if (options.data && options.dataFile) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Use only one of --data or --data-file.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  if (options.dataFile) {\n    const raw = await readFile(options.dataFile);\n    return {\n      body: new Uint8Array(raw),\n      source: \"file\",\n    };\n  }\n\n  if (typeof options.data === \"string\") {\n    return {\n      body: new TextEncoder().encode(options.data),\n      source: \"inline\",\n    };\n  }\n\n  if (options.required) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"One of --data or --data-file is required.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return { source: \"none\" };\n}\n\nfunction normalizeInlineJsonAppendBody(\n  body: Uint8Array | undefined,\n  source: RequestBodyResult[\"source\"],\n  contentType: string | null | undefined,\n  appendFraming: \"raw\" | \"binary\",\n): { body: Uint8Array | undefined; autoStringified: boolean } {\n  if (\n    !body ||\n    source !== \"inline\" ||\n    appendFraming !== \"raw\" ||\n    !isJsonContentType(contentType ?? null)\n  ) {\n    return { body, autoStringified: false };\n  }\n\n  const text = decodeBodyText(body);\n  try {\n    JSON.parse(text);\n    return { body, autoStringified: false };\n  } catch {\n    return {\n      body: UTF8_ENCODER.encode(JSON.stringify(text)),\n      autoStringified: true,\n    };\n  }\n}\n\nfunction decodeJsonMessages(rawBody: Uint8Array): DecodedMessage[] {\n  const text = decodeBodyText(rawBody);\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text) as unknown;\n  } catch (error) {\n    throw new CliError(\n      \"UPSTREAM_ERROR\",\n      `Read stream returned invalid JSON payload: ${(error as Error).message}`,\n      ExitCode.UpstreamError,\n    );\n  }\n\n  const values = Array.isArray(parsed) ? parsed : [parsed];\n  return values.map((value, index) => {\n    const serialized = JSON.stringify(value);\n    const bytes = UTF8_ENCODER.encode(serialized);\n    return {\n      id: String(index),\n      index,\n      kind: \"json\" as const,\n      length: bytes.length,\n      bytes,\n      value,\n    };\n  });\n}\n\nfunction decodeBinaryMessages(rawBody: Uint8Array): DecodedMessage[] {\n  const messages: DecodedMessage[] = [];\n  const view = new DataView(rawBody.buffer, rawBody.byteOffset, rawBody.byteLength);\n  let cursor = 0;\n  let index = 0;\n\n  while (cursor < rawBody.byteLength) {\n    if (cursor + 4 > rawBody.byteLength) {\n      throw new CliError(\n        \"UPSTREAM_ERROR\",\n        \"Read stream returned invalid binary payload: truncated length prefix\",\n        ExitCode.UpstreamError,\n      );\n    }\n\n    const itemLength = view.getUint32(cursor);\n    cursor += 4;\n    if (cursor + itemLength > rawBody.byteLength) {\n      throw new CliError(\n        \"UPSTREAM_ERROR\",\n        \"Read stream returned invalid binary payload: truncated item data\",\n        ExitCode.UpstreamError,\n      );\n    }\n\n    const bytes = rawBody.slice(cursor, cursor + itemLength);\n    messages.push({\n      id: String(index),\n      index,\n      kind: \"binary\",\n      length: itemLength,\n      bytes,\n    });\n    cursor += itemLength;\n    index += 1;\n  }\n\n  return messages;\n}\n\nfunction tryDecodeBinaryMessages(rawBody: Uint8Array): DecodedMessage[] | undefined {\n  try {\n    return decodeBinaryMessages(rawBody);\n  } catch {\n    return undefined;\n  }\n}\n\nfunction encodeSingleBinaryMessage(payload: Uint8Array): Uint8Array {\n  const out = new Uint8Array(payload.length + 4);\n  const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n  view.setUint32(0, payload.length);\n  out.set(payload, 4);\n  return out;\n}\n\nfunction decodeReadBody(\n  contentType: string | null,\n  rawBody: Uint8Array,\n  framingMode: ReadFramingMode,\n): DecodedReadBody {\n  if (rawBody.length === 0) {\n    return {\n      framing: \"raw\",\n      messages: [],\n    };\n  }\n\n  if (framingMode === \"raw\") {\n    return {\n      framing: \"raw\",\n      messages: [\n        {\n          id: \"0\",\n          index: 0,\n          kind: \"binary\",\n          length: rawBody.length,\n          bytes: rawBody,\n        },\n      ],\n    };\n  }\n\n  if (isJsonContentType(contentType)) {\n    return {\n      framing: \"json-array\",\n      messages: decodeJsonMessages(rawBody),\n    };\n  }\n\n  if (framingMode === \"binary\") {\n    return {\n      framing: \"binary\",\n      messages: decodeBinaryMessages(rawBody),\n    };\n  }\n\n  if (framingMode === \"auto\" && isBinaryContentType(contentType)) {\n    const maybeMessages = tryDecodeBinaryMessages(rawBody);\n    if (maybeMessages) {\n      return {\n        framing: \"binary\",\n        messages: maybeMessages,\n      };\n    }\n  }\n\n  return {\n    framing: \"raw\",\n    messages: [\n      {\n        id: \"0\",\n        index: 0,\n        kind: \"binary\",\n        length: rawBody.length,\n        bytes: rawBody,\n      },\n    ],\n  };\n}\n\nfunction truncateBytes(bytes: Uint8Array, maxBytes: number): { bytes: Uint8Array; truncated: boolean } {\n  if (bytes.length <= maxBytes) {\n    return { bytes, truncated: false };\n  }\n  return {\n    bytes: bytes.slice(0, maxBytes),\n    truncated: true,\n  };\n}\n\nfunction inlineTextPreview(value: string): string {\n  return value.replaceAll(\"\\r\", \"\\\\r\").replaceAll(\"\\n\", \"\\\\n\");\n}\n\nfunction renderMessageData(\n  message: DecodedMessage,\n  mode: MessageRenderMode,\n  previewBytes: number,\n): { data: string; truncated: boolean } {\n  const resolvedMode: MessageRenderMode =\n    mode === \"auto\" ? (message.kind === \"json\" ? \"json\" : \"utf8\") : mode;\n\n  if (resolvedMode === \"json\" && message.value !== undefined) {\n    const jsonText = JSON.stringify(message.value);\n    const jsonBytes = UTF8_ENCODER.encode(jsonText);\n    const preview = truncateBytes(jsonBytes, previewBytes);\n    return {\n      data: inlineTextPreview(decodeBodyText(preview.bytes)),\n      truncated: preview.truncated,\n    };\n  }\n\n  const preview = truncateBytes(message.bytes, previewBytes);\n  if (resolvedMode === \"hex\") {\n    return {\n      data: Buffer.from(preview.bytes).toString(\"hex\"),\n      truncated: preview.truncated,\n    };\n  }\n\n  if (resolvedMode === \"base64\" || resolvedMode === \"json\") {\n    return {\n      data: Buffer.from(preview.bytes).toString(\"base64\"),\n      truncated: preview.truncated,\n    };\n  }\n\n  return {\n    data: inlineTextPreview(decodeBodyText(preview.bytes)),\n    truncated: preview.truncated,\n  };\n}\n\nfunction renderDecodedMessages(\n  decoded: DecodedReadBody,\n  mode: MessageRenderMode,\n  previewBytes: number,\n): RenderedMessage[] {\n  return decoded.messages.map((message) => {\n    const preview = renderMessageData(message, mode, previewBytes);\n    return {\n      id: message.id,\n      index: message.index,\n      kind: message.kind,\n      length: message.length,\n      data: preview.data,\n      truncated: preview.truncated,\n    };\n  });\n}\n\nfunction formatStreamReadText(data: StreamReadData): string {\n  const lines: string[] = [];\n  lines.push(`HTTP ${data.response.status} ${data.response.statusText}`);\n  lines.push(`Request: ${data.request.method} ${data.request.url}`);\n  lines.push(\"Headers:\");\n  for (const line of formatHeaderLines(data.response.headers)) {\n    lines.push(`- ${line}`);\n  }\n  lines.push(\n    `Messages (${data.body.messageCount}, framing=${data.body.framing}, contentType=${data.body.contentType ?? \"unknown\"}, bytes=${data.body.bytes}):`,\n  );\n\n  if (data.messages.length === 0) {\n    lines.push(\"(empty)\");\n    return lines.join(\"\\n\");\n  }\n\n  for (const message of data.messages) {\n    lines.push(\n      `- id=${message.id}, kind=${message.kind}, data=${message.data}, length=${message.length}${message.truncated ? \", truncated=true\" : \"\"}`,\n    );\n  }\n\n  if (data.body.framing === \"raw\" && data.body.bytes > 0) {\n    lines.push(\n      \"Note: framing=raw means message boundaries are not available from stream bytes.\",\n    );\n    lines.push(\n      \"Use content-type application/octet-stream with binary framing or JSON mode for stable per-message decoding.\",\n    );\n  }\n\n  return lines.join(\"\\n\");\n}\n\nfunction formatStreamInspectText(data: StreamInspectData): string {\n  const lines: string[] = [];\n  lines.push(`HTTP ${data.response.status} ${data.response.statusText}`);\n  lines.push(`Request: ${data.request.method} ${data.request.url}`);\n  lines.push(\"Headers:\");\n  for (const line of formatHeaderLines(data.response.headers)) {\n    lines.push(`- ${line}`);\n  }\n  lines.push(\"Message:\");\n  lines.push(`- id=${data.message.id}`);\n  lines.push(`- index=${data.message.index}`);\n  lines.push(`- kind=${data.message.kind}`);\n  lines.push(`- length=${data.message.length}`);\n  lines.push(`- data=${data.message.data}${data.message.truncated ? \" (truncated)\" : \"\"}`);\n  return lines.join(\"\\n\");\n}\n\nfunction formatDsOutput(data: DsResponseData, context: CommandContext): CommandOutput {\n  return {\n    text: context.json ? undefined : formatDsResponseText(data),\n    data,\n  };\n}\n\nfunction dsResponseFromMeta(\n  meta: StreamOperationMeta,\n  contentType: string | null,\n  rawBody: Uint8Array,\n): DsResponseData {\n  return {\n    request: meta.request,\n    response: {\n      status: meta.response.status,\n      statusText: meta.response.statusText,\n      headers: extractHeaderSummary(new Headers(meta.response.headers)),\n    },\n    body: bodyPreview(meta.request.method, contentType, rawBody),\n  };\n}\n\nfunction requireOperationMeta(\n  meta: StreamOperationMeta | undefined,\n  actionLabel: string,\n): StreamOperationMeta {\n  if (meta) {\n    return meta;\n  }\n\n  throw new CliError(\n    \"INTERNAL\",\n    `${actionLabel} response was missing request metadata.`,\n    ExitCode.InternalError,\n  );\n}\n\nfunction summarizeStreamPart(part: StreamPart | null): {\n  contentType: string;\n  bytes: number;\n  preview: string;\n  kind: DsResponseData[\"body\"][\"kind\"];\n} | null {\n  if (!part) {\n    return null;\n  }\n\n  const preview = bodyPreview(\"GET\", part.contentType, part.body);\n  return {\n    contentType: part.contentType,\n    bytes: part.body.length,\n    preview: preview.preview,\n    kind: preview.kind,\n  };\n}\n\nfunction encodeBootstrapSummary(output: StreamsBootstrapOutput): Uint8Array {\n  return UTF8_ENCODER.encode(\n    JSON.stringify(\n      {\n        snapshotOffset: output.snapshotOffset,\n        nextOffset: output.nextOffset,\n        upToDate: output.upToDate,\n        cursor: output.cursor ?? null,\n        snapshot: summarizeStreamPart(output.snapshot),\n        updates: output.updates.map((part) => summarizeStreamPart(part)),\n      },\n      null,\n      2,\n    ),\n  );\n}\n\nasync function createStreamsClientForCommand(options: {\n  profile?: string;\n  bucket: string;\n  stream: string;\n}): Promise<StreamsClient> {\n  const access = await ensureAccessToken({\n    profileName: options.profile,\n    audience: \"gateway\",\n  });\n\n  return new StreamsClient({\n    url: gatewayRequestUrl(\n      access.profile.gatewayBaseUrl,\n      `ds/${encodePathPart(options.bucket, \"bucket\")}/${encodePathPart(options.stream, \"stream\")}`,\n    ),\n    auth: access.token,\n    headers: {\n      accept: \"*/*\",\n    },\n  });\n}\n\nasync function ensureBucketExistsForStreamCreate(options: {\n  profile?: string;\n  bucket: string;\n}): Promise<void> {\n  const access = await ensureAccessToken({\n    profileName: options.profile,\n    audience: \"gateway\",\n  });\n  const url = gatewayRequestUrl(\n    access.profile.gatewayBaseUrl,\n    `ds/${encodePathPart(options.bucket, \"bucket\")}`,\n  );\n  const response = await fetch(url, {\n    method: \"PUT\",\n    headers: {\n      authorization: `Bearer ${access.token}`,\n      accept: \"*/*\",\n    },\n  });\n  if (response.status === 200 || response.status === 201 || response.status === 409) {\n    return;\n  }\n  throw new CliError(\n    \"HTTP_ERROR\",\n    `Create bucket failed with HTTP ${response.status}`,\n    ExitCode.UpstreamError,\n    { status: response.status },\n  );\n}\n\nfunction toCliErrorFromStreamError(\n  error: StreamError,\n  actionLabel: string,\n): CliError {\n  switch (error.code) {\n    case \"bad_request\":\n    case \"unauthorized\":\n    case \"forbidden\":\n    case \"not_found\":\n    case \"conflict\":\n    case \"gone\":\n    case \"rate_limited\":\n      return fromHttpStatus(error.status, error.message, { details: error });\n    case \"timeout\":\n      return new CliError(\n        \"TIMEOUT\",\n        `${actionLabel} timed out during ${error.phase}.`,\n        ExitCode.NetworkError,\n        { details: error },\n      );\n    case \"network_error\":\n      return new CliError(\n        \"NETWORK_ERROR\",\n        `${actionLabel} failed due to a network error: ${error.message}`,\n        ExitCode.NetworkError,\n        { cause: error.cause },\n      );\n    case \"protocol_error\":\n      return new CliError(\n        \"UPSTREAM_ERROR\",\n        `${actionLabel} returned an invalid response: ${error.message}`,\n        ExitCode.UpstreamError,\n        {\n          details: error.detail,\n          status: error.status,\n        },\n      );\n    case \"unknown\":\n      if (error.status != null) {\n        return fromHttpStatus(\n          error.status,\n          `${actionLabel} failed: HTTP ${error.status}${error.statusText ? ` ${error.statusText}` : \"\"}${error.status >= 500 || !error.bodyText ? \"\" : `\\n${error.bodyText}`}`,\n          { details: error },\n        );\n      }\n      return new CliError(\n        \"UPSTREAM_ERROR\",\n        `${actionLabel} failed: ${error.message}`,\n        ExitCode.UpstreamError,\n        {\n          cause: error.cause,\n          details: error,\n        },\n      );\n  }\n}\n\nfunction isMissingBucketCreateError(error: StreamError): boolean {\n  return error.code === \"not_found\" && error.bodyText === \"bucket not found\";\n}\n\nasync function executeGatewayRequest(\n  options: {\n    profile?: string;\n    method: string;\n    path: string;\n    query?: Record<string, string | undefined>;\n    headers?: Record<string, string>;\n    body?: Uint8Array;\n    actionLabel: string;\n  },\n): Promise<GatewayResponseData> {\n  const access = await ensureAccessToken({\n    profileName: options.profile,\n    audience: \"gateway\",\n  });\n\n  const url = gatewayRequestUrl(access.profile.gatewayBaseUrl, options.path);\n  if (options.query) {\n    for (const [key, value] of Object.entries(options.query)) {\n      if (typeof value === \"string\" && value.length > 0) {\n        url.searchParams.set(key, value);\n      }\n    }\n  }\n\n  const headers: Record<string, string> = {\n    accept: \"*/*\",\n    authorization: `Bearer ${access.token}`,\n    ...(options.headers ?? {}),\n  };\n\n  let response: Response;\n  try {\n    const requestBody = options.body ? Buffer.from(options.body) : undefined;\n    response = await fetch(url, {\n      method: options.method,\n      headers,\n      body: requestBody,\n    });\n  } catch (error) {\n    throw new CliError(\n      \"NETWORK_ERROR\",\n      `Failed to request gateway endpoint: ${url.toString()}`,\n      ExitCode.NetworkError,\n      { cause: error },\n    );\n  }\n\n  const rawBody = new Uint8Array(await response.arrayBuffer());\n  const contentType = response.headers.get(\"content-type\");\n  if (!response.ok) {\n    const detail =\n      response.status < 500\n        ? isTextContentType(contentType)\n          ? trimPreview(decodeBodyText(rawBody), 512).text\n          : `binary body (${rawBody.length} bytes)`\n        : undefined;\n    throw fromHttpStatus(\n      response.status,\n      `${options.actionLabel} failed: HTTP ${response.status} ${response.statusText}${detail ? `\\n${detail}` : \"\"}`,\n    );\n  }\n\n  return {\n    request: {\n      method: options.method,\n      url: url.toString(),\n    },\n    response: {\n      status: response.status,\n      statusText: response.statusText,\n      headers: extractHeaderSummary(response.headers),\n    },\n    contentType,\n    rawBody,\n  };\n}\n\nasync function runGatewayRequest(\n  options: {\n    profile?: string;\n    method: string;\n    path: string;\n    query?: Record<string, string | undefined>;\n    headers?: Record<string, string>;\n    body?: Uint8Array;\n    actionLabel: string;\n  },\n  context: CommandContext,\n): Promise<CommandOutput> {\n  const response = await executeGatewayRequest(options);\n  const data: DsResponseData = {\n    request: response.request,\n    response: response.response,\n    body: bodyPreview(options.method, response.contentType, response.rawBody),\n  };\n\n  return formatDsOutput(data, context);\n}\n\nasync function runSseRead(\n  options: {\n    profile?: string;\n    path: string;\n    query: Record<string, string | undefined>;\n    actionLabel: string;\n  },\n  context: CommandContext,\n): Promise<CommandOutput> {\n  const access = await ensureAccessToken({\n    profileName: options.profile,\n    audience: \"gateway\",\n  });\n\n  const format: OutputFormat = context.json ? \"jsonl\" : \"text\";\n  const url = gatewayRequestUrl(access.profile.gatewayBaseUrl, options.path);\n  for (const [key, value] of Object.entries(options.query)) {\n    if (typeof value === \"string\" && value.length > 0) {\n      url.searchParams.set(key, value);\n    }\n  }\n\n  let response: Response;\n  try {\n    response = await fetch(url, {\n      method: \"GET\",\n      headers: {\n        accept: \"text/event-stream\",\n        authorization: `Bearer ${access.token}`,\n      },\n    });\n  } catch (error) {\n    throw new CliError(\n      \"NETWORK_ERROR\",\n      `Failed to connect SSE endpoint: ${url.toString()}`,\n      ExitCode.NetworkError,\n      { cause: error },\n    );\n  }\n\n  if (!response.ok) {\n    throw fromHttpStatus(\n      response.status,\n      `${options.actionLabel} failed: HTTP ${response.status} ${response.statusText}`,\n    );\n  }\n\n  if (!response.body) {\n    throw new CliError(\n      \"UPSTREAM_ERROR\",\n      \"Gateway response body is empty for SSE request\",\n      ExitCode.UpstreamError,\n    );\n  }\n\n  let eventCount = 0;\n  let nextOffset = response.headers.get(\"stream-next-offset\") ?? \"n/a\";\n\n  await consumeSseStream(response.body, async (event) => {\n    const parsedData = safeJsonParse(event.data);\n    const safeEventData = sanitizeWatchEventData(event.event, parsedData);\n    const extractedOffset = extractNextOffset(safeEventData);\n    if (extractedOffset) {\n      nextOffset = extractedOffset;\n    }\n\n    if (format === \"jsonl\") {\n      process.stdout.write(`${renderJsonlEvent(event.event, safeEventData)}\\n`);\n    } else {\n      process.stdout.write(`${renderTextEvent(event.event, safeEventData)}\\n`);\n    }\n\n    eventCount += 1;\n  });\n\n  emitWatchSummary(\n    context,\n    `${options.actionLabel} SSE stream ended. events=${eventCount} nextOffset=${nextOffset}`,\n  );\n  return {\n    data: {\n      endpoint: url.toString(),\n      events: eventCount,\n      nextOffset,\n    },\n    suppressFinalOutput: true,\n  };\n}\n\nasync function runStreamReadRequest(\n  options: {\n    profile?: string;\n    path: string;\n    query?: Record<string, string | undefined>;\n    outputFormat: OutputFormat;\n    framingMode: ReadFramingMode;\n    renderMode: MessageRenderMode;\n    previewBytes: number;\n  },\n  context: CommandContext,\n): Promise<CommandOutput> {\n  const response = await executeGatewayRequest({\n    profile: options.profile,\n    method: \"GET\",\n    path: options.path,\n    query: options.query,\n    actionLabel: \"Read stream\",\n  });\n\n  const decoded = decodeReadBody(response.contentType, response.rawBody, options.framingMode);\n  const messages = renderDecodedMessages(decoded, options.renderMode, options.previewBytes);\n\n  const data: StreamReadData = {\n    request: response.request,\n    response: response.response,\n    body: {\n      kind: \"messages\",\n      bytes: response.rawBody.length,\n      contentType: response.contentType,\n      framing: decoded.framing,\n      messageCount: messages.length,\n    },\n    messages,\n  };\n\n  if (context.json) {\n    return { data };\n  }\n\n  if (options.outputFormat === \"jsonl\") {\n    return {\n      text: messages.map((message) => JSON.stringify(message)).join(\"\\n\"),\n      data,\n    };\n  }\n\n  return {\n    text: formatStreamReadText(data),\n    data,\n  };\n}\n\nasync function runStreamInspectRequest(\n  options: {\n    profile?: string;\n    path: string;\n    query?: Record<string, string | undefined>;\n    messageId: number;\n    framingMode: ReadFramingMode;\n    renderMode: MessageRenderMode;\n    previewBytes: number;\n  },\n  context: CommandContext,\n): Promise<CommandOutput> {\n  const response = await executeGatewayRequest({\n    profile: options.profile,\n    method: \"GET\",\n    path: options.path,\n    query: options.query,\n    actionLabel: \"Inspect stream message\",\n  });\n\n  const decoded = decodeReadBody(response.contentType, response.rawBody, options.framingMode);\n  const messages = renderDecodedMessages(decoded, options.renderMode, options.previewBytes);\n  const message = messages.find((candidate) => candidate.index === options.messageId);\n  if (!message) {\n    throw fromHttpStatus(\n      404,\n      `Inspect stream message failed: message id ${options.messageId} was not found in this read window`,\n    );\n  }\n\n  const data: StreamInspectData = {\n    request: response.request,\n    response: response.response,\n    body: {\n      kind: \"messages\",\n      bytes: response.rawBody.length,\n      contentType: response.contentType,\n      framing: decoded.framing,\n      messageCount: messages.length,\n    },\n    messages,\n    message,\n  };\n\n  return {\n    text: context.json ? undefined : formatStreamInspectText(data),\n    data,\n  };\n}\n\nasync function runWatch(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (hasHelpFlag(args)) {\n    return { text: watchHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      from: { type: \"string\", default: \"now\" },\n      format: { type: \"string\" },\n      reconnect: { type: \"boolean\", default: false },\n      \"max-events\": { type: \"string\" },\n      profile: { type: \"string\" },\n    },\n  });\n\n  if (parsed.positionals.length !== 2) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"Usage: loro stream watch <bucket> <stream> [--from now|-1|<offset>] [--format text|jsonl] [--reconnect] [--max-events <n>] [--profile <name>]\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const bucket = parsed.positionals[0];\n  const stream = parsed.positionals[1];\n  const maxEvents = parseMaxEvents(parsed.values[\"max-events\"]);\n\n  const format = parsed.values.format ?? (context.json ? \"jsonl\" : \"text\");\n  if (format !== \"text\" && format !== \"jsonl\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--format must be one of: text, jsonl\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  const reconnect = parsed.values.reconnect;\n  const state: WatchState = {\n    emittedEvents: 0,\n    nextOffset: parsed.values.from,\n  };\n\n  while (true) {\n    const access = await ensureAccessToken({\n      profileName: parsed.values.profile,\n      audience: \"gateway\",\n    });\n\n    const streamPath = `/ds/${encodePathPart(bucket, \"bucket\")}/${encodePathPart(stream, \"stream\")}`;\n    const url = gatewayRequestUrl(access.profile.gatewayBaseUrl, streamPath);\n    url.searchParams.set(\"offset\", state.nextOffset);\n    url.searchParams.set(\"live\", \"sse\");\n\n    const response = await fetch(url, {\n      method: \"GET\",\n      headers: {\n        accept: \"text/event-stream\",\n        authorization: `Bearer ${access.token}`,\n      },\n    }).catch((error) => {\n      throw new CliError(\n        \"NETWORK_ERROR\",\n        `Failed to connect stream watch at ${url.toString()}`,\n        ExitCode.NetworkError,\n        {\n          cause: error,\n        },\n      );\n    });\n\n    if (!response.ok) {\n      throw fromHttpStatus(response.status, `Failed to watch stream ${bucket}/${stream}`);\n    }\n\n    const headerNextOffset = response.headers.get(\"stream-next-offset\");\n    if (headerNextOffset) {\n      state.nextOffset = headerNextOffset;\n    }\n\n    if (!response.body) {\n      throw new CliError(\n        \"UPSTREAM_ERROR\",\n        \"Gateway response body is empty for SSE watch\",\n        ExitCode.UpstreamError,\n      );\n    }\n\n    try {\n      await consumeSseStream(response.body, async (event) => {\n        const parsedData = safeJsonParse(event.data);\n        const safeEventData = sanitizeWatchEventData(event.event, parsedData);\n        const nextOffset = extractNextOffset(safeEventData);\n\n        if (nextOffset) {\n          state.nextOffset = nextOffset;\n        }\n\n        if (format === \"jsonl\") {\n          process.stdout.write(`${renderJsonlEvent(event.event, safeEventData)}\\n`);\n        } else {\n          process.stdout.write(`${renderTextEvent(event.event, safeEventData)}\\n`);\n        }\n\n        state.emittedEvents += 1;\n        if (maxEvents && state.emittedEvents >= maxEvents) {\n          throw new StopWatchError();\n        }\n      });\n    } catch (error) {\n      if (error instanceof StopWatchError) {\n        emitWatchSummary(\n          context,\n          `Watch stopped after ${state.emittedEvents} event(s). nextOffset=${state.nextOffset}`,\n        );\n        return {\n          data: {\n            bucket,\n            stream,\n            events: state.emittedEvents,\n            nextOffset: state.nextOffset,\n            stoppedByMaxEvents: Boolean(maxEvents),\n          },\n          suppressFinalOutput: true,\n        };\n      }\n\n      throw error;\n    }\n\n    if (!reconnect) {\n      break;\n    }\n\n    await sleep(1_000);\n  }\n\n  emitWatchSummary(\n    context,\n    `Watch ended. events=${state.emittedEvents} nextOffset=${state.nextOffset}`,\n  );\n  return {\n    data: {\n      bucket,\n      stream,\n      events: state.emittedEvents,\n      nextOffset: state.nextOffset,\n      reconnect,\n    },\n    suppressFinalOutput: true,\n  };\n}\n\nasync function runBucketCommand(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: bucketHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"create\" || action === \"get\" || action === \"delete\") {\n    if (hasHelpFlag(rest)) {\n      return { text: bucketActionHelp(action) };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 1) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        `Usage: loro bucket ${action} <bucket> [--profile <name>]`,\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const method = action === \"create\" ? \"PUT\" : action === \"get\" ? \"GET\" : \"DELETE\";\n\n    return runGatewayRequest(\n      {\n        profile: parsed.values.profile,\n        method,\n        path: `/ds/${bucket}`,\n        actionLabel: `Bucket ${action}`,\n      },\n      context,\n    );\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown bucket action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: bucketHelp(),\n    },\n  );\n}\n\nasync function runStreamSnapshotCommand(\n  args: string[],\n  context: CommandContext,\n): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: streamSnapshotHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"read\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamSnapshotReadHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        at: { type: \"string\" },\n        latest: { type: \"boolean\", default: false },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream snapshot read <bucket> <stream> [--at <offset>|--latest] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const at = parsed.values.at;\n    const latest = parsed.values.latest;\n\n    if (at && latest) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Use only one of --at or --latest.\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n\n    if (!at && latest) {\n      const result = await client.readLatestSnapshot({\n        includeMeta: true,\n      });\n      if (!result.ok) {\n        throw toCliErrorFromStreamError(result.result, \"Read stream snapshot\");\n      }\n      if (result.result == null) {\n        const data = {\n          snapshot: null,\n          latest: true,\n          found: false,\n          reason: \"No snapshot exists for this stream yet.\",\n        };\n        return {\n          text: context.json ? undefined : \"No snapshot found for this stream yet.\",\n          data,\n        };\n      }\n\n      return formatDsOutput(\n        dsResponseFromMeta(\n          requireOperationMeta(result.result.meta, \"Read stream snapshot\"),\n          result.result.payload.contentType,\n          result.result.payload.body,\n        ),\n        context,\n      );\n    }\n\n    const result = at\n      ? await client.readSnapshot(at, {\n          includeMeta: true,\n        })\n      : await client.readLatestSnapshot({\n          includeMeta: true,\n        });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Read stream snapshot\");\n    }\n    if (result.result == null) {\n      throw new CliError(\n        \"UPSTREAM_ERROR\",\n        \"Read stream snapshot returned no snapshot payload.\",\n        ExitCode.UpstreamError,\n      );\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Read stream snapshot\"),\n        result.result.payload.contentType,\n        result.result.payload.body,\n      ),\n      context,\n    );\n  }\n\n  if (action === \"write\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamSnapshotWriteHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        at: { type: \"string\" },\n        \"data-file\": { type: \"string\" },\n        \"content-type\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream snapshot write <bucket> <stream> --at <offset> --data-file <path> [--content-type <type>] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const at = parsed.values.at;\n    if (!at) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"--at is required\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const dataFile = parsed.values[\"data-file\"];\n    if (!dataFile) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"--data-file is required\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const body = new Uint8Array(await readFile(dataFile));\n\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    const result = await client.putSnapshot({\n      offset: at,\n      part: createStreamPart(\n        parsed.values[\"content-type\"] ?? BINARY_CONTENT_TYPE,\n        body,\n      ),\n      includeMeta: true,\n    });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Write stream snapshot\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Write stream snapshot\"),\n        null,\n        EMPTY_BYTES,\n      ),\n      context,\n    );\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown stream snapshot action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: streamSnapshotHelp(),\n    },\n  );\n}\n\nexport async function runStreamCommand(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (args.length === 0 || isHelpToken(args[0])) {\n    return { text: streamHelp() };\n  }\n\n  const [action, ...rest] = args;\n\n  if (action === \"watch\") {\n    return runWatch(rest, context);\n  }\n\n  if (action === \"create\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamCreateHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        \"content-type\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream create <bucket> <stream> [--content-type <type>] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const contentType = parsed.values[\"content-type\"] ?? JSON_CONTENT_TYPE;\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    let result = await client.create({\n      contentType,\n      includeMeta: true,\n    });\n    if (!result.ok && isMissingBucketCreateError(result.result)) {\n      await ensureBucketExistsForStreamCreate({\n        profile: parsed.values.profile,\n        bucket,\n      });\n      result = await client.create({\n        contentType,\n        includeMeta: true,\n      });\n    }\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Create stream\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Create stream\"),\n        null,\n        EMPTY_BYTES,\n      ),\n      context,\n    );\n  }\n\n  if (action === \"append\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamAppendHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        data: { type: \"string\" },\n        \"data-file\": { type: \"string\" },\n        \"content-type\": { type: \"string\" },\n        framing: { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream append <bucket> <stream> [--data <text>|--data-file <path>] [--content-type <type>] [--framing auto|raw|binary] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const appendFramingMode = parseAppendFramingMode(parsed.values.framing);\n    const inputBody = await readBodyFromOptions({\n      data: parsed.values.data,\n      dataFile: parsed.values[\"data-file\"],\n      required: true,\n    });\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    let contentType = parsed.values[\"content-type\"];\n    let appendFraming: \"raw\" | \"binary\";\n\n    if (appendFramingMode === \"auto\") {\n      if (!contentType) {\n        const head = await executeGatewayRequest({\n          profile: parsed.values.profile,\n          method: \"HEAD\",\n          path: `/ds/${bucket}/${stream}`,\n          actionLabel: \"Resolve append stream content type\",\n        });\n        contentType = head.contentType ?? BINARY_CONTENT_TYPE;\n      }\n\n      appendFraming = isBinaryContentType(contentType) ? \"binary\" : \"raw\";\n    } else {\n      appendFraming = appendFramingMode;\n      contentType =\n        contentType ??\n        (appendFraming === \"binary\" ? BINARY_CONTENT_TYPE : \"application/octet-stream\");\n    }\n\n    const baseBody =\n      appendFraming === \"binary\" && inputBody.body\n        ? encodeSingleBinaryMessage(inputBody.body)\n        : inputBody.body;\n    const normalized = normalizeInlineJsonAppendBody(\n      baseBody,\n      inputBody.source,\n      contentType,\n      appendFraming,\n    );\n\n    const result = await runGatewayRequest(\n      {\n        profile: parsed.values.profile,\n        method: \"POST\",\n        path: `/ds/${bucket}/${stream}`,\n        body: normalized.body,\n        headers: { \"content-type\": contentType },\n        actionLabel: \"Append stream\",\n      },\n      context,\n    );\n\n    if (!context.json && result.text) {\n      result.text = `${result.text}\\nAppend source: ${inputBody.source}\\nAppend framing: ${appendFraming}`;\n      if (normalized.autoStringified) {\n        result.text = `${result.text}\\nAppend payload: auto-stringified as JSON`;\n      }\n    }\n    return result;\n  }\n\n  if (action === \"read\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamReadHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        offset: { type: \"string\" },\n        live: { type: \"string\", default: \"none\" },\n        format: { type: \"string\" },\n        framing: { type: \"string\" },\n        \"data-format\": { type: \"string\" },\n        \"preview-bytes\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream read <bucket> <stream> [--offset <token>] [--live sse|none] [--format text|jsonl] [--framing auto|raw|binary] [--data-format auto|utf8|hex|base64|json] [--preview-bytes <n>] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const live = parseLiveMode(parsed.values.live);\n    const outputFormat = parseOutputFormat(parsed.values.format, \"--format\");\n    const framingMode = parseReadFramingMode(parsed.values.framing);\n    const renderMode = parseMessageRenderMode(parsed.values[\"data-format\"]);\n    const previewBytes = parsePreviewBytes(\n      parsed.values[\"preview-bytes\"],\n      \"--preview-bytes\",\n      32,\n    );\n    const offset = parsed.values.offset ?? (live === \"sse\" ? \"now\" : undefined);\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n\n    if (live === \"sse\") {\n      return runSseRead(\n        {\n          profile: parsed.values.profile,\n          path: `/ds/${bucket}/${stream}`,\n          query: {\n            offset,\n            live: \"sse\",\n          },\n          actionLabel: \"Read stream\",\n        },\n        context,\n      );\n    }\n\n    return runStreamReadRequest(\n      {\n        profile: parsed.values.profile,\n        path: `/ds/${bucket}/${stream}`,\n        query: { offset },\n        outputFormat,\n        framingMode,\n        renderMode,\n        previewBytes,\n      },\n      context,\n    );\n  }\n\n  if (action === \"inspect\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamInspectHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        offset: { type: \"string\" },\n        framing: { type: \"string\" },\n        \"data-format\": { type: \"string\" },\n        \"preview-bytes\": { type: \"string\" },\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 3) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream inspect <bucket> <stream> <message-id> [--offset <token>] [--framing auto|raw|binary] [--data-format auto|utf8|hex|base64|json] [--preview-bytes <n>] [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const messageId = parseMessageId(parsed.positionals[2]);\n    const framingMode = parseReadFramingMode(parsed.values.framing);\n    const renderMode = parseMessageRenderMode(parsed.values[\"data-format\"]);\n    const previewBytes = parsePreviewBytes(\n      parsed.values[\"preview-bytes\"],\n      \"--preview-bytes\",\n      4096,\n    );\n\n    return runStreamInspectRequest(\n      {\n        profile: parsed.values.profile,\n        path: `/ds/${bucket}/${stream}`,\n        query: { offset: parsed.values.offset },\n        messageId,\n        framingMode,\n        renderMode,\n        previewBytes,\n      },\n      context,\n    );\n  }\n\n  if (action === \"head\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamHeadHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream head <bucket> <stream> [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    const result = await client.head({\n      includeMeta: true,\n    });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Head stream\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Head stream\"),\n        null,\n        EMPTY_BYTES,\n      ),\n      context,\n    );\n  }\n\n  if (action === \"delete\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamDeleteHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream delete <bucket> <stream> [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    const result = await client.delete({\n      includeMeta: true,\n    });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Delete stream\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Delete stream\"),\n        null,\n        EMPTY_BYTES,\n      ),\n      context,\n    );\n  }\n\n  if (action === \"close\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamCloseHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream close <bucket> <stream> [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    const result = await client.close({\n      includeMeta: true,\n    });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Close stream\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Close stream\"),\n        null,\n        EMPTY_BYTES,\n      ),\n      context,\n    );\n  }\n\n  if (action === \"bootstrap\") {\n    if (hasHelpFlag(rest)) {\n      return { text: streamBootstrapHelp() };\n    }\n\n    const parsed = parseArgs({\n      args: rest,\n      allowPositionals: true,\n      strict: true,\n      options: {\n        profile: { type: \"string\" },\n      },\n    });\n\n    if (parsed.positionals.length !== 2) {\n      throw new CliError(\n        \"INVALID_ARGUMENTS\",\n        \"Usage: loro stream bootstrap <bucket> <stream> [--profile <name>]\",\n        ExitCode.InvalidArguments,\n      );\n    }\n\n    const bucket = encodePathPart(parsed.positionals[0], \"bucket\");\n    const stream = encodePathPart(parsed.positionals[1], \"stream\");\n    const client = await createStreamsClientForCommand({\n      profile: parsed.values.profile,\n      bucket,\n      stream,\n    });\n    const result = await client.bootstrap({\n      includeMeta: true,\n    });\n    if (!result.ok) {\n      throw toCliErrorFromStreamError(result.result, \"Bootstrap stream\");\n    }\n\n    return formatDsOutput(\n      dsResponseFromMeta(\n        requireOperationMeta(result.result.meta, \"Bootstrap stream\"),\n        JSON_CONTENT_TYPE,\n        encodeBootstrapSummary(result.result),\n      ),\n      context,\n    );\n  }\n\n  if (action === \"snapshot\") {\n    return runStreamSnapshotCommand(rest, context);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Unknown stream action\",\n    ExitCode.InvalidArguments,\n    {\n      hint: streamHelp(),\n    },\n  );\n}\n\nexport { runBucketCommand };\n","import { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport { load as loadYaml } from \"js-yaml\";\nimport {\n  applyEnvOverrides,\n  ensureProfile,\n  loadCredentials,\n  resolveProfileName,\n} from \"../core/credentials\";\nimport { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport type { CommandContext, CommandOutput, PromptSection } from \"../core/types\";\n\nconst runtimeDirectory = dirname(fileURLToPath(import.meta.url));\nconst DASHBOARD_OPENAPI_SOURCE = \"specs/dashboard-api-openapi.yaml\";\nconst GATEWAY_PROTOCOL_SOURCES = [\"specs/ds-protocol.md\", \"specs/ds-extensions.md\"] as const;\n\nconst HTTP_METHOD_ORDER = [\"get\", \"post\", \"put\", \"patch\", \"delete\", \"head\", \"options\"] as const;\n\ntype PromptFormat = \"markdown\" | \"json\" | \"yaml\";\ntype PromptProfile = \"catalog\" | \"minimal\" | \"full\";\ntype PromptTopicId = \"durable-stream\" | \"crdt-integration\" | \"permissions\" | \"backend-api\";\ntype PromptCatalogTopic = PromptTopicId | \"overview\";\n\ninterface PromptCatalogEntry {\n  id: PromptTopicId;\n  title: string;\n  summary: string;\n  command: string;\n  aliases: string[];\n}\n\ninterface PromptJsonOutput {\n  version: \"0.2\";\n  topic: PromptCatalogTopic;\n  sections: PromptSection[];\n  catalog: Array<Pick<PromptCatalogEntry, \"id\" | \"title\" | \"summary\" | \"command\">>;\n}\n\ninterface BackendApiPromptItem {\n  surface: \"dashboard\" | \"gateway\";\n  method: string;\n  path: string;\n  summary: string;\n  tags: string[];\n  auth: string;\n  request: unknown;\n  response: Record<string, unknown>;\n  response_headers: Record<string, Record<string, unknown>>;\n}\n\ninterface BackendApiJsonOutput {\n  version: \"0.3\";\n  topic: \"backend-api\";\n  source: string;\n  sources: string[];\n  surfaces: {\n    dashboard: {\n      base_url: string;\n    };\n    gateway: {\n      base_url: string;\n    };\n  };\n  items: BackendApiPromptItem[];\n}\n\ninterface BackendApiFilters {\n  path?: string;\n  tag?: string;\n}\n\nconst PROMPT_CATALOG: PromptCatalogEntry[] = [\n  {\n    id: \"durable-stream\",\n    title: \"Durable Stream Basics\",\n    summary: \"What DS is, core model, stream lifecycle, and operation patterns.\",\n    command: \"loro prompt durable-stream\",\n    aliases: [\"durable stream\", \"stream basics\", \"stream model\"],\n  },\n  {\n    id: \"crdt-integration\",\n    title: \"Durable Stream For CRDT\",\n    summary: \"How to integrate CRDT updates and use @loro-dev/streams-crdt effectively.\",\n    command: \"loro prompt integration with CRDT\",\n    aliases: [\n      \"crdt\",\n      \"crdt integration\",\n      \"integration with crdt\",\n      \"streams crdt\",\n      \"transport\",\n    ],\n  },\n  {\n    id: \"permissions\",\n    title: \"Permissions And Auth Model\",\n    summary: \"Organization context, API key/JWT flow, and permission boundaries.\",\n    command: \"loro prompt permissions\",\n    aliases: [\"permission\", \"permissions\", \"auth\", \"authorization\", \"access model\", \"scope\"],\n  },\n  {\n    id: \"backend-api\",\n    title: \"Backend API Task Guide\",\n    summary: \"Task-oriented index for deploy dashboard OpenAPI + riverrun gateway (DS protocol) with path/tag filters.\",\n    command: \"loro prompt backend-api\",\n    aliases: [\"backend api\", \"openapi\", \"api\", \"dashboard api\"],\n  },\n];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction promptHelp(): string {\n  return renderHelp({\n    title: \"loro prompt\",\n    summary: [\n      \"Print task-oriented guides for Loro Streams. The default output is an incremental overview, while topic mode dives into one area such as durable streams, CRDT integration, permissions, or backend APIs.\",\n    ],\n    usage: [\n      \"loro prompt\",\n      \"loro prompt topics\",\n      \"loro prompt <topic>\",\n      \"loro prompt <topic> --help\",\n    ],\n    commands: [\n      {\n        name: \"topics\",\n        description: \"List the available prompt topics and the exact commands to open them.\",\n      },\n      {\n        name: \"durable-stream\",\n        description: \"Overview of the DS model, lifecycle, and recovery path.\",\n      },\n      {\n        name: \"crdt-integration\",\n        description: \"How to map CRDT sync to durable streams and related transport tooling.\",\n      },\n      {\n        name: \"permissions\",\n        description: \"Organization context, API key/JWT flow, and permission boundaries.\",\n      },\n      {\n        name: \"backend-api\",\n        description: \"Task-oriented index over dashboard OpenAPI and gateway protocol surfaces, with path/tag filters.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--format <markdown|json|yaml>\",\n        description: \"Choose the output format. YAML is only valid with `backend-api --full`.\",\n      },\n      {\n        name: \"--profile <catalog|minimal|full>\",\n        description: \"Choose how much guide content to emit for the default overview mode.\",\n      },\n      {\n        name: \"--include-context\",\n        description: \"Append runtime profile context such as base URLs and active org id to markdown output.\",\n      },\n      {\n        name: \"--path <openapi-path>\",\n        description: \"Filter `backend-api` output to one path.\",\n      },\n      {\n        name: \"--tag <openapi-tag>\",\n        description: \"Filter `backend-api` output by tag.\",\n      },\n      {\n        name: \"--full\",\n        description: \"With `backend-api`, dump the full dashboard OpenAPI document instead of the compact task guide.\",\n      },\n    ],\n    examples: [\n      \"loro prompt\",\n      \"loro prompt topics\",\n      \"loro prompt durable-stream\",\n      \"loro prompt integration with CRDT\",\n      \"loro prompt backend-api --path /api/auth/api-key/token --format json\",\n      \"loro prompt backend-api --full\",\n    ],\n    tips: [\n      \"Use topic-specific help such as `loro prompt backend-api --help` when you only need one slice of the prompt system.\",\n      \"Prefer the compact `backend-api` view first; use `--full` only when you truly need the entire OpenAPI spec dump.\",\n    ],\n    seeAlso: [\"loro stream --help\", \"loro dashboard --help\"],\n  });\n}\n\nfunction promptTopicsHelp(): string {\n  return renderHelp({\n    title: \"loro prompt topics\",\n    summary: [\n      \"List the available prompt topics. Topics are aliases over curated guides rather than executable API calls.\",\n    ],\n    usage: [\"loro prompt topics\"],\n    commands: PROMPT_CATALOG.map((entry) => ({\n      name: entry.id,\n      description: `${entry.summary} Command: ${entry.command}`,\n    })),\n    seeAlso: PROMPT_CATALOG.map((entry) => entry.command),\n  });\n}\n\nfunction promptTopicHelp(topic: PromptTopicId): string {\n  if (topic === \"durable-stream\") {\n    return renderHelp({\n      title: \"loro prompt durable-stream\",\n      summary: [\n        \"Explain the durable-stream model, lifecycle, recovery flow, and the key `loro stream` commands you are likely to use.\",\n      ],\n      usage: [\"loro prompt durable-stream [--format <markdown|json>] [--include-context]\"],\n      options: [\n        { name: \"--format <markdown|json>\", description: \"Choose markdown or JSON output.\" },\n        { name: \"--include-context\", description: \"Append runtime profile context to markdown output.\" },\n      ],\n      examples: [\"loro prompt durable-stream\", \"loro prompt durable-stream --format json\"],\n      seeAlso: [\"loro stream --help\", \"loro prompt integration with CRDT\"],\n    });\n  }\n\n  if (topic === \"crdt-integration\") {\n    return renderHelp({\n      title: \"loro prompt crdt-integration\",\n      summary: [\n        \"Explain how to connect CRDT updates to durable streams, choose payload formats, and debug end-to-end sync behavior.\",\n      ],\n      usage: [\n        \"loro prompt crdt-integration [--format <markdown|json>] [--include-context]\",\n        \"loro prompt integration with CRDT [--format <markdown|json>] [--include-context]\",\n      ],\n      options: [\n        { name: \"--format <markdown|json>\", description: \"Choose markdown or JSON output.\" },\n        { name: \"--include-context\", description: \"Append runtime profile context to markdown output.\" },\n      ],\n      examples: [\"loro prompt integration with CRDT\", \"loro prompt crdt-integration --format json\"],\n      seeAlso: [\"loro stream append --help\", \"loro prompt durable-stream\"],\n    });\n  }\n\n  if (topic === \"permissions\") {\n    return renderHelp({\n      title: \"loro prompt permissions\",\n      summary: [\n        \"Explain the auth and permission model: human device flow, active org context, API keys, and gateway JWT exchange.\",\n      ],\n      usage: [\"loro prompt permissions [--format <markdown|json>] [--include-context]\"],\n      options: [\n        { name: \"--format <markdown|json>\", description: \"Choose markdown or JSON output.\" },\n        { name: \"--include-context\", description: \"Append runtime profile context to markdown output.\" },\n      ],\n      examples: [\"loro prompt permissions\", \"loro prompt permissions --format json\"],\n      seeAlso: [\"loro auth --help\", \"loro dashboard api-key --help\"],\n    });\n  }\n\n  return renderHelp({\n    title: \"loro prompt backend-api\",\n    summary: [\n      \"Print a compact, task-oriented API index over dashboard OpenAPI plus gateway protocol surfaces, or dump the full dashboard OpenAPI document.\",\n    ],\n    usage: [\n      \"loro prompt backend-api [--path <path>] [--tag <tag>] [--format <markdown|json>]\",\n      \"loro prompt backend-api --full [--format <yaml|json>]\",\n    ],\n    options: [\n      { name: \"--path <openapi-path>\", description: \"Filter the compact task guide to a single path.\" },\n      { name: \"--tag <openapi-tag>\", description: \"Filter the compact task guide by tag.\" },\n      { name: \"--format <markdown|json|yaml>\", description: \"Use markdown or JSON for the compact view; YAML/JSON for `--full`.\" },\n      { name: \"--full\", description: \"Dump the full dashboard OpenAPI document from `specs/dashboard-api-openapi.yaml`.\" },\n      { name: \"--include-context\", description: \"Append runtime profile context to markdown output.\" },\n    ],\n    examples: [\n      \"loro prompt backend-api\",\n      \"loro prompt backend-api --tag ApiKey --format json\",\n      \"loro prompt backend-api --path /api/auth/api-key/token --format json\",\n      \"loro prompt backend-api --full\",\n    ],\n    tips: [\n      \"`--path` and `--tag` only work with `backend-api`.\",\n      \"Use `--full` only when you need the raw OpenAPI material; the compact task guide is easier to consume for both humans and agents.\",\n    ],\n    seeAlso: [\"loro dashboard --help\", \"loro stream --help\"],\n  });\n}\n\nfunction extractLeadingPromptPositionals(args: string[]): string[] {\n  const positionals: string[] = [];\n  for (const arg of args) {\n    if (arg === \"--help\") {\n      continue;\n    }\n    if (arg.startsWith(\"-\")) {\n      break;\n    }\n    positionals.push(arg);\n  }\n  return positionals;\n}\n\nfunction promptTemplateCandidates(file: string): string[] {\n  return [\n    join(runtimeDirectory, \"prompt\", file),\n    join(runtimeDirectory, \"..\", \"prompt\", file),\n  ];\n}\n\nfunction dashboardOpenApiCandidates(): string[] {\n  return [\n    join(runtimeDirectory, \"specs\", \"dashboard-api-openapi.yaml\"),\n    join(runtimeDirectory, \"..\", \"..\", \"..\", \"..\", \"specs\", \"dashboard-api-openapi.yaml\"),\n  ];\n}\n\nasync function readBundledText(candidates: readonly string[]): Promise<string> {\n  let lastError: unknown = null;\n\n  for (const candidate of candidates) {\n    try {\n      return await readFile(candidate, \"utf8\");\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n        lastError = error;\n        continue;\n      }\n      throw error;\n    }\n  }\n\n  throw new CliError(\n    \"MISSING_PROMPT_ASSET\",\n    \"CLI prompt assets are missing from the installed package\",\n    ExitCode.InternalError,\n    {\n      cause: lastError ?? undefined,\n      hint: \"Reinstall the package or rebuild it before packing.\",\n    },\n  );\n}\n\nasync function loadTemplate(profile: \"full\" | \"minimal\"): Promise<string> {\n  const file = profile === \"full\" ? \"full.md\" : \"minimal.md\";\n  return readBundledText(promptTemplateCandidates(file));\n}\n\nfunction parseSections(markdown: string): PromptSection[] {\n  const lines = markdown.split(/\\r?\\n/);\n  const sections: PromptSection[] = [];\n  let currentTitle = \"Overview\";\n  let currentLines: string[] = [];\n\n  const flush = (): void => {\n    if (currentLines.length === 0) {\n      return;\n    }\n\n    const id = currentTitle\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, \"-\")\n      .replace(/^-|-$/g, \"\");\n\n    sections.push({\n      id: id || \"section\",\n      title: currentTitle,\n      content: currentLines.join(\"\\n\").trim(),\n    });\n\n    currentLines = [];\n  };\n\n  for (const line of lines) {\n    if (line.startsWith(\"## \")) {\n      flush();\n      currentTitle = line.slice(3).trim();\n      continue;\n    }\n\n    if (line.startsWith(\"# \") && sections.length === 0 && currentLines.length === 0) {\n      currentTitle = line.slice(2).trim();\n      continue;\n    }\n\n    currentLines.push(line);\n  }\n\n  flush();\n  return sections;\n}\n\nasync function buildContextSection(requestedProfile?: string): Promise<string> {\n  const credentials = await loadCredentials();\n  const profileName = resolveProfileName(credentials, requestedProfile);\n  const profile = applyEnvOverrides(ensureProfile(credentials, profileName));\n\n  const dashboardTokenExpiresAt = profile.auth?.accessTokens?.dashboard?.expiresAt ?? \"n/a\";\n  const gatewayTokenExpiresAt = profile.auth?.accessTokens?.gateway?.expiresAt ?? \"n/a\";\n  const activeOrgId = profile.activeOrgId ?? \"n/a\";\n\n  return [\n    \"## Runtime Context\",\n    \"\",\n    `- profile: ${profileName}`,\n    `- dashboardBaseUrl: ${profile.dashboardBaseUrl}`,\n    `- gatewayBaseUrl: ${profile.gatewayBaseUrl}`,\n    `- activeOrgId: ${activeOrgId}`,\n    `- dashboardAccessTokenExpiresAt: ${dashboardTokenExpiresAt}`,\n    `- gatewayAccessTokenExpiresAt: ${gatewayTokenExpiresAt}`,\n  ].join(\"\\n\");\n}\n\nfunction parsePromptFormat(raw: string | undefined): PromptFormat | undefined {\n  if (!raw) {\n    return undefined;\n  }\n  if (raw === \"markdown\" || raw === \"json\" || raw === \"yaml\") {\n    return raw;\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--format must be one of: markdown, json, yaml\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction parsePromptProfile(raw: string | undefined): PromptProfile {\n  if (!raw || raw === \"catalog\") {\n    return \"catalog\";\n  }\n  if (raw === \"minimal\") {\n    return \"minimal\";\n  }\n  if (raw === \"full\") {\n    return \"full\";\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"--profile must be one of: catalog, minimal, full\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nfunction resolvePromptFormat(\n  topic: PromptTopicId | \"topics\" | undefined,\n  isFullOpenApi: boolean,\n  rawFormat: string | undefined,\n): PromptFormat {\n  const explicitFormat = parsePromptFormat(rawFormat);\n  const resolved = explicitFormat ?? (topic === \"backend-api\" && isFullOpenApi ? \"yaml\" : \"markdown\");\n\n  if (resolved === \"yaml\" && !(topic === \"backend-api\" && isFullOpenApi)) {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--format yaml is only supported by `loro prompt backend-api --full`\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  return resolved;\n}\n\nfunction normalizeTopicQuery(value: string): string {\n  return value\n    .trim()\n    .toLowerCase()\n    .replace(/[_-]+/g, \" \")\n    .replace(/\\s+/g, \" \");\n}\n\nfunction catalogLines(includeHeader: boolean): string[] {\n  const lines: string[] = includeHeader\n    ? [\"## Prompt Directory\", \"\", \"Run one topic command when you need details.\"]\n    : [];\n\n  for (const entry of PROMPT_CATALOG) {\n    lines.push(`- ${entry.title}`);\n    lines.push(`  - command: \\`${entry.command}\\``);\n    lines.push(`  - summary: ${entry.summary}`);\n  }\n  return lines;\n}\n\nfunction renderOverviewMarkdown(profile: \"catalog\" | \"minimal\"): string {\n  const lines = [\n    \"# Loro Streams Agent Guide\",\n    \"\",\n    \"## Landing Page Mental Model (CRDT Sync)\",\n    \"\",\n    \"- You have a CRDT app and want durable, resumable sync (replay + resume from offsets).\",\n    \"- Loro Streams gives you append-only streams + server-provided offsets + live watch (SSE).\",\n    \"- If your sync can be modeled as \\\"append updates\\\" + \\\"resume from last offset\\\", start here.\",\n    \"\",\n    \"## Choose Your Path (Different User Perspectives)\",\n    \"\",\n    \"- CRDT app developer (frontend/mobile):\",\n    \"  - goal: ship doc sync with reconnect + resume\",\n    \"  - install: `npm install @loro-dev/streams-crdt` when you need to wire CRDT sync into your app\",\n    \"  - next: `loro prompt integration with CRDT`\",\n    \"- Backend/service developer:\",\n    \"  - goal: server-to-gateway calls with JWT + stable endpoints\",\n    \"  - next: `loro dashboard api-key create|token ...`\",\n    \"  - lookup: `loro prompt backend-api --tag ApiKey --format json`\",\n    \"  - lookup: `loro prompt backend-api --path /api/auth/api-key/token --format json`\",\n    \"  - gateway: `loro prompt backend-api --tag Gateway --format json`\",\n    \"- Admin/ops:\",\n    \"  - goal: org/members/key rotation/usage/quota\",\n    \"  - next: `loro dashboard --help`\",\n    \"- Debugger:\",\n    \"  - goal: inspect payloads, offsets, and recovery behavior\",\n    \"  - next: `loro prompt durable-stream`\",\n    \"- AI agent / automation:\",\n    \"  - goal: machine-readable output and OpenAPI-backed discovery\",\n    \"  - next: `loro prompt backend-api --format json`\",\n    \"  - filter: `loro prompt backend-api --path <path> --format json`\",\n    \"\",\n    \"## 10-Minute Smoke Test (No SDK)\",\n    \"\",\n    \"1. Login and pick org:\",\n    \"  - `loro auth login --host https://streams.loro.dev`\",\n    \"  - `loro dashboard organizations list`\",\n    \"  - `loro auth use-org <org-id>`\",\n    \"2. Create a JSON stream (easy to inspect):\",\n    \"  - `loro bucket create <bucket>`\",\n    \"  - `loro stream create <bucket> <stream> --content-type application/json`\",\n    \"3. Watch then append:\",\n    \"  - terminal A: `loro stream watch <bucket> <stream> --from -1 --format jsonl`\",\n    \"  - terminal B: `loro stream append <bucket> <stream> --data '{\\\"type\\\":\\\"update\\\",\\\"payload\\\":\\\"...\\\"}'`\",\n    \"\",\n    \"## Common Fixes (When Things Fail)\",\n    \"\",\n    \"- `401`: run `loro auth login` again.\",\n    \"- `403`: ensure the right org via `loro auth use-org <org-id>` and check permissions.\",\n    \"- `410 Gone`: run `loro stream bootstrap <bucket> <stream>` and continue from server offsets.\",\n    \"\",\n    \"## Output Tips\",\n    \"\",\n    \"- Add global `--json` for machine-readable envelopes.\",\n    \"- Add `--include-context` to include runtime base URLs and active org id.\",\n    \"- Avoid `loro prompt backend-api --full` unless you need the full OpenAPI dump.\",\n  ];\n\n  if (profile === \"catalog\") {\n    lines.push(\n      \"\",\n      \"## What To Do Next\",\n      \"\",\n      \"1. Run the smoke test above to validate auth + stream read/write + watch.\",\n      \"2. When moving to real CRDT payloads, start with `loro prompt integration with CRDT`.\",\n    );\n  }\n\n  lines.push(\"\", ...catalogLines(true));\n  return lines.join(\"\\n\");\n}\n\nfunction renderTopicsMarkdown(): string {\n  return [\"# Loro Prompt Topics\", \"\", ...catalogLines(false)].join(\"\\n\");\n}\n\nfunction renderDurableStreamMarkdown(): string {\n  return [\n    \"# Durable Stream Basics\",\n    \"\",\n    \"## What It Is\",\n    \"\",\n    \"- A durable, append-only stream model under `bucket -> stream`.\",\n    \"- Designed for replay/resume via opaque offsets.\",\n    \"- Supports read, watch (SSE), bootstrap, and snapshot flows.\",\n    \"\",\n    \"## Practical Workflow\",\n    \"\",\n    \"1. `loro bucket create <bucket>`\",\n    \"2. `loro stream create <bucket> <stream> --content-type application/json`\",\n    \"3. `loro stream append <bucket> <stream> --data '{...}'`\",\n    \"4. `loro stream read <bucket> <stream> --format jsonl`\",\n    \"5. `loro stream watch <bucket> <stream> --from now --format jsonl`\",\n    \"\",\n    \"## Recovery\",\n    \"\",\n    \"- If reads return `410 Gone`, recover with:\",\n    \"  - `loro stream bootstrap <bucket> <stream>`\",\n    \"- Snapshots can accelerate rehydration:\",\n    \"  - `loro stream snapshot read <bucket> <stream> --latest`\",\n    \"  - `loro stream snapshot write <bucket> <stream> --at <offset> --data-file <path>`\",\n  ].join(\"\\n\");\n}\n\nfunction renderCrdtIntegrationMarkdown(): string {\n  return [\n    \"# Durable Stream For CRDT\",\n    \"\",\n    \"## What You Get\",\n    \"\",\n    \"- Durable, replayable update log (append-only).\",\n    \"- Resume from server-provided offsets (no guessing).\",\n    \"- Live tail via SSE (`loro stream watch ...`).\",\n    \"\",\n    \"## Recommended Stack\",\n    \"\",\n    \"- `@loro-dev/flock-wasm` for CRDT state.\",\n    \"- `@loro-dev/streams-crdt` for flock/meta DS synchronization plumbing.\",\n    \"- `@loro-dev/streams-crdt/loro` when you need `LoroDoc` support.\",\n    \"- `loro stream` / `loro bucket` commands for manual inspection and debugging.\",\n    \"- Install `@loro-dev/streams-crdt` first when you need to integrate CRDT sync into your app: `npm install @loro-dev/streams-crdt`.\",\n    \"\",\n    \"## Stream Mapping\",\n    \"\",\n    \"- bucket: app/env namespace (e.g. `acme-prod`, `acme-staging`).\",\n    \"- stream: doc id / room id (one stream per collaborative unit).\",\n    \"\",\n    \"## Auth And Tokens\",\n    \"\",\n    \"- Local dev JWT: `loro auth token --audience gateway`.\",\n    \"- Service/agent JWT: `loro dashboard api-key token --key <api-key>`.\",\n    \"\",\n    \"## Minimal Adapter Setup\",\n    \"\",\n    \"```ts\",\n    \"import { LoroDoc } from \\\"loro-crdt\\\";\",\n    \"import { createLoroDocAdapter, StreamsCrdt } from \\\"@loro-dev/streams-crdt/loro\\\";\",\n    \"\",\n    \"const loroDoc = new LoroDoc();\",\n    \"const transport = new StreamsCrdt({\",\n    \"  streamUrl: \\\"<gatewayBaseUrl>/ds/<bucket>/<doc-id>\\\",\",\n    \"  auth: async () => \\\"<gateway-jwt>\\\",\",\n    \"  adapter: createLoroDocAdapter(loroDoc),\",\n    \"});\",\n    \"\",\n    \"await transport.sync();\",\n    \"transport.join();\",\n    \"```\",\n    \"\",\n    \"## Payload Format Choices\",\n    \"\",\n    \"- Start with `application/json` for easiest manual inspection.\",\n    \"- For binary batches, use binary framing + `application/octet-stream`.\",\n    \"\",\n    \"## Debugging Loop\",\n    \"\",\n    \"1. `loro stream watch <bucket> <stream> --from -1 --format jsonl`\",\n    \"2. `loro stream inspect <bucket> <stream> <message-id>`\",\n    \"3. If reads return `410 Gone`: `loro stream bootstrap <bucket> <stream>`\",\n  ].join(\"\\n\");\n}\n\nfunction renderPermissionsMarkdown(): string {\n  return [\n    \"# Permissions And Auth Model\",\n    \"\",\n    \"## Identity Layers\",\n    \"\",\n    \"- Login through device flow: `loro auth login`.\",\n    \"- Runtime org context from `activeOrgId`.\",\n    \"- Access tokens are audience-scoped (`dashboard` / `gateway`).\",\n    \"\",\n    \"## Key Authorization Paths\",\n    \"\",\n    \"- Human-to-dashboard: OAuth device flow + refresh token lifecycle.\",\n    \"- Service-to-platform: API key -> JWT exchange via `loro dashboard api-key token`.\",\n    \"- Gateway calls require JWT with matching org/scope permissions.\",\n    \"\",\n    \"## Permission-Oriented Commands\",\n    \"\",\n    \"- `loro dashboard members invite|remove` for org membership management.\",\n    \"- `loro dashboard api-key create|list|revoke|verify|token` for key lifecycle.\",\n    \"- `loro auth use-org <org-id>` to switch active org context.\",\n    \"\",\n    \"## API Key Bucket Scope\",\n    \"\",\n    \"`loro dashboard api-key create` accepts a single existing bucket id:\",\n    \"\",\n    \"```bash\",\n    \"loro dashboard api-key create --name agent-key --bucket demo\",\n    \"```\",\n    \"\",\n    \"The dashboard checks that the bucket exists in the authenticated org before creating the key.\",\n    \"\",\n    \"Generated scope behavior:\",\n    \"\",\n    \"- Bucket matching is exact for the selected bucket.\",\n    \"- Allowed operations: `bucket-get`, stream read/head/bootstrap/snapshot-read, `stream-create`, `stream-append`, `stream-snapshot-write`.\",\n    \"- Destructive operations such as `bucket-delete`, `stream-delete`, `stream-close`, and `stream-snapshot-delete` are not granted.\",\n    \"\",\n    \"Important behavior:\",\n    \"\",\n    \"- Old arbitrary `--permissions` / `buckets` JSON creation is deprecated and rejected.\",\n    \"- API key token exchange may still request a narrower JWT `scope`, but it must remain within the key's generated bucket scope.\",\n    \"\",\n    \"## Failure Interpretation\",\n    \"\",\n    \"- `401`: login/token invalid or expired.\",\n    \"- `403`: permission denied or org mismatch.\",\n    \"- Verify current identity with `loro auth whoami` before destructive actions.\",\n  ].join(\"\\n\");\n}\n\nfunction topicCatalogPayload(): PromptJsonOutput[\"catalog\"] {\n  return PROMPT_CATALOG.map(({ id, title, summary, command }) => ({\n    id,\n    title,\n    summary,\n    command,\n  }));\n}\n\nasync function loadDashboardOpenApiRaw(): Promise<string> {\n  return readBundledText(dashboardOpenApiCandidates());\n}\n\nfunction sanitizeOpenApiYamlForParser(rawText: string): string {\n  return rawText\n    .split(/\\r?\\n/)\n    .map((line) => {\n      const match = /^(\\s*(?:title|summary|description):\\s*)(.+)$/.exec(line);\n      if (!match) {\n        return line;\n      }\n\n      const prefix = match[1];\n      const value = match[2].trim();\n      if (\n        value.length === 0 ||\n        value === \"|\" ||\n        value === \">\" ||\n        value.startsWith('\"') ||\n        value.startsWith(\"'\")\n      ) {\n        return line;\n      }\n\n      if (value.includes(\": \")) {\n        return `${prefix}${JSON.stringify(value)}`;\n      }\n\n      return line;\n    })\n    .join(\"\\n\");\n}\n\nasync function loadDashboardOpenApiParsed(): Promise<Record<string, unknown>> {\n  const rawText = await loadDashboardOpenApiRaw();\n  const normalizedText = sanitizeOpenApiYamlForParser(rawText);\n  let parsedValue: unknown;\n  try {\n    parsedValue = loadYaml(normalizedText);\n  } catch (error) {\n    throw new CliError(\n      \"INVALID_OPENAPI_SPEC\",\n      `Cannot parse ${DASHBOARD_OPENAPI_SOURCE}: ${error instanceof Error ? error.message : \"unknown parse error\"}`,\n      ExitCode.InternalError,\n      {\n        cause: error,\n      },\n    );\n  }\n\n  if (!isRecord(parsedValue)) {\n    throw new CliError(\n      \"INVALID_OPENAPI_SPEC\",\n      `${DASHBOARD_OPENAPI_SOURCE} must parse into an object.`,\n      ExitCode.InternalError,\n    );\n  }\n\n  return parsedValue;\n}\n\nfunction resolveOpenApiRef(document: Record<string, unknown>, ref: string): unknown {\n  if (!ref.startsWith(\"#/\")) {\n    return undefined;\n  }\n\n  const segments = ref\n    .slice(2)\n    .split(\"/\")\n    .map((item) => item.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n  let cursor: unknown = document;\n  for (const segment of segments) {\n    if (!isRecord(cursor) || !(segment in cursor)) {\n      return undefined;\n    }\n    cursor = cursor[segment];\n  }\n  return cursor;\n}\n\nfunction schemaToExample(\n  schemaValue: unknown,\n  document: Record<string, unknown>,\n  seenRefs: Set<string> = new Set(),\n  depth = 0,\n): unknown {\n  if (depth > 10) {\n    return {};\n  }\n\n  if (isRecord(schemaValue) && typeof schemaValue.$ref === \"string\") {\n    const ref = schemaValue.$ref;\n    if (seenRefs.has(ref)) {\n      return {};\n    }\n\n    const resolved = resolveOpenApiRef(document, ref);\n    if (!isRecord(resolved)) {\n      return {};\n    }\n\n    const mergedSchema: Record<string, unknown> = { ...resolved };\n    for (const [key, value] of Object.entries(schemaValue)) {\n      if (key !== \"$ref\") {\n        mergedSchema[key] = value;\n      }\n    }\n\n    const nextRefs = new Set(seenRefs);\n    nextRefs.add(ref);\n    return schemaToExample(mergedSchema, document, nextRefs, depth + 1);\n  }\n\n  if (!isRecord(schemaValue)) {\n    return {};\n  }\n\n  if (\"example\" in schemaValue) {\n    return schemaValue.example;\n  }\n\n  if (Array.isArray(schemaValue.enum) && schemaValue.enum.length > 0) {\n    return schemaValue.enum[0];\n  }\n\n  if (\"const\" in schemaValue) {\n    return schemaValue.const;\n  }\n\n  if (Array.isArray(schemaValue.allOf) && schemaValue.allOf.length > 0) {\n    const merged: Record<string, unknown> = {};\n    let mergedAnyObject = false;\n    for (const part of schemaValue.allOf) {\n      const example = schemaToExample(part, document, seenRefs, depth + 1);\n      if (isRecord(example)) {\n        Object.assign(merged, example);\n        mergedAnyObject = true;\n      }\n    }\n    if (mergedAnyObject) {\n      return merged;\n    }\n    return schemaToExample(schemaValue.allOf[0], document, seenRefs, depth + 1);\n  }\n\n  if (Array.isArray(schemaValue.oneOf) && schemaValue.oneOf.length > 0) {\n    return schemaToExample(schemaValue.oneOf[0], document, seenRefs, depth + 1);\n  }\n\n  if (Array.isArray(schemaValue.anyOf) && schemaValue.anyOf.length > 0) {\n    return schemaToExample(schemaValue.anyOf[0], document, seenRefs, depth + 1);\n  }\n\n  if (schemaValue.type === \"object\" || isRecord(schemaValue.properties)) {\n    const objectValue: Record<string, unknown> = {};\n    const properties = isRecord(schemaValue.properties) ? schemaValue.properties : undefined;\n    if (properties) {\n      for (const [key, value] of Object.entries(properties)) {\n        objectValue[key] = schemaToExample(value, document, seenRefs, depth + 1);\n      }\n    }\n\n    if (\n      Object.keys(objectValue).length === 0 &&\n      isRecord(schemaValue.additionalProperties)\n    ) {\n      objectValue.example = schemaToExample(\n        schemaValue.additionalProperties,\n        document,\n        seenRefs,\n        depth + 1,\n      );\n    }\n\n    return objectValue;\n  }\n\n  if (schemaValue.type === \"array\" || \"items\" in schemaValue) {\n    if (!(\"items\" in schemaValue)) {\n      return [];\n    }\n    return [schemaToExample(schemaValue.items, document, seenRefs, depth + 1)];\n  }\n\n  if (schemaValue.type === \"boolean\") {\n    return true;\n  }\n\n  if (schemaValue.type === \"integer\") {\n    if (typeof schemaValue.example === \"number\") {\n      return schemaValue.example;\n    }\n    if (typeof schemaValue.minimum === \"number\") {\n      return schemaValue.minimum;\n    }\n    return 0;\n  }\n\n  if (schemaValue.type === \"number\") {\n    if (typeof schemaValue.example === \"number\") {\n      return schemaValue.example;\n    }\n    if (typeof schemaValue.minimum === \"number\") {\n      return schemaValue.minimum;\n    }\n    return 0;\n  }\n\n  if (schemaValue.type === \"string\") {\n    if (typeof schemaValue.default === \"string\") {\n      return schemaValue.default;\n    }\n    if (typeof schemaValue.example === \"string\") {\n      return schemaValue.example;\n    }\n    if (schemaValue.format === \"email\") {\n      return \"user@example.com\";\n    }\n    if (schemaValue.format === \"uri\") {\n      return \"https://example.com\";\n    }\n    if (schemaValue.format === \"date-time\") {\n      return \"2026-01-01T00:00:00.000Z\";\n    }\n    return \"string\";\n  }\n\n  return {};\n}\n\nfunction preferredContentSchema(\n  contentValue: unknown,\n  document: Record<string, unknown>,\n): unknown {\n  if (!isRecord(contentValue)) {\n    return undefined;\n  }\n\n  const preferredType = \"application/json\";\n  const mediaTypes = Object.keys(contentValue);\n  if (mediaTypes.length === 0) {\n    return undefined;\n  }\n\n  const targetType = mediaTypes.includes(preferredType) ? preferredType : mediaTypes[0];\n  if (!targetType) {\n    return undefined;\n  }\n  const mediaType = contentValue[targetType];\n  if (!isRecord(mediaType)) {\n    return undefined;\n  }\n  return schemaToExample(mediaType.schema, document);\n}\n\nfunction extractOperationRequest(\n  operation: Record<string, unknown>,\n  document: Record<string, unknown>,\n): unknown {\n  const requestBody = operation.requestBody;\n  if (!requestBody) {\n    return {};\n  }\n\n  let requestBodyObject: unknown = requestBody;\n  if (isRecord(requestBodyObject) && typeof requestBodyObject.$ref === \"string\") {\n    requestBodyObject = resolveOpenApiRef(document, requestBodyObject.$ref);\n  }\n  if (!isRecord(requestBodyObject)) {\n    return {};\n  }\n\n  const example = preferredContentSchema(requestBodyObject.content, document);\n  return example ?? {};\n}\n\nfunction extractOperationResponse(\n  operation: Record<string, unknown>,\n  document: Record<string, unknown>,\n): Record<string, unknown> {\n  const responsesValue = operation.responses;\n  if (!isRecord(responsesValue)) {\n    return {};\n  }\n\n  const entries = Object.entries(responsesValue);\n  const successEntries = entries.filter(([status]) => /^2\\d\\d$/.test(status));\n  const selectedEntries = successEntries.length > 0 ? successEntries : entries.slice(0, 1);\n  const response: Record<string, unknown> = {};\n\n  for (const [status, value] of selectedEntries) {\n    let responseObject: unknown = value;\n    if (isRecord(responseObject) && typeof responseObject.$ref === \"string\") {\n      responseObject = resolveOpenApiRef(document, responseObject.$ref);\n    }\n    if (!isRecord(responseObject)) {\n      response[status] = {};\n      continue;\n    }\n\n    const schemaExample = preferredContentSchema(responseObject.content, document);\n    if (schemaExample !== undefined) {\n      response[status] = schemaExample;\n      continue;\n    }\n\n    response[status] =\n      typeof responseObject.description === \"string\"\n        ? { description: responseObject.description }\n        : {};\n  }\n\n  return response;\n}\n\nfunction extractOperationResponseHeaders(\n  operation: Record<string, unknown>,\n  document: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n  const responsesValue = operation.responses;\n  if (!isRecord(responsesValue)) {\n    return {};\n  }\n\n  const entries = Object.entries(responsesValue);\n  const successEntries = entries.filter(([status]) => /^2\\d\\d$/.test(status));\n  const selectedEntries = successEntries.length > 0 ? successEntries : entries.slice(0, 1);\n  const headersByStatus: Record<string, Record<string, unknown>> = {};\n\n  for (const [status, value] of selectedEntries) {\n    let responseObject: unknown = value;\n    if (isRecord(responseObject) && typeof responseObject.$ref === \"string\") {\n      responseObject = resolveOpenApiRef(document, responseObject.$ref);\n    }\n\n    const headers: Record<string, unknown> = {};\n\n    if (isRecord(responseObject)) {\n      if (isRecord(responseObject.content)) {\n        const mediaTypes = Object.keys(responseObject.content);\n        if (mediaTypes.length === 1) {\n          headers[\"Content-Type\"] = mediaTypes[0]!;\n        } else if (mediaTypes.length > 1) {\n          headers[\"Content-Type\"] = mediaTypes;\n        }\n      }\n\n      if (isRecord(responseObject.headers)) {\n        for (const [headerName, headerValue] of Object.entries(responseObject.headers)) {\n          let headerObject: unknown = headerValue;\n          if (isRecord(headerObject) && typeof headerObject.$ref === \"string\") {\n            headerObject = resolveOpenApiRef(document, headerObject.$ref);\n          }\n\n          if (!isRecord(headerObject)) {\n            continue;\n          }\n\n          const schemaExample = schemaToExample(headerObject.schema, document);\n          if (\n            schemaExample !== undefined &&\n            (!isRecord(schemaExample) || Object.keys(schemaExample).length > 0)\n          ) {\n            headers[headerName] = schemaExample;\n            continue;\n          }\n\n          if (typeof headerObject.example !== \"undefined\") {\n            headers[headerName] = headerObject.example;\n            continue;\n          }\n\n          if (typeof headerObject.description === \"string\" && headerObject.description.trim().length > 0) {\n            headers[headerName] = { description: headerObject.description.trim() };\n          }\n        }\n      }\n    }\n\n    headersByStatus[status] = headers;\n  }\n\n  return headersByStatus;\n}\n\nfunction securitySchemeLabel(\n  schemeName: string,\n  schemeValue: unknown,\n): string {\n  if (schemeName === \"ApiKeyBearer\") {\n    return \"Authorization: Bearer <api-key>\";\n  }\n  if (schemeName === \"CliBearer\") {\n    return \"Authorization: Bearer <cli-access-token>\";\n  }\n  if (schemeName === \"SessionCookie\") {\n    return \"Cookie: better-auth.session_token=<session-token>\";\n  }\n\n  if (!isRecord(schemeValue)) {\n    return schemeName;\n  }\n\n  if (schemeValue.type === \"http\" && schemeValue.scheme === \"bearer\") {\n    return \"Authorization: Bearer <token>\";\n  }\n\n  if (schemeValue.type === \"apiKey\") {\n    const name = typeof schemeValue.name === \"string\" ? schemeValue.name : \"api_key\";\n    if (schemeValue.in === \"header\") {\n      return `${name}: <token>`;\n    }\n    if (schemeValue.in === \"query\") {\n      return `?${name}=<token>`;\n    }\n    if (schemeValue.in === \"cookie\") {\n      return `Cookie: ${name}=<token>`;\n    }\n  }\n\n  return schemeName;\n}\n\nfunction formatOperationAuth(\n  operation: Record<string, unknown>,\n  document: Record<string, unknown>,\n): string {\n  const securityValue = operation.security;\n  if (!Array.isArray(securityValue) || securityValue.length === 0) {\n    return \"No auth declared in OpenAPI\";\n  }\n\n  const components = isRecord(document.components) ? document.components : undefined;\n  const securitySchemes = components && isRecord(components.securitySchemes)\n    ? components.securitySchemes\n    : undefined;\n\n  const alternatives: string[] = [];\n  for (const requirement of securityValue) {\n    if (!isRecord(requirement)) {\n      continue;\n    }\n    const schemeNames = Object.keys(requirement);\n    if (schemeNames.length === 0) {\n      alternatives.push(\"No auth\");\n      continue;\n    }\n\n    const labels = schemeNames.map((name) =>\n      securitySchemeLabel(name, securitySchemes?.[name]),\n    );\n    alternatives.push(labels.join(\" + \"));\n  }\n\n  if (alternatives.length === 0) {\n    return \"No auth declared in OpenAPI\";\n  }\n\n  return Array.from(new Set(alternatives)).join(\" OR \");\n}\n\nfunction extractOperationSummary(\n  path: string,\n  method: string,\n  operation: Record<string, unknown>,\n): string {\n  if (typeof operation.summary === \"string\" && operation.summary.trim().length > 0) {\n    return operation.summary.trim();\n  }\n\n  if (typeof operation.description === \"string\" && operation.description.trim().length > 0) {\n    return operation.description.trim().split(/\\r?\\n/, 1)[0] ?? `${method} ${path}`;\n  }\n\n  return `${method} ${path}`;\n}\n\nfunction buildBackendApiItems(\n  document: Record<string, unknown>,\n  filters: BackendApiFilters,\n): BackendApiPromptItem[] {\n  const paths = isRecord(document.paths) ? document.paths : {};\n  const normalizedPath = filters.path?.trim();\n  const normalizedTag = filters.tag?.trim().toLowerCase();\n  const items: BackendApiPromptItem[] = [];\n\n  for (const path of Object.keys(paths).sort((left, right) => left.localeCompare(right))) {\n    if (normalizedPath && path !== normalizedPath) {\n      continue;\n    }\n\n    const pathItem = paths[path];\n    if (!isRecord(pathItem)) {\n      continue;\n    }\n\n    for (const method of HTTP_METHOD_ORDER) {\n      const operationValue = pathItem[method];\n      if (!isRecord(operationValue)) {\n        continue;\n      }\n\n      const tags =\n        Array.isArray(operationValue.tags)\n          ? operationValue.tags.filter((entry): entry is string => typeof entry === \"string\")\n          : [];\n\n      if (normalizedTag && !tags.some((entry) => entry.toLowerCase() === normalizedTag)) {\n        continue;\n      }\n\n      items.push({\n        surface: \"dashboard\",\n        method: method.toUpperCase(),\n        path,\n        summary: extractOperationSummary(path, method.toUpperCase(), operationValue),\n        tags,\n        auth: formatOperationAuth(operationValue, document),\n        request: extractOperationRequest(operationValue, document),\n        response: extractOperationResponse(operationValue, document),\n        response_headers: extractOperationResponseHeaders(operationValue, document),\n      });\n    }\n  }\n\n  return items;\n}\n\nfunction matchesBackendApiFilters(\n  item: Pick<BackendApiPromptItem, \"path\" | \"tags\">,\n  filters: BackendApiFilters,\n): boolean {\n  const normalizedPath = filters.path?.trim();\n  if (normalizedPath && item.path !== normalizedPath) {\n    return false;\n  }\n\n  const normalizedTag = filters.tag?.trim().toLowerCase();\n  if (normalizedTag) {\n    return item.tags.some((tag) => tag.toLowerCase() === normalizedTag);\n  }\n\n  return true;\n}\n\nfunction buildGatewayApiItems(filters: BackendApiFilters): BackendApiPromptItem[] {\n  const gatewayAuth = \"Authorization: Bearer <jwt> (audience=gateway)\";\n\n  const items: BackendApiPromptItem[] = [\n    {\n      surface: \"gateway\",\n      method: \"PUT\",\n      path: \"/ds/{bucket}\",\n      summary: \"Create bucket (required before creating streams).\",\n      tags: [\"Gateway\", \"DurableStream\", \"Bucket\"],\n      auth: gatewayAuth,\n      request: {},\n      response: {\n        \"201\": { description: \"Bucket created\" },\n      },\n      response_headers: {\n        \"201\": {},\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"PUT\",\n      path: \"/ds/{bucket}/{stream}\",\n      summary: \"Create/ensure stream. Bucket must exist. Content-Type becomes the stream type.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Stream\"],\n      auth: gatewayAuth,\n      request: {\n        headers: {\n          \"Content-Type\": \"application/json\",\n          \"Ephemeral-Stream-Retention-Seconds\": \"120 (optional)\",\n        },\n        body: \"<bytes>\",\n      },\n      response: {\n        \"201\": { description: \"Stream created\" },\n        \"200\": { description: \"Stream already exists (idempotent success)\" },\n      },\n      response_headers: {\n        \"201\": {\n          Location: \"/ds/{bucket}/{stream}\",\n          \"Content-Type\": \"<stream-content-type>\",\n          \"Stream-Next-Offset\": \"string\",\n        },\n        \"200\": {\n          \"Content-Type\": \"<stream-content-type>\",\n          \"Stream-Next-Offset\": \"string\",\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"POST\",\n      path: \"/ds/{bucket}/{stream}\",\n      summary: \"Append bytes to stream, or close it with `Stream-Closed: true` and an empty body.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Stream\", \"Append\", \"Close\"],\n      auth: gatewayAuth,\n      request: {\n        headers: {\n          \"Content-Type\": \"<stream-content-type>\",\n          \"Stream-Seq\": \"<lex-seq> (optional)\",\n          \"Stream-Closed\": \"true (optional; allows close-only with empty body)\",\n          \"Producer-Id\": \"<string> (optional, idempotent producer)\",\n          \"Producer-Epoch\": 0,\n          \"Producer-Seq\": 0,\n        },\n        body: \"<bytes> | empty body when Stream-Closed: true\",\n      },\n      response: {\n        \"204\": { description: \"Append accepted or close-only request applied\" },\n      },\n      response_headers: {\n        \"204\": {\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-Closed\": \"true (present when stream is closed)\",\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"HEAD\",\n      path: \"/ds/{bucket}/{stream}\",\n      summary: \"Stream metadata: existence + tail offset + TTL/expiry.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Stream\", \"Metadata\"],\n      auth: gatewayAuth,\n      request: {},\n      response: {\n        \"200\": { description: \"Stream exists\" },\n      },\n      response_headers: {\n        \"200\": {\n          \"Content-Type\": \"<stream-content-type>\",\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-TTL\": \"3600 (optional)\",\n          \"Stream-Expires-At\": \"2026-01-01T00:00:00.000Z (optional)\",\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"GET\",\n      path: \"/ds/{bucket}/{stream}\",\n      summary: \"Read stream (catch-up, long-poll, or SSE via query params).\",\n      tags: [\"Gateway\", \"DurableStream\", \"Stream\", \"Read\", \"Watch\"],\n      auth: gatewayAuth,\n      request: {\n        query: {\n          offset: \"-1 | now | <offset>\",\n          live: \"none | long-poll | sse\",\n          cursor: \"<cursor> (long-poll only)\",\n        },\n        headers: {\n          Accept: \"text/event-stream (required for live=sse)\",\n        },\n      },\n      response: {\n        \"200\": {\n          body: \"<bytes> | <json-array> | <sse-events>\",\n        },\n        \"204\": { description: \"No Content (long-poll timeout)\" },\n      },\n      response_headers: {\n        \"200\": {\n          \"Content-Type\": \"<stream-content-type> | text/event-stream\",\n          \"Stream-Cursor\": \"string\",\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-Up-To-Date\": true,\n        },\n        \"204\": {\n          \"Stream-Cursor\": \"string\",\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-Up-To-Date\": true,\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"DELETE\",\n      path: \"/ds/{bucket}/{stream}\",\n      summary: \"Delete stream and all data (terminal).\",\n      tags: [\"Gateway\", \"DurableStream\", \"Stream\", \"Delete\"],\n      auth: gatewayAuth,\n      request: {},\n      response: {\n        \"204\": { description: \"Deleted\" },\n      },\n      response_headers: {\n        \"204\": {},\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"GET\",\n      path: \"/ds/{bucket}/{stream}/snapshot\",\n      summary: \"Locate latest snapshot (redirect).\",\n      tags: [\"Gateway\", \"DurableStream\", \"Snapshot\"],\n      auth: gatewayAuth,\n      request: {},\n      response: {\n        \"307\": { description: \"Redirect to snapshot_at\" },\n      },\n      response_headers: {\n        \"307\": {\n          Location: \"/ds/{bucket}/{stream}/snapshot/<snapshot_offset>\",\n          \"Cache-Control\": \"private, max-age=5\",\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"GET\",\n      path: \"/ds/{bucket}/{stream}/snapshot/<snapshot_offset>\",\n      summary: \"Read snapshot bytes at offset.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Snapshot\"],\n      auth: gatewayAuth,\n      request: {},\n      response: {\n        \"200\": { body: \"<snapshot-bytes>\" },\n      },\n      response_headers: {\n        \"200\": {\n          \"Content-Type\": \"<snapshot-content-type>\",\n          \"Stream-Snapshot-Offset\": \"string\",\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-Up-To-Date\": true,\n        },\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"PUT\",\n      path: \"/ds/{bucket}/{stream}/snapshot/<snapshot_offset>\",\n      summary: \"Write snapshot bytes at offset. Triggers 410 for offsets < snapshot_offset.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Snapshot\"],\n      auth: gatewayAuth,\n      request: {\n        headers: {\n          \"Content-Type\": \"application/octet-stream (recommended)\",\n        },\n        body: \"<snapshot-bytes>\",\n      },\n      response: {\n        \"204\": { description: \"Snapshot stored\" },\n      },\n      response_headers: {\n        \"204\": {},\n      },\n    },\n    {\n      surface: \"gateway\",\n      method: \"GET\",\n      path: \"/ds/{bucket}/{stream}/bootstrap\",\n      summary: \"Bootstrap read: one-shot multipart snapshot + retained updates.\",\n      tags: [\"Gateway\", \"DurableStream\", \"Bootstrap\", \"CRDT\"],\n      auth: gatewayAuth,\n      request: {\n        query: {},\n        constraints: [\n          \"/bootstrap is one-shot only\",\n          \"Do not send live or cursor query params; servers should reject them with 400\",\n          \"Use the returned Stream-Next-Offset with ordinary GET reads for follow-up catch-up or live tail\",\n        ],\n      },\n      response: {\n        \"200\": {\n          content_type: \"multipart/mixed; boundary=<token>\",\n          parts: [\"<snapshot-part>\", \"<update-part>\", \"...\"],\n        },\n      },\n      response_headers: {\n        \"200\": {\n          \"Content-Type\": \"multipart/mixed; boundary=<token>\",\n          \"Stream-Snapshot-Offset\": \"-1 | <snapshot_offset>\",\n          \"Stream-Next-Offset\": \"string\",\n          \"Stream-Up-To-Date\": true,\n        },\n      },\n    },\n  ];\n\n  return items.filter((item) => matchesBackendApiFilters(item, filters));\n}\n\nfunction compactJson(value: unknown): string {\n  return JSON.stringify(value);\n}\n\nfunction renderBackendApiMarkdown(\n  items: BackendApiPromptItem[],\n  filters: BackendApiFilters,\n  surfaces: BackendApiJsonOutput[\"surfaces\"],\n): string {\n  const expandedView = Boolean(filters.path || filters.tag);\n  const dashboardBaseUrl = surfaces.dashboard.base_url;\n  const gatewayBaseUrl = surfaces.gateway.base_url;\n  const lines = [\n    \"# Backend API Task Guide\",\n    \"\",\n    \"Dashboard APIs and Gateway APIs do NOT share the same base URL.\",\n    \"\",\n    `- dashboardBaseUrl: ${dashboardBaseUrl}`,\n    \"  - paths: `/api/*` (streams.loro.dev backend, OpenAPI-backed)\",\n    `- gatewayBaseUrl: ${gatewayBaseUrl}`,\n    \"  - paths: `/ds/*` (streams-api.loro.dev backend, DS protocol + CRDT extensions)\",\n    \"\",\n    \"This topic indexes two backend surfaces:\",\n    \"\",\n    \"- Dashboard API (behind `https://streams.loro.dev`): org/auth/api-key operations.\",\n    `  - source: \\`${DASHBOARD_OPENAPI_SOURCE}\\` (OpenAPI)`,\n    \"- Gateway API (usually `https://streams-api.loro.dev`): Durable Streams (`/ds/*`) + CRDT extensions.\",\n    `  - sources: ${GATEWAY_PROTOCOL_SOURCES.map((source) => `\\`${source}\\``).join(\", \")}`,\n    \"\",\n    \"`--path` matches the path portion only (e.g. `/api/...` or `/ds/...`). Use `surface`/`url` lines below to see the full target URL.\",\n    \"- inspect: `loro config get`\",\n    \"- inline: `loro prompt backend-api --include-context`\",\n    \"\",\n    \"Key flow (service/agent):\",\n    \"1. Get a short-lived gateway JWT:\",\n    `  - \\`POST ${dashboardBaseUrl}/api/auth/api-key/token\\``,\n    \"  - auth: `Authorization: Bearer <api-key>`\",\n    \"  - returns: `{ token, expires_in }`\",\n    \"  - response headers: `Content-Type: application/json`\",\n    \"2. Call gateway with that JWT:\",\n    `  - \\`Authorization: Bearer <jwt>\\` against \\`${gatewayBaseUrl}/ds/*\\``,\n    \"  - persist offsets from `Stream-Next-Offset` response header\",\n    \"\",\n    \"Use `--path` and `--tag` to narrow results.\",\n    \"- dashboard-only: `loro prompt backend-api --tag ApiKey`\",\n    \"- gateway-only: `loro prompt backend-api --tag Gateway`\",\n    \"- example: `loro prompt backend-api --path /ds/{bucket}/{stream}/bootstrap --format json`\",\n    \"Use `--full` only when you need the dashboard OpenAPI dump (`specs/dashboard-api-openapi.yaml`).\",\n    expandedView\n      ? \"Current view is expanded because path/tag filters are active.\"\n      : \"Current view is compact. Add `--path` or `--tag` to expand request/response examples.\",\n    \"\",\n    \"## Active Filters\",\n    \"\",\n    `- path: ${filters.path ?? \"(none)\"}`,\n    `- tag: ${filters.tag ?? \"(none)\"}`,\n    \"\",\n    `## Matched Operations (${items.length})`,\n  ];\n\n  if (items.length === 0) {\n    lines.push(\"\", \"- No operations matched current filters.\");\n    return lines.join(\"\\n\");\n  }\n\n  const dashboardItems = items.filter((item) => item.surface === \"dashboard\");\n  const gatewayItems = items.filter((item) => item.surface === \"gateway\");\n\n  if (dashboardItems.length > 0) {\n    lines.push(\"\", `### Dashboard API Operations (${dashboardItems.length})`);\n    lines.push(`- base_url: ${dashboardBaseUrl}`);\n    for (const item of dashboardItems) {\n      lines.push(\"\", `#### ${item.method} ${item.path}`);\n      lines.push(\"- surface: dashboard\");\n      lines.push(`- url: ${dashboardBaseUrl}${item.path}`);\n      lines.push(`- summary: ${item.summary}`);\n      lines.push(`- tags: ${item.tags.length > 0 ? item.tags.join(\", \") : \"n/a\"}`);\n      lines.push(`- auth: ${item.auth}`);\n\n      if (expandedView) {\n        lines.push(`- request: \\`${compactJson(item.request)}\\``);\n        lines.push(`- response: \\`${compactJson(item.response)}\\``);\n        lines.push(`- response_headers: \\`${compactJson(item.response_headers)}\\``);\n      }\n    }\n  }\n\n  if (gatewayItems.length > 0) {\n    lines.push(\"\", `### Gateway API Operations (${gatewayItems.length})`);\n    lines.push(`- base_url: ${gatewayBaseUrl}`);\n    for (const item of gatewayItems) {\n      lines.push(\"\", `#### ${item.method} ${item.path}`);\n      lines.push(\"- surface: gateway\");\n      lines.push(`- url: ${gatewayBaseUrl}${item.path}`);\n      lines.push(`- summary: ${item.summary}`);\n      lines.push(`- tags: ${item.tags.length > 0 ? item.tags.join(\", \") : \"n/a\"}`);\n      lines.push(`- auth: ${item.auth}`);\n\n      if (expandedView) {\n        lines.push(`- request: \\`${compactJson(item.request)}\\``);\n        lines.push(`- response: \\`${compactJson(item.response)}\\``);\n        lines.push(`- response_headers: \\`${compactJson(item.response_headers)}\\``);\n      }\n    }\n  }\n\n  return lines.join(\"\\n\");\n}\n\nfunction unknownTopicError(rawQuery: string): never {\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `Unknown prompt topic: ${rawQuery}`,\n    ExitCode.InvalidArguments,\n    {\n      hint: [\n        \"Try one of:\",\n        ...PROMPT_CATALOG.map((entry) => `- ${entry.command}`),\n        \"- loro prompt topics\",\n      ].join(\"\\n\"),\n    },\n  );\n}\n\nfunction resolveTopicFromPositionals(positionals: string[]): PromptTopicId | \"topics\" | undefined {\n  if (positionals.length === 0) {\n    return undefined;\n  }\n\n  const rawQuery = positionals.join(\" \").trim();\n  const normalized = normalizeTopicQuery(rawQuery);\n  if (!normalized) {\n    return undefined;\n  }\n\n  if (normalized === \"topics\" || normalized === \"topic\" || normalized === \"catalog\") {\n    return \"topics\";\n  }\n\n  for (const entry of PROMPT_CATALOG) {\n    const aliases = [entry.id, ...entry.aliases].map(normalizeTopicQuery);\n    if (aliases.includes(normalized)) {\n      return entry.id;\n    }\n  }\n\n  if (normalized.includes(\"permission\") || normalized.includes(\"auth\") || normalized.includes(\"scope\")) {\n    return \"permissions\";\n  }\n\n  if (normalized.includes(\"crdt\") || normalized.includes(\"transport\") || normalized.includes(\"integration\")) {\n    return \"crdt-integration\";\n  }\n\n  if (normalized.includes(\"durable\") && normalized.includes(\"stream\")) {\n    return \"durable-stream\";\n  }\n\n  if (normalized.includes(\"openapi\") || normalized.includes(\"backend api\")) {\n    return \"backend-api\";\n  }\n\n  unknownTopicError(rawQuery);\n}\n\nfunction renderTopicMarkdown(topic: PromptTopicId): string {\n  if (topic === \"durable-stream\") {\n    return renderDurableStreamMarkdown();\n  }\n  if (topic === \"crdt-integration\") {\n    return renderCrdtIntegrationMarkdown();\n  }\n  if (topic === \"permissions\") {\n    return renderPermissionsMarkdown();\n  }\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    \"Use `loro prompt backend-api` for backend API guidance.\",\n    ExitCode.InvalidArguments,\n  );\n}\n\nasync function runBackendApiPrompt(\n  options: {\n    format: PromptFormat;\n    full: boolean;\n    filters: BackendApiFilters;\n    profileName?: string;\n  },\n  context: CommandContext,\n): Promise<CommandOutput> {\n  if (options.full) {\n    if (options.format === \"json\") {\n      const parsed = await loadDashboardOpenApiParsed();\n      return {\n        data: parsed,\n        text: context.json ? undefined : JSON.stringify(parsed, null, 2),\n      };\n    }\n\n    const raw = await loadDashboardOpenApiRaw();\n    return {\n      text: raw.trimEnd(),\n      data: {\n        topic: \"backend-api\",\n        source: DASHBOARD_OPENAPI_SOURCE,\n        full: true,\n        format: options.format,\n      },\n    };\n  }\n\n  const openApiDocument = await loadDashboardOpenApiParsed();\n  const dashboardItems = buildBackendApiItems(openApiDocument, options.filters);\n  const gatewayItems = buildGatewayApiItems(options.filters);\n  const credentials = await loadCredentials();\n  const resolvedProfileName = resolveProfileName(credentials, options.profileName);\n  const profile = applyEnvOverrides(ensureProfile(credentials, resolvedProfileName));\n  const surfaces: BackendApiJsonOutput[\"surfaces\"] = {\n    dashboard: { base_url: profile.dashboardBaseUrl },\n    gateway: { base_url: profile.gatewayBaseUrl },\n  };\n  const methodOrder: Record<string, number> = {\n    GET: 0,\n    POST: 1,\n    PUT: 2,\n    PATCH: 3,\n    DELETE: 4,\n    HEAD: 5,\n    OPTIONS: 6,\n  };\n  const items = [...dashboardItems, ...gatewayItems].sort((left, right) => {\n    const pathOrder = left.path.localeCompare(right.path);\n    if (pathOrder !== 0) {\n      return pathOrder;\n    }\n    const leftOrder = methodOrder[left.method] ?? 999;\n    const rightOrder = methodOrder[right.method] ?? 999;\n    if (leftOrder !== rightOrder) {\n      return leftOrder - rightOrder;\n    }\n    return left.surface.localeCompare(right.surface);\n  });\n\n  if (options.format === \"json\") {\n    const payload: BackendApiJsonOutput = {\n      version: \"0.3\",\n      topic: \"backend-api\",\n      source: DASHBOARD_OPENAPI_SOURCE,\n      sources: [DASHBOARD_OPENAPI_SOURCE, ...GATEWAY_PROTOCOL_SOURCES],\n      surfaces,\n      items,\n    };\n    return {\n      data: payload,\n      text: context.json ? undefined : JSON.stringify(payload, null, 2),\n    };\n  }\n\n  return {\n    text: renderBackendApiMarkdown(items, options.filters, surfaces).trimEnd(),\n    data: {\n      topic: \"backend-api\",\n      source: DASHBOARD_OPENAPI_SOURCE,\n      filters: options.filters,\n      itemCount: items.length,\n    },\n  };\n}\n\nexport async function runPromptCommand(\n  args: string[],\n  context: CommandContext,\n): Promise<CommandOutput> {\n  if (args.length > 0 && isHelpToken(args[0])) {\n    return { text: promptHelp() };\n  }\n\n  if (hasHelpFlag(args)) {\n    const helpPositionals = extractLeadingPromptPositionals(args);\n    try {\n      const topic = resolveTopicFromPositionals(helpPositionals);\n      if (topic === \"topics\") {\n        return { text: promptTopicsHelp() };\n      }\n      if (topic) {\n        return { text: promptTopicHelp(topic) };\n      }\n    } catch (error) {\n      if (!(error instanceof CliError)) {\n        throw error;\n      }\n    }\n    return { text: promptHelp() };\n  }\n\n  const parsed = parseArgs({\n    args,\n    allowPositionals: true,\n    strict: true,\n    options: {\n      profile: { type: \"string\" },\n      format: { type: \"string\" },\n      \"include-context\": { type: \"boolean\", default: false },\n      path: { type: \"string\" },\n      tag: { type: \"string\" },\n      full: { type: \"boolean\", default: false },\n    },\n  });\n\n  const resolvedTopic = resolveTopicFromPositionals(parsed.positionals);\n  const full = Boolean(parsed.values.full);\n  const format = resolvePromptFormat(resolvedTopic, full, parsed.values.format);\n\n  if (full && resolvedTopic !== \"backend-api\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--full can only be used with `loro prompt backend-api`.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  if ((parsed.values.path || parsed.values.tag) && resolvedTopic !== \"backend-api\") {\n    throw new CliError(\n      \"INVALID_ARGUMENTS\",\n      \"--path/--tag are only available for `loro prompt backend-api`.\",\n      ExitCode.InvalidArguments,\n    );\n  }\n\n  if (resolvedTopic === \"backend-api\") {\n    const output = await runBackendApiPrompt(\n      {\n        format,\n        full,\n        filters: {\n          path: parsed.values.path?.trim() || undefined,\n          tag: parsed.values.tag?.trim() || undefined,\n        },\n        profileName: parsed.values.profile,\n      },\n      context,\n    );\n    if (format === \"markdown\" && parsed.values[\"include-context\"] && typeof output.text === \"string\") {\n      const contextSection = await buildContextSection(parsed.values.profile);\n      output.text = `${output.text.trimEnd()}\\n\\n${contextSection}\\n`;\n    }\n    return output;\n  }\n\n  const profile = parsePromptProfile(parsed.values.profile);\n  let topic: PromptCatalogTopic = \"overview\";\n  let markdown: string;\n\n  if (resolvedTopic === \"topics\") {\n    markdown = renderTopicsMarkdown();\n  } else if (resolvedTopic) {\n    topic = resolvedTopic;\n    markdown = renderTopicMarkdown(resolvedTopic);\n  } else if (profile === \"full\") {\n    markdown = await loadTemplate(\"full\");\n  } else {\n    const mode = profile === \"minimal\" ? \"minimal\" : \"catalog\";\n    markdown = renderOverviewMarkdown(mode);\n  }\n\n  if (parsed.values[\"include-context\"]) {\n    const contextSection = await buildContextSection();\n    markdown = `${markdown.trimEnd()}\\n\\n${contextSection}\\n`;\n  }\n\n  if (format === \"json\") {\n    const payload: PromptJsonOutput = {\n      version: \"0.2\",\n      topic,\n      sections: parseSections(markdown),\n      catalog: topicCatalogPayload(),\n    };\n\n    return {\n      data: payload,\n      text: context.json ? undefined : JSON.stringify(payload, null, 2),\n    };\n  }\n\n  return {\n    text: markdown.trimEnd(),\n    data: {\n      topic,\n      profile,\n      format,\n      includeContext: parsed.values[\"include-context\"],\n      catalog: topicCatalogPayload(),\n    },\n  };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\n\ninterface CliPackageMetadata {\n  name: string;\n  version: string;\n}\n\nconst packageJsonUrl =\n  [new URL(\"../../package.json\", import.meta.url), new URL(\"../package.json\", import.meta.url)].find(\n    (candidate) => existsSync(fileURLToPath(candidate)),\n  ) ?? null;\n\nif (packageJsonUrl == null) {\n  throw new Error(\"Unable to locate loro-cli package.json\");\n}\n\nconst packageMetadata = JSON.parse(readFileSync(packageJsonUrl, \"utf8\")) as CliPackageMetadata;\n\nexport const CLI_PACKAGE_NAME = packageMetadata.name;\nexport const CLI_VERSION = packageMetadata.version;\n","import { CliError, ExitCode } from \"../core/errors\";\nimport { hasHelpFlag, isHelpToken, renderHelp } from \"../core/help\";\nimport type { CommandOutput } from \"../core/types\";\nimport { CLI_PACKAGE_NAME, CLI_VERSION } from \"../core/version\";\n\nfunction versionHelp(): string {\n  return renderHelp({\n    title: \"loro version\",\n    summary: [\n      \"Print the installed Loro CLI package version.\",\n      \"Use `--json` when you want both the package name and version for scripts or bug reports.\",\n    ],\n    usage: [\"loro version\", \"loro version --help\", \"loro --json version\"],\n    examples: [\"loro version\", \"loro --json version\"],\n    tips: [\n      \"Include this output when reporting CLI bugs so version mismatches are obvious.\",\n    ],\n    seeAlso: [\"loro --help\"],\n  });\n}\n\nexport async function runVersionCommand(args: string[]): Promise<CommandOutput> {\n  if (args.length > 0 && (isHelpToken(args[0]) || hasHelpFlag(args))) {\n    return { text: versionHelp() };\n  }\n\n  if (args.length > 0) {\n    throw new CliError(\"INVALID_ARGUMENTS\", \"Unexpected positional arguments\", ExitCode.InvalidArguments, {\n      hint: \"loro version\",\n    });\n  }\n\n  return {\n    text: CLI_VERSION,\n    data: {\n      name: CLI_PACKAGE_NAME,\n      version: CLI_VERSION,\n    },\n  };\n}\n","import { type CliError, isCliError, toCliError } from \"./errors\";\nimport type { CommandOutput } from \"./types\";\n\ninterface EnvelopeMeta {\n  version: string;\n  requestId?: string;\n}\n\ninterface OkEnvelope {\n  ok: true;\n  data: unknown;\n  meta: EnvelopeMeta;\n}\n\ninterface ErrorEnvelope {\n  ok: false;\n  error: {\n    code: string;\n    message: string;\n    hint?: string;\n  };\n}\n\nfunction printJson(value: unknown): void {\n  process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction formatHumanData(value: unknown): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n  return JSON.stringify(value, null, 2);\n}\n\nexport function printSuccess(output: CommandOutput | void, json: boolean): void {\n  if (output == null) {\n    if (json) {\n      const envelope: OkEnvelope = {\n        ok: true,\n        data: {},\n        meta: { version: \"0.1\" },\n      };\n      printJson(envelope);\n    }\n    return;\n  }\n\n  if (output.suppressFinalOutput) {\n    return;\n  }\n\n  if (json) {\n    const envelope: OkEnvelope = {\n      ok: true,\n      data: output.data ?? output.text ?? {},\n      meta: { version: \"0.1\" },\n    };\n    printJson(envelope);\n    return;\n  }\n\n  if (typeof output.text === \"string\") {\n    process.stdout.write(`${output.text}\\n`);\n    return;\n  }\n\n  if (output.data !== undefined) {\n    process.stdout.write(`${formatHumanData(output.data)}\\n`);\n  }\n}\n\nfunction toErrorEnvelope(error: CliError): ErrorEnvelope {\n  return {\n    ok: false,\n    error: {\n      code: error.code,\n      message: error.message,\n      hint: error.hint,\n    },\n  };\n}\n\nexport function printError(error: unknown, json: boolean): number {\n  const cliError = toCliError(error);\n\n  if (json) {\n    printJson(toErrorEnvelope(cliError));\n    return cliError.exitCode;\n  }\n\n  const firstLine = `[${cliError.code}] ${cliError.message}`;\n  process.stderr.write(`${firstLine}\\n`);\n\n  if (cliError.hint) {\n    process.stderr.write(`hint: ${cliError.hint}\\n`);\n  }\n\n  if (\n    process.env.LORO_DEBUG === \"1\" &&\n    !isCliError(error) &&\n    error instanceof Error &&\n    error.stack\n  ) {\n    process.stderr.write(`${error.stack}\\n`);\n  }\n\n  return cliError.exitCode;\n}\n","#!/usr/bin/env node\n\nimport { pathToFileURL } from \"node:url\";\nimport { runAuthCommand } from \"./commands/auth\";\nimport { runConfigCommand } from \"./commands/config\";\nimport { runDevCommand } from \"./commands/dev\";\nimport { runDashboardCommand } from \"./commands/dashboard\";\nimport { runStreamCommand, runBucketCommand } from \"./commands/stream\";\nimport { runPromptCommand } from \"./commands/prompt\";\nimport { runVersionCommand } from \"./commands/version\";\nimport { CliError, ExitCode } from \"./core/errors\";\nimport { renderHelp } from \"./core/help\";\nimport { printError, printSuccess } from \"./core/output\";\nimport type { CommandContext, CommandOutput } from \"./core/types\";\n\nfunction rootHelp(): string {\n  return renderHelp({\n    title: \"Loro CLI\",\n    summary: [\n      \"Operate Loro Streams from the terminal: log in, inspect org state, manage API keys, and read or write streams.\",\n      \"Help is hierarchical: every command, subcommand, and nested subcommand supports `--help`.\",\n    ],\n    usage: [\n      \"loro <command> [subcommand] [options]\",\n      \"loro <command> --help\",\n      \"loro <command> <subcommand> --help\",\n    ],\n    commands: [\n      {\n        name: \"auth\",\n        description: \"Login/logout, inspect identity, mint audience-scoped tokens, and switch active org context.\",\n      },\n      {\n        name: \"dashboard\",\n        description: \"Control-plane operations: buckets, usage, quota, organizations, members, and API keys.\",\n      },\n      {\n        name: \"stream\",\n        description: \"Data-plane operations on streams: create, append, read, watch, inspect, bootstrap, and snapshots.\",\n      },\n      {\n        name: \"bucket\",\n        description: \"Create, inspect, or delete buckets in the data plane.\",\n      },\n      {\n        name: \"prompt\",\n        description: \"Print task-oriented guides and protocol references for humans or AI agents.\",\n      },\n      {\n        name: \"config\",\n        description: \"Inspect or update local profile defaults such as dashboard and gateway base URLs.\",\n      },\n      {\n        name: \"dev\",\n        description: \"Start a local SQLite-backed single-node dev server for Loro Streams.\",\n      },\n      {\n        name: \"version\",\n        description: \"Print the installed CLI package version.\",\n      },\n    ],\n    options: [\n      {\n        name: \"--json\",\n        description: \"Return machine-readable output. Works with every command and is recommended for scripts and agents.\",\n      },\n      {\n        name: \"--help\",\n        description: \"Show help for the current command level instead of executing it.\",\n      },\n    ],\n    examples: [\n      \"loro auth login --host https://streams.loro.dev\",\n      \"loro dashboard api-key token --key <api-key>\",\n      \"loro stream append <bucket> <stream> --data '{\\\"type\\\":\\\"update\\\"}'\",\n      \"loro stream read <bucket> <stream> --format jsonl\",\n      \"loro bucket create <bucket>\",\n      \"loro prompt backend-api --path /api/auth/api-key/token --format json\",\n      \"loro dev --db-path ./data/dev.sqlite\",\n      \"loro version\",\n    ],\n    tips: [\n      \"Use `loro prompt` when you want a guided overview before touching the platform APIs directly.\",\n      \"Most `dashboard` commands rely on the active organization stored in your local profile; confirm it with `loro auth whoami`.\",\n      \"Stream offsets are opaque tokens. Store and replay them exactly; do not parse or derive them.\",\n    ],\n    seeAlso: [\n      \"loro auth --help\",\n      \"loro dashboard --help\",\n      \"loro stream --help\",\n      \"loro bucket --help\",\n      \"loro prompt --help\",\n      \"loro config --help\",\n      \"loro dev --help\",\n      \"loro version --help\",\n    ],\n  });\n}\n\nfunction extractGlobalFlags(argv: string[]): { args: string[]; json: boolean } {\n  const args: string[] = [];\n  let json = false;\n\n  for (const arg of argv) {\n    if (arg === \"--\") {\n      continue;\n    }\n    if (arg === \"--json\" || arg === \"-j\") {\n      json = true;\n      continue;\n    }\n    args.push(arg);\n  }\n\n  return { args, json };\n}\n\nasync function dispatch(args: string[], context: CommandContext): Promise<CommandOutput> {\n  if (args.length === 0 || args[0] === \"help\" || args[0] === \"--help\") {\n    return { text: rootHelp() };\n  }\n\n  const [command, ...rest] = args;\n\n  if (command === \"auth\") {\n    return runAuthCommand(rest, context);\n  }\n  if (command === \"dashboard\") {\n    return runDashboardCommand(rest);\n  }\n  if (command === \"stream\") {\n    return runStreamCommand(rest, context);\n  }\n  if (command === \"bucket\") {\n    return runBucketCommand(rest, context);\n  }\n  if (command === \"prompt\") {\n    return runPromptCommand(rest, context);\n  }\n  if (command === \"config\") {\n    return runConfigCommand(rest);\n  }\n  if (command === \"dev\") {\n    return runDevCommand(rest, context);\n  }\n  if (command === \"version\") {\n    return runVersionCommand(rest);\n  }\n\n  throw new CliError(\n    \"INVALID_ARGUMENTS\",\n    `Unknown command: ${command}`,\n    ExitCode.InvalidArguments,\n    {\n      hint: rootHelp(),\n    },\n  );\n}\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n  const { args, json } = extractGlobalFlags(argv);\n\n  try {\n    const result = await dispatch(args, { json });\n    printSuccess(result, json);\n    return ExitCode.Success;\n  } catch (error) {\n    return printError(error, json);\n  }\n}\n\nconst processArgvEntry = process.argv[1];\nif (processArgvEntry && import.meta.url === pathToFileURL(processArgvEntry).href) {\n  const exitCode = await main(process.argv.slice(2));\n  process.exitCode = exitCode;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,IAAY,WAAL,yBAAA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pC,SAAS,OAAO,QAAQ;GACxB,MAAM,KAAK;GACX,QAAQ,KAAK;GACb;GACA,OAAO,KAAK;GACZ,MAAM,KAAK;GACZ,CAAC;EAIA;EACD;;AAGH,SAAS,gBAAwB;AAC/B,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,oJACA,kIACD;EACD,OAAO;GACL;GACA;GACA;GACD;EACD,UAAU;GACR;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACF;EACD,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACd,EACD;GACE,MAAM;GACN,aAAa;GACd,CACF;EACD,UAAU;GACR;GACA;GACA;GACA;GACA;GACD;EACD,MAAM,CACJ,qIACA,gKACD;EACD,SAAS;GACP;GACA;GACA;GACA;GACD;EACF,CAAC;;AAGJ,SAAS,cAAsB;AAC7B,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,uIACD;EACD,OAAO,CACL,kDACA,qCACD;EACD,UAAU,CACR;GACE,MAAM;GACN,aAAa;GACd,CACF;EACD,SAAS,CAAC,sCAAsC,qBAAqB;EACtE,CAAC;;AAGJ,SAAS,kBAA0B;AACjC,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,yGACD;EACD,OAAO,CAAC,iDAAiD;EACzD,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACd,CACF;EACD,UAAU,CAAC,+BAA+B,6CAA6C;EACvF,MAAM,CACJ,qIACD;EACF,CAAC;;AAGJ,SAAS,YAAoB;AAC3B,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,6GACD;EACD,OAAO,CACL,2EACA,kCACD;EACD,UAAU,CACR;GACE,MAAM;GACN,aAAa;GACd,CACF;EACD,SAAS,C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AAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACF;EACD,UAAU,CACR,uEACA,iGACD;EACD,MAAM,CACJ,yEACD;EACF,CAAC;;AAGJ,SAAS,oBAA4B;AACnC,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,8GACD;EACD,OAAO,CACL,6GACD;EACD,SAAS;GACP;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACF;EACD,UAAU,CACR,+DACA,qEACD;EACF,CAAC;;AAGJ,SAAS,aAAqB;AAC5B,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,6JACD;EACD,OAAO,CACL,6CACA,yCACD;EACD,UAAU;GACR;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACF;EACD,UAAU;GACR;GACA;GACA;GACD;EACD,MAAM,CACJ,uHACA,iFACD;EACD,SAAS;GACP;GACA;GACA;GACD;EACF,CAAC;;AAGJ,SAAS,mBAA2B;AAClC,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,mFACD;EACD,OAAO,CACL,wGACD;EACD,SAAS;GACP;IAAE,MAAM;IAAiB,aAAa;IAA+C;GACrF;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACD;IACE,MAAM;IACN,aAAa;IACd;GACF;EACD,UAAU,CACR;GACE,OAAO;GACP,OAAO;IACL;IACA;IACA;IACA;IACA;IACD;GACF,CACF;EACD,UAAU,CACR,gEACA,mFACD;EACD,MAAM,CACJ,0IACA,4GACD;EACF,CAAC;;AAGJ,SAAS,iBAAyB;AAChC,QAAO,WAAW;EAChB,OAAO;EACP,SAAS,CACP,0EACD;EAC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A;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,SAAS,4BAAoC;AAC3C,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,KAAK;;AAGd,SAAS,sBAAmD;AAC1D,QAAO,eAAe,KAAK,EAAE,IAAI,OAAO,SAAS,eAAe;EAC9D;EACA;EACA;EACA;EACD,EAAE;;AAGL,eAAe,0BAA2C;AACxD,QAAO,gBAAgB,4BAA4B,CAAC;;AAGtD,SAAS,6BAA6B,SAAyB;AAC7D,QAAO,QACJ,MAAM,QAAQ,CACd,KAAK,SAAS;EACb,MAAM,QAAQ,+CAA+C,KAAK,KAAK;AACvE,MAAI,CAAC,MACH,QAAO;EAGT,MAAM,SAAS,MAAM;EACrB,MAAM,QAAQ,MAAM,GAAG,MAAM;AAC7B,MACE,MAAM,WAAW,KACjB,UAAU,OACV,UAAU,OACV,MAAM,WAAW,KAAI,IACrB,MAAM,WAAW,IAAI,CAErB,QAAO;AAGT,MAAI,MAAM,SAAS,KAAK,CACtB,QAAO,GAAG,SAAS,KAAK,UAAU,MAAM;AAG1C,SAAO;GACP,CACD,KAAK,KAAK;;AAGf,eAAe,6BAA+D;CAE5E,MAAM,iBAAiB,6BADP,MAAM,yBAAyB,CACa;CAC5D,IAAI;AACJ,KAAI;A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