@ateam-ai-mobile/core 0.1.38 → 0.1.40

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/dist/index.mjs CHANGED
@@ -108,8 +108,8 @@ async function apiFetch(path, options = {}) {
108
108
  notifyAuthFailure();
109
109
  throw new Error("Session expired");
110
110
  }
111
- const text = await retryRes.text().catch(() => "");
112
- throw new Error(`API ${retryRes.status}: ${text}`);
111
+ const text2 = await retryRes.text().catch(() => "");
112
+ throw new Error(`API ${retryRes.status}: ${text2}`);
113
113
  }
114
114
  if (outcome.ok === "auth_failed") {
115
115
  console.warn(`[adas] refresh auth_failed on ${path} (${outcome.reason}) \u2014 auth failure`);
@@ -119,8 +119,8 @@ async function apiFetch(path, options = {}) {
119
119
  throw new Error(`API 401: refresh transient (${outcome.reason})`);
120
120
  }
121
121
  if (!res.ok) {
122
- const text = await res.text();
123
- throw new Error(`API ${res.status}: ${text}`);
122
+ const text2 = await res.text();
123
+ throw new Error(`API ${res.status}: ${text2}`);
124
124
  }
125
125
  return res.json();
126
126
  }
@@ -150,8 +150,8 @@ async function connectorCall(connectorId, tool, args = {}) {
150
150
  }
151
151
  );
152
152
  if (!res.ok) {
153
- const text = await res.text();
154
- return { ok: false, result: null, error: `HTTP ${res.status}: ${text}` };
153
+ const text2 = await res.text();
154
+ return { ok: false, result: null, error: `HTTP ${res.status}: ${text2}` };
155
155
  }
156
156
  const data = await res.json();
157
157
  if (data.ok !== void 0) return data;
@@ -167,8 +167,8 @@ async function mcpFetch(body) {
167
167
  body: typeof body === "string" ? body : JSON.stringify(body)
168
168
  });
169
169
  if (!res.ok) {
170
- const text = await res.text();
171
- throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text}`);
170
+ const text2 = await res.text();
171
+ throw new Error(`MCP fetch failed: HTTP ${res.status}: ${text2}`);
172
172
  }
173
173
  return res.json();
174
174
  }
@@ -1147,30 +1147,30 @@ async function postJson(path, body, jwt) {
1147
1147
  },
1148
1148
  body: JSON.stringify(body)
1149
1149
  });
1150
- const text = await res.text();
1150
+ const text2 = await res.text();
1151
1151
  let parsed = null;
1152
1152
  try {
1153
- parsed = JSON.parse(text);
1153
+ parsed = JSON.parse(text2);
1154
1154
  } catch {
1155
1155
  }
1156
1156
  if (!res.ok || parsed?.ok === false) {
1157
1157
  if (parsed?.error) throw new Error(parsed.error);
1158
- throw new Error(cleanErrorMessage(res.status, text, `consumer-auth ${path} failed`));
1158
+ throw new Error(cleanErrorMessage(res.status, text2, `consumer-auth ${path} failed`));
1159
1159
  }
1160
1160
  return parsed;
1161
1161
  }
1162
1162
  async function fetchConsumerConfig() {
1163
1163
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/config?tenant=${encodeURIComponent(getTenant())}`;
1164
1164
  const res = await fetch(url);
1165
- const text = await res.text();
1165
+ const text2 = await res.text();
1166
1166
  let data = null;
1167
1167
  try {
1168
- data = JSON.parse(text);
1168
+ data = JSON.parse(text2);
1169
1169
  } catch {
1170
1170
  }
1171
1171
  if (!res.ok || !data?.ok) {
1172
1172
  if (data?.error) throw new Error(data.error);
1173
- throw new Error(cleanErrorMessage(res.status, text, "Failed to load sign-in config"));
1173
+ throw new Error(cleanErrorMessage(res.status, text2, "Failed to load sign-in config"));
1174
1174
  }
1175
1175
  return data;
1176
1176
  }
