@gemies/sdk 7.0.0 → 8.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 (35) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +9 -6
  3. package/package.json +1 -1
  4. package/src/accounts.ts +11 -0
  5. package/src/components/GemieBetweenGemies.tsx +115 -0
  6. package/src/components/GemieChatContent.tsx +38 -44
  7. package/src/components/GemieParticipants.tsx +12 -64
  8. package/src/components/GemieSharedConversation.tsx +1 -9
  9. package/src/components/thread/GemieConversationCard.tsx +120 -0
  10. package/src/components/thread/GemieThread.tsx +30 -80
  11. package/src/components/thread/ThreadRow.tsx +24 -5
  12. package/src/hooks/useThreadRows.ts +0 -12
  13. package/src/index.ts +5 -6
  14. package/src/lib/copy-en.ts +8 -5
  15. package/src/lib/copy-es.ts +8 -5
  16. package/src/lib/gemie-conversation-opener.ts +14 -0
  17. package/src/lib/participants.ts +16 -22
  18. package/src/realtime/cache.ts +5 -0
  19. package/src/realtime/contract.ts +4 -0
  20. package/src/runtime/channel-tasks.ts +78 -0
  21. package/src/runtime/connected-accounts.ts +18 -16
  22. package/src/runtime/conversations.ts +18 -8
  23. package/src/runtime/gemie-conversations.ts +122 -0
  24. package/src/runtime/index.ts +6 -2
  25. package/src/runtime/message-history.ts +9 -12
  26. package/src/runtime/query-keys.ts +8 -1
  27. package/src/runtime/room-events.ts +23 -17
  28. package/src/runtime/routes.ts +5 -0
  29. package/src/runtime/stream-events.ts +10 -7
  30. package/src/runtime/types.ts +10 -3
  31. package/src/runtime/use-conversation-stream.ts +31 -26
  32. package/src/runtime/use-conversation-thread.ts +1 -1
  33. package/src/components/thread/AgentExchangeView.tsx +0 -112
  34. package/src/runtime/thread/agent-exchange.ts +0 -94
  35. package/src/runtime/thread/speaker-changes.ts +0 -66
@@ -1,7 +1,6 @@
1
1
  import { AgentThinking } from '@oxy.so/bloom/agent-thinking';
2
2
  import { AiChatThread, type AiChatThreadHandle } from '@oxy.so/bloom/ai-chat';
3
3
  import { ChatDateHeader } from '@oxy.so/bloom/chat-screen';
4
- import { Button } from '@oxy.so/bloom/button';
5
4
  import { Divider } from '@oxy.so/bloom/divider';
6
5
  import { ThreadSkeleton } from './ThreadSkeleton';
7
6
  import * as Skeleton from '@oxy.so/bloom/skeleton';
@@ -27,7 +26,6 @@ import { useBubbles } from '../../lib/bubbles';
27
26
  import { useLabels } from '../../lib/labels';
28
27
  import type { AgentActivityState } from '../../runtime/thread/agent-activity';
29
28
  import type { FailedTurn } from '../../runtime/turn-failure';
30
- import { type AgentExchange, agentExchange } from '../../runtime/thread/agent-exchange';
31
29
  import type { Message } from '../../runtime/types';
32
30
  import type { MessageReactionSnapshot } from '../../runtime/message-reactions';
33
31
  import type { ThreadHistory } from '../../runtime/thread/thread-history';
@@ -62,8 +60,6 @@ export interface GemieThreadProps {
62
60
  isLoading: boolean;
63
61
  /** The conversation's messages are still on their way. */
64
62
  conversationLoading?: boolean;
65
- /** The agents taking part in this conversation (the direct agent or a group's members): they speak as themselves, with no "chat with" line. */
66
- memberIds?: ReadonlySet<string>;
67
63
  history?: ThreadHistory;
68
64
  /**
69
65
  * The message a jump was aimed at, by cursor, or `null` at the present. A window is half before
@@ -104,11 +100,6 @@ export interface GemieThreadProps {
104
100
  onReply?: (text: string) => void;
105
101
  /** A saved reaction updates the live message as well as the query cache. */
106
102
  onReactionChange?: (update: MessageReactionSnapshot) => void;
107
- /**
108
- * Open the internal conversation of an agent that came into this one (the "Chatted with" line).
109
- * Omitted, the line is plain text.
110
- */
111
- onOpenAgentChat?: (exchange: AgentExchange) => void;
112
103
  /** A conversation read by somebody it was shared with: no votes, no read-aloud, no regenerate. */
113
104
  readOnly?: boolean;
114
105
  }
