@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,144 @@
1
+ /**
2
+ * Narrow helpers for handling `unknown` caught errors without `any`.
3
+ *
4
+ * Supports both plain `Error` and Axios-style `{ response: { data, status } }` errors.
5
+ */
6
+
7
+ /**
8
+ * Body shape of an Axios-style error `response.data`.
9
+ *
10
+ * `error` is a STRING on some surfaces and an OBJECT on others: everything
11
+ * under `/v1` answers `{ error: { message, type } }`, which is the OpenAI shape
12
+ * it is compatible with. Typing it as a string was not a simplification, it was
13
+ * a claim that is false half the time — and it is what let an object reach a
14
+ * `<Text>` and crash the screen with React error #31.
15
+ */
16
+ export interface ErrorResponseData {
17
+ error?: string | { message?: string; type?: string };
18
+ message?: string;
19
+ code?: string;
20
+ creditsNeeded?: number;
21
+ [key: string]: unknown;
22
+ }
23
+
24
+ interface MaybeHttpError {
25
+ message?: string;
26
+ name?: string;
27
+ code?: number | string;
28
+ status?: number;
29
+ statusCode?: number;
30
+ response?: {
31
+ status?: number;
32
+ data?: ErrorResponseData;
33
+ };
34
+ }
35
+
36
+ function asObject(err: unknown): MaybeHttpError {
37
+ return typeof err === 'object' && err !== null ? (err as MaybeHttpError) : {};
38
+ }
39
+
40
+ /**
41
+ * A string out of an API error body, whichever shape it came in.
42
+ *
43
+ * `/v1` answers `{ error: { message, type } }` — the OpenAI shape it is
44
+ * compatible with — and everything else answers `{ error: "text" }`. Both are
45
+ * correct for their surface, so the reader has to know both; the alternative is
46
+ * every call site guessing, and the ones that guessed wrong put an object into
47
+ * a `<Text>` and took the screen down with React error #31.
48
+ *
49
+ * Exported because some callers hold a parsed body rather than the error it
50
+ * came from — a `fetch` that checked `res.ok` itself, for instance.
51
+ */
52
+ export function errorBodyText(
53
+ data: ErrorResponseData | undefined,
54
+ fallback = 'Something went wrong',
55
+ ): string {
56
+ if (typeof data?.error === 'string' && data.error) return data.error;
57
+ if (typeof data?.error === 'object' && data.error?.message) return data.error.message;
58
+ if (data?.message) return data.message;
59
+ return fallback;
60
+ }
61
+
62
+ /**
63
+ * Best-effort human-readable message, preferring an API `response.data.error`.
64
+ *
65
+ * Returns a STRING, always. It used to return whatever `data.error` held while
66
+ * declaring a string, so an `/v1` body — `{ error: { message, type } }` — came
67
+ * out as an object, was stored as an error, and crashed the render that tried
68
+ * to show it. A function whose return type is a promise the body does not keep
69
+ * is worse than one that admits it might fail.
70
+ */
71
+ export function errorMessage(err: unknown, fallback = 'Something went wrong'): string {
72
+ const e = asObject(err);
73
+ const body = e.response?.data;
74
+ if (body) {
75
+ const fromBody = errorBodyText(body, '');
76
+ if (fromBody) return fromBody;
77
+ }
78
+ if (err instanceof Error) return err.message;
79
+ if (e.message) return e.message;
80
+ if (typeof err === 'string') return err;
81
+ return fallback;
82
+ }
83
+
84
+ /** HTTP status from `response.status`, `status`, or `statusCode`. */
85
+ export function errorStatus(err: unknown): number | undefined {
86
+ const e = asObject(err);
87
+ return e.response?.status ?? e.status ?? e.statusCode;
88
+ }
89
+
90
+ /** Application/system error code (e.g. `'MODEL_NOT_IN_PLAN'`, `'ENOENT'`, `11000`). */
91
+ export function errorCode(err: unknown): number | string | undefined {
92
+ return asObject(err).code;
93
+ }
94
+
95
+ /** Error `name` (e.g. `'AbortError'`). */
96
+ export function errorName(err: unknown): string | undefined {
97
+ if (err instanceof Error) return err.name;
98
+ return asObject(err).name;
99
+ }
100
+
101
+ /** The Axios-style `response.data` body of an error, if present. */
102
+ export function errorResponseData(err: unknown): ErrorResponseData | undefined {
103
+ return asObject(err).response?.data;
104
+ }
105
+
106
+ /** A refusal body is a small JSON envelope; more than this is not one. */
107
+ const MAX_ERROR_BODY_BYTES = 64 * 1024;
108
+
109
+ /**
110
+ * The whole body of a non-OK streaming response, parsed as JSON, or `null`.
111
+ *
112
+ * A streaming fetch is body-oriented (`.json()` is not reliable on it), so the
113
+ * body is read through its reader. ONE `read()` is not the body: a network that
114
+ * splits the envelope across chunks handed `JSON.parse` half of it, which threw,
115
+ * and the typed `code` and `reference` were lost for a generic "Server error".
116
+ * It reads to the end, bounded, and always releases the reader.
117
+ */
118
+ export async function readErrorResponseBody(response: {
119
+ body?: ReadableStream<Uint8Array> | null;
120
+ }): Promise<unknown> {
121
+ const reader = response.body?.getReader();
122
+ if (!reader) return null;
123
+ const decoder = new TextDecoder();
124
+ let text = '';
125
+ let bytes = 0;
126
+ try {
127
+ while (bytes < MAX_ERROR_BODY_BYTES) {
128
+ const { done, value } = await reader.read();
129
+ if (done) break;
130
+ bytes += value.byteLength;
131
+ text += decoder.decode(value, { stream: true });
132
+ }
133
+ text += decoder.decode();
134
+ return JSON.parse(text);
135
+ } catch {
136
+ return null;
137
+ } finally {
138
+ try {
139
+ await reader.cancel();
140
+ } catch {
141
+ // Already closed: nothing left to release.
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,182 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import { useGemieApi } from './api';
4
+ import { errorStatus } from './error-utils';
5
+ import { gemieQueryKeys } from './query-keys';
6
+ import { AGENT_ROUTES } from './routes';
7
+
8
+ /**
9
+ * A gemie's connected accounts (ADR 0035): the WhatsApp and Telegram accounts the person linked to
10
+ * a gemie, which answers what arrives on them as their replies say. Each is the caller's own; the
11
+ * API never lists another person's. The Gemies app (in a gemie's editor) and the Alia app (for
12
+ * Alia's gemie) both manage them through these hooks and `GemieAccounts` (`@gemies/sdk/accounts`).
13
+ */
14
+
15
+ export const GEMIE_ACCOUNT_PLATFORMS = ['whatsapp', 'telegram'] as const;
16
+ export type GemieAccountPlatform = (typeof GEMIE_ACCOUNT_PLATFORMS)[number];
17
+
18
+ /** Where an account's session is, as the API reports it (the gateway's own vocabulary). */
19
+ export const GEMIE_ACCOUNT_STATUSES = [
20
+ 'qr-pending',
21
+ 'connected',
22
+ 'disconnected',
23
+ 'logged-out',
24
+ 'failed',
25
+ ] as const;
26
+ export type GemieAccountStatus = (typeof GEMIE_ACCOUNT_STATUSES)[number];
27
+
28
+ /** Who the gemie answers: everybody who writes, only the chosen chats, or nobody. */
29
+ export const GEMIE_ACCOUNT_REPLIES = ['everyone', 'chosen', 'nobody'] as const;
30
+ export type GemieAccountReplies = (typeof GEMIE_ACCOUNT_REPLIES)[number];
31
+ /** In a group: only when the message mentions or replies to the account, or never. */
32
+ export const GEMIE_ACCOUNT_GROUP_REPLIES = ['mentions', 'never'] as const;
33
+ export type GemieAccountGroupReplies = (typeof GEMIE_ACCOUNT_GROUP_REPLIES)[number];
34
+
35
+ /** One account, as `GET /agents/:id/accounts` lists it. */
36
+ export interface GemieAccount {
37
+ _id: string;
38
+ platform: GemieAccountPlatform;
39
+ displayName: string | null;
40
+ phoneNumber: string | null;
41
+ status: GemieAccountStatus;
42
+ oxyTaskState: 'active' | 'reauth_required';
43
+ replies: GemieAccountReplies;
44
+ replyChatIds: string[];
45
+ groupReplies: GemieAccountGroupReplies;
46
+ lastActiveAt: string | null;
47
+ }
48
+
49
+ /** One chat of an account, to choose which ones it answers. */
50
+ export interface GemieAccountChat {
51
+ chatId: string;
52
+ name: string;
53
+ kind: 'direct' | 'group';
54
+ }
55
+
56
+ /** A link waiting for its scan. */
57
+ export interface GemieAccountLink {
58
+ accountId: string;
59
+ qr: string | null;
60
+ }
61
+
62
+ export interface GemieAccountsAnswer {
63
+ accounts: GemieAccount[];
64
+ /** The platforms this deployment can link now: only those are offered. */
65
+ platforms: GemieAccountPlatform[];
66
+ }
67
+
68
+ /**
69
+ * The caller's accounts on a gemie, each as its session is now, and what can be linked. An account
70
+ * whose Oxy task lapsed is renewed on the way (the provider link is kept; the person looking is the
71
+ * verified requester); a renewal that fails leaves it typed inactive for the next visit to retry.
72
+ */
73
+ export function useGemieAccounts(gemieId: string) {
74
+ const api = useGemieApi();
75
+ const { isAuthenticated } = useOxy();
76
+ return useQuery({
77
+ queryKey: gemieQueryKeys.accounts.all(gemieId),
78
+ queryFn: async (): Promise<GemieAccountsAnswer> => {
79
+ const { data } = await api.get<GemieAccountsAnswer>(AGENT_ROUTES.accounts(gemieId));
80
+ await Promise.all(
81
+ data.accounts
82
+ .filter((account) => account.oxyTaskState === 'reauth_required')
83
+ .map(async (account) => {
84
+ try {
85
+ await api.post(`${AGENT_ROUTES.account(gemieId, account._id)}/reauthorize`);
86
+ account.oxyTaskState = 'active';
87
+ } catch {
88
+ /* Remains typed inactive; the next verified visit may retry. */
89
+ }
90
+ }),
91
+ );
92
+ return data;
93
+ },
94
+ enabled: isAuthenticated && gemieId !== '',
95
+ });
96
+ }
97
+
98
+ /**
99
+ * The code of an account being linked, refreshed while it waits (WhatsApp rotates its code every
100
+ * few seconds). It stops once the session leaves `qr-pending`, and the list is re-read then, so the
101
+ * account shows as it is.
102
+ */
103
+ export function useGemieAccountQr(gemieId: string, link: GemieAccountLink | null) {
104
+ const api = useGemieApi();
105
+ const queryClient = useQueryClient();
106
+ const accountId = link?.accountId ?? '';
107
+ return useQuery({
108
+ queryKey: gemieQueryKeys.accounts.qr(gemieId, accountId),
109
+ queryFn: async (): Promise<{ status: GemieAccountStatus; qr: string | null }> => {
110
+ const { data } = await api.get<{ status: GemieAccountStatus; qr: string | null }>(
111
+ `${AGENT_ROUTES.account(gemieId, accountId)}/qr`,
112
+ );
113
+ if (data.status !== 'qr-pending') {
114
+ await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
115
+ }
116
+ return data;
117
+ },
118
+ enabled: link !== null,
119
+ initialData: link ? { status: 'qr-pending' as const, qr: link.qr } : undefined,
120
+ initialDataUpdatedAt: 0,
121
+ refetchInterval: (query) => (query.state.data?.status === 'qr-pending' ? 4000 : false),
122
+ });
123
+ }
124
+
125
+ /** An account's recent chats, read while the person chooses which ones it answers. */
126
+ export function useGemieAccountChats(gemieId: string, accountId: string) {
127
+ const api = useGemieApi();
128
+ return useQuery({
129
+ queryKey: gemieQueryKeys.accounts.chats(gemieId, accountId),
130
+ queryFn: async (): Promise<GemieAccountChat[]> => {
131
+ try {
132
+ const { data } = await api.get<{ chats: GemieAccountChat[] }>(
133
+ `${AGENT_ROUTES.account(gemieId, accountId)}/chats`,
134
+ );
135
+ return data.chats;
136
+ } catch (error) {
137
+ if (errorStatus(error) === 404) return [];
138
+ throw error;
139
+ }
140
+ },
141
+ });
142
+ }
143
+
144
+ /** Linking, who it answers, and removing (its session ends and its task is revoked). */
145
+ export function useGemieAccountMutations(gemieId: string) {
146
+ const api = useGemieApi();
147
+ const queryClient = useQueryClient();
148
+ const invalidate = () =>
149
+ queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all(gemieId) });
150
+
151
+ const link = useMutation({
152
+ mutationFn: async (platform: GemieAccountPlatform): Promise<GemieAccountLink> => {
153
+ const { data } = await api.post<GemieAccountLink>(AGENT_ROUTES.accounts(gemieId), {
154
+ platform,
155
+ });
156
+ return data;
157
+ },
158
+ onSuccess: invalidate,
159
+ });
160
+
161
+ const setReplies = useMutation({
162
+ mutationFn: async (input: {
163
+ accountId: string;
164
+ replies?: GemieAccountReplies;
165
+ replyChatIds?: string[];
166
+ groupReplies?: GemieAccountGroupReplies;
167
+ }) => {
168
+ const { accountId, ...patch } = input;
169
+ await api.patch(AGENT_ROUTES.account(gemieId, accountId), patch);
170
+ },
171
+ onSuccess: invalidate,
172
+ });
173
+
174
+ const remove = useMutation({
175
+ mutationFn: async (accountId: string) => {
176
+ await api.delete(AGENT_ROUTES.account(gemieId, accountId));
177
+ },
178
+ onSuccess: invalidate,
179
+ });
180
+
181
+ return { link, setReplies, remove };
182
+ }
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Host tools: UI effects in the embedding client (`docs/agent-embedding.md` §2, ADR 0020 §6).
3
+ *
4
+ * A surface declares the effects its own client can perform with every request. The model sees
5
+ * each as `host_<app>__<name>`; when it calls one, the server records the call and emits
6
+ * `alia.host_action`, and this client — the only one that declared it — performs it and sends
7
+ * the outcome with its NEXT request, where it becomes that call's result. A host tool is never
8
+ * authority over data: it moves the host's own screen.
9
+ *
10
+ * A tool declared with `awaitsResult: true` is read in the SAME turn instead ("this tab's text",
11
+ * "the open tabs"): the server waits, and this client answers it at once on the turn's
12
+ * `host-results` route with the outcome and the `result` its `execute` returned — text, JSON or
13
+ * an image ({@link GemieHostImageResult}) the model sees as one.
14
+ *
15
+ * Three rules hold here, in a queue that knows nothing of React:
16
+ * - an action is performed at most once, whatever the stream repeats;
17
+ * - an outcome stays queued until a request carrying it has been accepted, so a turn that ends
18
+ * before its outcomes are sent hands them to the next one;
19
+ * - an awaited action's answer is sent once, never queued and never retried.
20
+ */
21
+
22
+ import type { HostAction } from './stream-events';
23
+
24
+ export type { HostAction as GemieHostAction } from './stream-events';
25
+
26
+ /** One effect the host can perform. `name` matches `^[a-z][a-z0-9_]{0,47}$`. */
27
+ export interface GemieHostToolDefinition {
28
+ name: string;
29
+ description: string;
30
+ /** A JSON Schema with an object root. */
31
+ inputSchema: Record<string, unknown>;
32
+ /**
33
+ * The model reads this tool's result in the same turn: `execute`'s `result` goes back to it at
34
+ * once. Needs an Gemies API with awaited host tools (`docs/agent-embedding.md` §2).
35
+ */
36
+ awaitsResult?: boolean;
37
+ }
38
+
39
+ export const HOST_OUTCOMES = ['applied', 'inline', 'rejected', 'stale', 'failed'] as const;
40
+ export type GemieHostOutcomeKind = (typeof HOST_OUTCOMES)[number];
41
+
42
+ /** What came of an action: the host's own word for it, and a line for the model. */
43
+ export interface GemieHostOutcome {
44
+ outcome: GemieHostOutcomeKind;
45
+ /** At most 500 characters; longer is cut. */
46
+ detail?: string;
47
+ /**
48
+ * What an awaited tool read, for the model: a string or any JSON value, at most
49
+ * {@link HOST_RESULT_MAX_CHARS} characters as JSON, or an {@link GemieHostImageResult} the model
50
+ * sees as an image. Ignored for a tool that does not await.
51
+ */
52
+ result?: unknown;
53
+ }
54
+
55
+ export const HOST_IMAGE_MEDIA_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const;
56
+ export type GemieHostImageMediaType = (typeof HOST_IMAGE_MEDIA_TYPES)[number];
57
+
58
+ /** The longest caption an image result may carry. */
59
+ export const HOST_IMAGE_TEXT_MAX_CHARS = 4_000;
60
+
61
+ /**
62
+ * An awaited tool's image (a tab's screenshot): the model sees the image itself in that turn, and
63
+ * the stored conversation keeps `{ type, mediaType, text?, omitted: true }` in its place.
64
+ * `data` is the image's bytes in standard base64, with no `data:` prefix; the whole result counts
65
+ * toward {@link HOST_RESULT_MAX_CHARS}, so size the image to fit (a JPEG of the viewport).
66
+ */
67
+ export interface GemieHostImageResult {
68
+ type: 'image';
69
+ mediaType: GemieHostImageMediaType;
70
+ data: string;
71
+ /** A caption for the model (the tab's URL and title), at most {@link HOST_IMAGE_TEXT_MAX_CHARS}. */
72
+ text?: string;
73
+ }
74
+
75
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
76
+ const IMAGE_KEYS = ['type', 'mediaType', 'data', 'text'];
77
+
78
+ /**
79
+ * Why a result that claims to be an image (`type: "image"`) is not a valid one, or `null`. The
80
+ * server refuses such an answer, which would leave the model waiting until the action goes stale;
81
+ * the runtime answers `failed` with this reason instead.
82
+ */
83
+ export function hostImageResultProblem(result: unknown): string | null {
84
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) return null;
85
+ const image = result as Record<string, unknown>;
86
+ if (image.type !== 'image') return null;
87
+ const extra = Object.keys(image).find((key) => !IMAGE_KEYS.includes(key));
88
+ if (extra !== undefined) return `An image result has no "${extra}".`;
89
+ if (!HOST_IMAGE_MEDIA_TYPES.includes(image.mediaType as GemieHostImageMediaType)) {
90
+ return `An image result's mediaType is one of ${HOST_IMAGE_MEDIA_TYPES.join(', ')}.`;
91
+ }
92
+ if (typeof image.data !== 'string' || image.data === '' || !BASE64.test(image.data)) {
93
+ return "An image result's data is standard base64 with no data: prefix.";
94
+ }
95
+ if (
96
+ image.text !== undefined &&
97
+ (typeof image.text !== 'string' || image.text.length > HOST_IMAGE_TEXT_MAX_CHARS)
98
+ ) {
99
+ return `An image result's text is a string of at most ${HOST_IMAGE_TEXT_MAX_CHARS} characters.`;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /**
105
+ * The host tools a surface declares (`hostTools` on the chat). They are the tools of the chat's
106
+ * `app`, which a surface with host tools must name: the app is said once, on the chat, and is what
107
+ * the model sees them under (`host_<app>__<name>`).
108
+ */
109
+ export interface GemieHostTools {
110
+ /**
111
+ * At most 16. What the host's screen shows now is not part of the declaration: it is the chat's
112
+ * `clientContext`, built by the host per turn.
113
+ */
114
+ definitions: readonly GemieHostToolDefinition[];
115
+ /** Perform `action` and say what came of it. Called once per action. */
116
+ execute: (action: HostAction) => Promise<GemieHostOutcome>;
117
+ /**
118
+ * An awaited action's answer could not be delivered (the request failed). It is not retried:
119
+ * the model reads that the app did not answer in time.
120
+ */
121
+ onUndelivered?: (action: HostAction, error: unknown) => void;
122
+ }
123
+
124
+ /** An outcome as a request carries it. */
125
+ export interface HostOutcomeRecord {
126
+ toolCallId: string;
127
+ outcome: GemieHostOutcomeKind;
128
+ detail?: string;
129
+ }
130
+
131
+ /** An awaited action's answer, as `POST /v1/chat/turns/:turnId/host-results` carries it. */
132
+ export interface HostResultRecord extends HostOutcomeRecord {
133
+ result?: unknown;
134
+ }
135
+
136
+ /** The request's `host` member. */
137
+ export interface HostRequest {
138
+ app: string;
139
+ version: 1;
140
+ tools: GemieHostToolDefinition[];
141
+ /** Omitted when there is nothing to report. */
142
+ outcomes?: HostOutcomeRecord[];
143
+ }
144
+
145
+ const DETAIL_LIMIT = 500;
146
+
147
+ /** The server's bound on an awaited action's `result`, as JSON. */
148
+ export const HOST_RESULT_MAX_CHARS = 100_000;
149
+
150
+ function resultOf(result: unknown): { result?: unknown } | 'too_large' | { invalid: string } {
151
+ if (result === undefined || result === null) return {};
152
+ const problem = hostImageResultProblem(result);
153
+ if (problem !== null) return { invalid: problem };
154
+ let text: string | undefined;
155
+ try {
156
+ text = JSON.stringify(result);
157
+ } catch {
158
+ return {};
159
+ }
160
+ if (text === undefined) return {};
161
+ return text.length > HOST_RESULT_MAX_CHARS ? 'too_large' : { result };
162
+ }
163
+
164
+ function record(toolCallId: string, outcome: GemieHostOutcome | undefined): HostOutcomeRecord {
165
+ const kind = HOST_OUTCOMES.includes(outcome?.outcome as GemieHostOutcomeKind)
166
+ ? (outcome?.outcome as GemieHostOutcomeKind)
167
+ : 'failed';
168
+ const detail = typeof outcome?.detail === 'string' ? outcome.detail.slice(0, DETAIL_LIMIT) : '';
169
+ return { toolCallId, outcome: kind, ...(detail === '' ? {} : { detail }) };
170
+ }
171
+
172
+ /** The outcomes of a conversation's host actions, between the stream that asked and the next request. */
173
+ export class HostOutcomeQueue {
174
+ private readonly performed = new Set<string>();
175
+ private ready: HostOutcomeRecord[] = [];
176
+
177
+ /**
178
+ * Perform `action` with the tools `app` declared, once. Resolves when its outcome is queued;
179
+ * `false` when the action had already been performed and nothing was done.
180
+ */
181
+ async dispatch(
182
+ action: HostAction,
183
+ tools: GemieHostTools | undefined,
184
+ app: string | undefined,
185
+ ): Promise<boolean> {
186
+ if (this.performed.has(action.toolCallId)) return false;
187
+ this.performed.add(action.toolCallId);
188
+ const outcome = await perform(action, tools, app);
189
+ this.ready.push(record(action.toolCallId, outcome));
190
+ return true;
191
+ }
192
+
193
+ /**
194
+ * Perform an awaited `action` once and `send` its answer at once, with its result. A failed send
195
+ * is reported to the host's `onUndelivered` and not retried. `false` when the action had already
196
+ * been performed.
197
+ */
198
+ async answer(
199
+ action: HostAction,
200
+ tools: GemieHostTools | undefined,
201
+ app: string | undefined,
202
+ send: (answer: HostResultRecord) => Promise<unknown>,
203
+ ): Promise<boolean> {
204
+ if (this.performed.has(action.toolCallId)) return false;
205
+ this.performed.add(action.toolCallId);
206
+ const outcome = await perform(action, tools, app);
207
+ const result = resultOf((outcome as GemieHostOutcome | undefined)?.result);
208
+ const answer: HostResultRecord =
209
+ result === 'too_large'
210
+ ? record(action.toolCallId, {
211
+ outcome: 'failed',
212
+ detail: 'The result was too large to send.',
213
+ })
214
+ : 'invalid' in result
215
+ ? record(action.toolCallId, { outcome: 'failed', detail: result.invalid })
216
+ : { ...record(action.toolCallId, outcome), ...result };
217
+ try {
218
+ await send(answer);
219
+ } catch (error) {
220
+ tools?.onUndelivered?.(action, error);
221
+ }
222
+ return true;
223
+ }
224
+
225
+ /** The outcomes ready to send, oldest first. */
226
+ pending(): HostOutcomeRecord[] {
227
+ return [...this.ready];
228
+ }
229
+
230
+ /** A request carrying `sent` was accepted: those are delivered. */
231
+ delivered(sent: readonly HostOutcomeRecord[]): void {
232
+ this.ready = this.ready.filter((outcome) => !sent.includes(outcome));
233
+ }
234
+
235
+ /** A different conversation: its outcomes are not this one's. What was performed stays performed. */
236
+ clear(): void {
237
+ this.ready = [];
238
+ }
239
+ }
240
+
241
+ async function perform(
242
+ action: HostAction,
243
+ tools: GemieHostTools | undefined,
244
+ app: string | undefined,
245
+ ): Promise<GemieHostOutcome> {
246
+ if (tools === undefined || app === undefined || action.app !== app) {
247
+ return { outcome: 'rejected', detail: 'This app did not declare that tool.' };
248
+ }
249
+ if (!tools.definitions.some((tool) => tool.name === action.name)) {
250
+ return { outcome: 'rejected', detail: `Unknown tool "${action.name}".` };
251
+ }
252
+ try {
253
+ return await tools.execute(action);
254
+ } catch (error) {
255
+ return {
256
+ outcome: 'failed',
257
+ detail: error instanceof Error ? error.message : 'The app could not do it.',
258
+ };
259
+ }
260
+ }
261
+
262
+ /**
263
+ * The `host` member of a request: the chat's `app` and its host tools (none is an empty list),
264
+ * or nothing for a chat that names no app — Alia's own.
265
+ *
266
+ * The app is also what labels a conversation this turn starts (`docs/agent-embedding.md` §6), so
267
+ * a surface without host tools still sends it.
268
+ */
269
+ export function hostRequest(
270
+ app: string | undefined,
271
+ tools: GemieHostTools | undefined,
272
+ outcomes: readonly HostOutcomeRecord[],
273
+ ): HostRequest | undefined {
274
+ if (app === undefined) return undefined;
275
+ return {
276
+ app,
277
+ version: 1,
278
+ tools: (tools?.definitions ?? []).map(({ name, description, inputSchema, awaitsResult }) => ({
279
+ name,
280
+ description,
281
+ inputSchema,
282
+ // Only when declared: an API before awaited host tools refuses the unknown field.
283
+ ...(awaitsResult === true ? { awaitsResult: true as const } : {}),
284
+ })),
285
+ ...(outcomes.length === 0 ? {} : { outcomes: [...outcomes] }),
286
+ };
287
+ }
288
+
289
+ /** The slug an app names itself by, here and on the server: `^[a-z][a-z0-9-]{0,31}$`. */
290
+ export const APP_SLUG = /^[a-z][a-z0-9-]{0,31}$/;