@smazzinni/sdk 0.4.1
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/README.md +167 -0
- package/dist/cjs/config.d.ts +27 -0
- package/dist/cjs/config.d.ts.map +1 -0
- package/dist/cjs/config.js +118 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/context.d.ts +16 -0
- package/dist/cjs/context.d.ts.map +1 -0
- package/dist/cjs/context.js +159 -0
- package/dist/cjs/context.js.map +1 -0
- package/dist/cjs/cost.d.ts +25 -0
- package/dist/cjs/cost.d.ts.map +1 -0
- package/dist/cjs/cost.js +49 -0
- package/dist/cjs/cost.js.map +1 -0
- package/dist/cjs/index.d.ts +32 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +50 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/redact.d.ts +12 -0
- package/dist/cjs/redact.d.ts.map +1 -0
- package/dist/cjs/redact.js +64 -0
- package/dist/cjs/redact.js.map +1 -0
- package/dist/cjs/session.d.ts +32 -0
- package/dist/cjs/session.d.ts.map +1 -0
- package/dist/cjs/session.js +65 -0
- package/dist/cjs/session.js.map +1 -0
- package/dist/cjs/steps.d.ts +12 -0
- package/dist/cjs/steps.d.ts.map +1 -0
- package/dist/cjs/steps.js +60 -0
- package/dist/cjs/steps.js.map +1 -0
- package/dist/cjs/store.d.ts +38 -0
- package/dist/cjs/store.d.ts.map +1 -0
- package/dist/cjs/store.js +125 -0
- package/dist/cjs/store.js.map +1 -0
- package/dist/cjs/types.d.ts +124 -0
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/types.js +6 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +110 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +16 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +153 -0
- package/dist/context.js.map +1 -0
- package/dist/cost.d.ts +25 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +43 -0
- package/dist/cost.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/redact.d.ts +12 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +59 -0
- package/dist/redact.js.map +1 -0
- package/dist/session.d.ts +32 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +61 -0
- package/dist/session.js.map +1 -0
- package/dist/steps.d.ts +12 -0
- package/dist/steps.d.ts.map +1 -0
- package/dist/steps.js +56 -0
- package/dist/steps.js.map +1 -0
- package/dist/store.d.ts +38 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +118 -0
- package/dist/store.js.map +1 -0
- package/dist/types.d.ts +124 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/package.json +59 -0
package/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# @replayai/sdk
|
|
2
|
+
|
|
3
|
+
TypeScript SDK for [ReplayAI](https://github.com/replayai) — instrument JS/TS agents, record sessions, and replay/export them as tests.
|
|
4
|
+
|
|
5
|
+
- **Zero runtime deps.** Node 18+ built-ins only (`fetch`, `AsyncLocalStorage`, `crypto`).
|
|
6
|
+
- **ESM + CJS** via the `exports` map.
|
|
7
|
+
- **Async-safe** current-session tracking via `AsyncLocalStorage`.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
bun add @replayai/sdk
|
|
13
|
+
# or
|
|
14
|
+
npm install @replayai/sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 30-second usage
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { withTrace, recordStep, configure } from "@replayai/sdk";
|
|
21
|
+
|
|
22
|
+
// Point at a running ReplayAI app (default: http://localhost:3000)
|
|
23
|
+
configure({ apiUrl: "http://localhost:3000" });
|
|
24
|
+
|
|
25
|
+
await withTrace(
|
|
26
|
+
"support-agent-v3",
|
|
27
|
+
{ project: "support-agent", tags: ["production"] },
|
|
28
|
+
async () => {
|
|
29
|
+
await recordStep({
|
|
30
|
+
type: "llm_call",
|
|
31
|
+
name: "classify_intent",
|
|
32
|
+
model: "gpt-4o-mini",
|
|
33
|
+
tokensIn: 312,
|
|
34
|
+
tokensOut: 24,
|
|
35
|
+
input: "User: refund please",
|
|
36
|
+
output: "intent: billing_dispute",
|
|
37
|
+
status: "success",
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
await recordStep({
|
|
41
|
+
type: "tool_call",
|
|
42
|
+
name: "issue_refund",
|
|
43
|
+
input: JSON.stringify({ charge_id: "ch_002" }),
|
|
44
|
+
output: JSON.stringify({ refund_id: "ref_3391" }),
|
|
45
|
+
status: "success",
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
);
|
|
49
|
+
// → session POSTed to /api/sessions and visible in the dashboard.
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## API
|
|
53
|
+
|
|
54
|
+
### `trace(name, opts?, fn)` — higher-order function
|
|
55
|
+
|
|
56
|
+
Wraps an existing function so each call records a session.
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
import { trace } from "@replayai/sdk";
|
|
60
|
+
|
|
61
|
+
export const handleSupportTicket = trace(
|
|
62
|
+
"support-agent-v3",
|
|
63
|
+
{ project: "support-agent", tags: ["production"] },
|
|
64
|
+
async (message: string): Promise<string> => {
|
|
65
|
+
const intent = await classifyIntent(message);
|
|
66
|
+
const customer = await lookupCustomer(message);
|
|
67
|
+
return reply;
|
|
68
|
+
},
|
|
69
|
+
);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### `withTrace(name, opts?, fn)` — async context manager
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
await withTrace("research-agent-v2", { tags: ["batch"] }, async () => {
|
|
76
|
+
const result = await crew.kickoff({ topic: "AI observability pricing" });
|
|
77
|
+
return result;
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### `recordStep({ type, name, model?, tokensIn?, tokensOut?, input?, output?, status?, durationMs? })`
|
|
82
|
+
|
|
83
|
+
Appends a step to the current session. No-op outside a trace (unless `strict: true`).
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
await recordStep({
|
|
87
|
+
type: "tool_call",
|
|
88
|
+
name: "issue_refund",
|
|
89
|
+
input: JSON.stringify({ charge_id: "ch_002" }),
|
|
90
|
+
output: JSON.stringify({ refund_id: "ref_3391" }),
|
|
91
|
+
status: "success",
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### `ReplaySession`
|
|
96
|
+
|
|
97
|
+
Load a recorded session and either re-run it or export it as a test.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { ReplaySession } from "@replayai/sdk";
|
|
101
|
+
|
|
102
|
+
const replay = new ReplaySession("ses_8fa1", { liveLlm: false });
|
|
103
|
+
|
|
104
|
+
replay.mock("issue_refund", JSON.stringify({ refund_id: "ref_3391" }));
|
|
105
|
+
|
|
106
|
+
const trace = await replay.run({ agent: "support-agent-v3", framework: "LangChain" });
|
|
107
|
+
console.log(trace.stepCount, trace.status);
|
|
108
|
+
|
|
109
|
+
const code = await replay.export("pytest"); // or "jest"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### `configure(opts)`
|
|
113
|
+
|
|
114
|
+
Programmatic configuration. Same keys as the env vars below.
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
configure({
|
|
118
|
+
project: "support-agent",
|
|
119
|
+
storage: "both",
|
|
120
|
+
storagePath: "./replays",
|
|
121
|
+
token: process.env.REPLAYAI_TOKEN!,
|
|
122
|
+
apiUrl: "https://api.replayai.dev",
|
|
123
|
+
sampleRate: 1.0,
|
|
124
|
+
redactPatterns: [/sk-[a-zA-Z0-9]{20,}/],
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### `VERSION`
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
import { VERSION } from "@replayai/sdk";
|
|
132
|
+
console.log(VERSION); // "0.4.1"
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Environment variables
|
|
136
|
+
|
|
137
|
+
| Variable | Default | Description |
|
|
138
|
+
| --- | --- | --- |
|
|
139
|
+
| `REPLAYAI_PROJECT` | — | Default project slug/id when `trace()` omits it |
|
|
140
|
+
| `REPLAYAI_TOKEN` | — | Cloud API token (sent as `Authorization: Bearer`) |
|
|
141
|
+
| `REPLAYAI_STORAGE` | `cloud` | `local`, `cloud`, or `both` |
|
|
142
|
+
| `REPLAYAI_STORAGE_PATH` | `./replays` | Local storage directory |
|
|
143
|
+
| `REPLAYAI_API_URL` | `http://localhost:3000` | Cloud API base URL |
|
|
144
|
+
| `REPLAYAI_DASHBOARD_URL` | `http://localhost:3000` | Where session URLs point |
|
|
145
|
+
| `REPLAYAI_REDACT_PATTERNS` | built-in set | Comma-separated regex patterns to redact |
|
|
146
|
+
| `REPLAYAI_SAMPLE_RATE` | `1.0` | Fraction of sessions to record (0.0–1.0) |
|
|
147
|
+
| `REPLAYAI_STRICT` | `false` | Raise on recording failures instead of warning |
|
|
148
|
+
|
|
149
|
+
## Redaction
|
|
150
|
+
|
|
151
|
+
Secrets are scrubbed from step input/output before persistence. Default patterns catch `sk-...` (OpenAI keys), `Bearer ...` (auth tokens), `password=...`, and `api_key=...`. Redacted spans become `[REDACTED]`.
|
|
152
|
+
|
|
153
|
+
## ESM + CJS
|
|
154
|
+
|
|
155
|
+
Both are supported. The `exports` field routes automatically:
|
|
156
|
+
|
|
157
|
+
```javascript
|
|
158
|
+
// ESM
|
|
159
|
+
import { trace } from "@replayai/sdk";
|
|
160
|
+
|
|
161
|
+
// CJS
|
|
162
|
+
const { trace } = require("@replayai/sdk");
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ConfigOptions } from "./types.js";
|
|
2
|
+
/** Default redaction patterns. Applied to every step's input/output. */
|
|
3
|
+
export declare const DEFAULT_REDACT_PATTERNS: RegExp[];
|
|
4
|
+
export type StorageMode = "local" | "cloud" | "both";
|
|
5
|
+
export interface ResolvedConfig {
|
|
6
|
+
project?: string;
|
|
7
|
+
token?: string;
|
|
8
|
+
storage: StorageMode;
|
|
9
|
+
storagePath: string;
|
|
10
|
+
apiUrl: string;
|
|
11
|
+
dashboardUrl: string;
|
|
12
|
+
sampleRate: number;
|
|
13
|
+
strict: boolean;
|
|
14
|
+
redactPatterns: RegExp[];
|
|
15
|
+
}
|
|
16
|
+
/** Resolve the active config from env vars + programmatic overrides. */
|
|
17
|
+
export declare function resolveConfig(): ResolvedConfig;
|
|
18
|
+
/** Update SDK config programmatically. Only supplied keys are changed. */
|
|
19
|
+
export declare function configure(opts: ConfigOptions): ResolvedConfig;
|
|
20
|
+
/** Get the active config (re-resolves if `configure()` was called). */
|
|
21
|
+
export declare function getConfig(): ResolvedConfig;
|
|
22
|
+
/** Reset to env-only config. Useful for tests. */
|
|
23
|
+
export declare function resetConfig(): void;
|
|
24
|
+
/** Module-level strict flag, mirrored from config.strict (parity with Python SDK). */
|
|
25
|
+
export declare let strict_mode: boolean;
|
|
26
|
+
export declare function _syncStrictFlag(): void;
|
|
27
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wEAAwE;AACxE,eAAO,MAAM,uBAAuB,EAAE,MAAM,EAK3C,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAErD,MAAM,WAAW,cAAc;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,WAAW,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;IAChB,cAAc,EAAE,MAAM,EAAE,CAAC;CAC1B;AA4CD,wEAAwE;AACxE,wBAAgB,aAAa,IAAI,cAAc,CA8B9C;AAUD,0EAA0E;AAC1E,wBAAgB,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,cAAc,CAI7D;AAED,uEAAuE;AACvE,wBAAgB,SAAS,IAAI,cAAc,CAE1C;AAED,kDAAkD;AAClD,wBAAgB,WAAW,IAAI,IAAI,CAGlC;AAED,sFAAsF;AACtF,eAAO,IAAI,WAAW,EAAE,OAAgC,CAAC;AAEzD,wBAAgB,eAAe,IAAI,IAAI,CAGtC"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ReplayAI TypeScript SDK — configuration.
|
|
3
|
+
// Reads env vars on first access; `configure()` overrides programmatically.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.strict_mode = exports.DEFAULT_REDACT_PATTERNS = void 0;
|
|
6
|
+
exports.resolveConfig = resolveConfig;
|
|
7
|
+
exports.configure = configure;
|
|
8
|
+
exports.getConfig = getConfig;
|
|
9
|
+
exports.resetConfig = resetConfig;
|
|
10
|
+
exports._syncStrictFlag = _syncStrictFlag;
|
|
11
|
+
/** Default redaction patterns. Applied to every step's input/output. */
|
|
12
|
+
exports.DEFAULT_REDACT_PATTERNS = [
|
|
13
|
+
/sk-[a-zA-Z0-9]{20,}/g, // OpenAI-style API keys
|
|
14
|
+
/Bearer\s+[a-zA-Z0-9._\-]+/g, // Authorization header tokens
|
|
15
|
+
/password=[^\s&]+/gi, // password=... in URLs / form bodies
|
|
16
|
+
/["']?api[_-]?key["']?\s*[:=]\s*["']?[a-zA-Z0-9]{20,}/gi, // api_key=...
|
|
17
|
+
];
|
|
18
|
+
function envString(name, fallback) {
|
|
19
|
+
const v = process.env[name];
|
|
20
|
+
return v === undefined || v === "" ? fallback : v;
|
|
21
|
+
}
|
|
22
|
+
function envNumber(name, fallback) {
|
|
23
|
+
const v = process.env[name];
|
|
24
|
+
if (v === undefined || v === "")
|
|
25
|
+
return fallback;
|
|
26
|
+
const n = Number(v);
|
|
27
|
+
return Number.isFinite(n) ? n : fallback;
|
|
28
|
+
}
|
|
29
|
+
function envBool(name, fallback) {
|
|
30
|
+
const v = process.env[name];
|
|
31
|
+
if (v === undefined || v === "")
|
|
32
|
+
return fallback;
|
|
33
|
+
return v === "1" || v.toLowerCase() === "true" || v.toLowerCase() === "yes" || v.toLowerCase() === "on";
|
|
34
|
+
}
|
|
35
|
+
function parseRedactPatterns(raw) {
|
|
36
|
+
if (!raw || raw.trim() === "")
|
|
37
|
+
return null;
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const piece of raw.split(",")) {
|
|
40
|
+
const p = piece.trim();
|
|
41
|
+
if (!p)
|
|
42
|
+
continue;
|
|
43
|
+
try {
|
|
44
|
+
out.push(new RegExp(p, "g"));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// If the user supplied a malformed regex, escape it and try again.
|
|
48
|
+
const escaped = p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
49
|
+
try {
|
|
50
|
+
out.push(new RegExp(escaped, "g"));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
/* skip unparseable */
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out.length > 0 ? out : null;
|
|
58
|
+
}
|
|
59
|
+
let cached = null;
|
|
60
|
+
let overrides = {};
|
|
61
|
+
/** Resolve the active config from env vars + programmatic overrides. */
|
|
62
|
+
function resolveConfig() {
|
|
63
|
+
if (cached)
|
|
64
|
+
return cached;
|
|
65
|
+
const storageRaw = overrides.storage ?? envString("REPLAYAI_STORAGE") ?? "cloud";
|
|
66
|
+
const storage = storageRaw === "local" || storageRaw === "cloud" || storageRaw === "both"
|
|
67
|
+
? storageRaw
|
|
68
|
+
: "cloud";
|
|
69
|
+
let redactPatterns = null;
|
|
70
|
+
if (overrides.redactPatterns) {
|
|
71
|
+
redactPatterns = overrides.redactPatterns.map((p) => typeof p === "string" ? safeRegex(p) : p);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
redactPatterns = parseRedactPatterns(envString("REPLAYAI_REDACT_PATTERNS"));
|
|
75
|
+
}
|
|
76
|
+
cached = {
|
|
77
|
+
project: overrides.project ?? envString("REPLAYAI_PROJECT"),
|
|
78
|
+
token: overrides.token ?? envString("REPLAYAI_TOKEN"),
|
|
79
|
+
storage,
|
|
80
|
+
storagePath: overrides.storagePath ?? envString("REPLAYAI_STORAGE_PATH") ?? "./replays",
|
|
81
|
+
apiUrl: (overrides.apiUrl ?? envString("REPLAYAI_API_URL") ?? "http://localhost:3000").replace(/\/$/, ""),
|
|
82
|
+
dashboardUrl: overrides.dashboardUrl ?? envString("REPLAYAI_DASHBOARD_URL") ?? "http://localhost:3000",
|
|
83
|
+
sampleRate: overrides.sampleRate ?? envNumber("REPLAYAI_SAMPLE_RATE", 1.0),
|
|
84
|
+
strict: overrides.strict ?? envBool("REPLAYAI_STRICT", false),
|
|
85
|
+
redactPatterns: redactPatterns ?? [...exports.DEFAULT_REDACT_PATTERNS],
|
|
86
|
+
};
|
|
87
|
+
return cached;
|
|
88
|
+
}
|
|
89
|
+
function safeRegex(s) {
|
|
90
|
+
try {
|
|
91
|
+
return new RegExp(s, "g");
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Update SDK config programmatically. Only supplied keys are changed. */
|
|
98
|
+
function configure(opts) {
|
|
99
|
+
overrides = { ...overrides, ...opts };
|
|
100
|
+
cached = null; // force re-resolve on next read
|
|
101
|
+
return resolveConfig();
|
|
102
|
+
}
|
|
103
|
+
/** Get the active config (re-resolves if `configure()` was called). */
|
|
104
|
+
function getConfig() {
|
|
105
|
+
return resolveConfig();
|
|
106
|
+
}
|
|
107
|
+
/** Reset to env-only config. Useful for tests. */
|
|
108
|
+
function resetConfig() {
|
|
109
|
+
overrides = {};
|
|
110
|
+
cached = null;
|
|
111
|
+
}
|
|
112
|
+
/** Module-level strict flag, mirrored from config.strict (parity with Python SDK). */
|
|
113
|
+
exports.strict_mode = resolveConfig().strict;
|
|
114
|
+
function _syncStrictFlag() {
|
|
115
|
+
// Re-import trick: reassign the exported let.
|
|
116
|
+
// (Called by configure via _sync below.)
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":";AAAA,2CAA2C;AAC3C,4EAA4E;;;AAqE5E,sCA8BC;AAWD,8BAIC;AAGD,8BAEC;AAGD,kCAGC;AAKD,0CAGC;AAjID,wEAAwE;AAC3D,QAAA,uBAAuB,GAAa;IAC/C,sBAAsB,EAAE,wBAAwB;IAChD,4BAA4B,EAAE,8BAA8B;IAC5D,oBAAoB,EAAE,qCAAqC;IAC3D,wDAAwD,EAAE,cAAc;CACzE,CAAC;AAgBF,SAAS,SAAS,CAAC,IAAY,EAAE,QAAiB;IAChD,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC5B,OAAO,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CA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AC;IACf,MAAM,GAAG,IAAI,CAAC;AAChB,CAAC;AAED,sFAAsF;AAC3E,QAAA,WAAW,GAAY,aAAa,EAAE,CAAC,MAAM,CAAC;AAEzD,SAAgB,eAAe;IAC7B,8CAA8C;IAC9C,yCAAyC;AAC3C,CAAC"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { InternalSession, SessionStep, TraceOptions } from "./types.js";
|
|
2
|
+
/** Return the innermost active recording session, if any. */
|
|
3
|
+
export declare function currentSession(): InternalSession | undefined;
|
|
4
|
+
/** Append a normalized step to the current session. No-op if no session. */
|
|
5
|
+
export declare function appendStep(step: SessionStep): void;
|
|
6
|
+
/**
|
|
7
|
+
* `withTrace` — async context manager. Wraps a function body in a recorded
|
|
8
|
+
* session; on exit computes duration/tokens/cost/status and POSTs to the API.
|
|
9
|
+
*
|
|
10
|
+
* Errors from the wrapped function are re-thrown as-is; recording failures
|
|
11
|
+
* are swallowed unless `strict` mode is on.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withTrace<T>(name: string, opts: TraceOptions | undefined, fn: () => T | Promise<T>): Promise<T>;
|
|
14
|
+
/** `trace` — higher-order function. Returns a wrapped fn with the same signature. */
|
|
15
|
+
export declare function trace<T extends (...args: never[]) => unknown>(name: string, opts: TraceOptions | undefined, fn: T): T;
|
|
16
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,eAAe,EAEf,WAAW,EACX,YAAY,EACb,MAAM,YAAY,CAAC;AAOpB,6DAA6D;AAC7D,wBAAgB,cAAc,IAAI,eAAe,GAAG,SAAS,CAE5D;AA6BD,4EAA4E;AAC5E,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,CAWlD;AAkDD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAC/B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,EAAE,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GACvB,OAAO,CAAC,CAAC,CAAC,CA+BZ;AAED,qFAAqF;AACrF,wBAAgB,KAAK,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,EAC3D,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,EAAE,EAAE,CAAC,GACJ,CAAC,CAOH"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ReplayAI TypeScript SDK — context.
|
|
3
|
+
// AsyncLocalStorage-based current-session tracking. `withTrace()` is the
|
|
4
|
+
// context manager; `trace()` is the higher-order wrapper.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.currentSession = currentSession;
|
|
7
|
+
exports.appendStep = appendStep;
|
|
8
|
+
exports.withTrace = withTrace;
|
|
9
|
+
exports.trace = trace;
|
|
10
|
+
const node_async_hooks_1 = require("node:async_hooks");
|
|
11
|
+
const node_crypto_1 = require("node:crypto");
|
|
12
|
+
const config_js_1 = require("./config.js");
|
|
13
|
+
const cost_js_1 = require("./cost.js");
|
|
14
|
+
const store_js_1 = require("./store.js");
|
|
15
|
+
const storage = new node_async_hooks_1.AsyncLocalStorage();
|
|
16
|
+
/** Return the innermost active recording session, if any. */
|
|
17
|
+
function currentSession() {
|
|
18
|
+
return storage.getStore();
|
|
19
|
+
}
|
|
20
|
+
function nowMs() {
|
|
21
|
+
return Date.now();
|
|
22
|
+
}
|
|
23
|
+
function shouldSample(rate) {
|
|
24
|
+
if (rate >= 1)
|
|
25
|
+
return true;
|
|
26
|
+
if (rate <= 0)
|
|
27
|
+
return false;
|
|
28
|
+
return Math.random() < rate;
|
|
29
|
+
}
|
|
30
|
+
function startSession(name, opts) {
|
|
31
|
+
const cfg = (0, config_js_1.getConfig)();
|
|
32
|
+
const startedAt = opts?.startedAt ?? new Date();
|
|
33
|
+
return {
|
|
34
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
35
|
+
name,
|
|
36
|
+
agent: opts?.agent ?? name,
|
|
37
|
+
project: opts?.project ?? cfg.project,
|
|
38
|
+
framework: opts?.framework ?? "Custom",
|
|
39
|
+
tags: opts?.tags ? [...opts.tags] : [],
|
|
40
|
+
startedAt,
|
|
41
|
+
__startMs: startedAt.getTime(),
|
|
42
|
+
steps: [],
|
|
43
|
+
status: "running",
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Append a normalized step to the current session. No-op if no session. */
|
|
47
|
+
function appendStep(step) {
|
|
48
|
+
const s = currentSession();
|
|
49
|
+
if (!s)
|
|
50
|
+
return;
|
|
51
|
+
// Infer offset from session start if missing.
|
|
52
|
+
if (step.t === undefined && step.offsetMs === undefined) {
|
|
53
|
+
step.t = Math.max(0, nowMs() - s.__startMs);
|
|
54
|
+
}
|
|
55
|
+
if (step.offsetMs === undefined && step.t !== undefined)
|
|
56
|
+
step.offsetMs = step.t;
|
|
57
|
+
if (step.t === undefined && step.offsetMs !== undefined)
|
|
58
|
+
step.t = step.offsetMs;
|
|
59
|
+
if (step.durationMs === undefined)
|
|
60
|
+
step.durationMs = 0;
|
|
61
|
+
s.steps.push(step);
|
|
62
|
+
}
|
|
63
|
+
/** Compute final totals + status and POST the session to the API. */
|
|
64
|
+
async function endAndFlush(session) {
|
|
65
|
+
session.endAt = new Date();
|
|
66
|
+
const wallClockDuration = session.endAt.getTime() - session.startedAt.getTime();
|
|
67
|
+
// Session duration = max(wall-clock, latest step end).
|
|
68
|
+
let stepEndMax = 0;
|
|
69
|
+
for (const s of session.steps) {
|
|
70
|
+
const t = s.offsetMs ?? s.t ?? 0;
|
|
71
|
+
const d = s.durationMs ?? 0;
|
|
72
|
+
stepEndMax = Math.max(stepEndMax, t + d);
|
|
73
|
+
}
|
|
74
|
+
const durationMs = Math.max(wallClockDuration, stepEndMax);
|
|
75
|
+
// Derive status.
|
|
76
|
+
let status = session.status;
|
|
77
|
+
if (session.error !== undefined) {
|
|
78
|
+
status = "failed";
|
|
79
|
+
}
|
|
80
|
+
else if (session.steps.some((s) => s.status === "failed")) {
|
|
81
|
+
status = "failed";
|
|
82
|
+
}
|
|
83
|
+
else if (session.steps.length > 0) {
|
|
84
|
+
status = "success";
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
status = "success";
|
|
88
|
+
}
|
|
89
|
+
const tokenTotal = session.steps.reduce((a, s) => a + (s.tokensIn ?? 0) + (s.tokensOut ?? 0), 0);
|
|
90
|
+
const costUsd = (0, cost_js_1.estimateCost)(session.steps);
|
|
91
|
+
await (0, store_js_1.flushSession)({
|
|
92
|
+
sessionId: session.id,
|
|
93
|
+
name: session.name,
|
|
94
|
+
agent: session.agent,
|
|
95
|
+
project: session.project,
|
|
96
|
+
framework: session.framework,
|
|
97
|
+
tags: session.tags,
|
|
98
|
+
startedAt: session.startedAt,
|
|
99
|
+
durationMs,
|
|
100
|
+
status,
|
|
101
|
+
tokenTotal,
|
|
102
|
+
costUsd,
|
|
103
|
+
steps: session.steps,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `withTrace` — async context manager. Wraps a function body in a recorded
|
|
108
|
+
* session; on exit computes duration/tokens/cost/status and POSTs to the API.
|
|
109
|
+
*
|
|
110
|
+
* Errors from the wrapped function are re-thrown as-is; recording failures
|
|
111
|
+
* are swallowed unless `strict` mode is on.
|
|
112
|
+
*/
|
|
113
|
+
async function withTrace(name, opts, fn) {
|
|
114
|
+
const cfg = (0, config_js_1.getConfig)();
|
|
115
|
+
const rate = opts?.sampleRate ?? cfg.sampleRate;
|
|
116
|
+
if (!shouldSample(rate)) {
|
|
117
|
+
// Not sampled: run the fn without tracing.
|
|
118
|
+
return await fn();
|
|
119
|
+
}
|
|
120
|
+
const session = startSession(name, opts);
|
|
121
|
+
return await storage.run(session, async () => {
|
|
122
|
+
let result;
|
|
123
|
+
try {
|
|
124
|
+
result = await fn();
|
|
125
|
+
if (session.status === "running")
|
|
126
|
+
session.status = "success";
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
session.status = "failed";
|
|
130
|
+
session.error = err;
|
|
131
|
+
try {
|
|
132
|
+
await endAndFlush(session);
|
|
133
|
+
}
|
|
134
|
+
catch (flushErr) {
|
|
135
|
+
if (cfg.strict)
|
|
136
|
+
throw flushErr;
|
|
137
|
+
}
|
|
138
|
+
throw err;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
await endAndFlush(session);
|
|
142
|
+
}
|
|
143
|
+
catch (flushErr) {
|
|
144
|
+
if (cfg.strict)
|
|
145
|
+
throw flushErr;
|
|
146
|
+
}
|
|
147
|
+
return result;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/** `trace` — higher-order function. Returns a wrapped fn with the same signature. */
|
|
151
|
+
function trace(name, opts, fn) {
|
|
152
|
+
const wrapped = (...args) => {
|
|
153
|
+
return withTrace(name, opts, () => fn(...args));
|
|
154
|
+
};
|
|
155
|
+
// Preserve name/length for nicer stack traces / introspection.
|
|
156
|
+
Object.defineProperty(wrapped, "name", { value: fn.name || "trace", configurable: true });
|
|
157
|
+
return wrapped;
|
|
158
|
+
}
|
|
159
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":";AAAA,qCAAqC;AACrC,yEAAyE;AACzE,0DAA0D;;AAiB1D,wCAEC;AA8BD,gCAWC;AAyDD,8BAmCC;AAGD,sBAWC;AApKD,uDAAqD;AACrD,6CAAyC;AAOzC,2CAAwC;AACxC,uCAAyC;AACzC,yCAA0C;AAE1C,MAAM,OAAO,GAAG,IAAI,oCAAiB,EAAmB,CAAC;AAEzD,6DAA6D;AAC7D,SAAgB,cAAc;IAC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C,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAoC,CAAC;IACrF,CAAC,CAAC;IACF,+DAA+D;IAC/D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,IAAI,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1F,OAAO,OAAuB,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { SessionStep } from "./types.js";
|
|
2
|
+
interface Rate {
|
|
3
|
+
in: number;
|
|
4
|
+
out: number;
|
|
5
|
+
}
|
|
6
|
+
/** Per-1M-token USD rates for common models. */
|
|
7
|
+
export declare const DEFAULT_RATES: Record<string, Rate>;
|
|
8
|
+
/** Fallback rate used when a model isn't in the table. Matches the API. */
|
|
9
|
+
export declare const FALLBACK_RATE: Rate;
|
|
10
|
+
/**
|
|
11
|
+
* Estimate total USD cost across a list of steps.
|
|
12
|
+
* Steps without a model use the fallback rate; steps without tokens
|
|
13
|
+
* contribute zero.
|
|
14
|
+
*/
|
|
15
|
+
export declare function estimateCost(steps: Array<SessionStep | {
|
|
16
|
+
model?: string | null;
|
|
17
|
+
tokensIn?: number | null;
|
|
18
|
+
tokensOut?: number | null;
|
|
19
|
+
}>): number;
|
|
20
|
+
/** Estimate cost for a single step. */
|
|
21
|
+
export declare function estimateStepCost(model: string | null | undefined, tokensIn?: number, tokensOut?: number): number;
|
|
22
|
+
/** Read-only copy of the rate table. */
|
|
23
|
+
export declare function getModelRates(): Record<string, Rate>;
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=cost.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.d.ts","sourceRoot":"","sources":["../../src/cost.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,UAAU,IAAI;IACZ,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;CACb;AAED,gDAAgD;AAChD,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAW9C,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,aAAa,EAAE,IAA8B,CAAC;AAE3D;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,WAAW,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,GAAG,MAAM,CAW/I;AAED,uCAAuC;AACvC,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAChC,QAAQ,SAAI,EACZ,SAAS,SAAI,GACZ,MAAM,CAER;AAED,wCAAwC;AACxC,wBAAgB,aAAa,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAEpD"}
|
package/dist/cjs/cost.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ReplayAI TypeScript SDK — per-model cost estimation.
|
|
3
|
+
// Rates are per 1,000,000 tokens in USD, matching the API's estimator.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.FALLBACK_RATE = exports.DEFAULT_RATES = void 0;
|
|
6
|
+
exports.estimateCost = estimateCost;
|
|
7
|
+
exports.estimateStepCost = estimateStepCost;
|
|
8
|
+
exports.getModelRates = getModelRates;
|
|
9
|
+
/** Per-1M-token USD rates for common models. */
|
|
10
|
+
exports.DEFAULT_RATES = {
|
|
11
|
+
"gpt-4o": { in: 2.5, out: 10.0 },
|
|
12
|
+
"gpt-4o-mini": { in: 0.15, out: 0.6 },
|
|
13
|
+
"gpt-4-turbo": { in: 10.0, out: 30.0 },
|
|
14
|
+
"gpt-3.5-turbo": { in: 0.5, out: 1.5 },
|
|
15
|
+
"claude-3.5-sonnet": { in: 3.0, out: 15.0 },
|
|
16
|
+
"claude-3-5-haiku": { in: 0.8, out: 4.0 },
|
|
17
|
+
"claude-3-opus": { in: 15.0, out: 75.0 },
|
|
18
|
+
"gemini-1.5-pro": { in: 1.25, out: 5.0 },
|
|
19
|
+
"gemini-1.5-flash": { in: 0.075, out: 0.3 },
|
|
20
|
+
"llama-3.1-70b": { in: 0.59, out: 0.79 },
|
|
21
|
+
};
|
|
22
|
+
/** Fallback rate used when a model isn't in the table. Matches the API. */
|
|
23
|
+
exports.FALLBACK_RATE = exports.DEFAULT_RATES["gpt-4o"];
|
|
24
|
+
/**
|
|
25
|
+
* Estimate total USD cost across a list of steps.
|
|
26
|
+
* Steps without a model use the fallback rate; steps without tokens
|
|
27
|
+
* contribute zero.
|
|
28
|
+
*/
|
|
29
|
+
function estimateCost(steps) {
|
|
30
|
+
let total = 0;
|
|
31
|
+
for (const s of steps) {
|
|
32
|
+
const model = s.model ?? undefined;
|
|
33
|
+
const rate = model && exports.DEFAULT_RATES[model] ? exports.DEFAULT_RATES[model] : exports.FALLBACK_RATE;
|
|
34
|
+
const tokensIn = s.tokensIn ?? 0;
|
|
35
|
+
const tokensOut = s.tokensOut ?? 0;
|
|
36
|
+
total += (tokensIn / 1_000_000) * rate.in;
|
|
37
|
+
total += (tokensOut / 1_000_000) * rate.out;
|
|
38
|
+
}
|
|
39
|
+
return Math.round(total * 1_000_000) / 1_000_000;
|
|
40
|
+
}
|
|
41
|
+
/** Estimate cost for a single step. */
|
|
42
|
+
function estimateStepCost(model, tokensIn = 0, tokensOut = 0) {
|
|
43
|
+
return estimateCost([{ model, tokensIn, tokensOut }]);
|
|
44
|
+
}
|
|
45
|
+
/** Read-only copy of the rate table. */
|
|
46
|
+
function getModelRates() {
|
|
47
|
+
return { ...exports.DEFAULT_RATES };
|
|
48
|
+
}
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AAK,IAAI,SAAS,CAAC;QACnC,MAAM,IAAI,GAAG,KAAK,IAAI,qBAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,qBAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,qBAAa,CAAC;QAClF,MAAM,QAAQ,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC;QACjC,MAAM,SAAS,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC;QACnC,KAAK,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;QAC1C,KAAK,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;IAC9C,CAAC;IACD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC;AACnD,CAAC;AAED,uCAAuC;AACvC,SAAgB,gBAAgB,CAC9B,KAAgC,EAChC,QAAQ,GAAG,CAAC,EACZ,SAAS,GAAG,CAAC;IAEb,OAAO,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,wCAAwC;AACxC,SAAgB,aAAa;IAC3B,OAAO,EAAE,GAAG,qBAAa,EAAE,CAAC;AAC9B,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { configure, getConfig, resetConfig } from "./config.js";
|
|
2
|
+
import { currentSession, trace, withTrace } from "./context.js";
|
|
3
|
+
import { recordStep, recordStepSync } from "./steps.js";
|
|
4
|
+
import { ReplaySession } from "./session.js";
|
|
5
|
+
import { flushSession, getLastFlushResult } from "./store.js";
|
|
6
|
+
import { estimateCost, estimateStepCost } from "./cost.js";
|
|
7
|
+
import { redactText, redactOptional } from "./redact.js";
|
|
8
|
+
import type { AgentProject, AgentSession, ConfigOptions, ExportLang, InternalSession, RecordStepInput, ReplaySessionOptions, RunOptions, SessionStatus, SessionStep, StepStatus, StepType, Trace, TraceOptions } from "./types.js";
|
|
9
|
+
/** SDK version. */
|
|
10
|
+
export declare const VERSION = "0.4.1";
|
|
11
|
+
export { trace, withTrace, recordStep, recordStepSync, configure, getConfig, resetConfig, currentSession, ReplaySession, flushSession, getLastFlushResult, estimateCost, estimateStepCost, redactText, redactOptional, };
|
|
12
|
+
export type { AgentProject, AgentSession, ConfigOptions, ExportLang, InternalSession, RecordStepInput, ReplaySessionOptions, RunOptions, SessionStatus, SessionStep, StepStatus, StepType, Trace, TraceOptions, };
|
|
13
|
+
declare const replayai: {
|
|
14
|
+
VERSION: string;
|
|
15
|
+
trace: typeof trace;
|
|
16
|
+
withTrace: typeof withTrace;
|
|
17
|
+
recordStep: typeof recordStep;
|
|
18
|
+
recordStepSync: typeof recordStepSync;
|
|
19
|
+
configure: typeof configure;
|
|
20
|
+
getConfig: typeof getConfig;
|
|
21
|
+
resetConfig: typeof resetConfig;
|
|
22
|
+
currentSession: typeof currentSession;
|
|
23
|
+
ReplaySession: typeof ReplaySession;
|
|
24
|
+
flushSession: typeof flushSession;
|
|
25
|
+
getLastFlushResult: typeof getLastFlushResult;
|
|
26
|
+
estimateCost: typeof estimateCost;
|
|
27
|
+
estimateStepCost: typeof estimateStepCost;
|
|
28
|
+
redactText: typeof redactText;
|
|
29
|
+
redactOptional: typeof redactOptional;
|
|
30
|
+
};
|
|
31
|
+
export default replayai;
|
|
32
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,a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