@withgateway/sdk 0.3.3 → 0.6.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/README.md +4 -3
- package/dist/cli.js +3005 -1401
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +2996 -1392
- package/dist/cli.mjs.map +1 -1
- package/dist/files/index.js +128 -37
- package/dist/files/index.js.map +1 -1
- package/dist/files/index.mjs +126 -35
- package/dist/files/index.mjs.map +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/index.js +124 -11
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +124 -11
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/{index-C3UzD0G3.d.mts → index-CDPQBsU5.d.mts} +19 -3
- package/dist/{index-C3UzD0G3.d.ts → index-CDPQBsU5.d.ts} +19 -3
- package/dist/{index-mJhG3vZU.d.mts → index-Di9nNqOY.d.mts} +26 -3
- package/dist/{index-DUHmS74p.d.ts → index-LA-PMRJT.d.ts} +26 -3
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1078 -260
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1040 -251
- package/dist/index.mjs.map +1 -1
- package/dist/replay/index.d.mts +1 -1
- package/dist/replay/index.d.ts +1 -1
- package/dist/replay/index.js.map +1 -1
- package/dist/replay/index.mjs.map +1 -1
- package/dist/traces/index.js +125 -34
- package/dist/traces/index.js.map +1 -1
- package/dist/traces/index.mjs +123 -32
- package/dist/traces/index.mjs.map +1 -1
- package/dist/tracing/index.d.mts +1 -1
- package/dist/tracing/index.d.ts +1 -1
- package/dist/tracing/index.js +7 -1
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +7 -1
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/worlds/index.d.mts +819 -438
- package/dist/worlds/index.d.ts +819 -438
- package/dist/worlds/index.js +912 -236
- package/dist/worlds/index.js.map +1 -1
- package/dist/worlds/index.mjs +908 -232
- package/dist/worlds/index.mjs.map +1 -1
- package/package.json +1 -1
- package/runtime/gatewaysdk/environment/_bundle.py +4 -6
- package/runtime/gatewaysdk/environment/_materialize.py +5 -25
- package/runtime/gatewaysdk/environment/_world.py +82 -66
- package/runtime/gatewaysdk/environment/backing.py +20 -24
- package/runtime/gatewaysdk/environment/core.py +1 -16
- package/runtime/gatewaysdk/environment/legacy_sqlite.py +14 -27
- package/runtime/gatewaysdk/environment/runtime.py +45 -2
- package/runtime/gatewaysdk/environment/schema/admission.py +174 -0
- package/runtime/gatewaysdk/environment/schema/api.py +198 -474
- package/runtime/gatewaysdk/environment/schema/assertions.py +458 -0
- package/runtime/gatewaysdk/environment/schema/batch.py +3 -3
- package/runtime/gatewaysdk/environment/schema/bundle_runtime.py +1 -0
- package/runtime/gatewaysdk/environment/schema/cache_layout.py +5 -0
- package/runtime/gatewaysdk/environment/schema/call_capture.py +321 -0
- package/runtime/gatewaysdk/environment/schema/call_log.py +276 -18
- package/runtime/gatewaysdk/environment/schema/call_redaction.py +207 -19
- package/runtime/gatewaysdk/environment/schema/cast.py +15 -35
- package/runtime/gatewaysdk/environment/schema/compiler.py +4 -1
- package/runtime/gatewaysdk/environment/schema/conform.py +38 -35
- package/runtime/gatewaysdk/environment/schema/connector.py +94 -152
- package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +1 -12
- package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +2 -1
- package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +217 -58
- package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +10 -19
- package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +10 -2
- package/runtime/gatewaysdk/environment/schema/connectors/github/tests/webhooks.json +47 -0
- package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +21 -0
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +185 -18
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +29 -14
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +43 -12
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +2 -2
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +4 -17
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/webhooks.json +107 -0
- package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -1
- package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +85 -1
- package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +19 -31
- package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +18 -8
- package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +19 -3
- package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/test_webhooks.py +71 -0
- package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +2 -5
- package/runtime/gatewaysdk/environment/schema/cors.py +54 -0
- package/runtime/gatewaysdk/environment/schema/credentials.py +313 -8
- package/runtime/gatewaysdk/environment/schema/data.py +14 -13
- package/runtime/gatewaysdk/environment/schema/database/base.py +106 -165
- package/runtime/gatewaysdk/environment/schema/database/guard.py +45 -37
- package/runtime/gatewaysdk/environment/schema/database/reads.py +169 -0
- package/runtime/gatewaysdk/environment/schema/database/sqlite.py +57 -31
- package/runtime/gatewaysdk/environment/schema/declared_routes.py +210 -0
- package/runtime/gatewaysdk/environment/schema/door.py +899 -0
- package/runtime/gatewaysdk/environment/schema/envelope.py +86 -28
- package/runtime/gatewaysdk/environment/schema/grading.py +58 -86
- package/runtime/gatewaysdk/environment/schema/handler_errors.py +52 -5
- package/runtime/gatewaysdk/environment/schema/host.py +229 -1695
- package/runtime/gatewaysdk/environment/schema/host_control.py +144 -0
- package/runtime/gatewaysdk/environment/schema/host_handoff.py +370 -0
- package/runtime/gatewaysdk/environment/schema/host_loops.py +97 -0
- package/runtime/gatewaysdk/environment/schema/host_owners.py +121 -0
- package/runtime/gatewaysdk/environment/schema/host_proxy.py +111 -0
- package/runtime/gatewaysdk/environment/schema/host_requests.py +6 -0
- package/runtime/gatewaysdk/environment/schema/host_session.py +126 -0
- package/runtime/gatewaysdk/environment/schema/host_surfaces.py +79 -21
- package/runtime/gatewaysdk/environment/schema/host_transfers.py +127 -0
- package/runtime/gatewaysdk/environment/schema/host_versions.py +242 -0
- package/runtime/gatewaysdk/environment/schema/host_workers.py +577 -0
- package/runtime/gatewaysdk/environment/schema/journal.py +438 -0
- package/runtime/gatewaysdk/environment/schema/ledger_spill.py +828 -0
- package/runtime/gatewaysdk/environment/schema/local.py +32 -116
- package/runtime/gatewaysdk/environment/schema/openapi_schemas.py +20 -5
- package/runtime/gatewaysdk/environment/schema/platform.py +29 -234
- package/runtime/gatewaysdk/environment/schema/request_body.py +238 -0
- package/runtime/gatewaysdk/environment/schema/request_ledger.py +958 -0
- package/runtime/gatewaysdk/environment/schema/route_bindings.py +25 -3
- package/runtime/gatewaysdk/environment/schema/route_miss.py +54 -0
- package/runtime/gatewaysdk/environment/schema/runtime.py +136 -176
- package/runtime/gatewaysdk/environment/schema/scaffold.py +2 -1
- package/runtime/gatewaysdk/environment/schema/session_files.py +133 -24
- package/runtime/gatewaysdk/environment/schema/session_move.py +275 -0
- package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +5 -1
- package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +8 -9
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +3 -3
- package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +50 -28
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +12 -8
- package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +20 -22
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +25 -25
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/gotchas.md +71 -7
- package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/journal-checks.md +182 -0
- package/runtime/gatewaysdk/environment/schema/snapshot.py +150 -30
- package/runtime/gatewaysdk/environment/schema/spill_files.py +228 -0
- package/runtime/gatewaysdk/environment/schema/tasks.py +229 -323
- package/runtime/gatewaysdk/environment/schema/tools_world.py +103 -203
- package/runtime/gatewaysdk/environment/schema/validation.py +69 -1
- package/runtime/gatewaysdk/environment/schema/verbs.py +38 -36
- package/runtime/gatewaysdk/environment/schema/webhooks.py +687 -0
- package/runtime/gatewaysdk/environment/schema/worker.py +6 -4
- package/runtime/gatewaysdk/environment/schema/workers.py +203 -39
- package/runtime/gatewaysdk/environment/schema/world_host.py +970 -0
- package/runtime/gatewaysdk/environment/schema/world_tests.py +83 -11
- package/runtime/gatewaysdk/environment/world.py +1 -1
- package/runtime/gatewaysdk/environment/world_session_contract.py +14 -0
- package/skills/agents/connector-template-author.md +5 -1
- package/skills/benchmarks-getting-started/SKILL.md +8 -9
- package/skills/connector-schema-authoring/CONNECTORS.md +3 -3
- package/skills/connector-schema-authoring/SKILL.md +50 -28
- package/skills/connector-schema-authoring/connector-worlds.md +282 -18
- package/skills/connector-schema-authoring/world-schema.md +7 -6
- package/skills/world-data-ingestion/ROWS.md +12 -8
- package/skills/world-data-ingestion/SKILL.md +20 -22
- package/skills/worlds-getting-started/SKILL.md +25 -25
- package/skills/worlds-getting-started/references/cli-mcp-map.md +24 -16
- package/skills/worlds-getting-started/references/gotchas.md +71 -7
- package/skills/worlds-getting-started/references/journal-checks.md +182 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sessions/index.ts","../../src/replay/index.ts"],"sourcesContent":["/**\n * Load Gateway sessions for replay and test-fixture generation.\n *\n * The premier workflow: pull a real production session from the platform and\n * turn it into a regression test in your repo.\n *\n * ```typescript\n * import { loadSession } from \"@withgateway/sdk/sessions\";\n *\n * const session = await loadSession(\"session-id\"); // env-configured Gateway\n * for (const turn of session.turns()) { // (input, output) per trace\n * const result = await myAgent(turn.input);\n * assert.deepEqual(result, turn.output); // or fuzzier assertions\n * }\n *\n * session.toFixture(\"tests/fixtures/checkout_regression.json\");\n * ```\n *\n * Auth/config mirror the tracing exporter: GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey explicitly). Data comes\n * from `GET /api/public/sessions/{id}?includeIO=true` — one call, full\n * untruncated input/output for every trace and observation.\n *\n * Mirrors the Python SDK's `gatewaysdk.sessions` module.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport const ENV_GATEWAY_HOST = \"GATEWAY_HOST\";\nexport const ENV_GATEWAY_PUBLIC_KEY = \"GATEWAY_PUBLIC_KEY\";\nexport const ENV_GATEWAY_SECRET_KEY = \"GATEWAY_SECRET_KEY\";\n\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\n\n/** Raised when a session cannot be loaded from Gateway. */\nexport class SessionLoadError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"SessionLoadError\";\n this.cause = options?.cause;\n }\n}\n\n/** One observation (LLM generation, tool call, span) with full IO. */\nexport type SessionObservation = {\n id: string;\n type: string | null;\n name: string | null;\n level: string | null;\n statusMessage: string | null;\n model: string | null;\n input: unknown;\n output: unknown;\n metadata: unknown;\n parentObservationId: string | null;\n startTime: string | null;\n endTime: string | null;\n};\n\nexport function sessionObservationFromApi(\n raw: Record<string, unknown>,\n): SessionObservation {\n return {\n id: String(raw.id ?? \"\"),\n type: asStringOrNull(raw.type),\n name: asStringOrNull(raw.name),\n level: asStringOrNull(raw.level),\n statusMessage: asStringOrNull(raw.statusMessage),\n model: asStringOrNull(raw.model),\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n parentObservationId: asStringOrNull(raw.parentObservationId),\n startTime: raw.startTime ? String(raw.startTime) : null,\n endTime: raw.endTime ? String(raw.endTime) : null,\n };\n}\n\ntype SessionTraceFields = {\n id: string;\n name: string | null;\n timestamp: string | null;\n input: unknown;\n output: unknown;\n metadata?: unknown;\n tags?: string[];\n observations?: SessionObservation[];\n};\n\n/** One trace (agent turn) in the session, with full IO + observations. */\nexport class SessionTrace {\n readonly id: string;\n readonly name: string | null;\n readonly timestamp: string | null;\n readonly input: unknown;\n readonly output: unknown;\n readonly metadata: unknown;\n readonly tags: string[];\n readonly observations: SessionObservation[];\n\n constructor(fields: SessionTraceFields) {\n this.id = fields.id;\n this.name = fields.name;\n this.timestamp = fields.timestamp;\n this.input = fields.input;\n this.output = fields.output;\n this.metadata = fields.metadata ?? null;\n this.tags = fields.tags ?? [];\n this.observations = fields.observations ?? [];\n }\n\n get toolCalls(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"TOOL\",\n );\n }\n\n get generations(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"GENERATION\",\n );\n }\n\n /**\n * The user message that started this turn.\n *\n * Handles the common recorded shapes: a plain string input, an OpenAI\n * message list (last role=user entry wins — earlier ones are carried\n * history), or an object with a content/input field.\n */\n userMessage(): string | null {\n const value = this.input;\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (isPlainObject(entry) && entry.role === \"user\") {\n const content = entry.content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n // content-part lists\n const parts = content\n .filter(isPlainObject)\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"));\n return parts.join(\"\") || null;\n }\n }\n }\n return null;\n }\n if (isPlainObject(value)) {\n for (const key of [\"content\", \"input\", \"text\", \"message\"]) {\n if (typeof value[key] === \"string\") {\n return value[key] as string;\n }\n }\n }\n return null;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionTrace {\n return new SessionTrace({\n id: String(raw.id ?? \"\"),\n name: asStringOrNull(raw.name),\n timestamp: raw.timestamp ? String(raw.timestamp) : null,\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],\n observations: (Array.isArray(raw.observations) ? raw.observations : [])\n .filter(isPlainObject)\n .map(sessionObservationFromApi),\n });\n }\n}\n\ntype SessionRecordingFields = {\n sessionId: string;\n projectId: string | null;\n environment: string | null;\n traces?: SessionTrace[];\n};\n\ntype SelectFilter = {\n type?: string;\n name?: string;\n level?: string;\n};\n\n/** A fully-loaded session: every trace, every observation, full IO. */\nexport class SessionRecording {\n readonly sessionId: string;\n readonly projectId: string | null;\n readonly environment: string | null;\n readonly traces: SessionTrace[];\n\n constructor(fields: SessionRecordingFields) {\n this.sessionId = fields.sessionId;\n this.projectId = fields.projectId;\n this.environment = fields.environment;\n this.traces = fields.traces ?? [];\n }\n\n /** Traces in chronological order — one per agent turn. */\n turns(): SessionTrace[] {\n return [...this.traces].sort((a, b) => {\n const left = a.timestamp ?? \"\";\n const right = b.timestamp ?? \"\";\n return left < right ? -1 : left > right ? 1 : 0;\n });\n }\n\n /** The nth chronological turn (negative indices allowed). */\n turn(index: number): SessionTrace {\n const ordered = this.turns();\n const found = ordered.at(index);\n if (!found) {\n throw new RangeError(\n `Turn index ${index} out of range (session has ${ordered.length} turns)`,\n );\n }\n return found;\n }\n\n /**\n * The user message of each turn, in order — feed these back to an agent\n * to re-drive the recorded conversation.\n */\n userMessages(): Array<string | null> {\n return this.turns().map((trace) => trace.userMessage());\n }\n\n /** Output of the last chronological turn (null when empty). */\n finalOutput(): unknown {\n const ordered = this.turns();\n return ordered.length > 0 ? ordered[ordered.length - 1].output : null;\n }\n\n /** Every TOOL observation across the session, chronological. */\n toolCalls(): SessionObservation[] {\n return this.select({ type: \"TOOL\" });\n }\n\n /** Every GENERATION observation across the session, chronological. */\n generations(): SessionObservation[] {\n return this.select({ type: \"GENERATION\" });\n }\n\n /** Filter observations across all turns (chronological order). */\n select(filter: SelectFilter = {}): SessionObservation[] {\n const selected: SessionObservation[] = [];\n for (const trace of this.turns()) {\n for (const observation of trace.observations) {\n if (\n filter.type &&\n (observation.type ?? \"\").toUpperCase() !== filter.type.toUpperCase()\n ) {\n continue;\n }\n if (filter.name && observation.name !== filter.name) {\n continue;\n }\n if (\n filter.level &&\n (observation.level ?? \"\").toUpperCase() !== filter.level.toUpperCase()\n ) {\n continue;\n }\n selected.push(observation);\n }\n }\n return selected;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n sessionId: this.sessionId,\n projectId: this.projectId,\n environment: this.environment,\n traces: this.turns().map((trace) => ({\n id: trace.id,\n name: trace.name,\n timestamp: trace.timestamp,\n input: trace.input,\n output: trace.output,\n metadata: trace.metadata,\n tags: trace.tags,\n observations: trace.observations.map((o) => ({ ...o })),\n })),\n };\n }\n\n /** Dump the full session as a JSON fixture (for regression tests). */\n toFixture(path: string): string {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), \"utf-8\");\n return path;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionRecording {\n return new SessionRecording({\n sessionId: String(raw.id ?? \"\"),\n projectId: asStringOrNull(raw.projectId),\n environment: asStringOrNull(raw.environment),\n traces: (Array.isArray(raw.traces) ? raw.traces : [])\n .filter(isPlainObject)\n .map(SessionTrace.fromApi),\n });\n }\n}\n\nexport type LoadSessionOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\n/**\n * Load a full session (all traces + observations, untruncated IO).\n *\n * Credentials default to the same environment variables the tracing\n * exporter uses: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.\n */\nexport async function loadSession(\n sessionId: string,\n options: LoadSessionOptions = {},\n): Promise<SessionRecording> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, GATEWAY_PUBLIC_KEY \" +\n \"and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey).\",\n );\n }\n\n const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: basicAuthHeader(publicKey, secretKey) },\n signal: AbortSignal.timeout(timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (response.status === 404) {\n throw new SessionLoadError(`Session not found: ${sessionId}`);\n }\n const text = await response.text();\n if (!response.ok) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: response is not valid JSON`,\n { cause: error },\n );\n }\n return SessionRecording.fromApi(\n isPlainObject(payload) ? payload : {},\n );\n}\n\nexport function basicAuthHeader(publicKey: string, secretKey: string): string {\n return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\")}`;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport const sessions = {\n load: loadSession,\n};\n","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by the dream agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const replay = {\n suite,\n run: runSuite,\n};\n"],"mappings":";;;;AA0BA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AAEjB,IAAM,mBAAmB;AACzB,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AAE/B,IAAM,0BAA0B;AAGhC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAkBO,SAAS,0BACd,KACoB;AACpB,SAAO;AAAA,IACL,IAAI,OAAO,IAAI,MAAM,EAAE;AAAA,IACvB,MAAM,eAAe,IAAI,IAAI;AAAA,IAC7B,MAAM,eAAe,IAAI,IAAI;AAAA,IAC7B,OAAO,eAAe,IAAI,KAAK;AAAA,IAC/B,eAAe,eAAe,IAAI,aAAa;AAAA,IAC/C,OAAO,eAAe,IAAI,KAAK;AAAA,IAC/B,OAAO,IAAI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Ac,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,gBAAgB,MAAuC;AAC9D,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,IAAI;AAC9B,WAAOA,eAAc,MAAM,IAAI,SAAS,CAAC;AAAA,EAC3C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEA,SAAS,YAAoB;AAC3B,SAAO,OAAO,WAAW,EAAE,QAAQ,MAAM,EAAE;AAC7C;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEO,IAAM,SAAS;AAAA,EACpB;AAAA,EACA,KAAK;AACP;","names":["isPlainObject"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sessions/index.ts","../../src/replay/index.ts"],"sourcesContent":["/**\n * Load Gateway sessions for replay and test-fixture generation.\n *\n * The premier workflow: pull a real production session from the platform and\n * turn it into a regression test in your repo.\n *\n * ```typescript\n * import { loadSession } from \"@withgateway/sdk/sessions\";\n *\n * const session = await loadSession(\"session-id\"); // env-configured Gateway\n * for (const turn of session.turns()) { // (input, output) per trace\n * const result = await myAgent(turn.input);\n * assert.deepEqual(result, turn.output); // or fuzzier assertions\n * }\n *\n * session.toFixture(\"tests/fixtures/checkout_regression.json\");\n * ```\n *\n * Auth/config mirror the tracing exporter: GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey explicitly). Data comes\n * from `GET /api/public/sessions/{id}?includeIO=true` — one call, full\n * untruncated input/output for every trace and observation.\n *\n * Mirrors the Python SDK's `gatewaysdk.sessions` module.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport const ENV_GATEWAY_HOST = \"GATEWAY_HOST\";\nexport const ENV_GATEWAY_PUBLIC_KEY = \"GATEWAY_PUBLIC_KEY\";\nexport const ENV_GATEWAY_SECRET_KEY = \"GATEWAY_SECRET_KEY\";\n\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\n\n/** Raised when a session cannot be loaded from Gateway. */\nexport class SessionLoadError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"SessionLoadError\";\n this.cause = options?.cause;\n }\n}\n\n/** One observation (LLM generation, tool call, span) with full IO. */\nexport type SessionObservation = {\n id: string;\n type: string | null;\n name: string | null;\n level: string | null;\n statusMessage: string | null;\n model: string | null;\n input: unknown;\n output: unknown;\n metadata: unknown;\n parentObservationId: string | null;\n startTime: string | null;\n endTime: string | null;\n};\n\nexport function sessionObservationFromApi(\n raw: Record<string, unknown>,\n): SessionObservation {\n return {\n id: String(raw.id ?? \"\"),\n type: asStringOrNull(raw.type),\n name: asStringOrNull(raw.name),\n level: asStringOrNull(raw.level),\n statusMessage: asStringOrNull(raw.statusMessage),\n model: asStringOrNull(raw.model),\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n parentObservationId: asStringOrNull(raw.parentObservationId),\n startTime: raw.startTime ? String(raw.startTime) : null,\n endTime: raw.endTime ? String(raw.endTime) : null,\n };\n}\n\ntype SessionTraceFields = {\n id: string;\n name: string | null;\n timestamp: string | null;\n input: unknown;\n output: unknown;\n metadata?: unknown;\n tags?: string[];\n observations?: SessionObservation[];\n};\n\n/** One trace (agent turn) in the session, with full IO + observations. */\nexport class SessionTrace {\n readonly id: string;\n readonly name: string | null;\n readonly timestamp: string | null;\n readonly input: unknown;\n readonly output: unknown;\n readonly metadata: unknown;\n readonly tags: string[];\n readonly observations: SessionObservation[];\n\n constructor(fields: SessionTraceFields) {\n this.id = fields.id;\n this.name = fields.name;\n this.timestamp = fields.timestamp;\n this.input = fields.input;\n this.output = fields.output;\n this.metadata = fields.metadata ?? null;\n this.tags = fields.tags ?? [];\n this.observations = fields.observations ?? [];\n }\n\n get toolCalls(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"TOOL\",\n );\n }\n\n get generations(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"GENERATION\",\n );\n }\n\n /**\n * The user message that started this turn.\n *\n * Handles the common recorded shapes: a plain string input, an OpenAI\n * message list (last role=user entry wins — earlier ones are carried\n * history), or an object with a content/input field.\n */\n userMessage(): string | null {\n const value = this.input;\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (isPlainObject(entry) && entry.role === \"user\") {\n const content = entry.content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n // content-part lists\n const parts = content\n .filter(isPlainObject)\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"));\n return parts.join(\"\") || null;\n }\n }\n }\n return null;\n }\n if (isPlainObject(value)) {\n for (const key of [\"content\", \"input\", \"text\", \"message\"]) {\n if (typeof value[key] === \"string\") {\n return value[key] as string;\n }\n }\n }\n return null;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionTrace {\n return new SessionTrace({\n id: String(raw.id ?? \"\"),\n name: asStringOrNull(raw.name),\n timestamp: raw.timestamp ? String(raw.timestamp) : null,\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],\n observations: (Array.isArray(raw.observations) ? raw.observations : [])\n .filter(isPlainObject)\n .map(sessionObservationFromApi),\n });\n }\n}\n\ntype SessionRecordingFields = {\n sessionId: string;\n projectId: string | null;\n environment: string | null;\n traces?: SessionTrace[];\n};\n\ntype SelectFilter = {\n type?: string;\n name?: string;\n level?: string;\n};\n\n/** A fully-loaded session: every trace, every observation, full IO. */\nexport class SessionRecording {\n readonly sessionId: string;\n readonly projectId: string | null;\n readonly environment: string | null;\n readonly traces: SessionTrace[];\n\n constructor(fields: SessionRecordingFields) {\n this.sessionId = fields.sessionId;\n this.projectId = fields.projectId;\n this.environment = fields.environment;\n this.traces = fields.traces ?? [];\n }\n\n /** Traces in chronological order — one per agent turn. */\n turns(): SessionTrace[] {\n return [...this.traces].sort((a, b) => {\n const left = a.timestamp ?? \"\";\n const right = b.timestamp ?? \"\";\n return left < right ? -1 : left > right ? 1 : 0;\n });\n }\n\n /** The nth chronological turn (negative indices allowed). */\n turn(index: number): SessionTrace {\n const ordered = this.turns();\n const found = ordered.at(index);\n if (!found) {\n throw new RangeError(\n `Turn index ${index} out of range (session has ${ordered.length} turns)`,\n );\n }\n return found;\n }\n\n /**\n * The user message of each turn, in order — feed these back to an agent\n * to re-drive the recorded conversation.\n */\n userMessages(): Array<string | null> {\n return this.turns().map((trace) => trace.userMessage());\n }\n\n /** Output of the last chronological turn (null when empty). */\n finalOutput(): unknown {\n const ordered = this.turns();\n return ordered.length > 0 ? ordered[ordered.length - 1].output : null;\n }\n\n /** Every TOOL observation across the session, chronological. */\n toolCalls(): SessionObservation[] {\n return this.select({ type: \"TOOL\" });\n }\n\n /** Every GENERATION observation across the session, chronological. */\n generations(): SessionObservation[] {\n return this.select({ type: \"GENERATION\" });\n }\n\n /** Filter observations across all turns (chronological order). */\n select(filter: SelectFilter = {}): SessionObservation[] {\n const selected: SessionObservation[] = [];\n for (const trace of this.turns()) {\n for (const observation of trace.observations) {\n if (\n filter.type &&\n (observation.type ?? \"\").toUpperCase() !== filter.type.toUpperCase()\n ) {\n continue;\n }\n if (filter.name && observation.name !== filter.name) {\n continue;\n }\n if (\n filter.level &&\n (observation.level ?? \"\").toUpperCase() !== filter.level.toUpperCase()\n ) {\n continue;\n }\n selected.push(observation);\n }\n }\n return selected;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n sessionId: this.sessionId,\n projectId: this.projectId,\n environment: this.environment,\n traces: this.turns().map((trace) => ({\n id: trace.id,\n name: trace.name,\n timestamp: trace.timestamp,\n input: trace.input,\n output: trace.output,\n metadata: trace.metadata,\n tags: trace.tags,\n observations: trace.observations.map((o) => ({ ...o })),\n })),\n };\n }\n\n /** Dump the full session as a JSON fixture (for regression tests). */\n toFixture(path: string): string {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), \"utf-8\");\n return path;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionRecording {\n return new SessionRecording({\n sessionId: String(raw.id ?? \"\"),\n projectId: asStringOrNull(raw.projectId),\n environment: asStringOrNull(raw.environment),\n traces: (Array.isArray(raw.traces) ? raw.traces : [])\n .filter(isPlainObject)\n .map(SessionTrace.fromApi),\n });\n }\n}\n\nexport type LoadSessionOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\n/**\n * Load a full session (all traces + observations, untruncated IO).\n *\n * Credentials default to the same environment variables the tracing\n * exporter uses: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.\n */\nexport async function loadSession(\n sessionId: string,\n options: LoadSessionOptions = {},\n): Promise<SessionRecording> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, GATEWAY_PUBLIC_KEY \" +\n \"and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey).\",\n );\n }\n\n const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: basicAuthHeader(publicKey, secretKey) },\n signal: AbortSignal.timeout(timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (response.status === 404) {\n throw new SessionLoadError(`Session not found: ${sessionId}`);\n }\n const text = await response.text();\n if (!response.ok) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: response is not valid JSON`,\n { cause: error },\n );\n }\n return SessionRecording.fromApi(\n isPlainObject(payload) ? payload : {},\n );\n}\n\nexport function basicAuthHeader(publicKey: string, secretKey: string): string {\n return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\")}`;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport const sessions = {\n load: loadSession,\n};\n","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by an agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve,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