@koda-sl/baker-cli 0.281.11-dev.0c0293389 → 0.282.0-dev.51855d0e5
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/README.md +197 -39
- package/dist/{chunk-RHEQTHT7.js → chunk-4YF56EGK.js} +3 -3
- package/dist/{chunk-XAUTT2Q6.js → chunk-A2VZOTCV.js} +6 -7
- package/dist/chunk-A2VZOTCV.js.map +1 -0
- package/dist/{chunk-P2PEABMQ.js → chunk-KDTHRRAC.js} +10 -3
- package/dist/chunk-KDTHRRAC.js.map +1 -0
- package/dist/{chunk-YNUBWTLR.js → chunk-LOUE7GTU.js} +104 -10
- package/dist/chunk-LOUE7GTU.js.map +1 -0
- package/dist/cli.js +11928 -6127
- package/dist/cli.js.map +1 -1
- package/dist/{client-KOUPT7HU.js → client-6KQHCXS2.js} +4 -2
- package/dist/engine/index.d.ts +13 -0
- package/dist/engine/index.js +1 -1
- package/dist/{output-ALQGBDPQ.js → output-RBM32FKJ.js} +3 -3
- package/dist/{shared-UKJH3PS7.js → shared-WJIJTWST.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-P2PEABMQ.js.map +0 -1
- package/dist/chunk-XAUTT2Q6.js.map +0 -1
- package/dist/chunk-YNUBWTLR.js.map +0 -1
- /package/dist/{chunk-RHEQTHT7.js.map → chunk-4YF56EGK.js.map} +0 -0
- /package/dist/{client-KOUPT7HU.js.map → client-6KQHCXS2.js.map} +0 -0
- /package/dist/{output-ALQGBDPQ.js.map → output-RBM32FKJ.js.map} +0 -0
- /package/dist/{shared-UKJH3PS7.js.map → shared-WJIJTWST.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/error-handler.ts","../src/commands/ads/cache.ts","../src/commands/ads/output.ts"],"sourcesContent":["import { writeJsonEnvelope } from \"./commands/ads/output.ts\";\n\ntype ConnectionPlatform = \"google_ads\" | \"ga4\" | \"gsc\" | \"x_ads\" | \"meta_ads\" | \"linkedin_ads\";\n\n/**\n * Platforms the agent can get connected without the user leaving the chat, via\n * the blocking `request_connection` tool, and the id that tool expects. Every\n * platform this CLI can talk to is here — keep it in step with\n * `CONNECTION_PLATFORMS` in `packages/bridge/src/hono/connection-input.ts`: a\n * platform the tool accepts but this map omits sends the user to Settings for a\n * door the agent could have opened itself.\n */\nconst REQUEST_CONNECTION_PLATFORM: Record<ConnectionPlatform, string> = {\n google_ads: \"google-ads\",\n ga4: \"google-analytics\",\n gsc: \"google-search-console\",\n linkedin_ads: \"linkedin\",\n meta_ads: \"meta\",\n x_ads: \"x-ads\",\n};\n\nconst PLATFORM_NAME: Record<ConnectionPlatform, string> = {\n google_ads: \"Google Ads\",\n ga4: \"Google Analytics 4\",\n gsc: \"Google Search Console\",\n x_ads: \"X Ads\",\n meta_ads: \"Meta Ads\",\n linkedin_ads: \"LinkedIn Ads\",\n};\n\n/**\n * How to tell the agent to get a platform connected. Never \"send them to\n * Settings\" for a platform `request_connection` covers — that ends the turn on a\n * wall the agent could have opened itself, and it now covers every platform this\n * CLI talks to. The fallback line matters too: a Session booted before the tool\n * shipped does not have it, and the agent must still be able to say where the\n * connect button is instead of stalling.\n */\nexport function connectionFixExplanation(platform: ConnectionPlatform): string {\n const name = PLATFORM_NAME[platform];\n const slug = REQUEST_CONNECTION_PLATFORM[platform];\n return (\n `${name} is not connected for this company (or no account has been picked). Do NOT send the user to Settings ` +\n `and do NOT end the turn here — call the \\`request_connection\\` tool with { platform: \"${slug}\", reason } and ` +\n `they connect and pick their accounts from inside the chat. If that tool is not available to you, tell them ` +\n `exactly where to do it: dashboard → Brain → Integrations → Tools → ${name}. Either way, carry on with the ` +\n `rest of the task and say what stays unavailable until it is connected.`\n );\n}\n\n/**\n * Shared error handler for \"No Connection\" scenarios.\n * Provides a structured error for AI agents with a suggested fix and alternative commands.\n */\nexport function handleConnectionError(platform: ConnectionPlatform, originalMessage?: string): never {\n const platformName = PLATFORM_NAME[platform];\n\n const alternative = {\n google_ads: \"keywords-for-site or research advertisers\",\n ga4: \"lighthouse for page performance\",\n gsc: \"keywords-for-site or research keyword-gap\",\n x_ads: \"research advertisers\",\n meta_ads: \"research advertisers or research keyword-ideas\",\n linkedin_ads: \"research advertisers (LinkedIn Ad Library) or research keyword-ideas\",\n }[platform];\n\n const code = {\n google_ads: \"NO_GOOGLE_ADS_CONNECTION\",\n ga4: \"NO_GA4_CONNECTION\",\n gsc: \"NO_GSC_CONNECTION\",\n x_ads: \"NO_X_ADS_CONNECTION\",\n meta_ads: \"NO_META_ADS_CONNECTION\",\n linkedin_ads: \"NO_LINKEDIN_ADS_CONNECTION\",\n }[platform];\n\n const envelope = {\n ok: false,\n error: {\n code,\n message: originalMessage || `No ${platformName} connection found for this company.`,\n fix: {\n action: \"request_connection\",\n explanation: `${connectionFixExplanation(platform)} (Optional fallback for estimated external insights: 'baker research ${alternative}'.)`,\n },\n retryable: false,\n },\n };\n\n writeJsonEnvelope(envelope);\n process.exit(1);\n}\n\n/**\n * Does this API failure mean \"the platform isn't connected\"? The read commands\n * surface the backend's own 404/403 verbatim, so the connect fix has to be\n * recognised from the code the client mapped it to plus the message.\n */\nexport function isNotConnectedError(code: string, message: string): boolean {\n if (code !== \"NOT_FOUND\" && code !== \"UNAUTHORIZED\" && code !== \"FORBIDDEN\") {\n return false;\n }\n // The last alternative is the write-path 403 (\"customer X is not in this\n // company's connected Google Ads accounts\") — a different sentence for the\n // same remedy: connect, and pick the account.\n return /no .* connection found|not connected|no .* (selected|picked)|is not in .* connected/i.test(message);\n}\n\n/**\n * Does this failure warrant the connect form? A dead token (401) always does —\n * whatever the wording, the remedy is to sign in again.\n *\n * A 404 or 403 only does when the backend says so. Both codes are overloaded:\n * 403 is also an asset-level refusal on a live connection (reconnecting cannot\n * grant it), and 404 is also how \"no staged op <ref> in this draft\" and a\n * mistyped `--chat` come back. Answering either with \"ask the user to connect\n * Meta Ads\" sends the agent to fix something that was never broken, and the\n * real missing-connection 404 says \"No <platform> connection found\" anyway.\n */\nexport function needsConnectionFix(code: string, message: string): boolean {\n if (code === \"UNAUTHORIZED\") {\n return true;\n }\n return isNotConnectedError(code, message);\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { CacheEntry } from \"./types.ts\";\n\nconst CACHE_DIR = join(homedir(), \".baker\", \"cache\", \"ads\");\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nfunction hashKey(key: string): string {\n return createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 16);\n}\n\nfunction cachePath(category: string, key: string): string {\n const dir = join(CACHE_DIR, category);\n ensureDir(dir);\n return join(dir, `${hashKey(key)}.json`);\n}\n\nexport function cacheGet<T>(category: string, key: string): CacheEntry<T> | null {\n const path = cachePath(category, key);\n if (!existsSync(path)) {\n return null;\n }\n try {\n const raw = readFileSync(path, \"utf-8\");\n const entry = JSON.parse(raw) as CacheEntry<T>;\n if (entry.expiresAt < Date.now()) {\n rmSync(path, { force: true });\n return null;\n }\n return entry;\n } catch {\n rmSync(path, { force: true });\n return null;\n }\n}\n\nexport function cacheSet<T>(\n category: string,\n key: string,\n data: T,\n ttlMs: number,\n fields?: Record<string, string>,\n): void {\n const path = cachePath(category, key);\n const entry: CacheEntry<T> = {\n expiresAt: Date.now() + ttlMs,\n data,\n fields,\n };\n writeFileSync(path, JSON.stringify(entry), \"utf-8\");\n}\n\nconst HOUR = 60 * 60 * 1000;\nconst MINUTE = 60 * 1000;\n\nexport function getQueryTtl(query: string): number {\n const upper = query.toUpperCase();\n if (upper.includes(\"TODAY\")) {\n return 15 * MINUTE;\n }\n if (upper.includes(\"LAST_7_DAYS\") || upper.includes(\"LAST_14_DAYS\")) {\n return 1 * HOUR;\n }\n // Historical data (BETWEEN, LAST_30_DAYS, LAST_90_DAYS, etc.)\n return 6 * HOUR;\n}\n\nexport function buildQueryCacheKey(customerId: string, query: string): string {\n const today = new Date().toISOString().slice(0, 10);\n return `${customerId}:${today}:${query.trim().replace(/\\s+/g, \" \")}`;\n}\n\ninterface CachedAccount {\n id: string;\n access_type: \"direct\" | \"managed\";\n manager_id?: string;\n}\n\nexport function getManagerIdForCustomer(customerId: string): string | undefined {\n const cached = cacheGet<CachedAccount[]>(\"accounts\", \"list\");\n if (!cached) return undefined;\n const account = cached.data.find((a) => a.id === customerId);\n if (account?.access_type === \"managed\") return account.manager_id;\n return undefined;\n}\n","import { ApiError, apiGet } from \"../../client.ts\";\nimport { getEnv } from \"../../env.ts\";\nimport { handleConnectionError, isNotConnectedError } from \"../../error-handler.ts\";\nimport type { QueryContext } from \"../../geo-context.ts\";\nimport { cacheGet, cacheSet } from \"./cache.ts\";\nimport type { AdsErrorEnvelope, AdsFileSummary, AdsSuccessEnvelope } from \"./types.ts\";\n\ntype AdsOutput =\n | AdsSuccessEnvelope<unknown>\n | AdsErrorEnvelope\n | AdsFileSummary\n | { ok: true; data: unknown; query_context?: QueryContext; cached?: true; fields?: Record<string, string> }\n | { ok: false; error: { code: string; message: string } };\n\nexport function writeAdsJson(envelope: AdsOutput): void {\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n}\n\nexport function writeJsonEnvelope(envelope: Record<string, unknown>): void {\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n}\n\nexport function toCsvRow(values: string[]): string {\n return values\n .map((v) => {\n if (v.includes(\",\") || v.includes('\"') || v.includes(\"\\n\")) {\n return `\"${v.replace(/\"/g, '\"\"')}\"`;\n }\n return v;\n })\n .join(\",\");\n}\n\nfunction flattenRow(row: Record<string, unknown>): Record<string, string> {\n const flat: Record<string, string> = {};\n for (const [key, val] of Object.entries(row)) {\n flat[key] = typeof val === \"object\" && val !== null ? JSON.stringify(val) : String(val ?? \"\");\n }\n return flat;\n}\n\nfunction writeAdsCsv(data: Array<Record<string, unknown>>, fields?: string[]): void {\n if (data.length === 0) return;\n const cols = fields ?? Object.keys(data[0] ?? {});\n process.stdout.write(`${toCsvRow(cols)}\\n`);\n for (const row of data) {\n const flat = flattenRow(row);\n process.stdout.write(`${toCsvRow(cols.map((f) => flat[f] ?? \"\"))}\\n`);\n }\n}\n\nfunction writeAdsJsonl(data: Array<Record<string, unknown>>): void {\n for (const row of data) {\n process.stdout.write(`${JSON.stringify(row)}\\n`);\n }\n}\n\nfunction writeAdsMd(data: Array<Record<string, unknown>>, fields?: string[]): void {\n if (data.length === 0) return;\n const cols = fields ?? Object.keys(data[0] ?? {});\n process.stdout.write(`| ${cols.join(\" | \")} |\\n`);\n process.stdout.write(`| ${cols.map(() => \"---\").join(\" | \")} |\\n`);\n for (const row of data) {\n const flat = flattenRow(row);\n process.stdout.write(`| ${cols.map((f) => flat[f] ?? \"\").join(\" | \")} |\\n`);\n }\n}\n\nexport function writeAdsOutput(data: Array<Record<string, unknown>>, format: string, fields?: string[]): void {\n switch (format) {\n case \"csv\":\n writeAdsCsv(data, fields);\n break;\n case \"jsonl\":\n writeAdsJsonl(data);\n break;\n case \"md\":\n writeAdsMd(data, fields);\n break;\n default:\n writeAdsJson({ ok: true, data });\n }\n}\n\ninterface AccountInfo {\n id: string;\n name: string;\n access_type: \"direct\" | \"managed\";\n level: number;\n manager_id?: string;\n}\n\nasync function fetchAccounts(useCache = true): Promise<AccountInfo[]> {\n if (useCache) {\n const cached = cacheGet<AccountInfo[]>(\"accounts\", \"list\");\n if (cached) return cached.data;\n }\n const params = !useCache ? { \"skip-cache\": \"true\" } : undefined;\n const data = await apiGet<AccountInfo[]>(\"/api/ads/google/accounts\", params);\n if (useCache) {\n cacheSet(\"accounts\", \"list\", data, 60 * 60 * 1000);\n }\n return data;\n}\n\nexport async function resolveCustomerId(args: Record<string, unknown>): Promise<string> {\n const fromArgs = args[\"customer-id\"] as string | undefined;\n const customerId = fromArgs || getEnv().BAKER_GOOGLE_ADS_CUSTOMER_ID;\n\n if (customerId) {\n if (!/^\\d{10}$/.test(customerId)) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"INVALID_CUSTOMER_ID\",\n message:\n \"Customer ID must be exactly 10 digits without dashes. Pass --customer-id or set BAKER_GOOGLE_ADS_CUSTOMER_ID.\",\n },\n });\n process.exit(1);\n }\n return customerId;\n }\n\n const useCache = !args[\"no-cache\"];\n\n try {\n const accounts = await fetchAccounts(useCache);\n const [single] = accounts;\n if (accounts.length === 1 && single) {\n process.stderr.write(`Using account \"${single.name}\" (${single.id})\\n`);\n return single.id;\n }\n if (accounts.length === 0) {\n handleConnectionError(\"google_ads\");\n }\n const list = accounts.map((a) => ` ${a.id} ${a.name}`).join(\"\\n\");\n writeAdsJson({\n ok: false,\n error: {\n code: \"MULTIPLE_ACCOUNTS\",\n message: `Multiple accounts found. Pass --customer-id or set BAKER_GOOGLE_ADS_CUSTOMER_ID:\\n${list}`,\n },\n });\n process.exit(1);\n } catch (err) {\n // \"No connection\" reaches here as a 404/403 from the accounts lookup. Reporting it as\n // an unusable customer id sends the agent hunting for an id that cannot exist yet.\n if (err instanceof ApiError && isNotConnectedError(err.code, err.message)) {\n handleConnectionError(\"google_ads\", err.message);\n }\n writeAdsJson({\n ok: false,\n error: {\n code: \"INVALID_CUSTOMER_ID\",\n message: \"Could not auto-detect account. Pass --customer-id or set BAKER_GOOGLE_ADS_CUSTOMER_ID.\",\n },\n });\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;AAYA,IAAM,8BAAkE;AAAA,EACtE,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,KAAK;AAAA,EACL,cAAc;AAAA,EACd,UAAU;AAAA,EACV,OAAO;AACT;AAEA,IAAM,gBAAoD;AAAA,EACxD,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,KAAK;AAAA,EACL,OAAO;AAAA,EACP,UAAU;AAAA,EACV,cAAc;AAChB;AAUO,SAAS,yBAAyB,UAAsC;AAC7E,QAAM,OAAO,cAAc,QAAQ;AACnC,QAAM,O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,YAAY,oBAAoB,IAAI,MAAM,IAAI,OAAO,GAAG;AACzE,4BAAsB,cAAc,IAAI,OAAO;AAAA,IACjD;AACA,iBAAa;AAAA,MACX,IAAI;AAAA,MACJ,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":[]}
|
|
@@ -79,6 +79,9 @@ function mapHttpError(status) {
|
|
|
79
79
|
if (status === 422 || status === 400) {
|
|
80
80
|
return "VALIDATION_ERROR";
|
|
81
81
|
}
|
|
82
|
+
if (status === 409) {
|
|
83
|
+
return "CONFLICT";
|
|
84
|
+
}
|
|
82
85
|
if (status === 429) {
|
|
83
86
|
return "RATE_LIMITED";
|
|
84
87
|
}
|
|
@@ -107,7 +110,7 @@ async function handleResponse(response) {
|
|
|
107
110
|
throw new ApiError("INTERNAL_ERROR", "Failed to parse API response as JSON");
|
|
108
111
|
}
|
|
109
112
|
}
|
|
110
|
-
async function
|
|
113
|
+
async function apiGetWithHeaders(path, params) {
|
|
111
114
|
const env = getEnv();
|
|
112
115
|
const url = new URL(path, env.BAKER_API_URL);
|
|
113
116
|
if (params) {
|
|
@@ -145,7 +148,10 @@ async function apiGet(path, params) {
|
|
|
145
148
|
responseBody: await readBodyForLog(response),
|
|
146
149
|
durationMs: Date.now() - startedAt
|
|
147
150
|
});
|
|
148
|
-
return handleResponse(response);
|
|
151
|
+
return { data: await handleResponse(response), headers: response.headers };
|
|
152
|
+
}
|
|
153
|
+
async function apiGet(path, params) {
|
|
154
|
+
return (await apiGetWithHeaders(path, params)).data;
|
|
149
155
|
}
|
|
150
156
|
async function apiPost(path, body, opts) {
|
|
151
157
|
const env = getEnv();
|
|
@@ -195,7 +201,8 @@ async function apiPost(path, body, opts) {
|
|
|
195
201
|
export {
|
|
196
202
|
ApiError,
|
|
197
203
|
validateConvexId,
|
|
204
|
+
apiGetWithHeaders,
|
|
198
205
|
apiGet,
|
|
199
206
|
apiPost
|
|
200
207
|
};
|
|
201
|
-
//# sourceMappingURL=chunk-
|
|
208
|
+
//# sourceMappingURL=chunk-KDTHRRAC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { debugLogHttp, readBodyForLog } from \"./debugLog.ts\";\nimport { getEnv } from \"./env.ts\";\n\nconst MAX_RATE_LIMIT_RETRIES = 3;\nconst MAX_TOTAL_WAIT_MS = 2 * 60 * 1000;\n\nasync function fetchWithRateLimitRetry(url: string, init: RequestInit): Promise<Response> {\n let totalWaited = 0;\n\n for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {\n const response = await fetch(url, init);\n\n if (response.status !== 429 || attempt >= MAX_RATE_LIMIT_RETRIES) {\n return response;\n }\n\n const retryAfterHeader = response.headers.get(\"Retry-After\");\n const waitMs = retryAfterHeader ? Number(retryAfterHeader) * 1000 : 2000 * 2 ** attempt;\n\n if (totalWaited + waitMs > MAX_TOTAL_WAIT_MS) {\n return response;\n }\n\n totalWaited += waitMs;\n await new Promise((resolve) => setTimeout(resolve, waitMs));\n }\n\n return fetch(url, init);\n}\n\ntype ErrorCode =\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"VALIDATION_ERROR\"\n | \"RATE_LIMITED\"\n | \"INTERNAL_ERROR\"\n | \"NETWORK_ERROR\"\n | \"TIMEOUT\"\n | \"IMAGE_PROCESSING_ERROR\";\n\nexport class ApiError extends Error {\n code: ErrorCode;\n\n constructor(code: ErrorCode, message: string) {\n super(message);\n this.name = \"ApiError\";\n this.code = code;\n }\n}\n\nconst CONVEX_ID_RE = /^[a-zA-Z0-9_]+$/;\n\nfunction hasControlCharacters(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n // Allow tab (9), newline (10), carriage return (13)\n if (code < 32 && code !== 9 && code !== 10 && code !== 13) {\n return true;\n }\n }\n return false;\n}\n\nfunction validateStringValue(value: string): void {\n if (hasControlCharacters(value)) {\n throw new ApiError(\"VALIDATION_ERROR\", \"String value contains invalid control characters\");\n }\n}\n\nexport function validateConvexId(id: string): void {\n if (!CONVEX_ID_RE.test(id)) {\n throw new ApiError(\"VALIDATION_ERROR\", `Invalid ID format: \"${id}\". Expected alphanumeric string.`);\n }\n}\n\nfunction sanitizeParams(params: Record<string, string>): Record<string, string> {\n const sanitized: Record<string, string> = {};\n for (const [key, value] of Object.entries(params)) {\n validateStringValue(value);\n sanitized[key] = value;\n }\n return sanitized;\n}\n\n/**\n * Sent on every call so the backend can attribute immediately-applied writes\n * (library images and videos, followed advertisers) to the Session they were\n * made from. Absent outside a chat-attached environment.\n */\nfunction chatHeader(): Record<string, string> {\n const chatId = getEnv().BAKER_CHAT_ID;\n return chatId ? { \"x-baker-chat-id\": chatId } : {};\n}\n\nfunction mapHttpError(status: number): ErrorCode {\n if (status === 401) {\n return \"UNAUTHORIZED\";\n }\n // 403 is never \"not connected\" — every backend `FORBIDDEN` means connected but\n // not allowed (an asset outside the granted scope, a capability the account\n // lacks). Folding it into UNAUTHORIZED sent agents down the reconnect path,\n // which cannot fix a permission gap and wastes the user's time.\n if (status === 403) {\n return \"FORBIDDEN\";\n }\n if (status === 404) {\n return \"NOT_FOUND\";\n }\n if (status === 422 || status === 400) {\n return \"VALIDATION_ERROR\";\n }\n // 409 is a state the caller has to change, never a fault to sit out. It is\n // what the backend returns for \"this workspace has not switched analytics on\n // yet\" and its siblings — folded into INTERNAL_ERROR, that reaches an agent\n // as a transient failure worth retrying, which it never is.\n if (status === 409) {\n return \"CONFLICT\";\n }\n if (status === 429) {\n return \"RATE_LIMITED\";\n }\n return \"INTERNAL_ERROR\";\n}\n\nasync function handleResponse<T>(response: Response): Promise<T> {\n const body = await response.text();\n\n if (!response.ok) {\n let message = `HTTP ${response.status}: ${response.statusText}`;\n try {\n const parsed = JSON.parse(body) as { error?: string | { message?: string }; message?: string };\n if (typeof parsed.error === \"string\") {\n message = parsed.error;\n } else if (parsed.error?.message) {\n message = parsed.error.message;\n } else if (parsed.message) {\n message = parsed.message;\n }\n } catch {\n // Use default message\n }\n throw new ApiError(mapHttpError(response.status), message);\n }\n\n try {\n return JSON.parse(body) as T;\n } catch {\n throw new ApiError(\"INTERNAL_ERROR\", \"Failed to parse API response as JSON\");\n }\n}\n\n/**\n * A GET that also hands back the response headers.\n *\n * Some endpoints have to say something *about* the answer that the answer has\n * no room for — `GET /api/testimonials` returns a bare array and sets\n * `X-Baker-Next-Cursor` when rows past this page remain unexamined, so the rows\n * alone cannot tell one page of a library from the whole of it.\n */\nexport async function apiGetWithHeaders<T>(\n path: string,\n params?: Record<string, string>,\n): Promise<{ data: T; headers: Headers }> {\n const env = getEnv();\n const url = new URL(path, env.BAKER_API_URL);\n if (params) {\n const clean = sanitizeParams(params);\n for (const [key, value] of Object.entries(clean)) {\n url.searchParams.set(key, value);\n }\n }\n\n const urlStr = url.toString();\n const startedAt = Date.now();\n let response: Response;\n try {\n response = await fetchWithRateLimitRetry(urlStr, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${env.BAKER_API_KEY}`,\n Accept: \"application/json\",\n ...chatHeader(),\n },\n signal: AbortSignal.timeout(60_000),\n });\n } catch (err) {\n debugLogHttp({ source: \"cli\", method: \"GET\", url: urlStr, durationMs: Date.now() - startedAt, error: err });\n if (err instanceof Error && (err.name === \"TimeoutError\" || err.name === \"AbortError\")) {\n throw new ApiError(\"TIMEOUT\", \"Request timed out after 60 seconds\");\n }\n throw new ApiError(\"NETWORK_ERROR\", `Request failed: ${err instanceof Error ? err.message : \"Unknown error\"}`);\n }\n\n debugLogHttp({\n source: \"cli\",\n method: \"GET\",\n url: urlStr,\n status: response.status,\n ok: response.ok,\n responseBody: await readBodyForLog(response),\n durationMs: Date.now() - startedAt,\n });\n return { data: await handleResponse<T>(response), headers: response.headers };\n}\n\nexport async function apiGet<T>(path: string, params?: Record<string, string>): Promise<T> {\n return (await apiGetWithHeaders<T>(path, params)).data;\n}\n\nexport async function apiPost<T>(path: string, body: unknown, opts?: { timeoutMs?: number }): Promise<T> {\n const env = getEnv();\n const timeoutMs = opts?.timeoutMs ?? 60_000;\n const urlStr = new URL(path, env.BAKER_API_URL).toString();\n const startedAt = Date.now();\n let response: Response;\n try {\n response = await fetchWithRateLimitRetry(urlStr, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${env.BAKER_API_KEY}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n ...chatHeader(),\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (err) {\n debugLogHttp({\n source: \"cli\",\n method: \"POST\",\n url: urlStr,\n requestBody: body,\n durationMs: Date.now() - startedAt,\n error: err,\n });\n if (err instanceof Error && (err.name === \"TimeoutError\" || err.name === \"AbortError\")) {\n throw new ApiError(\"TIMEOUT\", `Request timed out after ${Math.round(timeoutMs / 1000)} seconds`);\n }\n throw new ApiError(\"NETWORK_ERROR\", `Request failed: ${err instanceof Error ? err.message : \"Unknown error\"}`);\n }\n\n debugLogHttp({\n source: \"cli\",\n method: \"POST\",\n url: urlStr,\n requestBody: body,\n status: response.status,\n ok: response.ok,\n responseBody: await readBodyForLog(response),\n durationMs: Date.now() - startedAt,\n });\n return handleResponse<T>(response);\n}\n"],"mappings":";;;;;;;;;AAGA,IAAM,yBAAyB;AAC/B,IAAM,oBAAoB,IAAI,KAAK;AAEnC,eAAe,wBAAwB,KAAa,MAAsC;AACxF,MAAI,cAAc;AAElB,WAAS,UAAU,GAAG,WAAW,wBAAwB,WAAW;AAClE,UAAM,WAAW,MAAM,MAAM,KAAK,IAAI;AAEtC,QAAI,SAAS,WAAW,OAAO,WAAW,wBAAwB;AAChE,aAAO;AAAA,IACT;AAEA,UAAM,mBAAmB,SAAS,QAAQ,IAAI,aAAa;AAC3D,UAAM,SAAS,mBAAmB,OAAO,gBAAgB,IAAI,MAAO,MAAO,KAAK;AAEhF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AAA,MAChB;AAAA,MACA,MAAM,KAAK,UAAU,IAAI;AAAA,MACzB,QAAQ,YAAY,QAAQ,SAAS;AAAA,IACvC,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,iBAAa;AAAA,MACX,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,KAAK;AAAA,MACL,aAAa;AAAA,MACb,YAAY,KAAK,IAAI,IAAI;AAAA,MACzB,OAAO;AAAA,IACT,CAAC;AACD,QAAI,eAAe,UAAU,IAAI,SAAS,kBAAkB,IAAI,SAAS,eAAe;AACtF,YAAM,IAAI,SAAS,WAAW,2BAA2B,KAAK,MAAM,YAAY,GAAI,CAAC,UAAU;AAAA,IACjG;AACA,UAAM,IAAI,SAAS,iBAAiB,mBAAmB,eAAe,QAAQ,IAAI,UAAU,eAAe,EAAE;AAAA,EAC/G;AAEA,eAAa;AAAA,IACX,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK;AAAA,IACL,aAAa;AAAA,IACb,QAAQ,SAAS;AAAA,IACjB,IAAI,SAAS;AAAA,IACb,cAAc,MAAM,eAAe,QAAQ;AAAA,IAC3C,YAAY,KAAK,IAAI,IAAI;AAAA,EAC3B,CAAC;AACD,SAAO,eAAkB,QAAQ;AACnC;","names":[]}
|
|
@@ -17,9 +17,9 @@ import {
|
|
|
17
17
|
shouldEscalate
|
|
18
18
|
} from "./chunk-WFWU3CHS.js";
|
|
19
19
|
|
|
20
|
-
// ../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/
|
|
20
|
+
// ../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/509a695c9237c6e3727f1f1f99169917f329e3ff3f7877be290b684e24bf153d/node_modules/safe-stable-stringify/index.js
|
|
21
21
|
var require_safe_stable_stringify = __commonJS({
|
|
22
|
-
"../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/
|
|
22
|
+
"../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/509a695c9237c6e3727f1f1f99169917f329e3ff3f7877be290b684e24bf153d/node_modules/safe-stable-stringify/index.js"(exports, module) {
|
|
23
23
|
"use strict";
|
|
24
24
|
var { hasOwnProperty } = Object.prototype;
|
|
25
25
|
var stringify = configure2();
|
|
@@ -1098,7 +1098,7 @@ function resolveAdaptFormats(params) {
|
|
|
1098
1098
|
return params.formats ?? [];
|
|
1099
1099
|
}
|
|
1100
1100
|
|
|
1101
|
-
// ../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/
|
|
1101
|
+
// ../../.pnpm-store/v10/links/@/safe-stable-stringify/2.5.0/509a695c9237c6e3727f1f1f99169917f329e3ff3f7877be290b684e24bf153d/node_modules/safe-stable-stringify/esm/wrapper.js
|
|
1102
1102
|
var import__ = __toESM(require_safe_stable_stringify(), 1);
|
|
1103
1103
|
var configure = import__.default.configure;
|
|
1104
1104
|
var wrapper_default = import__.default;
|
|
@@ -1139,6 +1139,14 @@ function normalizeForCanonical(value) {
|
|
|
1139
1139
|
return void 0;
|
|
1140
1140
|
}
|
|
1141
1141
|
|
|
1142
|
+
// ../canvas-contract/src/frameRealism.ts
|
|
1143
|
+
function frameRealismDirection(opts = {}) {
|
|
1144
|
+
return " Everything obeys real-world physics: paper, card and screens are OPAQUE with nothing showing through from behind, every object is at believable real-world scale next to the people handling it, and every object has its real-world form and construction \u2014 a phone has ONE screen and it is on the front. NO readable text or numbers anywhere in frame \u2014 phone screens, documents and signage stay illegible or out of focus, because any figure the model invents will contradict the script. Hands are kept simple: no close-up of fingers manipulating small parts, no hand gripping the edge of an object, and each person has exactly TWO arms and TWO legs, all attached and all visible or all out of frame. Anyone working does so the way the trade actually does it: nobody stands or kneels on the equipment being installed, nothing is fitted overhanging an edge or floating unsupported, and every part rests on the structure that would really carry it." + // The newest clause, and the one no route had. A testimonial came back with the customer
|
|
1145
|
+
// repairing the panel herself: nothing said she was not the installer, so the model cast
|
|
1146
|
+
// her as one. Who someone IS in the picture has to be stated, or it is guessed.
|
|
1147
|
+
(opts.role ? ` The person on camera is ${opts.role} \u2014 they are shown as that and never doing somebody else's job.` : "") + (opts.currency ? ` If a currency is unavoidably visible it is ${opts.currency}.` : "");
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1142
1150
|
// ../canvas-contract/src/registry.ts
|
|
1143
1151
|
var OPENROUTER_IMAGE_AR = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
|
|
1144
1152
|
var OPENROUTER_IMAGE_AR_EXTREME = [...OPENROUTER_IMAGE_AR, "1:4", "4:1", "1:8", "8:1"];
|
|
@@ -1158,6 +1166,7 @@ var OPENROUTER_IMAGE_SIZES = ["0.5K", ...OPENROUTER_IMAGE_SIZE];
|
|
|
1158
1166
|
var OPENROUTER_IMAGE_SIZE_EXTENDED = OPENROUTER_IMAGE_SIZES;
|
|
1159
1167
|
var GEMINI_LITE_IMAGE_SIZE = ["1K"];
|
|
1160
1168
|
var OPENROUTER_IMAGE_QUALITY = ["auto", "low", "medium", "high"];
|
|
1169
|
+
var OPENROUTER_IMAGE_QUALITY_25 = ["auto", "low", "medium", "high", "xhigh", "max"];
|
|
1161
1170
|
var RECRAFT_IMAGE_AR = ["1:1", "4:3", "3:4", "16:9", "9:16"];
|
|
1162
1171
|
var SEEDANCE_DURATIONS = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
|
1163
1172
|
var SEEDANCE_25_DURATIONS = [
|
|
@@ -1220,6 +1229,7 @@ var REPLICATE_VIDEO_MIMES = ["video/mp4", "video/webm", "video/quicktime"];
|
|
|
1220
1229
|
var DECONSTRUCT_VIDEO_MIMES = ["video/mp4", "video/webm", "video/quicktime"];
|
|
1221
1230
|
var REPLICATE_AUDIO_MIMES = ["audio/wav", "audio/mpeg", "audio/mp3"];
|
|
1222
1231
|
var IMAGE_GENERATE_MODELS = [
|
|
1232
|
+
"openai/gpt-image-2.5-sunburst",
|
|
1223
1233
|
"openai/gpt-image-2",
|
|
1224
1234
|
"openai/gpt-5.4-image-2",
|
|
1225
1235
|
"google/gemini-3.1-flash-image-preview",
|
|
@@ -1365,6 +1375,20 @@ var MODEL_REGISTRY = {
|
|
|
1365
1375
|
// images as a side effect. Notable capability gaps vs the Gemini entries:
|
|
1366
1376
|
// no `image_size` (OpenAI picks the pixel dimensions from the ratio, and a
|
|
1367
1377
|
// `resolution` is silently ignored) and the narrower `..._AR_GPT` ratio set.
|
|
1378
|
+
"openai/gpt-image-2.5-sunburst": {
|
|
1379
|
+
// Identical to the gpt-image-2 entry below except for the quality ladder — the
|
|
1380
|
+
// ratio set, the 16-reference ceiling, the missing `image_size` and the reasons
|
|
1381
|
+
// `background` / `output_compression` stay undeclared all carry over unchanged.
|
|
1382
|
+
label: "OpenAI GPT Image 2.5",
|
|
1383
|
+
inputs: [],
|
|
1384
|
+
optional_inputs: [{ kind: "image", mimes: OPENROUTER_IMAGE_MIMES, max: GPT_IMAGE_MAX_REFERENCES }],
|
|
1385
|
+
required: ["prompt"],
|
|
1386
|
+
params: {
|
|
1387
|
+
prompt: { kind: "string", maxLength: GPT_IMAGE_PROMPT_MAX },
|
|
1388
|
+
aspect_ratio: { kind: "string", enum: OPENROUTER_IMAGE_AR_GPT },
|
|
1389
|
+
quality: { kind: "string", enum: OPENROUTER_IMAGE_QUALITY_25 }
|
|
1390
|
+
}
|
|
1391
|
+
},
|
|
1368
1392
|
"openai/gpt-image-2": {
|
|
1369
1393
|
// Its live endpoint also advertises `background` (auto|opaque) and
|
|
1370
1394
|
// `output_compression` (0-100), which we deliberately do not declare. Not an
|
|
@@ -2039,6 +2063,19 @@ function maxInputSlot(kind, model, inputKind) {
|
|
|
2039
2063
|
function maxInputReferences(kind, model) {
|
|
2040
2064
|
return maxInputSlot(kind, model, "image");
|
|
2041
2065
|
}
|
|
2066
|
+
function supportedQualities(kind, model) {
|
|
2067
|
+
const schema = MODEL_REGISTRY[kind]?.[model]?.params.quality;
|
|
2068
|
+
return schema?.kind === "string" ? schema.enum : void 0;
|
|
2069
|
+
}
|
|
2070
|
+
function bestSupportedQuality(kind, model, want) {
|
|
2071
|
+
const supported = supportedQualities(kind, model);
|
|
2072
|
+
if (!supported) return void 0;
|
|
2073
|
+
if (supported.includes(want)) return want;
|
|
2074
|
+
const ladder = supported.filter((step) => step !== "auto");
|
|
2075
|
+
const ceiling = ladder.indexOf(want);
|
|
2076
|
+
const reachable = ceiling === -1 ? ladder : ladder.slice(0, ceiling);
|
|
2077
|
+
return reachable[reachable.length - 1];
|
|
2078
|
+
}
|
|
2042
2079
|
function supportedAspectRatios(kind, model) {
|
|
2043
2080
|
const schema = MODEL_REGISTRY[kind]?.[model]?.params.aspect_ratio;
|
|
2044
2081
|
return schema?.kind === "string" ? schema.enum : void 0;
|
|
@@ -3123,6 +3160,16 @@ function dfsCycle(u, color, stack, reverseAdj) {
|
|
|
3123
3160
|
stack.pop();
|
|
3124
3161
|
return null;
|
|
3125
3162
|
}
|
|
3163
|
+
function nodesBeforeCheckpoint(graph, types, stopKinds) {
|
|
3164
|
+
const all = new Set(graph.keys());
|
|
3165
|
+
if (!stopKinds?.size) return all;
|
|
3166
|
+
const running = /* @__PURE__ */ new Set();
|
|
3167
|
+
for (const layer of topologicalLayers(graph)) {
|
|
3168
|
+
if (layer.some((id) => stopKinds.has(types.get(id) ?? ""))) return running;
|
|
3169
|
+
for (const id of layer) running.add(id);
|
|
3170
|
+
}
|
|
3171
|
+
return running;
|
|
3172
|
+
}
|
|
3126
3173
|
|
|
3127
3174
|
// src/engine/engine/validator.ts
|
|
3128
3175
|
import { readFile as readFile2 } from "fs/promises";
|
|
@@ -3242,9 +3289,14 @@ var GPT_IMAGE_PROFILE = {
|
|
|
3242
3289
|
id: "gpt-image",
|
|
3243
3290
|
constraintPlacement: "last",
|
|
3244
3291
|
photorealCue: true,
|
|
3245
|
-
// OpenRouter forwards `quality`; gpt-image
|
|
3246
|
-
//
|
|
3247
|
-
|
|
3292
|
+
// OpenRouter forwards `quality`; gpt-image already processes inputs at high fidelity
|
|
3293
|
+
// automatically, so we deliberately do NOT send `input_fidelity`.
|
|
3294
|
+
//
|
|
3295
|
+
// No `quality` here any more: it is the one default that depends on WHICH gpt-image is
|
|
3296
|
+
// pinned. 2.5 added `xhigh` and `max` above `high`, and the older entries would refuse
|
|
3297
|
+
// them at validate — so callers ask for the step they want through
|
|
3298
|
+
// `bestSupportedQuality` and get the best the chosen model actually has.
|
|
3299
|
+
paramDefaults: {}
|
|
3248
3300
|
};
|
|
3249
3301
|
var GEMINI_IMAGE_PROFILE = {
|
|
3250
3302
|
id: "gemini",
|
|
@@ -3755,6 +3807,19 @@ function checkSlotsForNode(ctx, n, _i) {
|
|
|
3755
3807
|
});
|
|
3756
3808
|
}
|
|
3757
3809
|
}
|
|
3810
|
+
function estimateCreditsFor(canvas, registry, ids) {
|
|
3811
|
+
let total = 0;
|
|
3812
|
+
for (const n of canvas.nodes) {
|
|
3813
|
+
if (!ids.has(n.id)) continue;
|
|
3814
|
+
const def = registry.get(n.type);
|
|
3815
|
+
if (!def?.cost) continue;
|
|
3816
|
+
try {
|
|
3817
|
+
total += def.cost({ params: def.params.parse(n.params ?? {}) }).credits;
|
|
3818
|
+
} catch {
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
return total;
|
|
3822
|
+
}
|
|
3758
3823
|
function estimateCredits(ctx) {
|
|
3759
3824
|
let total = 0;
|
|
3760
3825
|
for (const n of ctx.canvas.nodes) {
|
|
@@ -4579,6 +4644,13 @@ function unwrap(schema) {
|
|
|
4579
4644
|
}
|
|
4580
4645
|
|
|
4581
4646
|
// src/engine/engine/executor.ts
|
|
4647
|
+
function heldByCheckpoint(canvas, layer, kinds) {
|
|
4648
|
+
if (!kinds?.size) return [];
|
|
4649
|
+
return layer.filter((id) => {
|
|
4650
|
+
const type = canvas.nodes.find((n) => n.id === id)?.type;
|
|
4651
|
+
return type !== void 0 && kinds.has(type);
|
|
4652
|
+
});
|
|
4653
|
+
}
|
|
4582
4654
|
var Engine = class {
|
|
4583
4655
|
registry;
|
|
4584
4656
|
client;
|
|
@@ -4606,7 +4678,7 @@ var Engine = class {
|
|
|
4606
4678
|
async run(input, opts = {}) {
|
|
4607
4679
|
const validation = await this.validateDeep(input);
|
|
4608
4680
|
if (!validation.ok) throw new ValidationError(validation.issues);
|
|
4609
|
-
if (opts.max_credits !== void 0 && validation.estimatedCredits > opts.max_credits) {
|
|
4681
|
+
if (!opts.stop_before_kinds?.size && opts.max_credits !== void 0 && validation.estimatedCredits > opts.max_credits) {
|
|
4610
4682
|
throw new RunAbortedError(
|
|
4611
4683
|
"cost_cap",
|
|
4612
4684
|
`estimated ${validation.estimatedCredits} credits exceeds the ${opts.max_credits}-credit cap \u2014 nothing was billed; raise --max-credits or shrink the canvas`
|
|
@@ -4625,6 +4697,20 @@ var Engine = class {
|
|
|
4625
4697
|
const counters = { cachedNodes: 0, totalCredits: 0 };
|
|
4626
4698
|
const nodeRuns = [];
|
|
4627
4699
|
const graph = this.pruneToOutput(canvas, buildGraph(canvas));
|
|
4700
|
+
if (opts.max_credits !== void 0 && opts.stop_before_kinds?.size) {
|
|
4701
|
+
const willRun = nodesBeforeCheckpoint(
|
|
4702
|
+
graph,
|
|
4703
|
+
new Map(canvas.nodes.map((n) => [n.id, n.type])),
|
|
4704
|
+
opts.stop_before_kinds
|
|
4705
|
+
);
|
|
4706
|
+
const estimate = estimateCreditsFor(canvas, this.registry, willRun);
|
|
4707
|
+
if (estimate > opts.max_credits) {
|
|
4708
|
+
throw new RunAbortedError(
|
|
4709
|
+
"cost_cap",
|
|
4710
|
+
`estimated ${estimate} credits exceeds the ${opts.max_credits}-credit cap \u2014 nothing was billed; raise --max-credits or shrink the canvas`
|
|
4711
|
+
);
|
|
4712
|
+
}
|
|
4713
|
+
}
|
|
4628
4714
|
const needsBytes = computeNeedsLocalBytes(canvas, graph, this.registry);
|
|
4629
4715
|
this.emitProgress(opts, {
|
|
4630
4716
|
kind: "plan",
|
|
@@ -4669,6 +4755,13 @@ var Engine = class {
|
|
|
4669
4755
|
`spent ${counters.totalCredits} credits, over the ${opts.max_credits}-credit cap \u2014 completed nodes are cached; raise --max-credits to continue where this stopped`
|
|
4670
4756
|
);
|
|
4671
4757
|
}
|
|
4758
|
+
const held = heldByCheckpoint(canvas, layer, opts.stop_before_kinds);
|
|
4759
|
+
if (held.length > 0) {
|
|
4760
|
+
throw new RunAbortedError(
|
|
4761
|
+
"checkpoint",
|
|
4762
|
+
`stopped before ${held.join(", ")} \u2014 everything up to here is done and cached, so continuing this run id pays for none of it again`
|
|
4763
|
+
);
|
|
4764
|
+
}
|
|
4672
4765
|
const settled = await mapWithConcurrency(layer, limit, (nodeId) => {
|
|
4673
4766
|
if (opts.signal?.aborted) {
|
|
4674
4767
|
return Promise.reject(new RunAbortedError("signal", "run aborted before node dispatch"));
|
|
@@ -5514,7 +5607,6 @@ var YtDlpError = class extends Error {
|
|
|
5514
5607
|
this.stderrTail = stderrTail;
|
|
5515
5608
|
this.name = "YtDlpError";
|
|
5516
5609
|
}
|
|
5517
|
-
stderrTail;
|
|
5518
5610
|
};
|
|
5519
5611
|
function tail(text, maxLines) {
|
|
5520
5612
|
return text.split("\n").slice(-maxLines).join("\n");
|
|
@@ -8478,7 +8570,7 @@ var imageSearchNode = delegated({
|
|
|
8478
8570
|
id: "image_search",
|
|
8479
8571
|
version: "1.0.0",
|
|
8480
8572
|
category: "image",
|
|
8481
|
-
summary: "Agentic image search across Google Images, stock photography (
|
|
8573
|
+
summary: "Agentic image search across Google Images, free stock photography (Pexels and Pixabay), and Pinterest. An LLM agent picks the search tools and queries, selects the best matches, and the results are downloaded into canvas assets.",
|
|
8482
8574
|
when_to_use: "Use to gather real-world reference or inspiration images for a prompt (e.g. several photos of an australian shepherd) so a later step or the user can pick the best one. Not for creating new imagery \u2014 use image_generate for that.",
|
|
8483
8575
|
inputs: z23.object({}).loose(),
|
|
8484
8576
|
params: ImageSearchParams,
|
|
@@ -9230,6 +9322,7 @@ export {
|
|
|
9230
9322
|
describeFailureReason,
|
|
9231
9323
|
AD_FORMAT_PLATFORMS,
|
|
9232
9324
|
platformFormats,
|
|
9325
|
+
frameRealismDirection,
|
|
9233
9326
|
SEEDANCE_DURATIONS,
|
|
9234
9327
|
ELEVENLABS_MAX_MUSIC_LENGTH_MS,
|
|
9235
9328
|
IMAGE_GENERATE_MODELS,
|
|
@@ -9245,6 +9338,7 @@ export {
|
|
|
9245
9338
|
promptMaxLength,
|
|
9246
9339
|
maxInputSlot,
|
|
9247
9340
|
maxInputReferences,
|
|
9341
|
+
bestSupportedQuality,
|
|
9248
9342
|
nearestSupportedAspectRatio,
|
|
9249
9343
|
nearestSupportedImageSize,
|
|
9250
9344
|
estimateVideoCredits,
|
|
@@ -9285,4 +9379,4 @@ export {
|
|
|
9285
9379
|
defaultRegistry,
|
|
9286
9380
|
createEngineFromEnv
|
|
9287
9381
|
};
|
|
9288
|
-
//# sourceMappingURL=chunk-
|
|
9382
|
+
//# sourceMappingURL=chunk-LOUE7GTU.js.map
|