@tensorpass/aiconnect-react 0.1.6 → 0.1.8

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.
Files changed (87) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.js.map +1 -1
  3. package/dist/moduleMessages.d.ts +22 -0
  4. package/dist/moduleMessages.js +110 -0
  5. package/dist/moduleMessages.js.map +1 -1
  6. package/dist/modules/AiSearch.js +16 -5
  7. package/dist/modules/AiSearch.js.map +1 -1
  8. package/dist/modules/parts/ChatFrame.d.ts +1 -1
  9. package/dist/modules/parts/ChatFrame.js +11 -2
  10. package/dist/modules/parts/ChatFrame.js.map +1 -1
  11. package/dist/modules/parts/Composer.d.ts +9 -2
  12. package/dist/modules/parts/Composer.js +49 -12
  13. package/dist/modules/parts/Composer.js.map +1 -1
  14. package/dist/modules/parts/Conversation.js +14 -11
  15. package/dist/modules/parts/Conversation.js.map +1 -1
  16. package/dist/modules/parts/attachments/AttachButton.d.ts +5 -0
  17. package/dist/modules/parts/attachments/AttachButton.js +29 -0
  18. package/dist/modules/parts/attachments/AttachButton.js.map +1 -0
  19. package/dist/modules/parts/attachments/AttachmentChip.d.ts +12 -0
  20. package/dist/modules/parts/attachments/AttachmentChip.js +17 -0
  21. package/dist/modules/parts/attachments/AttachmentChip.js.map +1 -0
  22. package/dist/modules/parts/attachments/AttachmentRows.d.ts +11 -0
  23. package/dist/modules/parts/attachments/AttachmentRows.js +29 -0
  24. package/dist/modules/parts/attachments/AttachmentRows.js.map +1 -0
  25. package/dist/modules/parts/attachments/DropZone.d.ts +8 -0
  26. package/dist/modules/parts/attachments/DropZone.js +57 -0
  27. package/dist/modules/parts/attachments/DropZone.js.map +1 -0
  28. package/dist/modules/parts/attachments/Lightbox.d.ts +10 -0
  29. package/dist/modules/parts/attachments/Lightbox.js +43 -0
  30. package/dist/modules/parts/attachments/Lightbox.js.map +1 -0
  31. package/dist/modules/parts/attachments/attachmentList.d.ts +25 -0
  32. package/dist/modules/parts/attachments/attachmentList.js +26 -0
  33. package/dist/modules/parts/attachments/attachmentList.js.map +1 -0
  34. package/dist/modules/parts/attachments/fileSize.d.ts +1 -0
  35. package/dist/modules/parts/attachments/fileSize.js +14 -0
  36. package/dist/modules/parts/attachments/fileSize.js.map +1 -0
  37. package/dist/modules/parts/attachments/useAttachments.d.ts +13 -0
  38. package/dist/modules/parts/attachments/useAttachments.js +77 -0
  39. package/dist/modules/parts/attachments/useAttachments.js.map +1 -0
  40. package/dist/modules/parts/dictation/DictationBar.d.ts +4 -0
  41. package/dist/modules/parts/dictation/DictationBar.js +26 -0
  42. package/dist/modules/parts/dictation/DictationBar.js.map +1 -0
  43. package/dist/modules/parts/dictation/MicButton.d.ts +5 -0
  44. package/dist/modules/parts/dictation/MicButton.js +20 -0
  45. package/dist/modules/parts/dictation/MicButton.js.map +1 -0
  46. package/dist/modules/parts/dictation/audioCapture.d.ts +7 -0
  47. package/dist/modules/parts/dictation/audioCapture.js +44 -0
  48. package/dist/modules/parts/dictation/audioCapture.js.map +1 -0
  49. package/dist/modules/parts/dictation/browserSpeech.d.ts +37 -0
  50. package/dist/modules/parts/dictation/browserSpeech.js +32 -0
  51. package/dist/modules/parts/dictation/browserSpeech.js.map +1 -0
  52. package/dist/modules/parts/dictation/dictationLanguage.d.ts +2 -0
  53. package/dist/modules/parts/dictation/dictationLanguage.js +15 -0
  54. package/dist/modules/parts/dictation/dictationLanguage.js.map +1 -0
  55. package/dist/modules/parts/dictation/pcmWorklet.d.ts +1 -0
  56. package/dist/modules/parts/dictation/pcmWorklet.js +48 -0
  57. package/dist/modules/parts/dictation/pcmWorklet.js.map +1 -0
  58. package/dist/modules/parts/dictation/pcmWorkletUrl.d.ts +1 -0
  59. package/dist/modules/parts/dictation/pcmWorkletUrl.js +5 -0
  60. package/dist/modules/parts/dictation/pcmWorkletUrl.js.map +1 -0
  61. package/dist/modules/parts/dictation/recording.d.ts +19 -0
  62. package/dist/modules/parts/dictation/recording.js +45 -0
  63. package/dist/modules/parts/dictation/recording.js.map +1 -0
  64. package/dist/modules/parts/dictation/useDictation.d.ts +22 -0
  65. package/dist/modules/parts/dictation/useDictation.js +164 -0
  66. package/dist/modules/parts/dictation/useDictation.js.map +1 -0
  67. package/dist/modules/parts/icons.d.ts +5 -0
  68. package/dist/modules/parts/icons.js +6 -0
  69. package/dist/modules/parts/icons.js.map +1 -1
  70. package/dist/modules/parts/moduleAnalytics.d.ts +1 -1
  71. package/dist/modules/parts/moduleAnalytics.js.map +1 -1
  72. package/dist/modules/parts/useModuleChat.d.ts +6 -3
  73. package/dist/modules/parts/useModuleChat.js +20 -16
  74. package/dist/modules/parts/useModuleChat.js.map +1 -1
  75. package/dist/modules/types.d.ts +2 -0
  76. package/dist/modules/types.js +3 -2
  77. package/dist/modules/types.js.map +1 -1
  78. package/dist/modules/useOverlay.js +2 -1
  79. package/dist/modules/useOverlay.js.map +1 -1
  80. package/dist/styles.css +394 -0
  81. package/dist/transcriptBudget.d.ts +3 -0
  82. package/dist/transcriptBudget.js +34 -0
  83. package/dist/transcriptBudget.js.map +1 -0
  84. package/dist/useAiChat.d.ts +10 -1
  85. package/dist/useAiChat.js +30 -9
  86. package/dist/useAiChat.js.map +1 -1
  87. package/package.json +5 -4
