@gemies/sdk 0.0.0-stage → 1.1.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 (246) hide show
  1. package/CHANGELOG.md +1678 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +15 -0
  4. package/README.md +516 -2
  5. package/package.json +105 -4
  6. package/src/accounts.ts +29 -0
  7. package/src/animations.ts +5 -0
  8. package/src/ask-eager.ts +8 -0
  9. package/src/ask-text.ts +11 -0
  10. package/src/ask.ts +12 -0
  11. package/src/avatar.ts +13 -0
  12. package/src/character.ts +1 -0
  13. package/src/components/AmbientField.tsx +580 -0
  14. package/src/components/ComposerDropZone.tsx +235 -0
  15. package/src/components/ComposerSuggestions.tsx +45 -0
  16. package/src/components/GemieAccounts.tsx +433 -0
  17. package/src/components/GemieAskCore.tsx +184 -0
  18. package/src/components/GemieAskProvider.tsx +18 -0
  19. package/src/components/GemieAskProviderLazy.tsx +27 -0
  20. package/src/components/GemieAskProviderText.tsx +25 -0
  21. package/src/components/GemieAskSheet.tsx +51 -0
  22. package/src/components/GemieAskSheetWithVoice.tsx +10 -0
  23. package/src/components/GemieAvatar.tsx +57 -0
  24. package/src/components/GemieAvatarIcon.tsx +35 -0
  25. package/src/components/GemieChatContent.tsx +900 -0
  26. package/src/components/GemieChatHeader.tsx +123 -0
  27. package/src/components/GemieChatScreen.tsx +170 -0
  28. package/src/components/GemieChatSheet.tsx +368 -0
  29. package/src/components/GemieChatWithVoice.tsx +13 -0
  30. package/src/components/GemieComposer.tsx +388 -0
  31. package/src/components/GemieGroupWelcome.tsx +37 -0
  32. package/src/components/GemieParticipants.tsx +133 -0
  33. package/src/components/GemieParticipantsHeader.tsx +27 -0
  34. package/src/components/GemieRecentConversations.tsx +65 -0
  35. package/src/components/GemieSharedConversation.tsx +87 -0
  36. package/src/components/GemieWelcomeMessage.tsx +58 -0
  37. package/src/components/IdentityMark.tsx +225 -0
  38. package/src/components/Image.tsx +12 -0
  39. package/src/components/InertWhen.tsx +48 -0
  40. package/src/components/PlanPreviewCard.tsx +53 -0
  41. package/src/components/QuestionCard.tsx +64 -0
  42. package/src/components/ReplyMarkdown.tsx +373 -0
  43. package/src/components/RichBlocks.tsx +195 -0
  44. package/src/components/VoiceModeIcon.tsx +18 -0
  45. package/src/components/canvas/CanvasComponent.tsx +65 -0
  46. package/src/components/canvas/ChartRenderer.tsx +73 -0
  47. package/src/components/canvas/CodeRenderer.tsx +20 -0
  48. package/src/components/canvas/DashboardRenderer.tsx +70 -0
  49. package/src/components/canvas/DeckRenderer.tsx +43 -0
  50. package/src/components/canvas/FormRenderer.tsx +101 -0
  51. package/src/components/canvas/MarkdownRenderer.tsx +14 -0
  52. package/src/components/canvas/TableRenderer.tsx +47 -0
  53. package/src/components/icons/RiEmojiPicker.tsx +39 -0
  54. package/src/components/icons/RiMoreDots.tsx +32 -0
  55. package/src/components/icons/RiReplyLine.tsx +25 -0
  56. package/src/components/thought/FilesAndSources.tsx +120 -0
  57. package/src/components/thought/ThoughtPanel.tsx +426 -0
  58. package/src/components/thought/ToolStep.tsx +134 -0
  59. package/src/components/thread/AgentExchangeView.tsx +112 -0
  60. package/src/components/thread/AgentResultCard.tsx +125 -0
  61. package/src/components/thread/AgentTaskCard.tsx +127 -0
  62. package/src/components/thread/ChatBubble.tsx +256 -0
  63. package/src/components/thread/GemieThread.tsx +455 -0
  64. package/src/components/thread/MessageBlockBoundary.tsx +78 -0
  65. package/src/components/thread/NewConversationOffer.tsx +54 -0
  66. package/src/components/thread/ThreadRow.tsx +598 -0
  67. package/src/components/thread/ThreadSearch.tsx +130 -0
  68. package/src/components/thread/ThreadSkeleton.tsx +30 -0
  69. package/src/components/thread/ToolResultCard.tsx +254 -0
  70. package/src/components/thread/TurnMenu.tsx +54 -0
  71. package/src/components/thread/TurnStatusLine.tsx +34 -0
  72. package/src/components/voice/GemieVoiceCall.tsx +21 -0
  73. package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
  74. package/src/components/voice/VoiceCallContext.ts +13 -0
  75. package/src/components/voice/VoiceControls.tsx +106 -0
  76. package/src/components/voice/VoiceSession.tsx +120 -0
  77. package/src/components/voice/withVoiceCall.tsx +25 -0
  78. package/src/csp.ts +50 -0
  79. package/src/dictation.ts +40 -0
  80. package/src/hooks/useAmbientWave.ts +184 -0
  81. package/src/hooks/useAtBottom.ts +51 -0
  82. package/src/hooks/useAttachMenu.ts +93 -0
  83. package/src/hooks/useAttachmentIntake.ts +401 -0
  84. package/src/hooks/useAudioLevelMonitor.ts +46 -0
  85. package/src/hooks/useAudioLevels.ts +51 -0
  86. package/src/hooks/useChatComposer.ts +309 -0
  87. package/src/hooks/useChatVoice.ts +129 -0
  88. package/src/hooks/useComposerSuggestions.ts +84 -0
  89. package/src/hooks/useDictation.ts +292 -0
  90. package/src/hooks/useDocumentPicker.ts +11 -0
  91. package/src/hooks/useFailedTurnToast.ts +43 -0
  92. package/src/hooks/useFocusWhenPresented.ts +41 -0
  93. package/src/hooks/useGemieActivity.ts +31 -0
  94. package/src/hooks/useImagePicker.ts +38 -0
  95. package/src/hooks/useMessageReactions.ts +119 -0
  96. package/src/hooks/useMessageVote.ts +50 -0
  97. package/src/hooks/useOpenThought.ts +79 -0
  98. package/src/hooks/usePendingQuestions.ts +19 -0
  99. package/src/hooks/useReadAloud.ts +92 -0
  100. package/src/hooks/useShareHandler.ts +24 -0
  101. package/src/hooks/useSoundEffects.ts +137 -0
  102. package/src/hooks/useTTS.ts +303 -0
  103. package/src/hooks/useThoughtScope.ts +59 -0
  104. package/src/hooks/useThreadRows.ts +157 -0
  105. package/src/hooks/useThreadView.ts +67 -0
  106. package/src/hooks/useTimelineWindow.ts +256 -0
  107. package/src/hooks/useVoiceLauncher.ts +180 -0
  108. package/src/hooks/useVoiceRoom.ts +212 -0
  109. package/src/index.ts +141 -0
  110. package/src/lib/activity-socket.ts +102 -0
  111. package/src/lib/activity-store.ts +53 -0
  112. package/src/lib/add-menu.ts +7 -0
  113. package/src/lib/agent-character.ts +28 -0
  114. package/src/lib/alia-character.ts +14 -0
  115. package/src/lib/alia-gemie.ts +6 -0
  116. package/src/lib/attachment-intake.ts +154 -0
  117. package/src/lib/attachment-tiles.ts +74 -0
  118. package/src/lib/audio-level.ts +130 -0
  119. package/src/lib/audio-request-auth.ts +4 -0
  120. package/src/lib/audio-session-binding.ts +27 -0
  121. package/src/lib/bubbles.tsx +16 -0
  122. package/src/lib/call-thread.ts +33 -0
  123. package/src/lib/canvas-result.ts +21 -0
  124. package/src/lib/catalogue-tool.ts +22 -0
  125. package/src/lib/citations.ts +192 -0
  126. package/src/lib/clipboard.ts +23 -0
  127. package/src/lib/content-utils.ts +46 -0
  128. package/src/lib/copy-en.ts +333 -0
  129. package/src/lib/copy-es.ts +330 -0
  130. package/src/lib/copy.ts +38 -0
  131. package/src/lib/deferred/document-picker.ts +2 -0
  132. package/src/lib/deferred/document-picker.web.ts +12 -0
  133. package/src/lib/deferred/expo-audio.ts +2 -0
  134. package/src/lib/deferred/expo-audio.web.ts +12 -0
  135. package/src/lib/deferred/image-data-url.ts +5 -0
  136. package/src/lib/deferred/image-data-url.web.ts +12 -0
  137. package/src/lib/dictation-protocol.ts +142 -0
  138. package/src/lib/dictation-recorder-types.ts +37 -0
  139. package/src/lib/dictation-recorder.native.ts +90 -0
  140. package/src/lib/dictation-recorder.ts +131 -0
  141. package/src/lib/dictation-stream.ts +238 -0
  142. package/src/lib/dictation.ts +216 -0
  143. package/src/lib/document-picker.ts +31 -0
  144. package/src/lib/domain.ts +12 -0
  145. package/src/lib/flights.ts +33 -0
  146. package/src/lib/focus-return.ts +66 -0
  147. package/src/lib/greeting.ts +15 -0
  148. package/src/lib/image-data-url.ts +35 -0
  149. package/src/lib/keyboard.native.tsx +25 -0
  150. package/src/lib/keyboard.tsx +55 -0
  151. package/src/lib/labels-es.ts +113 -0
  152. package/src/lib/labels.tsx +207 -0
  153. package/src/lib/origins.ts +28 -0
  154. package/src/lib/participants.ts +97 -0
  155. package/src/lib/pcm.ts +57 -0
  156. package/src/lib/power-level-options.ts +66 -0
  157. package/src/lib/questions.ts +92 -0
  158. package/src/lib/speech-language.ts +20 -0
  159. package/src/lib/speech-messages.ts +54 -0
  160. package/src/lib/speech-synthesis.ts +156 -0
  161. package/src/lib/suggestions.ts +53 -0
  162. package/src/lib/task-labels.ts +35 -0
  163. package/src/lib/text-input.ts +10 -0
  164. package/src/lib/tool-call-status.ts +28 -0
  165. package/src/lib/tool-icons.ts +36 -0
  166. package/src/lib/tool-registry.ts +71 -0
  167. package/src/lib/tool-renderers.tsx +32 -0
  168. package/src/lib/turn-state.ts +15 -0
  169. package/src/lib/utils.ts +35 -0
  170. package/src/lib/voice-audio-engine-types.ts +59 -0
  171. package/src/lib/voice-audio-engine.native.ts +232 -0
  172. package/src/lib/voice-audio-engine.ts +206 -0
  173. package/src/lib/voice-call-request.ts +49 -0
  174. package/src/lib/voice-call.ts +627 -0
  175. package/src/lib/voice-controls-labels.ts +31 -0
  176. package/src/lib/voice-levels.ts +64 -0
  177. package/src/lib/voice-protocol.ts +328 -0
  178. package/src/lib/voice-worklets.ts +19 -0
  179. package/src/lib/work-log.ts +370 -0
  180. package/src/metro/chart-importers.json +18 -0
  181. package/src/metro/granular-charts.js +3 -0
  182. package/src/metro/index.cjs +227 -0
  183. package/src/metro/index.d.cts +5 -0
  184. package/src/runtime/agents.ts +151 -0
  185. package/src/runtime/api.ts +144 -0
  186. package/src/runtime/app-assertion.ts +51 -0
  187. package/src/runtime/attachment-utils.ts +97 -0
  188. package/src/runtime/chat-turn-control.ts +74 -0
  189. package/src/runtime/composer-draft-store.ts +270 -0
  190. package/src/runtime/config.tsx +222 -0
  191. package/src/runtime/conversation-dates.ts +31 -0
  192. package/src/runtime/conversation-store.ts +49 -0
  193. package/src/runtime/conversations.ts +633 -0
  194. package/src/runtime/error-utils.ts +144 -0
  195. package/src/runtime/gemie-accounts.ts +182 -0
  196. package/src/runtime/host-tools.ts +290 -0
  197. package/src/runtime/index.ts +137 -0
  198. package/src/runtime/message-history.ts +124 -0
  199. package/src/runtime/message-reactions.ts +214 -0
  200. package/src/runtime/model.ts +39 -0
  201. package/src/runtime/oxy-files.ts +37 -0
  202. package/src/runtime/power-levels.ts +66 -0
  203. package/src/runtime/query-keys.ts +60 -0
  204. package/src/runtime/random-uuid.ts +25 -0
  205. package/src/runtime/reaction-cache.ts +45 -0
  206. package/src/runtime/room-events.ts +333 -0
  207. package/src/runtime/routes.ts +85 -0
  208. package/src/runtime/sharing.ts +217 -0
  209. package/src/runtime/sse-frame-reader.ts +88 -0
  210. package/src/runtime/stream-events.ts +154 -0
  211. package/src/runtime/stream-outcome.ts +21 -0
  212. package/src/runtime/thought-store.ts +103 -0
  213. package/src/runtime/thread/agent-activity.ts +261 -0
  214. package/src/runtime/thread/agent-exchange.ts +94 -0
  215. package/src/runtime/thread/automation-labels.ts +79 -0
  216. package/src/runtime/thread/conversation-export.ts +135 -0
  217. package/src/runtime/thread/message-days.ts +120 -0
  218. package/src/runtime/thread/message-processor.ts +93 -0
  219. package/src/runtime/thread/speaker-changes.ts +66 -0
  220. package/src/runtime/thread/task-utils.ts +11 -0
  221. package/src/runtime/thread/thought-utils.ts +750 -0
  222. package/src/runtime/thread/thread-history.ts +139 -0
  223. package/src/runtime/thread/timeline.ts +202 -0
  224. package/src/runtime/thread/title-tags.ts +8 -0
  225. package/src/runtime/thread/tool-cards.ts +387 -0
  226. package/src/runtime/turn-failure.ts +108 -0
  227. package/src/runtime/turn-preparation.ts +21 -0
  228. package/src/runtime/types.ts +172 -0
  229. package/src/runtime/usage-limit-error.ts +44 -0
  230. package/src/runtime/use-agent-activity.ts +80 -0
  231. package/src/runtime/use-conversation-stream.ts +1669 -0
  232. package/src/runtime/use-conversation-thread.ts +590 -0
  233. package/src/runtime/use-gemie-thread.ts +54 -0
  234. package/src/runtime/use-room-events.ts +75 -0
  235. package/src/runtime/use-start-conversation.ts +107 -0
  236. package/src/runtime/use-thread-history.ts +73 -0
  237. package/src/runtime/use-thread-search.ts +100 -0
  238. package/src/runtime/use-turn-edit.ts +99 -0
  239. package/src/text.ts +19 -0
  240. package/src/theme.ts +16 -0
  241. package/src/tools.ts +27 -0
  242. package/src/types.ts +161 -0
  243. package/src/voice-messages.ts +2 -0
  244. package/src/voice.ts +67 -0
  245. package/tsconfig.json +17 -0
  246. package/worklets/voice-processors.js +152 -0
