@withgateway/sdk 0.1.3 → 0.1.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.
Files changed (49) hide show
  1. package/dist/context/index.mjs +3 -0
  2. package/dist/context/index.mjs.map +1 -1
  3. package/dist/experiments/index.mjs +2 -0
  4. package/dist/experiments/index.mjs.map +1 -1
  5. package/dist/index-DnowA8MG.d.mts +447 -0
  6. package/dist/index-DnowA8MG.d.ts +447 -0
  7. package/dist/index.d.mts +6 -1
  8. package/dist/index.d.ts +6 -1
  9. package/dist/index.js +1715 -20
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +1686 -19
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/memory/index.mjs +3 -0
  14. package/dist/memory/index.mjs.map +1 -1
  15. package/dist/personas/index.d.mts +102 -0
  16. package/dist/personas/index.d.ts +102 -0
  17. package/dist/personas/index.js +205 -0
  18. package/dist/personas/index.js.map +1 -0
  19. package/dist/personas/index.mjs +180 -0
  20. package/dist/personas/index.mjs.map +1 -0
  21. package/dist/replay/index.d.mts +351 -0
  22. package/dist/replay/index.d.ts +351 -0
  23. package/dist/replay/index.js +1094 -0
  24. package/dist/replay/index.js.map +1 -0
  25. package/dist/replay/index.mjs +1057 -0
  26. package/dist/replay/index.mjs.map +1 -0
  27. package/dist/security/index.mjs +2 -0
  28. package/dist/security/index.mjs.map +1 -1
  29. package/dist/sessions/index.d.mts +143 -0
  30. package/dist/sessions/index.d.ts +143 -0
  31. package/dist/sessions/index.js +320 -0
  32. package/dist/sessions/index.js.map +1 -0
  33. package/dist/sessions/index.mjs +288 -0
  34. package/dist/sessions/index.mjs.map +1 -0
  35. package/dist/tracing/index.d.mts +3 -1
  36. package/dist/tracing/index.d.ts +3 -1
  37. package/dist/tracing/index.js +435 -8
  38. package/dist/tracing/index.js.map +1 -1
  39. package/dist/tracing/index.mjs +431 -8
  40. package/dist/tracing/index.mjs.map +1 -1
  41. package/dist/users/index.d.mts +81 -0
  42. package/dist/users/index.d.ts +81 -0
  43. package/dist/users/index.js +168 -0
  44. package/dist/users/index.js.map +1 -0
  45. package/dist/users/index.mjs +144 -0
  46. package/dist/users/index.mjs.map +1 -0
  47. package/package.json +25 -1
  48. package/dist/index-Caw3XVub.d.mts +0 -193
  49. package/dist/index-Caw3XVub.d.ts +0 -193
