@senselab-ai/amfs 0.3.1 → 0.4.5

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/dist/replay.js ADDED
@@ -0,0 +1,514 @@
1
+ /**
2
+ * Answer a replay request: the customer's end of the repair loop's Tier 2.
3
+ *
4
+ * When SenseLab has drafted a fix for one of your agent's behaviours and wants
5
+ * proof from *your* agent before it ships, it sends one signed webhook per
6
+ * test case:
7
+ *
8
+ * POST <your replay URL>
9
+ * X-AMFS-Event: replay_requested
10
+ * X-AMFS-Delivery: <uuid, unique per request>
11
+ * X-AMFS-Signature: sha256=<hex HMAC-SHA256(secret, raw body)>
12
+ *
13
+ * {"event": "replay_requested", "fix_id": ..., "agent_id": ..., "branch":
14
+ * "repair/<fix-id>", "case_id": ..., "task_input": ..., "expected": {...},
15
+ * "deadline_at": ..., ...}
16
+ *
17
+ * Your side has three obligations, and this module discharges all of them:
18
+ *
19
+ * 1. verify the signature over the raw body ({@link verifyReplaySignature});
20
+ * 2. run the agent on `task_input` with its memory on `branch` — the branch
21
+ * holds the fix; a run on `main` never read it and proves nothing;
22
+ * 3. commit the outcome with `attributes.case_id` and
23
+ * `attributes.memory_branch` so the grader can find the trace.
24
+ *
25
+ * The sender waits ten seconds and retries a non-2xx a bounded number of
26
+ * times, so the receiver acknowledges with `202` at once and runs the agent
27
+ * afterwards; delivery is at-least-once, so a delivery id seen before is
28
+ * acknowledged again without a second run. A `ping` event is answered `200`.
29
+ *
30
+ * Runtime-agnostic, like the rest of the SDK: signatures use Web Crypto, so
31
+ * the receiver runs on Node 18+, Bun, Deno and edge runtimes alike.
32
+ * {@link ReplayReceiver.handle} takes headers and the raw body and returns a
33
+ * status and a JSON body, so it mounts in Express, Fastify or anything else;
34
+ * {@link createFetchHandler} wraps it as a `(Request) => Response` for
35
+ * Next.js route handlers, Hono, Bun and workers; {@link serveReplay} starts a
36
+ * `node:http` server around it.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const receiver = new ReplayReceiver({
41
+ * secret: process.env.AMFS_REPLAY_SECRET!,
42
+ * memoryFactory: (req) => new AgentMemory(req.agentId, { adapter: http, branch: req.branch }),
43
+ * run: async (taskInput, memory) => myAgent.answer(taskInput, memory),
44
+ * });
45
+ * app.post("/amfs/replay", express.raw({ type: "*\/*" }), async (req, res) => {
46
+ * const { status, body } = await receiver.handle(req.headers, req.body);
47
+ * res.status(status).json(body);
48
+ * });
49
+ * ```
50
+ */
51
+ import { OutcomeType } from "./models.js";
52
+ import { MEMORY_BRANCH_ATTRIBUTE } from "./memory.js";
53
+ import { SDK_STAMPED_ATTRIBUTES, SESSION_ATTRIBUTES_MAX_KEYS } from "./session.js";
54
+ export const SIGNATURE_HEADER = "X-AMFS-Signature";
55
+ export const EVENT_HEADER = "X-AMFS-Event";
56
+ export const DELIVERY_HEADER = "X-AMFS-Delivery";
57
+ export const EVENT_REPLAY_REQUESTED = "replay_requested";
58
+ export const EVENT_PING = "ping";
59
+ /** The attributes the grader reads a replayed trace through. */
60
+ export const CASE_ID_ATTRIBUTE = "case_id";
61
+ export const FIX_ID_ATTRIBUTE = "fix_id";
62
+ export const DELIVERY_ID_ATTRIBUTE = "replay_delivery_id";
63
+ export { MEMORY_BRANCH_ATTRIBUTE };
64
+ /** How many delivery ids the receiver remembers for de-duplication. */
65
+ export const SEEN_DELIVERIES = 4096;
66
+ const encoder = new TextEncoder();
67
+ const decoder = new TextDecoder();
68
+ function toBytes(body) {
69
+ if (typeof body === "string")
70
+ return encoder.encode(body);
71
+ // A view over a plain ArrayBuffer, as Web Crypto wants; copies only when the
72
+ // source sits on a SharedArrayBuffer or is a partial view.
73
+ if (body.buffer instanceof ArrayBuffer && body.byteOffset === 0 && body.byteLength === body.buffer.byteLength) {
74
+ return body;
75
+ }
76
+ const copy = new Uint8Array(body.byteLength);
77
+ copy.set(body);
78
+ return copy;
79
+ }
80
+ async function hmacHex(secret, body) {
81
+ const subtle = globalThis.crypto?.subtle;
82
+ if (!subtle)
83
+ throw new Error("Web Crypto (crypto.subtle) is not available in this runtime");
84
+ const key = await subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
85
+ const signature = await subtle.sign("HMAC", key, toBytes(body));
86
+ return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, "0")).join("");
87
+ }
88
+ function constantTimeEqual(a, b) {
89
+ if (a.length !== b.length)
90
+ return false;
91
+ let diff = 0;
92
+ for (let i = 0; i < a.length; i++)
93
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
94
+ return diff === 0;
95
+ }
96
+ /** The `X-AMFS-Signature` value for `body`: `sha256=<hex>`. */
97
+ export async function signReplayBody(secret, body) {
98
+ return `sha256=${await hmacHex(secret, body)}`;
99
+ }
100
+ /** Whether `header` signs `body` under `secret`. Constant-time; junk is `false`. */
101
+ export async function verifyReplaySignature(secret, body, header) {
102
+ if (!header || typeof header !== "string")
103
+ return false;
104
+ const eq = header.indexOf("=");
105
+ if (eq < 0)
106
+ return false;
107
+ const scheme = header.slice(0, eq).trim().toLowerCase();
108
+ const digest = header.slice(eq + 1).trim().toLowerCase();
109
+ if (scheme !== "sha256" || !digest)
110
+ return false;
111
+ return constantTimeEqual(await hmacHex(secret, body), digest);
112
+ }
113
+ function headerOf(headers, name) {
114
+ const wanted = name.toLowerCase();
115
+ if (typeof headers.get === "function" && !(Symbol.iterator in Object(headers) && Array.isArray(headers))) {
116
+ const value = headers.get(name);
117
+ if (value != null)
118
+ return value;
119
+ }
120
+ const entries = Symbol.iterator in Object(headers) && typeof headers.get !== "function"
121
+ ? headers
122
+ : Object.entries(headers);
123
+ for (const [key, value] of entries) {
124
+ if (String(key).toLowerCase() !== wanted)
125
+ continue;
126
+ if (Array.isArray(value))
127
+ return value[0] == null ? undefined : String(value[0]);
128
+ return value == null ? undefined : String(value);
129
+ }
130
+ return undefined;
131
+ }
132
+ function parseWhen(value) {
133
+ if (typeof value !== "string" || !value)
134
+ return undefined;
135
+ const d = new Date(value);
136
+ return Number.isNaN(d.getTime()) ? undefined : d;
137
+ }
138
+ export class ReplayError extends Error {
139
+ status;
140
+ code;
141
+ constructor(status, message, code) {
142
+ super(message);
143
+ this.status = status;
144
+ this.code = code;
145
+ this.name = "ReplayError";
146
+ }
147
+ }
148
+ export class SignatureError extends ReplayError {
149
+ constructor(message = "signature missing or invalid") {
150
+ super(401, message, "bad_signature");
151
+ this.name = "SignatureError";
152
+ }
153
+ }
154
+ export class PayloadError extends ReplayError {
155
+ constructor(message) {
156
+ super(400, message, "bad_payload");
157
+ this.name = "PayloadError";
158
+ }
159
+ }
160
+ /** The outcome reference a replay commits under. */
161
+ export function replayOutcomeRef(request) {
162
+ return `replay:${request.fixId.slice(0, 8)}:${request.caseId.slice(0, 8)}`;
163
+ }
164
+ /** The session attributes the committed outcome must carry. */
165
+ export function replayAttributes(request) {
166
+ return {
167
+ [CASE_ID_ATTRIBUTE]: request.caseId,
168
+ [MEMORY_BRANCH_ATTRIBUTE]: request.branch,
169
+ [FIX_ID_ATTRIBUTE]: request.fixId,
170
+ [DELIVERY_ID_ATTRIBUTE]: request.deliveryId,
171
+ };
172
+ }
173
+ /**
174
+ * Verify and parse one delivery. Throws {@link SignatureError} when `secret`
175
+ * is set and the signature does not match, {@link PayloadError} when the body
176
+ * is not a request the receiver can act on. `secret: null` skips
177
+ * verification — for a receiver behind its own authentication and for local
178
+ * simulations.
179
+ */
180
+ export async function parseReplayRequest(headers, body, options) {
181
+ if (options.secret) {
182
+ if (!(await verifyReplaySignature(options.secret, body, headerOf(headers, SIGNATURE_HEADER)))) {
183
+ throw new SignatureError();
184
+ }
185
+ }
186
+ const text = typeof body === "string" ? body : decoder.decode(body);
187
+ let payload;
188
+ try {
189
+ payload = JSON.parse(text);
190
+ }
191
+ catch (err) {
192
+ throw new PayloadError(`body is not JSON: ${err.message}`);
193
+ }
194
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
195
+ throw new PayloadError("body must be a JSON object");
196
+ }
197
+ const p = payload;
198
+ const str = (v) => (v == null ? "" : String(v)).trim();
199
+ const event = str(p.event) || str(headerOf(headers, EVENT_HEADER));
200
+ const deliveryId = str(p.delivery_id) || str(headerOf(headers, DELIVERY_HEADER));
201
+ if (event === EVENT_PING) {
202
+ return {
203
+ event: EVENT_PING,
204
+ deliveryId,
205
+ fixId: "",
206
+ agentId: str(p.agent_id),
207
+ branch: "",
208
+ caseId: "",
209
+ taskInput: "",
210
+ expected: {},
211
+ sentAt: parseWhen(p.sent_at),
212
+ };
213
+ }
214
+ if (event !== EVENT_REPLAY_REQUESTED)
215
+ throw new PayloadError(`unknown event ${JSON.stringify(event)}`);
216
+ const missing = ["fix_id", "branch", "case_id", "task_input"].filter((k) => !str(p[k]));
217
+ if (!deliveryId)
218
+ missing.unshift("delivery_id");
219
+ if (missing.length)
220
+ throw new PayloadError(`replay request is missing ${missing.join(", ")}`);
221
+ const branch = str(p.branch);
222
+ // The whole point of a replay is a run that read the fix. A request naming
223
+ // main is not one the sender makes; refuse it rather than commit a trace
224
+ // the grader would take for a repaired run.
225
+ if (branch === "main")
226
+ throw new PayloadError("a replay cannot run on main");
227
+ const expected = p.expected;
228
+ return {
229
+ event: EVENT_REPLAY_REQUESTED,
230
+ deliveryId,
231
+ fixId: str(p.fix_id),
232
+ agentId: str(p.agent_id),
233
+ branch,
234
+ caseId: str(p.case_id),
235
+ caseSetId: str(p.case_set_id) || undefined,
236
+ taskInput: String(p.task_input),
237
+ expected: expected && typeof expected === "object" && !Array.isArray(expected)
238
+ ? { ...expected }
239
+ : {},
240
+ deadlineAt: parseWhen(p.deadline_at),
241
+ sentAt: parseWhen(p.sent_at),
242
+ instructions: str(p.instructions) || undefined,
243
+ };
244
+ }
245
+ function toOutcome(value) {
246
+ if (value === undefined || value === null)
247
+ return OutcomeType.SUCCESS;
248
+ if (typeof value === "boolean")
249
+ return value ? OutcomeType.SUCCESS : OutcomeType.FAILURE;
250
+ return value;
251
+ }
252
+ /** The receiving end of the replay webhook. */
253
+ /**
254
+ * The bag the outcome is committed with: the grader's keys, then as many of
255
+ * the runner's as fit under `SESSION_ATTRIBUTES_MAX_KEYS`.
256
+ *
257
+ * The grader's keys (`case_id`, `fix_id`, `replay_delivery_id`,
258
+ * `memory_branch`) are what makes the case gradable at all, so they are never
259
+ * the ones to go. The runner's dimensions — the session bag it set while
260
+ * running and the `attributes` it answered with — fill what room is left, in
261
+ * that order; a runner that filled its bag to the cap must not cost the case
262
+ * its trace. The memory's own bag is cleared so the commit does not merge it
263
+ * back in over the trimmed set. What was dropped is returned, and the receiver
264
+ * reports it as `dropped_attributes` in its answer.
265
+ */
266
+ export function commitAttributes(request, memory, result) {
267
+ const grader = {};
268
+ for (const [k, v] of Object.entries(replayAttributes(request)))
269
+ grader[k.trim().toLowerCase()] = v;
270
+ let room = SESSION_ATTRIBUTES_MAX_KEYS;
271
+ for (const k of Object.keys(grader))
272
+ if (!SDK_STAMPED_ATTRIBUTES.has(k))
273
+ room -= 1;
274
+ const bag = memory.sessionAttributes ?? {};
275
+ const extras = {};
276
+ for (const source of [bag, result.attributes ?? {}]) {
277
+ for (const [rawKey, value] of Object.entries(source)) {
278
+ const key = String(rawKey).trim().toLowerCase();
279
+ if (!(key in grader))
280
+ extras[key] = value;
281
+ }
282
+ }
283
+ const kept = {};
284
+ const dropped = [];
285
+ for (const [k, v] of Object.entries(extras)) {
286
+ if (Object.keys(kept).length < Math.max(room, 0))
287
+ kept[k] = v;
288
+ else
289
+ dropped.push(k);
290
+ }
291
+ if (Object.keys(bag).length > 0)
292
+ memory.clearSessionAttributes?.();
293
+ return { attributes: { ...kept, ...grader }, dropped };
294
+ }
295
+ export class ReplayReceiver {
296
+ seen = new Map();
297
+ inflight = new Set();
298
+ options;
299
+ constructor(options) {
300
+ this.options = { background: true, now: () => new Date(), ...options };
301
+ }
302
+ /**
303
+ * Answer one HTTP request.
304
+ *
305
+ * - `ping` → 200; bad signature → 401; a body it cannot act on → 400;
306
+ * - past the deadline → 410; a delivery seen before → 200 with the first answer;
307
+ * - otherwise 202 and the run starts (200 with its outcome when inline).
308
+ */
309
+ async handle(headers, body) {
310
+ let request;
311
+ try {
312
+ request = await parseReplayRequest(headers, body, { secret: this.options.secret });
313
+ }
314
+ catch (err) {
315
+ if (err instanceof ReplayError) {
316
+ return { status: err.status, body: { ok: false, error: err.message, code: err.code } };
317
+ }
318
+ throw err;
319
+ }
320
+ if (request.event === EVENT_PING) {
321
+ return { status: 200, body: { ok: true, event: EVENT_PING, agent_id: request.agentId } };
322
+ }
323
+ const prior = this.seen.get(request.deliveryId);
324
+ if (prior)
325
+ return { status: 200, body: { ...prior, duplicate: true } };
326
+ if (request.deadlineAt && this.options.now() >= request.deadlineAt) {
327
+ return {
328
+ status: 410,
329
+ body: {
330
+ ok: false,
331
+ code: "past_deadline",
332
+ case_id: request.caseId,
333
+ error: `deadline ${request.deadlineAt.toISOString()} has passed`,
334
+ },
335
+ };
336
+ }
337
+ const answer = {
338
+ ok: true,
339
+ accepted: true,
340
+ delivery_id: request.deliveryId,
341
+ case_id: request.caseId,
342
+ branch: request.branch,
343
+ };
344
+ this.remember(request.deliveryId, answer);
345
+ if (!this.options.background) {
346
+ const outcome = await this.replay(request);
347
+ const full = { ...answer, accepted: false, ran: true, ...outcome };
348
+ this.remember(request.deliveryId, full);
349
+ return { status: 200, body: full };
350
+ }
351
+ const job = this.runInBackground(request);
352
+ this.inflight.add(job);
353
+ void job.finally(() => this.inflight.delete(job));
354
+ return { status: 202, body: answer };
355
+ }
356
+ /**
357
+ * Run one case and commit its outcome on the request's branch. A runner
358
+ * that throws is committed as a failure with the error as the answer: a
359
+ * graded failure tells the loop more than a case that never came back.
360
+ */
361
+ async replay(request) {
362
+ const memory = await this.options.memoryFactory(request);
363
+ if (typeof memory.checkout === "function" && memory.branch !== request.branch) {
364
+ memory.checkout(request.branch);
365
+ }
366
+ let result;
367
+ try {
368
+ const answer = await this.options.run(request.taskInput, memory, request);
369
+ result =
370
+ answer == null
371
+ ? { responseText: null }
372
+ : typeof answer === "string"
373
+ ? { responseText: answer }
374
+ : answer;
375
+ }
376
+ catch (err) {
377
+ const e = err;
378
+ result = {
379
+ responseText: `replay runner raised ${e?.name ?? "Error"}: ${e?.message ?? String(err)}`.slice(0, 2000),
380
+ outcomeType: OutcomeType.FAILURE,
381
+ attributes: { replay_error: e?.name ?? "Error" },
382
+ };
383
+ }
384
+ const outcomeType = toOutcome(result.outcomeType);
385
+ const { attributes, dropped } = commitAttributes(request, memory, result);
386
+ const outcomeRef = replayOutcomeRef(request);
387
+ const committed = await memory.commitOutcomeAsync(outcomeRef, outcomeType, {
388
+ attributes,
389
+ taskInput: request.taskInput,
390
+ responseText: result.responseText ?? null,
391
+ toolCalls: result.toolCalls,
392
+ });
393
+ const traceId = committed && typeof committed === "object"
394
+ ? (committed.trace_id ?? committed.id)
395
+ : undefined;
396
+ return {
397
+ outcome_type: outcomeType,
398
+ outcome_ref: outcomeRef,
399
+ trace_id: traceId == null ? null : String(traceId),
400
+ ...(dropped.length > 0 ? { dropped_attributes: dropped } : {}),
401
+ };
402
+ }
403
+ /** Wait for background runs to finish. */
404
+ async drain() {
405
+ while (this.inflight.size)
406
+ await Promise.allSettled([...this.inflight]);
407
+ }
408
+ /** What became of a delivery, if the receiver still remembers it. */
409
+ status(deliveryId) {
410
+ const s = this.seen.get(deliveryId);
411
+ return s ? { ...s } : undefined;
412
+ }
413
+ async runInBackground(request) {
414
+ try {
415
+ const outcome = await this.replay(request);
416
+ this.remember(request.deliveryId, { ...(this.seen.get(request.deliveryId) ?? {}), ran: true, ...outcome });
417
+ }
418
+ catch (err) {
419
+ this.remember(request.deliveryId, {
420
+ ...(this.seen.get(request.deliveryId) ?? {}),
421
+ ran: false,
422
+ error: "commit failed",
423
+ });
424
+ this.options.onError?.(err, request);
425
+ }
426
+ }
427
+ remember(deliveryId, answer) {
428
+ this.seen.delete(deliveryId);
429
+ this.seen.set(deliveryId, answer);
430
+ while (this.seen.size > SEEN_DELIVERIES) {
431
+ const oldest = this.seen.keys().next().value;
432
+ if (oldest === undefined)
433
+ break;
434
+ this.seen.delete(oldest);
435
+ }
436
+ }
437
+ }
438
+ const INTERNAL_ERROR = { ok: false, error: "internal error" };
439
+ function reportError(options, err) {
440
+ try {
441
+ (options?.onError ?? console.error)(err);
442
+ }
443
+ catch {
444
+ // A failing error hook must not turn one 500 into another.
445
+ }
446
+ return INTERNAL_ERROR;
447
+ }
448
+ /**
449
+ * A `(Request) => Promise<Response>` handler mounting `receiver` at `path` —
450
+ * the shape Next.js route handlers, Hono, Bun.serve, Deno.serve and workers
451
+ * take. `GET path` answers 200 for a health check; any other path is 404.
452
+ */
453
+ export function createFetchHandler(receiver, options) {
454
+ const path = options?.path ?? "/amfs/replay";
455
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
456
+ return async (request) => {
457
+ const url = new URL(request.url, "http://replay.local").pathname;
458
+ if (url !== path)
459
+ return json(404, { ok: false, error: "not found" });
460
+ if (request.method === "GET")
461
+ return json(200, { ok: true, receiver: "amfs-replay", path });
462
+ if (request.method !== "POST")
463
+ return json(405, { ok: false, error: "method not allowed" });
464
+ try {
465
+ const body = new Uint8Array(await request.arrayBuffer());
466
+ const { status, body: answer } = await receiver.handle(request.headers, body);
467
+ return json(status, answer);
468
+ }
469
+ catch (err) {
470
+ return json(500, reportError(options, err));
471
+ }
472
+ };
473
+ }
474
+ /**
475
+ * Start a `node:http` server around `receiver` (Node 18+). Resolves once it
476
+ * is listening; `server.address()` has the port when `port: 0` was asked for.
477
+ * Typed loosely on purpose: the SDK carries no Node type definitions.
478
+ */
479
+ export async function serveReplay(receiver, options) {
480
+ const specifier = "node:http";
481
+ const http = (await import(/* @vite-ignore */ specifier));
482
+ const path = options?.path ?? "/amfs/replay";
483
+ const server = http.createServer((req, res) => {
484
+ const send = (status, body) => {
485
+ const raw = encoder.encode(JSON.stringify(body));
486
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": String(raw.byteLength) });
487
+ res.end(raw);
488
+ };
489
+ const url = String(req.url ?? "/").split("?")[0];
490
+ if (url !== path)
491
+ return send(404, { ok: false, error: "not found" });
492
+ if (req.method === "GET")
493
+ return send(200, { ok: true, receiver: "amfs-replay", path });
494
+ if (req.method !== "POST")
495
+ return send(405, { ok: false, error: "method not allowed" });
496
+ const chunks = [];
497
+ req.on("data", (c) => chunks.push(c));
498
+ req.on("end", () => {
499
+ const total = chunks.reduce((n, c) => n + c.byteLength, 0);
500
+ const body = new Uint8Array(total);
501
+ let offset = 0;
502
+ for (const c of chunks) {
503
+ body.set(c, offset);
504
+ offset += c.byteLength;
505
+ }
506
+ receiver
507
+ .handle(req.headers, body)
508
+ .then(({ status, body: answer }) => send(status, answer))
509
+ .catch((err) => send(500, reportError(options, err)));
510
+ });
511
+ });
512
+ await new Promise((resolve) => server.listen(options?.port ?? 8787, options?.host ?? "0.0.0.0", resolve));
513
+ return server;
514
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Session metadata the SDK collects for a trace: the attribute bag a run is
3
+ * filtered and grouped by, and the LLM calls that give it real token and cost
4
+ * figures. Both travel in `session_metadata` when the outcome is committed —
5
+ * `attributes` and `llm_calls`, the same shape the Python SDK and MCP server
6
+ * write, so the server treats every producer alike.
7
+ */
8
+ export type AttributeValue = string | number | boolean;
9
+ export type SessionAttributes = Record<string, AttributeValue>;
10
+ /** Attributes are indexed server-side, so the bag is kept small and flat. */
11
+ export declare const SESSION_ATTRIBUTES_MAX_KEYS = 20;
12
+ export declare const SESSION_ATTRIBUTE_KEY_MAX_LEN = 64;
13
+ export declare const SESSION_ATTRIBUTE_VALUE_MAX_LEN = 256;
14
+ /**
15
+ * Attribute keys the SDK stamps itself, which do not count against
16
+ * `SESSION_ATTRIBUTES_MAX_KEYS`: a caller's bag at the cap is still accepted —
17
+ * locally and by the server, which exempts the same keys — for the branch it
18
+ * ran on.
19
+ */
20
+ export declare const SDK_STAMPED_ATTRIBUTES: ReadonlySet<string>;
21
+ /** How many of `keys` count against the cap. */
22
+ export declare function countedAttributeKeys(keys: Iterable<string>): number;
23
+ /**
24
+ * The validated form of an attribute bag, or a thrown `TypeError` / `RangeError`.
25
+ *
26
+ * Keys are trimmed and lowercased (the server indexes them that way, so two
27
+ * spellings of one dimension would otherwise never group together). Values
28
+ * must be string, finite number or boolean; at most 20 keys of up to 64
29
+ * characters, string values up to 256 characters. Rejected rather than
30
+ * trimmed: a silently shortened customer id is worse than an error at the
31
+ * call site.
32
+ */
33
+ export declare function validateSessionAttributes(attributes: unknown): SessionAttributes;
34
+ /** What {@link AgentMemory.recordLlmCall} takes. */
35
+ export interface RecordLlmCallInput {
36
+ model: string;
37
+ inputTokens: number;
38
+ outputTokens: number;
39
+ /** USD; omit when unknown — a blank cost is honest, a zero one is not. */
40
+ costUsd?: number | null;
41
+ latencyMs?: number | null;
42
+ provider?: string | null;
43
+ callId?: string | null;
44
+ /** Set when the call failed; the record still counts the attempt. */
45
+ error?: string | null;
46
+ }
47
+ /**
48
+ * One LLM call as stored in `session_metadata.llm_calls` (wire shape, snake_case).
49
+ * Mirrors the record the Python SDK's `record_llm_call` writes.
50
+ */
51
+ export interface LlmCallRecord {
52
+ call_id: string;
53
+ model: string;
54
+ provider: string;
55
+ input_tokens: number;
56
+ output_tokens: number;
57
+ cost_usd: number | null;
58
+ latency_ms: number | null;
59
+ started_at: string;
60
+ [extra: string]: unknown;
61
+ }
62
+ /** Validate and normalise a call into the wire record. Throws on bad input. */
63
+ export declare function toLlmCallRecord(input: RecordLlmCallInput, startedAt?: Date): LlmCallRecord;
64
+ /**
65
+ * The `session_metadata` object sent with an outcome: the two collections when
66
+ * they have content, nothing otherwise (so a server that predates them sees
67
+ * the request it always saw).
68
+ */
69
+ export declare function buildSessionMetadata(attributes: SessionAttributes, llmCalls: LlmCallRecord[]): Record<string, unknown> | undefined;