@agent-custody/state 0.8.0 → 0.9.0

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/stores.js CHANGED
@@ -1,10 +1,38 @@
1
+ /**
2
+ * The storedAt field of an entry: the first of the given times that parses, as an ISO string. The custody storedAt comes
3
+ * first. The store's own creation time follows, for entries that version 0.7.0 or earlier wrote.
4
+ */
5
+ const stored = (...times) => {
6
+ for (const t of times) {
7
+ const d = typeof t === "string" || t instanceof Date ? new Date(t) : null;
8
+ if (d && !Number.isNaN(d.getTime()))
9
+ return { storedAt: d.toISOString() };
10
+ }
11
+ return {};
12
+ };
13
+ /**
14
+ * The ids of a page that no earlier page of the same listing returned. A non-empty page with none of them means the
15
+ * backend ignores the cursor, and the listing throws instead of looping forever.
16
+ */
17
+ function freshIds(store, seen, ids) {
18
+ const fresh = new Set(ids.filter((i) => !seen.has(i)));
19
+ if (ids.length > 0 && fresh.size === 0)
20
+ throw new Error(`${store}: listing does not advance`);
21
+ for (const i of fresh)
22
+ seen.add(i);
23
+ return fresh;
24
+ }
25
+ /** The entry a fact has in a store, from the id the ledger recorded for it there. */
26
+ export function entryOf(fact, externalId) {
27
+ return { externalId, factId: fact.factId, text: factText(fact) };
28
+ }
1
29
  /** One line a retrieval store can index: what the fact says, in words. */
2
30
  export function factText(f) {
3
31
  return `${f.subject} ${f.predicate}: ${typeof f.value === "string" ? f.value : JSON.stringify(f.value)}`;
4
32
  }
5
33
  /** Metadata every store receives alongside the text, so a memory can always be traced back to its custody. */
6
34
  export function factMetadata(f) {
7
- return { factId: f.factId, space: f.space, actor: f.actor, provenance: f.provenance, receiptId: f.source.receiptId, validFrom: f.validFrom, source: "agent-custody" };
35
+ return { factId: f.factId, space: f.space, actor: f.actor, provenance: f.provenance, receiptId: f.source.receiptId, validFrom: f.validFrom, source: "agent-custody", storedAt: new Date().toISOString() /* the time of the store write, not of the fact; repair compares it with its cutoff */ };
8
36
  }
