@gemies/sdk 7.1.0 → 9.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 +43 -0
  2. package/README.md +9 -6
  3. package/package.json +1 -1
  4. package/src/accounts.ts +0 -11
  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/connected-accounts.ts +2 -24
  21. package/src/runtime/conversations.ts +18 -8
  22. package/src/runtime/gemie-conversations.ts +122 -0
  23. package/src/runtime/index.ts +6 -2
  24. package/src/runtime/message-history.ts +9 -12
  25. package/src/runtime/query-keys.ts +6 -3
  26. package/src/runtime/room-events.ts +23 -17
  27. package/src/runtime/routes.ts +0 -5
  28. package/src/runtime/stream-events.ts +10 -7
  29. package/src/runtime/types.ts +10 -3
  30. package/src/runtime/use-conversation-stream.ts +31 -26
  31. package/src/runtime/use-conversation-thread.ts +1 -1
  32. package/src/components/thread/AgentExchangeView.tsx +0 -112
  33. package/src/runtime/channel-tasks.ts +0 -78
  34. package/src/runtime/thread/agent-exchange.ts +0 -94
  35. package/src/runtime/thread/speaker-changes.ts +0 -66
@@ -1,78 +0,0 @@
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,94 +0,0 @@
1
- /**
2
- * What an agent was asked and what it answered, rebuilt from the thread alone.
3
- *
4
- * A consultation (`consultAgent`, ADR 0020 §5) is never a conversation of its own in storage. It
5
- * leaves two traces in the turn it happened in: the asker's reply carries the tool invocation (its
6
- * `args.task` is what was asked, its `result` the answer with the agent's identity), and the
7
- * consulted agent's own message (`agentInfo`) holds the answer. Both are already loaded with the
8
- * thread, so the internal exchange needs no request.
9
- *
10
- * Several consultations of one agent in a turn come out in the order they were made. A turn whose
11
- * task was not kept (an older message, a trimmed invocation) still yields the answers, with no
12
- * question.
13
- */
14
- import { messageText } from '../../lib/content-utils';
15
- import type { Message } from '../types';
16
-
17
- /** The tool the lead consults with (`lib/tools/consult-agent.ts`). */
18
- export const CONSULT_AGENT_TOOL = 'consultAgent';
19
-
20
- /** An agent as a message carries it (`Message.agentInfo`). */
21
- type ExchangeAgent = NonNullable<Message['agentInfo']>;
22
-
23
- interface AgentExchangePair {
24
- /** Who asked: the agent whose reply held the call, or `null` for the conversation's own lead. */
25
- asker: ExchangeAgent | null;
26
- /** What was asked; `null` when the stored invocation has no task. */
27
- task: string | null;
28
- /** What the consulted agent answered. */
29
- answer: string;
30
- }
31
-
32
- export interface AgentExchange {
33
- /** The consulted agent. */
34
- agent: ExchangeAgent;
35
- pairs: AgentExchangePair[];
36
- }
37
-
38
- type ExchangeRow = Pick<Message, 'id' | 'role' | 'content' | 'toolInvocations' | 'agentInfo'>;
39
-
40
- interface Consultation {
41
- asker: ExchangeAgent | null;
42
- task: string | null;
43
- response: string | null;
44
- }
45
-
46
- /**
47
- * The exchange between the conversation and the agent that speaks at `anchorId`, over the turn
48
- * (the rows between the questions of the person) that message is in. `null` when `anchorId` is
49
- * not a message of a consulted agent.
50
- */
51
- export function agentExchange(
52
- rows: readonly ExchangeRow[],
53
- anchorId: string,
54
- /** The direct agent or group members speak to the person, not in an internal exchange. */
55
- members?: ReadonlySet<string>,
56
- ): AgentExchange | null {
57
- const anchorIndex = rows.findIndex((row) => row.id === anchorId);
58
- const agent = rows[anchorIndex]?.agentInfo;
59
- if (anchorIndex < 0 || !agent || members?.has(agent.id)) return null;
60
-
61
- let start = anchorIndex;
62
- while (start > 0 && rows[start - 1]?.role !== 'user') start -= 1;
63
- let end = anchorIndex + 1;
64
- while (end < rows.length && rows[end]?.role !== 'user') end += 1;
65
- const turn = rows.slice(start, end);
66
-
67
- const consultations: Consultation[] = [];
68
- for (const row of turn) {
69
- for (const call of row.toolInvocations ?? []) {
70
- if (call.toolName !== CONSULT_AGENT_TOOL || call.state !== 'result') continue;
71
- const result = call.result;
72
- if (!result || typeof result !== 'object' || result.error || result.agentId !== agent.id) {
73
- continue;
74
- }
75
- const task = call.args?.task;
76
- consultations.push({
77
- asker: row.agentInfo ?? null,
78
- task: typeof task === 'string' && task.trim() !== '' ? task : null,
79
- response: typeof result.response === 'string' ? result.response : null,
80
- });
81
- }
82
- }
83
- const answers = turn.filter((row) => row.role === 'assistant' && row.agentInfo?.id === agent.id);
84
-
85
- const pairs: AgentExchangePair[] = [];
86
- for (let i = 0; i < Math.max(consultations.length, answers.length); i += 1) {
87
- const consultation = consultations[i];
88
- const stored = answers[i];
89
- const answer = stored ? messageText(stored) : (consultation?.response ?? '');
90
- if (answer === '' && !consultation?.task) continue;
91
- pairs.push({ asker: consultation?.asker ?? null, task: consultation?.task ?? null, answer });
92
- }
93
- return { agent, pairs };
94
- }
@@ -1,66 +0,0 @@
1
- /**
2
- * The turns where another agent comes into the conversation.
3
- *
4
- * Agent-authored replies carry `agentInfo`, including the lead's scheduled or proactive replies.
5
- * The conversation's members (the direct agent or the group's roster) distinguish those from
6
- * consultations with an outside agent. The thread marks the turn where a consulted agent starts
7
- * speaking, or starts again after the lead has spoken in between, with a line saying whom the person is now
8
- * chatting with. Consecutive replies of one agent get the line once; the lead resuming gets none
9
- * (it is the conversation's own voice) but does reset the run, so the same agent coming back is
10
- * announced again.
11
- *
12
- * Only an agent from OUTSIDE the conversation is announced. The members of a group chat are in
13
- * it: each speaks as itself, with its own name on its message, as in any group chat, and a line
14
- * saying whom the person is "now chatting with" at each change of speaker would be wrong.
15
- *
16
- * What a consulted agent said is not part of the person's conversation: the lead already answers
17
- * with it. The thread shows the line and nothing under it, and the line opens the exchange.
18
- */
19
- export interface SpeakerChange {
20
- /** The agent that starts speaking here. */
21
- readonly agentName: string;
22
- }
23
-
24
- export function speakerChanges(
25
- rows: readonly {
26
- readonly id: string;
27
- readonly role: string;
28
- readonly agentInfo?: { readonly id: string; readonly name: string } | null;
29
- }[],
30
- /** The direct agent or group members: never announced. */
31
- members?: ReadonlySet<string>,
32
- ): Map<string, SpeakerChange> {
33
- const changes = new Map<string, SpeakerChange>();
34
- let current: string | null = null;
35
- for (const row of rows) {
36
- if (row.role !== 'assistant') continue;
37
- const speaker = row.agentInfo?.id ?? null;
38
- if (speaker !== null && speaker !== current && row.agentInfo && !members?.has(speaker)) {
39
- changes.set(row.id, { agentName: row.agentInfo.name });
40
- }
41
- current = speaker;
42
- }
43
- return changes;
44
- }
45
-
46
- /**
47
- * The replies of agents from OUTSIDE the conversation, every one of them: what a consulted agent
48
- * said, which the thread leaves out under the line that announces it (the exchange it opens has
49
- * it). A group's members and the lead are never in it.
50
- */
51
- export function consultedReplies(
52
- rows: readonly {
53
- readonly id: string;
54
- readonly role: string;
55
- readonly agentInfo?: { readonly id: string; readonly name: string } | null;
56
- }[],
57
- members?: ReadonlySet<string>,
58
- ): Set<string> {
59
- const ids = new Set<string>();
60
- for (const row of rows) {
61
- if (row.role === 'assistant' && row.agentInfo && !members?.has(row.agentInfo.id)) {
62
- ids.add(row.id);
63
- }
64
- }
65
- return ids;
66
- }