@gemies/sdk 0.0.0-stage → 1.0.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.
Files changed (242) hide show
  1. package/CHANGELOG.md +1662 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +102 -4
  6. package/src/animations.ts +5 -0
  7. package/src/ask-eager.ts +8 -0
  8. package/src/ask-text.ts +11 -0
  9. package/src/ask.ts +12 -0
  10. package/src/avatar.ts +13 -0
  11. package/src/character.ts +1 -0
  12. package/src/components/AmbientField.tsx +580 -0
  13. package/src/components/ComposerDropZone.tsx +235 -0
  14. package/src/components/ComposerSuggestions.tsx +45 -0
  15. package/src/components/GemieAskCore.tsx +184 -0
  16. package/src/components/GemieAskProvider.tsx +18 -0
  17. package/src/components/GemieAskProviderLazy.tsx +27 -0
  18. package/src/components/GemieAskProviderText.tsx +25 -0
  19. package/src/components/GemieAskSheet.tsx +51 -0
  20. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  21. package/src/components/GemieAvatar.tsx +57 -0
  22. package/src/components/GemieAvatarIcon.tsx +35 -0
  23. package/src/components/GemieChatContent.tsx +900 -0
  24. package/src/components/GemieChatHeader.tsx +123 -0
  25. package/src/components/GemieChatScreen.tsx +170 -0
  26. package/src/components/GemieChatSheet.tsx +368 -0
  27. package/src/components/GemieChatWithVoice.tsx +13 -0
  28. package/src/components/GemieComposer.tsx +388 -0
  29. package/src/components/GemieGroupWelcome.tsx +37 -0
  30. package/src/components/GemieParticipants.tsx +133 -0
  31. package/src/components/GemieParticipantsHeader.tsx +27 -0
  32. package/src/components/GemieRecentConversations.tsx +65 -0
  33. package/src/components/GemieSharedConversation.tsx +87 -0
  34. package/src/components/GemieWelcomeMessage.tsx +58 -0
  35. package/src/components/IdentityMark.tsx +225 -0
  36. package/src/components/Image.tsx +12 -0
  37. package/src/components/InertWhen.tsx +48 -0
  38. package/src/components/PlanPreviewCard.tsx +53 -0
  39. package/src/components/QuestionCard.tsx +64 -0
  40. package/src/components/ReplyMarkdown.tsx +373 -0
  41. package/src/components/RichBlocks.tsx +195 -0
  42. package/src/components/VoiceModeIcon.tsx +18 -0
  43. package/src/components/canvas/CanvasComponent.tsx +65 -0
  44. package/src/components/canvas/ChartRenderer.tsx +73 -0
  45. package/src/components/canvas/CodeRenderer.tsx +20 -0
  46. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  47. package/src/components/canvas/DeckRenderer.tsx +43 -0
  48. package/src/components/canvas/FormRenderer.tsx +101 -0
  49. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  50. package/src/components/canvas/TableRenderer.tsx +47 -0
  51. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  52. package/src/components/icons/RiMoreDots.tsx +32 -0
  53. package/src/components/icons/RiReplyLine.tsx +25 -0
  54. package/src/components/thought/FilesAndSources.tsx +120 -0
  55. package/src/components/thought/ThoughtPanel.tsx +426 -0
  56. package/src/components/thought/ToolStep.tsx +134 -0
  57. package/src/components/thread/AgentExchangeView.tsx +112 -0
  58. package/src/components/thread/AgentResultCard.tsx +125 -0
  59. package/src/components/thread/AgentTaskCard.tsx +127 -0
  60. package/src/components/thread/ChatBubble.tsx +256 -0
  61. package/src/components/thread/GemieThread.tsx +455 -0
  62. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  63. package/src/components/thread/NewConversationOffer.tsx +54 -0
  64. package/src/components/thread/ThreadRow.tsx +598 -0
  65. package/src/components/thread/ThreadSearch.tsx +130 -0
  66. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  67. package/src/components/thread/ToolResultCard.tsx +254 -0
  68. package/src/components/thread/TurnMenu.tsx +54 -0
  69. package/src/components/thread/TurnStatusLine.tsx +34 -0
  70. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  71. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  72. package/src/components/voice/VoiceCallContext.ts +13 -0
  73. package/src/components/voice/VoiceControls.tsx +106 -0
  74. package/src/components/voice/VoiceSession.tsx +120 -0
  75. package/src/components/voice/withVoiceCall.tsx +25 -0
  76. package/src/csp.ts +50 -0
  77. package/src/dictation.ts +40 -0
  78. package/src/hooks/useAmbientWave.ts +184 -0
  79. package/src/hooks/useAtBottom.ts +51 -0
  80. package/src/hooks/useAttachMenu.ts +93 -0
  81. package/src/hooks/useAttachmentIntake.ts +401 -0
  82. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  83. package/src/hooks/useAudioLevels.ts +51 -0
  84. package/src/hooks/useChatComposer.ts +309 -0
  85. package/src/hooks/useChatVoice.ts +129 -0
  86. package/src/hooks/useComposerSuggestions.ts +84 -0
  87. package/src/hooks/useDictation.ts +292 -0
  88. package/src/hooks/useDocumentPicker.ts +11 -0
  89. package/src/hooks/useFailedTurnToast.ts +43 -0
  90. package/src/hooks/useFocusWhenPresented.ts +41 -0
  91. package/src/hooks/useGemieActivity.ts +31 -0
  92. package/src/hooks/useImagePicker.ts +38 -0
  93. package/src/hooks/useMessageReactions.ts +119 -0
  94. package/src/hooks/useMessageVote.ts +50 -0
  95. package/src/hooks/useOpenThought.ts +79 -0
  96. package/src/hooks/usePendingQuestions.ts +19 -0
  97. package/src/hooks/useReadAloud.ts +92 -0
  98. package/src/hooks/useShareHandler.ts +24 -0
  99. package/src/hooks/useSoundEffects.ts +137 -0
  100. package/src/hooks/useTTS.ts +303 -0
  101. package/src/hooks/useThoughtScope.ts +59 -0
  102. package/src/hooks/useThreadRows.ts +157 -0
  103. package/src/hooks/useThreadView.ts +67 -0
  104. package/src/hooks/useTimelineWindow.ts +256 -0
  105. package/src/hooks/useVoiceLauncher.ts +180 -0
  106. package/src/hooks/useVoiceRoom.ts +212 -0
  107. package/src/index.ts +140 -0
  108. package/src/lib/activity-socket.ts +102 -0
  109. package/src/lib/activity-store.ts +53 -0
  110. package/src/lib/add-menu.ts +7 -0
  111. package/src/lib/agent-character.ts +28 -0
  112. package/src/lib/alia-character.ts +14 -0
  113. package/src/lib/attachment-intake.ts +154 -0
  114. package/src/lib/attachment-tiles.ts +74 -0
  115. package/src/lib/audio-level.ts +130 -0
  116. package/src/lib/audio-request-auth.ts +4 -0
  117. package/src/lib/audio-session-binding.ts +27 -0
  118. package/src/lib/bubbles.tsx +16 -0
  119. package/src/lib/call-thread.ts +33 -0
  120. package/src/lib/canvas-result.ts +21 -0
  121. package/src/lib/catalogue-tool.ts +22 -0
  122. package/src/lib/citations.ts +192 -0
  123. package/src/lib/clipboard.ts +23 -0
  124. package/src/lib/content-utils.ts +46 -0
  125. package/src/lib/copy-en.ts +291 -0
  126. package/src/lib/copy-es.ts +287 -0
  127. package/src/lib/copy.ts +38 -0
  128. package/src/lib/deferred/document-picker.ts +2 -0
  129. package/src/lib/deferred/document-picker.web.ts +12 -0
  130. package/src/lib/deferred/expo-audio.ts +2 -0
  131. package/src/lib/deferred/expo-audio.web.ts +12 -0
  132. package/src/lib/deferred/image-data-url.ts +5 -0
  133. package/src/lib/deferred/image-data-url.web.ts +12 -0
  134. package/src/lib/dictation-protocol.ts +142 -0
  135. package/src/lib/dictation-recorder-types.ts +37 -0
  136. package/src/lib/dictation-recorder.native.ts +90 -0
  137. package/src/lib/dictation-recorder.ts +131 -0
  138. package/src/lib/dictation-stream.ts +238 -0
  139. package/src/lib/dictation.ts +216 -0
  140. package/src/lib/document-picker.ts +31 -0
  141. package/src/lib/domain.ts +12 -0
  142. package/src/lib/flights.ts +33 -0
  143. package/src/lib/focus-return.ts +66 -0
  144. package/src/lib/greeting.ts +15 -0
  145. package/src/lib/image-data-url.ts +35 -0
  146. package/src/lib/keyboard.native.tsx +25 -0
  147. package/src/lib/keyboard.tsx +55 -0
  148. package/src/lib/labels-es.ts +113 -0
  149. package/src/lib/labels.tsx +207 -0
  150. package/src/lib/origins.ts +28 -0
  151. package/src/lib/participants.ts +97 -0
  152. package/src/lib/pcm.ts +57 -0
  153. package/src/lib/power-level-options.ts +66 -0
  154. package/src/lib/questions.ts +92 -0
  155. package/src/lib/speech-language.ts +20 -0
  156. package/src/lib/speech-messages.ts +54 -0
  157. package/src/lib/speech-synthesis.ts +156 -0
  158. package/src/lib/suggestions.ts +53 -0
  159. package/src/lib/task-labels.ts +35 -0
  160. package/src/lib/text-input.ts +10 -0
  161. package/src/lib/tool-call-status.ts +28 -0
  162. package/src/lib/tool-icons.ts +36 -0
  163. package/src/lib/tool-registry.ts +71 -0
  164. package/src/lib/tool-renderers.tsx +32 -0
  165. package/src/lib/turn-state.ts +15 -0
  166. package/src/lib/utils.ts +35 -0
  167. package/src/lib/voice-audio-engine-types.ts +59 -0
  168. package/src/lib/voice-audio-engine.native.ts +232 -0
  169. package/src/lib/voice-audio-engine.ts +206 -0
  170. package/src/lib/voice-call-request.ts +49 -0
  171. package/src/lib/voice-call.ts +627 -0
  172. package/src/lib/voice-controls-labels.ts +31 -0
  173. package/src/lib/voice-levels.ts +64 -0
  174. package/src/lib/voice-protocol.ts +328 -0
  175. package/src/lib/voice-worklets.ts +19 -0
  176. package/src/lib/work-log.ts +370 -0
  177. package/src/metro/chart-importers.json +18 -0
  178. package/src/metro/granular-charts.js +3 -0
  179. package/src/metro/index.cjs +227 -0
  180. package/src/metro/index.d.cts +5 -0
  181. package/src/runtime/agents.ts +151 -0
  182. package/src/runtime/api.ts +144 -0
  183. package/src/runtime/app-assertion.ts +51 -0
  184. package/src/runtime/attachment-utils.ts +97 -0
  185. package/src/runtime/chat-turn-control.ts +74 -0
  186. package/src/runtime/composer-draft-store.ts +270 -0
  187. package/src/runtime/config.tsx +222 -0
  188. package/src/runtime/conversation-dates.ts +31 -0
  189. package/src/runtime/conversation-store.ts +49 -0
  190. package/src/runtime/conversations.ts +633 -0
  191. package/src/runtime/error-utils.ts +144 -0
  192. package/src/runtime/host-tools.ts +290 -0
  193. package/src/runtime/index.ts +137 -0
  194. package/src/runtime/message-history.ts +124 -0
  195. package/src/runtime/message-reactions.ts +214 -0
  196. package/src/runtime/model.ts +39 -0
  197. package/src/runtime/oxy-files.ts +37 -0
  198. package/src/runtime/power-levels.ts +66 -0
  199. package/src/runtime/query-keys.ts +49 -0
  200. package/src/runtime/random-uuid.ts +25 -0
  201. package/src/runtime/reaction-cache.ts +45 -0
  202. package/src/runtime/room-events.ts +333 -0
  203. package/src/runtime/routes.ts +81 -0
  204. package/src/runtime/sharing.ts +217 -0
  205. package/src/runtime/sse-frame-reader.ts +88 -0
  206. package/src/runtime/stream-events.ts +154 -0
  207. package/src/runtime/stream-outcome.ts +21 -0
  208. package/src/runtime/thought-store.ts +103 -0
  209. package/src/runtime/thread/agent-activity.ts +261 -0
  210. package/src/runtime/thread/agent-exchange.ts +94 -0
  211. package/src/runtime/thread/automation-labels.ts +79 -0
  212. package/src/runtime/thread/conversation-export.ts +135 -0
  213. package/src/runtime/thread/message-days.ts +120 -0
  214. package/src/runtime/thread/message-processor.ts +93 -0
  215. package/src/runtime/thread/speaker-changes.ts +66 -0
  216. package/src/runtime/thread/task-utils.ts +11 -0
  217. package/src/runtime/thread/thought-utils.ts +750 -0
  218. package/src/runtime/thread/thread-history.ts +139 -0
  219. package/src/runtime/thread/timeline.ts +202 -0
  220. package/src/runtime/thread/title-tags.ts +8 -0
  221. package/src/runtime/thread/tool-cards.ts +387 -0
  222. package/src/runtime/turn-failure.ts +108 -0
  223. package/src/runtime/turn-preparation.ts +21 -0
  224. package/src/runtime/types.ts +172 -0
  225. package/src/runtime/usage-limit-error.ts +44 -0
  226. package/src/runtime/use-agent-activity.ts +80 -0
  227. package/src/runtime/use-conversation-stream.ts +1669 -0
  228. package/src/runtime/use-conversation-thread.ts +590 -0
  229. package/src/runtime/use-gemie-thread.ts +54 -0
  230. package/src/runtime/use-room-events.ts +75 -0
  231. package/src/runtime/use-start-conversation.ts +107 -0
  232. package/src/runtime/use-thread-history.ts +73 -0
  233. package/src/runtime/use-thread-search.ts +100 -0
  234. package/src/runtime/use-turn-edit.ts +99 -0
  235. package/src/text.ts +19 -0
  236. package/src/theme.ts +16 -0
  237. package/src/tools.ts +27 -0
  238. package/src/types.ts +161 -0
  239. package/src/voice-messages.ts +2 -0
  240. package/src/voice.ts +67 -0
  241. package/tsconfig.json +17 -0
  242. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,94 @@
