@gemies/sdk 10.2.0 → 10.4.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.
@@ -125,11 +125,23 @@ export const COPY_EN: Readonly<Record<string, CopyEntry>> = {
125
125
  'chat.actionApproval.status.expired': 'Expired',
126
126
  'chat.actionApproval.sent': 'Sent',
127
127
  'chat.actionApproval.decisionFailed': 'Your decision couldn’t be saved. Try again.',
128
- 'chat.approval.allow': 'Allow',
129
- 'chat.approval.deny': 'Deny',
130
- 'chat.approval.resolved.allow': '%{tool}: allowed',
131
- 'chat.approval.resolved.deny': '%{tool}: denied',
128
+ 'chat.approval.bar.more': '%{count} more waiting',
129
+ 'chat.approval.bar.replyHint': 'Reply below to decline and tell %{agent} why.',
130
+ 'chat.approval.bar.title': '%{agent} is waiting to run %{tool}',
131
+ 'chat.approval.grant': 'Allowed for this session — %{tool}',
132
+ 'chat.approval.option.allow': 'Approve',
133
+ 'chat.approval.option.allow_session': 'Always allow this session',
134
+ 'chat.approval.option.cancel': 'Stop',
135
+ 'chat.approval.option.deny': 'Decline',
136
+ 'chat.approval.replyPlaceholder': 'Decline and tell %{agent} why…',
137
+ 'chat.approval.resolved.allow': '%{tool}: approved',
138
+ 'chat.approval.resolved.allow_session': '%{tool}: allowed for this session',
139
+ 'chat.approval.resolved.auto': '%{tool}: allowed, as you did for this session',
140
+ 'chat.approval.resolved.cancel': '%{tool}: stopped',
141
+ 'chat.approval.resolved.deny': '%{tool}: declined',
142
+ 'chat.approval.resolved.ended': '%{tool}: closed with the turn',
132
143
  'chat.approval.resolved.expired': '%{tool}: timed out',
144
+ 'chat.approval.revoke': 'Revoke',
133
145
  'chat.approval.sendFailed': "Your answer couldn't be sent. Try again.",
134
146
  'chat.approval.title': '%{agent} wants to run %{tool}',
135
147
  'chat.newConversationAccept': 'Start a new one',
@@ -124,11 +124,23 @@ export const COPY_ES: Readonly<Record<string, CopyEntry>> = {
124
124
  'chat.actionApproval.status.expired': 'Caducado',
125
125
  'chat.actionApproval.sent': 'Enviado',
126
126
  'chat.actionApproval.decisionFailed': 'Tu decisión no se pudo guardar. Inténtalo de nuevo.',
127
- 'chat.approval.allow': 'Permitir',
128
- 'chat.approval.deny': 'Denegar',
129
- 'chat.approval.resolved.allow': '%{tool}: permitido',
130
- 'chat.approval.resolved.deny': '%{tool}: denegado',
127
+ 'chat.approval.bar.more': '%{count} más esperando',
128
+ 'chat.approval.bar.replyHint': 'Responde abajo para rechazar y decirle a %{agent} por qué.',
129
+ 'chat.approval.bar.title': '%{agent} espera para ejecutar %{tool}',
130
+ 'chat.approval.grant': 'Permitido en esta sesión — %{tool}',
131
+ 'chat.approval.option.allow': 'Aprobar',
132
+ 'chat.approval.option.allow_session': 'Permitir siempre en esta sesión',
133
+ 'chat.approval.option.cancel': 'Detener',
134
+ 'chat.approval.option.deny': 'Rechazar',
135
+ 'chat.approval.replyPlaceholder': 'Rechaza y dile a %{agent} por qué…',
136
+ 'chat.approval.resolved.allow': '%{tool}: aprobado',
137
+ 'chat.approval.resolved.allow_session': '%{tool}: permitido en esta sesión',
138
+ 'chat.approval.resolved.auto': '%{tool}: permitido, como indicaste para esta sesión',
139
+ 'chat.approval.resolved.cancel': '%{tool}: detenido',
140
+ 'chat.approval.resolved.deny': '%{tool}: rechazado',
141
+ 'chat.approval.resolved.ended': '%{tool}: cerrado con el turno',
131
142
  'chat.approval.resolved.expired': '%{tool}: sin respuesta a tiempo',
143
+ 'chat.approval.revoke': 'Revocar',
132
144
  'chat.approval.sendFailed': 'No se pudo enviar tu respuesta. Inténtalo de nuevo.',
133
145
  'chat.approval.title': '%{agent} quiere ejecutar %{tool}',
134
146
  'chat.newConversationAccept': 'Empezar una nueva',
@@ -4,16 +4,45 @@
4
4
  * During a turn with an external agent (Claude Code on the person's computer), the CLI may stop and
5
5
  * ask whether it can run something there. The turn waits; the stream carries two named events:
6
6
  *
7
- * `alia.cli_permission_request` the CLI asks: which tool, on what.
8
- * `alia.cli_permission_resolved` the answer was given, or the time ran out.
7
+ * `alia.cli_permission_request` the CLI asks: which tool, on what, and the answers it offers.
8
+ * `alia.cli_permission_resolved` the answer was given, or the time ran out, or the turn ended.
9
9
  *
10
10
  * This is the third-party CLI's prompt to the person who runs it, on their own machine. It is not
11
11
  * an Oxy grant: nothing here reaches Oxy, and the SDK does not know the endpoint that carries the
12
12
  * answer — the host does (`GemieRuntimeHost.onApprovalDecision`).
13
13
  */
14
14
 
15
- export type ApprovalDecision = 'allow' | 'deny';
16
- export type ApprovalOutcome = ApprovalDecision | 'expired';
15
+ /**
16
+ * What the person answers with:
17
+ *
18
+ * `allow` this once.
19
+ * `allow_session` this tool on this target for the rest of the conversation's session.
20
+ * `deny` no; with the words the agent is told, when there are any.
21
+ * `cancel` no, and stop the turn.
22
+ */
23
+ export type ApprovalDecision = 'allow' | 'allow_session' | 'deny' | 'cancel';
24
+
25
+ /** How a question ended: an answer, a timeout, or the turn going on (or ending) without one. */
26
+ export type ApprovalOutcome = ApprovalDecision | 'expired' | 'ended';
27
+
28
+ /**
29
+ * One way to answer. `id` and `label` are the agent's own when it offered the option: the label is
30
+ * shown as given and the id goes back as given. A built-in option has no `label`; the thread names
31
+ * it in the person's language.
32
+ */
33
+ export interface ApprovalOption {
34
+ readonly id: string;
35
+ readonly kind: ApprovalDecision;
36
+ readonly label?: string;
37
+ }
38
+
39
+ /** What a host's `onApprovalDecision` carries beside the decision. */
40
+ export interface ApprovalDetails {
41
+ /** The agent's option the person picked; absent for a built-in answer. */
42
+ readonly optionId?: string;
43
+ /** Words for the agent, with a denial. */
44
+ readonly feedback?: string;
45
+ }
17
46
 
18
47
  export interface ApprovalRequest {
19
48
  readonly requestId: string;
@@ -24,16 +53,58 @@ export interface ApprovalRequest {
24
53
  readonly summary?: string;
25
54
  /** ISO time after which the CLI is told no. */
26
55
  readonly expiresAt: string;
56
+ /** What can be answered. Always at least one way to say no. */
57
+ readonly options: readonly ApprovalOption[];
27
58
  }
28
59
 
29
60
  /** A request and where it stands: waiting for the person, or how it ended. */
30
61
  export interface ApprovalEntry extends ApprovalRequest {
31
62
  readonly outcome: 'pending' | ApprovalOutcome;
63
+ /** The person did not answer: their earlier "allow for this session" did. */
64
+ readonly auto?: boolean;
65
+ /** What the person told the agent with a denial, kept to show beside the answer. */
66
+ readonly feedback?: string;
32
67
  }
33
68
 
34
69
  const text = (value: unknown, max: number): string | undefined =>
35
70
  typeof value === 'string' && value !== '' ? value.slice(0, max) : undefined;
36
71
 
72
+ const DECISIONS: readonly ApprovalDecision[] = ['allow', 'allow_session', 'deny', 'cancel'];
73
+ const isDecision = (value: unknown): value is ApprovalDecision =>
74
+ typeof value === 'string' && (DECISIONS as readonly string[]).includes(value);
75
+
76
+ /** What a server that predates the options offers: a yes and a no. */
77
+ export const DEFAULT_APPROVAL_OPTIONS: readonly ApprovalOption[] = [
78
+ { id: 'allow', kind: 'allow' },
79
+ { id: 'deny', kind: 'deny' },
80
+ ];
81
+
82
+ /**
83
+ * The options in a request frame, as given. Ids and labels are the agent's: they are not rewritten,
84
+ * only bounded. An option without a usable id or kind is dropped; a request that is left with no
85
+ * way to say no gets one, so a card never traps the person.
86
+ */
87
+ function parseOptions(raw: unknown): readonly ApprovalOption[] {
88
+ if (!Array.isArray(raw)) return DEFAULT_APPROVAL_OPTIONS;
89
+ const options: ApprovalOption[] = [];
90
+ for (const item of raw.slice(0, 8)) {
91
+ if (item === null || typeof item !== 'object') continue;
92
+ const { id, kind, label } = item as Record<string, unknown>;
93
+ if (typeof id !== 'string' || id === '' || id.length > 80 || !isDecision(kind)) continue;
94
+ if (options.some((o) => o.id === id)) continue;
95
+ const shown = text(label, 80)?.trim();
96
+ options.push({ id, kind, ...(shown ? { label: shown } : {}) });
97
+ }
98
+ if (options.length === 0) return DEFAULT_APPROVAL_OPTIONS;
99
+ if (!options.some((o) => o.kind === 'deny' || o.kind === 'cancel')) {
100
+ options.push({
101
+ id: options.some((o) => o.id === 'deny') ? 'gemies:deny' : 'deny',
102
+ kind: 'deny',
103
+ });
104
+ }
105
+ return options;
106
+ }
107
+
37
108
  /** The request in an `alia.cli_permission_request` frame, or `null` when the frame is not one. */
38
109
  export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
39
110
  if (data === null || typeof data !== 'object') return null;
@@ -46,20 +117,27 @@ export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
46
117
  return null;
47
118
  }
48
119
  const summary = text(d.summary, 200);
49
- return { requestId, agentId, tool, ...(summary ? { summary } : {}), expiresAt };
120
+ return {
121
+ requestId,
122
+ agentId,
123
+ tool,
124
+ ...(summary ? { summary } : {}),
125
+ expiresAt,
126
+ options: parseOptions(d.options),
127
+ };
50
128
  }
51
129
 
52
130
  /** The answer in an `alia.cli_permission_resolved` frame, or `null` when the frame is not one. */
53
131
  export function parseApprovalResolved(
54
132
  data: unknown,
55
- ): { requestId: string; outcome: ApprovalOutcome } | null {
133
+ ): { requestId: string; outcome: ApprovalOutcome; auto: boolean } | null {
56
134
  if (data === null || typeof data !== 'object') return null;
57
135
  const d = data as Record<string, unknown>;
58
136
  const requestId = text(d.requestId, 100);
59
137
  if (!requestId) return null;
60
138
  const decision = d.decision;
61
- if (decision !== 'allow' && decision !== 'deny' && decision !== 'expired') return null;
62
- return { requestId, outcome: decision };
139
+ if (!isDecision(decision) && decision !== 'expired' && decision !== 'ended') return null;
140
+ return { requestId, outcome: decision, auto: d.auto === true };
63
141
  }
64
142
 
65
143
  /** A request arrived: waiting, once. A repeat of one already here changes nothing. */
@@ -76,12 +154,50 @@ export function withApprovalOutcome(
76
154
  list: readonly ApprovalEntry[],
77
155
  requestId: string,
78
156
  outcome: ApprovalOutcome,
157
+ extras: { readonly auto?: boolean; readonly feedback?: string } = {},
79
158
  ): ApprovalEntry[] {
80
159
  return list.map((entry) =>
81
- entry.requestId === requestId && entry.outcome === 'pending' ? { ...entry, outcome } : entry,
160
+ entry.requestId === requestId && entry.outcome === 'pending'
161
+ ? {
162
+ ...entry,
163
+ outcome,
164
+ ...(extras.auto ? { auto: true } : {}),
165
+ ...(extras.feedback ? { feedback: extras.feedback } : {}),
166
+ }
167
+ : entry,
82
168
  );
83
169
  }
84
170
 
171
+ /**
172
+ * Every question still waiting ends as `outcome`. For the moments the stream cannot say it itself
173
+ * — it broke, the person stopped the turn, the conversation changed — so no card stays pressable
174
+ * for a request nobody is waiting on.
175
+ */
176
+ export function settlePending(
177
+ list: readonly ApprovalEntry[],
178
+ outcome: ApprovalOutcome,
179
+ ): ApprovalEntry[] {
180
+ return list.some((entry) => entry.outcome === 'pending')
181
+ ? list.map((entry) => (entry.outcome === 'pending' ? { ...entry, outcome } : entry))
182
+ : [...list];
183
+ }
184
+
185
+ /** What the person is being asked now: the oldest question still waiting, or `undefined`. */
186
+ export const firstPending = (list: readonly ApprovalEntry[]): ApprovalEntry | undefined =>
187
+ list.find((entry) => entry.outcome === 'pending');
188
+
189
+ /**
190
+ * What the person allowed for the rest of a conversation's session: one tool on one path or URL,
191
+ * until `expiresAt` or until they take it back.
192
+ */
193
+ export interface ApprovalGrant {
194
+ readonly id: string;
195
+ readonly tool: string;
196
+ /** The path or URL allowed. */
197
+ readonly target: string;
198
+ readonly expiresAt: string;
199
+ }
200
+
85
201
  /**
86
202
  * What a host's `onApprovalDecision` rejects with when the question is no longer open (answered
87
203
  * elsewhere, or its time ran out): the card then reads "Timed out" instead of offering a retry.
@@ -93,7 +209,28 @@ export class ApprovalExpiredError extends Error {
93
209
  }
94
210
  }
95
211
 
96
- /** What a new turn keeps of the last one's approvals: the ones still waiting. */
97
- export function stillPending(list: readonly ApprovalEntry[]): ApprovalEntry[] {
98
- return list.filter((entry) => entry.outcome === 'pending');
99
- }
212
+ /**
213
+ * The options in the order they are laid out: no on the left, yes on the right, as a pair of
214
+ * buttons reads. Options of one kind keep the agent's own order.
215
+ */
216
+ const LAYOUT_RANK: Record<ApprovalDecision, number> = {
217
+ cancel: 0,
218
+ deny: 1,
219
+ allow_session: 2,
220
+ allow: 3,
221
+ };
222
+ export const orderedApprovalOptions = (options: readonly ApprovalOption[]): ApprovalOption[] =>
223
+ [...options].sort((a, b) => LAYOUT_RANK[a.kind] - LAYOUT_RANK[b.kind]);
224
+
225
+ /**
226
+ * What an option says. The agent's own label is shown exactly as it gave it; a built-in option is
227
+ * named by the person's language (`chat.approval.option.<kind>`).
228
+ */
229
+ export const approvalOptionLabel = (option: ApprovalOption, t: (key: string) => string): string =>
230
+ option.label ?? t(`chat.approval.option.${option.kind}`);
231
+
232
+ /** The option to send for a decision: the first the question offers of that kind. */
233
+ export const optionOfKind = (
234
+ entry: Pick<ApprovalEntry, 'options'>,
235
+ kind: ApprovalDecision,
236
+ ): ApprovalOption | undefined => entry.options.find((o) => o.kind === kind);
@@ -1,5 +1,6 @@
1
1
  import { createContext, type ReactNode, useContext, useMemo } from 'react';
2
2
  import { GEMIES_API_URL } from '../lib/origins';
3
+ import type { ApprovalDecision, ApprovalDetails, ApprovalGrant } from './approvals';
3
4
  import type { AgentRun } from './types';
4
5
  import { GemieRealtimeProvider } from '../realtime/react';
5
6
 
@@ -123,13 +124,24 @@ export interface GemieRuntimeHost {
123
124
  /**
124
125
  * The person answered a coding CLI that asked for permission to run something on their own
125
126
  * computer (`alia.cli_permission_request`, ADR 0043). The host carries the answer to Gemies; the
126
- * promise rejects when it could not be sent. Omitted, the request is shown with no way to answer.
127
+ * promise rejects when it could not be sent, and with `ApprovalExpiredError` when the question is
128
+ * no longer open. `details` carries the agent's own option when the person picked one, and the
129
+ * words that go to the agent with a denial. Omitted, the request is shown with no way to answer.
127
130
  */
128
- onApprovalDecision?: (
131
+ onApprovalDecision?(
129
132
  requestId: string,
130
133
  agentId: string,
131
- decision: 'allow' | 'deny',
132
- ) => Promise<void>;
134
+ decision: ApprovalDecision,
135
+ details?: ApprovalDetails,
136
+ ): Promise<void>;
137
+ /**
138
+ * What the person allowed for the rest of this conversation's session with a coding CLI
139
+ * ("always allow this session"). Read after such an answer, and shown in the thread with a way
140
+ * to take each one back. Omitted, nothing is listed.
141
+ */
142
+ listApprovalGrants?(agentId: string, conversationId: string): Promise<readonly ApprovalGrant[]>;
143
+ /** Takes one allowance back: the next such question is asked again. */
144
+ revokeApprovalGrant?(agentId: string, grantId: string): Promise<void>;
133
145
  /** The agent's row in the host's list, ahead of the server: your line, then her answer. */
134
146
  onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
135
147
  /**
@@ -15,7 +15,15 @@
15
15
 
16
16
  export { GemieRuntimeProvider, useGemieRuntime } from './config';
17
17
  export { ApprovalExpiredError } from './approvals';
18
- export type { ApprovalDecision, ApprovalEntry, ApprovalRequest } from './approvals';
18
+ export type {
19
+ ApprovalDecision,
20
+ ApprovalDetails,
21
+ ApprovalEntry,
22
+ ApprovalGrant,
23
+ ApprovalOption,
24
+ ApprovalOutcome,
25
+ ApprovalRequest,
26
+ } from './approvals';
19
27
  export type {
20
28
  GemieArtifact,
21
29
  GemieRuntimeConfig,
@@ -0,0 +1,306 @@
1
+ /**
2
+ * The frames of a chat turn's stream, kept whole across a dropped connection.
3
+ *
4
+ * A mobile network switch, a sleeping tab or a proxy that closed an idle socket cuts the stream
5
+ * while the turn runs on in the server. The turn is not lost: the server numbers every frame it
6
+ * writes (the SSE `id:`) and keeps the newest ones (`docs/chat-runtime.mdx`, "Resuming a stream").
7
+ * This module is the client's half. It reads the stream's frames, remembers the number of the last
8
+ * one it passed on, and when the connection ends WITHOUT the terminator, or fails mid-read, opens
9
+ * `GET /v1/chat/turns/:turnId/stream` from that number, with exponential backoff and jitter, and
10
+ * carries on. The reader above it never sees the seam:
11
+ *
12
+ * - A frame it already has (a replay that overlaps, the same frame on two connections) is dropped
13
+ * by its number, so a delta is applied once.
14
+ * - A `alia.snapshot` (the cursor was older than the server's buffer, or the turn finished while
15
+ * the client was away) is turned into the frames the reader already understands: a reset of the
16
+ * words and the reasoning, then the words, the reasoning, each tool call and result the reader
17
+ * does not have yet, and the turn's other frames newer than its cursor. Applying one twice
18
+ * leaves the same message.
19
+ * - A turn that cannot be resumed (another person's, one the server no longer knows, a server
20
+ * that does not number its frames) is a stream that ended early, exactly as before: the reader
21
+ * decides what that means. A turn is only given up on once every attempt is spent.
22
+ *
23
+ * A server that does not number frames is read as before: nothing to dedupe, and a drop is the
24
+ * same failure it always was after one refused reconnect.
25
+ */
26
+
27
+ import { createSseFrameReader, type SseFrame } from './sse-frame-reader';
28
+ import { parseTurnSnapshot, TURN_SNAPSHOT_EVENT, type TurnSnapshot } from './stream-events';
29
+
30
+ /** The frame that tells the reader to empty the reply's words (and reasoning) before a snapshot's. */
31
+ export const TURN_RESET_EVENT = 'alia.turn_reset';
32
+
33
+ const DEFAULT_MAX_ATTEMPTS = 6;
34
+ const DEFAULT_BASE_DELAY_MS = 500;
35
+ const DEFAULT_MAX_DELAY_MS = 8_000;
36
+
37
+ /** A status that will not change by asking again: the turn is not this person's, or is gone. */
38
+ const isFinalStatus = (status: number): boolean =>
39
+ status >= 400 && status < 500 && status !== 408 && status !== 429;
40
+
41
+ /**
42
+ * Exponential backoff with equal jitter: half the step is kept, half is random, so reconnecting
43
+ * clients that were cut together do not return together.
44
+ */
45
+ export function resumeDelayMs(
46
+ attempt: number,
47
+ random: () => number = Math.random,
48
+ baseMs: number = DEFAULT_BASE_DELAY_MS,
49
+ maxMs: number = DEFAULT_MAX_DELAY_MS,
50
+ ): number {
51
+ const step = Math.min(maxMs, baseMs * 2 ** attempt);
52
+ return Math.round(step / 2 + (random() * step) / 2);
53
+ }
54
+
55
+ /** What an aborted wait rejects with: the signal's reason, or an `AbortError` where it carries none. */
56
+ const abortReason = (signal: AbortSignal): unknown =>
57
+ signal.reason ?? Object.assign(new Error('The stream was aborted'), { name: 'AbortError' });
58
+
59
+ function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
60
+ return new Promise((resolve, reject) => {
61
+ if (signal.aborted) return reject(abortReason(signal));
62
+ const timer = setTimeout(() => {
63
+ signal.removeEventListener('abort', onAbort);
64
+ resolve();
65
+ }, ms);
66
+ const onAbort = () => {
67
+ clearTimeout(timer);
68
+ reject(abortReason(signal));
69
+ };
70
+ signal.addEventListener('abort', onAbort, { once: true });
71
+ });
72
+ }
73
+
74
+ export interface ResumableFrameSourceOptions {
75
+ /** The turn's first response, already known to be `ok` with a body. */
76
+ response: Response;
77
+ /** Open the turn's stream again, after the frame numbered `cursor`. */
78
+ reconnect(cursor: number, signal: AbortSignal): Promise<Response>;
79
+ /** The turn's own signal: a Stop or a detach ends the stream, never a resume. */
80
+ signal: AbortSignal;
81
+ maxAttempts?: number;
82
+ baseDelayMs?: number;
83
+ maxDelayMs?: number;
84
+ random?: () => number;
85
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
86
+ }
87
+
88
+ export type FrameRead = { done: true } | { done: false; frames: SseFrame[] };
89
+
90
+ export interface ResumableFrameSource {
91
+ /** The frames of the next chunk, deduped and snapshots expanded; `done` once the turn's stream is over. */
92
+ read(): Promise<FrameRead>;
93
+ /** Stop reading: the reader above has what it needed (an error frame, a refusal). */
94
+ cancel(): void;
95
+ }
96
+
97
+ const text = (data: unknown): SseFrame => ({ event: '', data: JSON.stringify(data) });
98
+
99
+ /** The frames a snapshot stands for, given what the reader already has. */
100
+ function expandSnapshot(
101
+ snapshot: TurnSnapshot,
102
+ cursor: number,
103
+ seen: { calls: Set<string>; results: Set<string> },
104
+ ): SseFrame[] {
105
+ const frames: SseFrame[] = [
106
+ {
107
+ event: TURN_RESET_EVENT,
108
+ data: JSON.stringify({ eventVersion: 1, reasoning: snapshot.reasoning !== undefined }),
109
+ },
110
+ ];
111
+ if (snapshot.content !== '') {
112
+ frames.push(
113
+ text({ choices: [{ index: 0, delta: { content: snapshot.content }, finish_reason: null }] }),
114
+ );
115
+ }
116
+ if (snapshot.reasoning) {
117
+ frames.push({
118
+ event: 'alia.reasoning',
119
+ data: JSON.stringify({ eventVersion: 1, content: snapshot.reasoning }),
120
+ });
121
+ }
122
+ snapshot.toolInvocations.forEach((call, index) => {
123
+ if (!seen.calls.has(call.toolCallId)) {
124
+ seen.calls.add(call.toolCallId);
125
+ frames.push(
126
+ text({
127
+ choices: [
128
+ {
129
+ index: 0,
130
+ delta: {
131
+ tool_calls: [
132
+ {
133
+ index,
134
+ id: call.toolCallId,
135
+ type: 'function',
136
+ function: { name: call.toolName, arguments: call.arguments },
137
+ },
138
+ ],
139
+ },
140
+ finish_reason: null,
141
+ },
142
+ ],
143
+ }),
144
+ );
145
+ }
146
+ if (call.state === 'result' && !seen.results.has(call.toolCallId)) {
147
+ seen.results.add(call.toolCallId);
148
+ frames.push({
149
+ event: 'alia.tool_result',
150
+ data: JSON.stringify({
151
+ eventVersion: 1,
152
+ tool_call_id: call.toolCallId,
153
+ name: call.toolName,
154
+ output: call.result,
155
+ }),
156
+ });
157
+ }
158
+ });
159
+ for (const frame of snapshot.frames) {
160
+ if (frame.seq > cursor) frames.push({ event: frame.event, data: frame.data });
161
+ }
162
+ return frames;
163
+ }
164
+
165
+ export function createResumableFrameSource(
166
+ options: ResumableFrameSourceOptions,
167
+ ): ResumableFrameSource {
168
+ const maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
169
+ const random = options.random ?? Math.random;
170
+ const sleep = options.sleep ?? sleepUnlessAborted;
171
+ // Ends with the turn's own signal or with `cancel()`. Linked by hand: this runs on every turn,
172
+ // and `AbortSignal.any` is not in every React Native this package supports.
173
+ const lifetime = new AbortController();
174
+ const followTurn = () => lifetime.abort(options.signal.reason);
175
+ if (options.signal.aborted) followTurn();
176
+ else options.signal.addEventListener('abort', followTurn, { once: true });
177
+ const { signal } = lifetime;
178
+
179
+ let reader = options.response.body?.getReader();
180
+ let decoder = new TextDecoder();
181
+ let frames = createSseFrameReader();
182
+ /** The number of the newest frame passed on. */
183
+ let cursor = 0;
184
+ let sawTerminal = false;
185
+ /**
186
+ * Reconnects spent since the stream last delivered a frame. A connection that opens and drops
187
+ * again without one counts against the same budget, so a flapping link ends instead of looping.
188
+ */
189
+ let attempts = 0;
190
+ const seen = { calls: new Set<string>(), results: new Set<string>() };
191
+
192
+ /** Remember which tool calls and results the reader has, so a snapshot sends only what it lacks. */
193
+ const observe = (frame: SseFrame): void => {
194
+ if (frame.event === 'alia.tool_result') {
195
+ try {
196
+ const id = (JSON.parse(frame.data) as { tool_call_id?: unknown }).tool_call_id;
197
+ if (typeof id === 'string') {
198
+ seen.calls.add(id);
199
+ seen.results.add(id);
200
+ }
201
+ } catch {
202
+ // Not a frame the reader will apply either.
203
+ }
204
+ } else if (frame.event === '' && frame.data.includes('"tool_calls"')) {
205
+ try {
206
+ const parsed = JSON.parse(frame.data) as {
207
+ choices?: Array<{ delta?: { tool_calls?: Array<{ id?: unknown }> } }>;
208
+ };
209
+ for (const call of parsed.choices?.[0]?.delta?.tool_calls ?? []) {
210
+ if (typeof call.id === 'string') seen.calls.add(call.id);
211
+ }
212
+ } catch {
213
+ // Likewise.
214
+ }
215
+ }
216
+ };
217
+
218
+ /** Dedupe by number, expand snapshots, and note the terminator. */
219
+ const accept = (incoming: SseFrame[]): SseFrame[] => {
220
+ const out: SseFrame[] = [];
221
+ for (const frame of incoming) {
222
+ if (frame.id !== undefined) {
223
+ if (frame.id <= cursor) continue;
224
+ const before = cursor;
225
+ cursor = frame.id;
226
+ if (frame.event === TURN_SNAPSHOT_EVENT) {
227
+ const snapshot = parseSnapshot(frame.data);
228
+ if (snapshot) out.push(...expandSnapshot(snapshot, before, seen));
229
+ continue;
230
+ }
231
+ } else if (frame.event === TURN_SNAPSHOT_EVENT) {
232
+ // A stored reply with no number (the buffer is gone): applies whatever the cursor.
233
+ const snapshot = parseSnapshot(frame.data);
234
+ if (snapshot) out.push(...expandSnapshot(snapshot, cursor, seen));
235
+ continue;
236
+ }
237
+ if (frame.data === '[DONE]') sawTerminal = true;
238
+ observe(frame);
239
+ out.push(frame);
240
+ }
241
+ return out;
242
+ };
243
+
244
+ const parseSnapshot = (data: string): TurnSnapshot | null => {
245
+ try {
246
+ return parseTurnSnapshot(JSON.parse(data));
247
+ } catch {
248
+ return null;
249
+ }
250
+ };
251
+
252
+ /** Open the stream again; true once a connection is open, false when resuming is given up. */
253
+ const resume = async (): Promise<boolean> => {
254
+ while (attempts < maxAttempts) {
255
+ await sleep(resumeDelayMs(attempts, random, options.baseDelayMs, options.maxDelayMs), signal);
256
+ attempts++;
257
+ try {
258
+ const response = await options.reconnect(cursor, signal);
259
+ if (response.ok && response.body) {
260
+ reader = response.body.getReader();
261
+ decoder = new TextDecoder();
262
+ frames = createSseFrameReader();
263
+ return true;
264
+ }
265
+ await response.body?.cancel().catch(() => undefined);
266
+ if (isFinalStatus(response.status)) return false;
267
+ } catch (error) {
268
+ if (signal.aborted) throw error;
269
+ }
270
+ }
271
+ return false;
272
+ };
273
+
274
+ return {
275
+ async read(): Promise<FrameRead> {
276
+ let failure: unknown;
277
+ while (true) {
278
+ failure = undefined;
279
+ try {
280
+ if (!reader) return { done: true };
281
+ const { done, value } = await reader.read();
282
+ if (!done) {
283
+ const accepted = accept(frames.push(decoder.decode(value, { stream: true })));
284
+ if (accepted.length > 0) {
285
+ attempts = 0;
286
+ return { done: false, frames: accepted };
287
+ }
288
+ continue;
289
+ }
290
+ if (sawTerminal) return { done: true };
291
+ } catch (error) {
292
+ if (signal.aborted) throw error;
293
+ failure = error;
294
+ }
295
+ // The connection ended without the terminator, or broke: the turn may still be running.
296
+ if (await resume()) continue;
297
+ if (failure !== undefined) throw failure;
298
+ return { done: true };
299
+ }
300
+ },
301
+ cancel() {
302
+ lifetime.abort();
303
+ reader?.cancel().catch(() => undefined);
304
+ },
305
+ };
306
+ }
@@ -18,6 +18,20 @@ export const API_ROUTES = {
18
18
  },
19
19
  /** The answer to an awaited host action, read by the turn that is waiting for it. */
20
20
  hostResults: (turnId: string) => `/v1/chat/turns/${encodeURIComponent(turnId)}/host-results`,
21
+ /**
22
+ * A dropped chat stream, picked up after the frame numbered `cursor` (`runtime/resumable-stream.ts`).
23
+ * The conversation and reply name what the turn was streaming, so a turn that finished meanwhile
24
+ * is answered with its stored reply.
25
+ */
26
+ chatTurnStream: (
27
+ turnId: string,
28
+ resume: { cursor: number; conversationId?: string; assistantMessageId: string },
29
+ ) => {
30
+ const query = new URLSearchParams({ cursor: String(resume.cursor) });
31
+ if (resume.conversationId) query.set('conversationId', resume.conversationId);
32
+ query.set('assistantMessageId', resume.assistantMessageId);
33
+ return `/v1/chat/turns/${encodeURIComponent(turnId)}/stream?${query}`;
34
+ },
21
35
  /** The person's folders and projects (`runtime/collections.ts`). */
22
36
  collections: {
23
37
  list: '/v1/conversations/collections',