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