@@ -138,7 +129,6 @@ export const GemieThread = memo(function GemieThread({
138
129
  conversationId,
139
130
  isLoading,
140
131
  conversationLoading = false,
141
- memberIds,
142
132
  history: historyProps,
143
133
  focusCursor,
144
134
  failedTurn = null,
@@ -153,7 +143,6 @@ export const GemieThread = memo(function GemieThread({
153
143
  onScroll,
154
144
  onReply,
155
145
  onReactionChange,
156
- onOpenAgentChat,
157
146
  readOnly = false,
158
147
  }: GemieThreadProps) {
159
148
  const { t } = useLabels();
@@ -163,25 +152,13 @@ export const GemieThread = memo(function GemieThread({
163
152
 
164
153
  useFailedTurnToast(failedTurn, onRetryTurn);
165
154
 
166
- const {
167
- rows,
168
- live,
169
- history,
170
- ids,
171
- arrived,
172
- dayLabels,
173
- seamIds,
174
- speakers,
175
- consulted,
176
- lastReplyIndex,
177
- timingOf,
178
- } = useThreadRows({
179
- messages,
180
- history: pastMessages,
181
- conversationId,
182
- conversationLoading,
183
- memberIds,
184
- });
155
+ const { rows, live, history, ids, arrived, dayLabels, seamIds, lastReplyIndex, timingOf } =
156
+ useThreadRows({
157
+ messages,
158
+ history: pastMessages,
159
+ conversationId,
160
+ conversationLoading,
161
+ });
185
162
 
186
163
  // ── The thought panel: this conversation as it reads it, and opening it on a turn ──
187
164
  const thoughtScope = useThoughtScope({
@@ -302,9 +279,6 @@ export const GemieThread = memo(function GemieThread({
302
279
  );
303
280
  }
304
281
 
305
- const chattedWith = (messageId: string): string =>
306
- t('chat.chattedWith', { name: speakers.get(messageId)?.agentName ?? '' });
307
-
308
282
  const renderRow = (message: Message, index: number) => {
309
283
  const fromHistory = index < history.length;
310
284
  const timing = timingOf(message.id);
@@ -314,53 +288,29 @@ export const GemieThread = memo(function GemieThread({
314
288
  <Fragment key={message.id || `row-${index}`}>
315
289
  {seamIds.has(message.id) ? <Divider spacing={16}>{t('chat.newStretch')}</Divider> : null}
316
290
  {dayLabel === undefined ? null : <ChatDateHeader label={dayLabel} placement="inline" />}
317
- {/* Where another agent comes into the conversation: whom the person is chatting with now. */}
318
- {speakers.has(message.id) ? (
319
- <Divider spacing={16}>
320
- {onOpenAgentChat === undefined ? (
321
- chattedWith(message.id)
322
- ) : (
323
- <Button
324
- appearance="subtle"
325
- tone="neutral"
326
- size="xs"
327
- onPress={() => {
328
- const exchange = agentExchange(rows, message.id, memberIds);
329
- if (exchange !== null) onOpenAgentChat(exchange);
330
- }}
331
- >
332
- {chattedWith(message.id)}
333
- </Button>
334
- )}
335
- </Divider>
336
- ) : null}
337
- {/* What a consulted agent said is not drawn under its line: the lead answers with it, and
338
- the line opens the exchange. Without a way to open it, it stays where it was. */}
339
- {onOpenAgentChat !== undefined && consulted.has(message.id) ? null : (
340
- <ThreadRow
341
- message={message}
342
- // Only a message that arrived while this conversation was open animates in; none of the
343
- // history ever does.
344
- isNew={!fromHistory && arrived.has(message.id)}
345
- isLastReply={isLastReply}
346
- // Only the last reply reads it: handing it to every row would re-render the whole thread
347
- // when a turn starts and when it ends.
348
- isLoading={isLastReply ? isLoading : false}
349
- conversationId={conversationOf(index)}
350
- onLayout={index === focusIndex ? handleFocusLayout : undefined}
351
- actions={actions}
352
- readAloudState={readAloud.stateOf(message.id)}
353
- readAloudBlocked={readAloud.blocked}
354
- onRegenerate={canRegenerate(message, index) ? onRegenerate : undefined}
355
- // A question of an earlier conversation is not in the list an edit cuts, so the "edit"
356
- // would silently become a new turn.
357
- onStartEdit={
358
- message.role === 'user' && !fromHistory && !callActive ? onStartEdit : undefined
359
- }
360
- workStartedAt={timing.startedAt}
361
- workEndedAt={timing.endedAt}
362
- />
363
- )}
291
+ <ThreadRow
292
+ message={message}
293
+ // Only a message that arrived while this conversation was open animates in; none of the
294
+ // history ever does.
295
+ isNew={!fromHistory && arrived.has(message.id)}
296
+ isLastReply={isLastReply}
297
+ // Only the last reply reads it: handing it to every row would re-render the whole thread
298
+ // when a turn starts and when it ends.
299
+ isLoading={isLastReply ? isLoading : false}
300
+ conversationId={conversationOf(index)}
301
+ onLayout={index === focusIndex ? handleFocusLayout : undefined}
302
+ actions={actions}
303
+ readAloudState={readAloud.stateOf(message.id)}
304
+ readAloudBlocked={readAloud.blocked}
305
+ onRegenerate={canRegenerate(message, index) ? onRegenerate : undefined}
306
+ // A question of an earlier conversation is not in the list an edit cuts, so the "edit"
307
+ // would silently become a new turn.
308
+ onStartEdit={
309
+ message.role === 'user' && !fromHistory && !callActive ? onStartEdit : undefined
310
+ }
311
+ workStartedAt={timing.startedAt}
312
+ workEndedAt={timing.endedAt}
313
+ />
364
314
  </Fragment>
365
315
  );
366
316
  };
@@ -21,7 +21,9 @@ import { type LayoutChangeEvent, View } from 'react-native';
21
21
  import Animated from 'react-native-reanimated';
22
22
  import type { ReadAloudState } from '../../hooks/useReadAloud';
23
23
  import type { Vote } from '../../hooks/useMessageVote';
24
- import { readAgentCharacter } from '../../lib/agent-character';
24
+ import { agentCharacterOf } from '../../lib/participants';
25
+ import { gemieConversationOf } from '../../runtime/gemie-conversations';
26
+ import { GemieConversationCard } from './GemieConversationCard';
25
27
  import { useBubbles } from '../../lib/bubbles';
26
28
  import { messageText } from '../../lib/content-utils';
27
29
  import { hasAttachments, TurnAttachments } from './TurnAttachments';
@@ -259,7 +261,7 @@ function ReplyTurn({
259
261
  const plan = message.plan;
260
262
  const agent = message.agentInfo;
261
263
  const { readOnly = false } = actions;
262
- /** In an agent's thread every reply is a bubble, and so is a consulted agent's anywhere. */
264
+ /** In an agent's thread every reply is a bubble, and so is any reply under another gemie's name. */
263
265
  const bubbled = useBubbles() || agent !== undefined;
264
266
 
265
267
  // A host's own drawing of a catalogue tool's result, before any generic card: keyed by the
@@ -294,9 +296,17 @@ function ReplyTurn({
294
296
  : [{ key: call.toolCallId || `canvas-${message.id}-${index}`, call, canvas }];
295
297
  })
296
298
  : [];
299
+ // A gemie writing to another draws the card of their conversation, never a generic step.
300
+ const gemieConversations = toolInvocations.flatMap((call, index) => {
301
+ const conversation = gemieConversationOf(call);
302
+ return conversation === null
303
+ ? []
304
+ : [{ key: call.toolCallId || `gemies-${message.id}-${index}`, call, conversation }];
305
+ });
297
306
  const renderedCalls = new Set([
298
307
  ...rendered.map(({ call }) => call),
299
308
  ...inlineCanvases.map(({ call }) => call),
309
+ ...gemieConversations.map(({ call }) => call),
300
310
  ]);
301
311
 
302
312
  // The calls the work summary lists: every one that did not draw its own card. Read on each
@@ -399,13 +409,14 @@ function ReplyTurn({
399
409
 
400
410
  const { openThought } = actions;
401
411
  const viewDetails = openThought && (() => openThought(message.id, 'steps'));
402
- /** A consulted agent's reply is drawn from its first frame: its identity is where it joins from. */
412
+ /** A reply under a gemie's name is drawn from its first frame: its identity shows who is writing. */
403
413
  const showsContent =
404
414
  agent !== undefined ||
405
415
  text.length > 0 ||
406
416
  hasWorkLog ||
407
417
  toolCards.length > 0 ||
408
418
  rendered.length > 0 ||
419
+ gemieConversations.length > 0 ||
409
420
  inlineCanvases.length > 0 ||
410
421
  (message.isStreaming === true && message.source === 'voice');
411
422
  /** Its avatar is the source of the flight into the header while it is answering, and the landing of a group's first one. */
@@ -459,7 +470,7 @@ function ReplyTurn({
459
470
  {agent && agentAnchor ? (
460
471
  <View className="mb-0.5">
461
472
  <AgentReplyIdentity
462
- character={readAgentCharacter(agent.character, agent.color)}
473
+ character={agentCharacterOf(agent)}
463
474
  name={agent.name}
464
475
  thinking={agentLive && text.length === 0}
465
476
  workingKey={agent.id}
@@ -548,6 +559,14 @@ function ReplyTurn({
548
559
  <ToolResultCard card={card} />
549
560
  </MessageBlockBoundary>
550
561
  ))}
562
+ {gemieConversations.map(({ key, conversation }) => (
563
+ <MessageBlockBoundary key={key}>
564
+ <GemieConversationCard
565
+ call={conversation}
566
+ startedLive={message.isStreaming === true}
567
+ />
568
+ </MessageBlockBoundary>
569
+ ))}
551
570
  {questions.length === 0 ? null : (
552
571
  <MessageBlockBoundary>
553
572
  <AskedQuestions questions={questions} />
@@ -555,7 +574,7 @@ function ReplyTurn({
555
574
  )}
556
575
  {agent && message.turnOutcome === 'failed' && text.length === 0 ? (
557
576
  <Text className="text-sm text-muted-foreground">
558
- {t('chat.consultFailed', { name: agent.name })}
577
+ {t('chat.agentFailed', { name: agent.name })}
559
578
  </Text>
560
579
  ) : null}
561
580
  {/* A requested run that ended with no answer: the app's words, never the run's. */}
@@ -8,7 +8,6 @@ import {
8
8
  threadSeamIds,
9
9
  turnTimings,
10
10
  } from '../runtime/model';
11
- import { consultedReplies, speakerChanges } from '../runtime/thread/speaker-changes';
12
11
  import { useTimelineShape } from './useTimelineWindow';
13
12
 
14
13
  /** The history of a conversation that has none, as ONE array: a fresh `[]` per render would break every memo. */
@@ -31,8 +30,6 @@ export interface UseThreadRowsOptions {
31
30
  conversationId: string | undefined;
32
31
  /** The conversation's messages are still on their way. */
33
32
  conversationLoading: boolean;
34
- /** The agents that are part of this conversation (the direct agent or a group's members): not announced as newcomers. */
35
- memberIds?: ReadonlySet<string>;
36
33
  }
37
34
 
38
35
  /**
@@ -48,7 +45,6 @@ export function useThreadRows({
48
45
  history: historyMessages,
49
46
  conversationId,
50
47
  conversationLoading,
51
- memberIds,
52
48
  }: UseThreadRowsOptions) {
53
49
  const { t, locale } = useLabels();
54
50
  const history = historyMessages ?? NO_HISTORY;
@@ -125,12 +121,6 @@ export function useThreadRows({
125
121
  [history, liveShape, conversationId],
126
122
  );
127
123
 
128
- /** The turns where a consulted agent comes into the conversation: a line says whom the person is chatting with. */
129
- const speakers = useMemo(() => speakerChanges(shape, memberIds), [shape, memberIds]);
130
-
131
- /** What those agents said: under the line, nothing; the line opens it. */
132
- const consulted = useMemo(() => consultedReplies(shape, memberIds), [shape, memberIds]);
133
-
134
124
  const timingOf = useCallback(
135
125
  (messageId: string) => timings.get(messageId) ?? EMPTY_TIMING,
136
126
  [timings],
@@ -149,8 +139,6 @@ export function useThreadRows({
149
139
  arrived,
150
140
  dayLabels,
151
141
  seamIds,
152
- speakers,
153
- consulted,
154
142
  lastReplyIndex,
155
143
  timingOf,
156
144
  };
package/src/index.ts CHANGED
@@ -10,11 +10,10 @@ export type {
10
10
  GemieChatContentProps,
11
11
  GemieChatState,
12
12
  } from './components/GemieChatContent';
13
- export { GemieParticipants, useParticipants } from './components/GemieParticipants';
14
- export type {
15
- GemieParticipantsProps,
16
- UseParticipantsOptions,
17
- } from './components/GemieParticipants';
13
+ export { GemieParticipants } from './components/GemieParticipants';
14
+ export type { GemieParticipantsProps } from './components/GemieParticipants';
15
+ export { GemieBetweenGemies } from './components/GemieBetweenGemies';
16
+ export type { GemieBetweenGemiesProps } from './components/GemieBetweenGemies';
18
17
  export { GemieParticipantsHeader } from './components/GemieParticipantsHeader';
19
18
  export {
20
19
  GemieActivityLine,
@@ -24,7 +23,7 @@ export {
24
23
  export type { GemieActivityLineProps } from './components/GemieActivityLine';
25
24
  export type { GemieParticipantsHeaderProps } from './components/GemieParticipantsHeader';
26
25
  export { ALIA_GEMIE_ID } from './lib/alia-gemie';
27
- export { ALIA_LEAD, leadOf } from './lib/participants';
26
+ export { ALIA_LEAD, agentCharacterOf, leadOf } from './lib/participants';
28
27
  export type { GemieChatParticipants, GemieLead, GemieParticipant } from './lib/participants';
29
28
  export { ANCHORS, leadToProfile } from './lib/flights';
30
29
  export { parseCatalogueTool, toolRendererKey } from './lib/catalogue-tool';
@@ -89,8 +89,11 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
89
89
  'chat.newConversationDismiss': 'Not now',
90
90
  'chat.newConversationOffer': 'Start a new conversation?',
91
91
  'chat.newStretch': 'New conversation',
92
- 'chat.chattedWith': 'Chatted with %{name}',
93
- 'chat.agentChatNotice': 'Conversation between Gemies. Read only.',
92
+ 'chat.betweenGemiesNotice': 'Conversation between Gemies. Read only.',
93
+ 'chat.gemiesTalking': '%{from} is talking to %{to}…',
94
+ 'chat.gemiesTalked': '%{from} talked to %{to}',
95
+ 'chat.gemieWriting': '%{name} is writing…',
96
+ 'chat.gemiesOpen': 'See the conversation',
94
97
  'chat.reactToMessage': 'React to message',
95
98
  'chat.groupWelcome': 'A few minds, one conversation',
96
99
  'chat.groupPlaceholder': 'Message the group',
@@ -120,7 +123,7 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
120
123
  'chat.toolCard.paused': 'Paused',
121
124
  'chat.toolCard.scheduled': 'Scheduled',
122
125
  'chat.turnActions': 'Message actions',
123
- 'chat.consultFailed': "%{name} couldn't answer.",
126
+ 'chat.agentFailed': "%{name} couldn't answer.",
124
127
  'chat.taskUnfinished': "%{name} couldn't finish this task.",
125
128
  'chat.shareFailed': "Couldn't create the share link.",
126
129
  'chat.sharedFailed': "Couldn't load this conversation.",
@@ -373,7 +376,7 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
373
376
  'tasks.tool.done.agentSearch': 'Searched Gemies',
374
377
  'tasks.tool.done.browse': 'Browsed',
375
378
  'tasks.tool.done.codeInterpreter': 'Ran code',
376
- 'tasks.tool.done.consultAgent': 'Consulted a Gemie',
379
+ 'tasks.tool.done.sendMessage': 'Wrote to a Gemie',
377
380
  'tasks.tool.done.fileEdit': 'Edited file',
378
381
  'tasks.tool.done.generateFile': 'Generated file',
379
382
  'tasks.tool.done.shellExec': 'Ran command',
@@ -383,7 +386,7 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
383
386
  'tasks.tool.pill.agentSearch': 'Searching Gemies',
384
387
  'tasks.tool.pill.browse': 'Browsing',
385
388
  'tasks.tool.pill.codeInterpreter': 'Running code',
386
- 'tasks.tool.pill.consultAgent': 'Consulting a Gemie',
389
+ 'tasks.tool.pill.sendMessage': 'Writing to a Gemie',
387
390
  'tasks.tool.pill.fileEdit': 'Editing file',
388
391
  'tasks.tool.pill.generateFile': 'Generating file',
389
392
  'tasks.tool.pill.sendDiscord': 'Discord',
@@ -85,8 +85,11 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
85
85
  'chat.newConversationDismiss': 'Ahora no',
86
86
  'chat.newConversationOffer': '¿Empezar una conversación nueva?',
87
87
  'chat.newStretch': 'Conversación nueva',
88
- 'chat.chattedWith': 'Habló con %{name}',
89
- 'chat.agentChatNotice': 'Conversación entre Gemies. Solo lectura.',
88
+ 'chat.betweenGemiesNotice': 'Conversación entre Gemies. Solo lectura.',
89
+ 'chat.gemiesTalking': '%{from} está hablando con %{to}…',
90
+ 'chat.gemiesTalked': '%{from} habló con %{to}',
91
+ 'chat.gemieWriting': '%{name} está escribiendo…',
92
+ 'chat.gemiesOpen': 'Ver la conversación',
90
93
  'chat.groupWelcome': 'Varias mentes, una conversación',
91
94
  'chat.groupPlaceholder': 'Escribe al grupo',
92
95
  'chat.reaction': 'Has reaccionado con {{emoji}}',
@@ -116,7 +119,7 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
116
119
  'chat.toolCard.paused': 'En pausa',
117
120
  'chat.toolCard.scheduled': 'Programada',
118
121
  'chat.turnActions': 'Acciones del mensaje',
119
- 'chat.consultFailed': '%{name} no pudo responder.',
122
+ 'chat.agentFailed': '%{name} no pudo responder.',
120
123
  'chat.taskUnfinished': '%{name} no ha podido terminar esta tarea.',
121
124
  'chat.shareFailed': 'No se pudo crear el enlace para compartir.',
122
125
  'chat.sharedFailed': 'No se pudo cargar esta conversación.',
@@ -375,7 +378,7 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
375
378
  'tasks.tool.done.agentSearch': 'Buscó Gemies',
376
379
  'tasks.tool.done.browse': 'Navegó',
377
380
  'tasks.tool.done.codeInterpreter': 'Ejecutó código',
378
- 'tasks.tool.done.consultAgent': 'Consultó a un Gemie',
381
+ 'tasks.tool.done.sendMessage': 'Escribió a un Gemie',
379
382
  'tasks.tool.done.fileEdit': 'Editó un archivo',
380
383
  'tasks.tool.done.generateFile': 'Generó un archivo',
381
384
  'tasks.tool.done.shellExec': 'Ejecutó un comando',
@@ -385,7 +388,7 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
385
388
  'tasks.tool.pill.agentSearch': 'Buscando Gemies',
386
389
  'tasks.tool.pill.browse': 'Navegando',
387
390
  'tasks.tool.pill.codeInterpreter': 'Ejecutando código',
388
- 'tasks.tool.pill.consultAgent': 'Consultando a un Gemie',
391
+ 'tasks.tool.pill.sendMessage': 'Escribiendo a un Gemie',
389
392
  'tasks.tool.pill.fileEdit': 'Editando archivo',
390
393
  'tasks.tool.pill.generateFile': 'Generando archivo',
391
394
  'tasks.tool.pill.sendDiscord': 'Discord',
@@ -0,0 +1,14 @@
1
+ import { createContext, useContext } from 'react';
2
+
3
+ /**
4
+ * How a card in the thread opens a conversation between gemies (ADR 0042): the chat that draws it
5
+ * shows the conversation read-only over itself (`GemieChatContent`). `null` outside a chat — a
6
+ * shared conversation, for one — where the card opens nothing.
7
+ */
8
+ const GemieConversationOpener = createContext<((conversationId: string) => void) | null>(null);
9
+
10
+ export const GemieConversationOpenerProvider = GemieConversationOpener.Provider;
11
+
12
+ export function useOpenGemieConversation(): ((conversationId: string) => void) | null {
13
+ return useContext(GemieConversationOpener);
14
+ }
@@ -3,8 +3,9 @@ import type { GemieAgentProfile } from '../runtime/agents';
3
3
  import type { Message } from '../runtime/types';
4
4
  import { readAgentCharacter } from './agent-character';
5
5
  import { ALIA_AVATAR } from './alia-character';
6
+ import { ALIA_GEMIE_ID } from './alia-gemie';
6
7
 
7
- /** Somebody in the conversation who answers: its lead, or an agent the lead consulted. */
8
+ /** Somebody in the conversation who answers: its lead, a group's member, or a gemie of a conversation between gemies. */
8
9
  export interface GemieParticipant {
9
10
  id: string;
10
11
  name: string;
@@ -28,7 +29,7 @@ export interface GemieLead extends GemieParticipant {
28
29
  /** Who is in the conversation, as the header draws it: the lead, then whoever has joined. */
29
30
  export interface GemieChatParticipants {
30
31
  lead: GemieLead;
31
- /** The consulted agents that have joined the header, in the order they joined. */
32
+ /** The others in it: a group's other members, or the gemie the lead talks to. */
32
33
  joined: GemieParticipant[];
33
34
  /**
34
35
  * The conversation they are in, so the header can say live what one of them is doing
@@ -73,31 +74,24 @@ export function leadOf(profile: GemieAgentProfile | null | undefined): GemieLead
73
74
  };
74
75
  }
75
76
 
76
- /** A consulted agent as a message carries it (`agentInfo`). */
77
+ /**
78
+ * The character a gemie is drawn as, from what a message carries of it. Alia's gemie carries no
79
+ * character of its own (her look is the app's, `ALIA_AVATAR`), so she is drawn as herself rather
80
+ * than as the default a missing character falls back to.
81
+ */
82
+ export function agentCharacterOf(agentInfo: NonNullable<Message['agentInfo']>): AvatarCharacter {
83
+ return agentInfo.id === ALIA_GEMIE_ID
84
+ ? ALIA_AVATAR
85
+ : readAgentCharacter(agentInfo.character, agentInfo.color);
86
+ }
87
+
88
+ /** A gemie as a message carries it (`agentInfo`). */
77
89
  export function participantOf(agentInfo: NonNullable<Message['agentInfo']>): GemieParticipant {
78
90
  return {
79
91
  id: agentInfo.id,
80
92
  name: agentInfo.name,
81
93
  handle: agentInfo.handle,
82
- character: readAgentCharacter(agentInfo.character, agentInfo.color),
94
+ character: agentCharacterOf(agentInfo),
83
95
  color: agentInfo.color,
84
96
  };
85
97
  }
86
-
87
- /**
88
- * The agents that answered in `messages`, besides the lead, in the order they first did — each
89
- * with whether its first answer is the one being streamed now (it is joining) or one already
90
- * written (it was there when the chat opened).
91
- */
92
- export function consultedAgents(
93
- messages: readonly Message[],
94
- leadId: string,
95
- ): Array<{ participant: GemieParticipant; live: boolean }> {
96
- const seen = new Map<string, { participant: GemieParticipant; live: boolean }>();
97
- for (const message of messages) {
98
- const info = message.agentInfo;
99
- if (!info || info.id === leadId || seen.has(info.id)) continue;
100
- seen.set(info.id, { participant: participantOf(info), live: message.isStreaming === true });
101
- }
102
- return [...seen.values()];
103
- }
@@ -26,6 +26,8 @@ function toConversation(row: RealtimeConversationRow): Conversation {
26
26
  agentId: row.agentId,
27
27
  memberAgentIds: row.memberAgentIds,
28
28
  spaceId: row.spaceId,
29
+ ...(row.kind === undefined ? {} : { kind: row.kind }),
30
+ ...(row.members === undefined ? {} : { members: row.members }),
29
31
  threadId: row.threadId,
30
32
  app: row.app,
31
33
  unreadCount: row.unreadCount,
@@ -36,6 +38,9 @@ function toConversation(row: RealtimeConversationRow): Conversation {
36
38
  }
37
39
 
38
40
  function matches(filter: ConversationsFilter | undefined, row: Conversation): boolean {
41
+ // The person's own lists never hold a conversation between their gemies, and that list holds
42
+ // nothing else (ADR 0042).
43
+ if ((filter?.kind ?? 'person') !== (row.kind ?? 'person')) return false;
39
44
  if (!filter) return true;
40
45
  if (filter.agentId !== undefined && row.agentId !== filter.agentId) return false;
41
46
  if (filter.app !== undefined && row.app !== filter.app) return false;
@@ -66,6 +66,10 @@ export interface RealtimeConversationRow {
66
66
  readonly threadId: string | null;
67
67
  readonly memberAgentIds: string[];
68
68
  readonly spaceId: string | null;
69
+ /** `gemies` for a conversation between the person's gemies (ADR 0042), which they only read. */
70
+ readonly kind?: 'person' | 'gemies';
71
+ /** Its two gemies, when it is one between gemies. */
72
+ readonly members?: NonNullable<Message['agentInfo']>[];
69
73
  readonly app: string | null;
70
74
  readonly unreadCount: number;
71
75
  readonly createdAt: string;
@@ -0,0 +1,78 @@
1
+ import { useOxy } from '@oxy.so/services/ui/client';
2
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import type { GemieApi } from './api';
4
+ import { useGemieApi } from './api';
5
+ import { errorStatus } from './error-utils';
6
+ import { gemieQueryKeys } from './query-keys';
7
+ import { ACCOUNT_ROUTES } from './routes';
8
+
9
+ /**
10
+ * A person's channels' Oxy tasks: the authority each channel of theirs acts with — a connected
11
+ * account a gemie answers, a link to a system bot, a gemie's own Telegram bot they linked their
12
+ * Telegram to. Oxy lets only the person's present session mint one, so the apps renew them the
13
+ * way they renew every standing authority: silently while the person is in the app
14
+ * ({@link useChannelTaskRenewal}), and with one tap from the notice they get when a channel needs
15
+ * them ({@link useReauthorizeChannels}). The API renews only what is due: lapsed, undated, or
16
+ * lapsing within its renewal window.
17
+ */
18
+
19
+ export const CHANNEL_TASK_KINDS = ['account', 'bot_link', 'gemie_bot'] as const;
20
+ export type ChannelTaskKind = (typeof CHANNEL_TASK_KINDS)[number];
21
+
22
+ /** One channel: its kind, and its own id (a connected account's `_id`, for an `account`). */
23
+ export interface ChannelTaskRef {
24
+ kind: ChannelTaskKind;
25
+ id: string;
26
+ }
27
+
28
+ /** What one renewal did. */
29
+ export interface ChannelTaskRenewal {
30
+ renewed: ChannelTaskRef[];
31
+ /** The channels that still need the person: a gemie they may no longer grant, Oxy refusing. */
32
+ failed: ChannelTaskRef[];
33
+ }
34
+
35
+ /** Renew every channel of the signed-in person that needs it, with their present session. */
36
+ export async function renewChannelTasks(api: GemieApi): Promise<ChannelTaskRenewal> {
37
+ const { data } = await api.post<ChannelTaskRenewal>(ACCOUNT_ROUTES.renewChannelTasks);
38
+ return data;
39
+ }
40
+
41
+ /**
42
+ * The silent handshake: once a session for the signed-in account, as the apps' agents' work
43
+ * handshake (`POST /agents/:id/work`). Mount it once, where the app is signed in; it draws
44
+ * nothing. A renewed connected account re-reads the accounts list.
45
+ */
46
+ export function useChannelTaskRenewal(): void {
47
+ const api = useGemieApi();
48
+ const queryClient = useQueryClient();
49
+ const { user, isAuthenticated } = useOxy();
50
+ const userId = user?.id ?? '';
51
+ useQuery({
52
+ queryKey: gemieQueryKeys.accounts.channelTaskRenewal(userId),
53
+ queryFn: async () => {
54
+ const renewal = await renewChannelTasks(api);
55
+ if (renewal.renewed.some((ref) => ref.kind === 'account')) {
56
+ await queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all });
57
+ }
58
+ return renewal;
59
+ },
60
+ enabled: isAuthenticated && userId !== '',
61
+ staleTime: Number.POSITIVE_INFINITY,
62
+ // A session that is not the person's (401/403) will not become theirs by asking again.
63
+ retry: (attempt, error) => attempt < 2 && ![401, 403].includes(errorStatus(error) ?? 0),
64
+ });
65
+ }
66
+
67
+ /**
68
+ * The one-tap reauthorisation the notice links to: the tap is the person's say-so, and their
69
+ * present session renews every channel that needs it. Re-reads the accounts list after.
70
+ */
71
+ export function useReauthorizeChannels() {
72
+ const api = useGemieApi();
73
+ const queryClient = useQueryClient();
74
+ return useMutation({
75
+ mutationFn: () => renewChannelTasks(api),
76
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: gemieQueryKeys.accounts.all }),
77
+ });
78
+ }
@@ -1,6 +1,7 @@
1
1
  import { useOxy } from '@oxy.so/services/ui/client';
2
2
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
3
3
  import { useGemieApi } from './api';
4
+ import { renewChannelTasks } from './channel-tasks';
4
5
  import { errorStatus } from './error-utils';
5
6
  import { gemieQueryKeys } from './query-keys';
6
7
  import { ACCOUNT_ROUTES } from './routes';
@@ -88,9 +89,10 @@ export interface ConnectedAccountsAnswer {
88
89
 
89
90
  /**
90
91
  * The caller's accounts, each as its session is now with its grants, and what can be connected.
91
- * An account whose answering gemie's Oxy task lapsed is renewed on the way (the provider link is
92
- * kept; the person looking is the verified requester); a renewal that fails leaves it typed
93
- * inactive for the next visit to retry. An account nobody answers holds no task to renew.
92
+ * When an account's answering gemie's Oxy task lapsed, the person's channels are renewed on the way
93
+ * (`renewChannelTasks`: the provider link is kept; the person looking is the verified requester);
94
+ * one that could not be renewed stays typed inactive for the next visit to retry. An account nobody
95
+ * answers holds no task to renew.
94
96
  */
95
97
  export function useConnectedAccounts() {
96
98
  const api = useGemieApi();
@@ -99,20 +101,20 @@ export function useConnectedAccounts() {
99
101
  queryKey: gemieQueryKeys.accounts.all,
100
102
  queryFn: async (): Promise<ConnectedAccountsAnswer> => {
101
103
  const { data } = await api.get<ConnectedAccountsAnswer>(ACCOUNT_ROUTES.all);
102
- await Promise.all(
103
- data.accounts
104
- .filter(
105
- (account) => account.answeringGemieId && account.oxyTaskState === 'reauth_required',
106
- )
107
- .map(async (account) => {
108
- try {
109
- await api.post(`${ACCOUNT_ROUTES.one(account._id)}/reauthorize`);
110
- account.oxyTaskState = 'active';
111
- } catch {
112
- /* Remains typed inactive; the next verified visit may retry. */
113
- }
114
- }),
104
+ const lapsed = data.accounts.filter(
105
+ (account) => account.answeringGemieId && account.oxyTaskState === 'reauth_required',
115
106
  );
107
+ if (lapsed.length === 0) return data;
108
+ try {
109
+ const { renewed } = await renewChannelTasks(api);
110
+ for (const account of lapsed) {
111
+ if (renewed.some((ref) => ref.kind === 'account' && ref.id === account._id)) {
112
+ account.oxyTaskState = 'active';
113
+ }
114
+ }
115
+ } catch {
116
+ /* Remains typed inactive; the next verified visit may retry. */
117
+ }
116
118
  return data;
117
119
  },
118
120
  enabled: isAuthenticated,