/** * API Client for CLI Commands * Issue #518: HTTP communication layer with auth, error handling * * [DR1-01] Responsibilities separated: * - resolveAuthToken(): Token resolution (--token > CM_AUTH_TOKEN) * - handleApiError(): Error classification and user-friendly messages * - ApiClient: HTTP get/post with base URL and auth headers */ export { ApiError, FOREIGN_SESSION_ERROR_CODE, foreignSessionMessage, handleApiError, } from './api-client-errors'; export type { ApiErrorContext, ApiErrorPayload, ApiErrorResult } from './api-client-errors'; export { DeadlineExceededError, isDeadlineExceeded, rethrowIfDeadlineExceeded, } from './api-client-deadline'; /** Maximum stop-pattern length [SEC4-06] */ export declare const MAX_STOP_PATTERN_LENGTH = 500; /** * Validate worktree ID format [SEC4-04] * @param id - Worktree ID to validate * @returns True if valid */ export declare function isValidWorktreeId(id: string): boolean; /** * Validate agent instance ID format (Issue #868). * @param id - Instance ID to validate * @returns True if valid */ export declare function isValidInstanceId(id: string): boolean; /** * Resolve authentication token from options or environment. * [SEC4-01] Warns on stderr when --token flag is used. * * @param options - Options object with optional token * @param warn - Where the warning goes (default: stderr). Issue #4436: a command * whose first stderr line is a contract (the `auto-yes` refusal) collects it * and prints it after that line. * @returns Resolved token or undefined */ export declare function resolveAuthToken(options?: { token?: string; }, warn?: (line: string) => void): string | undefined; /** What {@link ApiClient.post} does to a body before it goes (Issue #4437). */ export type PostBodyStamp = (path: string, body: unknown) => unknown; /** * Set what every {@link ApiClient.post} of this process does to its body first, or * null for nothing (Issue #4437). `send`, `ask` and `respond` set `send-origin.ts`'s * `withSendOrigin`, so every request that types into a session — the strict * respond's own client included — says who is sending. A hook rather than an import: * reading the origin runs tmux, and this module is reached from `lib/brief` and * `lib/handoff`, which the guards keep free of it. */ export declare function setPostBodyStamp(stamp: PostBodyStamp | null): void; /** * API Client for CLI HTTP communication. * Uses Node.js built-in fetch. Handles auth headers and error mapping. */ export declare class ApiClient { private baseUrl; private token?; /** Epoch ms after which every request of this client fails (Issue #3983). */ private deadlineAt?; /** * @param options.onWarning - Issue #4436: where the construction warnings * (`--token` exposure, a token over plain HTTP) go. Default: stderr, at once — * or, Issue #4437, held while `send` / `ask` / `respond` hold them * (`clientWarning`), so a tool-policy refusal is the first stderr line. */ constructor(options?: { baseUrl?: string; token?: string; onWarning?: (line: string) => void; }); /** * The base URL this client actually dials (Issue #2404). * * Resolved once in the constructor: the `baseUrl` option when a caller passes * one (there is no CLI flag for it), else `CM_PORT` / `CM_BIND` through the * precedence in `loadClientEnv()` (exported > `~/.commandmate/.env` > 3000; * under `CM_UAT_ISOLATION=1` exported only, never 3000), which is why it is * read from here rather than re-derived by each * caller: a second derivation is a second answer, and "which server did this * command talk to" only helps if it is the one the request went to. */ get serverUrl(): string; /** * This client with every request bounded by `deadlineAt` (Issue #3983). * * `wait` / `ask` / `verify` take `--timeout` as the deadline of the whole * command, but only the poll's own reads were bounded by it: a task-ledger * read, an `--instance` resolution or a capability probe before the poll had * no deadline at all, so a server that stopped answering held the command for * as long as undici's own timeouts (minutes) and then, swallowed into a * degraded path, kept it going. The derived client carries one deadline for * every method (`get` / `post` / `patch` / `rawGet`), and a request it ends * fails with {@link DeadlineExceededError} — exit 124 — which the * degrade-on-failure catches rethrow ({@link isDeadlineExceeded}). * * One request lasts until its body has been read (`json()` / `text()`), the * body of a {@link rawGet} response included: a server that sends headers and * then stalls the body is not an answer. * * @param deadlineAt - Epoch ms; undefined returns this client unchanged * @returns A client sharing this one's server and token */ withDeadline(deadlineAt: number | undefined): ApiClient; /** The deadline this client carries, if any (Issue #3983). */ get deadline(): number | undefined; /** * The bound of one request: a signal that fires at the deadline (combined * with the caller's own, when it gave one), or null without a deadline. */ private startDeadline; private getHeaders; /** * GET without any status handling, for callers that must read the raw response. * * Issue #1925: the server-capability probe has to tell a real 404 (an older * daemon that predates the endpoint) from a 302 to /login (this request never * authenticated) and from an HTML body served by something in the middle. * {@link get} collapses all three into an exception with a message, which is * exactly the distinction the probe exists to make — so it issues its own * request, with `redirect: 'manual'` so a redirect stays visible instead of * being followed to a 200 that parses as nothing. * * @param path - Path appended to the client's base URL * @param init - Extra request headers merged over the client's own * @returns The raw Response, whatever its status */ rawGet(path: string, init?: { headers?: Record; }): Promise; /** * HTTP GET request * [DR1-05] Generic type parameter specified at call site * * Issue #3956: `init.signal` bounds the request; an aborted one throws an * `ApiError` like any other network failure, so a caller that set a deadline * reads `signal.aborted` to tell the two apart. Omitted, the request is as * before (no `signal` key on the fetch init). */ get(path: string, init?: { signal?: AbortSignal; }): Promise; /** * HTTP POST request * [DR1-05] Generic type parameter specified at call site * * Issue #4437: the body goes through the stamp the command set * ({@link setPostBodyStamp}): `send` / `ask` / `respond` put who is sending on * every request that types into a session, the strict respond's included. */ post(path: string, body?: unknown): Promise; /** * HTTP PATCH request (Issue #1000: agent-instance roster mutations via * PATCH /api/worktrees/[id]). * [DR1-05] Generic type parameter specified at call site */ patch(path: string, body?: unknown): Promise; /** * HTTP PUT request (Issue #4116: the role settings routes). * * @param headers - Added to this request: a condition, not part of the body (Issue #4132) */ put(path: string, body?: unknown, headers?: Record): Promise; /** HTTP DELETE request (Issue #4116: `roles rm`). */ delete(path: string): Promise; } /** * Assert that a parsed API response contains the given required top-level fields * (Issue #1357). * * get/post/patch cast the parsed body with `as T` and perform no runtime * validation, so a response from a stale daemon that omits a field silently * degrades to `undefined` downstream (e.g. a missing roster read as an empty * roster). Route responses whose fields you depend on through this guard so a * missing field surfaces as an actionable version-skew error instead of a silent * wrong value. * * @param value - Parsed response body * @param fields - Required top-level field names * @param context - Short endpoint/response label included in the error message * @returns value, typed as T, when it is an object and every required field is present * @throws ApiError when value is not an object or a required field is absent */ export declare function assertResponseShape(value: unknown, fields: ReadonlyArray, context: string): T; /** * Read the version the running daemon reports via GET /api/app/update-check. * Issue #1359 made that field a runtime package.json read, so it reflects the * daemon's actual running code rather than a build-time constant. * * Returns undefined when the endpoint is unreachable or omits currentVersion (an * older daemon predating the field) — callers treat that as "unknown", never as * an error. Never throws. */ export declare function fetchDaemonVersion(client: ApiClient): Promise; /** * Compare this CLI's version against the running daemon's and print a stderr * warning when they differ (Issue #1357). Advisory only: never throws, and stays * silent when either version is unknown. Intended to run once per CLI invocation * that connects to the server, so a stale daemon serving an older API is called * out before its responses are misread. */ export declare function warnIfVersionSkew(client: ApiClient): Promise; //# sourceMappingURL=api-client.d.ts.map