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