@athenaintel/react 0.10.41-rc.2 → 0.11.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.js CHANGED
@@ -18,10 +18,10 @@ var __privateWrapper = (obj, member, setter, getter) => ({
18
18
  }
19
19
  });
20
20
  var _focused, _cleanup, _setup, _a2, _provider, _providerCalled, _b, _online, _cleanup2, _setup2, _c, _gcTimeout, _d, _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, isInitialPausedFetch_fn, dispatch_fn, _e, _client2, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _f, _client3, _observers, _mutationCache, _retryer2, _Mutation_instances, dispatch_fn2, _g, _mutations, _scopes, _mutationId, _h, _queries, _i, _queryCache, _mutationCache2, _defaultOptions2, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline, _j;
21
- import { jsx, jsxs, Fragment as Fragment$1 } from "react/jsx-runtime";
22
- import { fromThreadMessageLike, bindExternalStoreMessage, getExternalStoreMessages, INTERNAL, useAssistantTransportRuntime, Tools, useAui, useAuiState, AuiProvider, useRemoteThreadListRuntime, AssistantRuntimeProvider, MessagePartPrimitive, MessagePrimitive, useScrollLock, ActionBarPrimitive, AuiIf, ActionBarMorePrimitive, ThreadPrimitive, ComposerPrimitive, ErrorPrimitive, ThreadListPrimitive, ThreadListItemPrimitive } from "@assistant-ui/react";
21
+ import { jsx, Fragment as Fragment$1, jsxs } from "react/jsx-runtime";
23
22
  import * as React from "react";
24
- import React__default, { useMemo, useState, useRef, useEffect, useContext, createContext, useCallback, useLayoutEffect, useReducer, useDebugValue, forwardRef, createRef, memo, createElement, version as version$1, useImperativeHandle } from "react";
23
+ import React__default, { useEffect, useSyncExternalStore, useCallback, useMemo, useState, useRef, useContext, createContext, useLayoutEffect, useReducer, useDebugValue, forwardRef, createRef, memo, createElement, version as version$2, useImperativeHandle } from "react";
24
+ import { fromThreadMessageLike, bindExternalStoreMessage, getExternalStoreMessages, INTERNAL, useAssistantTransportRuntime, Tools, useAui, useAuiState as useAuiState$1, AuiProvider, useRemoteThreadListRuntime, AssistantRuntimeProvider, MessagePartPrimitive, MessagePrimitive, useScrollLock, ActionBarPrimitive, AuiIf, ActionBarMorePrimitive, ThreadPrimitive, ComposerPrimitive, ErrorPrimitive, ThreadListPrimitive, ThreadListItemPrimitive } from "@assistant-ui/react";
25
25
  import { A as AthenaAuthContext } from "./AthenaAuthContext-DQsdayH2.js";
26
26
  import { LocalStorageSession } from "@assistant-ui/react-statewire/local-storage";
27
27
  import { resource, withKey } from "@assistant-ui/tap";
@@ -29,9 +29,913 @@ import { StatewireSendError, StatewireSSE, StatewireWS } from "statewire";
29
29
  import "@assistant-ui/core";
30
30
  import { createMessageConverter } from "@assistant-ui/core/react";
31
31
  import { convertLangChainMessages } from "@assistant-ui/react-langgraph";
32
- import { runsMaterialize, useStatewireState, StatewireThread, useStatewireSendCommand, useStatewireRuns } from "@assistant-ui/react-statewire";
32
+ import { runsMaterialize, StatewireThread, useStatewireSendCommand, useStatewireRuns, useStatewireState } from "@assistant-ui/react-statewire";
33
+ import { useAuiState } from "@assistant-ui/store";
33
34
  import * as ReactDOM from "react-dom";
34
35
  import ReactDOM__default, { flushSync } from "react-dom";