9
37
  export function mem0Store(client, opts) {
10
38
  return {
@@ -16,15 +44,35 @@ export function mem0Store(client, opts) {
16
44
  throw new Error("mem0 returned no memory id");
17
45
  return id;
18
46
  },
19
- async remove(externalId) {
47
+ async delete({ externalId }) {
20
48
  await client.delete(externalId);
21
49
  },
22
50
  ...(client.search
23
51
  ? {
24
- async verifyRemoved(externalId, fact) {
52
+ async verifyDeleted({ externalId, text }) {
25
53
  // Mem0's search scopes by filters, not by top-level entity parameters; the real client refuses the latter.
26
- const { results } = await client.search(factText(fact), { filters: { user_id: opts.userId } });
27
- return !results.some((r) => r.id === externalId || r.memory === factText(fact));
54
+ const { results } = await client.search(text, { filters: { user_id: opts.userId } });
55
+ return !results.some((r) => r.id === externalId || r.memory === text);
56
+ },
57
+ }
58
+ : {}),
59
+ ...(client.getAll
60
+ ? {
61
+ async list() {
62
+ const out = [];
63
+ const seen = new Set();
64
+ // The API is paginated by `next`, and it answers a page past the end with 404: never ask for that page.
65
+ for (let page = 1;; page++) {
66
+ const { results, next } = await client.getAll({ filters: { user_id: opts.userId }, page, pageSize: 100 });
67
+ const fresh = freshIds("mem0", seen, results.flatMap((r) => (r.id ? [r.id] : [])));
68
+ for (const r of results) {
69
+ const m = (r.metadata ?? {});
70
+ if (r.id && fresh.has(r.id) && m.source === "agent-custody" && typeof m.factId === "string")
71
+ out.push({ externalId: r.id, factId: m.factId, text: r.memory ?? "", ...stored(m.storedAt, r.createdAt) });
72
+ }
73
+ if (!next || results.length === 0)
74
+ return out;
75
+ }
28
76
  },
29
77
  }
30
78
  : {}),
@@ -35,25 +83,61 @@ export function zepStore(client, opts) {
35
83
  name: "zep",
36
84
  async put(fact) {
37
85
  const target = opts.graphId ? { graphId: opts.graphId } : { userId: opts.userId };
38
- const episode = await client.graph.add({ ...target, type: "json", data: JSON.stringify({ subject: fact.subject, predicate: fact.predicate, value: fact.value, ...factMetadata(fact) }), sourceDescription: "agent-custody", metadata: factMetadata(fact) });
86
+ const meta = factMetadata(fact);
87
+ const episode = await client.graph.add({ ...target, type: "json", data: JSON.stringify({ subject: fact.subject, predicate: fact.predicate, value: fact.value, ...meta }), sourceDescription: "agent-custody", metadata: meta });
39
88
  if (!episode?.uuid)
40
89
  throw new Error("zep returned no episode uuid");
41
90
  return episode.uuid;
42
91
  },
43
- async remove(externalId) {
92
+ async delete({ externalId }) {
44
93
  await client.graph.episode.delete(externalId);
45
94
  },
46
95
  ...(client.graph.search
47
96
  ? {
48
- async verifyRemoved(externalId, fact) {
97
+ async verifyDeleted({ externalId, text }) {
49
98
  const target = opts.graphId ? { graphId: opts.graphId } : { userId: opts.userId };
50
- const r = await client.graph.search({ ...target, query: factText(fact), limit: 20 });
99
+ const r = await client.graph.search({ ...target, query: text, limit: 20 });
51
100
  const episodeHit = (r.episodes ?? []).some((e) => e.uuid === externalId);
52
101
  const edgeHit = (r.edges ?? []).some((e) => (e.episodes ?? []).includes(externalId));
53
102
  return !episodeHit && !edgeHit;
54
103
  },
55
104
  }
56
105
  : {}),
106
+ ...((opts.graphId ? client.graph.episode.listByGraphId : client.graph.episode.listByUserId)
107
+ ? {
108
+ async list() {
109
+ const out = [];
110
+ const seen = new Set();
111
+ const cursors = new Set();
112
+ let cursor;
113
+ do {
114
+ const request = { limit: 50, ...(cursor ? { cursor } : {}) };
115
+ const { data, rawResponse } = await (opts.graphId ? client.graph.episode.listByGraphId(opts.graphId, request) : client.graph.episode.listByUserId(opts.userId, request)).withRawResponse();
116
+ const fresh = freshIds("zep", seen, data.map((e) => e.uuid));
117
+ for (const e of data) {
118
+ if (!fresh.has(e.uuid))
119
+ continue;
120
+ // The episode content is the JSON that put wrote. Text is rebuilt from it, the way search indexes it.
121
+ let d;
122
+ try {
123
+ d = JSON.parse(e.content);
124
+ }
125
+ catch {
126
+ continue;
127
+ }
128
+ if (d && d.source === "agent-custody" && typeof d.factId === "string")
129
+ out.push({ externalId: e.uuid, factId: d.factId, text: factText({ subject: String(d.subject), predicate: String(d.predicate), value: d.value }), ...stored(d.storedAt, e.createdAt) });
130
+ }
131
+ cursor = rawResponse.headers.get("Zep-Next-Cursor") || undefined;
132
+ if (cursor && cursors.has(cursor))
133
+ throw new Error("zep: listing does not advance");
134
+ if (cursor)
135
+ cursors.add(cursor);
136
+ } while (cursor);
137
+ return out;
138
+ },
139
+ }
140
+ : {}),
57
141
  };
58
142
  }
59
143
  /**
@@ -85,15 +169,20 @@ export function pgvectorStore(client, opts) {
85
169
  await client.query(`INSERT INTO ${table} (id, text, embedding, metadata) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO UPDATE SET text = EXCLUDED.text, embedding = EXCLUDED.embedding, metadata = EXCLUDED.metadata`, [fact.factId, text, literal(await opts.embed(text)), JSON.stringify(factMetadata(fact))]);
86
170
  return fact.factId;
87
171
  },
88
- async remove(externalId) {
172
+ async delete({ externalId }) {
89
173
  await init();
90
174
  await client.query(`DELETE FROM ${table} WHERE id = $1`, [externalId]);
91
175
  },
92
- async verifyRemoved(externalId, fact) {
176
+ async verifyDeleted({ externalId, text }) {
93
177
  await init();
94
- const rows = (await client.query(`SELECT id FROM ${table} ORDER BY embedding <=> $1 LIMIT $2`, [literal(await opts.embed(factText(fact))), opts.topK ?? 10])).rows;
178
+ const rows = (await client.query(`SELECT id FROM ${table} ORDER BY embedding <=> $1 LIMIT $2`, [literal(await opts.embed(text)), opts.topK ?? 10])).rows;
95
179
  return !rows.some((r) => r.id === externalId);
96
180
  },
181
+ async list() {
182
+ await init();
183
+ const rows = (await client.query(`SELECT id, text, metadata->>'factId' AS fact_id, COALESCE(metadata->>'storedAt', to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')) AS stored_at FROM ${table} WHERE metadata->>'source' = 'agent-custody'`)).rows;
184
+ return rows.filter((r) => r.fact_id).map((r) => ({ externalId: r.id, factId: r.fact_id, text: r.text, storedAt: r.stored_at }));
185
+ },
97
186
  };
98
187
  }
99
188
  /**
@@ -101,7 +190,7 @@ export function pgvectorStore(client, opts) {
101
190
  * (`agent-custody`, `fact:<id>`, `space:<name>`, `receipt:<id>`) so a passage always leads back to its fact.
102
191
  */
103
192
  export function lettaStore(client, opts) {
104
- const tagsFor = (f) => ["agent-custody", `fact:${f.factId}`, `space:${f.space}`, ...(f.source.receiptId ? [`receipt:${f.source.receiptId}`] : []), ...(opts.tags ?? [])];
193
+ const tagsFor = (f) => ["agent-custody", `fact:${f.factId}`, `space:${f.space}`, `stored:${new Date().toISOString()}`, ...(f.source.receiptId ? [`receipt:${f.source.receiptId}`] : []), ...(opts.tags ?? [])];
105
194
  return {
106
195
  name: "letta",
107
196
  async put(fact) {
@@ -111,37 +200,85 @@ export function lettaStore(client, opts) {
111
200
  throw new Error("letta returned no passage id");
112
201
  return id;
113
202
  },
114
- async remove(externalId) {
203
+ async delete({ externalId }) {
115
204
  await client.agents.passages.delete(externalId, { agent_id: opts.agentId });
116
205
  },
117
206
  ...(client.agents.passages.search
118
207
  ? {
119
- async verifyRemoved(externalId, fact) {
120
- const { results } = await client.agents.passages.search(opts.agentId, { query: factText(fact), tags: [`fact:${fact.factId}`], tag_match_mode: "any" });
121
- return !results.some((r) => r.id === externalId || r.content === factText(fact));
208
+ async verifyDeleted({ externalId, factId, text }) {
209
+ const { results } = await client.agents.passages.search(opts.agentId, { query: text, tags: [`fact:${factId}`], tag_match_mode: "any" });
210
+ return !results.some((r) => r.id === externalId || r.content === text);
211
+ },
212
+ }
213
+ : {}),
214
+ ...(client.agents.passages.list
215
+ ? {
216
+ async list() {
217
+ const out = [];
218
+ const limit = 100;
219
+ const seen = new Set();
220
+ const own = new Set(opts.tags ?? []);
221
+ for (let after;;) {
222
+ const page = await client.agents.passages.list(opts.agentId, { limit, ...(after ? { after } : {}) });
223
+ const fresh = freshIds("letta", seen, page.flatMap((p) => (p.id ? [p.id] : [])));
224
+ for (const p of page) {
225
+ if (!p.id || !fresh.has(p.id))
226
+ continue;
227
+ const factTag = p.tags?.find((t) => t.startsWith("fact:"));
228
+ const rest = new Set((p.tags ?? []).filter((t) => t !== "agent-custody" && !/^(fact|space|stored|receipt):/.test(t)));
229
+ if (p.id && factTag && p.tags.includes("agent-custody") && rest.size === own.size && [...own].every((t) => rest.has(t)))
230
+ out.push({ externalId: p.id, factId: factTag.slice("fact:".length), text: p.text, ...stored(p.tags.find((t) => t.startsWith("stored:"))?.slice("stored:".length), p.created_at) });
231
+ }
232
+ const last = page.at(-1)?.id;
233
+ if (page.length < limit || !last)
234
+ return out;
235
+ if (last === after)
236
+ throw new Error("letta: listing does not advance");
237
+ after = last;
238
+ }
122
239
  },
123
240
  }
124
241
  : {}),
125
242
  };
126
243
  }
127
244
  export function langgraphStore(store, opts) {
245
+ const sameNamespace = (ns) => ns.length === opts.namespace.length && ns.every((part, i) => part === opts.namespace[i]);
128
246
  return {
129
247
  name: "langgraph",
130
248
  async put(fact) {
131
249
  await store.put(opts.namespace, fact.factId, { content: factText(fact), subject: fact.subject, predicate: fact.predicate, value: fact.value, ...factMetadata(fact) });
132
250
  return fact.factId;
133
251
  },
134
- async remove(externalId) {
252
+ async delete({ externalId }) {
135
253
  await store.delete(opts.namespace, externalId);
136
254
  },
137
- async verifyRemoved(externalId, fact) {
255
+ async verifyDeleted({ externalId, factId }) {
138
256
  if ((await store.get(opts.namespace, externalId)) !== null)
139
257
  return false;
140
258
  if (!store.search)
141
259
  return true;
142
- const hits = await store.search(opts.namespace, { filter: { factId: fact.factId }, limit: 10 });
260
+ const hits = await store.search(opts.namespace, { filter: { factId }, limit: 10 });
143
261
  return !hits.some((h) => h.key === externalId);
144
262
  },
263
+ ...(store.search
264
+ ? {
265
+ async list() {
266
+ const out = [];
267
+ const seen = new Set();
268
+ for (let offset = 0, page = 100;; offset += page) {
269
+ const hits = await store.search(opts.namespace, { filter: { source: "agent-custody" }, limit: page, offset });
270
+ const idOf = (h) => [...h.namespace, h.key].join("\u0000");
271
+ const fresh = freshIds("langgraph", seen, hits.map(idOf));
272
+ // search matches by prefix; an item in a child namespace is not this store's to remove.
273
+ for (const h of hits)
274
+ if (sameNamespace(h.namespace) && fresh.has(idOf(h)) && typeof h.value.factId === "string")
275
+ out.push({ externalId: h.key, factId: h.value.factId, text: String(h.value.content ?? ""), ...stored(h.value.storedAt, h.createdAt) });
276
+ if (hits.length < page)
277
+ return out;
278
+ }
279
+ },
280
+ }
281
+ : {}),
145
282
  };
146
283
  }
147
284
  /**
@@ -202,11 +339,18 @@ export function cogneeStore(opts) {
202
339
  throw new Error(`cognee accepted the add but the dataset lists no item carrying fact ${fact.factId}`);
203
340
  return item.id;
204
341
  },
205
- async remove(externalId) {
342
+ async delete({ externalId }) {
206
343
  await call("DELETE", `api/v1/datasets/${opts.datasetId}/data/${externalId}`);
207
344
  },
208
- async verifyRemoved(externalId, fact) {
209
- return !(await list()).some((i) => i.id === externalId || metadataOf(i).factId === fact.factId);
345
+ async verifyDeleted({ externalId, factId }) {
346
+ return !(await list()).some((i) => i.id === externalId || metadataOf(i).factId === factId);
347
+ },
348
+ async list() {
349
+ // The data listing carries no text; the repair sweep needs the id and the fact id only, and this store verifies by them.
350
+ return (await list()).flatMap((i) => {
351
+ const m = metadataOf(i);
352
+ return m.source === "agent-custody" && typeof m.factId === "string" ? [{ externalId: i.id, factId: m.factId, text: "", ...stored(m.storedAt, i.created_at, i.createdAt) }] : [];
353
+ });
210
354
  },
211
355
  };
212
356
  }
@@ -0,0 +1,91 @@
1
+ export interface Envelope {
2
+ payloadType: string;
3
+ payload: string;
4
+ signatures: {
5
+ keyid: string;
6
+ sig: string;
7
+ }[];
8
+ }
9
+ export interface Bundle {
10
+ envelope: Envelope;
11
+ treeHead: Envelope;
12
+ inclusion: {
13
+ leafIndex: number;
14
+ treeSize: number;
15
+ hashes: string[];
16
+ };
17
+ }
18
+ export interface Check {
19
+ name: string;
20
+ ok: boolean;
21
+ detail?: string;
22
+ }
23
+ export interface PublicKey {
24
+ key: CryptoKey;
25
+ keyid: string;
26
+ pem: string;
27
+ }
28
+ export interface Result {
29
+ ok: boolean;
30
+ checks: Check[];
31
+ statement: any | null;
32
+ issuerNote: string | null;
33
+ treeHeadSigner: "log key" | "issuer key" | null;
34
+ }
35
+ type Bytes = Uint8Array<ArrayBuffer>;
36
+ export declare function canonicalize(value: unknown): string;
37
+ /** sha256 over the canonical JSON. A digest over withheld values is salted from their salts, which the browser never has, so it recomputes only digests over values in clear. */
38
+ export declare const digestOf: (v: unknown) => Promise<string>;
39
+ /** Loads an Ed25519 public key from SPKI PEM. keyid is the sha256 of the DER. */
40
+ export declare function publicKeyFromPem(pem: string): Promise<PublicKey>;
41
+ export declare function dsseVerify(env: Envelope, trusted: PublicKey[]): Promise<{
42
+ ok: true;
43
+ payload: any;
44
+ keyid: string;
45
+ } | {
46
+ ok: false;
47
+ error: string;
48
+ }>;
49
+ export declare function delegationHasParent(env: Envelope): boolean;
50
+ /** Mirrors verifyDelegation in the package: walks a chain to a grant signed by a trusted principal key. */
51
+ export declare function verifyDelegationChain(env: Envelope, trusted: PublicKey[], depth?: number): Promise<{
52
+ ok: true;
53
+ delegation: any;
54
+ keyid: string;
55
+ chain: any[];
56
+ } | {
57
+ ok: false;
58
+ error: string;
59
+ }>;
60
+ export declare function verifyInclusion(leaf: Bytes, proof: Bundle["inclusion"], rootHex: string): Promise<boolean>;
61
+ export declare function verifyConsistency(oldSize: number, oldRoot: string, newSize: number, newRoot: string, proofHex: string[]): Promise<boolean>;
62
+ export interface Options {
63
+ issuerKeys: PublicKey[];
64
+ principalKeys: PublicKey[];
65
+ approvalKeys?: PublicKey[];
66
+ logKeys?: PublicKey[];
67
+ upstreamKeys?: PublicKey[];
68
+ providerSecrets?: {
69
+ stripe?: string;
70
+ github?: string;
71
+ };
72
+ logId?: string;
73
+ logLeaves?: (string | {
74
+ pruned?: string;
75
+ hash?: string;
76
+ })[];
77
+ }
78
+ /** mirrors src/verify.ts structuralProblem: a capture note may never name what a verifier reads to run its checks, and those parts must be what every check assumes */
79
+ export declare function structuralProblem(p: unknown): string | null;
80
+ /** The same checks, in the same order, with the same names, as the reference verifyBundle. */
81
+ export declare function verifyBundle(bundle: Bundle, opts: Options): Promise<Result>;
82
+ export interface AuditResult {
83
+ ok: boolean;
84
+ checks: Check[];
85
+ }
86
+ export declare function auditExtends(older: Envelope, newer: Envelope, proof: string[], keys: PublicKey[], logId?: string, opts?: {
87
+ witnessKeys?: PublicKey[];
88
+ }): Promise<AuditResult>;
89
+ /** The human-readable report, the same shape the CLI prints. */
90
+ export declare function formatReport(r: Result): string;
91
+ export {};