{"version":3,"sources":["../src/errors.ts","../src/container/ca.ts","../src/container/credentials.ts","../src/container/index.ts","../src/agents/index.ts","../src/approvals/index.ts","../src/provisions/index.ts","../src/approvals/org.ts","../src/org/index.ts","../src/client.ts","../src/gateway/types.ts"],"sourcesContent":["export class OneCLIError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"OneCLIError\";\n  }\n}\n\nexport class OneCLIRequestError extends Error {\n  public readonly url: string;\n  public readonly statusCode: number;\n\n  constructor(\n    message: string,\n    requestData: { url: string; statusCode: number },\n  ) {\n    super(\n      `[URL=${requestData.url}] [StatusCode=${requestData.statusCode}] ${message}`,\n    );\n    this.name = \"OneCLIRequestError\";\n    this.url = requestData.url;\n    this.statusCode = requestData.statusCode;\n  }\n}\n\nexport function toOneCLIError(error: unknown): OneCLIError | OneCLIRequestError {\n  if (error instanceof OneCLIError || error instanceof OneCLIRequestError) {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    return new OneCLIError(error.message);\n  }\n\n  return new OneCLIError(String(error));\n}\n","import { readFileSync, writeFileSync } from \"fs\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\n\n/** Host-side system CA bundle locations (in priority order). */\nconst SYSTEM_CA_PATHS = [\n  \"/etc/ssl/cert.pem\", // macOS\n  \"/etc/ssl/certs/ca-certificates.crt\", // Debian / Ubuntu\n  \"/etc/pki/tls/certs/ca-bundle.crt\", // RHEL / CentOS / Fedora\n];\n\n/**\n * Write the proxy CA certificate PEM to a temp file on the host.\n * Returns the path to the written file.\n */\nexport function writeCaCertificate(caCertificate: string): string {\n  const outPath = join(tmpdir(), \"onecli-proxy-ca.pem\");\n  writeFileSync(outPath, caCertificate);\n  return outPath;\n}\n\n/**\n * Build a combined CA bundle (system CAs + OneCLI proxy CA) on the host.\n * Returns the path to the combined file, or `null` on failure.\n */\nexport function buildCombinedCaBundle(caCertificate: string): string | null {\n  for (const sysPath of SYSTEM_CA_PATHS) {\n    try {\n      const sysCa = readFileSync(sysPath, \"utf8\");\n      const combined = sysCa.trimEnd() + \"\\n\" + caCertificate.trimEnd() + \"\\n\";\n      const outPath = join(tmpdir(), \"onecli-combined-ca.pem\");\n      writeFileSync(outPath, combined);\n      return outPath;\n    } catch {\n      continue;\n    }\n  }\n\n  return null;\n}\n","import { mkdirSync, writeFileSync } from \"fs\";\nimport { tmpdir } from \"os\";\nimport { basename, join } from \"path\";\n\n/**\n * Write a credential stub to a temp file on the host.\n * Returns the path to the written file.\n */\nexport function writeCredentialStub(\n  containerPath: string,\n  content: string,\n): string {\n  const filename = `onecli-stub-${basename(containerPath)}`;\n  const outDir = join(tmpdir(), \"onecli-stubs\");\n  mkdirSync(outDir, { recursive: true });\n  const outPath = join(outDir, filename);\n  writeFileSync(outPath, content, { mode: 0o600 });\n  return outPath;\n}\n","import { OneCLIError, OneCLIRequestError, toOneCLIError } from \"../errors.js\";\nimport { writeCaCertificate, buildCombinedCaBundle } from \"./ca.js\";\nimport { writeCredentialStub } from \"./credentials.js\";\nimport type {\n  ApplyContainerConfigOptions,\n  ContainerConfig,\n  GetContainerConfigOptions,\n} from \"./types.js\";\nimport type { RequestOptions } from \"../request-options.js\";\n\nexport class ContainerClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private timeout: number;\n  private defaultProjectId: string | null;\n\n  constructor(\n    baseUrl: string,\n    apiKey: string,\n    timeout: number,\n    defaultProjectId: string | null,\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.timeout = timeout;\n    this.defaultProjectId = defaultProjectId;\n  }\n\n  private buildHeaders(options?: RequestOptions): Record<string, string> {\n    const headers: Record<string, string> = {};\n    if (this.apiKey) {\n      headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n    }\n    const projectId = options?.projectId ?? this.defaultProjectId;\n    if (projectId) {\n      headers[\"X-Project-Id\"] = projectId;\n    }\n    return headers;\n  }\n\n  /**\n   * Fetch the gateway skill markdown from OneCLI.\n   */\n  getGatewaySkill = async (options?: RequestOptions): Promise<string> => {\n    const url = `${this.baseUrl}/v1/skill/gateway`;\n    try {\n      const res = await fetch(url, {\n        headers: this.buildHeaders(options),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        throw new OneCLIRequestError(\n          `OneCLI returned ${res.status} ${res.statusText}`,\n          { url, statusCode: res.status },\n        );\n      }\n\n      return await res.text();\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n\n  /**\n   * Fetch the raw container configuration from OneCLI.\n   */\n  getContainerConfig = async (\n    options?: GetContainerConfigOptions,\n  ): Promise<ContainerConfig> => {\n    const { agent, ...requestOptions } = options ?? {};\n    const url = agent\n      ? `${this.baseUrl}/v1/container-config?agent=${encodeURIComponent(agent)}`\n      : `${this.baseUrl}/v1/container-config`;\n\n    try {\n      const res = await fetch(url, {\n        headers: this.buildHeaders(requestOptions),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        throw new OneCLIRequestError(\n          `OneCLI returned ${res.status} ${res.statusText}`,\n          { url, statusCode: res.status },\n        );\n      }\n\n      return (await res.json()) as ContainerConfig;\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n\n  /**\n   * Fetch the container config from OneCLI and push the corresponding\n   * `-e` and `-v` flags onto the Docker `run` argument array.\n   *\n   * Returns `true` once config is applied. Returns `false` only when OneCLI\n   * is unreachable or unhealthy (network error or 5xx) -- a transient outage\n   * shouldn't block container launches.\n   *\n   * Throws `OneCLIRequestError` on a 4xx response (e.g. the agent identifier\n   * isn't registered, or the API key is invalid). Those are caller\n   * misconfigurations: degrading silently would launch the container without\n   * credentials and leave it hanging. Handle the error -- don't swallow it.\n   */\n  applyContainerConfig = async (\n    args: string[],\n    options?: ApplyContainerConfigOptions,\n  ): Promise<boolean> => {\n    const {\n      combineCaBundle = true,\n      addHostMapping = true,\n      agent,\n      projectId,\n    } = options ?? {};\n\n    let config: ContainerConfig;\n    try {\n      config = await this.getContainerConfig({ agent, projectId });\n    } catch (error) {\n      // Fail loud on caller/config errors (4xx): a missing agent, invalid API\n      // key, or forbidden project means the container would otherwise launch\n      // WITHOUT credentials and silently hang. Surface it so it's traceable.\n      if (\n        error instanceof OneCLIRequestError &&\n        error.statusCode >= 400 &&\n        error.statusCode < 500\n      ) {\n        throw error;\n      }\n      // Graceful degradation only when OneCLI is unreachable or unhealthy\n      // (network error or 5xx) -- don't block launches on a transient outage.\n      return false;\n    }\n\n    // Inject server-controlled environment variables\n    for (const [key, value] of Object.entries(config.env)) {\n      args.push(\"-e\", `${key}=${value}`);\n    }\n\n    // Write CA certificate to host temp file and mount into container\n    const hostCaPath = writeCaCertificate(config.caCertificate);\n    args.push(\n      \"-v\",\n      `${hostCaPath}:${config.caCertificateContainerPath}:ro`,\n    );\n\n    // Build combined CA bundle for system-wide trust (curl, Python, Go, etc.)\n    if (combineCaBundle) {\n      const combinedPath = buildCombinedCaBundle(config.caCertificate);\n      if (combinedPath) {\n        args.push(\"-e\", \"SSL_CERT_FILE=/tmp/onecli-combined-ca.pem\");\n        // DENO_CERT: Deno does not respect SSL_CERT_FILE, it has its own env var\n        args.push(\"-e\", \"DENO_CERT=/tmp/onecli-combined-ca.pem\");\n        args.push(\"-v\", `${combinedPath}:/tmp/onecli-combined-ca.pem:ro`);\n      }\n    }\n\n    // Write credential stubs and mount into container\n    if (config.credentialStubs?.length) {\n      for (const stub of config.credentialStubs) {\n        const hostPath = writeCredentialStub(\n          stub.containerPath,\n          stub.content,\n        );\n        args.push(\"-v\", `${hostPath}:${stub.containerPath}:ro`);\n      }\n    }\n\n    // On Linux, host.docker.internal needs explicit mapping.\n    if (addHostMapping && process.platform === \"linux\") {\n      args.push(\"--add-host\", \"host.docker.internal:host-gateway\");\n    }\n\n    return true;\n  };\n}\n","import {\n  OneCLIError,\n  OneCLIRequestError,\n  toOneCLIError,\n} from \"../errors.js\";\nimport type {\n  Agent,\n  AgentGrants,\n  AgentWithGrantsSummary,\n  AppPermissionDefinition,\n  ConnectionAgentAccess,\n  ConnectionGrantInput,\n  ConnectionGrants,\n  EffectiveAppPermissions,\n  CreateAgentInput,\n  CreateAgentResponse,\n  EffectiveCredentials,\n  EnsureAgentResponse,\n} from \"./types.js\";\nimport type { RequestOptions } from \"../request-options.js\";\n\n/** Extract the server error-envelope message from a response body, if any. */\nconst parseErrorEnvelope = (body: string): string | null => {\n  try {\n    const parsed = JSON.parse(body) as {\n      error?: { message?: string } | string;\n    };\n    if (typeof parsed.error === \"string\") return parsed.error;\n    if (parsed.error && typeof parsed.error.message === \"string\") {\n      return parsed.error.message;\n    }\n    return null;\n  } catch {\n    return null;\n  }\n};\n\nexport class AgentsClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private timeout: number;\n  private defaultProjectId: string | null;\n\n  constructor(\n    baseUrl: string,\n    apiKey: string,\n    timeout: number,\n    defaultProjectId: string | null,\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.timeout = timeout;\n    this.defaultProjectId = defaultProjectId;\n  }\n\n  private buildHeaders(options?: RequestOptions): Record<string, string> {\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n    };\n    if (this.apiKey) {\n      headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n    }\n    const projectId = options?.projectId ?? this.defaultProjectId;\n    if (projectId) {\n      headers[\"X-Project-Id\"] = projectId;\n    }\n    return headers;\n  }\n\n  /**\n   * Create a new agent.\n   */\n  createAgent = async (\n    input: CreateAgentInput,\n    options?: RequestOptions,\n  ): Promise<CreateAgentResponse> => {\n    const url = `${this.baseUrl}/v1/agents`;\n\n    try {\n      const res = await fetch(url, {\n        method: \"POST\",\n        headers: this.buildHeaders(options),\n        body: JSON.stringify(input),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        throw new OneCLIRequestError(\n          `OneCLI returned ${res.status} ${res.statusText}`,\n          { url, statusCode: res.status },\n        );\n      }\n\n      return (await res.json()) as CreateAgentResponse;\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n\n  /**\n   * List all agents in the project.\n   */\n  listAgents = async (options?: RequestOptions): Promise<Agent[]> =>\n    this.request<Agent[]>(\"GET\", \"/v1/agents\", undefined, options);\n\n  /**\n   * List all agents with each one's attach summary — its granted connections,\n   * secrets, and LLM keys (`GET /v1/agents?include=grants-summary`).\n   */\n  listAgentsWithGrants = async (\n    options?: RequestOptions,\n  ): Promise<AgentWithGrantsSummary[]> =>\n    this.request<AgentWithGrantsSummary[]>(\n      \"GET\",\n      \"/v1/agents?include=grants-summary\",\n      undefined,\n      options,\n    );\n\n  /**\n   * Shared request path. Non-2xx responses surface the server's error-envelope\n   * message when one exists (`{ error: { message } }` or `{ error: \"...\" }`) —\n   * a 410's pointer at the replacement endpoint, a 422's validation law —\n   * instead of a bare status line. 204 responses resolve to undefined.\n   */\n  private request = async <T>(\n    method: \"GET\" | \"PUT\" | \"DELETE\",\n    path: string,\n    body?: unknown,\n    options?: RequestOptions,\n  ): Promise<T> => {\n    const url = `${this.baseUrl}${path}`;\n\n    try {\n      const res = await fetch(url, {\n        method,\n        headers: this.buildHeaders(options),\n        ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        const detail = parseErrorEnvelope(await res.text().catch(() => \"\"));\n        throw new OneCLIRequestError(\n          detail ?? `OneCLI returned ${res.status} ${res.statusText}`,\n          { url, statusCode: res.status },\n        );\n      }\n\n      if (res.status === 204) {\n        return undefined as T;\n      }\n      return (await res.json()) as T;\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n\n  /**\n   * Shared GET for the read-only reflections. Mirrors `listAgents`' error\n   * handling so every method on this client fails the same way.\n   */\n  private getJson = async <T>(\n    path: string,\n    options?: RequestOptions,\n  ): Promise<T> => this.request<T>(\"GET\", path, undefined, options);\n\n  /**\n   * The agent's grants: its attached app connections (with per-tool access)\n   * and secrets. Grants are attach INTENT — `getEffectiveCredentials` is the\n   * effective view with organization guardrails applied.\n   */\n  getAgentGrants = async (\n    agentId: string,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> =>\n    this.request<AgentGrants>(\n      \"GET\",\n      `/v1/agents/${encodeURIComponent(agentId)}/grants`,\n      undefined,\n      options,\n    );\n\n  /**\n   * Attach an app connection to the agent, or replace its per-tool access.\n   * Returns the agent's fresh grant set. Idempotent — an identical desired\n   * state writes nothing and still returns 200.\n   */\n  setConnectionGrant = async (\n    agentId: string,\n    connectionId: string,\n    input: ConnectionGrantInput,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> =>\n    this.request<AgentGrants>(\n      \"PUT\",\n      `/v1/agents/${encodeURIComponent(agentId)}/grants/connections/${encodeURIComponent(connectionId)}`,\n      input,\n      options,\n    );\n\n  /**\n   * Detach an app connection from the agent (204; resolves to void). Also the\n   * only way to express \"no tools at all\" — the server rejects an all-blocked\n   * custom grant with 422.\n   */\n  removeConnectionGrant = async (\n    agentId: string,\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<void> =>\n    this.request<void>(\n      \"DELETE\",\n      `/v1/agents/${encodeURIComponent(agentId)}/grants/connections/${encodeURIComponent(connectionId)}`,\n      undefined,\n      options,\n    );\n\n  /**\n   * Attach a secret or LLM key to the agent. Secrets have no per-tool axis —\n   * the PUT takes no body. Returns the agent's fresh grant set.\n   */\n  attachSecret = async (\n    agentId: string,\n    secretId: string,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> =>\n    this.request<AgentGrants>(\n      \"PUT\",\n      `/v1/agents/${encodeURIComponent(agentId)}/grants/secrets/${encodeURIComponent(secretId)}`,\n      undefined,\n      options,\n    );\n\n  /** Detach a secret from the agent (204; resolves to void). */\n  detachSecret = async (\n    agentId: string,\n    secretId: string,\n    options?: RequestOptions,\n  ): Promise<void> =>\n    this.request<void>(\n      \"DELETE\",\n      `/v1/agents/${encodeURIComponent(agentId)}/grants/secrets/${encodeURIComponent(secretId)}`,\n      undefined,\n      options,\n    );\n\n  /**\n   * Which agents a connection is granted to (attach intent, read-only).\n   * The connection-side writes are the same server operations as\n   * `setConnectionGrant`/`removeConnectionGrant` — use those.\n   */\n  getConnectionGrants = async (\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<ConnectionGrants> =>\n    this.request<ConnectionGrants>(\n      \"GET\",\n      `/v1/connections/${encodeURIComponent(connectionId)}/grants`,\n      undefined,\n      options,\n    );\n\n  /**\n   * Which credentials this agent can actually use, and what each one can do\n   * under the published policy.\n   *\n   * Replaces the retired `GET /v1/agents/:id/{secrets,connections}` reads. Those\n   * returned a stored assignment list; this returns the EFFECTIVE set, so a\n   * credential granted by a policy rule appears here even though no assignment\n   * row exists for it.\n   */\n  getEffectiveCredentials = async (\n    agentId: string,\n    options?: RequestOptions,\n  ): Promise<EffectiveCredentials> =>\n    this.getJson<EffectiveCredentials>(\n      `/v1/agents/${encodeURIComponent(agentId)}/effective-credentials`,\n      options,\n    );\n\n  /**\n   * What the project's published policy allows for an app, per tool. Omit\n   * `agentId` for the all-agents baseline.\n   *\n   * The project-scope twin of `org.getEffectiveAppPermissions`, and the\n   * replacement for the retired `/v1/rules/permissions/:provider`.\n   */\n  getEffectiveAppPermissions = async (\n    input: { provider: string; agentId?: string },\n    options?: RequestOptions,\n  ): Promise<EffectiveAppPermissions> => {\n    const query = new URLSearchParams({ provider: input.provider });\n    if (input.agentId) query.set(\"agentId\", input.agentId);\n    return this.getJson<EffectiveAppPermissions>(\n      `/v1/policy/effective-app-permissions?${query.toString()}`,\n      options,\n    );\n  };\n\n  /**\n   * Which agents can reach a connection, and what each can do with it.\n   *\n   * Replaces the retired `GET /v1/connections/:id/agents`.\n   */\n  getConnectionAgentAccess = async (\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<ConnectionAgentAccess> =>\n    this.getJson<ConnectionAgentAccess>(\n      `/v1/connections/${encodeURIComponent(connectionId)}/effective-agents`,\n      options,\n    );\n\n  /**\n   * Every provider's public tool catalog — the tool ids an app-target policy\n   * rule can name. Global data; no project context required.\n   */\n  listAppPermissionDefinitions = async (\n    options?: RequestOptions,\n  ): Promise<AppPermissionDefinition[]> =>\n    this.getJson<AppPermissionDefinition[]>(\n      \"/v1/apps/permission-definitions\",\n      options,\n    );\n\n  /**\n   * Whether an agent with the given identifier already exists in the project.\n   * Swallows lookup failures and returns `false` so callers can fall back to\n   * surfacing their original error when existence can't be confirmed.\n   */\n  private agentExists = async (\n    identifier: string,\n    options?: RequestOptions,\n  ): Promise<boolean> => {\n    try {\n      const agents = await this.listAgents(options);\n      return agents.some((a) => a.identifier === identifier);\n    } catch {\n      return false;\n    }\n  };\n\n  /**\n   * Ensure an agent exists. Creates it if missing, returns normally if it already exists.\n   * Unlike `createAgent`, this method treats a 409 conflict as success.\n   */\n  ensureAgent = async (\n    input: CreateAgentInput,\n    options?: RequestOptions,\n  ): Promise<EnsureAgentResponse> => {\n    try {\n      await this.createAgent(input, options);\n      return { name: input.name, identifier: input.identifier, created: true };\n    } catch (error) {\n      if (error instanceof OneCLIRequestError && error.statusCode === 409) {\n        return {\n          name: input.name,\n          identifier: input.identifier,\n          created: false,\n        };\n      }\n      // At the agent cap the server may evaluate the quota before the\n      // identifier-uniqueness check and return 403 where it would otherwise\n      // return 409 for an existing identifier. Re-creating an existing agent is\n      // a no-op, so confirm existence and treat it as success; only surface the\n      // quota error when the agent genuinely doesn't exist. See issue #40.\n      if (error instanceof OneCLIRequestError && error.statusCode === 403) {\n        if (await this.agentExists(input.identifier, options)) {\n          return {\n            name: input.name,\n            identifier: input.identifier,\n            created: false,\n          };\n        }\n      }\n      throw error;\n    }\n  };\n}\n","import { OneCLIRequestError } from \"../errors.js\";\nimport type { ApprovalRequest, ManualApprovalCallback } from \"./types.js\";\nimport type { RequestOptions } from \"../request-options.js\";\n\n/** Internal response shape from the gateway long-poll endpoint. */\ninterface PollResponse {\n  requests: ApprovalRequest[];\n  timeoutSeconds: number;\n}\n\nexport class ApprovalClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private gatewayUrl: string | null;\n  private defaultProjectId: string | null;\n  private running = false;\n  private abortController: AbortController | null = null;\n\n  /**\n   * Tracks approval IDs currently being processed by a callback.\n   * Prevents duplicate callback invocations for the same request\n   * when the poll returns it again before the decision is submitted.\n   */\n  private inFlight = new Set<string>();\n\n  constructor(\n    baseUrl: string,\n    apiKey: string,\n    gatewayUrl: string | null,\n    defaultProjectId: string | null,\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.gatewayUrl = gatewayUrl;\n    this.defaultProjectId = defaultProjectId;\n  }\n\n  private buildAuthHeaders(projectId?: string | null): Record<string, string> {\n    const headers: Record<string, string> = {\n      Authorization: `Bearer ${this.apiKey}`,\n    };\n    const resolved = projectId ?? this.defaultProjectId;\n    if (resolved) {\n      headers[\"X-Project-Id\"] = resolved;\n    }\n    return headers;\n  }\n\n  /**\n   * Resolve the gateway URL from the web app.\n   * Called once on first poll, then cached.\n   */\n  private async resolveGatewayUrl(\n    projectId?: string | null,\n  ): Promise<string> {\n    if (this.gatewayUrl) return this.gatewayUrl;\n\n    const url = `${this.baseUrl}/v1/gateway-url`;\n    const res = await fetch(url, {\n      headers: this.buildAuthHeaders(projectId),\n      signal: AbortSignal.timeout(5000),\n    });\n\n    if (!res.ok) {\n      throw new OneCLIRequestError(\"Failed to resolve gateway URL\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n\n    const data = (await res.json()) as { url: string };\n    this.gatewayUrl = data.url.replace(/\\/+$/, \"\");\n    return this.gatewayUrl;\n  }\n\n  /**\n   * Start the long-polling loop. Runs until stop() is called.\n   *\n   * Dispatches callbacks concurrently — multiple approvals are handled\n   * in parallel without blocking each other or the polling loop.\n   * Each approval ID is tracked in `inFlight` to prevent duplicate\n   * callback invocations. On failure (callback throws or decision\n   * submission fails), the ID is removed from `inFlight` and the\n   * approval will be retried on the next poll cycle.\n   */\n  async start(\n    callback: ManualApprovalCallback,\n    options?: RequestOptions,\n  ): Promise<void> {\n    this.running = true;\n    const projectId = options?.projectId ?? null;\n    const gatewayUrl = await this.resolveGatewayUrl(projectId);\n\n    while (this.running) {\n      try {\n        const poll = await this.poll(gatewayUrl, projectId);\n\n        for (const request of poll.requests) {\n          this.inFlight.add(request.id);\n          request.timeoutSeconds = poll.timeoutSeconds;\n\n          this.handleRequest(gatewayUrl, request, callback, projectId);\n        }\n      } catch {\n        if (!this.running) return;\n        await this.sleep(5000);\n      }\n    }\n  }\n\n  /**\n   * Process a single approval: call the callback, submit the decision.\n   * Runs independently — multiple calls execute concurrently.\n   * On any failure, removes from inFlight so the next poll retries.\n   */\n  private handleRequest(\n    gatewayUrl: string,\n    request: ApprovalRequest,\n    callback: ManualApprovalCallback,\n    projectId?: string | null,\n  ): void {\n    (async () => {\n      try {\n        const decision = await callback(request);\n        await this.submitDecision(gatewayUrl, request.id, decision, projectId);\n      } finally {\n        this.inFlight.delete(request.id);\n      }\n    })().catch(() => {\n      this.inFlight.delete(request.id);\n    });\n  }\n\n  /** Stop the polling loop and abort any in-flight poll request. */\n  stop(): void {\n    this.running = false;\n    this.abortController?.abort();\n  }\n\n  /**\n   * Long-poll the gateway for pending approvals.\n   * Server holds up to 30s; we set a 35s client timeout.\n   */\n  private async poll(\n    gatewayUrl: string,\n    projectId?: string | null,\n  ): Promise<PollResponse> {\n    this.abortController = new AbortController();\n\n    let url = `${gatewayUrl}/v1/approvals/pending`;\n    if (this.inFlight.size > 0) {\n      const exclude = [...this.inFlight].join(\",\");\n      url += `?exclude=${encodeURIComponent(exclude)}`;\n    }\n    const res = await fetch(url, {\n      headers: this.buildAuthHeaders(projectId),\n      signal: AbortSignal.any([\n        this.abortController.signal,\n        AbortSignal.timeout(35_000),\n      ]),\n    });\n\n    if (!res.ok) {\n      throw new OneCLIRequestError(\"Approval poll failed\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n\n    return (await res.json()) as PollResponse;\n  }\n\n  /** Submit a decision for a single approval request. */\n  private async submitDecision(\n    gatewayUrl: string,\n    id: string,\n    decision: string,\n    projectId?: string | null,\n  ): Promise<void> {\n    const url = `${gatewayUrl}/v1/approvals/${encodeURIComponent(id)}/decision`;\n\n    const headers = this.buildAuthHeaders(projectId);\n    headers[\"Content-Type\"] = \"application/json\";\n\n    const res = await fetch(url, {\n      method: \"POST\",\n      headers,\n      body: JSON.stringify({ decision }),\n      signal: AbortSignal.timeout(5000),\n    });\n\n    if (!res.ok && res.status !== 410) {\n      throw new OneCLIRequestError(\"Decision submission failed\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n  }\n\n  private sleep(ms: number): Promise<void> {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n  }\n}\n","import {\n  OneCLIError,\n  OneCLIRequestError,\n  toOneCLIError,\n} from \"../errors.js\";\nimport type { ProvisionProjectInput, ProvisionProjectResponse } from \"./types.js\";\nimport type { RequestOptions } from \"../request-options.js\";\n\nexport class ProvisionClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private timeout: number;\n  private defaultProjectId: string | null;\n\n  constructor(\n    baseUrl: string,\n    apiKey: string,\n    timeout: number,\n    defaultProjectId: string | null,\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.timeout = timeout;\n    this.defaultProjectId = defaultProjectId;\n  }\n\n  private buildHeaders(options?: RequestOptions): Record<string, string> {\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n    };\n    if (this.apiKey) {\n      headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n    }\n    const projectId = options?.projectId ?? this.defaultProjectId;\n    if (projectId) {\n      headers[\"X-Project-Id\"] = projectId;\n    }\n    return headers;\n  }\n\n  /**\n   * Provision a new project in your organization.\n   * Pre-creates a user account, project, and API key.\n   * Returns a claim URL and API key. Requires admin/owner role.\n   */\n  provisionProject = async (\n    input?: ProvisionProjectInput,\n    options?: RequestOptions,\n  ): Promise<ProvisionProjectResponse> => {\n    const url = `${this.baseUrl}/v1/team/provisions`;\n\n    try {\n      const res = await fetch(url, {\n        method: \"POST\",\n        headers: this.buildHeaders(options),\n        body: JSON.stringify(input ?? {}),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        if (res.status === 404) {\n          throw new OneCLIError(\n            \"Project provisioning requires OneCLI Cloud. See https://onecli.sh for details.\",\n          );\n        }\n        throw new OneCLIRequestError(\n          `OneCLI returned ${res.status} ${res.statusText}`,\n          { url, statusCode: res.status },\n        );\n      }\n\n      return (await res.json()) as ProvisionProjectResponse;\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n}\n","import { OneCLIRequestError } from \"../errors.js\";\nimport type {\n  OrgApprovalRequest,\n  OrgManualApprovalCallback,\n  OrgManualApprovalOptions,\n} from \"./types.js\";\n\n/** Internal response shape from the org-scoped long-poll endpoint. */\ninterface OrgPollResponse {\n  requests: OrgApprovalRequest[];\n  timeoutSeconds: number;\n}\n\n/**\n * Long-polls the gateway for pending approvals across **every** project in the\n * organization (`GET /v1/org/approvals/pending`) — a cross-project sibling of\n * `ApprovalClient`. Authenticates with an organization API key (`oc_org_...`)\n * and sends **no** `X-Project-Id` on the poll; each returned request carries its\n * own `projectId`, which is echoed back as `X-Project-Id` on the decision so the\n * gateway routes it to the right project (reusing the existing decision route).\n */\nexport class OrgApprovalClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private gatewayUrl: string | null;\n  private running = false;\n  private abortController: AbortController | null = null;\n\n  /**\n   * Approval IDs currently being processed by a callback. Prevents duplicate\n   * callback invocations when the poll returns a request again before its\n   * decision is submitted.\n   */\n  private inFlight = new Set<string>();\n\n  constructor(baseUrl: string, apiKey: string, gatewayUrl: string | null) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.gatewayUrl = gatewayUrl;\n  }\n\n  /**\n   * Auth headers for org requests. The poll sends only the bearer token — the\n   * organization is derived from the key. A decision additionally carries the\n   * request's `projectId` as `X-Project-Id` so it lands in the right project.\n   */\n  private buildAuthHeaders(projectId?: string): Record<string, string> {\n    const headers: Record<string, string> = {\n      Authorization: `Bearer ${this.apiKey}`,\n    };\n    if (projectId) {\n      headers[\"X-Project-Id\"] = projectId;\n    }\n    return headers;\n  }\n\n  /** Resolve the gateway URL from the web app. Called once, then cached. */\n  private async resolveGatewayUrl(): Promise<string> {\n    if (this.gatewayUrl) return this.gatewayUrl;\n\n    const url = `${this.baseUrl}/v1/gateway-url`;\n    const res = await fetch(url, {\n      headers: this.buildAuthHeaders(),\n      signal: AbortSignal.timeout(5000),\n    });\n\n    if (!res.ok) {\n      throw new OneCLIRequestError(\"Failed to resolve gateway URL\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n\n    const data = (await res.json()) as { url: string };\n    this.gatewayUrl = data.url.replace(/\\/+$/, \"\");\n    return this.gatewayUrl;\n  }\n\n  /**\n   * Start the long-polling loop. Runs until stop() is called. Dispatches\n   * callbacks concurrently, one per pending approval. On a failed poll cycle the\n   * error is passed to `options.onError` (if given) and the loop backs off and\n   * retries — unlike the project client, it does not swallow errors silently.\n   */\n  async start(\n    callback: OrgManualApprovalCallback,\n    options?: OrgManualApprovalOptions,\n  ): Promise<void> {\n    this.running = true;\n\n    while (this.running) {\n      try {\n        // Resolve inside the loop so a gateway-URL resolution failure also\n        // routes to `onError` and backs off (not just poll failures). It\n        // caches on success, so this is a cheap guard after the first poll.\n        const gatewayUrl = await this.resolveGatewayUrl();\n        const poll = await this.poll(gatewayUrl);\n\n        for (const request of poll.requests) {\n          this.inFlight.add(request.id);\n          request.timeoutSeconds = poll.timeoutSeconds;\n\n          this.handleRequest(gatewayUrl, request, callback);\n        }\n      } catch (error) {\n        if (!this.running) return;\n        options?.onError?.(error);\n        await this.sleep(5000);\n      }\n    }\n  }\n\n  /**\n   * Process a single approval: call the callback, submit the decision back to\n   * the request's own project. Runs independently (concurrent). On any failure,\n   * removes from inFlight so the next poll retries.\n   */\n  private handleRequest(\n    gatewayUrl: string,\n    request: OrgApprovalRequest,\n    callback: OrgManualApprovalCallback,\n  ): void {\n    (async () => {\n      try {\n        const decision = await callback(request);\n        await this.submitDecision(\n          gatewayUrl,\n          request.id,\n          decision,\n          request.projectId,\n        );\n      } finally {\n        this.inFlight.delete(request.id);\n      }\n    })().catch(() => {\n      this.inFlight.delete(request.id);\n    });\n  }\n\n  /** Stop the polling loop and abort any in-flight poll request. */\n  stop(): void {\n    this.running = false;\n    this.abortController?.abort();\n  }\n\n  /**\n   * Long-poll the gateway for pending approvals across the org.\n   * Server holds up to 30s; we set a 35s client timeout.\n   */\n  private async poll(gatewayUrl: string): Promise<OrgPollResponse> {\n    this.abortController = new AbortController();\n\n    let url = `${gatewayUrl}/v1/org/approvals/pending`;\n    if (this.inFlight.size > 0) {\n      const exclude = [...this.inFlight].join(\",\");\n      url += `?exclude=${encodeURIComponent(exclude)}`;\n    }\n    const res = await fetch(url, {\n      headers: this.buildAuthHeaders(),\n      signal: AbortSignal.any([\n        this.abortController.signal,\n        AbortSignal.timeout(35_000),\n      ]),\n    });\n\n    if (!res.ok) {\n      throw new OneCLIRequestError(\"Org approval poll failed\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n\n    return (await res.json()) as OrgPollResponse;\n  }\n\n  /** Submit a decision for a single approval, scoped to its own project. */\n  private async submitDecision(\n    gatewayUrl: string,\n    id: string,\n    decision: string,\n    projectId: string,\n  ): Promise<void> {\n    const url = `${gatewayUrl}/v1/approvals/${encodeURIComponent(id)}/decision`;\n\n    const headers = this.buildAuthHeaders(projectId);\n    headers[\"Content-Type\"] = \"application/json\";\n\n    const res = await fetch(url, {\n      method: \"POST\",\n      headers,\n      body: JSON.stringify({ decision }),\n      signal: AbortSignal.timeout(5000),\n    });\n\n    if (!res.ok && res.status !== 410) {\n      throw new OneCLIRequestError(\"Decision submission failed\", {\n        url,\n        statusCode: res.status,\n      });\n    }\n  }\n\n  private sleep(ms: number): Promise<void> {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n  }\n}\n","import {\n  OneCLIError,\n  OneCLIRequestError,\n  toOneCLIError,\n} from \"../errors.js\";\nimport { OrgApprovalClient } from \"../approvals/org.js\";\nimport type {\n  ManualApprovalHandle,\n  OrgManualApprovalCallback,\n  OrgManualApprovalOptions,\n} from \"../approvals/types.js\";\nimport type {\n  ConnectOrgAppInput,\n  CreateOrgPolicyRuleInput,\n  GetOrgAuthorizeUrlOptions,\n  OrgConnection,\n  EffectiveAppPermissions,\n  OrgPolicyRule,\n  PolicyLastPublish,\n  PolicyPublishResult,\n  PolicyRuleAction,\n  PolicyRuleStatus,\n  PolicyWriteOptions,\n  PolicyWriteResult,\n  UpdateOrgPolicyRuleInput,\n} from \"./types.js\";\n\nconst CLOUD_OR_ENTERPRISE_HINT =\n  \"Organization-level resources require OneCLI Cloud or a self-hosted Enterprise instance. See https://onecli.sh for details.\";\n\n/**\n * Extract the server's error message/type from either error shape: the\n * envelope `{error:{message,type}}` or the flat `{error:\"...\"}`.\n */\nconst parseErrorBody = (\n  body: string,\n): { message?: string; type?: string } | null => {\n  try {\n    const parsed = JSON.parse(body) as {\n      error?: { message?: string; type?: string } | string;\n    };\n    if (typeof parsed.error === \"string\") {\n      return { message: parsed.error };\n    }\n    if (parsed.error && typeof parsed.error === \"object\") {\n      return { message: parsed.error.message, type: parsed.error.type };\n    }\n    return null;\n  } catch {\n    return null;\n  }\n};\n\n/**\n * Organization-scoped resources: connections and rules shared by every\n * project in the organization. All operations require the admin or owner\n * role.\n *\n * Unlike the project-scoped clients, org requests carry no `X-Project-Id` —\n * the organization is derived from the API key itself (use an organization\n * API key, `oc_org_...`).\n */\nexport class OrgClient {\n  private baseUrl: string;\n  private apiKey: string;\n  private timeout: number;\n  private gatewayUrl: string | null;\n\n  constructor(\n    baseUrl: string,\n    apiKey: string,\n    timeout: number,\n    gatewayUrl: string | null = null,\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/+$/, \"\");\n    this.apiKey = apiKey;\n    this.timeout = timeout;\n    this.gatewayUrl = gatewayUrl;\n  }\n\n  private buildHeaders(): Record<string, string> {\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n    };\n    if (this.apiKey) {\n      headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n    }\n    return headers;\n  }\n\n  /**\n   * Build the error for a non-ok response. A 404 usually means the org\n   * surface doesn't exist on this server (OSS) — but on Cloud/Enterprise an\n   * id-addressed call can also 404 on a missing resource\n   * (`type: \"not_found_error\"`); only the route-miss case gets the\n   * availability hint.\n   */\n  private toRequestError(\n    url: string,\n    status: number,\n    statusText: string,\n    body: string,\n  ): OneCLIError | OneCLIRequestError {\n    const parsed = parseErrorBody(body);\n    if (status === 404 && parsed?.type !== \"not_found_error\") {\n      return new OneCLIError(CLOUD_OR_ENTERPRISE_HINT);\n    }\n    const message = parsed?.message\n      ? `OneCLI returned ${status}: ${parsed.message}`\n      : `OneCLI returned ${status} ${statusText}`;\n    return new OneCLIRequestError(message, { url, statusCode: status });\n  }\n\n  private async request<T>(\n    method: string,\n    path: string,\n    body?: unknown,\n  ): Promise<T> {\n    const url = `${this.baseUrl}${path}`;\n\n    try {\n      const res = await fetch(url, {\n        method,\n        headers: this.buildHeaders(),\n        body: body === undefined ? undefined : JSON.stringify(body),\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      if (!res.ok) {\n        const errorBody = await res.text().catch(() => \"\");\n        throw this.toRequestError(url, res.status, res.statusText, errorBody);\n      }\n\n      if (res.status === 204) {\n        return undefined as T;\n      }\n      return (await res.json()) as T;\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  }\n\n  /**\n   * Connect an app at the organization level with direct credentials\n   * (API-key / imported-credential apps). The connection is shared by every\n   * project in the organization.\n   */\n  connectApp = async (\n    provider: string,\n    input: ConnectOrgAppInput,\n  ): Promise<{ success: boolean }> => {\n    return this.request<{ success: boolean }>(\n      \"POST\",\n      `/v1/org/apps/${encodeURIComponent(provider)}/connect`,\n      input,\n    );\n  };\n\n  /**\n   * Start an org-scoped OAuth flow and return the provider's authorize URL.\n   * Open the URL in a browser to finish; the resulting connection is created\n   * at the organization level.\n   *\n   * Server-side runtimes only: it relies on `redirect: \"manual\"` exposing the\n   * `Location` header (Node's fetch does; browser fetch returns an opaque\n   * redirect and would always throw here).\n   */\n  getAuthorizeUrl = async (\n    provider: string,\n    options?: GetOrgAuthorizeUrlOptions,\n  ): Promise<string> => {\n    const query = options?.connectionId\n      ? `?connectionId=${encodeURIComponent(options.connectionId)}`\n      : \"\";\n    const url = `${this.baseUrl}/v1/org/apps/${encodeURIComponent(provider)}/authorize${query}`;\n\n    try {\n      const res = await fetch(url, {\n        method: \"GET\",\n        headers: this.buildHeaders(),\n        redirect: \"manual\",\n        signal: AbortSignal.timeout(this.timeout),\n      });\n\n      const location = res.headers.get(\"location\");\n      if (res.status >= 300 && res.status < 400 && location) {\n        return location;\n      }\n\n      const errorBody = await res.text().catch(() => \"\");\n      if (res.status >= 400) {\n        throw this.toRequestError(url, res.status, res.statusText, errorBody);\n      }\n      throw new OneCLIRequestError(\n        `OneCLI returned ${res.status} ${res.statusText} instead of an authorize redirect`,\n        { url, statusCode: res.status },\n      );\n    } catch (error) {\n      if (\n        error instanceof OneCLIError ||\n        error instanceof OneCLIRequestError\n      ) {\n        throw error;\n      }\n      throw toOneCLIError(error);\n    }\n  };\n\n  /**\n   * List the organization's app connections, optionally filtered by provider.\n   */\n  listConnections = async (provider?: string): Promise<OrgConnection[]> => {\n    const query = provider\n      ? `?provider=${encodeURIComponent(provider)}`\n      : \"\";\n    return this.request<OrgConnection[]>(\"GET\", `/v1/org/connections${query}`);\n  };\n\n  /**\n   * Rename an organization connection.\n   */\n  renameConnection = async (\n    connectionId: string,\n    label: string,\n  ): Promise<OrgConnection> => {\n    return this.request<OrgConnection>(\n      \"PATCH\",\n      `/v1/org/connections/${encodeURIComponent(connectionId)}`,\n      { label },\n    );\n  };\n\n  /**\n   * Delete an organization connection.\n   */\n  deleteConnection = async (connectionId: string): Promise<void> => {\n    await this.request<undefined>(\n      \"DELETE\",\n      `/v1/org/connections/${encodeURIComponent(connectionId)}`,\n    );\n  };\n\n  /**\n   * The org's effective app permissions for a provider — what the published\n   * policy actually allows, per tool. Read-only; the replacement for the\n   * retired `/v1/org/rules/permissions/:provider` surface.\n   */\n  getEffectiveAppPermissions = async (\n    input: { provider: string },\n  ): Promise<EffectiveAppPermissions> => {\n    return this.request<EffectiveAppPermissions>(\n      \"GET\",\n      `/v1/org/policy/effective-app-permissions?provider=${encodeURIComponent(input.provider)}`,\n    );\n  };\n\n  // ── The policy engine (staged draft → publish) ────────────────────────────\n  //\n  // Writes land in the org's DRAFT and enforce only after a publish. By\n  // default each write method publishes immediately; note a publish\n  // snapshots the WHOLE org draft — including changes staged by other users\n  // — so pass `{ skipPublish: true }` and call `publishPolicy()` explicitly\n  // when several people edit policy. If the publish step fails after a\n  // successful write, the write IS staged and the PUBLISH request's error is\n  // rethrown unchanged (its `url` ends with `/publish`) — do NOT retry the\n  // write (that would stage a duplicate); inspect via\n  // `listPolicyRules(\"draft\")` and retry `publishPolicy()` instead.\n\n  /**\n   * List the organization's policy-engine rules — the DRAFT working copy by\n   * default, or the enforced set with `\"published\"`.\n   */\n  listPolicyRules = async (\n    status: PolicyRuleStatus = \"draft\",\n  ): Promise<OrgPolicyRule[]> => {\n    return this.request<OrgPolicyRule[]>(\n      \"GET\",\n      `/v1/org/policy/rules?status=${status}`,\n    );\n  };\n\n  /**\n   * Get one DRAFT policy rule. Published row ids regenerate on every\n   * publish — list with `\"published\"` and match by `logicalId` instead.\n   */\n  getPolicyRule = async (ruleId: string): Promise<OrgPolicyRule> => {\n    return this.request<OrgPolicyRule>(\n      \"GET\",\n      `/v1/org/policy/rules/${encodeURIComponent(ruleId)}`,\n    );\n  };\n\n  /**\n   * Create a policy rule (and publish, unless `skipPublish`).\n   */\n  createPolicyRule = async (\n    input: CreateOrgPolicyRuleInput,\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<OrgPolicyRule>> => {\n    const rule = await this.request<OrgPolicyRule>(\n      \"POST\",\n      \"/v1/org/policy/rules\",\n      input,\n    );\n    return this.finishPolicyWrite(rule, options);\n  };\n\n  /**\n   * Update a DRAFT policy rule (and publish, unless `skipPublish`).\n   */\n  updatePolicyRule = async (\n    ruleId: string,\n    input: UpdateOrgPolicyRuleInput,\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<OrgPolicyRule>> => {\n    const rule = await this.request<OrgPolicyRule>(\n      \"PATCH\",\n      `/v1/org/policy/rules/${encodeURIComponent(ruleId)}`,\n      input,\n    );\n    return this.finishPolicyWrite(rule, options);\n  };\n\n  /**\n   * Delete a DRAFT policy rule (and publish, unless `skipPublish`).\n   */\n  deletePolicyRule = async (\n    ruleId: string,\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<null>> => {\n    await this.request<undefined>(\n      \"DELETE\",\n      `/v1/org/policy/rules/${encodeURIComponent(ruleId)}`,\n    );\n    return this.finishPolicyWrite(null, options);\n  };\n\n  /**\n   * Reorder the DRAFT (and publish, unless `skipPublish`). `orderedIds`\n   * must name EVERY non-default draft rule exactly once — take the full\n   * list from `listPolicyRules(\"draft\")`; the server rejects a partial\n   * permutation with 409.\n   */\n  reorderPolicyRules = async (\n    orderedIds: string[],\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<OrgPolicyRule[]>> => {\n    const rules = await this.request<OrgPolicyRule[]>(\n      \"PUT\",\n      \"/v1/org/policy/rules/order\",\n      { orderedIds },\n    );\n    return this.finishPolicyWrite(rules, options);\n  };\n\n  /**\n   * Get the organization's terminal Default Rule (a virtual default is\n   * returned when none is persisted yet).\n   */\n  getPolicyDefault = async (\n    status: PolicyRuleStatus = \"draft\",\n  ): Promise<OrgPolicyRule> => {\n    return this.request<OrgPolicyRule>(\n      \"GET\",\n      `/v1/org/policy/default?status=${status}`,\n    );\n  };\n\n  /**\n   * Set the Default Rule's action (and publish, unless `skipPublish`).\n   */\n  setPolicyDefault = async (\n    action: PolicyRuleAction,\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<OrgPolicyRule>> => {\n    const rule = await this.request<OrgPolicyRule>(\n      \"PATCH\",\n      \"/v1/org/policy/default\",\n      { action },\n    );\n    return this.finishPolicyWrite(rule, options);\n  };\n\n  /**\n   * Publish the WHOLE org draft — every staged change, including other\n   * users' — into a new enforced generation.\n   */\n  publishPolicy = async (): Promise<PolicyPublishResult> => {\n    return this.request<PolicyPublishResult>(\n      \"POST\",\n      \"/v1/org/policy/publish\",\n      {},\n    );\n  };\n\n  /**\n   * The most recent publish, or `null` when the org was never published.\n   */\n  getPolicyLastPublish = async (): Promise<PolicyLastPublish | null> => {\n    return this.request<PolicyLastPublish | null>(\n      \"GET\",\n      \"/v1/org/policy/last-publish\",\n    );\n  };\n\n  /** Complete a policy write per the publish option (see the section note). */\n  private finishPolicyWrite = async <T>(\n    result: T,\n    options?: PolicyWriteOptions,\n  ): Promise<PolicyWriteResult<T>> => {\n    if (options?.skipPublish) {\n      return { result, published: false, generation: null };\n    }\n    const publish = await this.publishPolicy();\n    return { result, published: true, generation: publish.generation };\n  };\n\n  /**\n   * Register a callback for manual approval requests across **every** project\n   * in the organization. Starts background long-polling to the gateway; the\n   * callback is invoked once per pending request (concurrently), each carrying\n   * its `projectId`, and each decision is routed back to that project. Returns\n   * a handle to stop polling when shutting down.\n   *\n   * Requires an organization API key (`oc_org_...`) and OneCLI Cloud or a\n   * self-hosted Enterprise instance.\n   */\n  configureManualApproval = (\n    callback: OrgManualApprovalCallback,\n    options?: OrgManualApprovalOptions,\n  ): ManualApprovalHandle => {\n    const client = new OrgApprovalClient(\n      this.baseUrl,\n      this.apiKey,\n      this.gatewayUrl,\n    );\n    client.start(callback, options).catch(() => {\n      // Poll errors surface via options.onError and retry with backoff.\n    });\n    return { stop: () => client.stop() };\n  };\n}\n","import { ContainerClient } from \"./container/index.js\";\nimport { AgentsClient } from \"./agents/index.js\";\nimport { ApprovalClient } from \"./approvals/index.js\";\nimport { ProvisionClient } from \"./provisions/index.js\";\nimport { OrgClient } from \"./org/index.js\";\nimport type { OneCLIOptions } from \"./types.js\";\nimport type { RequestOptions } from \"./request-options.js\";\nimport type {\n  ApplyContainerConfigOptions,\n  ContainerConfig,\n  GetContainerConfigOptions,\n} from \"./container/types.js\";\nimport type {\n  Agent,\n  AgentGrants,\n  AgentWithGrantsSummary,\n  AppPermissionDefinition,\n  ConnectionAgentAccess,\n  ConnectionGrantInput,\n  ConnectionGrants,\n  CreateAgentInput,\n  EffectiveAppPermissions,\n  CreateAgentResponse,\n  EffectiveCredentials,\n  EnsureAgentResponse,\n} from \"./agents/types.js\";\nimport type {\n  ManualApprovalCallback,\n  ManualApprovalHandle,\n} from \"./approvals/types.js\";\nimport type {\n  ProvisionProjectInput,\n  ProvisionProjectResponse,\n} from \"./provisions/types.js\";\n\nconst DEFAULT_URL = \"https://api.onecli.sh\";\nconst DEFAULT_TIMEOUT = 5000;\n\nexport class OneCLI {\n  private containerClient: ContainerClient;\n  private agentsClient: AgentsClient;\n  private approvalClient: ApprovalClient;\n  private provisionClient: ProvisionClient;\n\n  /**\n   * Organization-scoped resources (connections and rules shared by every\n   * project in the org). Requests carry no `X-Project-Id` — authenticate with\n   * an organization API key (`oc_org_...`). Requires OneCLI Cloud or a\n   * self-hosted Enterprise instance.\n   */\n  readonly org: OrgClient;\n\n  constructor(options: OneCLIOptions = {}) {\n    const apiKey = options.apiKey ?? process.env.ONECLI_API_KEY ?? \"\";\n    const url = options.url ?? process.env.ONECLI_URL ?? DEFAULT_URL;\n    const timeout = options.timeout ?? DEFAULT_TIMEOUT;\n    const gatewayUrl =\n      options.gatewayUrl ?? process.env.ONECLI_GATEWAY_URL ?? null;\n    const projectId =\n      options.projectId ?? process.env.ONECLI_PROJECT_ID ?? null;\n\n    this.containerClient = new ContainerClient(\n      url,\n      apiKey,\n      timeout,\n      projectId,\n    );\n    this.agentsClient = new AgentsClient(url, apiKey, timeout, projectId);\n    this.approvalClient = new ApprovalClient(\n      url,\n      apiKey,\n      gatewayUrl,\n      projectId,\n    );\n    this.provisionClient = new ProvisionClient(\n      url,\n      apiKey,\n      timeout,\n      projectId,\n    );\n    this.org = new OrgClient(url, apiKey, timeout, gatewayUrl);\n  }\n\n  /**\n   * Fetch the gateway skill markdown from OneCLI.\n   */\n  getGatewaySkill = (options?: RequestOptions): Promise<string> => {\n    return this.containerClient.getGatewaySkill(options);\n  };\n\n  /**\n   * Fetch the raw container configuration from OneCLI.\n   */\n  getContainerConfig = (\n    options?: GetContainerConfigOptions,\n  ): Promise<ContainerConfig> => {\n    return this.containerClient.getContainerConfig(options);\n  };\n\n  /**\n   * Fetch config and apply `-e` / `-v` flags to a Docker `run` argument array.\n   * Returns `true` on success, or `false` if OneCLI is unreachable or\n   * unhealthy (network error or 5xx). Throws `OneCLIRequestError` on a 4xx\n   * response (e.g. unknown agent identifier or invalid API key) -- handle it\n   * rather than launching an uncredentialed container.\n   */\n  applyContainerConfig = (\n    args: string[],\n    options?: ApplyContainerConfigOptions,\n  ): Promise<boolean> => {\n    return this.containerClient.applyContainerConfig(args, options);\n  };\n\n  /**\n   * List all agents in the project.\n   */\n  listAgents = (options?: RequestOptions): Promise<Agent[]> => {\n    return this.agentsClient.listAgents(options);\n  };\n\n  /**\n   * List all agents with each one's attach summary — its granted connections,\n   * secrets, and LLM keys.\n   */\n  listAgentsWithGrants = (\n    options?: RequestOptions,\n  ): Promise<AgentWithGrantsSummary[]> => {\n    return this.agentsClient.listAgentsWithGrants(options);\n  };\n\n  /**\n   * The agent's grants: its attached app connections (with per-tool access)\n   * and secrets. Grants are attach INTENT — `getEffectiveCredentials` is the\n   * effective view with organization guardrails applied.\n   */\n  getAgentGrants = (\n    agentId: string,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> => {\n    return this.agentsClient.getAgentGrants(agentId, options);\n  };\n\n  /**\n   * Attach an app connection to the agent, or replace its per-tool access.\n   * Returns the agent's fresh grant set.\n   */\n  setConnectionGrant = (\n    agentId: string,\n    connectionId: string,\n    input: ConnectionGrantInput,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> => {\n    return this.agentsClient.setConnectionGrant(\n      agentId,\n      connectionId,\n      input,\n      options,\n    );\n  };\n\n  /**\n   * Detach an app connection from the agent (204; resolves to void).\n   */\n  removeConnectionGrant = (\n    agentId: string,\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<void> => {\n    return this.agentsClient.removeConnectionGrant(\n      agentId,\n      connectionId,\n      options,\n    );\n  };\n\n  /**\n   * Attach a secret or LLM key to the agent (no request body — secrets have\n   * no per-tool axis). Returns the agent's fresh grant set.\n   */\n  attachSecret = (\n    agentId: string,\n    secretId: string,\n    options?: RequestOptions,\n  ): Promise<AgentGrants> => {\n    return this.agentsClient.attachSecret(agentId, secretId, options);\n  };\n\n  /** Detach a secret from the agent (204; resolves to void). */\n  detachSecret = (\n    agentId: string,\n    secretId: string,\n    options?: RequestOptions,\n  ): Promise<void> => {\n    return this.agentsClient.detachSecret(agentId, secretId, options);\n  };\n\n  /**\n   * Which agents a connection is granted to (attach intent, read-only).\n   */\n  getConnectionGrants = (\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<ConnectionGrants> => {\n    return this.agentsClient.getConnectionGrants(connectionId, options);\n  };\n\n  /**\n   * Create a new agent.\n   */\n  createAgent = (\n    input: CreateAgentInput,\n    options?: RequestOptions,\n  ): Promise<CreateAgentResponse> => {\n    return this.agentsClient.createAgent(input, options);\n  };\n\n  /**\n   * Ensure an agent exists. Creates it if missing, returns normally if it already exists.\n   */\n  /**\n   * Which credentials this agent can actually use, and what each one can do\n   * under the published policy. Read-only.\n   *\n   * Replaces the retired `GET /v1/agents/:id/{secrets,connections}` reads —\n   * those returned a stored assignment list, this returns the EFFECTIVE set.\n   */\n  getEffectiveCredentials = (\n    agentId: string,\n    options?: RequestOptions,\n  ): Promise<EffectiveCredentials> => {\n    return this.agentsClient.getEffectiveCredentials(agentId, options);\n  };\n\n  /**\n   * What the project's published policy allows for an app, per tool.\n   * Replaces the retired `GET /v1/rules/permissions/:provider`.\n   */\n  getEffectiveAppPermissions = (\n    input: { provider: string; agentId?: string },\n    options?: RequestOptions,\n  ): Promise<EffectiveAppPermissions> => {\n    return this.agentsClient.getEffectiveAppPermissions(input, options);\n  };\n\n  /**\n   * Which agents can reach a connection, and what each can do with it.\n   * Replaces the retired `GET /v1/connections/:id/agents`.\n   */\n  getConnectionAgentAccess = (\n    connectionId: string,\n    options?: RequestOptions,\n  ): Promise<ConnectionAgentAccess> => {\n    return this.agentsClient.getConnectionAgentAccess(connectionId, options);\n  };\n\n  /**\n   * Every provider's public tool catalog — the tool ids an `app`-target policy\n   * rule can name.\n   */\n  listAppPermissionDefinitions = (\n    options?: RequestOptions,\n  ): Promise<AppPermissionDefinition[]> => {\n    return this.agentsClient.listAppPermissionDefinitions(options);\n  };\n\n  ensureAgent = (\n    input: CreateAgentInput,\n    options?: RequestOptions,\n  ): Promise<EnsureAgentResponse> => {\n    return this.agentsClient.ensureAgent(input, options);\n  };\n\n  /**\n   * Provision a new project in your organization.\n   * Pre-creates a user account, project, and API key.\n   * Returns a claim URL and API key. Requires admin/owner role.\n   */\n  provisionProject = (\n    input?: ProvisionProjectInput,\n    options?: RequestOptions,\n  ): Promise<ProvisionProjectResponse> => {\n    return this.provisionClient.provisionProject(input, options);\n  };\n\n  /**\n   * Register a callback for manual approval requests.\n   * Starts background long-polling to the gateway. The callback is called\n   * once per pending approval request, concurrently for multiple requests.\n   * Returns a handle to stop polling when shutting down.\n   */\n  configureManualApproval = (\n    callback: ManualApprovalCallback,\n    options?: RequestOptions,\n  ): ManualApprovalHandle => {\n    this.approvalClient.start(callback, options).catch(() => {\n      // Errors handled internally with backoff\n    });\n    return { stop: () => this.approvalClient.stop() };\n  };\n}\n","// Typed bodies for the errors the OneCLI gateway returns on PROXIED agent\n// traffic (not the management REST API — those errors ride the\n// `{ error: { message, type } }` envelope instead).\n//\n// Agent requests reach providers through the gateway proxy transparently, so\n// these bodies arrive on ordinary fetch/HTTP responses inside agent code. All\n// of them carry `x-should-retry: false`: an unchanged retry will not succeed —\n// the fix is the named remediation (add the connection header, attach the\n// credential, open the URL).\n\n/** One connectable account, as listed in disambiguation responses and the\n * `x-onecli-connections` response header. */\nexport interface GatewayConnectionChoice {\n  id: string;\n  label: string | null;\n  provider: string;\n  display_name: string | null;\n}\n\n/** Request header naming which account a proxied request should use. */\nexport const CONNECTION_ID_HEADER = \"x-onecli-connection-id\";\n\n/** Response header advertising the available accounts (a JSON array of\n * {@link GatewayConnectionChoice}) on successfully forwarded responses. */\nexport const CONNECTIONS_HEADER = \"x-onecli-connections\";\n\n/**\n * 409 — two or more accounts of the SAME app could serve the request. Retry\n * the identical request with {@link CONNECTION_ID_HEADER} set to one of the\n * listed `connections[].id`.\n */\nexport interface MultipleConnectionsError {\n  error: \"multiple_connections\";\n  message: string;\n  connections: GatewayConnectionChoice[];\n  header: string;\n  example: string;\n}\n\n/** 409 — accounts of DIFFERENT apps both match the request. Same retry\n * protocol as {@link MultipleConnectionsError}. */\nexport interface MultipleProvidersError {\n  error: \"multiple_providers\";\n  message: string;\n  connections: GatewayConnectionChoice[];\n  header: string;\n  example: string;\n}\n\n/** 404 — the id sent in {@link CONNECTION_ID_HEADER} names no available\n * connection (stale or removed). Re-pick from `connections`. */\nexport interface ConnectionNotFoundError {\n  error: \"connection_not_found\";\n  message: string;\n  connections: GatewayConnectionChoice[];\n  header: string;\n}\n\n/**\n * 401/403 (the upstream status is preserved) — a credential for this host\n * exists in the project, but the agent has no grant for it. `manage_url`\n * opens the account's Agent access dialog.\n */\nexport interface AccessRestrictedError {\n  error: \"access_restricted\";\n  message: string;\n  provider: string;\n  manage_url: string;\n}\n\n/** 403 — a policy rule blocked the request. */\nexport interface BlockedByPolicyError {\n  error: \"blocked_by_policy\";\n  message: string;\n  rule_name: string;\n  method: string;\n  path: string;\n  dashboard_url: string;\n}\n\n/** 403 — nothing allowed the request under a deny-by-default posture. */\nexport interface BlockedByDefaultPolicyError {\n  error: \"blocked_by_default_policy\";\n  message: string;\n  method: string;\n  host: string;\n  path: string;\n  dashboard_url: string;\n}\n\n/** 401/403 (upstream status preserved) — no credential exists for the host at\n * all. `secret_url` is a pre-built create link. */\nexport interface CredentialNotFoundError {\n  error: \"credential_not_found\";\n  message: string;\n  hostname: string;\n  path: string;\n  secret_url: string;\n}\n\nexport type GatewayError =\n  | MultipleConnectionsError\n  | MultipleProvidersError\n  | ConnectionNotFoundError\n  | AccessRestrictedError\n  | BlockedByPolicyError\n  | BlockedByDefaultPolicyError\n  | CredentialNotFoundError;\n\nconst GATEWAY_ERROR_CODES = new Set<string>([\n  \"multiple_connections\",\n  \"multiple_providers\",\n  \"connection_not_found\",\n  \"access_restricted\",\n  \"blocked_by_policy\",\n  \"blocked_by_default_policy\",\n  \"credential_not_found\",\n]);\n\n/**\n * Narrow an already-parsed response body to a typed gateway error, or `null`\n * when the body is not one (an ordinary provider error, a management-API\n * envelope, a non-object).\n *\n * ```ts\n * const res = await fetch(\"https://gmail.googleapis.com/gmail/v1/users/me\");\n * if (!res.ok) {\n *   const err = parseGatewayError(await res.json().catch(() => null));\n *   if (err?.error === \"multiple_connections\") {\n *     // retry with { [CONNECTION_ID_HEADER]: err.connections[0].id }\n *   }\n * }\n * ```\n */\nexport const parseGatewayError = (body: unknown): GatewayError | null => {\n  if (typeof body !== \"object\" || body === null) return null;\n  const candidate = body as { error?: unknown };\n  if (\n    typeof candidate.error !== \"string\" ||\n    !GATEWAY_ERROR_CODES.has(candidate.error)\n  ) {\n    return null;\n  }\n  return body as GatewayError;\n};\n"],"mappings":";AAAO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EAEhB,YACE,SACA,aACA;AACA;AAAA,MACE,QAAQ,YAAY,GAAG,iBAAiB,YAAY,UAAU,KAAK,OAAO;AAAA,IAC5E;AACA,SAAK,OAAO;AACZ,SAAK,MAAM,YAAY;AACvB,SAAK,aAAa,YAAY;AAAA,EAChC;AACF;AAEO,SAAS,cAAc,OAAkD;AAC9E,MAAI,iBAAiB,eAAe,iBAAiB,oBAAoB;AACvE,WAAO;AAAA,EACT;AAEA,MAAI,iBAAiB,OAAO;AAC1B,WAAO,IAAI,YAAY,MAAM,OAAO;AAAA,EACtC;AAEA,SAAO,IAAI,YAAY,OAAO,KAAK,CAAC;AACtC;;;AClCA,SAAS,cAAc,qBAAqB;AAC5C,SAAS,cAAc;AACvB,SAAS,YAAY;AAGrB,IAAM,kBAAkB;AAAA,EACtB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAMO,SAAS,mBAAmB,eAA+B;AAChE,QAAM,UAAU,KAAK,OAAO,GAAG,qBAAqB;AACpD,gBAAc,SAAS,aAAa;AACpC,SAAO;AACT;AAMO,SAAS,sBAAsB,eAAsC;AAC1E,aAAW,WAAW,iBAAiB;AACrC,QAAI;AACF,YAAM,QAAQ,aAAa,SAAS,MAAM;AAC1C,YAAM,WAAW,MAAM,QAAQ,IAAI,OAAO,cAAc,QAAQ,IAAI;AACpE,YAAM,UAAU,KAAK,OAAO,GAAG,wBAAwB;AACvD,oBAAc,SAAS,QAAQ;A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