@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.
- package/dist/adapters/http.d.ts +185 -6
- package/dist/adapters/http.js +315 -12
- 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 +263 -0
- package/dist/memory.js +468 -32
- package/dist/models.d.ts +14 -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.d.ts
CHANGED
|
@@ -9,16 +9,56 @@ export interface HttpAdapterOptions {
|
|
|
9
9
|
agentId?: string;
|
|
10
10
|
headers?: Record<string, string>;
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* Request header naming the agent the calling session acts as. Read routes
|
|
14
|
+
* carry no agent in their query or body, so without it a hosted server cannot
|
|
15
|
+
* attribute a read or look up the agent's live repair canary.
|
|
16
|
+
*/
|
|
17
|
+
export declare const AGENT_ID_HEADER = "X-AMFS-Agent-Id";
|
|
18
|
+
/**
|
|
19
|
+
* Request header carrying the session id the SDK stamps on its trace — the key
|
|
20
|
+
* a hosted server hashes to keep one session on one arm of a live canary. A
|
|
21
|
+
* session that does not send it is never routed.
|
|
22
|
+
*/
|
|
23
|
+
export declare const SESSION_HEADER = "X-AMFS-Session";
|
|
12
24
|
export declare class HttpAdapter implements AmfsAdapter {
|
|
13
25
|
private readonly baseUrl;
|
|
14
26
|
private readonly headers;
|
|
15
27
|
private readonly agentId;
|
|
16
28
|
constructor(opts: HttpAdapterOptions);
|
|
29
|
+
private readonly opts;
|
|
30
|
+
/**
|
|
31
|
+
* An adapter on the same server that identifies itself as `agentId` in
|
|
32
|
+
* `sessionId` on every request. `AgentMemory` calls this when it is built, so
|
|
33
|
+
* two memories sharing one adapter never share an identity. Either id may be
|
|
34
|
+
* omitted; the header is then simply not sent.
|
|
35
|
+
*/
|
|
36
|
+
bind(agentId: string | undefined, sessionId: string | undefined): HttpAdapter;
|
|
37
|
+
/** The identity headers this adapter adds to every request (a copy). */
|
|
38
|
+
get identityHeaders(): Record<string, string>;
|
|
17
39
|
private fetch;
|
|
40
|
+
/** Like `fetch` but returns the server's JSON untouched (snake_case keys). */
|
|
41
|
+
private fetchRaw;
|
|
42
|
+
/**
|
|
43
|
+
* Call a route this adapter has no method for, and get the server's JSON back
|
|
44
|
+
* untouched (snake_case keys).
|
|
45
|
+
*
|
|
46
|
+
* The request is this adapter's own: the same base URL, API key and identity
|
|
47
|
+
* headers as every other call, and the same error, an `Error` whose message
|
|
48
|
+
* carries the status and the response body. `AgentMemory`'s room and
|
|
49
|
+
* negotiation methods go through it. `query` values that are `undefined` or
|
|
50
|
+
* `null` are left out; the rest are URL-encoded.
|
|
51
|
+
*/
|
|
52
|
+
requestRaw(method: string, path: string, options?: {
|
|
53
|
+
body?: unknown;
|
|
54
|
+
query?: Record<string, string | number | boolean | undefined | null>;
|
|
55
|
+
}): Promise<unknown>;
|
|
18
56
|
read(entityPath: string, key: string, options?: {
|
|
19
57
|
minConfidence?: number;
|
|
20
58
|
}): MemoryEntry | null;
|
|
21
|
-
readAsync(entityPath: string, key: string
|
|
59
|
+
readAsync(entityPath: string, key: string, options?: {
|
|
60
|
+
branch?: string;
|
|
61
|
+
}): Promise<MemoryEntry | null>;
|
|
22
62
|
write(entry: MemoryEntry): MemoryEntry;
|
|
23
63
|
writeAsync(entry: {
|
|
24
64
|
entityPath: string;
|
|
@@ -36,6 +76,7 @@ export declare class HttpAdapter implements AmfsAdapter {
|
|
|
36
76
|
}): MemoryEntry[];
|
|
37
77
|
listAsync(entityPath?: string, options?: {
|
|
38
78
|
includeSuperseded?: boolean;
|
|
79
|
+
branch?: string;
|
|
39
80
|
}): Promise<MemoryEntry[]>;
|
|
40
81
|
searchAsync(query: {
|
|
41
82
|
query?: string;
|
|
@@ -59,12 +100,30 @@ export declare class HttpAdapter implements AmfsAdapter {
|
|
|
59
100
|
causalEntryKeys?: string[];
|
|
60
101
|
causalConfidence?: number;
|
|
61
102
|
agentId?: string;
|
|
103
|
+
/**
|
|
104
|
+
* Already in wire shape (`attributes`, `llm_calls`, ...); the server lifts
|
|
105
|
+
* these onto the trace it seals for this outcome.
|
|
106
|
+
*/
|
|
107
|
+
sessionMetadata?: Record<string, unknown>;
|
|
108
|
+
/** The request the run answered — what a judge and training read the trace through. */
|
|
109
|
+
taskInput?: string | null;
|
|
110
|
+
/** The agent's answer, in full. */
|
|
111
|
+
responseText?: string | null;
|
|
112
|
+
/** The actions taken, as `{tool_name, arguments}` rows. */
|
|
113
|
+
toolCalls?: Array<Record<string, unknown>>;
|
|
62
114
|
}): Promise<unknown>;
|
|
63
115
|
statsAsync(): Promise<Record<string, unknown>>;
|
|
64
116
|
healthAsync(): Promise<Record<string, unknown>>;
|
|
65
117
|
briefingAsync(options?: {
|
|
66
118
|
entityPath?: string;
|
|
119
|
+
agentId?: string;
|
|
67
120
|
limit?: number;
|
|
121
|
+
/** Lead digest only, with its evidence sections; a fraction of the tokens. */
|
|
122
|
+
compact?: boolean;
|
|
123
|
+
/** Only what changed after this ISO-8601 moment in the list sections. */
|
|
124
|
+
since?: string;
|
|
125
|
+
/** Brief from a memory branch other than `main` (a repair branch, a canary). */
|
|
126
|
+
branch?: string;
|
|
68
127
|
}): Promise<unknown>;
|
|
69
128
|
consolidationStatusAsync(): Promise<unknown>;
|
|
70
129
|
consolidationProposalsAsync(options?: {
|
|
@@ -77,13 +136,65 @@ export declare class HttpAdapter implements AmfsAdapter {
|
|
|
77
136
|
consolidateAsync(options?: {
|
|
78
137
|
dryRun?: boolean;
|
|
79
138
|
}): Promise<unknown>;
|
|
80
|
-
|
|
139
|
+
/**
|
|
140
|
+
* One page of decision traces, newest first, exactly as the server pages them.
|
|
141
|
+
*
|
|
142
|
+
* Mirrors GET /api/v1/traces: pass `cursor` (the previous page's `nextCursor`)
|
|
143
|
+
* to continue; `offset` is honoured only when no cursor is given. `since`
|
|
144
|
+
* (inclusive) and `until` (exclusive) are sent to the server and bound the
|
|
145
|
+
* query itself, so a window that excludes the newest traces still returns
|
|
146
|
+
* the older matches rather than an empty first page.
|
|
147
|
+
*/
|
|
148
|
+
listTracesPageAsync(options?: ListTracesOptions): Promise<DecisionTracePage>;
|
|
149
|
+
/**
|
|
150
|
+
* Decision traces as a flat array. Accepts the same paging options as
|
|
151
|
+
* {@link listTracesPageAsync}; use that method when you need `nextCursor` /
|
|
152
|
+
* `hasMore` to walk beyond one page.
|
|
153
|
+
*/
|
|
154
|
+
listTracesAsync(options?: ListTracesOptions): Promise<DecisionTraceSummary[]>;
|
|
155
|
+
getTraceAsync(traceId: string): Promise<DecisionTrace | null>;
|
|
156
|
+
/** Server-side semantic retrieval (embedding + similarity + blend happen on the server). */
|
|
157
|
+
retrieveAsync(query: string, options?: {
|
|
81
158
|
entityPath?: string;
|
|
82
|
-
|
|
83
|
-
outcomeType?: string;
|
|
159
|
+
minConfidence?: number;
|
|
84
160
|
limit?: number;
|
|
85
|
-
|
|
86
|
-
|
|
161
|
+
semanticWeight?: number;
|
|
162
|
+
recencyWeight?: number;
|
|
163
|
+
confidenceWeight?: number;
|
|
164
|
+
includeArtifacts?: boolean;
|
|
165
|
+
branch?: string;
|
|
166
|
+
}): Promise<Array<{
|
|
167
|
+
entry: MemoryEntry;
|
|
168
|
+
score: number;
|
|
169
|
+
}>>;
|
|
170
|
+
/** Full version history of a key, ordered by version. */
|
|
171
|
+
historyAsync(entityPath: string, key: string, options?: {
|
|
172
|
+
since?: string;
|
|
173
|
+
until?: string;
|
|
174
|
+
}): Promise<MemoryEntry[]>;
|
|
175
|
+
/** Recent timeline events for an agent (writes, outcomes, cross-agent reads). */
|
|
176
|
+
timelineAsync(agentId: string, options?: {
|
|
177
|
+
eventType?: string;
|
|
178
|
+
since?: string;
|
|
179
|
+
limit?: number;
|
|
180
|
+
branch?: string;
|
|
181
|
+
}): Promise<unknown[]>;
|
|
182
|
+
/** Related entities in the knowledge graph (Pro). */
|
|
183
|
+
graphNeighborsAsync(options: {
|
|
184
|
+
entity: string;
|
|
185
|
+
relation?: string;
|
|
186
|
+
direction?: string;
|
|
187
|
+
minConfidence?: number;
|
|
188
|
+
depth?: number;
|
|
189
|
+
limit?: number;
|
|
190
|
+
}): Promise<unknown[]>;
|
|
191
|
+
/** Export outcome-validated knowledge as a fine-tuning dataset (Pro). */
|
|
192
|
+
exportTrainingDataAsync(options?: {
|
|
193
|
+
entityPath?: string;
|
|
194
|
+
minConfidence?: number;
|
|
195
|
+
format?: "sft" | "dpo" | "reward_model";
|
|
196
|
+
limit?: number;
|
|
197
|
+
}): Promise<unknown>;
|
|
87
198
|
}
|
|
88
199
|
export interface DecisionTraceSummary {
|
|
89
200
|
id: string;
|
|
@@ -96,6 +207,55 @@ export interface DecisionTraceSummary {
|
|
|
96
207
|
sessionDurationMs?: number;
|
|
97
208
|
createdAt: string;
|
|
98
209
|
}
|
|
210
|
+
/** Filters and paging for GET /api/v1/traces. */
|
|
211
|
+
export interface ListTracesOptions {
|
|
212
|
+
entityPath?: string;
|
|
213
|
+
agentId?: string;
|
|
214
|
+
outcomeType?: string;
|
|
215
|
+
limit?: number;
|
|
216
|
+
/** Rows to skip; honoured only when no `cursor` is given. */
|
|
217
|
+
offset?: number;
|
|
218
|
+
/** Opaque keyset position — the `nextCursor` of the previous page. */
|
|
219
|
+
cursor?: string;
|
|
220
|
+
/** Only traces created at or after this instant (ISO-8601 string or Date). */
|
|
221
|
+
since?: string | Date;
|
|
222
|
+
/** Only traces created before this instant (ISO-8601 string or Date). */
|
|
223
|
+
until?: string | Date;
|
|
224
|
+
}
|
|
225
|
+
/** One page of GET /api/v1/traces. Follow `nextCursor` while `hasMore` is true. */
|
|
226
|
+
export interface DecisionTracePage {
|
|
227
|
+
traces: DecisionTraceSummary[];
|
|
228
|
+
nextCursor: string | null;
|
|
229
|
+
hasMore: boolean;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* An action the agent recorded during the session (`amfs_record_action`).
|
|
233
|
+
* `arguments` is passed through exactly as stored — its keys are the caller's,
|
|
234
|
+
* not the API's, so they are not converted to camelCase.
|
|
235
|
+
*/
|
|
236
|
+
export interface ToolCall {
|
|
237
|
+
toolName: string;
|
|
238
|
+
arguments: Record<string, unknown>;
|
|
239
|
+
resultSummary: string;
|
|
240
|
+
resultHash: string;
|
|
241
|
+
startedAt?: string;
|
|
242
|
+
durationMs: number;
|
|
243
|
+
source?: string | null;
|
|
244
|
+
success: boolean;
|
|
245
|
+
}
|
|
246
|
+
/** Which model, client and toolset produced the session's decisions. */
|
|
247
|
+
export interface SessionMetadata {
|
|
248
|
+
model?: string | null;
|
|
249
|
+
clientName?: string | null;
|
|
250
|
+
platform?: string | null;
|
|
251
|
+
toolsAvailable: string[];
|
|
252
|
+
mcpClientId?: string | null;
|
|
253
|
+
mcpSessionId?: string | null;
|
|
254
|
+
/** The run's dimensions (`customer`, `task_type`, ...), when any were set. */
|
|
255
|
+
attributes: Record<string, string | number | boolean>;
|
|
256
|
+
/** LLM calls recorded for the run, in wire shape (snake_case keys). */
|
|
257
|
+
llmCalls: Array<Record<string, unknown>>;
|
|
258
|
+
}
|
|
99
259
|
export interface DecisionTrace {
|
|
100
260
|
id: string;
|
|
101
261
|
agentId: string;
|
|
@@ -103,6 +263,13 @@ export interface DecisionTrace {
|
|
|
103
263
|
outcomeRef: string;
|
|
104
264
|
outcomeType: string;
|
|
105
265
|
decisionSummary?: string;
|
|
266
|
+
/** The request that started the work, as it arrived (may be redacted). */
|
|
267
|
+
taskInput?: string | null;
|
|
268
|
+
/** The agent's answer, when it was captured. */
|
|
269
|
+
responseText?: string | null;
|
|
270
|
+
/** Actions the agent recorded; empty for read/write-only sessions. */
|
|
271
|
+
toolCalls: ToolCall[];
|
|
272
|
+
sessionMetadata?: SessionMetadata | null;
|
|
106
273
|
causalEntries: Array<{
|
|
107
274
|
entityPath: string;
|
|
108
275
|
key: string;
|
|
@@ -142,3 +309,15 @@ export interface DecisionTrace {
|
|
|
142
309
|
sessionDurationMs?: number;
|
|
143
310
|
createdAt: string;
|
|
144
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Map a raw (snake_case) trace from the server to a `DecisionTrace`.
|
|
314
|
+
*
|
|
315
|
+
* The bulk of the object goes through the generic key converter, as before;
|
|
316
|
+
* the fields the converter would get wrong are set explicitly afterwards:
|
|
317
|
+
* `toolCalls[].arguments` must keep the caller's own keys, and
|
|
318
|
+
* `taskInput` / `responseText` / `sessionMetadata` must exist (null, not
|
|
319
|
+
* undefined) so consumers can distinguish "not captured" from "old server".
|
|
320
|
+
*/
|
|
321
|
+
export declare function toDecisionTrace(raw: unknown): DecisionTrace;
|
|
322
|
+
/** Map a raw GET /api/v1/traces body (new page shape or legacy array) to a page. */
|
|
323
|
+
export declare function toDecisionTracePage(raw: unknown): DecisionTracePage;
|
package/dist/adapters/http.js
CHANGED
|
@@ -2,6 +2,25 @@
|
|
|
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
|
+
}
|
|
5
24
|
function snakeToCamel(str) {
|
|
6
25
|
return str.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
7
26
|
}
|
|
@@ -24,7 +43,12 @@ export class HttpAdapter {
|
|
|
24
43
|
headers;
|
|
25
44
|
agentId;
|
|
26
45
|
constructor(opts) {
|
|
27
|
-
|
|
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);
|
|
28
52
|
this.agentId = opts.agentId;
|
|
29
53
|
this.headers = {
|
|
30
54
|
"Content-Type": "application/json",
|
|
@@ -33,8 +57,44 @@ export class HttpAdapter {
|
|
|
33
57
|
if (opts.apiKey) {
|
|
34
58
|
this.headers["X-AMFS-API-Key"] = opts.apiKey;
|
|
35
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;
|
|
36
91
|
}
|
|
37
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) {
|
|
38
98
|
const resp = await globalThis.fetch(`${this.baseUrl}${path}`, {
|
|
39
99
|
...init,
|
|
40
100
|
headers: { ...this.headers, ...init?.headers },
|
|
@@ -43,15 +103,40 @@ export class HttpAdapter {
|
|
|
43
103
|
const body = await resp.text().catch(() => "");
|
|
44
104
|
throw new Error(`AMFS API ${resp.status}: ${body}`);
|
|
45
105
|
}
|
|
46
|
-
|
|
47
|
-
|
|
106
|
+
return resp.json();
|
|
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
|
+
});
|
|
48
129
|
}
|
|
49
130
|
read(entityPath, key, options) {
|
|
50
131
|
return null;
|
|
51
132
|
}
|
|
52
|
-
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();
|
|
53
138
|
try {
|
|
54
|
-
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}` : ""}`);
|
|
55
140
|
}
|
|
56
141
|
catch {
|
|
57
142
|
return null;
|
|
@@ -86,6 +171,8 @@ export class HttpAdapter {
|
|
|
86
171
|
params.set("entity_path", entityPath);
|
|
87
172
|
if (options?.includeSuperseded)
|
|
88
173
|
params.set("include_superseded", "true");
|
|
174
|
+
if (options?.branch && options.branch !== "main")
|
|
175
|
+
params.set("branch", options.branch);
|
|
89
176
|
const qs = params.toString();
|
|
90
177
|
const data = await this.fetch(`/api/v1/entries${qs ? `?${qs}` : ""}`);
|
|
91
178
|
if (Array.isArray(data))
|
|
@@ -106,7 +193,8 @@ export class HttpAdapter {
|
|
|
106
193
|
...(query.patternRef ? { pattern_ref: query.patternRef } : {}),
|
|
107
194
|
...(query.sortBy ? { sort_by: query.sortBy } : {}),
|
|
108
195
|
...(query.depth != null ? { depth: query.depth } : {}),
|
|
109
|
-
|
|
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 } : {}),
|
|
110
198
|
}),
|
|
111
199
|
});
|
|
112
200
|
}
|
|
@@ -163,6 +251,12 @@ export class HttpAdapter {
|
|
|
163
251
|
...(record.causalEntryKeys?.length ? { causal_entry_keys: record.causalEntryKeys } : {}),
|
|
164
252
|
...(record.causalConfidence != null ? { causal_confidence: record.causalConfidence } : {}),
|
|
165
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 } : {}),
|
|
166
260
|
}),
|
|
167
261
|
});
|
|
168
262
|
}
|
|
@@ -176,8 +270,16 @@ export class HttpAdapter {
|
|
|
176
270
|
const params = new URLSearchParams();
|
|
177
271
|
if (options?.entityPath)
|
|
178
272
|
params.set("entity_path", options.entityPath);
|
|
273
|
+
if (options?.agentId)
|
|
274
|
+
params.set("agent_id", options.agentId);
|
|
179
275
|
if (options?.limit)
|
|
180
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);
|
|
181
283
|
const qs = params.toString();
|
|
182
284
|
return this.fetch(`/api/v1/briefing${qs ? `?${qs}` : ""}`);
|
|
183
285
|
}
|
|
@@ -206,7 +308,16 @@ export class HttpAdapter {
|
|
|
206
308
|
body: JSON.stringify({ dry_run: options?.dryRun ?? true }),
|
|
207
309
|
});
|
|
208
310
|
}
|
|
209
|
-
|
|
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) {
|
|
210
321
|
const params = new URLSearchParams();
|
|
211
322
|
if (options?.entityPath)
|
|
212
323
|
params.set("entity_path", options.entityPath);
|
|
@@ -216,18 +327,210 @@ export class HttpAdapter {
|
|
|
216
327
|
params.set("outcome_type", options.outcomeType);
|
|
217
328
|
if (options?.limit)
|
|
218
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);
|
|
219
340
|
const qs = params.toString();
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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;
|
|
224
352
|
}
|
|
225
353
|
async getTraceAsync(traceId) {
|
|
226
354
|
try {
|
|
227
|
-
|
|
355
|
+
const raw = await this.fetchRaw(`/api/v1/traces/${encodeURIComponent(traceId)}`);
|
|
356
|
+
return toDecisionTrace(raw);
|
|
228
357
|
}
|
|
229
358
|
catch {
|
|
230
359
|
return null;
|
|
231
360
|
}
|
|
232
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
|
+
};
|
|
233
536
|
}
|