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