package/dist/styles.css CHANGED
@@ -1287,6 +1287,400 @@
1287
1287
  flex: 1;
1288
1288
  }
1289
1289
 
1290
+ /* src/modules/styles/attachments.css */
1291
+ @keyframes aic-drop-in {
1292
+ from {
1293
+ opacity: 0;
1294
+ transform: scale(0.985);
1295
+ }
1296
+ }
1297
+ @keyframes aic-spin {
1298
+ to {
1299
+ transform: rotate(360deg);
1300
+ }
1301
+ }
1302
+ .aic-drop-area {
1303
+ display: contents;
1304
+ }
1305
+ .aic-inline {
1306
+ position: relative;
1307
+ }
1308
+ .aic-drop {
1309
+ position: absolute;
1310
+ inset: 8px;
1311
+ z-index: 3;
1312
+ display: flex;
1313
+ flex-direction: column;
1314
+ align-items: center;
1315
+ justify-content: center;
1316
+ gap: 12px;
1317
+ border: 2px dashed var(--aic-cyan);
1318
+ border-radius: calc(var(--aic-radius) - 6px);
1319
+ background: color-mix(in srgb, var(--aic-surface) 90%, transparent);
1320
+ -webkit-backdrop-filter: blur(6px);
1321
+ backdrop-filter: blur(6px);
1322
+ color: var(--aic-ink);
1323
+ font-size: 15px;
1324
+ font-weight: 700;
1325
+ text-align: center;
1326
+ pointer-events: none;
1327
+ animation: aic-drop-in 160ms var(--aic-m-ease);
1328
+ }
1329
+ .aic-drop-icon {
1330
+ display: grid;
1331
+ place-items: center;
1332
+ width: 52px;
1333
+ height: 52px;
1334
+ border-radius: 50%;
1335
+ background: var(--aic-halo);
1336
+ color: var(--aic-focus);
1337
+ }
1338
+ .aic-drop[data-state=refused] {
1339
+ border-color: var(--aic-danger);
1340
+ }
1341
+ .aic-drop[data-state=refused] .aic-drop-icon {
1342
+ background: color-mix(in srgb, var(--aic-danger) 12%, var(--aic-surface));
1343
+ color: var(--aic-danger);
1344
+ }
1345
+ .aic-tool-button {
1346
+ flex: none;
1347
+ display: grid;
1348
+ place-items: center;
1349
+ width: 36px;
1350
+ height: 36px;
1351
+ margin: 0 0 1px;
1352
+ padding: 0;
1353
+ border: 0;
1354
+ border-radius: 50%;
1355
+ background: transparent;
1356
+ color: var(--aic-muted);
1357
+ cursor: pointer;
1358
+ transition: background-color 160ms ease, color 160ms ease;
1359
+ }
1360
+ .aic-tool-button:hover {
1361
+ background: var(--aic-m-fill);
1362
+ color: var(--aic-ink);
1363
+ }
1364
+ .aic-field {
1365
+ flex-wrap: wrap;
1366
+ }
1367
+ .aic-field > .aic-attach {
1368
+ margin-inline-start: -10px;
1369
+ }
1370
+ .aic-composer-note {
1371
+ margin: 0 4px 8px;
1372
+ color: var(--aic-danger);
1373
+ font-size: 13px;
1374
+ font-weight: 600;
1375
+ line-height: 1.4;
1376
+ }
1377
+ .aic-chips {
1378
+ display: flex;
1379
+ flex-wrap: wrap;
1380
+ gap: 8px;
1381
+ margin: 0;
1382
+ padding: 0;
1383
+ list-style: none;
1384
+ }
1385
+ .aic-field > .aic-chips {
1386
+ order: -1;
1387
+ flex-basis: 100%;
1388
+ padding-block: 6px 4px;
1389
+ }
1390
+ .aic-chips-note {
1391
+ order: -1;
1392
+ flex-basis: 100%;
1393
+ margin: 0;
1394
+ color: var(--aic-muted);
1395
+ font-size: 12px;
1396
+ font-weight: 600;
1397
+ }
1398
+ .aic-chip {
1399
+ position: relative;
1400
+ display: flex;
1401
+ align-items: center;
1402
+ gap: 10px;
1403
+ height: 56px;
1404
+ max-width: 230px;
1405
+ margin: 0;
1406
+ padding: 0;
1407
+ border: 1px solid var(--aic-border);
1408
+ border-radius: 14px;
1409
+ background: var(--aic-surface);
1410
+ color: var(--aic-ink);
1411
+ }
1412
+ .aic-chip[data-kind=image] {
1413
+ width: 56px;
1414
+ }
1415
+ .aic-chip:not([data-kind=image]) {
1416
+ padding-inline: 8px 14px;
1417
+ }
1418
+ .aic-chip[data-unread] {
1419
+ border-style: dashed;
1420
+ opacity: 0.55;
1421
+ }
1422
+ .aic-chip-open {
1423
+ display: block;
1424
+ width: 100%;
1425
+ height: 100%;
1426
+ margin: 0;
1427
+ padding: 0;
1428
+ border: 0;
1429
+ border-radius: 13px;
1430
+ background: none;
1431
+ cursor: zoom-in;
1432
+ }
1433
+ .aic-chip-thumb {
1434
+ display: block;
1435
+ width: 100%;
1436
+ height: 100%;
1437
+ border-radius: 13px;
1438
+ background: var(--aic-m-fill);
1439
+ object-fit: cover;
1440
+ }
1441
+ .aic-chip-icon {
1442
+ flex: none;
1443
+ display: grid;
1444
+ place-items: center;
1445
+ width: 38px;
1446
+ height: 38px;
1447
+ border-radius: 10px;
1448
+ background: var(--aic-halo);
1449
+ color: var(--aic-focus);
1450
+ }
1451
+ .aic-chip-text {
1452
+ display: grid;
1453
+ min-width: 0;
1454
+ line-height: 1.25;
1455
+ }
1456
+ .aic-chip-name {
1457
+ overflow: hidden;
1458
+ font-size: 13px;
1459
+ font-weight: 700;
1460
+ text-overflow: ellipsis;
1461
+ white-space: nowrap;
1462
+ }
1463
+ .aic-chip-size {
1464
+ color: var(--aic-muted);
1465
+ font-size: 12px;
1466
+ font-variant-numeric: tabular-nums;
1467
+ }
1468
+ .aic-chip-ring {
1469
+ position: absolute;
1470
+ inset: 0;
1471
+ display: grid;
1472
+ place-items: center;
1473
+ border-radius: 13px;
1474
+ background: color-mix(in srgb, var(--aic-surface) 55%, transparent);
1475
+ }
1476
+ .aic-chip-ring::after {
1477
+ content: "";
1478
+ width: 22px;
1479
+ height: 22px;
1480
+ border: 2.5px solid var(--aic-cyan-faint);
1481
+ border-block-start-color: var(--aic-cyan);
1482
+ border-radius: 50%;
1483
+ animation: aic-spin 800ms linear infinite;
1484
+ }
1485
+ .aic-chip-remove {
1486
+ position: absolute;
1487
+ inset-block-start: -7px;
1488
+ inset-inline-end: -7px;
1489
+ display: grid;
1490
+ place-items: center;
1491
+ width: 22px;
1492
+ height: 22px;
1493
+ margin: 0;
1494
+ padding: 0;
1495
+ border: 2px solid var(--aic-surface);
1496
+ border-radius: 50%;
1497
+ background: var(--aic-accent);
1498
+ color: var(--aic-accent-ink);
1499
+ cursor: pointer;
1500
+ }
1501
+ .aic-chip-remove svg {
1502
+ width: 11px;
1503
+ height: 11px;
1504
+ stroke-width: 3;
1505
+ }
1506
+ .aic-question-chips {
1507
+ justify-self: end;
1508
+ justify-content: flex-end;
1509
+ max-width: 86%;
1510
+ }
1511
+ .aic-question-chips .aic-chip[data-kind=image] {
1512
+ width: 96px;
1513
+ height: 96px;
1514
+ transition: transform 200ms var(--aic-m-ease), box-shadow 200ms var(--aic-m-ease);
1515
+ }
1516
+ .aic-question-chips .aic-chip[data-kind=image]:hover {
1517
+ transform: translateY(-1px);
1518
+ box-shadow: var(--aic-m-lift);
1519
+ }
1520
+ .aic-unread {
1521
+ justify-self: end;
1522
+ max-width: 86%;
1523
+ margin: 0;
1524
+ color: var(--aic-muted);
1525
+ font-size: 13px;
1526
+ line-height: 1.4;
1527
+ }
1528
+ @media (max-width: 480px) {
1529
+ .aic-chip {
1530
+ max-width: 180px;
1531
+ }
1532
+ .aic-question-chips .aic-chip[data-kind=image] {
1533
+ width: 80px;
1534
+ height: 80px;
1535
+ }
1536
+ }
1537
+
1538
+ /* src/modules/styles/dictation.css */
1539
+ @keyframes aic-listen {
1540
+ 50% {
1541
+ box-shadow: 0 0 0 1px var(--aic-cyan), 0 0 0 6px var(--aic-cyan-faint);
1542
+ }
1543
+ }
1544
+ .aic-field[data-dictating] {
1545
+ border-color: var(--aic-cyan);
1546
+ animation: aic-listen 2.4s ease-in-out infinite;
1547
+ }
1548
+ .aic-dictation {
1549
+ display: flex;
1550
+ flex: 1;
1551
+ align-items: flex-end;
1552
+ gap: 6px;
1553
+ min-width: 0;
1554
+ }
1555
+ .aic-dictation-live {
1556
+ display: flex;
1557
+ flex: 1;
1558
+ flex-direction: column;
1559
+ justify-content: flex-end;
1560
+ gap: 4px;
1561
+ min-width: 0;
1562
+ min-height: 38px;
1563
+ padding-block: 4px;
1564
+ }
1565
+ .aic-dictation-words {
1566
+ display: flex;
1567
+ flex-direction: column;
1568
+ justify-content: flex-end;
1569
+ max-height: 2.9em;
1570
+ margin: 0;
1571
+ overflow: hidden;
1572
+ color: var(--aic-m-ink-2);
1573
+ font-size: 15px;
1574
+ font-weight: 500;
1575
+ line-height: 1.45;
1576
+ }
1577
+ .aic-dictation-meter {
1578
+ display: flex;
1579
+ align-items: center;
1580
+ gap: 10px;
1581
+ }
1582
+ .aic-wave {
1583
+ display: flex;
1584
+ flex: 1;
1585
+ align-items: center;
1586
+ gap: 2px;
1587
+ height: 26px;
1588
+ min-width: 0;
1589
+ overflow: hidden;
1590
+ }
1591
+ .aic-wave i {
1592
+ flex: 1;
1593
+ max-width: 4px;
1594
+ height: 100%;
1595
+ border-radius: 2px;
1596
+ background: var(--aic-cyan);
1597
+ transform-origin: center;
1598
+ transition: transform 90ms linear;
1599
+ }
1600
+ .aic-dictation-time {
1601
+ flex: none;
1602
+ color: var(--aic-muted);
1603
+ font-family: var(--aic-mono);
1604
+ font-size: 12px;
1605
+ font-variant-numeric: tabular-nums;
1606
+ }
1607
+ .aic-dictation[data-status=transcribing] .aic-wave i {
1608
+ background: var(--aic-cyan-soft);
1609
+ }
1610
+ .aic-search-bar[data-dictating] {
1611
+ border-color: var(--aic-cyan);
1612
+ animation: aic-listen 2.4s ease-in-out infinite;
1613
+ }
1614
+
1615
+ /* src/modules/styles/lightbox.css */
1616
+ @keyframes aic-lightbox-in {
1617
+ from {
1618
+ opacity: 0;
1619
+ transform: scale(0.985);
1620
+ }
1621
+ }
1622
+ .aic-lightbox {
1623
+ position: fixed;
1624
+ inset: 0;
1625
+ z-index: calc(var(--aic-layer) + 20);
1626
+ display: grid;
1627
+ place-items: center;
1628
+ padding: 56px 16px 72px;
1629
+ animation: aic-lightbox-in 180ms var(--aic-m-ease);
1630
+ }
1631
+ .aic-lightbox-backdrop {
1632
+ position: absolute;
1633
+ inset: 0;
1634
+ margin: 0;
1635
+ padding: 0;
1636
+ border: 0;
1637
+ background: var(--aic-backdrop);
1638
+ -webkit-backdrop-filter: blur(8px);
1639
+ backdrop-filter: blur(8px);
1640
+ cursor: zoom-out;
1641
+ }
1642
+ .aic-lightbox-figure {
1643
+ position: relative;
1644
+ display: grid;
1645
+ justify-items: center;
1646
+ gap: 10px;
1647
+ max-width: 100%;
1648
+ max-height: 100%;
1649
+ margin: 0;
1650
+ }
1651
+ .aic-lightbox-figure img {
1652
+ display: block;
1653
+ max-width: min(92vw, 1100px);
1654
+ max-height: calc(100vh - 160px);
1655
+ border-radius: 14px;
1656
+ box-shadow: var(--aic-shadow);
1657
+ object-fit: contain;
1658
+ }
1659
+ .aic-lightbox-figure figcaption {
1660
+ padding: 4px 12px;
1661
+ border-radius: 999px;
1662
+ background: var(--aic-surface);
1663
+ color: var(--aic-ink);
1664
+ font-size: 13px;
1665
+ font-weight: 600;
1666
+ }
1667
+ .aic-lightbox-close {
1668
+ position: absolute;
1669
+ inset-block-start: 12px;
1670
+ inset-inline-end: 12px;
1671
+ background: var(--aic-surface);
1672
+ }
1673
+ .aic-lightbox-steps {
1674
+ position: absolute;
1675
+ inset-block-end: 16px;
1676
+ display: flex;
1677
+ gap: 12px;
1678
+ }
1679
+ .aic-lightbox-steps .aic-round {
1680
+ background: var(--aic-surface);
1681
+ color: var(--aic-ink);
1682
+ }
1683
+
1290
1684
  /* src/webAccounts.css */
