@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
|
@@ -459,9 +459,9 @@ class ConversationMemory {
|
|
|
459
459
|
* @param store Where history lives. Defaults to memory so core never
|
|
460
460
|
* reaches for a global; the web SDK passes its localStorage adapter.
|
|
461
461
|
*/
|
|
462
|
-
constructor(siteId, ttlMs, maxMessages,
|
|
462
|
+
constructor(siteId, ttlMs, maxMessages, store2 = new MemoryKVStore()) {
|
|
463
463
|
this.listener = null;
|
|
464
|
-
this.store =
|
|
464
|
+
this.store = store2;
|
|
465
465
|
this.storageKey = `guideai_chat_${siteId}`;
|
|
466
466
|
this.ttlMs = ttlMs != null ? ttlMs : DEFAULT_TTL_MS;
|
|
467
467
|
this.maxMessages = maxMessages != null ? maxMessages : DEFAULT_MAX_MESSAGES;
|
|
@@ -557,16 +557,16 @@ class ConversationMemory {
|
|
|
557
557
|
}
|
|
558
558
|
if (Array.isArray(cleaned)) {
|
|
559
559
|
const total = cleaned.length;
|
|
560
|
-
const pickFields = (
|
|
561
|
-
if (typeof
|
|
562
|
-
const obj =
|
|
560
|
+
const pickFields = (item2) => {
|
|
561
|
+
if (typeof item2 === "object" && item2 !== null) {
|
|
562
|
+
const obj = item2;
|
|
563
563
|
const picked = {};
|
|
564
564
|
for (const key of ["name", "id", "title", "path", "endpoint", "url", "type", "method", "label", "slug", "status"]) {
|
|
565
565
|
if (key in obj) picked[key] = obj[key];
|
|
566
566
|
}
|
|
567
567
|
return Object.keys(picked).length > 0 ? picked : Object.keys(obj).slice(0, 4).reduce((acc, k) => ({ ...acc, [k]: obj[k] }), {});
|
|
568
568
|
}
|
|
569
|
-
return
|
|
569
|
+
return item2;
|
|
570
570
|
};
|
|
571
571
|
const compactItems = cleaned.map(pickFields);
|
|
572
572
|
let itemsToShow = compactItems;
|
|
@@ -601,7 +601,7 @@ class ConversationMemory {
|
|
|
601
601
|
_stripSensitiveFields(data, depth = 0) {
|
|
602
602
|
if (depth > 5) return data;
|
|
603
603
|
if (Array.isArray(data)) {
|
|
604
|
-
return data.slice(0, 50).map((
|
|
604
|
+
return data.slice(0, 50).map((item2) => this._stripSensitiveFields(item2, depth + 1));
|
|
605
605
|
}
|
|
606
606
|
if (typeof data === "object" && data !== null) {
|
|
607
607
|
const result = {};
|
|
@@ -806,9 +806,9 @@ class ToolExecutor {
|
|
|
806
806
|
var _a, _b, _c, _d, _e;
|
|
807
807
|
if (typeof entry === "string") return entry.trim() || null;
|
|
808
808
|
if (!entry || typeof entry !== "object") return null;
|
|
809
|
-
const
|
|
810
|
-
const message = (_c = (_b = (_a =
|
|
811
|
-
const location = Array.isArray(
|
|
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;
|
|
812
812
|
if (!message) return location ? `${location}: invalid` : null;
|
|
813
813
|
return location ? `${location}: ${message}` : String(message);
|
|
814
814
|
}
|
|
@@ -2374,8 +2374,8 @@ class RNHttpTransport {
|
|
|
2374
2374
|
}
|
|
2375
2375
|
}
|
|
2376
2376
|
class NativeKVStore {
|
|
2377
|
-
constructor(
|
|
2378
|
-
this.store =
|
|
2377
|
+
constructor(store2) {
|
|
2378
|
+
this.store = store2;
|
|
2379
2379
|
}
|
|
2380
2380
|
getItem(key) {
|
|
2381
2381
|
var _a;
|
|
@@ -2564,8 +2564,8 @@ class ScreenRegistry {
|
|
|
2564
2564
|
}
|
|
2565
2565
|
};
|
|
2566
2566
|
}
|
|
2567
|
-
get(
|
|
2568
|
-
return this.elements.get(
|
|
2567
|
+
get(id2) {
|
|
2568
|
+
return this.elements.get(id2);
|
|
2569
2569
|
}
|
|
2570
2570
|
/** Resolve by id first, then by visible label — the model may send either. */
|
|
2571
2571
|
find(request) {
|
|
@@ -3031,6 +3031,44 @@ class RNApiClient {
|
|
|
3031
3031
|
}
|
|
3032
3032
|
return parsed;
|
|
3033
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
|
+
}
|
|
3034
3072
|
async postRaw(path, body, signal) {
|
|
3035
3073
|
const response = await this.transport.request({
|
|
3036
3074
|
url: this.url(path),
|
|
@@ -3106,48 +3144,48 @@ function traceApi(api) {
|
|
|
3106
3144
|
return {
|
|
3107
3145
|
supportsStreaming: api.supportsStreaming,
|
|
3108
3146
|
async get(path, timeoutMs) {
|
|
3109
|
-
const
|
|
3110
|
-
line("→", `#${
|
|
3147
|
+
const id2 = next();
|
|
3148
|
+
line("→", `#${id2} GET ${path}`);
|
|
3111
3149
|
try {
|
|
3112
3150
|
const result = await api.get(path, timeoutMs);
|
|
3113
|
-
dump(`[${stamp()}] ← #${
|
|
3151
|
+
dump(`[${stamp()}] ← #${id2} GET ${path} responded:`, result);
|
|
3114
3152
|
return result;
|
|
3115
3153
|
} catch (error) {
|
|
3116
|
-
line("✗", `#${
|
|
3154
|
+
line("✗", `#${id2} GET ${path} FAILED: ${describeError(error)}`);
|
|
3117
3155
|
throw error;
|
|
3118
3156
|
}
|
|
3119
3157
|
},
|
|
3120
3158
|
async post(path, body, timeoutMs) {
|
|
3121
|
-
const
|
|
3122
|
-
dump(`[${stamp()}] → #${
|
|
3159
|
+
const id2 = next();
|
|
3160
|
+
dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
|
|
3123
3161
|
try {
|
|
3124
3162
|
const result = await api.post(path, body, timeoutMs);
|
|
3125
|
-
dump(`[${stamp()}] ← #${
|
|
3163
|
+
dump(`[${stamp()}] ← #${id2} POST ${path} responded:`, result);
|
|
3126
3164
|
return result;
|
|
3127
3165
|
} catch (error) {
|
|
3128
|
-
line("✗", `#${
|
|
3166
|
+
line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
|
|
3129
3167
|
throw error;
|
|
3130
3168
|
}
|
|
3131
3169
|
},
|
|
3132
3170
|
async postRaw(path, body, signal) {
|
|
3133
3171
|
var _a;
|
|
3134
|
-
const
|
|
3135
|
-
dump(`[${stamp()}] → #${
|
|
3172
|
+
const id2 = next();
|
|
3173
|
+
dump(`[${stamp()}] → #${id2} POST ${path} body:`, body);
|
|
3136
3174
|
try {
|
|
3137
3175
|
const response = await api.postRaw(path, body, signal);
|
|
3138
|
-
line("←", `#${
|
|
3176
|
+
line("←", `#${id2} ${response.status} ${path} (${(_a = response.headers.get("content-type")) != null ? _a : "no content-type"})`);
|
|
3139
3177
|
if (response.stream) {
|
|
3140
|
-
return { ...response, stream: teeStream(response.stream,
|
|
3178
|
+
return { ...response, stream: teeStream(response.stream, id2) };
|
|
3141
3179
|
}
|
|
3142
3180
|
return response;
|
|
3143
3181
|
} catch (error) {
|
|
3144
|
-
line("✗", `#${
|
|
3182
|
+
line("✗", `#${id2} POST ${path} FAILED: ${describeError(error)}`);
|
|
3145
3183
|
throw error;
|
|
3146
3184
|
}
|
|
3147
3185
|
}
|
|
3148
3186
|
};
|
|
3149
3187
|
}
|
|
3150
|
-
function teeStream(stream,
|
|
3188
|
+
function teeStream(stream, id2) {
|
|
3151
3189
|
return {
|
|
3152
3190
|
async *[Symbol.asyncIterator]() {
|
|
3153
3191
|
var _a;
|
|
@@ -3158,12 +3196,12 @@ function teeStream(stream, id) {
|
|
|
3158
3196
|
buffer = (_a = parts.pop()) != null ? _a : "";
|
|
3159
3197
|
for (const frame of parts) {
|
|
3160
3198
|
const trimmed = frame.trim();
|
|
3161
|
-
if (trimmed) console.log(`[${stamp()}] ⋯ #${
|
|
3199
|
+
if (trimmed) console.log(`[${stamp()}] ⋯ #${id2} frame: ${trimmed}`);
|
|
3162
3200
|
}
|
|
3163
3201
|
yield chunk;
|
|
3164
3202
|
}
|
|
3165
|
-
if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${
|
|
3166
|
-
line("⋯", `#${
|
|
3203
|
+
if (buffer.trim()) console.log(`[${stamp()}] ⋯ #${id2} frame: ${buffer.trim()}`);
|
|
3204
|
+
line("⋯", `#${id2} stream ended`);
|
|
3167
3205
|
}
|
|
3168
3206
|
};
|
|
3169
3207
|
}
|
|
@@ -3172,18 +3210,18 @@ function traceTransport(transport) {
|
|
|
3172
3210
|
supportsStreaming: transport.supportsStreaming,
|
|
3173
3211
|
async request(req) {
|
|
3174
3212
|
var _a;
|
|
3175
|
-
const
|
|
3213
|
+
const id2 = next();
|
|
3176
3214
|
console.log(
|
|
3177
|
-
`[${stamp()}] ⇢ #${
|
|
3215
|
+
`[${stamp()}] ⇢ #${id2} ${req.method} ${req.url}
|
|
3178
3216
|
headers: ${JSON.stringify(req.headers)}
|
|
3179
3217
|
body: ${(_a = req.body) != null ? _a : "(none)"}`
|
|
3180
3218
|
);
|
|
3181
3219
|
try {
|
|
3182
3220
|
const response = await transport.request(req);
|
|
3183
|
-
line("⇠", `#${
|
|
3221
|
+
line("⇠", `#${id2} ${response.status} ${req.url}`);
|
|
3184
3222
|
return response;
|
|
3185
3223
|
} catch (error) {
|
|
3186
|
-
line("✗", `#${
|
|
3224
|
+
line("✗", `#${id2} ${req.method} ${req.url} FAILED: ${describeError(error)}`);
|
|
3187
3225
|
throw error;
|
|
3188
3226
|
}
|
|
3189
3227
|
}
|
|
@@ -3244,10 +3282,174 @@ ${text}`);
|
|
|
3244
3282
|
console.log(`${"═".repeat(60)}
|
|
3245
3283
|
`);
|
|
3246
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
|
+
}
|
|
3247
3448
|
const DEFAULT_BASE_URL = "https://cdn.3guideai.com";
|
|
3449
|
+
const CONVERSATION_TTL_MS = 365 * 24 * 60 * 60 * 1e3;
|
|
3248
3450
|
let configured = null;
|
|
3249
3451
|
function configure(config) {
|
|
3250
|
-
var _a, _b, _c, _d, _e, _f;
|
|
3452
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
3251
3453
|
const debug = (_a = config.debug) != null ? _a : false;
|
|
3252
3454
|
const baseApi = new RNApiClient({
|
|
3253
3455
|
baseUrl: (_b = config.baseUrl) != null ? _b : DEFAULT_BASE_URL,
|
|
@@ -3255,9 +3457,10 @@ function configure(config) {
|
|
|
3255
3457
|
requestOrigin: config.origin,
|
|
3256
3458
|
agent: ((_c = config.agent) == null ? void 0 : _c.trim()) || void 0
|
|
3257
3459
|
});
|
|
3460
|
+
const hydrated = !config.store && config.storage ? new HydratedStore(config.storage) : null;
|
|
3258
3461
|
const runtime = new GuideAIRuntime({
|
|
3259
3462
|
requestOrigin: config.origin,
|
|
3260
|
-
store: config.store,
|
|
3463
|
+
store: (_e = (_d = config.store) != null ? _d : hydrated) != null ? _e : void 0,
|
|
3261
3464
|
auth: {
|
|
3262
3465
|
getAuthToken: config.getAuthToken,
|
|
3263
3466
|
onAuthExpired: config.onAuthExpired,
|
|
@@ -3268,15 +3471,13 @@ function configure(config) {
|
|
|
3268
3471
|
) : void 0
|
|
3269
3472
|
});
|
|
3270
3473
|
configureGuideAI(runtime);
|
|
3474
|
+
const scope = ((_f = config.agent) == null ? void 0 : _f.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey;
|
|
3271
3475
|
const harness = new CopilotHarness(
|
|
3272
3476
|
debug ? traceApi(baseApi) : baseApi,
|
|
3273
3477
|
{
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
// read each other's conversation.
|
|
3278
|
-
siteId: ((_d = config.agent) == null ? void 0 : _d.trim()) ? `${config.apiKey}:${config.agent.trim()}` : config.apiKey,
|
|
3279
|
-
assistantLabel: config.assistantName
|
|
3478
|
+
siteId: scope,
|
|
3479
|
+
assistantLabel: config.assistantName,
|
|
3480
|
+
memoryTtlMs: CONVERSATION_TTL_MS
|
|
3280
3481
|
},
|
|
3281
3482
|
debug ? traceTools(runtime.tools) : runtime.tools,
|
|
3282
3483
|
runtime.storage,
|
|
@@ -3284,14 +3485,20 @@ function configure(config) {
|
|
|
3284
3485
|
runtime.credentials
|
|
3285
3486
|
);
|
|
3286
3487
|
if (config.toolContext) harness.setToolContext(config.toolContext);
|
|
3488
|
+
const conversations = new ConversationLibrary(runtime.storage, `guideai_chat_${scope}`, scope);
|
|
3287
3489
|
configured = {
|
|
3288
3490
|
runtime,
|
|
3289
3491
|
harness,
|
|
3290
3492
|
api: baseApi,
|
|
3291
3493
|
debug,
|
|
3292
|
-
visitorId: (
|
|
3293
|
-
profile: (
|
|
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
|
|
3294
3500
|
};
|
|
3501
|
+
void (hydrated == null ? void 0 : hydrated.ready.then(() => conversations.reload()));
|
|
3295
3502
|
}
|
|
3296
3503
|
function identify(userId) {
|
|
3297
3504
|
if (!configured) throw new Error("Call GuideAI.configure() before identify().");
|
|
@@ -3305,6 +3512,14 @@ function setUserProfile(profile) {
|
|
|
3305
3512
|
if (!configured) throw new Error("Call GuideAI.configure() before setUserProfile().");
|
|
3306
3513
|
configured.profile = profile;
|
|
3307
3514
|
}
|
|
3515
|
+
function setFollowUps(followUps) {
|
|
3516
|
+
if (!configured) throw new Error("Call GuideAI.configure() before setFollowUps().");
|
|
3517
|
+
configured.followUps = cleanFollowUps(followUps != null ? followUps : void 0);
|
|
3518
|
+
}
|
|
3519
|
+
function cleanFollowUps(list) {
|
|
3520
|
+
const clean = (list != null ? list : []).map((text) => text.trim()).filter(Boolean).slice(0, 4);
|
|
3521
|
+
return clean.length ? clean : void 0;
|
|
3522
|
+
}
|
|
3308
3523
|
function requireConfigured() {
|
|
3309
3524
|
if (!configured) {
|
|
3310
3525
|
throw new Error(
|
|
@@ -3319,7 +3534,351 @@ function isConfigured() {
|
|
|
3319
3534
|
function reset() {
|
|
3320
3535
|
configured = null;
|
|
3321
3536
|
}
|
|
3322
|
-
const GuideAI = { configure, identify, setUserProfile, setToolContext, isConfigured, reset };
|
|
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
|
+
}
|
|
3323
3882
|
const AUDIO_TYPES = {
|
|
3324
3883
|
m4a: "audio/m4a",
|
|
3325
3884
|
mp4: "audio/mp4",
|
|
@@ -3350,6 +3909,10 @@ function replyFields(result, streamed) {
|
|
|
3350
3909
|
}
|
|
3351
3910
|
let nextId = 0;
|
|
3352
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
|
+
}
|
|
3353
3916
|
function answerText(result, fallback) {
|
|
3354
3917
|
var _a, _b;
|
|
3355
3918
|
const answer = ((_a = result.answer) != null ? _a : "").trim();
|
|
@@ -3363,12 +3926,16 @@ function answerText(result, fallback) {
|
|
|
3363
3926
|
}
|
|
3364
3927
|
const FAILURE_MESSAGE = "I'm sorry, I can't complete your request right now. Would you like to talk to a human?";
|
|
3365
3928
|
function useGuideAI(options = {}) {
|
|
3366
|
-
var _a, _b;
|
|
3929
|
+
var _a, _b, _c, _d;
|
|
3367
3930
|
const runtime = useGuideAIRuntime();
|
|
3368
3931
|
const configured2 = requireConfigured();
|
|
3369
3932
|
const harness = (_a = options.harness) != null ? _a : configured2.harness;
|
|
3370
3933
|
const trace = (_b = options.trace) != null ? _b : configured2.debug;
|
|
3934
|
+
const defaultFollowUps = (_c = options.followUps) != null ? _c : configured2.followUps;
|
|
3371
3935
|
const mode = "assistant";
|
|
3936
|
+
const board = useWhiteboard();
|
|
3937
|
+
const library = configured2.conversations;
|
|
3938
|
+
const { version } = useConversationSnapshot(library);
|
|
3372
3939
|
const [messages, setMessages] = React.useState([]);
|
|
3373
3940
|
const [input, setInput] = React.useState("");
|
|
3374
3941
|
const [busy, setBusy] = React.useState(false);
|
|
@@ -3376,25 +3943,32 @@ function useGuideAI(options = {}) {
|
|
|
3376
3943
|
const [transcribing, setTranscribing] = React.useState(false);
|
|
3377
3944
|
const lastQuestion = React.useRef(null);
|
|
3378
3945
|
const pending = React.useRef(/* @__PURE__ */ new Map());
|
|
3946
|
+
const shownVersion = React.useRef(null);
|
|
3379
3947
|
const mounted = React.useRef(true);
|
|
3380
3948
|
React.useEffect(() => () => {
|
|
3381
3949
|
mounted.current = false;
|
|
3382
3950
|
}, []);
|
|
3383
3951
|
React.useEffect(() => {
|
|
3384
3952
|
if (typeof harness.hasHistory !== "function" || typeof harness.getConversationHistory !== "function") return;
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
};
|
|
3395
|
-
});
|
|
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
|
+
};
|
|
3396
3962
|
});
|
|
3397
|
-
|
|
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]);
|
|
3398
3972
|
const initialized = React.useRef(null);
|
|
3399
3973
|
const ensureInitialized = React.useCallback(() => {
|
|
3400
3974
|
if (!initialized.current) initialized.current = harness.initialize();
|
|
@@ -3419,40 +3993,45 @@ function useGuideAI(options = {}) {
|
|
|
3419
3993
|
if (result.confirmationNeeded && result.pendingToolCall) {
|
|
3420
3994
|
pending.current.set(replyId, { call: result.pendingToolCall, question });
|
|
3421
3995
|
}
|
|
3422
|
-
|
|
3423
|
-
|
|
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;
|
|
3424
4001
|
} catch (error) {
|
|
3425
4002
|
console.log("[GuideAI] ✗ turn failed:", error);
|
|
3426
4003
|
if (error instanceof Error && error.stack) {
|
|
3427
4004
|
console.log("[GuideAI] stack:", error.stack);
|
|
3428
4005
|
}
|
|
3429
|
-
if (!mounted.current) return;
|
|
4006
|
+
if (!mounted.current) return null;
|
|
3430
4007
|
setMessages((prev) => prev.map((message) => message.id === replyId ? {
|
|
3431
4008
|
...message,
|
|
3432
4009
|
content: FAILURE_MESSAGE,
|
|
3433
4010
|
streaming: false,
|
|
3434
4011
|
error: true
|
|
3435
4012
|
} : message));
|
|
4013
|
+
return null;
|
|
3436
4014
|
} finally {
|
|
3437
4015
|
if (mounted.current) {
|
|
3438
4016
|
setBusy(false);
|
|
3439
4017
|
setStatus(null);
|
|
3440
4018
|
}
|
|
3441
4019
|
}
|
|
3442
|
-
}, [runtime, trace]);
|
|
4020
|
+
}, [runtime, trace, library]);
|
|
3443
4021
|
const send = React.useCallback(async (question) => {
|
|
3444
4022
|
const text = (question != null ? question : input).trim();
|
|
3445
|
-
if (!text || busy) return;
|
|
4023
|
+
if (!text || busy) return null;
|
|
3446
4024
|
lastQuestion.current = text;
|
|
3447
4025
|
if (question === void 0) setInput("");
|
|
3448
4026
|
if (trace) traceUserMessage(text);
|
|
3449
4027
|
const replyId = nextMessageId();
|
|
4028
|
+
const now = Date.now();
|
|
3450
4029
|
setMessages((prev) => [
|
|
3451
4030
|
...prev,
|
|
3452
|
-
{ id: nextMessageId(), role: "user", content: text },
|
|
3453
|
-
{ id: replyId, role: "assistant", content: "", streaming: true }
|
|
4031
|
+
{ id: nextMessageId(), role: "user", content: text, createdAt: now },
|
|
4032
|
+
{ id: replyId, role: "assistant", content: "", streaming: true, createdAt: now, question: text }
|
|
3454
4033
|
]);
|
|
3455
|
-
|
|
4034
|
+
return runTurn(replyId, text, async (onStatus, onDelta) => {
|
|
3456
4035
|
await ensureInitialized();
|
|
3457
4036
|
const screen = runtime.getActiveScreen();
|
|
3458
4037
|
const { profile, visitorId } = requireConfigured();
|
|
@@ -3480,7 +4059,8 @@ function useGuideAI(options = {}) {
|
|
|
3480
4059
|
setMessages([]);
|
|
3481
4060
|
lastQuestion.current = null;
|
|
3482
4061
|
pending.current.clear();
|
|
3483
|
-
|
|
4062
|
+
library.startNew();
|
|
4063
|
+
}, [library]);
|
|
3484
4064
|
const settleAction = React.useCallback((messageId) => {
|
|
3485
4065
|
const action = pending.current.get(messageId);
|
|
3486
4066
|
pending.current.delete(messageId);
|
|
@@ -3492,7 +4072,14 @@ function useGuideAI(options = {}) {
|
|
|
3492
4072
|
const action = settleAction(messageId);
|
|
3493
4073
|
if (!action) return;
|
|
3494
4074
|
const replyId = nextMessageId();
|
|
3495
|
-
setMessages((prev) => [...prev, {
|
|
4075
|
+
setMessages((prev) => [...prev, {
|
|
4076
|
+
id: replyId,
|
|
4077
|
+
role: "assistant",
|
|
4078
|
+
content: "",
|
|
4079
|
+
streaming: true,
|
|
4080
|
+
createdAt: Date.now(),
|
|
4081
|
+
question: action.question
|
|
4082
|
+
}]);
|
|
3496
4083
|
await runTurn(replyId, action.question, async (onStatus, onDelta) => {
|
|
3497
4084
|
await ensureInitialized();
|
|
3498
4085
|
return harness.executeToolCall(action.call, action.question, onStatus, onDelta);
|
|
@@ -3500,7 +4087,12 @@ function useGuideAI(options = {}) {
|
|
|
3500
4087
|
}, [busy, settleAction, runTurn, ensureInitialized, harness]);
|
|
3501
4088
|
const cancel = React.useCallback((messageId) => {
|
|
3502
4089
|
if (!settleAction(messageId)) return;
|
|
3503
|
-
setMessages((prev) => [...prev, {
|
|
4090
|
+
setMessages((prev) => [...prev, {
|
|
4091
|
+
id: nextMessageId(),
|
|
4092
|
+
role: "assistant",
|
|
4093
|
+
content: "Okay, I haven't changed anything.",
|
|
4094
|
+
createdAt: Date.now()
|
|
4095
|
+
}]);
|
|
3504
4096
|
}, [settleAction]);
|
|
3505
4097
|
const sendVoice = React.useCallback(async (recording) => {
|
|
3506
4098
|
var _a2;
|
|
@@ -3518,8 +4110,8 @@ function useGuideAI(options = {}) {
|
|
|
3518
4110
|
const heard = ((_a2 = result == null ? void 0 : result.text) == null ? void 0 : _a2.trim()) || "";
|
|
3519
4111
|
if (!heard) return { text: null, error: "I didn't catch that. Please try again." };
|
|
3520
4112
|
if (mounted.current) setTranscribing(false);
|
|
3521
|
-
await send(heard);
|
|
3522
|
-
return { text: heard };
|
|
4113
|
+
const answer = await send(heard);
|
|
4114
|
+
return { text: heard, answer };
|
|
3523
4115
|
} catch (error) {
|
|
3524
4116
|
console.log("[GuideAI] ✗ voice transcription failed:", error);
|
|
3525
4117
|
const message = error instanceof UploadError && error.status === 422 ? error.message : "I couldn't process that recording. Please try again or type your message.";
|
|
@@ -3528,8 +4120,26 @@ function useGuideAI(options = {}) {
|
|
|
3528
4120
|
if (mounted.current) setTranscribing(false);
|
|
3529
4121
|
}
|
|
3530
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]);
|
|
3531
4137
|
return {
|
|
3532
|
-
messages,
|
|
4138
|
+
messages: shown,
|
|
4139
|
+
typing,
|
|
4140
|
+
followUps,
|
|
4141
|
+
whiteboardAvailable: board.available,
|
|
4142
|
+
explainOnWhiteboard,
|
|
3533
4143
|
input,
|
|
3534
4144
|
setInput,
|
|
3535
4145
|
send,
|
|
@@ -3579,13 +4189,29 @@ function useOnboarding() {
|
|
|
3579
4189
|
}, [refresh]);
|
|
3580
4190
|
return { checklist, loading, refresh, dismiss };
|
|
3581
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;
|
|
3582
4205
|
exports.EP = EP;
|
|
3583
4206
|
exports.GuideAI = GuideAI;
|
|
4207
|
+
exports.LIMITS = LIMITS;
|
|
3584
4208
|
exports.RegistryContext = RegistryContext;
|
|
3585
4209
|
exports.ScreenRegistry = ScreenRegistry;
|
|
3586
4210
|
exports.requireConfigured = requireConfigured;
|
|
4211
|
+
exports.useConversations = useConversations;
|
|
3587
4212
|
exports.useGuideAI = useGuideAI;
|
|
3588
4213
|
exports.useGuideAIRuntime = useGuideAIRuntime;
|
|
3589
4214
|
exports.useOnboarding = useOnboarding;
|
|
3590
4215
|
exports.useScreenRegistry = useScreenRegistry;
|
|
3591
|
-
|
|
4216
|
+
exports.useWhiteboard = useWhiteboard;
|
|
4217
|
+
//# sourceMappingURL=useConversations-C9ivx2l-.cjs.map
|