@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.
- package/CHANGELOG.md +1662 -0
- package/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +516 -2
- package/package.json +102 -4
- package/src/animations.ts +5 -0
- package/src/ask-eager.ts +8 -0
- package/src/ask-text.ts +11 -0
- package/src/ask.ts +12 -0
- package/src/avatar.ts +13 -0
- package/src/character.ts +1 -0
- package/src/components/AmbientField.tsx +580 -0
- package/src/components/ComposerDropZone.tsx +235 -0
- package/src/components/ComposerSuggestions.tsx +45 -0
- package/src/components/GemieAskCore.tsx +184 -0
- package/src/components/GemieAskProvider.tsx +18 -0
- package/src/components/GemieAskProviderLazy.tsx +27 -0
- package/src/components/GemieAskProviderText.tsx +25 -0
- package/src/components/GemieAskSheet.tsx +51 -0
- package/src/components/GemieAskSheetWithVoice.tsx +10 -0
- package/src/components/GemieAvatar.tsx +57 -0
- package/src/components/GemieAvatarIcon.tsx +35 -0
- package/src/components/GemieChatContent.tsx +900 -0
- package/src/components/GemieChatHeader.tsx +123 -0
- package/src/components/GemieChatScreen.tsx +170 -0
- package/src/components/GemieChatSheet.tsx +368 -0
- package/src/components/GemieChatWithVoice.tsx +13 -0
- package/src/components/GemieComposer.tsx +388 -0
- package/src/components/GemieGroupWelcome.tsx +37 -0
- package/src/components/GemieParticipants.tsx +133 -0
- package/src/components/GemieParticipantsHeader.tsx +27 -0
- package/src/components/GemieRecentConversations.tsx +65 -0
- package/src/components/GemieSharedConversation.tsx +87 -0
- package/src/components/GemieWelcomeMessage.tsx +58 -0
- package/src/components/IdentityMark.tsx +225 -0
- package/src/components/Image.tsx +12 -0
- package/src/components/InertWhen.tsx +48 -0
- package/src/components/PlanPreviewCard.tsx +53 -0
- package/src/components/QuestionCard.tsx +64 -0
- package/src/components/ReplyMarkdown.tsx +373 -0
- package/src/components/RichBlocks.tsx +195 -0
- package/src/components/VoiceModeIcon.tsx +18 -0
- package/src/components/canvas/CanvasComponent.tsx +65 -0
- package/src/components/canvas/ChartRenderer.tsx +73 -0
- package/src/components/canvas/CodeRenderer.tsx +20 -0
- package/src/components/canvas/DashboardRenderer.tsx +70 -0
- package/src/components/canvas/DeckRenderer.tsx +43 -0
- package/src/components/canvas/FormRenderer.tsx +101 -0
- package/src/components/canvas/MarkdownRenderer.tsx +14 -0
- package/src/components/canvas/TableRenderer.tsx +47 -0
- package/src/components/icons/RiEmojiPicker.tsx +39 -0
- package/src/components/icons/RiMoreDots.tsx +32 -0
- package/src/components/icons/RiReplyLine.tsx +25 -0
- package/src/components/thought/FilesAndSources.tsx +120 -0
- package/src/components/thought/ThoughtPanel.tsx +426 -0
- package/src/components/thought/ToolStep.tsx +134 -0
- package/src/components/thread/AgentExchangeView.tsx +112 -0
- package/src/components/thread/AgentResultCard.tsx +125 -0
- package/src/components/thread/AgentTaskCard.tsx +127 -0
- package/src/components/thread/ChatBubble.tsx +256 -0
- package/src/components/thread/GemieThread.tsx +455 -0
- package/src/components/thread/MessageBlockBoundary.tsx +78 -0
- package/src/components/thread/NewConversationOffer.tsx +54 -0
- package/src/components/thread/ThreadRow.tsx +598 -0
- package/src/components/thread/ThreadSearch.tsx +130 -0
- package/src/components/thread/ThreadSkeleton.tsx +30 -0
- package/src/components/thread/ToolResultCard.tsx +254 -0
- package/src/components/thread/TurnMenu.tsx +54 -0
- package/src/components/thread/TurnStatusLine.tsx +34 -0
- package/src/components/voice/GemieVoiceCall.tsx +21 -0
- package/src/components/voice/GemieVoiceCall.web.tsx +17 -0
- package/src/components/voice/VoiceCallContext.ts +13 -0
- package/src/components/voice/VoiceControls.tsx +106 -0
- package/src/components/voice/VoiceSession.tsx +120 -0
- package/src/components/voice/withVoiceCall.tsx +25 -0
- package/src/csp.ts +50 -0
- package/src/dictation.ts +40 -0
- package/src/hooks/useAmbientWave.ts +184 -0
- package/src/hooks/useAtBottom.ts +51 -0
- package/src/hooks/useAttachMenu.ts +93 -0
- package/src/hooks/useAttachmentIntake.ts +401 -0
- package/src/hooks/useAudioLevelMonitor.ts +46 -0
- package/src/hooks/useAudioLevels.ts +51 -0
- package/src/hooks/useChatComposer.ts +309 -0
- package/src/hooks/useChatVoice.ts +129 -0
- package/src/hooks/useComposerSuggestions.ts +84 -0
- package/src/hooks/useDictation.ts +292 -0
- package/src/hooks/useDocumentPicker.ts +11 -0
- package/src/hooks/useFailedTurnToast.ts +43 -0
- package/src/hooks/useFocusWhenPresented.ts +41 -0
- package/src/hooks/useGemieActivity.ts +31 -0
- package/src/hooks/useImagePicker.ts +38 -0
- package/src/hooks/useMessageReactions.ts +119 -0
- package/src/hooks/useMessageVote.ts +50 -0
- package/src/hooks/useOpenThought.ts +79 -0
- package/src/hooks/usePendingQuestions.ts +19 -0
- package/src/hooks/useReadAloud.ts +92 -0
- package/src/hooks/useShareHandler.ts +24 -0
- package/src/hooks/useSoundEffects.ts +137 -0
- package/src/hooks/useTTS.ts +303 -0
- package/src/hooks/useThoughtScope.ts +59 -0
- package/src/hooks/useThreadRows.ts +157 -0
- package/src/hooks/useThreadView.ts +67 -0
- package/src/hooks/useTimelineWindow.ts +256 -0
- package/src/hooks/useVoiceLauncher.ts +180 -0
- package/src/hooks/useVoiceRoom.ts +212 -0
- package/src/index.ts +140 -0
- package/src/lib/activity-socket.ts +102 -0
- package/src/lib/activity-store.ts +53 -0
- package/src/lib/add-menu.ts +7 -0
- package/src/lib/agent-character.ts +28 -0
- package/src/lib/alia-character.ts +14 -0
- package/src/lib/attachment-intake.ts +154 -0
- package/src/lib/attachment-tiles.ts +74 -0
- package/src/lib/audio-level.ts +130 -0
- package/src/lib/audio-request-auth.ts +4 -0
- package/src/lib/audio-session-binding.ts +27 -0
- package/src/lib/bubbles.tsx +16 -0
- package/src/lib/call-thread.ts +33 -0
- package/src/lib/canvas-result.ts +21 -0
- package/src/lib/catalogue-tool.ts +22 -0
- package/src/lib/citations.ts +192 -0
- package/src/lib/clipboard.ts +23 -0
- package/src/lib/content-utils.ts +46 -0
- package/src/lib/copy-en.ts +291 -0
- package/src/lib/copy-es.ts +287 -0
- package/src/lib/copy.ts +38 -0
- package/src/lib/deferred/document-picker.ts +2 -0
- package/src/lib/deferred/document-picker.web.ts +12 -0
- package/src/lib/deferred/expo-audio.ts +2 -0
- package/src/lib/deferred/expo-audio.web.ts +12 -0
- package/src/lib/deferred/image-data-url.ts +5 -0
- package/src/lib/deferred/image-data-url.web.ts +12 -0
- package/src/lib/dictation-protocol.ts +142 -0
- package/src/lib/dictation-recorder-types.ts +37 -0
- package/src/lib/dictation-recorder.native.ts +90 -0
- package/src/lib/dictation-recorder.ts +131 -0
- package/src/lib/dictation-stream.ts +238 -0
- package/src/lib/dictation.ts +216 -0
- package/src/lib/document-picker.ts +31 -0
- package/src/lib/domain.ts +12 -0
- package/src/lib/flights.ts +33 -0
- package/src/lib/focus-return.ts +66 -0
- package/src/lib/greeting.ts +15 -0
- package/src/lib/image-data-url.ts +35 -0
- package/src/lib/keyboard.native.tsx +25 -0
- package/src/lib/keyboard.tsx +55 -0
- package/src/lib/labels-es.ts +113 -0
- package/src/lib/labels.tsx +207 -0
- package/src/lib/origins.ts +28 -0
- package/src/lib/participants.ts +97 -0
- package/src/lib/pcm.ts +57 -0
- package/src/lib/power-level-options.ts +66 -0
- package/src/lib/questions.ts +92 -0
- package/src/lib/speech-language.ts +20 -0
- package/src/lib/speech-messages.ts +54 -0
- package/src/lib/speech-synthesis.ts +156 -0
- package/src/lib/suggestions.ts +53 -0
- package/src/lib/task-labels.ts +35 -0
- package/src/lib/text-input.ts +10 -0
- package/src/lib/tool-call-status.ts +28 -0
- package/src/lib/tool-icons.ts +36 -0
- package/src/lib/tool-registry.ts +71 -0
- package/src/lib/tool-renderers.tsx +32 -0
- package/src/lib/turn-state.ts +15 -0
- package/src/lib/utils.ts +35 -0
- package/src/lib/voice-audio-engine-types.ts +59 -0
- package/src/lib/voice-audio-engine.native.ts +232 -0
- package/src/lib/voice-audio-engine.ts +206 -0
- package/src/lib/voice-call-request.ts +49 -0
- package/src/lib/voice-call.ts +627 -0
- package/src/lib/voice-controls-labels.ts +31 -0
- package/src/lib/voice-levels.ts +64 -0
- package/src/lib/voice-protocol.ts +328 -0
- package/src/lib/voice-worklets.ts +19 -0
- package/src/lib/work-log.ts +370 -0
- package/src/metro/chart-importers.json +18 -0
- package/src/metro/granular-charts.js +3 -0
- package/src/metro/index.cjs +227 -0
- package/src/metro/index.d.cts +5 -0
- package/src/runtime/agents.ts +151 -0
- package/src/runtime/api.ts +144 -0
- package/src/runtime/app-assertion.ts +51 -0
- package/src/runtime/attachment-utils.ts +97 -0
- package/src/runtime/chat-turn-control.ts +74 -0
- package/src/runtime/composer-draft-store.ts +270 -0
- package/src/runtime/config.tsx +222 -0
- package/src/runtime/conversation-dates.ts +31 -0
- package/src/runtime/conversation-store.ts +49 -0
- package/src/runtime/conversations.ts +633 -0
- package/src/runtime/error-utils.ts +144 -0
- package/src/runtime/host-tools.ts +290 -0
- package/src/runtime/index.ts +137 -0
- package/src/runtime/message-history.ts +124 -0
- package/src/runtime/message-reactions.ts +214 -0
- package/src/runtime/model.ts +39 -0
- package/src/runtime/oxy-files.ts +37 -0
- package/src/runtime/power-levels.ts +66 -0
- package/src/runtime/query-keys.ts +49 -0
- package/src/runtime/random-uuid.ts +25 -0
- package/src/runtime/reaction-cache.ts +45 -0
- package/src/runtime/room-events.ts +333 -0
- package/src/runtime/routes.ts +81 -0
- package/src/runtime/sharing.ts +217 -0
- package/src/runtime/sse-frame-reader.ts +88 -0
- package/src/runtime/stream-events.ts +154 -0
- package/src/runtime/stream-outcome.ts +21 -0
- package/src/runtime/thought-store.ts +103 -0
- package/src/runtime/thread/agent-activity.ts +261 -0
- package/src/runtime/thread/agent-exchange.ts +94 -0
- package/src/runtime/thread/automation-labels.ts +79 -0
- package/src/runtime/thread/conversation-export.ts +135 -0
- package/src/runtime/thread/message-days.ts +120 -0
- package/src/runtime/thread/message-processor.ts +93 -0
- package/src/runtime/thread/speaker-changes.ts +66 -0
- package/src/runtime/thread/task-utils.ts +11 -0
- package/src/runtime/thread/thought-utils.ts +750 -0
- package/src/runtime/thread/thread-history.ts +139 -0
- package/src/runtime/thread/timeline.ts +202 -0
- package/src/runtime/thread/title-tags.ts +8 -0
- package/src/runtime/thread/tool-cards.ts +387 -0
- package/src/runtime/turn-failure.ts +108 -0
- package/src/runtime/turn-preparation.ts +21 -0
- package/src/runtime/types.ts +172 -0
- package/src/runtime/usage-limit-error.ts +44 -0
- package/src/runtime/use-agent-activity.ts +80 -0
- package/src/runtime/use-conversation-stream.ts +1669 -0
- package/src/runtime/use-conversation-thread.ts +590 -0
- package/src/runtime/use-gemie-thread.ts +54 -0
- package/src/runtime/use-room-events.ts +75 -0
- package/src/runtime/use-start-conversation.ts +107 -0
- package/src/runtime/use-thread-history.ts +73 -0
- package/src/runtime/use-thread-search.ts +100 -0
- package/src/runtime/use-turn-edit.ts +99 -0
- package/src/text.ts +19 -0
- package/src/theme.ts +16 -0
- package/src/tools.ts +27 -0
- package/src/types.ts +161 -0
- package/src/voice-messages.ts +2 -0
- package/src/voice.ts +67 -0
- package/tsconfig.json +17 -0
- package/worklets/voice-processors.js +152 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { useOxy } from '@oxy.so/services/ui/client';
|
|
2
|
+
import { useQuery } from '@tanstack/react-query';
|
|
3
|
+
import { useGemieApi } from './api';
|
|
4
|
+
import { gemieQueryKeys } from './query-keys';
|
|
5
|
+
import { API_ROUTES } from './routes';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The agent a chat is opened on, as `GET /v1/agents/:id/profile` answers it
|
|
9
|
+
* (`docs/agent-embedding.md` §1). Alia herself has no profile: she is the lead when no agent is
|
|
10
|
+
* named.
|
|
11
|
+
*/
|
|
12
|
+
export interface GemieAgentProfile {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
handle?: string;
|
|
16
|
+
/** Its look, as Oxy stores a character (JSON); drawn through `readAgentCharacter`. */
|
|
17
|
+
character?: unknown;
|
|
18
|
+
color?: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
/** What the empty chat says; omitted, the chat's own greeting. */
|
|
21
|
+
greeting?: string;
|
|
22
|
+
/** The lines offered over the composer of an empty chat. */
|
|
23
|
+
starters: GemieAgentStarter[];
|
|
24
|
+
access?: 'private' | 'public';
|
|
25
|
+
/** Which of Alia's features this agent gates behind an app's own check. */
|
|
26
|
+
features: Array<{ key: string; gated: boolean }>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface GemieAgentStarter {
|
|
30
|
+
title: string;
|
|
31
|
+
prompt: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** One of Alia's features, for one agent and the person present (`GET /v1/agents/:id/features`). */
|
|
35
|
+
export interface GemieAgentFeature {
|
|
36
|
+
key: string;
|
|
37
|
+
state: 'available' | 'locked';
|
|
38
|
+
/** How many uses are left, when the publishing app counts them. */
|
|
39
|
+
remaining?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The feature keys the chat itself reads: the attach menu's two rows. */
|
|
43
|
+
export const GEMIE_FEATURES = {
|
|
44
|
+
documents: 'attachments.documents',
|
|
45
|
+
images: 'attachments.images',
|
|
46
|
+
} as const;
|
|
47
|
+
|
|
48
|
+
const FIVE_MINUTES = 1000 * 60 * 5;
|
|
49
|
+
|
|
50
|
+
/** A string, or nothing: the profile is read field by field rather than cast. */
|
|
51
|
+
const text = (value: unknown): string | undefined =>
|
|
52
|
+
typeof value === 'string' && value !== '' ? value : undefined;
|
|
53
|
+
|
|
54
|
+
/** The profile the server sent, kept only where it has the shape the contract names. */
|
|
55
|
+
export function readAgentProfile(value: unknown): GemieAgentProfile | null {
|
|
56
|
+
if (value === null || typeof value !== 'object') return null;
|
|
57
|
+
const raw = value as Record<string, unknown>;
|
|
58
|
+
const id = text(raw.id);
|
|
59
|
+
const name = text(raw.name);
|
|
60
|
+
if (id === undefined || name === undefined) return null;
|
|
61
|
+
const starters = Array.isArray(raw.starters)
|
|
62
|
+
? raw.starters.flatMap((starter): GemieAgentStarter[] => {
|
|
63
|
+
if (starter === null || typeof starter !== 'object') return [];
|
|
64
|
+
const { title, prompt } = starter as Record<string, unknown>;
|
|
65
|
+
const line = text(prompt);
|
|
66
|
+
return line === undefined ? [] : [{ title: text(title) ?? line, prompt: line }];
|
|
67
|
+
})
|
|
68
|
+
: [];
|
|
69
|
+
const features = Array.isArray(raw.features)
|
|
70
|
+
? raw.features.flatMap((feature): Array<{ key: string; gated: boolean }> => {
|
|
71
|
+
if (feature === null || typeof feature !== 'object') return [];
|
|
72
|
+
const { key, gated } = feature as Record<string, unknown>;
|
|
73
|
+
return typeof key === 'string' ? [{ key, gated: gated === true }] : [];
|
|
74
|
+
})
|
|
75
|
+
: [];
|
|
76
|
+
return {
|
|
77
|
+
id,
|
|
78
|
+
name,
|
|
79
|
+
handle: text(raw.handle),
|
|
80
|
+
character: raw.character ?? undefined,
|
|
81
|
+
color: text(raw.color),
|
|
82
|
+
description: text(raw.description),
|
|
83
|
+
greeting: text(raw.greeting),
|
|
84
|
+
starters,
|
|
85
|
+
access: raw.access === 'public' || raw.access === 'private' ? raw.access : undefined,
|
|
86
|
+
features,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The feature states the server sent; an entry of any other shape is not a state. */
|
|
91
|
+
export function readAgentFeatures(value: unknown): GemieAgentFeature[] {
|
|
92
|
+
const list =
|
|
93
|
+
value !== null && typeof value === 'object'
|
|
94
|
+
? (value as { features?: unknown }).features
|
|
95
|
+
: undefined;
|
|
96
|
+
if (!Array.isArray(list)) return [];
|
|
97
|
+
return list.flatMap((feature): GemieAgentFeature[] => {
|
|
98
|
+
if (feature === null || typeof feature !== 'object') return [];
|
|
99
|
+
const { key, state, remaining } = feature as Record<string, unknown>;
|
|
100
|
+
if (typeof key !== 'string' || (state !== 'available' && state !== 'locked')) return [];
|
|
101
|
+
return [{ key, state, ...(typeof remaining === 'number' ? { remaining } : {}) }];
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The profile of the agent `agentId`, or nothing for Alia (no id) and while it loads. */
|
|
106
|
+
export function useAgentProfile(agentId: string | undefined) {
|
|
107
|
+
const { isAuthenticated } = useOxy();
|
|
108
|
+
const api = useGemieApi();
|
|
109
|
+
return useQuery({
|
|
110
|
+
queryKey: gemieQueryKeys.agents.profile(agentId ?? ''),
|
|
111
|
+
queryFn: async () =>
|
|
112
|
+
readAgentProfile((await api.get<unknown>(API_ROUTES.agents.profile(agentId ?? ''))).data),
|
|
113
|
+
enabled: agentId !== undefined && isAuthenticated,
|
|
114
|
+
staleTime: FIVE_MINUTES,
|
|
115
|
+
retry: 1,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* What of Alia's features the agent `agentId` offers the person present. Alia (no id) gates
|
|
121
|
+
* nothing, so she has no answer to wait for; see `featureRows` for what the chat makes of it.
|
|
122
|
+
*/
|
|
123
|
+
export function useAgentFeatures(agentId: string | undefined) {
|
|
124
|
+
const { isAuthenticated } = useOxy();
|
|
125
|
+
const api = useGemieApi();
|
|
126
|
+
return useQuery({
|
|
127
|
+
queryKey: gemieQueryKeys.agents.features(agentId ?? ''),
|
|
128
|
+
queryFn: async () =>
|
|
129
|
+
readAgentFeatures((await api.get<unknown>(API_ROUTES.agents.features(agentId ?? ''))).data),
|
|
130
|
+
enabled: agentId !== undefined && isAuthenticated,
|
|
131
|
+
// A gate's state moves with the person's plan in another app: read it each time the chat opens.
|
|
132
|
+
staleTime: 0,
|
|
133
|
+
retry: 1,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** How an attachment feature is offered: attached, an upsell, or not at all. */
|
|
138
|
+
export type FeatureOffer = 'available' | 'locked' | 'absent';
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* What the attach menu offers for `key`. Alia's own chat (`features === undefined`) offers every
|
|
142
|
+
* attachment; an agent offers what its feature answer lists — `locked` is still offered, as the
|
|
143
|
+
* host's upsell — and nothing it does not list.
|
|
144
|
+
*/
|
|
145
|
+
export function featureOffer(
|
|
146
|
+
features: readonly GemieAgentFeature[] | undefined,
|
|
147
|
+
key: string,
|
|
148
|
+
): FeatureOffer {
|
|
149
|
+
if (features === undefined) return 'available';
|
|
150
|
+
return features.find((feature) => feature.key === key)?.state ?? 'absent';
|
|
151
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { useOxy } from '@oxy.so/services/ui/client';
|
|
2
|
+
import { useMemo } from 'react';
|
|
3
|
+
import {
|
|
4
|
+
type AppAssertionHeaders,
|
|
5
|
+
NO_APP_ASSERTION,
|
|
6
|
+
useAppAssertionHeaders,
|
|
7
|
+
} from './app-assertion';
|
|
8
|
+
import { useGemieRuntime } from './config';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A refusal or failure from the Gemies API, shaped so the helpers in
|
|
12
|
+
* `error-utils.ts` read it: `status`, and the parsed body under
|
|
13
|
+
* `response.data`.
|
|
14
|
+
*/
|
|
15
|
+
export class GemieApiError extends Error {
|
|
16
|
+
readonly status: number;
|
|
17
|
+
readonly response: { status: number; data: unknown };
|
|
18
|
+
|
|
19
|
+
constructor(status: number, data: unknown, message?: string) {
|
|
20
|
+
super(message ?? `Alia request failed with status ${status}.`);
|
|
21
|
+
this.name = 'GemieApiError';
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.response = { status, data };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface GemieApiResult<T> {
|
|
28
|
+
status: number;
|
|
29
|
+
data: T;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface GemieApiRequest {
|
|
33
|
+
params?: Record<string, string | number | undefined>;
|
|
34
|
+
body?: unknown;
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Alia's REST API for the signed-in person. Authentication, the preflight
|
|
40
|
+
* refresh and the single 401 replay belong to the linked Oxy client; this
|
|
41
|
+
* layer never reads or writes a bearer itself.
|
|
42
|
+
*/
|
|
43
|
+
export interface GemieApi {
|
|
44
|
+
get<T>(path: string, request?: GemieApiRequest): Promise<GemieApiResult<T>>;
|
|
45
|
+
post<T>(path: string, body?: unknown, request?: GemieApiRequest): Promise<GemieApiResult<T>>;
|
|
46
|
+
patch<T>(path: string, body?: unknown, request?: GemieApiRequest): Promise<GemieApiResult<T>>;
|
|
47
|
+
/** Replaces a resource whole, for the routes that take PUT (the memory profile's sections). */
|
|
48
|
+
put<T>(path: string, body?: unknown, request?: GemieApiRequest): Promise<GemieApiResult<T>>;
|
|
49
|
+
delete<T>(path: string, request?: GemieApiRequest): Promise<GemieApiResult<T>>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function withParams(path: string, params: GemieApiRequest['params']): string {
|
|
53
|
+
if (!params) return path;
|
|
54
|
+
const search = new URLSearchParams();
|
|
55
|
+
for (const [key, value] of Object.entries(params)) {
|
|
56
|
+
if (value !== undefined) search.append(key, String(value));
|
|
57
|
+
}
|
|
58
|
+
const query = search.toString();
|
|
59
|
+
return query === '' ? path : `${path}${path.includes('?') ? '&' : '?'}${query}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function readBody(response: Response): Promise<unknown> {
|
|
63
|
+
const text = await response.text().catch(() => '');
|
|
64
|
+
if (text === '') return undefined;
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(text);
|
|
67
|
+
} catch {
|
|
68
|
+
return text;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The structural slice of `OxyServices` the API layer needs. */
|
|
73
|
+
export interface LinkableOxy {
|
|
74
|
+
createLinkedClient(config: { baseURL: string }): {
|
|
75
|
+
client: {
|
|
76
|
+
requestAuthenticatedResponse(config: {
|
|
77
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
78
|
+
url: string;
|
|
79
|
+
body?: string;
|
|
80
|
+
headers?: Record<string, string>;
|
|
81
|
+
signal?: AbortSignal;
|
|
82
|
+
fetch?: typeof fetch;
|
|
83
|
+
}): Promise<Response>;
|
|
84
|
+
};
|
|
85
|
+
dispose(): void;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Build the API over an Oxy client for `apiUrl`. Exposed for tests and for non-React callers.
|
|
91
|
+
*
|
|
92
|
+
* @param appAssertionHeaders the host's `X-Oxy-App-Assertion` (`app-assertion.ts`), on every request
|
|
93
|
+
*/
|
|
94
|
+
export function createGemieApi(
|
|
95
|
+
oxyServices: LinkableOxy,
|
|
96
|
+
apiUrl: string,
|
|
97
|
+
appAssertionHeaders: AppAssertionHeaders = NO_APP_ASSERTION,
|
|
98
|
+
): GemieApi {
|
|
99
|
+
async function send<T>(
|
|
100
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
|
101
|
+
path: string,
|
|
102
|
+
request: GemieApiRequest = {},
|
|
103
|
+
): Promise<GemieApiResult<T>> {
|
|
104
|
+
const assertion = await appAssertionHeaders();
|
|
105
|
+
const linked = oxyServices.createLinkedClient({ baseURL: apiUrl });
|
|
106
|
+
try {
|
|
107
|
+
const headers = {
|
|
108
|
+
...assertion,
|
|
109
|
+
...(request.body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
110
|
+
};
|
|
111
|
+
const response = await linked.client.requestAuthenticatedResponse({
|
|
112
|
+
method,
|
|
113
|
+
url: withParams(path, request.params),
|
|
114
|
+
...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
|
|
115
|
+
...(Object.keys(headers).length === 0 ? {} : { headers }),
|
|
116
|
+
...(request.signal ? { signal: request.signal } : {}),
|
|
117
|
+
});
|
|
118
|
+
const data = await readBody(response);
|
|
119
|
+
if (!response.ok) throw new GemieApiError(response.status, data);
|
|
120
|
+
return { status: response.status, data: data as T };
|
|
121
|
+
} finally {
|
|
122
|
+
linked.dispose();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
get: (path, request) => send('GET', path, request),
|
|
128
|
+
post: (path, body, request) => send('POST', path, { ...request, body: body ?? {} }),
|
|
129
|
+
patch: (path, body, request) => send('PATCH', path, { ...request, body: body ?? {} }),
|
|
130
|
+
put: (path, body, request) => send('PUT', path, { ...request, body: body ?? {} }),
|
|
131
|
+
delete: (path, request) => send('DELETE', path, request),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Alia's REST API for the nearest runtime's `apiUrl`, as the signed-in person. */
|
|
136
|
+
export function useGemieApi(): GemieApi {
|
|
137
|
+
const { oxyServices } = useOxy();
|
|
138
|
+
const { apiUrl } = useGemieRuntime();
|
|
139
|
+
const appAssertionHeaders = useAppAssertionHeaders();
|
|
140
|
+
return useMemo(
|
|
141
|
+
() => createGemieApi(oxyServices as LinkableOxy, apiUrl, appAssertionHeaders),
|
|
142
|
+
[oxyServices, apiUrl, appAssertionHeaders],
|
|
143
|
+
);
|
|
144
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useAppAssertion } from '@oxy.so/services/ui/client';
|
|
2
|
+
import { useMemo } from 'react';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Which Oxy app this conversation is in, for Alia (Alia ADR 0021, Oxy ADR 0045).
|
|
6
|
+
*
|
|
7
|
+
* An Oxy app may confine its own agent to itself — Clarity's assistant opens
|
|
8
|
+
* only inside Clarity — and the official apps share one session that names no
|
|
9
|
+
* app, so Alia reads the app from the Oxy-signed assertion the host's
|
|
10
|
+
* `OxyProvider` obtains and keeps current. Every request the SDK makes to Alia
|
|
11
|
+
* carries it as `X-Oxy-App-Assertion` when there is one; without one (an app
|
|
12
|
+
* Oxy cannot recognise yet, a signed-out person) nothing is sent, and only a
|
|
13
|
+
* confined agent is affected.
|
|
14
|
+
*
|
|
15
|
+
* The SDK never builds, stores or inspects the assertion: it is the host's
|
|
16
|
+
* provider's, read at send time so it is never stale.
|
|
17
|
+
*/
|
|
18
|
+
export type AppAssertionHeaders = () => Promise<Record<string, string>>;
|
|
19
|
+
|
|
20
|
+
/** No app assertion: what a caller outside a React tree, or a test, passes. */
|
|
21
|
+
export const NO_APP_ASSERTION: AppAssertionHeaders = async () => ({});
|
|
22
|
+
|
|
23
|
+
/** The host's app assertion as request headers, `{}` when it has none or cannot get one. */
|
|
24
|
+
export function useAppAssertionHeaders(): AppAssertionHeaders {
|
|
25
|
+
const { getAppAssertionHeaders } = useAppAssertion();
|
|
26
|
+
return useMemo(
|
|
27
|
+
() => async () => {
|
|
28
|
+
try {
|
|
29
|
+
return await getAppAssertionHeaders();
|
|
30
|
+
} catch {
|
|
31
|
+
return {};
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
[getAppAssertionHeaders],
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The host's app assertion itself, for the voice socket, which cannot carry a header. */
|
|
39
|
+
export function useAppAssertionToken(): () => Promise<string | null> {
|
|
40
|
+
const { getAppAssertion } = useAppAssertion();
|
|
41
|
+
return useMemo(
|
|
42
|
+
() => async () => {
|
|
43
|
+
try {
|
|
44
|
+
return await getAppAssertion();
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
[getAppAssertion],
|
|
50
|
+
);
|
|
51
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { loadImageDataUrl } from '../lib/deferred/image-data-url';
|
|
2
|
+
import type { GemieAttachment } from '../types';
|
|
3
|
+
|
|
4
|
+
export type MessageContentPart =
|
|
5
|
+
| { type: 'text'; text: string }
|
|
6
|
+
| { type: 'image_url'; image_url: { url: string } }
|
|
7
|
+
| { type: 'file'; file: { file_id: string; filename: string; mime: string } };
|
|
8
|
+
|
|
9
|
+
export interface BuiltMessageContent {
|
|
10
|
+
content: string | MessageContentPart[];
|
|
11
|
+
/**
|
|
12
|
+
* Attachments the request does NOT carry, so the caller can say so.
|
|
13
|
+
*
|
|
14
|
+
* Never empty silently: everything here was visibly attached in the composer,
|
|
15
|
+
* and a file that appears attached and then is not sent is the failure #608
|
|
16
|
+
* §1.6 is about — a visible state that does not correspond to a real
|
|
17
|
+
* capability.
|
|
18
|
+
*/
|
|
19
|
+
dropped: DroppedAttachment[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DroppedAttachment {
|
|
23
|
+
name: string;
|
|
24
|
+
/**
|
|
25
|
+
* `unsupported` — the chat has no way to send a document (no upload was given).
|
|
26
|
+
* `unreadable` — an image whose bytes could not be read off the device, or a
|
|
27
|
+
* document that could not be uploaded.
|
|
28
|
+
*/
|
|
29
|
+
reason: 'unsupported' | 'unreadable';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Puts a document in the person's Oxy Files and answers its id. */
|
|
33
|
+
export type UploadDocument = (attachment: GemieAttachment) => Promise<string>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The request body for a turn that carries attachments, and an account of what
|
|
37
|
+
* it could not carry.
|
|
38
|
+
*
|
|
39
|
+
* A photo travels inline, as an `image_url` part with its `data:` URL. A
|
|
40
|
+
* document travels as a `file` part naming an Oxy Files id
|
|
41
|
+
* (`docs/agent-embedding.md` §5): it is uploaded to the person's Files first,
|
|
42
|
+
* with `upload`, and a chat given no `upload` cannot send documents and says so.
|
|
43
|
+
*/
|
|
44
|
+
export async function buildMessageContent(
|
|
45
|
+
text: string,
|
|
46
|
+
attachments: GemieAttachment[],
|
|
47
|
+
upload?: UploadDocument,
|
|
48
|
+
): Promise<BuiltMessageContent> {
|
|
49
|
+
const dropped: DroppedAttachment[] = [];
|
|
50
|
+
|
|
51
|
+
const usable = attachments.filter((att) => {
|
|
52
|
+
if (!att.uri) return false;
|
|
53
|
+
if (att.type !== 'image' && upload === undefined) {
|
|
54
|
+
dropped.push({ name: att.name, reason: 'unsupported' });
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
return true;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
if (usable.length === 0) return { content: text, dropped };
|
|
61
|
+
|
|
62
|
+
const parts: MessageContentPart[] = [{ type: 'text', text }];
|
|
63
|
+
|
|
64
|
+
// The readers need the platform's file access, loaded on the first attachment: on native a turn
|
|
65
|
+
// of plain text (and everything that imports this module) never touches it.
|
|
66
|
+
const { imageUriToDataUrl } = await loadImageDataUrl();
|
|
67
|
+
for (const att of usable) {
|
|
68
|
+
if (att.type !== 'image' && upload !== undefined) {
|
|
69
|
+
try {
|
|
70
|
+
const fileId = await upload(att);
|
|
71
|
+
parts.push({
|
|
72
|
+
type: 'file',
|
|
73
|
+
file: { file_id: fileId, filename: att.name, mime: att.mimeType },
|
|
74
|
+
});
|
|
75
|
+
} catch {
|
|
76
|
+
dropped.push({ name: att.name, reason: 'unreadable' });
|
|
77
|
+
}
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
parts.push({
|
|
82
|
+
type: 'image_url',
|
|
83
|
+
image_url: { url: await imageUriToDataUrl(att.uri, att.mimeType) },
|
|
84
|
+
});
|
|
85
|
+
} catch {
|
|
86
|
+
// Reported rather than skipped. A picture that did not arrive is worth
|
|
87
|
+
// a sentence; it used to be a `continue`.
|
|
88
|
+
dropped.push({ name: att.name, reason: 'unreadable' });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Every attachment failed, so the parts array is a text part and nothing
|
|
93
|
+
// else — which is just the text, said in a more expensive way.
|
|
94
|
+
if (parts.length === 1) return { content: text, dropped };
|
|
95
|
+
|
|
96
|
+
return { content: parts, dropped };
|
|
97
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { OxyServices } from '@oxy.so/core';
|
|
2
|
+
import { createRandomUuid } from './random-uuid';
|
|
3
|
+
import { awaitTurnPreparation } from './turn-preparation';
|
|
4
|
+
|
|
5
|
+
type LinkedClient = ReturnType<OxyServices['createLinkedClient']>;
|
|
6
|
+
|
|
7
|
+
/** One client turn, created before any asynchronous preparation or metadata. */
|
|
8
|
+
export function createChatTurnControl(
|
|
9
|
+
linked: LinkedClient,
|
|
10
|
+
headers: Promise<Record<string, string>>,
|
|
11
|
+
conversationId: string | undefined,
|
|
12
|
+
controller: AbortController,
|
|
13
|
+
) {
|
|
14
|
+
// A host can reject before Stop is pressed. Observe that rejection immediately;
|
|
15
|
+
// awaiting the original promise below still reports the failure to Stop.
|
|
16
|
+
void headers.catch(() => undefined);
|
|
17
|
+
const id = createRandomUuid();
|
|
18
|
+
let stopping: Promise<void> | undefined;
|
|
19
|
+
let ended = false;
|
|
20
|
+
const lifetime = new AbortController();
|
|
21
|
+
const epoch = linked.client.getSessionEpoch();
|
|
22
|
+
const current = () => linked.client.getSessionEpoch() === epoch;
|
|
23
|
+
const unsubscribe = linked.client.addTokenChangeListener(() => {
|
|
24
|
+
if (!current()) {
|
|
25
|
+
const reason = new Error('The conversation account changed');
|
|
26
|
+
lifetime.abort(reason);
|
|
27
|
+
controller.abort(reason);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
id,
|
|
32
|
+
/** Only a deliberate Stop invokes this. View teardown merely aborts its transport. */
|
|
33
|
+
stop(): Promise<void> {
|
|
34
|
+
if (stopping) return stopping;
|
|
35
|
+
if (ended || controller.signal.aborted) return Promise.resolve();
|
|
36
|
+
stopping = (async () => {
|
|
37
|
+
const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(10_000)]);
|
|
38
|
+
const assertionHeaders = await awaitTurnPreparation(headers, signal);
|
|
39
|
+
signal.throwIfAborted();
|
|
40
|
+
controller.signal.throwIfAborted();
|
|
41
|
+
if (!current()) throw new Error('The conversation account changed');
|
|
42
|
+
const response = await linked.client.requestAuthenticatedResponse({
|
|
43
|
+
url: `/v1/chat/turns/${id}/cancel`,
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { ...assertionHeaders, 'Content-Type': 'application/json' },
|
|
46
|
+
body: JSON.stringify({ ...(conversationId ? { conversationId } : {}) }),
|
|
47
|
+
// The cancelled chat signal must NOT cancel its own control request.
|
|
48
|
+
signal,
|
|
49
|
+
});
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
await response.body?.cancel();
|
|
52
|
+
throw new Error('Generation could not be stopped. Try again.');
|
|
53
|
+
}
|
|
54
|
+
await response.body?.cancel();
|
|
55
|
+
controller.abort();
|
|
56
|
+
})().catch((error) => {
|
|
57
|
+
stopping = undefined;
|
|
58
|
+
throw error;
|
|
59
|
+
});
|
|
60
|
+
return stopping;
|
|
61
|
+
},
|
|
62
|
+
async finish() {
|
|
63
|
+
ended = true;
|
|
64
|
+
// The stream can close before the replica answering Stop sends its acknowledgement.
|
|
65
|
+
await stopping?.catch(() => undefined);
|
|
66
|
+
lifetime.abort();
|
|
67
|
+
unsubscribe();
|
|
68
|
+
linked.dispose();
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Public lifecycle handle for hosts that render their own Stop control. */
|
|
74
|
+
export type GemieChatTurnControl = ReturnType<typeof createChatTurnControl>;
|