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