1291
1685
  .aic-web,
1292
1686
  .aic-web-step {
@@ -0,0 +1,3 @@
1
+ import type { ChatMessage } from '@tensorpass/aiconnect';
2
+ export declare const REQUEST_BUDGET = 7500000;
3
+ export declare function withinRequestBudget(messages: ChatMessage[], budget?: number): ChatMessage[];
@@ -0,0 +1,34 @@
1
+ // The conversation as the wallet takes it in one request: 8 million characters at most, its attachments
2
+ // included (the wallet's SITE_LIMITS). Every question resends the conversation, so once it would pass that
3
+ // size, the attachments of the oldest questions give way to a note naming them, and the model reads that
4
+ // the visitor had attached them.
5
+ export const REQUEST_BUDGET = 7_500_000;
6
+ function requestSize(messages) {
7
+ return JSON.stringify(messages).length;
8
+ }
9
+ function note(part) {
10
+ switch (part.type) {
11
+ case 'image':
12
+ return { type: 'text', text: '[An image the visitor attached earlier]' };
13
+ case 'file':
14
+ return { type: 'text', text: `[${part.name}, a file the visitor attached earlier]` };
15
+ default:
16
+ return part;
17
+ }
18
+ }
19
+ function withoutAttachments(message) {
20
+ return typeof message.content === 'string' ? message : { ...message, content: message.content.map(note) };
21
+ }
22
+ // The messages with the attachments of the oldest questions replaced by notes until the request fits. The
23
+ // last message, the question being asked, keeps its own.
24
+ export function withinRequestBudget(messages, budget = REQUEST_BUDGET) {
25
+ let fitted = messages;
26
+ for (let index = 0; index < fitted.length - 1 && requestSize(fitted) > budget; index += 1) {
27
+ const message = fitted[index];
28
+ if (message.role === 'user' && typeof message.content !== 'string') {
29
+ fitted = fitted.with(index, withoutAttachments(message));
30
+ }
31
+ }
32
+ return fitted;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O,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC9B,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;YACnE,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,kBAAkB,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["// The conversation as the wallet takes it in one request: 8 million characters at most, its attachments\n// included (the wallet's SITE_LIMITS). Every question resends the conversation, so once it would pass that\n// size, the attachments of the oldest questions give way to a note naming them, and the model reads that\n// the visitor had attached them.\n\nimport type { ChatMessage, ContentPart, UserMessage } from '@tensorpass/aiconnect';\n\nexport const REQUEST_BUDGET = 7_500_000;\n\nfunction requestSize(messages: ChatMessage[]): number {\n return JSON.stringify(messages).length;\n}\n\nfunction note(part: ContentPart): ContentPart {\n switch (part.type) {\n case 'image':\n return { type: 'text', text: '[An image the visitor attached earlier]' };\n case 'file':\n return { type: 'text', text: `[${part.name}, a file the visitor attached earlier]` };\n default:\n return part;\n }\n}\n\nfunction withoutAttachments(message: UserMessage): UserMessage {\n return typeof message.content === 'string' ? message : { ...message, content: message.content.map(note) };\n}\n\n// The messages with the attachments of the oldest questions replaced by notes until the request fits. The\n// last message, the question being asked, keeps its own.\nexport function withinRequestBudget(messages: ChatMessage[], budget = REQUEST_BUDGET): ChatMessage[] {\n let fitted = messages;\n for (let index = 0; index < fitted.length - 1 && requestSize(fitted) > budget; index += 1) {\n const message = fitted[index];\n if (message.role === 'user' && typeof message.content !== 'string') {\n fitted = fitted.with(index, withoutAttachments(message));\n }\n }\n return fitted;\n}\n"]}
@@ -1,11 +1,18 @@
1
1
  import type { GuardPolicy, ToolCall, ToolSource } from '@tensorpass/aiconnect';
2
+ import type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';
2
3
  export interface ToolActivity {
3
4
  call: ToolCall;
4
5
  result: string | null;
5
6
  visible?: boolean;
6
7
  }
8
+ export interface AskedQuestion {
9
+ text: string;
10
+ attachments: PreparedAttachment[];
11
+ }
7
12
  export interface ChatTurn {
8
13
  question: string;
14
+ attachments?: PreparedAttachment[];
15
+ unread?: number;
9
16
  answer: string;
10
17
  tools: ToolActivity[];
11
18
  blocked?: 'question' | 'answer';
@@ -21,7 +28,7 @@ export interface AnswerFailure {
21
28
  }
22
29
  export declare function useAiChat({ system, tools, guards }: UseAiChatOptions): {
23
30
  turns: ChatTurn[];
24
- send: (question: string) => Promise<void>;
31
+ send: (question: string | AskedQuestion) => Promise<void>;
25
32
  stop: () => void | undefined;
26
33
  reset: () => void;
27
34
  dropFailedTurn: () => void;
@@ -29,5 +36,7 @@ export declare function useAiChat({ system, tools, guards }: UseAiChatOptions):
29
36
  error: string | null;
30
37
  refusal: string | null;
31
38
  connected: boolean;
39
+ reads: import("@tensorpass/aiconnect").ReadableParts;
40
+ dictation: import("@tensorpass/aiconnect").Dictation | null;
32
41
  linkAllowed: (href: string) => boolean;
33
42
  };
package/dist/useAiChat.js CHANGED
@@ -3,11 +3,14 @@
3
3
  // tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and
4
4
  // the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with
5
5
  // `guards`: a question or an answer they stop shows the site's safe answer in its place, and
6
- // `linkAllowed` tells the interface which links of an answer it may draw.
6
+ // `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files
7
+ // the visitor attached, which reach the model as the account that answers reads them.
7
8
  import { useCallback, useRef, useState } from 'react';
8
9
  import { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';
10
+ import { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';
9
11
  import { useAiConnect } from "./AiConnectProvider.js";
10
12
  import { failedAnswerText } from "./messages.js";
13
+ import { withinRequestBudget } from "./transcriptBudget.js";
11
14
  // Before the first question there is no answer, so no link to draw.
12
15
  const NO_LINKS = () => false;
13
16
  function updateLast(turns, change) {
@@ -39,7 +42,7 @@ async function answerQuestion({ session, tools, guard, transcript, asked, contro
39
42
  session,
40
43
  tools,
41
44
  guard,
42
- messages: [...transcript.current, asked],
45
+ messages: withinRequestBudget([...transcript.current, asked]),
43
46
  signal: controller.signal,
44
47
  ...lastTurnHooks(setTurns, controller.signal, guard),
45
48
  });
@@ -64,17 +67,32 @@ function answerFailure(reason, connection, copy) {
64
67
  : failedAnswerText(reason, connection.providerName, copy);
65
68
  return { text, code: typeof code === 'string' ? code : null };
66
69
  }
70
+ // The visitor's message: the text, then the attachments as the account that answers reads them.
71
+ async function askedMessage(question, context) {
72
+ if (question.attachments.length === 0) {
73
+ return { role: 'user', content: question.text };
74
+ }
75
+ const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);
76
+ if (unread) {
77
+ context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));
78
+ }
79
+ const text = question.text ? [{ type: 'text', text: question.text }] : [];
80
+ return { role: 'user', content: [...text, ...parts] };
81
+ }
67
82
  // Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.
68
- async function sendQuestion(text, context) {
83
+ async function sendQuestion(question, context) {
69
84
  const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;
70
85
  const controller = new AbortController();
71
86
  abort.current = controller;
72
87
  setBusy(true);
73
88
  setFailure(null);
74
- setTurns((current) => [...current, { question: text, answer: '', tools: [] }]);
89
+ setTurns((current) => [...current, {
90
+ question: question.text, attachments: question.attachments, answer: '', tools: [],
91
+ }]);
75
92
  const run = { session: connection.session, tools, guard, transcript, controller, setTurns,
76
- asked: { role: 'user', content: text } };
93
+ asked: { role: 'user', content: question.text } };
77
94
  try {
95
+ run.asked = await askedMessage(question, context);
78
96
  await answerQuestion(run);
79
97
  }
80
98
  catch (reason) {
@@ -108,14 +126,15 @@ export function useAiChat({ system, tools, guards }) {
108
126
  // wallet connected the site goes out as soon as the client is connected.
109
127
  const send = useCallback(async (question) => {
110
128
  const connection = client.state;
111
- const text = question.trim();
112
- if (connection.status !== 'connected' || !text) {
129
+ const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;
130
+ const text = asked.text.trim();
131
+ if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {
113
132
  return;
114
133
  }
115
134
  activeGuard.current ??= createChatGuard(guards);
116
135
  setGuard(activeGuard.current);
117
- await sendQuestion(text, { connection, guard: activeGuard.current, tools, transcript, abort, setTurns,
118
- setFailure, setBusy, copy: moduleMessages });
136
+ await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,
137
+ setTurns, setFailure, setBusy, copy: moduleMessages });
119
138
  }, [client, tools, guards, moduleMessages]);
120
139
  const stop = useCallback(() => abort.current?.abort(), []);
121
140
  const reset = useCallback(() => {
@@ -137,6 +156,8 @@ export function useAiChat({ system, tools, guards }) {
137
156
  return {
138
157
  turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,
139
158
  connected: state.status === 'connected',
159
+ reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,
160
+ dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,
140
161
  linkAllowed: guard?.linkAllowed ?? NO_LINKS,
141
162
  };
142
163
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,0EAA0E;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAIpF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AA4BjD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site's tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ConversationHooks, GuardPolicy, ProviderSession, ToolCall, ToolSource,\n} from '@tensorpass/aiconnect';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\nexport interface ChatTurn {\n question: string;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run.\n// A conversation that was stopped writes nothing more, so a question sent right after it keeps its\n// own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n return {\n onText: (delta) => updateTurn((turn) => ({ ...turn, answer: turn.answer + delta })),\n onToolCall: (call) => updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n })),\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: [...transcript.current, asked],\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(text: string, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, { question: text, answer: '', tools: [] }]);\n const run = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: text } satisfies ChatMessage };\n try {\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string) => {\n const connection = client.state;\n const text = question.trim();\n if (connection.status !== 'connected' || !text) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion(text, { connection, guard: activeGuard.current, tools, transcript, abort, setTurns,\n setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}
1
+ {"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,yGAAyG;AACzG,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKpF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EA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EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI;QAC5G,SAAS,EAAE,KAAK,CAAC,MAAM,KAAK,WAAW;QACvC,KAAK,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,aAAa;QAChF,SAAS,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,IAAI;QAC/E,WAAW,EAAE,KAAK,EAAE,WAAW,IAAI,QAAQ;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["// A conversation with the visitor's own model, using the site's tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files\n// the visitor attached, which reach the model as the account that answers reads them.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ContentPart, ConversationHooks, GuardPolicy, ProviderSession, ToolCall,\n ToolSource,\n} from '@tensorpass/aiconnect';\nimport { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\nimport { withinRequestBudget } from './transcriptBudget.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\n// A question as the visitor sends it: the text they typed or dictated and the files they attached.\nexport interface AskedQuestion {\n text: string;\n attachments: PreparedAttachment[];\n}\n\nexport interface ChatTurn {\n question: string;\n // The files the visitor attached to the question.\n attachments?: PreparedAttachment[];\n // The attached images and pages the answering model does not read, such as images for a text only model.\n unread?: number;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run.\n// A conversation that was stopped writes nothing more, so a question sent right after it keeps its\n// own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n return {\n onText: (delta) => updateTurn((turn) => ({ ...turn, answer: turn.answer + delta })),\n onToolCall: (call) => updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n })),\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: withinRequestBudget([...transcript.current, asked]),\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// The visitor's message: the text, then the attachments as the account that answers reads them.\nasync function askedMessage(question: AskedQuestion, context: SendContext): Promise<ChatMessage> {\n if (question.attachments.length === 0) {\n return { role: 'user', content: question.text };\n }\n const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);\n if (unread) {\n context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));\n }\n const text: ContentPart[] = question.text ? [{ type: 'text', text: question.text }] : [];\n return { role: 'user', content: [...text, ...parts] };\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(question: AskedQuestion, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, {\n question: question.text, attachments: question.attachments, answer: '', tools: [],\n }]);\n const run: QuestionRun = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: question.text } };\n try {\n run.asked = await askedMessage(question, context);\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string | AskedQuestion) => {\n const connection = client.state;\n const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;\n const text = asked.text.trim();\n if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,\n setTurns, setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,\n dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}