@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,88 @@
1
+ /**
2
+ * Reassembles an SSE byte stream into whole frames.
3
+ *
4
+ * ## Why this is a module rather than a few lines inside the read loop
5
+ *
6
+ * It used to be a few lines inside the read loop, and that is exactly how the
7
+ * bug happened. `buffer` was correctly declared outside the loop, so a line
8
+ * split across two `reader.read()` calls survived — but `currentEventType` was
9
+ * declared INSIDE it and reset to `''` on every chunk. A frame is
10
+ * `event: X\ndata: {…}\n\n` (`packages/api/src/lib/sse-emitter.ts:24`), and a
11
+ * chunk boundary falls wherever the network puts it, so any frame split between
12
+ * its `event:` and `data:` lines arrived with its type forgotten. It then fell
13
+ * through to the OpenAI-shaped branch, found no `choices[0]`, and was dropped
14
+ * without a trace.
15
+ *
16
+ * The events that carry the most bytes are the ones most likely to be split, so
17
+ * this was not rare and not uniform: `alia.title`, `alia.tool_result`,
18
+ * `alia.plan_preview`, `alia.host_action`, `alia.agent_turn` and the
19
+ * artifact events are precisely the large ones. A title that sometimes does not
20
+ * arrive, a canvas that sometimes does not open.
21
+ *
22
+ * Two pieces of state that must both outlive a chunk are easy to get half
23
+ * right when they are loose variables in a 1 000-line hook, and hard to get
24
+ * wrong when they are fields of one object whose whole job is to hold them.
25
+ * That is the reason for this file, and the reason the test can feed the same
26
+ * stream split at every byte offset — which no test of the hook could do.
27
+ */
28
+
29
+ export interface SseFrame {
30
+ /** The `event:` name, or `''` for an unnamed (OpenAI-shaped) frame. */
31
+ readonly event: string;
32
+ /** The `data:` payload, trimmed. `[DONE]` is passed through as-is. */
33
+ readonly data: string;
34
+ }
35
+
36
+ export interface SseFrameReader {
37
+ /** Feed one decoded chunk; get back every frame it completed. */
38
+ push(chunk: string): SseFrame[];
39
+ }
40
+
41
+ export function createSseFrameReader(): SseFrameReader {
42
+ let buffer = '';
43
+ let currentEventType = '';
44
+
45
+ return {
46
+ push(chunk: string): SseFrame[] {
47
+ buffer += chunk;
48
+
49
+ const frames: SseFrame[] = [];
50
+ const lines = buffer.split('\n');
51
+ // The trailing element is whatever came after the last newline, which is
52
+ // an incomplete line unless the chunk happened to end on a boundary (in
53
+ // which case it is `''` and costs nothing to carry).
54
+ buffer = lines.pop() ?? '';
55
+
56
+ for (const rawLine of lines) {
57
+ // A stream that uses CRLF leaves the CR on the end of every line;
58
+ // `data: {…}\r` is not valid JSON.
59
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
60
+
61
+ if (line.startsWith('event: ')) {
62
+ currentEventType = line.slice(7).trim();
63
+ continue;
64
+ }
65
+
66
+ // A blank line closes a frame. Resetting here is what stops a `data:`
67
+ // line in the NEXT frame inheriting this frame's event name.
68
+ if (line === '') {
69
+ currentEventType = '';
70
+ continue;
71
+ }
72
+
73
+ if (line.startsWith('data: ')) {
74
+ frames.push({ event: currentEventType, data: line.slice(6).trim() });
75
+ // One `data:` line is one frame for this protocol. The event name is
76
+ // consumed with it, so a second `data:` without its own `event:` is
77
+ // correctly unnamed rather than inheriting.
78
+ currentEventType = '';
79
+ }
80
+
81
+ // Comments (`: keep-alive`) and any field this client does not read
82
+ // are ignored, as the SSE specification requires.
83
+ }
84
+
85
+ return frames;
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The stream frames of ADR 0020, read strictly (`docs/agent-embedding.md` §2, §4, §5).
3
+ *
4
+ * A frame is kept only when it has the version and every field the contract names, with the
5
+ * types it names; anything else is not that frame and is dropped whole, never half-applied. Pure:
6
+ * `use-conversation-stream.ts` decides what each one does to the thread.
7
+ */
8
+
9
+ /** The consulted agent, as `alia.agent_start` names it. */
10
+ export interface ConsultAgent {
11
+ id: string;
12
+ name: string;
13
+ handle?: string;
14
+ color?: string;
15
+ character?: unknown;
16
+ }
17
+
18
+ export type ConsultEvent =
19
+ | { type: 'start'; consultId: string; agent: ConsultAgent; task?: string }
20
+ | { type: 'delta'; consultId: string; content: string }
21
+ | {
22
+ type: 'tool';
23
+ consultId: string;
24
+ phase: 'call' | 'result';
25
+ toolCallId: string;
26
+ name: string;
27
+ input?: Record<string, unknown>;
28
+ output?: unknown;
29
+ }
30
+ | {
31
+ type: 'end';
32
+ consultId: string;
33
+ status: 'completed' | 'failed';
34
+ content?: string;
35
+ messageId?: string;
36
+ errorCode?: string;
37
+ };
38
+ type Raw = Record<string, unknown>;
39
+
40
+ const isObject = (value: unknown): value is Raw =>
41
+ value !== null && typeof value === 'object' && !Array.isArray(value);
42
+ const isText = (value: unknown): value is string => typeof value === 'string' && value !== '';
43
+ const optionalText = (value: unknown): string | undefined =>
44
+ typeof value === 'string' && value !== '' ? value : undefined;
45
+
46
+ /** A frame of this contract: version 1 and a consult it belongs to. */
47
+ function versioned(data: unknown): (Raw & { consultId: string }) | null {
48
+ if (!isObject(data) || data.eventVersion !== 1 || !isText(data.consultId)) return null;
49
+ return data as Raw & { consultId: string };
50
+ }
51
+
52
+ /** The consult frame `event` carries, or `null` when it is not one or not well-formed. */
53
+ export function parseConsultEvent(event: string, data: unknown): ConsultEvent | null {
54
+ const frame = versioned(data);
55
+ if (frame === null) return null;
56
+ const { consultId } = frame;
57
+ switch (event) {
58
+ case 'alia.agent_start': {
59
+ const agent = frame.agent;
60
+ if (!isObject(agent) || !isText(agent.id) || !isText(agent.name)) return null;
61
+ return {
62
+ type: 'start',
63
+ consultId,
64
+ agent: {
65
+ id: agent.id,
66
+ name: agent.name,
67
+ ...(optionalText(agent.handle) ? { handle: agent.handle as string } : {}),
68
+ ...(optionalText(agent.color) ? { color: agent.color as string } : {}),
69
+ ...(agent.character === undefined || agent.character === null
70
+ ? {}
71
+ : { character: agent.character }),
72
+ },
73
+ ...(optionalText(frame.task) ? { task: frame.task as string } : {}),
74
+ };
75
+ }
76
+ case 'alia.agent_delta':
77
+ return typeof frame.content === 'string'
78
+ ? { type: 'delta', consultId, content: frame.content }
79
+ : null;
80
+ case 'alia.agent_tool': {
81
+ const { phase, toolCallId, name, input } = frame;
82
+ if ((phase !== 'call' && phase !== 'result') || !isText(toolCallId) || !isText(name)) {
83
+ return null;
84
+ }
85
+ if (input !== undefined && !isObject(input)) return null;
86
+ return {
87
+ type: 'tool',
88
+ consultId,
89
+ phase,
90
+ toolCallId,
91
+ name,
92
+ ...(input === undefined ? {} : { input }),
93
+ ...(phase === 'result' ? { output: frame.output } : {}),
94
+ };
95
+ }
96
+ case 'alia.agent_end': {
97
+ const { status, content, error, messageId } = frame;
98
+ if (status !== 'completed' && status !== 'failed') return null;
99
+ if (content !== undefined && typeof content !== 'string') return null;
100
+ if (messageId !== undefined && !isText(messageId)) return null;
101
+ const errorCode = isObject(error) && isText(error.code) ? error.code : undefined;
102
+ return {
103
+ type: 'end',
104
+ consultId,
105
+ status,
106
+ ...(content === undefined ? {} : { content }),
107
+ ...(messageId === undefined ? {} : { messageId }),
108
+ ...(errorCode === undefined ? {} : { errorCode }),
109
+ };
110
+ }
111
+ default:
112
+ return null;
113
+ }
114
+ }
115
+
116
+ /** A UI effect the model asked the embedding client for (`alia.host_action`). */
117
+ export interface HostAction {
118
+ toolCallId: string;
119
+ app: string;
120
+ name: string;
121
+ input: Record<string, unknown>;
122
+ /**
123
+ * The model is waiting for this action's result within the same turn: its outcome is answered
124
+ * at once on the turn's `host-results` route, never with the next request.
125
+ */
126
+ awaitsResult?: true;
127
+ /** The turn that waits, present exactly when `awaitsResult` is. */
128
+ turnId?: string;
129
+ }
130
+
131
+ /** The host action an `alia.host_action` frame carries, or `null` when it is not well-formed. */
132
+ export function parseHostAction(data: unknown): HostAction | null {
133
+ if (!isObject(data) || data.eventVersion !== 1) return null;
134
+ const { toolCallId, app, name, input, awaitsResult, turnId } = data;
135
+ if (!isText(toolCallId) || !isText(app) || !isText(name)) return null;
136
+ if (input !== undefined && !isObject(input)) return null;
137
+ if (awaitsResult !== undefined && (awaitsResult !== true || !isText(turnId))) return null;
138
+ return {
139
+ toolCallId,
140
+ app,
141
+ name,
142
+ input: (input as Record<string, unknown> | undefined) ?? {},
143
+ ...(awaitsResult === true ? { awaitsResult: true as const, turnId: turnId as string } : {}),
144
+ };
145
+ }
146
+
147
+ /** The error code that ends a turn an agent's feature gate refused (§5). */
148
+ export const FEATURE_ENTITLEMENT_REQUIRED = 'feature_entitlement_required';
149
+
150
+ /** The feature an error refused, when the error is a feature gate's refusal. */
151
+ export function lockedFeatureOf(error: unknown): string | null {
152
+ if (!isObject(error) || error.code !== FEATURE_ENTITLEMENT_REQUIRED) return null;
153
+ return isText(error.feature) ? error.feature : null;
154
+ }
@@ -0,0 +1,21 @@
1
+ /** Evidence the client may use to decide whether a streamed turn answered. */
2
+ export interface StreamOutputEvidence {
3
+ realOutputChars: number;
4
+ agentOutputChars: number;
5
+ durableArtifactCount: number;
6
+ /** Progress only. Deliberately not sufficient for success. */
7
+ toolInvocationCount: number;
8
+ }
9
+
10
+ /**
11
+ * A successful turn needs a user-facing answer or durable product output.
12
+ * Reasoning and ordinary tool cards are progress; accepting either on stream
13
+ * close leaves an empty assistant bubble that looks successfully completed.
14
+ */
15
+ export function hasUsableStreamOutput(evidence: StreamOutputEvidence): boolean {
16
+ return (
17
+ evidence.realOutputChars > 0 ||
18
+ evidence.agentOutputChars > 0 ||
19
+ evidence.durableArtifactCount > 0
20
+ );
21
+ }
@@ -0,0 +1,103 @@
1
+ import { create } from 'zustand';
2
+ import type { FailedTurn } from './turn-failure';
3
+ import type { Message } from './types';
4
+
5
+ /** The thought panel's tabs. The store owns them because it owns which one opens. */
6
+ export type ThoughtTab = 'steps' | 'sources' | 'activity';
7
+
8
+ /**
9
+ * Whether the conversation a selection belongs to has its messages yet. `loading` is the
10
+ * seeded-then-upgraded window in which a message can be on screen without its tool history;
11
+ * `failed` is a load that will not arrive. The panel shows each as itself instead of as "no steps".
12
+ */
13
+ export type ThoughtScopeStatus = 'loading' | 'ready' | 'failed';
14
+
15
+ /**
16
+ * The conversation a thought selection was made in, as the panel reads it.
17
+ *
18
+ * ## Why the messages travel WITH the selection
19
+ *
20
+ * The panel used to read one global array that the chat screen copied into only while the panel
21
+ * was open. So the first press on a tool row rendered against whatever the array held — the
22
+ * previous conversation, or nothing — and found no message by id: three empty tabs under five
23
+ * visible tool rows. And with the new-chat screen mounted under a conversation, TWO chat screens
24
+ * raced to write the array, and the empty one could win.
25
+ *
26
+ * Now a selection names its conversation and carries that conversation's messages, written in the
27
+ * same update as the message id, and a later sync is accepted only from the SAME conversation. A
28
+ * screen showing another conversation cannot blank what was opened from this one.
29
+ */
30
+ export interface ThoughtScope {
31
+ /** `null` for a conversation that has not been created yet — the first turn of a new chat. */
32
+ conversationId: string | null;
33
+ messages: Message[];
34
+ status: ThoughtScopeStatus;
35
+ /** A turn is in flight in this conversation. */
36
+ isLoading: boolean;
37
+ /** The turn that got no answer in this conversation, or `null`. */
38
+ failedTurn: FailedTurn | null;
39
+ }
40
+
41
+ /** The turn the thought panel is about. */
42
+ export interface ThoughtSelection {
43
+ messageId: string;
44
+ /**
45
+ * Which tab the panel opens on. A caller that already knows what the reader asked for — the
46
+ * Sources row under an answer — says so, instead of landing them on Steps to go hunting.
47
+ */
48
+ tab: ThoughtTab;
49
+ /** The conversation the message lives in. */
50
+ scope: ThoughtScope;
51
+ }
52
+
53
+ interface ThoughtState {
54
+ /** `null` while no turn is selected. */
55
+ selection: ThoughtSelection | null;
56
+ /**
57
+ * Select a turn, with the conversation it was pressed in. One update: there is no render in
58
+ * which the id is set and the messages are not.
59
+ */
60
+ open: (messageId: string, scope: ThoughtScope, tab?: ThoughtTab) => void;
61
+ setTab: (tab: ThoughtTab) => void;
62
+ /**
63
+ * The chat screen's newest view of a conversation. Taken only when it is the conversation the
64
+ * open selection belongs to; every other screen's write is dropped, which is what keeps a second
65
+ * mounted chat from blanking the panel.
66
+ */
67
+ sync: (scope: ThoughtScope) => void;
68
+ /** Clear the selection. */
69
+ close: () => void;
70
+ }
71
+
72
+ /**
73
+ * What the thought panel shows. Session state: the thread writes it, the panel (which the host
74
+ * places — a right panel, a sheet) reads it.
75
+ */
76
+ export const useThoughtStore = create<ThoughtState>()((set, get) => ({
77
+ selection: null,
78
+
79
+ open: (messageId, scope, tab = 'steps') => set({ selection: { messageId, tab, scope } }),
80
+
81
+ setTab: (tab) => {
82
+ const { selection } = get();
83
+ if (selection !== null) set({ selection: { ...selection, tab } });
84
+ },
85
+
86
+ sync: (scope) => {
87
+ const { selection } = get();
88
+ if (selection === null || selection.scope.conversationId !== scope.conversationId) return;
89
+ const held = selection.scope;
90
+ if (
91
+ held.messages === scope.messages &&
92
+ held.status === scope.status &&
93
+ held.isLoading === scope.isLoading &&
94
+ held.failedTurn === scope.failedTurn
95
+ )
96
+ return;
97
+ set({ selection: { ...selection, scope } });
98
+ },
99
+
100
+ close: () => {
101
+ if (get().selection !== null) set({ selection: null });
102
+ },
103
+ }));
@@ -0,0 +1,261 @@
1
+ /**
2
+ * What an agent's run is doing, as data: the events it emits, and the state they add up to.
3
+ *
4
+ * Pure. `use-agent-activity.ts` subscribes to the run and feeds `applyActivityEvent` with what
5
+ * arrives; `hydrateActivity` seeds the state from what the run had already done when the screen
6
+ * opened. Both the live card in the thread and a task's timeline read the result.
7
+ */
8
+
9
+ export interface PlanItem {
10
+ id: number;
11
+ text: string;
12
+ status: string;
13
+ }
14
+
15
+ export interface PlanProgress {
16
+ items: PlanItem[];
17
+ completed: number;
18
+ total: number;
19
+ }
20
+
21
+ export type AgentActivityEventType =
22
+ | 'system'
23
+ | 'thinking'
24
+ | 'response'
25
+ | 'tool_call'
26
+ | 'tool_result'
27
+ | 'error'
28
+ | 'complete'
29
+ | 'screenshot'
30
+ | 'plan_progress'
31
+ | 'file_change'
32
+ | 'source_found'
33
+ | 'threat';
34
+
35
+ export interface AgentActivityEvent {
36
+ type: AgentActivityEventType;
37
+ content: string;
38
+ timestamp: number;
39
+ sessionId: string;
40
+ agentId?: string;
41
+ metadata?: {
42
+ toolName?: string;
43
+ /** What the tool was called with; the browser tool's `action`, `url` and `query`, a plan's `action`, a delegate's `agent`. */
44
+ args?: {
45
+ action?: string;
46
+ url?: string;
47
+ query?: string;
48
+ agent?: string;
49
+ [key: string]: unknown;
50
+ };
51
+ duration?: number;
52
+ url?: string;
53
+ title?: string;
54
+ domain?: string;
55
+ };
56
+ data?: {
57
+ url?: string;
58
+ plan?: PlanProgress;
59
+ currentStep?: number;
60
+ maxSteps?: number;
61
+ };
62
+ }
63
+
64
+ export interface AgentSource {
65
+ url: string;
66
+ title: string;
67
+ domain: string;
68
+ snippet: string;
69
+ timestamp: number;
70
+ }
71
+
72
+ export interface AgentActivityState {
73
+ /** Current plan with checklist items */
74
+ plan: PlanProgress | null;
75
+ /** Current action being executed */
76
+ currentAction: { toolName: string; content: string } | null;
77
+ /** Whether the agent has completed */
78
+ isComplete: boolean;
79
+ /** Whether there's an error */
80
+ hasError: boolean;
81
+ /** Last error message */
82
+ lastError: string | null;
83
+ /** Total events received */
84
+ eventCount: number;
85
+ /** All activity events (last 50) */
86
+ events: AgentActivityEvent[];
87
+ /** Start time of first event */
88
+ startedAt: number | null;
89
+ /** Sources found during browsing */
90
+ sources: AgentSource[];
91
+ /** Latest text response from agent */
92
+ latestResponse: string | null;
93
+ /** Total credits charged for this session (present once the run settles) */
94
+ creditsCharged?: number;
95
+ }
96
+
97
+ export const INITIAL_ACTIVITY: AgentActivityState = {
98
+ plan: null,
99
+ currentAction: null,
100
+ isComplete: false,
101
+ hasError: false,
102
+ lastError: null,
103
+ eventCount: 0,
104
+ events: [],
105
+ startedAt: null,
106
+ sources: [],
107
+ latestResponse: null,
108
+ };
109
+
110
+ /** How many events the state keeps. */
111
+ export const MAX_ACTIVITY_EVENTS = 50;
112
+
113
+ /** Add one event to the run's state. */
114
+ export function applyActivityEvent(
115
+ prev: AgentActivityState,
116
+ event: AgentActivityEvent,
117
+ ): AgentActivityState {
118
+ const next: AgentActivityState = {
119
+ ...prev,
120
+ eventCount: prev.eventCount + 1,
121
+ events: [...prev.events.slice(-(MAX_ACTIVITY_EVENTS - 1)), event],
122
+ startedAt: prev.startedAt ?? event.timestamp,
123
+ };
124
+
125
+ switch (event.type) {
126
+ case 'plan_progress':
127
+ if (event.data?.plan) next.plan = event.data.plan;
128
+ break;
129
+
130
+ case 'tool_call':
131
+ next.currentAction = {
132
+ toolName: event.metadata?.toolName || 'action',
133
+ content: event.content,
134
+ };
135
+ break;
136
+
137
+ case 'tool_result':
138
+ next.currentAction = null;
139
+ break;
140
+
141
+ case 'error':
142
+ next.hasError = true;
143
+ next.lastError = event.content;
144
+ next.currentAction = null;
145
+ break;
146
+
147
+ case 'complete':
148
+ next.isComplete = true;
149
+ next.currentAction = null;
150
+ next.latestResponse = null;
151
+ break;
152
+
153
+ case 'source_found': {
154
+ const url = event.metadata?.url;
155
+ if (url && !prev.sources.some((source) => source.url === url)) {
156
+ next.sources = [
157
+ ...prev.sources,
158
+ {
159
+ url,
160
+ title: event.metadata?.title || '',
161
+ domain: event.metadata?.domain || new URL(url).hostname,
162
+ snippet: event.content?.slice(0, 200) || '',
163
+ timestamp: event.timestamp,
164
+ },
165
+ ];
166
+ }
167
+ break;
168
+ }
169
+
170
+ case 'response':
171
+ next.latestResponse = event.content;
172
+ break;
173
+ }
174
+
175
+ return next;
176
+ }
177
+
178
+ /** An event as the session-status route stores it. */
179
+ interface PersistedAgentEvent {
180
+ type: string;
181
+ content: string;
182
+ timestamp: number;
183
+ metadata?: AgentActivityEvent['metadata'];
184
+ }
185
+
186
+ /** What `GET` on a session's status answers. */
187
+ export interface AgentSessionStatus {
188
+ recentEvents?: PersistedAgentEvent[];
189
+ session?: {
190
+ plan?: { items?: PlanItem[] };
191
+ status?: string;
192
+ result?: string;
193
+ stats?: { creditsCharged?: number };
194
+ };
195
+ }
196
+
197
+ function eventTypeOf(type: string): AgentActivityEventType {
198
+ switch (type) {
199
+ case 'action':
200
+ return 'tool_call';
201
+ case 'observation':
202
+ return 'tool_result';
203
+ case 'threat_detected':
204
+ return 'threat';
205
+ case 'thinking':
206
+ case 'response':
207
+ case 'error':
208
+ case 'complete':
209
+ case 'screenshot':
210
+ case 'plan_progress':
211
+ case 'file_change':
212
+ case 'source_found':
213
+ return type;
214
+ // `user_message`, `system_message`, `plan_update` and anything newer.
215
+ default:
216
+ return 'system';
217
+ }
218
+ }
219
+
220
+ /** Seed the state with what the run had done before this screen subscribed to it. */
221
+ export function hydrateActivity(
222
+ prev: AgentActivityState,
223
+ status: AgentSessionStatus,
224
+ sessionId: string,
225
+ ): AgentActivityState {
226
+ const events = (Array.isArray(status.recentEvents) ? status.recentEvents : [])
227
+ .map(
228
+ (entry): AgentActivityEvent => ({
229
+ type: eventTypeOf(entry.type),
230
+ content: entry.content,
231
+ timestamp: entry.timestamp,
232
+ sessionId,
233
+ metadata: entry.metadata,
234
+ }),
235
+ )
236
+ .slice(-MAX_ACTIVITY_EVENTS);
237
+ const session = status.session;
238
+ const planItems = Array.isArray(session?.plan?.items) ? session.plan.items : [];
239
+ const failed = session?.status === 'failed';
240
+ const credits = session?.stats?.creditsCharged;
241
+
242
+ return {
243
+ ...prev,
244
+ events,
245
+ eventCount: events.length,
246
+ startedAt: events[0]?.timestamp || prev.startedAt,
247
+ plan:
248
+ planItems.length > 0
249
+ ? {
250
+ items: planItems,
251
+ completed: planItems.filter((item) => item.status === 'completed').length,
252
+ total: planItems.length,
253
+ }
254
+ : prev.plan,
255
+ isComplete: session?.status === 'completed' || session?.status === 'cancelled',
256
+ hasError: failed,
257
+ lastError: failed ? session?.result || prev.lastError : prev.lastError,
258
+ latestResponse: session?.result || prev.latestResponse,
259
+ creditsCharged: typeof credits === 'number' ? credits : prev.creditsCharged,
260
+ };
261
+ }