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