@nones/agentflow-core 0.1.0 → 0.6.1
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/LICENSE +21 -0
- package/README.md +179 -0
- package/package.json +16 -2
- package/src/artifact-history.ts +853 -0
- package/src/client.ts +92 -1
- package/src/engine.ts +2382 -97
- package/src/history.ts +1268 -0
- package/src/ids.ts +3 -0
- package/src/index.ts +46 -3
- package/src/inspection.ts +1580 -0
- package/src/protocol.ts +165 -0
- package/src/server.ts +544 -56
- package/src/session-configuration.ts +82 -0
- package/src/store.ts +956 -20
- package/src/types.ts +484 -2
- package/src/validation.ts +458 -1
package/src/history.ts
ADDED
|
@@ -0,0 +1,1268 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider-neutral durable history capability.
|
|
3
|
+
*
|
|
4
|
+
* A provider adapter that can read visible conversation history publishes an
|
|
5
|
+
* optional `history` capability. This module turns that capability into
|
|
6
|
+
* bounded, redacted, upserted records in the owner-only store, so an offline
|
|
7
|
+
* inspector can render the newest safe view without the provider being up.
|
|
8
|
+
*
|
|
9
|
+
* Boundaries:
|
|
10
|
+
* - the engine and the inspector own their own files; this module only exposes
|
|
11
|
+
* small functions they can call (see the glue steps at the end of its tests);
|
|
12
|
+
* - nothing here sends a prompt, so reconciling history never causes work;
|
|
13
|
+
* - raw tool arguments, tool output, provider headers and private reasoning are
|
|
14
|
+
* never persisted; every loss is recorded as an explicit omission/redaction
|
|
15
|
+
* state so missing data never looks like success;
|
|
16
|
+
* - the provider's message/part ids and reported cursor are the durable
|
|
17
|
+
* identity, so a replayed page or a duplicate SSE event upserts instead of
|
|
18
|
+
* double-counting usage;
|
|
19
|
+
* - a provider failure is never stored as an empty transcript.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { Database } from "bun:sqlite";
|
|
23
|
+
import { AgentFlowError } from "./errors";
|
|
24
|
+
import { fromJson, isPlainObject, toJson } from "./json";
|
|
25
|
+
import type { Store } from "./store";
|
|
26
|
+
|
|
27
|
+
/** Default records per page; the hard maximum keeps IPC pages bounded. */
|
|
28
|
+
export const HISTORY_DEFAULT_PAGE_SIZE = 100;
|
|
29
|
+
export const HISTORY_MAX_PAGE_SIZE = 500;
|
|
30
|
+
/** Default record budget for a single persisted history. */
|
|
31
|
+
export const HISTORY_DEFAULT_MAX_RECORDS = 500;
|
|
32
|
+
/** Default retained characters of one message or part text. */
|
|
33
|
+
export const HISTORY_DEFAULT_MAX_TEXT = 4_000;
|
|
34
|
+
/** Default retained parts of one message. */
|
|
35
|
+
export const HISTORY_DEFAULT_MAX_PARTS = 100;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* State of any bounded or unavailable value. `unknown` means the provider did
|
|
39
|
+
* not report it (never a manufactured zero); `unsupported` means this build has
|
|
40
|
+
* no mapping for it, `disabled` that collection was turned off deliberately.
|
|
41
|
+
*/
|
|
42
|
+
export type HistoryState =
|
|
43
|
+
| "complete"
|
|
44
|
+
| "truncated"
|
|
45
|
+
| "omitted"
|
|
46
|
+
| "redacted"
|
|
47
|
+
| "disabled"
|
|
48
|
+
| "unsupported"
|
|
49
|
+
| "unknown";
|
|
50
|
+
|
|
51
|
+
export type HistoryRole = "assistant" | "user" | "unknown";
|
|
52
|
+
|
|
53
|
+
/** Token counters under the provider's actual semantics; absent means unknown. */
|
|
54
|
+
export interface HistoryUsage {
|
|
55
|
+
input?: number;
|
|
56
|
+
output?: number;
|
|
57
|
+
cachedInput?: number;
|
|
58
|
+
cacheWrite?: number;
|
|
59
|
+
/** Reported by some providers; kept separate from `output` and never summed into it. */
|
|
60
|
+
reasoning?: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface HistoryPart {
|
|
64
|
+
/** Stable provider part id. */
|
|
65
|
+
id: string;
|
|
66
|
+
kind: "text" | "tool" | "reasoning" | "unknown";
|
|
67
|
+
/** Bounded safe token for the raw provider type. */
|
|
68
|
+
type?: string;
|
|
69
|
+
state: HistoryState;
|
|
70
|
+
/** Bounded visible text for `kind: "text"`; absent for every other kind. */
|
|
71
|
+
text?: string;
|
|
72
|
+
/** Provider-reported or normalized visible length. */
|
|
73
|
+
length?: number;
|
|
74
|
+
/** Safe tool name/status tokens; never arguments, output or error text. */
|
|
75
|
+
name?: string;
|
|
76
|
+
status?: string;
|
|
77
|
+
timeStart?: number;
|
|
78
|
+
timeEnd?: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One normalized provider message as persisted. */
|
|
82
|
+
export interface HistoryRecord {
|
|
83
|
+
providerMessageId: string;
|
|
84
|
+
role: HistoryRole;
|
|
85
|
+
providerSessionId?: string;
|
|
86
|
+
parentMessageId?: string;
|
|
87
|
+
/** Model that answered this message, when the provider reported one. */
|
|
88
|
+
model?: { providerID: string; id: string };
|
|
89
|
+
createdAt?: number;
|
|
90
|
+
completedAt?: number;
|
|
91
|
+
usage?: HistoryUsage;
|
|
92
|
+
usageState: "complete" | "partial" | "unknown";
|
|
93
|
+
/** Counter names the provider reported that this mapping does not count. */
|
|
94
|
+
unmappedCounters: string[];
|
|
95
|
+
/** Visible text of the message, bounded. */
|
|
96
|
+
text: string;
|
|
97
|
+
textState: HistoryState;
|
|
98
|
+
parts: HistoryPart[];
|
|
99
|
+
/** Explicit redactions/omissions for this message. */
|
|
100
|
+
omissions: string[];
|
|
101
|
+
/** Opaque durable provider cursor at which this record was last observed. */
|
|
102
|
+
cursor?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** One normalized history page handed to the store. */
|
|
106
|
+
export interface HistoryIngestInput {
|
|
107
|
+
provider: string;
|
|
108
|
+
providerSessionId: string;
|
|
109
|
+
/** Position in a paged walk: `cursor` is the request cursor, `nextCursor` the answer. */
|
|
110
|
+
cursor?: string;
|
|
111
|
+
nextCursor?: string;
|
|
112
|
+
/** Explicit capture time; defaults to the store clock. */
|
|
113
|
+
capturedAt?: number;
|
|
114
|
+
/** `false` when the provider returned a bare list without paging metadata. */
|
|
115
|
+
paging: "complete" | "unknown" | "unsupported";
|
|
116
|
+
records: readonly HistoryRecord[];
|
|
117
|
+
/** Provider failure message; when set nothing is written and the status is `error`. */
|
|
118
|
+
error?: string;
|
|
119
|
+
/** Non-fatal notice stored on the snapshot without changing its status. */
|
|
120
|
+
notice?: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface HistoryIngestResult {
|
|
124
|
+
providerSessionId: string;
|
|
125
|
+
/** Records newly inserted. */
|
|
126
|
+
inserted: number;
|
|
127
|
+
/** Records whose content changed in place (same provider message id). */
|
|
128
|
+
updated: number;
|
|
129
|
+
/** Records that already existed with identical content; replays land here. */
|
|
130
|
+
unchanged: number;
|
|
131
|
+
/** Records whose identity could not be persisted safely. */
|
|
132
|
+
rejected: number;
|
|
133
|
+
/** Records evicted to stay inside the record budget or the page bound. */
|
|
134
|
+
pruned: number;
|
|
135
|
+
/** Cursor to request next; absent when the walk is finished or paging is unsupported. */
|
|
136
|
+
nextCursor?: string;
|
|
137
|
+
paging: "complete" | "unknown" | "unsupported";
|
|
138
|
+
capturedAt: number;
|
|
139
|
+
/** Newest safe usage after this page. */
|
|
140
|
+
usage: HistoryUsage & {
|
|
141
|
+
attempts: number;
|
|
142
|
+
state: "complete" | "partial" | "unknown";
|
|
143
|
+
};
|
|
144
|
+
/** The stored view is a bounded suffix or paging is not complete. */
|
|
145
|
+
truncated: boolean;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Newest safe view an offline inspector may render. */
|
|
149
|
+
export interface HistorySnapshot {
|
|
150
|
+
provider: string;
|
|
151
|
+
providerSessionId: string;
|
|
152
|
+
/** Cursor recorded for the most recent page. */
|
|
153
|
+
cursor?: string;
|
|
154
|
+
capturedAt: number;
|
|
155
|
+
/**
|
|
156
|
+
* `empty` means a successful read returned no messages; `error` means the last
|
|
157
|
+
* read failed and the records are only the last known state.
|
|
158
|
+
*/
|
|
159
|
+
status: "ok" | "empty" | "error";
|
|
160
|
+
/** Stored notice or the safe summary of the last failure. */
|
|
161
|
+
error?: string;
|
|
162
|
+
/** Whether this view is only a bounded part of the provider history. */
|
|
163
|
+
truncated: boolean;
|
|
164
|
+
total: number;
|
|
165
|
+
records: HistoryRecord[];
|
|
166
|
+
usage: HistoryUsage & {
|
|
167
|
+
attempts: number;
|
|
168
|
+
state: "complete" | "partial" | "unknown";
|
|
169
|
+
};
|
|
170
|
+
createdAt: number;
|
|
171
|
+
updatedAt: number;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A keyset page of stored records for read-only inspection. */
|
|
175
|
+
export interface HistoryPage {
|
|
176
|
+
records: HistoryRecord[];
|
|
177
|
+
/** Pass as `after` to continue; absent when the page is the last one. */
|
|
178
|
+
nextCursor?: number;
|
|
179
|
+
highWater: number;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface HistoryStoreOptions {
|
|
183
|
+
maxRecords?: number;
|
|
184
|
+
maxPageSize?: number;
|
|
185
|
+
maxTextLength?: number;
|
|
186
|
+
maxParts?: number;
|
|
187
|
+
/** Provider notice/error text is stored only as a bounded safe summary. */
|
|
188
|
+
maxErrorLength?: number;
|
|
189
|
+
/** Clock for capture times; defaults to `Date.now`. */
|
|
190
|
+
now?: () => number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const MAX_ID_LENGTH = 256;
|
|
194
|
+
const MAX_SAFE_TOKEN = 120;
|
|
195
|
+
const MAX_OMISSIONS = 32;
|
|
196
|
+
const USAGE_KEYS = [
|
|
197
|
+
"input",
|
|
198
|
+
"output",
|
|
199
|
+
"cachedInput",
|
|
200
|
+
"cacheWrite",
|
|
201
|
+
"reasoning",
|
|
202
|
+
] as const;
|
|
203
|
+
/** Provider-native aliases for a stable part id. */
|
|
204
|
+
const PART_ID_KEYS = ["id", "partID", "partId", "callID", "callId"] as const;
|
|
205
|
+
|
|
206
|
+
function safeToken(value: unknown): string | undefined {
|
|
207
|
+
if (typeof value !== "string") return undefined;
|
|
208
|
+
const trimmed = value.trim();
|
|
209
|
+
if (trimmed === "") return undefined;
|
|
210
|
+
return trimmed.length <= MAX_SAFE_TOKEN
|
|
211
|
+
? trimmed
|
|
212
|
+
: trimmed.slice(0, MAX_SAFE_TOKEN);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function safeId(value: unknown): string | undefined {
|
|
216
|
+
if (typeof value !== "string") return undefined;
|
|
217
|
+
const trimmed = value.trim();
|
|
218
|
+
if (trimmed === "" || trimmed.length > MAX_ID_LENGTH) return undefined;
|
|
219
|
+
// Control characters make keyset paging and projection logs ambiguous.
|
|
220
|
+
if (/[\u0000-\u001f\u007f]/u.test(trimmed)) return undefined;
|
|
221
|
+
return trimmed;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function isPaging(
|
|
225
|
+
value: unknown,
|
|
226
|
+
): value is "complete" | "unknown" | "unsupported" {
|
|
227
|
+
return value === "complete" || value === "unknown" || value === "unsupported";
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function finiteNonNegative(value: unknown): number | undefined {
|
|
231
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
232
|
+
? value
|
|
233
|
+
: undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function counter(value: unknown): number | undefined {
|
|
237
|
+
const parsed = finiteNonNegative(value);
|
|
238
|
+
return parsed === undefined ? undefined : Math.floor(parsed);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function safeErrorSummary(
|
|
242
|
+
error: string | undefined,
|
|
243
|
+
max: number,
|
|
244
|
+
): string | undefined {
|
|
245
|
+
if (error === undefined) return undefined;
|
|
246
|
+
// Only the message text is kept and it stays short, because providers may echo
|
|
247
|
+
// credentials or resolved references inside error payloads.
|
|
248
|
+
const flat = error.replace(/\s+/gu, " ").trim();
|
|
249
|
+
if (flat === "") return "provider history read failed";
|
|
250
|
+
return flat.length <= max ? flat : `${flat.slice(0, max)}…`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function boundText(
|
|
254
|
+
value: string,
|
|
255
|
+
maxLength: number,
|
|
256
|
+
): { text: string; state: HistoryState } {
|
|
257
|
+
if (value.trim() === "") return { text: "", state: "omitted" };
|
|
258
|
+
if (maxLength <= 0) return { text: "", state: "truncated" };
|
|
259
|
+
if (value.length <= maxLength) return { text: value, state: "complete" };
|
|
260
|
+
return { text: value.slice(0, maxLength), state: "truncated" };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Normalize one message's counters or report explicitly that nothing is known. */
|
|
264
|
+
export function normalizeHistoryUsage(
|
|
265
|
+
value: unknown,
|
|
266
|
+
unmappedCounters: readonly string[] = [],
|
|
267
|
+
): Pick<HistoryRecord, "usage" | "usageState" | "unmappedCounters"> {
|
|
268
|
+
const source = isPlainObject(value) ? value : undefined;
|
|
269
|
+
const reported: HistoryUsage = {};
|
|
270
|
+
for (const key of USAGE_KEYS) {
|
|
271
|
+
const parsed = counter(source?.[key]);
|
|
272
|
+
if (parsed !== undefined) reported[key] = parsed;
|
|
273
|
+
}
|
|
274
|
+
const known = Object.keys(reported).length;
|
|
275
|
+
const unmapped = [...new Set(unmappedCounters)]
|
|
276
|
+
.map((key) => safeToken(key))
|
|
277
|
+
.filter((key): key is string => key !== undefined)
|
|
278
|
+
.slice(0, 64);
|
|
279
|
+
// A reported counter this mapping ignores makes the attempt explicitly partial.
|
|
280
|
+
return {
|
|
281
|
+
...(known === 0 ? {} : { usage: reported }),
|
|
282
|
+
usageState:
|
|
283
|
+
known === 0 ? "unknown" : unmapped.length > 0 ? "partial" : "complete",
|
|
284
|
+
unmappedCounters: unmapped,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Validate and bound a record supplied by a capability. Anything without safe
|
|
290
|
+
* provider identity is rejected: it could not be upserted without inventing an
|
|
291
|
+
* id, and a synthesized id would let a later page double-count its usage.
|
|
292
|
+
*/
|
|
293
|
+
export function normalizeHistoryRecord(
|
|
294
|
+
input: HistoryRecord,
|
|
295
|
+
options: Pick<HistoryStoreOptions, "maxTextLength" | "maxParts"> = {},
|
|
296
|
+
): HistoryRecord | undefined {
|
|
297
|
+
if (!isPlainObject(input)) return undefined;
|
|
298
|
+
const messageId = safeId(input.providerMessageId);
|
|
299
|
+
if (!messageId) return undefined;
|
|
300
|
+
const providerMessageId: string = messageId;
|
|
301
|
+
const role = input.role;
|
|
302
|
+
if (role !== "assistant" && role !== "user" && role !== "unknown")
|
|
303
|
+
return undefined;
|
|
304
|
+
|
|
305
|
+
const maxText = Math.max(
|
|
306
|
+
0,
|
|
307
|
+
Math.floor(options.maxTextLength ?? HISTORY_DEFAULT_MAX_TEXT),
|
|
308
|
+
);
|
|
309
|
+
const maxParts = Math.max(
|
|
310
|
+
1,
|
|
311
|
+
Math.floor(options.maxParts ?? HISTORY_DEFAULT_MAX_PARTS),
|
|
312
|
+
);
|
|
313
|
+
const text = boundText(
|
|
314
|
+
typeof input.text === "string" ? input.text : "",
|
|
315
|
+
maxText,
|
|
316
|
+
);
|
|
317
|
+
|
|
318
|
+
const parts: HistoryPart[] = [];
|
|
319
|
+
const partIds = new Set<string>();
|
|
320
|
+
// Caps on what one provider message may contribute to the stored record.
|
|
321
|
+
const rawParts = Array.isArray(input.parts) ? input.parts : [];
|
|
322
|
+
const keptParts = rawParts.filter((raw) => {
|
|
323
|
+
if (!isPlainObject(raw)) return false;
|
|
324
|
+
const kind = raw.kind;
|
|
325
|
+
return (
|
|
326
|
+
kind === "text" ||
|
|
327
|
+
kind === "tool" ||
|
|
328
|
+
kind === "reasoning" ||
|
|
329
|
+
kind === "unknown"
|
|
330
|
+
);
|
|
331
|
+
});
|
|
332
|
+
const omissions = [
|
|
333
|
+
...new Set(Array.isArray(input.omissions) ? input.omissions : []),
|
|
334
|
+
];
|
|
335
|
+
if (keptParts.length > maxParts) {
|
|
336
|
+
// Dropped parts are an explicit omission, never a silent gap.
|
|
337
|
+
omissions.push(
|
|
338
|
+
`${keptParts.length - maxParts} parts omitted by the record budget`,
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
for (const raw of keptParts.slice(0, maxParts)) {
|
|
342
|
+
const rawId = PART_ID_KEYS.map((key) =>
|
|
343
|
+
safeId((raw as unknown as Record<string, unknown>)[key]),
|
|
344
|
+
).find((candidate) => candidate !== undefined);
|
|
345
|
+
if (!rawId || partIds.has(rawId)) continue;
|
|
346
|
+
const id: string = rawId;
|
|
347
|
+
const kind = raw.kind as HistoryPart["kind"];
|
|
348
|
+
partIds.add(id);
|
|
349
|
+
const bounded =
|
|
350
|
+
kind === "text" && typeof raw.text === "string"
|
|
351
|
+
? boundText(raw.text, maxText)
|
|
352
|
+
: undefined;
|
|
353
|
+
const providerLength = finiteNonNegative(raw.length);
|
|
354
|
+
parts.push({
|
|
355
|
+
id,
|
|
356
|
+
kind,
|
|
357
|
+
...(safeToken(raw.type) === undefined
|
|
358
|
+
? {}
|
|
359
|
+
: { type: safeToken(raw.type) }),
|
|
360
|
+
state:
|
|
361
|
+
kind === "reasoning"
|
|
362
|
+
? "redacted"
|
|
363
|
+
: kind === "text"
|
|
364
|
+
? (bounded?.state ?? "omitted")
|
|
365
|
+
: "omitted",
|
|
366
|
+
// Only visible text parts ever carry text; tool arguments and output are dropped here.
|
|
367
|
+
...(bounded === undefined || bounded.state === "omitted"
|
|
368
|
+
? {}
|
|
369
|
+
: { text: bounded.text }),
|
|
370
|
+
...(providerLength === undefined
|
|
371
|
+
? bounded === undefined || bounded.state === "omitted"
|
|
372
|
+
? {}
|
|
373
|
+
: { length: bounded.text.length }
|
|
374
|
+
: { length: Math.floor(providerLength) }),
|
|
375
|
+
...(safeToken(raw.name) === undefined
|
|
376
|
+
? {}
|
|
377
|
+
: { name: safeToken(raw.name) }),
|
|
378
|
+
...(safeToken(raw.status) === undefined
|
|
379
|
+
? {}
|
|
380
|
+
: { status: safeToken(raw.status) }),
|
|
381
|
+
...(finiteNonNegative(raw.timeStart) === undefined
|
|
382
|
+
? {}
|
|
383
|
+
: { timeStart: finiteNonNegative(raw.timeStart) }),
|
|
384
|
+
...(finiteNonNegative(raw.timeEnd) === undefined
|
|
385
|
+
? {}
|
|
386
|
+
: { timeEnd: finiteNonNegative(raw.timeEnd) }),
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const usage = normalizeHistoryUsage(input.usage, input.unmappedCounters);
|
|
391
|
+
const model =
|
|
392
|
+
isPlainObject(input.model) &&
|
|
393
|
+
safeToken(input.model.providerID) !== undefined &&
|
|
394
|
+
safeToken(input.model.id) !== undefined
|
|
395
|
+
? {
|
|
396
|
+
providerID: safeToken(input.model.providerID)!,
|
|
397
|
+
id: safeToken(input.model.id)!,
|
|
398
|
+
}
|
|
399
|
+
: undefined;
|
|
400
|
+
|
|
401
|
+
const boundedOmissions = [...new Set(omissions)]
|
|
402
|
+
.map((entry) => safeToken(entry))
|
|
403
|
+
.filter((entry): entry is string => entry !== undefined)
|
|
404
|
+
.slice(0, MAX_OMISSIONS);
|
|
405
|
+
|
|
406
|
+
const providerSessionId = safeId(input.providerSessionId);
|
|
407
|
+
const parentMessageId = safeId(input.parentMessageId);
|
|
408
|
+
const createdAt = finiteNonNegative(input.createdAt);
|
|
409
|
+
const completedAt = finiteNonNegative(input.completedAt);
|
|
410
|
+
const cursor = safeToken(input.cursor);
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
providerMessageId,
|
|
414
|
+
role,
|
|
415
|
+
...(providerSessionId === undefined ? {} : { providerSessionId }),
|
|
416
|
+
...(parentMessageId === undefined ? {} : { parentMessageId }),
|
|
417
|
+
...(model === undefined ? {} : { model }),
|
|
418
|
+
...(createdAt === undefined ? {} : { createdAt }),
|
|
419
|
+
...(completedAt === undefined ? {} : { completedAt }),
|
|
420
|
+
...(usage.usage === undefined ? {} : { usage: usage.usage }),
|
|
421
|
+
usageState: usage.usageState,
|
|
422
|
+
unmappedCounters: usage.unmappedCounters,
|
|
423
|
+
text: text.state === "omitted" ? "" : text.text,
|
|
424
|
+
textState: text.state,
|
|
425
|
+
parts,
|
|
426
|
+
omissions: boundedOmissions,
|
|
427
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
interface HistorySessionRow {
|
|
432
|
+
provider: string;
|
|
433
|
+
provider_session_id: string;
|
|
434
|
+
cursor: string | null;
|
|
435
|
+
captured_at: number;
|
|
436
|
+
status: "ok" | "empty" | "error";
|
|
437
|
+
error: string | null;
|
|
438
|
+
truncated: number;
|
|
439
|
+
created_at: number;
|
|
440
|
+
updated_at: number;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
interface HistoryRecordRow {
|
|
444
|
+
provider: string;
|
|
445
|
+
provider_session_id: string;
|
|
446
|
+
provider_message_id: string;
|
|
447
|
+
seq: number;
|
|
448
|
+
record_json: string;
|
|
449
|
+
usage_input: number | null;
|
|
450
|
+
usage_output: number | null;
|
|
451
|
+
usage_cached_input: number | null;
|
|
452
|
+
usage_cache_write: number | null;
|
|
453
|
+
usage_reasoning: number | null;
|
|
454
|
+
usage_state: "complete" | "partial" | "unknown";
|
|
455
|
+
updated_at: number;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
interface UsageTotals {
|
|
459
|
+
attempts: number;
|
|
460
|
+
input?: number;
|
|
461
|
+
output?: number;
|
|
462
|
+
cachedInput?: number;
|
|
463
|
+
cacheWrite?: number;
|
|
464
|
+
reasoning?: number;
|
|
465
|
+
state: "complete" | "partial" | "unknown";
|
|
466
|
+
/** Stored messages without any known counter. */
|
|
467
|
+
unknown: number;
|
|
468
|
+
/** Usage-bearing messages this mapping counted only partially. */
|
|
469
|
+
partial: number;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Additive tables owned by this capability. They live in the existing SQLite
|
|
474
|
+
* file so they share its transactionality and backups, while staying outside
|
|
475
|
+
* the `Store` schema version that another worker owns.
|
|
476
|
+
*/
|
|
477
|
+
const HISTORY_DDL = `
|
|
478
|
+
CREATE TABLE IF NOT EXISTS provider_history_sessions (
|
|
479
|
+
provider TEXT NOT NULL,
|
|
480
|
+
provider_session_id TEXT NOT NULL,
|
|
481
|
+
cursor TEXT,
|
|
482
|
+
captured_at INTEGER NOT NULL,
|
|
483
|
+
status TEXT NOT NULL,
|
|
484
|
+
error TEXT,
|
|
485
|
+
truncated INTEGER NOT NULL DEFAULT 0,
|
|
486
|
+
created_at INTEGER NOT NULL,
|
|
487
|
+
updated_at INTEGER NOT NULL,
|
|
488
|
+
PRIMARY KEY (provider, provider_session_id)
|
|
489
|
+
);
|
|
490
|
+
CREATE TABLE IF NOT EXISTS provider_history_records (
|
|
491
|
+
provider TEXT NOT NULL,
|
|
492
|
+
provider_session_id TEXT NOT NULL,
|
|
493
|
+
provider_message_id TEXT NOT NULL,
|
|
494
|
+
seq INTEGER NOT NULL,
|
|
495
|
+
record_json TEXT NOT NULL,
|
|
496
|
+
usage_input INTEGER,
|
|
497
|
+
usage_output INTEGER,
|
|
498
|
+
usage_cached_input INTEGER,
|
|
499
|
+
usage_cache_write INTEGER,
|
|
500
|
+
usage_reasoning INTEGER,
|
|
501
|
+
usage_state TEXT NOT NULL,
|
|
502
|
+
updated_at INTEGER NOT NULL,
|
|
503
|
+
PRIMARY KEY (provider, provider_session_id, provider_message_id)
|
|
504
|
+
);
|
|
505
|
+
CREATE INDEX IF NOT EXISTS provider_history_records_page_idx
|
|
506
|
+
ON provider_history_records (provider, provider_session_id, seq);
|
|
507
|
+
`;
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Durable, provider-neutral history store. Construct it with an open `Store`
|
|
511
|
+
* (or with the result of `openHistoryStore` in a read-only tool).
|
|
512
|
+
*/
|
|
513
|
+
export class HistoryStore {
|
|
514
|
+
private readonly db: Database;
|
|
515
|
+
private readonly options: HistoryStoreOptions;
|
|
516
|
+
|
|
517
|
+
constructor(store: Store, options: HistoryStoreOptions = {}) {
|
|
518
|
+
const db = (store as unknown as { db?: Database }).db;
|
|
519
|
+
if (!db) {
|
|
520
|
+
throw new AgentFlowError(
|
|
521
|
+
"validation",
|
|
522
|
+
"history storage needs an open AgentFlow store",
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
this.db = db;
|
|
526
|
+
this.options = options;
|
|
527
|
+
this.db.exec(HISTORY_DDL);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
private now(): number {
|
|
531
|
+
return this.options.now?.() ?? Date.now();
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
private maxRecords(): number {
|
|
535
|
+
return Math.max(
|
|
536
|
+
1,
|
|
537
|
+
Math.floor(this.options.maxRecords ?? HISTORY_DEFAULT_MAX_RECORDS),
|
|
538
|
+
);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private pageSize(): number {
|
|
542
|
+
return Math.max(
|
|
543
|
+
1,
|
|
544
|
+
Math.min(
|
|
545
|
+
Math.floor(this.options.maxPageSize ?? HISTORY_MAX_PAGE_SIZE),
|
|
546
|
+
HISTORY_MAX_PAGE_SIZE,
|
|
547
|
+
),
|
|
548
|
+
);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Upsert one normalized page inside a single transaction. A provider failure
|
|
553
|
+
* is recorded as `error` and writes no records, so an outage never looks like
|
|
554
|
+
* an empty history.
|
|
555
|
+
*/
|
|
556
|
+
ingestPage(input: HistoryIngestInput): HistoryIngestResult {
|
|
557
|
+
const provider = safeId(input.provider);
|
|
558
|
+
const providerSessionId = safeId(input.providerSessionId);
|
|
559
|
+
if (!provider || !providerSessionId || !isPaging(input.paging)) {
|
|
560
|
+
throw new AgentFlowError(
|
|
561
|
+
"validation",
|
|
562
|
+
"history page needs a provider, a provider session id and a valid paging mode",
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const now = this.now();
|
|
566
|
+
const capturedAt = finiteNonNegative(input.capturedAt) ?? now;
|
|
567
|
+
const maxError = Math.max(
|
|
568
|
+
16,
|
|
569
|
+
Math.floor(this.options.maxErrorLength ?? 300),
|
|
570
|
+
);
|
|
571
|
+
const error = safeErrorSummary(input.error, maxError);
|
|
572
|
+
const notice = safeErrorSummary(input.notice, maxError);
|
|
573
|
+
const cursor = safeToken(input.cursor);
|
|
574
|
+
const nextCursor = safeToken(input.nextCursor);
|
|
575
|
+
|
|
576
|
+
// A provider sweep (no cursor supplied) starts a fresh walk: older rows that
|
|
577
|
+
// its bounded prefix no longer covers are evicted rather than mixed with rows
|
|
578
|
+
// from earlier sweeps. Pages are always applied newest-last.
|
|
579
|
+
const sweep = cursor === undefined;
|
|
580
|
+
|
|
581
|
+
const accepted: HistoryRecord[] = [];
|
|
582
|
+
let rejected = 0;
|
|
583
|
+
for (const record of input.records) {
|
|
584
|
+
const normalized = normalizeHistoryRecord(record, this.options);
|
|
585
|
+
if (!normalized) {
|
|
586
|
+
rejected += 1;
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
accepted.push({
|
|
590
|
+
...normalized,
|
|
591
|
+
providerSessionId: normalized.providerSessionId ?? providerSessionId,
|
|
592
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
// A page is bounded exactly like the stored history: the newest records up
|
|
596
|
+
// to the budget win. Keeping only the oldest `pageSize` would pin the store
|
|
597
|
+
// to a prefix, so the excess is counted as pruned and the view becomes
|
|
598
|
+
// explicitly truncated instead of silently dropping the newest messages.
|
|
599
|
+
const acceptedCap = Math.min(this.pageSize(), this.maxRecords());
|
|
600
|
+
let pruned = 0;
|
|
601
|
+
if (accepted.length > acceptedCap) {
|
|
602
|
+
pruned = accepted.length - acceptedCap;
|
|
603
|
+
accepted.splice(0, pruned);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
return this.db.transaction(() => {
|
|
607
|
+
if (error !== undefined) {
|
|
608
|
+
// Keep the previous records and cursor untouched; only the status moves.
|
|
609
|
+
this.upsertSession({
|
|
610
|
+
provider,
|
|
611
|
+
providerSessionId,
|
|
612
|
+
cursor,
|
|
613
|
+
capturedAt,
|
|
614
|
+
status: "error",
|
|
615
|
+
error,
|
|
616
|
+
truncated: this.isTruncated(provider, providerSessionId),
|
|
617
|
+
now,
|
|
618
|
+
});
|
|
619
|
+
const totals = this.usageTotals(provider, providerSessionId);
|
|
620
|
+
return {
|
|
621
|
+
providerSessionId,
|
|
622
|
+
inserted: 0,
|
|
623
|
+
updated: 0,
|
|
624
|
+
unchanged: 0,
|
|
625
|
+
rejected,
|
|
626
|
+
pruned: 0,
|
|
627
|
+
paging: input.paging,
|
|
628
|
+
capturedAt,
|
|
629
|
+
usage: totalsOf(totals),
|
|
630
|
+
truncated: this.isTruncated(provider, providerSessionId),
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const selectExisting = this.db.query<HistoryRecordRow, SQLQueryBindings3>(
|
|
635
|
+
`SELECT * FROM provider_history_records
|
|
636
|
+
WHERE provider = ? AND provider_session_id = ? AND provider_message_id = ?`,
|
|
637
|
+
);
|
|
638
|
+
const insert = this.db.query(
|
|
639
|
+
`INSERT INTO provider_history_records
|
|
640
|
+
(provider, provider_session_id, provider_message_id, seq, record_json,
|
|
641
|
+
usage_input, usage_output, usage_cached_input, usage_cache_write,
|
|
642
|
+
usage_reasoning, usage_state, updated_at)
|
|
643
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
644
|
+
);
|
|
645
|
+
const update = this.db.query(
|
|
646
|
+
`UPDATE provider_history_records
|
|
647
|
+
SET record_json = ?, usage_input = ?, usage_output = ?, usage_cached_input = ?,
|
|
648
|
+
usage_cache_write = ?, usage_reasoning = ?, usage_state = ?, updated_at = ?
|
|
649
|
+
WHERE provider = ? AND provider_session_id = ? AND provider_message_id = ?`,
|
|
650
|
+
);
|
|
651
|
+
|
|
652
|
+
if (sweep && input.paging !== "complete") {
|
|
653
|
+
// Without paging metadata or a start cursor the sweep is one bounded
|
|
654
|
+
// page, so rows from earlier sweeps are dropped; the count is reported.
|
|
655
|
+
pruned += this.countRecords(provider, providerSessionId);
|
|
656
|
+
if (pruned > 0)
|
|
657
|
+
this.db
|
|
658
|
+
.query(
|
|
659
|
+
"DELETE FROM provider_history_records WHERE provider = ? AND provider_session_id = ?",
|
|
660
|
+
)
|
|
661
|
+
.run(provider, providerSessionId);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const counts = { inserted: 0, updated: 0, unchanged: 0 };
|
|
665
|
+
let seq = this.nextSeq(provider, providerSessionId);
|
|
666
|
+
for (const record of accepted) {
|
|
667
|
+
const json = toJson(record);
|
|
668
|
+
const usageValues = [
|
|
669
|
+
record.usage?.input ?? null,
|
|
670
|
+
record.usage?.output ?? null,
|
|
671
|
+
record.usage?.cachedInput ?? null,
|
|
672
|
+
record.usage?.cacheWrite ?? null,
|
|
673
|
+
record.usage?.reasoning ?? null,
|
|
674
|
+
record.usageState,
|
|
675
|
+
] as const;
|
|
676
|
+
const existing = selectExisting.get(
|
|
677
|
+
provider,
|
|
678
|
+
providerSessionId,
|
|
679
|
+
record.providerMessageId,
|
|
680
|
+
);
|
|
681
|
+
// A replayed page is identical, so it must not disturb order or usage.
|
|
682
|
+
if (existing && existing.record_json === json) {
|
|
683
|
+
counts.unchanged += 1;
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (existing) {
|
|
687
|
+
update.run(
|
|
688
|
+
json,
|
|
689
|
+
...usageValues,
|
|
690
|
+
now,
|
|
691
|
+
provider,
|
|
692
|
+
providerSessionId,
|
|
693
|
+
record.providerMessageId,
|
|
694
|
+
);
|
|
695
|
+
counts.updated += 1;
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
seq += 1;
|
|
699
|
+
insert.run(
|
|
700
|
+
provider,
|
|
701
|
+
providerSessionId,
|
|
702
|
+
record.providerMessageId,
|
|
703
|
+
seq,
|
|
704
|
+
json,
|
|
705
|
+
...usageValues,
|
|
706
|
+
now,
|
|
707
|
+
);
|
|
708
|
+
counts.inserted += 1;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Bound the stored history to the newest records.
|
|
712
|
+
const budget = this.maxRecords();
|
|
713
|
+
const stored = this.countRecords(provider, providerSessionId);
|
|
714
|
+
// Whether a later page already overflowed the budget or could not page.
|
|
715
|
+
let reachedBudget = this.isTruncated(provider, providerSessionId);
|
|
716
|
+
if (stored > budget) {
|
|
717
|
+
const excess = stored - budget;
|
|
718
|
+
this.db
|
|
719
|
+
.query(
|
|
720
|
+
`DELETE FROM provider_history_records
|
|
721
|
+
WHERE rowid IN (
|
|
722
|
+
SELECT rowid FROM provider_history_records
|
|
723
|
+
WHERE provider = ? AND provider_session_id = ?
|
|
724
|
+
ORDER BY seq ASC LIMIT ?
|
|
725
|
+
)`,
|
|
726
|
+
)
|
|
727
|
+
.run(provider, providerSessionId, excess);
|
|
728
|
+
pruned += excess;
|
|
729
|
+
reachedBudget = true;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
const remaining = this.countRecords(provider, providerSessionId);
|
|
733
|
+
// Dropped messages, an earlier eviction or incomplete paging mean this view
|
|
734
|
+
// is a bounded part of the transcript, never the whole transcript.
|
|
735
|
+
const truncated =
|
|
736
|
+
pruned > 0 || input.paging !== "complete" || reachedBudget;
|
|
737
|
+
this.upsertSession({
|
|
738
|
+
provider,
|
|
739
|
+
providerSessionId,
|
|
740
|
+
cursor,
|
|
741
|
+
capturedAt,
|
|
742
|
+
status: remaining === 0 ? "empty" : "ok",
|
|
743
|
+
error: notice,
|
|
744
|
+
truncated,
|
|
745
|
+
now,
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
return {
|
|
749
|
+
providerSessionId,
|
|
750
|
+
...counts,
|
|
751
|
+
rejected,
|
|
752
|
+
pruned,
|
|
753
|
+
...(input.paging === "complete" && nextCursor !== undefined
|
|
754
|
+
? { nextCursor }
|
|
755
|
+
: {}),
|
|
756
|
+
paging: input.paging,
|
|
757
|
+
capturedAt,
|
|
758
|
+
usage: totalsOf(this.usageTotals(provider, providerSessionId)),
|
|
759
|
+
truncated,
|
|
760
|
+
};
|
|
761
|
+
})();
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** Newest safe view for offline inspection; `undefined` when nothing was stored. */
|
|
765
|
+
snapshot(
|
|
766
|
+
provider: string,
|
|
767
|
+
providerSessionId: string,
|
|
768
|
+
): HistorySnapshot | undefined {
|
|
769
|
+
const row = this.db
|
|
770
|
+
.query<HistorySessionRow, SQLQueryBindings2>(
|
|
771
|
+
`SELECT * FROM provider_history_sessions
|
|
772
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
773
|
+
)
|
|
774
|
+
.get(provider, providerSessionId);
|
|
775
|
+
if (!row) return undefined;
|
|
776
|
+
const records = this.db
|
|
777
|
+
.query<HistoryRecordRow, SQLQueryBindings2>(
|
|
778
|
+
`SELECT * FROM provider_history_records
|
|
779
|
+
WHERE provider = ? AND provider_session_id = ?
|
|
780
|
+
ORDER BY seq ASC`,
|
|
781
|
+
)
|
|
782
|
+
.all(provider, providerSessionId)
|
|
783
|
+
.map((entry) => fromJson<HistoryRecord | null>(entry.record_json, null))
|
|
784
|
+
.filter((entry): entry is HistoryRecord => entry !== null);
|
|
785
|
+
return {
|
|
786
|
+
provider: row.provider,
|
|
787
|
+
providerSessionId: row.provider_session_id,
|
|
788
|
+
...(row.cursor === null ? {} : { cursor: row.cursor }),
|
|
789
|
+
capturedAt: row.captured_at,
|
|
790
|
+
status: row.status,
|
|
791
|
+
...(row.error === null ? {} : { error: row.error }),
|
|
792
|
+
truncated: row.truncated === 1,
|
|
793
|
+
total: records.length,
|
|
794
|
+
records,
|
|
795
|
+
usage: totalsOf(this.usageTotals(provider, providerSessionId)),
|
|
796
|
+
createdAt: row.created_at,
|
|
797
|
+
updatedAt: row.updated_at,
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** Keyset page over the stored records, bounded by `limit` (max 500). */
|
|
802
|
+
page(
|
|
803
|
+
provider: string,
|
|
804
|
+
providerSessionId: string,
|
|
805
|
+
options: { after?: number; limit?: number } = {},
|
|
806
|
+
): HistoryPage {
|
|
807
|
+
const limit = Math.max(
|
|
808
|
+
1,
|
|
809
|
+
Math.min(
|
|
810
|
+
Math.floor(options.limit ?? HISTORY_DEFAULT_PAGE_SIZE),
|
|
811
|
+
HISTORY_MAX_PAGE_SIZE,
|
|
812
|
+
),
|
|
813
|
+
);
|
|
814
|
+
const after = Math.max(0, Math.floor(options.after ?? 0));
|
|
815
|
+
const rows = this.db
|
|
816
|
+
.query<HistoryRecordRow, SQLQueryBindings4>(
|
|
817
|
+
`SELECT * FROM provider_history_records
|
|
818
|
+
WHERE provider = ? AND provider_session_id = ? AND seq > ?
|
|
819
|
+
ORDER BY seq ASC LIMIT ?`,
|
|
820
|
+
)
|
|
821
|
+
.all(provider, providerSessionId, after, limit + 1);
|
|
822
|
+
const page = rows.slice(0, limit);
|
|
823
|
+
const records = page
|
|
824
|
+
.map((entry) => fromJson<HistoryRecord | null>(entry.record_json, null))
|
|
825
|
+
.filter((entry): entry is HistoryRecord => entry !== null);
|
|
826
|
+
return {
|
|
827
|
+
records,
|
|
828
|
+
...(rows.length > limit
|
|
829
|
+
? { nextCursor: page[page.length - 1]!.seq }
|
|
830
|
+
: {}),
|
|
831
|
+
highWater: this.nextSeq(provider, providerSessionId),
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* `true` when at least one stored message cannot be shown in full: truncated,
|
|
837
|
+
* redacted or explicitly omitted text, tool activity or whole message.
|
|
838
|
+
*/
|
|
839
|
+
hasOmissions(provider: string, providerSessionId: string): boolean {
|
|
840
|
+
const rows = this.db
|
|
841
|
+
.query<HistoryRecordRow, SQLQueryBindings2>(
|
|
842
|
+
`SELECT * FROM provider_history_records
|
|
843
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
844
|
+
)
|
|
845
|
+
.all(provider, providerSessionId);
|
|
846
|
+
return rows.some((entry) => {
|
|
847
|
+
const record = fromJson<HistoryRecord | null>(entry.record_json, null);
|
|
848
|
+
// An unreadable stored record is reported as an omission, not as success.
|
|
849
|
+
if (!record) return true;
|
|
850
|
+
return (
|
|
851
|
+
record.textState !== "complete" ||
|
|
852
|
+
record.omissions.length > 0 ||
|
|
853
|
+
record.parts.some(
|
|
854
|
+
(part) =>
|
|
855
|
+
part.state === "truncated" ||
|
|
856
|
+
part.state === "redacted" ||
|
|
857
|
+
part.state === "unsupported",
|
|
858
|
+
)
|
|
859
|
+
);
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
private countRecords(provider: string, providerSessionId: string): number {
|
|
864
|
+
const row = this.db
|
|
865
|
+
.query<{ count: number }, SQLQueryBindings2>(
|
|
866
|
+
`SELECT COUNT(*) AS count FROM provider_history_records
|
|
867
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
868
|
+
)
|
|
869
|
+
.get(provider, providerSessionId);
|
|
870
|
+
return row?.count ?? 0;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
private nextSeq(provider: string, providerSessionId: string): number {
|
|
874
|
+
const row = this.db
|
|
875
|
+
.query<{ seq: number | null }, SQLQueryBindings2>(
|
|
876
|
+
`SELECT MAX(seq) AS seq FROM provider_history_records
|
|
877
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
878
|
+
)
|
|
879
|
+
.get(provider, providerSessionId);
|
|
880
|
+
return row?.seq ?? 0;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
private isTruncated(provider: string, providerSessionId: string): boolean {
|
|
884
|
+
const row = this.db
|
|
885
|
+
.query<{ truncated: number }, SQLQueryBindings2>(
|
|
886
|
+
`SELECT truncated FROM provider_history_sessions
|
|
887
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
888
|
+
)
|
|
889
|
+
.get(provider, providerSessionId);
|
|
890
|
+
return row?.truncated === 1;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Aggregate counters once per stored message id. Counters are summed only
|
|
895
|
+
* when reported, so a counter nobody reported stays absent, not zero.
|
|
896
|
+
*/
|
|
897
|
+
private usageTotals(
|
|
898
|
+
provider: string,
|
|
899
|
+
providerSessionId: string,
|
|
900
|
+
): UsageTotals {
|
|
901
|
+
const totals: UsageTotals = {
|
|
902
|
+
attempts: 0,
|
|
903
|
+
state: "unknown",
|
|
904
|
+
unknown: 0,
|
|
905
|
+
partial: 0,
|
|
906
|
+
};
|
|
907
|
+
const rows = this.db
|
|
908
|
+
.query<
|
|
909
|
+
{
|
|
910
|
+
usage_input: number | null;
|
|
911
|
+
usage_output: number | null;
|
|
912
|
+
usage_cached_input: number | null;
|
|
913
|
+
usage_cache_write: number | null;
|
|
914
|
+
usage_reasoning: number | null;
|
|
915
|
+
usage_state: "complete" | "partial" | "unknown";
|
|
916
|
+
},
|
|
917
|
+
SQLQueryBindings2
|
|
918
|
+
>(
|
|
919
|
+
`SELECT usage_input, usage_output, usage_cached_input, usage_cache_write,
|
|
920
|
+
usage_reasoning, usage_state
|
|
921
|
+
FROM provider_history_records
|
|
922
|
+
WHERE provider = ? AND provider_session_id = ?`,
|
|
923
|
+
)
|
|
924
|
+
.all(provider, providerSessionId);
|
|
925
|
+
for (const row of rows) {
|
|
926
|
+
if (row.usage_state === "unknown") {
|
|
927
|
+
totals.unknown += 1;
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
930
|
+
totals.attempts += 1;
|
|
931
|
+
if (row.usage_state === "partial") totals.partial += 1;
|
|
932
|
+
const values = {
|
|
933
|
+
input: row.usage_input,
|
|
934
|
+
output: row.usage_output,
|
|
935
|
+
cachedInput: row.usage_cached_input,
|
|
936
|
+
cacheWrite: row.usage_cache_write,
|
|
937
|
+
reasoning: row.usage_reasoning,
|
|
938
|
+
} as const;
|
|
939
|
+
for (const key of USAGE_KEYS) {
|
|
940
|
+
const value = values[key];
|
|
941
|
+
if (value === null) continue;
|
|
942
|
+
totals[key] = (totals[key] ?? 0) + value;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
totals.state =
|
|
946
|
+
totals.attempts === 0
|
|
947
|
+
? "unknown"
|
|
948
|
+
: totals.partial > 0 || totals.unknown > 0
|
|
949
|
+
? "partial"
|
|
950
|
+
: "complete";
|
|
951
|
+
return totals;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
private upsertSession(input: {
|
|
955
|
+
provider: string;
|
|
956
|
+
providerSessionId: string;
|
|
957
|
+
cursor: string | undefined;
|
|
958
|
+
capturedAt: number;
|
|
959
|
+
status: "ok" | "empty" | "error";
|
|
960
|
+
error: string | undefined;
|
|
961
|
+
truncated: boolean;
|
|
962
|
+
now: number;
|
|
963
|
+
}): void {
|
|
964
|
+
this.db
|
|
965
|
+
.query(
|
|
966
|
+
`INSERT INTO provider_history_sessions
|
|
967
|
+
(provider, provider_session_id, cursor, captured_at, status, error,
|
|
968
|
+
truncated, created_at, updated_at)
|
|
969
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
970
|
+
ON CONFLICT (provider, provider_session_id) DO UPDATE SET
|
|
971
|
+
cursor = COALESCE(excluded.cursor, provider_history_sessions.cursor),
|
|
972
|
+
captured_at = MAX(excluded.captured_at, provider_history_sessions.captured_at),
|
|
973
|
+
status = excluded.status,
|
|
974
|
+
error = excluded.error,
|
|
975
|
+
truncated = excluded.truncated,
|
|
976
|
+
updated_at = excluded.updated_at`,
|
|
977
|
+
)
|
|
978
|
+
.run(
|
|
979
|
+
input.provider,
|
|
980
|
+
input.providerSessionId,
|
|
981
|
+
input.cursor ?? null,
|
|
982
|
+
input.capturedAt,
|
|
983
|
+
input.status,
|
|
984
|
+
input.error ?? null,
|
|
985
|
+
input.truncated ? 1 : 0,
|
|
986
|
+
input.now,
|
|
987
|
+
input.now,
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
type SQLQueryBindings2 = [string, string];
|
|
993
|
+
type SQLQueryBindings3 = [string, string, string];
|
|
994
|
+
type SQLQueryBindings4 = [string, string, number, number];
|
|
995
|
+
|
|
996
|
+
function totalsOf(totals: UsageTotals): HistorySnapshot["usage"] {
|
|
997
|
+
return {
|
|
998
|
+
attempts: totals.attempts,
|
|
999
|
+
state: totals.state,
|
|
1000
|
+
...(totals.input === undefined ? {} : { input: totals.input }),
|
|
1001
|
+
...(totals.output === undefined ? {} : { output: totals.output }),
|
|
1002
|
+
...(totals.cachedInput === undefined
|
|
1003
|
+
? {}
|
|
1004
|
+
: { cachedInput: totals.cachedInput }),
|
|
1005
|
+
...(totals.cacheWrite === undefined
|
|
1006
|
+
? {}
|
|
1007
|
+
: { cacheWrite: totals.cacheWrite }),
|
|
1008
|
+
...(totals.reasoning === undefined ? {} : { reasoning: totals.reasoning }),
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// --------------------------------------------------------- capability bridge
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* The slice of a provider adapter that can read visible history. It is optional
|
|
1016
|
+
* on every adapter: one without it reports `unsupported` rather than an empty
|
|
1017
|
+
* transcript. `read` must not send a prompt, so reconciliation is safe while an
|
|
1018
|
+
* attempt is idle or its owner is reclaiming it.
|
|
1019
|
+
*/
|
|
1020
|
+
export interface HistoryCapability {
|
|
1021
|
+
read(request: {
|
|
1022
|
+
sessionId: string;
|
|
1023
|
+
cursor?: string;
|
|
1024
|
+
limit?: number;
|
|
1025
|
+
signal?: AbortSignal;
|
|
1026
|
+
}): Promise<CapabilityHistoryPage>;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
export interface CapabilityHistoryPage {
|
|
1030
|
+
records: readonly HistoryRecord[];
|
|
1031
|
+
nextCursor?: string;
|
|
1032
|
+
paging: "complete" | "unknown" | "unsupported";
|
|
1033
|
+
capturedAt?: number;
|
|
1034
|
+
/** Set instead of throwing when the caller wants the failure stored. */
|
|
1035
|
+
error?: string;
|
|
1036
|
+
/** Non-fatal notice, for example that only the last page could be read. */
|
|
1037
|
+
notice?: string;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
export interface HistoryReadOptions {
|
|
1041
|
+
/** Adapter id persisted as `provider`; defaults to the adapter's `id`. */
|
|
1042
|
+
provider?: string;
|
|
1043
|
+
/** Provider session id; the engine already persists it on the agent row. */
|
|
1044
|
+
sessionId: string;
|
|
1045
|
+
/** Durable cursor to resume from; read from the snapshot when omitted. */
|
|
1046
|
+
cursor?: string;
|
|
1047
|
+
limit?: number;
|
|
1048
|
+
/** Maximum pages walked in one call. Default 4. */
|
|
1049
|
+
maxPages?: number;
|
|
1050
|
+
signal?: AbortSignal;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
export interface HistoryReadResult {
|
|
1054
|
+
provider: string;
|
|
1055
|
+
providerSessionId: string;
|
|
1056
|
+
/** `unsupported`/`disabled` mean nothing was read and nothing was written. */
|
|
1057
|
+
state: "ok" | "error" | "unsupported" | "disabled";
|
|
1058
|
+
pages: number;
|
|
1059
|
+
result?: HistoryIngestResult;
|
|
1060
|
+
snapshot?: HistorySnapshot;
|
|
1061
|
+
reason?: string;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/**
|
|
1065
|
+
* Resolve the optional capability from an adapter. A direct `history` property
|
|
1066
|
+
* or a `createHistory()` factory are both accepted, so an adapter can build it
|
|
1067
|
+
* lazily. A missing capability, or the literal `"disabled"`, is a supported
|
|
1068
|
+
* state and never an error.
|
|
1069
|
+
*/
|
|
1070
|
+
export function resolveHistoryCapability(
|
|
1071
|
+
adapter: unknown,
|
|
1072
|
+
):
|
|
1073
|
+
| { state: "ok"; capability: HistoryCapability }
|
|
1074
|
+
| { state: "unsupported" | "disabled"; reason: string } {
|
|
1075
|
+
if (typeof adapter !== "object" || adapter === null) {
|
|
1076
|
+
return { state: "unsupported", reason: "adapter is not object-like" };
|
|
1077
|
+
}
|
|
1078
|
+
const candidate = adapter as { history?: unknown; createHistory?: unknown };
|
|
1079
|
+
const disabled = () => ({
|
|
1080
|
+
state: "disabled" as const,
|
|
1081
|
+
reason: "provider disabled history",
|
|
1082
|
+
});
|
|
1083
|
+
if (candidate.history === "disabled") return disabled();
|
|
1084
|
+
let capability = candidate.history;
|
|
1085
|
+
if (
|
|
1086
|
+
capability === undefined &&
|
|
1087
|
+
typeof candidate.createHistory === "function"
|
|
1088
|
+
) {
|
|
1089
|
+
try {
|
|
1090
|
+
capability = (candidate.createHistory as () => unknown)();
|
|
1091
|
+
} catch {
|
|
1092
|
+
return {
|
|
1093
|
+
state: "unsupported",
|
|
1094
|
+
reason: "history capability failed to initialize",
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
if (capability === undefined || capability === null) {
|
|
1099
|
+
return {
|
|
1100
|
+
state: "unsupported",
|
|
1101
|
+
reason: "provider has no history capability",
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
if (capability === "disabled") return disabled();
|
|
1105
|
+
if (typeof capability !== "object") {
|
|
1106
|
+
return { state: "unsupported", reason: "history capability is malformed" };
|
|
1107
|
+
}
|
|
1108
|
+
if (typeof (capability as { read?: unknown }).read !== "function") {
|
|
1109
|
+
return { state: "unsupported", reason: "history capability has no read" };
|
|
1110
|
+
}
|
|
1111
|
+
return { state: "ok", capability: capability as HistoryCapability };
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
function providerIdOf(adapter: unknown): string | undefined {
|
|
1115
|
+
return typeof adapter === "object" && adapter !== null
|
|
1116
|
+
? safeId((adapter as { id?: unknown }).id)
|
|
1117
|
+
: undefined;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* Walk a provider's history through its optional capability and upsert every
|
|
1122
|
+
* page. Read-only: no prompt is sent. A capability failure is stored as an
|
|
1123
|
+
* `error` snapshot with the previous records and cursor intact.
|
|
1124
|
+
*/
|
|
1125
|
+
export async function readProviderHistory(
|
|
1126
|
+
adapter: unknown,
|
|
1127
|
+
store: HistoryStore,
|
|
1128
|
+
options: HistoryReadOptions,
|
|
1129
|
+
): Promise<HistoryReadResult> {
|
|
1130
|
+
const provider = safeId(options.provider) ?? providerIdOf(adapter);
|
|
1131
|
+
const providerSessionId = safeId(options.sessionId);
|
|
1132
|
+
if (!provider || !providerSessionId) {
|
|
1133
|
+
throw new AgentFlowError(
|
|
1134
|
+
"validation",
|
|
1135
|
+
"history read needs a provider id and a provider session id",
|
|
1136
|
+
);
|
|
1137
|
+
}
|
|
1138
|
+
const resolved = resolveHistoryCapability(adapter);
|
|
1139
|
+
if (resolved.state !== "ok") {
|
|
1140
|
+
return {
|
|
1141
|
+
provider,
|
|
1142
|
+
providerSessionId,
|
|
1143
|
+
state: resolved.state,
|
|
1144
|
+
pages: 0,
|
|
1145
|
+
reason: resolved.reason,
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const maxPages = Math.max(1, Math.floor(options.maxPages ?? 4));
|
|
1150
|
+
const limit = Math.max(
|
|
1151
|
+
1,
|
|
1152
|
+
Math.min(
|
|
1153
|
+
Math.floor(options.limit ?? HISTORY_DEFAULT_PAGE_SIZE),
|
|
1154
|
+
HISTORY_MAX_PAGE_SIZE,
|
|
1155
|
+
),
|
|
1156
|
+
);
|
|
1157
|
+
let cursor =
|
|
1158
|
+
safeToken(options.cursor) ??
|
|
1159
|
+
store.snapshot(provider, providerSessionId)?.cursor;
|
|
1160
|
+
const seen = new Set<string>();
|
|
1161
|
+
let pages = 0;
|
|
1162
|
+
let last: HistoryIngestResult | undefined;
|
|
1163
|
+
|
|
1164
|
+
while (pages < maxPages) {
|
|
1165
|
+
if (cursor !== undefined) {
|
|
1166
|
+
// A provider repeating a cursor would loop forever; stop explicitly.
|
|
1167
|
+
if (seen.has(cursor)) break;
|
|
1168
|
+
seen.add(cursor);
|
|
1169
|
+
}
|
|
1170
|
+
let page: CapabilityHistoryPage;
|
|
1171
|
+
try {
|
|
1172
|
+
page = await resolved.capability.read({
|
|
1173
|
+
sessionId: providerSessionId,
|
|
1174
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
1175
|
+
limit,
|
|
1176
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
1177
|
+
});
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
const reason = capacityFailure(error);
|
|
1180
|
+
last = store.ingestPage({
|
|
1181
|
+
provider,
|
|
1182
|
+
providerSessionId,
|
|
1183
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
1184
|
+
paging: "unknown",
|
|
1185
|
+
records: [],
|
|
1186
|
+
error: reason,
|
|
1187
|
+
});
|
|
1188
|
+
pages += 1;
|
|
1189
|
+
return {
|
|
1190
|
+
provider,
|
|
1191
|
+
providerSessionId,
|
|
1192
|
+
state: "error",
|
|
1193
|
+
pages,
|
|
1194
|
+
result: last,
|
|
1195
|
+
snapshot: store.snapshot(provider, providerSessionId),
|
|
1196
|
+
reason,
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
pages += 1;
|
|
1201
|
+
last = store.ingestPage({
|
|
1202
|
+
provider,
|
|
1203
|
+
providerSessionId,
|
|
1204
|
+
...(cursor === undefined ? {} : { cursor }),
|
|
1205
|
+
...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }),
|
|
1206
|
+
...(page.capturedAt === undefined ? {} : { capturedAt: page.capturedAt }),
|
|
1207
|
+
paging: page.paging,
|
|
1208
|
+
records: page.records,
|
|
1209
|
+
...(page.notice === undefined ? {} : { notice: page.notice }),
|
|
1210
|
+
...(page.error === undefined ? {} : { error: page.error }),
|
|
1211
|
+
});
|
|
1212
|
+
if (page.error !== undefined) {
|
|
1213
|
+
return {
|
|
1214
|
+
provider,
|
|
1215
|
+
providerSessionId,
|
|
1216
|
+
state: "error",
|
|
1217
|
+
pages,
|
|
1218
|
+
result: last,
|
|
1219
|
+
snapshot: store.snapshot(provider, providerSessionId),
|
|
1220
|
+
reason: safeErrorSummary(page.error, 300),
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
if (last.nextCursor === undefined) break;
|
|
1224
|
+
cursor = last.nextCursor;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
return {
|
|
1228
|
+
provider,
|
|
1229
|
+
providerSessionId,
|
|
1230
|
+
state: "ok",
|
|
1231
|
+
pages,
|
|
1232
|
+
...(last === undefined ? {} : { result: last }),
|
|
1233
|
+
snapshot: store.snapshot(provider, providerSessionId),
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Record that history collection was turned off for a session. The snapshot
|
|
1239
|
+
* stays explicitly `disabled`-flagged through its notice so it never reads as
|
|
1240
|
+
* "provider returned nothing".
|
|
1241
|
+
*/
|
|
1242
|
+
export function recordHistoryDisabled(
|
|
1243
|
+
store: HistoryStore,
|
|
1244
|
+
provider: string,
|
|
1245
|
+
providerSessionId: string,
|
|
1246
|
+
reason = "history disabled by configuration",
|
|
1247
|
+
): HistorySnapshot | undefined {
|
|
1248
|
+
store.ingestPage({
|
|
1249
|
+
provider,
|
|
1250
|
+
providerSessionId,
|
|
1251
|
+
paging: "unknown",
|
|
1252
|
+
records: [],
|
|
1253
|
+
notice: `disabled: ${reason}`,
|
|
1254
|
+
});
|
|
1255
|
+
return store.snapshot(provider, providerSessionId);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
function capacityFailure(error: unknown): string {
|
|
1259
|
+
if (error instanceof Error && error.message.trim() !== "") {
|
|
1260
|
+
return (
|
|
1261
|
+
safeErrorSummary(error.message, 300) ?? "provider history read failed"
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
if (typeof error === "string" && error.trim() !== "") {
|
|
1265
|
+
return safeErrorSummary(error, 300) ?? "provider history read failed";
|
|
1266
|
+
}
|
|
1267
|
+
return "provider history read failed";
|
|
1268
|
+
}
|