@lovable.dev/sdk 1.4.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -265,10 +265,10 @@ var LovableClient = class {
265
265
  if (options.uploadedFiles?.length) ({fileRefs, ephemeralFileRefs} = this.partitionUploadedFiles(options.uploadedFiles));
266
266
  else if (options.files?.length) fileRefs = await this.uploadProjectFiles(projectId, options.files);
267
267
  const body = { message: options.message };
268
- if (options.variantId) body.variant_id = options.variantId;
269
268
  if (fileRefs) body.files = fileRefs;
270
269
  if (ephemeralFileRefs) body.ephemeral_files = ephemeralFileRefs;
271
270
  if (options.planMode) body.plan_mode = true;
271
+ if (options.maxMode) body.max_mode = true;
272
272
  if (options.continuation) body.continuation = options.continuation;
273
273
  const { data } = await this.typed.POST("/v1/messages", { body: {
274
274
  ...body,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sleep","parseRetryAfterMs"],"sources":["../src/retryFetch.ts","../src/types.ts","../src/client.ts"],"sourcesContent":["const RETRY_DELAYS_MS = [100, 300, 500] as const;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction parseRetryAfterMs(headers: Headers): number | undefined {\n const raw = headers.get(\"retry-after\");\n if (!raw) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) {\n const delta = dateMs - Date.now();\n return delta > 0 ? delta : 0;\n }\n return undefined;\n}\n\nexport type RetryFetch = (input: Request) => Promise<Response>;\n\n/**\n * Wraps a fetch implementation with retry on HTTP 429. Up to three retries\n * at 100ms / 300ms / 500ms; if the server sends `Retry-After` and it's\n * larger than the planned delay, we honor the server value. The Request is\n * cloned before each attempt so its body remains replayable.\n *\n * Matches openapi-fetch's `fetch` option signature: a single `Request` in,\n * `Promise<Response>` out.\n */\nexport function makeRetryFetch(baseFetch: RetryFetch = (input) => globalThis.fetch(input)): RetryFetch {\n return async (input) => {\n // Request.clone() and the fetch parameter resolve to different Request type\n // definitions when @types/node (undici) and @types/bun are both in scope;\n // the cloned object is structurally the same Request, so assert the param type.\n const clone = (): Parameters<RetryFetch>[0] => input.clone() as Parameters<RetryFetch>[0];\n let response = await baseFetch(clone());\n for (const planned of RETRY_DELAYS_MS) {\n if (response.status !== 429) break;\n const serverDelay = parseRetryAfterMs(response.headers);\n await sleep(Math.max(planned, serverDelay ?? 0));\n response = await baseFetch(clone());\n }\n return response;\n };\n}\n","// Type definitions for the Lovable SDK.\n//\n// Response and request body types come straight from the generated OpenAPI\n// types (`./generated/paths.ts`, produced by `openapi-typescript` from the\n// trimmed v1 spec). The same trimmed spec also drives `./generated/zod/`\n// (consumed by `@lovable.dev/sdk/schemas` for runtime validation), so the\n// type aliases here are guaranteed to match the schemas the MCP server\n// uses — there is no hand-maintained parallel shape to drift.\n//\n// Types that don't have a 1:1 OpenAPI counterpart (request options, SDK\n// wrappers like `MessageCompletionResult` that re-shape responses, helper\n// interfaces like `FileInput`) stay hand-written below.\n\nimport type { components, paths } from \"./generated/paths.js\";\n\ntype Schemas = components[\"schemas\"];\n\ntype ListProjectsQuery = NonNullable<paths[\"/v1/projects\"][\"get\"][\"parameters\"][\"query\"]>;\ntype ListConnectorsQuery = NonNullable<paths[\"/v1/connectors\"][\"get\"][\"parameters\"][\"query\"]>;\n\n// =============================================================================\n// API types — derived from the OpenAPI spec\n// =============================================================================\n\n// --- Users & workspaces ---\n\nexport type MeWorkspace = Schemas[\"GetMeWorkspace\"];\nexport type MeResponse = Schemas[\"GetMeOutputBody\"];\nexport type WorkspaceMembership = Schemas[\"PublicV1WorkspaceMember\"];\nexport type WorkspaceWithMembership = Schemas[\"PublicV1WorkspaceWithMembership\"];\nexport type GetWorkspacesResponse = Schemas[\"V1ListWorkspacesBody\"] & {\n workspaces: WorkspaceWithMembership[];\n};\n\n// Role enum lives on WorkspaceMembership in the spec; reuse it so SDK callers\n// always pick from the same set the server returns.\nexport type MemberRole = WorkspaceMembership[\"role\"];\n\n// --- Projects ---\n\n// Lean shape returned by GET /v1/projects/{id} and POST /v1/projects.\nexport type ProjectResponse = Schemas[\"V1ProjectResponse\"];\nexport type CreateProjectResponse = Schemas[\"PublicV1CreateProjectResponse\"] & { id: string };\nexport type CreateProjectBody = Omit<Schemas[\"PublicV1ProjectCreateInputBody\"], \"workspace_id\">;\nexport type UpdateProjectOptions = Schemas[\"PublicV1PatchProjectBody\"];\nexport type EmbedURLResponse = Schemas[\"V1CreateEmbedURLOutputBody\"];\n\n// Wider listing shape returned by the projects list endpoint.\nexport type ListProjectItem = Schemas[\"PublicV1ProjectListItem\"];\nexport type ListProjectsResponse = Schemas[\"CursorListResponsePublicV1ProjectListItem\"] & {\n projects: ListProjectItem[] | null;\n total?: number;\n has_more?: boolean;\n};\nexport type GetWorkspaceProjectsResponse = ListProjectsResponse;\nexport type MoveProjectsToFolderResponse = Schemas[\"AddProjectsToFolderResult\"];\n\n// Compatibility export; curated response fields accept future string values.\nexport type ProjectVisibility = \"public\" | \"private\" | \"draft\" | \"workspace_view\";\nexport type ProjectPatchVisibility = NonNullable<UpdateProjectOptions[\"visibility\"]>;\n\n// --- Messages ---\n\nexport type SendMessageResponse = Schemas[\"V1SendMessageOutputBody\"];\nexport type GetMessageResponse = Schemas[\"V1MessageResponse\"];\nexport type MessageSummary = Schemas[\"V1MessageListItem\"];\ntype AwaitingInputSummary = Partial<Schemas[\"V1AwaitingInputSummary\"]>;\nexport type ListMessagesResponse = Schemas[\"CursorListResponseV1MessageListItem\"] & {\n messages: MessageSummary[] | null;\n has_more: boolean;\n};\nexport interface ListMessagesOptions {\n limit?: number;\n cursor?: string;\n /** @deprecated Use `cursor` from `pagination.next_cursor`; kept for source compatibility. */\n before?: string;\n}\n\nexport interface ChatResponse {\n content: string;\n previewUrl: string;\n messageId: string;\n}\n\nexport interface ChatResponseOptions {\n timeout?: number;\n}\n\nexport type CreateVariantResponse = Schemas[\"V1CreateVariantOutputBody\"];\n\n// --- Deployment ---\n\nexport type DeploymentResponse = Schemas[\"V1DeployProjectOutputBody\"];\n\n// --- Database ---\n\nexport type DatabaseStatus = Schemas[\"V1GetDatabaseStatusOutputBody\"];\nexport type EnableDatabaseResult = Schemas[\"V1EnableDatabaseOutputBody\"];\n// POST /v1/database/query is served but sits outside the public OpenAPI\n// boundary, so no generated type exists; hand-maintained for queryDatabase\n// and the MCP query_database tool.\nexport type DatabaseQueryResult = {\n rows: Record<string, unknown>[] | null;\n};\n\n// --- Knowledge ---\n\nexport type KnowledgeResponse = Schemas[\"V1KnowledgeResponse\"];\n\n// --- Skills ---\n\nexport type WorkspaceSkillFile = Schemas[\"ProjectFileInfo\"];\nexport type WorkspaceSkill = Schemas[\"V1WorkspaceSkillDTO\"];\nexport type ListWorkspaceSkillsResponse = Schemas[\"V1ListWorkspaceSkillsOutputBody\"];\nexport type WorkspaceSkillResponse = Schemas[\"V1GetWorkspaceSkillOutputBody\"];\nexport type WorkspaceSkillWriteResponse = Schemas[\"V1WriteWorkspaceSkillOutputBody\"];\nexport type WorkspaceSkillDeleteResponse = Schemas[\"V1DeleteWorkspaceSkillOutputBody\"];\n\nexport type ProjectSkill = Schemas[\"V1ProjectSkillDTO\"];\nexport type ListProjectSkillsResponse = Schemas[\"CursorListResponseV1ProjectSkillDTO\"] & {\n skills: ProjectSkill[];\n};\nexport type ProjectSkillResponse = Schemas[\"V1SetProjectSkillEnabledOutputBody\"];\n\n// --- File upload ---\n\nexport type FileUploadUrlResponse = Schemas[\"V1FileUploadURLOutputBody\"];\nexport type UnscopedFile = Schemas[\"V1UnscopedFile\"];\n\n// --- Git / diffs / files / edits ---\n\nexport type DiffLine = Schemas[\"DiffLine\"];\nexport type DiffHunk = Schemas[\"DiffHunk\"];\nexport type DiffEntry = Schemas[\"V1DiffEntry\"];\nexport type GitDiffResponse = Schemas[\"V1DiffResponse\"];\nexport type GitFileEntry = Schemas[\"GitFileEntryLite\"];\nexport type GitFilesResponse = Schemas[\"PublicV1GitFilesResponse\"] & { files: GitFileEntry[] };\nexport type EditSummary = Schemas[\"V1EditSummary\"];\nexport type EditsResponse = Schemas[\"PublicV1GetEditsOutputBody\"];\n\n// --- Libraries & templates ---\n\nexport type LibraryProjectResponse = Record<string, unknown>;\nexport type TemplateProjectResponse = Record<string, unknown>;\nexport type ListLibraryProjectsResponse = {\n libraries: LibraryProjectResponse[];\n total?: number;\n has_more?: boolean;\n};\nexport type ListTemplateProjectsResponse = {\n templates: TemplateProjectResponse[];\n total?: number;\n has_more?: boolean;\n};\n\n// --- Connectors ---\n\nexport type ConnectorItem = Schemas[\"PublicV1ConnectorItem\"];\nexport type StandardConnectorItem = ConnectorItem;\nexport type SeamlessConnectorItem = ConnectorItem;\nexport type MCPConnectorItem = ConnectorItem;\nexport type ListConnectorsResponse = Omit<Schemas[\"CursorListResponsePublicV1ConnectorItem\"], \"data\"> & {\n data: ConnectorItem[];\n connectors: ConnectorItem[];\n has_more: boolean;\n};\nexport type ListStandardConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> & {\n connectors: StandardConnectorItem[];\n};\nexport type ListSeamlessConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> & {\n connectors: SeamlessConnectorItem[];\n};\nexport type ListMCPConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> &\n Partial<Omit<Schemas[\"V1ListMCPConnectorsResponse\"], \"connectors\">> & {\n data: MCPConnectorItem[];\n connectors: MCPConnectorItem[];\n };\n\n// --- Analytics ---\n\nexport type TimeSeriesDataPoint = Schemas[\"TimeSeriesDataPoint\"];\nexport type TimeSeriesData = Schemas[\"TimeSeriesData\"];\nexport type ListDataPoint = Schemas[\"ListDataPoint\"];\nexport type ListData = Schemas[\"ListData\"];\nexport type ProjectAnalyticsResponse = Schemas[\"ProjectAnalyticsResponse\"];\nexport type TrendDataPoint = Schemas[\"TrendDataPoint\"];\nexport type ProjectAnalyticsTrendResponse = Schemas[\"ProjectTrendResponse\"];\n\n// --- Remix ---\n\nexport type RemixJobStepInfo = Schemas[\"RemixJobStepInfo\"];\nexport type RemixInitResponse = { job_id: string };\nexport type RemixProgressResult = Schemas[\"V1RemixProgressResult\"];\nexport type RemixProgressResponse = {\n status: string;\n step?: RemixJobStepInfo;\n result?: RemixProgressResult;\n error_message?: string;\n error_code?: string;\n};\n\n// The V1 spec types `status` as plain string. The Go handler returns one of\n// these five values — keep the narrow union here as an SDK-side aid for\n// callers that switch on it. If the spec ever exposes this as an enum,\n// replace with `Schemas[\"V1RemixProgressOutputBody\"][\"status\"]`.\nexport type RemixJobStatus = \"unknown\" | \"preparing\" | \"running\" | \"completed\" | \"error\";\nexport type RemixJobStep =\n | \"starting\"\n | \"creating_new_project\"\n | \"restoring_supabase\"\n | \"copying_history\"\n | \"preparing_repository\"\n | \"remixing_integration\"\n | \"pushing_repository\"\n | \"finalizing\"\n | \"completed\";\n\n// V1 status field on V1ProjectResponse is plain string; the Go handler returns\n// one of these three. Same rationale as RemixJobStatus.\nexport type ProjectStatus = \"completed\" | \"in_progress\" | \"failed\";\n\n// =============================================================================\n// SDK helpers — no OpenAPI counterpart\n// =============================================================================\n\nexport interface ChatRequest {\n id: string;\n message: string;\n chat_only: boolean;\n headless: boolean;\n ai_message_id?: string;\n intent?: string;\n model?: string;\n temperature?: number;\n current_page?: string;\n view?: string;\n view_description?: string;\n prev_session_id?: string;\n is_creation?: boolean;\n files?: UnscopedFile[];\n}\n\n/** @deprecated `remixProject()` now uses POST /v1/projects with `source_project_id`. */\nexport interface RemixInitBody extends Omit<Schemas[\"V1RemixInitInputBody\"], \"initial_message\"> {\n initial_message?: ChatRequest;\n message_id?: string;\n remix_mode?: RemixMode;\n skip_integrations?: boolean;\n}\n\nexport type RemixCreateProjectBody = Schemas[\"PublicV1ProjectRemixInputBody\"];\n\nexport interface FileInput {\n name: string;\n data: Blob | ArrayBuffer | Uint8Array;\n type: string;\n}\n\nexport interface CreateProjectOptions {\n description: string;\n projectName?: string;\n techStack?: string;\n /** Sandbox runtime template. Requires a workspace with access to the requested template. */\n sandboxTemplate?: string;\n visibility?: ProjectVisibility;\n templateProjectId?: string;\n initialMessage?: string;\n /** Files to upload and attach to the initial message. The SDK handles uploading. */\n files?: (File | FileInput)[];\n /** Pre-uploaded file references to attach to the initial message. Skips upload. */\n uploadedFiles?: UnscopedFile[];\n /** Public image or HTML file URLs to fetch server-side and attach to the initial message. */\n fileUrls?: string[];\n /** Design system library projects to connect to the new project. */\n selectedLibraries?: { project_id: string }[];\n}\n\n/**\n * Controls prompt cache continuation behavior for a message.\n *\n * - `\"force\"` — skip cache TTL and token/criteria checks (force continuation)\n * - `\"fresh_build\"` — force a full prompt rebuild from scratch\n * - `\"allow_expired_cache\"` — skip cache TTL check but respect token/criteria limits\n *\n * Omit for default behavior (5-min TTL, token and criteria checks apply).\n */\nexport type ContinuationOverride = \"force\" | \"fresh_build\" | \"allow_expired_cache\";\n\nexport interface ChatMessageOptions {\n message: string;\n /** Send the message to this project variant instead of the main agent. */\n variantId?: string;\n /** Files to upload and attach. The SDK handles uploading them first. */\n files?: (File | FileInput)[];\n /** Pre-uploaded file references. Skips upload. */\n uploadedFiles?: UnscopedFile[];\n /** Enable plan mode: the agent discusses and plans without editing code. */\n planMode?: boolean;\n /**\n * Override continuation behavior for this message.\n * Controls whether the agent reuses the prompt cache or rebuilds from scratch.\n */\n continuation?: ContinuationOverride;\n}\n\nexport interface CreateVariantOptions {\n /** Display name. The API assigns the next Draft number when omitted. */\n label?: string;\n /** Full 40-character commit SHA to base the variant branch on. Defaults to the project main branch. */\n baseSha?: string;\n}\n\nexport interface LovableClientOptions {\n /** API key for authentication (mutually exclusive with bearerToken) */\n apiKey?: string;\n /** Bearer token for OAuth authentication (mutually exclusive with apiKey) */\n bearerToken?: string;\n baseUrl?: string;\n /** Additional headers to include on every request */\n headers?: Record<string, string>;\n /**\n * Identifier for the originating client, sent as the `X-Client-Source` header.\n * Used by the API to tag audit logs and observability with the message origin.\n * Defaults to `\"sdk\"`. The Go API allowlist accepts `\"mcp\"`, `\"sdk\"`, `\"cli\"`.\n */\n clientSource?: string;\n}\n\nexport interface LovableError extends Error {\n status: number;\n type?: string;\n detail?: string;\n}\n\nexport interface WaitOptions {\n pollInterval?: number;\n timeout?: number;\n onProgress?: (project: ProjectResponse) => void;\n}\n\nexport interface ListCursorPaginationOptions {\n limit?: number;\n cursor?: string;\n}\n\nexport interface ListOffsetPaginationOptions {\n limit?: number;\n offset?: number;\n}\n\nexport interface ListHybridPaginationOptions {\n limit?: number;\n cursor?: string;\n offset?: number;\n}\n\nexport type ListConnectorsOptions = Omit<ListConnectorsQuery, \"workspace_id\">;\n\n/** @deprecated Use the cursor, offset, or hybrid pagination option type that matches the route. */\nexport type ListPaginationOptions = ListHybridPaginationOptions;\n\nexport type CursorPaginationOptions = ListCursorPaginationOptions;\n\nexport type RemixMode = \"before\" | \"including\";\n\nexport interface RemixProjectOptions {\n workspaceId: string;\n messageId?: string;\n remixMode?: RemixMode;\n includeHistory?: boolean;\n includeCustomKnowledge?: boolean;\n initialMessage?: string;\n description?: string;\n projectName?: string;\n skipInitialRemixMessage?: boolean;\n skipIntegrations?: boolean;\n}\n\n// camelCase wrapper — not a direct alias of V1RemixProgressResult.\nexport interface RemixResult {\n projectId: string;\n}\n\nexport interface RemixWaitOptions {\n pollInterval?: number;\n timeout?: number;\n onProgress?: (status: RemixJobStatus, step?: RemixJobStepInfo) => void;\n}\n\nexport interface MessageCompletionResult {\n status: \"completed\" | \"stopped\" | \"awaiting_input\" | \"timeout\" | \"error\";\n message_id: string;\n content: string;\n awaiting_input?: AwaitingInputSummary;\n edit_id?: string;\n commit_sha?: string;\n summary?: string;\n cost_credits?: number;\n error?: string;\n}\n\nexport interface MessageCompletionOptions {\n /** Trajectory thread returned by chat(). Enables thread-aware completion. */\n threadId?: string;\n /**\n * Maximum seconds the server holds each long-poll request before returning\n * a non-terminal snapshot. Clamped server-side to [0, 55]. Defaults to 30.\n */\n waitSeconds?: number;\n /** Maximum total time to wait in ms (default: 600000 = 10 minutes) */\n timeout?: number;\n /**\n * @deprecated Long-poll replaces client-side polling; this is ignored.\n * Kept for source-compat with callers that still pass it.\n */\n pollInterval?: number;\n}\n\nexport interface GetMessageOptions {\n /** Trajectory thread returned by chat(). Enables thread-aware status reads. */\n threadId?: string;\n /**\n * Long-poll: ask the server to hold the request until the message reaches a\n * terminal state or this many seconds elapse. Clamped server-side to [0, 55].\n */\n waitSeconds?: number;\n}\n\nexport interface ListProjectsOptions {\n /** Full-text search; mapped to `q` on the wire. */\n query?: string;\n visibility?: ListProjectsQuery[\"visibility\"];\n publish_status?: ListProjectsQuery[\"publish_status\"];\n folder_id?: ListProjectsQuery[\"folder_id\"];\n folder_ids?: ListProjectsQuery[\"folder_ids\"];\n user_id?: ListProjectsQuery[\"user_id\"];\n type?: ListProjectsQuery[\"type\"];\n search_fields?: ListProjectsQuery[\"search_fields\"];\n viewed_by_me?: ListProjectsQuery[\"viewed_by_me\"];\n cursor?: ListProjectsQuery[\"cursor\"];\n limit?: ListProjectsQuery[\"limit\"];\n}\n\n// =============================================================================\n// Runtime exports\n// =============================================================================\n\nexport interface RateLimitInfo {\n /** X-RateLimit-Limit: the request budget for the current window. */\n limit?: number;\n /** X-RateLimit-Remaining: requests left in the current window. */\n remaining?: number;\n /** Retry-After in milliseconds (parsed from the Retry-After header). */\n retryAfterMs?: number;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly type?: string;\n readonly detail?: string;\n readonly props?: Record<string, unknown>;\n readonly rateLimit?: RateLimitInfo;\n\n constructor(\n status: number,\n message: string,\n type?: string,\n detail?: string,\n props?: Record<string, unknown>,\n rateLimit?: RateLimitInfo,\n ) {\n super(message);\n this.status = status;\n this.type = type;\n this.detail = detail;\n this.props = props;\n this.rateLimit = rateLimit;\n }\n}\n","import type { Client, Middleware } from \"openapi-fetch\";\n\nimport createClient from \"openapi-fetch\";\n\nimport type { components, paths } from \"./generated/paths.js\";\n\ntype Schemas = components[\"schemas\"];\ntype CreateProjectPostBody = paths[\"/v1/projects\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n// POST /v1/database/query is served but sits outside the public OpenAPI\n// boundary, so the generated paths omit it; this mirrors the openapi-typescript\n// operation shape for queryDatabase.\ntype DatabaseQueryCompatPaths = {\n \"/v1/database/query\": {\n parameters: { query?: never; header?: never; path?: never; cookie?: never };\n get?: never;\n put?: never;\n post: {\n parameters: { query?: never; header?: never; path?: never; cookie?: never };\n requestBody: {\n content: { \"application/json\": { project_id: string; sql: string } };\n };\n responses: {\n 200: {\n headers: { [name: string]: unknown };\n content: { \"application/json\": DatabaseQueryResult };\n };\n default: {\n headers: { [name: string]: unknown };\n content: { \"application/problem+json\": Record<string, unknown> };\n };\n };\n };\n delete?: never;\n options?: never;\n head?: never;\n patch?: never;\n trace?: never;\n };\n};\nimport type {\n LovableClientOptions,\n CreateProjectOptions,\n ChatMessageOptions,\n CreateVariantOptions,\n WaitOptions,\n ProjectResponse,\n CreateProjectResponse,\n CreateProjectBody,\n UpdateProjectOptions,\n EmbedURLResponse,\n ProjectPatchVisibility,\n DeploymentResponse,\n UnscopedFile,\n FileInput,\n RemixProjectOptions,\n RemixCreateProjectBody,\n RemixJobStatus,\n RemixResult,\n RemixWaitOptions,\n MeResponse,\n MeWorkspace,\n GetWorkspacesResponse,\n WorkspaceWithMembership,\n DatabaseStatus,\n EnableDatabaseResult,\n DatabaseQueryResult,\n SendMessageResponse,\n GetMessageResponse,\n ListMessagesResponse,\n ListMessagesOptions,\n ChatResponse,\n ChatResponseOptions,\n CreateVariantResponse,\n MessageCompletionResult,\n MessageCompletionOptions,\n GetMessageOptions,\n KnowledgeResponse,\n FileUploadUrlResponse,\n GitDiffResponse,\n GitFilesResponse,\n EditsResponse,\n ListProjectsResponse,\n ListProjectsOptions,\n ListConnectorsOptions,\n ListCursorPaginationOptions,\n ListHybridPaginationOptions,\n ListOffsetPaginationOptions,\n CursorPaginationOptions,\n MoveProjectsToFolderResponse,\n ListConnectorsResponse,\n ListStandardConnectorsResponse,\n ListSeamlessConnectorsResponse,\n ListMCPConnectorsResponse,\n ProjectAnalyticsResponse,\n ProjectAnalyticsTrendResponse,\n ListLibraryProjectsResponse,\n ListTemplateProjectsResponse,\n ListWorkspaceSkillsResponse,\n WorkspaceSkillResponse,\n WorkspaceSkillWriteResponse,\n WorkspaceSkillDeleteResponse,\n ListProjectSkillsResponse,\n ProjectSkillResponse,\n RateLimitInfo,\n} from \"./types.js\";\n\nimport { makeRetryFetch } from \"./retryFetch.js\";\nimport { ApiError } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.lovable.dev\";\nconst PUBLIC_API_CURSOR_VERSION = 1;\n\nfunction normalizeBaseUrl(url: string | undefined): string {\n if (!url) return DEFAULT_BASE_URL;\n\n const normalized = url.replace(/\\/$/, \"\");\n\n if (!normalized.startsWith(\"http://\") && !normalized.startsWith(\"https://\")) {\n throw new Error(`baseUrl must include a protocol (http:// or https://). Got: \"${url}\"`);\n }\n\n return normalized;\n}\n\nfunction encodePublicCursor(id: string): string {\n const raw = JSON.stringify({ v: PUBLIC_API_CURSOR_VERSION, id });\n const bytes = new TextEncoder().encode(raw);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction normalizeWorkspaceList<T>(body: { data?: T[] | null; workspaces?: T[] | null }): T[] {\n return body.data ?? body.workspaces ?? [];\n}\n\nfunction cursorHasMore(body: { pagination?: { has_more?: boolean } | null; has_more?: boolean }): boolean {\n return body.pagination?.has_more ?? body.has_more ?? false;\n}\n\nfunction requireCreateProjectId<T extends { id?: string }>(project: T): T & { id: string } {\n if (!project.id) throw new Error(\"Create project response missing project ID\");\n return project as T & { id: string };\n}\n\n/**\n * openapi-fetch middleware that converts non-2xx Response objects into the\n * SDK's ApiError, preserving the existing error contract (status/type/detail/\n * props) used by every other method in this client.\n */\nconst errorMiddleware: Middleware = {\n async onResponse({ response }) {\n if (response.ok) return;\n let errorBody:\n | {\n type?: string;\n title?: string;\n message?: string;\n detail?: string;\n details?: string;\n props?: Record<string, unknown>;\n }\n | undefined;\n try {\n errorBody = (await response.clone().json()) as typeof errorBody;\n } catch {\n // Ignore JSON parse errors\n }\n const message = buildErrorMessage(errorBody, response.status, response.statusText);\n const type = errorBody?.type ?? errorBody?.title;\n const detail = errorBody?.detail ?? errorBody?.details;\n throw new ApiError(response.status, message, type, detail, errorBody?.props, parseRateLimitInfo(response.headers));\n },\n};\n\nfunction parseRateLimitInfo(headers: Headers): RateLimitInfo | undefined {\n const limit = parsePositiveInt(headers.get(\"x-ratelimit-limit\"));\n const remaining = parsePositiveInt(headers.get(\"x-ratelimit-remaining\"));\n const retryAfterMs = parseRetryAfterMs(headers.get(\"retry-after\"));\n if (limit == null && remaining == null && retryAfterMs == null) return undefined;\n return { limit, remaining, retryAfterMs };\n}\n\nfunction parsePositiveInt(raw: string | null): number | undefined {\n if (raw == null) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\nfunction parseRetryAfterMs(raw: string | null): number | undefined {\n if (!raw) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) {\n const delta = dateMs - Date.now();\n return delta > 0 ? delta : 0;\n }\n return undefined;\n}\n\n// HTTP/2 leaves response.statusText empty, and some Go API endpoints return\n// `{message: \"\"}` / `{title: \"\"}` bodies on errors. `??` would preserve the\n// empty string and produce an ApiError with no usable message; consumers\n// downstream (MCP, logs, UI) then render an unlabeled failure.\nfunction buildErrorMessage(\n body: { message?: string; title?: string } | undefined,\n status: number,\n statusText: string,\n): string {\n return body?.message || body?.title || (statusText ? `HTTP ${status}: ${statusText}` : `HTTP ${status}`);\n}\n\nexport class LovableClient {\n private readonly authHeaders: Record<string, string>;\n private readonly baseUrl: string;\n private readonly extraHeaders: Record<string, string>;\n private readonly clientSource: string;\n private readonly typedClient: Client<paths>;\n\n constructor(options: LovableClientOptions) {\n const hasApiKey = !!options.apiKey;\n const hasBearerToken = !!options.bearerToken;\n\n if (!hasApiKey && !hasBearerToken) {\n throw new Error(\"Either apiKey or bearerToken is required\");\n }\n if (hasApiKey && hasBearerToken) {\n throw new Error(\"Provide either apiKey or bearerToken, not both\");\n }\n\n this.authHeaders = hasApiKey\n ? { \"Lovable-API-Key\": options.apiKey! }\n : { Authorization: `Bearer ${options.bearerToken}` };\n\n this.baseUrl = normalizeBaseUrl(options.baseUrl);\n this.extraHeaders = options.headers ?? {};\n this.clientSource = options.clientSource ?? \"sdk\";\n\n this.typedClient = createClient<paths>({\n baseUrl: this.baseUrl,\n headers: {\n \"X-Client-Source\": this.clientSource,\n ...this.authHeaders,\n ...this.extraHeaders,\n Accept: \"application/json\",\n },\n fetch: makeRetryFetch(),\n });\n this.typedClient.use(errorMiddleware);\n }\n\n /**\n * Type-safe access to any documented API route, driven by the auto-generated\n * OpenAPI schema. Path / query params and request bodies are checked at compile\n * time; calling an unknown path is a type error.\n *\n * Non-2xx responses throw `ApiError`; on success, `data` is set on the result.\n */\n get typed(): Client<paths> {\n return this.typedClient;\n }\n\n /**\n * Get the current authenticated user and their workspaces.\n * Useful for validating an API key and discovering workspace IDs.\n */\n async me(): Promise<MeResponse> {\n const { data } = await this.typed.GET(\"/v1/me\");\n return {\n ...data!,\n workspaces: normalizeWorkspaceList<MeWorkspace>(\n data! as { data?: MeWorkspace[] | null; workspaces?: MeWorkspace[] | null },\n ),\n };\n }\n\n /**\n * List workspaces the authenticated user has access to.\n */\n async listWorkspaces(options: ListHybridPaginationOptions = {}): Promise<GetWorkspacesResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces\", {\n params: { query: options },\n });\n return { ...data!, workspaces: normalizeWorkspaceList<WorkspaceWithMembership>(data!) };\n }\n\n /**\n * Get a specific workspace by ID\n */\n async getWorkspace(workspaceId: string) {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}\", {\n params: { path: { workspace_id: workspaceId } },\n });\n return data!.workspace;\n }\n\n /**\n * List projects in a workspace.\n * Supports full-text search, filtering by visibility/publish status/folder/creator,\n * and cursor pagination.\n */\n async listProjects(workspaceId: string, options?: ListProjectsOptions): Promise<ListProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/projects\", {\n params: {\n query: {\n workspace_id: workspaceId,\n q: options?.query,\n visibility: options?.visibility,\n publish_status: options?.publish_status,\n folder_id: options?.folder_id,\n folder_ids: options?.folder_ids,\n user_id: options?.user_id,\n type: options?.type,\n search_fields: options?.search_fields,\n viewed_by_me: options?.viewed_by_me,\n cursor: options?.cursor,\n limit: options?.limit,\n },\n },\n });\n const projects =\n (data as unknown as { projects?: ListProjectsResponse[\"projects\"] }).projects ?? data!.data ?? null;\n const total = (data as unknown as { total?: number }).total;\n return {\n ...data!,\n projects,\n ...(total === undefined ? {} : { total }),\n has_more: data!.pagination?.has_more ?? (data as unknown as { has_more?: boolean }).has_more,\n };\n }\n\n /**\n * Create a new project in a workspace\n */\n async createProject(workspaceId: string, options: CreateProjectOptions): Promise<CreateProjectResponse> {\n let fileRefs: UnscopedFile[] | undefined;\n let ephemeralFileRefs: UnscopedFile[] | undefined;\n if (options.uploadedFiles?.length) {\n ({ fileRefs, ephemeralFileRefs } = this.partitionUploadedFiles(options.uploadedFiles));\n } else if (options.files?.length) {\n ephemeralFileRefs = await this.uploadEphemeralFiles(options.files);\n }\n\n const body: CreateProjectBody = {\n description: options.description,\n template_project_id: options.templateProjectId,\n };\n if (options.projectName) {\n body.display_name = options.projectName;\n }\n if (options.visibility) {\n body.visibility = options.visibility;\n }\n if (options.techStack) {\n body.tech_stack = options.techStack;\n }\n if (options.sandboxTemplate) {\n body.sandbox_template = options.sandboxTemplate;\n }\n if (options.selectedLibraries?.length) {\n body.selected_libraries = options.selectedLibraries;\n }\n if (options.initialMessage) {\n body.initial_message = options.initialMessage;\n }\n if (fileRefs?.length) {\n body.files = fileRefs;\n }\n if (options.fileUrls?.length) {\n body.file_urls = options.fileUrls;\n }\n if (ephemeralFileRefs?.length) {\n body.ephemeral_files = ephemeralFileRefs;\n }\n\n const { data } = await this.typed.POST(\"/v1/projects\", {\n body: { ...body, workspace_id: workspaceId },\n });\n return requireCreateProjectId(data!);\n }\n\n /**\n * Send a chat message to a project.\n *\n * The API accepts the message and processes it in the background.\n * Returns the message ID and status. Use `waitForMessageCompletion()`\n * to poll for the AI response.\n */\n async chat(projectId: string, options: ChatMessageOptions): Promise<SendMessageResponse> {\n let fileRefs: UnscopedFile[] | undefined;\n let ephemeralFileRefs: UnscopedFile[] | undefined;\n if (options.uploadedFiles?.length) {\n ({ fileRefs, ephemeralFileRefs } = this.partitionUploadedFiles(options.uploadedFiles));\n } else if (options.files?.length) {\n fileRefs = await this.uploadProjectFiles(projectId, options.files);\n }\n\n const body: Omit<Schemas[\"PublicV1SendMessageInputBody\"], \"project_id\"> = {\n message: options.message,\n };\n if (options.variantId) {\n body.variant_id = options.variantId;\n }\n if (fileRefs) {\n body.files = fileRefs;\n }\n if (ephemeralFileRefs) {\n body.ephemeral_files = ephemeralFileRefs;\n }\n if (options.planMode) {\n body.plan_mode = true;\n }\n if (options.continuation) {\n body.continuation = options.continuation;\n }\n\n const { data } = await this.typed.POST(\"/v1/messages\", {\n body: { ...body, project_id: projectId },\n });\n return data!;\n }\n\n /**\n * Create an independent variant from the project's current main branch, or from a full baseSha when provided.\n */\n async createVariant(projectId: string, options: CreateVariantOptions = {}): Promise<CreateVariantResponse> {\n const { data } = await this.typed.POST(\"/v1/projects/{project_id}/variants\", {\n params: { path: { project_id: projectId } },\n body: { label: options.label, base_sha: options.baseSha },\n });\n return data!;\n }\n\n /**\n * Get project details by ID\n */\n async getProject(projectId: string): Promise<ProjectResponse> {\n const { data } = await this.typed.GET(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Create an anonymous, one-hour static preview URL for one exact HTTPS parent origin.\n */\n async createEmbedUrl(projectId: string, parentOrigin: string): Promise<EmbedURLResponse> {\n const { data } = await this.typed.POST(\"/v1/projects/{project_id}/embed-url\", {\n params: { path: { project_id: projectId } },\n body: { parent_origin: parentOrigin },\n });\n return data!;\n }\n\n /**\n * Update supported project fields.\n */\n async updateProject(projectId: string, options: UpdateProjectOptions): Promise<ProjectResponse> {\n const { data } = await this.typed.PATCH(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n body: options,\n });\n return data!;\n }\n\n /**\n * Soft-delete a project. Repeated deletes are treated as successful.\n */\n async deleteProject(projectId: string): Promise<void> {\n await this.typed.DELETE(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n });\n }\n\n /**\n * Get the preview URL for a project.\n *\n * The preview URL is available once the project reaches \"completed\" status.\n * This URL allows viewing the project in development mode.\n *\n * @param projectId - The project ID\n * @returns The preview URL\n */\n getPreviewUrl(projectId: string): string {\n return `https://id-preview--${projectId}.lovable.app`;\n }\n\n /**\n * Get the published URL for a project (if published).\n *\n * Returns the public URL if the project has been published, or null if not.\n *\n * @param projectId - The project ID\n * @returns The published URL or null if not published\n */\n async getPublishedUrl(projectId: string): Promise<string | null> {\n const project = await this.getProject(projectId);\n return project.is_published && project.url ? project.url : null;\n }\n\n /**\n * Get the cloud database status for a project.\n *\n * @param projectId - The project ID\n * @returns Whether the database is enabled and which stack is used\n */\n async getDatabaseStatus(projectId: string): Promise<DatabaseStatus> {\n const { data } = await this.typed.GET(\"/v1/database\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Enable (provision) a cloud database for a project.\n *\n * This triggers database provisioning which takes 30-60 seconds.\n * The call blocks until provisioning completes.\n *\n * @param projectId - The project ID\n * @returns The database status after enablement\n */\n async enableDatabase(projectId: string): Promise<EnableDatabaseResult> {\n const { data } = await this.typed.POST(\"/v1/database/enable\", {\n body: { project_id: projectId },\n });\n return data!;\n }\n\n /**\n * Execute a SQL query against the project's cloud database.\n *\n * Supports SELECT, INSERT, UPDATE, DELETE, and DDL statements.\n * The database must be enabled first (see enableDatabase).\n *\n * @param projectId - The project ID\n * @param sql - SQL query to execute\n * @returns Query result rows as JSON objects\n */\n async queryDatabase(projectId: string, sql: string): Promise<DatabaseQueryResult> {\n // The route sits outside the public OpenAPI boundary, so the generated\n // paths lack it; DatabaseQueryCompatPaths stands in for the generated shape.\n const compat = this.typedClient as unknown as Client<DatabaseQueryCompatPaths>;\n const { data } = await compat.POST(\"/v1/database/query\", {\n body: { project_id: projectId, sql },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Messages\n // ---------------------------------------------------------------------------\n\n /**\n * Get a message by ID. Returns the message content, status, and (for user messages)\n * the AI response if available.\n *\n * Pass `waitSeconds` to long-poll: the server holds the request until the\n * message reaches a terminal state (completed / stopped / error / awaiting_input) or the\n * duration elapses. This replaces client-side polling for `waitForMessageCompletion`.\n */\n async getMessage(projectId: string, messageId: string, options?: GetMessageOptions): Promise<GetMessageResponse> {\n const waitSeconds = options?.waitSeconds;\n const query = {\n wait: waitSeconds && waitSeconds > 0 ? `${Math.floor(waitSeconds)}s` : undefined,\n thread_id: options?.threadId,\n };\n const { data } = await this.typed.GET(\"/v1/messages/{message_id}\", {\n params: { path: { message_id: messageId }, query: { ...query, project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * List recent messages in a project, newest first. Use `cursor` from the\n * previous page's `pagination.next_cursor` to paginate through history.\n */\n async listMessages(projectId: string, params?: ListMessagesOptions): Promise<ListMessagesResponse> {\n const cursor = params?.cursor ?? (params?.before ? encodePublicCursor(params.before) : undefined);\n const { data } = await this.typed.GET(\"/v1/messages\", {\n params: {\n query: { project_id: projectId, limit: params?.limit, cursor },\n },\n });\n return {\n ...data!,\n messages: data!.data,\n has_more: cursorHasMore(data!),\n };\n }\n\n /**\n * Wait for the AI response to reach a terminal status (completed, stopped, error, awaiting_input)\n * or for `timeout` to elapse.\n *\n * Primary path is SSE against `/v1/messages/{message_id}/stream`: one\n * held connection that pushes a snapshot on every relevant change and closes\n * on terminal. If SSE isn't reachable (proxy strips text/event-stream, server\n * returns 404 / 415 / 501) we fall back to the long-poll JSON endpoint on the\n * same URL. Both paths share the same `MessageCompletionResult` shape.\n */\n async waitForMessageCompletion(\n projectId: string,\n messageId: string,\n options?: MessageCompletionOptions,\n ): Promise<MessageCompletionResult> {\n const timeout = options?.timeout ?? 600_000;\n const deadline = Date.now() + timeout;\n\n const sse = await this.waitForMessageCompletionViaSSE(projectId, messageId, deadline, options?.threadId);\n if (sse.kind === \"result\") {\n return sse.result;\n }\n if (Date.now() >= deadline) {\n return timeoutResult(messageId, timeout);\n }\n return this.waitForMessageCompletionViaLongPoll(projectId, messageId, deadline, timeout, options);\n }\n\n /**\n * @deprecated Use `chat()` or `createProject()`'s returned `message_id`,\n * then call `waitForMessageCompletion(projectId, messageId)`.\n *\n * Throws when the turn pauses for human input (`awaiting_input`) — the\n * legacy `ChatResponse` shape cannot carry resume metadata. HITL-capable\n * flows need `waitForMessageCompletion` plus `respondToTool`.\n */\n async waitForResponse(projectId: string, options?: ChatResponseOptions): Promise<ChatResponse> {\n const messages = await this.listMessages(projectId, { limit: 10 });\n const latest = messages.messages?.find((message) => message.role === \"user\");\n\n if (!latest?.message_id) {\n throw new Error(`No messages found for project ${projectId}`);\n }\n\n const completionOptions = options?.timeout === undefined ? undefined : { timeout: options.timeout };\n const result = await this.waitForMessageCompletion(projectId, latest.message_id, completionOptions);\n // Preserve the pre-deprecation contract: throw on failure. waitForMessageCompletion\n // returns (never throws) on timeout/error, so without this a timed-out or errored run\n // looks like a successful empty response to try/catch callers.\n if (result.status !== \"completed\" && result.status !== \"stopped\") {\n throw new Error(result.error ?? `Message ${latest.message_id} did not complete (status: ${result.status})`);\n }\n return {\n content: result.content,\n messageId: result.message_id,\n previewUrl: this.getPreviewUrl(projectId),\n };\n }\n\n private async waitForMessageCompletionViaSSE(\n projectId: string,\n messageId: string,\n deadline: number,\n threadId?: string,\n ): Promise<{ kind: \"result\"; result: MessageCompletionResult } | { kind: \"fallback\" } | { kind: \"timeout\" }> {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return { kind: \"timeout\" };\n\n const url = new URL(`${this.baseUrl}/v1/messages/${encodeURIComponent(messageId)}/stream`);\n url.searchParams.set(\"project_id\", projectId);\n if (threadId) {\n url.searchParams.set(\"thread_id\", threadId);\n }\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), remaining);\n\n let response: Response;\n try {\n response = await fetch(url, {\n headers: {\n ...this.authHeaders,\n ...this.extraHeaders,\n \"X-Client-Source\": this.clientSource,\n Accept: \"text/event-stream\",\n },\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (isAbortError(err)) return { kind: \"timeout\" };\n return { kind: \"fallback\" };\n }\n\n if (!response.ok) {\n clearTimeout(timeoutId);\n if (response.status === 404 || response.status === 415 || response.status === 501) {\n await cancelResponseBody(response);\n return { kind: \"fallback\" };\n }\n if (response.status >= 500) {\n await cancelResponseBody(response);\n return { kind: \"fallback\" };\n }\n const detail = await safeReadText(response);\n throw new ApiError(response.status, detail || `HTTP ${response.status}`);\n }\n\n if (!response.body) {\n clearTimeout(timeoutId);\n return { kind: \"fallback\" };\n }\n\n try {\n for await (const frame of parseSSEFrames(response.body)) {\n if (!frame.data) continue;\n let snapshot: GetMessageResponse;\n try {\n snapshot = JSON.parse(frame.data) as GetMessageResponse;\n } catch {\n continue;\n }\n\n const queuedResult = queuedExitResult(snapshot, messageId);\n if (queuedResult) return { kind: \"result\", result: queuedResult };\n\n const terminal = terminalResultFromMessage(snapshot, messageId);\n if (terminal) {\n return { kind: \"result\", result: terminal };\n }\n }\n return { kind: \"fallback\" };\n } catch (err) {\n if (isAbortError(err)) return { kind: \"timeout\" };\n return { kind: \"fallback\" };\n } finally {\n clearTimeout(timeoutId);\n controller.abort();\n }\n }\n\n private async waitForMessageCompletionViaLongPoll(\n projectId: string,\n messageId: string,\n deadline: number,\n totalTimeoutMs: number,\n options?: MessageCompletionOptions,\n ): Promise<MessageCompletionResult> {\n const waitSeconds = Math.max(1, Math.min(55, options?.waitSeconds ?? 30));\n const transientBackoffMs = 1000;\n let notFoundSince: number | null = null;\n const notFoundGraceMs = 15_000;\n\n while (Date.now() < deadline) {\n const remainingMs = deadline - Date.now();\n const perCallSeconds = Math.min(waitSeconds, Math.floor(remainingMs / 1000));\n const waitOptions = perCallSeconds > 0 ? { waitSeconds: perCallSeconds } : undefined;\n\n const callStartedAt = Date.now();\n try {\n const msg = await this.getMessage(projectId, messageId, { ...waitOptions, threadId: options?.threadId });\n notFoundSince = null;\n\n const queuedResult = queuedExitResult(msg, messageId);\n if (queuedResult) return queuedResult;\n\n const terminal = terminalResultFromMessage(msg, messageId);\n if (terminal) return terminal;\n\n // Server returned a non-terminal snapshot far faster than the wait\n // window it was given. That happens when the streamer is nil or its\n // subscription fails server-side, or for queued messages that have no\n // stream events yet. Backoff so we don't tight-loop until the deadline.\n if (Date.now() - callStartedAt < transientBackoffMs) {\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n }\n } catch (err) {\n if (err instanceof ApiError) {\n if (err.status === 404) {\n if (notFoundSince === null) {\n notFoundSince = Date.now();\n }\n if (Date.now() - notFoundSince < notFoundGraceMs) {\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n continue;\n }\n return {\n status: \"error\",\n message_id: messageId,\n content: \"\",\n error: \"Message not found. It may have been deleted from the queue.\",\n };\n }\n if (err.status < 500) {\n throw err;\n }\n }\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n }\n }\n\n return timeoutResult(messageId, totalTimeoutMs);\n }\n\n // ---------------------------------------------------------------------------\n // Knowledge\n // ---------------------------------------------------------------------------\n\n /** Get workspace knowledge (custom instructions for the AI agent). */\n async getWorkspaceKnowledge(workspaceId: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/knowledge\", {\n params: { path: { workspace_id: workspaceId } },\n });\n return data!;\n }\n\n /** Set workspace knowledge. Max 10,000 characters. */\n async setWorkspaceKnowledge(workspaceId: string, content: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/knowledge\", {\n params: { path: { workspace_id: workspaceId } },\n body: { content },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Workspace skills\n // ---------------------------------------------------------------------------\n\n /** List workspace skills. */\n async listWorkspaceSkills(\n workspaceId: string,\n options: { includeMarkdown?: boolean } & ListOffsetPaginationOptions = {},\n ): Promise<ListWorkspaceSkillsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/skills\", {\n params: {\n path: { workspace_id: workspaceId },\n query: { include_markdown: options.includeMarkdown, limit: options.limit, offset: options.offset },\n },\n });\n return { ...data!, skills: data!.skills ?? [] };\n }\n\n /** Get a single workspace skill, including SKILL.md contents. */\n async getWorkspaceSkill(workspaceId: string, skillName: string): Promise<WorkspaceSkillResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n });\n return data!;\n }\n\n /** Create a workspace skill from full SKILL.md markdown. */\n async createWorkspaceSkill(\n workspaceId: string,\n skillName: string,\n markdown: string,\n ): Promise<WorkspaceSkillWriteResponse> {\n const { data } = await this.typed.POST(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n body: { markdown },\n });\n return data!;\n }\n\n /** Update a workspace skill by replacing its SKILL.md markdown. */\n async updateWorkspaceSkill(\n workspaceId: string,\n skillName: string,\n markdown: string,\n ): Promise<WorkspaceSkillWriteResponse> {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n body: { markdown },\n });\n return data!;\n }\n\n /** Delete a workspace skill. */\n async deleteWorkspaceSkill(workspaceId: string, skillName: string): Promise<WorkspaceSkillDeleteResponse> {\n const { data } = await this.typed.DELETE(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Project skills\n // ---------------------------------------------------------------------------\n\n /** List project skills, including whether each skill is enabled. */\n async listProjectSkills(\n projectId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListProjectSkillsResponse> {\n const { data } = await this.typed.GET(\"/v1/skills\", {\n params: { query: { project_id: projectId, limit: options.limit, cursor: options.cursor } },\n });\n const skills = (data as unknown as { skills?: ListProjectSkillsResponse[\"skills\"] }).skills ?? data!.data ?? [];\n return { ...data!, skills };\n }\n\n /** Enable or disable a project skill without removing it from the project repo. */\n async setProjectSkillEnabled(projectId: string, skillName: string, enabled: boolean): Promise<ProjectSkillResponse> {\n const { data } = await this.typed.PATCH(\"/v1/skills/{skill_name}\", {\n params: { path: { skill_name: skillName } },\n body: { project_id: projectId, enabled },\n });\n return data!;\n }\n\n /** Get project knowledge (custom instructions for the AI agent). */\n async getProjectKnowledge(projectId: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.GET(\"/v1/knowledge\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /** Set project knowledge. Max 10,000 characters. */\n async setProjectKnowledge(projectId: string, content: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.PUT(\"/v1/knowledge\", {\n body: { project_id: projectId, content },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Git operations\n // ---------------------------------------------------------------------------\n\n /**\n * Get the structured diff for a message or commit.\n * Pass `messageId` to get the diff for a specific AI message,\n * or `sha` for a specific commit.\n */\n async getDiff(\n projectId: string,\n params: { messageId?: string; sha?: string; baseSha?: string },\n ): Promise<GitDiffResponse> {\n const { data } = await this.typed.GET(\"/v1/git/diff\", {\n params: {\n query: { project_id: projectId, message_id: params.messageId, sha: params.sha, base_sha: params.baseSha },\n },\n });\n return data!;\n }\n\n /** List files in a project. Omitting ref uses the API default. */\n async listFiles(projectId: string, ref?: string, options?: CursorPaginationOptions): Promise<GitFilesResponse>;\n async listFiles(projectId: string, options?: CursorPaginationOptions): Promise<GitFilesResponse>;\n async listFiles(\n projectId: string,\n refOrOptions?: string | CursorPaginationOptions,\n options: CursorPaginationOptions = {},\n ): Promise<GitFilesResponse> {\n const ref = typeof refOrOptions === \"string\" ? refOrOptions : undefined;\n const pagination = typeof refOrOptions === \"string\" ? options : (refOrOptions ?? options);\n const { data } = await this.typed.GET(\"/v1/git/files\", {\n params: { query: { project_id: projectId, ref, limit: pagination.limit, cursor: pagination.cursor } },\n });\n const files = data!.data ?? [];\n return { ...data!, data: files, files };\n }\n\n /** Read the raw content of a single file. Omitting ref uses the API default. */\n async readFile(projectId: string, path: string, ref?: string): Promise<string> {\n // The Go OpenAPI annotation for this route declares 200 as `content?: never`\n // even though the handler returns the raw file text. `parseAs: \"text\"` makes\n // openapi-fetch read the body as text at runtime; the cast covers the spec\n // gap. Drop the cast once the Go annotation declares text/plain content.\n const { data } = await this.typed.GET(\"/v1/git/files/{path}\", {\n params: { path: { path }, query: { project_id: projectId, ref } },\n parseAs: \"text\",\n });\n return data as unknown as string;\n }\n\n // ---------------------------------------------------------------------------\n // Edits\n // ---------------------------------------------------------------------------\n\n /** List the edit history of a project. */\n async listEdits(\n projectId: string,\n params?: { limit?: number; before?: string; cursor?: string },\n ): Promise<EditsResponse> {\n const { data } = await this.typed.GET(\"/v1/edits\", {\n params: {\n query: {\n project_id: projectId,\n limit: params?.limit,\n before: params?.before,\n cursor: params?.cursor,\n },\n },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // File upload\n // ---------------------------------------------------------------------------\n\n /** Get an ephemeral presigned URL for uploading a file before a project exists. */\n async getFileUploadUrl(params: { file_name: string; content_type?: string }): Promise<FileUploadUrlResponse> {\n return this.getEphemeralFileUploadUrl({ content_type: params.content_type });\n }\n\n /** Get a project-scoped presigned URL for uploading a file. Returns the upload URL, file ID, and required PUT headers. */\n async getProjectFileUploadUrl(projectId: string, params: { content_type?: string }): Promise<FileUploadUrlResponse> {\n const { data } = await this.typed.POST(\"/v1/project-files/upload-url\", {\n body: { project_id: projectId, ...params },\n });\n return data!;\n }\n\n /** Get an ephemeral presigned URL for uploading a file before a project exists. */\n async getEphemeralFileUploadUrl(params: { content_type?: string }): Promise<FileUploadUrlResponse> {\n const { data } = await this.typed.POST(\"/v1/files/ephemeral-upload-url\", { body: params });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Visibility\n // ---------------------------------------------------------------------------\n\n /** Set a project's visibility (draft, private, workspace_view, or public). */\n async setProjectVisibility(projectId: string, visibility: ProjectPatchVisibility): Promise<ProjectResponse> {\n return this.updateProject(projectId, { visibility });\n }\n\n /** Set a folder's visibility (personal or workspace). */\n async setFolderVisibility(workspaceId: string, folderId: string, visibility: \"personal\" | \"workspace\") {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/folders/{folder_id}/visibility\", {\n params: { path: { workspace_id: workspaceId, folder_id: folderId } },\n body: { visibility },\n });\n return data!;\n }\n\n /** Move projects into a folder, removing existing folder memberships first. */\n async moveProjectsToFolder(\n workspaceId: string,\n folderId: string,\n projectIds: string[],\n ): Promise<MoveProjectsToFolderResponse> {\n const { data } = await this.typed.POST(\"/v1/workspaces/{workspace_id}/folders/{folder_id}/projects/move\", {\n params: { path: { workspace_id: workspaceId, folder_id: folderId } },\n body: { project_ids: projectIds },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Library & template projects\n // ---------------------------------------------------------------------------\n\n /** List available design system library projects in a workspace. */\n async listLibraryProjects(\n workspaceId: string,\n options: ListOffsetPaginationOptions = {},\n ): Promise<ListLibraryProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/available-library-projects\", {\n params: { path: { workspace_id: workspaceId }, query: options },\n });\n return { ...data!, libraries: data!.libraries ?? [] };\n }\n\n /** List available template projects in a workspace. */\n async listTemplateProjects(\n workspaceId: string,\n options: ListOffsetPaginationOptions = {},\n ): Promise<ListTemplateProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/available-template-projects\", {\n params: { path: { workspace_id: workspaceId }, query: options },\n });\n return { ...data!, templates: data!.templates ?? [] };\n }\n\n // ---------------------------------------------------------------------------\n // Connectors (MCP servers)\n // ---------------------------------------------------------------------------\n\n /** List all connectors in a workspace. */\n async listConnectors(workspaceId: string, options: ListConnectorsOptions = {}): Promise<ListConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: {\n query: {\n workspace_id: workspaceId,\n type: options.type,\n status: options.status,\n limit: options.limit,\n cursor: options.cursor,\n },\n },\n });\n const connectors =\n (data as unknown as { connectors?: ListConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n // ---------------------------------------------------------------------------\n // Connectors\n // ---------------------------------------------------------------------------\n\n /** List standard (OAuth-based) connectors in a workspace. */\n async listStandardConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListStandardConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"standard\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListStandardConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n /** List seamless (zero-config) connectors in a workspace. */\n async listSeamlessConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListSeamlessConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"seamless\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListSeamlessConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n /** List MCP connectors in a workspace. */\n async listMCPConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListMCPConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"mcp\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListMCPConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n // ---------------------------------------------------------------------------\n // Analytics\n // ---------------------------------------------------------------------------\n\n /** Get historical analytics for a published project. */\n async getProjectAnalytics(\n projectId: string,\n params: { startDate: string; endDate: string; granularity?: string },\n ): Promise<ProjectAnalyticsResponse> {\n const { data } = await this.typed.GET(\"/v1/analytics\", {\n params: {\n query: {\n project_id: projectId,\n startDate: params.startDate,\n endDate: params.endDate,\n granularity: params.granularity,\n },\n },\n });\n return data!;\n }\n\n /** Get real-time visitor trend for a published project. */\n async getProjectAnalyticsTrend(projectId: string): Promise<ProjectAnalyticsTrendResponse> {\n const { data } = await this.typed.GET(\"/v1/analytics/trend\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Publish a project.\n *\n * This triggers a deployment which makes the project publicly accessible.\n * The deployment runs asynchronously - use waitForProjectPublished() to wait for completion.\n *\n * @param projectId - The project ID to publish\n * @param options.name - Optional custom slug for the published URL\n * @returns Deployment info including deployment ID\n */\n async publish(projectId: string, options?: { name?: string }): Promise<DeploymentResponse> {\n const { data } = await this.typed.POST(\"/v1/deployments\", {\n body: { project_id: projectId, name: options?.name },\n });\n return data!;\n }\n\n /**\n * Remix (fork) an existing project, optionally at a specific message point in time.\n *\n * When `messageId` is provided, the remix captures the project state after\n * that message and its AI response by default. Set `remixMode: \"before\"` to\n * start before the message was processed.\n * Without `messageId`, the full current state is remixed.\n *\n * @param sourceProjectId - The project to remix from\n * @param options.workspaceId - Target workspace for the new project\n * @param options.messageId - Optional message ID to snapshot at\n * @param options.remixMode - \"including\" (server default): state after the message and its AI response; \"before\": state before the message\n * @param options.includeHistory - Whether to preserve chat history (default: false)\n * @param options.includeCustomKnowledge - Whether to copy custom instructions (default: false)\n * @param options.initialMessage - Optional initial message to send after remix\n * @param options.description - Optional custom description for the new project\n * @returns The remix job ID for polling progress\n */\n async remixProject(sourceProjectId: string, options: RemixProjectOptions): Promise<string> {\n const body: RemixCreateProjectBody = {\n workspace_id: options.workspaceId,\n source_project_id: sourceProjectId,\n include_history: options.includeHistory,\n include_custom_knowledge: options.includeCustomKnowledge,\n description: options.description,\n display_name: options.projectName,\n skip_initial_remix_message: options.skipInitialRemixMessage,\n skip_integrations: options.skipIntegrations,\n };\n\n if (options.messageId) {\n body.message_id = options.messageId;\n if (options.remixMode) {\n body.remix_mode = options.remixMode;\n }\n }\n\n if (options.initialMessage) {\n body.initial_message = options.initialMessage;\n }\n\n const { data } = await this.typed.POST(\"/v1/projects\", {\n body: body as CreateProjectPostBody,\n });\n const remix = data;\n if (!remix?.job_id) {\n throw new Error(\"Failed to get job ID from remix create\");\n }\n return remix.job_id;\n }\n\n /**\n * Wait for a remix operation to complete.\n *\n * Polls the remix progress endpoint until the job reaches \"completed\" or \"error\" status.\n *\n * @param sourceProjectId - The source project ID (used for the progress endpoint)\n * @param jobId - The job ID returned by `remixProject()`\n * @param options.pollInterval - Time between polls in ms (default: 2000)\n * @param options.timeout - Maximum time to wait in ms (default: 300000 = 5 minutes)\n * @param options.onProgress - Optional callback for status/step updates\n * @returns The new project ID\n * @throws Error if the remix fails or timeout is reached\n */\n async waitForRemix(sourceProjectId: string, jobId: string, options?: RemixWaitOptions): Promise<RemixResult> {\n const pollInterval = options?.pollInterval ?? 2000;\n const timeout = options?.timeout ?? 300000;\n const startTime = Date.now();\n\n while (true) {\n const { data } = await this.typed.GET(\"/v1/projects/{project_id}/remix/progress\", {\n params: {\n path: { project_id: sourceProjectId },\n query: { job_id: jobId },\n },\n });\n const progress = data!;\n const status = progress.status as RemixJobStatus;\n options?.onProgress?.(status, progress.step);\n\n if (status === \"completed\" && progress.result) {\n return { projectId: progress.result.project_id };\n }\n\n if (status === \"error\") {\n throw new Error(progress.error_message ?? \"Remix failed\");\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for remix of project ${sourceProjectId}`);\n }\n\n await sleep(pollInterval);\n }\n }\n\n /**\n * Wait for a project to reach \"completed\" status.\n *\n * Projects start in \"in_progress\" status while being created/built.\n * This method polls until the status becomes \"completed\" or \"failed\".\n * A successful completion means the project's preview is ready to view.\n *\n * @param projectId - The project ID to wait for\n * @param options.pollInterval - Time between polls in ms (default: 2000)\n * @param options.timeout - Maximum time to wait in ms (default: 300000 = 5 minutes)\n * @param options.onProgress - Optional callback for status updates\n * @returns The completed project\n * @throws Error if project fails or timeout is reached\n */\n async waitForProjectReady(projectId: string, options?: WaitOptions): Promise<ProjectResponse> {\n const pollInterval = options?.pollInterval ?? 2000;\n const timeout = options?.timeout ?? 300000;\n const startTime = Date.now();\n\n while (true) {\n const project = await this.getProject(projectId);\n options?.onProgress?.(project);\n\n if (project.status === \"completed\") {\n return project;\n }\n\n if (project.status === \"failed\") {\n throw new Error(`Project ${projectId} failed to build`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for project ${projectId} to be ready`);\n }\n\n await sleep(pollInterval);\n }\n }\n\n private isFileInput(file: File | FileInput): file is FileInput {\n return \"data\" in file;\n }\n\n private async uploadFile(\n file: File | FileInput,\n getUploadUrl: (fileName: string, mimeType: string) => Promise<FileUploadUrlResponse>,\n ): Promise<UnscopedFile> {\n const fileName = this.isFileInput(file) ? file.name : file.name;\n const mimeType = this.isFileInput(file) ? file.type : file.type;\n const body = this.isFileInput(file) ? file.data : file;\n\n const uploadUrl = await getUploadUrl(fileName, mimeType);\n const { url, file_id: objectPath, headers } = uploadUrl;\n\n const uploadResponse = await fetch(url, {\n method: \"PUT\",\n body,\n headers: { \"Content-Type\": mimeType, ...headers },\n });\n if (!uploadResponse.ok) {\n throw new Error(`File upload failed for \"${fileName}\": HTTP ${uploadResponse.status}`);\n }\n\n return { file_id: objectPath, type: \"user_upload\", file_name: fileName, mime_type: mimeType };\n }\n\n private async uploadProjectFiles(projectId: string, files: (File | FileInput)[]): Promise<UnscopedFile[]> {\n return Promise.all(\n files.map((file) =>\n this.uploadFile(file, (_fileName, mimeType) =>\n this.getProjectFileUploadUrl(projectId, { content_type: mimeType }),\n ),\n ),\n );\n }\n\n private async uploadEphemeralFiles(files: (File | FileInput)[]): Promise<UnscopedFile[]> {\n return Promise.all(\n files.map((file) =>\n this.uploadFile(file, (_fileName, mimeType) => this.getEphemeralFileUploadUrl({ content_type: mimeType })),\n ),\n );\n }\n\n private partitionUploadedFiles(files: UnscopedFile[]): {\n fileRefs: UnscopedFile[] | undefined;\n ephemeralFileRefs: UnscopedFile[] | undefined;\n } {\n const fileRefs: UnscopedFile[] = [];\n const ephemeralFileRefs: UnscopedFile[] = [];\n for (const file of files) {\n if (file.file_id.startsWith(\"ephemeral/\")) {\n ephemeralFileRefs.push(file);\n } else {\n fileRefs.push(file);\n }\n }\n return {\n fileRefs: fileRefs.length > 0 ? fileRefs : undefined,\n ephemeralFileRefs: ephemeralFileRefs.length > 0 ? ephemeralFileRefs : undefined,\n };\n }\n /**\n * Wait for a project to be published (deployed).\n *\n * This method polls until the project has `is_published: true` and a `url`.\n *\n * @param projectId - The project ID to wait for\n * @param options.pollInterval - Time between polls in ms (default: 3000)\n * @param options.timeout - Maximum time to wait in ms (default: 600000 = 10 minutes)\n * @param options.onProgress - Optional callback for status updates\n * @returns The published project with URL\n * @throws Error if timeout is reached\n */\n async waitForProjectPublished(projectId: string, options?: WaitOptions): Promise<ProjectResponse> {\n const pollInterval = options?.pollInterval ?? 3000;\n const timeout = options?.timeout ?? 600000;\n const startTime = Date.now();\n\n while (true) {\n const project = await this.getProject(projectId);\n options?.onProgress?.(project);\n\n if (project.is_published && project.url) {\n return project;\n }\n\n if (project.status === \"failed\") {\n throw new Error(`Project ${projectId} failed to build`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for project ${projectId} to be published`);\n }\n\n await sleep(pollInterval);\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"name\" in err && err.name === \"AbortError\";\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n try {\n await response.body?.cancel();\n } catch {}\n}\n\nasync function* parseSSEFrames(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: string }, void, void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let sep = buffer.indexOf(\"\\n\\n\");\n while (sep !== -1) {\n const raw = buffer.slice(0, sep);\n buffer = buffer.slice(sep + 2);\n sep = buffer.indexOf(\"\\n\\n\");\n\n let event = \"message\";\n const dataLines: string[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) {\n event = line.slice(6).trimStart();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length === 0) continue;\n yield { event, data: dataLines.join(\"\\n\") };\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // ignore\n }\n try {\n await body.cancel();\n } catch {\n // ignore\n }\n }\n}\n\nfunction terminalResultFromMessage(msg: GetMessageResponse, fallbackMessageId: string): MessageCompletionResult | null {\n const ai = msg.response;\n if (ai && isTerminalAIStatus(ai.status)) {\n return {\n status: messageCompletionStatus(ai.status),\n message_id: ai.message_id || fallbackMessageId,\n content: ai.content,\n edit_id: ai.edit_id,\n commit_sha: ai.commit_sha,\n summary: ai.summary,\n cost_credits: ai.cost_credits,\n awaiting_input: ai.awaiting_input,\n ...(ai.status === \"error\" ? { error: \"Agent reported an error.\" } : {}),\n };\n }\n if (msg.role === \"assistant\" && isTerminalAIStatus(msg.status)) {\n return {\n status: messageCompletionStatus(msg.status),\n message_id: msg.message_id || fallbackMessageId,\n content: msg.content,\n edit_id: msg.edit_id,\n commit_sha: msg.commit_sha,\n summary: msg.summary,\n cost_credits: msg.cost_credits,\n awaiting_input: msg.awaiting_input,\n ...(msg.status === \"error\" ? { error: \"Agent reported an error.\" } : {}),\n };\n }\n return null;\n}\n\nfunction messageCompletionStatus(status: string): MessageCompletionResult[\"status\"] {\n return status === \"completed\" || status === \"stopped\" || status === \"awaiting_input\" ? status : \"error\";\n}\n\nfunction isTerminalAIStatus(status: string | undefined): boolean {\n return status === \"completed\" || status === \"stopped\" || status === \"error\" || status === \"awaiting_input\";\n}\n\nfunction queuedExitResult(msg: GetMessageResponse, fallbackMessageId: string): MessageCompletionResult | null {\n if (msg.status !== \"queued\") return null;\n if (!msg.queue_paused) return null;\n if (msg.queue_pause_reason === \"hitl_tool\") return null;\n return {\n status: \"error\",\n message_id: fallbackMessageId,\n content: \"\",\n error:\n `Message is queued (position ${msg.queue_position ?? \"unknown\"}) but the queue is paused` +\n (msg.queue_pause_reason ? ` (reason: ${msg.queue_pause_reason})` : \"\") +\n `. Unpause the queue in the Lovable editor, or use wait=false to return immediately.`,\n };\n}\n\nfunction timeoutResult(messageId: string, timeoutMs: number): MessageCompletionResult {\n return {\n status: \"timeout\",\n message_id: messageId,\n content: \"\",\n error: `Agent did not finish within ${Math.max(0, Math.round(timeoutMs / 1000))}s`,\n };\n}\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AS,IAAI;EACb,YAAY,IAAI;EAChB,SAAS,IAAI;EACb,cAAc,IAAI;EAClB,gBAAgB,IAAI;EACpB,GAAI,IAAI,WAAW,UAAU,EAAE,OAAO,2BAA2B,IAAI,CAAC;CACxE;CAEF,OAAO;AACT;AAEA,SAAS,wBAAwB,QAAmD;CAClF,OAAO,WAAW,eAAe,WAAW,aAAa,WAAW,mBAAmB,SAAS;AAClG;AAEA,SAAS,mBAAmB,QAAqC;CAC/D,OAAO,WAAW,eAAe,WAAW,aAAa,WAAW,WAAW,WAAW;AAC5F;AAEA,SAAS,iBAAiB,KAAyB,mBAA2D;CAC5G,IAAI,IAAI,WAAW,UAAU,OAAO;CACpC,IAAI,CAAC,IAAI,cAAc,OAAO;CAC9B,IAAI,IAAI,uBAAuB,aAAa,OAAO;CACnD,OAAO;EACL,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,OACE,+BAA+B,IAAI,kBAAkB,UAAU,8BAC9D,IAAI,qBAAqB,aAAa,IAAI,mBAAmB,KAAK,MACnE;CACJ;AACF;AAEA,SAAS,cAAc,WAAmB,WAA4C;CACpF,OAAO;EACL,QAAQ;EACR,YAAY;EACZ,SAAS;EACT,OAAO,+BAA+B,KAAK,IAAI,GAAG,KAAK,MAAM,YAAY,GAAI,CAAC,EAAE;CAClF;AACF"}
1
+ {"version":3,"file":"index.js","names":["sleep","parseRetryAfterMs"],"sources":["../src/retryFetch.ts","../src/types.ts","../src/client.ts"],"sourcesContent":["const RETRY_DELAYS_MS = [100, 300, 500] as const;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction parseRetryAfterMs(headers: Headers): number | undefined {\n const raw = headers.get(\"retry-after\");\n if (!raw) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) {\n const delta = dateMs - Date.now();\n return delta > 0 ? delta : 0;\n }\n return undefined;\n}\n\nexport type RetryFetch = (input: Request) => Promise<Response>;\n\n/**\n * Wraps a fetch implementation with retry on HTTP 429. Up to three retries\n * at 100ms / 300ms / 500ms; if the server sends `Retry-After` and it's\n * larger than the planned delay, we honor the server value. The Request is\n * cloned before each attempt so its body remains replayable.\n *\n * Matches openapi-fetch's `fetch` option signature: a single `Request` in,\n * `Promise<Response>` out.\n */\nexport function makeRetryFetch(baseFetch: RetryFetch = (input) => globalThis.fetch(input)): RetryFetch {\n return async (input) => {\n // Request.clone() and the fetch parameter resolve to different Request type\n // definitions when @types/node (undici) and @types/bun are both in scope;\n // the cloned object is structurally the same Request, so assert the param type.\n const clone = (): Parameters<RetryFetch>[0] => input.clone() as Parameters<RetryFetch>[0];\n let response = await baseFetch(clone());\n for (const planned of RETRY_DELAYS_MS) {\n if (response.status !== 429) break;\n const serverDelay = parseRetryAfterMs(response.headers);\n await sleep(Math.max(planned, serverDelay ?? 0));\n response = await baseFetch(clone());\n }\n return response;\n };\n}\n","// Type definitions for the Lovable SDK.\n//\n// Response and request body types come straight from the generated OpenAPI\n// types (`./generated/paths.ts`, produced by `openapi-typescript` from the\n// trimmed v1 spec). The same trimmed spec also drives `./generated/zod/`\n// (consumed by `@lovable.dev/sdk/schemas` for runtime validation), so the\n// type aliases here are guaranteed to match the schemas the MCP server\n// uses — there is no hand-maintained parallel shape to drift.\n//\n// Types that don't have a 1:1 OpenAPI counterpart (request options, SDK\n// wrappers like `MessageCompletionResult` that re-shape responses, helper\n// interfaces like `FileInput`) stay hand-written below.\n\nimport type { components, paths } from \"./generated/paths.js\";\n\ntype Schemas = components[\"schemas\"];\n\ntype ListProjectsQuery = NonNullable<paths[\"/v1/projects\"][\"get\"][\"parameters\"][\"query\"]>;\ntype ListConnectorsQuery = NonNullable<paths[\"/v1/connectors\"][\"get\"][\"parameters\"][\"query\"]>;\n\n// =============================================================================\n// API types — derived from the OpenAPI spec\n// =============================================================================\n\n// --- Users & workspaces ---\n\nexport type MeWorkspace = Schemas[\"GetMeWorkspace\"];\nexport type MeResponse = Schemas[\"GetMeOutputBody\"];\nexport type WorkspaceMembership = Schemas[\"PublicV1WorkspaceMember\"];\nexport type WorkspaceWithMembership = Schemas[\"PublicV1WorkspaceWithMembership\"];\nexport type GetWorkspacesResponse = Schemas[\"V1ListWorkspacesBody\"] & {\n workspaces: WorkspaceWithMembership[];\n};\n\n// Role enum lives on WorkspaceMembership in the spec; reuse it so SDK callers\n// always pick from the same set the server returns.\nexport type MemberRole = WorkspaceMembership[\"role\"];\n\n// --- Projects ---\n\n// Lean shape returned by GET /v1/projects/{id} and POST /v1/projects.\nexport type ProjectResponse = Schemas[\"V1ProjectResponse\"];\nexport type CreateProjectResponse = Schemas[\"PublicV1CreateProjectResponse\"] & { id: string };\nexport type CreateProjectBody = Omit<Schemas[\"PublicV1ProjectCreateInputBody\"], \"workspace_id\">;\nexport type UpdateProjectOptions = Schemas[\"PublicV1PatchProjectBody\"];\nexport type EmbedURLResponse = Schemas[\"V1CreateEmbedURLOutputBody\"];\n\n// Wider listing shape returned by the projects list endpoint.\nexport type ListProjectItem = Schemas[\"PublicV1ProjectListItem\"];\nexport type ListProjectsResponse = Schemas[\"CursorListResponsePublicV1ProjectListItem\"] & {\n projects: ListProjectItem[] | null;\n total?: number;\n has_more?: boolean;\n};\nexport type GetWorkspaceProjectsResponse = ListProjectsResponse;\nexport type MoveProjectsToFolderResponse = Schemas[\"AddProjectsToFolderResult\"];\n\n// Compatibility export; curated response fields accept future string values.\nexport type ProjectVisibility = \"public\" | \"private\" | \"draft\" | \"workspace_view\";\nexport type ProjectPatchVisibility = NonNullable<UpdateProjectOptions[\"visibility\"]>;\n\n// --- Messages ---\n\nexport type SendMessageResponse = Schemas[\"V1SendMessageOutputBody\"];\nexport type GetMessageResponse = Schemas[\"V1MessageResponse\"];\nexport type MessageSummary = Schemas[\"V1MessageListItem\"];\ntype AwaitingInputSummary = Partial<Schemas[\"V1AwaitingInputSummary\"]>;\nexport type ListMessagesResponse = Schemas[\"CursorListResponseV1MessageListItem\"] & {\n messages: MessageSummary[] | null;\n has_more: boolean;\n};\nexport interface ListMessagesOptions {\n limit?: number;\n cursor?: string;\n /** @deprecated Use `cursor` from `pagination.next_cursor`; kept for source compatibility. */\n before?: string;\n}\n\nexport interface ChatResponse {\n content: string;\n previewUrl: string;\n messageId: string;\n}\n\nexport interface ChatResponseOptions {\n timeout?: number;\n}\n\nexport type CreateVariantResponse = Schemas[\"V1CreateVariantOutputBody\"];\n\n// --- Deployment ---\n\nexport type DeploymentResponse = Schemas[\"V1DeployProjectOutputBody\"];\n\n// --- Database ---\n\nexport type DatabaseStatus = Schemas[\"V1GetDatabaseStatusOutputBody\"];\nexport type EnableDatabaseResult = Schemas[\"V1EnableDatabaseOutputBody\"];\n// POST /v1/database/query is served but sits outside the public OpenAPI\n// boundary, so no generated type exists; hand-maintained for queryDatabase\n// and the MCP query_database tool.\nexport type DatabaseQueryResult = {\n rows: Record<string, unknown>[] | null;\n};\n\n// --- Knowledge ---\n\nexport type KnowledgeResponse = Schemas[\"V1KnowledgeResponse\"];\n\n// --- Skills ---\n\nexport type WorkspaceSkillFile = Schemas[\"ProjectFileInfo\"];\nexport type WorkspaceSkill = Schemas[\"V1WorkspaceSkillDTO\"];\nexport type ListWorkspaceSkillsResponse = Schemas[\"V1ListWorkspaceSkillsOutputBody\"];\nexport type WorkspaceSkillResponse = Schemas[\"V1GetWorkspaceSkillOutputBody\"];\nexport type WorkspaceSkillWriteResponse = Schemas[\"V1WriteWorkspaceSkillOutputBody\"];\nexport type WorkspaceSkillDeleteResponse = Schemas[\"V1DeleteWorkspaceSkillOutputBody\"];\n\nexport type ProjectSkill = Schemas[\"V1ProjectSkillDTO\"];\nexport type ListProjectSkillsResponse = Schemas[\"CursorListResponseV1ProjectSkillDTO\"] & {\n skills: ProjectSkill[];\n};\nexport type ProjectSkillResponse = Schemas[\"V1SetProjectSkillEnabledOutputBody\"];\n\n// --- File upload ---\n\nexport type FileUploadUrlResponse = Schemas[\"V1FileUploadURLOutputBody\"];\nexport type UnscopedFile = Schemas[\"V1UnscopedFile\"];\n\n// --- Git / diffs / files / edits ---\n\nexport type DiffLine = Schemas[\"DiffLine\"];\nexport type DiffHunk = Schemas[\"DiffHunk\"];\nexport type DiffEntry = Schemas[\"V1DiffEntry\"];\nexport type GitDiffResponse = Schemas[\"V1DiffResponse\"];\nexport type GitFileEntry = Schemas[\"GitFileEntryLite\"];\nexport type GitFilesResponse = Schemas[\"PublicV1GitFilesResponse\"] & { files: GitFileEntry[] };\nexport type EditSummary = Schemas[\"V1EditSummary\"];\nexport type EditsResponse = Schemas[\"CursorListResponseV1EditSummary\"];\n\n// --- Libraries & templates ---\n\nexport type LibraryProjectResponse = Record<string, unknown>;\nexport type TemplateProjectResponse = Record<string, unknown>;\nexport type ListLibraryProjectsResponse = {\n libraries: LibraryProjectResponse[];\n total?: number;\n has_more?: boolean;\n};\nexport type ListTemplateProjectsResponse = {\n templates: TemplateProjectResponse[];\n total?: number;\n has_more?: boolean;\n};\n\n// --- Connectors ---\n\nexport type ConnectorItem = Schemas[\"PublicV1ConnectorItem\"];\nexport type StandardConnectorItem = ConnectorItem;\nexport type SeamlessConnectorItem = ConnectorItem;\nexport type MCPConnectorItem = ConnectorItem;\nexport type ListConnectorsResponse = Omit<Schemas[\"CursorListResponsePublicV1ConnectorItem\"], \"data\"> & {\n data: ConnectorItem[];\n connectors: ConnectorItem[];\n has_more: boolean;\n};\nexport type ListStandardConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> & {\n connectors: StandardConnectorItem[];\n};\nexport type ListSeamlessConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> & {\n connectors: SeamlessConnectorItem[];\n};\nexport type ListMCPConnectorsResponse = Omit<ListConnectorsResponse, \"connectors\"> &\n Partial<Omit<Schemas[\"V1ListMCPConnectorsResponse\"], \"connectors\">> & {\n data: MCPConnectorItem[];\n connectors: MCPConnectorItem[];\n };\n\n// --- Analytics ---\n\nexport type TimeSeriesDataPoint = Schemas[\"TimeSeriesDataPoint\"];\nexport type TimeSeriesData = Schemas[\"TimeSeriesData\"];\nexport type ListDataPoint = Schemas[\"ListDataPoint\"];\nexport type ListData = Schemas[\"ListData\"];\nexport type ProjectAnalyticsResponse = Schemas[\"ProjectAnalyticsResponse\"];\nexport type TrendDataPoint = Schemas[\"TrendDataPoint\"];\nexport type ProjectAnalyticsTrendResponse = Schemas[\"ProjectTrendResponse\"];\n\n// --- Remix ---\n\nexport type RemixJobStepInfo = Schemas[\"RemixJobStepInfo\"];\nexport type RemixInitResponse = { job_id: string };\nexport type RemixProgressResult = Schemas[\"V1RemixProgressResult\"];\nexport type RemixProgressResponse = {\n status: string;\n step?: RemixJobStepInfo;\n result?: RemixProgressResult;\n error_message?: string;\n error_code?: string;\n};\n\n// The V1 spec types `status` as plain string. The Go handler returns one of\n// these five values — keep the narrow union here as an SDK-side aid for\n// callers that switch on it. If the spec ever exposes this as an enum,\n// replace with `Schemas[\"V1RemixProgressOutputBody\"][\"status\"]`.\nexport type RemixJobStatus = \"unknown\" | \"preparing\" | \"running\" | \"completed\" | \"error\";\nexport type RemixJobStep =\n | \"starting\"\n | \"creating_new_project\"\n | \"restoring_supabase\"\n | \"copying_history\"\n | \"preparing_repository\"\n | \"remixing_integration\"\n | \"pushing_repository\"\n | \"finalizing\"\n | \"completed\";\n\n// V1 status field on V1ProjectResponse is plain string; the Go handler returns\n// one of these three. Same rationale as RemixJobStatus.\nexport type ProjectStatus = \"completed\" | \"in_progress\" | \"failed\";\n\n// =============================================================================\n// SDK helpers — no OpenAPI counterpart\n// =============================================================================\n\nexport interface ChatRequest {\n id: string;\n message: string;\n chat_only: boolean;\n headless: boolean;\n ai_message_id?: string;\n intent?: string;\n model?: string;\n temperature?: number;\n current_page?: string;\n view?: string;\n view_description?: string;\n prev_session_id?: string;\n is_creation?: boolean;\n files?: UnscopedFile[];\n}\n\n/** @deprecated `remixProject()` now uses POST /v1/projects with `source_project_id`. */\nexport interface RemixInitBody extends Omit<Schemas[\"V1RemixInitInputBody\"], \"initial_message\"> {\n initial_message?: ChatRequest;\n message_id?: string;\n remix_mode?: RemixMode;\n skip_integrations?: boolean;\n}\n\nexport type RemixCreateProjectBody = Schemas[\"PublicV1ProjectRemixInputBody\"];\n\nexport interface FileInput {\n name: string;\n data: Blob | ArrayBuffer | Uint8Array;\n type: string;\n}\n\nexport interface CreateProjectOptions {\n description: string;\n projectName?: string;\n techStack?: string;\n /** Sandbox runtime template. Requires a workspace with access to the requested template. */\n sandboxTemplate?: string;\n visibility?: ProjectVisibility;\n templateProjectId?: string;\n initialMessage?: string;\n /** Files to upload and attach to the initial message. The SDK handles uploading. */\n files?: (File | FileInput)[];\n /** Pre-uploaded file references to attach to the initial message. Skips upload. */\n uploadedFiles?: UnscopedFile[];\n /** Public image or HTML file URLs to fetch server-side and attach to the initial message. */\n fileUrls?: string[];\n /** Design system library projects to connect to the new project. */\n selectedLibraries?: { project_id: string }[];\n}\n\n/**\n * Controls prompt cache continuation behavior for a message.\n *\n * - `\"force\"` — skip cache TTL and token/criteria checks (force continuation)\n * - `\"fresh_build\"` — force a full prompt rebuild from scratch\n * - `\"allow_expired_cache\"` — skip cache TTL check but respect token/criteria limits\n *\n * Omit for default behavior (5-min TTL, token and criteria checks apply).\n */\nexport type ContinuationOverride = \"force\" | \"fresh_build\" | \"allow_expired_cache\";\n\nexport interface ChatMessageOptions {\n message: string;\n /** Files to upload and attach. The SDK handles uploading them first. */\n files?: (File | FileInput)[];\n /** Pre-uploaded file references. Skips upload. */\n uploadedFiles?: UnscopedFile[];\n /** Enable plan mode: the agent discusses and plans without editing code. */\n planMode?: boolean;\n /**\n * Run this turn in Max mode: the strongest model at high effort, 2.5x credits.\n * Build turns only; ignored when planMode is set. Requires the max-mode\n * feature or a Lovable-on-Lovable project; rejected with 403 otherwise.\n */\n maxMode?: boolean;\n /** @deprecated Eco-max mode has been removed; this option is ignored by the server. */\n ecoMaxMode?: boolean;\n /**\n * Override continuation behavior for this message.\n * Controls whether the agent reuses the prompt cache or rebuilds from scratch.\n */\n continuation?: ContinuationOverride;\n}\n\nexport interface CreateVariantOptions {\n /** Display name. The API assigns the next Draft number when omitted. */\n label?: string;\n /** Full 40-character commit SHA to base the variant branch on. Defaults to the project main branch. */\n baseSha?: string;\n}\n\nexport interface LovableClientOptions {\n /** API key for authentication (mutually exclusive with bearerToken) */\n apiKey?: string;\n /** Bearer token for OAuth authentication (mutually exclusive with apiKey) */\n bearerToken?: string;\n baseUrl?: string;\n /** Additional headers to include on every request */\n headers?: Record<string, string>;\n /**\n * Identifier for the originating client, sent as the `X-Client-Source` header.\n * Used by the API to tag audit logs and observability with the message origin.\n * Defaults to `\"sdk\"`. The Go API allowlist accepts `\"mcp\"`, `\"sdk\"`, `\"cli\"`.\n */\n clientSource?: string;\n}\n\nexport interface LovableError extends Error {\n status: number;\n type?: string;\n detail?: string;\n}\n\nexport interface WaitOptions {\n pollInterval?: number;\n timeout?: number;\n onProgress?: (project: ProjectResponse) => void;\n}\n\nexport interface ListCursorPaginationOptions {\n limit?: number;\n cursor?: string;\n}\n\nexport interface ListOffsetPaginationOptions {\n limit?: number;\n offset?: number;\n}\n\nexport interface ListHybridPaginationOptions {\n limit?: number;\n cursor?: string;\n offset?: number;\n}\n\nexport type ListConnectorsOptions = Omit<ListConnectorsQuery, \"workspace_id\">;\n\n/** @deprecated Use the cursor, offset, or hybrid pagination option type that matches the route. */\nexport type ListPaginationOptions = ListHybridPaginationOptions;\n\nexport type CursorPaginationOptions = ListCursorPaginationOptions;\n\nexport type RemixMode = \"before\" | \"including\";\n\nexport interface RemixProjectOptions {\n workspaceId: string;\n messageId?: string;\n remixMode?: RemixMode;\n includeHistory?: boolean;\n includeCustomKnowledge?: boolean;\n initialMessage?: string;\n description?: string;\n projectName?: string;\n skipInitialRemixMessage?: boolean;\n skipIntegrations?: boolean;\n}\n\n// camelCase wrapper — not a direct alias of V1RemixProgressResult.\nexport interface RemixResult {\n projectId: string;\n}\n\nexport interface RemixWaitOptions {\n pollInterval?: number;\n timeout?: number;\n onProgress?: (status: RemixJobStatus, step?: RemixJobStepInfo) => void;\n}\n\nexport interface MessageCompletionResult {\n status: \"completed\" | \"stopped\" | \"awaiting_input\" | \"timeout\" | \"error\";\n message_id: string;\n content: string;\n awaiting_input?: AwaitingInputSummary;\n edit_id?: string;\n commit_sha?: string;\n summary?: string;\n cost_credits?: number;\n error?: string;\n}\n\nexport interface MessageCompletionOptions {\n /** Trajectory thread returned by chat(). Enables thread-aware completion. */\n threadId?: string;\n /**\n * Maximum seconds the server holds each long-poll request before returning\n * a non-terminal snapshot. Clamped server-side to [0, 55]. Defaults to 30.\n */\n waitSeconds?: number;\n /** Maximum total time to wait in ms (default: 600000 = 10 minutes) */\n timeout?: number;\n /**\n * @deprecated Long-poll replaces client-side polling; this is ignored.\n * Kept for source-compat with callers that still pass it.\n */\n pollInterval?: number;\n}\n\nexport interface GetMessageOptions {\n /** Trajectory thread returned by chat(). Enables thread-aware status reads. */\n threadId?: string;\n /**\n * Long-poll: ask the server to hold the request until the message reaches a\n * terminal state or this many seconds elapse. Clamped server-side to [0, 55].\n */\n waitSeconds?: number;\n}\n\nexport interface ListProjectsOptions {\n /** Full-text search; mapped to `q` on the wire. */\n query?: string;\n visibility?: ListProjectsQuery[\"visibility\"];\n publish_status?: ListProjectsQuery[\"publish_status\"];\n folder_id?: ListProjectsQuery[\"folder_id\"];\n folder_ids?: ListProjectsQuery[\"folder_ids\"];\n user_id?: ListProjectsQuery[\"user_id\"];\n type?: ListProjectsQuery[\"type\"];\n search_fields?: ListProjectsQuery[\"search_fields\"];\n viewed_by_me?: ListProjectsQuery[\"viewed_by_me\"];\n cursor?: ListProjectsQuery[\"cursor\"];\n limit?: ListProjectsQuery[\"limit\"];\n}\n\n// =============================================================================\n// Runtime exports\n// =============================================================================\n\nexport interface RateLimitInfo {\n /** X-RateLimit-Limit: the request budget for the current window. */\n limit?: number;\n /** X-RateLimit-Remaining: requests left in the current window. */\n remaining?: number;\n /** Retry-After in milliseconds (parsed from the Retry-After header). */\n retryAfterMs?: number;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly type?: string;\n readonly detail?: string;\n readonly props?: Record<string, unknown>;\n readonly rateLimit?: RateLimitInfo;\n\n constructor(\n status: number,\n message: string,\n type?: string,\n detail?: string,\n props?: Record<string, unknown>,\n rateLimit?: RateLimitInfo,\n ) {\n super(message);\n this.status = status;\n this.type = type;\n this.detail = detail;\n this.props = props;\n this.rateLimit = rateLimit;\n }\n}\n","import type { Client, Middleware } from \"openapi-fetch\";\n\nimport createClient from \"openapi-fetch\";\n\nimport type { components, paths } from \"./generated/paths.js\";\n\ntype Schemas = components[\"schemas\"];\ntype CreateProjectPostBody = paths[\"/v1/projects\"][\"post\"][\"requestBody\"][\"content\"][\"application/json\"];\n\n// POST /v1/database/query is served but sits outside the public OpenAPI\n// boundary, so the generated paths omit it; this mirrors the openapi-typescript\n// operation shape for queryDatabase.\ntype DatabaseQueryCompatPaths = {\n \"/v1/database/query\": {\n parameters: { query?: never; header?: never; path?: never; cookie?: never };\n get?: never;\n put?: never;\n post: {\n parameters: { query?: never; header?: never; path?: never; cookie?: never };\n requestBody: {\n content: { \"application/json\": { project_id: string; sql: string } };\n };\n responses: {\n 200: {\n headers: { [name: string]: unknown };\n content: { \"application/json\": DatabaseQueryResult };\n };\n default: {\n headers: { [name: string]: unknown };\n content: { \"application/problem+json\": Record<string, unknown> };\n };\n };\n };\n delete?: never;\n options?: never;\n head?: never;\n patch?: never;\n trace?: never;\n };\n};\nimport type {\n LovableClientOptions,\n CreateProjectOptions,\n ChatMessageOptions,\n CreateVariantOptions,\n WaitOptions,\n ProjectResponse,\n CreateProjectResponse,\n CreateProjectBody,\n UpdateProjectOptions,\n EmbedURLResponse,\n ProjectPatchVisibility,\n DeploymentResponse,\n UnscopedFile,\n FileInput,\n RemixProjectOptions,\n RemixCreateProjectBody,\n RemixJobStatus,\n RemixResult,\n RemixWaitOptions,\n MeResponse,\n MeWorkspace,\n GetWorkspacesResponse,\n WorkspaceWithMembership,\n DatabaseStatus,\n EnableDatabaseResult,\n DatabaseQueryResult,\n SendMessageResponse,\n GetMessageResponse,\n ListMessagesResponse,\n ListMessagesOptions,\n ChatResponse,\n ChatResponseOptions,\n CreateVariantResponse,\n MessageCompletionResult,\n MessageCompletionOptions,\n GetMessageOptions,\n KnowledgeResponse,\n FileUploadUrlResponse,\n GitDiffResponse,\n GitFilesResponse,\n EditsResponse,\n ListProjectsResponse,\n ListProjectsOptions,\n ListConnectorsOptions,\n ListCursorPaginationOptions,\n ListHybridPaginationOptions,\n ListOffsetPaginationOptions,\n CursorPaginationOptions,\n MoveProjectsToFolderResponse,\n ListConnectorsResponse,\n ListStandardConnectorsResponse,\n ListSeamlessConnectorsResponse,\n ListMCPConnectorsResponse,\n ProjectAnalyticsResponse,\n ProjectAnalyticsTrendResponse,\n ListLibraryProjectsResponse,\n ListTemplateProjectsResponse,\n ListWorkspaceSkillsResponse,\n WorkspaceSkillResponse,\n WorkspaceSkillWriteResponse,\n WorkspaceSkillDeleteResponse,\n ListProjectSkillsResponse,\n ProjectSkillResponse,\n RateLimitInfo,\n} from \"./types.js\";\n\nimport { makeRetryFetch } from \"./retryFetch.js\";\nimport { ApiError } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.lovable.dev\";\nconst PUBLIC_API_CURSOR_VERSION = 1;\n\nfunction normalizeBaseUrl(url: string | undefined): string {\n if (!url) return DEFAULT_BASE_URL;\n\n const normalized = url.replace(/\\/$/, \"\");\n\n if (!normalized.startsWith(\"http://\") && !normalized.startsWith(\"https://\")) {\n throw new Error(`baseUrl must include a protocol (http:// or https://). Got: \"${url}\"`);\n }\n\n return normalized;\n}\n\nfunction encodePublicCursor(id: string): string {\n const raw = JSON.stringify({ v: PUBLIC_API_CURSOR_VERSION, id });\n const bytes = new TextEncoder().encode(raw);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction normalizeWorkspaceList<T>(body: { data?: T[] | null; workspaces?: T[] | null }): T[] {\n return body.data ?? body.workspaces ?? [];\n}\n\nfunction cursorHasMore(body: { pagination?: { has_more?: boolean } | null; has_more?: boolean }): boolean {\n return body.pagination?.has_more ?? body.has_more ?? false;\n}\n\nfunction requireCreateProjectId<T extends { id?: string }>(project: T): T & { id: string } {\n if (!project.id) throw new Error(\"Create project response missing project ID\");\n return project as T & { id: string };\n}\n\n/**\n * openapi-fetch middleware that converts non-2xx Response objects into the\n * SDK's ApiError, preserving the existing error contract (status/type/detail/\n * props) used by every other method in this client.\n */\nconst errorMiddleware: Middleware = {\n async onResponse({ response }) {\n if (response.ok) return;\n let errorBody:\n | {\n type?: string;\n title?: string;\n message?: string;\n detail?: string;\n details?: string;\n props?: Record<string, unknown>;\n }\n | undefined;\n try {\n errorBody = (await response.clone().json()) as typeof errorBody;\n } catch {\n // Ignore JSON parse errors\n }\n const message = buildErrorMessage(errorBody, response.status, response.statusText);\n const type = errorBody?.type ?? errorBody?.title;\n const detail = errorBody?.detail ?? errorBody?.details;\n throw new ApiError(response.status, message, type, detail, errorBody?.props, parseRateLimitInfo(response.headers));\n },\n};\n\nfunction parseRateLimitInfo(headers: Headers): RateLimitInfo | undefined {\n const limit = parsePositiveInt(headers.get(\"x-ratelimit-limit\"));\n const remaining = parsePositiveInt(headers.get(\"x-ratelimit-remaining\"));\n const retryAfterMs = parseRetryAfterMs(headers.get(\"retry-after\"));\n if (limit == null && remaining == null && retryAfterMs == null) return undefined;\n return { limit, remaining, retryAfterMs };\n}\n\nfunction parsePositiveInt(raw: string | null): number | undefined {\n if (raw == null) return undefined;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : undefined;\n}\n\nfunction parseRetryAfterMs(raw: string | null): number | undefined {\n if (!raw) return undefined;\n const seconds = Number(raw);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n const dateMs = Date.parse(raw);\n if (!Number.isNaN(dateMs)) {\n const delta = dateMs - Date.now();\n return delta > 0 ? delta : 0;\n }\n return undefined;\n}\n\n// HTTP/2 leaves response.statusText empty, and some Go API endpoints return\n// `{message: \"\"}` / `{title: \"\"}` bodies on errors. `??` would preserve the\n// empty string and produce an ApiError with no usable message; consumers\n// downstream (MCP, logs, UI) then render an unlabeled failure.\nfunction buildErrorMessage(\n body: { message?: string; title?: string } | undefined,\n status: number,\n statusText: string,\n): string {\n return body?.message || body?.title || (statusText ? `HTTP ${status}: ${statusText}` : `HTTP ${status}`);\n}\n\nexport class LovableClient {\n private readonly authHeaders: Record<string, string>;\n private readonly baseUrl: string;\n private readonly extraHeaders: Record<string, string>;\n private readonly clientSource: string;\n private readonly typedClient: Client<paths>;\n\n constructor(options: LovableClientOptions) {\n const hasApiKey = !!options.apiKey;\n const hasBearerToken = !!options.bearerToken;\n\n if (!hasApiKey && !hasBearerToken) {\n throw new Error(\"Either apiKey or bearerToken is required\");\n }\n if (hasApiKey && hasBearerToken) {\n throw new Error(\"Provide either apiKey or bearerToken, not both\");\n }\n\n this.authHeaders = hasApiKey\n ? { \"Lovable-API-Key\": options.apiKey! }\n : { Authorization: `Bearer ${options.bearerToken}` };\n\n this.baseUrl = normalizeBaseUrl(options.baseUrl);\n this.extraHeaders = options.headers ?? {};\n this.clientSource = options.clientSource ?? \"sdk\";\n\n this.typedClient = createClient<paths>({\n baseUrl: this.baseUrl,\n headers: {\n \"X-Client-Source\": this.clientSource,\n ...this.authHeaders,\n ...this.extraHeaders,\n Accept: \"application/json\",\n },\n fetch: makeRetryFetch(),\n });\n this.typedClient.use(errorMiddleware);\n }\n\n /**\n * Type-safe access to any documented API route, driven by the auto-generated\n * OpenAPI schema. Path / query params and request bodies are checked at compile\n * time; calling an unknown path is a type error.\n *\n * Non-2xx responses throw `ApiError`; on success, `data` is set on the result.\n */\n get typed(): Client<paths> {\n return this.typedClient;\n }\n\n /**\n * Get the current authenticated user and their workspaces.\n * Useful for validating an API key and discovering workspace IDs.\n */\n async me(): Promise<MeResponse> {\n const { data } = await this.typed.GET(\"/v1/me\");\n return {\n ...data!,\n workspaces: normalizeWorkspaceList<MeWorkspace>(\n data! as { data?: MeWorkspace[] | null; workspaces?: MeWorkspace[] | null },\n ),\n };\n }\n\n /**\n * List workspaces the authenticated user has access to.\n */\n async listWorkspaces(options: ListHybridPaginationOptions = {}): Promise<GetWorkspacesResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces\", {\n params: { query: options },\n });\n return { ...data!, workspaces: normalizeWorkspaceList<WorkspaceWithMembership>(data!) };\n }\n\n /**\n * Get a specific workspace by ID\n */\n async getWorkspace(workspaceId: string) {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}\", {\n params: { path: { workspace_id: workspaceId } },\n });\n return data!.workspace;\n }\n\n /**\n * List projects in a workspace.\n * Supports full-text search, filtering by visibility/publish status/folder/creator,\n * and cursor pagination.\n */\n async listProjects(workspaceId: string, options?: ListProjectsOptions): Promise<ListProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/projects\", {\n params: {\n query: {\n workspace_id: workspaceId,\n q: options?.query,\n visibility: options?.visibility,\n publish_status: options?.publish_status,\n folder_id: options?.folder_id,\n folder_ids: options?.folder_ids,\n user_id: options?.user_id,\n type: options?.type,\n search_fields: options?.search_fields,\n viewed_by_me: options?.viewed_by_me,\n cursor: options?.cursor,\n limit: options?.limit,\n },\n },\n });\n const projects =\n (data as unknown as { projects?: ListProjectsResponse[\"projects\"] }).projects ?? data!.data ?? null;\n const total = (data as unknown as { total?: number }).total;\n return {\n ...data!,\n projects,\n ...(total === undefined ? {} : { total }),\n has_more: data!.pagination?.has_more ?? (data as unknown as { has_more?: boolean }).has_more,\n };\n }\n\n /**\n * Create a new project in a workspace\n */\n async createProject(workspaceId: string, options: CreateProjectOptions): Promise<CreateProjectResponse> {\n let fileRefs: UnscopedFile[] | undefined;\n let ephemeralFileRefs: UnscopedFile[] | undefined;\n if (options.uploadedFiles?.length) {\n ({ fileRefs, ephemeralFileRefs } = this.partitionUploadedFiles(options.uploadedFiles));\n } else if (options.files?.length) {\n ephemeralFileRefs = await this.uploadEphemeralFiles(options.files);\n }\n\n const body: CreateProjectBody = {\n description: options.description,\n template_project_id: options.templateProjectId,\n };\n if (options.projectName) {\n body.display_name = options.projectName;\n }\n if (options.visibility) {\n body.visibility = options.visibility;\n }\n if (options.techStack) {\n body.tech_stack = options.techStack;\n }\n if (options.sandboxTemplate) {\n body.sandbox_template = options.sandboxTemplate;\n }\n if (options.selectedLibraries?.length) {\n body.selected_libraries = options.selectedLibraries;\n }\n if (options.initialMessage) {\n body.initial_message = options.initialMessage;\n }\n if (fileRefs?.length) {\n body.files = fileRefs;\n }\n if (options.fileUrls?.length) {\n body.file_urls = options.fileUrls;\n }\n if (ephemeralFileRefs?.length) {\n body.ephemeral_files = ephemeralFileRefs;\n }\n\n const { data } = await this.typed.POST(\"/v1/projects\", {\n body: { ...body, workspace_id: workspaceId },\n });\n return requireCreateProjectId(data!);\n }\n\n /**\n * Send a chat message to a project.\n *\n * The API accepts the message and processes it in the background.\n * Returns the message ID and status. Use `waitForMessageCompletion()`\n * to poll for the AI response.\n */\n async chat(projectId: string, options: ChatMessageOptions): Promise<SendMessageResponse> {\n let fileRefs: UnscopedFile[] | undefined;\n let ephemeralFileRefs: UnscopedFile[] | undefined;\n if (options.uploadedFiles?.length) {\n ({ fileRefs, ephemeralFileRefs } = this.partitionUploadedFiles(options.uploadedFiles));\n } else if (options.files?.length) {\n fileRefs = await this.uploadProjectFiles(projectId, options.files);\n }\n\n const body: Omit<Schemas[\"PublicV1SendMessageInputBody\"], \"project_id\"> & {\n max_mode?: boolean;\n } = {\n message: options.message,\n };\n if (fileRefs) {\n body.files = fileRefs;\n }\n if (ephemeralFileRefs) {\n body.ephemeral_files = ephemeralFileRefs;\n }\n if (options.planMode) {\n body.plan_mode = true;\n }\n if (options.maxMode) {\n body.max_mode = true;\n }\n if (options.continuation) {\n body.continuation = options.continuation;\n }\n\n const { data } = await this.typed.POST(\"/v1/messages\", {\n body: { ...body, project_id: projectId },\n });\n return data!;\n }\n\n /**\n * Create an independent variant from the project's current main branch, or from a full baseSha when provided.\n */\n async createVariant(projectId: string, options: CreateVariantOptions = {}): Promise<CreateVariantResponse> {\n const { data } = await this.typed.POST(\"/v1/projects/{project_id}/variants\", {\n params: { path: { project_id: projectId } },\n body: { label: options.label, base_sha: options.baseSha },\n });\n return data!;\n }\n\n /**\n * Get project details by ID\n */\n async getProject(projectId: string): Promise<ProjectResponse> {\n const { data } = await this.typed.GET(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Create an anonymous, one-hour static preview URL for one exact HTTPS parent origin.\n */\n async createEmbedUrl(projectId: string, parentOrigin: string): Promise<EmbedURLResponse> {\n const { data } = await this.typed.POST(\"/v1/projects/{project_id}/embed-url\", {\n params: { path: { project_id: projectId } },\n body: { parent_origin: parentOrigin },\n });\n return data!;\n }\n\n /**\n * Update supported project fields.\n */\n async updateProject(projectId: string, options: UpdateProjectOptions): Promise<ProjectResponse> {\n const { data } = await this.typed.PATCH(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n body: options,\n });\n return data!;\n }\n\n /**\n * Soft-delete a project. Repeated deletes are treated as successful.\n */\n async deleteProject(projectId: string): Promise<void> {\n await this.typed.DELETE(\"/v1/projects/{project_id}\", {\n params: { path: { project_id: projectId } },\n });\n }\n\n /**\n * Get the preview URL for a project.\n *\n * The preview URL is available once the project reaches \"completed\" status.\n * This URL allows viewing the project in development mode.\n *\n * @param projectId - The project ID\n * @returns The preview URL\n */\n getPreviewUrl(projectId: string): string {\n return `https://id-preview--${projectId}.lovable.app`;\n }\n\n /**\n * Get the published URL for a project (if published).\n *\n * Returns the public URL if the project has been published, or null if not.\n *\n * @param projectId - The project ID\n * @returns The published URL or null if not published\n */\n async getPublishedUrl(projectId: string): Promise<string | null> {\n const project = await this.getProject(projectId);\n return project.is_published && project.url ? project.url : null;\n }\n\n /**\n * Get the cloud database status for a project.\n *\n * @param projectId - The project ID\n * @returns Whether the database is enabled and which stack is used\n */\n async getDatabaseStatus(projectId: string): Promise<DatabaseStatus> {\n const { data } = await this.typed.GET(\"/v1/database\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Enable (provision) a cloud database for a project.\n *\n * This triggers database provisioning which takes 30-60 seconds.\n * The call blocks until provisioning completes.\n *\n * @param projectId - The project ID\n * @returns The database status after enablement\n */\n async enableDatabase(projectId: string): Promise<EnableDatabaseResult> {\n const { data } = await this.typed.POST(\"/v1/database/enable\", {\n body: { project_id: projectId },\n });\n return data!;\n }\n\n /**\n * Execute a SQL query against the project's cloud database.\n *\n * Supports SELECT, INSERT, UPDATE, DELETE, and DDL statements.\n * The database must be enabled first (see enableDatabase).\n *\n * @param projectId - The project ID\n * @param sql - SQL query to execute\n * @returns Query result rows as JSON objects\n */\n async queryDatabase(projectId: string, sql: string): Promise<DatabaseQueryResult> {\n // The route sits outside the public OpenAPI boundary, so the generated\n // paths lack it; DatabaseQueryCompatPaths stands in for the generated shape.\n const compat = this.typedClient as unknown as Client<DatabaseQueryCompatPaths>;\n const { data } = await compat.POST(\"/v1/database/query\", {\n body: { project_id: projectId, sql },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Messages\n // ---------------------------------------------------------------------------\n\n /**\n * Get a message by ID. Returns the message content, status, and (for user messages)\n * the AI response if available.\n *\n * Pass `waitSeconds` to long-poll: the server holds the request until the\n * message reaches a terminal state (completed / stopped / error / awaiting_input) or the\n * duration elapses. This replaces client-side polling for `waitForMessageCompletion`.\n */\n async getMessage(projectId: string, messageId: string, options?: GetMessageOptions): Promise<GetMessageResponse> {\n const waitSeconds = options?.waitSeconds;\n const query = {\n wait: waitSeconds && waitSeconds > 0 ? `${Math.floor(waitSeconds)}s` : undefined,\n thread_id: options?.threadId,\n };\n const { data } = await this.typed.GET(\"/v1/messages/{message_id}\", {\n params: { path: { message_id: messageId }, query: { ...query, project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * List recent messages in a project, newest first. Use `cursor` from the\n * previous page's `pagination.next_cursor` to paginate through history.\n */\n async listMessages(projectId: string, params?: ListMessagesOptions): Promise<ListMessagesResponse> {\n const cursor = params?.cursor ?? (params?.before ? encodePublicCursor(params.before) : undefined);\n const { data } = await this.typed.GET(\"/v1/messages\", {\n params: {\n query: { project_id: projectId, limit: params?.limit, cursor },\n },\n });\n return {\n ...data!,\n messages: data!.data,\n has_more: cursorHasMore(data!),\n };\n }\n\n /**\n * Wait for the AI response to reach a terminal status (completed, stopped, error, awaiting_input)\n * or for `timeout` to elapse.\n *\n * Primary path is SSE against `/v1/messages/{message_id}/stream`: one\n * held connection that pushes a snapshot on every relevant change and closes\n * on terminal. If SSE isn't reachable (proxy strips text/event-stream, server\n * returns 404 / 415 / 501) we fall back to the long-poll JSON endpoint on the\n * same URL. Both paths share the same `MessageCompletionResult` shape.\n */\n async waitForMessageCompletion(\n projectId: string,\n messageId: string,\n options?: MessageCompletionOptions,\n ): Promise<MessageCompletionResult> {\n const timeout = options?.timeout ?? 600_000;\n const deadline = Date.now() + timeout;\n\n const sse = await this.waitForMessageCompletionViaSSE(projectId, messageId, deadline, options?.threadId);\n if (sse.kind === \"result\") {\n return sse.result;\n }\n if (Date.now() >= deadline) {\n return timeoutResult(messageId, timeout);\n }\n return this.waitForMessageCompletionViaLongPoll(projectId, messageId, deadline, timeout, options);\n }\n\n /**\n * @deprecated Use `chat()` or `createProject()`'s returned `message_id`,\n * then call `waitForMessageCompletion(projectId, messageId)`.\n *\n * Throws when the turn pauses for human input (`awaiting_input`) — the\n * legacy `ChatResponse` shape cannot carry resume metadata. HITL-capable\n * flows need `waitForMessageCompletion` plus `respondToTool`.\n */\n async waitForResponse(projectId: string, options?: ChatResponseOptions): Promise<ChatResponse> {\n const messages = await this.listMessages(projectId, { limit: 10 });\n const latest = messages.messages?.find((message) => message.role === \"user\");\n\n if (!latest?.message_id) {\n throw new Error(`No messages found for project ${projectId}`);\n }\n\n const completionOptions = options?.timeout === undefined ? undefined : { timeout: options.timeout };\n const result = await this.waitForMessageCompletion(projectId, latest.message_id, completionOptions);\n // Preserve the pre-deprecation contract: throw on failure. waitForMessageCompletion\n // returns (never throws) on timeout/error, so without this a timed-out or errored run\n // looks like a successful empty response to try/catch callers.\n if (result.status !== \"completed\" && result.status !== \"stopped\") {\n throw new Error(result.error ?? `Message ${latest.message_id} did not complete (status: ${result.status})`);\n }\n return {\n content: result.content,\n messageId: result.message_id,\n previewUrl: this.getPreviewUrl(projectId),\n };\n }\n\n private async waitForMessageCompletionViaSSE(\n projectId: string,\n messageId: string,\n deadline: number,\n threadId?: string,\n ): Promise<{ kind: \"result\"; result: MessageCompletionResult } | { kind: \"fallback\" } | { kind: \"timeout\" }> {\n const remaining = deadline - Date.now();\n if (remaining <= 0) return { kind: \"timeout\" };\n\n const url = new URL(`${this.baseUrl}/v1/messages/${encodeURIComponent(messageId)}/stream`);\n url.searchParams.set(\"project_id\", projectId);\n if (threadId) {\n url.searchParams.set(\"thread_id\", threadId);\n }\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), remaining);\n\n let response: Response;\n try {\n response = await fetch(url, {\n headers: {\n ...this.authHeaders,\n ...this.extraHeaders,\n \"X-Client-Source\": this.clientSource,\n Accept: \"text/event-stream\",\n },\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timeoutId);\n if (isAbortError(err)) return { kind: \"timeout\" };\n return { kind: \"fallback\" };\n }\n\n if (!response.ok) {\n clearTimeout(timeoutId);\n if (response.status === 404 || response.status === 415 || response.status === 501) {\n await cancelResponseBody(response);\n return { kind: \"fallback\" };\n }\n if (response.status >= 500) {\n await cancelResponseBody(response);\n return { kind: \"fallback\" };\n }\n const detail = await safeReadText(response);\n throw new ApiError(response.status, detail || `HTTP ${response.status}`);\n }\n\n if (!response.body) {\n clearTimeout(timeoutId);\n return { kind: \"fallback\" };\n }\n\n try {\n for await (const frame of parseSSEFrames(response.body)) {\n if (!frame.data) continue;\n let snapshot: GetMessageResponse;\n try {\n snapshot = JSON.parse(frame.data) as GetMessageResponse;\n } catch {\n continue;\n }\n\n const queuedResult = queuedExitResult(snapshot, messageId);\n if (queuedResult) return { kind: \"result\", result: queuedResult };\n\n const terminal = terminalResultFromMessage(snapshot, messageId);\n if (terminal) {\n return { kind: \"result\", result: terminal };\n }\n }\n return { kind: \"fallback\" };\n } catch (err) {\n if (isAbortError(err)) return { kind: \"timeout\" };\n return { kind: \"fallback\" };\n } finally {\n clearTimeout(timeoutId);\n controller.abort();\n }\n }\n\n private async waitForMessageCompletionViaLongPoll(\n projectId: string,\n messageId: string,\n deadline: number,\n totalTimeoutMs: number,\n options?: MessageCompletionOptions,\n ): Promise<MessageCompletionResult> {\n const waitSeconds = Math.max(1, Math.min(55, options?.waitSeconds ?? 30));\n const transientBackoffMs = 1000;\n let notFoundSince: number | null = null;\n const notFoundGraceMs = 15_000;\n\n while (Date.now() < deadline) {\n const remainingMs = deadline - Date.now();\n const perCallSeconds = Math.min(waitSeconds, Math.floor(remainingMs / 1000));\n const waitOptions = perCallSeconds > 0 ? { waitSeconds: perCallSeconds } : undefined;\n\n const callStartedAt = Date.now();\n try {\n const msg = await this.getMessage(projectId, messageId, { ...waitOptions, threadId: options?.threadId });\n notFoundSince = null;\n\n const queuedResult = queuedExitResult(msg, messageId);\n if (queuedResult) return queuedResult;\n\n const terminal = terminalResultFromMessage(msg, messageId);\n if (terminal) return terminal;\n\n // Server returned a non-terminal snapshot far faster than the wait\n // window it was given. That happens when the streamer is nil or its\n // subscription fails server-side, or for queued messages that have no\n // stream events yet. Backoff so we don't tight-loop until the deadline.\n if (Date.now() - callStartedAt < transientBackoffMs) {\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n }\n } catch (err) {\n if (err instanceof ApiError) {\n if (err.status === 404) {\n if (notFoundSince === null) {\n notFoundSince = Date.now();\n }\n if (Date.now() - notFoundSince < notFoundGraceMs) {\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n continue;\n }\n return {\n status: \"error\",\n message_id: messageId,\n content: \"\",\n error: \"Message not found. It may have been deleted from the queue.\",\n };\n }\n if (err.status < 500) {\n throw err;\n }\n }\n await sleep(Math.min(transientBackoffMs, Math.max(0, deadline - Date.now())));\n }\n }\n\n return timeoutResult(messageId, totalTimeoutMs);\n }\n\n // ---------------------------------------------------------------------------\n // Knowledge\n // ---------------------------------------------------------------------------\n\n /** Get workspace knowledge (custom instructions for the AI agent). */\n async getWorkspaceKnowledge(workspaceId: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/knowledge\", {\n params: { path: { workspace_id: workspaceId } },\n });\n return data!;\n }\n\n /** Set workspace knowledge. Max 10,000 characters. */\n async setWorkspaceKnowledge(workspaceId: string, content: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/knowledge\", {\n params: { path: { workspace_id: workspaceId } },\n body: { content },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Workspace skills\n // ---------------------------------------------------------------------------\n\n /** List workspace skills. */\n async listWorkspaceSkills(\n workspaceId: string,\n options: { includeMarkdown?: boolean } & ListOffsetPaginationOptions = {},\n ): Promise<ListWorkspaceSkillsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/skills\", {\n params: {\n path: { workspace_id: workspaceId },\n query: { include_markdown: options.includeMarkdown, limit: options.limit, offset: options.offset },\n },\n });\n return { ...data!, skills: data!.skills ?? [] };\n }\n\n /** Get a single workspace skill, including SKILL.md contents. */\n async getWorkspaceSkill(workspaceId: string, skillName: string): Promise<WorkspaceSkillResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n });\n return data!;\n }\n\n /** Create a workspace skill from full SKILL.md markdown. */\n async createWorkspaceSkill(\n workspaceId: string,\n skillName: string,\n markdown: string,\n ): Promise<WorkspaceSkillWriteResponse> {\n const { data } = await this.typed.POST(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n body: { markdown },\n });\n return data!;\n }\n\n /** Update a workspace skill by replacing its SKILL.md markdown. */\n async updateWorkspaceSkill(\n workspaceId: string,\n skillName: string,\n markdown: string,\n ): Promise<WorkspaceSkillWriteResponse> {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n body: { markdown },\n });\n return data!;\n }\n\n /** Delete a workspace skill. */\n async deleteWorkspaceSkill(workspaceId: string, skillName: string): Promise<WorkspaceSkillDeleteResponse> {\n const { data } = await this.typed.DELETE(\"/v1/workspaces/{workspace_id}/skills/{skill_name}\", {\n params: { path: { workspace_id: workspaceId, skill_name: skillName } },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Project skills\n // ---------------------------------------------------------------------------\n\n /** List project skills, including whether each skill is enabled. */\n async listProjectSkills(\n projectId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListProjectSkillsResponse> {\n const { data } = await this.typed.GET(\"/v1/skills\", {\n params: { query: { project_id: projectId, limit: options.limit, cursor: options.cursor } },\n });\n const skills = (data as unknown as { skills?: ListProjectSkillsResponse[\"skills\"] }).skills ?? data!.data ?? [];\n return { ...data!, skills };\n }\n\n /** Enable or disable a project skill without removing it from the project repo. */\n async setProjectSkillEnabled(projectId: string, skillName: string, enabled: boolean): Promise<ProjectSkillResponse> {\n const { data } = await this.typed.PATCH(\"/v1/skills/{skill_name}\", {\n params: { path: { skill_name: skillName } },\n body: { project_id: projectId, enabled },\n });\n return data!;\n }\n\n /** Get project knowledge (custom instructions for the AI agent). */\n async getProjectKnowledge(projectId: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.GET(\"/v1/knowledge\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /** Set project knowledge. Max 10,000 characters. */\n async setProjectKnowledge(projectId: string, content: string): Promise<KnowledgeResponse> {\n const { data } = await this.typed.PUT(\"/v1/knowledge\", {\n body: { project_id: projectId, content },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Git operations\n // ---------------------------------------------------------------------------\n\n /**\n * Get the structured diff for a message or commit.\n * Pass `messageId` to get the diff for a specific AI message,\n * or `sha` for a specific commit.\n */\n async getDiff(\n projectId: string,\n params: { messageId?: string; sha?: string; baseSha?: string },\n ): Promise<GitDiffResponse> {\n const { data } = await this.typed.GET(\"/v1/git/diff\", {\n params: {\n query: { project_id: projectId, message_id: params.messageId, sha: params.sha, base_sha: params.baseSha },\n },\n });\n return data!;\n }\n\n /** List files in a project. Omitting ref uses the API default. */\n async listFiles(projectId: string, ref?: string, options?: CursorPaginationOptions): Promise<GitFilesResponse>;\n async listFiles(projectId: string, options?: CursorPaginationOptions): Promise<GitFilesResponse>;\n async listFiles(\n projectId: string,\n refOrOptions?: string | CursorPaginationOptions,\n options: CursorPaginationOptions = {},\n ): Promise<GitFilesResponse> {\n const ref = typeof refOrOptions === \"string\" ? refOrOptions : undefined;\n const pagination = typeof refOrOptions === \"string\" ? options : (refOrOptions ?? options);\n const { data } = await this.typed.GET(\"/v1/git/files\", {\n params: { query: { project_id: projectId, ref, limit: pagination.limit, cursor: pagination.cursor } },\n });\n const files = data!.data ?? [];\n return { ...data!, data: files, files };\n }\n\n /** Read the raw content of a single file. Omitting ref uses the API default. */\n async readFile(projectId: string, path: string, ref?: string): Promise<string> {\n // The Go OpenAPI annotation for this route declares 200 as `content?: never`\n // even though the handler returns the raw file text. `parseAs: \"text\"` makes\n // openapi-fetch read the body as text at runtime; the cast covers the spec\n // gap. Drop the cast once the Go annotation declares text/plain content.\n const { data } = await this.typed.GET(\"/v1/git/files/{path}\", {\n params: { path: { path }, query: { project_id: projectId, ref } },\n parseAs: \"text\",\n });\n return data as unknown as string;\n }\n\n // ---------------------------------------------------------------------------\n // Edits\n // ---------------------------------------------------------------------------\n\n /** List the edit history of a project. */\n async listEdits(\n projectId: string,\n params?: { limit?: number; before?: string; cursor?: string },\n ): Promise<EditsResponse> {\n const { data } = await this.typed.GET(\"/v1/edits\", {\n params: {\n query: {\n project_id: projectId,\n limit: params?.limit,\n before: params?.before,\n cursor: params?.cursor,\n },\n },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // File upload\n // ---------------------------------------------------------------------------\n\n /** Get an ephemeral presigned URL for uploading a file before a project exists. */\n async getFileUploadUrl(params: { file_name: string; content_type?: string }): Promise<FileUploadUrlResponse> {\n return this.getEphemeralFileUploadUrl({ content_type: params.content_type });\n }\n\n /** Get a project-scoped presigned URL for uploading a file. Returns the upload URL, file ID, and required PUT headers. */\n async getProjectFileUploadUrl(projectId: string, params: { content_type?: string }): Promise<FileUploadUrlResponse> {\n const { data } = await this.typed.POST(\"/v1/project-files/upload-url\", {\n body: { project_id: projectId, ...params },\n });\n return data!;\n }\n\n /** Get an ephemeral presigned URL for uploading a file before a project exists. */\n async getEphemeralFileUploadUrl(params: { content_type?: string }): Promise<FileUploadUrlResponse> {\n const { data } = await this.typed.POST(\"/v1/files/ephemeral-upload-url\", { body: params });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Visibility\n // ---------------------------------------------------------------------------\n\n /** Set a project's visibility (draft, private, workspace_view, or public). */\n async setProjectVisibility(projectId: string, visibility: ProjectPatchVisibility): Promise<ProjectResponse> {\n return this.updateProject(projectId, { visibility });\n }\n\n /** Set a folder's visibility (personal or workspace). */\n async setFolderVisibility(workspaceId: string, folderId: string, visibility: \"personal\" | \"workspace\") {\n const { data } = await this.typed.PUT(\"/v1/workspaces/{workspace_id}/folders/{folder_id}/visibility\", {\n params: { path: { workspace_id: workspaceId, folder_id: folderId } },\n body: { visibility },\n });\n return data!;\n }\n\n /** Move projects into a folder, removing existing folder memberships first. */\n async moveProjectsToFolder(\n workspaceId: string,\n folderId: string,\n projectIds: string[],\n ): Promise<MoveProjectsToFolderResponse> {\n const { data } = await this.typed.POST(\"/v1/workspaces/{workspace_id}/folders/{folder_id}/projects/move\", {\n params: { path: { workspace_id: workspaceId, folder_id: folderId } },\n body: { project_ids: projectIds },\n });\n return data!;\n }\n\n // ---------------------------------------------------------------------------\n // Library & template projects\n // ---------------------------------------------------------------------------\n\n /** List available design system library projects in a workspace. */\n async listLibraryProjects(\n workspaceId: string,\n options: ListOffsetPaginationOptions = {},\n ): Promise<ListLibraryProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/available-library-projects\", {\n params: { path: { workspace_id: workspaceId }, query: options },\n });\n return { ...data!, libraries: data!.libraries ?? [] };\n }\n\n /** List available template projects in a workspace. */\n async listTemplateProjects(\n workspaceId: string,\n options: ListOffsetPaginationOptions = {},\n ): Promise<ListTemplateProjectsResponse> {\n const { data } = await this.typed.GET(\"/v1/workspaces/{workspace_id}/available-template-projects\", {\n params: { path: { workspace_id: workspaceId }, query: options },\n });\n return { ...data!, templates: data!.templates ?? [] };\n }\n\n // ---------------------------------------------------------------------------\n // Connectors (MCP servers)\n // ---------------------------------------------------------------------------\n\n /** List all connectors in a workspace. */\n async listConnectors(workspaceId: string, options: ListConnectorsOptions = {}): Promise<ListConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: {\n query: {\n workspace_id: workspaceId,\n type: options.type,\n status: options.status,\n limit: options.limit,\n cursor: options.cursor,\n },\n },\n });\n const connectors =\n (data as unknown as { connectors?: ListConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n // ---------------------------------------------------------------------------\n // Connectors\n // ---------------------------------------------------------------------------\n\n /** List standard (OAuth-based) connectors in a workspace. */\n async listStandardConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListStandardConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"standard\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListStandardConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n /** List seamless (zero-config) connectors in a workspace. */\n async listSeamlessConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListSeamlessConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"seamless\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListSeamlessConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n /** List MCP connectors in a workspace. */\n async listMCPConnectors(\n workspaceId: string,\n options: ListCursorPaginationOptions = {},\n ): Promise<ListMCPConnectorsResponse> {\n const { data } = await this.typed.GET(\"/v1/connectors\", {\n params: { query: { workspace_id: workspaceId, type: \"mcp\", limit: options.limit, cursor: options.cursor } },\n });\n const connectors =\n (data as unknown as { connectors?: ListMCPConnectorsResponse[\"connectors\"] }).connectors ?? data!.data ?? [];\n return { ...data!, data: connectors, connectors, has_more: cursorHasMore(data!) };\n }\n\n // ---------------------------------------------------------------------------\n // Analytics\n // ---------------------------------------------------------------------------\n\n /** Get historical analytics for a published project. */\n async getProjectAnalytics(\n projectId: string,\n params: { startDate: string; endDate: string; granularity?: string },\n ): Promise<ProjectAnalyticsResponse> {\n const { data } = await this.typed.GET(\"/v1/analytics\", {\n params: {\n query: {\n project_id: projectId,\n startDate: params.startDate,\n endDate: params.endDate,\n granularity: params.granularity,\n },\n },\n });\n return data!;\n }\n\n /** Get real-time visitor trend for a published project. */\n async getProjectAnalyticsTrend(projectId: string): Promise<ProjectAnalyticsTrendResponse> {\n const { data } = await this.typed.GET(\"/v1/analytics/trend\", {\n params: { query: { project_id: projectId } },\n });\n return data!;\n }\n\n /**\n * Publish a project.\n *\n * This triggers a deployment which makes the project publicly accessible.\n * The deployment runs asynchronously - use waitForProjectPublished() to wait for completion.\n *\n * @param projectId - The project ID to publish\n * @param options.name - Optional custom slug for the published URL\n * @returns Deployment info including deployment ID\n */\n async publish(projectId: string, options?: { name?: string }): Promise<DeploymentResponse> {\n const { data } = await this.typed.POST(\"/v1/deployments\", {\n body: { project_id: projectId, name: options?.name },\n });\n return data!;\n }\n\n /**\n * Remix (fork) an existing project, optionally at a specific message point in time.\n *\n * When `messageId` is provided, the remix captures the project state after\n * that message and its AI response by default. Set `remixMode: \"before\"` to\n * start before the message was processed.\n * Without `messageId`, the full current state is remixed.\n *\n * @param sourceProjectId - The project to remix from\n * @param options.workspaceId - Target workspace for the new project\n * @param options.messageId - Optional message ID to snapshot at\n * @param options.remixMode - \"including\" (server default): state after the message and its AI response; \"before\": state before the message\n * @param options.includeHistory - Whether to preserve chat history (default: false)\n * @param options.includeCustomKnowledge - Whether to copy custom instructions (default: false)\n * @param options.initialMessage - Optional initial message to send after remix\n * @param options.description - Optional custom description for the new project\n * @returns The remix job ID for polling progress\n */\n async remixProject(sourceProjectId: string, options: RemixProjectOptions): Promise<string> {\n const body: RemixCreateProjectBody = {\n workspace_id: options.workspaceId,\n source_project_id: sourceProjectId,\n include_history: options.includeHistory,\n include_custom_knowledge: options.includeCustomKnowledge,\n description: options.description,\n display_name: options.projectName,\n skip_initial_remix_message: options.skipInitialRemixMessage,\n skip_integrations: options.skipIntegrations,\n };\n\n if (options.messageId) {\n body.message_id = options.messageId;\n if (options.remixMode) {\n body.remix_mode = options.remixMode;\n }\n }\n\n if (options.initialMessage) {\n body.initial_message = options.initialMessage;\n }\n\n const { data } = await this.typed.POST(\"/v1/projects\", {\n body: body as CreateProjectPostBody,\n });\n const remix = data;\n if (!remix?.job_id) {\n throw new Error(\"Failed to get job ID from remix create\");\n }\n return remix.job_id;\n }\n\n /**\n * Wait for a remix operation to complete.\n *\n * Polls the remix progress endpoint until the job reaches \"completed\" or \"error\" status.\n *\n * @param sourceProjectId - The source project ID (used for the progress endpoint)\n * @param jobId - The job ID returned by `remixProject()`\n * @param options.pollInterval - Time between polls in ms (default: 2000)\n * @param options.timeout - Maximum time to wait in ms (default: 300000 = 5 minutes)\n * @param options.onProgress - Optional callback for status/step updates\n * @returns The new project ID\n * @throws Error if the remix fails or timeout is reached\n */\n async waitForRemix(sourceProjectId: string, jobId: string, options?: RemixWaitOptions): Promise<RemixResult> {\n const pollInterval = options?.pollInterval ?? 2000;\n const timeout = options?.timeout ?? 300000;\n const startTime = Date.now();\n\n while (true) {\n const { data } = await this.typed.GET(\"/v1/projects/{project_id}/remix/progress\", {\n params: {\n path: { project_id: sourceProjectId },\n query: { job_id: jobId },\n },\n });\n const progress = data!;\n const status = progress.status as RemixJobStatus;\n options?.onProgress?.(status, progress.step);\n\n if (status === \"completed\" && progress.result) {\n return { projectId: progress.result.project_id };\n }\n\n if (status === \"error\") {\n throw new Error(progress.error_message ?? \"Remix failed\");\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for remix of project ${sourceProjectId}`);\n }\n\n await sleep(pollInterval);\n }\n }\n\n /**\n * Wait for a project to reach \"completed\" status.\n *\n * Projects start in \"in_progress\" status while being created/built.\n * This method polls until the status becomes \"completed\" or \"failed\".\n * A successful completion means the project's preview is ready to view.\n *\n * @param projectId - The project ID to wait for\n * @param options.pollInterval - Time between polls in ms (default: 2000)\n * @param options.timeout - Maximum time to wait in ms (default: 300000 = 5 minutes)\n * @param options.onProgress - Optional callback for status updates\n * @returns The completed project\n * @throws Error if project fails or timeout is reached\n */\n async waitForProjectReady(projectId: string, options?: WaitOptions): Promise<ProjectResponse> {\n const pollInterval = options?.pollInterval ?? 2000;\n const timeout = options?.timeout ?? 300000;\n const startTime = Date.now();\n\n while (true) {\n const project = await this.getProject(projectId);\n options?.onProgress?.(project);\n\n if (project.status === \"completed\") {\n return project;\n }\n\n if (project.status === \"failed\") {\n throw new Error(`Project ${projectId} failed to build`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for project ${projectId} to be ready`);\n }\n\n await sleep(pollInterval);\n }\n }\n\n private isFileInput(file: File | FileInput): file is FileInput {\n return \"data\" in file;\n }\n\n private async uploadFile(\n file: File | FileInput,\n getUploadUrl: (fileName: string, mimeType: string) => Promise<FileUploadUrlResponse>,\n ): Promise<UnscopedFile> {\n const fileName = this.isFileInput(file) ? file.name : file.name;\n const mimeType = this.isFileInput(file) ? file.type : file.type;\n const body = this.isFileInput(file) ? file.data : file;\n\n const uploadUrl = await getUploadUrl(fileName, mimeType);\n const { url, file_id: objectPath, headers } = uploadUrl;\n\n const uploadResponse = await fetch(url, {\n method: \"PUT\",\n body,\n headers: { \"Content-Type\": mimeType, ...headers },\n });\n if (!uploadResponse.ok) {\n throw new Error(`File upload failed for \"${fileName}\": HTTP ${uploadResponse.status}`);\n }\n\n return { file_id: objectPath, type: \"user_upload\", file_name: fileName, mime_type: mimeType };\n }\n\n private async uploadProjectFiles(projectId: string, files: (File | FileInput)[]): Promise<UnscopedFile[]> {\n return Promise.all(\n files.map((file) =>\n this.uploadFile(file, (_fileName, mimeType) =>\n this.getProjectFileUploadUrl(projectId, { content_type: mimeType }),\n ),\n ),\n );\n }\n\n private async uploadEphemeralFiles(files: (File | FileInput)[]): Promise<UnscopedFile[]> {\n return Promise.all(\n files.map((file) =>\n this.uploadFile(file, (_fileName, mimeType) => this.getEphemeralFileUploadUrl({ content_type: mimeType })),\n ),\n );\n }\n\n private partitionUploadedFiles(files: UnscopedFile[]): {\n fileRefs: UnscopedFile[] | undefined;\n ephemeralFileRefs: UnscopedFile[] | undefined;\n } {\n const fileRefs: UnscopedFile[] = [];\n const ephemeralFileRefs: UnscopedFile[] = [];\n for (const file of files) {\n if (file.file_id.startsWith(\"ephemeral/\")) {\n ephemeralFileRefs.push(file);\n } else {\n fileRefs.push(file);\n }\n }\n return {\n fileRefs: fileRefs.length > 0 ? fileRefs : undefined,\n ephemeralFileRefs: ephemeralFileRefs.length > 0 ? ephemeralFileRefs : undefined,\n };\n }\n /**\n * Wait for a project to be published (deployed).\n *\n * This method polls until the project has `is_published: true` and a `url`.\n *\n * @param projectId - The project ID to wait for\n * @param options.pollInterval - Time between polls in ms (default: 3000)\n * @param options.timeout - Maximum time to wait in ms (default: 600000 = 10 minutes)\n * @param options.onProgress - Optional callback for status updates\n * @returns The published project with URL\n * @throws Error if timeout is reached\n */\n async waitForProjectPublished(projectId: string, options?: WaitOptions): Promise<ProjectResponse> {\n const pollInterval = options?.pollInterval ?? 3000;\n const timeout = options?.timeout ?? 600000;\n const startTime = Date.now();\n\n while (true) {\n const project = await this.getProject(projectId);\n options?.onProgress?.(project);\n\n if (project.is_published && project.url) {\n return project;\n }\n\n if (project.status === \"failed\") {\n throw new Error(`Project ${projectId} failed to build`);\n }\n\n if (Date.now() - startTime > timeout) {\n throw new Error(`Timeout waiting for project ${projectId} to be published`);\n }\n\n await sleep(pollInterval);\n }\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"name\" in err && err.name === \"AbortError\";\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n try {\n await response.body?.cancel();\n } catch {}\n}\n\nasync function* parseSSEFrames(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: string }, void, void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let sep = buffer.indexOf(\"\\n\\n\");\n while (sep !== -1) {\n const raw = buffer.slice(0, sep);\n buffer = buffer.slice(sep + 2);\n sep = buffer.indexOf(\"\\n\\n\");\n\n let event = \"message\";\n const dataLines: string[] = [];\n for (const line of raw.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) {\n event = line.slice(6).trimStart();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length === 0) continue;\n yield { event, data: dataLines.join(\"\\n\") };\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // ignore\n }\n try {\n await body.cancel();\n } catch {\n // ignore\n }\n }\n}\n\nfunction terminalResultFromMessage(msg: GetMessageResponse, fallbackMessageId: string): MessageCompletionResult | null {\n const ai = msg.response;\n if (ai && isTerminalAIStatus(ai.status)) {\n return {\n status: messageCompletionStatus(ai.status),\n message_id: ai.message_id || fallbackMessageId,\n content: ai.content,\n edit_id: ai.edit_id,\n commit_sha: ai.commit_sha,\n summary: ai.summary,\n cost_credits: ai.cost_credits,\n awaiting_input: ai.awaiting_input,\n ...(ai.status === \"error\" ? { error: \"Agent reported an error.\" } : {}),\n };\n }\n if (msg.role === \"assistant\" && isTerminalAIStatus(msg.status)) {\n return {\n status: messageCompletionStatus(msg.status),\n message_id: msg.message_id || fallbackMessageId,\n content: msg.content,\n edit_id: msg.edit_id,\n commit_sha: msg.commit_sha,\n summary: msg.summary,\n cost_credits: msg.cost_credits,\n awaiting_input: msg.awaiting_input,\n ...(msg.status === \"error\" ? { error: \"Agent reported an error.\" } : {}),\n };\n }\n return null;\n}\n\nfunction messageCompletionStatus(status: string): MessageCompletionResult[\"status\"] {\n return status === \"completed\" || status === \"stopped\" || status === \"awaiting_input\" ? status : \"error\";\n}\n\nfunction isTerminalAIStatus(status: string | undefined): boolean {\n return status === \"completed\" || status === \"stopped\" || status === \"error\" || status === \"awaiting_input\";\n}\n\nfunction queuedExitResult(msg: GetMessageResponse, fallbackMessageId: string): MessageCompletionResult | null {\n if (msg.status !== \"queued\") return null;\n if (!msg.queue_paused) return null;\n if (msg.queue_pause_reason === \"hitl_tool\") return null;\n return {\n status: \"error\",\n message_id: fallbackMessageId,\n content: \"\",\n error:\n `Message is queued (position ${msg.queue_position ?? \"unknown\"}) but the queue is paused` +\n (msg.queue_pause_reason ? ` (reason: ${msg.queue_pause_reason})` : \"\") +\n `. Unpause the queue in the Lovable editor, or use wait=false to return immediately.`,\n };\n}\n\nfunction timeoutResult(messageId: string, timeoutMs: number): MessageCompletionResult {\n return {\n status: \"timeout\",\n message_id: messageId,\n content: \"\",\n error: `Agent did not finish within ${Math.max(0, Math.round(timeoutMs / 1000))}s`,\n };\n}\n"],"mappings":";;AAAA,MAAM,kBAAkB;CAAC;CAAK;CAAK;AAAG;AAEtC,MAAMA,WAAS,OAA8B,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AAE7F,SAASC,oBAAkB,SAAsC;CAC/D,MAAM,MAAM,QAAQ,IAAI,aAAa;CACrC,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,MAAM,UAAU,OAAO,GAAG;CAC1B,IAAI,OAAO,SAAS,OAAO,KAAK,WAAW,GAAG,OAAO,UAAU;CAC/D,MAAM,SAAS,KAAK,MAAM,GAAG;CAC7B,IAAI,CAAC,OAAO,MAAM,MAAM,GAAG;EACzB,MAAM,QAAQ,SAAS,KAAK,IAAI;EAChC,OAAO,QAAQ,IAAI,QAAQ;CAC7B;AAEF;;;;;;;;;;AAaA,SAAgB,eAAe,aAAyB,UAAU,WAAW,MAAM,KAAK,GAAe;CACrG,OAAO,OAAO,UAAU;EAItB,MAAM,cAAyC,MAAM,MAAM;EAC3D,IAAI,WAAW,MAAM,UAAU,MAAM,CAAC;EACtC,KAAK,MAAM,WAAW,iBAAiB;GACrC,IAAI,SAAS,WAAW,KAAK;GAC7B,MAAM,cAAcA,oBAAkB,SAAS,OAAO;GACtD,MAAMD,QAAM,KAAK,IAAI,SAAS,eAAe,CAAC,CAAC;GAC/C,WAAW,MAAM,UAAU,M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