@oxy-hq/sdk 2.3.0 → 2.5.0

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.
@@ -0,0 +1,2258 @@
1
+ // @oxy/sdk - TypeScript SDK for Oxy data platform
2
+ import * as React from "react";
3
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
4
+
5
+ //#region src/customer-app/logger.ts
6
+ let activeLogger = createConsoleLogger();
7
+ /** Replace the global logger. Pass `null` to silence everything. */
8
+ function setOxyAppLogger(logger) {
9
+ activeLogger = logger ?? silentLogger();
10
+ }
11
+ /** Used by the SDK internals; not part of the public surface. */
12
+ function getOxyAppLogger() {
13
+ return activeLogger;
14
+ }
15
+ function createConsoleLogger() {
16
+ return { log(level, msg, ctx) {
17
+ if (typeof console === "undefined") return;
18
+ const prefix = "[oxy-app]";
19
+ const args = ctx ? [
20
+ prefix,
21
+ msg,
22
+ ctx
23
+ ] : [prefix, msg];
24
+ switch (level) {
25
+ case "debug":
26
+ console.debug(...args);
27
+ break;
28
+ case "info":
29
+ console.info(...args);
30
+ break;
31
+ case "warn":
32
+ console.warn(...args);
33
+ break;
34
+ case "error":
35
+ console.error(...args);
36
+ break;
37
+ }
38
+ } };
39
+ }
40
+ function silentLogger() {
41
+ return { log() {} };
42
+ }
43
+
44
+ //#endregion
45
+ //#region src/customer-app/errors.ts
46
+ /**
47
+ * Error thrown by all customer-app hooks when an API call returns a
48
+ * non-2xx response. Carries the structured `code` + `hint` the server
49
+ * emits so bundle UIs can render an actionable message instead of
50
+ * "404: { ...json... }".
51
+ */
52
+ var OxyApiError = class extends Error {
53
+ constructor(opts) {
54
+ const base = opts.message || `HTTP ${opts.status}`;
55
+ const code = opts.code ? ` [${opts.code}]` : "";
56
+ const hint = opts.hint ? `\n\n${opts.hint}` : "";
57
+ super(`${base}${code}${hint}`);
58
+ this.name = "OxyApiError";
59
+ this.status = opts.status;
60
+ this.code = opts.code ?? null;
61
+ this.hint = opts.hint ?? null;
62
+ }
63
+ };
64
+ /**
65
+ * Read a non-2xx response from oxy and return an `OxyApiError`.
66
+ * Parses the JSON envelope when present; falls back to raw text
67
+ * (truncated to 240 chars so a runaway HTML error page doesn't
68
+ * dominate the bundle UI).
69
+ */
70
+ async function apiErrorFromResponse(resp) {
71
+ let body;
72
+ let raw = "";
73
+ try {
74
+ raw = await resp.text();
75
+ body = raw ? JSON.parse(raw) : void 0;
76
+ } catch {}
77
+ if (body && typeof body === "object") {
78
+ const b = body;
79
+ return new OxyApiError({
80
+ status: resp.status,
81
+ message: typeof b.message === "string" ? b.message : `HTTP ${resp.status}`,
82
+ code: typeof b.code === "string" ? b.code : null,
83
+ hint: typeof b.hint === "string" ? b.hint : null
84
+ });
85
+ }
86
+ const snippet = raw.length > 240 ? `${raw.slice(0, 237)}…` : raw;
87
+ return new OxyApiError({
88
+ status: resp.status,
89
+ message: snippet || `HTTP ${resp.status}`
90
+ });
91
+ }
92
+ const ARCH_DOC = "internal-docs/customer-apps.md";
93
+ /** Interpret a thrown error as a structured report for UI display. */
94
+ function interpretCustomerAppError(err) {
95
+ const message = err instanceof Error ? err.message : String(err);
96
+ if (/Failed to load oxy-app\.json.*HTTP 404/.test(message)) return {
97
+ title: "Manifest not found",
98
+ message,
99
+ hint: "The bundle is being served, but oxy-app.json was not. Check that public/oxy-app.json is committed in the customer-app repo and that the build copied it into the static output. If you're using Next.js, anything under public/ is auto-copied to out/.",
100
+ docs: ARCH_DOC
101
+ };
102
+ if (/Failed to load oxy-app\.json/.test(message)) return {
103
+ title: "Manifest could not be loaded",
104
+ message,
105
+ hint: "Network error fetching the manifest. Confirm the bundle is being served from a path that matches OXY_APP_BASE_PATH at build time — a mismatch causes assets and the manifest to 404.",
106
+ docs: ARCH_DOC
107
+ };
108
+ if (/schemaVersion/i.test(message)) return {
109
+ title: "Manifest schema mismatch",
110
+ message,
111
+ hint: "This bundle was built against a different version of the data-product contract than the SDK it ships. Rebuild the bundle with a compatible @oxy-hq/sdk version.",
112
+ docs: ARCH_DOC
113
+ };
114
+ if (/^401:/m.test(message)) return {
115
+ title: "Session expired",
116
+ message,
117
+ hint: "Reload the page to re-authenticate via oxy's session cookie.",
118
+ docs: ARCH_DOC
119
+ };
120
+ if (/^403:.*origin not allowed/im.test(message)) return {
121
+ title: "Request origin not allowed",
122
+ message,
123
+ hint: "The bundle's host isn't in oxy's OXY_ALLOWED_ORIGINS. Production: add the bundle's serving origin to the env var. Local dev: oxy auto-allows http://localhost:5173 and :5174.",
124
+ docs: ARCH_DOC
125
+ };
126
+ if (/^403:.*not a member/im.test(message)) return {
127
+ title: "Access denied",
128
+ message,
129
+ hint: "Your account isn't a member of the org that owns this project. Ask an org owner to add you.",
130
+ docs: ARCH_DOC
131
+ };
132
+ if (/^403:.*SELECT.*WITH/im.test(message)) return {
133
+ title: "Query rejected — read-only endpoint",
134
+ message,
135
+ hint: "This proxy only runs SELECT or WITH queries. Mutations (INSERT/UPDATE/DELETE/DROP) are not allowed from customer-app bundles.",
136
+ docs: ARCH_DOC
137
+ };
138
+ if (/^403:/m.test(message)) return {
139
+ title: "Access denied",
140
+ message,
141
+ hint: "The request was rejected by the server. Check the oxy server logs for details.",
142
+ docs: ARCH_DOC
143
+ };
144
+ if (/^404:/m.test(message) && /project/i.test(message)) return {
145
+ title: "Project not found",
146
+ message,
147
+ hint: "The projectId in oxy-app.json doesn't match any registered project. Confirm the manifest's projectId is a real UUID for this deployment.",
148
+ docs: ARCH_DOC
149
+ };
150
+ if (/^400:.*sql.*must be non-empty/im.test(message)) return {
151
+ title: "Empty SQL",
152
+ message,
153
+ hint: "useQuery was called with an empty or whitespace-only `sql`. Pass a real query, or set `enabled: false` to skip the call.",
154
+ docs: ARCH_DOC
155
+ };
156
+ if (/^400:/m.test(message) && /query failed/i.test(message)) return {
157
+ title: "Query failed",
158
+ message,
159
+ hint: "The SQL ran but the warehouse rejected it. Full error in the oxy server logs (look for the projects::query span).",
160
+ docs: ARCH_DOC
161
+ };
162
+ if (/^502:/m.test(message)) return {
163
+ title: "Warehouse unreachable",
164
+ message,
165
+ hint: "Oxy couldn't reach the configured database. Check connector config + warehouse health.",
166
+ docs: ARCH_DOC
167
+ };
168
+ if (/Unexpected token '<'|<!doctype/i.test(message)) return {
169
+ title: "Fetched HTML where JSON was expected",
170
+ message,
171
+ hint: "Most likely the built bundle is stale — built against an old SDK whose endpoints no longer exist on the server. Rebuild the bundle (vite build) with @oxy-hq/sdk@^2.0.0 and reload. If the bundle is current, check that OXY_APP_BASE_PATH matches the path the customer-app row is served at.",
172
+ docs: ARCH_DOC
173
+ };
174
+ return {
175
+ title: "Unexpected error loading the dashboard",
176
+ message,
177
+ hint: "Check the browser console for the full stack trace, and the oxy server logs for the corresponding request.",
178
+ docs: ARCH_DOC
179
+ };
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/customer-app/inject.ts
184
+ /**
185
+ * Read the runtime app-config oxy injected at serve time. Returns
186
+ * `undefined` outside the browser or when the global isn't set
187
+ * (`pnpm dev` against a non-oxy server, etc. — manifest hints are
188
+ * the fallback).
189
+ */
190
+ function readInjectedAppConfig() {
191
+ if (typeof window === "undefined") return void 0;
192
+ return window.__OXY_APP__;
193
+ }
194
+
195
+ //#endregion
196
+ //#region src/customer-app/manifest.ts
197
+ let cached = null;
198
+ /**
199
+ * Load + validate the manifest. Cached after the first call so callers
200
+ * can invoke this from every component without coordinating.
201
+ */
202
+ function loadCustomerAppManifest(options = {}) {
203
+ if (!cached) cached = fetchAndValidate(options);
204
+ return cached;
205
+ }
206
+ /** For tests: reset the cache between runs. */
207
+ function _resetCustomerAppManifestCacheForTest() {
208
+ cached = null;
209
+ }
210
+ async function fetchAndValidate(options) {
211
+ const log = getOxyAppLogger();
212
+ const injected = readInjectedAppConfig();
213
+ const manifestUrl = options.manifestUrl ?? defaultManifestUrl(injected);
214
+ log.log("info", "loading manifest", {
215
+ manifestUrl,
216
+ injectionPresent: !!injected,
217
+ orgSlug: injected?.orgSlug,
218
+ appSlug: injected?.slug,
219
+ appId: injected?.appId
220
+ });
221
+ const startedAt = Date.now();
222
+ const res = await fetch(manifestUrl, { credentials: "same-origin" });
223
+ if (!res.ok) {
224
+ log.log("error", "manifest fetch failed", {
225
+ manifestUrl,
226
+ status: res.status,
227
+ statusText: res.statusText
228
+ });
229
+ throw new Error(`Failed to load oxy-app.json from ${manifestUrl} (HTTP ${res.status}). The customer-app repo must commit this file alongside the bundle.`);
230
+ }
231
+ const manifest = validateManifest(await res.json(), manifestUrl);
232
+ const resolved = {
233
+ manifest,
234
+ productNames: [],
235
+ orgSlug: injected?.orgSlug ?? "",
236
+ appSlug: injected?.slug ?? "",
237
+ apiBaseUrl: injected?.apiBaseUrl || "",
238
+ appId: injected?.appId,
239
+ projectId: injected?.projectId ?? manifest.projectId
240
+ };
241
+ log.log("info", "manifest ready", {
242
+ durationMs: Date.now() - startedAt,
243
+ schemaVersion: manifest.schemaVersion,
244
+ slug: manifest.slug
245
+ });
246
+ return resolved;
247
+ }
248
+ /**
249
+ * Default manifest URL.
250
+ *
251
+ * Resolution order (bundler-agnostic):
252
+ * 1. `window.__OXY_APP__.orgSlug`/`slug` injection → the canonical
253
+ * `/customer-apps/<org>/<app>/oxy-app.json`. Works for every
254
+ * bundle oxy serves regardless of how it was built.
255
+ * 2. `NEXT_PUBLIC_APP_BASE_PATH` env var — kept for backward compat
256
+ * with Next.js bundles that bake basePath at build time.
257
+ * 3. Empty basePath → `/oxy-app.json` (only matches when running in
258
+ * a `vite dev` / `next dev` root mount; will 404 under oxy).
259
+ */
260
+ function defaultManifestUrl(injected) {
261
+ if (injected?.orgSlug && injected?.slug) return `/customer-apps/${encodeURIComponent(injected.orgSlug)}/${encodeURIComponent(injected.slug)}/oxy-app.json`;
262
+ return "/oxy-app.json";
263
+ }
264
+ /**
265
+ * Validate a v2 manifest. Required: schemaVersion === 2, slug (non-empty).
266
+ * Optional: name (display), orgSlug (dev-time hint for the admin dialog),
267
+ * projectId (dev-time hint when there's no server-side injection).
268
+ *
269
+ * At serve time, oxy's identity injection (window.__OXY_APP__) overrides
270
+ * the manifest's orgSlug/projectId — the manifest fields are advisory.
271
+ */
272
+ function validateManifest(raw, url) {
273
+ if (!isRecord(raw)) throw new Error(`Manifest at ${url} is not a JSON object`);
274
+ if (raw.schemaVersion !== 2) throw new Error(`oxy-app.json: schemaVersion must be 2 (got ${JSON.stringify(raw.schemaVersion)}). v1 manifests are no longer supported — upgrade to the identity-only shape.`);
275
+ if (raw.products !== void 0 || raw.writers !== void 0) throw new Error(`oxy-app.json is schemaVersion 2 (identity-only); \`products\` and \`writers\` are no longer supported`);
276
+ if (typeof raw.slug !== "string" || !raw.slug.trim()) throw new Error("oxy-app.json: `slug` is required and must be a non-empty string");
277
+ return {
278
+ schemaVersion: 2,
279
+ name: typeof raw.name === "string" ? raw.name : void 0,
280
+ slug: raw.slug,
281
+ orgSlug: typeof raw.orgSlug === "string" ? raw.orgSlug : void 0,
282
+ projectId: typeof raw.projectId === "string" ? raw.projectId : void 0,
283
+ functions: raw.functions !== void 0 ? validateFunctions(raw.functions) : void 0,
284
+ ask: isRecord(raw.ask) ? {
285
+ agent: typeof raw.ask.agent === "string" ? raw.ask.agent : void 0,
286
+ suggestedQuestions: Array.isArray(raw.ask.suggestedQuestions) ? raw.ask.suggestedQuestions.filter((q) => typeof q === "string") : void 0
287
+ } : void 0
288
+ };
289
+ }
290
+ const FUNCTION_NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
291
+ /**
292
+ * Validate the optional `functions` map. Each key is a function name;
293
+ * each value declares how the function is invoked. Mirrors the
294
+ * server-side validation in `customer_apps_publish.rs` so a bad
295
+ * manifest fails at build, not at publish.
296
+ */
297
+ function validateFunctions(raw) {
298
+ if (!isRecord(raw)) throw new Error("oxy-app.json: `functions` must be an object keyed by function name");
299
+ const out = {};
300
+ for (const [fnName, value] of Object.entries(raw)) {
301
+ if (!FUNCTION_NAME_RE.test(fnName)) throw new Error(`oxy-app.json: function name "${fnName}" must match ^[a-z][a-z0-9-]{0,63}$`);
302
+ if (!isRecord(value)) throw new Error(`oxy-app.json: function "${fnName}" must be an object`);
303
+ const fn = {};
304
+ if (value.entry !== void 0) {
305
+ if (typeof value.entry !== "string" || !value.entry.trim()) throw new Error(`oxy-app.json: function "${fnName}" \`entry\` must be a non-empty string`);
306
+ fn.entry = value.entry;
307
+ }
308
+ if (value.schedule !== void 0) {
309
+ if (typeof value.schedule !== "string" || !value.schedule.trim()) throw new Error(`oxy-app.json: function "${fnName}" \`schedule\` must be a cron string`);
310
+ fn.schedule = value.schedule;
311
+ }
312
+ if (value.timezone !== void 0) {
313
+ if (typeof value.timezone !== "string") throw new Error(`oxy-app.json: function "${fnName}" \`timezone\` must be a string`);
314
+ fn.timezone = value.timezone;
315
+ }
316
+ if (value.route !== void 0) {
317
+ if (typeof value.route !== "boolean") throw new Error(`oxy-app.json: function "${fnName}" \`route\` must be a boolean`);
318
+ fn.route = value.route;
319
+ }
320
+ if (value.airwayStep !== void 0) {
321
+ const step = value.airwayStep;
322
+ if (!isRecord(step) || typeof step.pipeline !== "string" || typeof step.resource !== "string") throw new Error(`oxy-app.json: function "${fnName}" \`airwayStep\` must be { pipeline, resource }`);
323
+ fn.airwayStep = {
324
+ pipeline: step.pipeline,
325
+ resource: step.resource
326
+ };
327
+ }
328
+ if (value.timeoutSeconds !== void 0) {
329
+ const t = value.timeoutSeconds;
330
+ if (typeof t !== "number" || !Number.isInteger(t) || t < 1 || t > 300) throw new Error(`oxy-app.json: function "${fnName}" \`timeoutSeconds\` must be an integer in [1, 300]`);
331
+ fn.timeoutSeconds = t;
332
+ }
333
+ if (value.cache !== void 0) {
334
+ const c = value.cache;
335
+ if (!isRecord(c)) throw new Error(`oxy-app.json: function "${fnName}" \`cache\` must be an object`);
336
+ if (c.ttlSeconds !== void 0) {
337
+ const ttl = c.ttlSeconds;
338
+ if (typeof ttl !== "number" || !Number.isInteger(ttl) || ttl < 1) throw new Error(`oxy-app.json: function "${fnName}" \`cache.ttlSeconds\` must be a positive integer`);
339
+ fn.cache = { ttlSeconds: ttl };
340
+ }
341
+ }
342
+ if (value.retries !== void 0) {
343
+ const r = value.retries;
344
+ if (!isRecord(r)) throw new Error(`oxy-app.json: function "${fnName}" \`retries\` must be an object`);
345
+ const retries = {};
346
+ for (const key of [
347
+ "maxAttempts",
348
+ "minTimeoutMs",
349
+ "maxTimeoutMs"
350
+ ]) {
351
+ const n = r[key];
352
+ if (n !== void 0) {
353
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1) throw new Error(`oxy-app.json: function "${fnName}" \`retries.${key}\` must be a positive integer`);
354
+ retries[key] = n;
355
+ }
356
+ }
357
+ fn.retries = retries;
358
+ }
359
+ if (value.inputExample !== void 0) fn.inputExample = value.inputExample;
360
+ const hasSchedule = fn.schedule !== void 0;
361
+ const hasAirway = fn.airwayStep !== void 0;
362
+ if (!(fn.route ?? !(hasSchedule || hasAirway)) && !hasSchedule && !hasAirway) throw new Error(`oxy-app.json: function "${fnName}" must enable at least one of route/schedule/airwayStep`);
363
+ out[fnName] = fn;
364
+ }
365
+ return out;
366
+ }
367
+ function isRecord(v) {
368
+ return typeof v === "object" && v !== null && !Array.isArray(v);
369
+ }
370
+
371
+ //#endregion
372
+ //#region src/customer-app/function-invoke.ts
373
+ const inflight$1 = /* @__PURE__ */ new Map();
374
+ /**
375
+ * Dedup key for an invocation: function name + its (stable-serialized) body,
376
+ * joined by a newline. Function names are `[a-z][a-z0-9-]*` (no newline), so
377
+ * the separator can never collide with a name.
378
+ */
379
+ function functionInvokeKey(name, body) {
380
+ return `${name}\n${JSON.stringify(body ?? {})}`;
381
+ }
382
+ /**
383
+ * Run `run()` unless an identical invocation is already in flight, in which
384
+ * case share its promise. The entry is removed once the promise settles — so
385
+ * this dedups concurrency only, it does NOT memoize the result.
386
+ */
387
+ function sharedFunctionInvoke(key, run) {
388
+ const existing = inflight$1.get(key);
389
+ if (existing) return existing;
390
+ const p = run().finally(() => {
391
+ inflight$1.delete(key);
392
+ });
393
+ inflight$1.set(key, p);
394
+ return p;
395
+ }
396
+
397
+ //#endregion
398
+ //#region src/customer-app/function-sse.ts
399
+ /**
400
+ * Read a `text/event-stream` function response to completion. Resolves with the
401
+ * decoded result + captured logs, or rejects (with `.logs` attached) on an
402
+ * `event: error` frame / a stream that ends without a terminal event.
403
+ */
404
+ async function readFunctionSseStream(resp) {
405
+ const reader = resp.body?.getReader();
406
+ if (!reader) throw new Error("function response has no body stream");
407
+ const decoder = new TextDecoder();
408
+ let buffer = "";
409
+ let dataPayload = "";
410
+ const logs = [];
411
+ const handleFrame = (frame) => {
412
+ let event = "message";
413
+ let data = "";
414
+ for (const line of frame.split("\n")) if (line.startsWith("event:")) event = line.slice(6).trim();
415
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
416
+ if (event === "log") try {
417
+ const l = JSON.parse(data);
418
+ logs.push({
419
+ level: String(l.level ?? "info"),
420
+ message: String(l.message ?? "")
421
+ });
422
+ } catch {}
423
+ else if (event === "data") dataPayload = data;
424
+ else if (event === "done") return {
425
+ done: true,
426
+ value: dataPayload ? JSON.parse(dataPayload) : null
427
+ };
428
+ else if (event === "error") {
429
+ const payload = data ? JSON.parse(data) : {};
430
+ const err = new Error(payload.message || payload.error || "function invocation failed");
431
+ err.name = payload.error || "FunctionError";
432
+ err.logs = logs;
433
+ throw err;
434
+ }
435
+ };
436
+ for (;;) {
437
+ const { done, value } = await reader.read();
438
+ if (done) break;
439
+ buffer += decoder.decode(value, { stream: true });
440
+ let sep;
441
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
442
+ const frame = buffer.slice(0, sep);
443
+ buffer = buffer.slice(sep + 2);
444
+ const result = handleFrame(frame);
445
+ if (result) return {
446
+ value: result.value,
447
+ logs
448
+ };
449
+ }
450
+ }
451
+ throw new Error("function stream ended without a terminal event");
452
+ }
453
+
454
+ //#endregion
455
+ //#region src/customer-app/interpolate.ts
456
+ /**
457
+ * Interpolate `{{ params.X }}` and `{{ params.X | sqlquote }}` placeholders
458
+ * in a SQL template.
459
+ *
460
+ * - `{{ params.X | sqlquote }}` — quote strings ('foo'), pass numbers and
461
+ * booleans raw, nullish becomes NULL. Mirrors the server's Jinja sqlquote
462
+ * filter.
463
+ * - `{{ params.X }}` — raw pass-through. Used for already-trusted values
464
+ * (numbers, identifiers the caller has validated). Caller is responsible
465
+ * for safety.
466
+ *
467
+ * Not a security boundary. The server still gates SQL execution by
468
+ * project membership. Bundles that accept untrusted user input should
469
+ * use `| sqlquote` or validate/coerce before passing.
470
+ */
471
+ function interpolateSqlParams(sql, params) {
472
+ return sql.replace(/\{\{\s*params\.([a-zA-Z0-9_]+)(\s*\|\s*sqlquote)?\s*\}\}/g, (_match, key, sqlquote) => {
473
+ const v = params[key];
474
+ if (v === null || v === void 0) return "NULL";
475
+ if (sqlquote) {
476
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
477
+ return `'${String(v).replace(/'/g, "''")}'`;
478
+ }
479
+ return String(v);
480
+ });
481
+ }
482
+
483
+ //#endregion
484
+ //#region src/customer-app/markdown.ts
485
+ /**
486
+ * Allowlist for `[text](url)` href values in agent-emitted markdown.
487
+ * Markdown comes from an LLM, which sits across an external trust
488
+ * boundary — without this filter, a `javascript:` URL produced by
489
+ * the model would render as a clickable XSS in the bundle's origin.
490
+ *
491
+ * Accepts:
492
+ * - http(s):// absolute URLs
493
+ * - mailto: addresses
494
+ * - root-relative paths (`/foo`)
495
+ * - same-page fragments (`#section`)
496
+ *
497
+ * Rejects everything else, including `javascript:`, `data:`,
498
+ * protocol-relative `//evil.com`, and any other scheme. Comparison
499
+ * is case-insensitive after stripping leading whitespace + ASCII
500
+ * control bytes (browsers strip these before scheme resolution, so
501
+ * `java\tscript:` would otherwise slip past a naive prefix check).
502
+ */
503
+ function isSafeLinkHref(raw) {
504
+ let cleaned = "";
505
+ for (let i = 0; i < raw.length; i++) {
506
+ const cc = raw.charCodeAt(i);
507
+ if (cc > 32 && cc !== 127) cleaned += raw[i];
508
+ }
509
+ if (cleaned === "") return false;
510
+ if (cleaned.startsWith("#") || cleaned.startsWith("/")) {
511
+ if (cleaned.startsWith("//")) return false;
512
+ return true;
513
+ }
514
+ const lower = cleaned.toLowerCase();
515
+ return lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("mailto:");
516
+ }
517
+ /** Unescape GFM cell escapes (`\|` → `|`, `\\` → `\`). */
518
+ function unescapeCell(cell) {
519
+ return cell.replace(/\\([|\\])/g, "$1");
520
+ }
521
+ /** Split a GFM table row into trimmed cells, dropping the outer pipes.
522
+ * Splits on UNESCAPED `|` only — a `\|` inside a cell is a literal pipe,
523
+ * not a column separator — then unescapes each cell. */
524
+ function splitTableRow(line) {
525
+ const s = line.trim();
526
+ const cells = [];
527
+ let cur = "";
528
+ for (let i = 0; i < s.length; i++) {
529
+ const ch = s[i];
530
+ if (ch === "\\" && i + 1 < s.length) {
531
+ cur += ch + s[i + 1];
532
+ i++;
533
+ continue;
534
+ }
535
+ if (ch === "|") {
536
+ cells.push(cur);
537
+ cur = "";
538
+ continue;
539
+ }
540
+ cur += ch;
541
+ }
542
+ cells.push(cur);
543
+ if (cells.length > 1 && cells[0].trim() === "") cells.shift();
544
+ if (cells.length > 1 && cells[cells.length - 1].trim() === "") cells.pop();
545
+ return cells.map((c) => unescapeCell(c.trim()));
546
+ }
547
+ /** A GFM delimiter row: every cell is `-`s with optional leading/trailing `:`. */
548
+ function isTableDelimiter(line) {
549
+ if (!line?.includes("-")) return false;
550
+ const cells = splitTableRow(line);
551
+ return cells.length > 0 && cells.every((c) => /^:?-{1,}:?$/.test(c));
552
+ }
553
+ /** A table starts at `idx` when that line has a pipe and the next line is a
554
+ * delimiter row. */
555
+ function isTableStart(lines, idx) {
556
+ return (lines[idx] ?? "").includes("|") && isTableDelimiter(lines[idx + 1] ?? "");
557
+ }
558
+
559
+ //#endregion
560
+ //#region src/customer-app/query-cache.ts
561
+ const SWR_TTL_MS = 3e4;
562
+ const inflight = /* @__PURE__ */ new Map();
563
+ const cache = /* @__PURE__ */ new Map();
564
+ function queryKey(projectId, db, sql) {
565
+ return `${projectId} ${db ?? ""} ${sql}`;
566
+ }
567
+ function getCached(projectId, sql, db) {
568
+ const e = cache.get(queryKey(projectId, db, sql));
569
+ return e && Date.now() - e.at < SWR_TTL_MS ? e.data : void 0;
570
+ }
571
+ /** Fetch with in-flight dedup + cache. `force` bypasses the fresh-cache
572
+ * short-circuit (used by refetch) but still dedupes a concurrent in-flight. */
573
+ async function sharedQuery(fetcher, projectId, sql, db, opts = {}) {
574
+ const key = queryKey(projectId, db, sql);
575
+ if (!opts.force) {
576
+ const fresh = getCached(projectId, sql, db);
577
+ if (fresh) return fresh;
578
+ }
579
+ const existing = inflight.get(key);
580
+ if (existing) return existing;
581
+ const body = JSON.stringify({
582
+ sql,
583
+ ...db ? { database: db } : {}
584
+ });
585
+ const p = (async () => {
586
+ const resp = await fetcher(`/api/projects/${projectId}/query`, {
587
+ method: "POST",
588
+ headers: { "content-type": "application/json" },
589
+ body
590
+ });
591
+ if (!resp.ok) throw await apiErrorFromResponse(resp);
592
+ const data = await resp.json();
593
+ cache.set(key, {
594
+ at: Date.now(),
595
+ data
596
+ });
597
+ return data;
598
+ })().finally(() => inflight.delete(key));
599
+ inflight.set(key, p);
600
+ return p;
601
+ }
602
+
603
+ //#endregion
604
+ //#region src/customer-app/react.tsx
605
+ function defaultFetcher(input, init) {
606
+ return fetch(input, {
607
+ credentials: "include",
608
+ ...init
609
+ });
610
+ }
611
+ /**
612
+ * Resolve relative ("/…") request paths against `backendUrl` so the SDK's API
613
+ * calls reach a cross-origin oxy backend instead of the app's own origin.
614
+ *
615
+ * This is what lets a standalone dev app (e.g. served on `localhost:3005`)
616
+ * drive the wired shell — `shell-context`, Ask Oxygen agent asks, events —
617
+ * against oxy on another origin (`localhost:3000`) WITHOUT a same-origin dev
618
+ * proxy. The target origin must permit the app's origin (oxy's main `/api`
619
+ * allows configured dev origins + `credentials`); the external data API is a
620
+ * separate, wildcard-CORS surface.
621
+ *
622
+ * Opt-in: when `backendUrl` is unset the base fetcher is returned unchanged, so
623
+ * apps served same-origin by oxy keep their existing relative-URL behaviour.
624
+ * Absolute URLs and non-string inputs pass through untouched (no double-prefix).
625
+ */
626
+ function withBackendBase(base, backendUrl) {
627
+ if (!backendUrl) return base;
628
+ const origin = backendUrl.replace(/\/+$/, "");
629
+ return (input, init) => base(typeof input === "string" && input.startsWith("/") ? origin + input : input, init);
630
+ }
631
+ const OxyAppContext = React.createContext(void 0);
632
+ /**
633
+ * Top-level provider. Loads the manifest once on mount; children only
634
+ * render after the manifest is ready (or the error fallback fires).
635
+ */
636
+ function OxyAppProvider(props) {
637
+ const { manifestOptions, fallback, errorFallback, fetcher: fetcherProp, backendUrl, children } = props;
638
+ const fetcher = React.useMemo(() => withBackendBase(fetcherProp ?? defaultFetcher, backendUrl), [fetcherProp, backendUrl]);
639
+ const [state, setState] = React.useState({
640
+ status: "loading",
641
+ fetcher
642
+ });
643
+ React.useEffect(() => {
644
+ let cancelled = false;
645
+ loadCustomerAppManifest(manifestOptions).then((resolved) => {
646
+ if (!cancelled) setState({
647
+ status: "ready",
648
+ resolved,
649
+ fetcher
650
+ });
651
+ }).catch((e) => {
652
+ if (!cancelled) setState({
653
+ status: "error",
654
+ error: interpretCustomerAppError(e),
655
+ fetcher
656
+ });
657
+ });
658
+ return () => {
659
+ cancelled = true;
660
+ };
661
+ }, [manifestOptions, fetcher]);
662
+ if (state.status === "error" && state.error) {
663
+ const err = state.error;
664
+ return /* @__PURE__ */ jsx(OxyAppContext.Provider, {
665
+ value: state,
666
+ children: errorFallback ? errorFallback(err) : defaultErrorFallback(err)
667
+ });
668
+ }
669
+ if (state.status === "loading") return /* @__PURE__ */ jsx(OxyAppContext.Provider, {
670
+ value: state,
671
+ children: fallback ?? null
672
+ });
673
+ return /* @__PURE__ */ jsx(OxyAppContext.Provider, {
674
+ value: state,
675
+ children
676
+ });
677
+ }
678
+ function defaultErrorFallback(err) {
679
+ return /* @__PURE__ */ jsxs("div", {
680
+ style: {
681
+ margin: "2rem auto",
682
+ maxWidth: "640px",
683
+ padding: "1rem",
684
+ border: "1px solid #fca5a5",
685
+ background: "#fee2e2",
686
+ color: "#991b1b",
687
+ borderRadius: "8px",
688
+ fontFamily: "system-ui, -apple-system, sans-serif",
689
+ fontSize: "14px"
690
+ },
691
+ children: [
692
+ /* @__PURE__ */ jsx("div", {
693
+ style: { fontWeight: 600 },
694
+ children: err.title
695
+ }),
696
+ /* @__PURE__ */ jsx("pre", {
697
+ style: {
698
+ fontSize: "12px",
699
+ marginTop: "4px"
700
+ },
701
+ children: err.message
702
+ }),
703
+ /* @__PURE__ */ jsxs("div", {
704
+ style: { marginTop: "12px" },
705
+ children: [
706
+ /* @__PURE__ */ jsx("strong", { children: "What to try:" }),
707
+ " ",
708
+ err.hint
709
+ ]
710
+ })
711
+ ]
712
+ });
713
+ }
714
+ /**
715
+ * Emit a one-time `console.warn` the first time a beta hook is
716
+ * used in a given page load. Bundles upgrading from a future GA
717
+ * release won't see the warning; the message lets us flag rough
718
+ * edges without breaking the build.
719
+ */
720
+ const _warnedBeta = /* @__PURE__ */ new Set();
721
+ function warnBetaOnce(name) {
722
+ if (_warnedBeta.has(name)) return;
723
+ _warnedBeta.add(name);
724
+ if (typeof console !== "undefined" && typeof console.warn === "function") console.warn(`[@oxy-hq/sdk] \`${name}\` is in beta — interface and behavior may change. See https://github.com/oxy-hq/customer-apps for caveats and the migration guide.`);
725
+ }
726
+ /**
727
+ * Read the resolved manifest from context. Throws if called outside
728
+ * `<OxyAppProvider>` — that's a programmer error worth surfacing
729
+ * loudly, not silently swallowing.
730
+ */
731
+ function useResolvedManifest() {
732
+ const ctx = React.useContext(OxyAppContext);
733
+ if (!ctx) throw new Error("useResolvedManifest must be called inside <OxyAppProvider>");
734
+ if (ctx.status !== "ready" || !ctx.resolved) throw new Error("useResolvedManifest called before manifest finished loading. Use the provider's `fallback` prop to render while loading.");
735
+ return ctx.resolved;
736
+ }
737
+ /**
738
+ * Low-level hook that returns the raw context value (including the
739
+ * fetcher). Prefer `useResolvedManifest` for manifest access; use
740
+ * this only when you need the fetcher or identity without requiring
741
+ * the manifest to be ready (e.g. inside `useQuery`, or the shell
742
+ * chrome, which must never block the app on the manifest load).
743
+ */
744
+ function useOxyApp() {
745
+ const ctx = React.useContext(OxyAppContext);
746
+ if (!ctx) throw new Error("useOxyApp must be called inside <OxyAppProvider>");
747
+ return {
748
+ projectId: ctx.resolved?.projectId,
749
+ appSlug: ctx.resolved?.appSlug,
750
+ orgSlug: ctx.resolved?.orgSlug,
751
+ fetcher: ctx.fetcher
752
+ };
753
+ }
754
+ /**
755
+ * Execute an ad-hoc SQL query against the project linked to this
756
+ * customer app. The query is specified inline by the caller; no
757
+ * manifest declaration is involved.
758
+ *
759
+ * Re-runs whenever `input` or enabled `params` change. Use the
760
+ * `enabled` option to defer the first fetch until required data is
761
+ * available (e.g. a user-supplied filter value).
762
+ */
763
+ function useQuery(input, opts = {}) {
764
+ const { projectId, fetcher } = useOxyApp();
765
+ const enabled = opts.enabled !== false;
766
+ const paramsKey = JSON.stringify(opts.params);
767
+ const sqlWithParams = React.useMemo(() => interpolateSqlParams(input.sql, opts.params ?? {}), [input.sql, paramsKey]);
768
+ const [state, setState] = React.useState({
769
+ rows: [],
770
+ columns: [],
771
+ loading: enabled && !!projectId,
772
+ error: null
773
+ });
774
+ const [nonce, setNonce] = React.useState(0);
775
+ React.useEffect(() => {
776
+ if (!enabled || !projectId) {
777
+ setState((s) => s.loading ? {
778
+ ...s,
779
+ loading: false
780
+ } : s);
781
+ return;
782
+ }
783
+ let cancelled = false;
784
+ const cached = getCached(projectId, sqlWithParams, input.database);
785
+ if (cached && nonce === 0) {
786
+ const { columns, rows } = cached;
787
+ const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
788
+ setState({
789
+ rows: objects,
790
+ columns,
791
+ loading: false,
792
+ error: null
793
+ });
794
+ return;
795
+ }
796
+ setState((s) => ({
797
+ ...s,
798
+ loading: true,
799
+ error: null
800
+ }));
801
+ sharedQuery(fetcher, projectId, sqlWithParams, input.database, { force: nonce > 0 }).then(({ columns, rows }) => {
802
+ if (cancelled) return;
803
+ const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
804
+ setState({
805
+ rows: objects,
806
+ columns,
807
+ loading: false,
808
+ error: null
809
+ });
810
+ }).catch((err) => {
811
+ if (cancelled) return;
812
+ setState((s) => ({
813
+ ...s,
814
+ loading: false,
815
+ error: err instanceof Error ? err : new Error(String(err))
816
+ }));
817
+ });
818
+ return () => {
819
+ cancelled = true;
820
+ };
821
+ }, [
822
+ enabled,
823
+ projectId,
824
+ sqlWithParams,
825
+ input.database,
826
+ nonce,
827
+ fetcher
828
+ ]);
829
+ return {
830
+ rows: state.rows,
831
+ columns: state.columns,
832
+ loading: state.loading,
833
+ error: state.error,
834
+ refetch: () => setNonce((n) => n + 1)
835
+ };
836
+ }
837
+ /**
838
+ * Imperative hook for invoking an Oxy Function by name.
839
+ *
840
+ * ```tsx
841
+ * const refresh = useFunction("refresh-sales");
842
+ * <button disabled={refresh.isLoading} onClick={() => refresh.invoke({ full: true })}>
843
+ * Refresh
844
+ * </button>
845
+ * ```
846
+ */
847
+ function useFunction(name) {
848
+ const ctx = React.useContext(OxyAppContext);
849
+ if (!ctx) throw new Error("useFunction must be called inside <OxyAppProvider>");
850
+ const fetcher = ctx.fetcher;
851
+ const resolved = ctx.resolved;
852
+ const [state, setState] = React.useState({
853
+ data: null,
854
+ isLoading: false,
855
+ error: null,
856
+ logs: []
857
+ });
858
+ return {
859
+ invoke: React.useCallback(async (body, opts) => {
860
+ if (!resolved) throw new Error("useFunction.invoke called before the manifest finished loading. Render behind the provider's `fallback` until ready.");
861
+ const { orgSlug, appSlug, apiBaseUrl } = resolved;
862
+ const url = `${apiBaseUrl || ""}/customer-apps/${encodeURIComponent(orgSlug)}/${encodeURIComponent(appSlug)}/fn/${encodeURIComponent(name)}`;
863
+ setState((s) => ({
864
+ ...s,
865
+ isLoading: true,
866
+ error: null
867
+ }));
868
+ try {
869
+ const headers = {
870
+ "content-type": "application/json",
871
+ accept: "text/event-stream"
872
+ };
873
+ if (opts?.idempotencyKey) headers["idempotency-key"] = opts.idempotencyKey;
874
+ const result = await sharedFunctionInvoke(functionInvokeKey(name, body), async () => {
875
+ const resp = await fetcher(url, {
876
+ method: "POST",
877
+ headers,
878
+ body: JSON.stringify(body ?? {})
879
+ });
880
+ if (!resp.ok && resp.status !== 200) throw await apiErrorFromResponse(resp);
881
+ return readFunctionSseStream(resp);
882
+ });
883
+ setState({
884
+ data: result.value,
885
+ isLoading: false,
886
+ error: null,
887
+ logs: result.logs
888
+ });
889
+ return result.value;
890
+ } catch (err) {
891
+ const e = err instanceof Error ? err : new Error(String(err));
892
+ const logs = e.logs ?? [];
893
+ setState((s) => ({
894
+ ...s,
895
+ isLoading: false,
896
+ error: e,
897
+ logs
898
+ }));
899
+ throw e;
900
+ }
901
+ }, [
902
+ resolved,
903
+ fetcher,
904
+ name
905
+ ]),
906
+ data: state.data,
907
+ isLoading: state.isLoading,
908
+ error: state.error,
909
+ logs: state.logs
910
+ };
911
+ }
912
+ /**
913
+ * Run a semantic-layer query against the project's `.view.yml` /
914
+ * `.topic.yml` definitions. The server compiles to SQL and executes
915
+ * through the same connector path as `useQuery`, so result shape
916
+ * matches.
917
+ *
918
+ * Re-runs whenever the input shape changes (deep-compared via JSON).
919
+ * Use `opts.enabled = false` to defer the first fetch until required
920
+ * inputs (e.g. a user-picked filter value) are available.
921
+ */
922
+ function useSemanticQuery(input, opts = {}) {
923
+ const { projectId, fetcher } = useOxyApp();
924
+ const enabled = opts.enabled !== false;
925
+ const debug = opts.debug === true;
926
+ const inputKey = React.useMemo(() => JSON.stringify(input), [input]);
927
+ const [state, setState] = React.useState({
928
+ rows: [],
929
+ columns: [],
930
+ truncated: false,
931
+ sql: null,
932
+ loading: enabled && !!projectId,
933
+ error: null
934
+ });
935
+ const [nonce, setNonce] = React.useState(0);
936
+ React.useEffect(() => {
937
+ if (!enabled || !projectId) {
938
+ setState((s) => s.loading ? {
939
+ ...s,
940
+ loading: false
941
+ } : s);
942
+ return;
943
+ }
944
+ const ctrl = new AbortController();
945
+ let cancelled = false;
946
+ setState((s) => ({
947
+ ...s,
948
+ loading: true,
949
+ error: null
950
+ }));
951
+ const body = JSON.stringify({
952
+ v: 1,
953
+ topic: input.topic,
954
+ dimensions: input.dimensions ?? [],
955
+ measures: input.measures ?? [],
956
+ time_dimensions: input.time_dimensions ?? [],
957
+ filters: input.filters ?? [],
958
+ ...input.limit != null ? { limit: input.limit } : {}
959
+ });
960
+ const url = `/api/projects/${projectId}/semantic-query${debug ? "?debug=1" : ""}`;
961
+ fetcher(url, {
962
+ method: "POST",
963
+ headers: { "content-type": "application/json" },
964
+ body,
965
+ signal: ctrl.signal
966
+ }).then(async (resp) => {
967
+ if (!resp.ok) throw await apiErrorFromResponse(resp);
968
+ return resp.json();
969
+ }).then(({ columns, rows, truncated, sql }) => {
970
+ if (cancelled) return;
971
+ const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
972
+ setState({
973
+ rows: objects,
974
+ columns,
975
+ truncated,
976
+ sql: sql ?? null,
977
+ loading: false,
978
+ error: null
979
+ });
980
+ }).catch((err) => {
981
+ if (cancelled) return;
982
+ if (err instanceof DOMException && err.name === "AbortError") return;
983
+ setState((s) => ({
984
+ ...s,
985
+ loading: false,
986
+ error: err instanceof Error ? err : new Error(String(err))
987
+ }));
988
+ });
989
+ return () => {
990
+ cancelled = true;
991
+ ctrl.abort();
992
+ };
993
+ }, [
994
+ enabled,
995
+ projectId,
996
+ inputKey,
997
+ debug,
998
+ nonce,
999
+ fetcher
1000
+ ]);
1001
+ return {
1002
+ rows: state.rows,
1003
+ columns: state.columns,
1004
+ truncated: state.truncated,
1005
+ sql: state.sql,
1006
+ loading: state.loading,
1007
+ error: state.error,
1008
+ refetch: () => setNonce((n) => n + 1)
1009
+ };
1010
+ }
1011
+ const PROCEDURE_POLL_MS = 2e3;
1012
+ const PROCEDURE_BACKOFF_MS = 5e3;
1013
+ const PROCEDURE_MAX_WAIT_MS = 3600 * 1e3;
1014
+ /**
1015
+ * @beta Long-running procedure runner. The wire shape works end-to-end
1016
+ * (start → poll → cancel; runs survive server restarts via the
1017
+ * `customer_app_procedure_runs` table) but a few rough edges remain
1018
+ * before this is GA-ready:
1019
+ *
1020
+ * - Hint surfaces for `procedure_not_found` are correct but the
1021
+ * procedure-discovery rules (which directories the server scans,
1022
+ * case-sensitivity, branch awareness) aren't documented yet.
1023
+ * - Cancellation across multi-instance deployments leans on a
1024
+ * periodic sweep — fine for now, but expect occasional latency
1025
+ * between `cancel()` and the run actually stopping.
1026
+ * - Progress reporting requires the procedure to emit named
1027
+ * steps; bundles get `progress: null` until that lands.
1028
+ *
1029
+ * The API surface is stable; expect breaking changes only if the
1030
+ * server-side `customer_app_procedure_runs` schema changes.
1031
+ */
1032
+ function useProcedureRun(input, opts = {}) {
1033
+ warnBetaOnce("useProcedureRun");
1034
+ const { projectId, fetcher } = useOxyApp();
1035
+ const pollMs = opts.pollIntervalMs ?? PROCEDURE_POLL_MS;
1036
+ const backoffMs = opts.pollIntervalBackoffMs ?? PROCEDURE_BACKOFF_MS;
1037
+ const maxWaitMs = opts.maxWaitMs ?? PROCEDURE_MAX_WAIT_MS;
1038
+ const [state, setState] = React.useState({
1039
+ state: "idle",
1040
+ progress: null,
1041
+ result: null,
1042
+ error: null
1043
+ });
1044
+ const inflight = React.useRef({});
1045
+ const cancel = React.useCallback(() => {
1046
+ const runId = inflight.current.runId;
1047
+ if (!projectId || !runId) return;
1048
+ inflight.current.abort?.abort();
1049
+ inflight.current.runId = void 0;
1050
+ fetcher(`/api/projects/${projectId}/procedures/runs/${encodeURIComponent(runId)}/cancel`, { method: "POST" }).catch(() => {});
1051
+ setState({
1052
+ state: "failed",
1053
+ progress: null,
1054
+ result: null,
1055
+ error: /* @__PURE__ */ new Error("procedure cancelled by user")
1056
+ });
1057
+ }, [projectId, fetcher]);
1058
+ const run = React.useCallback((params) => {
1059
+ if (!projectId) {
1060
+ setState((s) => ({
1061
+ ...s,
1062
+ state: "failed",
1063
+ error: /* @__PURE__ */ new Error("project not configured")
1064
+ }));
1065
+ return;
1066
+ }
1067
+ inflight.current.abort?.abort();
1068
+ const ctrl = new AbortController();
1069
+ inflight.current = { abort: ctrl };
1070
+ setState({
1071
+ state: "running",
1072
+ progress: null,
1073
+ result: null,
1074
+ error: null
1075
+ });
1076
+ (async () => {
1077
+ try {
1078
+ const body = JSON.stringify({
1079
+ v: 1,
1080
+ ...params ? { params } : {}
1081
+ });
1082
+ const startResp = await fetcher(`/api/projects/${projectId}/procedures/${encodeURIComponent(input.procedureId)}/runs`, {
1083
+ method: "POST",
1084
+ headers: { "content-type": "application/json" },
1085
+ body,
1086
+ signal: ctrl.signal
1087
+ });
1088
+ if (!startResp.ok) throw await apiErrorFromResponse(startResp);
1089
+ const { run_id } = await startResp.json();
1090
+ inflight.current.runId = run_id;
1091
+ const startedAt = Date.now();
1092
+ let pollCount = 0;
1093
+ while (true) {
1094
+ if (ctrl.signal.aborted) return;
1095
+ if (Date.now() - startedAt > maxWaitMs) throw new Error("procedure run timed out client-side");
1096
+ await sleep(pollCount < 6 ? pollMs : backoffMs, ctrl.signal);
1097
+ if (ctrl.signal.aborted) return;
1098
+ pollCount += 1;
1099
+ const pollResp = await fetcher(`/api/projects/${projectId}/procedures/runs/${encodeURIComponent(run_id)}`, {
1100
+ method: "GET",
1101
+ signal: ctrl.signal
1102
+ });
1103
+ if (!pollResp.ok) throw await apiErrorFromResponse(pollResp);
1104
+ const poll = await pollResp.json();
1105
+ if (poll.status === "running") {
1106
+ if (poll.progress) setState((s) => ({
1107
+ ...s,
1108
+ progress: poll.progress ?? null
1109
+ }));
1110
+ continue;
1111
+ }
1112
+ if (poll.status === "done") {
1113
+ inflight.current.runId = void 0;
1114
+ setState({
1115
+ state: "done",
1116
+ progress: null,
1117
+ result: poll.result,
1118
+ error: null
1119
+ });
1120
+ return;
1121
+ }
1122
+ if (poll.status === "cancelled") {
1123
+ inflight.current.runId = void 0;
1124
+ setState({
1125
+ state: "failed",
1126
+ progress: null,
1127
+ result: null,
1128
+ error: /* @__PURE__ */ new Error("procedure cancelled")
1129
+ });
1130
+ return;
1131
+ }
1132
+ inflight.current.runId = void 0;
1133
+ setState({
1134
+ state: "failed",
1135
+ progress: null,
1136
+ result: null,
1137
+ error: new Error(poll.error.message)
1138
+ });
1139
+ return;
1140
+ }
1141
+ } catch (e) {
1142
+ if (e instanceof DOMException && e.name === "AbortError") return;
1143
+ inflight.current.runId = void 0;
1144
+ setState({
1145
+ state: "failed",
1146
+ progress: null,
1147
+ result: null,
1148
+ error: e instanceof Error ? e : new Error(String(e))
1149
+ });
1150
+ }
1151
+ })();
1152
+ }, [
1153
+ projectId,
1154
+ fetcher,
1155
+ input.procedureId,
1156
+ pollMs,
1157
+ backoffMs,
1158
+ maxWaitMs
1159
+ ]);
1160
+ React.useEffect(() => {
1161
+ return () => {
1162
+ inflight.current.abort?.abort();
1163
+ };
1164
+ }, []);
1165
+ return {
1166
+ state: state.state,
1167
+ run,
1168
+ cancel,
1169
+ progress: state.progress,
1170
+ result: state.result,
1171
+ error: state.error
1172
+ };
1173
+ }
1174
+ function useAgentRun(input) {
1175
+ const { projectId, fetcher } = useOxyApp();
1176
+ const [state, setState] = React.useState({
1177
+ state: "idle",
1178
+ events: [],
1179
+ artifacts: [],
1180
+ answer: null,
1181
+ clarification: null,
1182
+ threadId: null,
1183
+ threadUrl: null,
1184
+ error: null
1185
+ });
1186
+ const inflight = React.useRef({});
1187
+ const cancel = React.useCallback(() => {
1188
+ const runId = inflight.current.runId;
1189
+ if (!projectId || !runId) return;
1190
+ inflight.current.abort?.abort();
1191
+ inflight.current.runId = void 0;
1192
+ fetcher(`/api/projects/${projectId}/agents/asks/${encodeURIComponent(runId)}/cancel`, { method: "POST" }).catch(() => {});
1193
+ setState((s) => ({
1194
+ ...s,
1195
+ state: "failed",
1196
+ error: /* @__PURE__ */ new Error("agent run cancelled by user")
1197
+ }));
1198
+ }, [projectId, fetcher]);
1199
+ const ask = React.useCallback((question, opts = {}) => {
1200
+ if (!projectId) {
1201
+ setState((s) => ({
1202
+ ...s,
1203
+ state: "failed",
1204
+ error: /* @__PURE__ */ new Error("project not configured")
1205
+ }));
1206
+ return;
1207
+ }
1208
+ inflight.current.abort?.abort();
1209
+ const ctrl = new AbortController();
1210
+ inflight.current = { abort: ctrl };
1211
+ setState({
1212
+ state: "running",
1213
+ events: [],
1214
+ artifacts: [],
1215
+ answer: null,
1216
+ clarification: null,
1217
+ threadId: opts.threadId ?? null,
1218
+ threadUrl: opts.threadId ? `/threads/${opts.threadId}` : null,
1219
+ error: null
1220
+ });
1221
+ (async () => {
1222
+ try {
1223
+ const body = JSON.stringify({
1224
+ v: 1,
1225
+ question,
1226
+ ...opts.threadId ? { thread_id: opts.threadId } : {}
1227
+ });
1228
+ const startResp = await fetcher(`/api/projects/${projectId}/agents/${encodeURIComponent(input.agentId)}/asks`, {
1229
+ method: "POST",
1230
+ headers: { "content-type": "application/json" },
1231
+ body,
1232
+ signal: ctrl.signal
1233
+ });
1234
+ if (!startResp.ok) throw await apiErrorFromResponse(startResp);
1235
+ const { run_id, thread_id, thread_url } = await startResp.json();
1236
+ inflight.current.runId = run_id;
1237
+ setState((s) => ({
1238
+ ...s,
1239
+ threadId: thread_id,
1240
+ threadUrl: thread_url ?? `/threads/${thread_id}`
1241
+ }));
1242
+ let lastEventId = "";
1243
+ let attempts = 0;
1244
+ let terminated = false;
1245
+ while (true) {
1246
+ if (ctrl.signal.aborted) return;
1247
+ if (terminated) return;
1248
+ attempts += 1;
1249
+ try {
1250
+ await consumeSseStream({
1251
+ url: `/api/projects/${projectId}/agents/runs/${encodeURIComponent(run_id)}/events`,
1252
+ fetcher,
1253
+ signal: ctrl.signal,
1254
+ lastEventId,
1255
+ onEvent: (ev) => {
1256
+ if (ev.id) lastEventId = ev.id;
1257
+ const data = parseSseData(ev.data);
1258
+ const eventType = ev.event || "message";
1259
+ const artifact = extractSqlArtifact(eventType, ev.id, data);
1260
+ const token = eventType === "text_delta" && typeof data === "object" && data !== null && "token" in data ? String(data.token) : null;
1261
+ setState((s) => ({
1262
+ ...s,
1263
+ events: [...s.events, {
1264
+ type: eventType,
1265
+ data
1266
+ }],
1267
+ artifacts: artifact ? [...s.artifacts, artifact] : s.artifacts,
1268
+ answer: token !== null ? (s.answer ?? "") + token : s.answer
1269
+ }));
1270
+ if (ev.event === "done") {
1271
+ terminated = true;
1272
+ inflight.current.runId = void 0;
1273
+ setState((s) => ({
1274
+ ...s,
1275
+ state: "done"
1276
+ }));
1277
+ } else if (ev.event === "failed" || ev.event === "error" || ev.event === "cancelled") {
1278
+ terminated = true;
1279
+ inflight.current.runId = void 0;
1280
+ const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : `agent run ${ev.event}`;
1281
+ setState((s) => ({
1282
+ ...s,
1283
+ state: "failed",
1284
+ error: new Error(message)
1285
+ }));
1286
+ } else if (ev.event === "awaiting_input") {
1287
+ terminated = true;
1288
+ const clarification = clarificationFromData(data) ?? "Agent needs clarification.";
1289
+ setState((s) => ({
1290
+ ...s,
1291
+ state: "needs_clarification",
1292
+ clarification
1293
+ }));
1294
+ }
1295
+ }
1296
+ });
1297
+ } catch (err) {
1298
+ if (err instanceof DOMException && err.name === "AbortError") return;
1299
+ if (attempts >= 5) {
1300
+ inflight.current.runId = void 0;
1301
+ setState((s) => ({
1302
+ ...s,
1303
+ state: "failed",
1304
+ error: err instanceof Error ? err : new Error(String(err))
1305
+ }));
1306
+ return;
1307
+ }
1308
+ }
1309
+ if (terminated) return;
1310
+ if (attempts >= 5) {
1311
+ inflight.current.runId = void 0;
1312
+ setState((s) => ({
1313
+ ...s,
1314
+ state: "failed",
1315
+ error: /* @__PURE__ */ new Error("run event stream closed without a terminal event")
1316
+ }));
1317
+ return;
1318
+ }
1319
+ await sleep(1e3, ctrl.signal);
1320
+ }
1321
+ } catch (e) {
1322
+ if (e instanceof DOMException && e.name === "AbortError") return;
1323
+ inflight.current.runId = void 0;
1324
+ setState((s) => ({
1325
+ ...s,
1326
+ state: "failed",
1327
+ error: e instanceof Error ? e : new Error(String(e))
1328
+ }));
1329
+ }
1330
+ })();
1331
+ }, [
1332
+ projectId,
1333
+ fetcher,
1334
+ input.agentId
1335
+ ]);
1336
+ React.useEffect(() => {
1337
+ return () => {
1338
+ inflight.current.abort?.abort();
1339
+ };
1340
+ }, []);
1341
+ return {
1342
+ state: state.state,
1343
+ ask,
1344
+ cancel,
1345
+ events: state.events,
1346
+ artifacts: state.artifacts,
1347
+ answer: state.answer,
1348
+ clarification: state.clarification,
1349
+ threadId: state.threadId,
1350
+ threadUrl: state.threadUrl,
1351
+ error: state.error
1352
+ };
1353
+ }
1354
+ /** Parsed JSON payload of an SSE `data:` line, falling back to raw
1355
+ * string on parse failure. */
1356
+ function parseSseData(raw) {
1357
+ try {
1358
+ return JSON.parse(raw);
1359
+ } catch {
1360
+ return raw;
1361
+ }
1362
+ }
1363
+ /** Extract the clarifying-question text from an `awaiting_input` payload.
1364
+ * The server sends `{ questions: [{ prompt, suggestions }] }`; older shapes
1365
+ * used a single `{ question }`. Returns null when neither is present. */
1366
+ function clarificationFromData(data) {
1367
+ if (typeof data !== "object" || data === null) return null;
1368
+ const d = data;
1369
+ const first = (Array.isArray(d.questions) ? d.questions : [])[0];
1370
+ if (first && typeof first.prompt === "string") return first.prompt;
1371
+ if (typeof d.question === "string") return d.question;
1372
+ return null;
1373
+ }
1374
+ /** UI event types in the analytics taxonomy that carry SQL the bundle
1375
+ * may want to render alongside the answer. Each carries the same
1376
+ * shape (`query` / `columns` / `rows` / `success`) so we can parse
1377
+ * uniformly. New types added upstream don't surface as artifacts
1378
+ * until added here — that's intentional, the renderer needs to
1379
+ * know how to display each. */
1380
+ const SQL_EVENT_TYPES = /* @__PURE__ */ new Set([
1381
+ "query_executed",
1382
+ "query_generated",
1383
+ "verified_sql",
1384
+ "semantic_query",
1385
+ "omni_query"
1386
+ ]);
1387
+ /** Extract a SQL artifact from a single SSE event when the type +
1388
+ * payload shape match. Returns `null` for events that aren't SQL
1389
+ * carriers or whose payload doesn't include the expected fields. */
1390
+ function extractSqlArtifact(eventType, eventId, data) {
1391
+ if (!SQL_EVENT_TYPES.has(eventType)) return null;
1392
+ if (typeof data !== "object" || data === null) return null;
1393
+ const obj = data;
1394
+ const sql = typeof obj.query === "string" ? obj.query : typeof obj.sql === "string" ? obj.sql : null;
1395
+ if (!sql) return null;
1396
+ const columns = Array.isArray(obj.columns) ? obj.columns.map(String) : void 0;
1397
+ const rows = Array.isArray(obj.rows) ? obj.rows : void 0;
1398
+ const rowCount = typeof obj.row_count === "number" ? obj.row_count : typeof obj.rowCount === "number" ? obj.rowCount : rows?.length;
1399
+ const artifact = {
1400
+ type: "sql",
1401
+ id: eventId || `${eventType}-${sql.slice(0, 32)}`,
1402
+ source: eventType,
1403
+ sql
1404
+ };
1405
+ if (columns && rows) artifact.results = {
1406
+ columns,
1407
+ rows,
1408
+ rowCount: rowCount ?? rows.length
1409
+ };
1410
+ const errMsg = typeof obj.error === "string" ? obj.error : obj.success === false && typeof obj.message === "string" ? obj.message : void 0;
1411
+ if (errMsg) artifact.error = errMsg;
1412
+ return artifact;
1413
+ }
1414
+ /**
1415
+ * Hand-rolled SSE consumer using `fetch` + `ReadableStream`. We use
1416
+ * this in place of `EventSource` because:
1417
+ * 1. EventSource doesn't expose the connection's `Last-Event-ID`
1418
+ * header in a way you can control. The browser tracks it
1419
+ * internally but you can't pass a starting value, so a hook
1420
+ * that wants to resume after a tab switch / network blip has
1421
+ * no way to ask the server to replay from a known point.
1422
+ * 2. EventSource can't pass `Authorization` / other custom
1423
+ * headers — only `withCredentials` for cookies. Fine today,
1424
+ * but couples us to cookie auth forever.
1425
+ *
1426
+ * The parser handles the message-block model from the SSE spec
1427
+ * verbatim: lines split by `\n` (or `\r\n` / `\r`), event blocks
1428
+ * separated by blank lines, `id:` / `event:` / `data:` fields
1429
+ * accumulated per block. Multiple `data:` lines concatenate with
1430
+ * `\n` (per spec) — we honor that even though the server emits
1431
+ * single-line data today.
1432
+ *
1433
+ * Throws on network error or non-2xx. Returns when the stream ends
1434
+ * normally (server closed connection cleanly).
1435
+ */
1436
+ async function consumeSseStream(opts) {
1437
+ const headers = {
1438
+ accept: "text/event-stream",
1439
+ "cache-control": "no-cache"
1440
+ };
1441
+ if (opts.lastEventId) headers["Last-Event-ID"] = opts.lastEventId;
1442
+ const resp = await opts.fetcher(opts.url, {
1443
+ method: "GET",
1444
+ headers,
1445
+ signal: opts.signal
1446
+ });
1447
+ if (!resp.ok) throw await apiErrorFromResponse(resp);
1448
+ if (!resp.body) throw new Error("SSE response has no body");
1449
+ const reader = resp.body.getReader();
1450
+ const decoder = new TextDecoder();
1451
+ let buffer = "";
1452
+ let currentId = "";
1453
+ let currentEvent = "message";
1454
+ let currentData = [];
1455
+ const dispatch = () => {
1456
+ if (currentData.length === 0 && currentEvent === "message" && !currentId) return;
1457
+ opts.onEvent({
1458
+ id: currentId,
1459
+ event: currentEvent,
1460
+ data: currentData.join("\n")
1461
+ });
1462
+ currentEvent = "message";
1463
+ currentData = [];
1464
+ };
1465
+ while (true) {
1466
+ const { value, done } = await reader.read();
1467
+ if (done) break;
1468
+ buffer += decoder.decode(value, { stream: true });
1469
+ let nlIndex;
1470
+ while ((nlIndex = buffer.search(/\r\n|\r|\n/)) !== -1) {
1471
+ if (nlIndex === buffer.length - 1 && buffer[nlIndex] === "\r") break;
1472
+ const line = buffer.slice(0, nlIndex);
1473
+ const sep = buffer.slice(nlIndex, nlIndex + 2);
1474
+ buffer = buffer.slice(nlIndex + (sep === "\r\n" ? 2 : 1));
1475
+ if (line === "") {
1476
+ dispatch();
1477
+ continue;
1478
+ }
1479
+ if (line.startsWith(":")) continue;
1480
+ const colonAt = line.indexOf(":");
1481
+ const field = colonAt === -1 ? line : line.slice(0, colonAt);
1482
+ let value = colonAt === -1 ? "" : line.slice(colonAt + 1);
1483
+ if (value.startsWith(" ")) value = value.slice(1);
1484
+ switch (field) {
1485
+ case "id":
1486
+ currentId = value;
1487
+ break;
1488
+ case "event":
1489
+ currentEvent = value;
1490
+ break;
1491
+ case "data":
1492
+ currentData.push(value);
1493
+ break;
1494
+ }
1495
+ }
1496
+ }
1497
+ if (currentData.length > 0) dispatch();
1498
+ }
1499
+ function sleep(ms, signal) {
1500
+ return new Promise((resolve, reject) => {
1501
+ const t = setTimeout(resolve, ms);
1502
+ signal?.addEventListener("abort", () => {
1503
+ clearTimeout(t);
1504
+ reject(new DOMException("aborted", "AbortError"));
1505
+ }, { once: true });
1506
+ });
1507
+ }
1508
+ /**
1509
+ * Engineer-tagged usage event. Free-form `event_name` (≤ 64 chars,
1510
+ * `[a-z][a-z0-9-]*` validated server-side) + optional JSON `payload`
1511
+ * (object, ≤ 4 KiB serialized). Surfaces in the admin Activity tab
1512
+ * grouped by name, with drill-down into recent occurrences.
1513
+ *
1514
+ * The handler returned by [`useTrackEvent`] is **fire-and-forget**:
1515
+ * it enqueues the event into an in-memory batch flushed every second
1516
+ * (and on `pagehide` so a navigation away doesn't drop the tail).
1517
+ * No await semantics — call it inline from a click handler without
1518
+ * awaiting it. Server-side validation errors are logged to the
1519
+ * console; the call site doesn't need to handle them.
1520
+ *
1521
+ * Example:
1522
+ * ```tsx
1523
+ * const track = useTrackEvent();
1524
+ * <button
1525
+ * onClick={() => {
1526
+ * track("export-clicked", { format: "csv", rowCount });
1527
+ * doExport();
1528
+ * }}
1529
+ * >Export</button>
1530
+ * ```
1531
+ *
1532
+ * Rate-limited at 60/min per (user, app) on the server. A burst that
1533
+ * trips the limit drops the excess events with a console warning;
1534
+ * within-limit events are unaffected.
1535
+ */
1536
+ function useTrackEvent() {
1537
+ const { projectId, fetcher } = useOxyApp();
1538
+ const queueRef = React.useRef([]);
1539
+ const flushTimerRef = React.useRef(null);
1540
+ const flush = React.useCallback(() => {
1541
+ flushTimerRef.current = null;
1542
+ if (!projectId) return;
1543
+ const batch = queueRef.current;
1544
+ if (batch.length === 0) return;
1545
+ queueRef.current = [];
1546
+ for (const evt of batch) {
1547
+ const url = `/api/customer-apps/${projectId}/events`;
1548
+ const body = JSON.stringify(evt);
1549
+ try {
1550
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function" && document.visibilityState === "hidden") navigator.sendBeacon(url, new Blob([body], { type: "application/json" }));
1551
+ else fetcher(url, {
1552
+ method: "POST",
1553
+ headers: { "content-type": "application/json" },
1554
+ body
1555
+ }).catch((e) => {
1556
+ console.warn("[oxy] useTrackEvent flush failed:", e);
1557
+ });
1558
+ } catch (e) {
1559
+ console.warn("[oxy] useTrackEvent enqueue failed:", e);
1560
+ }
1561
+ }
1562
+ }, [projectId, fetcher]);
1563
+ React.useEffect(() => {
1564
+ if (typeof window === "undefined") return;
1565
+ const onHide = () => flush();
1566
+ window.addEventListener("pagehide", onHide);
1567
+ return () => {
1568
+ window.removeEventListener("pagehide", onHide);
1569
+ flush();
1570
+ if (flushTimerRef.current !== null) {
1571
+ clearTimeout(flushTimerRef.current);
1572
+ flushTimerRef.current = null;
1573
+ }
1574
+ };
1575
+ }, [flush]);
1576
+ return React.useCallback((name, payload) => {
1577
+ queueRef.current.push({
1578
+ event_name: name,
1579
+ payload: payload ?? {}
1580
+ });
1581
+ if (flushTimerRef.current === null) flushTimerRef.current = setTimeout(flush, 1e3);
1582
+ }, [flush]);
1583
+ }
1584
+ /**
1585
+ * Renders an agent run's answer + artifacts + thread link as a
1586
+ * single block. The default styling is intentionally neutral
1587
+ * (system fonts, gray surfaces) so it blends into any bundle.
1588
+ *
1589
+ * Designed to be paired with `useAgentRun`:
1590
+ *
1591
+ * ```tsx
1592
+ * const run = useAgentRun({ agentId: "analyst" });
1593
+ * return (
1594
+ * <>
1595
+ * <button onClick={() => run.ask("how many users last week?")}>Ask</button>
1596
+ * <OxyAnswer {...run} />
1597
+ * </>
1598
+ * );
1599
+ * ```
1600
+ */
1601
+ function OxyAnswer(props) {
1602
+ ensureSpinKeyframes();
1603
+ const { answer, artifacts = [], state, clarification, error, threadUrl, threadLinkLabel = "Continue this thread in Oxy", maxArtifactRows = 10, className } = props;
1604
+ const isRunning = state === "running";
1605
+ const isFailed = state === "failed";
1606
+ const needsClarification = state === "needs_clarification";
1607
+ return /* @__PURE__ */ jsxs("div", {
1608
+ className,
1609
+ style: styles.answerWrap,
1610
+ children: [
1611
+ isRunning && answer === null ? /* @__PURE__ */ jsxs("div", {
1612
+ style: styles.statusRow,
1613
+ children: [/* @__PURE__ */ jsx("span", {
1614
+ style: styles.spinner,
1615
+ "aria-hidden": "true"
1616
+ }), /* @__PURE__ */ jsx("span", {
1617
+ style: styles.statusText,
1618
+ children: "Thinking…"
1619
+ })]
1620
+ }) : null,
1621
+ artifacts.length > 0 ? /* @__PURE__ */ jsx("div", {
1622
+ style: styles.artifactList,
1623
+ children: artifacts.map((a) => /* @__PURE__ */ jsx(SqlArtifactBlock, {
1624
+ artifact: a,
1625
+ maxRows: maxArtifactRows
1626
+ }, a.id))
1627
+ }) : null,
1628
+ answer ? /* @__PURE__ */ jsx("div", {
1629
+ style: styles.markdown,
1630
+ children: /* @__PURE__ */ jsx(MarkdownText, { text: answer })
1631
+ }) : null,
1632
+ needsClarification && clarification ? /* @__PURE__ */ jsxs("div", {
1633
+ style: styles.clarification,
1634
+ children: [/* @__PURE__ */ jsx("strong", { children: "Agent needs clarification:" }), /* @__PURE__ */ jsx("div", {
1635
+ style: { marginTop: 4 },
1636
+ children: clarification
1637
+ })]
1638
+ }) : null,
1639
+ isFailed && error ? /* @__PURE__ */ jsx(ErrorBlock, { error }) : null,
1640
+ threadUrl && (answer || artifacts.length > 0) ? /* @__PURE__ */ jsxs("div", {
1641
+ style: styles.threadLinkRow,
1642
+ children: [/* @__PURE__ */ jsxs("a", {
1643
+ href: threadUrl,
1644
+ target: "_blank",
1645
+ rel: "noreferrer noopener",
1646
+ style: styles.threadLink,
1647
+ children: [threadLinkLabel, " →"]
1648
+ }), /* @__PURE__ */ jsx("span", {
1649
+ style: styles.betaBadge,
1650
+ title: "Thread linking is in beta — see docs",
1651
+ children: "beta"
1652
+ })]
1653
+ }) : null
1654
+ ]
1655
+ });
1656
+ }
1657
+ /**
1658
+ * Complete drop-in chat surface. One agent, one input, one answer
1659
+ * view. The chat is single-turn by default — each new question
1660
+ * cancels the previous run and clears the answer. Bundles that
1661
+ * want a multi-turn conversation history compose their own UI
1662
+ * using `useAgentRun` directly.
1663
+ *
1664
+ * Single-turn keeps the surface dead simple: bundles use this for
1665
+ * the "ask anything about your data" widget that sits next to
1666
+ * structured panels. Multi-turn is rare in those contexts and
1667
+ * better expressed by the bundle.
1668
+ */
1669
+ function OxyChat(props) {
1670
+ ensureSpinKeyframes();
1671
+ const { agentId, placeholder = "Ask a question about your data…", submitLabel = "Ask", emptyState, maxArtifactRows, className } = props;
1672
+ const run = useAgentRun({ agentId });
1673
+ const [question, setQuestion] = React.useState("");
1674
+ const submit = React.useCallback((e) => {
1675
+ e?.preventDefault();
1676
+ const q = question.trim();
1677
+ if (!q || run.state === "running") return;
1678
+ run.ask(q);
1679
+ }, [question, run]);
1680
+ return /* @__PURE__ */ jsxs("div", {
1681
+ className,
1682
+ style: styles.chatWrap,
1683
+ children: [/* @__PURE__ */ jsxs("form", {
1684
+ onSubmit: submit,
1685
+ style: styles.chatForm,
1686
+ children: [
1687
+ /* @__PURE__ */ jsx("input", {
1688
+ type: "text",
1689
+ value: question,
1690
+ onChange: (e) => setQuestion(e.target.value),
1691
+ placeholder,
1692
+ disabled: run.state === "running",
1693
+ style: styles.chatInput,
1694
+ "aria-label": "Question"
1695
+ }),
1696
+ /* @__PURE__ */ jsx("button", {
1697
+ type: "submit",
1698
+ disabled: run.state === "running" || question.trim() === "",
1699
+ style: styles.chatSubmit,
1700
+ children: run.state === "running" ? "…" : submitLabel
1701
+ }),
1702
+ run.state === "running" ? /* @__PURE__ */ jsx("button", {
1703
+ type: "button",
1704
+ onClick: run.cancel,
1705
+ style: styles.chatCancel,
1706
+ children: "Stop"
1707
+ }) : null
1708
+ ]
1709
+ }), run.state === "idle" ? emptyState ?? /* @__PURE__ */ jsx("div", {
1710
+ style: styles.emptyState,
1711
+ children: "Ask a question to get started."
1712
+ }) : /* @__PURE__ */ jsx(OxyAnswer, {
1713
+ answer: run.answer,
1714
+ artifacts: run.artifacts,
1715
+ state: run.state,
1716
+ clarification: run.clarification,
1717
+ error: run.error,
1718
+ threadUrl: run.threadUrl,
1719
+ maxArtifactRows
1720
+ })]
1721
+ });
1722
+ }
1723
+ function SqlArtifactBlock(props) {
1724
+ const { artifact, maxRows } = props;
1725
+ const [open, setOpen] = React.useState(false);
1726
+ const results = artifact.results;
1727
+ const truncated = results ? results.rows.length > maxRows : false;
1728
+ const visibleRows = results ? results.rows.slice(0, maxRows) : [];
1729
+ const sourceLabel = artifact.source === "verified_sql" ? "Verified query" : artifact.source === "semantic_query" ? "Semantic query" : artifact.source === "omni_query" ? "Omni query" : "Query";
1730
+ return /* @__PURE__ */ jsxs("div", {
1731
+ style: styles.artifact,
1732
+ children: [/* @__PURE__ */ jsxs("button", {
1733
+ type: "button",
1734
+ onClick: () => setOpen((o) => !o),
1735
+ style: styles.artifactHeader,
1736
+ children: [
1737
+ /* @__PURE__ */ jsx("span", {
1738
+ style: styles.artifactBadge,
1739
+ children: sourceLabel
1740
+ }),
1741
+ /* @__PURE__ */ jsx("span", {
1742
+ style: styles.artifactSummary,
1743
+ children: results ? `${results.rowCount} row${results.rowCount === 1 ? "" : "s"}` : artifact.error ? "execution failed" : "SQL only"
1744
+ }),
1745
+ /* @__PURE__ */ jsx("span", {
1746
+ style: styles.artifactToggle,
1747
+ children: open ? "Hide" : "Show"
1748
+ })
1749
+ ]
1750
+ }), open ? /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("pre", {
1751
+ style: styles.sqlBlock,
1752
+ children: artifact.sql
1753
+ }), artifact.error ? /* @__PURE__ */ jsx("div", {
1754
+ style: styles.error,
1755
+ children: artifact.error
1756
+ }) : results ? /* @__PURE__ */ jsxs("div", {
1757
+ style: styles.resultsWrap,
1758
+ children: [/* @__PURE__ */ jsxs("table", {
1759
+ style: styles.resultsTable,
1760
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: results.columns.map((c) => /* @__PURE__ */ jsx("th", {
1761
+ style: styles.resultsTh,
1762
+ children: c
1763
+ }, c)) }) }), /* @__PURE__ */ jsx("tbody", { children: visibleRows.map((row, i) => /* @__PURE__ */ jsx("tr", { children: row.map((cell, j) => /* @__PURE__ */ jsx("td", {
1764
+ style: styles.resultsTd,
1765
+ children: formatCell(cell)
1766
+ }, j)) }, i)) })]
1767
+ }), truncated ? /* @__PURE__ */ jsxs("div", {
1768
+ style: styles.truncatedNote,
1769
+ children: [
1770
+ "+",
1771
+ results.rows.length - maxRows,
1772
+ " more rows. Open the thread in Oxy to see all."
1773
+ ]
1774
+ }) : null]
1775
+ }) : null] }) : null]
1776
+ });
1777
+ }
1778
+ function formatCell(value) {
1779
+ if (value === null || value === void 0) return "—";
1780
+ if (typeof value === "object") return JSON.stringify(value);
1781
+ return String(value);
1782
+ }
1783
+ /**
1784
+ * Renders a thrown Error with the server's `hint` line broken out
1785
+ * if the error is an `OxyApiError`. Falls back to `error.message`
1786
+ * for plain Errors. Whitespace-preserving so multi-line hints from
1787
+ * the server land readably.
1788
+ */
1789
+ function ErrorBlock(props) {
1790
+ const { error } = props;
1791
+ if (error instanceof OxyApiError) return /* @__PURE__ */ jsxs("div", {
1792
+ style: styles.error,
1793
+ children: [/* @__PURE__ */ jsxs("div", { children: [
1794
+ /* @__PURE__ */ jsx("strong", { children: "Run failed:" }),
1795
+ " ",
1796
+ error.message.split("\n\n")[0]
1797
+ ] }), error.hint ? /* @__PURE__ */ jsxs("div", {
1798
+ style: {
1799
+ marginTop: 6,
1800
+ fontWeight: 400,
1801
+ whiteSpace: "pre-wrap"
1802
+ },
1803
+ children: [
1804
+ /* @__PURE__ */ jsx("strong", { children: "Hint:" }),
1805
+ " ",
1806
+ error.hint
1807
+ ]
1808
+ }) : null]
1809
+ });
1810
+ return /* @__PURE__ */ jsxs("div", {
1811
+ style: styles.error,
1812
+ children: [
1813
+ /* @__PURE__ */ jsx("strong", { children: "Run failed:" }),
1814
+ " ",
1815
+ error.message
1816
+ ]
1817
+ });
1818
+ }
1819
+ function MarkdownText(props) {
1820
+ return /* @__PURE__ */ jsx(Fragment$1, { children: React.useMemo(() => parseMarkdown(props.text), [props.text]) });
1821
+ }
1822
+ function parseMarkdown(text) {
1823
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
1824
+ const blocks = [];
1825
+ let i = 0;
1826
+ while (i < lines.length) {
1827
+ const line = lines[i];
1828
+ if (line === void 0) {
1829
+ i++;
1830
+ continue;
1831
+ }
1832
+ const fence = line.match(/^```(\w*)\s*$/);
1833
+ if (fence) {
1834
+ const lang = fence[1] ?? "";
1835
+ const buf = [];
1836
+ i++;
1837
+ while (i < lines.length && !/^```\s*$/.test(lines[i] ?? "")) {
1838
+ buf.push(lines[i] ?? "");
1839
+ i++;
1840
+ }
1841
+ i++;
1842
+ blocks.push({
1843
+ kind: "code",
1844
+ lang,
1845
+ code: buf.join("\n")
1846
+ });
1847
+ continue;
1848
+ }
1849
+ const h = line.match(/^(#{1,3})\s+(.+)$/);
1850
+ if (h) {
1851
+ blocks.push({
1852
+ kind: "h",
1853
+ level: h[1]?.length,
1854
+ text: h[2]
1855
+ });
1856
+ i++;
1857
+ continue;
1858
+ }
1859
+ if (isTableStart(lines, i)) {
1860
+ const headers = splitTableRow(line);
1861
+ i += 2;
1862
+ const rows = [];
1863
+ while (i < lines.length && (lines[i] ?? "").includes("|") && (lines[i] ?? "").trim() !== "") {
1864
+ rows.push(splitTableRow(lines[i] ?? ""));
1865
+ i++;
1866
+ }
1867
+ blocks.push({
1868
+ kind: "table",
1869
+ headers,
1870
+ rows
1871
+ });
1872
+ continue;
1873
+ }
1874
+ if (/^\s*[-*]\s+/.test(line)) {
1875
+ const items = [];
1876
+ while (i < lines.length && /^\s*[-*]\s+/.test(lines[i] ?? "")) {
1877
+ items.push((lines[i] ?? "").replace(/^\s*[-*]\s+/, ""));
1878
+ i++;
1879
+ }
1880
+ blocks.push({
1881
+ kind: "list",
1882
+ items
1883
+ });
1884
+ continue;
1885
+ }
1886
+ if (line.trim() === "") {
1887
+ i++;
1888
+ continue;
1889
+ }
1890
+ const buf = [line];
1891
+ i++;
1892
+ while (i < lines.length) {
1893
+ const next = lines[i] ?? "";
1894
+ if (next.trim() === "" || /^#{1,3}\s+/.test(next) || /^```/.test(next) || /^\s*[-*]\s+/.test(next) || isTableStart(lines, i)) break;
1895
+ buf.push(next);
1896
+ i++;
1897
+ }
1898
+ blocks.push({
1899
+ kind: "p",
1900
+ text: buf.join(" ")
1901
+ });
1902
+ }
1903
+ return blocks.map((b, idx) => {
1904
+ switch (b.kind) {
1905
+ case "h": return /* @__PURE__ */ jsx(`h${b.level}`, {
1906
+ style: b.level === 1 ? styles.h1 : b.level === 2 ? styles.h2 : styles.h3,
1907
+ children: renderInline(b.text)
1908
+ }, idx);
1909
+ case "code": return /* @__PURE__ */ jsx("pre", {
1910
+ style: styles.codeBlock,
1911
+ "data-lang": b.lang || void 0,
1912
+ children: /* @__PURE__ */ jsx("code", { children: b.code })
1913
+ }, idx);
1914
+ case "list": return /* @__PURE__ */ jsx("ul", {
1915
+ style: styles.list,
1916
+ children: b.items.map((item, i) => /* @__PURE__ */ jsx("li", { children: renderInline(item) }, i))
1917
+ }, idx);
1918
+ case "table": return /* @__PURE__ */ jsx("div", {
1919
+ style: styles.mdTableWrap,
1920
+ children: /* @__PURE__ */ jsxs("table", {
1921
+ style: styles.mdTable,
1922
+ children: [/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: b.headers.map((h, hi) => /* @__PURE__ */ jsx("th", {
1923
+ style: styles.mdTh,
1924
+ children: renderInline(h)
1925
+ }, `${hi}-${h}`)) }) }), /* @__PURE__ */ jsx("tbody", { children: b.rows.map((row, ri) => /* @__PURE__ */ jsx("tr", { children: b.headers.map((_h, ci) => /* @__PURE__ */ jsx("td", {
1926
+ style: styles.mdTd,
1927
+ children: renderInline(row[ci] ?? "")
1928
+ }, ci)) }, `${ri}-${row[0] ?? ""}`)) })]
1929
+ })
1930
+ }, idx);
1931
+ case "p": return /* @__PURE__ */ jsx("p", {
1932
+ style: styles.paragraph,
1933
+ children: renderInline(b.text)
1934
+ }, idx);
1935
+ }
1936
+ });
1937
+ }
1938
+ /**
1939
+ * Inline tokenizer for **bold**, *italic*, `code`, and [text](url).
1940
+ * Lazy: scan once, split into segments. The patterns are matched in
1941
+ * priority order (code first so backticks don't get eaten by bold).
1942
+ */
1943
+ function renderInline(text) {
1944
+ const segments = [];
1945
+ let remaining = text;
1946
+ let key = 0;
1947
+ const patterns = [
1948
+ {
1949
+ re: /`([^`]+)`/,
1950
+ render: (m) => /* @__PURE__ */ jsx("code", {
1951
+ style: styles.inlineCode,
1952
+ children: m[1]
1953
+ })
1954
+ },
1955
+ {
1956
+ re: /\[([^\]]+)\]\(([^)]+)\)/,
1957
+ render: (m) => {
1958
+ if (isSafeLinkHref(m[2])) return /* @__PURE__ */ jsx("a", {
1959
+ href: m[2],
1960
+ target: "_blank",
1961
+ rel: "noreferrer noopener",
1962
+ style: styles.link,
1963
+ children: m[1]
1964
+ });
1965
+ return /* @__PURE__ */ jsx(Fragment$1, { children: m[1] });
1966
+ }
1967
+ },
1968
+ {
1969
+ re: /\*\*([^*]+)\*\*/,
1970
+ render: (m) => /* @__PURE__ */ jsx("strong", { children: m[1] })
1971
+ },
1972
+ {
1973
+ re: /\*([^*]+)\*/,
1974
+ render: (m) => /* @__PURE__ */ jsx("em", { children: m[1] })
1975
+ }
1976
+ ];
1977
+ while (remaining.length > 0) {
1978
+ let earliest = null;
1979
+ for (const { re, render } of patterns) {
1980
+ const m = re.exec(remaining);
1981
+ if (m && (earliest === null || m.index < earliest.idx)) earliest = {
1982
+ idx: m.index,
1983
+ len: m[0].length,
1984
+ node: render(m)
1985
+ };
1986
+ }
1987
+ if (earliest === null) {
1988
+ segments.push(remaining);
1989
+ break;
1990
+ }
1991
+ if (earliest.idx > 0) segments.push(remaining.slice(0, earliest.idx));
1992
+ segments.push(/* @__PURE__ */ jsx(React.Fragment, { children: earliest.node }, key++));
1993
+ remaining = remaining.slice(earliest.idx + earliest.len);
1994
+ }
1995
+ return segments;
1996
+ }
1997
+ let spinKeyframesInjected = false;
1998
+ function ensureSpinKeyframes() {
1999
+ if (spinKeyframesInjected || typeof document === "undefined") return;
2000
+ spinKeyframesInjected = true;
2001
+ if (document.getElementById("oxy-spin-keyframes")) return;
2002
+ const el = document.createElement("style");
2003
+ el.id = "oxy-spin-keyframes";
2004
+ el.textContent = "@keyframes oxy-spin { to { transform: rotate(360deg); } }";
2005
+ document.head.appendChild(el);
2006
+ }
2007
+ const SANS = "-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif";
2008
+ const MONO = "ui-monospace, SFMono-Regular, \"SF Mono\", Menlo, Consolas, monospace";
2009
+ const styles = {
2010
+ answerWrap: {
2011
+ fontFamily: SANS,
2012
+ fontSize: 14,
2013
+ lineHeight: 1.5,
2014
+ color: "var(--oxy-shell-foreground, #1f2937)"
2015
+ },
2016
+ statusRow: {
2017
+ display: "flex",
2018
+ alignItems: "center",
2019
+ gap: 8,
2020
+ padding: "8px 0"
2021
+ },
2022
+ spinner: {
2023
+ display: "inline-block",
2024
+ width: 12,
2025
+ height: 12,
2026
+ borderRadius: "50%",
2027
+ border: "2px solid var(--oxy-shell-border, #d1d5db)",
2028
+ borderTopColor: "var(--oxy-shell-muted-fg, #6b7280)",
2029
+ animation: "oxy-spin 0.8s linear infinite"
2030
+ },
2031
+ statusText: { color: "var(--oxy-shell-muted-fg, #6b7280)" },
2032
+ markdown: { marginTop: 8 },
2033
+ h1: {
2034
+ fontSize: 20,
2035
+ fontWeight: 600,
2036
+ margin: "16px 0 8px"
2037
+ },
2038
+ h2: {
2039
+ fontSize: 17,
2040
+ fontWeight: 600,
2041
+ margin: "14px 0 6px"
2042
+ },
2043
+ h3: {
2044
+ fontSize: 15,
2045
+ fontWeight: 600,
2046
+ margin: "12px 0 4px"
2047
+ },
2048
+ paragraph: { margin: "0 0 8px" },
2049
+ list: {
2050
+ margin: "0 0 8px",
2051
+ paddingLeft: 20
2052
+ },
2053
+ codeBlock: {
2054
+ fontFamily: MONO,
2055
+ fontSize: 12,
2056
+ background: "var(--oxy-shell-accent, #f3f4f6)",
2057
+ border: "1px solid var(--oxy-shell-border, #e5e7eb)",
2058
+ borderRadius: 6,
2059
+ padding: "8px 10px",
2060
+ overflowX: "auto",
2061
+ margin: "8px 0"
2062
+ },
2063
+ inlineCode: {
2064
+ fontFamily: MONO,
2065
+ fontSize: "0.92em",
2066
+ background: "var(--oxy-shell-accent, #f3f4f6)",
2067
+ padding: "1px 4px",
2068
+ borderRadius: 3
2069
+ },
2070
+ link: {
2071
+ color: "var(--oxy-shell-link, #2563eb)",
2072
+ textDecoration: "underline"
2073
+ },
2074
+ clarification: {
2075
+ marginTop: 12,
2076
+ padding: "10px 12px",
2077
+ background: "#fef3c7",
2078
+ border: "1px solid #fcd34d",
2079
+ borderRadius: 6,
2080
+ color: "#78350f"
2081
+ },
2082
+ error: {
2083
+ marginTop: 12,
2084
+ padding: "10px 12px",
2085
+ background: "#fee2e2",
2086
+ border: "1px solid #fca5a5",
2087
+ borderRadius: 6,
2088
+ color: "#991b1b"
2089
+ },
2090
+ threadLinkRow: {
2091
+ marginTop: 12,
2092
+ textAlign: "right",
2093
+ display: "flex",
2094
+ justifyContent: "flex-end",
2095
+ alignItems: "center",
2096
+ gap: 6
2097
+ },
2098
+ threadLink: {
2099
+ fontSize: 12,
2100
+ color: "var(--oxy-shell-muted-fg, #6b7280)",
2101
+ textDecoration: "none"
2102
+ },
2103
+ betaBadge: {
2104
+ fontSize: 9,
2105
+ fontWeight: 600,
2106
+ letterSpacing: .5,
2107
+ textTransform: "uppercase",
2108
+ padding: "1px 5px",
2109
+ borderRadius: 3,
2110
+ background: "#fef3c7",
2111
+ color: "#92400e",
2112
+ border: "1px solid #fcd34d"
2113
+ },
2114
+ artifactList: {
2115
+ display: "flex",
2116
+ flexDirection: "column",
2117
+ gap: 8,
2118
+ marginBottom: 8
2119
+ },
2120
+ artifact: {
2121
+ border: "1px solid var(--oxy-shell-border, #e5e7eb)",
2122
+ borderRadius: 6,
2123
+ background: "var(--oxy-shell-accent, #fafafa)",
2124
+ overflow: "hidden"
2125
+ },
2126
+ artifactHeader: {
2127
+ display: "flex",
2128
+ alignItems: "center",
2129
+ gap: 10,
2130
+ width: "100%",
2131
+ padding: "6px 10px",
2132
+ background: "transparent",
2133
+ border: "none",
2134
+ borderBottom: "1px solid transparent",
2135
+ cursor: "pointer",
2136
+ fontFamily: SANS,
2137
+ fontSize: 12,
2138
+ color: "var(--oxy-shell-foreground, #374151)"
2139
+ },
2140
+ artifactBadge: {
2141
+ fontWeight: 600,
2142
+ fontSize: 11,
2143
+ textTransform: "uppercase",
2144
+ letterSpacing: .4,
2145
+ color: "var(--oxy-shell-muted-fg, #4b5563)"
2146
+ },
2147
+ artifactSummary: {
2148
+ color: "var(--oxy-shell-muted-fg, #6b7280)",
2149
+ flex: 1
2150
+ },
2151
+ artifactToggle: { color: "var(--oxy-shell-link, #2563eb)" },
2152
+ sqlBlock: {
2153
+ fontFamily: MONO,
2154
+ fontSize: 12,
2155
+ margin: 0,
2156
+ padding: "8px 10px",
2157
+ background: "#0f172a",
2158
+ color: "#e2e8f0",
2159
+ overflowX: "auto"
2160
+ },
2161
+ resultsWrap: {
2162
+ padding: 8,
2163
+ overflowX: "auto"
2164
+ },
2165
+ resultsTable: {
2166
+ width: "100%",
2167
+ borderCollapse: "collapse",
2168
+ fontSize: 12
2169
+ },
2170
+ resultsTh: {
2171
+ textAlign: "left",
2172
+ padding: "4px 8px",
2173
+ borderBottom: "1px solid var(--oxy-shell-border, #e5e7eb)",
2174
+ fontWeight: 600,
2175
+ color: "var(--oxy-shell-foreground, #374151)"
2176
+ },
2177
+ resultsTd: {
2178
+ padding: "4px 8px",
2179
+ borderBottom: "1px solid var(--oxy-shell-border, #f3f4f6)",
2180
+ color: "var(--oxy-shell-foreground, #1f2937)"
2181
+ },
2182
+ truncatedNote: {
2183
+ fontSize: 11,
2184
+ color: "var(--oxy-shell-muted-fg, #6b7280)",
2185
+ padding: "6px 8px"
2186
+ },
2187
+ mdTableWrap: {
2188
+ overflowX: "auto",
2189
+ margin: "8px 0"
2190
+ },
2191
+ mdTable: {
2192
+ width: "100%",
2193
+ borderCollapse: "collapse",
2194
+ fontSize: 12.5,
2195
+ border: "1px solid var(--oxy-shell-border, #e5e7eb)"
2196
+ },
2197
+ mdTh: {
2198
+ textAlign: "left",
2199
+ padding: "5px 9px",
2200
+ borderBottom: "1px solid var(--oxy-shell-border, #e5e7eb)",
2201
+ background: "var(--oxy-shell-accent, #f3f4f6)",
2202
+ fontWeight: 600,
2203
+ whiteSpace: "nowrap",
2204
+ color: "var(--oxy-shell-foreground, #374151)"
2205
+ },
2206
+ mdTd: {
2207
+ padding: "5px 9px",
2208
+ borderTop: "1px solid var(--oxy-shell-border, #f3f4f6)",
2209
+ verticalAlign: "top",
2210
+ color: "var(--oxy-shell-foreground, #1f2937)"
2211
+ },
2212
+ chatWrap: {
2213
+ fontFamily: SANS,
2214
+ fontSize: 14,
2215
+ color: "var(--oxy-shell-foreground, #1f2937)"
2216
+ },
2217
+ chatForm: {
2218
+ display: "flex",
2219
+ gap: 8,
2220
+ marginBottom: 12
2221
+ },
2222
+ chatInput: {
2223
+ flex: 1,
2224
+ padding: "8px 12px",
2225
+ border: "1px solid var(--oxy-shell-border, #d1d5db)",
2226
+ borderRadius: 6,
2227
+ fontSize: 14,
2228
+ fontFamily: SANS
2229
+ },
2230
+ chatSubmit: {
2231
+ padding: "8px 16px",
2232
+ border: "none",
2233
+ borderRadius: 6,
2234
+ background: "var(--oxy-shell-link, #2563eb)",
2235
+ color: "#ffffff",
2236
+ fontSize: 14,
2237
+ fontWeight: 500,
2238
+ cursor: "pointer"
2239
+ },
2240
+ chatCancel: {
2241
+ padding: "8px 12px",
2242
+ border: "1px solid var(--oxy-shell-border, #d1d5db)",
2243
+ borderRadius: 6,
2244
+ background: "var(--oxy-shell-background, #ffffff)",
2245
+ color: "var(--oxy-shell-foreground, #374151)",
2246
+ fontSize: 14,
2247
+ cursor: "pointer"
2248
+ },
2249
+ emptyState: {
2250
+ padding: "12px 0",
2251
+ color: "var(--oxy-shell-muted-fg, #9ca3af)",
2252
+ fontStyle: "italic"
2253
+ }
2254
+ };
2255
+
2256
+ //#endregion
2257
+ export { interpretCustomerAppError as _, useFunction as a, useQuery as c, useTrackEvent as d, _resetCustomerAppManifestCacheForTest as f, apiErrorFromResponse as g, OxyApiError as h, useAgentRun as i, useResolvedManifest as l, readInjectedAppConfig as m, OxyAppProvider as n, useOxyApp as o, loadCustomerAppManifest as p, OxyChat as r, useProcedureRun as s, OxyAnswer as t, useSemanticQuery as u, getOxyAppLogger as v, setOxyAppLogger as y };
2258
+ //# sourceMappingURL=react-CVdWXcu8.mjs.map