@guideai/react-native 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,4 @@
1
- import { useContext, createContext, useState, useRef, useEffect, useCallback } from "react";
2
- const DRAWING_URL = /^https:\/\/res\.cloudinary\.com\/[\w-]+\/image\/upload\//;
3
- const IMAGE_BLOCK = /```image[ \t]*\n([\s\S]*?)```/g;
4
- function headlessImages(text) {
5
- const images = [];
6
- const out = (text || "").replace(IMAGE_BLOCK, (_block, raw) => {
7
- let data;
8
- try {
9
- data = JSON.parse(raw.trim());
10
- } catch {
11
- return "";
12
- }
13
- if (typeof data.url !== "string" || !DRAWING_URL.test(data.url)) return "";
14
- const image = {
15
- url: data.url,
16
- svg: typeof data.svg === "string" && DRAWING_URL.test(data.svg) ? data.svg : null,
17
- alt: typeof data.alt === "string" ? data.alt.slice(0, 200) : "",
18
- width: Math.round(Number(data.width)) || 1600,
19
- height: Math.round(Number(data.height)) || 900
20
- };
21
- images.push(image);
22
- return `![${image.alt.replace(/[[\]]/g, "")}](${image.url})`;
23
- });
24
- return { text: out, images };
25
- }
1
+ import { useContext, createContext } from "react";
26
2
  const NAME_PREFIXES = [
27
3
  /^api[\s_-]*v?\d*[\s_-]*/i,
28
4
  /^(get|fetch|list|read|retrieve|show|query|search|find|lookup|look up)[\s_-]+/i,
@@ -83,7 +59,7 @@ function describeToolCall(toolCall) {
83
59
  const ownScope = /\s+(me|self|current|mine)$/.test(noun);
84
60
  if (ownScope) noun = `your ${noun.replace(/\s+(me|self|current|mine)$/, "")}`;
85
61
  if (SELF_DESCRIBING.test(noun) || ownScope) return `${verb} ${noun}`;
86
- const singular = noun.replace(new RegExp("([a-z])(?<!s|u|i)s$"), "$1");
62
+ const singular = noun.replace(/([a-z])(?<!s|u|i)s$/, "$1");
87
63
  return `${verb} ${singular} information`;
88
64
  }
89
65
  function describeToolBatch(toolCalls) {
@@ -651,8 +627,11 @@ class ToolExecutor {
651
627
  }
652
628
  /** Read the user's auth token from the configured browser storage. */
653
629
  getAuthToken() {
630
+ var _a, _b;
654
631
  if (this.authConfig.type === "none") return null;
655
632
  try {
633
+ const supplied = this.authConfig.type === "bearer" ? (_b = (_a = this.credentials).authToken) == null ? void 0 : _b.call(_a) : null;
634
+ if (supplied) return supplied;
656
635
  let raw = null;
657
636
  const storageKey = this.authConfig.key;
658
637
  if (storageKey && this.authConfig.source) {
@@ -838,6 +817,7 @@ class ToolExecutor {
838
817
  });
839
818
  }
840
819
  _buildHeaders(toolCall) {
820
+ var _a;
841
821
  const headers = {
842
822
  "Content-Type": "application/json",
843
823
  Accept: "application/json"
@@ -884,6 +864,16 @@ class ToolExecutor {
884
864
  mergeHeader(name, value);
885
865
  }
886
866
  }
867
+ for (const declared of (_a = this.authConfig.app_headers) != null ? _a : []) {
868
+ if (!(declared == null ? void 0 : declared.name)) continue;
869
+ let value = null;
870
+ try {
871
+ value = this.credentials.read("app", declared.name);
872
+ } catch {
873
+ value = null;
874
+ }
875
+ mergeHeader(declared.name, value);
876
+ }
887
877
  return headers;
888
878
  }
889
879
  _resolveHeaderValue(value) {
@@ -1026,6 +1016,7 @@ const EP = {
1026
1016
  guidesRecord: () => _j([..._v, "guides", "record"]),
1027
1017
  events: () => _j([..._v, "events"]),
1028
1018
  chatAsk: () => _j([..._v, "chat", "ask"]),
1019
+ chatExecuteTool: () => _j([..._v, "chat", "execute-tool"]),
1029
1020
  onboardingCurrent: (userId) => `${_j([..._v, "onboarding", "current"])}?user_id=${encodeURIComponent(userId)}`,
1030
1021
  onboardingObserve: () => _j([..._v, "onboarding", "observe"]),
1031
1022
  onboardingDismiss: () => _j([..._v, "onboarding", "dismiss"]),
@@ -1083,6 +1074,9 @@ const MAX_CHAIN_ROUNDS = 5;
1083
1074
  const MAX_TOTAL_TOOL_CALLS = 10;
1084
1075
  const MAX_REPAIR_ROUNDS = 1;
1085
1076
  const REPAIRABLE_ERROR_TYPES = /* @__PURE__ */ new Set(["validation", "client", "not_found"]);
1077
+ function isServerTool(toolCall) {
1078
+ return (toolCall.method || "").toUpperCase() === "MCP";
1079
+ }
1086
1080
  class CopilotHarness {
1087
1081
  /**
1088
1082
  * @param tools How this platform actually touches the screen. Defaults to
@@ -1166,6 +1160,24 @@ class CopilotHarness {
1166
1160
  setToolContext(values) {
1167
1161
  this.toolContext = values && Object.keys(values).length > 0 ? values : void 0;
1168
1162
  }
1163
+ /**
1164
+ * The app's tool inputs as the API names them. A value declared in Copilot
1165
+ * Tools as filling other inputs (app key `course` fills `content_id`) is
1166
+ * sent under those names too; one the app set by that name already wins.
1167
+ */
1168
+ contextForTools() {
1169
+ var _a, _b, _c, _d;
1170
+ if (!this.toolContext) return void 0;
1171
+ const out = { ...this.toolContext };
1172
+ for (const input of (_c = (_b = (_a = this.activeTools) == null ? void 0 : _a.auth_config) == null ? void 0 : _b.app_inputs) != null ? _c : []) {
1173
+ const value = (input == null ? void 0 : input.key) ? this.toolContext[input.key] : void 0;
1174
+ if (value === void 0) continue;
1175
+ for (const name of (_d = input.fills) != null ? _d : []) {
1176
+ if (name && !(name in out)) out[name] = value;
1177
+ }
1178
+ }
1179
+ return out;
1180
+ }
1169
1181
  /** Whether copilot action tools are available for this site. */
1170
1182
  isEnabled() {
1171
1183
  return this.tools.definitions().length > 0 || this.activeTools !== null && this.activeTools.tools.length > 0;
@@ -1180,8 +1192,7 @@ class CopilotHarness {
1180
1192
  * 5. For non-tool queries, returns JSON response directly
1181
1193
  */
1182
1194
  async processMessage(question, pageUrl, pageSnapshot, chatMode, onStatus, onTextDelta, onToolCallEvent, abortSignal, userContext, onboardingUserId) {
1183
- var _a2, _b2, _c2;
1184
- var _a, _b, _c, _d, _e, _f, _g, _h;
1195
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j2, _k;
1185
1196
  const inputCheck = this.validator.validateUserInput(question);
1186
1197
  if (!inputCheck.valid) {
1187
1198
  return this._errorResponse(inputCheck.error || "Invalid input.");
@@ -1196,10 +1207,10 @@ class CopilotHarness {
1196
1207
  });
1197
1208
  const conversationHistory = this.memory.getRecentForLLM(10);
1198
1209
  const mayForwardToken = ((_b = (_a = this.activeTools) == null ? void 0 : _a.auth_config) == null ? void 0 : _b.forward_user_token) === true;
1199
- const userToken = mayForwardToken ? (_a2 = (_c = this.toolExecutor) == null ? void 0 : _c.getAuthToken()) != null ? _a2 : null : null;
1210
+ const userToken = mayForwardToken ? (_d = (_c = this.toolExecutor) == null ? void 0 : _c.getAuthToken()) != null ? _d : null : null;
1200
1211
  let analytics = {};
1201
1212
  try {
1202
- analytics = (_b2 = (_e = (_d = this.config).analyticsIds) == null ? void 0 : _e.call(_d)) != null ? _b2 : {};
1213
+ analytics = (_g = (_f = (_e = this.config).analyticsIds) == null ? void 0 : _f.call(_e)) != null ? _g : {};
1203
1214
  } catch {
1204
1215
  }
1205
1216
  const requestBody = {
@@ -1209,8 +1220,8 @@ class CopilotHarness {
1209
1220
  distinct_id: analytics.distinct_id || void 0,
1210
1221
  page_snapshot: pageSnapshot,
1211
1222
  chat_mode: chatMode || "guidance",
1212
- assistant_label: ((_f = this.config.assistantLabel) == null ? void 0 : _f.trim()) || void 0,
1213
- delegate_instruction: ((_g = this.config.delegationInstruction) == null ? void 0 : _g.trim().slice(0, 1e3)) || void 0,
1223
+ assistant_label: ((_h = this.config.assistantLabel) == null ? void 0 : _h.trim()) || void 0,
1224
+ delegate_instruction: ((_i = this.config.delegationInstruction) == null ? void 0 : _i.trim().slice(0, 1e3)) || void 0,
1214
1225
  conversation_history: conversationHistory,
1215
1226
  stream: this.api.supportsStreaming,
1216
1227
  user_token: userToken || void 0,
@@ -1218,8 +1229,8 @@ class CopilotHarness {
1218
1229
  client_tools: chatMode === "assistant" ? this.tools.definitions() : void 0,
1219
1230
  user_context: userContext,
1220
1231
  onboarding_user_id: onboardingUserId,
1221
- tool_context: this.toolContext,
1222
- client_capabilities: ((_h = this.config.clientCapabilities) == null ? void 0 : _h.length) ? this.config.clientCapabilities : void 0
1232
+ tool_context: this.contextForTools(),
1233
+ client_capabilities: ((_j2 = this.config.clientCapabilities) == null ? void 0 : _j2.length) ? this.config.clientCapabilities : void 0
1223
1234
  };
1224
1235
  let rawResponse;
1225
1236
  try {
@@ -1259,7 +1270,7 @@ class CopilotHarness {
1259
1270
  const harnessResponse = this._handleJsonResponse(response, chatMode);
1260
1271
  if (harnessResponse.autoExecuteToolCall && harnessResponse.pendingToolCall) {
1261
1272
  return this._executePendingToolCall(
1262
- (_c2 = harnessResponse.pendingToolCalls) != null ? _c2 : [harnessResponse.pendingToolCall],
1273
+ (_k = harnessResponse.pendingToolCalls) != null ? _k : [harnessResponse.pendingToolCall],
1263
1274
  sanitizedQuestion,
1264
1275
  onStatus,
1265
1276
  onTextDelta,
@@ -1584,8 +1595,7 @@ class CopilotHarness {
1584
1595
  return result.trim();
1585
1596
  }
1586
1597
  _parseStreamedResponse(response) {
1587
- var _a2;
1588
- var _a, _b, _c, _d;
1598
+ var _a, _b, _c, _d, _e;
1589
1599
  const respCheck = this.validator.validateResponse(response);
1590
1600
  const answer = respCheck.sanitized || response.answer || "";
1591
1601
  if ((_a = response.tool_call) == null ? void 0 : _a.requires_confirm) {
@@ -1615,7 +1625,7 @@ class CopilotHarness {
1615
1625
  let toolResult;
1616
1626
  if (response.tool_result) {
1617
1627
  toolResult = {
1618
- success: (_a2 = response.tool_result.success) != null ? _a2 : true,
1628
+ success: (_c = response.tool_result.success) != null ? _c : true,
1619
1629
  data: response.tool_result.data,
1620
1630
  error: response.tool_result.error,
1621
1631
  status: response.tool_result.status
@@ -1635,10 +1645,10 @@ class CopilotHarness {
1635
1645
  escalation: response.escalation || void 0,
1636
1646
  demo: response.demo || void 0,
1637
1647
  point: response.point || void 0,
1638
- actions: ((_c = response.actions) == null ? void 0 : _c.length) ? response.actions : void 0,
1648
+ actions: ((_d = response.actions) == null ? void 0 : _d.length) ? response.actions : void 0,
1639
1649
  payment: response.payment || void 0,
1640
1650
  coach: response.coach || void 0,
1641
- quickReplies: ((_d = response.quick_replies) == null ? void 0 : _d.length) ? response.quick_replies : void 0
1651
+ quickReplies: ((_e = response.quick_replies) == null ? void 0 : _e.length) ? response.quick_replies : void 0
1642
1652
  };
1643
1653
  }
1644
1654
  /**
@@ -1666,14 +1676,13 @@ class CopilotHarness {
1666
1676
  return plan;
1667
1677
  }
1668
1678
  _handleJsonResponse(response, chatMode, toolResult) {
1669
- var _a2;
1670
- var _a, _b, _c;
1679
+ var _a, _b, _c, _d;
1671
1680
  const respCheck = this.validator.validateResponse(response);
1672
1681
  if (!respCheck.valid) {
1673
1682
  return this._errorResponse(respCheck.error || "Invalid server response.");
1674
1683
  }
1675
1684
  const answer = respCheck.sanitized || response.answer;
1676
- const plan = (_a2 = this._announcePlan(response.plan)) != null ? _a2 : this.currentPlan;
1685
+ const plan = (_a = this._announcePlan(response.plan)) != null ? _a : this.currentPlan;
1677
1686
  if (response.tool_call && response.tool_call.requires_confirm) {
1678
1687
  return {
1679
1688
  mode: "answer",
@@ -1690,7 +1699,7 @@ class CopilotHarness {
1690
1699
  answer,
1691
1700
  plan,
1692
1701
  pendingToolCall: response.tool_call,
1693
- pendingToolCalls: ((_a = response.tool_calls) == null ? void 0 : _a.length) ? response.tool_calls : [response.tool_call],
1702
+ pendingToolCalls: ((_b = response.tool_calls) == null ? void 0 : _b.length) ? response.tool_calls : [response.tool_call],
1694
1703
  autoExecuteToolCall: true,
1695
1704
  autoExecute: false
1696
1705
  };
@@ -1718,10 +1727,10 @@ class CopilotHarness {
1718
1727
  escalation: response.escalation || void 0,
1719
1728
  demo: response.demo || void 0,
1720
1729
  point: response.point || void 0,
1721
- actions: ((_b = response.actions) == null ? void 0 : _b.length) ? response.actions : void 0,
1730
+ actions: ((_c = response.actions) == null ? void 0 : _c.length) ? response.actions : void 0,
1722
1731
  payment: response.payment || void 0,
1723
1732
  coach: response.coach || void 0,
1724
- quickReplies: ((_c = response.quick_replies) == null ? void 0 : _c.length) ? response.quick_replies : void 0
1733
+ quickReplies: ((_d = response.quick_replies) == null ? void 0 : _d.length) ? response.quick_replies : void 0
1725
1734
  };
1726
1735
  this.memory.addMessage({
1727
1736
  role: "assistant",
@@ -1756,7 +1765,7 @@ class CopilotHarness {
1756
1765
  tool_history: toolHistory,
1757
1766
  tools_remaining: budget == null ? void 0 : budget.toolsRemaining,
1758
1767
  force_answer: (_a = budget == null ? void 0 : budget.forceAnswer) != null ? _a : false,
1759
- tool_context: this.toolContext,
1768
+ tool_context: this.contextForTools(),
1760
1769
  client_tools: this.tools.definitions()
1761
1770
  }
1762
1771
  );
@@ -1935,12 +1944,14 @@ class CopilotHarness {
1935
1944
  return !!this.toolExecutor || this.tools.definitions().length > 0;
1936
1945
  }
1937
1946
  canExecuteTool(toolCall) {
1947
+ if (isServerTool(toolCall)) return true;
1938
1948
  if (this.tools.canExecute(toolCall.tool)) {
1939
1949
  return this.tools.canExecuteCall(toolCall);
1940
1950
  }
1941
1951
  return !!this.toolExecutor;
1942
1952
  }
1943
1953
  executeLocalTool(toolCall) {
1954
+ if (isServerTool(toolCall)) return this.executeOnServer(toolCall);
1944
1955
  if (this.tools.canExecute(toolCall.tool)) {
1945
1956
  return this.tools.execute(toolCall);
1946
1957
  }
@@ -1951,6 +1962,30 @@ class CopilotHarness {
1951
1962
  error_type: "tool_unavailable"
1952
1963
  });
1953
1964
  }
1965
+ /**
1966
+ * An MCP tool, after the user approved it: we cannot call it — it is
1967
+ * reached from GuideAI's network with a secret the client never holds —
1968
+ * so the backend runs it, told who the user is by their token.
1969
+ */
1970
+ async executeOnServer(toolCall) {
1971
+ var _a, _b;
1972
+ try {
1973
+ return await this.api.post(EP.chatExecuteTool(), {
1974
+ tool: toolCall.tool,
1975
+ method: toolCall.method,
1976
+ path: toolCall.path,
1977
+ params: toolCall.params,
1978
+ body: toolCall.body,
1979
+ user_token: (_b = (_a = this.toolExecutor) == null ? void 0 : _a.getAuthToken()) != null ? _b : void 0
1980
+ });
1981
+ } catch (error) {
1982
+ return {
1983
+ success: false,
1984
+ error: error instanceof Error ? error.message : "The tool could not be run.",
1985
+ error_type: "tool_unavailable"
1986
+ };
1987
+ }
1988
+ }
1954
1989
  executeLocalToolBatch(toolCalls, onComplete) {
1955
1990
  return Promise.all(toolCalls.map(async (toolCall) => {
1956
1991
  const result = await this.executeLocalTool(toolCall);
@@ -2348,6 +2383,7 @@ class RNCredentialSource {
2348
2383
  this.storage = storage;
2349
2384
  this.session = session;
2350
2385
  this.hostToken = null;
2386
+ this.appValues = /* @__PURE__ */ new Map();
2351
2387
  }
2352
2388
  /**
2353
2389
  * Set by the runtime from `getAuthToken()` before every turn, so the
@@ -2359,12 +2395,20 @@ class RNCredentialSource {
2359
2395
  authToken() {
2360
2396
  return this.hostToken;
2361
2397
  }
2398
+ /** Set from `getRequestHeaders()` before every turn. */
2399
+ setAppValues(values) {
2400
+ this.appValues = new Map(Object.entries(values).map(([k, v]) => [k.toLowerCase(), v]));
2401
+ }
2362
2402
  read(source, key) {
2403
+ var _a;
2363
2404
  switch (source) {
2364
2405
  case "localStorage":
2365
2406
  return this.storage.getItem(key);
2366
2407
  case "sessionStorage":
2367
2408
  return this.session.getItem(key);
2409
+ // A header the toolset declares as supplied by the app.
2410
+ case "app":
2411
+ return (_a = this.appValues.get(key.toLowerCase())) != null ? _a : null;
2368
2412
  // No cookie jar on a device. Saying so is the honest answer.
2369
2413
  case "cookie":
2370
2414
  return null;
@@ -2378,6 +2422,7 @@ function rnPlatform(options = {}) {
2378
2422
  const session = new MemoryStore();
2379
2423
  return { storage, session, credentials: new RNCredentialSource(storage, session) };
2380
2424
  }
2425
+ const RESERVED_HEADERS = /* @__PURE__ */ new Set(["authorization", "host", "content-length", "cookie"]);
2381
2426
  class HostAuth {
2382
2427
  constructor(credentials, options = {}) {
2383
2428
  this.credentials = credentials;
@@ -2390,9 +2435,24 @@ class HostAuth {
2390
2435
  current() {
2391
2436
  return this.credentials.authToken();
2392
2437
  }
2393
- /** Read the host's token now. Never throws: a failed read is "signed out". */
2438
+ /** Read the host's token and extra headers now. Never throws. */
2394
2439
  async refresh() {
2395
2440
  var _a;
2441
+ if (this.options.getRequestHeaders) {
2442
+ let raw = null;
2443
+ try {
2444
+ raw = await this.options.getRequestHeaders();
2445
+ } catch (error) {
2446
+ console.warn("[GuideAI] getRequestHeaders failed; sending none:", error);
2447
+ }
2448
+ const clean = {};
2449
+ for (const [name, value] of Object.entries(raw != null ? raw : {})) {
2450
+ if (/^[A-Za-z0-9-]{1,64}$/.test(name) && !RESERVED_HEADERS.has(name.toLowerCase()) && typeof value === "string" && value && !/[\r\n]/.test(value)) {
2451
+ clean[name] = value;
2452
+ }
2453
+ }
2454
+ this.credentials.setAppValues(clean);
2455
+ }
2396
2456
  if (!this.options.getAuthToken) return null;
2397
2457
  let token = null;
2398
2458
  try {
@@ -3159,7 +3219,7 @@ ${text}`);
3159
3219
  console.log(`${"═".repeat(60)}
3160
3220
  `);
3161
3221
  }
3162
- const DEFAULT_BASE_URL = "https://api.guideai.dev";
3222
+ const DEFAULT_BASE_URL = "https://cdn.3guideai.com";
3163
3223
  let configured = null;
3164
3224
  function configure(config) {
3165
3225
  var _a, _b, _c, _d, _e, _f;
@@ -3173,7 +3233,11 @@ function configure(config) {
3173
3233
  const runtime = new GuideAIRuntime({
3174
3234
  requestOrigin: config.origin,
3175
3235
  store: config.store,
3176
- auth: { getAuthToken: config.getAuthToken, onAuthExpired: config.onAuthExpired },
3236
+ auth: {
3237
+ getAuthToken: config.getAuthToken,
3238
+ onAuthExpired: config.onAuthExpired,
3239
+ getRequestHeaders: config.getRequestHeaders
3240
+ },
3177
3241
  navigation: config.navigation ? navigationBridge(
3178
3242
  typeof config.navigation === "function" ? config.navigation : () => config.navigation
3179
3243
  ) : void 0
@@ -3194,23 +3258,37 @@ function configure(config) {
3194
3258
  debug ? traceTransport(runtime.transport) : runtime.transport,
3195
3259
  runtime.credentials
3196
3260
  );
3261
+ if (config.toolContext) harness.setToolContext(config.toolContext);
3197
3262
  configured = {
3198
3263
  runtime,
3199
3264
  harness,
3200
3265
  api: baseApi,
3201
3266
  debug,
3202
3267
  visitorId: (_e = config.visitorId) != null ? _e : null,
3203
- profile: (_f = config.userProfile) != null ? _f : null
3268
+ profile: (_f = config.userProfile) != null ? _f : null,
3269
+ followUps: cleanFollowUps(config.followUps)
3204
3270
  };
3205
3271
  }
3206
3272
  function identify(userId) {
3207
3273
  if (!configured) throw new Error("Call GuideAI.configure() before identify().");
3208
3274
  configured.visitorId = (userId == null ? void 0 : userId.trim()) || null;
3209
3275
  }
3276
+ function setToolContext(values) {
3277
+ if (!configured) throw new Error("Call GuideAI.configure() before setToolContext().");
3278
+ configured.harness.setToolContext(values != null ? values : void 0);
3279
+ }
3210
3280
  function setUserProfile(profile) {
3211
3281
  if (!configured) throw new Error("Call GuideAI.configure() before setUserProfile().");
3212
3282
  configured.profile = profile;
3213
3283
  }
3284
+ function setFollowUps(followUps) {
3285
+ if (!configured) throw new Error("Call GuideAI.configure() before setFollowUps().");
3286
+ configured.followUps = cleanFollowUps(followUps != null ? followUps : void 0);
3287
+ }
3288
+ function cleanFollowUps(list) {
3289
+ const clean = (list != null ? list : []).map((text) => text.trim()).filter(Boolean).slice(0, 4);
3290
+ return clean.length ? clean : void 0;
3291
+ }
3214
3292
  function requireConfigured() {
3215
3293
  if (!configured) {
3216
3294
  throw new Error(
@@ -3225,275 +3303,18 @@ function isConfigured() {
3225
3303
  function reset() {
3226
3304
  configured = null;
3227
3305
  }
3228
- const GuideAI = { configure, identify, setUserProfile, isConfigured, reset };
3229
- const AUDIO_TYPES = {
3230
- m4a: "audio/m4a",
3231
- mp4: "audio/mp4",
3232
- aac: "audio/aac",
3233
- caf: "audio/x-caf",
3234
- wav: "audio/wav",
3235
- mp3: "audio/mpeg",
3236
- webm: "audio/webm",
3237
- ogg: "audio/ogg",
3238
- "3gp": "audio/3gpp"
3239
- };
3240
- function audioType(uri) {
3241
- var _a, _b;
3242
- const extension = ((_a = uri.split("?")[0].split(".").pop()) != null ? _a : "").toLowerCase();
3243
- const type = (_b = AUDIO_TYPES[extension]) != null ? _b : "audio/m4a";
3244
- return { type, name: `voice.${AUDIO_TYPES[extension] ? extension : "m4a"}` };
3245
- }
3246
- function replyFields(result, streamed) {
3247
- var _a, _b;
3248
- const { text, images } = headlessImages(answerText(result, streamed));
3249
- const call = result.confirmationNeeded ? result.pendingToolCall : void 0;
3250
- return {
3251
- content: text,
3252
- images: images.length ? images : void 0,
3253
- suggestions: ((_a = result.quickReplies) == null ? void 0 : _a.length) ? result.quickReplies.slice(0, 4) : void 0,
3254
- pendingAction: call ? { label: ((_b = call.label) == null ? void 0 : _b.trim()) || describeToolCall(call), tool: call.tool } : void 0
3255
- };
3256
- }
3257
- let nextId = 0;
3258
- const nextMessageId = () => `m${nextId += 1}`;
3259
- function answerText(result, fallback) {
3260
- var _a, _b;
3261
- const answer = ((_a = result.answer) != null ? _a : "").trim();
3262
- if (answer) return answer;
3263
- const first = (_b = result.guideSteps) == null ? void 0 : _b[0];
3264
- const body = typeof (first == null ? void 0 : first.body) === "string" ? first.body.trim() : "";
3265
- if (body) return body;
3266
- const title = typeof (first == null ? void 0 : first.title) === "string" ? first.title.trim() : "";
3267
- if (title) return title;
3268
- return fallback || "Done.";
3269
- }
3270
- const FAILURE_MESSAGE = "I'm sorry, I can't complete your request right now. Would you like to talk to a human?";
3271
- function useGuideAI(options = {}) {
3272
- var _a, _b;
3273
- const runtime = useGuideAIRuntime();
3274
- const configured2 = requireConfigured();
3275
- const harness = (_a = options.harness) != null ? _a : configured2.harness;
3276
- const trace = (_b = options.trace) != null ? _b : configured2.debug;
3277
- const mode = "assistant";
3278
- const [messages, setMessages] = useState([]);
3279
- const [input, setInput] = useState("");
3280
- const [busy, setBusy] = useState(false);
3281
- const [status, setStatus] = useState(null);
3282
- const [transcribing, setTranscribing] = useState(false);
3283
- const lastQuestion = useRef(null);
3284
- const pending = useRef(/* @__PURE__ */ new Map());
3285
- const mounted = useRef(true);
3286
- useEffect(() => () => {
3287
- mounted.current = false;
3288
- }, []);
3289
- useEffect(() => {
3290
- if (typeof harness.hasHistory !== "function" || typeof harness.getConversationHistory !== "function") return;
3291
- if (!harness.hasHistory()) return;
3292
- setMessages((previous) => {
3293
- if (previous.length > 0) return previous;
3294
- return harness.getConversationHistory().filter((entry) => typeof entry.content === "string" && entry.content.trim()).map((entry, index) => {
3295
- var _a2;
3296
- return {
3297
- id: (_a2 = entry.id) != null ? _a2 : `h${index}`,
3298
- role: entry.role,
3299
- content: entry.content
3300
- };
3301
- });
3302
- });
3303
- }, [harness]);
3304
- const initialized = useRef(null);
3305
- const ensureInitialized = useCallback(() => {
3306
- if (!initialized.current) initialized.current = harness.initialize();
3307
- return initialized.current;
3308
- }, [harness]);
3309
- const runTurn = useCallback(async (replyId, question, work) => {
3310
- var _a2, _b2;
3311
- setBusy(true);
3312
- setStatus(null);
3313
- let streamed = "";
3314
- const appendDelta = (delta) => {
3315
- streamed += delta;
3316
- if (!mounted.current) return;
3317
- setMessages((prev) => prev.map((message) => message.id === replyId ? { ...message, content: message.content + delta } : message));
3318
- };
3319
- try {
3320
- await ((_a2 = runtime.auth) == null ? void 0 : _a2.refresh());
3321
- const result = await work((next2) => {
3322
- if (mounted.current) setStatus(next2);
3323
- }, appendDelta);
3324
- if (trace) traceAssistantAnswer((_b2 = result.answer) != null ? _b2 : "(empty)", result.mode);
3325
- if (result.confirmationNeeded && result.pendingToolCall) {
3326
- pending.current.set(replyId, { call: result.pendingToolCall, question });
3327
- }
3328
- if (!mounted.current) return;
3329
- setMessages((prev) => prev.map((message) => message.id === replyId ? { ...message, ...replyFields(result, streamed), streaming: false } : message));
3330
- } catch (error) {
3331
- console.log("[GuideAI] ✗ turn failed:", error);
3332
- if (error instanceof Error && error.stack) {
3333
- console.log("[GuideAI] stack:", error.stack);
3334
- }
3335
- if (!mounted.current) return;
3336
- setMessages((prev) => prev.map((message) => message.id === replyId ? {
3337
- ...message,
3338
- content: FAILURE_MESSAGE,
3339
- streaming: false,
3340
- error: true
3341
- } : message));
3342
- } finally {
3343
- if (mounted.current) {
3344
- setBusy(false);
3345
- setStatus(null);
3346
- }
3347
- }
3348
- }, [runtime, trace]);
3349
- const send = useCallback(async (question) => {
3350
- const text = (question != null ? question : input).trim();
3351
- if (!text || busy) return;
3352
- lastQuestion.current = text;
3353
- if (question === void 0) setInput("");
3354
- if (trace) traceUserMessage(text);
3355
- const replyId = nextMessageId();
3356
- setMessages((prev) => [
3357
- ...prev,
3358
- { id: nextMessageId(), role: "user", content: text },
3359
- { id: replyId, role: "assistant", content: "", streaming: true }
3360
- ]);
3361
- await runTurn(replyId, text, async (onStatus, onDelta) => {
3362
- await ensureInitialized();
3363
- const screen = runtime.getActiveScreen();
3364
- const { profile, visitorId } = requireConfigured();
3365
- return harness.processMessage(
3366
- text,
3367
- screen == null ? void 0 : screen.path,
3368
- runtime.captureSnapshot(),
3369
- mode,
3370
- onStatus,
3371
- onDelta,
3372
- void 0,
3373
- void 0,
3374
- // Who is asking, as the app knows them; the agent pitches to it.
3375
- profile ? { profile } : void 0,
3376
- visitorId != null ? visitorId : void 0
3377
- );
3378
- });
3379
- }, [busy, input, harness, mode, runtime, ensureInitialized, trace, runTurn]);
3380
- const retry = useCallback(async () => {
3381
- if (!lastQuestion.current || busy) return;
3382
- setMessages((prev) => prev.slice(0, -2));
3383
- await send(lastQuestion.current);
3384
- }, [busy, send]);
3385
- const clear = useCallback(() => {
3386
- setMessages([]);
3387
- lastQuestion.current = null;
3388
- pending.current.clear();
3389
- }, []);
3390
- const settleAction = useCallback((messageId) => {
3391
- const action = pending.current.get(messageId);
3392
- pending.current.delete(messageId);
3393
- setMessages((prev) => prev.map((message) => message.id === messageId ? { ...message, pendingAction: void 0 } : message));
3394
- return action;
3395
- }, []);
3396
- const confirm = useCallback(async (messageId) => {
3397
- if (busy) return;
3398
- const action = settleAction(messageId);
3399
- if (!action) return;
3400
- const replyId = nextMessageId();
3401
- setMessages((prev) => [...prev, { id: replyId, role: "assistant", content: "", streaming: true }]);
3402
- await runTurn(replyId, action.question, async (onStatus, onDelta) => {
3403
- await ensureInitialized();
3404
- return harness.executeToolCall(action.call, action.question, onStatus, onDelta);
3405
- });
3406
- }, [busy, settleAction, runTurn, ensureInitialized, harness]);
3407
- const cancel = useCallback((messageId) => {
3408
- if (!settleAction(messageId)) return;
3409
- setMessages((prev) => [...prev, { id: nextMessageId(), role: "assistant", content: "Okay, I haven't changed anything." }]);
3410
- }, [settleAction]);
3411
- const sendVoice = useCallback(async (recording) => {
3412
- var _a2;
3413
- if (busy || transcribing) return { text: null, error: "Wait for the current reply to finish." };
3414
- const guessed = audioType(recording.uri);
3415
- setTranscribing(true);
3416
- try {
3417
- const result = await requireConfigured().api.postFile(
3418
- EP.batchVoiceTranscribe(),
3419
- "audio",
3420
- { uri: recording.uri, name: guessed.name, type: recording.mimeType || guessed.type },
3421
- { language_code: recording.languageCode || "en-US" },
3422
- 45e3
3423
- );
3424
- const heard = ((_a2 = result == null ? void 0 : result.text) == null ? void 0 : _a2.trim()) || "";
3425
- if (!heard) return { text: null, error: "I didn't catch that. Please try again." };
3426
- if (mounted.current) setTranscribing(false);
3427
- await send(heard);
3428
- return { text: heard };
3429
- } catch (error) {
3430
- console.log("[GuideAI] ✗ voice transcription failed:", error);
3431
- const message = error instanceof UploadError && error.status === 422 ? error.message : "I couldn't process that recording. Please try again or type your message.";
3432
- return { text: null, error: message };
3433
- } finally {
3434
- if (mounted.current) setTranscribing(false);
3435
- }
3436
- }, [busy, transcribing, send]);
3437
- return {
3438
- messages,
3439
- input,
3440
- setInput,
3441
- send,
3442
- busy,
3443
- canSend: Boolean(input.trim()) && !busy,
3444
- status,
3445
- retry,
3446
- clear,
3447
- confirm,
3448
- cancel,
3449
- sendVoice,
3450
- transcribing
3451
- };
3452
- }
3453
- function useOnboarding() {
3454
- const runtime = useGuideAIRuntime();
3455
- const [checklist, setChecklist] = useState(null);
3456
- const [loading, setLoading] = useState(true);
3457
- const refresh = useCallback(async () => {
3458
- var _a;
3459
- const { api, visitorId } = requireConfigured();
3460
- if (!visitorId) {
3461
- setChecklist(null);
3462
- setLoading(false);
3463
- return;
3464
- }
3465
- try {
3466
- const current = await api.get(EP.onboardingCurrent(visitorId));
3467
- const screen = (_a = runtime.getActiveScreen()) == null ? void 0 : _a.path;
3468
- const updated = current && !current.completed && !current.dismissed && screen ? await api.post(EP.onboardingObserve(), { user_id: visitorId, screen }) : current;
3469
- setChecklist(updated);
3470
- } catch {
3471
- } finally {
3472
- setLoading(false);
3473
- }
3474
- }, [runtime]);
3475
- const dismiss = useCallback(async () => {
3476
- const { api, visitorId } = requireConfigured();
3477
- if (!visitorId) return;
3478
- const updated = await api.post(EP.onboardingDismiss(), { user_id: visitorId });
3479
- setChecklist(updated);
3480
- }, []);
3481
- useEffect(() => {
3482
- void refresh();
3483
- const timer = setInterval(() => void refresh(), 5e3);
3484
- return () => clearInterval(timer);
3485
- }, [refresh]);
3486
- return { checklist, loading, refresh, dismiss };
3487
- }
3306
+ const GuideAI = { configure, identify, setUserProfile, setToolContext, setFollowUps, isConfigured, reset };
3488
3307
  export {
3489
3308
  EP as E,
3490
3309
  GuideAI as G,
3491
3310
  RegistryContext as R,
3492
3311
  ScreenRegistry as S,
3312
+ UploadError as U,
3493
3313
  useScreenRegistry as a,
3494
- useGuideAI as b,
3495
- useOnboarding as c,
3314
+ traceUserMessage as b,
3315
+ describeToolCall as d,
3496
3316
  requireConfigured as r,
3317
+ traceAssistantAnswer as t,
3497
3318
  useGuideAIRuntime as u
3498
3319
  };
3499
- //# sourceMappingURL=useOnboarding-DhVtf0U2.js.map
3320
+ //# sourceMappingURL=setup-CkXajERE.js.map