@guideai/react-native 0.3.0 → 0.7.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.
@@ -1,4 +1,28 @@
1
- import { useContext, createContext } from "react";
1
+ import { useContext, createContext, useSyncExternalStore, useState, useEffect, useCallback, useRef, useMemo } from "react";
2
+ const DRAWING_URL = /^https:\/\/res\.cloudinary\.com\/[\w-]+\/image\/upload\//;
3
+ const IMAGE_BLOCK = /```image[ \t]*\n([\s\S]*?)```/g;
4
+ function headlessImages(text) {
5
+ const images = [];
6
+ const out = (text || "").replace(IMAGE_BLOCK, (_block, raw) => {
7
+ let data;
8
+ try {
9
+ data = JSON.parse(raw.trim());
10
+ } catch {
11
+ return "";
12
+ }
13
+ if (typeof data.url !== "string" || !DRAWING_URL.test(data.url)) return "";
14
+ const image = {
15
+ url: data.url,
16
+ svg: typeof data.svg === "string" && DRAWING_URL.test(data.svg) ? data.svg : null,
17
+ alt: typeof data.alt === "string" ? data.alt.slice(0, 200) : "",
18
+ width: Math.round(Number(data.width)) || 1600,
19
+ height: Math.round(Number(data.height)) || 900
20
+ };
21
+ images.push(image);
22
+ return `![${image.alt.replace(/[[\]]/g, "")}](${image.url})`;
23
+ });
24
+ return { text: out, images };
25
+ }
2
26
  const NAME_PREFIXES = [
3
27
  /^api[\s_-]*v?\d*[\s_-]*/i,
4
28
  /^(get|fetch|list|read|retrieve|show|query|search|find|lookup|look up)[\s_-]+/i,
@@ -434,9 +458,9 @@ class ConversationMemory {
434
458
  * @param store Where history lives. Defaults to memory so core never
435
459
  * reaches for a global; the web SDK passes its localStorage adapter.
436
460
  */
437
- constructor(siteId, ttlMs, maxMessages, store = new MemoryKVStore()) {
461
+ constructor(siteId, ttlMs, maxMessages, store2 = new MemoryKVStore()) {
438
462
  this.listener = null;
439
- this.store = store;
463
+ this.store = store2;
440
464
  this.storageKey = `guideai_chat_${siteId}`;
441
465
  this.ttlMs = ttlMs != null ? ttlMs : DEFAULT_TTL_MS;
442
466
  this.maxMessages = maxMessages != null ? maxMessages : DEFAULT_MAX_MESSAGES;
@@ -532,16 +556,16 @@ class ConversationMemory {
532
556
  }
533
557
  if (Array.isArray(cleaned)) {
534
558
  const total = cleaned.length;
535
- const pickFields = (item) => {
536
- if (typeof item === "object" && item !== null) {
537
- const obj = item;
559
+ const pickFields = (item2) => {
560
+ if (typeof item2 === "object" && item2 !== null) {
561
+ const obj = item2;
538
562
  const picked = {};
539
563
  for (const key of ["name", "id", "title", "path", "endpoint", "url", "type", "method", "label", "slug", "status"]) {
540
564
  if (key in obj) picked[key] = obj[key];
541
565
  }
542
566
  return Object.keys(picked).length > 0 ? picked : Object.keys(obj).slice(0, 4).reduce((acc, k) => ({ ...acc, [k]: obj[k] }), {});
543
567
  }
544
- return item;
568
+ return item2;
545
569
  };
546
570
  const compactItems = cleaned.map(pickFields);
547
571
  let itemsToShow = compactItems;
@@ -576,7 +600,7 @@ class ConversationMemory {
576
600
  _stripSensitiveFields(data, depth = 0) {
577
601
  if (depth > 5) return data;
578
602
  if (Array.isArray(data)) {
579
- return data.slice(0, 50).map((item) => this._stripSensitiveFields(item, depth + 1));
603
+ return data.slice(0, 50).map((item2) => this._stripSensitiveFields(item2, depth + 1));
580
604
  }
581
605
  if (typeof data === "object" && data !== null) {
582
606
  const result = {};
@@ -781,9 +805,9 @@ class ToolExecutor {
781
805
  var _a, _b, _c, _d, _e;
782
806
  if (typeof entry === "string") return entry.trim() || null;
783
807
  if (!entry || typeof entry !== "object") return null;
784
- const item = entry;
785
- const message = (_c = (_b = (_a = item.msg) != null ? _a : item.message) != null ? _b : item.error) != null ? _c : item.detail;
786
- const location = Array.isArray(item.loc) ? item.loc.filter((part) => part !== "body").join(".") : (_e = (_d = item.field) != null ? _d : item.param) != null ? _e : item.name;
808
+ const item2 = entry;
809
+ const message = (_c = (_b = (_a = item2.msg) != null ? _a : item2.message) != null ? _b : item2.error) != null ? _c : item2.detail;
810
+ const location = Array.isArray(item2.loc) ? item2.loc.filter((part) => part !== "body").join(".") : (_e = (_d = item2.field) != null ? _d : item2.param) != null ? _e : item2.name;
787
811
  if (!message) return location ? `${location}: invalid` : null;
788
812
  return location ? `${location}: ${message}` : String(message);
789
813
  }
@@ -2349,8 +2373,8 @@ class RNHttpTransport {
2349
2373
  }
2350
2374
  }
2351
2375
  class NativeKVStore {
2352
- constructor(store) {
2353
- this.store = store;
2376
+ constructor(store2) {
2377
+ this.store = store2;
2354
2378
  }
2355
2379
  getItem(key) {
2356
2380
  var _a;
@@ -2539,8 +2563,8 @@ class ScreenRegistry {
2539
2563
  }
2540
2564
  };
2541
2565
  }
2542
- get(id) {
2543
- return this.elements.get(id);
2566
+ get(id2) {
2567
+ return this.elements.get(id2);
2544
2568
  }
2545
2569
  /** Resolve by id first, then by visible label — the model may send either. */
2546
2570
  find(request) {
@@ -3006,6 +3030,44 @@ class RNApiClient {
3006
3030
  }
3007
3031
  return parsed;
3008
3032
  }
3033
+ /**
3034
+ * POST JSON and read the answer as bytes: a spoken line. XHR, because
3035
+ * React Native's fetch has no reliable binary body.
3036
+ */
3037
+ async postForAudio(path, body, timeoutMs) {
3038
+ const headers = this.headers();
3039
+ if (this.options.requestOrigin) headers[REQUEST_ORIGIN_HEADER] = this.options.requestOrigin;
3040
+ const request = new Promise((resolve, reject) => {
3041
+ const xhr = new XMLHttpRequest();
3042
+ xhr.open("POST", this.url(path));
3043
+ xhr.responseType = "arraybuffer";
3044
+ for (const [name, value] of Object.entries(headers)) xhr.setRequestHeader(name, value);
3045
+ xhr.onreadystatechange = () => {
3046
+ var _a;
3047
+ if (xhr.readyState === 4) {
3048
+ resolve({
3049
+ status: xhr.status,
3050
+ data: xhr.response,
3051
+ type: (_a = xhr.getResponseHeader("content-type")) != null ? _a : "",
3052
+ rate: xhr.getResponseHeader("x-audio-sample-rate")
3053
+ });
3054
+ }
3055
+ };
3056
+ xhr.onerror = () => reject(new Error(`Network error for ${path}`));
3057
+ xhr.send(JSON.stringify(body != null ? body : {}));
3058
+ });
3059
+ const { status, data, type, rate } = await this.withTimeout(request, timeoutMs != null ? timeoutMs : this.timeoutMs, path);
3060
+ if (status < 200 || status >= 300 || !(data instanceof ArrayBuffer)) {
3061
+ throw new UploadError(status, `HTTP ${status} for ${path}`);
3062
+ }
3063
+ const parsedRate = rate ? Number.parseInt(rate, 10) : NaN;
3064
+ const fromType = /rate=(\d+)/.exec(type);
3065
+ return {
3066
+ bytes: new Uint8Array(data),
3067
+ contentType: type,
3068
+ sampleRate: Number.isFinite(parsedRate) ? parsedRate : fromType ? Number(fromType[1]) : null
3069
+ };
3070
+ }
3009
3071
  async postRaw(path, body, signal) {
3010
3072
  const response = await this.transport.request({
3011
3073
  url: this.url(path),
@@ -3081,48 +3143,48 @@ function traceApi(api) {
3081
3143
  return {
3082
3144
  supportsStreaming: api.supportsStreaming,
3083
3145
  async get(path, timeoutMs) {
3084
- const id = next();
3085
- line("→", `#${id} GET ${path}`);
3146
+ const id2 = next();
3147
+ line("→", `#${id2} GET ${path}`);
3086
3148
  try {
3087
3149
  const result = await api.get(path, timeoutMs);
3088
- dump(`[${stamp()}] ← #${id} GET ${path} responded:`, result);
3150
+ dump(`[${stamp()}] ← #${id2} GET ${path} responded:`, result);
3089
3151
  return result;
3090
3152
  } catch (error) {
3091
- line("✗", `#${id} GET ${path} FAILED: ${describeError(error)}`);
3153
+ line("✗", `#${id2} GET ${path} FAILED: ${describeError(error)}`);
3092
3154
  throw error;
3093
3155
  }
3094
3156
  },
3095
3157
  async post(path, body, timeoutMs) {
3096
- const id = next();
3097
- dump(`[${stamp()}] → #${id} POST ${path} body:`, body);
3158
+ const id2 = next();
3159
+ dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
3098
3160
  try {
3099
3161
  const result = await api.post(path, body, timeoutMs);
3100
- dump(`[${stamp()}] ← #${id} POST ${path} responded:`, result);
3162
+ dump(`[${stamp()}] ← #${id2} POST ${path} responded:`, result);
3101
3163
  return result;
3102
3164
  } catch (error) {
3103
- line("✗", `#${id} POST ${path} FAILED: ${describeError(error)}`);
3165
+ line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
3104
3166
  throw error;
3105
3167
  }
3106
3168
  },
3107
3169
  async postRaw(path, body, signal) {
3108
3170
  var _a;
3109
- const id = next();
3110
- dump(`[${stamp()}] → #${id} POST ${path} body:`, body);
3171
+ const id2 = next();
3172
+ dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
3111
3173
  try {
3112
3174
  const response = await api.postRaw(path, body, signal);
3113
- line("←", `#${id} ${response.status} ${path} (${(_a = response.headers.get("content-type")) != null ? _a : "no content-type"})`);
3175
+ line("←", `#${id2} ${response.status} ${path} (${(_a = response.headers.get("content-type")) != null ? _a : "no content-type"})`);
3114
3176
  if (response.stream) {
3115
- return { ...response, stream: teeStream(response.stream, id) };
3177
+ return { ...response, stream: teeStream(response.stream, id2) };
3116
3178
  }
3117
3179
  return response;
3118
3180
  } catch (error) {
3119
- line("✗", `#${id} POST ${path} FAILED: ${describeError(error)}`);
3181
+ line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
3120
3182
  throw error;
3121
3183
  }
3122
3184
  }
3123
3185
  };
3124
3186
  }
3125
- function teeStream(stream, id) {
3187
+ function teeStream(stream, id2) {
3126
3188
  return {
3127
3189
  async *[Symbol.asyncIterator]() {
3128
3190
  var _a;
@@ -3133,12 +3195,12 @@ function teeStream(stream, id) {
3133
3195
  buffer = (_a = parts.pop()) != null ? _a : "";
3134
3196
  for (const frame of parts) {
3135
3197
  const trimmed = frame.trim();
3136
- if (trimmed) console.log(`[${stamp()}] ⋯ #${id} frame: ${trimmed}`);
3198
+ if (trimmed) console.log(`[${stamp()}] ⋯ #${id2} frame: ${trimmed}`);
3137
3199
  }
3138
3200
  yield chunk;
3139
3201
  }
3140
- if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${id} frame: ${buffer.trim()}`);
3141
- line("⋯", `#${id} stream ended`);
3202
+ if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${id2} frame: ${buffer.trim()}`);
3203
+ line("⋯", `#${id2} stream ended`);
3142
3204
  }
3143
3205
  };
3144
3206
  }
@@ -3147,18 +3209,18 @@ function traceTransport(transport) {
3147
3209
  supportsStreaming: transport.supportsStreaming,
3148
3210
  async request(req) {
3149
3211
  var _a;
3150
- const id = next();
3212
+ const id2 = next();
3151
3213
  console.log(
3152
- `[${stamp()}] ⇢ #${id} ${req.method} ${req.url}
3214
+ `[${stamp()}] ⇢ #${id2} ${req.method} ${req.url}
3153
3215
  headers: ${JSON.stringify(req.headers)}
3154
3216
  body: ${(_a = req.body) != null ? _a : "(none)"}`
3155
3217
  );
3156
3218
  try {
3157
3219
  const response = await transport.request(req);
3158
- line("⇠", `#${id} ${response.status} ${req.url}`);
3220
+ line("⇠", `#${id2} ${response.status} ${req.url}`);
3159
3221
  return response;
3160
3222
  } catch (error) {
3161
- line("✗", `#${id} ${req.method} ${req.url} FAILED: ${describeError(error)}`);
3223
+ line("✗", `#${id2} ${req.method} ${req.url} FAILED: ${describeError(error)}`);
3162
3224
  throw error;
3163
3225
  }
3164
3226
  }
@@ -3219,10 +3281,174 @@ ${text}`);
3219
3281
  console.log(`${"═".repeat(60)}
3220
3282
  `);
3221
3283
  }
3284
+ const PREFIX = "guideai:";
3285
+ class HydratedStore {
3286
+ constructor(storage) {
3287
+ this.storage = storage;
3288
+ this.values = /* @__PURE__ */ new Map();
3289
+ this.touched = /* @__PURE__ */ new Set();
3290
+ this.ready = this.load();
3291
+ }
3292
+ async load() {
3293
+ try {
3294
+ const keys = (await this.storage.getAllKeys()).filter((key) => key.startsWith(PREFIX));
3295
+ if (!keys.length) return;
3296
+ for (const [key, value] of await this.storage.multiGet(keys)) {
3297
+ const own = key.slice(PREFIX.length);
3298
+ if (value !== null && !this.touched.has(own)) this.values.set(own, value);
3299
+ }
3300
+ } catch (error) {
3301
+ console.log("[GuideAI] ✗ could not load saved conversations:", error);
3302
+ }
3303
+ }
3304
+ getString(key) {
3305
+ return this.values.get(key);
3306
+ }
3307
+ set(key, value) {
3308
+ this.touched.add(key);
3309
+ this.values.set(key, value);
3310
+ void this.storage.setItem(PREFIX + key, value).catch(() => void 0);
3311
+ }
3312
+ delete(key) {
3313
+ this.touched.add(key);
3314
+ this.values.delete(key);
3315
+ void this.storage.removeItem(PREFIX + key).catch(() => void 0);
3316
+ }
3317
+ }
3318
+ const TITLE_CHARS = 60;
3319
+ const newId = () => `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
3320
+ function titleOf(raw) {
3321
+ var _a, _b;
3322
+ if (!raw) return "";
3323
+ try {
3324
+ const first = (_a = JSON.parse(raw).messages) == null ? void 0 : _a.find((m) => {
3325
+ var _a2;
3326
+ return m.role === "user" && ((_a2 = m.content) == null ? void 0 : _a2.trim());
3327
+ });
3328
+ const text = ((_b = first == null ? void 0 : first.content) != null ? _b : "").replace(/\s+/g, " ").trim();
3329
+ return text.length > TITLE_CHARS ? `${text.slice(0, TITLE_CHARS - 1)}…` : text;
3330
+ } catch {
3331
+ return "";
3332
+ }
3333
+ }
3334
+ class ConversationLibrary {
3335
+ /**
3336
+ * @param memoryKey The key core's memory keeps the open conversation under.
3337
+ * @param scope One app + agent: a tutor and a course builder keep separate lists.
3338
+ */
3339
+ constructor(store2, memoryKey, scope) {
3340
+ this.store = store2;
3341
+ this.memoryKey = memoryKey;
3342
+ this.scope = scope;
3343
+ this.listeners = /* @__PURE__ */ new Set();
3344
+ this.unsavedId = newId();
3345
+ this.subscribe = (listener) => {
3346
+ this.listeners.add(listener);
3347
+ return () => {
3348
+ this.listeners.delete(listener);
3349
+ };
3350
+ };
3351
+ this.getSnapshot = () => this.snapshot;
3352
+ this.snapshot = this.read(0);
3353
+ }
3354
+ get indexKey() {
3355
+ return `guideai_chats_${this.scope}`;
3356
+ }
3357
+ get activeKey() {
3358
+ return `guideai_chats_active_${this.scope}`;
3359
+ }
3360
+ archiveKey(id2) {
3361
+ return `guideai_chat_${this.scope}#${id2}`;
3362
+ }
3363
+ read(version) {
3364
+ var _a;
3365
+ let list = [];
3366
+ try {
3367
+ list = JSON.parse((_a = this.store.getItem(this.indexKey)) != null ? _a : "[]");
3368
+ } catch {
3369
+ list = [];
3370
+ }
3371
+ const activeId = this.store.getItem(this.activeKey) || this.unsavedId;
3372
+ return { conversations: list.sort((a, b) => b.updatedAt - a.updatedAt), activeId, version };
3373
+ }
3374
+ publish(replaced) {
3375
+ this.snapshot = this.read(this.snapshot.version + (replaced ? 1 : 0));
3376
+ for (const listener of this.listeners) listener();
3377
+ }
3378
+ writeIndex(list) {
3379
+ this.store.setItem(this.indexKey, JSON.stringify(list));
3380
+ }
3381
+ /** The store finished loading what was saved: the open conversation may have changed. */
3382
+ reload() {
3383
+ this.publish(true);
3384
+ }
3385
+ /** Record the open conversation in the list (after each turn). */
3386
+ touch() {
3387
+ const { activeId } = this.snapshot;
3388
+ const raw = this.store.getItem(this.memoryKey);
3389
+ const title = titleOf(raw);
3390
+ if (!title) return;
3391
+ const list = this.snapshot.conversations.filter((c) => c.id !== activeId);
3392
+ list.push({ id: activeId, title, updatedAt: Date.now() });
3393
+ this.writeIndex(list);
3394
+ this.store.setItem(this.activeKey, activeId);
3395
+ this.publish(false);
3396
+ }
3397
+ /** Put the open conversation away, then make `id`'s (or an empty one) the open one. */
3398
+ swapTo(id2, raw) {
3399
+ const current = this.store.getItem(this.memoryKey);
3400
+ if (current && titleOf(current)) this.store.setItem(this.archiveKey(this.snapshot.activeId), current);
3401
+ if (raw) {
3402
+ try {
3403
+ const data = JSON.parse(raw);
3404
+ this.store.setItem(this.memoryKey, JSON.stringify({ ...data, updated_at: Date.now() }));
3405
+ } catch {
3406
+ this.store.removeItem(this.memoryKey);
3407
+ }
3408
+ } else {
3409
+ this.store.removeItem(this.memoryKey);
3410
+ }
3411
+ this.store.setItem(this.activeKey, id2);
3412
+ }
3413
+ /** Start an empty conversation; the current one stays in the list. */
3414
+ startNew() {
3415
+ if (!titleOf(this.store.getItem(this.memoryKey))) return;
3416
+ this.touch();
3417
+ this.swapTo(newId(), null);
3418
+ this.publish(true);
3419
+ }
3420
+ /** Open a conversation from the list. */
3421
+ open(id2) {
3422
+ if (id2 === this.snapshot.activeId) return;
3423
+ const raw = this.store.getItem(this.archiveKey(id2));
3424
+ if (!raw) return;
3425
+ this.touch();
3426
+ this.swapTo(id2, raw);
3427
+ this.store.removeItem(this.archiveKey(id2));
3428
+ this.publish(true);
3429
+ }
3430
+ /** Delete a conversation. Deleting the open one starts an empty one. */
3431
+ remove(id2) {
3432
+ this.writeIndex(this.snapshot.conversations.filter((c) => c.id !== id2));
3433
+ if (id2 === this.snapshot.activeId) {
3434
+ this.store.removeItem(this.memoryKey);
3435
+ this.unsavedId = newId();
3436
+ this.store.removeItem(this.activeKey);
3437
+ this.publish(true);
3438
+ return;
3439
+ }
3440
+ this.store.removeItem(this.archiveKey(id2));
3441
+ this.publish(false);
3442
+ }
3443
+ }
3444
+ function useConversationSnapshot(library) {
3445
+ return useSyncExternalStore(library.subscribe, library.getSnapshot, library.getSnapshot);
3446
+ }
3222
3447
  const DEFAULT_BASE_URL = "https://cdn.3guideai.com";
3448
+ const CONVERSATION_TTL_MS = 365 * 24 * 60 * 60 * 1e3;
3223
3449
  let configured = null;
3224
3450
  function configure(config) {
3225
- var _a, _b, _c, _d, _e, _f;
3451
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
3226
3452
  const debug = (_a = config.debug) != null ? _a : false;
3227
3453
  const baseApi = new RNApiClient({
3228
3454
  baseUrl: (_b = config.baseUrl) != null ? _b : DEFAULT_BASE_URL,
@@ -3230,9 +3456,10 @@ function configure(config) {
3230
3456
  requestOrigin: config.origin,
3231
3457
  agent: ((_c = config.agent) == null ? void 0 : _c.trim()) || void 0
3232
3458
  });
3459
+ const hydrated = !config.store && config.storage ? new HydratedStore(config.storage) : null;
3233
3460
  const runtime = new GuideAIRuntime({
3234
3461
  requestOrigin: config.origin,
3235
- store: config.store,
3462
+ store: (_e = (_d = config.store) != null ? _d : hydrated) != null ? _e : void 0,
3236
3463
  auth: {
3237
3464
  getAuthToken: config.getAuthToken,
3238
3465
  onAuthExpired: config.onAuthExpired,
@@ -3243,15 +3470,13 @@ function configure(config) {
3243
3470
  ) : void 0
3244
3471
  });
3245
3472
  configureGuideAI(runtime);
3473
+ const scope = ((_f = config.agent) == null ? void 0 : _f.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey;
3246
3474
  const harness = new CopilotHarness(
3247
3475
  debug ? traceApi(baseApi) : baseApi,
3248
3476
  {
3249
- // The site id is resolved server-side from the API key; the
3250
- // harness only needs a stable string to key its local memory.
3251
- // Per agent too: a tutor and a course builder in one app must not
3252
- // read each other's conversation.
3253
- siteId: ((_d = config.agent) == null ? void 0 : _d.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey,
3254
- assistantLabel: config.assistantName
3477
+ siteId: scope,
3478
+ assistantLabel: config.assistantName,
3479
+ memoryTtlMs: CONVERSATION_TTL_MS
3255
3480
  },
3256
3481
  debug ? traceTools(runtime.tools) : runtime.tools,
3257
3482
  runtime.storage,
@@ -3259,15 +3484,20 @@ function configure(config) {
3259
3484
  runtime.credentials
3260
3485
  );
3261
3486
  if (config.toolContext) harness.setToolContext(config.toolContext);
3487
+ const conversations = new ConversationLibrary(runtime.storage, `guideai_chat_${scope}`, scope);
3262
3488
  configured = {
3263
3489
  runtime,
3264
3490
  harness,
3265
3491
  api: baseApi,
3266
3492
  debug,
3267
- visitorId: (_e = config.visitorId) != null ? _e : null,
3268
- profile: (_f = config.userProfile) != null ? _f : null,
3269
- followUps: cleanFollowUps(config.followUps)
3493
+ visitorId: (_g = config.visitorId) != null ? _g : null,
3494
+ profile: (_h = config.userProfile) != null ? _h : null,
3495
+ followUps: cleanFollowUps(config.followUps),
3496
+ speech: (_i = config.speech) != null ? _i : null,
3497
+ conversations,
3498
+ storage: runtime.storage
3270
3499
  };
3500
+ void (hydrated == null ? void 0 : hydrated.ready.then(() => conversations.reload()));
3271
3501
  }
3272
3502
  function identify(userId) {
3273
3503
  if (!configured) throw new Error("Call GuideAI.configure() before identify().");
@@ -3304,17 +3534,710 @@ function reset() {
3304
3534
  configured = null;
3305
3535
  }
3306
3536
  const GuideAI = { configure, identify, setUserProfile, setToolContext, setFollowUps, isConfigured, reset };
3537
+ const LIMITS = {
3538
+ steps: 12,
3539
+ // A label round a photo arrives as two items: its words and its arrow.
3540
+ itemsPerStep: 16,
3541
+ items: 96,
3542
+ say: 300,
3543
+ text: 60,
3544
+ art: 80,
3545
+ title: 80,
3546
+ freePoints: 32,
3547
+ tableRows: 6,
3548
+ tableCols: 4,
3549
+ cell: 24,
3550
+ artContours: 400,
3551
+ contourChars: 2e4
3552
+ };
3553
+ const INK_KINDS = [
3554
+ "line",
3555
+ "arrow",
3556
+ "poly",
3557
+ "curve",
3558
+ "free",
3559
+ "oval",
3560
+ "corner",
3561
+ "arc",
3562
+ "dot",
3563
+ "circle",
3564
+ "box",
3565
+ "underline",
3566
+ "cross",
3567
+ "tick",
3568
+ "bracket"
3569
+ ];
3570
+ const POINT_INKS = ["poly", "curve", "free", "corner", "arc"];
3571
+ const BOARD_W = 160;
3572
+ const BOARD_H = 100;
3573
+ const POINT_MARKS = ["circle", "underline", "box"];
3574
+ class SceneError extends Error {
3575
+ constructor() {
3576
+ super(...arguments);
3577
+ this.name = "SceneError";
3578
+ }
3579
+ }
3580
+ const ID = /^[A-Za-z0-9_-]{1,24}$/;
3581
+ const SIZES = ["s", "m", "l"];
3582
+ const TONES = ["ink", "blue", "red", "green"];
3583
+ const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]*$/;
3584
+ const PHOTO_URL = /^https:\/\/res\.cloudinary\.com\/[A-Za-z0-9_-]+\/image\/upload\/[^\s"'<>\\]+$/;
3585
+ const flat = (value, max) => typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, max) : "";
3586
+ const clamp = (n, top = BOARD_H) => Math.round(Math.min(top, Math.max(0, n)) * 10) / 10;
3587
+ function num(value) {
3588
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
3589
+ }
3590
+ let wide = 1;
3591
+ function point(raw) {
3592
+ if (!Array.isArray(raw) || raw.length !== 2) return null;
3593
+ const [x, y] = raw.map(num);
3594
+ return x === null || y === null ? null : [clamp(x * wide, BOARD_W), clamp(y)];
3595
+ }
3596
+ function box(raw) {
3597
+ if (!Array.isArray(raw) || raw.length !== 4) return null;
3598
+ const v = raw.map(num);
3599
+ if (v.some((n) => n === null)) return null;
3600
+ const x = clamp(v[0] * wide, BOARD_W);
3601
+ const y = clamp(v[1]);
3602
+ const w = Math.min(Math.max(1, v[2] * wide), BOARD_W - x);
3603
+ const h = Math.min(Math.max(1, v[3]), BOARD_H - y);
3604
+ return w >= 1 && h >= 1 ? [x, y, w, h] : null;
3605
+ }
3606
+ function tone(raw) {
3607
+ return typeof raw === "string" && TONES.includes(raw) ? raw : "ink";
3608
+ }
3609
+ function id(raw) {
3610
+ return typeof raw === "string" && ID.test(raw) ? raw : void 0;
3611
+ }
3612
+ function item(raw) {
3613
+ var _a;
3614
+ if (!raw || typeof raw !== "object") return null;
3615
+ const r = raw;
3616
+ const kinds = ["art", "photo", "text", "ink", "rows", "mark", "erase", "point"].filter((k) => r[k] !== void 0 && r[k] !== null && r[k] !== "");
3617
+ if (kinds.length !== 1) return null;
3618
+ switch (kinds[0]) {
3619
+ case "art": {
3620
+ const at = box(r.at);
3621
+ const art = flat(r.art, LIMITS.art);
3622
+ return at && art ? { kind: "art", id: id(r.id), art, at, tone: tone(r.tone) } : null;
3623
+ }
3624
+ case "photo": {
3625
+ const at = box(r.at);
3626
+ const photo2 = flat(r.photo, LIMITS.art);
3627
+ return at && photo2 ? { kind: "photo", id: id(r.id), photo: photo2, at } : null;
3628
+ }
3629
+ case "text": {
3630
+ const at = point(Array.isArray(r.at) ? r.at.slice(0, 2) : null);
3631
+ const text = flat(r.text, LIMITS.text);
3632
+ const size = typeof r.size === "string" && SIZES.includes(r.size) ? r.size : "m";
3633
+ return at && text ? { kind: "text", id: id(r.id), text, at, size, tone: tone(r.tone) } : null;
3634
+ }
3635
+ case "ink": {
3636
+ const ink = r.ink;
3637
+ if (!INK_KINDS.includes(ink)) return null;
3638
+ const base = { kind: "ink", id: id(r.id), ink, tone: tone(r.tone) };
3639
+ if (POINT_INKS.includes(ink)) {
3640
+ const pts = Array.isArray(r.pts) ? r.pts.slice(0, LIMITS.freePoints).map(point).filter((p) => !!p) : [];
3641
+ if (ink === "corner" || ink === "arc") return pts.length === 3 ? { ...base, pts } : null;
3642
+ if (pts.length < 2) return null;
3643
+ return ink === "poly" && r.closed === true ? { ...base, pts, closed: true } : { ...base, pts };
3644
+ }
3645
+ if (ink === "dot") {
3646
+ const at2 = point(r.at);
3647
+ return at2 ? { ...base, at: at2 } : null;
3648
+ }
3649
+ if (ink === "line" || ink === "arrow") {
3650
+ const at2 = point(r.at);
3651
+ const to = point(r.to);
3652
+ return at2 && to ? { ...base, at: at2, to } : null;
3653
+ }
3654
+ const at = box(r.at);
3655
+ return at ? { ...base, at } : null;
3656
+ }
3657
+ case "rows": {
3658
+ if (!Array.isArray(r.rows) || !Array.isArray(r.at) || r.at.length < 2) return null;
3659
+ const rows = r.rows.slice(0, LIMITS.tableRows).filter((row) => Array.isArray(row) && row.length > 0).map((row) => row.slice(0, LIMITS.tableCols).map((cell) => flat(String(cell != null ? cell : ""), LIMITS.cell)));
3660
+ const at = point(r.at.slice(0, 2));
3661
+ if (!rows.length || !at) return null;
3662
+ const width = ((_a = num(r.at[2])) != null ? _a : 40) * wide;
3663
+ return { kind: "table", id: id(r.id), rows, at: [at[0], at[1], Math.min(Math.max(5, width), BOARD_W - at[0])], tone: tone(r.tone) };
3664
+ }
3665
+ case "mark": {
3666
+ const mark = id(r.mark);
3667
+ return mark ? { kind: "mark", mark } : null;
3668
+ }
3669
+ case "erase": {
3670
+ const erase = id(r.erase);
3671
+ return erase ? { kind: "erase", erase } : null;
3672
+ }
3673
+ case "point": {
3674
+ const target = id(r.point);
3675
+ const as = typeof r.as === "string" && POINT_MARKS.includes(r.as) ? r.as : "circle";
3676
+ return target ? { kind: "point", point: target, as } : null;
3677
+ }
3678
+ default:
3679
+ return null;
3680
+ }
3681
+ }
3682
+ function artInk(raw) {
3683
+ if (!raw || typeof raw !== "object") return null;
3684
+ const r = raw;
3685
+ if (typeof r.icon === "string") return /^[a-z]{1,20}$/.test(r.icon) ? { icon: r.icon } : null;
3686
+ if (!Array.isArray(r.contours)) return null;
3687
+ const contours = r.contours.slice(0, LIMITS.artContours).filter((d) => typeof d === "string" && d.length <= LIMITS.contourChars && PATH_DATA.test(d));
3688
+ const viewBox = typeof r.view_box === "string" && /^[\d.\s-]+$/.test(r.view_box) ? r.view_box : "0 0 100 100";
3689
+ const transform = typeof r.transform === "string" && /^[a-z()\d.,\s-]*$/i.test(r.transform) ? r.transform : "";
3690
+ return contours.length ? { view_box: viewBox, transform, contours } : null;
3691
+ }
3692
+ function photo(raw) {
3693
+ if (!raw || typeof raw !== "object") return null;
3694
+ const r = raw;
3695
+ const w = num(r.w);
3696
+ const h = num(r.h);
3697
+ if (typeof r.url !== "string" || r.url.length > 600 || !PHOTO_URL.test(r.url) || !w || !h || w <= 0 || h <= 0) return null;
3698
+ const credit = flat(r.credit, 60);
3699
+ return credit ? { url: r.url, w, h, credit } : { url: r.url, w, h };
3700
+ }
3701
+ function validateScene(raw) {
3702
+ if (!raw || typeof raw !== "object") throw new SceneError("A scene is an object.");
3703
+ const r = raw;
3704
+ if (!Array.isArray(r.steps) || r.steps.length === 0) throw new SceneError("A scene needs steps.");
3705
+ if (r.steps.length > LIMITS.steps) throw new SceneError(`A scene has at most ${LIMITS.steps} steps.`);
3706
+ wide = r.v === 3 ? 1 : BOARD_W / 100;
3707
+ let total = 0;
3708
+ const steps = [];
3709
+ let onBoard = /* @__PURE__ */ new Set();
3710
+ for (const rawStep of r.steps) {
3711
+ if (!rawStep || typeof rawStep !== "object") continue;
3712
+ const s = rawStep;
3713
+ const clear = s.clear === true;
3714
+ if (clear) onBoard = /* @__PURE__ */ new Set();
3715
+ const draw = [];
3716
+ const items = Array.isArray(s.draw) ? s.draw.slice(0, LIMITS.itemsPerStep) : [];
3717
+ for (const rawItem of items) {
3718
+ if (total >= LIMITS.items) break;
3719
+ const it = item(rawItem);
3720
+ if (!it) continue;
3721
+ if (it.kind === "mark" && !onBoard.has(it.mark)) continue;
3722
+ if (it.kind === "erase") {
3723
+ if (!onBoard.has(it.erase)) continue;
3724
+ onBoard.delete(it.erase);
3725
+ }
3726
+ if ("id" in it && it.id) onBoard.add(it.id);
3727
+ draw.push(it);
3728
+ total += 1;
3729
+ }
3730
+ const say = flat(s.say, LIMITS.say);
3731
+ if (!say && !draw.length) continue;
3732
+ steps.push({ say, clear, draw });
3733
+ }
3734
+ if (!steps.length) throw new SceneError("Nothing in this scene can be drawn.");
3735
+ const art = {};
3736
+ if (r.art && typeof r.art === "object") {
3737
+ for (const [name, value] of Object.entries(r.art)) {
3738
+ const ink = artInk(value);
3739
+ if (ink) art[name.slice(0, LIMITS.art)] = ink;
3740
+ }
3741
+ }
3742
+ const photos = {};
3743
+ if (r.photos && typeof r.photos === "object") {
3744
+ for (const [name, value] of Object.entries(r.photos)) {
3745
+ const pic = photo(value);
3746
+ if (pic) photos[name.slice(0, LIMITS.art)] = pic;
3747
+ }
3748
+ }
3749
+ return {
3750
+ v: 3,
3751
+ title: flat(r.title, LIMITS.title) || "Explanation",
3752
+ sample: r.sample === true,
3753
+ steps,
3754
+ art,
3755
+ photos
3756
+ };
3757
+ }
3758
+ const BLOCKS_PATH = "/api/v1/chat/blocks";
3759
+ const WHITEBOARD_PATH = "/api/v1/chat/whiteboard";
3760
+ const BLOCKS_TTL_MS = 6e4;
3761
+ const KEEP = 12;
3762
+ const CLOSED = { status: "closed", scene: null, error: null, question: "" };
3763
+ function readableAnswer(text) {
3764
+ return text.replace(/```[a-z]*[ \t]*\n[\s\S]*?```/gi, " ").replace(/\s+/g, " ").trim();
3765
+ }
3766
+ class WhiteboardStore {
3767
+ constructor(api, language = () => void 0, clock = () => Date.now()) {
3768
+ this.api = api;
3769
+ this.language = language;
3770
+ this.clock = clock;
3771
+ this.state = CLOSED;
3772
+ this.listeners = /* @__PURE__ */ new Set();
3773
+ this.kept = /* @__PURE__ */ new Map();
3774
+ this.blocks = null;
3775
+ this.blocksPending = null;
3776
+ this.request = 0;
3777
+ this.getState = () => this.state;
3778
+ this.subscribe = (listener) => {
3779
+ this.listeners.add(listener);
3780
+ return () => this.listeners.delete(listener);
3781
+ };
3782
+ }
3783
+ /** Whether the Blueprint has the whiteboard. False when it cannot be asked. */
3784
+ async available() {
3785
+ var _a;
3786
+ if (this.blocks && this.clock() - this.blocks.at < BLOCKS_TTL_MS) return this.blocks.on;
3787
+ (_a = this.blocksPending) != null ? _a : this.blocksPending = this.api().get(BLOCKS_PATH, 1e4).then((res) => {
3788
+ var _a2;
3789
+ return ((_a2 = res == null ? void 0 : res.blocks) == null ? void 0 : _a2.whiteboard) === true;
3790
+ }, () => false).then((on) => {
3791
+ this.blocks = { at: this.clock(), on };
3792
+ this.blocksPending = null;
3793
+ return on;
3794
+ });
3795
+ return this.blocksPending;
3796
+ }
3797
+ /** Explain *question* (and the answer on screen) on the board. */
3798
+ async explain(question, answer) {
3799
+ const q = question.trim().slice(0, 500);
3800
+ if (!q) return false;
3801
+ const a = answer ? readableAnswer(answer).slice(0, 4e3) : void 0;
3802
+ const key = `${q}\0${a != null ? a : ""}`;
3803
+ const known = this.kept.get(key);
3804
+ if (known) {
3805
+ this.set({ status: "playing", scene: known, error: null, question: q, answer: a });
3806
+ return true;
3807
+ }
3808
+ const token = ++this.request;
3809
+ this.set({ status: "loading", scene: null, error: null, question: q, answer: a });
3810
+ try {
3811
+ const raw = await this.api().post(
3812
+ WHITEBOARD_PATH,
3813
+ // pictures: this board shows real photos with labelled parts.
3814
+ { question: q, answer: a || void 0, language: this.language(), pictures: true },
3815
+ 6e4
3816
+ );
3817
+ if (token !== this.request) return false;
3818
+ const scene = validateScene(raw);
3819
+ this.keep(key, scene);
3820
+ this.set({ status: "playing", scene, error: null, question: q, answer: a });
3821
+ return true;
3822
+ } catch (err) {
3823
+ if (token !== this.request) return false;
3824
+ this.set({
3825
+ status: "error",
3826
+ scene: null,
3827
+ error: err instanceof SceneError ? "This board could not be drawn." : "The whiteboard is not available right now.",
3828
+ question: q,
3829
+ answer: a
3830
+ });
3831
+ return false;
3832
+ }
3833
+ }
3834
+ /** Ask again after an error. */
3835
+ retry() {
3836
+ if (this.state.status === "error") void this.explain(this.state.question, this.state.answer);
3837
+ }
3838
+ /** Play a board the host built. A board that cannot be drawn throws SceneError. */
3839
+ play(scene) {
3840
+ const valid = validateScene(scene);
3841
+ this.request += 1;
3842
+ this.set({ status: "playing", scene: valid, error: null, question: valid.title });
3843
+ }
3844
+ close() {
3845
+ this.request += 1;
3846
+ this.set(CLOSED);
3847
+ }
3848
+ keep(key, scene) {
3849
+ this.kept.delete(key);
3850
+ this.kept.set(key, scene);
3851
+ while (this.kept.size > KEEP) {
3852
+ const oldest = this.kept.keys().next().value;
3853
+ if (oldest === void 0) break;
3854
+ this.kept.delete(oldest);
3855
+ }
3856
+ }
3857
+ set(next2) {
3858
+ this.state = next2;
3859
+ for (const listener of [...this.listeners]) listener();
3860
+ }
3861
+ }
3862
+ let store = null;
3863
+ let owner = null;
3864
+ function whiteboardStore() {
3865
+ const configured2 = requireConfigured();
3866
+ if (!store || owner !== configured2) {
3867
+ store == null ? void 0 : store.close();
3868
+ owner = configured2;
3869
+ store = new WhiteboardStore(
3870
+ () => configured2.api,
3871
+ () => {
3872
+ var _a;
3873
+ const language = (_a = configured2.profile) == null ? void 0 : _a.language;
3874
+ return typeof language === "string" && language ? language : void 0;
3875
+ }
3876
+ );
3877
+ }
3878
+ return store;
3879
+ }
3880
+ const IDLE = new WhiteboardStore(() => {
3881
+ throw new Error("Call GuideAI.configure() before using the whiteboard.");
3882
+ });
3883
+ function useWhiteboard() {
3884
+ const board = GuideAI.isConfigured() ? whiteboardStore() : IDLE;
3885
+ const state = useSyncExternalStore(board.subscribe, board.getState, board.getState);
3886
+ const [available, setAvailable] = useState(false);
3887
+ useEffect(() => {
3888
+ if (board === IDLE) return;
3889
+ let live = true;
3890
+ void board.available().then((on) => {
3891
+ if (live) setAvailable(on);
3892
+ });
3893
+ return () => {
3894
+ live = false;
3895
+ };
3896
+ }, [board]);
3897
+ return {
3898
+ available,
3899
+ state,
3900
+ explain: useCallback((question, answer) => board.explain(question, answer), [board]),
3901
+ play: useCallback((scene) => board.play(scene), [board]),
3902
+ retry: useCallback(() => board.retry(), [board]),
3903
+ close: useCallback(() => board.close(), [board])
3904
+ };
3905
+ }
3906
+ const AUDIO_TYPES = {
3907
+ m4a: "audio/m4a",
3908
+ mp4: "audio/mp4",
3909
+ aac: "audio/aac",
3910
+ caf: "audio/x-caf",
3911
+ wav: "audio/wav",
3912
+ mp3: "audio/mpeg",
3913
+ webm: "audio/webm",
3914
+ ogg: "audio/ogg",
3915
+ "3gp": "audio/3gpp"
3916
+ };
3917
+ function audioType(uri) {
3918
+ var _a, _b;
3919
+ const extension = ((_a = uri.split("?")[0].split(".").pop()) != null ? _a : "").toLowerCase();
3920
+ const type = (_b = AUDIO_TYPES[extension]) != null ? _b : "audio/m4a";
3921
+ return { type, name: `voice.${AUDIO_TYPES[extension] ? extension : "m4a"}` };
3922
+ }
3923
+ function replyFields(result, streamed) {
3924
+ var _a, _b;
3925
+ const { text, images } = headlessImages(answerText(result, streamed));
3926
+ const call = result.confirmationNeeded ? result.pendingToolCall : void 0;
3927
+ return {
3928
+ content: text,
3929
+ images: images.length ? images : void 0,
3930
+ suggestions: ((_a = result.quickReplies) == null ? void 0 : _a.length) ? result.quickReplies.slice(0, 4) : void 0,
3931
+ pendingAction: call ? { label: ((_b = call.label) == null ? void 0 : _b.trim()) || describeToolCall(call), tool: call.tool } : void 0
3932
+ };
3933
+ }
3934
+ let nextId = 0;
3935
+ const nextMessageId = () => `m${nextId += 1}`;
3936
+ function questionBefore(entries, index) {
3937
+ for (let i = index - 1; i >= 0; i -= 1) if (entries[i].role === "user") return entries[i].content;
3938
+ return void 0;
3939
+ }
3940
+ function answerText(result, fallback) {
3941
+ var _a, _b;
3942
+ const answer = ((_a = result.answer) != null ? _a : "").trim();
3943
+ if (answer) return answer;
3944
+ const first = (_b = result.guideSteps) == null ? void 0 : _b[0];
3945
+ const body = typeof (first == null ? void 0 : first.body) === "string" ? first.body.trim() : "";
3946
+ if (body) return body;
3947
+ const title = typeof (first == null ? void 0 : first.title) === "string" ? first.title.trim() : "";
3948
+ if (title) return title;
3949
+ return fallback || "Done.";
3950
+ }
3951
+ const FAILURE_MESSAGE = "I'm sorry, I can't complete your request right now. Would you like to talk to a human?";
3952
+ function useGuideAI(options = {}) {
3953
+ var _a, _b, _c, _d;
3954
+ const runtime = useGuideAIRuntime();
3955
+ const configured2 = requireConfigured();
3956
+ const harness = (_a = options.harness) != null ? _a : configured2.harness;
3957
+ const trace = (_b = options.trace) != null ? _b : configured2.debug;
3958
+ const defaultFollowUps = (_c = options.followUps) != null ? _c : configured2.followUps;
3959
+ const mode = "assistant";
3960
+ const board = useWhiteboard();
3961
+ const library = configured2.conversations;
3962
+ const { version } = useConversationSnapshot(library);
3963
+ const [messages, setMessages] = useState([]);
3964
+ const [input, setInput] = useState("");
3965
+ const [busy, setBusy] = useState(false);
3966
+ const [status, setStatus] = useState(null);
3967
+ const [transcribing, setTranscribing] = useState(false);
3968
+ const lastQuestion = useRef(null);
3969
+ const pending = useRef(/* @__PURE__ */ new Map());
3970
+ const shownVersion = useRef(null);
3971
+ const mounted = useRef(true);
3972
+ useEffect(() => () => {
3973
+ mounted.current = false;
3974
+ }, []);
3975
+ useEffect(() => {
3976
+ if (typeof harness.hasHistory !== "function" || typeof harness.getConversationHistory !== "function") return;
3977
+ const restored = () => (harness.hasHistory() ? harness.getConversationHistory() : []).filter((entry) => typeof entry.content === "string" && entry.content.trim()).map((entry, index, all) => {
3978
+ var _a2;
3979
+ return {
3980
+ id: (_a2 = entry.id) != null ? _a2 : `h${index}`,
3981
+ role: entry.role,
3982
+ content: entry.content,
3983
+ createdAt: typeof entry.timestamp === "number" ? entry.timestamp : Date.now(),
3984
+ question: entry.role === "assistant" ? questionBefore(all, index) : void 0
3985
+ };
3986
+ });
3987
+ if (shownVersion.current === version) {
3988
+ setMessages((previous) => previous.length > 0 ? previous : restored());
3989
+ return;
3990
+ }
3991
+ shownVersion.current = version;
3992
+ pending.current.clear();
3993
+ lastQuestion.current = null;
3994
+ setMessages(restored());
3995
+ }, [harness, version]);
3996
+ const initialized = useRef(null);
3997
+ const ensureInitialized = useCallback(() => {
3998
+ if (!initialized.current) initialized.current = harness.initialize();
3999
+ return initialized.current;
4000
+ }, [harness]);
4001
+ const runTurn = useCallback(async (replyId, question, work) => {
4002
+ var _a2, _b2;
4003
+ setBusy(true);
4004
+ setStatus(null);
4005
+ let streamed = "";
4006
+ const appendDelta = (delta) => {
4007
+ streamed += delta;
4008
+ if (!mounted.current) return;
4009
+ setMessages((prev) => prev.map((message) => message.id === replyId ? { ...message, content: message.content + delta } : message));
4010
+ };
4011
+ try {
4012
+ await ((_a2 = runtime.auth) == null ? void 0 : _a2.refresh());
4013
+ const result = await work((next2) => {
4014
+ if (mounted.current) setStatus(next2);
4015
+ }, appendDelta);
4016
+ if (trace) traceAssistantAnswer((_b2 = result.answer) != null ? _b2 : "(empty)", result.mode);
4017
+ if (result.confirmationNeeded && result.pendingToolCall) {
4018
+ pending.current.set(replyId, { call: result.pendingToolCall, question });
4019
+ }
4020
+ library.touch();
4021
+ const reply = replyFields(result, streamed);
4022
+ if (!mounted.current) return reply.content;
4023
+ setMessages((prev) => prev.map((message) => message.id === replyId ? { ...message, ...reply, streaming: false } : message));
4024
+ return reply.content;
4025
+ } catch (error) {
4026
+ console.log("[GuideAI] ✗ turn failed:", error);
4027
+ if (error instanceof Error && error.stack) {
4028
+ console.log("[GuideAI] stack:", error.stack);
4029
+ }
4030
+ if (!mounted.current) return null;
4031
+ setMessages((prev) => prev.map((message) => message.id === replyId ? {
4032
+ ...message,
4033
+ content: FAILURE_MESSAGE,
4034
+ streaming: false,
4035
+ error: true
4036
+ } : message));
4037
+ return null;
4038
+ } finally {
4039
+ if (mounted.current) {
4040
+ setBusy(false);
4041
+ setStatus(null);
4042
+ }
4043
+ }
4044
+ }, [runtime, trace, library]);
4045
+ const send = useCallback(async (question) => {
4046
+ const text = (question != null ? question : input).trim();
4047
+ if (!text || busy) return null;
4048
+ lastQuestion.current = text;
4049
+ if (question === void 0) setInput("");
4050
+ if (trace) traceUserMessage(text);
4051
+ const replyId = nextMessageId();
4052
+ const now = Date.now();
4053
+ setMessages((prev) => [
4054
+ ...prev,
4055
+ { id: nextMessageId(), role: "user", content: text, createdAt: now },
4056
+ { id: replyId, role: "assistant", content: "", streaming: true, createdAt: now, question: text }
4057
+ ]);
4058
+ return runTurn(replyId, text, async (onStatus, onDelta) => {
4059
+ await ensureInitialized();
4060
+ const screen = runtime.getActiveScreen();
4061
+ const { profile, visitorId } = requireConfigured();
4062
+ return harness.processMessage(
4063
+ text,
4064
+ screen == null ? void 0 : screen.path,
4065
+ runtime.captureSnapshot(),
4066
+ mode,
4067
+ onStatus,
4068
+ onDelta,
4069
+ void 0,
4070
+ void 0,
4071
+ // Who is asking, as the app knows them; the agent pitches to it.
4072
+ profile ? { profile } : void 0,
4073
+ visitorId != null ? visitorId : void 0
4074
+ );
4075
+ });
4076
+ }, [busy, input, harness, mode, runtime, ensureInitialized, trace, runTurn]);
4077
+ const retry = useCallback(async () => {
4078
+ if (!lastQuestion.current || busy) return;
4079
+ setMessages((prev) => prev.slice(0, -2));
4080
+ await send(lastQuestion.current);
4081
+ }, [busy, send]);
4082
+ const clear = useCallback(() => {
4083
+ setMessages([]);
4084
+ lastQuestion.current = null;
4085
+ pending.current.clear();
4086
+ library.startNew();
4087
+ }, [library]);
4088
+ const settleAction = useCallback((messageId) => {
4089
+ const action = pending.current.get(messageId);
4090
+ pending.current.delete(messageId);
4091
+ setMessages((prev) => prev.map((message) => message.id === messageId ? { ...message, pendingAction: void 0 } : message));
4092
+ return action;
4093
+ }, []);
4094
+ const confirm = useCallback(async (messageId) => {
4095
+ if (busy) return;
4096
+ const action = settleAction(messageId);
4097
+ if (!action) return;
4098
+ const replyId = nextMessageId();
4099
+ setMessages((prev) => [...prev, {
4100
+ id: replyId,
4101
+ role: "assistant",
4102
+ content: "",
4103
+ streaming: true,
4104
+ createdAt: Date.now(),
4105
+ question: action.question
4106
+ }]);
4107
+ await runTurn(replyId, action.question, async (onStatus, onDelta) => {
4108
+ await ensureInitialized();
4109
+ return harness.executeToolCall(action.call, action.question, onStatus, onDelta);
4110
+ });
4111
+ }, [busy, settleAction, runTurn, ensureInitialized, harness]);
4112
+ const cancel = useCallback((messageId) => {
4113
+ if (!settleAction(messageId)) return;
4114
+ setMessages((prev) => [...prev, {
4115
+ id: nextMessageId(),
4116
+ role: "assistant",
4117
+ content: "Okay, I haven't changed anything.",
4118
+ createdAt: Date.now()
4119
+ }]);
4120
+ }, [settleAction]);
4121
+ const sendVoice = useCallback(async (recording) => {
4122
+ var _a2;
4123
+ if (busy || transcribing) return { text: null, error: "Wait for the current reply to finish." };
4124
+ const guessed = audioType(recording.uri);
4125
+ setTranscribing(true);
4126
+ try {
4127
+ const result = await requireConfigured().api.postFile(
4128
+ EP.batchVoiceTranscribe(),
4129
+ "audio",
4130
+ { uri: recording.uri, name: guessed.name, type: recording.mimeType || guessed.type },
4131
+ { language_code: recording.languageCode || "en-US" },
4132
+ 45e3
4133
+ );
4134
+ const heard = ((_a2 = result == null ? void 0 : result.text) == null ? void 0 : _a2.trim()) || "";
4135
+ if (!heard) return { text: null, error: "I didn't catch that. Please try again." };
4136
+ if (mounted.current) setTranscribing(false);
4137
+ const answer = await send(heard);
4138
+ return { text: heard, answer };
4139
+ } catch (error) {
4140
+ console.log("[GuideAI] ✗ voice transcription failed:", error);
4141
+ const message = error instanceof UploadError && error.status === 422 ? error.message : "I couldn't process that recording. Please try again or type your message.";
4142
+ return { text: null, error: message };
4143
+ } finally {
4144
+ if (mounted.current) setTranscribing(false);
4145
+ }
4146
+ }, [busy, transcribing, send]);
4147
+ const shown = useMemo(() => messages.filter((message) => message.content || !message.streaming).map((message) => {
4148
+ var _a2;
4149
+ if (message.role !== "assistant" || message.streaming || message.error || !message.content) return message;
4150
+ const suggestions = (_a2 = message.suggestions) != null ? _a2 : (defaultFollowUps == null ? void 0 : defaultFollowUps.length) ? defaultFollowUps : void 0;
4151
+ return { ...message, suggestions, whiteboard: board.available || void 0 };
4152
+ }), [messages, defaultFollowUps, board.available]);
4153
+ const last = shown[shown.length - 1];
4154
+ const followUps = !busy && (last == null ? void 0 : last.role) === "assistant" && !last.pendingAction ? (_d = last.suggestions) != null ? _d : [] : [];
4155
+ const typing = busy && messages.some((message) => message.streaming && !message.content);
4156
+ const explainOnWhiteboard = useCallback(async (messageId) => {
4157
+ const answer = messages.find((message) => message.id === messageId);
4158
+ if (!answer || answer.role !== "assistant" || !answer.content) return false;
4159
+ return board.explain(answer.question || answer.content.slice(0, 200), answer.content);
4160
+ }, [messages, board]);
4161
+ return {
4162
+ messages: shown,
4163
+ typing,
4164
+ followUps,
4165
+ whiteboardAvailable: board.available,
4166
+ explainOnWhiteboard,
4167
+ input,
4168
+ setInput,
4169
+ send,
4170
+ busy,
4171
+ canSend: Boolean(input.trim()) && !busy,
4172
+ status,
4173
+ retry,
4174
+ clear,
4175
+ confirm,
4176
+ cancel,
4177
+ sendVoice,
4178
+ transcribing
4179
+ };
4180
+ }
4181
+ function useOnboarding() {
4182
+ const runtime = useGuideAIRuntime();
4183
+ const [checklist, setChecklist] = useState(null);
4184
+ const [loading, setLoading] = useState(true);
4185
+ const refresh = useCallback(async () => {
4186
+ var _a;
4187
+ const { api, visitorId } = requireConfigured();
4188
+ if (!visitorId) {
4189
+ setChecklist(null);
4190
+ setLoading(false);
4191
+ return;
4192
+ }
4193
+ try {
4194
+ const current = await api.get(EP.onboardingCurrent(visitorId));
4195
+ const screen = (_a = runtime.getActiveScreen()) == null ? void 0 : _a.path;
4196
+ const updated = current && !current.completed && !current.dismissed && screen ? await api.post(EP.onboardingObserve(), { user_id: visitorId, screen }) : current;
4197
+ setChecklist(updated);
4198
+ } catch {
4199
+ } finally {
4200
+ setLoading(false);
4201
+ }
4202
+ }, [runtime]);
4203
+ const dismiss = useCallback(async () => {
4204
+ const { api, visitorId } = requireConfigured();
4205
+ if (!visitorId) return;
4206
+ const updated = await api.post(EP.onboardingDismiss(), { user_id: visitorId });
4207
+ setChecklist(updated);
4208
+ }, []);
4209
+ useEffect(() => {
4210
+ void refresh();
4211
+ const timer = setInterval(() => void refresh(), 5e3);
4212
+ return () => clearInterval(timer);
4213
+ }, [refresh]);
4214
+ return { checklist, loading, refresh, dismiss };
4215
+ }
4216
+ function useConversations() {
4217
+ const library = requireConfigured().conversations;
4218
+ const { conversations, activeId } = useConversationSnapshot(library);
4219
+ return {
4220
+ conversations,
4221
+ activeId,
4222
+ newConversation: useCallback(() => library.startNew(), [library]),
4223
+ openConversation: useCallback((id2) => library.open(id2), [library]),
4224
+ deleteConversation: useCallback((id2) => library.remove(id2), [library])
4225
+ };
4226
+ }
3307
4227
  export {
4228
+ BOARD_W as B,
3308
4229
  EP as E,
3309
4230
  GuideAI as G,
4231
+ LIMITS as L,
3310
4232
  RegistryContext as R,
3311
4233
  ScreenRegistry as S,
3312
- UploadError as U,
3313
4234
  useScreenRegistry as a,
3314
- traceUserMessage as b,
3315
- describeToolCall as d,
4235
+ useConversations as b,
4236
+ useGuideAI as c,
4237
+ useOnboarding as d,
4238
+ useWhiteboard as e,
4239
+ BOARD_H as f,
3316
4240
  requireConfigured as r,
3317
- traceAssistantAnswer as t,
3318
4241
  useGuideAIRuntime as u
3319
4242
  };
3320
- //# sourceMappingURL=setup-CkXajERE.js.map
4243
+ //# sourceMappingURL=useConversations-B_7km_uH.js.map