@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.
- package/CHANGELOG.md +39 -0
- package/package.json +1 -1
- package/src/components/GemieChatContent.tsx +23 -6
- package/src/components/diff/FileChangeSection.tsx +172 -0
- package/src/components/diff/FileChangesCard.tsx +51 -0
- package/src/components/diff/FileChangesViewer.tsx +135 -0
- package/src/components/diff/PatchLines.tsx +119 -0
- package/src/components/diff/diff-renderer.ts +38 -0
- package/src/components/thread/ActionApprovalCard.tsx +95 -0
- package/src/components/thread/GemieThread.tsx +17 -0
- package/src/components/thread/ThreadRow.tsx +16 -1
- package/src/index.ts +6 -0
- package/src/lib/copy-en.ts +40 -0
- package/src/lib/copy-es.ts +43 -0
- package/src/runtime/action-approvals.ts +127 -0
- package/src/runtime/config.tsx +16 -0
- package/src/runtime/index.ts +1 -0
- package/src/runtime/model.ts +1 -0
- package/src/runtime/resumable-stream.ts +306 -0
- package/src/runtime/routes.ts +19 -0
- package/src/runtime/sse-frame-reader.ts +20 -1
- package/src/runtime/stream-events.ts +68 -0
- package/src/runtime/thread/file-changes.ts +150 -0
- package/src/runtime/use-conversation-stream.ts +63 -30
|
@@ -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
|
+
}
|
package/src/runtime/routes.ts
CHANGED
|
@@ -11,8 +11,27 @@
|
|
|
11
11
|
*/
|
|
12
12
|
export const API_ROUTES = {
|
|
13
13
|
chat: '/v1/chat/completions',
|
|
14
|
+
actionApprovals: {
|
|
15
|
+
list: '/v1/action-approvals',
|
|
16
|
+
decide: (id: string, decision: 'approve' | 'reject') =>
|
|
17
|
+
`/v1/action-approvals/${encodeURIComponent(id)}/${decision}`,
|
|
18
|
+
},
|
|
14
19
|
/** The answer to an awaited host action, read by the turn that is waiting for it. */
|
|
15
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
|
+
},
|
|
16
35
|
/** The person's folders and projects (`runtime/collections.ts`). */
|
|
17
36
|
collections: {
|
|
18
37
|
list: '/v1/conversations/collections',
|
|
@@ -31,6 +31,11 @@ export interface SseFrame {
|
|
|
31
31
|
readonly event: string;
|
|
32
32
|
/** The `data:` payload, trimmed. `[DONE]` is passed through as-is. */
|
|
33
33
|
readonly data: string;
|
|
34
|
+
/**
|
|
35
|
+
* The frame's `id:`, the turn's sequence number (`resumable-stream.ts`), when it has one. A frame
|
|
36
|
+
* of a server that numbers nothing has none.
|
|
37
|
+
*/
|
|
38
|
+
readonly id?: number;
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
export interface SseFrameReader {
|
|
@@ -41,6 +46,7 @@ export interface SseFrameReader {
|
|
|
41
46
|
export function createSseFrameReader(): SseFrameReader {
|
|
42
47
|
let buffer = '';
|
|
43
48
|
let currentEventType = '';
|
|
49
|
+
let currentId: number | undefined;
|
|
44
50
|
|
|
45
51
|
return {
|
|
46
52
|
push(chunk: string): SseFrame[] {
|
|
@@ -63,19 +69,32 @@ export function createSseFrameReader(): SseFrameReader {
|
|
|
63
69
|
continue;
|
|
64
70
|
}
|
|
65
71
|
|
|
72
|
+
// Only a whole number is a sequence number; anything else is a field this client ignores.
|
|
73
|
+
if (line.startsWith('id: ')) {
|
|
74
|
+
const id = line.slice(4).trim();
|
|
75
|
+
currentId = /^\d{1,15}$/.test(id) ? Number(id) : undefined;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
|
|
66
79
|
// A blank line closes a frame. Resetting here is what stops a `data:`
|
|
67
80
|
// line in the NEXT frame inheriting this frame's event name.
|
|
68
81
|
if (line === '') {
|
|
69
82
|
currentEventType = '';
|
|
83
|
+
currentId = undefined;
|
|
70
84
|
continue;
|
|
71
85
|
}
|
|
72
86
|
|
|
73
87
|
if (line.startsWith('data: ')) {
|
|
74
|
-
frames.push({
|
|
88
|
+
frames.push({
|
|
89
|
+
event: currentEventType,
|
|
90
|
+
data: line.slice(6).trim(),
|
|
91
|
+
...(currentId === undefined ? {} : { id: currentId }),
|
|
92
|
+
});
|
|
75
93
|
// One `data:` line is one frame for this protocol. The event name is
|
|
76
94
|
// consumed with it, so a second `data:` without its own `event:` is
|
|
77
95
|
// correctly unnamed rather than inheriting.
|
|
78
96
|
currentEventType = '';
|
|
97
|
+
currentId = undefined;
|
|
79
98
|
}
|
|
80
99
|
|
|
81
100
|
// Comments (`: keep-alive`) and any field this client does not read
|
|
@@ -155,3 +155,71 @@ export function lockedFeatureOf(error: unknown): string | null {
|
|
|
155
155
|
if (!isObject(error) || error.code !== FEATURE_ENTITLEMENT_REQUIRED) return null;
|
|
156
156
|
return isText(error.feature) ? error.feature : null;
|
|
157
157
|
}
|
|
158
|
+
|
|
159
|
+
/** The event name of a resume's snapshot of the turn (`resumable-stream.ts`). */
|
|
160
|
+
export const TURN_SNAPSHOT_EVENT = 'alia.snapshot';
|
|
161
|
+
|
|
162
|
+
/** One tool call of a snapshot; `arguments` is the JSON string the wire sends them as. */
|
|
163
|
+
export interface SnapshotToolInvocation {
|
|
164
|
+
toolCallId: string;
|
|
165
|
+
toolName: string;
|
|
166
|
+
state: 'call' | 'result';
|
|
167
|
+
arguments: string;
|
|
168
|
+
result?: unknown;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The turn's state the server sends when a reconnect cannot be given the frames it missed: the
|
|
173
|
+
* words, the reasoning and the tool calls so far, and the turn's other frames. `seq` is the number
|
|
174
|
+
* the state runs through; `reasoning` is absent when the reader should keep its own.
|
|
175
|
+
*/
|
|
176
|
+
export interface TurnSnapshot {
|
|
177
|
+
seq?: number;
|
|
178
|
+
content: string;
|
|
179
|
+
reasoning?: string;
|
|
180
|
+
toolInvocations: SnapshotToolInvocation[];
|
|
181
|
+
frames: Array<{ seq: number; event: string; data: string }>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The snapshot a `alia.snapshot` frame carries, or `null` when it is not well-formed. */
|
|
185
|
+
export function parseTurnSnapshot(data: unknown): TurnSnapshot | null {
|
|
186
|
+
if (!isObject(data) || data.eventVersion !== 1 || typeof data.content !== 'string') return null;
|
|
187
|
+
if (data.reasoning !== undefined && typeof data.reasoning !== 'string') return null;
|
|
188
|
+
if (data.seq !== undefined && !(Number.isSafeInteger(data.seq) && (data.seq as number) >= 0)) {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
if (!Array.isArray(data.toolInvocations) || !Array.isArray(data.frames)) return null;
|
|
192
|
+
|
|
193
|
+
const toolInvocations: SnapshotToolInvocation[] = [];
|
|
194
|
+
for (const call of data.toolInvocations) {
|
|
195
|
+
if (!isObject(call) || !isText(call.toolCallId) || !isText(call.toolName)) return null;
|
|
196
|
+
if (call.state !== 'call' && call.state !== 'result') return null;
|
|
197
|
+
if (typeof call.arguments !== 'string') return null;
|
|
198
|
+
toolInvocations.push({
|
|
199
|
+
toolCallId: call.toolCallId,
|
|
200
|
+
toolName: call.toolName,
|
|
201
|
+
state: call.state,
|
|
202
|
+
arguments: call.arguments,
|
|
203
|
+
...(call.result === undefined ? {} : { result: call.result }),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const frames: TurnSnapshot['frames'] = [];
|
|
207
|
+
for (const frame of data.frames) {
|
|
208
|
+
if (
|
|
209
|
+
!isObject(frame) ||
|
|
210
|
+
!Number.isSafeInteger(frame.seq) ||
|
|
211
|
+
typeof frame.event !== 'string' ||
|
|
212
|
+
typeof frame.data !== 'string'
|
|
213
|
+
) {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
frames.push({ seq: frame.seq as number, event: frame.event, data: frame.data });
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
...(data.seq === undefined ? {} : { seq: data.seq as number }),
|
|
220
|
+
content: data.content,
|
|
221
|
+
...(data.reasoning === undefined ? {} : { reasoning: data.reasoning }),
|
|
222
|
+
toolInvocations,
|
|
223
|
+
frames,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { ToolInvocation } from '../types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The files an external agent (Claude Code, Codex, OpenCode) changed, as the conversation keeps
|
|
5
|
+
* them (ADR 0043 §5): the tool result of an edit carries `changes`, one standard `diff --git` patch
|
|
6
|
+
* per file, made by the server from whatever each CLI recorded
|
|
7
|
+
* (`packages/api/src/lib/external-agents/file-changes.ts`).
|
|
8
|
+
*
|
|
9
|
+
* Pure. The result is read like every tool result (`cardOf`): the snapshot is untrusted JSON, so
|
|
10
|
+
* every field is checked and an entry that is not a change is left out.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type FileChangeOperation = 'add' | 'update' | 'delete' | 'rename';
|
|
14
|
+
|
|
15
|
+
export interface FileChange {
|
|
16
|
+
/** Relative to the agent's folder when the daemon said so. */
|
|
17
|
+
path: string;
|
|
18
|
+
/** Where a renamed file was. */
|
|
19
|
+
oldPath?: string;
|
|
20
|
+
operation: FileChangeOperation;
|
|
21
|
+
/** Not text (an image, a binary): its patch only says the file changed. */
|
|
22
|
+
binary: boolean;
|
|
23
|
+
/** Absent when nothing was recorded to build one from, or it was too large to keep. */
|
|
24
|
+
patch?: string;
|
|
25
|
+
additions: number;
|
|
26
|
+
deletions: number;
|
|
27
|
+
/** The patch was left out because it was too large (the stats are still the file's). */
|
|
28
|
+
truncated: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A change and the call that made it, so two edits of one file stay two sections. */
|
|
32
|
+
export interface CallFileChange extends FileChange {
|
|
33
|
+
/** Unique within the turn: the call's id and the file's place in it. */
|
|
34
|
+
key: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface FileChangeTotals {
|
|
38
|
+
/** Distinct paths: a file edited twice is one file. */
|
|
39
|
+
files: number;
|
|
40
|
+
additions: number;
|
|
41
|
+
deletions: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const OPERATIONS: readonly FileChangeOperation[] = ['add', 'update', 'delete', 'rename'];
|
|
45
|
+
|
|
46
|
+
const isCount = (value: unknown): value is number =>
|
|
47
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
48
|
+
|
|
49
|
+
function fileChange(value: unknown): FileChange | null {
|
|
50
|
+
if (value === null || typeof value !== 'object') return null;
|
|
51
|
+
const v = value as Record<string, unknown>;
|
|
52
|
+
if (typeof v.path !== 'string' || v.path === '') return null;
|
|
53
|
+
if (!OPERATIONS.includes(v.operation as FileChangeOperation)) return null;
|
|
54
|
+
return {
|
|
55
|
+
path: v.path,
|
|
56
|
+
...(typeof v.oldPath === 'string' && v.oldPath !== '' ? { oldPath: v.oldPath } : {}),
|
|
57
|
+
operation: v.operation as FileChangeOperation,
|
|
58
|
+
binary: v.binary === true,
|
|
59
|
+
...(typeof v.patch === 'string' ? { patch: v.patch } : {}),
|
|
60
|
+
additions: isCount(v.additions) ? v.additions : 0,
|
|
61
|
+
deletions: isCount(v.deletions) ? v.deletions : 0,
|
|
62
|
+
truncated: v.truncated === true,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The files a finished call changed, in the order it reported them; none for any other call. */
|
|
67
|
+
export function fileChangesOf(call: ToolInvocation): CallFileChange[] {
|
|
68
|
+
if (call.state !== 'result') return [];
|
|
69
|
+
const changes = (call.result as { changes?: unknown } | undefined)?.changes;
|
|
70
|
+
if (!Array.isArray(changes)) return [];
|
|
71
|
+
return changes.flatMap((entry, index) => {
|
|
72
|
+
const change = fileChange(entry);
|
|
73
|
+
return change === null ? [] : [{ ...change, key: `${call.toolCallId}:${index}` }];
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Every file the calls of a turn changed, call by call. */
|
|
78
|
+
export function turnFileChanges(calls: readonly ToolInvocation[]): CallFileChange[] {
|
|
79
|
+
return calls.flatMap(fileChangesOf);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** What "N files changed +X −Y" says of a list of changes. */
|
|
83
|
+
export function fileChangeTotals(changes: readonly FileChange[]): FileChangeTotals {
|
|
84
|
+
const files = new Set<string>();
|
|
85
|
+
let additions = 0;
|
|
86
|
+
let deletions = 0;
|
|
87
|
+
for (const change of changes) {
|
|
88
|
+
files.add(change.path);
|
|
89
|
+
additions += change.additions;
|
|
90
|
+
deletions += change.deletions;
|
|
91
|
+
}
|
|
92
|
+
return { files: files.size, additions, deletions };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The file's name, without its folder. */
|
|
96
|
+
export function fileChangeName(path: string): string {
|
|
97
|
+
const parts = path.replaceAll('\\', '/').split('/');
|
|
98
|
+
return parts.at(-1) || path;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** One line of a patch's hunks, as a plain list can draw it. */
|
|
102
|
+
export type PatchLine =
|
|
103
|
+
| { kind: 'hunk'; text: string }
|
|
104
|
+
| { kind: 'context' | 'add' | 'delete'; text: string; oldLine?: number; newLine?: number }
|
|
105
|
+
| { kind: 'note'; text: string };
|
|
106
|
+
|
|
107
|
+
const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The lines of a patch's hunks with their line numbers, for a view that draws no more than text.
|
|
111
|
+
* The headers before the first hunk (`diff --git`, `---`, `+++`, `new file mode`) are not lines of
|
|
112
|
+
* the file and are left out; `` is kept as a note.
|
|
113
|
+
*/
|
|
114
|
+
export function patchLines(patch: string): PatchLine[] {
|
|
115
|
+
const out: PatchLine[] = [];
|
|
116
|
+
let oldLine = 0;
|
|
117
|
+
let newLine = 0;
|
|
118
|
+
let inHunk = false;
|
|
119
|
+
const lines = patch.split('\n');
|
|
120
|
+
if (lines.at(-1) === '') lines.pop();
|
|
121
|
+
for (const line of lines) {
|
|
122
|
+
const header = HUNK_HEADER.exec(line);
|
|
123
|
+
if (header) {
|
|
124
|
+
inHunk = true;
|
|
125
|
+
oldLine = Number(header[1]);
|
|
126
|
+
newLine = Number(header[2]);
|
|
127
|
+
out.push({ kind: 'hunk', text: line });
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (!inHunk) continue;
|
|
131
|
+
if (line.startsWith('\\')) {
|
|
132
|
+
out.push({ kind: 'note', text: line.slice(1).trim() });
|
|
133
|
+
} else if (line.startsWith('+')) {
|
|
134
|
+
out.push({ kind: 'add', text: line.slice(1), newLine: newLine++ });
|
|
135
|
+
} else if (line.startsWith('-')) {
|
|
136
|
+
out.push({ kind: 'delete', text: line.slice(1), oldLine: oldLine++ });
|
|
137
|
+
} else if (line.startsWith('diff --git ')) {
|
|
138
|
+
// A second file's section in a patch of several: the viewer is handed one file's patch.
|
|
139
|
+
break;
|
|
140
|
+
} else {
|
|
141
|
+
out.push({
|
|
142
|
+
kind: 'context',
|
|
143
|
+
text: line.startsWith(' ') ? line.slice(1) : line,
|
|
144
|
+
oldLine: oldLine++,
|
|
145
|
+
newLine: newLine++,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|