@gemies/sdk 10.1.0 → 10.3.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.
@@ -39,7 +39,7 @@ import {
39
39
  } from './approvals';
40
40
  import { type GemieHostTools, HostOutcomeQueue, hostRequest } from './host-tools';
41
41
  import { API_ROUTES } from './routes';
42
- import { createSseFrameReader } from './sse-frame-reader';
42
+ import { createResumableFrameSource, TURN_RESET_EVENT } from './resumable-stream';
43
43
  import {
44
44
  type MemberTurnEvent,
45
45
  lockedFeatureOf,
@@ -726,7 +726,7 @@ export function useConversationStream({
726
726
  return;
727
727
  }
728
728
  if (isGroupTurn && event.errorCode === 'agent_declined') {
729
- // A superseded room reply was never stored. Drop its provisional text
729
+ // A declined room reply was never stored. Drop its provisional text
730
730
  // across both transports instead of presenting it as a failed saved reply.
731
731
  roomRef.current.ended.add(event.consultId);
732
732
  roomRef.current.discarded.add(event.consultId);
@@ -949,34 +949,47 @@ export function useConversationStream({
949
949
  // The server has the outcomes this request carried: they are its calls' results now.
950
950
  hostOutcomesRef.current.delivered(outcomes);
951
951
 
952
- const reader = response.body.getReader();
953
- const decoder = new TextDecoder();
954
952
  /**
955
- * Frame reassembly lives in `sse-frame-reader.ts`.
953
+ * Frame reassembly lives in `sse-frame-reader.ts` and the seam across a dropped connection
954
+ * in `resumable-stream.ts`, which reads the turn's frames, drops the ones already applied
955
+ * by their number, and resumes the turn from its last frame when the connection ends
956
+ * before the server said the turn was over.
956
957
  *
957
- * It used to be loose variables here, and that is how the bug happened:
958
- * `buffer` was declared outside the read loop and survived a chunk
959
- * boundary, but the current event name was declared INSIDE it and reset
960
- * on every `reader.read()`. A frame is `event: X\ndata: {…}\n\n`, so any
961
- * frame split between those two lines lost its name, fell through to the
962
- * OpenAI-shaped branch below, found no `choices[0]`, and was dropped in
963
- * silence — most often for the largest payloads, which are the ones that
964
- * do not fit in one read: `alia.title`, `alia.tool_result`,
965
- * `alia.plan_preview`, `alia.agent_start`, `alia.host_action`.
966
- *
967
- * Two pieces of state that must both outlive a chunk are fields of one
968
- * object now, and its test feeds a stream split at every byte offset —
969
- * which is not something a test of this hook could do.
958
+ * Frame reassembly used to be loose variables here, and that is how the bug happened:
959
+ * `buffer` was declared outside the read loop and survived a chunk boundary, but the
960
+ * current event name was declared INSIDE it and reset on every `reader.read()`. A frame is
961
+ * `event: X\ndata: {…}\n\n`, so any frame split between those two lines lost its name,
962
+ * fell through to the OpenAI-shaped branch below, found no `choices[0]`, and was dropped in
963
+ * silence — most often for the largest payloads, which are the ones that do not fit in one
964
+ * read: `alia.title`, `alia.tool_result`, `alia.plan_preview`, `alia.agent_start`,
965
+ * `alia.host_action`. Its test feeds a stream split at every byte offset.
970
966
  */
971
- const sse = createSseFrameReader();
967
+ const turnId = turnControl.id;
968
+ const client = linked.client;
969
+ const source = createResumableFrameSource({
970
+ response,
971
+ signal: controller.signal,
972
+ reconnect: async (cursor, signal) =>
973
+ client.requestAuthenticatedResponse({
974
+ method: 'GET',
975
+ url: API_ROUTES.chatTurnStream(turnId, {
976
+ cursor,
977
+ ...(conversationId && { conversationId }),
978
+ assistantMessageId: assistantMessage.id,
979
+ }),
980
+ headers: { ...(await appAssertionHeaders()), Accept: 'text/event-stream' },
981
+ signal,
982
+ ...(streamFetch ? { fetch: streamFetch } : {}),
983
+ }),
984
+ });
972
985
  let lastOutputAt = 0;
973
986
  /** The server closed the turn: `[DONE]`, or a chunk that carries a finish reason. */
974
987
  let sawTerminal = false;
975
988
 
976
989
  while (true) {
977
- const { done, value } = await reader.read();
990
+ const next = await source.read();
978
991
 
979
- if (done) {
992
+ if (next.done) {
980
993
  // Flush any remaining batched content before checking
981
994
  flushPendingUpdates();
982
995
 
@@ -1000,11 +1013,7 @@ export function useConversationStream({
1000
1013
  break;
1001
1014
  }
1002
1015
 
1003
- // `{ stream: true }`: a multi-byte character split across two reads
1004
- // decodes to U+FFFD without it.
1005
- const chunk = decoder.decode(value, { stream: true });
1006
-
1007
- for (const frame of sse.push(chunk)) {
1016
+ for (const frame of next.frames) {
1008
1017
  const data = frame.data;
1009
1018
  const currentEventType = frame.event;
1010
1019
 
@@ -1036,6 +1045,26 @@ export function useConversationStream({
1036
1045
  setMessages((prev) => prev.filter((m) => m.id !== assistantMessage.id));
1037
1046
  continue;
1038
1047
  }
1048
+ case TURN_RESET_EVENT: {
1049
+ // A snapshot follows (`resumable-stream.ts`): it carries the words, so the
1050
+ // ones this connection built are emptied first and the snapshot applies once.
1051
+ dropPendingUpdates();
1052
+ outputEvidence.realOutputChars = 0;
1053
+ replyText = '';
1054
+ const clearsReasoning = parsed.reasoning === true;
1055
+ setMessages((prev) => {
1056
+ const last = prev[prev.length - 1];
1057
+ if (last?.role !== 'assistant') return prev;
1058
+ const updated = [...prev];
1059
+ updated[updated.length - 1] = {
1060
+ ...last,
1061
+ content: '',
1062
+ ...(clearsReasoning ? { thinking: '' } : {}),
1063
+ };
1064
+ return updated;
1065
+ });
1066
+ continue;
1067
+ }
1039
1068
  case 'alia.reasoning': {
1040
1069
  const content = parsed.content;
1041
1070
  if (content) {
@@ -1213,6 +1242,10 @@ export function useConversationStream({
1213
1242
  }
1214
1243
  continue;
1215
1244
  }
1245
+ case 'alia.credits_fallback': {
1246
+ host.onCreditsFallback?.({ reason: 'credits', tools: 'paused' });
1247
+ continue;
1248
+ }
1216
1249
  case 'alia.agent_turn': {
1217
1250
  if (parsed.turnId) {
1218
1251
  const run = {
@@ -1239,7 +1272,7 @@ export function useConversationStream({
1239
1272
  flushPendingUpdates();
1240
1273
  settleAssistant('cancelled');
1241
1274
  abortThisTurn();
1242
- reader.cancel().catch(() => {});
1275
+ source.cancel();
1243
1276
  return 'aborted';
1244
1277
  }
1245
1278
  // An agent's feature gate refused the turn before anything was spent: the host
@@ -1248,7 +1281,7 @@ export function useConversationStream({
1248
1281
  if (lockedFeature !== null) {
1249
1282
  setIsLoading(false);
1250
1283
  abortThisTurn();
1251
- reader.cancel().catch(() => {});
1284
+ source.cancel();
1252
1285
  host.onFeatureLocked?.(lockedFeature);
1253
1286
  return settleError();
1254
1287
  }
@@ -1294,7 +1327,7 @@ export function useConversationStream({
1294
1327
  setError(new Error(msg));
1295
1328
  setIsLoading(false);
1296
1329
  abortThisTurn();
1297
- reader.cancel().catch(() => {});
1330
+ source.cancel();
1298
1331
  // A turn that failed after it started carries a run reference:
1299
1332
  // its card says code and reference, never the server's English
1300
1333
  // prose. A refusal without one (a gate, a bad request) keeps its
@@ -1469,7 +1502,7 @@ export function useConversationStream({
1469
1502
  abortThisTurn();
1470
1503
 
1471
1504
  // Break out of the streaming loop
1472
- reader.cancel().catch(() => {});
1505
+ source.cancel();
1473
1506
  return keepFailedTurn(true, errMsg);
1474
1507
  }
1475
1508
  } catch (frameError: unknown) {