1
+ /**
2
+ * What an agent was asked and what it answered, rebuilt from the thread alone.
3
+ *
4
+ * A consultation (`consultAgent`, ADR 0020 §5) is never a conversation of its own in storage. It
5
+ * leaves two traces in the turn it happened in: the asker's reply carries the tool invocation (its
6
+ * `args.task` is what was asked, its `result` the answer with the agent's identity), and the
7
+ * consulted agent's own message (`agentInfo`) holds the answer. Both are already loaded with the
8
+ * thread, so the internal exchange needs no request.
9
+ *
10
+ * Several consultations of one agent in a turn come out in the order they were made. A turn whose
11
+ * task was not kept (an older message, a trimmed invocation) still yields the answers, with no
12
+ * question.
13
+ */
14
+ import { messageText } from '../../lib/content-utils';
15
+ import type { Message } from '../types';
16
+
17
+ /** The tool the lead consults with (`lib/tools/consult-agent.ts`). */
18
+ export const CONSULT_AGENT_TOOL = 'consultAgent';
19
+
20
+ /** An agent as a message carries it (`Message.agentInfo`). */
21
+ type ExchangeAgent = NonNullable<Message['agentInfo']>;
22
+
23
+ interface AgentExchangePair {
24
+ /** Who asked: the agent whose reply held the call, or `null` for the conversation's own lead. */
25
+ asker: ExchangeAgent | null;
26
+ /** What was asked; `null` when the stored invocation has no task. */
27
+ task: string | null;
28
+ /** What the consulted agent answered. */
29
+ answer: string;
30
+ }
31
+
32
+ export interface AgentExchange {
33
+ /** The consulted agent. */
34
+ agent: ExchangeAgent;
35
+ pairs: AgentExchangePair[];
36
+ }
37
+
38
+ type ExchangeRow = Pick<Message, 'id' | 'role' | 'content' | 'toolInvocations' | 'agentInfo'>;
39
+
40
+ interface Consultation {
41
+ asker: ExchangeAgent | null;
42
+ task: string | null;
43
+ response: string | null;
44
+ }
45
+
46
+ /**
47
+ * The exchange between the conversation and the agent that speaks at `anchorId`, over the turn
48
+ * (the rows between the questions of the person) that message is in. `null` when `anchorId` is
49
+ * not a message of a consulted agent.
50
+ */
51
+ export function agentExchange(
52
+ rows: readonly ExchangeRow[],
53
+ anchorId: string,
54
+ /** The direct agent or group members speak to the person, not in an internal exchange. */
55
+ members?: ReadonlySet<string>,
56
+ ): AgentExchange | null {
57
+ const anchorIndex = rows.findIndex((row) => row.id === anchorId);
58
+ const agent = rows[anchorIndex]?.agentInfo;
59
+ if (anchorIndex < 0 || !agent || members?.has(agent.id)) return null;
60
+
61
+ let start = anchorIndex;
62
+ while (start > 0 && rows[start - 1]?.role !== 'user') start -= 1;
63
+ let end = anchorIndex + 1;
64
+ while (end < rows.length && rows[end]?.role !== 'user') end += 1;
65
+ const turn = rows.slice(start, end);
66
+
67
+ const consultations: Consultation[] = [];
68
+ for (const row of turn) {
69
+ for (const call of row.toolInvocations ?? []) {
70
+ if (call.toolName !== CONSULT_AGENT_TOOL || call.state !== 'result') continue;
71
+ const result = call.result;
72
+ if (!result || typeof result !== 'object' || result.error || result.agentId !== agent.id) {
73
+ continue;
74
+ }
75
+ const task = call.args?.task;
76
+ consultations.push({
77
+ asker: row.agentInfo ?? null,
78
+ task: typeof task === 'string' && task.trim() !== '' ? task : null,
79
+ response: typeof result.response === 'string' ? result.response : null,
80
+ });
81
+ }
82
+ }
83
+ const answers = turn.filter((row) => row.role === 'assistant' && row.agentInfo?.id === agent.id);
84
+
85
+ const pairs: AgentExchangePair[] = [];
86
+ for (let i = 0; i < Math.max(consultations.length, answers.length); i += 1) {
87
+ const consultation = consultations[i];
88
+ const stored = answers[i];
89
+ const answer = stored ? messageText(stored) : (consultation?.response ?? '');
90
+ if (answer === '' && !consultation?.task) continue;
91
+ pairs.push({ asker: consultation?.asker ?? null, task: consultation?.task ?? null, answer });
92
+ }
93
+ return { agent, pairs };
94
+ }
@@ -0,0 +1,79 @@
1
+ import type { Translate } from '../../lib/copy';
2
+ import type { AutomationTrigger } from '../types';
3
+
4
+ /**
5
+ * A scheduled task's trigger as words.
6
+ *
7
+ * Drawn by the thread's scheduled-task card, and by every host that lists the person's tasks, so
8
+ * the words live beside the type rather than in either. Pure: the translator is a parameter.
9
+ */
10
+
11
+ function cronDayList(field: string): number[] | null {
12
+ const days: number[] = [];
13
+ for (const part of field.split(',')) {
14
+ const range = part.match(/^(\d)(?:-(\d))?$/);
15
+ if (!range) return null;
16
+ const from = Number(range[1]);
17
+ const to = range[2] === undefined ? from : Number(range[2]);
18
+ if (from > 6 || to > 6 || to < from) return null;
19
+ for (let day = from; day <= to; day += 1) days.push(day);
20
+ }
21
+ // Cron accepts 7 for Sunday in some dialects; the scheduler here writes 0.
22
+ const unique = [...new Set(days)].sort((a, b) => a - b);
23
+ return unique.length > 0 ? unique : null;
24
+ }
25
+
26
+ /**
27
+ * A cron expression as a sentence, for the shapes the app itself writes.
28
+ *
29
+ * `scheduleToCron` on the API produces exactly three forms from the create
30
+ * dialog — `*\/N * * * *` for an interval, `M H * * *` for every day and
31
+ * `M H * * 1,3,5` for chosen days — and those are what a person expects to
32
+ * read back as "Every hour" or "Mondays at 09:00", not as five fields (#537).
33
+ * Anything else (a hand-written structured schedule) is returned verbatim
34
+ * rather than guessed at: a wrong sentence is worse than a cron string.
35
+ */
36
+ export function cronLabel(cron: string, t: Translate): string {
37
+ const fields = cron.trim().split(/\s+/);
38
+ if (fields.length !== 5) return cron;
39
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [
40
+ string,
41
+ string,
42
+ string,
43
+ string,
44
+ string,
45
+ ];
46
+ if (dayOfMonth !== '*' || month !== '*') return cron;
47
+
48
+ const interval = minute.match(/^\*\/(\d+)$/);
49
+ if (interval && hour === '*' && dayOfWeek === '*') {
50
+ const minutes = Number(interval[1]);
51
+ if (minutes === 60) return t('automations.cron.everyHour');
52
+ if (minutes > 60 && minutes % 60 === 0)
53
+ return t('automations.cron.everyHours', { count: minutes / 60 });
54
+ return t('automations.cron.everyMinutes', { count: minutes });
55
+ }
56
+
57
+ if (!/^\d{1,2}$/.test(minute) || !/^\d{1,2}$/.test(hour)) return cron;
58
+ if (Number(minute) > 59 || Number(hour) > 23) return cron;
59
+ const time = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
60
+ if (dayOfWeek === '*') return t('automations.cron.dailyAt', { time });
61
+ const days = cronDayList(dayOfWeek);
62
+ if (!days) return cron;
63
+ if (days.length === 7) return t('automations.cron.dailyAt', { time });
64
+ if (days.length === 5 && days.every((day, index) => day === index + 1)) {
65
+ return t('automations.cron.weekdaysAt', { time });
66
+ }
67
+ if (days.length === 2 && days[0] === 0 && days[1] === 6)
68
+ return t('automations.cron.weekendsAt', { time });
69
+ const names = days.map((day) => t(`automations.cron.dayPlural.${day}`));
70
+ return t('automations.cron.daysAt', { days: names.join(', '), time });
71
+ }
72
+
73
+ export function triggerLabel(trigger: AutomationTrigger, t: Translate): string {
74
+ if (trigger.type === 'manual') return t('automations.trigger.manual');
75
+ if (trigger.type === 'event') {
76
+ return `${trigger.appId ?? t('automations.trigger.anyApp')} · ${trigger.eventType ?? t('automations.trigger.anyEvent')}`;
77
+ }
78
+ return `${trigger.cron ? cronLabel(trigger.cron, t) : t('automations.trigger.unscheduled')} · ${trigger.timezone ?? 'UTC'}`;
79
+ }
@@ -0,0 +1,135 @@
1
+ import type { Message } from '../types';
2
+ import { extractSources } from './thought-utils';
3
+
4
+ /**
5
+ * A conversation as a Markdown document.
6
+ *
7
+ * Pure, and deliberately so: the header's menu item is the only thing that
8
+ * asks for this, and what it hands over is the same `messages` array the
9
+ * screen is streaming into. Everything about DELIVERY — a download on web, the
10
+ * share sheet on a phone — lives in `conversation-share.ts`, so this module can
11
+ * be tested against a string and nothing else.
12
+ *
13
+ * ## What is kept and what is left out
14
+ *
15
+ * - Roles, as headings. The person is `## You` (or the translation handed in)
16
+ * and the answer is `## Alia`, or the agent's own name when the thread is
17
+ * with one, or the delegated agent's name on a turn that came from one.
18
+ * - The text, verbatim. An answer is already Markdown — fenced code blocks,
19
+ * lists, tables — so it is pasted as it is rather than re-rendered, which is
20
+ * what makes a code block survive the round trip.
21
+ * - Images, as image links. A multi-part user turn carries them as
22
+ * `image_url` parts, and Markdown has a spelling for exactly that.
23
+ * - Sources, as a list of links under the answer that used them. They are
24
+ * read out of `toolInvocations` — the same jsonb the message is stored with
25
+ * — by the same `extractSources` the thread shows them from, so the export
26
+ * cites what the screen cites.
27
+ * - Thinking is OMITTED. It is the model's scratchpad, shown in a side panel
28
+ * on request; a document of the conversation is a document of what was
29
+ * said.
30
+ * - `system` turns are omitted too: they are not part of the exchange.
31
+ */
32
+ export interface ConversationExportOptions {
33
+ /** The conversation's title, as the document's heading. */
34
+ title: string;
35
+ messages: readonly Message[];
36
+ /** When the document was made — the header states it. */
37
+ exportedAt: Date;
38
+ /** The name Alia answers under here; the heading for assistant turns. */
39
+ assistantName?: string;
40
+ /** The heading for the person's own turns, in their language. */
41
+ userLabel?: string;
42
+ }
43
+
44
+ const DEFAULT_ASSISTANT = 'Alia';
45
+ const DEFAULT_USER = 'You';
46
+
47
+ /** `YYYY-MM-DD` in the reader's own timezone, not the UTC one `toISOString` gives. */
48
+ export function localDate(date: Date): string {
49
+ const pad = (n: number) => String(n).padStart(2, '0');
50
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
51
+ }
52
+
53
+ /**
54
+ * The body of one message as Markdown: its text, then its images.
55
+ *
56
+ * A part the exporter does not know is dropped rather than stringified — an
57
+ * unknown part in a saved message is a shape from a later version of the app,
58
+ * and `[object Object]` in the middle of a document helps nobody.
59
+ */
60
+ function messageBody(content: Message['content']): string {
61
+ if (typeof content === 'string') return content.trim();
62
+ if (!Array.isArray(content)) return '';
63
+
64
+ const text: string[] = [];
65
+ const images: string[] = [];
66
+ for (const part of content) {
67
+ if (part.type === 'text' && typeof part.text === 'string') {
68
+ text.push(part.text);
69
+ } else if (part.type === 'image_url') {
70
+ const url = (part.image_url as { url?: unknown } | undefined)?.url;
71
+ if (typeof url === 'string' && url !== '') images.push(url);
72
+ }
73
+ }
74
+
75
+ const lines = [text.join('').trim()];
76
+ images.forEach((url, i) => lines.push(`![Image ${i + 1}](${url})`));
77
+ return lines.filter((line) => line !== '').join('\n\n');
78
+ }
79
+
80
+ /** The heading a turn is written under. */
81
+ function heading(message: Message, assistantName: string, userLabel: string): string {
82
+ if (message.role === 'user') return userLabel;
83
+ return message.agentInfo?.name || assistantName;
84
+ }
85
+
86
+ export function buildConversationMarkdown({
87
+ title,
88
+ messages,
89
+ exportedAt,
90
+ assistantName = DEFAULT_ASSISTANT,
91
+ userLabel = DEFAULT_USER,
92
+ }: ConversationExportOptions): string {
93
+ const sections: string[] = [
94
+ `# ${title.trim() || DEFAULT_ASSISTANT}`,
95
+ `_Exported ${localDate(exportedAt)}_`,
96
+ ];
97
+
98
+ for (const message of messages) {
99
+ if (message.role !== 'user' && message.role !== 'assistant') continue;
100
+
101
+ const body = messageBody(message.content);
102
+ const sources = message.role === 'assistant' ? extractSources(message.toolInvocations) : [];
103
+ // An assistant placeholder that never got its answer, or a turn whose
104
+ // only content was a part the exporter dropped: nothing to write under
105
+ // the heading, so no heading.
106
+ if (body === '' && sources.length === 0) continue;
107
+
108
+ const parts = [`## ${heading(message, assistantName, userLabel)}`];
109
+ if (body !== '') parts.push(body);
110
+ if (sources.length > 0) {
111
+ parts.push(['### Sources', ...sources.map((s) => `- [${s.title}](${s.url})`)].join('\n'));
112
+ }
113
+ sections.push(parts.join('\n\n'));
114
+ }
115
+
116
+ return `${sections.join('\n\n')}\n`;
117
+ }
118
+
119
+ /**
120
+ * A file name for the document: the title, made safe for a file system, with
121
+ * the date so two exports of one thread do not overwrite each other.
122
+ */
123
+ export function exportFilename(title: string, exportedAt: Date): string {
124
+ // NFD splits an accented letter into letter + combining mark, and the range
125
+ // is the combining marks block, spelled as a range and not as `\p{M}`: a
126
+ // property escape throws at RUNTIME on Hermes, where this code runs.
127
+ const slug = title
128
+ .toLowerCase()
129
+ .normalize('NFD')
130
+ .replace(/[\u0300-\u036f]/g, '')
131
+ .replace(/[^a-z0-9]+/g, '-')
132
+ .replace(/^-+|-+$/g, '')
133
+ .slice(0, 60);
134
+ return `${slug || 'conversation'}-${localDate(exportedAt)}.md`;
135
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Where a thread changes day, and which day it changed to.
3
+ *
4
+ * This is the DERIVED boundary, and the only one drawn from a timestamp: the
5
+ * clock passed midnight, and nobody decided it. A thread's other boundary — "a
6
+ * new conversation starts here" — is a seam between two conversations, read
7
+ * from which one each message belongs to, so it is not computed here and never
8
+ * from elapsed time. "N hours passed, draw a line" lies the day somebody comes
9
+ * back a week later to continue the same idea.
10
+ *
11
+ * ## The timezone is the client's, and that is the whole difficulty
12
+ *
13
+ * `createdAt` arrives as an ISO instant, which names no day: 23:40 on the 4th
14
+ * in Madrid and 22:40 on the 4th in London are the same instant, and 12:00 UTC
15
+ * is the 1st in Niue and the 2nd in Kiritimati. A separator computed from the
16
+ * UTC calendar is therefore wrong for most of the planet for part of every day,
17
+ * and wrong in the way nobody reports: the line lands an hour off, or a
18
+ * conversation that ran through local midnight shows none at all.
19
+ *
20
+ * So the day of an instant is read through `Date`'s LOCAL accessors, which is
21
+ * the device's own timezone — the one the person reading the thread is in.
22
+ *
23
+ * ## A message with no timestamp draws no line
24
+ *
25
+ * Everything the server sends carries `createdAt`; a message the client has
26
+ * only just appended may not, if it has not made the round trip. Those are
27
+ * skipped rather than assumed to be today, because assuming would draw a line
28
+ * that a reload then removes — and a separator that appears and disappears is
29
+ * worse than one that arrives a moment late.
30
+ */
31
+
32
+ /** What a separator says. `today` and `yesterday` are named so the caller can translate them. */
33
+ export type DaySeparatorLabel =
34
+ | { readonly kind: 'today' }
35
+ | { readonly kind: 'yesterday' }
36
+ | { readonly kind: 'date'; readonly text: string };
37
+
38
+ export interface DaySeparator {
39
+ /** The id of the message this separator sits directly above. */
40
+ readonly messageId: string;
41
+ readonly label: DaySeparatorLabel;
42
+ }
43
+
44
+ /** The two fields a separator is derived from. */
45
+ interface DatedMessage {
46
+ readonly id: string;
47
+ readonly createdAt?: string;
48
+ }
49
+
50
+ /** The local calendar day of an instant, as a key that compares equal only within one day. */
51
+ function localDayKey(date: Date): string {
52
+ return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
53
+ }
54
+
55
+ /** The instant a value names, or `null` if it names none. */
56
+ function instant(value: string | undefined): Date | null {
57
+ if (value === undefined) return null;
58
+ const date = new Date(value);
59
+ return Number.isNaN(date.getTime()) ? null : date;
60
+ }
61
+
62
+ /**
63
+ * How many local days back `date` is from `now`.
64
+ *
65
+ * Counted between local CALENDAR days rather than by subtracting milliseconds:
66
+ * a day is not 24 hours on the two days a year a timezone shifts, and an hour
67
+ * of error on those days would relabel "yesterday" as a date.
68
+ */
69
+ function daysBefore(date: Date, now: Date): number {
70
+ const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
71
+ const startOfNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
72
+ return Math.round((startOfNow.getTime() - startOfDate.getTime()) / 86_400_000);
73
+ }
74
+
75
+ function labelFor(date: Date, now: Date, locale: string): DaySeparatorLabel {
76
+ const back = daysBefore(date, now);
77
+ if (back === 0) return { kind: 'today' };
78
+ if (back === 1) return { kind: 'yesterday' };
79
+ return {
80
+ kind: 'date',
81
+ text: new Intl.DateTimeFormat(locale, {
82
+ weekday: 'short',
83
+ day: 'numeric',
84
+ month: 'short',
85
+ // Only when it is not this year. A year on every line is noise; a year on
86
+ // none of them is a thread that silently spans two.
87
+ ...(date.getFullYear() === now.getFullYear() ? {} : { year: 'numeric' }),
88
+ }).format(date),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * The separators a message list needs, in order.
94
+ *
95
+ * One per CHANGE of local day, so two messages on the same day produce none and
96
+ * a pair that straddles local midnight produces one. There is no separator above
97
+ * the first message: it would say "today" on top of every conversation anyone is
98
+ * currently having, which is a label for a boundary that is not there.
99
+ */
100
+ export function daySeparators(
101
+ messages: readonly DatedMessage[],
102
+ now: Date,
103
+ locale: string,
104
+ ): DaySeparator[] {
105
+ const separators: DaySeparator[] = [];
106
+ let previousKey: string | null = null;
107
+
108
+ for (const message of messages) {
109
+ const date = instant(message.createdAt);
110
+ if (date === null) continue;
111
+
112
+ const key = localDayKey(date);
113
+ if (previousKey !== null && key !== previousKey) {
114
+ separators.push({ messageId: message.id, label: labelFor(date, now, locale) });
115
+ }
116
+ previousKey = key;
117
+ }
118
+
119
+ return separators;
120
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Message Processor - Platform-specific message processing
3
+ *
4
+ * This module handles platform-specific processing of AI responses.
5
+ * Different platforms (Web/Mobile App vs Telegram) have different capabilities,
6
+ * so we process messages differently for each.
7
+ */
8
+
9
+ import { TITLE_STRIP_RE } from './title-tags';
10
+
11
+ export type Platform = 'app' | 'telegram';
12
+
13
+ export interface ProcessedMessage {
14
+ text: string;
15
+ components?: any[]; // Visual components for the app (COMPACTLIST, BANNER, etc.)
16
+ metadata?: Record<string, any>;
17
+ }
18
+
19
+ /**
20
+ * Process a message for the Web/Mobile App
21
+ * - Removes Telegram-specific tags ([REACT], [TGIMAGE], [TGLINKS], [TGDOC])
22
+ * - Preserves app-specific components ([COMPACTLIST], [BANNER], [COMPARISON], etc.)
23
+ */
24
+ function processForApp(content: string): ProcessedMessage {
25
+ // Remove Telegram-specific tags and title tags
26
+ const cleanedText = content
27
+ .replace(/\[(?:ALIA_)?REACT:[^\]]+\]\s*/g, '')
28
+ .replace(/\[(?:ALIA_)?TGIMAGE[^\]]*\]\s*/g, '')
29
+ .replace(/\[(?:ALIA_)?TGLINKS[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TGLINKS\]\s*/g, '')
30
+ .replace(/\[(?:ALIA_)?TGDOC[^\]]*\]\s*/g, '')
31
+ .replace(TITLE_STRIP_RE, '')
32
+ .trim();
33
+
34
+ // App-specific components like [COMPACTLIST], [BANNER], etc. are kept
35
+ // They will be rendered by the Markdown component
36
+ return {
37
+ text: cleanedText,
38
+ components: [], // Could extract components here if needed
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Process a message for Telegram
44
+ * - Removes app-specific components ([COMPACTLIST], [BANNER], etc.)
45
+ * - Preserves Telegram-specific tags for bot processing
46
+ */
47
+ function processForTelegram(content: string): ProcessedMessage {
48
+ // Remove app-specific visual components (not supported in Telegram)
49
+ const cleanedText = content
50
+ .replace(/\[(?:ALIA_)?COMPACTLIST[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPACTLIST\]\s*/g, '')
51
+ .replace(/\[(?:ALIA_)?BANNER[^\]]*\][\s\S]*?\[\/(?:ALIA_)?BANNER\]\s*/g, '')
52
+ .replace(/\[(?:ALIA_)?COMPARISON[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPARISON\]\s*/g, '')
53
+ .replace(/\[(?:ALIA_)?TIMELINE[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TIMELINE\]\s*/g, '')
54
+ .replace(/\[(?:ALIA_)?IMAGE[^\]]*\]/g, '')
55
+ .replace(/\[(?:ALIA_)?CREDIBILITY[^\]]*\]/g, '')
56
+ .replace(TITLE_STRIP_RE, '')
57
+ .trim();
58
+
59
+ // Telegram tags like [REACT], [TGIMAGE], etc. are kept
60
+ // They will be processed by the Telegram bot
61
+ return {
62
+ text: cleanedText,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Main message processor - Routes to platform-specific processor
68
+ */
69
+ export function processMessage(content: string, platform: Platform): ProcessedMessage {
70
+ switch (platform) {
71
+ case 'app':
72
+ return processForApp(content);
73
+ case 'telegram':
74
+ return processForTelegram(content);
75
+ default:
76
+ // Fallback: remove all special tags
77
+ return {
78
+ text: content
79
+ .replace(/\[(?:ALIA_)?REACT:[^\]]+\]\s*/g, '')
80
+ .replace(/\[(?:ALIA_)?TGIMAGE[^\]]*\]\s*/g, '')
81
+ .replace(/\[(?:ALIA_)?TGLINKS[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TGLINKS\]\s*/g, '')
82
+ .replace(/\[(?:ALIA_)?TGDOC[^\]]*\]\s*/g, '')
83
+ .replace(/\[(?:ALIA_)?COMPACTLIST[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPACTLIST\]\s*/g, '')
84
+ .replace(/\[(?:ALIA_)?BANNER[^\]]*\][\s\S]*?\[\/(?:ALIA_)?BANNER\]\s*/g, '')
85
+ .replace(/\[(?:ALIA_)?COMPARISON[^\]]*\][\s\S]*?\[\/(?:ALIA_)?COMPARISON\]\s*/g, '')
86
+ .replace(/\[(?:ALIA_)?TIMELINE[^\]]*\][\s\S]*?\[\/(?:ALIA_)?TIMELINE\]\s*/g, '')
87
+ .replace(/\[(?:ALIA_)?IMAGE[^\]]*\]/g, '')
88
+ .replace(/\[(?:ALIA_)?CREDIBILITY[^\]]*\]/g, '')
89
+ .replace(TITLE_STRIP_RE, '')
90
+ .trim(),
91
+ };
92
+ }
93
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The turns where another agent comes into the conversation.
3
+ *
4
+ * Agent-authored replies carry `agentInfo`, including the lead's scheduled or proactive replies.
5
+ * The conversation's members (the direct agent or the group's roster) distinguish those from
6
+ * consultations with an outside agent. The thread marks the turn where a consulted agent starts
7
+ * speaking, or starts again after the lead has spoken in between, with a line saying whom the person is now
8
+ * chatting with. Consecutive replies of one agent get the line once; the lead resuming gets none
9
+ * (it is the conversation's own voice) but does reset the run, so the same agent coming back is
10
+ * announced again.
11
+ *
12
+ * Only an agent from OUTSIDE the conversation is announced. The members of a group chat are in
13
+ * it: each speaks as itself, with its own name on its message, as in any group chat, and a line
14
+ * saying whom the person is "now chatting with" at each change of speaker would be wrong.
15
+ *
16
+ * What a consulted agent said is not part of the person's conversation: the lead already answers
17
+ * with it. The thread shows the line and nothing under it, and the line opens the exchange.
18
+ */
19
+ export interface SpeakerChange {
20
+ /** The agent that starts speaking here. */
21
+ readonly agentName: string;
22
+ }
23
+
24
+ export function speakerChanges(
25
+ rows: readonly {
26
+ readonly id: string;
27
+ readonly role: string;
28
+ readonly agentInfo?: { readonly id: string; readonly name: string } | null;
29
+ }[],
30
+ /** The direct agent or group members: never announced. */
31
+ members?: ReadonlySet<string>,
32
+ ): Map<string, SpeakerChange> {
33
+ const changes = new Map<string, SpeakerChange>();
34
+ let current: string | null = null;
35
+ for (const row of rows) {
36
+ if (row.role !== 'assistant') continue;
37
+ const speaker = row.agentInfo?.id ?? null;
38
+ if (speaker !== null && speaker !== current && row.agentInfo && !members?.has(speaker)) {
39
+ changes.set(row.id, { agentName: row.agentInfo.name });
40
+ }
41
+ current = speaker;
42
+ }
43
+ return changes;
44
+ }
45
+
46
+ /**
47
+ * The replies of agents from OUTSIDE the conversation, every one of them: what a consulted agent
48
+ * said, which the thread leaves out under the line that announces it (the exchange it opens has
49
+ * it). A group's members and the lead are never in it.
50
+ */
51
+ export function consultedReplies(
52
+ rows: readonly {
53
+ readonly id: string;
54
+ readonly role: string;
55
+ readonly agentInfo?: { readonly id: string; readonly name: string } | null;
56
+ }[],
57
+ members?: ReadonlySet<string>,
58
+ ): Set<string> {
59
+ const ids = new Set<string>();
60
+ for (const row of rows) {
61
+ if (row.role === 'assistant' && row.agentInfo && !members?.has(row.agentInfo.id)) {
62
+ ids.add(row.id);
63
+ }
64
+ }
65
+ return ids;
66
+ }
@@ -0,0 +1,11 @@
1
+ export function formatDuration(ms: number): string {
2
+ const seconds = Math.floor(ms / 1000);
3
+ if (seconds < 60) return `${seconds}s`;
4
+ const minutes = Math.floor(seconds / 60);
5
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
6
+ const hours = Math.floor(minutes / 60);
7
+ return `${hours}h ${minutes % 60}m`;
8
+ }
9
+
10
+ // The words for a tool — one definition, the SDK's, so its chat and this app name a call alike.
11
+ export { getToolDoneLabel, getToolPillLabel } from '../../tools';