@guideai/react-native 0.2.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.
- package/README.md +72 -20
- package/dist/GuideAIChat-DLtQYk2N.js +2439 -0
- package/dist/GuideAIChat-DLtQYk2N.js.map +1 -0
- package/dist/GuideAIChat-DQEa_Ff0.cjs +2438 -0
- package/dist/GuideAIChat-DQEa_Ff0.cjs.map +1 -0
- package/dist/index.cjs +116 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +246 -6
- package/dist/index.mjs +112 -4
- package/dist/index.mjs.map +1 -1
- package/dist/ui.cjs +22 -770
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.d.ts +262 -4
- package/dist/ui.mjs +14 -761
- package/dist/ui.mjs.map +1 -1
- package/dist/{useOnboarding-DAEGoYSs.js → useConversations-B4WYG2Qz.js} +703 -77
- package/dist/useConversations-B4WYG2Qz.js.map +1 -0
- package/dist/{useOnboarding-DWkCW5v0.cjs → useConversations-C9ivx2l-.cjs} +700 -74
- package/dist/useConversations-C9ivx2l-.cjs.map +1 -0
- package/dist/voice.cjs +540 -0
- package/dist/voice.cjs.map +1 -0
- package/dist/voice.d.ts +407 -0
- package/dist/voice.mjs +541 -0
- package/dist/voice.mjs.map +1 -0
- package/package.json +30 -11
- package/dist/useOnboarding-DAEGoYSs.js.map +0 -1
- package/dist/useOnboarding-DWkCW5v0.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useContext, createContext,
|
|
1
|
+
import { useContext, createContext, useSyncExternalStore, useState, useEffect, useCallback, useRef, useMemo } from "react";
|
|
2
2
|
const DRAWING_URL = /^https:\/\/res\.cloudinary\.com\/[\w-]+\/image\/upload\//;
|
|
3
3
|
const IMAGE_BLOCK = /```image[ \t]*\n([\s\S]*?)```/g;
|
|
4
4
|
function headlessImages(text) {
|
|
@@ -458,9 +458,9 @@ class ConversationMemory {
|
|
|
458
458
|
* @param store Where history lives. Defaults to memory so core never
|
|
459
459
|
* reaches for a global; the web SDK passes its localStorage adapter.
|
|
460
460
|
*/
|
|
461
|
-
constructor(siteId, ttlMs, maxMessages,
|
|
461
|
+
constructor(siteId, ttlMs, maxMessages, store2 = new MemoryKVStore()) {
|
|
462
462
|
this.listener = null;
|
|
463
|
-
this.store =
|
|
463
|
+
this.store = store2;
|
|
464
464
|
this.storageKey = `guideai_chat_${siteId}`;
|
|
465
465
|
this.ttlMs = ttlMs != null ? ttlMs : DEFAULT_TTL_MS;
|
|
466
466
|
this.maxMessages = maxMessages != null ? maxMessages : DEFAULT_MAX_MESSAGES;
|
|
@@ -556,16 +556,16 @@ class ConversationMemory {
|
|
|
556
556
|
}
|
|
557
557
|
if (Array.isArray(cleaned)) {
|
|
558
558
|
const total = cleaned.length;
|
|
559
|
-
const pickFields = (
|
|
560
|
-
if (typeof
|
|
561
|
-
const obj =
|
|
559
|
+
const pickFields = (item2) => {
|
|
560
|
+
if (typeof item2 === "object" && item2 !== null) {
|
|
561
|
+
const obj = item2;
|
|
562
562
|
const picked = {};
|
|
563
563
|
for (const key of ["name", "id", "title", "path", "endpoint", "url", "type", "method", "label", "slug", "status"]) {
|
|
564
564
|
if (key in obj) picked[key] = obj[key];
|
|
565
565
|
}
|
|
566
566
|
return Object.keys(picked).length > 0 ? picked : Object.keys(obj).slice(0, 4).reduce((acc, k) => ({ ...acc, [k]: obj[k] }), {});
|
|
567
567
|
}
|
|
568
|
-
return
|
|
568
|
+
return item2;
|
|
569
569
|
};
|
|
570
570
|
const compactItems = cleaned.map(pickFields);
|
|
571
571
|
let itemsToShow = compactItems;
|
|
@@ -600,7 +600,7 @@ class ConversationMemory {
|
|
|
600
600
|
_stripSensitiveFields(data, depth = 0) {
|
|
601
601
|
if (depth > 5) return data;
|
|
602
602
|
if (Array.isArray(data)) {
|
|
603
|
-
return data.slice(0, 50).map((
|
|
603
|
+
return data.slice(0, 50).map((item2) => this._stripSensitiveFields(item2, depth + 1));
|
|
604
604
|
}
|
|
605
605
|
if (typeof data === "object" && data !== null) {
|
|
606
606
|
const result = {};
|
|
@@ -805,9 +805,9 @@ class ToolExecutor {
|
|
|
805
805
|
var _a, _b, _c, _d, _e;
|
|
806
806
|
if (typeof entry === "string") return entry.trim() || null;
|
|
807
807
|
if (!entry || typeof entry !== "object") return null;
|
|
808
|
-
const
|
|
809
|
-
const message = (_c = (_b = (_a =
|
|
810
|
-
const location = Array.isArray(
|
|
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;
|
|
811
811
|
if (!message) return location ? `${location}: invalid` : null;
|
|
812
812
|
return location ? `${location}: ${message}` : String(message);
|
|
813
813
|
}
|
|
@@ -2373,8 +2373,8 @@ class RNHttpTransport {
|
|
|
2373
2373
|
}
|
|
2374
2374
|
}
|
|
2375
2375
|
class NativeKVStore {
|
|
2376
|
-
constructor(
|
|
2377
|
-
this.store =
|
|
2376
|
+
constructor(store2) {
|
|
2377
|
+
this.store = store2;
|
|
2378
2378
|
}
|
|
2379
2379
|
getItem(key) {
|
|
2380
2380
|
var _a;
|
|
@@ -2563,8 +2563,8 @@ class ScreenRegistry {
|
|
|
2563
2563
|
}
|
|
2564
2564
|
};
|
|
2565
2565
|
}
|
|
2566
|
-
get(
|
|
2567
|
-
return this.elements.get(
|
|
2566
|
+
get(id2) {
|
|
2567
|
+
return this.elements.get(id2);
|
|
2568
2568
|
}
|
|
2569
2569
|
/** Resolve by id first, then by visible label — the model may send either. */
|
|
2570
2570
|
find(request) {
|
|
@@ -3030,6 +3030,44 @@ class RNApiClient {
|
|
|
3030
3030
|
}
|
|
3031
3031
|
return parsed;
|
|
3032
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
|
+
}
|
|
3033
3071
|
async postRaw(path, body, signal) {
|
|
3034
3072
|
const response = await this.transport.request({
|
|
3035
3073
|
url: this.url(path),
|
|
@@ -3105,48 +3143,48 @@ function traceApi(api) {
|
|
|
3105
3143
|
return {
|
|
3106
3144
|
supportsStreaming: api.supportsStreaming,
|
|
3107
3145
|
async get(path, timeoutMs) {
|
|
3108
|
-
const
|
|
3109
|
-
line("→", `#${
|
|
3146
|
+
const id2 = next();
|
|
3147
|
+
line("→", `#${id2} GET ${path}`);
|
|
3110
3148
|
try {
|
|
3111
3149
|
const result = await api.get(path, timeoutMs);
|
|
3112
|
-
dump(`[${stamp()}] ← #${
|
|
3150
|
+
dump(`[${stamp()}] ← #${id2} GET ${path} responded:`, result);
|
|
3113
3151
|
return result;
|
|
3114
3152
|
} catch (error) {
|
|
3115
|
-
line("✗", `#${
|
|
3153
|
+
line("✗", `#${id2} GET ${path} FAILED: ${describeError(error)}`);
|
|
3116
3154
|
throw error;
|
|
3117
3155
|
}
|
|
3118
3156
|
},
|
|
3119
3157
|
async post(path, body, timeoutMs) {
|
|
3120
|
-
const
|
|
3121
|
-
dump(`[${stamp()}] → #${
|
|
3158
|
+
const id2 = next();
|
|
3159
|
+
dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
|
|
3122
3160
|
try {
|
|
3123
3161
|
const result = await api.post(path, body, timeoutMs);
|
|
3124
|
-
dump(`[${stamp()}] ← #${
|
|
3162
|
+
dump(`[${stamp()}] ← #${id2} POST ${path} responded:`, result);
|
|
3125
3163
|
return result;
|
|
3126
3164
|
} catch (error) {
|
|
3127
|
-
line("✗", `#${
|
|
3165
|
+
line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
|
|
3128
3166
|
throw error;
|
|
3129
3167
|
}
|
|
3130
3168
|
},
|
|
3131
3169
|
async postRaw(path, body, signal) {
|
|
3132
3170
|
var _a;
|
|
3133
|
-
const
|
|
3134
|
-
dump(`[${stamp()}] → #${
|
|
3171
|
+
const id2 = next();
|
|
3172
|
+
dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
|
|
3135
3173
|
try {
|
|
3136
3174
|
const response = await api.postRaw(path, body, signal);
|
|
3137
|
-
line("←", `#${
|
|
3175
|
+
line("←", `#${id2} ${response.status} ${path} (${(_a = response.headers.get("content-type")) != null ? _a : "no content-type"})`);
|
|
3138
3176
|
if (response.stream) {
|
|
3139
|
-
return { ...response, stream: teeStream(response.stream,
|
|
3177
|
+
return { ...response, stream: teeStream(response.stream, id2) };
|
|
3140
3178
|
}
|
|
3141
3179
|
return response;
|
|
3142
3180
|
} catch (error) {
|
|
3143
|
-
line("✗", `#${
|
|
3181
|
+
line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
|
|
3144
3182
|
throw error;
|
|
3145
3183
|
}
|
|
3146
3184
|
}
|
|
3147
3185
|
};
|
|
3148
3186
|
}
|
|
3149
|
-
function teeStream(stream,
|
|
3187
|
+
function teeStream(stream, id2) {
|
|
3150
3188
|
return {
|
|
3151
3189
|
async *[Symbol.asyncIterator]() {
|
|
3152
3190
|
var _a;
|
|
@@ -3157,12 +3195,12 @@ function teeStream(stream, id) {
|
|
|
3157
3195
|
buffer = (_a = parts.pop()) != null ? _a : "";
|
|
3158
3196
|
for (const frame of parts) {
|
|
3159
3197
|
const trimmed = frame.trim();
|
|
3160
|
-
if (trimmed) console.log(`[${stamp()}] ⋯ #${
|
|
3198
|
+
if (trimmed) console.log(`[${stamp()}] ⋯ #${id2} frame: ${trimmed}`);
|
|
3161
3199
|
}
|
|
3162
3200
|
yield chunk;
|
|
3163
3201
|
}
|
|
3164
|
-
if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${
|
|
3165
|
-
line("⋯", `#${
|
|
3202
|
+
if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${id2} frame: ${buffer.trim()}`);
|
|
3203
|
+
line("⋯", `#${id2} stream ended`);
|
|
3166
3204
|
}
|
|
3167
3205
|
};
|
|
3168
3206
|
}
|
|
@@ -3171,18 +3209,18 @@ function traceTransport(transport) {
|
|
|
3171
3209
|
supportsStreaming: transport.supportsStreaming,
|
|
3172
3210
|
async request(req) {
|
|
3173
3211
|
var _a;
|
|
3174
|
-
const
|
|
3212
|
+
const id2 = next();
|
|
3175
3213
|
console.log(
|
|
3176
|
-
`[${stamp()}] ⇢ #${
|
|
3214
|
+
`[${stamp()}] ⇢ #${id2} ${req.method} ${req.url}
|
|
3177
3215
|
headers: ${JSON.stringify(req.headers)}
|
|
3178
3216
|
body: ${(_a = req.body) != null ? _a : "(none)"}`
|
|
3179
3217
|
);
|
|
3180
3218
|
try {
|
|
3181
3219
|
const response = await transport.request(req);
|
|
3182
|
-
line("⇠", `#${
|
|
3220
|
+
line("⇠", `#${id2} ${response.status} ${req.url}`);
|
|
3183
3221
|
return response;
|
|
3184
3222
|
} catch (error) {
|
|
3185
|
-
line("✗", `#${
|
|
3223
|
+
line("✗", `#${id2} ${req.method} ${req.url} FAILED: ${describeError(error)}`);
|
|
3186
3224
|
throw error;
|
|
3187
3225
|
}
|
|
3188
3226
|
}
|
|
@@ -3243,10 +3281,174 @@ ${text}`);
|
|
|
3243
3281
|
console.log(`${"═".repeat(60)}
|
|
3244
3282
|
`);
|
|
3245
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
|
+
}
|
|
3246
3447
|
const DEFAULT_BASE_URL = "https://cdn.3guideai.com";
|
|
3448
|
+
const CONVERSATION_TTL_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
3247
3449
|
let configured = null;
|
|
3248
3450
|
function configure(config) {
|
|
3249
|
-
var _a, _b, _c, _d, _e, _f;
|
|
3451
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
3250
3452
|
const debug = (_a = config.debug) != null ? _a : false;
|
|
3251
3453
|
const baseApi = new RNApiClient({
|
|
3252
3454
|
baseUrl: (_b = config.baseUrl) != null ? _b : DEFAULT_BASE_URL,
|
|
@@ -3254,9 +3456,10 @@ function configure(config) {
|
|
|
3254
3456
|
requestOrigin: config.origin,
|
|
3255
3457
|
agent: ((_c = config.agent) == null ? void 0 : _c.trim()) || void 0
|
|
3256
3458
|
});
|
|
3459
|
+
const hydrated = !config.store && config.storage ? new HydratedStore(config.storage) : null;
|
|
3257
3460
|
const runtime = new GuideAIRuntime({
|
|
3258
3461
|
requestOrigin: config.origin,
|
|
3259
|
-
store: config.store,
|
|
3462
|
+
store: (_e = (_d = config.store) != null ? _d : hydrated) != null ? _e : void 0,
|
|
3260
3463
|
auth: {
|
|
3261
3464
|
getAuthToken: config.getAuthToken,
|
|
3262
3465
|
onAuthExpired: config.onAuthExpired,
|
|
@@ -3267,15 +3470,13 @@ function configure(config) {
|
|
|
3267
3470
|
) : void 0
|
|
3268
3471
|
});
|
|
3269
3472
|
configureGuideAI(runtime);
|
|
3473
|
+
const scope = ((_f = config.agent) == null ? void 0 : _f.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey;
|
|
3270
3474
|
const harness = new CopilotHarness(
|
|
3271
3475
|
debug ? traceApi(baseApi) : baseApi,
|
|
3272
3476
|
{
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
// read each other's conversation.
|
|
3277
|
-
siteId: ((_d = config.agent) == null ? void 0 : _d.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey,
|
|
3278
|
-
assistantLabel: config.assistantName
|
|
3477
|
+
siteId: scope,
|
|
3478
|
+
assistantLabel: config.assistantName,
|
|
3479
|
+
memoryTtlMs: CONVERSATION_TTL_MS
|
|
3279
3480
|
},
|
|
3280
3481
|
debug ? traceTools(runtime.tools) : runtime.tools,
|
|
3281
3482
|
runtime.storage,
|
|
@@ -3283,14 +3484,20 @@ function configure(config) {
|
|
|
3283
3484
|
runtime.credentials
|
|
3284
3485
|
);
|
|
3285
3486
|
if (config.toolContext) harness.setToolContext(config.toolContext);
|
|
3487
|
+
const conversations = new ConversationLibrary(runtime.storage, `guideai_chat_${scope}`, scope);
|
|
3286
3488
|
configured = {
|
|
3287
3489
|
runtime,
|
|
3288
3490
|
harness,
|
|
3289
3491
|
api: baseApi,
|
|
3290
3492
|
debug,
|
|
3291
|
-
visitorId: (
|
|
3292
|
-
profile: (
|
|
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
|
|
3293
3499
|
};
|
|
3500
|
+
void (hydrated == null ? void 0 : hydrated.ready.then(() => conversations.reload()));
|
|
3294
3501
|
}
|
|
3295
3502
|
function identify(userId) {
|
|
3296
3503
|
if (!configured) throw new Error("Call GuideAI.configure() before identify().");
|
|
@@ -3304,6 +3511,14 @@ function setUserProfile(profile) {
|
|
|
3304
3511
|
if (!configured) throw new Error("Call GuideAI.configure() before setUserProfile().");
|
|
3305
3512
|
configured.profile = profile;
|
|
3306
3513
|
}
|
|
3514
|
+
function setFollowUps(followUps) {
|
|
3515
|
+
if (!configured) throw new Error("Call GuideAI.configure() before setFollowUps().");
|
|
3516
|
+
configured.followUps = cleanFollowUps(followUps != null ? followUps : void 0);
|
|
3517
|
+
}
|
|
3518
|
+
function cleanFollowUps(list) {
|
|
3519
|
+
const clean = (list != null ? list : []).map((text) => text.trim()).filter(Boolean).slice(0, 4);
|
|
3520
|
+
return clean.length ? clean : void 0;
|
|
3521
|
+
}
|
|
3307
3522
|
function requireConfigured() {
|
|
3308
3523
|
if (!configured) {
|
|
3309
3524
|
throw new Error(
|
|
@@ -3318,7 +3533,351 @@ function isConfigured() {
|
|
|
3318
3533
|
function reset() {
|
|
3319
3534
|
configured = null;
|
|
3320
3535
|
}
|
|
3321
|
-
const GuideAI = { configure, identify, setUserProfile, setToolContext, isConfigured, reset };
|
|
3536
|
+
const GuideAI = { configure, identify, setUserProfile, setToolContext, setFollowUps, isConfigured, reset };
|
|
3537
|
+
const LIMITS = {
|
|
3538
|
+
steps: 12,
|
|
3539
|
+
itemsPerStep: 8,
|
|
3540
|
+
items: 60,
|
|
3541
|
+
say: 300,
|
|
3542
|
+
text: 60,
|
|
3543
|
+
art: 80,
|
|
3544
|
+
title: 80,
|
|
3545
|
+
freePoints: 32,
|
|
3546
|
+
tableRows: 6,
|
|
3547
|
+
tableCols: 4,
|
|
3548
|
+
cell: 24,
|
|
3549
|
+
artContours: 400,
|
|
3550
|
+
contourChars: 2e4
|
|
3551
|
+
};
|
|
3552
|
+
const INK_KINDS = [
|
|
3553
|
+
"line",
|
|
3554
|
+
"arrow",
|
|
3555
|
+
"poly",
|
|
3556
|
+
"curve",
|
|
3557
|
+
"free",
|
|
3558
|
+
"oval",
|
|
3559
|
+
"corner",
|
|
3560
|
+
"arc",
|
|
3561
|
+
"dot",
|
|
3562
|
+
"circle",
|
|
3563
|
+
"box",
|
|
3564
|
+
"underline",
|
|
3565
|
+
"cross",
|
|
3566
|
+
"tick",
|
|
3567
|
+
"bracket"
|
|
3568
|
+
];
|
|
3569
|
+
const POINT_INKS = ["poly", "curve", "free", "corner", "arc"];
|
|
3570
|
+
const BOARD_W = 160;
|
|
3571
|
+
const BOARD_H = 100;
|
|
3572
|
+
const POINT_MARKS = ["circle", "underline", "box"];
|
|
3573
|
+
class SceneError extends Error {
|
|
3574
|
+
constructor() {
|
|
3575
|
+
super(...arguments);
|
|
3576
|
+
this.name = "SceneError";
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
const ID = /^[A-Za-z0-9_-]{1,24}$/;
|
|
3580
|
+
const SIZES = ["s", "m", "l"];
|
|
3581
|
+
const TONES = ["ink", "blue", "red", "green"];
|
|
3582
|
+
const PATH_DATA = /^[MmLlHhVvCcSsQqTtAaZz0-9eE.,\s+-]*$/;
|
|
3583
|
+
const flat = (value, max) => typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, max) : "";
|
|
3584
|
+
const clamp = (n, top = BOARD_H) => Math.round(Math.min(top, Math.max(0, n)) * 10) / 10;
|
|
3585
|
+
function num(value) {
|
|
3586
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
3587
|
+
}
|
|
3588
|
+
let wide = 1;
|
|
3589
|
+
function point(raw) {
|
|
3590
|
+
if (!Array.isArray(raw) || raw.length !== 2) return null;
|
|
3591
|
+
const [x, y] = raw.map(num);
|
|
3592
|
+
return x === null || y === null ? null : [clamp(x * wide, BOARD_W), clamp(y)];
|
|
3593
|
+
}
|
|
3594
|
+
function box(raw) {
|
|
3595
|
+
if (!Array.isArray(raw) || raw.length !== 4) return null;
|
|
3596
|
+
const v = raw.map(num);
|
|
3597
|
+
if (v.some((n) => n === null)) return null;
|
|
3598
|
+
const x = clamp(v[0] * wide, BOARD_W);
|
|
3599
|
+
const y = clamp(v[1]);
|
|
3600
|
+
const w = Math.min(Math.max(1, v[2] * wide), BOARD_W - x);
|
|
3601
|
+
const h = Math.min(Math.max(1, v[3]), BOARD_H - y);
|
|
3602
|
+
return w >= 1 && h >= 1 ? [x, y, w, h] : null;
|
|
3603
|
+
}
|
|
3604
|
+
function tone(raw) {
|
|
3605
|
+
return typeof raw === "string" && TONES.includes(raw) ? raw : "ink";
|
|
3606
|
+
}
|
|
3607
|
+
function id(raw) {
|
|
3608
|
+
return typeof raw === "string" && ID.test(raw) ? raw : void 0;
|
|
3609
|
+
}
|
|
3610
|
+
function item(raw) {
|
|
3611
|
+
var _a;
|
|
3612
|
+
if (!raw || typeof raw !== "object") return null;
|
|
3613
|
+
const r = raw;
|
|
3614
|
+
const kinds = ["art", "text", "ink", "rows", "mark", "erase", "point"].filter((k) => r[k] !== void 0 && r[k] !== null && r[k] !== "");
|
|
3615
|
+
if (kinds.length !== 1) return null;
|
|
3616
|
+
switch (kinds[0]) {
|
|
3617
|
+
case "art": {
|
|
3618
|
+
const at = box(r.at);
|
|
3619
|
+
const art = flat(r.art, LIMITS.art);
|
|
3620
|
+
return at && art ? { kind: "art", id: id(r.id), art, at, tone: tone(r.tone) } : null;
|
|
3621
|
+
}
|
|
3622
|
+
case "text": {
|
|
3623
|
+
const at = point(Array.isArray(r.at) ? r.at.slice(0, 2) : null);
|
|
3624
|
+
const text = flat(r.text, LIMITS.text);
|
|
3625
|
+
const size = typeof r.size === "string" && SIZES.includes(r.size) ? r.size : "m";
|
|
3626
|
+
return at && text ? { kind: "text", id: id(r.id), text, at, size, tone: tone(r.tone) } : null;
|
|
3627
|
+
}
|
|
3628
|
+
case "ink": {
|
|
3629
|
+
const ink = r.ink;
|
|
3630
|
+
if (!INK_KINDS.includes(ink)) return null;
|
|
3631
|
+
const base = { kind: "ink", id: id(r.id), ink, tone: tone(r.tone) };
|
|
3632
|
+
if (POINT_INKS.includes(ink)) {
|
|
3633
|
+
const pts = Array.isArray(r.pts) ? r.pts.slice(0, LIMITS.freePoints).map(point).filter((p) => !!p) : [];
|
|
3634
|
+
if (ink === "corner" || ink === "arc") return pts.length === 3 ? { ...base, pts } : null;
|
|
3635
|
+
if (pts.length < 2) return null;
|
|
3636
|
+
return ink === "poly" && r.closed === true ? { ...base, pts, closed: true } : { ...base, pts };
|
|
3637
|
+
}
|
|
3638
|
+
if (ink === "dot") {
|
|
3639
|
+
const at2 = point(r.at);
|
|
3640
|
+
return at2 ? { ...base, at: at2 } : null;
|
|
3641
|
+
}
|
|
3642
|
+
if (ink === "line" || ink === "arrow") {
|
|
3643
|
+
const at2 = point(r.at);
|
|
3644
|
+
const to = point(r.to);
|
|
3645
|
+
return at2 && to ? { ...base, at: at2, to } : null;
|
|
3646
|
+
}
|
|
3647
|
+
const at = box(r.at);
|
|
3648
|
+
return at ? { ...base, at } : null;
|
|
3649
|
+
}
|
|
3650
|
+
case "rows": {
|
|
3651
|
+
if (!Array.isArray(r.rows) || !Array.isArray(r.at) || r.at.length < 2) return null;
|
|
3652
|
+
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)));
|
|
3653
|
+
const at = point(r.at.slice(0, 2));
|
|
3654
|
+
if (!rows.length || !at) return null;
|
|
3655
|
+
const width = ((_a = num(r.at[2])) != null ? _a : 40) * wide;
|
|
3656
|
+
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) };
|
|
3657
|
+
}
|
|
3658
|
+
case "mark": {
|
|
3659
|
+
const mark = id(r.mark);
|
|
3660
|
+
return mark ? { kind: "mark", mark } : null;
|
|
3661
|
+
}
|
|
3662
|
+
case "erase": {
|
|
3663
|
+
const erase = id(r.erase);
|
|
3664
|
+
return erase ? { kind: "erase", erase } : null;
|
|
3665
|
+
}
|
|
3666
|
+
case "point": {
|
|
3667
|
+
const target = id(r.point);
|
|
3668
|
+
const as = typeof r.as === "string" && POINT_MARKS.includes(r.as) ? r.as : "circle";
|
|
3669
|
+
return target ? { kind: "point", point: target, as } : null;
|
|
3670
|
+
}
|
|
3671
|
+
default:
|
|
3672
|
+
return null;
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
function artInk(raw) {
|
|
3676
|
+
if (!raw || typeof raw !== "object") return null;
|
|
3677
|
+
const r = raw;
|
|
3678
|
+
if (typeof r.icon === "string") return /^[a-z]{1,20}$/.test(r.icon) ? { icon: r.icon } : null;
|
|
3679
|
+
if (!Array.isArray(r.contours)) return null;
|
|
3680
|
+
const contours = r.contours.slice(0, LIMITS.artContours).filter((d) => typeof d === "string" && d.length <= LIMITS.contourChars && PATH_DATA.test(d));
|
|
3681
|
+
const viewBox = typeof r.view_box === "string" && /^[\d.\s-]+$/.test(r.view_box) ? r.view_box : "0 0 100 100";
|
|
3682
|
+
const transform = typeof r.transform === "string" && /^[a-z()\d.,\s-]*$/i.test(r.transform) ? r.transform : "";
|
|
3683
|
+
return contours.length ? { view_box: viewBox, transform, contours } : null;
|
|
3684
|
+
}
|
|
3685
|
+
function validateScene(raw) {
|
|
3686
|
+
if (!raw || typeof raw !== "object") throw new SceneError("A scene is an object.");
|
|
3687
|
+
const r = raw;
|
|
3688
|
+
if (!Array.isArray(r.steps) || r.steps.length === 0) throw new SceneError("A scene needs steps.");
|
|
3689
|
+
if (r.steps.length > LIMITS.steps) throw new SceneError(`A scene has at most ${LIMITS.steps} steps.`);
|
|
3690
|
+
wide = r.v === 3 ? 1 : BOARD_W / 100;
|
|
3691
|
+
let total = 0;
|
|
3692
|
+
const steps = [];
|
|
3693
|
+
let onBoard = /* @__PURE__ */ new Set();
|
|
3694
|
+
for (const rawStep of r.steps) {
|
|
3695
|
+
if (!rawStep || typeof rawStep !== "object") continue;
|
|
3696
|
+
const s = rawStep;
|
|
3697
|
+
const clear = s.clear === true;
|
|
3698
|
+
if (clear) onBoard = /* @__PURE__ */ new Set();
|
|
3699
|
+
const draw = [];
|
|
3700
|
+
const items = Array.isArray(s.draw) ? s.draw.slice(0, LIMITS.itemsPerStep) : [];
|
|
3701
|
+
for (const rawItem of items) {
|
|
3702
|
+
if (total >= LIMITS.items) break;
|
|
3703
|
+
const it = item(rawItem);
|
|
3704
|
+
if (!it) continue;
|
|
3705
|
+
if (it.kind === "mark" && !onBoard.has(it.mark)) continue;
|
|
3706
|
+
if (it.kind === "erase") {
|
|
3707
|
+
if (!onBoard.has(it.erase)) continue;
|
|
3708
|
+
onBoard.delete(it.erase);
|
|
3709
|
+
}
|
|
3710
|
+
if ("id" in it && it.id) onBoard.add(it.id);
|
|
3711
|
+
draw.push(it);
|
|
3712
|
+
total += 1;
|
|
3713
|
+
}
|
|
3714
|
+
const say = flat(s.say, LIMITS.say);
|
|
3715
|
+
if (!say && !draw.length) continue;
|
|
3716
|
+
steps.push({ say, clear, draw });
|
|
3717
|
+
}
|
|
3718
|
+
if (!steps.length) throw new SceneError("Nothing in this scene can be drawn.");
|
|
3719
|
+
const art = {};
|
|
3720
|
+
if (r.art && typeof r.art === "object") {
|
|
3721
|
+
for (const [name, value] of Object.entries(r.art)) {
|
|
3722
|
+
const ink = artInk(value);
|
|
3723
|
+
if (ink) art[name.slice(0, LIMITS.art)] = ink;
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
return {
|
|
3727
|
+
v: 3,
|
|
3728
|
+
title: flat(r.title, LIMITS.title) || "Explanation",
|
|
3729
|
+
sample: r.sample === true,
|
|
3730
|
+
steps,
|
|
3731
|
+
art
|
|
3732
|
+
};
|
|
3733
|
+
}
|
|
3734
|
+
const BLOCKS_PATH = "/api/v1/chat/blocks";
|
|
3735
|
+
const WHITEBOARD_PATH = "/api/v1/chat/whiteboard";
|
|
3736
|
+
const BLOCKS_TTL_MS = 6e4;
|
|
3737
|
+
const KEEP = 12;
|
|
3738
|
+
const CLOSED = { status: "closed", scene: null, error: null, question: "" };
|
|
3739
|
+
function readableAnswer(text) {
|
|
3740
|
+
return text.replace(/```[a-z]*[ \t]*\n[\s\S]*?```/gi, " ").replace(/\s+/g, " ").trim();
|
|
3741
|
+
}
|
|
3742
|
+
class WhiteboardStore {
|
|
3743
|
+
constructor(api, language = () => void 0, clock = () => Date.now()) {
|
|
3744
|
+
this.api = api;
|
|
3745
|
+
this.language = language;
|
|
3746
|
+
this.clock = clock;
|
|
3747
|
+
this.state = CLOSED;
|
|
3748
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
3749
|
+
this.kept = /* @__PURE__ */ new Map();
|
|
3750
|
+
this.blocks = null;
|
|
3751
|
+
this.blocksPending = null;
|
|
3752
|
+
this.request = 0;
|
|
3753
|
+
this.getState = () => this.state;
|
|
3754
|
+
this.subscribe = (listener) => {
|
|
3755
|
+
this.listeners.add(listener);
|
|
3756
|
+
return () => this.listeners.delete(listener);
|
|
3757
|
+
};
|
|
3758
|
+
}
|
|
3759
|
+
/** Whether the Blueprint has the whiteboard. False when it cannot be asked. */
|
|
3760
|
+
async available() {
|
|
3761
|
+
var _a;
|
|
3762
|
+
if (this.blocks && this.clock() - this.blocks.at < BLOCKS_TTL_MS) return this.blocks.on;
|
|
3763
|
+
(_a = this.blocksPending) != null ? _a : this.blocksPending = this.api().get(BLOCKS_PATH, 1e4).then((res) => {
|
|
3764
|
+
var _a2;
|
|
3765
|
+
return ((_a2 = res == null ? void 0 : res.blocks) == null ? void 0 : _a2.whiteboard) === true;
|
|
3766
|
+
}, () => false).then((on) => {
|
|
3767
|
+
this.blocks = { at: this.clock(), on };
|
|
3768
|
+
this.blocksPending = null;
|
|
3769
|
+
return on;
|
|
3770
|
+
});
|
|
3771
|
+
return this.blocksPending;
|
|
3772
|
+
}
|
|
3773
|
+
/** Explain *question* (and the answer on screen) on the board. */
|
|
3774
|
+
async explain(question, answer) {
|
|
3775
|
+
const q = question.trim().slice(0, 500);
|
|
3776
|
+
if (!q) return false;
|
|
3777
|
+
const a = answer ? readableAnswer(answer).slice(0, 4e3) : void 0;
|
|
3778
|
+
const key = `${q}\0${a != null ? a : ""}`;
|
|
3779
|
+
const known = this.kept.get(key);
|
|
3780
|
+
if (known) {
|
|
3781
|
+
this.set({ status: "playing", scene: known, error: null, question: q, answer: a });
|
|
3782
|
+
return true;
|
|
3783
|
+
}
|
|
3784
|
+
const token = ++this.request;
|
|
3785
|
+
this.set({ status: "loading", scene: null, error: null, question: q, answer: a });
|
|
3786
|
+
try {
|
|
3787
|
+
const raw = await this.api().post(
|
|
3788
|
+
WHITEBOARD_PATH,
|
|
3789
|
+
{ question: q, answer: a || void 0, language: this.language() },
|
|
3790
|
+
6e4
|
|
3791
|
+
);
|
|
3792
|
+
if (token !== this.request) return false;
|
|
3793
|
+
const scene = validateScene(raw);
|
|
3794
|
+
this.keep(key, scene);
|
|
3795
|
+
this.set({ status: "playing", scene, error: null, question: q, answer: a });
|
|
3796
|
+
return true;
|
|
3797
|
+
} catch (err) {
|
|
3798
|
+
if (token !== this.request) return false;
|
|
3799
|
+
this.set({
|
|
3800
|
+
status: "error",
|
|
3801
|
+
scene: null,
|
|
3802
|
+
error: err instanceof SceneError ? "This board could not be drawn." : "The whiteboard is not available right now.",
|
|
3803
|
+
question: q,
|
|
3804
|
+
answer: a
|
|
3805
|
+
});
|
|
3806
|
+
return false;
|
|
3807
|
+
}
|
|
3808
|
+
}
|
|
3809
|
+
/** Ask again after an error. */
|
|
3810
|
+
retry() {
|
|
3811
|
+
if (this.state.status === "error") void this.explain(this.state.question, this.state.answer);
|
|
3812
|
+
}
|
|
3813
|
+
/** Play a board the host built. A board that cannot be drawn throws SceneError. */
|
|
3814
|
+
play(scene) {
|
|
3815
|
+
const valid = validateScene(scene);
|
|
3816
|
+
this.request += 1;
|
|
3817
|
+
this.set({ status: "playing", scene: valid, error: null, question: valid.title });
|
|
3818
|
+
}
|
|
3819
|
+
close() {
|
|
3820
|
+
this.request += 1;
|
|
3821
|
+
this.set(CLOSED);
|
|
3822
|
+
}
|
|
3823
|
+
keep(key, scene) {
|
|
3824
|
+
this.kept.delete(key);
|
|
3825
|
+
this.kept.set(key, scene);
|
|
3826
|
+
while (this.kept.size > KEEP) {
|
|
3827
|
+
const oldest = this.kept.keys().next().value;
|
|
3828
|
+
if (oldest === void 0) break;
|
|
3829
|
+
this.kept.delete(oldest);
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
set(next2) {
|
|
3833
|
+
this.state = next2;
|
|
3834
|
+
for (const listener of [...this.listeners]) listener();
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
let store = null;
|
|
3838
|
+
let owner = null;
|
|
3839
|
+
function whiteboardStore() {
|
|
3840
|
+
const configured2 = requireConfigured();
|
|
3841
|
+
if (!store || owner !== configured2) {
|
|
3842
|
+
store == null ? void 0 : store.close();
|
|
3843
|
+
owner = configured2;
|
|
3844
|
+
store = new WhiteboardStore(
|
|
3845
|
+
() => configured2.api,
|
|
3846
|
+
() => {
|
|
3847
|
+
var _a;
|
|
3848
|
+
const language = (_a = configured2.profile) == null ? void 0 : _a.language;
|
|
3849
|
+
return typeof language === "string" && language ? language : void 0;
|
|
3850
|
+
}
|
|
3851
|
+
);
|
|
3852
|
+
}
|
|
3853
|
+
return store;
|
|
3854
|
+
}
|
|
3855
|
+
const IDLE = new WhiteboardStore(() => {
|
|
3856
|
+
throw new Error("Call GuideAI.configure() before using the whiteboard.");
|
|
3857
|
+
});
|
|
3858
|
+
function useWhiteboard() {
|
|
3859
|
+
const board = GuideAI.isConfigured() ? whiteboardStore() : IDLE;
|
|
3860
|
+
const state = useSyncExternalStore(board.subscribe, board.getState, board.getState);
|
|
3861
|
+
const [available, setAvailable] = useState(false);
|
|
3862
|
+
useEffect(() => {
|
|
3863
|
+
if (board === IDLE) return;
|
|
3864
|
+
let live = true;
|
|
3865
|
+
void board.available().then((on) => {
|
|
3866
|
+
if (live) setAvailable(on);
|
|
3867
|
+
});
|
|
3868
|
+
return () => {
|
|
3869
|
+
live = false;
|
|
3870
|
+
};
|
|
3871
|
+
}, [board]);
|
|
3872
|
+
return {
|
|
3873
|
+
available,
|
|
3874
|
+
state,
|
|
3875
|
+
explain: useCallback((question, answer) => board.explain(question, answer), [board]),
|
|
3876
|
+
play: useCallback((scene) => board.play(scene), [board]),
|
|
3877
|
+
retry: useCallback(() => board.retry(), [board]),
|
|
3878
|
+
close: useCallback(() => board.close(), [board])
|
|
3879
|
+
};
|
|
3880
|
+
}
|
|
3322
3881
|
const AUDIO_TYPES = {
|
|
3323
3882
|
m4a: "audio/m4a",
|
|
3324
3883
|
mp4: "audio/mp4",
|
|
@@ -3349,6 +3908,10 @@ function replyFields(result, streamed) {
|
|
|
3349
3908
|
}
|
|
3350
3909
|
let nextId = 0;
|
|
3351
3910
|
const nextMessageId = () => `m${nextId += 1}`;
|
|
3911
|
+
function questionBefore(entries, index) {
|
|
3912
|
+
for (let i = index - 1; i >= 0; i -= 1) if (entries[i].role === "user") return entries[i].content;
|
|
3913
|
+
return void 0;
|
|
3914
|
+
}
|
|
3352
3915
|
function answerText(result, fallback) {
|
|
3353
3916
|
var _a, _b;
|
|
3354
3917
|
const answer = ((_a = result.answer) != null ? _a : "").trim();
|
|
@@ -3362,12 +3925,16 @@ function answerText(result, fallback) {
|
|
|
3362
3925
|
}
|
|
3363
3926
|
const FAILURE_MESSAGE = "I'm sorry, I can't complete your request right now. Would you like to talk to a human?";
|
|
3364
3927
|
function useGuideAI(options = {}) {
|
|
3365
|
-
var _a, _b;
|
|
3928
|
+
var _a, _b, _c, _d;
|
|
3366
3929
|
const runtime = useGuideAIRuntime();
|
|
3367
3930
|
const configured2 = requireConfigured();
|
|
3368
3931
|
const harness = (_a = options.harness) != null ? _a : configured2.harness;
|
|
3369
3932
|
const trace = (_b = options.trace) != null ? _b : configured2.debug;
|
|
3933
|
+
const defaultFollowUps = (_c = options.followUps) != null ? _c : configured2.followUps;
|
|
3370
3934
|
const mode = "assistant";
|
|
3935
|
+
const board = useWhiteboard();
|
|
3936
|
+
const library = configured2.conversations;
|
|
3937
|
+
const { version } = useConversationSnapshot(library);
|
|
3371
3938
|
const [messages, setMessages] = useState([]);
|
|
3372
3939
|
const [input, setInput] = useState("");
|
|
3373
3940
|
const [busy, setBusy] = useState(false);
|
|
@@ -3375,25 +3942,32 @@ function useGuideAI(options = {}) {
|
|
|
3375
3942
|
const [transcribing, setTranscribing] = useState(false);
|
|
3376
3943
|
const lastQuestion = useRef(null);
|
|
3377
3944
|
const pending = useRef(/* @__PURE__ */ new Map());
|
|
3945
|
+
const shownVersion = useRef(null);
|
|
3378
3946
|
const mounted = useRef(true);
|
|
3379
3947
|
useEffect(() => () => {
|
|
3380
3948
|
mounted.current = false;
|
|
3381
3949
|
}, []);
|
|
3382
3950
|
useEffect(() => {
|
|
3383
3951
|
if (typeof harness.hasHistory !== "function" || typeof harness.getConversationHistory !== "function") return;
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
};
|
|
3394
|
-
});
|
|
3952
|
+
const restored = () => (harness.hasHistory() ? harness.getConversationHistory() : []).filter((entry) => typeof entry.content === "string" && entry.content.trim()).map((entry, index, all) => {
|
|
3953
|
+
var _a2;
|
|
3954
|
+
return {
|
|
3955
|
+
id: (_a2 = entry.id) != null ? _a2 : `h${index}`,
|
|
3956
|
+
role: entry.role,
|
|
3957
|
+
content: entry.content,
|
|
3958
|
+
createdAt: typeof entry.timestamp === "number" ? entry.timestamp : Date.now(),
|
|
3959
|
+
question: entry.role === "assistant" ? questionBefore(all, index) : void 0
|
|
3960
|
+
};
|
|
3395
3961
|
});
|
|
3396
|
-
|
|
3962
|
+
if (shownVersion.current === version) {
|
|
3963
|
+
setMessages((previous) => previous.length > 0 ? previous : restored());
|
|
3964
|
+
return;
|
|
3965
|
+
}
|
|
3966
|
+
shownVersion.current = version;
|
|
3967
|
+
pending.current.clear();
|
|
3968
|
+
lastQuestion.current = null;
|
|
3969
|
+
setMessages(restored());
|
|
3970
|
+
}, [harness, version]);
|
|
3397
3971
|
const initialized = useRef(null);
|
|
3398
3972
|
const ensureInitialized = useCallback(() => {
|
|
3399
3973
|
if (!initialized.current) initialized.current = harness.initialize();
|
|
@@ -3418,40 +3992,45 @@ function useGuideAI(options = {}) {
|
|
|
3418
3992
|
if (result.confirmationNeeded && result.pendingToolCall) {
|
|
3419
3993
|
pending.current.set(replyId, { call: result.pendingToolCall, question });
|
|
3420
3994
|
}
|
|
3421
|
-
|
|
3422
|
-
|
|
3995
|
+
library.touch();
|
|
3996
|
+
const reply = replyFields(result, streamed);
|
|
3997
|
+
if (!mounted.current) return reply.content;
|
|
3998
|
+
setMessages((prev) => prev.map((message) => message.id === replyId ? { ...message, ...reply, streaming: false } : message));
|
|
3999
|
+
return reply.content;
|
|
3423
4000
|
} catch (error) {
|
|
3424
4001
|
console.log("[GuideAI] ✗ turn failed:", error);
|
|
3425
4002
|
if (error instanceof Error && error.stack) {
|
|
3426
4003
|
console.log("[GuideAI] stack:", error.stack);
|
|
3427
4004
|
}
|
|
3428
|
-
if (!mounted.current) return;
|
|
4005
|
+
if (!mounted.current) return null;
|
|
3429
4006
|
setMessages((prev) => prev.map((message) => message.id === replyId ? {
|
|
3430
4007
|
...message,
|
|
3431
4008
|
content: FAILURE_MESSAGE,
|
|
3432
4009
|
streaming: false,
|
|
3433
4010
|
error: true
|
|
3434
4011
|
} : message));
|
|
4012
|
+
return null;
|
|
3435
4013
|
} finally {
|
|
3436
4014
|
if (mounted.current) {
|
|
3437
4015
|
setBusy(false);
|
|
3438
4016
|
setStatus(null);
|
|
3439
4017
|
}
|
|
3440
4018
|
}
|
|
3441
|
-
}, [runtime, trace]);
|
|
4019
|
+
}, [runtime, trace, library]);
|
|
3442
4020
|
const send = useCallback(async (question) => {
|
|
3443
4021
|
const text = (question != null ? question : input).trim();
|
|
3444
|
-
if (!text || busy) return;
|
|
4022
|
+
if (!text || busy) return null;
|
|
3445
4023
|
lastQuestion.current = text;
|
|
3446
4024
|
if (question === void 0) setInput("");
|
|
3447
4025
|
if (trace) traceUserMessage(text);
|
|
3448
4026
|
const replyId = nextMessageId();
|
|
4027
|
+
const now = Date.now();
|
|
3449
4028
|
setMessages((prev) => [
|
|
3450
4029
|
...prev,
|
|
3451
|
-
{ id: nextMessageId(), role: "user", content: text },
|
|
3452
|
-
{ id: replyId, role: "assistant", content: "", streaming: true }
|
|
4030
|
+
{ id: nextMessageId(), role: "user", content: text, createdAt: now },
|
|
4031
|
+
{ id: replyId, role: "assistant", content: "", streaming: true, createdAt: now, question: text }
|
|
3453
4032
|
]);
|
|
3454
|
-
|
|
4033
|
+
return runTurn(replyId, text, async (onStatus, onDelta) => {
|
|
3455
4034
|
await ensureInitialized();
|
|
3456
4035
|
const screen = runtime.getActiveScreen();
|
|
3457
4036
|
const { profile, visitorId } = requireConfigured();
|
|
@@ -3479,7 +4058,8 @@ function useGuideAI(options = {}) {
|
|
|
3479
4058
|
setMessages([]);
|
|
3480
4059
|
lastQuestion.current = null;
|
|
3481
4060
|
pending.current.clear();
|
|
3482
|
-
|
|
4061
|
+
library.startNew();
|
|
4062
|
+
}, [library]);
|
|
3483
4063
|
const settleAction = useCallback((messageId) => {
|
|
3484
4064
|
const action = pending.current.get(messageId);
|
|
3485
4065
|
pending.current.delete(messageId);
|
|
@@ -3491,7 +4071,14 @@ function useGuideAI(options = {}) {
|
|
|
3491
4071
|
const action = settleAction(messageId);
|
|
3492
4072
|
if (!action) return;
|
|
3493
4073
|
const replyId = nextMessageId();
|
|
3494
|
-
setMessages((prev) => [...prev, {
|
|
4074
|
+
setMessages((prev) => [...prev, {
|
|
4075
|
+
id: replyId,
|
|
4076
|
+
role: "assistant",
|
|
4077
|
+
content: "",
|
|
4078
|
+
streaming: true,
|
|
4079
|
+
createdAt: Date.now(),
|
|
4080
|
+
question: action.question
|
|
4081
|
+
}]);
|
|
3495
4082
|
await runTurn(replyId, action.question, async (onStatus, onDelta) => {
|
|
3496
4083
|
await ensureInitialized();
|
|
3497
4084
|
return harness.executeToolCall(action.call, action.question, onStatus, onDelta);
|
|
@@ -3499,7 +4086,12 @@ function useGuideAI(options = {}) {
|
|
|
3499
4086
|
}, [busy, settleAction, runTurn, ensureInitialized, harness]);
|
|
3500
4087
|
const cancel = useCallback((messageId) => {
|
|
3501
4088
|
if (!settleAction(messageId)) return;
|
|
3502
|
-
setMessages((prev) => [...prev, {
|
|
4089
|
+
setMessages((prev) => [...prev, {
|
|
4090
|
+
id: nextMessageId(),
|
|
4091
|
+
role: "assistant",
|
|
4092
|
+
content: "Okay, I haven't changed anything.",
|
|
4093
|
+
createdAt: Date.now()
|
|
4094
|
+
}]);
|
|
3503
4095
|
}, [settleAction]);
|
|
3504
4096
|
const sendVoice = useCallback(async (recording) => {
|
|
3505
4097
|
var _a2;
|
|
@@ -3517,8 +4109,8 @@ function useGuideAI(options = {}) {
|
|
|
3517
4109
|
const heard = ((_a2 = result == null ? void 0 : result.text) == null ? void 0 : _a2.trim()) || "";
|
|
3518
4110
|
if (!heard) return { text: null, error: "I didn't catch that. Please try again." };
|
|
3519
4111
|
if (mounted.current) setTranscribing(false);
|
|
3520
|
-
await send(heard);
|
|
3521
|
-
return { text: heard };
|
|
4112
|
+
const answer = await send(heard);
|
|
4113
|
+
return { text: heard, answer };
|
|
3522
4114
|
} catch (error) {
|
|
3523
4115
|
console.log("[GuideAI] ✗ voice transcription failed:", error);
|
|
3524
4116
|
const message = error instanceof UploadError && error.status === 422 ? error.message : "I couldn't process that recording. Please try again or type your message.";
|
|
@@ -3527,8 +4119,26 @@ function useGuideAI(options = {}) {
|
|
|
3527
4119
|
if (mounted.current) setTranscribing(false);
|
|
3528
4120
|
}
|
|
3529
4121
|
}, [busy, transcribing, send]);
|
|
4122
|
+
const shown = useMemo(() => messages.filter((message) => message.content || !message.streaming).map((message) => {
|
|
4123
|
+
var _a2;
|
|
4124
|
+
if (message.role !== "assistant" || message.streaming || message.error || !message.content) return message;
|
|
4125
|
+
const suggestions = (_a2 = message.suggestions) != null ? _a2 : (defaultFollowUps == null ? void 0 : defaultFollowUps.length) ? defaultFollowUps : void 0;
|
|
4126
|
+
return { ...message, suggestions, whiteboard: board.available || void 0 };
|
|
4127
|
+
}), [messages, defaultFollowUps, board.available]);
|
|
4128
|
+
const last = shown[shown.length - 1];
|
|
4129
|
+
const followUps = !busy && (last == null ? void 0 : last.role) === "assistant" && !last.pendingAction ? (_d = last.suggestions) != null ? _d : [] : [];
|
|
4130
|
+
const typing = busy && messages.some((message) => message.streaming && !message.content);
|
|
4131
|
+
const explainOnWhiteboard = useCallback(async (messageId) => {
|
|
4132
|
+
const answer = messages.find((message) => message.id === messageId);
|
|
4133
|
+
if (!answer || answer.role !== "assistant" || !answer.content) return false;
|
|
4134
|
+
return board.explain(answer.question || answer.content.slice(0, 200), answer.content);
|
|
4135
|
+
}, [messages, board]);
|
|
3530
4136
|
return {
|
|
3531
|
-
messages,
|
|
4137
|
+
messages: shown,
|
|
4138
|
+
typing,
|
|
4139
|
+
followUps,
|
|
4140
|
+
whiteboardAvailable: board.available,
|
|
4141
|
+
explainOnWhiteboard,
|
|
3532
4142
|
input,
|
|
3533
4143
|
setInput,
|
|
3534
4144
|
send,
|
|
@@ -3578,15 +4188,31 @@ function useOnboarding() {
|
|
|
3578
4188
|
}, [refresh]);
|
|
3579
4189
|
return { checklist, loading, refresh, dismiss };
|
|
3580
4190
|
}
|
|
4191
|
+
function useConversations() {
|
|
4192
|
+
const library = requireConfigured().conversations;
|
|
4193
|
+
const { conversations, activeId } = useConversationSnapshot(library);
|
|
4194
|
+
return {
|
|
4195
|
+
conversations,
|
|
4196
|
+
activeId,
|
|
4197
|
+
newConversation: useCallback(() => library.startNew(), [library]),
|
|
4198
|
+
openConversation: useCallback((id2) => library.open(id2), [library]),
|
|
4199
|
+
deleteConversation: useCallback((id2) => library.remove(id2), [library])
|
|
4200
|
+
};
|
|
4201
|
+
}
|
|
3581
4202
|
export {
|
|
4203
|
+
BOARD_W as B,
|
|
3582
4204
|
EP as E,
|
|
3583
4205
|
GuideAI as G,
|
|
4206
|
+
LIMITS as L,
|
|
3584
4207
|
RegistryContext as R,
|
|
3585
4208
|
ScreenRegistry as S,
|
|
3586
4209
|
useScreenRegistry as a,
|
|
3587
|
-
|
|
3588
|
-
|
|
4210
|
+
useConversations as b,
|
|
4211
|
+
useGuideAI as c,
|
|
4212
|
+
useOnboarding as d,
|
|
4213
|
+
useWhiteboard as e,
|
|
4214
|
+
BOARD_H as f,
|
|
3589
4215
|
requireConfigured as r,
|
|
3590
4216
|
useGuideAIRuntime as u
|
|
3591
4217
|
};
|
|
3592
|
-
//# sourceMappingURL=
|
|
4218
|
+
//# sourceMappingURL=useConversations-B4WYG2Qz.js.map
|