36
+ const version$1 = "0.11.0";
37
+ const packageJson = {
38
+ version: version$1
39
+ };
40
+ const ATHENA_REACT_SDK_VERSION = packageJson.version;
41
+ const DEFAULT_CAPTURE_GATE_CONFIG = {
42
+ globalMaxPerWindow: 50,
43
+ globalWindowMs: 1e4,
44
+ criticalReservePerWindow: 15,
45
+ defaultEventMaxPerWindow: 12,
46
+ defaultEventWindowMs: 6e4,
47
+ defaultDedupeWindowMs: 5e3,
48
+ flushIntervalMs: 3e4,
49
+ flushCoalesceThreshold: 20,
50
+ eventOverrides: {
51
+ memory_profile_sample: { maxPerWindow: 2, windowMs: 3e4, dedupeWindowMs: 15e3 },
52
+ long_task_detected: { maxPerWindow: 3, windowMs: 6e4, dedupeWindowMs: 1e4 },
53
+ collab_connection_status_changed: { maxPerWindow: 6, windowMs: 6e4 },
54
+ collab_first_remote_update: { maxPerWindow: 3, windowMs: 6e4 },
55
+ collab_first_local_update: { maxPerWindow: 3, windowMs: 6e4 },
56
+ collab_render_time_sync_fix: { maxPerWindow: 3, windowMs: 6e4 },
57
+ collab_visibility_recovery: { maxPerWindow: 4, windowMs: 6e4 },
58
+ langgraph_message_validation_error: {
59
+ maxPerWindow: 8,
60
+ windowMs: 6e4,
61
+ dedupeWindowMs: 15e3
62
+ },
63
+ langgraph_messages_validation_error: {
64
+ maxPerWindow: 5,
65
+ windowMs: 6e4,
66
+ dedupeWindowMs: 15e3
67
+ },
68
+ langgraph_interrupt_validation_error: {
69
+ maxPerWindow: 5,
70
+ windowMs: 6e4,
71
+ dedupeWindowMs: 15e3
72
+ },
73
+ langgraph_state_validation_error: {
74
+ maxPerWindow: 5,
75
+ windowMs: 6e4,
76
+ dedupeWindowMs: 15e3
77
+ },
78
+ graphql_error: { maxPerWindow: 12, windowMs: 6e4, dedupeWindowMs: 1e4 },
79
+ chat_error: { maxPerWindow: 8, windowMs: 6e4, dedupeWindowMs: 5e3 },
80
+ memory_critical_threshold: { maxPerWindow: 3, windowMs: 3e5 },
81
+ memory_warning_threshold: { maxPerWindow: 3, windowMs: 3e5 },
82
+ pptx_slide_changed: { maxPerWindow: 8, windowMs: 3e4 }
83
+ }
84
+ };
85
+ const CRITICAL_EVENT_PATTERNS = [
86
+ /(?:^|_)failed$/,
87
+ /(?:^|_)error(?:_|$)/,
88
+ /crash/,
89
+ /^oom_/,
90
+ /aw_snap/,
91
+ /chunk_load/,
92
+ /global_error/,
93
+ /\$exception$/,
94
+ /^404_error$/,
95
+ /^500_error$/,
96
+ /_boundary_/
97
+ ];
98
+ const BYPASS_OPTION_KEY = "__posthog_gate_bypass";
99
+ function isCriticalPosthogEvent(event) {
100
+ return CRITICAL_EVENT_PATTERNS.some((pattern) => pattern.test(event));
101
+ }
102
+ function shouldBypassCaptureGate(options) {
103
+ if (!options || typeof options !== "object") return false;
104
+ return options[BYPASS_OPTION_KEY] === true;
105
+ }
106
+ function withCaptureGateBypass(options) {
107
+ return {
108
+ ...options ?? {},
109
+ [BYPASS_OPTION_KEY]: true
110
+ };
111
+ }
112
+ function pruneWindow(window2, now, windowMs) {
113
+ const cutoff = now - windowMs;
114
+ while (window2.timestamps.length > 0 && window2.timestamps[0] < cutoff) {
115
+ window2.timestamps.shift();
116
+ }
117
+ }
118
+ function countInWindow(window2, now, windowMs) {
119
+ pruneWindow(window2, now, windowMs);
120
+ return window2.timestamps.length;
121
+ }
122
+ function recordInWindow(window2, now) {
123
+ window2.timestamps.push(now);
124
+ }
125
+ function stableStringify(value) {
126
+ if (value == null) return String(value);
127
+ if (typeof value !== "object") return String(value);
128
+ if (Array.isArray(value)) {
129
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
130
+ }
131
+ const record2 = value;
132
+ const keys2 = Object.keys(record2).sort();
133
+ return `{${keys2.map((key) => `${key}:${stableStringify(record2[key])}`).join(",")}}`;
134
+ }
135
+ function fingerprintProperties(properties) {
136
+ if (!properties) return "";
137
+ const keys2 = [
138
+ "error",
139
+ "error_message",
140
+ "message",
141
+ "reason",
142
+ "status",
143
+ "code",
144
+ "asset_id",
145
+ "doc_id",
146
+ "thread_id",
147
+ "session_id",
148
+ "operation",
149
+ "path",
150
+ "url",
151
+ "chunk_identifier",
152
+ "validation_path"
153
+ ];
154
+ const subset = {};
155
+ for (const key of keys2) {
156
+ if (key in properties) {
157
+ subset[key] = properties[key];
158
+ }
159
+ }
160
+ return stableStringify(subset);
161
+ }
162
+ function buildCaptureFingerprint(event, properties) {
163
+ return `${event}|${fingerprintProperties(properties)}`;
164
+ }
165
+ function buildCoalescedCaptureProperties(payload) {
166
+ const windowMs = payload.lastAt - payload.firstAt;
167
+ return {
168
+ ...payload.properties,
169
+ coalesced: true,
170
+ coalesced_count: payload.coalescedCount,
171
+ coalesced_first_at: new Date(payload.firstAt).toISOString(),
172
+ coalesced_last_at: new Date(payload.lastAt).toISOString(),
173
+ coalesced_window_ms: windowMs,
174
+ coalesced_suppression_reason: payload.suppressionReason
175
+ };
176
+ }
177
+ class PosthogCaptureGate {
178
+ constructor(config2 = DEFAULT_CAPTURE_GATE_CONFIG) {
179
+ __publicField(this, "config");
180
+ __publicField(this, "globalWindow", { timestamps: [] });
181
+ __publicField(this, "eventWindows", /* @__PURE__ */ new Map());
182
+ __publicField(this, "activeDedupe", /* @__PURE__ */ new Map());
183
+ __publicField(this, "coalesceBuckets", /* @__PURE__ */ new Map());
184
+ __publicField(this, "emittedTotal", 0);
185
+ __publicField(this, "coalescedTotal", 0);
186
+ __publicField(this, "flushedCoalescedTotal", 0);
187
+ this.config = config2;
188
+ }
189
+ resetForTests() {
190
+ this.globalWindow.timestamps.length = 0;
191
+ this.eventWindows.clear();
192
+ this.activeDedupe.clear();
193
+ this.coalesceBuckets.clear();
194
+ this.emittedTotal = 0;
195
+ this.coalescedTotal = 0;
196
+ this.flushedCoalescedTotal = 0;
197
+ }
198
+ getSnapshot() {
199
+ const coalescedPendingByEvent = {};
200
+ let coalescedPending = 0;
201
+ for (const bucket of this.coalesceBuckets.values()) {
202
+ coalescedPending += bucket.count;
203
+ coalescedPendingByEvent[bucket.event] = (coalescedPendingByEvent[bucket.event] ?? 0) + bucket.count;
204
+ }
205
+ return {
206
+ coalescedPending,
207
+ coalescedPendingByEvent,
208
+ emittedTotal: this.emittedTotal,
209
+ coalescedTotal: this.coalescedTotal,
210
+ flushedCoalescedTotal: this.flushedCoalescedTotal
211
+ };
212
+ }
213
+ evaluateCapture(event, properties, options, now = Date.now()) {
214
+ if (shouldBypassCaptureGate(options)) {
215
+ return { action: "emit" };
216
+ }
217
+ const fingerprint = buildCaptureFingerprint(event, properties);
218
+ const bucketKey = fingerprint;
219
+ const override = this.config.eventOverrides[event];
220
+ const dedupeWindowMs = (override == null ? void 0 : override.dedupeWindowMs) ?? this.config.defaultDedupeWindowMs;
221
+ const lastDedupe = this.activeDedupe.get(event);
222
+ if (lastDedupe && lastDedupe.fingerprint === fingerprint && now - lastDedupe.at < dedupeWindowMs) {
223
+ return this.recordCoalesce(event, bucketKey, fingerprint, properties, "dedupe", now);
224
+ }
225
+ const critical = isCriticalPosthogEvent(event);
226
+ const globalCount = countInWindow(this.globalWindow, now, this.config.globalWindowMs);
227
+ const normalBudget = Math.max(
228
+ 0,
229
+ this.config.globalMaxPerWindow - this.config.criticalReservePerWindow
230
+ );
231
+ if (critical) {
232
+ if (globalCount >= this.config.globalMaxPerWindow) {
233
+ return this.recordCoalesce(event, bucketKey, fingerprint, properties, "global_budget", now);
234
+ }
235
+ } else if (globalCount >= normalBudget) {
236
+ return this.recordCoalesce(event, bucketKey, fingerprint, properties, "global_budget", now);
237
+ }
238
+ const eventWindow = this.eventWindows.get(event) ?? { timestamps: [] };
239
+ this.eventWindows.set(event, eventWindow);
240
+ const eventMax = (override == null ? void 0 : override.maxPerWindow) ?? this.config.defaultEventMaxPerWindow;
241
+ const eventWindowMs = (override == null ? void 0 : override.windowMs) ?? this.config.defaultEventWindowMs;
242
+ const eventCount = countInWindow(eventWindow, now, eventWindowMs);
243
+ if (eventCount >= eventMax) {
244
+ return this.recordCoalesce(event, bucketKey, fingerprint, properties, "event_budget", now);
245
+ }
246
+ recordInWindow(this.globalWindow, now);
247
+ recordInWindow(eventWindow, now);
248
+ this.activeDedupe.set(event, { fingerprint, bucketKey, at: now });
249
+ this.emittedTotal += 1;
250
+ return { action: "emit" };
251
+ }
252
+ /** Returns payloads ready to flush (does not mutate buckets until caller confirms). */
253
+ collectFlushCandidates(now = Date.now()) {
254
+ const payloads = [];
255
+ for (const bucket of this.coalesceBuckets.values()) {
256
+ const shouldFlushBySize = bucket.count >= this.config.flushCoalesceThreshold;
257
+ const shouldFlushByAge = now - bucket.firstAt >= this.config.flushIntervalMs;
258
+ if (!shouldFlushBySize && !shouldFlushByAge) {
259
+ continue;
260
+ }
261
+ payloads.push({
262
+ bucketKey: bucket.bucketKey,
263
+ event: bucket.event,
264
+ properties: bucket.sampleProperties,
265
+ coalescedCount: bucket.count,
266
+ firstAt: bucket.firstAt,
267
+ lastAt: bucket.lastAt,
268
+ suppressionReason: bucket.suppressionReason
269
+ });
270
+ }
271
+ return payloads;
272
+ }
273
+ /** Remove flushed bucket keys after successful emit. */
274
+ acknowledgeFlushed(payloads) {
275
+ for (const payload of payloads) {
276
+ this.coalesceBuckets.delete(payload.bucketKey);
277
+ this.flushedCoalescedTotal += payload.coalescedCount;
278
+ }
279
+ }
280
+ /** After coalescing, flush immediately if the bucket crossed the early threshold. */
281
+ takeBucketIfReady(bucketKey, now = Date.now()) {
282
+ const bucket = this.coalesceBuckets.get(bucketKey);
283
+ if (!bucket) return null;
284
+ const shouldFlushBySize = bucket.count >= this.config.flushCoalesceThreshold;
285
+ const shouldFlushByAge = now - bucket.firstAt >= this.config.flushIntervalMs;
286
+ if (!shouldFlushBySize && !shouldFlushByAge) {
287
+ return null;
288
+ }
289
+ this.coalesceBuckets.delete(bucketKey);
290
+ this.flushedCoalescedTotal += bucket.count;
291
+ return {
292
+ bucketKey: bucket.bucketKey,
293
+ event: bucket.event,
294
+ properties: bucket.sampleProperties,
295
+ coalescedCount: bucket.count,
296
+ firstAt: bucket.firstAt,
297
+ lastAt: bucket.lastAt,
298
+ suppressionReason: bucket.suppressionReason
299
+ };
300
+ }
301
+ /** Force-flush every pending bucket (e.g. page hide). */
302
+ collectAllPending() {
303
+ return [...this.coalesceBuckets.values()].map((bucket) => ({
304
+ bucketKey: bucket.bucketKey,
305
+ event: bucket.event,
306
+ properties: bucket.sampleProperties,
307
+ coalescedCount: bucket.count,
308
+ firstAt: bucket.firstAt,
309
+ lastAt: bucket.lastAt,
310
+ suppressionReason: bucket.suppressionReason
311
+ }));
312
+ }
313
+ recordCoalesce(event, bucketKey, fingerprint, properties, reason, now) {
314
+ const existing = this.coalesceBuckets.get(bucketKey);
315
+ if (existing) {
316
+ existing.count += 1;
317
+ existing.lastAt = now;
318
+ existing.sampleProperties = { ...existing.sampleProperties, ...properties ?? {} };
319
+ } else {
320
+ this.coalesceBuckets.set(bucketKey, {
321
+ event,
322
+ bucketKey,
323
+ fingerprint,
324
+ count: 1,
325
+ firstAt: now,
326
+ lastAt: now,
327
+ suppressionReason: reason,
328
+ sampleProperties: { ...properties ?? {} }
329
+ });
330
+ }
331
+ this.coalescedTotal += 1;
332
+ this.activeDedupe.set(event, { fingerprint, bucketKey, at: now });
333
+ return { action: "coalesce", reason, bucketKey };
334
+ }
335
+ }
336
+ const gate = new PosthogCaptureGate(DEFAULT_CAPTURE_GATE_CONFIG);
337
+ let wrappedClient = null;
338
+ let originalCaptureRef = null;
339
+ let flushTimer = null;
340
+ let lifecycleHooksInstalled = false;
341
+ function getPosthogCaptureGate() {
342
+ return gate;
343
+ }
344
+ function emitThroughOriginal(event, properties, options) {
345
+ if (!originalCaptureRef) return void 0;
346
+ return originalCaptureRef(event, properties, withCaptureGateBypass(options));
347
+ }
348
+ function flushCoalescedPayload(payload) {
349
+ emitThroughOriginal(payload.event, buildCoalescedCaptureProperties(payload));
350
+ }
351
+ function flushCoalescedCaptures(options) {
352
+ const payloads = (options == null ? void 0 : options.force) ? gate.collectAllPending() : gate.collectFlushCandidates();
353
+ if (payloads.length === 0) return;
354
+ for (const payload of payloads) {
355
+ flushCoalescedPayload(payload);
356
+ }
357
+ gate.acknowledgeFlushed(payloads);
358
+ }
359
+ function installLifecycleFlushHooks() {
360
+ if (lifecycleHooksInstalled || typeof window === "undefined") return;
361
+ lifecycleHooksInstalled = true;
362
+ const flushOnHide = () => {
363
+ flushCoalescedCaptures({ force: true });
364
+ };
365
+ window.addEventListener("pagehide", flushOnHide);
366
+ document.addEventListener("visibilitychange", () => {
367
+ if (document.visibilityState === "hidden") {
368
+ flushOnHide();
369
+ }
370
+ });
371
+ if (!flushTimer) {
372
+ flushTimer = setInterval(() => {
373
+ flushCoalescedCaptures();
374
+ }, DEFAULT_CAPTURE_GATE_CONFIG.flushIntervalMs);
375
+ }
376
+ }
377
+ function wrapPosthogClient(client) {
378
+ if (wrappedClient === client) {
379
+ return client;
380
+ }
381
+ originalCaptureRef = client.capture.bind(client);
382
+ const originalCaptureException = typeof client.captureException === "function" ? client.captureException.bind(client) : null;
383
+ installLifecycleFlushHooks();
384
+ client.capture = ((event, properties, options) => {
385
+ const outcome = gate.evaluateCapture(event, properties, options);
386
+ if (outcome.action === "coalesce") {
387
+ const readyPayload = gate.takeBucketIfReady(outcome.bucketKey);
388
+ if (readyPayload) {
389
+ flushCoalescedPayload(readyPayload);
390
+ }
391
+ return void 0;
392
+ }
393
+ return emitThroughOriginal(event, properties, options);
394
+ });
395
+ if (originalCaptureException) {
396
+ client.captureException = ((error2, additionalProperties) => {
397
+ const mergedProperties = {
398
+ ...additionalProperties ?? {},
399
+ $exception_message: error2 instanceof Error ? error2.message : String(error2),
400
+ $exception_type: error2 instanceof Error ? error2.name : typeof error2
401
+ };
402
+ const outcome = gate.evaluateCapture("$exception", mergedProperties);
403
+ if (outcome.action === "coalesce") {
404
+ const readyPayload = gate.takeBucketIfReady(outcome.bucketKey);
405
+ if (readyPayload) {
406
+ flushCoalescedPayload(readyPayload);
407
+ }
408
+ return void 0;
409
+ }
410
+ return originalCaptureException(error2, additionalProperties);
411
+ });
412
+ }
413
+ wrappedClient = client;
414
+ return client;
415
+ }
416
+ function capturePosthogEvent(client, event, properties, options) {
417
+ if (!client || typeof client.capture !== "function") return;
418
+ client.capture(event, properties, options);
419
+ }
420
+ function capturePosthogException(client, error2, properties, options) {
421
+ if (!client) return;
422
+ if (typeof client.captureException === "function") {
423
+ client.captureException(error2, properties);
424
+ return;
425
+ }
426
+ capturePosthogEvent(
427
+ client,
428
+ "$exception",
429
+ {
430
+ ...properties ?? {},
431
+ $exception_message: error2.message,
432
+ $exception_type: error2.name,
433
+ $exception_stack: error2.stack
434
+ },
435
+ options
436
+ );
437
+ }
438
+ let posthogInstance = null;
439
+ let initPromise = null;
440
+ const DEFAULT_HOST = "https://us.i.posthog.com";
441
+ async function initializePostHog(apiKey, host, debug) {
442
+ if (posthogInstance) return posthogInstance;
443
+ if (typeof window === "undefined") return null;
444
+ try {
445
+ const posthog = (await import("posthog-js")).default;
446
+ posthog.init(apiKey, {
447
+ api_host: host,
448
+ autocapture: true,
449
+ capture_pageview: false,
450
+ session_recording: {
451
+ recordCrossOriginIframes: true,
452
+ maskAllInputs: true
453
+ },
454
+ loaded: (ph) => {
455
+ wrapPosthogClient(ph);
456
+ if (debug) {
457
+ ph.debug(true);
458
+ }
459
+ }
460
+ });
461
+ wrapPosthogClient(posthog);
462
+ posthogInstance = posthog;
463
+ return posthog;
464
+ } catch {
465
+ initPromise = null;
466
+ return null;
467
+ }
468
+ }
469
+ function getPostHogInstance() {
470
+ return posthogInstance;
471
+ }
472
+ function PostHogProvider({
473
+ children,
474
+ config: config2
475
+ }) {
476
+ const apiKey = (config2 == null ? void 0 : config2.apiKey) ?? "";
477
+ const host = (config2 == null ? void 0 : config2.host) ?? DEFAULT_HOST;
478
+ const debug = (config2 == null ? void 0 : config2.debug) ?? false;
479
+ useEffect(() => {
480
+ if (!apiKey || typeof window === "undefined") return;
481
+ if (!initPromise) {
482
+ initPromise = initializePostHog(apiKey, host, debug);
483
+ }
484
+ }, [apiKey, host, debug]);
485
+ return /* @__PURE__ */ jsx(Fragment$1, { children });
486
+ }
487
+ const ATHENA_SDK_ERROR_CODES = {
488
+ /** No token and no API key resolved before a request had to be sent. */
489
+ auth_missing: "auth_missing",
490
+ /** The server refused the credential (401 / statewire `unauthorized` fin). */
491
+ auth_rejected: "auth_rejected",
492
+ /** `/_athena/auth` or the iframe bridge did not answer within the timeout. */
493
+ auth_bridge_timeout: "auth_bridge_timeout",
494
+ /** `/_athena/auth` answered with a non-404 error. */
495
+ auth_bridge_failed: "auth_bridge_failed",
496
+ /** The statewire sync URL could not be derived from the configuration. */
497
+ config_invalid: "config_invalid",
498
+ /** A prop was set that the active transport ignores (e.g. `agent` on statewire). */
499
+ config_ignored: "config_ignored",
500
+ /** The thread list request failed. */
501
+ threads_list_failed: "threads_list_failed",
502
+ /** Loading a thread's history failed. */
503
+ thread_load_failed: "thread_load_failed",
504
+ /** The statewire host rejected a command (structured `{status, detail}`). */
505
+ statewire_rejected: "statewire_rejected",
506
+ /** The statewire connection is gone and will not reconnect on its own. */
507
+ statewire_gone: "statewire_gone",
508
+ /** The legacy `/api/chat` stream failed. */
509
+ stream_failed: "stream_failed",
510
+ /** The selected collab agent / channel was refused by the backend. */
511
+ collab_agent_rejected: "collab_agent_rejected",
512
+ /** Anything else. */
513
+ unknown: "unknown"
514
+ };
515
+ class AthenaSdkError extends Error {
516
+ constructor(options) {
517
+ super(options.message, options.cause === void 0 ? void 0 : { cause: options.cause });
518
+ __publicField(this, "code");
519
+ __publicField(this, "hint");
520
+ __publicField(this, "status");
521
+ __publicField(this, "detail");
522
+ __publicField(this, "context");
523
+ this.name = "AthenaSdkError";
524
+ this.code = options.code;
525
+ this.hint = options.hint;
526
+ this.status = options.status;
527
+ this.detail = options.detail;
528
+ this.context = options.context ?? {};
529
+ }
530
+ /** A log/console-friendly one-liner: `[code] message — hint`. */
531
+ describe() {
532
+ return `[${this.code}] ${this.message}${this.hint ? ` — ${this.hint}` : ""}`;
533
+ }
534
+ toJSON() {
535
+ return {
536
+ name: this.name,
537
+ code: this.code,
538
+ message: this.message,
539
+ hint: this.hint,
540
+ status: this.status,
541
+ detail: this.detail,
542
+ context: this.context
543
+ };
544
+ }
545
+ }
546
+ function isAthenaSdkError(value) {
547
+ return value instanceof AthenaSdkError;
548
+ }
549
+ function toAthenaSdkError(value, fallback) {
550
+ if (isAthenaSdkError(value)) return value;
551
+ const message = value instanceof Error && value.message ? value.message : fallback.message;
552
+ return new AthenaSdkError({ ...fallback, message, cause: value });
553
+ }
554
+ function readRejectionDetail(detail) {
555
+ if (typeof detail === "string") return { code: null, message: detail || null };
556
+ if (!detail || typeof detail !== "object") return { code: null, message: null };
557
+ const record2 = detail;
558
+ return {
559
+ code: typeof record2.code === "string" ? record2.code : null,
560
+ message: typeof record2.message === "string" ? record2.message : null
561
+ };
562
+ }
563
+ const ATHENA_DIAGNOSTIC_LEVELS = ["debug", "info", "warn", "error"];
564
+ const LEVEL_RANK = {
565
+ debug: 0,
566
+ info: 1,
567
+ warn: 2,
568
+ error: 3
569
+ };
570
+ const DEFAULT_CONFIG = {
571
+ console: false,
572
+ posthog: false,
573
+ bufferSize: 300
574
+ };
575
+ const CONSOLE_PREFIX = "[AthenaSDK]";
576
+ const LOCAL_STORAGE_DEBUG_KEY = "athena:debug";
577
+ const GLOBAL_KEY = "__ATHENA_SDK__";
578
+ const REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;
579
+ function redact(data) {
580
+ if (!data) return void 0;
581
+ const out = {};
582
+ for (const [key, value] of Object.entries(data)) {
583
+ if (REDACT_KEYS.test(key)) {
584
+ out[key] = typeof value === "string" && value.length > 0 ? `<redacted:${value.length}>` : "<redacted>";
585
+ } else {
586
+ out[key] = value;
587
+ }
588
+ }
589
+ return out;
590
+ }
591
+ function nowMs() {
592
+ return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
593
+ }
594
+ function readLocalDebugLevel() {
595
+ try {
596
+ if (typeof localStorage === "undefined") return null;
597
+ const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);
598
+ if (!raw) return null;
599
+ if (ATHENA_DIAGNOSTIC_LEVELS.includes(raw)) {
600
+ return raw;
601
+ }
602
+ return raw === "1" || raw === "true" ? "debug" : null;
603
+ } catch {
604
+ return null;
605
+ }
606
+ }
607
+ class AthenaDiagnosticsBus {
608
+ constructor() {
609
+ __publicField(this, "config", { ...DEFAULT_CONFIG });
610
+ __publicField(this, "events", []);
611
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
612
+ __publicField(this, "snapshotListeners", /* @__PURE__ */ new Set());
613
+ __publicField(this, "seq", 0);
614
+ __publicField(this, "gauges", {});
615
+ __publicField(this, "timings", {});
616
+ __publicField(this, "spans", /* @__PURE__ */ new Map());
617
+ __publicField(this, "cachedSnapshot", null);
618
+ }
619
+ configure(partial2) {
620
+ this.config = { ...this.config, ...partial2 };
621
+ if (this.events.length > this.config.bufferSize) {
622
+ this.events = this.events.slice(-this.config.bufferSize);
623
+ }
624
+ this.invalidate();
625
+ }
626
+ getConfig() {
627
+ return this.config;
628
+ }
629
+ /** Effective console level: the configured one, or `localStorage['athena:debug']`. */
630
+ consoleLevel() {
631
+ if (this.config.console !== false) return this.config.console;
632
+ return readLocalDebugLevel() ?? false;
633
+ }
634
+ emit(name, options = {}) {
635
+ const level = options.level ?? (options.error !== void 0 ? "error" : "info");
636
+ const error2 = options.error === void 0 ? void 0 : toAthenaSdkError(options.error, {
637
+ code: "unknown",
638
+ message: `Unexpected error during ${name}`
639
+ });
640
+ const event = {
641
+ seq: ++this.seq,
642
+ t: Math.round(nowMs() * 10) / 10,
643
+ at: (/* @__PURE__ */ new Date()).toISOString(),
644
+ name,
645
+ level,
646
+ ...options.durationMs !== void 0 && { durationMs: Math.round(options.durationMs) },
647
+ ...options.data && { data: redact(options.data) },
648
+ ...error2 && { error: error2 }
649
+ };
650
+ this.events.push(event);
651
+ if (this.events.length > this.config.bufferSize) {
652
+ this.events.splice(0, this.events.length - this.config.bufferSize);
653
+ }
654
+ if (event.durationMs !== void 0) {
655
+ this.timings[name] = event.durationMs;
656
+ }
657
+ this.invalidate();
658
+ this.echoToConsole(event);
659
+ this.forwardToPostHog(event);
660
+ for (const listener of this.listeners) {
661
+ try {
662
+ listener(event);
663
+ } catch (listenerError) {
664
+ console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);
665
+ }
666
+ }
667
+ if (this.config.onEvent) {
668
+ try {
669
+ this.config.onEvent(event);
670
+ } catch (callbackError) {
671
+ console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);
672
+ }
673
+ }
674
+ if (error2 && this.config.onError) {
675
+ try {
676
+ this.config.onError(error2, event);
677
+ } catch (callbackError) {
678
+ console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);
679
+ }
680
+ }
681
+ for (const notify of this.snapshotListeners) notify();
682
+ return event;
683
+ }
684
+ /** Record an error-level event. Returns the normalized `AthenaSdkError`. */
685
+ error(name, error2, fallback, data) {
686
+ const normalized = toAthenaSdkError(error2, fallback);
687
+ this.emit(name, { level: "error", error: normalized, data });
688
+ return normalized;
689
+ }
690
+ /**
691
+ * Start a named span. Returns a function that ends it and emits `doneName`
692
+ * with `durationMs` (or `errorName` when passed an error). Also records a
693
+ * `performance.measure` so the span shows in the browser's Performance panel.
694
+ */
695
+ span(spanName, startName, data) {
696
+ const startedAt = nowMs();
697
+ this.spans.set(spanName, startedAt);
698
+ this.mark(`${spanName}:start`);
699
+ this.emit(startName, { level: "debug", data });
700
+ return (doneName, doneOptions = {}) => {
701
+ const durationMs = nowMs() - startedAt;
702
+ this.spans.delete(spanName);
703
+ this.mark(`${spanName}:end`);
704
+ this.measure(spanName);
705
+ this.emit(doneName, {
706
+ level: doneOptions.error !== void 0 ? "error" : "info",
707
+ durationMs,
708
+ data: doneOptions.data,
709
+ error: doneOptions.error
710
+ });
711
+ return durationMs;
712
+ };
713
+ }
714
+ /** Set a gauge (latest-value metric): connection status, transport, auth mode. */
715
+ gauge(name, value) {
716
+ if (this.gauges[name] === value) return;
717
+ this.gauges[name] = value;
718
+ this.invalidate();
719
+ for (const notify of this.snapshotListeners) notify();
720
+ }
721
+ subscribe(listener) {
722
+ this.listeners.add(listener);
723
+ return () => {
724
+ this.listeners.delete(listener);
725
+ };
726
+ }
727
+ /**
728
+ * Additive consumer registration: every registered consumer receives every
729
+ * event (and every error), unlike the single `onEvent`/`onError` config
730
+ * slots which are last-writer-wins. `AthenaProvider` registers through this
731
+ * so two mounted providers never clobber each other's callbacks.
732
+ */
733
+ addConsumer(consumer) {
734
+ return this.subscribe((event) => {
735
+ var _a3, _b2;
736
+ try {
737
+ (_a3 = consumer.onEvent) == null ? void 0 : _a3.call(consumer, event);
738
+ } catch (callbackError) {
739
+ console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);
740
+ }
741
+ if (event.error) {
742
+ try {
743
+ (_b2 = consumer.onError) == null ? void 0 : _b2.call(consumer, event.error, event);
744
+ } catch (callbackError) {
745
+ console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);
746
+ }
747
+ }
748
+ });
749
+ }
750
+ /** Subscribe to snapshot changes (for `useSyncExternalStore`). */
751
+ subscribeSnapshot(listener) {
752
+ this.snapshotListeners.add(listener);
753
+ return () => {
754
+ this.snapshotListeners.delete(listener);
755
+ };
756
+ }
757
+ snapshot() {
758
+ if (!this.cachedSnapshot) {
759
+ const { onEvent: _onEvent, onError: _onError, ...config2 } = this.config;
760
+ this.cachedSnapshot = {
761
+ sdkVersion: ATHENA_REACT_SDK_VERSION,
762
+ config: config2,
763
+ events: [...this.events],
764
+ gauges: { ...this.gauges },
765
+ timings: { ...this.timings }
766
+ };
767
+ }
768
+ return this.cachedSnapshot;
769
+ }
770
+ /** Copy-paste-able JSON of the current snapshot (errors serialized). */
771
+ export() {
772
+ return JSON.stringify(
773
+ this.snapshot(),
774
+ (_key, value) => isAthenaSdkError(value) ? value.toJSON() : value,
775
+ 2
776
+ );
777
+ }
778
+ clear() {
779
+ this.events = [];
780
+ this.timings = {};
781
+ this.invalidate();
782
+ for (const notify of this.snapshotListeners) notify();
783
+ }
784
+ invalidate() {
785
+ this.cachedSnapshot = null;
786
+ }
787
+ mark(name) {
788
+ try {
789
+ if (typeof performance !== "undefined" && typeof performance.mark === "function") {
790
+ performance.mark(`athena-sdk:${name}`);
791
+ }
792
+ } catch {
793
+ }
794
+ }
795
+ measure(spanName) {
796
+ try {
797
+ if (typeof performance !== "undefined" && typeof performance.measure === "function") {
798
+ performance.measure(
799
+ `athena-sdk:${spanName}`,
800
+ `athena-sdk:${spanName}:start`,
801
+ `athena-sdk:${spanName}:end`
802
+ );
803
+ }
804
+ } catch {
805
+ }
806
+ }
807
+ echoToConsole(event) {
808
+ const level = this.consoleLevel();
809
+ if (level === false) {
810
+ if (event.level === "error" && event.error) {
811
+ console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? "");
812
+ }
813
+ return;
814
+ }
815
+ if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;
816
+ const suffix = event.durationMs !== void 0 ? ` (${event.durationMs}ms)` : "";
817
+ const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;
818
+ const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;
819
+ const method = event.level === "error" ? console.error : event.level === "warn" ? console.warn : event.level === "debug" ? console.debug : console.info;
820
+ method(line, payload ?? "");
821
+ }
822
+ forwardToPostHog(event) {
823
+ if (!this.config.posthog) return;
824
+ if (event.durationMs === void 0 && event.level !== "error") return;
825
+ try {
826
+ const client = getPostHogInstance();
827
+ capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\./g, "_")}`, {
828
+ sdk_version: ATHENA_REACT_SDK_VERSION,
829
+ level: event.level,
830
+ ...event.durationMs !== void 0 && { duration_ms: event.durationMs },
831
+ ...event.error && {
832
+ error_code: event.error.code,
833
+ error_message: event.error.message,
834
+ error_status: event.error.status
835
+ },
836
+ ...event.data
837
+ });
838
+ } catch {
839
+ }
840
+ }
841
+ }
842
+ const athenaDiagnostics = new AthenaDiagnosticsBus();
843
+ function installAthenaDiagnosticsGlobal() {
844
+ if (typeof window === "undefined") return;
845
+ const globalWindow = window;
846
+ const existing = globalWindow[GLOBAL_KEY] ?? {};
847
+ globalWindow[GLOBAL_KEY] = {
848
+ ...existing,
849
+ version: ATHENA_REACT_SDK_VERSION,
850
+ diagnostics: {
851
+ snapshot: () => athenaDiagnostics.snapshot(),
852
+ export: () => athenaDiagnostics.export(),
853
+ clear: () => athenaDiagnostics.clear(),
854
+ enableConsole: (level = "debug") => {
855
+ try {
856
+ localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);
857
+ } catch {
858
+ }
859
+ athenaDiagnostics.configure({ console: level });
860
+ },
861
+ disableConsole: () => {
862
+ try {
863
+ localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);
864
+ } catch {
865
+ }
866
+ athenaDiagnostics.configure({ console: false });
867
+ }
868
+ }
869
+ };
870
+ }
871
+ function debugPropToDiagnosticsConfig(debug) {
872
+ if (debug === void 0) return {};
873
+ if (debug === true) return { console: "debug" };
874
+ if (debug === false) return { console: false };
875
+ if (typeof debug === "string") return { console: debug };
876
+ return debug;
877
+ }
878
+ function useAthenaDiagnostics() {
879
+ const snapshot = useSyncExternalStore(
880
+ athenaDiagnostics.subscribeSnapshot.bind(athenaDiagnostics),
881
+ athenaDiagnostics.snapshot.bind(athenaDiagnostics),
882
+ athenaDiagnostics.snapshot.bind(athenaDiagnostics)
883
+ );
884
+ const clear = useCallback(() => athenaDiagnostics.clear(), []);
885
+ const exportJson = useCallback(() => athenaDiagnostics.export(), []);
886
+ return { ...snapshot, clear, export: exportJson };
887
+ }
888
+ const DEEP_AGENT_RUNTIME_MARKER = "athena_deep_agent";
889
+ const STATEWIRE_START_CHANNEL = "web";
890
+ const STATEWIRE_RUN_LABEL = "Athena SDK";
891
+ const DEFAULT_STATEWIRE_MODEL = "claude-sonnet-5";
892
+ const COLLAB_AGENT_REF_PREFIX = "collab_agent:";
893
+ function parseCollabAgentRef(agent2) {
894
+ if (typeof agent2 !== "string" || !agent2.startsWith(COLLAB_AGENT_REF_PREFIX)) return null;
895
+ const assetId = agent2.slice(COLLAB_AGENT_REF_PREFIX.length).trim();
896
+ return assetId || null;
897
+ }
898
+ function buildStatewireRunConfig(options = {}) {
899
+ var _a3, _b2, _c2, _d2, _e2;
900
+ const collabAgentId = parseCollabAgentRef(options.agent);
901
+ const collabChannelId = collabAgentId && ((_a3 = options.channel) == null ? void 0 : _a3.trim()) ? options.channel.trim() : void 0;
902
+ const model = options.model ?? (collabAgentId ? void 0 : DEFAULT_STATEWIRE_MODEL);
903
+ const panelModel = model ?? DEFAULT_STATEWIRE_MODEL;
904
+ const enabledTools = Array.from(
905
+ /* @__PURE__ */ new Set([...options.tools ?? [], ...options.frontendToolIds ?? []])
906
+ );
907
+ const systemPrompt = ((_b2 = options.systemPrompt) == null ? void 0 : _b2.trim()) ?? "";
908
+ return {
909
+ custom: {
910
+ runtime: DEEP_AGENT_RUNTIME_MARKER,
911
+ // With a collab channel selected, omit the SDK's own 'web' stamp: the
912
+ // request's explicit start_channel would win over the backend overlay's
913
+ // kind-mapped provenance (a custom SMS channel must stamp 'sms').
914
+ ...collabChannelId ? {} : { start_channel: STATEWIRE_START_CHANNEL },
915
+ ...model ? { model } : {},
916
+ // An empty list is behavior-identical to an absent key for the parser
917
+ // (both coerce to []), but the collab-agent overlay merges request keys
918
+ // OVER the agent definition — so an explicit empty list would erase the
919
+ // agent's configured tools. Omit it when empty.
920
+ ...enabledTools.length > 0 ? { enabled_tools: enabledTools } : {},
921
+ panel_config: {
922
+ model: panelModel,
923
+ enabled_tools: enabledTools,
924
+ system_prompt: systemPrompt,
925
+ run_label: STATEWIRE_RUN_LABEL
926
+ },
927
+ ...collabAgentId ? { collab_agent_id: collabAgentId } : {},
928
+ ...collabChannelId ? { collab_channel_id: collabChannelId } : {},
929
+ ...systemPrompt ? { system_prompt: systemPrompt } : {},
930
+ ...((_c2 = options.workbench) == null ? void 0 : _c2.length) ? { workbench: options.workbench } : {},
931
+ ...((_d2 = options.knowledgeBase) == null ? void 0 : _d2.length) ? { knowledge_base: options.knowledgeBase } : {},
932
+ ...options.customToolConfigs ? { custom_tool_configs: options.customToolConfigs } : {},
933
+ ...options.appId ? { app_id: options.appId } : {},
934
+ ...((_e2 = options.clientTools) == null ? void 0 : _e2.length) ? { client_tools: options.clientTools } : {},
935
+ ...options.extraRunConfig ?? {}
936
+ }
937
+ };
938
+ }
35
939
  const ATHENA_ENVIRONMENT_URLS = {
36
940
  production: {
37
941
  apiUrl: "https://iris.prd.athenaintel.com/api/chat",
@@ -235,7 +1139,7 @@ const normalizeOrigin = (value) => {
235
1139
  return null;
236
1140
  }
237
1141
  };
238
- const getTokenRefreshDelay = (expiresAt, nowMs) => {
1142
+ const getTokenRefreshDelay = (expiresAt, nowMs2) => {
239
1143
  if (typeof expiresAt !== "string") {
240
1144
  return DEFAULT_TOKEN_REFRESH_MS;
241
1145
  }
@@ -243,7 +1147,7 @@ const getTokenRefreshDelay = (expiresAt, nowMs) => {
243
1147
  if (!Number.isFinite(expiresAtMs)) {
244
1148
  return DEFAULT_TOKEN_REFRESH_MS;
245
1149
  }
246
- return Math.max(TOKEN_REFRESH_RETRY_BASE_MS, expiresAtMs - nowMs - TOKEN_REFRESH_BUFFER_MS);
1150
+ return Math.max(TOKEN_REFRESH_RETRY_BASE_MS, expiresAtMs - nowMs2 - TOKEN_REFRESH_BUFFER_MS);
247
1151
  };
248
1152
  const getAuthRetryDelay = (retryAttempt) => {
249
1153
  const safeAttempt = Number.isFinite(retryAttempt) ? Math.max(0, Math.floor(retryAttempt)) : 0;
@@ -277,6 +1181,15 @@ function useParentBridge({
277
1181
  const configReceived = useRef(false);
278
1182
  useEffect(() => {
279
1183
  if (!isInIframe) return;
1184
+ const endBridgeSpan = athenaDiagnostics.span("auth.bridge", "auth.bridge.start", {
1185
+ mode: "iframe"
1186
+ });
1187
+ let spanEnded = false;
1188
+ const endOnce = (name, options) => {
1189
+ if (spanEnded) return 0;
1190
+ spanEnded = true;
1191
+ return endBridgeSpan(name, options);
1192
+ };
280
1193
  const handler = (event) => {
281
1194
  if (!isTrustedOrigin({ origin: event.origin, trustedOrigins: runtimeTrustedOrigins })) {
282
1195
  return;
@@ -295,6 +1208,11 @@ function useParentBridge({
295
1208
  }));
296
1209
  }
297
1210
  if (event.data.type === "athena-auth" && typeof event.data.token === "string") {
1211
+ endOnce("auth.bridge.ready", { data: { mode: "iframe" } });
1212
+ athenaDiagnostics.emit("auth.token.acquired", {
1213
+ level: "debug",
1214
+ data: { source: "iframe-postmessage" }
1215
+ });
298
1216
  setState((prev) => ({
299
1217
  ...prev,
300
1218
  token: event.data.token,
@@ -308,6 +1226,13 @@ function useParentBridge({
308
1226
  readySignalSent.current = true;
309
1227
  }
310
1228
  const timer = setTimeout(() => {
1229
+ endOnce("auth.bridge.timeout", {
1230
+ data: {
1231
+ mode: "iframe",
1232
+ timeout_ms: BRIDGE_TIMEOUT_MS,
1233
+ config_received: configReceived.current
1234
+ }
1235
+ });
311
1236
  setState((prev) => prev.ready ? prev : { ...prev, ready: true });
312
1237
  }, BRIDGE_TIMEOUT_MS);
313
1238
  return () => {
@@ -360,9 +1285,20 @@ function useParentBridge({
360
1285
  }) => {
361
1286
  controller == null ? void 0 : controller.abort();
362
1287
  controller = new AbortController();
1288
+ const isInitial = markReadyOnFailure;
1289
+ const rawEndSpan = isInitial ? athenaDiagnostics.span("auth.bridge", "auth.bridge.start", { mode: "marathon" }) : null;
1290
+ let spanEnded = false;
1291
+ const endBridgeSpan = rawEndSpan ? (name, options) => {
1292
+ if (spanEnded) return 0;
1293
+ spanEnded = true;
1294
+ return rawEndSpan(name, options);
1295
+ } : null;
363
1296
  clearRequestTimer();
364
1297
  requestTimer = setTimeout(() => {
365
1298
  controller == null ? void 0 : controller.abort();
1299
+ endBridgeSpan == null ? void 0 : endBridgeSpan("auth.bridge.timeout", {
1300
+ data: { mode: "marathon", timeout_ms: BRIDGE_TIMEOUT_MS }
1301
+ });
366
1302
  if (markReadyOnFailure) {
367
1303
  markReady();
368
1304
  }
@@ -376,17 +1312,43 @@ function useParentBridge({
376
1312
  if (cancelled) return;
377
1313
  if (!resp.ok) {
378
1314
  if (resp.status === 404) {
1315
+ endBridgeSpan == null ? void 0 : endBridgeSpan("auth.bridge.absent", {
1316
+ data: { mode: "marathon", status: resp.status }
1317
+ });
379
1318
  markReady();
380
- } else if (markReadyOnFailure) {
381
- markReady();
382
- scheduleRetry();
383
1319
  } else {
1320
+ const failure = {
1321
+ level: "warn",
1322
+ data: { mode: "marathon", status: resp.status }
1323
+ };
1324
+ if (endBridgeSpan) {
1325
+ endBridgeSpan("auth.bridge.error", failure);
1326
+ } else {
1327
+ athenaDiagnostics.emit("auth.token.refresh_failed", failure);
1328
+ }
1329
+ if (markReadyOnFailure) {
1330
+ markReady();
1331
+ }
384
1332
  scheduleRetry();
385
1333
  }
386
1334
  return;
387
1335
  }
388
1336
  const data = await resp.json();
389
1337
  if (cancelled) return;
1338
+ if (endBridgeSpan) {
1339
+ endBridgeSpan("auth.bridge.ready", {
1340
+ data: { mode: "marathon", has_token: typeof data.token === "string" }
1341
+ });
1342
+ athenaDiagnostics.emit("auth.token.acquired", {
1343
+ level: "debug",
1344
+ data: { source: "marathon", expires_at: data.expires_at }
1345
+ });
1346
+ } else {
1347
+ athenaDiagnostics.emit("auth.token.refreshed", {
1348
+ level: "debug",
1349
+ data: { source: "marathon", expires_at: data.expires_at }
1350
+ });
1351
+ }
390
1352
  setState({
391
1353
  token: typeof data.token === "string" ? data.token : null,
392
1354
  apiUrl: typeof data.apiUrl === "string" ? data.apiUrl : null,
@@ -395,7 +1357,15 @@ function useParentBridge({
395
1357
  ready: true
396
1358
  });
397
1359
  scheduleRefresh(data.expires_at);
398
- } catch {
1360
+ } catch (error2) {
1361
+ if (!cancelled && !(error2 instanceof DOMException && error2.name === "AbortError")) {
1362
+ const failure = { level: "warn", data: { mode: "marathon" }, error: error2 };
1363
+ if (endBridgeSpan) {
1364
+ endBridgeSpan("auth.bridge.error", failure);
1365
+ } else {
1366
+ athenaDiagnostics.emit("auth.token.refresh_failed", failure);
1367
+ }
1368
+ }
399
1369
  if (markReadyOnFailure) {
400
1370
  markReady();
401
1371
  }
@@ -9841,24 +10811,42 @@ function getAthenaApiBaseUrl(backendUrl) {
9841
10811
  return stripped;
9842
10812
  }
9843
10813
  async function listThreads(backendUrl, auth, opts = {}) {
10814
+ var _a3;
9844
10815
  const base2 = getAthenaApiBaseUrl(backendUrl);
9845
- const res = await fetch(`${base2}/api/conversations/threads/list`, {
9846
- method: "POST",
9847
- headers: { "Content-Type": "application/json", ...getAuthHeaders(auth) },
9848
- body: JSON.stringify({
9849
- limit: opts.limit ?? 50,
9850
- offset: opts.offset ?? 0,
9851
- // Default to the full recent-conversations set unless a caller
9852
- // explicitly asks to hide triggered/background sessions.
9853
- exclude_triggered: opts.exclude_triggered ?? false,
9854
- ...opts.app_id ? { app_id: opts.app_id } : {},
9855
- ...opts.start_channel ? { start_channel: opts.start_channel } : {}
9856
- })
10816
+ const endSpan = athenaDiagnostics.span("threads.list", "threads.list.start", {
10817
+ auth_mode: getAuthMode(auth),
10818
+ app_id: opts.app_id
9857
10819
  });
9858
- if (!res.ok) {
9859
- throw new Error(`[AthenaSDK] Failed to list threads: ${res.status}`);
10820
+ try {
10821
+ const res = await fetch(`${base2}/api/conversations/threads/list`, {
10822
+ method: "POST",
10823
+ headers: { "Content-Type": "application/json", ...getAuthHeaders(auth) },
10824
+ body: JSON.stringify({
10825
+ limit: opts.limit ?? 50,
10826
+ offset: opts.offset ?? 0,
10827
+ // Default to the full recent-conversations set unless a caller
10828
+ // explicitly asks to hide triggered/background sessions.
10829
+ exclude_triggered: opts.exclude_triggered ?? false,
10830
+ ...opts.app_id ? { app_id: opts.app_id } : {},
10831
+ ...opts.start_channel ? { start_channel: opts.start_channel } : {}
10832
+ })
10833
+ });
10834
+ if (!res.ok) {
10835
+ throw new AthenaSdkError({
10836
+ code: res.status === 401 || res.status === 403 ? "auth_rejected" : "threads_list_failed",
10837
+ message: `Failed to list threads: ${res.status}`,
10838
+ status: res.status,
10839
+ hint: res.status === 401 || res.status === 403 ? "The credential was refused. Check the token/API key and that the user belongs to the workspace." : "Check backendUrl points at the Agora API base.",
10840
+ context: { auth_mode: getAuthMode(auth) }
10841
+ });
10842
+ }
10843
+ const data = await res.json();
10844
+ endSpan("threads.list.done", { data: { count: ((_a3 = data.threads) == null ? void 0 : _a3.length) ?? 0 } });
10845
+ return data;
10846
+ } catch (error2) {
10847
+ endSpan("threads.list.error", { error: error2 });
10848
+ throw error2;
9860
10849
  }
9861
- return res.json();
9862
10850
  }
9863
10851
  async function setThreadReadState(backendUrl, auth, opts) {
9864
10852
  const base2 = getAthenaApiBaseUrl(backendUrl);
@@ -9919,31 +10907,49 @@ function getResponseErrorBody(response) {
9919
10907
  return response.text().catch(() => "");
9920
10908
  }
9921
10909
  async function getThreadState(backendUrl, auth, threadId) {
10910
+ var _a3, _b2, _c2, _d2;
9922
10911
  const base2 = getAthenaApiBaseUrl(backendUrl);
9923
10912
  const authMode = getAuthMode(auth);
9924
10913
  const endpoint = `${base2}/api/conversations/threads/get`;
9925
- console.info("[AthenaSDK] Loading thread state from conversations API:", {
9926
- threadId,
9927
- endpoint,
9928
- authMode,
9929
- hasToken: Boolean(auth.token),
9930
- hasApiKey: Boolean(auth.apiKey)
9931
- });
9932
- const res = await fetch(endpoint, {
9933
- method: "POST",
9934
- headers: { "Content-Type": "application/json", ...getAuthHeaders(auth) },
9935
- body: JSON.stringify({
9936
- thread_id: threadId,
9937
- skip_cache: true
9938
- })
10914
+ const endSpan = athenaDiagnostics.span("threads.history", "threads.history.start", {
10915
+ thread_id: threadId,
10916
+ auth_mode: authMode
9939
10917
  });
10918
+ let res;
10919
+ try {
10920
+ res = await fetch(endpoint, {
10921
+ method: "POST",
10922
+ headers: { "Content-Type": "application/json", ...getAuthHeaders(auth) },
10923
+ body: JSON.stringify({
10924
+ thread_id: threadId,
10925
+ skip_cache: true
10926
+ })
10927
+ });
10928
+ } catch (error2) {
10929
+ endSpan("threads.history.error", { error: error2, data: { thread_id: threadId } });
10930
+ throw error2;
10931
+ }
9940
10932
  if (!res.ok) {
9941
10933
  const body = await getResponseErrorBody(res);
9942
- throw new Error(
9943
- `[AthenaSDK] Failed to get thread state: ${res.status} (${authMode})${body ? `: ${body.slice(0, 300)}` : ""}`
9944
- );
10934
+ const error2 = new AthenaSdkError({
10935
+ code: res.status === 401 || res.status === 403 ? "auth_rejected" : "thread_load_failed",
10936
+ message: `Failed to get thread state: ${res.status} (${authMode})${body ? `: ${body.slice(0, 300)}` : ""}`,
10937
+ status: res.status,
10938
+ hint: "A brand-new thread may not be persisted yet; anything else means the credential or backendUrl is wrong.",
10939
+ context: { thread_id: threadId, auth_mode: authMode }
10940
+ });
10941
+ endSpan("threads.history.error", { error: error2, data: { thread_id: threadId } });
10942
+ throw error2;
9945
10943
  }
9946
10944
  const data = await res.json();
10945
+ const channelMessages = (_b2 = (_a3 = data.thread) == null ? void 0 : _a3.channel_values) == null ? void 0 : _b2.messages;
10946
+ endSpan("threads.history.done", {
10947
+ data: {
10948
+ thread_id: threadId,
10949
+ found: data.thread_found !== false,
10950
+ message_count: Array.isArray(channelMessages) ? channelMessages.length : ((_d2 = (_c2 = data.thread) == null ? void 0 : _c2.messages) == null ? void 0 : _d2.length) ?? 0
10951
+ }
10952
+ });
9947
10953
  const thread = data.thread;
9948
10954
  if (data.thread_found === false || !thread) {
9949
10955
  return {
@@ -10225,17 +11231,35 @@ const useAthenaRuntime = (config2) => {
10225
11231
  };
10226
11232
  },
10227
11233
  onResponse: () => {
11234
+ athenaDiagnostics.emit("stream.connected", {
11235
+ level: "debug",
11236
+ data: { transport: "legacy", thread_id: threadIdRef.current }
11237
+ });
10228
11238
  if (IS_DEV) {
10229
11239
  console.log("[AthenaSDK] Stream connected");
10230
11240
  }
10231
11241
  },
10232
11242
  onFinish: () => {
11243
+ athenaDiagnostics.emit("run.done", {
11244
+ level: "debug",
11245
+ data: { transport: "legacy", thread_id: threadIdRef.current }
11246
+ });
10233
11247
  if (IS_DEV) {
10234
11248
  console.log("[AthenaSDK] Stream completed");
10235
11249
  }
10236
11250
  },
10237
11251
  onError: (error2, { commands: commands2, updateState }) => {
10238
11252
  var _a3;
11253
+ athenaDiagnostics.error(
11254
+ "stream.error",
11255
+ error2,
11256
+ {
11257
+ code: /\b401\b|unauthori[sz]ed/i.test(error2.message) ? "auth_rejected" : "stream_failed",
11258
+ message: error2.message || "The chat stream failed",
11259
+ hint: "Check the Iris apiUrl and the credential; the raw error is in `cause`."
11260
+ },
11261
+ { transport: "legacy", thread_id: threadIdRef.current }
11262
+ );
10239
11263
  const pendingCommands = commandsToMessages(commands2);
10240
11264
  const isInvalidStringLength = error2 instanceof RangeError && /Invalid string length/i.test(error2.message);
10241
11265
  const userErrorMessage = isInvalidStringLength ? "The response was too large to process. Try reducing the amount of content in a single request or starting a new chat." : error2.message;
@@ -10357,33 +11381,21 @@ const useAthenaRuntime = (config2) => {
10357
11381
  if (isExistingThread && !hasResumedRef.current) {
10358
11382
  hasResumedRef.current = true;
10359
11383
  (async () => {
10360
- var _a3, _b2;
11384
+ var _a3;
10361
11385
  const currentToken = getTokenRef.current ? await getTokenRef.current() ?? tokenRef.current : tokenRef.current;
10362
11386
  const auth = { apiKey: apiKeyRef.current, token: currentToken };
10363
- console.log("[AthenaSDK] Loading existing thread state:", {
10364
- threadId,
10365
- backendUrl
10366
- });
10367
11387
  try {
10368
11388
  const state = await getThreadState(backendUrl, auth, threadId);
10369
- const messageCount = ((_a3 = state == null ? void 0 : state.messages) == null ? void 0 : _a3.length) ?? 0;
10370
- console.log("[AthenaSDK] Got thread state:", {
10371
- threadId,
10372
- messageCount,
10373
- hasMessages: messageCount > 0
10374
- });
10375
11389
  runtime.thread.importExternalState({
10376
11390
  ...state
10377
11391
  });
10378
- console.log(
10379
- "[AthenaSDK] importExternalState completed, runtime messages:",
10380
- runtime.thread.getState().messages.length
10381
- );
10382
11392
  } catch (err) {
10383
- console.warn(
10384
- "[AthenaSDK] Failed to load thread state (may be a new streaming thread):",
10385
- err
10386
- );
11393
+ if (IS_DEV) {
11394
+ console.warn(
11395
+ "[AthenaSDK] Failed to load thread state (may be a new streaming thread):",
11396
+ err
11397
+ );
11398
+ }
10387
11399
  }
10388
11400
  try {
10389
11401
  const statusRes = await fetch(resolvedStatusApiUrl, {
@@ -10395,7 +11407,7 @@ const useAthenaRuntime = (config2) => {
10395
11407
  const status = await statusRes.json();
10396
11408
  if (status.isRunning) {
10397
11409
  try {
10398
- const lastMessageId = ((_b2 = runtime.thread.getState().messages.at(-1)) == null ? void 0 : _b2.id) ?? null;
11410
+ const lastMessageId = ((_a3 = runtime.thread.getState().messages.at(-1)) == null ? void 0 : _a3.id) ?? null;
10399
11411
  runtime.thread.resumeRun({ parentId: lastMessageId });
10400
11412
  } catch (resumeErr) {
10401
11413
  if (IS_DEV) {
@@ -10543,6 +11555,7 @@ function projectDeepAgentConnection(connection) {
10543
11555
  return {
10544
11556
  status: connection.status,
10545
11557
  cause: connection.cause,
11558
+ attempt: connection.attempt,
10546
11559
  ...message !== void 0 && { message }
10547
11560
  };
10548
11561
  }
@@ -10718,6 +11731,22 @@ function liftAopSourceIntoMetadata(message) {
10718
11731
  }
10719
11732
  };
10720
11733
  }
11734
+ function liftBranchIntoMetadata(message) {
11735
+ if (message.type !== "human" && message.type !== "ai") return message;
11736
+ const branch = message.branch;
11737
+ if (typeof branch !== "object" || branch === null || Array.isArray(branch)) return message;
11738
+ const kwargs = message.additional_kwargs;
11739
+ const existingMetadata = kwargs == null ? void 0 : kwargs.metadata;
11740
+ const metadata = typeof existingMetadata === "object" && existingMetadata !== null ? existingMetadata : {};
11741
+ if (typeof metadata.branch === "object" && metadata.branch !== null) return message;
11742
+ return {
11743
+ ...message,
11744
+ additional_kwargs: {
11745
+ ...kwargs,
11746
+ metadata: { ...metadata, branch }
11747
+ }
11748
+ };
11749
+ }
10721
11750
  const TOOL_MESSAGE_INTERNAL_KWARGS = /* @__PURE__ */ new Set([
10722
11751
  "reasoning",
10723
11752
  "tool_outputs",
@@ -10770,11 +11799,13 @@ function isConvertibleChatMessage(message) {
10770
11799
  }
10771
11800
  function sanitizeLangChainMessages(messages) {
10772
11801
  return messages.filter((message) => isConvertibleChatMessage(message) && !isMessageHiddenFromFrontend(message)).map(
10773
- (message) => liftToolMessageMetadataIntoArtifact(
10774
- liftAopSourceIntoMetadata(
10775
- liftCompactionBoundaryIntoMetadata(
10776
- liftConversationStatsIntoMetadata(
10777
- liftModelIntoMetadata(liftRunMarkerIntoMetadata(message))
11802
+ (message) => liftBranchIntoMetadata(
11803
+ liftToolMessageMetadataIntoArtifact(
11804
+ liftAopSourceIntoMetadata(
11805
+ liftCompactionBoundaryIntoMetadata(
11806
+ liftConversationStatsIntoMetadata(
11807
+ liftModelIntoMetadata(liftRunMarkerIntoMetadata(message))
11808
+ )
10778
11809
  )
10779
11810
  )
10780
11811
  )
@@ -10807,14 +11838,15 @@ function registerDeepAgentRunConfig(aui, getRunConfig) {
10807
11838
  })
10808
11839
  });
10809
11840
  }
10810
- function deepAgentThreadStatus(state) {
10811
- var _a3;
10812
- const runs = state == null ? void 0 : state.runs;
10813
- if (runs === void 0) return "loading";
10814
- return ((_a3 = runs[0]) == null ? void 0 : _a3.status) ?? "ready";
10815
- }
10816
11841
  function useDeepAgentThreadStatus() {
10817
- return useStatewireState(deepAgentThreadStatus);
11842
+ return useAuiState((s) => {
11843
+ var _a3;
11844
+ const status = (_a3 = s.thread.extras) == null ? void 0 : _a3.status;
11845
+ if (status === void 0) {
11846
+ throw new Error("useDeepAgentThreadStatus requires a statewire thread");
11847
+ }
11848
+ return status;
11849
+ });
10818
11850
  }
10819
11851
  function shouldNotifyRunningChange(previous, next) {
10820
11852
  if (previous === null) return next.isRunning;
@@ -11035,7 +12067,7 @@ function useDeepAgentThread({
11035
12067
  }
11036
12068
  const connection = projectDeepAgentConnection(meta.connection);
11037
12069
  const previous = lastConnectionRef.current;
11038
- if ((previous == null ? void 0 : previous.threadId) !== attachId || previous.connection.status !== connection.status || previous.connection.cause !== connection.cause || previous.connection.message !== connection.message) {
12070
+ if ((previous == null ? void 0 : previous.threadId) !== attachId || previous.connection.status !== connection.status || previous.connection.cause !== connection.cause || previous.connection.message !== connection.message || previous.connection.attempt !== connection.attempt) {
11039
12071
  const update = { threadId: attachId, connection };
11040
12072
  lastConnectionRef.current = update;
11041
12073
  queueMicrotask(() => {
@@ -11107,46 +12139,30 @@ function toJSONSchema(schema2) {
11107
12139
  if (isStandardSchema(schema2)) throw new Error("Could not convert schema to JSON Schema. The schema implements Standard Schema but does not support JSON Schema conversion. If you are using Zod, please upgrade to Zod v4 (npm install zod@latest). Alternatively, pass a plain JSON Schema object instead.");
11108
12140
  return schema2;
11109
12141
  }
11110
- function defaultToolFilter(_name, tool) {
11111
- return !tool.disabled && tool.type !== "backend" && (tool.type !== "frontend" || tool.execute !== void 0);
11112
- }
11113
- function toolHasUploadableParameters(tool) {
11114
- var _a3;
11115
- return tool.parameters !== void 0 && !((_a3 = tool.unstable_backendDefault) == null ? void 0 : _a3.parameters);
11116
- }
11117
- function toToolsJSONSchema(tools, options = {}) {
11118
- if (!tools) return {};
11119
- const filter = options.filter ?? defaultToolFilter;
11120
- return Object.fromEntries(Object.entries(tools).filter(([name, tool]) => filter(name, tool)).filter((entry) => toolHasUploadableParameters(entry[1])).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, tool]) => [name, {
11121
- ...tool.description && { description: tool.description },
11122
- parameters: toJSONSchema(tool.parameters),
11123
- ...tool.providerOptions && { providerOptions: tool.providerOptions }
11124
- }]));
11125
- }
11126
12142
  function hasCallableExecute(entry) {
11127
12143
  return !!entry && typeof entry === "object" && typeof entry.execute === "function";
11128
12144
  }
11129
12145
  function collectStatewireClientTools(toolkit) {
11130
12146
  const executable = Object.entries(toolkit).filter(([, entry]) => hasCallableExecute(entry));
11131
12147
  if (executable.length === 0) return [];
11132
- let schemas;
11133
- try {
11134
- schemas = toToolsJSONSchema(toolkit, {
11135
- filter: (name) => executable.some(([toolName]) => toolName === name)
11136
- });
11137
- } catch (error2) {
11138
- console.warn("[AthenaSDK] failed to convert frontend tool schemas for statewire:", error2);
11139
- return [];
11140
- }
11141
12148
  return executable.flatMap(([name, entry]) => {
11142
- const schema2 = schemas[name];
11143
- if (!schema2) return [];
12149
+ if (entry.parameters === void 0) return [];
12150
+ let parameters;
12151
+ try {
12152
+ parameters = toJSONSchema(entry.parameters);
12153
+ } catch (error2) {
12154
+ console.warn(
12155
+ `[AthenaSDK] failed to convert frontend tool schema for statewire (${name}):`,
12156
+ error2
12157
+ );
12158
+ return [];
12159
+ }
11144
12160
  const execute = entry.execute;
11145
12161
  return [
11146
12162
  {
11147
12163
  name,
11148
- description: schema2.description,
11149
- parameters: schema2.parameters ?? { type: "object" },
12164
+ description: entry.description,
12165
+ parameters,
11150
12166
  handler: async (args, { toolCallId }) => {
11151
12167
  const controller = new AbortController();
11152
12168
  const output = await execute(args, {
@@ -11170,39 +12186,6 @@ function statewireClientToolWireEntries(tools) {
11170
12186
  requires_write: false
11171
12187
  }));
11172
12188
  }
11173
- const DEEP_AGENT_RUNTIME_MARKER = "athena_deep_agent";
11174
- const STATEWIRE_START_CHANNEL = "web";
11175
- const STATEWIRE_RUN_LABEL = "Athena SDK";
11176
- const DEFAULT_STATEWIRE_MODEL = "claude-sonnet-5";
11177
- function buildStatewireRunConfig(options = {}) {
11178
- var _a3, _b2, _c2, _d2;
11179
- const model = options.model ?? DEFAULT_STATEWIRE_MODEL;
11180
- const enabledTools = Array.from(
11181
- /* @__PURE__ */ new Set([...options.tools ?? [], ...options.frontendToolIds ?? []])
11182
- );
11183
- const systemPrompt = ((_a3 = options.systemPrompt) == null ? void 0 : _a3.trim()) ?? "";
11184
- return {
11185
- custom: {
11186
- runtime: DEEP_AGENT_RUNTIME_MARKER,
11187
- start_channel: STATEWIRE_START_CHANNEL,
11188
- model,
11189
- enabled_tools: enabledTools,
11190
- panel_config: {
11191
- model,
11192
- enabled_tools: enabledTools,
11193
- system_prompt: systemPrompt,
11194
- run_label: STATEWIRE_RUN_LABEL
11195
- },
11196
- ...systemPrompt ? { system_prompt: systemPrompt } : {},
11197
- ...((_b2 = options.workbench) == null ? void 0 : _b2.length) ? { workbench: options.workbench } : {},
11198
- ...((_c2 = options.knowledgeBase) == null ? void 0 : _c2.length) ? { knowledge_base: options.knowledgeBase } : {},
11199
- ...options.customToolConfigs ? { custom_tool_configs: options.customToolConfigs } : {},
11200
- ...options.appId ? { app_id: options.appId } : {},
11201
- ...((_d2 = options.clientTools) == null ? void 0 : _d2.length) ? { client_tools: options.clientTools } : {},
11202
- ...options.extraRunConfig ?? {}
11203
- }
11204
- };
11205
- }
11206
12189
  const EMPTY_TOOLKIT = {};
11207
12190
  const EMPTY_TOOL_IDS = [];
11208
12191
  function useStatewireClientTools(frontendToolkit) {
@@ -11220,6 +12203,8 @@ function useAthenaStatewireRuntime(config2) {
11220
12203
  token,
11221
12204
  getToken,
11222
12205
  model,
12206
+ agent: agent2,
12207
+ channel,
11223
12208
  tools = EMPTY_TOOL_IDS,
11224
12209
  frontendToolIds = EMPTY_TOOL_IDS,
11225
12210
  frontendToolkit = EMPTY_TOOLKIT,
@@ -11247,6 +12232,28 @@ function useAthenaStatewireRuntime(config2) {
11247
12232
  const clientToolsRef = useRef(clientTools);
11248
12233
  clientToolsRef.current = clientTools;
11249
12234
  const [canPersistSession] = useState(() => typeof localStorage !== "undefined");
12235
+ useEffect(() => {
12236
+ if (agent2 && !parseCollabAgentRef(agent2)) {
12237
+ athenaDiagnostics.emit("sdk.config.warning", {
12238
+ level: "warn",
12239
+ data: {
12240
+ prop: "agent",
12241
+ value: agent2,
12242
+ reason: "the statewire transport always runs the Athena deep agent; only 'collab_agent:<asset_id>' refs apply. Use transport='legacy' for named agents."
12243
+ }
12244
+ });
12245
+ }
12246
+ }, [agent2]);
12247
+ const attachSpanRef = useRef(null);
12248
+ const attachThreadRef = useRef(null);
12249
+ if (attachThreadRef.current !== threadId) {
12250
+ attachThreadRef.current = threadId;
12251
+ attachSpanRef.current = athenaDiagnostics.span(
12252
+ `statewire.attach:${threadId}`,
12253
+ "statewire.attach.start",
12254
+ { thread_id: threadId, is_new_chat: isNewChat }
12255
+ );
12256
+ }
11250
12257
  const thread = useDeepAgentThread({
11251
12258
  threadId,
11252
12259
  baseUrl: syncUrl,
@@ -11276,11 +12283,47 @@ function useAthenaStatewireRuntime(config2) {
11276
12283
  }
11277
12284
  },
11278
12285
  capabilities: { edit: true, reload: true, continue: true },
11279
- onConnectionChange,
12286
+ onStateChange: () => {
12287
+ const endSpan = attachSpanRef.current;
12288
+ if (endSpan) {
12289
+ attachSpanRef.current = null;
12290
+ endSpan("statewire.snapshot", { data: { thread_id: threadId } });
12291
+ }
12292
+ },
12293
+ onConnectionChange: (connection) => {
12294
+ athenaDiagnostics.gauge("statewire.connection", (connection == null ? void 0 : connection.status) ?? null);
12295
+ if ((connection == null ? void 0 : connection.status) === "gone") {
12296
+ athenaDiagnostics.emit("statewire.connection", {
12297
+ level: "warn",
12298
+ data: { status: connection.status, message: connection.message }
12299
+ });
12300
+ }
12301
+ onConnectionChange == null ? void 0 : onConnectionChange(connection);
12302
+ },
11280
12303
  onRawConnectionChange,
11281
- onLegacyReadOnly,
12304
+ onLegacyReadOnly: (legacyReadOnly) => {
12305
+ if (legacyReadOnly) {
12306
+ athenaDiagnostics.emit("statewire.read_only", {
12307
+ level: "warn",
12308
+ data: { thread_id: threadId }
12309
+ });
12310
+ }
12311
+ onLegacyReadOnly == null ? void 0 : onLegacyReadOnly(legacyReadOnly);
12312
+ },
11282
12313
  onRunningChange,
11283
12314
  onError: (error2) => {
12315
+ if (!isStatewireChannelTeardown(error2)) {
12316
+ athenaDiagnostics.error(
12317
+ "statewire.error",
12318
+ error2,
12319
+ {
12320
+ code: "statewire_rejected",
12321
+ message: "The statewire host rejected a command",
12322
+ hint: "Inspect error.detail — agora rejections carry a structured {code, message}."
12323
+ },
12324
+ { thread_id: threadId }
12325
+ );
12326
+ }
11284
12327
  if (onErrorRef.current) {
11285
12328
  onErrorRef.current(error2);
11286
12329
  return;
@@ -11296,6 +12339,8 @@ function useAthenaStatewireRuntime(config2) {
11296
12339
  const aui = useAui({ thread, tools: auiTools });
11297
12340
  const runConfigInputsRef = useRef({
11298
12341
  model,
12342
+ agent: agent2,
12343
+ channel,
11299
12344
  tools,
11300
12345
  frontendToolIds,
11301
12346
  workbench,
@@ -11307,6 +12352,8 @@ function useAthenaStatewireRuntime(config2) {
11307
12352
  });
11308
12353
  runConfigInputsRef.current = {
11309
12354
  model,
12355
+ agent: agent2,
12356
+ channel,
11310
12357
  tools,
11311
12358
  frontendToolIds,
11312
12359
  workbench,
@@ -11354,7 +12401,9 @@ function athenaStatewireErrorNotice(error2) {
11354
12401
  return {
11355
12402
  kind: "command",
11356
12403
  title: "Message was not sent",
11357
- message: error2 instanceof Error && error2.message.length > 0 ? error2.message : "The chat runtime rejected the command. Please try again."
12404
+ // The server's own detail names the actionable reason; the Error message is
12405
+ // generic client-side text like `command rejected (500)`.
12406
+ message: readDetailMessage(rejection == null ? void 0 : rejection.detail) ?? (error2 instanceof Error && error2.message.length > 0 ? error2.message : "The chat runtime rejected the command. Please try again.")
11358
12407
  };
11359
12408
  }
11360
12409
  const AthenaStatewireLifecycleContext = createContext(null);
@@ -11382,6 +12431,20 @@ function StatewireClientToolBridge({
11382
12431
  const toolsRef = useRef(tools);
11383
12432
  toolsRef.current = tools;
11384
12433
  const pendingRequest = inputRequests == null ? void 0 : inputRequests.find(isPendingClientToolRequest);
12434
+ const ownedClaimsRef = useRef(/* @__PURE__ */ new Set());
12435
+ const activeRef = useRef(true);
12436
+ const releaseClaim = useCallback((claim) => {
12437
+ ownedClaimsRef.current.delete(claim);
12438
+ clientToolRequests.release(claim);
12439
+ }, []);
12440
+ useEffect(() => {
12441
+ activeRef.current = true;
12442
+ return () => {
12443
+ activeRef.current = false;
12444
+ for (const claim of ownedClaimsRef.current) clientToolRequests.release(claim);
12445
+ ownedClaimsRef.current.clear();
12446
+ };
12447
+ }, []);
11385
12448
  const liveRequestIdsRef = useRef(/* @__PURE__ */ new Set());
11386
12449
  liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));
11387
12450
  const executeRequest = useCallback(
@@ -11392,8 +12455,8 @@ function StatewireClientToolBridge({
11392
12455
  const registry2 = new Map(toolsRef.current.map((tool) => [tool.name, tool]));
11393
12456
  const results = {};
11394
12457
  for (const call of calls) {
11395
- if (!liveRequestIdsRef.current.has(request.id)) {
11396
- clientToolRequests.release(requestKey(threadId, request.id));
12458
+ if (!activeRef.current || !liveRequestIdsRef.current.has(request.id)) {
12459
+ releaseClaim(requestKey(threadId, request.id));
11397
12460
  return;
11398
12461
  }
11399
12462
  const tool = registry2.get(call.tool_name);
@@ -11415,8 +12478,8 @@ function StatewireClientToolBridge({
11415
12478
  results[call.interrupt_id] = clientToolErrorEnvelope(error2);
11416
12479
  }
11417
12480
  }
11418
- if (!liveRequestIdsRef.current.has(request.id)) {
11419
- clientToolRequests.release(requestKey(threadId, request.id));
12481
+ if (!activeRef.current || !liveRequestIdsRef.current.has(request.id)) {
12482
+ releaseClaim(requestKey(threadId, request.id));
11420
12483
  return;
11421
12484
  }
11422
12485
  try {
@@ -11426,16 +12489,19 @@ function StatewireClientToolBridge({
11426
12489
  requestId: request.id,
11427
12490
  response: { type: "resume", value: wireValue }
11428
12491
  });
12492
+ ownedClaimsRef.current.delete(requestKey(threadId, request.id));
11429
12493
  } catch (error2) {
11430
- clientToolRequests.release(requestKey(threadId, request.id));
12494
+ releaseClaim(requestKey(threadId, request.id));
11431
12495
  console.error("[AthenaSDK] failed to resume client tool results:", error2);
11432
12496
  }
11433
12497
  },
11434
- [sendCommand, threadId]
12498
+ [releaseClaim, sendCommand, threadId]
11435
12499
  );
11436
12500
  useEffect(() => {
11437
12501
  if (!pendingRequest) return;
11438
- if (!clientToolRequests.claim(requestKey(threadId, pendingRequest.id))) return;
12502
+ const claim = requestKey(threadId, pendingRequest.id);
12503
+ if (!clientToolRequests.claim(claim)) return;
12504
+ ownedClaimsRef.current.add(claim);
11439
12505
  void executeRequest(pendingRequest);
11440
12506
  }, [executeRequest, pendingRequest, threadId]);
11441
12507
  return null;
@@ -11450,6 +12516,9 @@ function resolveAthenaTransport({
11450
12516
  }) {
11451
12517
  return { transport: transport ?? DEFAULT_ATHENA_TRANSPORT, fallbackReason: null };
11452
12518
  }
12519
+ function allowsMidRunSend(transport) {
12520
+ return transport === ATHENA_TRANSPORTS.statewire;
12521
+ }
11453
12522
  var __defProp$i = Object.defineProperty;
11454
12523
  var __name$h = (target, value) => __defProp$i(target, "name", { value, configurable: true });
11455
12524
  function setRef$1(ref, value) {
@@ -16047,7 +17116,7 @@ function selectThreadListItemRemoteId(state) {
16047
17116
  return (_a3 = state.threadListItem) == null ? void 0 : _a3.remoteId;
16048
17117
  }
16049
17118
  function useAthenaAuiThreadRemoteId() {
16050
- return useAuiState(selectThreadListItemRemoteId);
17119
+ return useAuiState$1(selectThreadListItemRemoteId);
16051
17120
  }
16052
17121
  function useAthenaThreadId() {
16053
17122
  return useContext(AthenaThreadIdContext);
@@ -18785,16 +19854,19 @@ function StatewireThreadListState({
18785
19854
  initialThreadId,
18786
19855
  children
18787
19856
  }) {
19857
+ var _a3;
18788
19858
  const [active, setActive] = useState(
18789
19859
  () => initialThreadId ? { id: initialThreadId, isNew: false } : { id: mintThreadId(), isNew: true }
18790
19860
  );
18791
19861
  const tokenRef = useRef(token);
18792
19862
  tokenRef.current = token;
19863
+ const authContext = useContext(AthenaAuthContext);
19864
+ const principal = ((_a3 = authContext == null ? void 0 : authContext.user) == null ? void 0 : _a3.userId) ?? "";
18793
19865
  const hasAuth = !!(apiKey || token);
18794
19866
  const { data, isLoading, refetch } = useQuery({
18795
- // Keyed on the user identity surface, not the raw token — token rotation
18796
- // for the same session must not refetch the whole list.
18797
- queryKey: [THREADS_QUERY_KEY, backendUrl, appId ?? "", apiKey ?? "", hasAuth],
19867
+ queryKey: [THREADS_QUERY_KEY, backendUrl, appId ?? "", principal, hasAuth],
19868
+ // Never serve another principal's list while the new one loads.
19869
+ placeholderData: void 0,
18798
19870
  queryFn: async () => {
18799
19871
  const { threads } = await listThreads(
18800
19872
  backendUrl,
@@ -18812,6 +19884,7 @@ function StatewireThreadListState({
18812
19884
  void refetch();
18813
19885
  }, [refetch]);
18814
19886
  const selectThread = useCallback((threadId) => {
19887
+ if (!threadId) return;
18815
19888
  setActive(
18816
19889
  (current) => current.id === threadId ? current : { id: threadId, isNew: false }
18817
19890
  );
@@ -18819,6 +19892,12 @@ function StatewireThreadListState({
18819
19892
  const newThread = useCallback(() => {
18820
19893
  setActive({ id: mintThreadId(), isNew: true });
18821
19894
  }, []);
19895
+ const isPersisted = !!(data == null ? void 0 : data.some((thread) => thread.id === active.id));
19896
+ useEffect(() => {
19897
+ if (isPersisted) {
19898
+ setActive((current) => current.isNew ? { ...current, isNew: false } : current);
19899
+ }
19900
+ }, [isPersisted]);
18822
19901
  const value = useMemo(
18823
19902
  () => ({
18824
19903
  threads: data ?? [],
@@ -18860,7 +19939,7 @@ const TITLE_POLL_MAX_DURATION_MS = 6e4;
18860
19939
  function StatewireThreadTitlePoller() {
18861
19940
  var _a3;
18862
19941
  const list2 = useAthenaStatewireThreadList();
18863
- const hasMessages = useAuiState((s) => {
19942
+ const hasMessages = useAuiState$1((s) => {
18864
19943
  var _a4;
18865
19944
  return (((_a4 = s.optional.thread) == null ? void 0 : _a4.messages.length) ?? 0) > 0;
18866
19945
  });
@@ -18915,15 +19994,15 @@ function useActiveThreadStateHydration({
18915
19994
  }) {
18916
19995
  const aui = useAui();
18917
19996
  const hasThread = aui.thread.source !== null;
18918
- const threadId = useAuiState((s) => {
19997
+ const threadId = useAuiState$1((s) => {
18919
19998
  const item = s.optional.threadListItem;
18920
19999
  return item ? selectHydratableThreadId(item) : null;
18921
20000
  });
18922
- const messageCount = useAuiState((s) => {
20001
+ const messageCount = useAuiState$1((s) => {
18923
20002
  var _a3;
18924
20003
  return ((_a3 = s.optional.thread) == null ? void 0 : _a3.messages.length) ?? 0;
18925
20004
  });
18926
- const isRunning = useAuiState((s) => {
20005
+ const isRunning = useAuiState$1((s) => {
18927
20006
  var _a3;
18928
20007
  return ((_a3 = s.optional.thread) == null ? void 0 : _a3.isRunning) ?? false;
18929
20008
  });
@@ -18981,15 +20060,13 @@ const selectActiveThreadRemoteId = (state) => {
18981
20060
  };
18982
20061
  function useAthenaThreadManager() {
18983
20062
  const statewireList = useAthenaStatewireThreadList();
18984
- const statewireIsThreadLoading = useAuiState((s) => {
20063
+ const statewireIsThreadLoading = useAuiState$1((s) => {
18985
20064
  var _a3;
18986
20065
  return ((_a3 = s.optional.thread) == null ? void 0 : _a3.isLoading) ?? false;
18987
20066
  });
18988
20067
  const statewireManager = useMemo(() => {
18989
20068
  if (!statewireList) return null;
18990
20069
  return {
18991
- // A never-started local chat stays out of the URL, mirroring the
18992
- // legacy manager's local-placeholder handling.
18993
20070
  activeThreadId: statewireList.isNewChat ? null : statewireList.activeThreadId,
18994
20071
  isListLoading: statewireList.isLoading,
18995
20072
  isThreadLoading: statewireIsThreadLoading,
@@ -18999,15 +20076,15 @@ function useAthenaThreadManager() {
18999
20076
  }, [statewireList, statewireIsThreadLoading]);
19000
20077
  const aui = useAui();
19001
20078
  const hasThreads = aui.threads.source !== null;
19002
- const activeThreadId = useAuiState((s) => {
20079
+ const activeThreadId = useAuiState$1((s) => {
19003
20080
  const threads = s.optional.threads;
19004
20081
  return threads ? selectActiveThreadRemoteId(threads) : null;
19005
20082
  });
19006
- const isThreadLoading = useAuiState((s) => {
20083
+ const isThreadLoading = useAuiState$1((s) => {
19007
20084
  var _a3;
19008
20085
  return ((_a3 = s.optional.thread) == null ? void 0 : _a3.isLoading) ?? false;
19009
20086
  });
19010
- const isListLoading = useAuiState((s) => {
20087
+ const isListLoading = useAuiState$1((s) => {
19011
20088
  var _a3;
19012
20089
  return (_a3 = s.optional.threads) == null ? void 0 : _a3.isLoading;
19013
20090
  });
@@ -19039,17 +20116,17 @@ const POLL_DELAY_MS = 5e3;
19039
20116
  const POLL_INTERVAL_MS = 1e3;
19040
20117
  const POLL_MAX_DURATION_MS = 6e4;
19041
20118
  function useThreadTitlePolling(refresh) {
19042
- const threadKey = useAuiState(
20119
+ const threadKey = useAuiState$1(
19043
20120
  (s) => {
19044
20121
  var _a3, _b2;
19045
20122
  return ((_a3 = s.optional.threadListItem) == null ? void 0 : _a3.remoteId) ?? ((_b2 = s.optional.threadListItem) == null ? void 0 : _b2.id) ?? null;
19046
20123
  }
19047
20124
  );
19048
- const hasMessages = useAuiState((s) => {
20125
+ const hasMessages = useAuiState$1((s) => {
19049
20126
  var _a3;
19050
20127
  return (((_a3 = s.optional.thread) == null ? void 0 : _a3.messages.length) ?? 0) > 0;
19051
20128
  });
19052
- const currentTitle = useAuiState((s) => {
20129
+ const currentTitle = useAuiState$1((s) => {
19053
20130
  var _a3;
19054
20131
  return ((_a3 = s.optional.threadListItem) == null ? void 0 : _a3.title) ?? "";
19055
20132
  });
@@ -19271,452 +20348,6 @@ const themes = {
19271
20348
  radius: "0.625rem"
19272
20349
  }
19273
20350
  };
19274
- const DEFAULT_CAPTURE_GATE_CONFIG = {
19275
- globalMaxPerWindow: 50,
19276
- globalWindowMs: 1e4,
19277
- criticalReservePerWindow: 15,
19278
- defaultEventMaxPerWindow: 12,
19279
- defaultEventWindowMs: 6e4,
19280
- defaultDedupeWindowMs: 5e3,
19281
- flushIntervalMs: 3e4,
19282
- flushCoalesceThreshold: 20,
19283
- eventOverrides: {
19284
- memory_profile_sample: { maxPerWindow: 2, windowMs: 3e4, dedupeWindowMs: 15e3 },
19285
- long_task_detected: { maxPerWindow: 3, windowMs: 6e4, dedupeWindowMs: 1e4 },
19286
- collab_connection_status_changed: { maxPerWindow: 6, windowMs: 6e4 },
19287
- collab_first_remote_update: { maxPerWindow: 3, windowMs: 6e4 },
19288
- collab_first_local_update: { maxPerWindow: 3, windowMs: 6e4 },
19289
- collab_render_time_sync_fix: { maxPerWindow: 3, windowMs: 6e4 },
19290
- collab_visibility_recovery: { maxPerWindow: 4, windowMs: 6e4 },
19291
- langgraph_message_validation_error: {
19292
- maxPerWindow: 8,
19293
- windowMs: 6e4,
19294
- dedupeWindowMs: 15e3
19295
- },
19296
- langgraph_messages_validation_error: {
19297
- maxPerWindow: 5,
19298
- windowMs: 6e4,
19299
- dedupeWindowMs: 15e3
19300
- },
19301
- langgraph_interrupt_validation_error: {
19302
- maxPerWindow: 5,
19303
- windowMs: 6e4,
19304
- dedupeWindowMs: 15e3
19305
- },
19306
- langgraph_state_validation_error: {
19307
- maxPerWindow: 5,
19308
- windowMs: 6e4,
19309
- dedupeWindowMs: 15e3
19310
- },
19311
- graphql_error: { maxPerWindow: 12, windowMs: 6e4, dedupeWindowMs: 1e4 },
19312
- chat_error: { maxPerWindow: 8, windowMs: 6e4, dedupeWindowMs: 5e3 },
19313
- memory_critical_threshold: { maxPerWindow: 3, windowMs: 3e5 },
19314
- memory_warning_threshold: { maxPerWindow: 3, windowMs: 3e5 },
19315
- pptx_slide_changed: { maxPerWindow: 8, windowMs: 3e4 }
19316
- }
19317
- };
19318
- const CRITICAL_EVENT_PATTERNS = [
19319
- /(?:^|_)failed$/,
19320
- /(?:^|_)error(?:_|$)/,
19321
- /crash/,
19322
- /^oom_/,
19323
- /aw_snap/,
19324
- /chunk_load/,
19325
- /global_error/,
19326
- /\$exception$/,
19327
- /^404_error$/,
19328
- /^500_error$/,
19329
- /_boundary_/
19330
- ];
19331
- const BYPASS_OPTION_KEY = "__posthog_gate_bypass";
19332
- function isCriticalPosthogEvent(event) {
19333
- return CRITICAL_EVENT_PATTERNS.some((pattern) => pattern.test(event));
19334
- }
19335
- function shouldBypassCaptureGate(options) {
19336
- if (!options || typeof options !== "object") return false;
19337
- return options[BYPASS_OPTION_KEY] === true;
19338
- }
19339
- function withCaptureGateBypass(options) {
19340
- return {
19341
- ...options ?? {},
19342
- [BYPASS_OPTION_KEY]: true
19343
- };
19344
- }
19345
- function pruneWindow(window2, now, windowMs) {
19346
- const cutoff = now - windowMs;
19347
- while (window2.timestamps.length > 0 && window2.timestamps[0] < cutoff) {
19348
- window2.timestamps.shift();
19349
- }
19350
- }
19351
- function countInWindow(window2, now, windowMs) {
19352
- pruneWindow(window2, now, windowMs);
19353
- return window2.timestamps.length;
19354
- }
19355
- function recordInWindow(window2, now) {
19356
- window2.timestamps.push(now);
19357
- }
19358
- function stableStringify(value) {
19359
- if (value == null) return String(value);
19360
- if (typeof value !== "object") return String(value);
19361
- if (Array.isArray(value)) {
19362
- return `[${value.map((item) => stableStringify(item)).join(",")}]`;
19363
- }
19364
- const record2 = value;
19365
- const keys2 = Object.keys(record2).sort();
19366
- return `{${keys2.map((key) => `${key}:${stableStringify(record2[key])}`).join(",")}}`;
19367
- }
19368
- function fingerprintProperties(properties) {
19369
- if (!properties) return "";
19370
- const keys2 = [
19371
- "error",
19372
- "error_message",
19373
- "message",
19374
- "reason",
19375
- "status",
19376
- "code",
19377
- "asset_id",
19378
- "doc_id",
19379
- "thread_id",
19380
- "session_id",
19381
- "operation",
19382
- "path",
19383
- "url",
19384
- "chunk_identifier",
19385
- "validation_path"
19386
- ];
19387
- const subset = {};
19388
- for (const key of keys2) {
19389
- if (key in properties) {
19390
- subset[key] = properties[key];
19391
- }
19392
- }
19393
- return stableStringify(subset);
19394
- }
19395
- function buildCaptureFingerprint(event, properties) {
19396
- return `${event}|${fingerprintProperties(properties)}`;
19397
- }
19398
- function buildCoalescedCaptureProperties(payload) {
19399
- const windowMs = payload.lastAt - payload.firstAt;
19400
- return {
19401
- ...payload.properties,
19402
- coalesced: true,
19403
- coalesced_count: payload.coalescedCount,
19404
- coalesced_first_at: new Date(payload.firstAt).toISOString(),
19405
- coalesced_last_at: new Date(payload.lastAt).toISOString(),
19406
- coalesced_window_ms: windowMs,
19407
- coalesced_suppression_reason: payload.suppressionReason
19408
- };
19409
- }
19410
- class PosthogCaptureGate {
19411
- constructor(config2 = DEFAULT_CAPTURE_GATE_CONFIG) {
19412
- __publicField(this, "config");
19413
- __publicField(this, "globalWindow", { timestamps: [] });
19414
- __publicField(this, "eventWindows", /* @__PURE__ */ new Map());
19415
- __publicField(this, "activeDedupe", /* @__PURE__ */ new Map());
19416
- __publicField(this, "coalesceBuckets", /* @__PURE__ */ new Map());
19417
- __publicField(this, "emittedTotal", 0);
19418
- __publicField(this, "coalescedTotal", 0);
19419
- __publicField(this, "flushedCoalescedTotal", 0);
19420
- this.config = config2;
19421
- }
19422
- resetForTests() {
19423
- this.globalWindow.timestamps.length = 0;
19424
- this.eventWindows.clear();
19425
- this.activeDedupe.clear();
19426
- this.coalesceBuckets.clear();
19427
- this.emittedTotal = 0;
19428
- this.coalescedTotal = 0;
19429
- this.flushedCoalescedTotal = 0;
19430
- }
19431
- getSnapshot() {
19432
- const coalescedPendingByEvent = {};
19433
- let coalescedPending = 0;
19434
- for (const bucket of this.coalesceBuckets.values()) {
19435
- coalescedPending += bucket.count;
19436
- coalescedPendingByEvent[bucket.event] = (coalescedPendingByEvent[bucket.event] ?? 0) + bucket.count;
19437
- }
19438
- return {
19439
- coalescedPending,
19440
- coalescedPendingByEvent,
19441
- emittedTotal: this.emittedTotal,
19442
- coalescedTotal: this.coalescedTotal,
19443
- flushedCoalescedTotal: this.flushedCoalescedTotal
19444
- };
19445
- }
19446
- evaluateCapture(event, properties, options, now = Date.now()) {
19447
- if (shouldBypassCaptureGate(options)) {
19448
- return { action: "emit" };
19449
- }
19450
- const fingerprint = buildCaptureFingerprint(event, properties);
19451
- const bucketKey = fingerprint;
19452
- const override = this.config.eventOverrides[event];
19453
- const dedupeWindowMs = (override == null ? void 0 : override.dedupeWindowMs) ?? this.config.defaultDedupeWindowMs;
19454
- const lastDedupe = this.activeDedupe.get(event);
19455
- if (lastDedupe && lastDedupe.fingerprint === fingerprint && now - lastDedupe.at < dedupeWindowMs) {
19456
- return this.recordCoalesce(event, bucketKey, fingerprint, properties, "dedupe", now);
19457
- }
19458
- const critical = isCriticalPosthogEvent(event);
19459
- const globalCount = countInWindow(this.globalWindow, now, this.config.globalWindowMs);
19460
- const normalBudget = Math.max(
19461
- 0,
19462
- this.config.globalMaxPerWindow - this.config.criticalReservePerWindow
19463
- );
19464
- if (critical) {
19465
- if (globalCount >= this.config.globalMaxPerWindow) {
19466
- return this.recordCoalesce(event, bucketKey, fingerprint, properties, "global_budget", now);
19467
- }
19468
- } else if (globalCount >= normalBudget) {
19469
- return this.recordCoalesce(event, bucketKey, fingerprint, properties, "global_budget", now);
19470
- }
19471
- const eventWindow = this.eventWindows.get(event) ?? { timestamps: [] };
19472
- this.eventWindows.set(event, eventWindow);
19473
- const eventMax = (override == null ? void 0 : override.maxPerWindow) ?? this.config.defaultEventMaxPerWindow;
19474
- const eventWindowMs = (override == null ? void 0 : override.windowMs) ?? this.config.defaultEventWindowMs;
19475
- const eventCount = countInWindow(eventWindow, now, eventWindowMs);
19476
- if (eventCount >= eventMax) {
19477
- return this.recordCoalesce(event, bucketKey, fingerprint, properties, "event_budget", now);
19478
- }
19479
- recordInWindow(this.globalWindow, now);
19480
- recordInWindow(eventWindow, now);
19481
- this.activeDedupe.set(event, { fingerprint, bucketKey, at: now });
19482
- this.emittedTotal += 1;
19483
- return { action: "emit" };
19484
- }
19485
- /** Returns payloads ready to flush (does not mutate buckets until caller confirms). */
19486
- collectFlushCandidates(now = Date.now()) {
19487
- const payloads = [];
19488
- for (const bucket of this.coalesceBuckets.values()) {
19489
- const shouldFlushBySize = bucket.count >= this.config.flushCoalesceThreshold;
19490
- const shouldFlushByAge = now - bucket.firstAt >= this.config.flushIntervalMs;
19491
- if (!shouldFlushBySize && !shouldFlushByAge) {
19492
- continue;
19493
- }
19494
- payloads.push({
19495
- bucketKey: bucket.bucketKey,
19496
- event: bucket.event,
19497
- properties: bucket.sampleProperties,
19498
- coalescedCount: bucket.count,
19499
- firstAt: bucket.firstAt,
19500
- lastAt: bucket.lastAt,
19501
- suppressionReason: bucket.suppressionReason
19502
- });
19503
- }
19504
- return payloads;
19505
- }
19506
- /** Remove flushed bucket keys after successful emit. */
19507
- acknowledgeFlushed(payloads) {
19508
- for (const payload of payloads) {
19509
- this.coalesceBuckets.delete(payload.bucketKey);
19510
- this.flushedCoalescedTotal += payload.coalescedCount;
19511
- }
19512
- }
19513
- /** After coalescing, flush immediately if the bucket crossed the early threshold. */
19514
- takeBucketIfReady(bucketKey, now = Date.now()) {
19515
- const bucket = this.coalesceBuckets.get(bucketKey);
19516
- if (!bucket) return null;
19517
- const shouldFlushBySize = bucket.count >= this.config.flushCoalesceThreshold;
19518
- const shouldFlushByAge = now - bucket.firstAt >= this.config.flushIntervalMs;
19519
- if (!shouldFlushBySize && !shouldFlushByAge) {
19520
- return null;
19521
- }
19522
- this.coalesceBuckets.delete(bucketKey);
19523
- this.flushedCoalescedTotal += bucket.count;
19524
- return {
19525
- bucketKey: bucket.bucketKey,
19526
- event: bucket.event,
19527
- properties: bucket.sampleProperties,
19528
- coalescedCount: bucket.count,
19529
- firstAt: bucket.firstAt,
19530
- lastAt: bucket.lastAt,
19531
- suppressionReason: bucket.suppressionReason
19532
- };
19533
- }
19534
- /** Force-flush every pending bucket (e.g. page hide). */
19535
- collectAllPending() {
19536
- return [...this.coalesceBuckets.values()].map((bucket) => ({
19537
- bucketKey: bucket.bucketKey,
19538
- event: bucket.event,
19539
- properties: bucket.sampleProperties,
19540
- coalescedCount: bucket.count,
19541
- firstAt: bucket.firstAt,
19542
- lastAt: bucket.lastAt,
19543
- suppressionReason: bucket.suppressionReason
19544
- }));
19545
- }
19546
- recordCoalesce(event, bucketKey, fingerprint, properties, reason, now) {
19547
- const existing = this.coalesceBuckets.get(bucketKey);
19548
- if (existing) {
19549
- existing.count += 1;
19550
- existing.lastAt = now;
19551
- existing.sampleProperties = { ...existing.sampleProperties, ...properties ?? {} };
19552
- } else {
19553
- this.coalesceBuckets.set(bucketKey, {
19554
- event,
19555
- bucketKey,
19556
- fingerprint,
19557
- count: 1,
19558
- firstAt: now,
19559
- lastAt: now,
19560
- suppressionReason: reason,
19561
- sampleProperties: { ...properties ?? {} }
19562
- });
19563
- }
19564
- this.coalescedTotal += 1;
19565
- this.activeDedupe.set(event, { fingerprint, bucketKey, at: now });
19566
- return { action: "coalesce", reason, bucketKey };
19567
- }
19568
- }
19569
- const gate = new PosthogCaptureGate(DEFAULT_CAPTURE_GATE_CONFIG);
19570
- let wrappedClient = null;
19571
- let originalCaptureRef = null;
19572
- let flushTimer = null;
19573
- let lifecycleHooksInstalled = false;
19574
- function getPosthogCaptureGate() {
19575
- return gate;
19576
- }
19577
- function emitThroughOriginal(event, properties, options) {
19578
- if (!originalCaptureRef) return void 0;
19579
- return originalCaptureRef(event, properties, withCaptureGateBypass(options));
19580
- }
19581
- function flushCoalescedPayload(payload) {
19582
- emitThroughOriginal(payload.event, buildCoalescedCaptureProperties(payload));
19583
- }
19584
- function flushCoalescedCaptures(options) {
19585
- const payloads = (options == null ? void 0 : options.force) ? gate.collectAllPending() : gate.collectFlushCandidates();
19586
- if (payloads.length === 0) return;
19587
- for (const payload of payloads) {
19588
- flushCoalescedPayload(payload);
19589
- }
19590
- gate.acknowledgeFlushed(payloads);
19591
- }
19592
- function installLifecycleFlushHooks() {
19593
- if (lifecycleHooksInstalled || typeof window === "undefined") return;
19594
- lifecycleHooksInstalled = true;
19595
- const flushOnHide = () => {
19596
- flushCoalescedCaptures({ force: true });
19597
- };
19598
- window.addEventListener("pagehide", flushOnHide);
19599
- document.addEventListener("visibilitychange", () => {
19600
- if (document.visibilityState === "hidden") {
19601
- flushOnHide();
19602
- }
19603
- });
19604
- if (!flushTimer) {
19605
- flushTimer = setInterval(() => {
19606
- flushCoalescedCaptures();
19607
- }, DEFAULT_CAPTURE_GATE_CONFIG.flushIntervalMs);
19608
- }
19609
- }
19610
- function wrapPosthogClient(client) {
19611
- if (wrappedClient === client) {
19612
- return client;
19613
- }
19614
- originalCaptureRef = client.capture.bind(client);
19615
- const originalCaptureException = typeof client.captureException === "function" ? client.captureException.bind(client) : null;
19616
- installLifecycleFlushHooks();
19617
- client.capture = ((event, properties, options) => {
19618
- const outcome = gate.evaluateCapture(event, properties, options);
19619
- if (outcome.action === "coalesce") {
19620
- const readyPayload = gate.takeBucketIfReady(outcome.bucketKey);
19621
- if (readyPayload) {
19622
- flushCoalescedPayload(readyPayload);
19623
- }
19624
- return void 0;
19625
- }
19626
- return emitThroughOriginal(event, properties, options);
19627
- });
19628
- if (originalCaptureException) {
19629
- client.captureException = ((error2, additionalProperties) => {
19630
- const mergedProperties = {
19631
- ...additionalProperties ?? {},
19632
- $exception_message: error2 instanceof Error ? error2.message : String(error2),
19633
- $exception_type: error2 instanceof Error ? error2.name : typeof error2
19634
- };
19635
- const outcome = gate.evaluateCapture("$exception", mergedProperties);
19636
- if (outcome.action === "coalesce") {
19637
- const readyPayload = gate.takeBucketIfReady(outcome.bucketKey);
19638
- if (readyPayload) {
19639
- flushCoalescedPayload(readyPayload);
19640
- }
19641
- return void 0;
19642
- }
19643
- return originalCaptureException(error2, additionalProperties);
19644
- });
19645
- }
19646
- wrappedClient = client;
19647
- return client;
19648
- }
19649
- function capturePosthogEvent(client, event, properties, options) {
19650
- if (!client || typeof client.capture !== "function") return;
19651
- client.capture(event, properties, options);
19652
- }
19653
- function capturePosthogException(client, error2, properties, options) {
19654
- if (!client) return;
19655
- if (typeof client.captureException === "function") {
19656
- client.captureException(error2, properties);
19657
- return;
19658
- }
19659
- capturePosthogEvent(
19660
- client,
19661
- "$exception",
19662
- {
19663
- ...properties ?? {},
19664
- $exception_message: error2.message,
19665
- $exception_type: error2.name,
19666
- $exception_stack: error2.stack
19667
- },
19668
- options
19669
- );
19670
- }
19671
- let posthogInstance = null;
19672
- let initPromise = null;
19673
- const DEFAULT_HOST = "https://us.i.posthog.com";
19674
- async function initializePostHog(apiKey, host, debug) {
19675
- if (posthogInstance) return posthogInstance;
19676
- if (typeof window === "undefined") return null;
19677
- try {
19678
- const posthog = (await import("posthog-js")).default;
19679
- posthog.init(apiKey, {
19680
- api_host: host,
19681
- autocapture: true,
19682
- capture_pageview: false,
19683
- session_recording: {
19684
- recordCrossOriginIframes: true,
19685
- maskAllInputs: true
19686
- },
19687
- loaded: (ph) => {
19688
- wrapPosthogClient(ph);
19689
- if (debug) {
19690
- ph.debug(true);
19691
- }
19692
- }
19693
- });
19694
- wrapPosthogClient(posthog);
19695
- posthogInstance = posthog;
19696
- return posthog;
19697
- } catch {
19698
- initPromise = null;
19699
- return null;
19700
- }
19701
- }
19702
- function getPostHogInstance() {
19703
- return posthogInstance;
19704
- }
19705
- function PostHogProvider({
19706
- children,
19707
- config: config2
19708
- }) {
19709
- const apiKey = (config2 == null ? void 0 : config2.apiKey) ?? "";
19710
- const host = (config2 == null ? void 0 : config2.host) ?? DEFAULT_HOST;
19711
- const debug = (config2 == null ? void 0 : config2.debug) ?? false;
19712
- useEffect(() => {
19713
- if (!apiKey || typeof window === "undefined") return;
19714
- if (!initPromise) {
19715
- initPromise = initializePostHog(apiKey, host, debug);
19716
- }
19717
- }, [apiKey, host, debug]);
19718
- return /* @__PURE__ */ jsx(Fragment$1, { children });
19719
- }
19720
20351
  const resolveTokenOverride = ({
19721
20352
  config: config2,
19722
20353
  token
@@ -19819,9 +20450,16 @@ const initialStatewireLifecycle = {
19819
20450
  reconnect: null
19820
20451
  };
19821
20452
  function statewireLifecycleReducer(state, action) {
20453
+ var _a3, _b2;
19822
20454
  switch (action.type) {
19823
- case "connection":
19824
- return { ...state, connection: action.connection };
20455
+ case "connection": {
20456
+ const healthy = ((_a3 = action.connection) == null ? void 0 : _a3.status) === "live" || ((_b2 = action.connection) == null ? void 0 : _b2.status) === "idle";
20457
+ return {
20458
+ ...state,
20459
+ connection: action.connection,
20460
+ error: healthy ? null : state.error
20461
+ };
20462
+ }
19825
20463
  case "error":
19826
20464
  return { ...state, error: action.error };
19827
20465
  case "legacy-read-only":
@@ -19839,6 +20477,8 @@ function AthenaStatewireStandalone({
19839
20477
  token,
19840
20478
  getToken,
19841
20479
  model,
20480
+ agent: agent2,
20481
+ channel,
19842
20482
  tools,
19843
20483
  frontendToolIds,
19844
20484
  frontendTools,
@@ -19870,6 +20510,8 @@ function AthenaStatewireStandalone({
19870
20510
  token,
19871
20511
  getToken,
19872
20512
  model,
20513
+ agent: agent2,
20514
+ channel,
19873
20515
  tools,
19874
20516
  frontendToolIds,
19875
20517
  frontendToolkit: frontendTools,
@@ -20145,6 +20787,7 @@ function AthenaProvider({
20145
20787
  apiKey,
20146
20788
  token: tokenProp,
20147
20789
  agent: agent2,
20790
+ channel,
20148
20791
  model,
20149
20792
  tools = [],
20150
20793
  frontendTools = {},
@@ -20167,8 +20810,32 @@ function AthenaProvider({
20167
20810
  theme,
20168
20811
  linkClicks,
20169
20812
  citationLinks,
20170
- posthog: posthogProp
20813
+ posthog: posthogProp,
20814
+ debug,
20815
+ onDiagnostic,
20816
+ onError
20171
20817
  }) {
20818
+ const onDiagnosticRef = useRef(onDiagnostic);
20819
+ onDiagnosticRef.current = onDiagnostic;
20820
+ const onErrorRef = useRef(onError);
20821
+ onErrorRef.current = onError;
20822
+ useEffect(() => {
20823
+ installAthenaDiagnosticsGlobal();
20824
+ return athenaDiagnostics.addConsumer({
20825
+ onEvent: (event) => {
20826
+ var _a3;
20827
+ return (_a3 = onDiagnosticRef.current) == null ? void 0 : _a3.call(onDiagnosticRef, event);
20828
+ },
20829
+ onError: (error2, event) => {
20830
+ var _a3;
20831
+ return (_a3 = onErrorRef.current) == null ? void 0 : _a3.call(onErrorRef, error2, event);
20832
+ }
20833
+ });
20834
+ }, []);
20835
+ const debugKey = JSON.stringify(debugPropToDiagnosticsConfig(debug));
20836
+ useEffect(() => {
20837
+ athenaDiagnostics.configure(debugPropToDiagnosticsConfig(debug));
20838
+ }, [debugKey]);
20172
20839
  const frontendToolNames = useMemo(() => Object.keys(frontendTools), [frontendTools]);
20173
20840
  const effectiveFrontendTools = useMemo(
20174
20841
  () => disableAutoOpen ? frontendTools : { ...DEFAULT_AUTO_OPEN_TOOLS, ...frontendTools },
@@ -20187,16 +20854,39 @@ function AthenaProvider({
20187
20854
  const configuredAppUrl = (config2 == null ? void 0 : config2.appUrl) ?? appUrl;
20188
20855
  const configuredTransport = (config2 == null ? void 0 : config2.transport) ?? transport;
20189
20856
  const configuredStatewireSyncUrl = (config2 == null ? void 0 : config2.statewireSyncUrl) ?? statewireSyncUrl;
20857
+ const configuredGetToken = (config2 == null ? void 0 : config2.getToken) ?? getToken;
20858
+ const configuredExtraRunConfig = (config2 == null ? void 0 : config2.extraRunConfig) ?? extraRunConfig;
20190
20859
  const configuredTrustedParentOrigins = config2 == null ? void 0 : config2.trustedParentOrigins;
20191
20860
  const posthogConfig = (config2 == null ? void 0 : config2.posthog) ?? posthogProp;
20192
20861
  const { transport: effectiveTransport, fallbackReason: transportFallbackReason } = resolveAthenaTransport({
20193
20862
  transport: configuredTransport
20194
20863
  });
20195
20864
  useEffect(() => {
20865
+ athenaDiagnostics.gauge("sdk.transport", effectiveTransport);
20866
+ athenaDiagnostics.emit("sdk.transport", {
20867
+ level: "debug",
20868
+ data: { transport: effectiveTransport, thread_list: enableThreadList }
20869
+ });
20196
20870
  if (transportFallbackReason) {
20871
+ athenaDiagnostics.emit("sdk.config.warning", {
20872
+ level: "warn",
20873
+ data: { prop: "transport", reason: transportFallbackReason }
20874
+ });
20197
20875
  console.warn(`[AthenaSDK] ${transportFallbackReason}`);
20198
20876
  }
20199
- }, [transportFallbackReason]);
20877
+ }, [effectiveTransport, enableThreadList, transportFallbackReason]);
20878
+ useEffect(() => {
20879
+ if (channel && effectiveTransport !== "statewire") {
20880
+ athenaDiagnostics.emit("sdk.config.warning", {
20881
+ level: "warn",
20882
+ data: {
20883
+ prop: "channel",
20884
+ value: channel,
20885
+ reason: "the 'channel' prop requires transport='statewire'; the legacy transport ignores it."
20886
+ }
20887
+ });
20888
+ }
20889
+ }, [channel, effectiveTransport]);
20200
20890
  const bridge = useParentBridge({
20201
20891
  trustedOrigins: configuredTrustedParentOrigins
20202
20892
  });
@@ -20221,8 +20911,10 @@ function AthenaProvider({
20221
20911
  appUrl: effectiveAppUrl,
20222
20912
  apiKey: configuredApiKey,
20223
20913
  token: effectiveToken,
20224
- getToken,
20914
+ getToken: configuredGetToken,
20225
20915
  model,
20916
+ agent: agent2,
20917
+ channel,
20226
20918
  tools,
20227
20919
  frontendToolIds: frontendToolNames,
20228
20920
  frontendTools: effectiveFrontendTools,
@@ -20231,7 +20923,7 @@ function AthenaProvider({
20231
20923
  systemPrompt,
20232
20924
  customToolConfigs,
20233
20925
  appId,
20234
- extraRunConfig,
20926
+ extraRunConfig: configuredExtraRunConfig,
20235
20927
  linkClicks,
20236
20928
  citationLinks
20237
20929
  };
@@ -36878,7 +37570,7 @@ function requireUseSyncExternalStoreShim_development$1() {
36878
37570
  var useState2 = React$1.useState, useEffect2 = React$1.useEffect, useLayoutEffect3 = React$1.useLayoutEffect, useDebugValue2 = React$1.useDebugValue;
36879
37571
  var didWarnOld18Alpha = false;
36880
37572
  var didWarnUncachedGetSnapshot = false;
36881
- function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
37573
+ function useSyncExternalStore2(subscribe, getSnapshot, getServerSnapshot) {
36882
37574
  {
36883
37575
  if (!didWarnOld18Alpha) {
36884
37576
  if (React$1.startTransition !== void 0) {
@@ -36945,7 +37637,7 @@ function requireUseSyncExternalStoreShim_development$1() {
36945
37637
  }
36946
37638
  var canUseDOM2 = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
36947
37639
  var isServerEnvironment = !canUseDOM2;
36948
- var shim2 = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
37640
+ var shim2 = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore2;
36949
37641
  var useSyncExternalStore$2 = React$1.useSyncExternalStore !== void 0 ? React$1.useSyncExternalStore : shim2;
36950
37642
  useSyncExternalStoreShim_development$1.useSyncExternalStore = useSyncExternalStore$2;
36951
37643
  if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
@@ -37248,7 +37940,7 @@ function requireWithSelector_development$1() {
37248
37940
  return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
37249
37941
  }
37250
37942
  var objectIs = typeof Object.is === "function" ? Object.is : is;
37251
- var useSyncExternalStore = shim2.useSyncExternalStore;
37943
+ var useSyncExternalStore2 = shim2.useSyncExternalStore;
37252
37944
  var useRef2 = React$1.useRef, useEffect2 = React$1.useEffect, useMemo2 = React$1.useMemo, useDebugValue2 = React$1.useDebugValue;
37253
37945
  function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
37254
37946
  var instRef = useRef2(null);
@@ -37305,7 +37997,7 @@ function requireWithSelector_development$1() {
37305
37997
  };
37306
37998
  return [getSnapshotWithSelector, getServerSnapshotWithSelector];
37307
37999
  }, [getSnapshot, getServerSnapshot, selector, isEqual]), getSelection2 = _useMemo[0], getServerSelection = _useMemo[1];
37308
- var value = useSyncExternalStore(subscribe, getSelection2, getServerSelection);
38000
+ var value = useSyncExternalStore2(subscribe, getSelection2, getServerSelection);
37309
38001
  useEffect2(function() {
37310
38002
  inst.hasValue = true;
37311
38003
  inst.value = value;
@@ -37674,8 +38366,8 @@ function canReceiveRef(Component) {
37674
38366
  }
37675
38367
  function isReact19Plus() {
37676
38368
  try {
37677
- if (version$1) {
37678
- const majorVersion = parseInt(version$1.split(".")[0], 10);
38369
+ if (version$2) {
38370
+ const majorVersion = parseInt(version$2.split(".")[0], 10);
37679
38371
  return majorVersion >= 19;
37680
38372
  }
37681
38373
  } catch {
@@ -54354,7 +55046,7 @@ function requireWithSelector_production() {
54354
55046
  function is(x, y) {
54355
55047
  return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
54356
55048
  }
54357
- var objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue2 = React2.useDebugValue;
55049
+ var objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore2 = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue2 = React2.useDebugValue;
54358
55050
  withSelector_production.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
54359
55051
  var instRef = useRef2(null);
54360
55052
  if (null === instRef.current) {
@@ -54395,7 +55087,7 @@ function requireWithSelector_production() {
54395
55087
  },
54396
55088
  [getSnapshot, getServerSnapshot, selector, isEqual]
54397
55089
  );
54398
- var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
55090
+ var value = useSyncExternalStore2(subscribe, instRef[0], instRef[1]);
54399
55091
  useEffect2(
54400
55092
  function() {
54401
55093
  inst.hasValue = true;
@@ -54427,7 +55119,7 @@ function requireWithSelector_development() {
54427
55119
  return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
54428
55120
  }
54429
55121
  "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
54430
- var React2 = React__default, shim2 = requireShim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue2 = React2.useDebugValue;
55122
+ var React2 = React__default, shim2 = requireShim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore2 = shim2.useSyncExternalStore, useRef2 = React2.useRef, useEffect2 = React2.useEffect, useMemo2 = React2.useMemo, useDebugValue2 = React2.useDebugValue;
54431
55123
  withSelector_development.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
54432
55124
  var instRef = useRef2(null);
54433
55125
  if (null === instRef.current) {
@@ -54469,7 +55161,7 @@ function requireWithSelector_development() {
54469
55161
  },
54470
55162
  [getSnapshot, getServerSnapshot, selector, isEqual]
54471
55163
  );
54472
- var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
55164
+ var value = useSyncExternalStore2(subscribe, instRef[0], instRef[1]);
54473
55165
  useEffect2(
54474
55166
  function() {
54475
55167
  inst.hasValue = true;
@@ -55283,8 +55975,8 @@ const TiptapComposer = ({ tools = [], rootCategories }) => {
55283
55975
  quoteRef.current = quote;
55284
55976
  const isUploadingRef = useRef(isUploading);
55285
55977
  isUploadingRef.current = isUploading;
55286
- const isRunningThread = useAuiState((s) => s.thread.isRunning);
55287
- const isThreadRunning = transport === "statewire" ? false : isRunningThread;
55978
+ const isRunningThread = useAuiState$1((s) => s.thread.isRunning);
55979
+ const isThreadRunning = allowsMidRunSend(transport) ? false : isRunningThread;
55288
55980
  const isThreadRunningRef = useRef(isThreadRunning);
55289
55981
  isThreadRunningRef.current = isThreadRunning;
55290
55982
  const handleSubmit = useCallback(() => {
@@ -55306,10 +55998,8 @@ const TiptapComposer = ({ tools = [], rootCategories }) => {
55306
55998
  appUrl
55307
55999
  });
55308
56000
  if (fullMessage) {
55309
- aui.thread.append({
55310
- role: "user",
55311
- content: [{ type: "text", text: fullMessage }]
55312
- });
56001
+ aui.composer.setText(fullMessage);
56002
+ aui.composer.send();
55313
56003
  clearAttachments();
55314
56004
  clearQuote();
55315
56005
  }
@@ -55536,7 +56226,7 @@ function readInterruptMessage(value) {
55536
56226
  }
55537
56227
  const PENDING_RESUME_GRACE_MS = 15e3;
55538
56228
  const StatewireApprovalCard = () => {
55539
- const extras = useAuiState((s) => s.thread.extras);
56229
+ const extras = useAuiState$1((s) => s.thread.extras);
55540
56230
  if (!hasStatewireThreadExtras(extras)) return null;
55541
56231
  return /* @__PURE__ */ jsx(StatewireApprovalCardInner, {});
55542
56232
  };
@@ -55556,16 +56246,22 @@ const StatewireApprovalCardInner = () => {
55556
56246
  prevRequestIdRef.current = requestId;
55557
56247
  if (pending) setPending(false);
55558
56248
  }
55559
- const isRunning = useAuiState((s) => s.thread.isRunning);
56249
+ const isRunning = useAuiState$1((s) => s.thread.isRunning);
55560
56250
  const sawResumeRunRef = useRef(false);
55561
- if (pending && isRunning) {
55562
- sawResumeRunRef.current = true;
55563
- } else if (pending && sawResumeRunRef.current && !isRunning) {
55564
- sawResumeRunRef.current = false;
55565
- setPending(false);
55566
- } else if (!pending) {
55567
- sawResumeRunRef.current = false;
55568
- }
56251
+ useEffect(() => {
56252
+ if (!pending) {
56253
+ sawResumeRunRef.current = false;
56254
+ return;
56255
+ }
56256
+ if (isRunning) {
56257
+ sawResumeRunRef.current = true;
56258
+ return;
56259
+ }
56260
+ if (sawResumeRunRef.current) {
56261
+ sawResumeRunRef.current = false;
56262
+ setPending(false);
56263
+ }
56264
+ }, [pending, isRunning]);
55569
56265
  useEffect(() => {
55570
56266
  if (!pending) return;
55571
56267
  const timer = setTimeout(() => {
@@ -55672,7 +56368,7 @@ function queueItemText(parts) {
55672
56368
  ).join("\n\n");
55673
56369
  }
55674
56370
  const StatewireQueuedMessages = () => {
55675
- const extras = useAuiState((s) => s.thread.extras);
56371
+ const extras = useAuiState$1((s) => s.thread.extras);
55676
56372
  if (!hasStatewireThreadExtras(extras)) return null;
55677
56373
  return /* @__PURE__ */ jsx(StatewireQueuedMessagesInner, {});
55678
56374
  };
@@ -55856,7 +56552,7 @@ const StatewireLegacyReadOnlyBanner = () => {
55856
56552
  /* @__PURE__ */ jsx(Archive, { className: "mt-0.5 size-4 shrink-0" }),
55857
56553
  /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
55858
56554
  /* @__PURE__ */ jsx("p", { className: "font-semibold text-xs", children: "Read-only conversation" }),
55859
- /* @__PURE__ */ jsx("p", { className: "pt-0.5 text-xs leading-snug text-amber-800", children: "Its history remains available, but new messages cannot be added. Start a new chat to continue." })
56555
+ /* @__PURE__ */ jsx("p", { className: "pt-0.5 text-xs leading-snug text-amber-800", children: "This conversation’s history remains available, but new messages cannot be added. Start a new chat to continue." })
55860
56556
  ] })
55861
56557
  ] });
55862
56558
  };
@@ -59836,13 +60532,13 @@ const TOOLKIT_THEMES = {
59836
60532
  };
59837
60533
  const DEFAULT_THEME = { color: "#919EAB" };
59838
60534
  const CollapsibleGroup = ({ groupKey, indices, children }) => {
59839
- const isMessageRunning = useAuiState((s) => {
60535
+ const isMessageRunning = useAuiState$1((s) => {
59840
60536
  var _a3;
59841
60537
  return ((_a3 = s.message.status) == null ? void 0 : _a3.type) === "running";
59842
60538
  });
59843
60539
  const [userOpened, setOpen] = useState();
59844
60540
  const open = userOpened ?? isMessageRunning;
59845
- const toolCallCount = useAuiState((s) => {
60541
+ const toolCallCount = useAuiState$1((s) => {
59846
60542
  if (s.message.role !== "assistant") return 0;
59847
60543
  const parts = s.message.content;
59848
60544
  if (!parts) return 0;
@@ -60115,8 +60811,8 @@ function PulsingDots() {
60115
60811
  const SuperGroupingFinalText = memo(function SuperGroupingFinalText2({
60116
60812
  TextComponent
60117
60813
  }) {
60118
- const messageContent = useAuiState((s) => s.message.content);
60119
- const isRunning = useAuiState((s) => {
60814
+ const messageContent = useAuiState$1((s) => s.message.content);
60815
+ const isRunning = useAuiState$1((s) => {
60120
60816
  var _a3;
60121
60817
  return ((_a3 = s.message.status) == null ? void 0 : _a3.type) === "running";
60122
60818
  });
@@ -60146,7 +60842,7 @@ const SuperGroupingCard = memo(function SuperGroupingCard2({
60146
60842
  ReasoningComponent,
60147
60843
  getToolGroupKey = defaultGetToolGroupKey
60148
60844
  }) {
60149
- const messageId = useAuiState((s) => s.message.id);
60845
+ const messageId = useAuiState$1((s) => s.message.id);
60150
60846
  const [showDetails, setShowDetails] = useState(() => expandedMessageIds.has(messageId));
60151
60847
  const handleToggleDetails = useCallback(() => {
60152
60848
  setShowDetails((prev) => {
@@ -60171,7 +60867,7 @@ const SuperGroupingCard = memo(function SuperGroupingCard2({
60171
60867
  expandedMessageIds.delete(messageId);
60172
60868
  };
60173
60869
  }, [messageId, showDetails]);
60174
- const messageStatus = useAuiState((s) => {
60870
+ const messageStatus = useAuiState$1((s) => {
60175
60871
  var _a3;
60176
60872
  return (_a3 = s.message.status) == null ? void 0 : _a3.type;
60177
60873
  });
@@ -60191,7 +60887,7 @@ const SuperGroupingCard = memo(function SuperGroupingCard2({
60191
60887
  })).filter((g) => g.indices.length > 0);
60192
60888
  };
60193
60889
  }, [getToolGroupKey]);
60194
- const messageContent = useAuiState((s) => s.message.content);
60890
+ const messageContent = useAuiState$1((s) => s.message.content);
60195
60891
  const toolStatuses = useMemo(() => {
60196
60892
  if (!messageContent) return EMPTY_STATUSES;
60197
60893
  const statuses = [];
@@ -61070,7 +61766,7 @@ const useScrollToTop = () => {
61070
61766
  };
61071
61767
  const ThreadScrollToTop = () => {
61072
61768
  const { isAtTop, containerRef, handleClick: handleClick2 } = useScrollToTop();
61073
- const isEmpty3 = useAuiState((s) => s.thread.isEmpty);
61769
+ const isEmpty3 = useAuiState$1((s) => s.thread.isEmpty);
61074
61770
  if (isEmpty3) return null;
61075
61771
  return /* @__PURE__ */ jsx("div", { className: "sticky top-0 z-10 mx-auto flex h-0 w-full max-w-(--thread-max-width) justify-center", children: /* @__PURE__ */ jsx(
61076
61772
  TooltipIconButton,
@@ -61095,7 +61791,7 @@ const ThreadScrollToBottom = () => /* @__PURE__ */ jsx(ThreadPrimitive.ScrollToB
61095
61791
  ) });
61096
61792
  const ComposerAction = () => {
61097
61793
  const { transport } = useAthenaConfig();
61098
- const queuesWhileRunning = transport === "statewire";
61794
+ const queuesWhileRunning = allowsMidRunSend(transport);
61099
61795
  return /* @__PURE__ */ jsxs("div", { className: "aui-composer-action-wrapper relative mx-2 mb-2 flex items-center justify-between", children: [
61100
61796
  /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(FileUploadButton, {}) }),
61101
61797
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
@@ -61121,8 +61817,8 @@ const ComposerSendWithQuote = () => {
61121
61817
  const { attachments, clearAttachments, isUploading } = useAttachments();
61122
61818
  const editorRef = useComposerEditorRef();
61123
61819
  const editorEmpty = useComposerEditorEmpty();
61124
- const isRunningThread = useAuiState((s) => s.thread.isRunning);
61125
- const isThreadRunning = transport === "statewire" ? false : isRunningThread;
61820
+ const isRunningThread = useAuiState$1((s) => s.thread.isRunning);
61821
+ const isThreadRunning = allowsMidRunSend(transport) ? false : isRunningThread;
61126
61822
  const hasExtras = !!quote || attachments.length > 0;
61127
61823
  const handleSend = useCallback(() => {
61128
61824
  var _a3;
@@ -61138,10 +61834,8 @@ const ComposerSendWithQuote = () => {
61138
61834
  appUrl
61139
61835
  });
61140
61836
  if (!fullMessage) return;
61141
- aui.thread.append({
61142
- role: "user",
61143
- content: [{ type: "text", text: fullMessage }]
61144
- });
61837
+ aui.composer.setText(fullMessage);
61838
+ aui.composer.send();
61145
61839
  clearQuote();
61146
61840
  clearAttachments();
61147
61841
  } else {
@@ -61187,8 +61881,8 @@ const AthenaAssistantMessageEmpty = ({ status }) => {
61187
61881
  const AthenaMessageEmptyIndicator = ({
61188
61882
  EmptyComponent: EmptyComponent2
61189
61883
  }) => {
61190
- const hasParts = useAuiState((s) => s.message.parts.length > 0);
61191
- const isRunning = useAuiState((s) => {
61884
+ const hasParts = useAuiState$1((s) => s.message.parts.length > 0);
61885
+ const isRunning = useAuiState$1((s) => {
61192
61886
  var _a3;
61193
61887
  return ((_a3 = s.message.status) == null ? void 0 : _a3.type) === "running";
61194
61888
  });
@@ -61202,11 +61896,11 @@ const AthenaReasoningPart = ({
61202
61896
  }) => {
61203
61897
  const inheritedTextComponent = useContext(AthenaReasoningTextComponentContext);
61204
61898
  const EffectiveTextComponent = TextComponent ?? inheritedTextComponent ?? TiptapText;
61205
- const isMessageRunning = useAuiState((state) => {
61899
+ const isMessageRunning = useAuiState$1((state) => {
61206
61900
  var _a3;
61207
61901
  return ((_a3 = state.message.status) == null ? void 0 : _a3.type) === "running";
61208
61902
  });
61209
- const reasoningTokens = useAuiState(
61903
+ const reasoningTokens = useAuiState$1(
61210
61904
  (state) => getReasoningTokensFromMetadata(state.message.metadata)
61211
61905
  );
61212
61906
  const isRunning = isMessageRunning || (status == null ? void 0 : status.type) === "running";
@@ -62378,6 +63072,8 @@ function useComposerAttachment() {
62378
63072
  return { addFile, addContent, clear };
62379
63073
  }
62380
63074
  export {
63075
+ ATHENA_REACT_SDK_VERSION,
63076
+ ATHENA_SDK_ERROR_CODES,
62381
63077
  ATHENA_TRANSPORTS,
62382
63078
  AppendDocumentToolUI,
62383
63079
  AssetPanel,
@@ -62388,10 +63084,12 @@ export {
62388
63084
  AthenaLayout,
62389
63085
  AthenaProvider,
62390
63086
  AthenaReasoningPart,
63087
+ AthenaSdkError,
62391
63088
  AthenaThreadIdContext,
62392
63089
  AthenaUserMessage,
62393
63090
  BrowseToolUI,
62394
63091
  Button,
63092
+ COLLAB_AGENT_REF_PREFIX,
62395
63093
  Collapsible,
62396
63094
  CollapsibleContent,
62397
63095
  CollapsibleTrigger,
@@ -62448,8 +63146,10 @@ export {
62448
63146
  TooltipTrigger,
62449
63147
  UpdateSheetRangeToolUI,
62450
63148
  WebSearchToolUI,
63149
+ allowsMidRunSend,
62451
63150
  archiveThread,
62452
63151
  asHitlApproval,
63152
+ athenaDiagnostics,
62453
63153
  athenaStatewireErrorNotice,
62454
63154
  autoCloseInFlightSubgraphMessages,
62455
63155
  buildCoalescedCaptureProperties,
@@ -62473,13 +63173,17 @@ export {
62473
63173
  getPosthogCaptureGate,
62474
63174
  getThreadState,
62475
63175
  hasStatewireThreadExtras,
63176
+ installAthenaDiagnosticsGlobal,
62476
63177
  isAthenaCitationUrl,
63178
+ isAthenaSdkError,
62477
63179
  isCriticalPosthogEvent,
62478
63180
  isPendingInterrupt,
62479
63181
  listThreads,
62480
63182
  normalizeResult,
62481
63183
  parseAthenaCitationLink,
63184
+ parseCollabAgentRef,
62482
63185
  readInterruptMessage,
63186
+ readRejectionDetail,
62483
63187
  resetAssetAutoOpen,
62484
63188
  resolveAthenaTransport,
62485
63189
  resolveStatewireSyncUrl,
@@ -62487,6 +63191,7 @@ export {
62487
63191
  statewireClientToolWireEntries,
62488
63192
  themeToStyleVars,
62489
63193
  themes,
63194
+ toAthenaSdkError,
62490
63195
  truncate,
62491
63196
  tryParseJson$2 as tryParseJson,
62492
63197
  useAppendToComposer,
@@ -62494,6 +63199,7 @@ export {
62494
63199
  useAssetPanelStore,
62495
63200
  useAthenaCitationLinkHandler,
62496
63201
  useAthenaConfig,
63202
+ useAthenaDiagnostics,
62497
63203
  useAthenaLinkClickHandler,
62498
63204
  useAthenaRuntime,
62499
63205
  useAthenaStatewireLifecycle,