@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,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,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}$/;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation runtime: the data layer under the sheet, the screen and the Alia app.
|
|
3
|
+
*
|
|
4
|
+
* Layers, each depending only on the ones above it in this list:
|
|
5
|
+
*
|
|
6
|
+
* 1. transport — `api` (REST over the signed-in Oxy client), the turn's SSE stream
|
|
7
|
+
* 2. model and state — `types`, `query-keys`, the zustand stores, the cached conversation lists
|
|
8
|
+
* 3. hooks — `useConversations`…, `useConversationThread`
|
|
9
|
+
*
|
|
10
|
+
* Nothing here draws anything. It is also a leaf entry, `@gemies/sdk/runtime`, for a host that
|
|
11
|
+
* needs the data layer without the chat UI (a sidebar, a test).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export { GemieRuntimeProvider, useGemieRuntime } from './config';
|
|
15
|
+
export type {
|
|
16
|
+
GemieArtifact,
|
|
17
|
+
GemieRuntimeConfig,
|
|
18
|
+
GemieRuntimeHost,
|
|
19
|
+
GemieRuntimeProviderProps,
|
|
20
|
+
GemieTurnRequest,
|
|
21
|
+
GemieUsageFrame,
|
|
22
|
+
OfflineConversationStore,
|
|
23
|
+
SpeechPreferences,
|
|
24
|
+
ThoughtOpening,
|
|
25
|
+
} from './config';
|
|
26
|
+
export type { RoomEvent } from './room-events';
|
|
27
|
+
export type { MessageReactionUpdate } from './message-reactions';
|
|
28
|
+
export { GemieApiError, useGemieApi } from './api';
|
|
29
|
+
export {
|
|
30
|
+
GEMIE_FEATURES,
|
|
31
|
+
featureOffer,
|
|
32
|
+
readAgentFeatures,
|
|
33
|
+
readAgentProfile,
|
|
34
|
+
useAgentFeatures,
|
|
35
|
+
useAgentProfile,
|
|
36
|
+
} from './agents';
|
|
37
|
+
export type {
|
|
38
|
+
GemieAgentFeature,
|
|
39
|
+
GemieAgentProfile,
|
|
40
|
+
GemieAgentStarter,
|
|
41
|
+
FeatureOffer,
|
|
42
|
+
} from './agents';
|
|
43
|
+
export {
|
|
44
|
+
HOST_IMAGE_MEDIA_TYPES,
|
|
45
|
+
HOST_IMAGE_TEXT_MAX_CHARS,
|
|
46
|
+
HOST_OUTCOMES,
|
|
47
|
+
HOST_RESULT_MAX_CHARS,
|
|
48
|
+
HostOutcomeQueue,
|
|
49
|
+
hostImageResultProblem,
|
|
50
|
+
hostRequest,
|
|
51
|
+
} from './host-tools';
|
|
52
|
+
export type {
|
|
53
|
+
GemieHostAction,
|
|
54
|
+
GemieHostImageMediaType,
|
|
55
|
+
GemieHostImageResult,
|
|
56
|
+
GemieHostOutcome,
|
|
57
|
+
GemieHostOutcomeKind,
|
|
58
|
+
GemieHostToolDefinition,
|
|
59
|
+
GemieHostTools,
|
|
60
|
+
HostResultRecord as GemieHostResultRecord,
|
|
61
|
+
} from './host-tools';
|
|
62
|
+
export { FEATURE_ENTITLEMENT_REQUIRED, parseConsultEvent, parseHostAction } from './stream-events';
|
|
63
|
+
export type { ConsultAgent, ConsultEvent } from './stream-events';
|
|
64
|
+
export {
|
|
65
|
+
DEFAULT_SHARE_TTL_HOURS,
|
|
66
|
+
readSharedConversation,
|
|
67
|
+
SharedConversationGoneError,
|
|
68
|
+
sharedMessages,
|
|
69
|
+
useShareConversation,
|
|
70
|
+
useSharedConversation,
|
|
71
|
+
} from './sharing';
|
|
72
|
+
export { gemiesSharedConversationUrl } from '../lib/origins';
|
|
73
|
+
export type {
|
|
74
|
+
GemieConversationShare,
|
|
75
|
+
GemieSharedAgent,
|
|
76
|
+
GemieSharedConversationData,
|
|
77
|
+
GemieSharedMessage,
|
|
78
|
+
} from './sharing';
|
|
79
|
+
export { uploadToOxyFiles, useDocumentUpload } from './oxy-files';
|
|
80
|
+
export type { OxyFilesClient } from './oxy-files';
|
|
81
|
+
export type { GemieApi, GemieApiRequest, GemieApiResult } from './api';
|
|
82
|
+
export { gemieQueryKeys, type ConversationsFilter } from './query-keys';
|
|
83
|
+
export {
|
|
84
|
+
ConversationNotFoundError,
|
|
85
|
+
useClearConversation,
|
|
86
|
+
useConversation,
|
|
87
|
+
useConversations,
|
|
88
|
+
useCreateConversation,
|
|
89
|
+
useDeleteConversation,
|
|
90
|
+
usePrefetchConversation,
|
|
91
|
+
useRenameConversation,
|
|
92
|
+
useSaveConversation,
|
|
93
|
+
} from './conversations';
|
|
94
|
+
export { useConversationThread, mergeEditedContent } from './use-conversation-thread';
|
|
95
|
+
export type {
|
|
96
|
+
ConversationThread,
|
|
97
|
+
EditedContent,
|
|
98
|
+
UseConversationThreadOptions,
|
|
99
|
+
} from './use-conversation-thread';
|
|
100
|
+
export type { SendOutcome } from './use-conversation-stream';
|
|
101
|
+
export { useConversationStore } from './conversation-store';
|
|
102
|
+
export type { PendingInitialMessage } from './conversation-store';
|
|
103
|
+
export {
|
|
104
|
+
releaseAttachments,
|
|
105
|
+
useComposerDraft,
|
|
106
|
+
useComposerDraftStore,
|
|
107
|
+
useDraftAddress,
|
|
108
|
+
} from './composer-draft-store';
|
|
109
|
+
export type {
|
|
110
|
+
ComposerDraft,
|
|
111
|
+
DraftAddress,
|
|
112
|
+
DraftTarget,
|
|
113
|
+
} from './composer-draft-store';
|
|
114
|
+
export { useAgentActivity } from './use-agent-activity';
|
|
115
|
+
export type { UseAgentActivityResult } from './use-agent-activity';
|
|
116
|
+
export { useThoughtStore } from './thought-store';
|
|
117
|
+
export type {
|
|
118
|
+
ThoughtScope,
|
|
119
|
+
ThoughtScopeStatus,
|
|
120
|
+
ThoughtSelection,
|
|
121
|
+
ThoughtTab,
|
|
122
|
+
} from './thought-store';
|
|
123
|
+
export { useThreadHistory } from './use-thread-history';
|
|
124
|
+
export { useThreadSearch, useThreadWindow } from './use-thread-search';
|
|
125
|
+
export { useGemieThread } from './use-gemie-thread';
|
|
126
|
+
export type { GemieThreadInfo } from './use-gemie-thread';
|
|
127
|
+
export type { GemieThreadAddress } from './routes';
|
|
128
|
+
export { useStartConversation } from './use-start-conversation';
|
|
129
|
+
export type { StartConversationOptions } from './use-start-conversation';
|
|
130
|
+
export { useTurnEdit } from './use-turn-edit';
|
|
131
|
+
export { buildMessageContent } from './attachment-utils';
|
|
132
|
+
export type { BuiltMessageContent, DroppedAttachment, UploadDocument } from './attachment-utils';
|
|
133
|
+
|
|
134
|
+
// The conversation as data (also the leaf entry `@gemies/sdk/model`).
|
|
135
|
+
export * from './model';
|
|
136
|
+
|
|
137
|
+
export { createChatTurnControl, type GemieChatTurnControl } from './chat-turn-control';
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { Message, ToolInvocation } from './types';
|
|
2
|
+
|
|
3
|
+
/** Message shape accepted by the chat-completions endpoint. */
|
|
4
|
+
export interface OutboundMessage {
|
|
5
|
+
/**
|
|
6
|
+
* The id this screen draws the message under. The server stores the turn
|
|
7
|
+
* with the ids it was sent (`packages/api/src/lib/conversation-saver.ts`), so
|
|
8
|
+
* a vote or a read-aloud addressed by `Message.id` finds the row without a
|
|
9
|
+
* reload in between.
|
|
10
|
+
*/
|
|
11
|
+
id: string;
|
|
12
|
+
role: string;
|
|
13
|
+
content: Message['content'];
|
|
14
|
+
toolInvocations?: Array<{
|
|
15
|
+
toolCallId: string;
|
|
16
|
+
toolName: string;
|
|
17
|
+
state: ToolInvocation['state'];
|
|
18
|
+
args?: Record<string, unknown>;
|
|
19
|
+
result?: unknown;
|
|
20
|
+
}>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function formatOutboundMessage(message: Message): OutboundMessage {
|
|
24
|
+
const outbound: OutboundMessage = {
|
|
25
|
+
id: message.id,
|
|
26
|
+
role: message.role,
|
|
27
|
+
content: message.content,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
if (message.role === 'assistant' && message.toolInvocations?.length) {
|
|
31
|
+
outbound.toolInvocations = message.toolInvocations.map((invocation) => ({
|
|
32
|
+
toolCallId: invocation.toolCallId,
|
|
33
|
+
toolName: invocation.toolName,
|
|
34
|
+
state: invocation.state,
|
|
35
|
+
args: invocation.args,
|
|
36
|
+
result: invocation.result,
|
|
37
|
+
}));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return outbound;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The id of the `index`-th consulted agent's answer (`alia.agent_start`, in the
|
|
45
|
+
* order the consultations started) in the turn whose reply is `assistantMessageId`.
|
|
46
|
+
*
|
|
47
|
+
* Derived, not received: the frames name a consultation (`consultId`), not a
|
|
48
|
+
* message. The server stores the same answer under the same derivation
|
|
49
|
+
* (`conversation-saver.ts` `agentMessageId`).
|
|
50
|
+
*/
|
|
51
|
+
export function agentMessageId(assistantMessageId: string, index: number): string {
|
|
52
|
+
return `${agentMessagePrefix(assistantMessageId)}${index}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Whether `id` is one of the agent answers {@link agentMessageId} names for this reply. */
|
|
56
|
+
export function isAgentMessageOf(id: string, assistantMessageId: string): boolean {
|
|
57
|
+
return id.startsWith(agentMessagePrefix(assistantMessageId));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function agentMessagePrefix(assistantMessageId: string): string {
|
|
61
|
+
return `${assistantMessageId}-agent-`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Build a turn from the history captured before optimistic UI updates. */
|
|
65
|
+
export function buildOutboundMessages(
|
|
66
|
+
historySnapshot: readonly Message[],
|
|
67
|
+
userMessage: Message,
|
|
68
|
+
): OutboundMessage[] {
|
|
69
|
+
return [...historySnapshot, userMessage].map(formatOutboundMessage);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sameContent(a: Message['content'], b: Message['content']): boolean {
|
|
73
|
+
if (a === b) return true;
|
|
74
|
+
try {
|
|
75
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function isEmptyAssistantPlaceholder(message: Message | undefined): boolean {
|
|
82
|
+
return (
|
|
83
|
+
message?.role === 'assistant' &&
|
|
84
|
+
message.content === '' &&
|
|
85
|
+
!message.thinking &&
|
|
86
|
+
!message.toolInvocations?.length &&
|
|
87
|
+
!message.agentInfo
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Hide histories written by the former optimistic-send race.
|
|
93
|
+
*
|
|
94
|
+
* That race persisted one exact sequence: user, empty assistant placeholder,
|
|
95
|
+
* the same user again. Only that signature is collapsed; intentional repeated
|
|
96
|
+
* prompts separated by a real assistant response remain untouched. The next
|
|
97
|
+
* successful turn rewrites divergent server history from this clean view.
|
|
98
|
+
*/
|
|
99
|
+
export function normalizeConversationMessages(messages: readonly Message[]): Message[] {
|
|
100
|
+
const normalized: Message[] = [];
|
|
101
|
+
// A host's client context travels as a system message and is never part of the thread.
|
|
102
|
+
messages = messages.filter((message) => message.role !== 'system');
|
|
103
|
+
|
|
104
|
+
for (let index = 0; index < messages.length; index += 1) {
|
|
105
|
+
const current = messages[index] as Message;
|
|
106
|
+
const placeholder = messages[index + 1];
|
|
107
|
+
const duplicate = messages[index + 2];
|
|
108
|
+
|
|
109
|
+
if (
|
|
110
|
+
current.role === 'user' &&
|
|
111
|
+
isEmptyAssistantPlaceholder(placeholder) &&
|
|
112
|
+
duplicate?.role === 'user' &&
|
|
113
|
+
sameContent(current.content, duplicate.content)
|
|
114
|
+
) {
|
|
115
|
+
normalized.push(current);
|
|
116
|
+
index += 2;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
normalized.push(current);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return normalized;
|
|
124
|
+
}
|