@@ -0,0 +1,750 @@
1
+ import { getToolLabel } from '../../lib/tool-registry';
2
+ import type { FailedTurn } from '../turn-failure';
3
+ import type { Message, ToolInvocation } from '../types';
4
+
5
+ export interface Source {
6
+ title: string;
7
+ url: string;
8
+ snippet: string;
9
+ domain: string;
10
+ }
11
+
12
+ export interface ThoughtStep {
13
+ /**
14
+ * `thinking`, `tool` and `writing` are phases of the work; the other three are
15
+ * how it ENDED, and at most one of them closes a list. The panel translates
16
+ * every non-tool type itself — `label` is the English default, kept so a
17
+ * caller without a translator still has something to print.
18
+ */
19
+ type: 'thinking' | 'tool' | 'writing' | 'done' | 'failed' | 'cancelled';
20
+ label: string;
21
+ toolName?: string;
22
+ sources?: Source[];
23
+ state?: 'partial-call' | 'call' | 'result';
24
+ /**
25
+ * The invocation a tool step was built from, so a row can open its input
26
+ * and output in place without a second lookup by position. Only tool steps
27
+ * carry one.
28
+ */
29
+ invocation?: ToolInvocation;
30
+ }
31
+
32
+ /**
33
+ * Where a turn is in its life, as the runtime knows it — never as guessed
34
+ * from what the message happens to contain.
35
+ *
36
+ * - `queued`: the turn is in flight and nothing has arrived for it yet.
37
+ * - `running`: tokens, reasoning or tool calls are arriving.
38
+ * - `completed`: the run ended on its own terms.
39
+ * - `failed`: the run ended with an error — the failed-turn card is its twin.
40
+ * - `cancelled`: the person stopped it, or a persisted turn shows a tool that
41
+ * never returned, which is a run that was interrupted before it finished.
42
+ */
43
+ export type TurnLifecycle = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
44
+
45
+ /**
46
+ * What the streaming runtime knows about the conversation a message sits in.
47
+ *
48
+ * All of it is optional because a message read back from the server after a
49
+ * reload has none of it — and a message with no live context is, by
50
+ * definition, one whose turn is over.
51
+ */
52
+ export interface TurnContext {
53
+ /** The hook's `isLoading`: a turn is in flight in THIS conversation. */
54
+ isLoading?: boolean;
55
+ /**
56
+ * The message is the last assistant message of the conversation, which is
57
+ * the one a running turn writes into. Only meaningful with `isLoading`.
58
+ */
59
+ isLastAssistant?: boolean;
60
+ /** The turn that got no answer, if any — its anchor names the failed message. */
61
+ failedTurn?: FailedTurn | null;
62
+ }
63
+
64
+ /** The fields of a message the lifecycle is read from; a `Message` satisfies it. */
65
+ export type LifecycleMessage = Pick<
66
+ Message,
67
+ | 'id'
68
+ | 'content'
69
+ | 'thinking'
70
+ | 'toolInvocations'
71
+ | 'isStreaming'
72
+ | 'turnOutcome'
73
+ | 'researchProgress'
74
+ >;
75
+
76
+ /** A tool that was called and never came back — `call` or `partial-call`. */
77
+ function hasUnresolvedTool(message: Pick<LifecycleMessage, 'toolInvocations'>): boolean {
78
+ return message.toolInvocations?.some((inv) => inv.state !== 'result') ?? false;
79
+ }
80
+
81
+ function hasContent(content: LifecycleMessage['content'] | undefined): boolean {
82
+ return typeof content === 'string'
83
+ ? content.length > 0
84
+ : Array.isArray(content) && content.length > 0;
85
+ }
86
+
87
+ /** Anything at all has arrived for the turn: text, reasoning, a tool call or a research phase. */
88
+ function hasAnyOutput(message: LifecycleMessage): boolean {
89
+ return (
90
+ hasContent(message.content) ||
91
+ (message.thinking !== undefined && message.thinking.length > 0) ||
92
+ (message.toolInvocations?.length ?? 0) > 0 ||
93
+ message.researchProgress !== undefined
94
+ );
95
+ }
96
+
97
+ /**
98
+ * The lifecycle of a turn, from the signals the runtime actually tracks.
99
+ *
100
+ * The panel used to decide a turn had ended by looking at whether the message
101
+ * had content — so the first streamed token flipped a running answer to
102
+ * "Done", a finished tool-only turn looked like it was still running, and
103
+ * array content counted as finished the moment it existed. None of those
104
+ * are the turn's state; they are what the message happened to hold.
105
+ *
106
+ * The order here is the order of certainty:
107
+ *
108
+ * 1. A settled outcome on the message, or the failed-turn card anchored on
109
+ * it, is final — a stream cannot un-fail.
110
+ * 2. Otherwise the turn is live while its message is being streamed into.
111
+ * `isStreaming` is the hook's own stamp and is trusted on its own, EXCEPT
112
+ * against an explicit `isLoading: false`: a stamp that outlived the turn
113
+ * (persisted mid-stream, or left on a voice row) must not run forever.
114
+ * The `isLoading && isLastAssistant` pair is the fallback for a message
115
+ * that carries no stamp at all.
116
+ * 3. With no live signal the turn is over. A tool still in `call` then is
117
+ * one that never returned — an interrupted run, not a finished one.
118
+ */
119
+ export function turnLifecycle(message: LifecycleMessage, ctx: TurnContext = {}): TurnLifecycle {
120
+ if (message.turnOutcome === 'failed' || ctx.failedTurn?.anchorMessageId === message.id)
121
+ return 'failed';
122
+ if (message.turnOutcome === 'cancelled') return 'cancelled';
123
+ if (message.turnOutcome === 'completed') return 'completed';
124
+
125
+ const stamped = message.isStreaming === true && ctx.isLoading !== false;
126
+ const inferred = ctx.isLoading === true && ctx.isLastAssistant === true;
127
+ if (stamped || inferred) return hasAnyOutput(message) ? 'running' : 'queued';
128
+
129
+ return hasUnresolvedTool(message) ? 'cancelled' : 'completed';
130
+ }
131
+
132
+ /** The lifecycles during which the panel still animates. */
133
+ export function isLiveLifecycle(lifecycle: TurnLifecycle): boolean {
134
+ return lifecycle === 'queued' || lifecycle === 'running';
135
+ }
136
+
137
+ function getDomain(url: string): string {
138
+ try {
139
+ return new URL(url).hostname.replace('www.', '');
140
+ } catch {
141
+ return url;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The sources of a finished `deepResearch` invocation, as the research
147
+ * handler persists them: `{ id, url, title }[]` under `result.sources`, the
148
+ * same shape the final `alia.research_progress` event carries live. No
149
+ * snippet — research keeps excerpts server-side — so the card shows the
150
+ * title alone.
151
+ */
152
+ function researchInvocationSources(result: { sources?: unknown }): Source[] {
153
+ if (!Array.isArray(result.sources)) return [];
154
+ return researchSourcesToSources(
155
+ result.sources as Array<{ id?: unknown; url?: unknown; title?: unknown }>,
156
+ );
157
+ }
158
+
159
+ /**
160
+ * Research sources — from a persisted invocation or from the live progress
161
+ * event — in the shape the Sources row and panel render. One per URL: the
162
+ * tracker already de-duplicates server-side, and this keeps that true of
163
+ * whatever a row holds.
164
+ */
165
+ export function researchSourcesToSources(
166
+ sources?: Array<{ id?: unknown; url?: unknown; title?: unknown }> | null,
167
+ ): Source[] {
168
+ if (!sources) return [];
169
+ const seen = new Set<string>();
170
+ const out: Source[] = [];
171
+ for (const s of sources) {
172
+ if (!s || typeof s.url !== 'string' || s.url.length === 0 || seen.has(s.url)) continue;
173
+ seen.add(s.url);
174
+ const title =
175
+ typeof s.title === 'string' && s.title.trim().length > 0 ? s.title.trim() : getDomain(s.url);
176
+ out.push({ title, url: s.url, snippet: '', domain: getDomain(s.url) });
177
+ }
178
+ return out;
179
+ }
180
+
181
+ /** The union of two source lists, first occurrence of a URL winning. */
182
+ export function mergeSources(...lists: Source[][]): Source[] {
183
+ const seen = new Set<string>();
184
+ const out: Source[] = [];
185
+ for (const list of lists) {
186
+ for (const source of list) {
187
+ if (seen.has(source.url)) continue;
188
+ seen.add(source.url);
189
+ out.push(source);
190
+ }
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /**
196
+ * Extract unique sources from tool invocations (webSearch, webScraper,
197
+ * browse, and the `deepResearch` record a research answer is saved with).
198
+ */
199
+ export function extractSources(toolInvocations?: ToolInvocation[]): Source[] {
200
+ if (!toolInvocations) return [];
201
+
202
+ const seen = new Set<string>();
203
+ const sources: Source[] = [];
204
+
205
+ for (const inv of toolInvocations) {
206
+ if (inv.state !== 'result' || !inv.result) continue;
207
+
208
+ if (inv.toolName === 'deepResearch') {
209
+ for (const source of researchInvocationSources(inv.result)) {
210
+ if (seen.has(source.url)) continue;
211
+ seen.add(source.url);
212
+ sources.push(source);
213
+ }
214
+ continue;
215
+ }
216
+
217
+ if (
218
+ (inv.toolName === 'webSearch' ||
219
+ (inv.toolName === 'browse' && inv.result.action === 'search')) &&
220
+ Array.isArray(inv.result.results)
221
+ ) {
222
+ for (const r of inv.result.results) {
223
+ if (r.url && !seen.has(r.url)) {
224
+ seen.add(r.url);
225
+ sources.push({
226
+ title: r.title || getDomain(r.url),
227
+ url: r.url,
228
+ snippet: r.snippet || '',
229
+ domain: getDomain(r.url),
230
+ });
231
+ }
232
+ }
233
+ }
234
+
235
+ if (inv.toolName === 'browse' && inv.result.action === 'read' && inv.result.url) {
236
+ const url = inv.result.url;
237
+ if (!seen.has(url)) {
238
+ seen.add(url);
239
+ sources.push({
240
+ title: inv.result.title || getDomain(url),
241
+ url,
242
+ snippet: inv.result.content ? inv.result.content.slice(0, 200) : '',
243
+ domain: getDomain(url),
244
+ });
245
+ }
246
+ }
247
+
248
+ if (inv.toolName === 'webScraper' && inv.result.url) {
249
+ const url = inv.result.url;
250
+ if (!seen.has(url)) {
251
+ seen.add(url);
252
+ sources.push({
253
+ title: inv.result.title || getDomain(url),
254
+ url,
255
+ snippet: inv.result.content ? inv.result.content.slice(0, 200) : '',
256
+ domain: getDomain(url),
257
+ });
258
+ }
259
+ }
260
+ }
261
+
262
+ return sources;
263
+ }
264
+
265
+ /**
266
+ * Build an ordered timeline of steps from a message's thinking + tool
267
+ * invocations, closed by the step its lifecycle earns.
268
+ *
269
+ * The closing step is decided by the LIFECYCLE and nothing else: text in the
270
+ * message does not mean the turn is over (it is "Writing" while the turn
271
+ * runs), and a turn that ended in an error or a stop never reads "Done" — it
272
+ * gets its own terminal step. A tool still running is left in its own state
273
+ * so a finished tool before it does not hide it.
274
+ */
275
+ export function buildSteps(
276
+ message: Partial<Pick<LifecycleMessage, 'thinking' | 'content' | 'toolInvocations'>>,
277
+ lifecycle: TurnLifecycle,
278
+ ): ThoughtStep[] {
279
+ const steps: ThoughtStep[] = [];
280
+
281
+ // 1. Thinking step — also what a queued turn shows, since a turn with nothing
282
+ // to show yet is nonetheless being thought about.
283
+ if (message.thinking || lifecycle === 'queued') {
284
+ steps.push({ type: 'thinking', label: 'Thinking' });
285
+ }
286
+
287
+ // 2. Tool invocation steps
288
+ if (message.toolInvocations) {
289
+ for (const inv of message.toolInvocations) {
290
+ const step: ThoughtStep = {
291
+ type: 'tool',
292
+ label: getToolLabel(inv.toolName),
293
+ toolName: inv.toolName,
294
+ state: inv.state,
295
+ invocation: inv,
296
+ };
297
+
298
+ // A research step carries every source the answer was written from.
299
+ if (inv.toolName === 'deepResearch' && inv.state === 'result' && inv.result) {
300
+ const researchSources = researchInvocationSources(inv.result);
301
+ if (researchSources.length > 0) step.sources = researchSources;
302
+ }
303
+
304
+ // Attach sources for search tools that have results
305
+ if (
306
+ (inv.toolName === 'webSearch' ||
307
+ (inv.toolName === 'browse' && inv.result?.action === 'search')) &&
308
+ inv.state === 'result' &&
309
+ inv.result?.results
310
+ ) {
311
+ step.sources = inv.result.results
312
+ .filter((r: any) => r.url)
313
+ .map((r: any) => ({
314
+ title: r.title || getDomain(r.url),
315
+ url: r.url,
316
+ snippet: r.snippet || '',
317
+ domain: getDomain(r.url),
318
+ }));
319
+ }
320
+
321
+ steps.push(step);
322
+ }
323
+ }
324
+
325
+ // 3. The step the lifecycle closes the list with.
326
+ switch (lifecycle) {
327
+ case 'queued':
328
+ break;
329
+ case 'running':
330
+ // A tool that has not returned is the live step; otherwise the model is
331
+ // writing, whether or not its first token has been flushed yet.
332
+ if (!hasUnresolvedTool(message)) steps.push({ type: 'writing', label: 'Writing' });
333
+ break;
334
+ case 'completed':
335
+ // "Done" under a message that holds nothing at all would be a step
336
+ // about nothing; a finished tool-only turn, though, is done.
337
+ if (steps.length > 0 || hasContent(message.content))
338
+ steps.push({ type: 'done', label: 'Done' });
339
+ break;
340
+ case 'failed':
341
+ steps.push({ type: 'failed', label: 'Failed' });
342
+ break;
343
+ case 'cancelled':
344
+ steps.push({ type: 'cancelled', label: 'Stopped' });
345
+ break;
346
+ }
347
+
348
+ return steps;
349
+ }
350
+
351
+ /**
352
+ * Text an audit row shows, before it is translated.
353
+ *
354
+ * The timeline is built outside React, with no translator, and it used to
355
+ * build its rows' words in English right here ("Plan", "3 steps",
356
+ * "Research: synthesizing") — so the Activity tab was English in every
357
+ * locale. It now says WHAT to show and the panel says it:
358
+ *
359
+ * - `key`: an i18n key and its params.
360
+ * - `tool`: a tool's own label, by tool name — see `toolLabel`.
361
+ * - `text`: words that are the conversation's own (a query, a file name, a
362
+ * server's progress message), shown as they are.
363
+ */
364
+ export type AuditText =
365
+ | { key: string; params?: Record<string, string | number> }
366
+ | { tool: string }
367
+ | { text: string };
368
+
369
+ /**
370
+ * The tools this app has its own words for, in every locale.
371
+ *
372
+ * A set rather than a lookup into the catalog: `toolName` is an open string
373
+ * off the wire, and `thought.tool.constructor` would resolve to
374
+ * `Object.prototype.constructor` inside i18n-js. Anything else falls back to
375
+ * the SDK registry's English label, then to the raw name.
376
+ */
377
+ const TRANSLATED_TOOLS: ReadonlySet<string> = new Set([
378
+ 'webSearch',
379
+ 'scrapeURL',
380
+ 'getTimeline',
381
+ 'searchKnowledgeBase',
382
+ 'webScraper',
383
+ 'browse',
384
+ 'sendAccountMessage',
385
+ 'listAccountChats',
386
+ 'readAccountMessages',
387
+ 'sendTelegramMessage',
388
+ 'getCurrentDate',
389
+ 'generateFile',
390
+ 'saveUserMemory',
391
+ 'updateUserPreferences',
392
+ 'updateUserContext',
393
+ ]);
394
+
395
+ type Translate = (key: string, params?: Record<string, unknown>) => string;
396
+
397
+ /** A tool's label in the reader's language, where the app has one. */
398
+ export function toolLabel(toolName: string, t: Translate): string {
399
+ return TRANSLATED_TOOLS.has(toolName) ? t(`thought.tool.${toolName}`) : getToolLabel(toolName);
400
+ }
401
+
402
+ /** An `AuditText`, as the words a row shows. */
403
+ export function auditText(text: AuditText, t: Translate): string {
404
+ if ('key' in text) return t(text.key, text.params);
405
+ if ('tool' in text) return toolLabel(text.tool, t);
406
+ return text.text;
407
+ }
408
+
409
+ /** Research phases the Activity tab names; any other reads as "Researching". */
410
+ const RESEARCH_PHASES: ReadonlySet<string> = new Set([
411
+ 'decomposing',
412
+ 'searching',
413
+ 'reading',
414
+ 'synthesizing',
415
+ 'follow_up',
416
+ 'finalizing',
417
+ ]);
418
+
419
+ /**
420
+ * Entry in the action audit timeline.
421
+ */
422
+ export interface AuditEntry {
423
+ id: string;
424
+ type: 'tool_call' | 'research_phase' | 'agent_delegation' | 'plan' | 'artifact_generated';
425
+ label: AuditText;
426
+ description: AuditText;
427
+ /** `interrupted` is a tool call that never returned in a turn that is over. */
428
+ status: 'in_progress' | 'complete' | 'interrupted';
429
+ toolName?: string;
430
+ messageId: string;
431
+ }
432
+
433
+ /**
434
+ * Build a chronological audit timeline from all conversation messages.
435
+ *
436
+ * A tool call without a result is "in progress" only while its turn is
437
+ * actually running; in a turn that ended — stopped, failed, or read back from
438
+ * the server that way — it is a call that never returned, and it must not
439
+ * pulse forever.
440
+ */
441
+ export function buildAuditTimeline(
442
+ messages: Message[],
443
+ ctx: Omit<TurnContext, 'isLastAssistant'> = {},
444
+ ): AuditEntry[] {
445
+ const entries: AuditEntry[] = [];
446
+ const lastAssistant = [...messages].reverse().find((m) => m.role === 'assistant');
447
+
448
+ for (const msg of messages) {
449
+ if (msg.role !== 'assistant') continue;
450
+ const live = isLiveLifecycle(
451
+ turnLifecycle(msg, { ...ctx, isLastAssistant: msg === lastAssistant }),
452
+ );
453
+
454
+ // Agent delegation
455
+ if (msg.agentInfo) {
456
+ entries.push({
457
+ id: `agent-${msg.id}`,
458
+ type: 'agent_delegation',
459
+ label: { key: 'thought.audit.agent', params: { name: msg.agentInfo.name } },
460
+ description: { text: typeof msg.content === 'string' ? msg.content.slice(0, 80) : '' },
461
+ status: 'complete',
462
+ messageId: msg.id,
463
+ });
464
+ }
465
+
466
+ // The plan it showed
467
+ if (msg.plan) {
468
+ entries.push({
469
+ id: `plan-${msg.id}`,
470
+ type: 'plan',
471
+ label: { key: 'thought.audit.plan' },
472
+ description: {
473
+ key: 'thought.audit.planSteps',
474
+ params: { count: msg.plan.steps?.length || 0 },
475
+ },
476
+ status: 'complete',
477
+ messageId: msg.id,
478
+ });
479
+ }
480
+
481
+ // Tool invocations
482
+ if (msg.toolInvocations) {
483
+ for (const inv of msg.toolInvocations) {
484
+ const isDone = inv.state === 'result';
485
+ let description = '';
486
+ if (inv.args?.query) {
487
+ const q = String(inv.args.query);
488
+ description = q.length > 50 ? q.slice(0, 50) + '...' : q;
489
+ } else if (inv.args?.url) {
490
+ const u = String(inv.args.url);
491
+ description = u.length > 50 ? u.slice(0, 50) + '...' : u;
492
+ }
493
+
494
+ entries.push({
495
+ id: inv.toolCallId || `tool-${msg.id}-${inv.toolName}`,
496
+ type: 'tool_call',
497
+ label: { tool: inv.toolName },
498
+ description: { text: description },
499
+ status: isDone ? 'complete' : live ? 'in_progress' : 'interrupted',
500
+ toolName: inv.toolName,
501
+ messageId: msg.id,
502
+ });
503
+
504
+ // Artifact generated from generateFile
505
+ if (inv.toolName === 'generateFile' && isDone && inv.result) {
506
+ entries.push({
507
+ id: `artifact-${inv.toolCallId}`,
508
+ type: 'artifact_generated',
509
+ label: { key: 'thought.audit.fileGenerated' },
510
+ description: { text: inv.result.filename || inv.result.title || '' },
511
+ status: 'complete',
512
+ messageId: msg.id,
513
+ });
514
+ }
515
+ }
516
+ }
517
+
518
+ // Research phases. `failed` is the engine saying the write-up did not
519
+ // happen: finished, not in progress, and not "complete" either.
520
+ if (msg.researchProgress) {
521
+ const rp = msg.researchProgress;
522
+ const failed = rp.phase === 'failed';
523
+ entries.push({
524
+ id: `research-${msg.id}`,
525
+ type: 'research_phase',
526
+ label: failed
527
+ ? { key: 'thought.audit.researchIncomplete' }
528
+ : rp.isComplete
529
+ ? { key: 'thought.audit.researchComplete' }
530
+ : rp.phase !== undefined && RESEARCH_PHASES.has(rp.phase)
531
+ ? { key: `thought.audit.researchPhase.${rp.phase}` }
532
+ : { key: 'thought.audit.researching' },
533
+ description: { text: rp.message || '' },
534
+ status: rp.isComplete || failed ? 'complete' : 'in_progress',
535
+ messageId: msg.id,
536
+ });
537
+ }
538
+ }
539
+
540
+ return entries;
541
+ }
542
+
543
+ // ---------------------------------------------------------------------------
544
+ // Execution rows (#544): what one tool call reads as, what a turn produced,
545
+ // and how long it worked.
546
+ // ---------------------------------------------------------------------------
547
+
548
+ /**
549
+ * How a single tool call reads in an execution row (`running`, `done`, `error`,
550
+ * `interrupted`). One definition, the SDK's, so its chat and this app agree.
551
+ */
552
+ export { type ToolCallStatus, toolCallStatus } from '../../tools';
553
+
554
+ /** Upper bound on the text an expanded row prints for one side of a call. */
555
+ const TOOL_TEXT_LIMIT = 4000;
556
+
557
+ /**
558
+ * One side of a tool call — its arguments or its result — as text a reader
559
+ * can scan. Strings are printed as they are; anything else is pretty JSON.
560
+ * Long output is cut with a marker rather than hidden, so a row never shows
561
+ * a fragment as if it were the whole.
562
+ */
563
+ export function toolCallText(value: unknown, limit = TOOL_TEXT_LIMIT): string {
564
+ if (value === undefined || value === null) return '';
565
+ let text: string;
566
+ if (typeof value === 'string') {
567
+ text = value;
568
+ } else {
569
+ try {
570
+ text = JSON.stringify(value, null, 2) ?? '';
571
+ } catch {
572
+ text = String(value);
573
+ }
574
+ }
575
+ return text.length > limit ? `${text.slice(0, limit)}\n…` : text;
576
+ }
577
+
578
+ /** A file a turn produced, as the Outputs section lists it. */
579
+ export interface OutputFile {
580
+ /** The invocation's id, which is also the canvas artifact's id when one was made. */
581
+ id: string;
582
+ name: string;
583
+ toolName: string;
584
+ }
585
+
586
+ /**
587
+ * The files a message's tools generated, read off the same persisted
588
+ * `toolInvocations` the sources come from: a finished `generateFile` names
589
+ * its file, and any tool that returned an `artifact` names that. Nothing is
590
+ * invented for a call that did not return — a running or interrupted
591
+ * generation is a step, not an output.
592
+ */
593
+ export function extractOutputs(toolInvocations?: ToolInvocation[]): OutputFile[] {
594
+ if (!toolInvocations) return [];
595
+ const outputs: OutputFile[] = [];
596
+ for (const inv of toolInvocations) {
597
+ if (inv.state !== 'result' || !inv.result || typeof inv.result !== 'object') continue;
598
+ const result = inv.result as {
599
+ filename?: unknown;
600
+ title?: unknown;
601
+ artifact?: { title?: unknown } | null;
602
+ };
603
+ let name: string | null = null;
604
+ if (inv.toolName === 'generateFile') {
605
+ name =
606
+ typeof result.filename === 'string' && result.filename.length > 0
607
+ ? result.filename
608
+ : typeof result.title === 'string' && result.title.length > 0
609
+ ? result.title
610
+ : getToolLabel(inv.toolName);
611
+ } else if (result.artifact && typeof result.artifact === 'object') {
612
+ name =
613
+ typeof result.artifact.title === 'string' && result.artifact.title.length > 0
614
+ ? result.artifact.title
615
+ : getToolLabel(inv.toolName);
616
+ }
617
+ if (name === null) continue;
618
+ outputs.push({
619
+ id: inv.toolCallId || `output-${outputs.length}`,
620
+ name,
621
+ toolName: inv.toolName,
622
+ });
623
+ }
624
+ return outputs;
625
+ }
626
+
627
+ /**
628
+ * When a turn started and, if the conversation says, when it ended — both as
629
+ * epoch milliseconds, `null` where the conversation does not say.
630
+ *
631
+ * The start is the send: the user message before this one carries the
632
+ * client's own stamp (the hook writes it and `POST /conversations` keeps it).
633
+ * The end is the assistant row's stamp, which the server writes when the
634
+ * turn is SAVED — after the model finished — so on a reloaded thread the two
635
+ * bracket the work. A message the client has only just appended carries the
636
+ * send time on both rows, and an older thread saved before clients stamped
637
+ * their sends carries the save time on both; either way the gap is nothing,
638
+ * which is not an elapsed time. Under a second is therefore read as "the
639
+ * conversation does not say".
640
+ */
641
+ export interface TurnTiming {
642
+ startedAt: number | null;
643
+ endedAt: number | null;
644
+ }
645
+
646
+ const MIN_PERSISTED_ELAPSED_MS = 1000;
647
+
648
+ function stampToMs(stamp: string | undefined): number | null {
649
+ if (stamp === undefined) return null;
650
+ const ms = Date.parse(stamp);
651
+ return Number.isNaN(ms) ? null : ms;
652
+ }
653
+
654
+ /**
655
+ * Every turn's timing, in one pass over the thread.
656
+ *
657
+ * ## Why this exists beside `turnTiming`
658
+ *
659
+ * `turnTiming` answers for ONE message and has to find it first, so it opens
660
+ * with `messages.findIndex(...)` and then walks backwards for the send that
661
+ * started the turn. Both are scans. That is the right shape for the execution
662
+ * panel, which asks about a single message a person has opened.
663
+ *
664
+ * The thread asks about all of them. The thread once called it once per
665
+ * row, inside the render, with the WHOLE list as the second argument — so
666
+ * drawing n messages cost O(n²) comparisons, and it paid that on every render.
667
+ * The list re-renders roughly twenty times a second while an answer streams,
668
+ * which is where this stops being a curiosity: at a thousand messages the
669
+ * lookup alone is on the order of half a million comparisons per frame, for an
670
+ * answer that does not change as tokens arrive.
671
+ *
672
+ * One pass, carrying the last user stamp forward, gives the same answers in
673
+ * O(n). The per-message function stays for its own callers and for the cases
674
+ * this one cannot serve — a message that is not in the list it was handed.
675
+ *
676
+ * Keyed by message id. A message with no id is skipped rather than colliding
677
+ * with another one under `undefined`.
678
+ */
679
+ export function turnTimings(
680
+ messages: ReadonlyArray<{ id: string; role: string; createdAt?: string }>,
681
+ ): Map<string, TurnTiming> {
682
+ const timings = new Map<string, TurnTiming>();
683
+ /** The stamp of the last user message SEEN, which is the send that opened the turn each row below belongs to. */
684
+ let sendStamp: number | null = null;
685
+
686
+ for (const message of messages) {
687
+ const ownStamp = stampToMs(message.createdAt);
688
+
689
+ // Read before writing: a user message's own turn is bracketed by the send
690
+ // BEFORE it, never by itself. The original walked backwards from the row
691
+ // and broke on the first user message, which is the same message this
692
+ // carries forward.
693
+ if (message.id !== undefined) {
694
+ timings.set(message.id, {
695
+ startedAt: sendStamp ?? ownStamp,
696
+ endedAt:
697
+ sendStamp !== null &&
698
+ ownStamp !== null &&
699
+ ownStamp - sendStamp >= MIN_PERSISTED_ELAPSED_MS
700
+ ? ownStamp
701
+ : null,
702
+ });
703
+ }
704
+
705
+ if (message.role === 'user') sendStamp = ownStamp;
706
+ }
707
+
708
+ return timings;
709
+ }
710
+
711
+ export function turnTiming(
712
+ message: { id: string; createdAt?: string },
713
+ messages: ReadonlyArray<{ id: string; role: string; createdAt?: string }>,
714
+ ): TurnTiming {
715
+ const index = messages.findIndex((m) => m.id === message.id);
716
+ let sendStamp: number | null = null;
717
+ for (let i = index - 1; i >= 0; i -= 1) {
718
+ const earlier = messages[i];
719
+ if (earlier?.role === 'user') {
720
+ sendStamp = stampToMs(earlier.createdAt);
721
+ break;
722
+ }
723
+ }
724
+ const ownStamp = stampToMs(message.createdAt);
725
+ const startedAt = sendStamp ?? ownStamp;
726
+ const endedAt =
727
+ sendStamp !== null && ownStamp !== null && ownStamp - sendStamp >= MIN_PERSISTED_ELAPSED_MS
728
+ ? ownStamp
729
+ : null;
730
+ return { startedAt, endedAt };
731
+ }
732
+
733
+ /**
734
+ * An elapsed time the way the summary row prints it: `10s`, `1m 5s`, `1h 2m`.
735
+ * `long` spells the units out for an accessible name, where "10s" is read as
736
+ * a letter. Rounded to the second; anything under one reads as `0s`.
737
+ */
738
+ export function formatElapsed(ms: number, long = false): string {
739
+ const total = Math.max(0, Math.round(ms / 1000));
740
+ const hours = Math.floor(total / 3600);
741
+ const minutes = Math.floor((total % 3600) / 60);
742
+ const seconds = total % 60;
743
+ const unit = (n: number, short: string, one: string, many: string): string =>
744
+ long ? `${n} ${n === 1 ? one : many}` : `${n}${short}`;
745
+ if (hours > 0)
746
+ return `${unit(hours, 'h', 'hour', 'hours')} ${unit(minutes, 'm', 'minute', 'minutes')}`;
747
+ if (minutes > 0)
748
+ return `${unit(minutes, 'm', 'minute', 'minutes')} ${unit(seconds, 's', 'second', 'seconds')}`;
749
+ return unit(seconds, 's', 'second', 'seconds');
750
+ }