@ateam-ai-mobile/core 0.1.32 → 0.1.35

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
@@ -1347,6 +1347,264 @@ function focusPlugin(pluginId, props) {
1347
1347
  pluginCommandEmitter.emit("focus-plugin", { pluginId, props });
1348
1348
  }
1349
1349
 
1350
+ // src/storage/types.ts
1351
+ var MAX_ATTACHMENT_BYTES = 90 * 1024 * 1024;
1352
+ var MAX_INLINE_ATTACHMENT_BYTES = 7 * 1024 * 1024;
1353
+
1354
+ // src/chat/attachments.ts
1355
+ var mb = (bytes) => Math.round(bytes / 1024 / 1024);
1356
+ var base64Length = (bytes) => Math.ceil(bytes / 3) * 4;
1357
+ var MAX_INLINE_CHARS = base64Length(MAX_INLINE_ATTACHMENT_BYTES);
1358
+ function tooLarge(name) {
1359
+ return new Error(`"${name}" is too large (max ${mb(MAX_ATTACHMENT_BYTES)} MB)`);
1360
+ }
1361
+ function errorFrom(status, body, name) {
1362
+ let message = "";
1363
+ try {
1364
+ message = String(JSON.parse(body)?.error || "");
1365
+ } catch {
1366
+ }
1367
+ if (status === 413) {
1368
+ return new Error(message || `This server can't take files this big yet ("${name}")`);
1369
+ }
1370
+ if (status === 429) return new Error(message || "Too many uploads: wait a moment and try again");
1371
+ return new Error(message || `The upload of "${name}" failed (${status})`);
1372
+ }
1373
+ async function sendRaw(uploader, att, onProgress) {
1374
+ const query = new URLSearchParams({ mimeType: att.mimeType || "application/octet-stream", name: att.name || "upload" });
1375
+ const url = `${getCoreApiUrl()}/api/artifacts?${query.toString()}`;
1376
+ const attempt = () => {
1377
+ const token = getToken();
1378
+ return uploader.upload({
1379
+ url,
1380
+ uri: att.uri,
1381
+ headers: {
1382
+ "Content-Type": "application/octet-stream",
1383
+ ...token ? { Authorization: `Bearer ${token}` } : {}
1384
+ },
1385
+ onProgress
1386
+ });
1387
+ };
1388
+ let res = await attempt();
1389
+ if (res.status === 401 && getToken()) {
1390
+ const outcome = await refreshToken();
1391
+ if (outcome.ok === "ok") {
1392
+ res = await attempt();
1393
+ if (res.status === 401 || res.status === 403) {
1394
+ notifyAuthFailure();
1395
+ throw new Error("Session expired: sign in again to upload this file");
1396
+ }
1397
+ } else if (outcome.ok === "auth_failed") {
1398
+ notifyAuthFailure();
1399
+ throw new Error("Session expired: sign in again to upload this file");
1400
+ } else {
1401
+ throw new Error("Could not reach the server to refresh your sign-in: check your connection and try again");
1402
+ }
1403
+ }
1404
+ return res;
1405
+ }
1406
+ async function uploadOne(att, onProgress, budget) {
1407
+ const name = att.name || "attachment";
1408
+ if (att.data !== void 0) return { data: att.data, mimeType: att.mimeType, name: att.name };
1409
+ if (!att.uri) throw new Error(`The attachment "${name}" has no file to send`);
1410
+ if (att.size !== void 0 && att.size > MAX_ATTACHMENT_BYTES) throw tooLarge(name);
1411
+ const uploader = getConfig().fileUploader;
1412
+ if (!uploader) throw new Error("This app cannot upload files yet: initAdas needs a fileUploader");
1413
+ const res = await sendRaw(uploader, att, onProgress);
1414
+ if (res.status >= 200 && res.status < 300) {
1415
+ let parsed = null;
1416
+ try {
1417
+ parsed = JSON.parse(res.body);
1418
+ } catch {
1419
+ }
1420
+ if (parsed?.ok && typeof parsed.hash === "string") {
1421
+ onProgress(1);
1422
+ return { hash: parsed.hash, name: att.name, mimeType: parsed.mimeType || att.mimeType };
1423
+ }
1424
+ throw errorFrom(res.status, res.body, name);
1425
+ }
1426
+ if (res.status === 400) {
1427
+ const size = att.size !== void 0 ? att.size : await uploader.fileSize?.(att.uri);
1428
+ if (size === void 0) {
1429
+ throw new Error(`Cannot tell how big "${name}" is, and this server cannot take large files yet`);
1430
+ }
1431
+ if (base64Length(size) > budget.chars) {
1432
+ throw new Error(`"${name}" is too big for this server, which cannot take more than ${mb(MAX_INLINE_ATTACHMENT_BYTES)} MB of files in one message yet`);
1433
+ }
1434
+ const data = await uploader.readBase64(att.uri);
1435
+ budget.chars -= data.length;
1436
+ onProgress(1);
1437
+ return { data, mimeType: att.mimeType, name: att.name };
1438
+ }
1439
+ throw errorFrom(res.status, res.body, name);
1440
+ }
1441
+ async function prepareAttachments(attachments, onProgress) {
1442
+ const budget = { chars: MAX_INLINE_CHARS - attachments.reduce((n, a) => n + (a.data !== void 0 ? a.data.length : 0), 0) };
1443
+ const out = [];
1444
+ for (let i = 0; i < attachments.length; i++) {
1445
+ out.push(await uploadOne(attachments[i], (f) => onProgress?.((i + f) / attachments.length), budget));
1446
+ }
1447
+ return out;
1448
+ }
1449
+
1450
+ // src/chat/blockText.ts
1451
+ var TABLE_BLOCK_OPEN = "\uE100";
1452
+ var TABLE_BLOCK_CLOSE = "\uE101";
1453
+ var DETAILS_BLOCK_OPEN = "\uE102";
1454
+ var DETAILS_BLOCK_CLOSE = "\uE103";
1455
+ var DIAGRAM_BLOCK_OPEN = "\uE104";
1456
+ var DIAGRAM_BLOCK_CLOSE = "\uE105";
1457
+ var SENTINEL_CHARS = /[\uE100-\uE105]/g;
1458
+ var clean = (text) => text.replace(SENTINEL_CHARS, "");
1459
+ function renderTableShape(content) {
1460
+ if (!content || typeof content !== "object") return null;
1461
+ const cols = Array.isArray(content.columns) ? content.columns : null;
1462
+ const rows = Array.isArray(content.rows) ? content.rows : null;
1463
+ if (!cols || !rows) return null;
1464
+ const payload = encodeURIComponent(JSON.stringify({ columns: cols, rows }));
1465
+ return `${TABLE_BLOCK_OPEN}${payload}${TABLE_BLOCK_CLOSE}`;
1466
+ }
1467
+ var DIAGRAM_STATUSES = ["ok", "bad", "warn", "info"];
1468
+ var str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : "";
1469
+ var statusOf = (v) => DIAGRAM_STATUSES.includes(v) ? v : "";
1470
+ function diagramView(content) {
1471
+ if (!content || typeof content !== "object" || !Array.isArray(content.steps)) return null;
1472
+ const steps = [];
1473
+ for (const s of content.steps) {
1474
+ if (!s || typeof s !== "object") continue;
1475
+ const title = str(s.title);
1476
+ const text = str(s.text);
1477
+ if (!title && !text) continue;
1478
+ const badges = [];
1479
+ for (const b of Array.isArray(s.badges) ? s.badges : []) {
1480
+ const bt = str(b && typeof b === "object" ? b.text : b);
1481
+ if (bt) badges.push({ text: bt, status: statusOf(b && b.status) });
1482
+ }
1483
+ steps.push({ title: title || text, text: title ? text : "", status: statusOf(s.status), badges });
1484
+ }
1485
+ return steps.length < 2 ? null : { title: str(content.title), steps };
1486
+ }
1487
+ function diagramAsText(d) {
1488
+ const lines = d.title ? [d.title] : [];
1489
+ d.steps.forEach((s, i) => {
1490
+ const badges = s.badges.length ? ` [${s.badges.map((b) => b.text).join(", ")}]` : "";
1491
+ lines.push(`${i + 1}. ${s.title}${s.text ? ` \u2014 ${s.text}` : ""}${badges}`);
1492
+ });
1493
+ return lines.join("\n");
1494
+ }
1495
+ function fence(code, language) {
1496
+ const longest = (code.match(/`+/g) || []).reduce((n, run) => Math.max(n, run.length), 0);
1497
+ const ticks = "`".repeat(Math.max(3, longest + 1));
1498
+ return `${ticks}${language}
1499
+ ${code}
1500
+ ${ticks}`;
1501
+ }
1502
+ function blockText(b) {
1503
+ if (b.kind === "text" || b.kind === "markdown" || b.kind === "description") {
1504
+ return typeof b.content === "string" ? clean(b.content) : "";
1505
+ }
1506
+ if (b.kind === "code") {
1507
+ const nested = b.content && typeof b.content === "object";
1508
+ const code = nested ? b.content.content : b.content;
1509
+ if (typeof code !== "string" || !code.trim()) return "";
1510
+ const lang = clean(String((nested ? b.content.language : b.language) || "").trim());
1511
+ return fence(clean(code), lang && lang.toLowerCase() !== "auto" ? lang : "");
1512
+ }
1513
+ if (b.kind === "table" && b.content && typeof b.content === "object") {
1514
+ const md = renderTableShape(b.content);
1515
+ if (md) return md;
1516
+ }
1517
+ if (b.kind === "diagram") {
1518
+ const view = diagramView(b.content);
1519
+ if (view) return `${DIAGRAM_BLOCK_OPEN}${encodeURIComponent(JSON.stringify(view))}${DIAGRAM_BLOCK_CLOSE}`;
1520
+ }
1521
+ if (b.kind === "json") {
1522
+ const md = renderTableShape(b.content);
1523
+ if (md) return md;
1524
+ const pretty = JSON.stringify(b.content, null, 2);
1525
+ return typeof pretty === "string" ? fence(clean(pretty), "json") : "";
1526
+ }
1527
+ if (b.kind === "html") {
1528
+ return typeof b.content === "string" ? clean(b.content) : "";
1529
+ }
1530
+ if (typeof b.content === "string") return clean(b.content);
1531
+ return b.content === void 0 ? "" : clean(JSON.stringify(b.content) ?? "");
1532
+ }
1533
+ function blocksToText(blocks) {
1534
+ if (!blocks || blocks.length === 0) return "";
1535
+ return blocks.map((b) => {
1536
+ if (!b || typeof b !== "object") return "";
1537
+ const text = blockText(b);
1538
+ if (!text) return "";
1539
+ if (text.startsWith(TABLE_BLOCK_OPEN) || text.startsWith(DIAGRAM_BLOCK_OPEN)) return text;
1540
+ return b.meta?.display === "folded" ? `${DETAILS_BLOCK_OPEN}${encodeURIComponent(text)}${DETAILS_BLOCK_CLOSE}` : text;
1541
+ }).filter(Boolean).join("\n\n");
1542
+ }
1543
+ var PAIRS = [
1544
+ { kind: "table", open: TABLE_BLOCK_OPEN, close: TABLE_BLOCK_CLOSE },
1545
+ { kind: "details", open: DETAILS_BLOCK_OPEN, close: DETAILS_BLOCK_CLOSE },
1546
+ { kind: "diagram", open: DIAGRAM_BLOCK_OPEN, close: DIAGRAM_BLOCK_CLOSE }
1547
+ ];
1548
+ function splitBlockSegments(content) {
1549
+ const segments = [];
1550
+ if (!content) return segments;
1551
+ let cursor = 0;
1552
+ while (cursor < content.length) {
1553
+ let found = null;
1554
+ for (const pair of PAIRS) {
1555
+ const index = content.indexOf(pair.open, cursor);
1556
+ if (index !== -1 && (!found || index < found.index)) found = { index, pair };
1557
+ }
1558
+ if (!found) {
1559
+ segments.push({ kind: "md", content: content.slice(cursor) });
1560
+ break;
1561
+ }
1562
+ if (found.index > cursor) {
1563
+ segments.push({ kind: "md", content: content.slice(cursor, found.index) });
1564
+ }
1565
+ const close = content.indexOf(found.pair.close, found.index + found.pair.open.length);
1566
+ if (close === -1) {
1567
+ segments.push({ kind: "md", content: content.slice(found.index) });
1568
+ break;
1569
+ }
1570
+ segments.push({ kind: found.pair.kind, content: content.slice(found.index + found.pair.open.length, close) });
1571
+ cursor = close + found.pair.close.length;
1572
+ }
1573
+ return segments;
1574
+ }
1575
+ function tableAsText(payload) {
1576
+ try {
1577
+ const data = JSON.parse(decodeURIComponent(payload));
1578
+ const cols = Array.isArray(data?.columns) ? data.columns : [];
1579
+ const rows = Array.isArray(data?.rows) ? data.rows : [];
1580
+ const cell = (v) => v == null ? "" : typeof v === "object" ? JSON.stringify(v) : String(v);
1581
+ const line = (cells) => (Array.isArray(cells) ? cells : [cells]).map(cell).join(" | ");
1582
+ return [line(cols), ...rows.map(line)].join("\n");
1583
+ } catch {
1584
+ return "";
1585
+ }
1586
+ }
1587
+ function plainTextOf(content) {
1588
+ if (!content) return "";
1589
+ return splitBlockSegments(content).map((seg) => {
1590
+ if (seg.kind === "md") return seg.content;
1591
+ if (seg.kind === "table") return tableAsText(seg.content);
1592
+ if (seg.kind === "diagram") {
1593
+ try {
1594
+ const view = diagramView(JSON.parse(decodeURIComponent(seg.content)));
1595
+ return view ? diagramAsText(view) : "";
1596
+ } catch {
1597
+ return "";
1598
+ }
1599
+ }
1600
+ try {
1601
+ return decodeURIComponent(seg.content);
1602
+ } catch {
1603
+ return seg.content;
1604
+ }
1605
+ }).join("");
1606
+ }
1607
+
1350
1608
  // src/chat/store.ts
1351
1609
  function coreHeaders() {
1352
1610
  const token = getToken();
@@ -1426,48 +1684,6 @@ function isTerminalSnapshot(snap) {
1426
1684
  if (extractPendingQuestion(snap)) return false;
1427
1685
  return snap?.done === true || isTerminalStatus(snap?.status);
1428
1686
  }
1429
- var TABLE_BLOCK_OPEN = "\uE100";
1430
- var TABLE_BLOCK_CLOSE = "\uE101";
1431
- function renderTableShape(content) {
1432
- if (!content || typeof content !== "object") return null;
1433
- const cols = Array.isArray(content.columns) ? content.columns : null;
1434
- const rows = Array.isArray(content.rows) ? content.rows : null;
1435
- if (!cols || !rows) return null;
1436
- const payload = encodeURIComponent(JSON.stringify({ columns: cols, rows }));
1437
- return `${TABLE_BLOCK_OPEN}${payload}${TABLE_BLOCK_CLOSE}`;
1438
- }
1439
- function blocksToText(blocks) {
1440
- if (!blocks || blocks.length === 0) return "";
1441
- const hasTextBlock = blocks.some(
1442
- (b) => b.kind === "text" || b.kind === "markdown" || b.kind === "description"
1443
- );
1444
- return blocks.map((b) => {
1445
- if ((b.kind === "json" || b.kind === "code") && hasTextBlock) return "";
1446
- if (b.kind === "text" || b.kind === "markdown" || b.kind === "description") {
1447
- return typeof b.content === "string" ? b.content : "";
1448
- }
1449
- if (b.kind === "code") {
1450
- const code = typeof b.content === "object" ? b.content.content : b.content;
1451
- return `\`\`\`
1452
- ${code}
1453
- \`\`\``;
1454
- }
1455
- if (b.kind === "table" && b.content && typeof b.content === "object") {
1456
- const md = renderTableShape(b.content);
1457
- if (md) return md;
1458
- }
1459
- if (b.kind === "json") {
1460
- if (b.content && typeof b.content === "object" && "pendingQuestion" in b.content) return "";
1461
- const md = renderTableShape(b.content);
1462
- if (md) return md;
1463
- return "```json\n" + JSON.stringify(b.content, null, 2) + "\n```";
1464
- }
1465
- if (b.kind === "html") {
1466
- return typeof b.content === "string" ? b.content : "";
1467
- }
1468
- return typeof b.content === "string" ? b.content : JSON.stringify(b.content);
1469
- }).filter(Boolean).join("\n\n");
1470
- }
1471
1687
  function blocksToAttachments(blocks) {
1472
1688
  if (!blocks || blocks.length === 0) return void 0;
1473
1689
  const atts = [];
@@ -1681,8 +1897,11 @@ var useChatStore = create4((set, get) => ({
1681
1897
  attachments: attachments.map((a) => ({
1682
1898
  mimeType: a.mimeType,
1683
1899
  name: a.name,
1684
- previewUri: a.mimeType.startsWith("image/") ? `data:${a.mimeType};base64,${a.data}` : void 0
1685
- }))
1900
+ // An image on the phone previews from its own file; an inline one from its base64.
1901
+ previewUri: !a.mimeType.startsWith("image/") ? void 0 : a.data !== void 0 ? `data:${a.mimeType};base64,${a.data}` : a.uri
1902
+ })),
1903
+ // A file on the phone is uploaded before the message is posted: the bubble shows how far along it is.
1904
+ ...attachments.some((a) => a.uri && a.data === void 0) ? { uploadProgress: 0 } : {}
1686
1905
  } : {}
1687
1906
  };
1688
1907
  set((s) => ({ messages: [...s.messages, userMsg], loading: true, error: null }));
@@ -1699,7 +1918,15 @@ var useChatStore = create4((set, get) => ({
1699
1918
  }
1700
1919
  };
1701
1920
  if (skillSlug) body.skillSlug = skillSlug;
1702
- if (attachments?.length) body.attachments = attachments;
1921
+ if (attachments?.length) {
1922
+ let shown = 0;
1923
+ body.attachments = await prepareAttachments(attachments, (f) => {
1924
+ if (f - shown < 0.01 && f < 1) return;
1925
+ shown = f;
1926
+ set((s) => ({ messages: s.messages.map((m) => m.id === userMsg.id && m.uploadProgress !== void 0 ? { ...m, uploadProgress: f } : m) }));
1927
+ });
1928
+ set((s) => ({ messages: s.messages.map((m) => m.id === userMsg.id ? { ...m, uploadProgress: void 0 } : m) }));
1929
+ }
1703
1930
  const res = await fetch(`${getCoreApiUrl()}/api/chat`, {
1704
1931
  method: "POST",
1705
1932
  headers: coreHeaders(),
@@ -1766,7 +1993,7 @@ var useChatStore = create4((set, get) => ({
1766
1993
  streamJob(jobId, getTenant(), getToken());
1767
1994
  } catch (err) {
1768
1995
  set((s) => ({
1769
- messages: [...s.messages, {
1996
+ messages: [...s.messages.map((m) => m.id === userMsg.id && m.uploadProgress !== void 0 ? { ...m, uploadProgress: void 0 } : m), {
1770
1997
  id: `error-${Date.now()}`,
1771
1998
  role: "system",
1772
1999
  content: `Error: ${err.message}`,
@@ -2223,6 +2450,13 @@ var borderRadius = {
2223
2450
  full: 9999
2224
2451
  };
2225
2452
  export {
2453
+ DETAILS_BLOCK_CLOSE,
2454
+ DETAILS_BLOCK_OPEN,
2455
+ DIAGRAM_BLOCK_CLOSE,
2456
+ DIAGRAM_BLOCK_OPEN,
2457
+ DIAGRAM_STATUSES,
2458
+ MAX_ATTACHMENT_BYTES,
2459
+ MAX_INLINE_ATTACHMENT_BYTES,
2226
2460
  PluginCommandEmitter,
2227
2461
  TABLE_BLOCK_CLOSE,
2228
2462
  TABLE_BLOCK_OPEN,
@@ -2240,6 +2474,8 @@ export {
2240
2474
  createPushRegistration,
2241
2475
  deleteArtifact,
2242
2476
  devModeFromCatalog,
2477
+ diagramAsText,
2478
+ diagramView,
2243
2479
  disconnectAcsWs,
2244
2480
  exchangeHandoff,
2245
2481
  fetchConsumerConfig,
@@ -2281,8 +2517,10 @@ export {
2281
2517
  parseInviteCode,
2282
2518
  patchArtifact,
2283
2519
  patchHomeAction,
2520
+ plainTextOf,
2284
2521
  pluginCommandEmitter,
2285
2522
  postCommandResult,
2523
+ prepareAttachments,
2286
2524
  previewInvite,
2287
2525
  readDevMode,
2288
2526
  recentDispatches as recentNotifDispatches,
@@ -2301,6 +2539,7 @@ export {
2301
2539
  signInWithApple,
2302
2540
  signInWithGoogle,
2303
2541
  spacing,
2542
+ splitBlockSegments,
2304
2543
  switchTenant,
2305
2544
  tenantFromToken,
2306
2545
  unlinkChannel as unlinkNotifChannel,