@senselab-ai/amfs 0.3.2 → 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.
@@ -0,0 +1,228 @@
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 type { SessionAttributes } from "./session.js";
54
+ export declare const SIGNATURE_HEADER = "X-AMFS-Signature";
55
+ export declare const EVENT_HEADER = "X-AMFS-Event";
56
+ export declare const DELIVERY_HEADER = "X-AMFS-Delivery";
57
+ export declare const EVENT_REPLAY_REQUESTED = "replay_requested";
58
+ export declare const EVENT_PING = "ping";
59
+ /** The attributes the grader reads a replayed trace through. */
60
+ export declare const CASE_ID_ATTRIBUTE = "case_id";
61
+ export declare const FIX_ID_ATTRIBUTE = "fix_id";
62
+ export declare 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 declare const SEEN_DELIVERIES = 4096;
66
+ export type HeaderBag = Record<string, string | string[] | undefined> | Headers | Iterable<[string, string]>;
67
+ /** The `X-AMFS-Signature` value for `body`: `sha256=<hex>`. */
68
+ export declare function signReplayBody(secret: string, body: string | Uint8Array): Promise<string>;
69
+ /** Whether `header` signs `body` under `secret`. Constant-time; junk is `false`. */
70
+ export declare function verifyReplaySignature(secret: string, body: string | Uint8Array, header: string | undefined | null): Promise<boolean>;
71
+ export declare class ReplayError extends Error {
72
+ readonly status: number;
73
+ readonly code: string;
74
+ constructor(status: number, message: string, code: string);
75
+ }
76
+ export declare class SignatureError extends ReplayError {
77
+ constructor(message?: string);
78
+ }
79
+ export declare class PayloadError extends ReplayError {
80
+ constructor(message: string);
81
+ }
82
+ /** One verified replay request, as the sender framed it. */
83
+ export interface ReplayRequest {
84
+ event: string;
85
+ deliveryId: string;
86
+ fixId: string;
87
+ agentId: string;
88
+ branch: string;
89
+ caseId: string;
90
+ caseSetId?: string;
91
+ taskInput: string;
92
+ expected: Record<string, unknown>;
93
+ deadlineAt?: Date;
94
+ sentAt?: Date;
95
+ instructions?: string;
96
+ }
97
+ /** The outcome reference a replay commits under. */
98
+ export declare function replayOutcomeRef(request: ReplayRequest): string;
99
+ /** The session attributes the committed outcome must carry. */
100
+ export declare function replayAttributes(request: ReplayRequest): SessionAttributes;
101
+ /**
102
+ * Verify and parse one delivery. Throws {@link SignatureError} when `secret`
103
+ * is set and the signature does not match, {@link PayloadError} when the body
104
+ * is not a request the receiver can act on. `secret: null` skips
105
+ * verification — for a receiver behind its own authentication and for local
106
+ * simulations.
107
+ */
108
+ export declare function parseReplayRequest(headers: HeaderBag, body: string | Uint8Array, options: {
109
+ secret: string | null;
110
+ }): Promise<ReplayRequest>;
111
+ /** What a run hands back. A plain string is the agent's answer, taken as a success. */
112
+ export interface ReplayResult {
113
+ responseText?: string | null;
114
+ outcomeType?: OutcomeType | `${OutcomeType}` | boolean;
115
+ attributes?: SessionAttributes;
116
+ /** The actions the run took, recorded on the trace so a judge can grade the expected action. */
117
+ toolCalls?: Array<Record<string, unknown>>;
118
+ }
119
+ export type ReplayAnswer = ReplayResult | string | null | undefined;
120
+ /**
121
+ * A memory the receiver can run a case through: reads on `branch` and a
122
+ * remote outcome commit. `AgentMemory` over an `HttpAdapter` satisfies it.
123
+ */
124
+ export interface ReplayMemory {
125
+ readonly branch?: string;
126
+ checkout?(branch: string): string;
127
+ /** The bag a run set while it ran; read so the grader's keys can be fitted ahead of it. */
128
+ readonly sessionAttributes?: SessionAttributes;
129
+ clearSessionAttributes?(): void;
130
+ commitOutcomeAsync(outcomeRef: string, outcomeType: OutcomeType, options?: {
131
+ attributes?: SessionAttributes;
132
+ taskInput?: string;
133
+ responseText?: string | null;
134
+ toolCalls?: Array<Record<string, unknown>>;
135
+ }): Promise<unknown>;
136
+ }
137
+ export interface ReplayReceiverOptions<M extends ReplayMemory = ReplayMemory> {
138
+ /** The shared secret registered with the webhook; `null` accepts unsigned requests. */
139
+ secret: string | null;
140
+ /** Builds the memory for a request — on `request.branch`. */
141
+ memoryFactory: (request: ReplayRequest) => M | Promise<M>;
142
+ /** Answers a case: `run(taskInput, memory)`; read through `memory` and the run reads the fix. */
143
+ run: (taskInput: string, memory: M, request: ReplayRequest) => Promise<ReplayAnswer> | ReplayAnswer;
144
+ /** Acknowledge with 202 and run afterwards (default). `false` runs inline and answers 200 with the outcome. */
145
+ background?: boolean;
146
+ /** Called with a run that could not be committed at all. */
147
+ onError?: (error: unknown, request: ReplayRequest) => void;
148
+ now?: () => Date;
149
+ }
150
+ export interface ReplayResponse {
151
+ status: number;
152
+ body: Record<string, unknown>;
153
+ }
154
+ /** The receiving end of the replay webhook. */
155
+ /**
156
+ * The bag the outcome is committed with: the grader's keys, then as many of
157
+ * the runner's as fit under `SESSION_ATTRIBUTES_MAX_KEYS`.
158
+ *
159
+ * The grader's keys (`case_id`, `fix_id`, `replay_delivery_id`,
160
+ * `memory_branch`) are what makes the case gradable at all, so they are never
161
+ * the ones to go. The runner's dimensions — the session bag it set while
162
+ * running and the `attributes` it answered with — fill what room is left, in
163
+ * that order; a runner that filled its bag to the cap must not cost the case
164
+ * its trace. The memory's own bag is cleared so the commit does not merge it
165
+ * back in over the trimmed set. What was dropped is returned, and the receiver
166
+ * reports it as `dropped_attributes` in its answer.
167
+ */
168
+ export declare function commitAttributes(request: ReplayRequest, memory: ReplayMemory, result: ReplayResult): {
169
+ attributes: SessionAttributes;
170
+ dropped: string[];
171
+ };
172
+ export declare class ReplayReceiver<M extends ReplayMemory = ReplayMemory> {
173
+ private readonly seen;
174
+ private readonly inflight;
175
+ private readonly options;
176
+ constructor(options: ReplayReceiverOptions<M>);
177
+ /**
178
+ * Answer one HTTP request.
179
+ *
180
+ * - `ping` → 200; bad signature → 401; a body it cannot act on → 400;
181
+ * - past the deadline → 410; a delivery seen before → 200 with the first answer;
182
+ * - otherwise 202 and the run starts (200 with its outcome when inline).
183
+ */
184
+ handle(headers: HeaderBag, body: string | Uint8Array): Promise<ReplayResponse>;
185
+ /**
186
+ * Run one case and commit its outcome on the request's branch. A runner
187
+ * that throws is committed as a failure with the error as the answer: a
188
+ * graded failure tells the loop more than a case that never came back.
189
+ */
190
+ replay(request: ReplayRequest): Promise<Record<string, unknown>>;
191
+ /** Wait for background runs to finish. */
192
+ drain(): Promise<void>;
193
+ /** What became of a delivery, if the receiver still remembers it. */
194
+ status(deliveryId: string): Record<string, unknown> | undefined;
195
+ private runInBackground;
196
+ private remember;
197
+ }
198
+ /** Options shared by the fetch and Node handlers. */
199
+ export interface HandlerOptions {
200
+ /** Where the receiver is mounted. Default `/amfs/replay`. */
201
+ path?: string;
202
+ /**
203
+ * Called with an error `handle()` did not expect (a `ReplayError` is
204
+ * answered with its own status and never reaches this). Default
205
+ * `console.error`. The response to the caller is a generic 500 either way:
206
+ * the message and stack of an internal error describe this server, not the
207
+ * request, and are not the caller's to read.
208
+ */
209
+ onError?: (err: unknown) => void;
210
+ }
211
+ /**
212
+ * A `(Request) => Promise<Response>` handler mounting `receiver` at `path` —
213
+ * the shape Next.js route handlers, Hono, Bun.serve, Deno.serve and workers
214
+ * take. `GET path` answers 200 for a health check; any other path is 404.
215
+ */
216
+ export declare function createFetchHandler(receiver: ReplayReceiver<any>, options?: HandlerOptions): (request: Request) => Promise<Response>;
217
+ /**
218
+ * Start a `node:http` server around `receiver` (Node 18+). Resolves once it
219
+ * is listening; `server.address()` has the port when `port: 0` was asked for.
220
+ * Typed loosely on purpose: the SDK carries no Node type definitions.
221
+ */
222
+ export declare function serveReplay(receiver: ReplayReceiver<any>, options?: HandlerOptions & {
223
+ host?: string;
224
+ port?: number;
225
+ }): Promise<{
226
+ close(): void;
227
+ address(): unknown;
228
+ }>;