@@ -1192,16 +1192,16 @@ async function exchangeHandoff(code) {
1192
1192
  async function previewInvite(code) {
1193
1193
  const url = `${getConsumerAuthApiUrl()}/platform/consumer/invite/${encodeURIComponent(code)}`;
1194
1194
  const res = await fetch(url);
1195
- const text = await res.text();
1195
+ const text2 = await res.text();
1196
1196
  let data = null;
1197
1197
  try {
1198
- data = JSON.parse(text);
1198
+ data = JSON.parse(text2);
1199
1199
  } catch {
1200
1200
  }
1201
1201
  if (res.status === 404) throw new Error("This invite is invalid or has expired.");
1202
1202
  if (!res.ok || !data?.ok) {
1203
1203
  if (data?.error) throw new Error(data.error);
1204
- throw new Error(cleanErrorMessage(res.status, text, "Could not load invite"));
1204
+ throw new Error(cleanErrorMessage(res.status, text2, "Could not load invite"));
1205
1205
  }
1206
1206
  return data;
1207
1207
  }
@@ -1481,7 +1481,7 @@ var COMPARISON_BLOCK_CLOSE = "\uE109";
1481
1481
  var TIMELINE_BLOCK_OPEN = "\uE10A";
1482
1482
  var TIMELINE_BLOCK_CLOSE = "\uE10B";
1483
1483
  var SENTINEL_CHARS = /[\uE100-\uE10B]/g;
1484
- var clean = (text) => text.replace(SENTINEL_CHARS, "");
1484
+ var clean = (text2) => text2.replace(SENTINEL_CHARS, "");
1485
1485
  function renderTableShape(content) {
1486
1486
  if (!content || typeof content !== "object") return null;
1487
1487
  const cols = Array.isArray(content.columns) ? content.columns : null;
@@ -1502,14 +1502,14 @@ function diagramView(content) {
1502
1502
  kept[i + 1] = 0;
1503
1503
  if (!s || typeof s !== "object") return;
1504
1504
  const title = str(s.title);
1505
- const text = str(s.text);
1506
- if (!title && !text) return;
1505
+ const text2 = str(s.text);
1506
+ if (!title && !text2) return;
1507
1507
  const badges = [];
1508
1508
  for (const b of Array.isArray(s.badges) ? s.badges : []) {
1509
1509
  const bt = str(b && typeof b === "object" ? b.text : b);
1510
1510
  if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
1511
1511
  }
1512
- steps.push({ title: title || text, text: title ? text : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1512
+ steps.push({ title: title || text2, text: title ? text2 : "", status: statusOf(s.status), badges, decision: s.kind === "decision" || s.decision === true, next: null });
1513
1513
  rawNext.push(Array.isArray(s.next) ? s.next : null);
1514
1514
  kept[i + 1] = steps.length;
1515
1515
  });
@@ -1685,10 +1685,10 @@ function blocksToText(blocks) {
1685
1685
  if (!blocks || blocks.length === 0) return "";
1686
1686
  return blocks.map((b) => {
1687
1687
  if (!b || typeof b !== "object") return "";
1688
- const text = blockText(b);
1689
- if (!text) return "";
1690
- if (text.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text.startsWith(v.open))) return text;
1691
- return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}` : text;
1688
+ const text2 = blockText(b);
1689
+ if (!text2) return "";
1690
+ if (text2.startsWith(TABLE_BLOCK_OPEN) || Object.values(VISUALS).some((v) => text2.startsWith(v.open))) return text2;
1691
+ return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text2)}${DETAILS_BLOCK_CLOSE}` : text2;
1692
1692
  }).filter(Boolean).join("\n\n");
1693
1693
  }
1694
1694
  var PAIRS = [
@@ -2034,11 +2034,11 @@ var useChatStore = create4((set, get) => ({
2034
2034
  // Send message via Core API
2035
2035
  // POST /api/chat { goal } → { jobId } → stream → fetch turn result
2036
2036
  // -----------------------------------------------------------------------
2037
- sendMessage: async (text, skillSlug, attachments) => {
2037
+ sendMessage: async (text2, skillSlug, attachments) => {
2038
2038
  const userMsg = {
2039
2039
  id: `user-${Date.now()}`,
2040
2040
  role: "user",
2041
- content: text,
2041
+ content: text2,
2042
2042
  timestamp: /* @__PURE__ */ new Date(),
2043
2043
  ...attachments?.length ? {
2044
2044
  attachments: attachments.map((a) => ({
@@ -2055,7 +2055,7 @@ var useChatStore = create4((set, get) => ({
2055
2055
  try {
2056
2056
  const actor = getUser();
2057
2057
  const body = {
2058
- goal: text,
2058
+ goal: text2,
2059
2059
  // Opt in to the Chain Additions router (attach/cancel/new while a
2060
2060
  // chain runs). Backend ignores it where not applicable — safe to send.
2061
2061
  chainRouting: true,
@@ -2082,11 +2082,11 @@ var useChatStore = create4((set, get) => ({
2082
2082
  if (!res.ok) {
2083
2083
  let errMsg = `Server error (${res.status})`;
2084
2084
  try {
2085
- const text2 = await res.text();
2086
- if (text2.startsWith("<") || text2.startsWith("<!")) {
2085
+ const text3 = await res.text();
2086
+ if (text3.startsWith("<") || text3.startsWith("<!")) {
2087
2087
  errMsg = res.status === 502 ? "Server is temporarily unavailable. Please try again." : `Server error (${res.status})`;
2088
2088
  } else {
2089
- const parsed = JSON.parse(text2);
2089
+ const parsed = JSON.parse(text3);
2090
2090
  errMsg = parsed.error || errMsg;
2091
2091
  }
2092
2092
  } catch {
@@ -2369,12 +2369,12 @@ async function fetchTurnResult(jobId, jobSnap) {
2369
2369
  const turn = items[0];
2370
2370
  if (turn?.assistant || turn?.turn?.assistant) {
2371
2371
  const assistant = turn.assistant || turn.turn?.assistant;
2372
- const text = blocksToText(assistant.blocks);
2372
+ const text2 = blocksToText(assistant.blocks);
2373
2373
  const actions = Array.isArray(assistant.actions) && assistant.actions.length ? assistant.actions : void 0;
2374
- if (text) {
2374
+ if (text2) {
2375
2375
  updateJobProgress(jobId, {
2376
2376
  status,
2377
- resultMessage: text,
2377
+ resultMessage: text2,
2378
2378
  ...actions ? { resultActions: actions } : {}
2379
2379
  });
2380
2380
  return;
@@ -2427,6 +2427,181 @@ async function pollJob(jobId, token) {
2427
2427
  }
2428
2428
  }
2429
2429
 
2430
+ // src/chat/sideChat.ts
2431
+ import { create as create5 } from "zustand";
2432
+
2433
+ // src/chat/sideChatPure.ts
2434
+ var SIDE_CHAT_LIMITS = { title: 60, header: 40, welcome: 200, placeholder: 60 };
2435
+ var HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2436
+ var text = (v, max) => typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "";
2437
+ function sideChatOptions(payload) {
2438
+ const p = payload && typeof payload === "object" ? payload : {};
2439
+ return {
2440
+ title: text(p.title, SIDE_CHAT_LIMITS.title),
2441
+ header: text(p.header, SIDE_CHAT_LIMITS.header),
2442
+ welcome: text(p.welcome, SIDE_CHAT_LIMITS.welcome),
2443
+ placeholder: text(p.placeholder, SIDE_CHAT_LIMITS.placeholder),
2444
+ accent: typeof p.accent === "string" && HEX.test(p.accent.trim()) ? p.accent.trim() : null,
2445
+ side: p.side === "left" ? "left" : "right"
2446
+ };
2447
+ }
2448
+ var SHORT = /* @__PURE__ */ new Set(["ui", "ai", "mcp", "api", "crm", "sms", "pa"]);
2449
+ var nameOf = (slug) => slug.split(/[-_]+/).filter(Boolean).map((w) => SHORT.has(w.toLowerCase()) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1)).join(" ");
2450
+ function topicLabel(pageId, title) {
2451
+ if (title) return title;
2452
+ const last = String(pageId || "").split(":").pop() || "";
2453
+ return nameOf(last) || "Side chat";
2454
+ }
2455
+ function mergeSideChatHistory(saved, current) {
2456
+ const savedChains = new Set(saved.map((m) => m.chainId).filter(Boolean));
2457
+ const keep = current.filter((m) => m.local && !(m.chainId && savedChains.has(m.chainId)));
2458
+ return [...saved, ...keep];
2459
+ }
2460
+
2461
+ // src/chat/sideChat.ts
2462
+ var HISTORY_TURNS = 20;
2463
+ var stores = /* @__PURE__ */ new Map();
2464
+ function getSideChatStore(pageId) {
2465
+ const key = `${getTenant()}\0${pageId}`;
2466
+ let s = stores.get(key);
2467
+ if (!s) {
2468
+ s = createSideChatStore(pageId);
2469
+ stores.set(key, s);
2470
+ }
2471
+ return s;
2472
+ }
2473
+ function clearSideChats() {
2474
+ stores.clear();
2475
+ }
2476
+ function turnToMessages(turn) {
2477
+ const out = [];
2478
+ const chainId = typeof turn?.chainId === "string" ? turn.chainId : void 0;
2479
+ const base = turn?.jobId || turn?.chainId || `${turn?.startedAt || Date.now()}`;
2480
+ const userText = blocksToText(turn?.user?.blocks);
2481
+ const userAtts = blocksToAttachments(turn?.user?.blocks);
2482
+ if (userText || userAtts) {
2483
+ out.push({ id: `user-${base}`, role: "user", content: userText || "", timestamp: new Date(turn.startedAt || Date.now()), ...userAtts ? { attachments: userAtts } : {}, ...chainId ? { chainId } : {} });
2484
+ }
2485
+ const answer = blocksToText(turn?.assistant?.blocks);
2486
+ const actions = Array.isArray(turn?.assistant?.actions) && turn.assistant.actions.length ? turn.assistant.actions : void 0;
2487
+ if (answer || actions) {
2488
+ out.push({ id: `bot-${base}`, role: "assistant", content: answer || "", timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), skillSlug: turn.skillSlug, ...actions ? { actions } : {}, ...chainId ? { chainId } : {} });
2489
+ } else if (turn?.status === "failed") {
2490
+ out.push({ id: `err-${base}`, role: "system", content: turn.failReason || "This turn failed.", timestamp: new Date(turn.finishedAt || turn.startedAt || Date.now()), ...chainId ? { chainId } : {} });
2491
+ }
2492
+ return out;
2493
+ }
2494
+ function createSideChatStore(pageId) {
2495
+ return create5((set, get) => {
2496
+ const local = (m) => ({ ...m, local: true });
2497
+ const patchJob = (jobId, p) => set((s) => ({ messages: s.messages.map((m) => m.jobProgress?.jobId === jobId ? { ...m, jobProgress: { ...m.jobProgress, ...p } } : m) }));
2498
+ async function follow(jobId, chainId) {
2499
+ let ended = null;
2500
+ for (let i = 0; !ended; i++) {
2501
+ if (i > 0) await new Promise((r) => setTimeout(r, i < 120 ? 1500 : 5e3));
2502
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) return;
2503
+ try {
2504
+ const res = await fetch(`${getCoreApiUrl()}/api/job/${encodeURIComponent(jobId)}/status`, { headers: coreHeaders() });
2505
+ if (!res.ok) {
2506
+ if (res.status === 404) break;
2507
+ continue;
2508
+ }
2509
+ const snap = await res.json();
2510
+ const handoff = snap?.isHandoff || snap?.state?.handoffTransfer;
2511
+ if (isTerminalSnapshot(snap) && !(normalizeJobStatus(snap) === "done" && handoff)) ended = snap;
2512
+ else patchJob(jobId, snapshotToProgress(snap, jobId));
2513
+ } catch {
2514
+ }
2515
+ }
2516
+ for (let t = 0; t < 5; t++) {
2517
+ await get().load();
2518
+ if (!get().messages.some((m) => m.jobProgress?.jobId === jobId)) {
2519
+ set({ loading: false });
2520
+ return;
2521
+ }
2522
+ await new Promise((r) => setTimeout(r, 800));
2523
+ }
2524
+ const failed = ended ? normalizeJobStatus(ended) === "error" : false;
2525
+ const fallback = ended?.result?.message || ended?.state?.finalReply || (failed ? "Something went wrong. Please try again." : "Done.");
2526
+ set((s) => ({
2527
+ loading: false,
2528
+ messages: s.messages.map((m) => m.jobProgress?.jobId === jobId ? { ...m, id: `done-${jobId}`, content: fallback, jobProgress: { ...m.jobProgress, status: failed ? "error" : "done" }, chainId } : m)
2529
+ }));
2530
+ }
2531
+ return {
2532
+ pageId,
2533
+ messages: [],
2534
+ loading: false,
2535
+ loaded: false,
2536
+ load: async () => {
2537
+ try {
2538
+ const res = await fetch(`${getCoreApiUrl()}/api/conversation?topic=${encodeURIComponent(pageId)}&page_size=${HISTORY_TURNS}`, { headers: coreHeaders() });
2539
+ if (!res.ok) {
2540
+ set({ loaded: true });
2541
+ return;
2542
+ }
2543
+ const json = await res.json();
2544
+ const items = Array.isArray(json?.items) ? [...json.items].reverse() : [];
2545
+ const seen = /* @__PURE__ */ new Set();
2546
+ const saved = items.filter((t) => {
2547
+ const k = t?.jobId;
2548
+ if (!k) return true;
2549
+ if (seen.has(k)) return false;
2550
+ seen.add(k);
2551
+ return true;
2552
+ }).flatMap(turnToMessages);
2553
+ set((s) => ({ messages: mergeSideChatHistory(saved, s.messages), loaded: true }));
2554
+ } catch {
2555
+ set({ loaded: true });
2556
+ }
2557
+ },
2558
+ send: async (text2) => {
2559
+ const t = text2.trim();
2560
+ if (!t || get().loading) return false;
2561
+ const echo = local({ id: `user-${Date.now()}`, role: "user", content: t, timestamp: /* @__PURE__ */ new Date() });
2562
+ set((s) => ({ messages: [...s.messages, echo], loading: true }));
2563
+ const fail = (msg) => set((s) => ({ loading: false, messages: [...s.messages, local({ id: `error-${Date.now()}`, role: "system", content: msg, timestamp: /* @__PURE__ */ new Date() })] }));
2564
+ try {
2565
+ const actor = getUser();
2566
+ const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
2567
+ method: "POST",
2568
+ headers: coreHeaders(),
2569
+ body: JSON.stringify({
2570
+ goal: t,
2571
+ triggerContext: {
2572
+ channel: "mobile",
2573
+ replyContext: { chatId: actor?.actorId || "unknown" },
2574
+ pageContext: { page: pageId, chat: "page" }
2575
+ }
2576
+ })
2577
+ });
2578
+ const json = await res.json().catch(() => null);
2579
+ const jobId = json?.jobId || json?.id;
2580
+ if (!res.ok || !jobId) {
2581
+ fail(json?.error || `Could not start (${res.status}).`);
2582
+ return false;
2583
+ }
2584
+ const chainId = json.job?.chainId || jobId;
2585
+ const bubble = local({
2586
+ id: `job-${jobId}`,
2587
+ role: "assistant",
2588
+ content: "Working on it...",
2589
+ timestamp: /* @__PURE__ */ new Date(),
2590
+ chainId,
2591
+ jobProgress: { jobId, actorId: actor?.actorId, status: "running", subStatus: "Starting...", chainStartedAt: Date.now() }
2592
+ });
2593
+ set((s) => ({ messages: [...s.messages.map((m) => m.id === echo.id ? { ...m, chainId } : m), bubble] }));
2594
+ void follow(jobId, chainId);
2595
+ return true;
2596
+ } catch (e) {
2597
+ fail(`Request failed: ${e?.message || e}`);
2598
+ return false;
2599
+ }
2600
+ }
2601
+ };
2602
+ });
2603
+ }
2604
+
2430
2605
  // src/api/tenants.ts
2431
2606
  function nestByMaster(tenants) {
2432
2607
  const ids = new Set(tenants.map((t) => t.id));
@@ -2494,6 +2669,7 @@ async function switchTenant(targetTenantId) {
2494
2669
  await onSession(session);
2495
2670
  closeChatStream();
2496
2671
  useChatStore.getState().clearChat();
2672
+ clearSideChats();
2497
2673
  return session;
2498
2674
  }
2499
2675
 
@@ -2609,6 +2785,7 @@ export {
2609
2785
  MAX_ATTACHMENT_BYTES,
2610
2786
  MAX_INLINE_ATTACHMENT_BYTES,
2611
2787
  PluginCommandEmitter,
2788
+ SIDE_CHAT_LIMITS,
2612
2789
  TABLE_BLOCK_CLOSE,
2613
2790
  TABLE_BLOCK_OPEN,
2614
2791
  TIMELINE_BLOCK_CLOSE,
@@ -2623,6 +2800,7 @@ export {
2623
2800
  chartAsText,
2624
2801
  chartScale,
2625
2802
  chartView,
2803
+ clearSideChats,
2626
2804
  closeChatStream,
2627
2805
  colors,
2628
2806
  comparisonAsText,
@@ -2649,6 +2827,7 @@ export {
2649
2827
  getPrefs as getNotifPrefs,
2650
2828
  getTelegramBotInfo as getNotifTelegramBotInfo,
2651
2829
  getSession,
2830
+ getSideChatStore,
2652
2831
  getTenant,
2653
2832
  getToken,
2654
2833
  getUser,
@@ -2668,6 +2847,7 @@ export {
2668
2847
  listSurface,
2669
2848
  mcpFetch,
2670
2849
  mcpToolCall,
2850
+ mergeSideChatHistory,
2671
2851
  nestByMaster,
2672
2852
  notifyAcsWsForeground,
2673
2853
  notifyAppForeground,
@@ -2700,6 +2880,7 @@ export {
2700
2880
  setHomeActionOrder,
2701
2881
  setPrefs as setNotifPrefs,
2702
2882
  setOrder,
2883
+ sideChatOptions,
2703
2884
  signInWithApple,
2704
2885
  signInWithGoogle,
2705
2886
  spacing,
@@ -2708,6 +2889,7 @@ export {
2708
2889
  tenantFromToken,
2709
2890
  timelineAsText,
2710
2891
  timelineView,
2892
+ topicLabel,
2711
2893
  unlinkChannel as unlinkNotifChannel,
2712
2894
  unregisterDevice as unregisterPushDevice,
2713
2895
  unwrapMcpResult,