@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/adapters/http.d.ts +240 -39
- package/dist/adapters/http.js +377 -13
- package/dist/index.d.ts +10 -4
- package/dist/index.js +6 -3
- package/dist/instrument/anthropic.d.ts +15 -0
- package/dist/instrument/anthropic.js +53 -0
- package/dist/instrument/common.d.ts +47 -0
- package/dist/instrument/common.js +179 -0
- package/dist/instrument/index.d.ts +3 -0
- package/dist/instrument/index.js +2 -0
- package/dist/instrument/openai.d.ts +28 -0
- package/dist/instrument/openai.js +88 -0
- package/dist/memory.d.ts +264 -1
- package/dist/memory.js +468 -32
- package/dist/models.d.ts +19 -0
- package/dist/models.js +15 -0
- package/dist/replay.d.ts +228 -0
- package/dist/replay.js +514 -0
- package/dist/session.d.ts +69 -0
- package/dist/session.js +139 -0
- package/package.json +10 -1
package/dist/adapters/http.js
CHANGED
|
@@ -2,12 +2,53 @@
|
|
|
2
2
|
* HttpAdapter — connects the TS SDK to a remote AMFS HTTP API server.
|
|
3
3
|
*/
|
|
4
4
|
import { createWatchHandle } from "../adapter.js";
|
|
5
|
+
/**
|
|
6
|
+
* Request header naming the agent the calling session acts as. Read routes
|
|
7
|
+
* carry no agent in their query or body, so without it a hosted server cannot
|
|
8
|
+
* attribute a read or look up the agent's live repair canary.
|
|
9
|
+
*/
|
|
10
|
+
export const AGENT_ID_HEADER = "X-AMFS-Agent-Id";
|
|
11
|
+
/**
|
|
12
|
+
* Request header carrying the session id the SDK stamps on its trace — the key
|
|
13
|
+
* a hosted server hashes to keep one session on one arm of a live canary. A
|
|
14
|
+
* session that does not send it is never routed.
|
|
15
|
+
*/
|
|
16
|
+
export const SESSION_HEADER = "X-AMFS-Session";
|
|
17
|
+
/** `value` as a header value (printable ASCII, single line), or undefined. */
|
|
18
|
+
function headerValue(value) {
|
|
19
|
+
if (value === undefined || value === null)
|
|
20
|
+
return undefined;
|
|
21
|
+
const cleaned = String(value).replace(/[^\x20-\x7e]/g, "").trim().slice(0, 256);
|
|
22
|
+
return cleaned || undefined;
|
|
23
|
+
}
|
|
24
|
+
function snakeToCamel(str) {
|
|
25
|
+
return str.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
26
|
+
}
|
|
27
|
+
function convertKeys(obj) {
|
|
28
|
+
if (obj === null || obj === undefined)
|
|
29
|
+
return obj;
|
|
30
|
+
if (Array.isArray(obj))
|
|
31
|
+
return obj.map(convertKeys);
|
|
32
|
+
if (typeof obj === "object") {
|
|
33
|
+
const result = {};
|
|
34
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
35
|
+
result[snakeToCamel(k)] = convertKeys(v);
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
return obj;
|
|
40
|
+
}
|
|
5
41
|
export class HttpAdapter {
|
|
6
42
|
baseUrl;
|
|
7
43
|
headers;
|
|
8
44
|
agentId;
|
|
9
45
|
constructor(opts) {
|
|
10
|
-
|
|
46
|
+
// Not `replace(/\/+$/, "")`: that backtracks quadratically on a long run
|
|
47
|
+
// of slashes that is not at the end.
|
|
48
|
+
let end = opts.url.length;
|
|
49
|
+
while (end > 0 && opts.url[end - 1] === "/")
|
|
50
|
+
end--;
|
|
51
|
+
this.baseUrl = opts.url.slice(0, end);
|
|
11
52
|
this.agentId = opts.agentId;
|
|
12
53
|
this.headers = {
|
|
13
54
|
"Content-Type": "application/json",
|
|
@@ -16,8 +57,44 @@ export class HttpAdapter {
|
|
|
16
57
|
if (opts.apiKey) {
|
|
17
58
|
this.headers["X-AMFS-API-Key"] = opts.apiKey;
|
|
18
59
|
}
|
|
60
|
+
this.opts = opts;
|
|
61
|
+
}
|
|
62
|
+
opts;
|
|
63
|
+
/**
|
|
64
|
+
* An adapter on the same server that identifies itself as `agentId` in
|
|
65
|
+
* `sessionId` on every request. `AgentMemory` calls this when it is built, so
|
|
66
|
+
* two memories sharing one adapter never share an identity. Either id may be
|
|
67
|
+
* omitted; the header is then simply not sent.
|
|
68
|
+
*/
|
|
69
|
+
bind(agentId, sessionId) {
|
|
70
|
+
const identity = {};
|
|
71
|
+
const agent = headerValue(agentId);
|
|
72
|
+
const session = headerValue(sessionId);
|
|
73
|
+
if (agent)
|
|
74
|
+
identity[AGENT_ID_HEADER] = agent;
|
|
75
|
+
if (session)
|
|
76
|
+
identity[SESSION_HEADER] = session;
|
|
77
|
+
return new HttpAdapter({
|
|
78
|
+
...this.opts,
|
|
79
|
+
agentId: agentId ?? this.opts.agentId,
|
|
80
|
+
headers: { ...this.opts.headers, ...identity },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** The identity headers this adapter adds to every request (a copy). */
|
|
84
|
+
get identityHeaders() {
|
|
85
|
+
const out = {};
|
|
86
|
+
for (const name of [AGENT_ID_HEADER, SESSION_HEADER]) {
|
|
87
|
+
if (this.headers[name])
|
|
88
|
+
out[name] = this.headers[name];
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
19
91
|
}
|
|
20
92
|
async fetch(path, init) {
|
|
93
|
+
const raw = await this.fetchRaw(path, init);
|
|
94
|
+
return convertKeys(raw);
|
|
95
|
+
}
|
|
96
|
+
/** Like `fetch` but returns the server's JSON untouched (snake_case keys). */
|
|
97
|
+
async fetchRaw(path, init) {
|
|
21
98
|
const resp = await globalThis.fetch(`${this.baseUrl}${path}`, {
|
|
22
99
|
...init,
|
|
23
100
|
headers: { ...this.headers, ...init?.headers },
|
|
@@ -28,20 +105,44 @@ export class HttpAdapter {
|
|
|
28
105
|
}
|
|
29
106
|
return resp.json();
|
|
30
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Call a route this adapter has no method for, and get the server's JSON back
|
|
110
|
+
* untouched (snake_case keys).
|
|
111
|
+
*
|
|
112
|
+
* The request is this adapter's own: the same base URL, API key and identity
|
|
113
|
+
* headers as every other call, and the same error, an `Error` whose message
|
|
114
|
+
* carries the status and the response body. `AgentMemory`'s room and
|
|
115
|
+
* negotiation methods go through it. `query` values that are `undefined` or
|
|
116
|
+
* `null` are left out; the rest are URL-encoded.
|
|
117
|
+
*/
|
|
118
|
+
async requestRaw(method, path, options) {
|
|
119
|
+
const params = new URLSearchParams();
|
|
120
|
+
for (const [name, value] of Object.entries(options?.query ?? {})) {
|
|
121
|
+
if (value !== undefined && value !== null)
|
|
122
|
+
params.set(name, String(value));
|
|
123
|
+
}
|
|
124
|
+
const qs = params.toString();
|
|
125
|
+
return this.fetchRaw(`${path}${qs ? `?${qs}` : ""}`, {
|
|
126
|
+
method,
|
|
127
|
+
...(options?.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
31
130
|
read(entityPath, key, options) {
|
|
32
|
-
// Synchronous interface — return null and let callers use readAsync
|
|
33
131
|
return null;
|
|
34
132
|
}
|
|
35
|
-
async readAsync(entityPath, key) {
|
|
133
|
+
async readAsync(entityPath, key, options) {
|
|
134
|
+
const params = new URLSearchParams();
|
|
135
|
+
if (options?.branch && options.branch !== "main")
|
|
136
|
+
params.set("branch", options.branch);
|
|
137
|
+
const qs = params.toString();
|
|
36
138
|
try {
|
|
37
|
-
return await this.fetch(`/api/v1/entries/${encodeURIComponent(entityPath)}/${encodeURIComponent(key)}`);
|
|
139
|
+
return await this.fetch(`/api/v1/entries/${encodeURIComponent(entityPath)}/${encodeURIComponent(key)}${qs ? `?${qs}` : ""}`);
|
|
38
140
|
}
|
|
39
141
|
catch {
|
|
40
142
|
return null;
|
|
41
143
|
}
|
|
42
144
|
}
|
|
43
145
|
write(entry) {
|
|
44
|
-
// Synchronous interface — callers should use writeAsync for HTTP
|
|
45
146
|
return entry;
|
|
46
147
|
}
|
|
47
148
|
async writeAsync(entry) {
|
|
@@ -62,7 +163,6 @@ export class HttpAdapter {
|
|
|
62
163
|
});
|
|
63
164
|
}
|
|
64
165
|
list(entityPath, options) {
|
|
65
|
-
// Synchronous interface — return empty, callers should use listAsync
|
|
66
166
|
return [];
|
|
67
167
|
}
|
|
68
168
|
async listAsync(entityPath, options) {
|
|
@@ -71,8 +171,13 @@ export class HttpAdapter {
|
|
|
71
171
|
params.set("entity_path", entityPath);
|
|
72
172
|
if (options?.includeSuperseded)
|
|
73
173
|
params.set("include_superseded", "true");
|
|
174
|
+
if (options?.branch && options.branch !== "main")
|
|
175
|
+
params.set("branch", options.branch);
|
|
74
176
|
const qs = params.toString();
|
|
75
|
-
|
|
177
|
+
const data = await this.fetch(`/api/v1/entries${qs ? `?${qs}` : ""}`);
|
|
178
|
+
if (Array.isArray(data))
|
|
179
|
+
return data;
|
|
180
|
+
return data.entries ?? [];
|
|
76
181
|
}
|
|
77
182
|
async searchAsync(query) {
|
|
78
183
|
return this.fetch("/api/v1/search", {
|
|
@@ -82,8 +187,14 @@ export class HttpAdapter {
|
|
|
82
187
|
entity_path: query.entityPath,
|
|
83
188
|
min_confidence: query.minConfidence ?? 0.0,
|
|
84
189
|
limit: query.limit ?? 100,
|
|
190
|
+
...(query.maxConfidence != null ? { max_confidence: query.maxConfidence } : {}),
|
|
85
191
|
...(query.agentId ? { agent_id: query.agentId } : {}),
|
|
192
|
+
...(query.since ? { since: query.since } : {}),
|
|
193
|
+
...(query.patternRef ? { pattern_ref: query.patternRef } : {}),
|
|
86
194
|
...(query.sortBy ? { sort_by: query.sortBy } : {}),
|
|
195
|
+
...(query.depth != null ? { depth: query.depth } : {}),
|
|
196
|
+
// Omitted for main, like every other read, so a hosted canary can route the session.
|
|
197
|
+
...(query.branch && query.branch !== "main" ? { branch: query.branch } : {}),
|
|
87
198
|
}),
|
|
88
199
|
});
|
|
89
200
|
}
|
|
@@ -110,7 +221,7 @@ export class HttpAdapter {
|
|
|
110
221
|
const raw = line.slice(5).trim();
|
|
111
222
|
if (raw) {
|
|
112
223
|
try {
|
|
113
|
-
callback(JSON.parse(raw));
|
|
224
|
+
callback(convertKeys(JSON.parse(raw)));
|
|
114
225
|
}
|
|
115
226
|
catch { /* skip malformed */ }
|
|
116
227
|
}
|
|
@@ -127,10 +238,10 @@ export class HttpAdapter {
|
|
|
127
238
|
return createWatchHandle(() => controller.abort());
|
|
128
239
|
}
|
|
129
240
|
commitOutcome(record) {
|
|
130
|
-
// Synchronous interface — return empty, callers should use commitOutcomeAsync
|
|
131
241
|
return [];
|
|
132
242
|
}
|
|
133
243
|
async commitOutcomeAsync(record) {
|
|
244
|
+
const agentId = record.agentId ?? this.agentId;
|
|
134
245
|
return this.fetch("/api/v1/outcomes", {
|
|
135
246
|
method: "POST",
|
|
136
247
|
body: JSON.stringify({
|
|
@@ -138,6 +249,14 @@ export class HttpAdapter {
|
|
|
138
249
|
outcome_type: record.outcomeType,
|
|
139
250
|
...(record.entityPath ? { entity_path: record.entityPath } : {}),
|
|
140
251
|
...(record.causalEntryKeys?.length ? { causal_entry_keys: record.causalEntryKeys } : {}),
|
|
252
|
+
...(record.causalConfidence != null ? { causal_confidence: record.causalConfidence } : {}),
|
|
253
|
+
...(agentId ? { agent_id: agentId } : {}),
|
|
254
|
+
...(record.sessionMetadata && Object.keys(record.sessionMetadata).length
|
|
255
|
+
? { session_metadata: record.sessionMetadata }
|
|
256
|
+
: {}),
|
|
257
|
+
...(record.taskInput != null ? { task_input: record.taskInput } : {}),
|
|
258
|
+
...(record.responseText != null ? { response_text: record.responseText } : {}),
|
|
259
|
+
...(record.toolCalls?.length ? { tool_calls: record.toolCalls } : {}),
|
|
141
260
|
}),
|
|
142
261
|
});
|
|
143
262
|
}
|
|
@@ -147,7 +266,58 @@ export class HttpAdapter {
|
|
|
147
266
|
async healthAsync() {
|
|
148
267
|
return this.fetch("/api/v1/health");
|
|
149
268
|
}
|
|
150
|
-
async
|
|
269
|
+
async briefingAsync(options) {
|
|
270
|
+
const params = new URLSearchParams();
|
|
271
|
+
if (options?.entityPath)
|
|
272
|
+
params.set("entity_path", options.entityPath);
|
|
273
|
+
if (options?.agentId)
|
|
274
|
+
params.set("agent_id", options.agentId);
|
|
275
|
+
if (options?.limit)
|
|
276
|
+
params.set("limit", String(options.limit));
|
|
277
|
+
if (options?.compact)
|
|
278
|
+
params.set("compact", "true");
|
|
279
|
+
if (options?.since)
|
|
280
|
+
params.set("since", options.since);
|
|
281
|
+
if (options?.branch && options.branch !== "main")
|
|
282
|
+
params.set("branch", options.branch);
|
|
283
|
+
const qs = params.toString();
|
|
284
|
+
return this.fetch(`/api/v1/briefing${qs ? `?${qs}` : ""}`);
|
|
285
|
+
}
|
|
286
|
+
async consolidationStatusAsync() {
|
|
287
|
+
return this.fetch("/api/v1/cortex/consolidation/status");
|
|
288
|
+
}
|
|
289
|
+
async consolidationProposalsAsync(options) {
|
|
290
|
+
const params = new URLSearchParams();
|
|
291
|
+
if (options?.status)
|
|
292
|
+
params.set("status", options.status);
|
|
293
|
+
if (options?.limit)
|
|
294
|
+
params.set("limit", String(options.limit));
|
|
295
|
+
const qs = params.toString();
|
|
296
|
+
return this.fetch(`/api/v1/cortex/consolidation/proposals${qs ? `?${qs}` : ""}`);
|
|
297
|
+
}
|
|
298
|
+
async consolidationCandidatesAsync(options) {
|
|
299
|
+
const params = new URLSearchParams();
|
|
300
|
+
if (options?.limit)
|
|
301
|
+
params.set("limit", String(options.limit));
|
|
302
|
+
const qs = params.toString();
|
|
303
|
+
return this.fetch(`/api/v1/cortex/consolidation/candidates${qs ? `?${qs}` : ""}`);
|
|
304
|
+
}
|
|
305
|
+
async consolidateAsync(options) {
|
|
306
|
+
return this.fetch("/api/v1/cortex/consolidate", {
|
|
307
|
+
method: "POST",
|
|
308
|
+
body: JSON.stringify({ dry_run: options?.dryRun ?? true }),
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* One page of decision traces, newest first, exactly as the server pages them.
|
|
313
|
+
*
|
|
314
|
+
* Mirrors GET /api/v1/traces: pass `cursor` (the previous page's `nextCursor`)
|
|
315
|
+
* to continue; `offset` is honoured only when no cursor is given. `since`
|
|
316
|
+
* (inclusive) and `until` (exclusive) are sent to the server and bound the
|
|
317
|
+
* query itself, so a window that excludes the newest traces still returns
|
|
318
|
+
* the older matches rather than an empty first page.
|
|
319
|
+
*/
|
|
320
|
+
async listTracesPageAsync(options) {
|
|
151
321
|
const params = new URLSearchParams();
|
|
152
322
|
if (options?.entityPath)
|
|
153
323
|
params.set("entity_path", options.entityPath);
|
|
@@ -157,16 +327,210 @@ export class HttpAdapter {
|
|
|
157
327
|
params.set("outcome_type", options.outcomeType);
|
|
158
328
|
if (options?.limit)
|
|
159
329
|
params.set("limit", String(options.limit));
|
|
330
|
+
if (options?.cursor)
|
|
331
|
+
params.set("cursor", options.cursor);
|
|
332
|
+
else if (options?.offset)
|
|
333
|
+
params.set("offset", String(options.offset));
|
|
334
|
+
const since = toIsoString(options?.since);
|
|
335
|
+
const until = toIsoString(options?.until);
|
|
336
|
+
if (since)
|
|
337
|
+
params.set("since", since);
|
|
338
|
+
if (until)
|
|
339
|
+
params.set("until", until);
|
|
160
340
|
const qs = params.toString();
|
|
161
|
-
const
|
|
162
|
-
return
|
|
341
|
+
const raw = await this.fetchRaw(`/api/v1/traces${qs ? `?${qs}` : ""}`);
|
|
342
|
+
return toDecisionTracePage(raw);
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Decision traces as a flat array. Accepts the same paging options as
|
|
346
|
+
* {@link listTracesPageAsync}; use that method when you need `nextCursor` /
|
|
347
|
+
* `hasMore` to walk beyond one page.
|
|
348
|
+
*/
|
|
349
|
+
async listTracesAsync(options) {
|
|
350
|
+
const page = await this.listTracesPageAsync(options);
|
|
351
|
+
return page.traces;
|
|
163
352
|
}
|
|
164
353
|
async getTraceAsync(traceId) {
|
|
165
354
|
try {
|
|
166
|
-
|
|
355
|
+
const raw = await this.fetchRaw(`/api/v1/traces/${encodeURIComponent(traceId)}`);
|
|
356
|
+
return toDecisionTrace(raw);
|
|
167
357
|
}
|
|
168
358
|
catch {
|
|
169
359
|
return null;
|
|
170
360
|
}
|
|
171
361
|
}
|
|
362
|
+
/** Server-side semantic retrieval (embedding + similarity + blend happen on the server). */
|
|
363
|
+
async retrieveAsync(query, options) {
|
|
364
|
+
const data = await this.fetch("/api/v1/retrieve", {
|
|
365
|
+
method: "POST",
|
|
366
|
+
body: JSON.stringify({
|
|
367
|
+
query,
|
|
368
|
+
min_confidence: options?.minConfidence ?? 0.0,
|
|
369
|
+
limit: options?.limit ?? 10,
|
|
370
|
+
semantic_weight: options?.semanticWeight ?? 0.5,
|
|
371
|
+
recency_weight: options?.recencyWeight ?? 0.3,
|
|
372
|
+
confidence_weight: options?.confidenceWeight ?? 0.2,
|
|
373
|
+
include_artifacts: options?.includeArtifacts ?? true,
|
|
374
|
+
// Omitted for main, like every other read: a named main is an explicit
|
|
375
|
+
// choice the server honours over a routed canary branch.
|
|
376
|
+
...(options?.branch && options.branch !== "main" ? { branch: options.branch } : {}),
|
|
377
|
+
...(options?.entityPath ? { entity_path: options.entityPath } : {}),
|
|
378
|
+
}),
|
|
379
|
+
});
|
|
380
|
+
const rows = Array.isArray(data) ? data : (data.entries ?? []);
|
|
381
|
+
return rows.map((row) => {
|
|
382
|
+
const r = row;
|
|
383
|
+
// The server tags each row with a sidecar `_score`, but `fetch` has
|
|
384
|
+
// already run convertKeys (snake→camel), which rewrites a leading
|
|
385
|
+
// underscore key into a capitalized one — so `_score` arrives as `Score`.
|
|
386
|
+
// Read that first, falling back to the raw forms for older servers.
|
|
387
|
+
const rawScore = r.Score ?? r._score ?? r.score;
|
|
388
|
+
const score = typeof rawScore === "number" ? rawScore : 0;
|
|
389
|
+
return { entry: r, score };
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
/** Full version history of a key, ordered by version. */
|
|
393
|
+
async historyAsync(entityPath, key, options) {
|
|
394
|
+
const params = new URLSearchParams();
|
|
395
|
+
if (options?.since)
|
|
396
|
+
params.set("since", options.since);
|
|
397
|
+
if (options?.until)
|
|
398
|
+
params.set("until", options.until);
|
|
399
|
+
const qs = params.toString();
|
|
400
|
+
const data = await this.fetch(`/api/v1/history/${encodeURIComponent(entityPath)}/${encodeURIComponent(key)}${qs ? `?${qs}` : ""}`);
|
|
401
|
+
if (Array.isArray(data))
|
|
402
|
+
return data;
|
|
403
|
+
return data.versions ?? [];
|
|
404
|
+
}
|
|
405
|
+
/** Recent timeline events for an agent (writes, outcomes, cross-agent reads). */
|
|
406
|
+
async timelineAsync(agentId, options) {
|
|
407
|
+
const params = new URLSearchParams();
|
|
408
|
+
if (options?.eventType)
|
|
409
|
+
params.set("event_type", options.eventType);
|
|
410
|
+
if (options?.since)
|
|
411
|
+
params.set("since", options.since);
|
|
412
|
+
if (options?.branch)
|
|
413
|
+
params.set("branch", options.branch);
|
|
414
|
+
params.set("limit", String(options?.limit ?? 100));
|
|
415
|
+
const data = await this.fetch(`/api/v1/agents/${encodeURIComponent(agentId)}/timeline?${params.toString()}`);
|
|
416
|
+
if (Array.isArray(data))
|
|
417
|
+
return data;
|
|
418
|
+
return data.events ?? [];
|
|
419
|
+
}
|
|
420
|
+
/** Related entities in the knowledge graph (Pro). */
|
|
421
|
+
async graphNeighborsAsync(options) {
|
|
422
|
+
const params = new URLSearchParams();
|
|
423
|
+
params.set("entity", options.entity);
|
|
424
|
+
if (options.relation)
|
|
425
|
+
params.set("relation", options.relation);
|
|
426
|
+
if (options.direction)
|
|
427
|
+
params.set("direction", options.direction);
|
|
428
|
+
if (options.minConfidence != null)
|
|
429
|
+
params.set("min_confidence", String(options.minConfidence));
|
|
430
|
+
if (options.depth != null)
|
|
431
|
+
params.set("depth", String(options.depth));
|
|
432
|
+
if (options.limit != null)
|
|
433
|
+
params.set("limit", String(options.limit));
|
|
434
|
+
const data = await this.fetch(`/api/v1/pro/graph/neighbors?${params.toString()}`);
|
|
435
|
+
if (Array.isArray(data))
|
|
436
|
+
return data;
|
|
437
|
+
return data.edges ?? [];
|
|
438
|
+
}
|
|
439
|
+
/** Export outcome-validated knowledge as a fine-tuning dataset (Pro). */
|
|
440
|
+
async exportTrainingDataAsync(options) {
|
|
441
|
+
const params = new URLSearchParams();
|
|
442
|
+
params.set("format", options?.format ?? "sft");
|
|
443
|
+
params.set("min_confidence", String(options?.minConfidence ?? 0.7));
|
|
444
|
+
params.set("limit", String(options?.limit ?? 100));
|
|
445
|
+
if (options?.entityPath)
|
|
446
|
+
params.set("entity_path", options.entityPath);
|
|
447
|
+
return this.fetch(`/api/v1/pro/export?${params.toString()}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function asRecord(value) {
|
|
451
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
452
|
+
? value
|
|
453
|
+
: {};
|
|
454
|
+
}
|
|
455
|
+
function toToolCall(raw) {
|
|
456
|
+
const r = asRecord(raw);
|
|
457
|
+
return {
|
|
458
|
+
toolName: String(r.tool_name ?? ""),
|
|
459
|
+
// Caller-owned keys: never camelCased.
|
|
460
|
+
arguments: asRecord(r.arguments),
|
|
461
|
+
resultSummary: String(r.result_summary ?? ""),
|
|
462
|
+
resultHash: String(r.result_hash ?? ""),
|
|
463
|
+
startedAt: typeof r.started_at === "string" ? r.started_at : undefined,
|
|
464
|
+
durationMs: typeof r.duration_ms === "number" ? r.duration_ms : 0,
|
|
465
|
+
source: r.source ?? null,
|
|
466
|
+
success: r.success !== false,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
function toSessionMetadata(raw) {
|
|
470
|
+
if (raw === null || raw === undefined)
|
|
471
|
+
return null;
|
|
472
|
+
const r = asRecord(raw);
|
|
473
|
+
return {
|
|
474
|
+
model: r.model ?? null,
|
|
475
|
+
clientName: r.client_name ?? null,
|
|
476
|
+
platform: r.platform ?? null,
|
|
477
|
+
toolsAvailable: Array.isArray(r.tools_available) ? r.tools_available.map(String) : [],
|
|
478
|
+
mcpClientId: r.mcp_client_id ?? null,
|
|
479
|
+
mcpSessionId: r.mcp_session_id ?? null,
|
|
480
|
+
attributes: toAttributeBag(r.attributes),
|
|
481
|
+
// Caller-owned records: keys stay as the wire has them.
|
|
482
|
+
llmCalls: Array.isArray(r.llm_calls) ? r.llm_calls.map(asRecord) : [],
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
function toAttributeBag(raw) {
|
|
486
|
+
const out = {};
|
|
487
|
+
for (const [k, v] of Object.entries(asRecord(raw))) {
|
|
488
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean")
|
|
489
|
+
out[k] = v;
|
|
490
|
+
}
|
|
491
|
+
return out;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Map a raw (snake_case) trace from the server to a `DecisionTrace`.
|
|
495
|
+
*
|
|
496
|
+
* The bulk of the object goes through the generic key converter, as before;
|
|
497
|
+
* the fields the converter would get wrong are set explicitly afterwards:
|
|
498
|
+
* `toolCalls[].arguments` must keep the caller's own keys, and
|
|
499
|
+
* `taskInput` / `responseText` / `sessionMetadata` must exist (null, not
|
|
500
|
+
* undefined) so consumers can distinguish "not captured" from "old server".
|
|
501
|
+
*/
|
|
502
|
+
export function toDecisionTrace(raw) {
|
|
503
|
+
const r = asRecord(raw);
|
|
504
|
+
const converted = convertKeys(r);
|
|
505
|
+
const toolCalls = Array.isArray(r.tool_calls) ? r.tool_calls.map(toToolCall) : [];
|
|
506
|
+
return {
|
|
507
|
+
...converted,
|
|
508
|
+
taskInput: r.task_input ?? null,
|
|
509
|
+
responseText: r.response_text ?? null,
|
|
510
|
+
toolCalls,
|
|
511
|
+
sessionMetadata: toSessionMetadata(r.session_metadata),
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/** ISO-8601 for a query parameter; `undefined` when absent or unparseable. */
|
|
515
|
+
function toIsoString(value) {
|
|
516
|
+
if (value === undefined)
|
|
517
|
+
return undefined;
|
|
518
|
+
if (value instanceof Date)
|
|
519
|
+
return Number.isNaN(value.getTime()) ? undefined : value.toISOString();
|
|
520
|
+
return Number.isNaN(Date.parse(value)) ? undefined : value;
|
|
521
|
+
}
|
|
522
|
+
/** Map a raw GET /api/v1/traces body (new page shape or legacy array) to a page. */
|
|
523
|
+
export function toDecisionTracePage(raw) {
|
|
524
|
+
const rows = Array.isArray(raw)
|
|
525
|
+
? raw
|
|
526
|
+
: Array.isArray(asRecord(raw).traces)
|
|
527
|
+
? asRecord(raw).traces
|
|
528
|
+
: [];
|
|
529
|
+
const body = Array.isArray(raw) ? {} : asRecord(raw);
|
|
530
|
+
const traces = rows.map((t) => toDecisionTrace(t));
|
|
531
|
+
return {
|
|
532
|
+
traces,
|
|
533
|
+
nextCursor: typeof body.next_cursor === "string" ? body.next_cursor : null,
|
|
534
|
+
hasMore: body.has_more === true,
|
|
535
|
+
};
|
|
172
536
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @senselab-ai/amfs — Agent Memory File System TypeScript SDK
|
|
3
3
|
*/
|
|
4
|
-
export { AgentMemory, MemoryScope } from "./memory.js";
|
|
4
|
+
export { AgentMemory, MemoryScope, API_KEY_ENV, BRANCH_ENV, HTTP_URL_ENV, MEMORY_BRANCH_ATTRIBUTE, } from "./memory.js";
|
|
5
5
|
export type { AgentMemoryOptions, SearchOptions, MemoryStats } from "./memory.js";
|
|
6
6
|
export type { AmfsAdapter, WatchHandle } from "./adapter.js";
|
|
7
7
|
export { createWatchHandle } from "./adapter.js";
|
|
8
8
|
export { InMemoryAdapter } from "./adapters/filesystem.js";
|
|
9
|
-
export { HttpAdapter } from "./adapters/http.js";
|
|
10
|
-
export type { HttpAdapterOptions, DecisionTrace, DecisionTraceSummary } from "./adapters/http.js";
|
|
9
|
+
export { AGENT_ID_HEADER, HttpAdapter, SESSION_HEADER, toDecisionTrace, toDecisionTracePage, } from "./adapters/http.js";
|
|
10
|
+
export type { HttpAdapterOptions, DecisionTrace, DecisionTraceSummary, DecisionTracePage, ListTracesOptions, ToolCall, SessionMetadata, } from "./adapters/http.js";
|
|
11
|
+
export { validateSessionAttributes, SESSION_ATTRIBUTES_MAX_KEYS, SDK_STAMPED_ATTRIBUTES, SESSION_ATTRIBUTE_KEY_MAX_LEN, SESSION_ATTRIBUTE_VALUE_MAX_LEN, } from "./session.js";
|
|
12
|
+
export type { AttributeValue, SessionAttributes, RecordLlmCallInput, LlmCallRecord, } from "./session.js";
|
|
13
|
+
export { instrumentOpenAI, instrumentAnthropic } from "./instrument/index.js";
|
|
14
|
+
export type { LlmCallSink } from "./instrument/index.js";
|
|
11
15
|
export { CausalTagger, CoWEngine } from "./engine.js";
|
|
12
16
|
export { ReadTracker } from "./tracker.js";
|
|
13
17
|
export type { ExternalContext } from "./tracker.js";
|
|
14
18
|
export { OutcomeBackPropagator } from "./outcome.js";
|
|
19
|
+
export { ReplayReceiver, ReplayError, SignatureError, PayloadError, parseReplayRequest, signReplayBody, verifyReplaySignature, replayAttributes, replayOutcomeRef, createFetchHandler, commitAttributes, serveReplay, CASE_ID_ATTRIBUTE, EVENT_PING, EVENT_REPLAY_REQUESTED, SIGNATURE_HEADER, EVENT_HEADER, DELIVERY_HEADER, } from "./replay.js";
|
|
20
|
+
export type { ReplayRequest, ReplayResult, ReplayAnswer, ReplayMemory, ReplayReceiverOptions, ReplayResponse, HeaderBag, } from "./replay.js";
|
|
15
21
|
export { defaultConfig } from "./config.js";
|
|
16
|
-
export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
22
|
+
export { MemoryType, OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
17
23
|
export type { MemoryEntry, OutcomeRecord, Provenance, ArtifactRef, AMFSConfig, LayerConfig, RecallConfig, ScopeInfo, ScoredEntry, } from "./models.js";
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @senselab-ai/amfs — Agent Memory File System TypeScript SDK
|
|
3
3
|
*/
|
|
4
|
-
export { AgentMemory, MemoryScope } from "./memory.js";
|
|
4
|
+
export { AgentMemory, MemoryScope, API_KEY_ENV, BRANCH_ENV, HTTP_URL_ENV, MEMORY_BRANCH_ATTRIBUTE, } from "./memory.js";
|
|
5
5
|
export { createWatchHandle } from "./adapter.js";
|
|
6
6
|
export { InMemoryAdapter } from "./adapters/filesystem.js";
|
|
7
|
-
export { HttpAdapter } from "./adapters/http.js";
|
|
7
|
+
export { AGENT_ID_HEADER, HttpAdapter, SESSION_HEADER, toDecisionTrace, toDecisionTracePage, } from "./adapters/http.js";
|
|
8
|
+
export { validateSessionAttributes, SESSION_ATTRIBUTES_MAX_KEYS, SDK_STAMPED_ATTRIBUTES, SESSION_ATTRIBUTE_KEY_MAX_LEN, SESSION_ATTRIBUTE_VALUE_MAX_LEN, } from "./session.js";
|
|
9
|
+
export { instrumentOpenAI, instrumentAnthropic } from "./instrument/index.js";
|
|
8
10
|
export { CausalTagger, CoWEngine } from "./engine.js";
|
|
9
11
|
export { ReadTracker } from "./tracker.js";
|
|
10
12
|
export { OutcomeBackPropagator } from "./outcome.js";
|
|
13
|
+
export { ReplayReceiver, ReplayError, SignatureError, PayloadError, parseReplayRequest, signReplayBody, verifyReplaySignature, replayAttributes, replayOutcomeRef, createFetchHandler, commitAttributes, serveReplay, CASE_ID_ATTRIBUTE, EVENT_PING, EVENT_REPLAY_REQUESTED, SIGNATURE_HEADER, EVENT_HEADER, DELIVERY_HEADER, } from "./replay.js";
|
|
11
14
|
export { defaultConfig } from "./config.js";
|
|
12
|
-
export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
15
|
+
export { MemoryType, OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentAnthropic(client, memory)` — every `messages.create` on the
|
|
3
|
+
* `@anthropic-ai/sdk` client is recorded with `memory.recordLlmCall`.
|
|
4
|
+
*
|
|
5
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends: input
|
|
6
|
+
* tokens come from `message_start`, output tokens from the final
|
|
7
|
+
* `message_delta`. The `messages.stream()` helper is not patched; iterate
|
|
8
|
+
* `create({ stream: true })` or call `memory.recordLlmCall` by hand.
|
|
9
|
+
* `@anthropic-ai/sdk` is an optional peer and is not imported here.
|
|
10
|
+
*/
|
|
11
|
+
import type { Extractor, LlmCallSink } from "./common.js";
|
|
12
|
+
export declare const extractMessage: Extractor;
|
|
13
|
+
export declare const extractMessageEvent: Extractor;
|
|
14
|
+
/** Instrument an Anthropic client in place and return it. Idempotent. */
|
|
15
|
+
export declare function instrumentAnthropic<C>(client: C, memory: LlmCallSink): C;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentAnthropic(client, memory)` — every `messages.create` on the
|
|
3
|
+
* `@anthropic-ai/sdk` client is recorded with `memory.recordLlmCall`.
|
|
4
|
+
*
|
|
5
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends: input
|
|
6
|
+
* tokens come from `message_start`, output tokens from the final
|
|
7
|
+
* `message_delta`. The `messages.stream()` helper is not patched; iterate
|
|
8
|
+
* `create({ stream: true })` or call `memory.recordLlmCall` by hand.
|
|
9
|
+
* `@anthropic-ai/sdk` is an optional peer and is not imported here.
|
|
10
|
+
*/
|
|
11
|
+
import { asInt, get, isInstrumented, markInstrumented, patchMethod, resolve } from "./common.js";
|
|
12
|
+
const PROVIDER = "anthropic";
|
|
13
|
+
function readUsage(u, usage, outputOnly = false) {
|
|
14
|
+
if (!u)
|
|
15
|
+
return;
|
|
16
|
+
if (!outputOnly) {
|
|
17
|
+
const inTok = asInt(get(u, "input_tokens"));
|
|
18
|
+
if (inTok !== undefined)
|
|
19
|
+
usage.inputTokens = inTok;
|
|
20
|
+
}
|
|
21
|
+
const outTok = asInt(get(u, "output_tokens"));
|
|
22
|
+
if (outTok !== undefined)
|
|
23
|
+
usage.outputTokens = outTok;
|
|
24
|
+
}
|
|
25
|
+
export const extractMessage = (message, usage) => {
|
|
26
|
+
const model = get(message, "model");
|
|
27
|
+
if (typeof model === "string" && model)
|
|
28
|
+
usage.model = model;
|
|
29
|
+
readUsage(get(message, "usage"), usage);
|
|
30
|
+
};
|
|
31
|
+
export const extractMessageEvent = (event, usage) => {
|
|
32
|
+
const type = String(get(event, "type") ?? "");
|
|
33
|
+
if (type === "message_start")
|
|
34
|
+
extractMessage(get(event, "message"), usage);
|
|
35
|
+
else if (type === "message_delta")
|
|
36
|
+
readUsage(get(event, "usage"), usage, true);
|
|
37
|
+
};
|
|
38
|
+
/** Instrument an Anthropic client in place and return it. Idempotent. */
|
|
39
|
+
export function instrumentAnthropic(client, memory) {
|
|
40
|
+
if (isInstrumented(client))
|
|
41
|
+
return client;
|
|
42
|
+
const messages = resolve(client, ["messages"]);
|
|
43
|
+
if (messages) {
|
|
44
|
+
patchMethod(messages, "create", {
|
|
45
|
+
provider: PROVIDER,
|
|
46
|
+
sink: memory,
|
|
47
|
+
extract: extractMessage,
|
|
48
|
+
onChunk: extractMessageEvent,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
markInstrumented(client);
|
|
52
|
+
return client;
|
|
53
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared machinery for the provider instrumentations.
|
|
3
|
+
*
|
|
4
|
+
* Each `instrument*` function replaces a client method on the *instance* with a
|
|
5
|
+
* wrapper that times the call, reads token usage off the response (or, for a
|
|
6
|
+
* stream, accumulates it while the caller iterates and records when the stream
|
|
7
|
+
* ends) and hands the result to `memory.recordLlmCall`. The wrapped call is
|
|
8
|
+
* never altered: an instrumentation failure is logged and swallowed, an error
|
|
9
|
+
* from the provider is recorded as a failed call and re-thrown unchanged.
|
|
10
|
+
*
|
|
11
|
+
* Responses are read by duck typing, so neither `openai` nor `@anthropic-ai/sdk`
|
|
12
|
+
* is imported — they are optional peers — and tests drive the wrappers with
|
|
13
|
+
* plain objects.
|
|
14
|
+
*/
|
|
15
|
+
import type { RecordLlmCallInput } from "../session.js";
|
|
16
|
+
/** The one method of `AgentMemory` the instrumentations need. */
|
|
17
|
+
export interface LlmCallSink {
|
|
18
|
+
recordLlmCall(call: RecordLlmCallInput, startedAt?: Date): unknown;
|
|
19
|
+
}
|
|
20
|
+
export interface Usage {
|
|
21
|
+
model?: string;
|
|
22
|
+
inputTokens?: number;
|
|
23
|
+
outputTokens?: number;
|
|
24
|
+
}
|
|
25
|
+
export type Extractor = (response: unknown, usage: Usage) => void;
|
|
26
|
+
export declare function isInstrumented(target: unknown): boolean;
|
|
27
|
+
export declare function markInstrumented(target: unknown): void;
|
|
28
|
+
export declare function get(obj: unknown, key: string): unknown;
|
|
29
|
+
export declare function asInt(value: unknown): number | undefined;
|
|
30
|
+
export declare function resolve(target: unknown, path: string[]): unknown;
|
|
31
|
+
export interface PatchOptions {
|
|
32
|
+
provider: string;
|
|
33
|
+
sink: LlmCallSink;
|
|
34
|
+
/** Reads usage from a complete response. */
|
|
35
|
+
extract: Extractor;
|
|
36
|
+
/** Reads usage from one stream chunk, accumulating into the usage. */
|
|
37
|
+
onChunk: Extractor;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Replace `owner[method]` with an instrumented wrapper. Returns whether anything
|
|
41
|
+
* was patched (`false` when the method is missing or already wrapped).
|
|
42
|
+
*
|
|
43
|
+
* The provider SDKs return a promise-like (`APIPromise`) from `create`; the
|
|
44
|
+
* wrapper awaits it, so callers always get a plain `Promise`. `stream: true`
|
|
45
|
+
* calls resolve to an async iterable, which is proxied.
|
|
46
|
+
*/
|
|
47
|
+
export declare function patchMethod(owner: unknown, method: string, options: PatchOptions): boolean;
|