@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,139 @@
1
+ /**
2
+ * Session metadata the SDK collects for a trace: the attribute bag a run is
3
+ * filtered and grouped by, and the LLM calls that give it real token and cost
4
+ * figures. Both travel in `session_metadata` when the outcome is committed —
5
+ * `attributes` and `llm_calls`, the same shape the Python SDK and MCP server
6
+ * write, so the server treats every producer alike.
7
+ */
8
+ /** Attributes are indexed server-side, so the bag is kept small and flat. */
9
+ export const SESSION_ATTRIBUTES_MAX_KEYS = 20;
10
+ export const SESSION_ATTRIBUTE_KEY_MAX_LEN = 64;
11
+ export const SESSION_ATTRIBUTE_VALUE_MAX_LEN = 256;
12
+ /**
13
+ * Attribute keys the SDK stamps itself, which do not count against
14
+ * `SESSION_ATTRIBUTES_MAX_KEYS`: a caller's bag at the cap is still accepted —
15
+ * locally and by the server, which exempts the same keys — for the branch it
16
+ * ran on.
17
+ */
18
+ export const SDK_STAMPED_ATTRIBUTES = new Set([
19
+ "memory_branch",
20
+ // Stamped by a hosted server when the session was routed through a live
21
+ // repair canary (which fix, which arm). Never set by the SDK; exempt so a
22
+ // caller's bag at the cap is not refused for a stamp it did not add.
23
+ "canary_fix_id",
24
+ "canary_arm",
25
+ ]);
26
+ /** How many of `keys` count against the cap. */
27
+ export function countedAttributeKeys(keys) {
28
+ let n = 0;
29
+ for (const key of keys) {
30
+ if (!SDK_STAMPED_ATTRIBUTES.has(String(key).trim().toLowerCase()))
31
+ n += 1;
32
+ }
33
+ return n;
34
+ }
35
+ /**
36
+ * The validated form of an attribute bag, or a thrown `TypeError` / `RangeError`.
37
+ *
38
+ * Keys are trimmed and lowercased (the server indexes them that way, so two
39
+ * spellings of one dimension would otherwise never group together). Values
40
+ * must be string, finite number or boolean; at most 20 keys of up to 64
41
+ * characters, string values up to 256 characters. Rejected rather than
42
+ * trimmed: a silently shortened customer id is worse than an error at the
43
+ * call site.
44
+ */
45
+ export function validateSessionAttributes(attributes) {
46
+ if (attributes === null || attributes === undefined)
47
+ return {};
48
+ if (typeof attributes !== "object" || Array.isArray(attributes)) {
49
+ throw new TypeError("attributes must be an object of scalar values");
50
+ }
51
+ const entries = Object.entries(attributes);
52
+ const counted = countedAttributeKeys(entries.map(([k]) => k));
53
+ if (counted > SESSION_ATTRIBUTES_MAX_KEYS) {
54
+ throw new RangeError(`at most ${SESSION_ATTRIBUTES_MAX_KEYS} session attributes are allowed (got ${counted})`);
55
+ }
56
+ const out = {};
57
+ for (const [rawKey, value] of entries) {
58
+ const key = String(rawKey).trim().toLowerCase();
59
+ if (!key)
60
+ throw new RangeError("attribute keys must be non-empty strings");
61
+ if (key.length > SESSION_ATTRIBUTE_KEY_MAX_LEN) {
62
+ throw new RangeError(`attribute key '${key.slice(0, 20)}...' exceeds ${SESSION_ATTRIBUTE_KEY_MAX_LEN} characters`);
63
+ }
64
+ if (typeof value === "string") {
65
+ if (value.length > SESSION_ATTRIBUTE_VALUE_MAX_LEN) {
66
+ throw new RangeError(`attribute '${key}' exceeds ${SESSION_ATTRIBUTE_VALUE_MAX_LEN} characters`);
67
+ }
68
+ out[key] = value;
69
+ }
70
+ else if (typeof value === "number") {
71
+ if (!Number.isFinite(value))
72
+ throw new RangeError(`attribute '${key}' must be a finite number`);
73
+ out[key] = value;
74
+ }
75
+ else if (typeof value === "boolean") {
76
+ out[key] = value;
77
+ }
78
+ else {
79
+ throw new TypeError(`attribute '${key}' must be a string, number or boolean, not ${value === null ? "null" : typeof value}`);
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+ function nonNegativeInt(value, label) {
85
+ if (typeof value !== "number" || !Number.isFinite(value)) {
86
+ throw new TypeError(`${label} must be a number`);
87
+ }
88
+ const n = Math.trunc(value);
89
+ if (n < 0)
90
+ throw new RangeError(`${label} must be non-negative`);
91
+ return n;
92
+ }
93
+ function optionalNonNegative(value, label) {
94
+ if (value === null || value === undefined)
95
+ return null;
96
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
97
+ throw new RangeError(`${label} must be a non-negative number or null`);
98
+ }
99
+ return value;
100
+ }
101
+ function newCallId() {
102
+ const c = globalThis.crypto;
103
+ if (c?.randomUUID)
104
+ return c.randomUUID();
105
+ // Fallback for runtimes without WebCrypto: time + random, unique enough per session.
106
+ return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 14)}`;
107
+ }
108
+ /** Validate and normalise a call into the wire record. Throws on bad input. */
109
+ export function toLlmCallRecord(input, startedAt) {
110
+ if (typeof input?.model !== "string" || !input.model) {
111
+ throw new TypeError("model must be a non-empty string");
112
+ }
113
+ const record = {
114
+ call_id: input.callId || newCallId(),
115
+ model: input.model,
116
+ provider: input.provider ?? "",
117
+ input_tokens: nonNegativeInt(input.inputTokens, "inputTokens"),
118
+ output_tokens: nonNegativeInt(input.outputTokens, "outputTokens"),
119
+ cost_usd: optionalNonNegative(input.costUsd, "costUsd"),
120
+ latency_ms: optionalNonNegative(input.latencyMs, "latencyMs"),
121
+ started_at: (startedAt ?? new Date()).toISOString(),
122
+ };
123
+ if (input.error)
124
+ record.error = String(input.error);
125
+ return record;
126
+ }
127
+ /**
128
+ * The `session_metadata` object sent with an outcome: the two collections when
129
+ * they have content, nothing otherwise (so a server that predates them sees
130
+ * the request it always saw).
131
+ */
132
+ export function buildSessionMetadata(attributes, llmCalls) {
133
+ const out = {};
134
+ if (Object.keys(attributes).length)
135
+ out.attributes = { ...attributes };
136
+ if (llmCalls.length)
137
+ out.llm_calls = llmCalls.map((c) => ({ ...c }));
138
+ return Object.keys(out).length ? out : undefined;
139
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senselab-ai/amfs",
3
- "version": "0.3.2",
3
+ "version": "0.4.5",
4
4
  "description": "AMFS TypeScript SDK — Agent Memory File System",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -13,10 +13,19 @@
13
13
  },
14
14
  "scripts": {
15
15
  "build": "tsc",
16
+ "typecheck": "tsc --noEmit",
16
17
  "test": "vitest run",
17
18
  "test:watch": "vitest"
18
19
  },
19
20
  "dependencies": {},
21
+ "peerDependencies": {
22
+ "openai": ">=4.0.0",
23
+ "@anthropic-ai/sdk": ">=0.20.0"
24
+ },
25
+ "peerDependenciesMeta": {
26
+ "openai": { "optional": true },
27
+ "@anthropic-ai/sdk": { "optional": true }
28
+ },
20
29
  "devDependencies": {
21
30
  "typescript": "^5.4",
22
31
  "vitest": "^3.1"