@@ -0,0 +1,180 @@
1
+ import { createRequire as __gatewayCreateRequire } from "module";
2
+ const require = __gatewayCreateRequire(import.meta.url);
3
+
4
+ // src/personas/index.ts
5
+ var PersonaError = class extends Error {
6
+ constructor(message, options) {
7
+ super(message);
8
+ this.name = "PersonaError";
9
+ this.cause = options?.cause;
10
+ }
11
+ };
12
+ var Persona = class {
13
+ id;
14
+ name;
15
+ description;
16
+ version;
17
+ instructions;
18
+ examples;
19
+ client;
20
+ constructor(fields) {
21
+ this.id = fields.id;
22
+ this.name = fields.name;
23
+ this.description = fields.description;
24
+ this.version = fields.version;
25
+ this.instructions = fields.instructions;
26
+ this.examples = fields.examples ?? [];
27
+ this.client = fields.client ?? null;
28
+ }
29
+ /**
30
+ * Get the persona's next user message for a conversation.
31
+ *
32
+ * `messages` use your agent's perspective: role `user` for the simulated
33
+ * user's prior turns, `assistant` for your agent's turns.
34
+ * `done` is true when the persona considers its goal met.
35
+ */
36
+ respond(messages) {
37
+ if (this.client === null) {
38
+ throw new PersonaError("Persona is not bound to a client.");
39
+ }
40
+ return this.client.chat(this.id, messages);
41
+ }
42
+ };
43
+ var PersonasClient = class _PersonasClient {
44
+ host;
45
+ publicKey;
46
+ secretKey;
47
+ timeoutSeconds;
48
+ debug;
49
+ constructor(config) {
50
+ this.host = config.host.replace(/\/$/, "");
51
+ this.publicKey = config.publicKey;
52
+ this.secretKey = config.secretKey;
53
+ this.timeoutSeconds = config.timeoutSeconds ?? 120;
54
+ this.debug = config.debug ?? false;
55
+ }
56
+ /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
57
+ static fromEnv(config = {}) {
58
+ const host = config.host ?? process.env.GATEWAY_HOST;
59
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
60
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
61
+ const missing = [
62
+ ["host", host],
63
+ ["publicKey", publicKey],
64
+ ["secretKey", secretKey]
65
+ ].filter(([, value]) => !value).map(([name]) => name);
66
+ if (missing.length > 0) {
67
+ throw new PersonaError(
68
+ `Missing Gateway persona configuration: ${missing.join(", ")}`
69
+ );
70
+ }
71
+ return new _PersonasClient({
72
+ ...config,
73
+ host,
74
+ publicKey,
75
+ secretKey
76
+ });
77
+ }
78
+ /** List the project's personas (without full instructions). */
79
+ async list() {
80
+ const payload = await this.requestJson("GET", "/api/public/personas");
81
+ const items = Array.isArray(payload.data) ? payload.data : [];
82
+ return items.filter(isRecord).map(
83
+ (item) => new Persona({
84
+ id: String(item.id),
85
+ name: String(item.name),
86
+ description: item.description ?? null,
87
+ version: typeof item.version === "number" ? item.version : 1,
88
+ instructions: "",
89
+ client: this
90
+ })
91
+ );
92
+ }
93
+ /** Fetch a persona (full definition) bound to this client. */
94
+ async get(personaId) {
95
+ const item = await this.requestJson(
96
+ "GET",
97
+ `/api/public/personas/${encodeURIComponent(personaId)}/chat`
98
+ );
99
+ return new Persona({
100
+ id: String(item.id),
101
+ name: String(item.name),
102
+ description: item.description ?? null,
103
+ version: typeof item.version === "number" ? item.version : 1,
104
+ instructions: typeof item.instructions === "string" ? item.instructions : "",
105
+ examples: Array.isArray(item.examples) ? item.examples.map((example) => String(example)) : [],
106
+ client: this
107
+ });
108
+ }
109
+ /** Play one persona turn. See {@link Persona.respond}. */
110
+ async chat(personaId, messages) {
111
+ const payload = await this.requestJson(
112
+ "POST",
113
+ `/api/public/personas/${encodeURIComponent(personaId)}/chat`,
114
+ { messages }
115
+ );
116
+ return {
117
+ content: typeof payload.content === "string" ? payload.content : "",
118
+ done: Boolean(payload.done)
119
+ };
120
+ }
121
+ async requestJson(method, path, payload) {
122
+ let response;
123
+ try {
124
+ response = await fetch(`${this.host}${path}`, {
125
+ method,
126
+ headers: {
127
+ Authorization: this.authHeader(),
128
+ "Content-Type": "application/json"
129
+ },
130
+ ...payload ? { body: JSON.stringify(payload) } : {},
131
+ signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
132
+ });
133
+ } catch (error) {
134
+ const reason = error instanceof Error ? error.message : String(error);
135
+ throw new PersonaError(`${method} ${path} failed: ${reason}`, {
136
+ cause: error
137
+ });
138
+ }
139
+ const text = await response.text();
140
+ if (!response.ok) {
141
+ const detail = text.slice(0, 500);
142
+ throw new PersonaError(
143
+ `${method} ${path} failed (${response.status}): ${detail}`
144
+ );
145
+ }
146
+ this.log("%s %s -> %s", method, path, response.status);
147
+ return safeJson(text);
148
+ }
149
+ authHeader() {
150
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
151
+ "base64"
152
+ )}`;
153
+ }
154
+ log(message, ...args) {
155
+ if (this.debug) {
156
+ console.log(`[gateway.personas] ${message}`, ...args);
157
+ }
158
+ }
159
+ };
160
+ function isRecord(value) {
161
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
162
+ }
163
+ function safeJson(value) {
164
+ try {
165
+ const parsed = JSON.parse(value);
166
+ return isRecord(parsed) ? parsed : {};
167
+ } catch {
168
+ return {};
169
+ }
170
+ }
171
+ var personas = {
172
+ fromEnv: PersonasClient.fromEnv
173
+ };
174
+ export {
175
+ Persona,
176
+ PersonaError,
177
+ PersonasClient,
178
+ personas
179
+ };
180
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/personas/index.ts"],"sourcesContent":["/**\n * Personas — simulated users served by the Gateway platform.\n *\n * A persona is a crafted user profile (usually derived from real sessions on\n * the platform) that Gateway serves as an endpoint. Use it to drive your agent\n * in tests: the persona plays the user, your agent plays itself.\n *\n * Example:\n * ```ts\n * import { PersonasClient } from \"@withgateway/sdk/personas\";\n *\n * const personas = PersonasClient.fromEnv();\n * const persona = await personas.get(\"persona_id\");\n *\n * const messages: PersonaMessage[] = [];\n * let reply = await persona.respond(messages); // persona opens the conversation\n * while (!reply.done) {\n * messages.push({ role: \"user\", content: reply.content });\n * const agentAnswer = await myAgent(messages); // your agent under test\n * messages.push({ role: \"assistant\", content: agentAnswer });\n * reply = await persona.respond(messages);\n * }\n * ```\n *\n * Message roles are from YOUR agent's perspective: `user` = the simulated\n * user's turns, `assistant` = your agent's turns.\n */\n\ntype PersonaMessage = {\n role: \"user\" | \"assistant\";\n content: string;\n};\n\n/** One simulated-user turn. */\ntype PersonaReply = {\n content: string;\n done: boolean;\n};\n\ntype PersonasClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype PersonasClientFromEnvConfig = Partial<PersonasClientConfig>;\n\n/** Raised when the Gateway personas API cannot complete a request. */\nexport class PersonaError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"PersonaError\";\n this.cause = options?.cause;\n }\n}\n\n/** A persona definition plus a bound `respond` helper. */\nexport class Persona {\n readonly id: string;\n readonly name: string;\n readonly description: string | null;\n readonly version: number;\n readonly instructions: string;\n readonly examples: string[];\n private readonly client: PersonasClient | null;\n\n constructor(fields: {\n id: string;\n name: string;\n description: string | null;\n version: number;\n instructions: string;\n examples?: string[];\n client?: PersonasClient | null;\n }) {\n this.id = fields.id;\n this.name = fields.name;\n this.description = fields.description;\n this.version = fields.version;\n this.instructions = fields.instructions;\n this.examples = fields.examples ?? [];\n this.client = fields.client ?? null;\n }\n\n /**\n * Get the persona's next user message for a conversation.\n *\n * `messages` use your agent's perspective: role `user` for the simulated\n * user's prior turns, `assistant` for your agent's turns.\n * `done` is true when the persona considers its goal met.\n */\n respond(messages: PersonaMessage[]): Promise<PersonaReply> {\n if (this.client === null) {\n throw new PersonaError(\"Persona is not bound to a client.\");\n }\n return this.client.chat(this.id, messages);\n }\n}\n\n/** Client for Gateway's persona endpoints (HTTP Basic project keys). */\nexport class PersonasClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: PersonasClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 120;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: PersonasClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new PersonaError(\n `Missing Gateway persona configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new PersonasClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** List the project's personas (without full instructions). */\n async list(): Promise<Persona[]> {\n const payload = await this.requestJson(\"GET\", \"/api/public/personas\");\n const items = Array.isArray(payload.data) ? payload.data : [];\n return items\n .filter(isRecord)\n .map(\n (item) =>\n new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: \"\",\n client: this,\n }),\n );\n }\n\n /** Fetch a persona (full definition) bound to this client. */\n async get(personaId: string): Promise<Persona> {\n const item = await this.requestJson(\n \"GET\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n );\n return new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: typeof item.instructions === \"string\" ? item.instructions : \"\",\n examples: Array.isArray(item.examples)\n ? item.examples.map((example) => String(example))\n : [],\n client: this,\n });\n }\n\n /** Play one persona turn. See {@link Persona.respond}. */\n async chat(\n personaId: string,\n messages: PersonaMessage[],\n ): Promise<PersonaReply> {\n const payload = await this.requestJson(\n \"POST\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n { messages },\n );\n return {\n content: typeof payload.content === \"string\" ? payload.content : \"\",\n done: Boolean(payload.done),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new PersonaError(`${method} ${path} failed: ${reason}`, {\n cause: error,\n });\n }\n\n const text = await response.text();\n if (!response.ok) {\n const detail = text.slice(0, 500);\n throw new PersonaError(\n `${method} ${path} failed (${response.status}): ${detail}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.personas] ${message}`, ...args);\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport const personas = {\n fromEnv: PersonasClient.fromEnv,\n};\n\nexport type {\n PersonaMessage,\n PersonaReply,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K,IAAI,eAAe,QAAQ,MAAM,SAAS,MAAM;AACrD,WAAO,SAAS,IAAI;AAAA,EACtB;AAAA,EAEQ,aAAa;AACnB,WAAO,SAAS,OAAO,KAAK,GAAG,KAAK,SAAS,IAAI,KAAK,SAAS,EAAE,EAAE;AAAA,MACjE;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEQ,IAAI,YAAoB,MAAiB;AAC/C,QAAI,KAAK,OAAO;AACd,cAAQ,IAAI,sBAAsB,OAAO,IAAI,GAAG,IAAI;AAAA,IACtD;AAAA,EACF;AACF;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAwC;AACxD,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,WAAO,SAAS,MAAM,IAAI,SAAS,CAAC;AAAA,EACtC,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,IAAM,WAAW;AAAA,EACtB,SAAS,eAAe;AAC1B;","names":[]}
@@ -0,0 +1,351 @@
1
+ import { SessionRecording } from '../sessions/index.mjs';
2
+
3
+ /**
4
+ * Regression suites replayed from platform task sets.
5
+ *
6
+ * A TASK SET on the platform (filed by the dream agent or a human) is a
7
+ * runnable regression suite: each task carries its prompt, expected behavior,
8
+ * and provenance to the RECORDED SESSION that motivated it. This module turns
9
+ * that into tests:
10
+ *
11
+ * ```typescript
12
+ * import { suite } from "@withgateway/sdk/replay";
13
+ *
14
+ * const regressions = await suite("groceat-regressions");
15
+ * for (const testCase of regressions) {
16
+ * const stubs = await testCase.stubs(); // the recorded world
17
+ * const out = await myAgent(testCase.prompt, stubs.asRegistry());
18
+ * const result = testCase.check(out, { calledTools: stubs.calledNames() });
19
+ * assert.ok(result.passed, result.explain());
20
+ * }
21
+ * ```
22
+ *
23
+ * Three layers pin three different things:
24
+ * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)
25
+ * - invariants pin THE CONTRACT (must/must-not tool calls)
26
+ * - your own assertions / platform judges pin THE SEMANTICS
27
+ *
28
+ * Case triage is three-way: PASS, FAIL (real regression — the world simulated
29
+ * fine and the contract broke), and DRIFT (the recorded world no longer
30
+ * matches the system — stub misses, renamed tools; the TEST is stale, not the
31
+ * agent).
32
+ *
33
+ * Mirrors the Python SDK's `gatewaysdk.replay` package.
34
+ */
35
+
36
+ /** Base error for replay loading/config problems. */
37
+ declare class ReplayError extends Error {
38
+ constructor(message: string, options?: {
39
+ cause?: unknown;
40
+ });
41
+ }
42
+ /** Strict-mode stub lookup failed — the recorded world has no answer. */
43
+ declare class StubMissError extends Error {
44
+ constructor(message: string);
45
+ }
46
+ /** The recorded session no longer matches the system (re-baseline the case). */
47
+ declare class DriftError extends ReplayError {
48
+ constructor(message: string);
49
+ }
50
+ type RecordedToolCall = {
51
+ name: string;
52
+ input: unknown;
53
+ output: unknown;
54
+ observationId: string;
55
+ };
56
+ type MissPolicy = "error" | "reuse" | "passthrough";
57
+ type StubMatch = "local" | "exact" | "exact-repeat" | "ordinal" | "reuse" | "miss";
58
+ type StubCallLogEntry = {
59
+ tool: string;
60
+ match: StubMatch;
61
+ input: unknown;
62
+ };
63
+ type StubFallback = (toolName: string, toolInput: unknown) => unknown;
64
+ type LocalTool = (toolInput: unknown) => unknown;
65
+ type ToolStub = (toolInput?: unknown) => unknown;
66
+ /**
67
+ * Tool registry that synthesizes stubs for unknown names (see
68
+ * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable
69
+ * that routes through `lookup()`, so the call is LOGGED and follows the miss
70
+ * policy instead of dying on an undefined-is-not-a-function error.
71
+ */
72
+ type StubRegistryMapping = Record<string, ToolStub>;
73
+ type StubRegistryOptions = {
74
+ missPolicy?: MissPolicy;
75
+ fallback?: StubFallback;
76
+ local?: Record<string, LocalTool>;
77
+ };
78
+ /**
79
+ * Replays recorded tool outputs from a case's recorded session.
80
+ *
81
+ * Match strategies (tried in order):
82
+ * local — the tool was declared `local`: run its live impl (new
83
+ * or deterministic tools that never need recordings)
84
+ * exact — normalized-JSON equality of the tool input
85
+ * exact-repeat — same (name, input) already replayed: return that output
86
+ * again (idempotent world reads never exhaust)
87
+ * ordinal — nth un-consumed recording for that tool name (robust to
88
+ * arg phrasing drift across models/prompts)
89
+ *
90
+ * Miss policy:
91
+ * "error" — throw StubMissError (strict replay; recorded as drift).
92
+ * NOTE: most agent frameworks catch tool errors and feed
93
+ * them to the model as error output, so this does NOT
94
+ * hard-stop such runs — the drift still lands in the
95
+ * report either way.
96
+ * "reuse" — exhausted a tool's recordings? replay the LAST recorded
97
+ * output for that name again (drift recorded). Keeps
98
+ * research-heavy agents running when they make more calls
99
+ * than the recording holds. Never-recorded names still
100
+ * throw (or hit `fallback` when provided).
101
+ * "passthrough" — call the `fallback` callable (live tool) and record the
102
+ * miss as drift for the report
103
+ */
104
+ declare class ToolStubRegistry {
105
+ readonly callLog: StubCallLogEntry[];
106
+ readonly driftEvents: string[];
107
+ private readonly recorded;
108
+ private readonly consumed;
109
+ private readonly consumptionOrder;
110
+ private missPolicy;
111
+ private fallback;
112
+ private readonly local;
113
+ constructor(calls: RecordedToolCall[], options?: StubRegistryOptions);
114
+ static fromSession(session: SessionRecording, options?: StubRegistryOptions): ToolStubRegistry;
115
+ /** Resolve a tool call against the recorded world. */
116
+ lookup(toolName: string, toolInput?: unknown): unknown;
117
+ /**
118
+ * Mapping of toolName → callable, drop-in for most agent tool layers.
119
+ *
120
+ * `local` merges in tools that should ALWAYS run live (new tools the
121
+ * recording predates, or deterministic/pure helpers) — they're logged for
122
+ * the contract check but never count as drift.
123
+ *
124
+ * UNKNOWN tool names also resolve (to a stub that routes through
125
+ * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the
126
+ * miss policy instead of dying on an undefined lookup — that log is what
127
+ * lets `check()` classify a forbidden-but-unrecorded call as FAIL.
128
+ */
129
+ asRegistry(options?: {
130
+ fallback?: StubFallback;
131
+ local?: Record<string, LocalTool>;
132
+ }): StubRegistryMapping;
133
+ calledNames(): string[];
134
+ /**
135
+ * 1:1 comparison of this replay against the recorded trace.
136
+ *
137
+ * The recording is the expectation: every recorded tool call should be
138
+ * replayed exactly once, in order, with nothing extra. Use for strict
139
+ * did-it-do-everything-the-original-did checks (`mode: "exact"`).
140
+ *
141
+ * `includeLocal`: count local-tool calls as extras (default false — local
142
+ * tools are declared live on purpose; their recorded calls are likewise
143
+ * excluded from "missing", since local bypasses recordings).
144
+ */
145
+ compare(options?: {
146
+ includeLocal?: boolean;
147
+ }): TraceDiff;
148
+ get drifted(): boolean;
149
+ }
150
+ /** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */
151
+ declare class TraceDiff {
152
+ readonly matched: string[];
153
+ readonly missing: string[];
154
+ readonly extra: string[];
155
+ readonly outOfOrder: string[];
156
+ constructor(fields?: {
157
+ matched?: string[];
158
+ missing?: string[];
159
+ extra?: string[];
160
+ outOfOrder?: string[];
161
+ });
162
+ get identical(): boolean;
163
+ explain(): string;
164
+ }
165
+ type ReplayTaskFields = {
166
+ id: string;
167
+ name?: string | null;
168
+ prompt?: unknown;
169
+ expectedOutput?: unknown;
170
+ metadata?: Record<string, unknown>;
171
+ };
172
+ /** One task-set item as served by GET /task-sets/{id}/tasks. */
173
+ declare class ReplayTask {
174
+ readonly id: string;
175
+ readonly name: string | null;
176
+ readonly prompt: unknown;
177
+ readonly expectedOutput: unknown;
178
+ readonly metadata: Record<string, unknown>;
179
+ constructor(fields: ReplayTaskFields);
180
+ get sourceSessionId(): string | null;
181
+ get sourceTraceId(): string | null;
182
+ static fromApi(raw: Record<string, unknown>): ReplayTask;
183
+ }
184
+ type ReplayStatus = "PASS" | "FAIL" | "DRIFT";
185
+ /** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */
186
+ declare class ReplayCheck {
187
+ readonly status: ReplayStatus;
188
+ readonly failures: string[];
189
+ readonly drift: string[];
190
+ readonly traceDiff: TraceDiff | null;
191
+ constructor(status: ReplayStatus, fields?: {
192
+ failures?: string[];
193
+ drift?: string[];
194
+ traceDiff?: TraceDiff | null;
195
+ });
196
+ get passed(): boolean;
197
+ get drifted(): boolean;
198
+ explain(): string;
199
+ }
200
+ type SessionLoader = (sessionId: string) => SessionRecording | Promise<SessionRecording>;
201
+ type ReplayMode = "contract" | "exact";
202
+ type CheckOptions = {
203
+ calledTools?: string[];
204
+ stubs?: ToolStubRegistry;
205
+ mode?: ReplayMode;
206
+ };
207
+ /** One regression case: a task bound to the session it was filed from. */
208
+ declare class ReplayCase {
209
+ readonly task: ReplayTask;
210
+ private readonly loader;
211
+ private _recording;
212
+ private _stubs;
213
+ constructor(task: ReplayTask, options: {
214
+ loader: SessionLoader;
215
+ });
216
+ get id(): string;
217
+ get name(): string;
218
+ get prompt(): unknown;
219
+ get expected(): unknown;
220
+ /** The full recorded session this case was filed from. */
221
+ recording(): Promise<SessionRecording>;
222
+ stubs(options?: StubRegistryOptions): Promise<ToolStubRegistry>;
223
+ /**
224
+ * The recorded conversation's user messages, one per turn — feed them to
225
+ * your agent in order to re-drive the full session (each turn was one
226
+ * trace in the recording).
227
+ */
228
+ conversation(): Promise<string[]>;
229
+ /**
230
+ * Contract invariants + drift triage.
231
+ *
232
+ * Invariants come from task metadata (the workbench-style contract):
233
+ * metadata.expectTools — every listed tool MUST have been called
234
+ * metadata.mustNotCall — none of these may have been called
235
+ * Semantic grading stays with the caller (assert on `output` /
236
+ * `case.expected`, or run a platform judge on the replay trace).
237
+ *
238
+ * `mode` (or task `metadata.replayMode`):
239
+ * "contract" (default) — grade only the invariants above
240
+ * "exact" — true 1:1 replay: the agent must reproduce EVERY
241
+ * recorded tool call, in order, with nothing extra
242
+ * (see TraceDiff); any divergence is a FAIL. The
243
+ * full diff lands in the failure reasons and
244
+ * `traceDiff`.
245
+ */
246
+ check(output?: unknown, options?: CheckOptions): ReplayCheck;
247
+ }
248
+ type ReplayCredentials = {
249
+ host: string;
250
+ publicKey: string;
251
+ secretKey: string;
252
+ timeoutSeconds?: number;
253
+ };
254
+ type ReplaySuiteLoadOptions = {
255
+ host?: string;
256
+ publicKey?: string;
257
+ secretKey?: string;
258
+ timeoutSeconds?: number;
259
+ };
260
+ type ReplaySuiteFields = {
261
+ taskSetId: string;
262
+ taskSetName: string;
263
+ cases: ReplayCase[];
264
+ /** Platform credentials for recording replay runs back to the task set. */
265
+ credentials?: ReplayCredentials | null;
266
+ };
267
+ /** All cases of one task set, iterable and indexable by name or id. */
268
+ declare class ReplaySuite implements Iterable<ReplayCase> {
269
+ readonly taskSetId: string;
270
+ readonly taskSetName: string;
271
+ readonly cases: ReplayCase[];
272
+ /** Credentials for recording replay runs back to the platform. */
273
+ readonly credentials: ReplayCredentials | null;
274
+ constructor(fields: ReplaySuiteFields);
275
+ [Symbol.iterator](): Iterator<ReplayCase>;
276
+ get length(): number;
277
+ /** Look up a case by id or name (throws when absent). */
278
+ get(key: string): ReplayCase;
279
+ static fromTaskSet(nameOrId: string, options?: ReplaySuiteLoadOptions): Promise<ReplaySuite>;
280
+ /** Run the whole suite against `agent` — see `runSuite()`. */
281
+ run(agent: ReplayAgent, options?: RunSuiteOptions): Promise<ReplayReport>;
282
+ /** Pin every case's recorded session into the repo as JSON fixtures. */
283
+ snapshot(directory: string): Promise<string[]>;
284
+ }
285
+ /**
286
+ * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`
287
+ * — declare only the parameters you need (this replaces the Python SDK's
288
+ * signature sniffing with idiomatic JavaScript):
289
+ *
290
+ * `(prompt) => ...` — prompt-only agents
291
+ * `(prompt, tools) => ...` — the common shape
292
+ * `(prompt, tools, replayCase) => ...` — full case access
293
+ * (rebuild stubs via `replayCase.stubs()`)
294
+ */
295
+ type ReplayAgent = (prompt: unknown, tools: StubRegistryMapping, replayCase: ReplayCase) => unknown | Promise<unknown>;
296
+ declare class ReplayReport {
297
+ readonly results: Record<string, ReplayCheck>;
298
+ readonly runName: string | null;
299
+ readonly recordingErrors: string[];
300
+ constructor(results: Record<string, ReplayCheck>, fields?: {
301
+ runName?: string | null;
302
+ recordingErrors?: string[];
303
+ });
304
+ get passed(): number;
305
+ get failed(): number;
306
+ get drifted(): number;
307
+ /** True when nothing FAILED (drift is stale-test signal, not failure). */
308
+ get ok(): boolean;
309
+ explain(): string;
310
+ private count;
311
+ }
312
+ /**
313
+ * Replay traffic records under this environment — the platform hides it from
314
+ * the sessions/traces tables by default (users opt back in via the
315
+ * environment filter), so regression runs never pollute real usage views.
316
+ */
317
+ declare const REPLAY_ENVIRONMENT = "gateway-replay";
318
+ type RunSuiteOptions = {
319
+ missPolicy?: MissPolicy;
320
+ record?: boolean;
321
+ runName?: string;
322
+ };
323
+ /**
324
+ * Run every case and triage. The agent is invoked as
325
+ * `agent(prompt, tools, replayCase)` — declare only what you need.
326
+ *
327
+ * Recording (`record` undefined → auto when the suite was loaded from the
328
+ * platform): each case is filed as a dataset-run item on the task set, so
329
+ * the replay run shows up in the task set's runs with per-case status.
330
+ *
331
+ * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —
332
+ * the TypeScript tracing module has no per-trace context primitive yet. Run
333
+ * items are filed with a synthetic trace id, exactly like a Python run
334
+ * without tracing configured.
335
+ */
336
+ declare function runSuite(suiteToRun: ReplaySuite, agent: ReplayAgent, options?: RunSuiteOptions): Promise<ReplayReport>;
337
+ /**
338
+ * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:
339
+ *
340
+ * ```typescript
341
+ * import * as replay from "@withgateway/sdk/replay";
342
+ * const report = await (await replay.suite("checkout-regressions")).run(myAgent);
343
+ * ```
344
+ */
345
+ declare function suite(nameOrId: string, options?: ReplaySuiteLoadOptions): Promise<ReplaySuite>;
346
+ declare const replay: {
347
+ suite: typeof suite;
348
+ run: typeof runSuite;
349
+ };
350
+
351
+ export { DriftError, type LocalTool, type MissPolicy, REPLAY_ENVIRONMENT, type RecordedToolCall, type ReplayAgent, ReplayCase, ReplayCheck, type ReplayCredentials, ReplayError, type ReplayMode, ReplayReport, type ReplayStatus, ReplaySuite, type ReplaySuiteLoadOptions, ReplayTask, type RunSuiteOptions, type SessionLoader, type StubCallLogEntry, type StubFallback, type StubMatch, StubMissError, type StubRegistryMapping, type ToolStub, ToolStubRegistry, TraceDiff, replay, runSuite, suite };