Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

add sdk for harness (#10)

pranjaltrvd5fa6c1e60251
diff --git a/.github/workflows/generate-sdk.yaml b/.github/workflows/generate-sdk.yaml
new file mode 100644
index 000000000..35b7a0825
--- /dev/null
+++ b/.github/workflows/generate-sdk.yaml
@@ -0,0 +1,138 @@
+name: Generate SDK
+
+# Regenerates the OpenAPI document and the SDK, and commits both to the branch.
+on:
+ push:
+ branches: [main]
+ # Only sources the document is built from; tests and metadata cannot change it.
+ paths:
+ - 'packages/server/src/**'
+ - 'packages/server/scripts/**'
+ - 'packages/harness/src/**'
+ - 'fern/**'
+ - '.github/workflows/generate-sdk.yaml'
+ pull_request:
+ types: [opened, synchronize, reopened]
+ paths:
+ - 'packages/server/src/**'
+ - 'packages/server/scripts/**'
+ - 'packages/harness/src/**'
+ - 'fern/**'
+ - '.github/workflows/generate-sdk.yaml'
+
+concurrency:
+ group: generate-sdk-${{ github.head_ref || github.ref_name }}
+ cancel-in-progress: true
+
+jobs:
+ generate:
+ name: Generate OpenAPI and TypeScript SDK
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ # A pull_request path filter matches the whole PR, not just the new commit,
+ # so this job's own commits would otherwise retrigger it indefinitely.
+ if: github.actor != 'github-actions[bot]'
+ permissions:
+ contents: write
+
+ steps:
+ # Branch tip, not the merge commit, so output can be pushed back; forks need the head repo named.
+ - name: Check out repository code
+ uses: actions/checkout@v4
+ with:
+ repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
+ ref: ${{ github.head_ref || github.ref_name }}
+ # Full history, so the gate below can diff against the base commit.
+ fetch-depth: 0
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@v4
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: '24'
+ cache: 'pnpm'
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ # The spec script imports @truefoundry/utils from its build output.
+ - name: Build utils
+ run: pnpm --filter @truefoundry/utils build
+
+ - name: Write OpenAPI document
+ run: pnpm --filter @truefoundry/server openapi:write
+
+ # Generation and its Docker pull are the slow part, so skip everything below
+ # when neither the document nor the generator config moved.
+ - name: Decide whether the SDK needs regenerating
+ id: decide
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
+ run: |
+ set -euo pipefail
+
+ reason=""
+ if [ -n "$(git status --porcelain -- fern/openapi/openapi.json)" ]; then
+ reason="the OpenAPI document changed"
+ elif ! git rev-parse --verify --quiet "${BASE_SHA}^{commit}" >/dev/null; then
+ # A branch's first push reports an all-zero base commit.
+ reason="there is no base commit to compare against"
+ elif ! git diff --quiet "$BASE_SHA" HEAD -- fern/generators.yml fern/fern.config.json; then
+ reason="the generator config changed"
+ fi
+
+ if [ -n "$reason" ]; then
+ echo "Regenerating: $reason."
+ echo "needed=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "Skipping: the OpenAPI document and generator config are unchanged."
+ echo "needed=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ # Pinned in one place so CI and local runs agree; upgrades are manual edits.
+ - name: Install Fern
+ if: steps.decide.outputs.needed == 'true'
+ run: npm install -g "fern-api@$(jq -r .version fern/fern.config.json)"
+
+ - name: Check API is valid
+ if: steps.decide.outputs.needed == 'true'
+ run: fern check
+
+ # `--generate-tests` is the only thing that makes Fern emit a full package rather than loose sources.
+ - name: Generate TypeScript SDK
+ if: steps.decide.outputs.needed == 'true'
+ run: fern generate --group ts-sdk --version 0.0.0 --local --generate-tests --log-level debug
+
+ # Fern generates no CI for this output mode, so this is what proves the SDK compiles.
+ - name: Verify the generated SDK builds
+ if: steps.decide.outputs.needed == 'true'
+ working-directory: packages/sdk
+ run: bash .fern/verify.sh
+
+ # Forks get a read-only token, so only the commit is skipped. TODO: an approval flow that can push to the fork.
+ - name: Commit generated output
+ if: steps.decide.outputs.needed == 'true' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)
+ # Passed as env, never interpolated into the script, so it cannot inject shell.
+ env:
+ BRANCH: ${{ github.head_ref || github.ref_name }}
+ run: |
+ set -euo pipefail
+
+ # --porcelain, not `git diff`, so new files count too.
+ if [ -z "$(git status --porcelain -- fern/openapi packages/sdk)" ]; then
+ echo "OpenAPI document and SDK are already up to date."
+ exit 0
+ fi
+
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git add fern/openapi packages/sdk
+ git commit -m "Regenerate OpenAPI document and TypeScript SDK"
+ git push origin "HEAD:refs/heads/$BRANCH"
+
+ - name: Report skipped commit on fork
+ if: steps.decide.outputs.needed == 'true' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
+ run: |
+ echo "::notice::Generation succeeded. The commit was skipped because pull requests from forks cannot push; a maintainer will regenerate after merge."
diff --git a/.prettierignore b/.prettierignore
index 0bcce075f..4dc4f1bd7 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -1,5 +1,8 @@
node_modules/
dist/
+# Fern-generated: formatted by the generator, not by this repo's config.
+packages/sdk/
+fern/openapi/
coverage/
.turbo/
pnpm-lock.yaml
diff --git a/README.md b/README.md
index ee653d2e0..60f928c80 100644
--- a/README.md
+++ b/README.md
@@ -63,6 +63,18 @@ Starts Postgres 17 (data in `./data/postgres`), the API, and the frontend. The s
The local `.env` file, `packages/server/registry/`, and `data/` are ignored by Git. Docker Compose requires `packages/server/.env` and mounts the registry read-only into the server container.
+## SDK generation
+
+`packages/sdk` and `fern/openapi/openapi.json` are both generated by
+[Fern](https://buildwithfern.com) and committed — edit `packages/server/src/routes/`, never the
+output. [`generate-sdk.yaml`](.github/workflows/generate-sdk.yaml) regenerates them on every change;
+see its comments for the flags if you need to run it by hand (Docker required):
+
+```bash
+pnpm openapi:write
+fern check && fern generate --group ts-sdk --version 0.0.0 --local --generate-tests
+```
+
## Library imports
```ts
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 9af08830c..da7422aca 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -50,6 +50,8 @@ export default defineConfig(
'**/.eslintcache',
// Excluded from package tsconfigs; run via tsx/jest, not the type-aware ESLint project.
'**/*.test.ts',
+ // Fern-generated SDK: not part of any tsconfig project, and not ours to lint.
+ 'packages/sdk/**',
],
},
{
diff --git a/fern/.gitignore b/fern/.gitignore
new file mode 100644
index 000000000..a56da8355
--- /dev/null
+++ b/fern/.gitignore
@@ -0,0 +1,2 @@
+**/.definition
+**/.preview
diff --git a/fern/fern.config.json b/fern/fern.config.json
new file mode 100644
index 000000000..14e880ebf
--- /dev/null
+++ b/fern/fern.config.json
@@ -0,0 +1,4 @@
+{
+ "organization": "truefoundry",
+ "version": "5.82.0"
+}
diff --git a/fern/generators.yml b/fern/generators.yml
new file mode 100644
index 000000000..ce3b3c532
--- /dev/null
+++ b/fern/generators.yml
@@ -0,0 +1,64 @@
+# yaml-language-server: $schema=https://schema.buildwithfern.dev/generators-yml.json
+#
+# openapi/openapi.json is committed by `pnpm openapi:write`, so Fern never needs the server.
+readme:
+ introduction: >
+ TypeScript client for the TrueFoundry agent harness server: a self-hosted
+ runtime that executes agent turns and streams them over Server-Sent Events.
+
+
+ The harness server has no built-in authentication, so point the client at
+ your own deployment's base URL.
+ # Fern keys this lookup on the stream flag, so the string form misses and fails.
+ defaultEndpoint:
+ method: POST
+ path: /v1/sessions/{sessionId}/turns
+ stream: true
+api:
+ specs:
+ - openapi: openapi/openapi.json
+ settings:
+ title-as-schema-name: false
+ prefer-undiscriminated-unions-with-literals: true
+ only-include-referenced-schemas: true
+ type-dates-as-strings: true
+ object-query-parameters: false
+ idiomatic-request-names: true
+ respect-nullable-schemas: true
+ wrap-references-to-nullable-in-optional: false
+ coerce-optional-schemas-to-nullable: false
+ inline-path-parameters: false
+ coerce-enums-to-literals: true
+ respect-forward-compatible-enums: true
+groups:
+ # `local-file-system` allows no `github` block, so the workflow commits the result itself.
+ ts-sdk:
+ generators:
+ - name: fernapi/fern-typescript-node-sdk
+ version: 3.85.0
+ output:
+ location: local-file-system
+ path: ../packages/sdk
+ config:
+ # TODO: settle the public name before the first publish.
+ packageJson:
+ name: trueharness
+ allowExtraFields: true
+ allowCustomFetcher: true
+ enableInlineTypes: false
+ fetchSupport: native
+ fileResponseType: binary-response
+ formDataSupport: Node18
+ includeApiReference: true
+ inlineFileProperties: true
+ inlinePathParameters: true
+ naming:
+ namespace: TrueHarness
+ client: TrueHarness
+ noSerdeLayer: false
+ omitUndefined: true
+ retainOriginalCasing: false
+ skipResponseValidation: true
+ streamType: web
+ useDefaultRequestParameterValues: true
+ smart-casing: true
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.json
new file mode 100644
index 000000000..52d3e7527
--- /dev/null
+++ b/fern/openapi/openapi.json
@@ -0,0 +1,3374 @@
+{
+ "components": {
+ "parameters": {},
+ "schemas": {
+ "ActionRequiredEvent": {
+ "discriminator": {
+ "mapping": {
+ "mcp.auth_required": "#/components/schemas/MCPAuthRequiredEvent",
+ "tool.approval_required": "#/components/schemas/ToolApprovalRequiredEvent",
+ "tool.response_required": "#/components/schemas/ToolResponseRequiredEvent"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ToolApprovalRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolResponseRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/MCPAuthRequiredEvent"
+ }
+ ]
+ },
+ "AgentInfo": {
+ "properties": {
+ "input": {
+ "type": "string"
+ },
+ "model": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "dynamic"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name",
+ "input"
+ ],
+ "type": "object"
+ },
+ "AgentParent": {
+ "properties": {
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_call_id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "thread_id",
+ "tool_call_id"
+ ],
+ "type": "object"
+ },
+ "AgentSpec": {
+ "description": "Agent Definition",
+ "properties": {
+ "config": {
+ "$ref": "#/components/schemas/RuntimeConfig"
+ },
+ "instructions": {
+ "type": "string"
+ },
+ "mcp_servers": {
+ "items": {
+ "$ref": "#/components/schemas/MCPServer"
+ },
+ "type": "array"
+ },
+ "messages": {
+ "items": {
+ "$ref": "#/components/schemas/AgentSpecUserMessage"
+ },
+ "type": "array"
+ },
+ "model": {
+ "$ref": "#/components/schemas/Model"
+ },
+ "response_format": {
+ "$ref": "#/components/schemas/ResponseFormat"
+ },
+ "skills": {
+ "items": {
+ "$ref": "#/components/schemas/SkillMount"
+ },
+ "type": "array"
+ },
+ "variables": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ }
+ },
+ "required": [
+ "model"
+ ],
+ "type": "object"
+ },
+ "AgentSpecUserMessage": {
+ "properties": {
+ "content": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "user.message"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "content"
+ ],
+ "type": "object"
+ },
+ "ApprovalAllow": {
+ "properties": {
+ "status": {
+ "enum": [
+ "allow"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "ApprovalDecision": {
+ "discriminator": {
+ "mapping": {
+ "allow": "#/components/schemas/ApprovalAllow",
+ "deny": "#/components/schemas/ApprovalDeny"
+ },
+ "propertyName": "status"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ApprovalAllow"
+ },
+ {
+ "$ref": "#/components/schemas/ApprovalDeny"
+ }
+ ]
+ },
+ "ApprovalDeny": {
+ "properties": {
+ "reason": {
+ "type": "string"
+ },
+ "status": {
+ "enum": [
+ "deny"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "AskUserQuestionsConfig": {
+ "properties": {
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "BaseMCPAuthRequiredEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "thread_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "created_at",
+ "thread_id"
+ ],
+ "type": "object"
+ },
+ "BaseThreadDoneEvent": {
+ "properties": {
+ "parent": {
+ "$ref": "#/components/schemas/AgentParent"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "thread_id",
+ "title"
+ ],
+ "type": "object"
+ },
+ "CancelSessionRequest": {
+ "properties": {},
+ "type": "object"
+ },
+ "CancelSessionResponse": {
+ "properties": {},
+ "type": "object"
+ },
+ "ChatCompletionChunkDeltaToolCall": {
+ "properties": {
+ "function": {
+ "properties": {
+ "arguments": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "index": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "type": {
+ "enum": [
+ "function"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "index"
+ ],
+ "type": "object"
+ },
+ "ChatCompletionContentPartRefusal": {
+ "properties": {
+ "refusal": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "refusal"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "refusal"
+ ],
+ "type": "object"
+ },
+ "ChatCompletionContentPartText": {
+ "properties": {
+ "text": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "text"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "text"
+ ],
+ "type": "object"
+ },
+ "ChatCompletionMessageToolCall": {
+ "properties": {
+ "function": {
+ "properties": {
+ "arguments": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "arguments"
+ ],
+ "type": "object"
+ },
+ "id": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "function"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "type",
+ "function"
+ ],
+ "type": "object"
+ },
+ "ContextManagementConfig": {
+ "default": {
+ "compaction": {
+ "enabled": true
+ },
+ "large_tool_response": {
+ "enabled": true
+ }
+ },
+ "properties": {
+ "compaction": {
+ "default": {
+ "enabled": true
+ },
+ "properties": {
+ "compaction_threshold_tokens": {
+ "default": 50000,
+ "exclusiveMinimum": 0,
+ "type": "integer"
+ },
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "large_tool_response": {
+ "$ref": "#/components/schemas/LargeToolResponseConfig"
+ }
+ },
+ "type": "object"
+ },
+ "CreateSessionRequest": {
+ "properties": {
+ "agent_spec": {
+ "$ref": "#/components/schemas/AgentSpec"
+ }
+ },
+ "required": [
+ "agent_spec"
+ ],
+ "type": "object"
+ },
+ "CreateTurnRequest": {
+ "properties": {
+ "input": {
+ "items": {
+ "$ref": "#/components/schemas/TurnInputItem"
+ },
+ "type": "array"
+ },
+ "previous_turn_id": {
+ "$ref": "#/components/schemas/PreviousTurnIdInput"
+ }
+ },
+ "type": "object"
+ },
+ "DynamicSubAgentsConfig": {
+ "properties": {
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "ExtendedChunkDeltaToolCall": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ChatCompletionChunkDeltaToolCall"
+ },
+ {
+ "properties": {
+ "provider_specific_fields": {
+ "additionalProperties": {},
+ "type": "object"
+ },
+ "tool_info": {
+ "$ref": "#/components/schemas/ToolInfo"
+ }
+ },
+ "type": "object"
+ }
+ ]
+ },
+ "FileContent": {
+ "properties": {
+ "data": {
+ "description": "Data URI: `data:<mime>;base64,<payload>`. MIME type is parsed from the URI.",
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "file"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name",
+ "data"
+ ],
+ "type": "object"
+ },
+ "FinishReason": {
+ "enum": [
+ "stop",
+ "length",
+ "tool_calls",
+ "content_filter",
+ "function_call"
+ ],
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "GenerativeUIConfig": {
+ "properties": {
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "GetCapabilitiesResponse": {
+ "properties": {
+ "data": {
+ "properties": {
+ "sandbox": {
+ "properties": {
+ "enabled": {
+ "description": "Whether this server has a sandbox provider configured.",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "enabled"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "sandbox"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "GetSessionResponse": {
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/Session"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "GetTurnResponse": {
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/Turn"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "LargeToolResponseConfig": {
+ "default": {
+ "enabled": true
+ },
+ "properties": {
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
+ "ListMcpServersResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/McpServerEntry"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "ListMcpToolsResponse": {
+ "properties": {
+ "data": {
+ "description": "MCP `tools/list` entries, passed through verbatim from the MCP server.",
+ "items": {
+ "additionalProperties": {},
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "ListModelsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/ModelEntry"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "ListSessionEventsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/SessionEventItem"
+ },
+ "type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
+ }
+ },
+ "required": [
+ "data",
+ "pagination"
+ ],
+ "type": "object"
+ },
+ "ListSessionsOrder": {
+ "default": "desc",
+ "description": "Sort sessions by creation time. Defaults to \"desc\".",
+ "enum": [
+ "asc",
+ "desc"
+ ],
+ "type": "string"
+ },
+ "ListSessionsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/Session"
+ },
+ "type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
+ }
+ },
+ "required": [
+ "data",
+ "pagination"
+ ],
+ "type": "object"
+ },
+ "ListSkillsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/SkillEntry"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
+ "ListTurnEventsOrder": {
+ "default": "asc",
+ "description": "Sort events by insertion order. Defaults to \"asc\".",
+ "enum": [
+ "asc",
+ "desc"
+ ],
+ "type": "string"
+ },
+ "ListTurnEventsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/SessionEvent"
+ },
+ "type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
+ }
+ },
+ "required": [
+ "data",
+ "pagination"
+ ],
+ "type": "object"
+ },
+ "ListTurnsResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/Turn"
+ },
+ "type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
+ }
+ },
+ "required": [
+ "data",
+ "pagination"
+ ],
+ "type": "object"
+ },
+ "MCPAuthRequiredEvent": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/BaseMCPAuthRequiredEvent"
+ },
+ {
+ "properties": {
+ "mcp_servers": {
+ "items": {
+ "$ref": "#/components/schemas/MCPServerAuthInfo"
+ },
+ "type": "array"
+ },
+ "type": {
+ "enum": [
+ "mcp.auth_required"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "mcp_servers"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "MCPInitializeEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "mcp_servers": {
+ "items": {
+ "$ref": "#/components/schemas/MCPServerInitInfo"
+ },
+ "type": "array"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "mcp.initialize"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "created_at",
+ "thread_id",
+ "mcp_servers"
+ ],
+ "type": "object"
+ },
+ "MCPServer": {
+ "properties": {
+ "disable_tools": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "enum": [
+ "@all",
+ "@read-only"
+ ],
+ "type": "string"
+ },
+ {
+ "minLength": 1,
+ "type": "string"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "enable_tools": {
+ "default": [
+ "@all"
+ ],
+ "items": {
+ "anyOf": [
+ {
+ "enum": [
+ "@all",
+ "@read-only"
+ ],
+ "type": "string"
+ },
+ {
+ "minLength": 1,
+ "type": "string"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "preload": {
+ "default": false,
+ "type": "boolean"
+ },
+ "preload_tools": {
+ "default": [],
+ "items": {
+ "anyOf": [
+ {
+ "enum": [
+ "@all",
+ "@read-only"
+ ],
+ "type": "string"
+ },
+ {
+ "minLength": 1,
+ "type": "string"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ "require_approval_for_tools": {
+ "default": [
+ "@write",
+ "@destructive"
+ ],
+ "items": {
+ "anyOf": [
+ {
+ "enum": [
+ "@all",
+ "@write",
+ "@destructive"
+ ],
+ "type": "string"
+ },
+ {
+ "minLength": 1,
+ "type": "string"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "MCPServerAuthInfo": {
+ "properties": {
+ "auth_url": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "name",
+ "auth_url"
+ ],
+ "type": "object"
+ },
+ "MCPServerInitInfo": {
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "session_id": {
+ "type": "string"
+ },
+ "transport_type": {
+ "enum": [
+ "streamable-http",
+ "sse"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "name"
+ ],
+ "type": "object"
+ },
+ "MCPToolInfo": {
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "server_id": {
+ "type": "string"
+ },
+ "server_name": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "mcp"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "server_id",
+ "server_name",
+ "name"
+ ],
+ "type": "object"
+ },
+ "McpServerEntry": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "url"
+ ],
+ "type": "object"
+ },
+ "Model": {
+ "properties": {
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "params": {
+ "$ref": "#/components/schemas/ModelParams"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "ModelEntry": {
+ "additionalProperties": false,
+ "properties": {
+ "max_output_tokens": {
+ "exclusiveMinimum": 0,
+ "type": "integer"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "reasoning_efforts": {
+ "items": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": [
+ "name",
+ "max_output_tokens"
+ ],
+ "type": "object"
+ },
+ "ModelMessageDeltaEvent": {
+ "properties": {
+ "content": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "finish_reason": {
+ "$ref": "#/components/schemas/FinishReason"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "reasoning_content": {
+ "type": "string"
+ },
+ "refusal": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_calls": {
+ "items": {
+ "$ref": "#/components/schemas/ExtendedChunkDeltaToolCall"
+ },
+ "type": "array"
+ },
+ "type": {
+ "enum": [
+ "model.message.delta"
+ ],
+ "type": "string"
+ },
+ "usage": {
+ "$ref": "#/components/schemas/ModelMessageUsage"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "thread_id"
+ ],
+ "type": "object"
+ },
+ "ModelMessageEvent": {
+ "properties": {
+ "content": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/ChatCompletionContentPartText"
+ },
+ {
+ "$ref": "#/components/schemas/ChatCompletionContentPartRefusal"
+ }
+ ]
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "finish_reason": {
+ "$ref": "#/components/schemas/FinishReason"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "reasoning_content": {
+ "type": "string"
+ },
+ "refusal": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_calls": {
+ "items": {
+ "$ref": "#/components/schemas/ToolCall"
+ },
+ "type": "array"
+ },
+ "type": {
+ "enum": [
+ "model.message"
+ ],
+ "type": "string"
+ },
+ "usage": {
+ "$ref": "#/components/schemas/ModelMessageUsage"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "thread_id",
+ "created_at"
+ ],
+ "type": "object"
+ },
+ "ModelMessageUsage": {
+ "properties": {
+ "cache_read_tokens": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "cache_write_tokens": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "input_tokens": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "input_tokens_breakdown": {
+ "properties": {
+ "harness": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "instructions": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "messages": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "skills": {
+ "minimum": 0,
+ "type": "integer"
+ },
+ "tool_definitions": {
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "harness",
+ "skills",
+ "instructions",
+ "tool_definitions",
+ "messages"
+ ],
+ "type": "object"
+ },
+ "output_tokens": {
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "input_tokens",
+ "output_tokens",
+ "input_tokens_breakdown"
+ ],
+ "type": "object"
+ },
+ "ModelParams": {
+ "properties": {
+ "max_tokens": {
+ "type": "number"
+ },
+ "parallel_tool_calls": {
+ "type": "boolean"
+ },
+ "reasoning_effort": {
+ "type": "string"
+ },
+ "temperature": {
+ "type": "number"
+ },
+ "top_k": {
+ "type": "number"
+ },
+ "top_p": {
+ "type": "number"
+ }
+ },
+ "type": "object"
+ },
+ "PreviousTurnIdInput": {
+ "anyOf": [
+ {
+ "enum": [
+ "auto"
+ ],
+ "type": "string"
+ },
+ {
+ "minLength": 1,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": "auto",
+ "description": "Defaults to 'auto' (chain to session last turn). Use 'null' for the session's first turn."
+ },
+ "RawToolCall": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ChatCompletionMessageToolCall"
+ },
+ {
+ "properties": {
+ "provider_specific_fields": {
+ "additionalProperties": {},
+ "type": "object"
+ }
+ },
+ "type": "object"
+ }
+ ]
+ },
+ "RequestErrorResponse": {
+ "properties": {
+ "error": {
+ "properties": {
+ "code": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "message": {
+ "type": "string"
+ },
+ "param": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "message"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "error"
+ ],
+ "type": "object"
+ },
+ "ResponseFormat": {
+ "oneOf": [
+ {
+ "properties": {
+ "type": {
+ "enum": [
+ "text"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "enum": [
+ "json_object"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "json_schema": {
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "schema": {
+ "additionalProperties": {},
+ "type": "object"
+ },
+ "strict": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "type": "object"
+ },
+ "type": {
+ "enum": [
+ "json_schema"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "json_schema"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "RuntimeConfig": {
+ "properties": {
+ "ask_user_questions": {
+ "$ref": "#/components/schemas/AskUserQuestionsConfig"
+ },
+ "context_management": {
+ "$ref": "#/components/schemas/ContextManagementConfig"
+ },
+ "dynamic_sub_agents": {
+ "$ref": "#/components/schemas/DynamicSubAgentsConfig"
+ },
+ "generative_ui": {
+ "$ref": "#/components/schemas/GenerativeUIConfig"
+ },
+ "iteration_limit": {
+ "default": 100,
+ "exclusiveMinimum": 0,
+ "maximum": 1024,
+ "type": "integer"
+ },
+ "sandbox": {
+ "$ref": "#/components/schemas/SandboxConfig"
+ }
+ },
+ "type": "object"
+ },
+ "SandboxConfig": {
+ "properties": {
+ "enabled": {
+ "type": "boolean"
+ },
+ "file_downloads": {
+ "default": true,
+ "type": "boolean"
+ },
+ "network_policy": {
+ "$ref": "#/components/schemas/SandboxNetworkPolicy"
+ }
+ },
+ "required": [
+ "enabled"
+ ],
+ "type": "object"
+ },
+ "SandboxCreatedEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "sandbox_id": {
+ "type": "string"
+ },
+ "thread_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "enum": [
+ "sandbox.created"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "created_at",
+ "sandbox_id",
+ "thread_id"
+ ],
+ "type": "object"
+ },
+ "SandboxNetworkPolicy": {
+ "properties": {
+ "auth_inject": {
+ "items": {
+ "properties": {
+ "auth_data": {
+ "properties": {
+ "password": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "basic"
+ ],
+ "type": "string"
+ },
+ "username": {
+ "pattern": "^\\S+$",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "username",
+ "password"
+ ],
+ "type": "object"
+ },
+ "match": {
+ "properties": {
+ "hosts": {
+ "items": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": [
+ "hosts"
+ ],
+ "type": "object"
+ },
+ "type": {
+ "enum": [
+ "git"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "match",
+ "auth_data"
+ ],
+ "type": "object"
+ },
+ "maxItems": 1,
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "Session": {
+ "properties": {
+ "agent_spec": {
+ "$ref": "#/components/schemas/AgentSpec"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "updated_at": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "agent_spec",
+ "title",
+ "created_at",
+ "updated_at"
+ ],
+ "type": "object"
+ },
+ "SessionEvent": {
+ "discriminator": {
+ "mapping": {
+ "mcp.auth_required": "#/components/schemas/MCPAuthRequiredEvent",
+ "mcp.initialize": "#/components/schemas/MCPInitializeEvent",
+ "model.message": "#/components/schemas/ModelMessageEvent",
+ "sandbox.created": "#/components/schemas/SandboxCreatedEvent",
+ "thread.created": "#/components/schemas/ThreadCreatedEvent",
+ "thread.done": "#/components/schemas/ThreadDoneEvent",
+ "tool.approval_required": "#/components/schemas/ToolApprovalRequiredEvent",
+ "tool.response": "#/components/schemas/ToolResponseEvent",
+ "tool.response_required": "#/components/schemas/ToolResponseRequiredEvent",
+ "turn.created": "#/components/schemas/TurnCreatedEvent",
+ "turn.done": "#/components/schemas/TurnDoneEvent"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/TurnCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/TurnDoneEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ModelMessageEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolResponseEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadDoneEvent"
+ },
+ {
+ "$ref": "#/components/schemas/MCPAuthRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/MCPInitializeEvent"
+ },
+ {
+ "$ref": "#/components/schemas/SandboxCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolApprovalRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolResponseRequiredEvent"
+ }
+ ]
+ },
+ "SessionEventItem": {
+ "properties": {
+ "event": {
+ "$ref": "#/components/schemas/SessionEvent"
+ },
+ "turn_id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "turn_id",
+ "event"
+ ],
+ "type": "object"
+ },
+ "SkillEntry": {
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "name": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "path": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "ref": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "url": {
+ "format": "uri",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "url",
+ "description"
+ ],
+ "type": "object"
+ },
+ "SkillMount": {
+ "properties": {
+ "description": {
+ "description": "Concise guidance for when the agent should use the skill.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "name": {
+ "description": "Name for the skill, used as directory name in sandbox.",
+ "maxLength": 64,
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9._-]+$",
+ "type": "string"
+ },
+ "path": {
+ "description": "Path to the skill directory within the repository. Omit to use the repository root.",
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9._\\-/]+$",
+ "type": "string"
+ },
+ "ref": {
+ "description": "Git ref — branch name, tag, or commit SHA.",
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9._\\-/]+$",
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "git"
+ ],
+ "type": "string"
+ },
+ "url": {
+ "description": "Full HTTPS URL of a GitHub or GitLab repository.",
+ "minLength": 1,
+ "pattern": "^https:\\/\\/(github\\.com\\/[A-Za-z0-9._-]+\\/[A-Za-z0-9._-]+|gitlab\\.com\\/[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+)(\\/|\\.git)?$",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "url",
+ "name",
+ "description",
+ "ref"
+ ],
+ "type": "object"
+ },
+ "TextContent": {
+ "properties": {
+ "text": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "text"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "text"
+ ],
+ "type": "object"
+ },
+ "ThreadCreatedEvent": {
+ "properties": {
+ "agent_info": {
+ "$ref": "#/components/schemas/AgentInfo"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "parent": {
+ "$ref": "#/components/schemas/AgentParent"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "thread.created"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "agent_info",
+ "created_at",
+ "parent",
+ "thread_id",
+ "title"
+ ],
+ "type": "object"
+ },
+ "ThreadDoneEvent": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/BaseThreadDoneEvent"
+ },
+ {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "state": {
+ "$ref": "#/components/schemas/ThreadState"
+ },
+ "type": {
+ "enum": [
+ "thread.done"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "created_at",
+ "state"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "ThreadState": {
+ "discriminator": {
+ "mapping": {
+ "done": "#/components/schemas/ThreadStateDone",
+ "error": "#/components/schemas/ThreadStateError"
+ },
+ "propertyName": "status"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ThreadStateDone"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadStateError"
+ }
+ ]
+ },
+ "ThreadStateDone": {
+ "properties": {
+ "output": {
+ "$ref": "#/components/schemas/ModelMessageEvent"
+ },
+ "status": {
+ "enum": [
+ "done"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "output"
+ ],
+ "type": "object"
+ },
+ "ThreadStateError": {
+ "properties": {
+ "error": {
+ "type": "string"
+ },
+ "output": {
+ "$ref": "#/components/schemas/ModelMessageEvent"
+ },
+ "status": {
+ "enum": [
+ "error"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "error"
+ ],
+ "type": "object"
+ },
+ "TokenPagination": {
+ "properties": {
+ "limit": {
+ "exclusiveMinimum": 0,
+ "type": "integer"
+ },
+ "next_page_token": {
+ "type": "string"
+ },
+ "previous_page_token": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "limit"
+ ],
+ "type": "object"
+ },
+ "ToolApprovalRequiredEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_calls": {
+ "items": {
+ "$ref": "#/components/schemas/ToolCallRef"
+ },
+ "type": "array"
+ },
+ "type": {
+ "enum": [
+ "tool.approval_required"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "created_at",
+ "thread_id",
+ "tool_calls"
+ ],
+ "type": "object"
+ },
+ "ToolCall": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RawToolCall"
+ },
+ {
+ "properties": {
+ "tool_info": {
+ "$ref": "#/components/schemas/ToolInfo"
+ }
+ },
+ "required": [
+ "tool_info"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ "ToolCallRef": {
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "source_event_id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "source_event_id"
+ ],
+ "type": "object"
+ },
+ "ToolInfo": {
+ "discriminator": {
+ "mapping": {
+ "mcp": "#/components/schemas/MCPToolInfo",
+ "truefoundry-system": "#/components/schemas/TrueFoundrySystemToolInfo"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/TrueFoundrySystemToolInfo"
+ },
+ {
+ "$ref": "#/components/schemas/MCPToolInfo"
+ }
+ ]
+ },
+ "ToolResponseEvent": {
+ "properties": {
+ "content": {
+ "type": "string"
+ },
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_call_id": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "tool.response"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool_call_id",
+ "content",
+ "type",
+ "id",
+ "thread_id",
+ "created_at"
+ ],
+ "type": "object"
+ },
+ "ToolResponseRequiredEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "thread_id": {
+ "type": "string"
+ },
+ "tool_calls": {
+ "items": {
+ "$ref": "#/components/schemas/ToolCallRef"
+ },
+ "type": "array"
+ },
+ "type": {
+ "enum": [
+ "tool.response_required"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "created_at",
+ "thread_id",
+ "tool_calls"
+ ],
+ "type": "object"
+ },
+ "TrueFoundrySystemToolInfo": {
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "truefoundry-system"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "name"
+ ],
+ "type": "object"
+ },
+ "Turn": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "input": {
+ "items": {
+ "$ref": "#/components/schemas/TurnInputItem"
+ },
+ "type": "array"
+ },
+ "previous_turn_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "session_id": {
+ "type": "string"
+ },
+ "state": {
+ "$ref": "#/components/schemas/TurnState"
+ }
+ },
+ "required": [
+ "id",
+ "session_id",
+ "previous_turn_id",
+ "state",
+ "created_at"
+ ],
+ "type": "object"
+ },
+ "TurnCreatedEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "input": {
+ "items": {
+ "$ref": "#/components/schemas/TurnInputItem"
+ },
+ "type": "array"
+ },
+ "previous_turn_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "state": {
+ "$ref": "#/components/schemas/TurnStateRunning"
+ },
+ "thread_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "turn_id": {
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "turn.created"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "turn_id",
+ "previous_turn_id",
+ "state",
+ "created_at",
+ "thread_id"
+ ],
+ "type": "object"
+ },
+ "TurnDoneEvent": {
+ "properties": {
+ "created_at": {
+ "type": "string"
+ },
+ "id": {
+ "description": "Unique identifier for the event",
+ "type": "string"
+ },
+ "state": {
+ "discriminator": {
+ "mapping": {
+ "cancelled": "#/components/schemas/TurnStateCancelled",
+ "done": "#/components/schemas/TurnStateDone",
+ "error": "#/components/schemas/TurnStateError"
+ },
+ "propertyName": "status"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/TurnStateDone"
+ },
+ {
+ "$ref": "#/components/schemas/TurnStateCancelled"
+ },
+ {
+ "$ref": "#/components/schemas/TurnStateError"
+ }
+ ]
+ },
+ "thread_id": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {
+ "enum": [
+ "turn.done"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "state",
+ "created_at",
+ "thread_id"
+ ],
+ "type": "object"
+ },
+ "TurnInputItem": {
+ "discriminator": {
+ "mapping": {
+ "user.message": "#/components/schemas/UserMessage",
+ "user.tool_approval": "#/components/schemas/UserToolApprovalEvent",
+ "user.tool_response": "#/components/schemas/UserToolResponseEvent"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/UserMessage"
+ },
+ {
+ "$ref": "#/components/schemas/UserToolApprovalEvent"
+ },
+ {
+ "$ref": "#/components/schemas/UserToolResponseEvent"
+ }
+ ]
+ },
+ "TurnState": {
+ "discriminator": {
+ "mapping": {
+ "cancelled": "#/components/schemas/TurnStateCancelled",
+ "done": "#/components/schemas/TurnStateDone",
+ "error": "#/components/schemas/TurnStateError",
+ "running": "#/components/schemas/TurnStateRunning"
+ },
+ "propertyName": "status"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/TurnStateRunning"
+ },
+ {
+ "$ref": "#/components/schemas/TurnStateDone"
+ },
+ {
+ "$ref": "#/components/schemas/TurnStateCancelled"
+ },
+ {
+ "$ref": "#/components/schemas/TurnStateError"
+ }
+ ]
+ },
+ "TurnStateCancelled": {
+ "properties": {
+ "completed_at": {
+ "type": "string"
+ },
+ "reason": {
+ "$ref": "#/components/schemas/TurnStateCancelledReason"
+ },
+ "status": {
+ "enum": [
+ "cancelled"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "reason",
+ "completed_at"
+ ],
+ "type": "object"
+ },
+ "TurnStateCancelledReason": {
+ "description": "Reason for the cancellation.",
+ "enum": [
+ "server-execution-timeout",
+ "client-cancelled",
+ "cancelled-for-next-turn",
+ "abandoned"
+ ],
+ "type": "string"
+ },
+ "TurnStateDone": {
+ "properties": {
+ "completed_at": {
+ "type": "string"
+ },
+ "output": {
+ "$ref": "#/components/schemas/ModelMessageEvent"
+ },
+ "required_actions": {
+ "items": {
+ "$ref": "#/components/schemas/ActionRequiredEvent"
+ },
+ "type": "array"
+ },
+ "status": {
+ "enum": [
+ "done"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "required_actions",
+ "completed_at"
+ ],
+ "type": "object"
+ },
+ "TurnStateError": {
+ "properties": {
+ "completed_at": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "status": {
+ "enum": [
+ "error"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "message",
+ "completed_at"
+ ],
+ "type": "object"
+ },
+ "TurnStateRunning": {
+ "properties": {
+ "status": {
+ "enum": [
+ "running"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "TurnStreamingEvent": {
+ "discriminator": {
+ "mapping": {
+ "mcp.auth_required": "#/components/schemas/MCPAuthRequiredEvent",
+ "mcp.initialize": "#/components/schemas/MCPInitializeEvent",
+ "model.message": "#/components/schemas/ModelMessageEvent",
+ "model.message.delta": "#/components/schemas/ModelMessageDeltaEvent",
+ "sandbox.created": "#/components/schemas/SandboxCreatedEvent",
+ "thread.created": "#/components/schemas/ThreadCreatedEvent",
+ "thread.done": "#/components/schemas/ThreadDoneEvent",
+ "tool.approval_required": "#/components/schemas/ToolApprovalRequiredEvent",
+ "tool.response": "#/components/schemas/ToolResponseEvent",
+ "tool.response_required": "#/components/schemas/ToolResponseRequiredEvent",
+ "turn.created": "#/components/schemas/TurnCreatedEvent",
+ "turn.done": "#/components/schemas/TurnDoneEvent"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/ModelMessageEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ModelMessageDeltaEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolResponseEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ThreadDoneEvent"
+ },
+ {
+ "$ref": "#/components/schemas/MCPAuthRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/MCPInitializeEvent"
+ },
+ {
+ "$ref": "#/components/schemas/SandboxCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolApprovalRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/ToolResponseRequiredEvent"
+ },
+ {
+ "$ref": "#/components/schemas/TurnCreatedEvent"
+ },
+ {
+ "$ref": "#/components/schemas/TurnDoneEvent"
+ }
+ ]
+ },
+ "UpdateSessionRequest": {
+ "properties": {
+ "agent_spec": {
+ "$ref": "#/components/schemas/AgentSpec"
+ }
+ },
+ "type": "object"
+ },
+ "UserMessage": {
+ "properties": {
+ "content": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "items": {
+ "$ref": "#/components/schemas/UserMessageContentItem"
+ },
+ "type": "array"
+ }
+ ]
+ },
+ "type": {
+ "enum": [
+ "user.message"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "content"
+ ],
+ "type": "object"
+ },
+ "UserMessageContentItem": {
+ "discriminator": {
+ "mapping": {
+ "file": "#/components/schemas/FileContent",
+ "text": "#/components/schemas/TextContent"
+ },
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/TextContent"
+ },
+ {
+ "$ref": "#/components/schemas/FileContent"
+ }
+ ]
+ },
+ "UserToolApprovalEvent": {
+ "properties": {
+ "approval": {
+ "$ref": "#/components/schemas/ApprovalDecision"
+ },
+ "thread_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "tool_call_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "user.tool_approval"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "thread_id",
+ "tool_call_id",
+ "approval"
+ ],
+ "type": "object"
+ },
+ "UserToolResponseEvent": {
+ "properties": {
+ "content": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "thread_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "tool_call_id": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "user.tool_response"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "thread_id",
+ "tool_call_id",
+ "content"
+ ],
+ "type": "object"
+ }
+ }
+ },
+ "info": {
+ "description": "Agent server exposing models, MCP servers and skills from local YAML config.",
+ "title": "Agent Server",
+ "version": "0.1.0"
+ },
+ "openapi": "3.1.0",
+ "paths": {
+ "/v1/capabilities": {
+ "get": {
+ "description": "Report optional runtime capabilities available in this server deployment.",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetCapabilitiesResponse"
+ }
+ }
+ },
+ "description": "Server capabilities."
+ }
+ },
+ "summary": "Get server capabilities",
+ "tags": [
+ "Capabilities"
+ ],
+ "x-fern-sdk-group-name": [
+ "server"
+ ],
+ "x-fern-sdk-method-name": "get_capabilities"
+ }
+ },
+ "/v1/mcp-servers": {
+ "get": {
+ "description": "MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListMcpServersResponse"
+ }
+ }
+ },
+ "description": "All configured MCP servers."
+ }
+ },
+ "summary": "List MCP servers",
+ "tags": [
+ "MCP Servers"
+ ],
+ "x-fern-sdk-group-name": [
+ "mcp_servers"
+ ],
+ "x-fern-sdk-method-name": "list"
+ }
+ },
+ "/v1/mcp-servers/{name}/tools": {
+ "get": {
+ "description": "All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.",
+ "parameters": [
+ {
+ "description": "MCP server name from mcp.yaml.",
+ "in": "path",
+ "name": "name",
+ "required": true,
+ "schema": {
+ "description": "MCP server name from mcp.yaml.",
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListMcpToolsResponse"
+ }
+ }
+ },
+ "description": "All tools of the MCP server."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The MCP server requires authentication (configure MCP_HEADERS / MCP_{NAME}_HEADERS)."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "MCP server not declared in mcp.yaml."
+ },
+ "502": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The MCP server could not be reached or returned an error."
+ }
+ },
+ "summary": "List tools of an MCP server",
+ "tags": [
+ "MCP Servers"
+ ],
+ "x-fern-sdk-group-name": [
+ "mcp_servers"
+ ],
+ "x-fern-sdk-method-name": "list_tools"
+ }
+ },
+ "/v1/models": {
+ "get": {
+ "description": "Models declared in models.yaml, reachable through the OpenAI-compatible API at the file's base_url.",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListModelsResponse"
+ }
+ }
+ },
+ "description": "All configured models."
+ }
+ },
+ "summary": "List models",
+ "tags": [
+ "Models"
+ ],
+ "x-fern-sdk-group-name": [
+ "models"
+ ],
+ "x-fern-sdk-method-name": "list"
+ }
+ },
+ "/v1/sessions": {
+ "get": {
+ "description": "List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.",
+ "parameters": [
+ {
+ "description": "Page size. Defaults to 10, max 100.",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 10,
+ "description": "Page size. Defaults to 10, max 100.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "description": "Sort sessions by creation time. Defaults to \"desc\".",
+ "in": "query",
+ "name": "order",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ListSessionsOrder"
+ }
+ },
+ {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "in": "query",
+ "name": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Inclusive lower bound on `created_at` (ISO-8601).",
+ "in": "query",
+ "name": "start_timestamp",
+ "required": false,
+ "schema": {
+ "description": "Inclusive lower bound on `created_at` (ISO-8601).",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Inclusive upper bound on `created_at` (ISO-8601).",
+ "in": "query",
+ "name": "end_timestamp",
+ "required": false,
+ "schema": {
+ "description": "Inclusive upper bound on `created_at` (ISO-8601).",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListSessionsResponse"
+ }
+ }
+ },
+ "description": "Paginated sessions."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid query parameters or page token."
+ }
+ },
+ "summary": "List sessions",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "list"
+ },
+ "post": {
+ "description": "Create a session holding an inline agent spec. Turns are executed against this spec.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateSessionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetSessionResponse"
+ }
+ }
+ },
+ "description": "Session created."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid request body."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills)."
+ }
+ },
+ "summary": "Create a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "create"
+ }
+ },
+ "/v1/sessions/{sessionId}": {
+ "get": {
+ "description": "Fetch a session by ID.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetSessionResponse"
+ }
+ }
+ },
+ "description": "Session data."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session not found."
+ }
+ },
+ "summary": "Get a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "get"
+ },
+ "patch": {
+ "description": "Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateSessionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetSessionResponse"
+ }
+ }
+ },
+ "description": "Session updated."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid request body."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session not found."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills)."
+ }
+ },
+ "summary": "Update a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "update"
+ }
+ },
+ "/v1/sessions/{sessionId}/cancel": {
+ "post": {
+ "description": "Cancel the running last turn for a session.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CancelSessionRequest"
+ }
+ }
+ },
+ "required": false
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CancelSessionResponse"
+ }
+ }
+ },
+ "description": "Turn cancelled."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session not found."
+ },
+ "412": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Requested action cannot be performed on the session because it is no longer usable, or the executor owning the running turn is unreachable."
+ }
+ },
+ "summary": "Cancel a running turn in a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "cancel"
+ }
+ },
+ "/v1/sessions/{sessionId}/events": {
+ "get": {
+ "description": "List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Pagination cursor from `pagination.next_page_token`. It retains the branch anchor turn and returns older events toward the session start.",
+ "in": "query",
+ "name": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Pagination cursor from `pagination.next_page_token`. It retains the branch anchor turn and returns older events toward the session start.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn.",
+ "in": "query",
+ "name": "last_turn_id",
+ "required": false,
+ "schema": {
+ "description": "Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Max events per response. Default 100, max 100.",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 100,
+ "description": "Max events per response. Default 100, max 100.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListSessionEventsResponse"
+ }
+ }
+ },
+ "description": "Paginated session events."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid page token."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session not found."
+ }
+ },
+ "summary": "List session events",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "list_events"
+ }
+ },
+ "/v1/sessions/{sessionId}/turns": {
+ "get": {
+ "description": "List turns for a session (newest first by default), token-paginated.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Page size. Defaults to 10, max 100.",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 10,
+ "description": "Page size. Defaults to 10, max 100.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "in": "query",
+ "name": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListTurnsResponse"
+ }
+ }
+ },
+ "description": "Paginated turns."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid page token."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session not found."
+ }
+ },
+ "summary": "List turns in a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "list_turns"
+ },
+ "post": {
+ "description": "Create a turn within a session and stream its execution as Server-Sent Events.\nUse `previous_turn_id` to chain to the session's last turn (defaults to `auto`).",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateTurnRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "text/event-stream": {
+ "schema": {
+ "$ref": "#/components/schemas/TurnStreamingEvent"
+ }
+ }
+ },
+ "description": "Server-Sent Events stream of turn events."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid request body."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session or prior turn not found."
+ },
+ "412": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Requested action cannot be performed on the session because it is no longer usable."
+ }
+ },
+ "summary": "Create and execute a turn in a session",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "create_turn",
+ "x-fern-streaming": {
+ "format": "sse",
+ "resumable": false
+ }
+ }
+ },
+ "/v1/sessions/{sessionId}/turns/{turnId}": {
+ "get": {
+ "description": "Fetch a single turn by ID.",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Turn identifier.",
+ "in": "path",
+ "name": "turnId",
+ "required": true,
+ "schema": {
+ "description": "Turn identifier.",
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetTurnResponse"
+ }
+ }
+ },
+ "description": "Turn data."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session or turn not found."
+ }
+ },
+ "summary": "Get a turn",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "get_turn"
+ }
+ },
+ "/v1/sessions/{sessionId}/turns/{turnId}/events": {
+ "get": {
+ "description": "Paginated persisted events for a turn (insertion order by default).",
+ "parameters": [
+ {
+ "description": "Session identifier.",
+ "in": "path",
+ "name": "sessionId",
+ "required": true,
+ "schema": {
+ "description": "Session identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Turn identifier.",
+ "in": "path",
+ "name": "turnId",
+ "required": true,
+ "schema": {
+ "description": "Turn identifier.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ {
+ "description": "Max events per response. Default 25, max 100.",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 25,
+ "description": "Max events per response. Default 25, max 100.",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "in": "query",
+ "name": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Sort events by insertion order. Defaults to \"asc\".",
+ "in": "query",
+ "name": "order",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ListTurnEventsOrder"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListTurnEventsResponse"
+ }
+ }
+ },
+ "description": "Paginated turn events."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid page token."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Session or turn not found."
+ }
+ },
+ "summary": "List turn events",
+ "tags": [
+ "Sessions"
+ ],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
+ "x-fern-sdk-group-name": [
+ "sessions"
+ ],
+ "x-fern-sdk-method-name": "list_turn_events"
+ }
+ },
+ "/v1/skills": {
+ "get": {
+ "description": "Agent skills declared in skills.yaml.",
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListSkillsResponse"
+ }
+ }
+ },
+ "description": "All configured skills."
+ }
+ },
+ "summary": "List skills",
+ "tags": [
+ "Skills"
+ ],
+ "x-fern-sdk-group-name": [
+ "skills"
+ ],
+ "x-fern-sdk-method-name": "list"
+ }
+ }
+ },
+ "webhooks": {}
+}
diff --git a/package.json b/package.json
index ff9003fd9..909465e25 100644
--- a/package.json
+++ b/package.json
@@ -13,6 +13,7 @@
"test": "pnpm --filter @truefoundry/utils test && pnpm --filter @truefoundry/server test && pnpm --filter frontend test",
"test:store:local": "bash scripts/test-store-with-postgres.sh",
"dev:server": "pnpm --filter @truefoundry/server dev",
+ "openapi:write": "pnpm --filter @truefoundry/server openapi:write",
"dev:frontend": "pnpm --filter frontend dev",
"ui:shot": "node ui-shots/shot.mjs",
"ui:clean": "node ui-shots/clean.mjs",
diff --git a/packages/harness/src/agent-session/TurnHandle.ts b/packages/harness/src/agent-session/TurnHandle.ts
index f676eeb6f..c90733480 100644
--- a/packages/harness/src/agent-session/TurnHandle.ts
+++ b/packages/harness/src/agent-session/TurnHandle.ts
@@ -277,7 +277,8 @@ export class TurnHandle<TTurnCustom extends object = Record<string, never>> {
} else {
terminalState = {
status: 'done',
- output: executeResult.output,
+ // TODO: revert alongside TurnStateDone.output.
+ ...(executeResult.output && { output: executeResult.output }),
required_actions: executeResult.required_actions,
completed_at: createdAt,
};
diff --git a/packages/harness/src/agent-session/schemas/turn.ts b/packages/harness/src/agent-session/schemas/turn.ts
index a3a482be0..8a275c823 100644
--- a/packages/harness/src/agent-session/schemas/turn.ts
+++ b/packages/harness/src/agent-session/schemas/turn.ts
@@ -49,7 +49,8 @@ export const TurnStateErrorSchema = z
export const TurnStateDoneSchema = z
.object({
status: z.literal('done'),
- output: ModelMessageEventSchema.nullable(),
+ // TODO: restore `.nullable()`; it marks the shared component nullable and breaks SDK codegen.
+ output: ModelMessageEventSchema.optional(),
required_actions: z.array(ActionRequiredEventSchema),
completed_at: z.string(),
})
diff --git a/packages/harness/tests/agent-session/testHelpers.ts b/packages/harness/tests/agent-session/testHelpers.ts
index 90972c146..c1e869d33 100644
--- a/packages/harness/tests/agent-session/testHelpers.ts
+++ b/packages/harness/tests/agent-session/testHelpers.ts
@@ -176,8 +176,8 @@ export function makeCreateTurnInput(input: {
export function makeDoneTurnState(): TerminalTurnState {
return {
+ // TODO: restore `output: null` alongside TurnStateDone.output.
status: 'done',
- output: null,
required_actions: [],
completed_at: new Date().toISOString(),
};
diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.json
new file mode 100644
index 000000000..b4dab6b60
--- /dev/null
+++ b/packages/sdk/.fern/metadata.json
@@ -0,0 +1,35 @@
+{
+ "cliVersion": "5.82.0",
+ "generatorName": "fernapi/fern-typescript-node-sdk",
+ "generatorVersion": "3.85.0",
+ "generatorConfig": {
+ "packageJson": {
+ "name": "trueharness"
+ },
+ "allowExtraFields": true,
+ "allowCustomFetcher": true,
+ "enableInlineTypes": false,
+ "fetchSupport": "native",
+ "fileResponseType": "binary-response",
+ "formDataSupport": "Node18",
+ "includeApiReference": true,
+ "inlineFileProperties": true,
+ "inlinePathParameters": true,
+ "naming": {
+ "namespace": "TrueHarness",
+ "client": "TrueHarness"
+ },
+ "noSerdeLayer": false,
+ "omitUndefined": true,
+ "retainOriginalCasing": false,
+ "skipResponseValidation": true,
+ "streamType": "web",
+ "useDefaultRequestParameterValues": true
+ },
+ "originGitCommit": "70854f9f99677aeca430caf131a2d13df2996205",
+ "originGitCommitIsDirty": false,
+ "invokedBy": "ci",
+ "requestedVersion": "0.0.0",
+ "ciProvider": "github",
+ "sdkVersion": "0.0.0"
+}
diff --git a/packages/sdk/.fern/verify.sh b/packages/sdk/.fern/verify.sh
new file mode 100755
index 000000000..a224ac815
--- /dev/null
+++ b/packages/sdk/.fern/verify.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+set -euo pipefail
+pnpm install
+pnpm build
+pnpm test
diff --git a/packages/sdk/.fernignore b/packages/sdk/.fernignore
new file mode 100644
index 000000000..b3acc113a
--- /dev/null
+++ b/packages/sdk/.fernignore
@@ -0,0 +1,3 @@
+# Fern replaces everything it generated on each run. The lockfile is written by
+# `pnpm install`, not by Fern, and is committed so the SDK build is reproducible.
+pnpm-lock.yaml
diff --git a/packages/sdk/.gitignore b/packages/sdk/.gitignore
new file mode 100644
index 000000000..72271e049
--- /dev/null
+++ b/packages/sdk/.gitignore
@@ -0,0 +1,3 @@
+node_modules
+.DS_Store
+/dist
\ No newline at end of file
diff --git a/packages/sdk/CONTRIBUTING.md b/packages/sdk/CONTRIBUTING.md
new file mode 100644
index 000000000..fe5bc2f77
--- /dev/null
+++ b/packages/sdk/CONTRIBUTING.md
@@ -0,0 +1,133 @@
+# Contributing
+
+Thanks for your interest in contributing to this SDK! This document provides guidelines for contributing to the project.
+
+## Getting Started
+
+### Prerequisites
+
+- Node.js 20 or higher
+- pnpm package manager
+
+### Installation
+
+Install the project dependencies:
+
+```bash
+pnpm install
+```
+
+### Building
+
+Build the project:
+
+```bash
+pnpm build
+```
+
+### Testing
+
+Run the test suite:
+
+```bash
+pnpm test
+```
+
+Run specific test types:
+- `pnpm test:unit` - Run unit tests
+- `pnpm test:wire` - Run wire/integration tests
+
+### Linting and Formatting
+
+Check code style:
+
+```bash
+pnpm run lint
+pnpm run format:check
+```
+
+Fix code style issues:
+
+```bash
+pnpm run lint:fix
+pnpm run format:fix
+```
+
+Or use the combined check command:
+
+```bash
+pnpm run check:fix
+```
+
+## About Generated Code
+
+**Important**: Most files in this SDK are automatically generated by [Fern](https://buildwithfern.com) from the API definition. Direct modifications to generated files will be overwritten the next time the SDK is generated.
+
+### Generated Files
+
+The following directories contain generated code:
+- `src/api/` - API client classes and types
+- `src/serialization/` - Serialization/deserialization logic
+- Most TypeScript files in `src/`
+
+### How to Customize
+
+If you need to customize the SDK, you have two options:
+
+#### Option 1: Use `.fernignore`
+
+For custom code that should persist across SDK regenerations:
+
+1. Create a `.fernignore` file in the project root
+2. Add file patterns for files you want to preserve (similar to `.gitignore` syntax)
+3. Add your custom code to those files
+
+Files listed in `.fernignore` will not be overwritten when the SDK is regenerated.
+
+For more information, see the [Fern documentation on custom code](https://buildwithfern.com/learn/sdks/overview/custom-code).
+
+#### Option 2: Contribute to the Generator
+
+If you want to change how code is generated for all users of this SDK:
+
+1. The TypeScript SDK generator lives in the [Fern repository](https://github.com/fern-api/fern)
+2. Generator code is located at `generators/typescript/sdk/`
+3. Follow the [Fern contributing guidelines](https://github.com/fern-api/fern/blob/main/CONTRIBUTING.md)
+4. Submit a pull request with your changes to the generator
+
+This approach is best for:
+- Bug fixes in generated code
+- New features that would benefit all users
+- Improvements to code generation patterns
+
+## Making Changes
+
+### Workflow
+
+1. Create a new branch for your changes
+2. Make your modifications
+3. Run tests to ensure nothing breaks: `pnpm test`
+4. Run linting and formatting: `pnpm run check:fix`
+5. Build the project: `pnpm build`
+6. Commit your changes with a clear commit message
+7. Push your branch and create a pull request
+
+### Commit Messages
+
+Write clear, descriptive commit messages that explain what changed and why.
+
+### Code Style
+
+This project uses automated code formatting and linting. Run `pnpm run check:fix` before committing to ensure your code meets the project's style guidelines.
+
+## Questions or Issues?
+
+If you have questions or run into issues:
+
+1. Check the [Fern documentation](https://buildwithfern.com)
+2. Search existing [GitHub issues](https://github.com/fern-api/fern/issues)
+3. Open a new issue if your question hasn't been addressed
+
+## License
+
+By contributing to this project, you agree that your contributions will be licensed under the same license as the project.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
new file mode 100644
index 000000000..fae45d4b7
--- /dev/null
+++ b/packages/sdk/README.md
@@ -0,0 +1,332 @@
+# Truefoundry TypeScript Library
+
+[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=Truefoundry%2FTypeScript)
+[![npm shield](https://img.shields.io/npm/v/trueharness)](https://www.npmjs.com/package/trueharness)
+
+TypeScript client for the TrueFoundry agent harness server: a self-hosted runtime that executes agent turns and streams them over Server-Sent Events.
+
+The harness server has no built-in authentication, so point the client at your own deployment's base URL.
+
+
+## Table of Contents
+
+- [Installation](#installation)
+- [Reference](#reference)
+- [Usage](#usage)
+- [Request and Response Types](#request-and-response-types)
+- [Exception Handling](#exception-handling)
+- [Streaming Response](#streaming-response)
+- [Advanced](#advanced)
+ - [Subpackage Exports](#subpackage-exports)
+ - [Additional Headers](#additional-headers)
+ - [Additional Query String Parameters](#additional-query-string-parameters)
+ - [Retries](#retries)
+ - [Timeouts](#timeouts)
+ - [Aborting Requests](#aborting-requests)
+ - [Access Raw Response Data](#access-raw-response-data)
+ - [Logging](#logging)
+ - [Custom Fetch](#custom-fetch)
+ - [Custom Fetcher](#custom-fetcher)
+ - [Runtime Compatibility](#runtime-compatibility)
+- [Contributing](#contributing)
+
+## Installation
+
+```sh
+npm i -s trueharness
+```
+
+## Reference
+
+A full reference for this library is available [here](./reference.md).
+
+## Usage
+
+Instantiate and use the client with the following:
+
+```typescript
+import { TrueHarness } from "trueharness";
+
+const client = new TrueHarness({ baseUrl: "YOUR_BASE_URL" });
+const response = await client.sessions.createTurn("sessionId");
+for await (const item of response) {
+ console.log(item);
+}
+```
+
+## Request and Response Types
+
+The SDK exports all request and response types as TypeScript interfaces. Simply import them with the
+following namespace:
+
+```typescript
+import { TrueHarness } from "trueharness";
+
+const request: TrueHarness.ListSessionsRequest = {
+ ...
+};
+```
+
+## Exception Handling
+
+When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error
+will be thrown.
+
+```typescript
+import { TrueHarnessError } from "trueharness";
+
+try {
+ await client.sessions.createTurn(...);
+} catch (err) {
+ if (err instanceof TrueHarnessError) {
+ console.log(err.statusCode);
+ console.log(err.message);
+ console.log(err.body);
+ console.log(err.rawResponse);
+ }
+}
+```
+
+## Streaming Response
+
+Some endpoints return streaming responses instead of returning the full response at once.
+The SDK uses async iterators, so you can consume the responses using a `for await...of` loop.
+
+```typescript
+import { TrueHarness } from "trueharness";
+
+const client = new TrueHarness({ baseUrl: "YOUR_BASE_URL" });
+const response = await client.sessions.createTurn("sessionId");
+for await (const item of response) {
+ console.log(item);
+}
+```
+
+## Advanced
+
+### Subpackage Exports
+
+This SDK supports direct imports of subpackage clients, which allows JavaScript bundlers to tree-shake and include only the imported subpackage code. This results in much smaller bundle sizes.
+
+```typescript
+import { ServerClient } from 'trueharness/server';
+
+const client = new ServerClient({...});
+```
+
+### Additional Headers
+
+If you would like to send additional headers as part of the request, use the `headers` request option.
+
+```typescript
+import { TrueHarness } from "trueharness";
+
+const client = new TrueHarness({
+ ...
+ headers: {
+ 'X-Custom-Header': 'custom value'
+ }
+});
+
+const response = await client.sessions.createTurn(..., {
+ headers: {
+ 'X-Custom-Header': 'custom value'
+ }
+});
+```
+
+### Additional Query String Parameters
+
+If you would like to send additional query string parameters as part of the request, use the `queryParams` request option.
+
+```typescript
+const response = await client.sessions.createTurn(..., {
+ queryParams: {
+ 'customQueryParamKey': 'custom query param value'
+ }
+});
+```
+
+### Retries
+
+The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
+as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
+retry limit (default: 2).
+
+Which status codes are retried depends on the `retryStatusCodes` generator configuration:
+
+**`legacy`** (current default): retries on
+- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
+- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
+- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) (All server errors, including 500)
+
+**`recommended`**: retries on
+- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
+- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
+- [502](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) (Bad Gateway)
+- [503](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) (Service Unavailable)
+- [504](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504) (Gateway Timeout)
+
+Use the `maxRetries` request option to configure this behavior.
+
+```typescript
+const response = await client.sessions.createTurn(..., {
+ maxRetries: 0 // override maxRetries at the request level
+});
+```
+
+### Timeouts
+
+The SDK defaults to a 60 second timeout. Use the `timeoutInSeconds` option to configure this behavior.
+
+```typescript
+const response = await client.sessions.createTurn(..., {
+ timeoutInSeconds: 30 // override timeout to 30s
+});
+```
+
+### Aborting Requests
+
+The SDK allows users to abort requests at any point by passing in an abort signal.
+
+```typescript
+const controller = new AbortController();
+const response = await client.sessions.createTurn(..., {
+ abortSignal: controller.signal
+});
+controller.abort(); // aborts the request
+```
+
+### Access Raw Response Data
+
+The SDK provides access to raw response data, including headers, through the `.withRawResponse()` method.
+The `.withRawResponse()` method returns a promise that results to an object with a `data` and a `rawResponse` property.
+
+```typescript
+const { data, rawResponse } = await client.sessions.createTurn(...).withRawResponse();
+
+console.log(data);
+console.log(rawResponse.headers['X-My-Header']);
+```
+
+### Logging
+
+The SDK supports logging. You can configure the logger by passing in a `logging` object to the client options.
+
+```typescript
+import { TrueHarness, logging } from "trueharness";
+
+const client = new TrueHarness({
+ ...
+ logging: {
+ level: logging.LogLevel.Debug, // defaults to logging.LogLevel.Info
+ logger: new logging.ConsoleLogger(), // defaults to ConsoleLogger
+ silent: false, // defaults to true, set to false to enable logging
+ }
+});
+```
+The `logging` object can have the following properties:
+- `level`: The log level to use. Defaults to `logging.LogLevel.Info`.
+- `logger`: The logger to use. Defaults to a `logging.ConsoleLogger`.
+- `silent`: Whether to silence the logger. Defaults to `true`.
+
+The `level` property can be one of the following values:
+- `logging.LogLevel.Debug`
+- `logging.LogLevel.Info`
+- `logging.LogLevel.Warn`
+- `logging.LogLevel.Error`
+
+To provide a custom logger, you can pass in an object that implements the `logging.ILogger` interface.
+
+<details>
+<summary>Custom logger examples</summary>
+
+Here's an example using the popular `winston` logging library.
+```ts
+import winston from 'winston';
+
+const winstonLogger = winston.createLogger({...});
+
+const logger: logging.ILogger = {
+ debug: (msg, ...args) => winstonLogger.debug(msg, ...args),
+ info: (msg, ...args) => winstonLogger.info(msg, ...args),
+ warn: (msg, ...args) => winstonLogger.warn(msg, ...args),
+ error: (msg, ...args) => winstonLogger.error(msg, ...args),
+};
+```
+
+Here's an example using the popular `pino` logging library.
+
+```ts
+import pino from 'pino';
+
+const pinoLogger = pino({...});
+
+const logger: logging.ILogger = {
+ debug: (msg, ...args) => pinoLogger.debug(args, msg),
+ info: (msg, ...args) => pinoLogger.info(args, msg),
+ warn: (msg, ...args) => pinoLogger.warn(args, msg),
+ error: (msg, ...args) => pinoLogger.error(args, msg),
+};
+```
+</details>
+
+
+### Custom Fetch
+
+The SDK provides a low-level `fetch` method for making custom HTTP requests while still
+benefiting from SDK-level configuration like authentication, retries, timeouts, and logging.
+This is useful for calling API endpoints not yet supported in the SDK.
+
+```typescript
+const response = await client.fetch("/v1/custom/endpoint", {
+ method: "GET",
+}, {
+ timeoutInSeconds: 30,
+ maxRetries: 3,
+ headers: {
+ "X-Custom-Header": "custom-value",
+ },
+});
+
+const data = await response.json();
+```
+
+### Custom Fetcher
+
+The SDK provides a way for you to customize the underlying HTTP client / Fetch function. If you're running in an
+unsupported environment, this provides a way for you to break glass and ensure the SDK works.
+
+```typescript
+import { TrueHarness } from "trueharness";
+
+const client = new TrueHarness({
+ ...
+ fetcher: // provide your implementation here
+});
+```
+
+### Runtime Compatibility
+
+
+The SDK works in the following runtimes:
+
+
+
+- Node.js 18+
+- Vercel
+- Cloudflare Workers
+- Deno v1.25+
+- Bun 1.0+
+- React Native
+
+
+## Contributing
+
+While we value open-source contributions to this SDK, this library is generated programmatically.
+Additions made directly to this library would have to be moved over to our generation code,
+otherwise they would be overwritten upon the next generated release. Feel free to open a PR as
+a proof of concept, but know that we will not be able to merge it as-is. We suggest opening
+an issue first to discuss with us!
+
+On the other hand, contributions to the README are always very welcome!
diff --git a/packages/sdk/biome.json b/packages/sdk/biome.json
new file mode 100644
index 000000000..6b89164f9
--- /dev/null
+++ b/packages/sdk/biome.json
@@ -0,0 +1,74 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json",
+ "root": true,
+ "vcs": {
+ "enabled": false
+ },
+ "files": {
+ "ignoreUnknown": true,
+ "includes": [
+ "**",
+ "!!dist",
+ "!!**/dist",
+ "!!lib",
+ "!!**/lib",
+ "!!_tmp_*",
+ "!!**/_tmp_*",
+ "!!*.tmp",
+ "!!**/*.tmp",
+ "!!.tmp/",
+ "!!**/.tmp/",
+ "!!*.log",
+ "!!**/*.log",
+ "!!**/.DS_Store",
+ "!!**/Thumbs.db"
+ ]
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "space",
+ "indentWidth": 4,
+ "lineWidth": 120
+ },
+ "javascript": {
+ "formatter": {
+ "quoteStyle": "double"
+ }
+ },
+ "assist": {
+ "enabled": true,
+ "actions": {
+ "source": {
+ "organizeImports": "on"
+ }
+ }
+ },
+ "linter": {
+ "rules": {
+ "style": {
+ "useNodejsImportProtocol": "off"
+ },
+ "suspicious": {
+ "noAssignInExpressions": "warn",
+ "noUselessEscapeInString": {
+ "level": "warn",
+ "fix": "none",
+ "options": {}
+ },
+ "noThenProperty": "warn",
+ "useIterableCallbackReturn": "warn",
+ "noShadowRestrictedNames": "warn",
+ "noTsIgnore": {
+ "level": "warn",
+ "fix": "none",
+ "options": {}
+ },
+ "noConfusingVoidType": {
+ "level": "warn",
+ "fix": "none",
+ "options": {}
+ }
+ }
+ }
+ }
+}
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
new file mode 100644
index 000000000..0b1fbf342
--- /dev/null
+++ b/packages/sdk/package.json
@@ -0,0 +1,131 @@
+{
+ "name": "trueharness",
+ "version": "0.0.0",
+ "private": false,
+ "type": "commonjs",
+ "main": "./dist/cjs/index.js",
+ "module": "./dist/esm/index.mjs",
+ "types": "./dist/cjs/index.d.ts",
+ "exports": {
+ ".": {
+ "import": {
+ "types": "./dist/esm/index.d.mts",
+ "default": "./dist/esm/index.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/index.d.ts",
+ "default": "./dist/cjs/index.js"
+ },
+ "default": "./dist/cjs/index.js"
+ },
+ "./serialization": {
+ "import": {
+ "types": "./dist/esm/serialization/index.d.mts",
+ "default": "./dist/esm/serialization/index.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/serialization/index.d.ts",
+ "default": "./dist/cjs/serialization/index.js"
+ },
+ "default": "./dist/cjs/serialization/index.js"
+ },
+ "./server": {
+ "import": {
+ "types": "./dist/esm/api/resources/server/exports.d.mts",
+ "default": "./dist/esm/api/resources/server/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/server/exports.d.ts",
+ "default": "./dist/cjs/api/resources/server/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/server/exports.js"
+ },
+ "./mcpServers": {
+ "import": {
+ "types": "./dist/esm/api/resources/mcpServers/exports.d.mts",
+ "default": "./dist/esm/api/resources/mcpServers/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/mcpServers/exports.d.ts",
+ "default": "./dist/cjs/api/resources/mcpServers/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/mcpServers/exports.js"
+ },
+ "./models": {
+ "import": {
+ "types": "./dist/esm/api/resources/models/exports.d.mts",
+ "default": "./dist/esm/api/resources/models/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/models/exports.d.ts",
+ "default": "./dist/cjs/api/resources/models/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/models/exports.js"
+ },
+ "./sessions": {
+ "import": {
+ "types": "./dist/esm/api/resources/sessions/exports.d.mts",
+ "default": "./dist/esm/api/resources/sessions/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/sessions/exports.d.ts",
+ "default": "./dist/cjs/api/resources/sessions/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/sessions/exports.js"
+ },
+ "./skills": {
+ "import": {
+ "types": "./dist/esm/api/resources/skills/exports.d.mts",
+ "default": "./dist/esm/api/resources/skills/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/skills/exports.d.ts",
+ "default": "./dist/cjs/api/resources/skills/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/skills/exports.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "dist",
+ "reference.md",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "format": "biome format --write --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "format:check": "biome format --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "lint": "biome lint --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "lint:fix": "biome lint --fix --unsafe --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "check": "biome check --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "check:fix": "biome check --fix --unsafe --skip-parse-errors --no-errors-on-unmatched --max-diagnostics=none",
+ "build": "pnpm build:cjs && pnpm build:esm",
+ "build:cjs": "tsc --project ./tsconfig.cjs.json",
+ "build:esm": "tsc --project ./tsconfig.esm.json && node scripts/rename-to-esm-files.js dist/esm",
+ "test": "vitest",
+ "test:unit": "vitest --project unit",
+ "test:wire": "vitest --project wire"
+ },
+ "dependencies": {},
+ "devDependencies": {
+ "webpack": "^5.105.4",
+ "ts-loader": "^9.5.4",
+ "vitest": "^4.1.1",
+ "msw": "2.11.2",
+ "@types/node": "^20.0.0",
+ "typescript": "~5.9.3",
+ "@biomejs/biome": "2.4.10"
+ },
+ "browser": {
+ "fs": false,
+ "os": false,
+ "path": false,
+ "stream": false,
+ "crypto": false
+ },
+ "packageManager": "[email protected]",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "sideEffects": false
+}
diff --git a/packages/sdk/pnpm-lock.yaml b/packages/sdk/pnpm-lock.yaml
new file mode 100644
index 000000000..f55317a22
--- /dev/null
+++ b/packages/sdk/pnpm-lock.yaml
@@ -0,0 +1,1847 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@biomejs/biome':
+ specifier: 2.4.10
+ version: 2.4.10
+ '@types/node':
+ specifier: ^20.0.0
+ version: 20.19.43
+ msw:
+ specifier: 2.11.2
+ version: 2.11.2(@types/[email protected])([email protected])
+ ts-loader:
+ specifier: ^9.5.4
+ typescript:
+ specifier: ~5.9.3
+ version: 5.9.3
+ vitest:
+ specifier: ^4.1.1
+ webpack:
+ specifier: ^5.105.4
+ version: 5.109.2
+
+packages:
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-xxA3AphFQ1geij4JTHXv4EeSTda1IFn22ye9LdyVPoJU19fNVl0uzfEuhsfQ4Yue/0FaLs2/ccVi4UDiE7R30w==}
+ engines: {node: '>=14.21.3'}
+ hasBin: true
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-vuzzI1cWqDVzOMIkYyHbKqp+AkQq4K7k+UCXWpkYcY/HDn1UxdsbsfgtVpa40shem8Kax4TLDLlx8kMAecgqiw==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-14fzASRo+BPotwp7nWULy2W5xeUyFnTaq1V13Etrrxkrih+ez/2QfgFm5Ehtf5vSjtgx/IJycMMpn5kPd5ZNaA==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-WrJY6UuiSD/Dh+nwK2qOTu8kdMDlLV3dLMmychIghHPAysWFq1/DGC1pVZx8POE3ZkzKR3PUUnVrtZfMfaJjyQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-7MH1CMW5uuxQ/s7FLST63qF8B3Hgu2HRdZ7tA1X1+mk+St4JOuIrqdhIBnnyqeyWJNI+Bww7Es5QZ0wIc1Cmkw==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-kDTi3pI6PBN6CiczsWYOyP2zk0IJI08EWEQyDMQWW221rPaaEz6FvjLhnU07KMzLv8q3qSuoB93ua6inSQ55Tw==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-tZLvEEi2u9Xu1zAqRjTcpIDGVtldigVvzug2fTuPG0ME/g8/mXpRPcNgLB22bGn6FvLJpHHnqLnwliOu8xjYrg==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-umwQU6qPzH+ISTf/eHyJ/QoQnJs3V9Vpjz2OjZXe9MVBZ7prgGafMy7yYeRGnlmDAn87AKTF3Q6weLoMGpeqdQ==}
+ engines: {node: '>=14.21.3'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@biomejs/[email protected]':
+ resolution: {integrity: sha512-aW/JU5GuyH4uxMrNYpoC2kjaHlyJGLgIa3XkhPEZI0uKhZhJZU8BuEyJmvgzSPQNGozBwWjC972RaNdcJ9KyJg==}
+ engines: {node: '>=14.21.3'}
+ cpu: [x64]
+ os: [win32]
+
+ '@bundled-es-modules/[email protected]':
+ resolution: {integrity: sha512-8o+5fRPLNbjbdGRRmJj3h6Hh1AQJf2dk3qQ/5ZFb+PXkRNiSoMGGUKlsgLfrxneb72axVJyIYji64E2+nNfYyw==}
+
+ '@bundled-es-modules/[email protected]':
+ resolution: {integrity: sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg==}
+
+ '@emnapi/[email protected]':
+ resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==}
+
+ '@emnapi/[email protected]':
+ resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==}
+
+ '@emnapi/[email protected]':
+ resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==}
+ engines: {node: '>=18'}
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==}
+ engines: {node: '>=18'}
+
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/node': '>=18'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
+ engines: {node: '>=6.0.0'}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+
+ '@mswjs/[email protected]':
+ resolution: {integrity: sha512-2+BzZbjRO7Ct61k8fMNHEtoKjeWI9pIlHFTqBwZ5icHpqszIgEZbjb1MW5Z0+bITTCTl3gk4PDBxs9tA/csXvA==}
+ engines: {node: '>=18'}
+
+ '@napi-rs/[email protected]':
+ resolution: {integrity: sha512-kDoONqMa+VnZ4vvvu/ZUurpJ4gkZU57e7g69qpNgWhYcZFPUHZM2CEMKm+cG6ufDVALbjMvfmMjFVqaK7uEMnA==}
+ engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
+ peerDependencies:
+ '@emnapi/core': ^2.0.0-alpha.3
+ '@emnapi/runtime': ^2.0.0-alpha.3
+
+ '@open-draft/[email protected]':
+ resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==}
+
+ '@open-draft/[email protected]':
+ resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==}
+
+ '@open-draft/[email protected]':
+ resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
+
+ '@oxc-project/[email protected]':
+ resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==}
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [android]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [wasm32]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [win32]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+
+ '@standard-schema/[email protected]':
+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+
+ '@tybys/[email protected]':
+ resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==}
+ peerDependencies:
+ msw: ^2.4.9
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ msw:
+ optional: true
+ vite:
+ optional: true
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==}
+
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==}
+
+ '@webassemblyjs/[email protected]':
+ resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==}
+
+ resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}
+
+ resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==}
+
+ resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
+ engines: {node: '>=0.4.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==}
+ peerDependencies:
+ ajv: ^8.0.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+
+ resolution: {integrity: sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==}
+ peerDependencies:
+ ajv: ^8.8.2
+
+ resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}
+
+ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-APw5YuIQAg6L9w4sHDI6j26DGFJI6RpYOhnkMPdC9lWbkKvsyPHzDsve1yd73lk21yz7Y09Kci8B2Pp9FonzWA==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==}
+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
+ hasBin: true
+
+ resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+
+ resolution: {integrity: sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==}
+
+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==}
+ engines: {node: '>=6.0'}
+
+ resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}
+ engines: {node: '>= 12'}
+
+ resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
+ engines: {node: '>=7.0.0'}
+
+ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
+
+ resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}
+
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
+ resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
+ engines: {node: '>= 0.6'}
+
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-AsvhAxopJGh6museTDMIjn6JpDYOfgu4RLlygomt87MUwBUqTfd/1EiPtx10/LZE8xpTvkP2E9Gafq7lkLtodQ==}
+
+ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}
+
+ resolution: {integrity: sha512-GVoi+ICHocoOIU7qVVM48wOJziRsqrsyqlI0Ce0LdowRn6v3bcH2zUa9kp85ncx0nwIb9/HOCOLS3fdThDG/XQ==}
+ engines: {node: '>=10.13.0'}
+
+ resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==}
+
+ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==}
+ engines: {node: '>=8.0.0'}
+
+ resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==}
+ engines: {node: '>=4.0'}
+
+ resolution: {integrity: sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==}
+ engines: {node: '>=4.0'}
+
+ resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}
+ engines: {node: '>=4.0'}
+
+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+
+ resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
+ engines: {node: '>=0.8.x'}
+
+ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
+
+ resolution: {integrity: sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==}
+
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}
+ engines: {node: 6.* || 8.* || >= 10.*}
+
+ resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
+
+ resolution: {integrity: sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==}
+ engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
+
+ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==}
+
+ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw==}
+
+ resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==}
+ engines: {node: '>= 10.13.0'}
+
+ resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
+
+ resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
+ engines: {node: '>= 12.0.0'}
+
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+
+ resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==}
+
+ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}
+ engines: {node: '>= 0.6'}
+
+ resolution: {integrity: sha512-DoeAZz8Q1C1znwsUzej1fdoi4jCf7/+Em27ouLqfK/+3m8G+D7yDhUwrc3CNhjSzGUN1kn7Iv4sWmjflQHenpw==}
+ engines: {node: '>= 10.13.0'}
+ peerDependencies:
+ '@minify-html/node': '*'
+ '@swc/core': '*'
+ '@swc/css': '*'
+ '@swc/html': '*'
+ clean-css: '*'
+ cssnano: '*'
+ csso: '*'
+ esbuild: '*'
+ html-minifier-terser: '*'
+ lightningcss: '*'
+ postcss: '*'
+ uglify-js: '*'
+ webpack: ^5.1.0
+ peerDependenciesMeta:
+ '@minify-html/node':
+ optional: true
+ '@swc/core':
+ optional: true
+ '@swc/css':
+ optional: true
+ '@swc/html':
+ optional: true
+ clean-css:
+ optional: true
+ cssnano:
+ optional: true
+ csso:
+ optional: true
+ esbuild:
+ optional: true
+ html-minifier-terser:
+ optional: true
+ lightningcss:
+ optional: true
+ postcss:
+ optional: true
+ uglify-js:
+ optional: true
+
+ resolution: {integrity: sha512-MI54hLCsrMwiflkcqlgYYNJJddY5/+S0SnONvhv1owOplvqohKSQyGejpNdUGyCwgs4IH7PqaNbPw/sKOEze9Q==}
+ engines: {node: '>=18'}
+ hasBin: true
+ peerDependencies:
+ typescript: '>= 4.8.x'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==}
+ engines: {node: ^18.17.0 || >=20.5.0}
+
+ resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==}
+
+ resolution: {integrity: sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==}
+ engines: {node: '>=12.20.0'}
+
+ resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==}
+
+ resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
+
+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
+
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-LPRKoHnLKd/r3dVxcwO7vhCW+orkOGj9ViueosEBK6ie89CijnfRlhaDhHq/3Hxu4CkWQtxwlBG0mzTQY6uQjw==}
+
+ resolution: {integrity: sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+
+ resolution: {integrity: sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==}
+ engines: {node: '>= 10.13.0'}
+
+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
+
+ resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
+ engines: {node: '>=14'}
+
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==}
+
+ resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
+ engines: {node: '>= 12'}
+
+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
+
+ resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
+ engines: {node: '>= 0.8'}
+
+ resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}
+
+ resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==}
+
+ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
+ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+
+ resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==}
+ engines: {node: '>=14.0.0'}
+
+ resolution: {integrity: sha512-DxKfPBI52p2msTEu7MPhdpdDTBhhVQg1a/8PjQckeyAvO13eMYElX545grIp6nnTGIMZlRvFZPvFhvI/WIz2Vg==}
+
+ resolution: {integrity: sha512-3kZ8wQQ/k5DrChD4X4FVvr2D7E5uoRgAqkPyLpSCGUvqOvqu+JEdr3mwMUaVWb+vMHZaKhF5fp2PBigKsui7hA==}
+ hasBin: true
+
+ resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-R4iuczmtgxvtuI556s+hTZ6/7Ee03VCAk/l/M8LY1OAsUgB7YydsCxkgq9D9pKRaD7GJqUi2u8fp9zZP/ufjKA==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ loader-utils: '*'
+ typescript: '*'
+ webpack: ^4.0.0 || ^5.0.0
+ peerDependenciesMeta:
+ loader-utils:
+ optional: true
+
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+
+ resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
+
+ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
+ hasBin: true
+ peerDependencies:
+ browserslist: '>= 4.21.0'
+
+ resolution: {integrity: sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^20.19.0 || >=22.12.0
+ '@vitejs/devtools': ^0.3.0
+ esbuild: ^0.27.0 || ^0.28.0
+ jiti: '>=1.21.0'
+ less: ^4.0.0
+ sass: ^1.70.0
+ sass-embedded: ^1.70.0
+ stylus: '>=0.54.8'
+ sugarss: ^5.0.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ '@vitejs/devtools':
+ optional: true
+ esbuild:
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==}
+ engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
+ hasBin: true
+ peerDependencies:
+ '@edge-runtime/vm': '*'
+ '@opentelemetry/api': ^1.9.0
+ '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
+ '@vitest/browser-playwright': 4.1.10
+ '@vitest/browser-preview': 4.1.10
+ '@vitest/browser-webdriverio': 4.1.10
+ '@vitest/coverage-istanbul': 4.1.10
+ '@vitest/coverage-v8': 4.1.10
+ '@vitest/ui': 4.1.10
+ happy-dom: '*'
+ jsdom: '*'
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ '@edge-runtime/vm':
+ optional: true
+ '@opentelemetry/api':
+ optional: true
+ '@types/node':
+ optional: true
+ '@vitest/browser-playwright':
+ optional: true
+ '@vitest/browser-preview':
+ optional: true
+ '@vitest/browser-webdriverio':
+ optional: true
+ '@vitest/coverage-istanbul':
+ optional: true
+ '@vitest/coverage-v8':
+ optional: true
+ '@vitest/ui':
+ optional: true
+ happy-dom:
+ optional: true
+ jsdom:
+ optional: true
+
+ resolution: {integrity: sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==}
+ engines: {node: '>=10.13.0'}
+
+ resolution: {integrity: sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==}
+ engines: {node: '>=10.13.0'}
+
+ resolution: {integrity: sha512-U9/cvLzxObKNEZ9+TtdqrHM5/9z3lgl2c+c4BzbqGxFQvQvBAq87yql5A8pQ+rrMbS496MZJeF5enVBndIy2hw==}
+ engines: {node: '>=10.13.0'}
+ hasBin: true
+ peerDependencies:
+ webpack-cli: '*'
+ peerDependenciesMeta:
+ webpack-cli:
+ optional: true
+
+ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
+ engines: {node: '>=8'}
+ hasBin: true
+
+ resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
+ engines: {node: '>=18'}
+
+snapshots:
+
+ '@biomejs/[email protected]':
+ optionalDependencies:
+ '@biomejs/cli-darwin-arm64': 2.4.10
+ '@biomejs/cli-darwin-x64': 2.4.10
+ '@biomejs/cli-linux-arm64': 2.4.10
+ '@biomejs/cli-linux-arm64-musl': 2.4.10
+ '@biomejs/cli-linux-x64': 2.4.10
+ '@biomejs/cli-linux-x64-musl': 2.4.10
+ '@biomejs/cli-win32-arm64': 2.4.10
+ '@biomejs/cli-win32-x64': 2.4.10
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@biomejs/[email protected]':
+ optional: true
+
+ '@bundled-es-modules/[email protected]':
+ dependencies:
+ cookie: 0.7.2
+
+ '@bundled-es-modules/[email protected]':
+ dependencies:
+ statuses: 2.0.2
+
+ '@emnapi/[email protected]':
+ dependencies:
+ '@emnapi/wasi-threads': 1.2.2
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@inquirer/[email protected]': {}
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/core': 10.3.2(@types/[email protected])
+ '@inquirer/type': 3.0.10(@types/[email protected])
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@inquirer/[email protected](@types/[email protected])':
+ dependencies:
+ '@inquirer/ansi': 1.0.2
+ '@inquirer/figures': 1.0.15
+ '@inquirer/type': 3.0.10(@types/[email protected])
+ cli-width: 4.1.0
+ mute-stream: 2.0.0
+ signal-exit: 4.1.0
+ wrap-ansi: 6.2.0
+ yoctocolors-cjs: 2.1.3
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@inquirer/[email protected]': {}
+
+ '@inquirer/[email protected](@types/[email protected])':
+ optionalDependencies:
+ '@types/node': 20.19.43
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ '@mswjs/[email protected]':
+ dependencies:
+ '@open-draft/deferred-promise': 2.2.0
+ '@open-draft/logger': 0.3.0
+ '@open-draft/until': 2.1.0
+ is-node-process: 1.2.0
+ outvariant: 1.4.3
+ strict-event-emitter: 0.5.1
+
+ dependencies:
+ '@emnapi/core': 1.11.1
+ '@emnapi/runtime': 1.11.1
+ '@tybys/wasm-util': 0.10.3
+ optional: true
+
+ '@open-draft/[email protected]': {}
+
+ '@open-draft/[email protected]':
+ dependencies:
+ is-node-process: 1.2.0
+ outvariant: 1.4.3
+
+ '@open-draft/[email protected]': {}
+
+ '@oxc-project/[email protected]': {}
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ dependencies:
+ '@emnapi/core': 1.11.1
+ '@emnapi/runtime': 1.11.1
+ '@napi-rs/wasm-runtime': 1.2.0(@emnapi/[email protected])(@emnapi/[email protected])
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]': {}
+
+ '@standard-schema/[email protected]': {}
+
+ '@tybys/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/deep-eql': 4.0.2
+ assertion-error: 2.0.1
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 6.21.0
+
+ '@types/[email protected]': {}
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@types/chai': 5.2.3
+ '@vitest/spy': 4.1.10
+ '@vitest/utils': 4.1.10
+ chai: 6.2.2
+ tinyrainbow: 3.1.1
+
+ dependencies:
+ '@vitest/spy': 4.1.10
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ msw: 2.11.2(@types/[email protected])([email protected])
+ vite: 8.1.5(@types/[email protected])([email protected])
+
+ '@vitest/[email protected]':
+ dependencies:
+ tinyrainbow: 3.1.1
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/utils': 4.1.10
+ pathe: 2.0.3
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 4.1.10
+ '@vitest/utils': 4.1.10
+ magic-string: 0.30.21
+ pathe: 2.0.3
+
+ '@vitest/[email protected]': {}
+
+ '@vitest/[email protected]':
+ dependencies:
+ '@vitest/pretty-format': 4.1.10
+ convert-source-map: 2.0.0
+ tinyrainbow: 3.1.1
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/helper-numbers': 1.13.2
+ '@webassemblyjs/helper-wasm-bytecode': 1.13.2
+
+ '@webassemblyjs/[email protected]': {}
+
+ '@webassemblyjs/[email protected]': {}
+
+ '@webassemblyjs/[email protected]': {}
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/floating-point-hex-parser': 1.13.2
+ '@webassemblyjs/helper-api-error': 1.13.2
+ '@xtuc/long': 4.2.2
+
+ '@webassemblyjs/[email protected]': {}
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/helper-buffer': 1.14.1
+ '@webassemblyjs/helper-wasm-bytecode': 1.13.2
+ '@webassemblyjs/wasm-gen': 1.14.1
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@xtuc/ieee754': 1.2.0
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@xtuc/long': 4.2.2
+
+ '@webassemblyjs/[email protected]': {}
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/helper-buffer': 1.14.1
+ '@webassemblyjs/helper-wasm-bytecode': 1.13.2
+ '@webassemblyjs/helper-wasm-section': 1.14.1
+ '@webassemblyjs/wasm-gen': 1.14.1
+ '@webassemblyjs/wasm-opt': 1.14.1
+ '@webassemblyjs/wasm-parser': 1.14.1
+ '@webassemblyjs/wast-printer': 1.14.1
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/helper-wasm-bytecode': 1.13.2
+ '@webassemblyjs/ieee754': 1.13.2
+ '@webassemblyjs/leb128': 1.13.2
+ '@webassemblyjs/utf8': 1.13.2
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/helper-buffer': 1.14.1
+ '@webassemblyjs/wasm-gen': 1.14.1
+ '@webassemblyjs/wasm-parser': 1.14.1
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/helper-api-error': 1.13.2
+ '@webassemblyjs/helper-wasm-bytecode': 1.13.2
+ '@webassemblyjs/ieee754': 1.13.2
+ '@webassemblyjs/leb128': 1.13.2
+ '@webassemblyjs/utf8': 1.13.2
+
+ '@webassemblyjs/[email protected]':
+ dependencies:
+ '@webassemblyjs/ast': 1.14.1
+ '@xtuc/long': 4.2.2
+
+ '@xtuc/[email protected]': {}
+
+ '@xtuc/[email protected]': {}
+
+
+ optionalDependencies:
+ ajv: 8.20.0
+
+ dependencies:
+ ajv: 8.20.0
+ fast-deep-equal: 3.1.3
+
+ dependencies:
+ fast-deep-equal: 3.1.3
+ fast-uri: 3.1.4
+ json-schema-traverse: 1.0.0
+ require-from-string: 2.0.2
+
+
+ dependencies:
+ color-convert: 2.0.1
+
+
+
+ dependencies:
+ baseline-browser-mapping: 2.11.7
+ caniuse-lite: 1.0.30001806
+ electron-to-chromium: 1.5.398
+ node-releases: 2.0.51
+ update-browserslist-db: 1.2.3([email protected])
+
+
+
+
+ dependencies:
+ ansi-styles: 4.3.0
+ supports-color: 7.2.0
+
+
+
+ dependencies:
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+ wrap-ansi: 7.0.0
+
+ dependencies:
+ color-name: 1.1.4
+
+
+
+
+
+
+
+
+ dependencies:
+ graceful-fs: 4.2.11
+ tapable: 2.3.3
+
+
+
+ dependencies:
+ esrecurse: 4.3.0
+ estraverse: 4.3.0
+
+ dependencies:
+ estraverse: 5.3.0
+
+
+
+ dependencies:
+ '@types/estree': 1.0.9
+
+
+
+
+
+ optionalDependencies:
+ picomatch: 4.0.5
+
+ optional: true
+
+
+
+
+
+
+
+
+ dependencies:
+ '@types/node': 20.19.43
+ merge-stream: 2.0.0
+ supports-color: 8.1.1
+
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.33.0
+ lightningcss-darwin-arm64: 1.33.0
+ lightningcss-darwin-x64: 1.33.0
+ lightningcss-freebsd-x64: 1.33.0
+ lightningcss-linux-arm-gnueabihf: 1.33.0
+ lightningcss-linux-arm64-gnu: 1.33.0
+ lightningcss-linux-arm64-musl: 1.33.0
+ lightningcss-linux-x64-gnu: 1.33.0
+ lightningcss-linux-x64-musl: 1.33.0
+ lightningcss-win32-arm64-msvc: 1.33.0
+ lightningcss-win32-x64-msvc: 1.33.0
+
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ jest-worker: 27.5.1
+ schema-utils: 4.3.3
+ terser: 5.49.0
+ webpack: 5.109.2
+
+ dependencies:
+ '@bundled-es-modules/cookie': 2.0.1
+ '@bundled-es-modules/statuses': 1.0.1
+ '@inquirer/confirm': 5.1.21(@types/[email protected])
+ '@mswjs/interceptors': 0.39.8
+ '@open-draft/deferred-promise': 2.2.0
+ '@open-draft/until': 2.1.0
+ '@types/cookie': 0.6.0
+ '@types/statuses': 2.0.6
+ graphql: 16.14.2
+ headers-polyfill: 4.0.3
+ is-node-process: 1.2.0
+ outvariant: 1.4.3
+ path-to-regexp: 6.3.0
+ picocolors: 1.1.1
+ rettime: 0.7.0
+ strict-event-emitter: 0.5.1
+ tough-cookie: 6.0.2
+ type-fest: 4.41.0
+ yargs: 17.7.3
+ optionalDependencies:
+ typescript: 5.9.3
+ transitivePeerDependencies:
+ - '@types/node'
+
+
+
+
+
+
+
+
+
+
+
+ dependencies:
+ nanoid: 3.3.16
+ picocolors: 1.1.1
+ source-map-js: 1.2.1
+
+
+
+
+ dependencies:
+ '@oxc-project/types': 0.139.0
+ '@rolldown/pluginutils': 1.0.1
+ optionalDependencies:
+ '@rolldown/binding-android-arm64': 1.1.5
+ '@rolldown/binding-darwin-arm64': 1.1.5
+ '@rolldown/binding-darwin-x64': 1.1.5
+ '@rolldown/binding-freebsd-x64': 1.1.5
+ '@rolldown/binding-linux-arm-gnueabihf': 1.1.5
+ '@rolldown/binding-linux-arm64-gnu': 1.1.5
+ '@rolldown/binding-linux-arm64-musl': 1.1.5
+ '@rolldown/binding-linux-ppc64-gnu': 1.1.5
+ '@rolldown/binding-linux-s390x-gnu': 1.1.5
+ '@rolldown/binding-linux-x64-gnu': 1.1.5
+ '@rolldown/binding-linux-x64-musl': 1.1.5
+ '@rolldown/binding-openharmony-arm64': 1.1.5
+ '@rolldown/binding-wasm32-wasi': 1.1.5
+ '@rolldown/binding-win32-arm64-msvc': 1.1.5
+ '@rolldown/binding-win32-x64-msvc': 1.1.5
+
+ dependencies:
+ '@types/json-schema': 7.0.15
+ ajv: 8.20.0
+ ajv-formats: 2.1.1([email protected])
+ ajv-keywords: 5.1.0([email protected])
+
+
+
+
+ dependencies:
+ buffer-from: 1.1.2
+ source-map: 0.6.1
+
+
+
+
+
+
+
+ dependencies:
+ emoji-regex: 8.0.0
+ is-fullwidth-code-point: 3.0.0
+ strip-ansi: 6.0.1
+
+ dependencies:
+ ansi-regex: 5.0.1
+
+ dependencies:
+ has-flag: 4.0.0
+
+ dependencies:
+ has-flag: 4.0.0
+
+
+ dependencies:
+ '@jridgewell/source-map': 0.3.11
+ acorn: 8.18.0
+ commander: 2.20.3
+ source-map-support: 0.5.21
+
+
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.5
+
+
+
+ dependencies:
+ tldts-core: 7.4.9
+
+ dependencies:
+ tldts: 7.4.9
+
+ dependencies:
+ chalk: 4.1.2
+ picomatch: 4.0.5
+ source-map: 0.7.6
+ typescript: 5.9.3
+ webpack: 5.109.2
+
+ optional: true
+
+
+
+
+ dependencies:
+ browserslist: 4.28.7
+ escalade: 3.2.0
+ picocolors: 1.1.1
+
+ dependencies:
+ lightningcss: 1.33.0
+ picomatch: 4.0.5
+ postcss: 8.5.25
+ rolldown: 1.1.5
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ '@types/node': 20.19.43
+ fsevents: 2.3.3
+ terser: 5.49.0
+
+ dependencies:
+ '@vitest/expect': 4.1.10
+ '@vitest/pretty-format': 4.1.10
+ '@vitest/runner': 4.1.10
+ '@vitest/snapshot': 4.1.10
+ '@vitest/spy': 4.1.10
+ '@vitest/utils': 4.1.10
+ es-module-lexer: 2.3.1
+ expect-type: 1.4.0
+ magic-string: 0.30.21
+ obug: 2.1.4
+ pathe: 2.0.3
+ picomatch: 4.0.5
+ std-env: 4.2.0
+ tinybench: 2.9.0
+ tinyexec: 1.2.4
+ tinyglobby: 0.2.17
+ tinyrainbow: 3.1.1
+ vite: 8.1.5(@types/[email protected])([email protected])
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@types/node': 20.19.43
+ transitivePeerDependencies:
+ - msw
+
+ dependencies:
+ graceful-fs: 4.2.11
+
+
+ dependencies:
+ '@types/estree': 1.0.9
+ '@types/json-schema': 7.0.15
+ '@webassemblyjs/ast': 1.14.1
+ '@webassemblyjs/wasm-edit': 1.14.1
+ '@webassemblyjs/wasm-parser': 1.14.1
+ acorn: 8.18.0
+ browserslist: 4.28.7
+ chrome-trace-event: 1.0.4
+ enhanced-resolve: 5.24.4
+ es-module-lexer: 2.3.1
+ eslint-scope: 5.1.1
+ events: 3.3.0
+ graceful-fs: 4.2.11
+ mime-db: 1.54.0
+ minimizer-webpack-plugin: 5.6.1([email protected])
+ neo-async: 2.6.2
+ schema-utils: 4.3.3
+ tapable: 2.3.3
+ watchpack: 2.5.2
+ webpack-sources: 3.5.1
+ transitivePeerDependencies:
+ - '@minify-html/node'
+ - '@swc/core'
+ - '@swc/css'
+ - '@swc/html'
+ - clean-css
+ - cssnano
+ - csso
+ - esbuild
+ - html-minifier-terser
+ - lightningcss
+ - postcss
+ - uglify-js
+
+ dependencies:
+ siginfo: 2.0.0
+ stackback: 0.0.2
+
+ dependencies:
+ ansi-styles: 4.3.0
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+
+ dependencies:
+ ansi-styles: 4.3.0
+ string-width: 4.2.3
+ strip-ansi: 6.0.1
+
+
+
+ dependencies:
+ cliui: 8.0.1
+ escalade: 3.2.0
+ get-caller-file: 2.0.5
+ require-directory: 2.1.1
+ string-width: 4.2.3
+ y18n: 5.0.8
+ yargs-parser: 21.1.1
+
diff --git a/packages/sdk/pnpm-workspace.yaml b/packages/sdk/pnpm-workspace.yaml
new file mode 100644
index 000000000..6e4c39510
--- /dev/null
+++ b/packages/sdk/pnpm-workspace.yaml
@@ -0,0 +1 @@
+packages: ['.']
\ No newline at end of file
diff --git a/packages/sdk/reference.md b/packages/sdk/reference.md
new file mode 100644
index 000000000..eccfcc639
--- /dev/null
+++ b/packages/sdk/reference.md
@@ -0,0 +1,993 @@
+# Reference
+## Server
+<details><summary><code>client.server.<a href="/src/api/resources/server/client/Client.ts">getCapabilities</a>() -> TrueHarness.GetCapabilitiesResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Report optional runtime capabilities available in this server deployment.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.server.getCapabilities();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**requestOptions:** `ServerClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+## McpServers
+<details><summary><code>client.mcpServers.<a href="/src/api/resources/mcpServers/client/Client.ts">list</a>() -> TrueHarness.ListMcpServersResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.mcpServers.list();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**requestOptions:** `McpServersClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.mcpServers.<a href="/src/api/resources/mcpServers/client/Client.ts">listTools</a>(name) -> TrueHarness.ListMcpToolsResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.mcpServers.listTools("name");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**name:** `string` — MCP server name from mcp.yaml.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `McpServersClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+## Models
+<details><summary><code>client.models.<a href="/src/api/resources/models/client/Client.ts">list</a>() -> TrueHarness.ListModelsResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Models declared in models.yaml, reachable through the OpenAI-compatible API at the file's base_url.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.models.list();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**requestOptions:** `ModelsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+## Sessions
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">list</a>({ ...params }) -> core.Page&lt;TrueHarness.Session, TrueHarness.ListSessionsResponse&gt;</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.list();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.ListSessionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">create</a>({ ...params }) -> TrueHarness.GetSessionResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Create a session holding an inline agent spec. Turns are executed against this spec.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.create({
+ agentSpec: {
+ model: {
+ name: "name"
+ }
+ }
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.CreateSessionRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">get</a>(sessionId) -> TrueHarness.GetSessionResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Fetch a session by ID.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.get("sessionId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">update</a>(sessionId, { ...params }) -> TrueHarness.GetSessionResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.update("sessionId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.UpdateSessionRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">cancel</a>(sessionId, { ...params }) -> TrueHarness.CancelSessionResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Cancel the running last turn for a session.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.cancel("sessionId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.CancelSessionRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">listEvents</a>(sessionId, { ...params }) -> core.Page&lt;TrueHarness.SessionEventItem, TrueHarness.ListSessionEventsResponse&gt;</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.listEvents("sessionId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.ListEventsSessionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">listTurns</a>(sessionId, { ...params }) -> core.Page&lt;TrueHarness.Turn, TrueHarness.ListTurnsResponse&gt;</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+List turns for a session (newest first by default), token-paginated.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.listTurns("sessionId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.ListTurnsSessionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">createTurn</a>(sessionId, { ...params }) -> core.Stream&lt;TrueHarness.TurnStreamingEvent&gt;</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Create a turn within a session and stream its execution as Server-Sent Events.
+Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`).
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+const response = await client.sessions.createTurn("sessionId");
+for await (const item of response) {
+ console.log(item);
+}
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.CreateTurnRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">getTurn</a>(sessionId, turnId) -> TrueHarness.GetTurnResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Fetch a single turn by ID.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.getTurn("sessionId", "turnId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**turnId:** `string` — Turn identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.sessions.<a href="/src/api/resources/sessions/client/Client.ts">listTurnEvents</a>(sessionId, turnId, { ...params }) -> core.Page&lt;TrueHarness.SessionEvent, TrueHarness.ListTurnEventsResponse&gt;</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Paginated persisted events for a turn (insertion order by default).
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.sessions.listTurnEvents("sessionId", "turnId");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**sessionId:** `string` — Session identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**turnId:** `string` — Turn identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueHarness.ListTurnEventsSessionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SessionsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+## Skills
+<details><summary><code>client.skills.<a href="/src/api/resources/skills/client/Client.ts">list</a>() -> TrueHarness.ListSkillsResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Agent skills declared in skills.yaml.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.skills.list();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**requestOptions:** `SkillsClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
diff --git a/packages/sdk/scripts/rename-to-esm-files.js b/packages/sdk/scripts/rename-to-esm-files.js
new file mode 100644
index 000000000..0a03de137
--- /dev/null
+++ b/packages/sdk/scripts/rename-to-esm-files.js
@@ -0,0 +1,188 @@
+#!/usr/bin/env node
+
+const fs = require("fs").promises;
+const fsSync = require("fs");
+const path = require("path");
+
+const extensionMap = {
+ ".js": ".mjs",
+ ".d.ts": ".d.mts",
+};
+const oldExtensions = Object.keys(extensionMap);
+
+async function findFiles(rootPath) {
+ const files = [];
+
+ async function scan(directory) {
+ const entries = await fs.readdir(directory, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(directory, entry.name);
+
+ if (entry.isDirectory()) {
+ if (entry.name !== "node_modules" && !entry.name.startsWith(".")) {
+ await scan(fullPath);
+ }
+ } else if (entry.isFile()) {
+ if (oldExtensions.some((ext) => entry.name.endsWith(ext))) {
+ files.push(fullPath);
+ }
+ }
+ }
+ }
+
+ await scan(rootPath);
+ return files;
+}
+
+async function updateFiles(files) {
+ const updatedFiles = [];
+ for (const file of files) {
+ const updated = await updateFileContents(file);
+ updatedFiles.push(updated);
+ }
+
+ console.log(`Updated imports in ${updatedFiles.length} files.`);
+}
+
+const KNOWN_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".jsx", ".json", ".ts", ".mts", ".cts", ".tsx", ".node"]);
+
+function hasFileExtension(importPath) {
+ const basename = path.basename(importPath);
+ const dotIndex = basename.lastIndexOf(".");
+ if (dotIndex <= 0) {
+ return false;
+ }
+ return KNOWN_EXTENSIONS.has(basename.slice(dotIndex).toLowerCase());
+}
+
+function resolveExtensionlessImport(dir, importPath) {
+ const resolvedPath = path.resolve(dir, importPath);
+ if (fsSync.existsSync(`${resolvedPath}.js`)) {
+ return `${importPath}.mjs`;
+ }
+ const indexPath = path.join(resolvedPath, "index.js");
+ if (fsSync.existsSync(indexPath)) {
+ return `${importPath}/index.mjs`;
+ }
+ return null;
+}
+
+async function updateFileContents(file) {
+ const content = await fs.readFile(file, "utf8");
+ const dir = path.dirname(file);
+
+ let newContent = content;
+ // Update each extension type defined in the map
+ for (const [oldExt, newExt] of Object.entries(extensionMap)) {
+ // Handle static imports/exports
+ const staticRegex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g");
+ newContent = newContent.replace(staticRegex, `$1$2$3${newExt}$5`);
+
+ // Handle dynamic imports (yield import, await import, regular import())
+ const dynamicRegex = new RegExp(
+ `(yield\\s+import|await\\s+import|import)\\s*\\(\\s*['"](\\.\\.\?\\/[^'"]+)(\\${oldExt})['"]\\s*\\)`,
+ "g",
+ );
+ newContent = newContent.replace(dynamicRegex, `$1("$2${newExt}")`);
+ }
+
+ // Handle extensionless relative imports (e.g. from "./oauth" or from "../utils").
+ // These violate the ESM spec and break Node's ESM loader and Turbopack.
+ const staticExtensionless = /(import|export)(.+from\s+['"])(\.\.?\/[^'"]+?)(['"])/g;
+ const staticReplacements = [];
+ let match;
+ while ((match = staticExtensionless.exec(newContent)) !== null) {
+ const importPath = match[3];
+ if (hasFileExtension(importPath)) continue;
+ const resolved = resolveExtensionlessImport(dir, importPath);
+ if (resolved != null) {
+ staticReplacements.push({
+ start: match.index,
+ end: match.index + match[0].length,
+ replacement: `${match[1]}${match[2]}${resolved}${match[4]}`,
+ });
+ }
+ }
+ for (const { start, end, replacement } of staticReplacements.reverse()) {
+ newContent = newContent.slice(0, start) + replacement + newContent.slice(end);
+ }
+
+ // Handle extensionless dynamic imports
+ const dynamicExtensionless = /(yield\s+import|await\s+import|import)\s*\(\s*['"](\.\.?\/[^'"]+?)['"]\s*\)/g;
+ const dynamicReplacements = [];
+ while ((match = dynamicExtensionless.exec(newContent)) !== null) {
+ const importPath = match[2];
+ if (hasFileExtension(importPath)) continue;
+ const resolved = resolveExtensionlessImport(dir, importPath);
+ if (resolved != null) {
+ dynamicReplacements.push({
+ start: match.index,
+ end: match.index + match[0].length,
+ replacement: `${match[1]}("${resolved}")`,
+ });
+ }
+ }
+ for (const { start, end, replacement } of dynamicReplacements.reverse()) {
+ newContent = newContent.slice(0, start) + replacement + newContent.slice(end);
+ }
+
+ if (content !== newContent) {
+ await fs.writeFile(file, newContent, "utf8");
+ return true;
+ }
+ return false;
+}
+
+async function renameFiles(files) {
+ let counter = 0;
+ for (const file of files) {
+ const ext = oldExtensions.find((ext) => file.endsWith(ext));
+ const newExt = extensionMap[ext];
+
+ if (newExt) {
+ const newPath = file.slice(0, -ext.length) + newExt;
+ await fs.rename(file, newPath);
+ counter++;
+ }
+ }
+
+ console.log(`Renamed ${counter} files.`);
+}
+
+async function main() {
+ try {
+ const targetDir = process.argv[2];
+ if (!targetDir) {
+ console.error("Please provide a target directory");
+ process.exit(1);
+ }
+
+ const targetPath = path.resolve(targetDir);
+ const targetStats = await fs.stat(targetPath);
+
+ if (!targetStats.isDirectory()) {
+ console.error("The provided path is not a directory");
+ process.exit(1);
+ }
+
+ console.log(`Scanning directory: ${targetDir}`);
+
+ const files = await findFiles(targetDir);
+
+ if (files.length === 0) {
+ console.log("No matching files found.");
+ process.exit(0);
+ }
+
+ console.log(`Found ${files.length} files.`);
+ await updateFiles(files);
+ await renameFiles(files);
+ console.log("\nDone!");
+ } catch (error) {
+ console.error("An error occurred:", error.message);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/packages/sdk/src/BaseClient.ts b/packages/sdk/src/BaseClient.ts
new file mode 100644
index 000000000..bb278e898
--- /dev/null
+++ b/packages/sdk/src/BaseClient.ts
@@ -0,0 +1,66 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import { mergeHeaders } from "./core/headers.js";
+import * as core from "./core/index.js";
+
+export interface BaseClientOptions {
+ environment: core.Supplier<string>;
+ /** Specify a custom URL to connect the client to. */
+ baseUrl?: core.Supplier<string>;
+ /** Additional headers to include in requests. */
+ headers?: Record<string, string | core.Supplier<string | null | undefined> | null | undefined>;
+ /** The default maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** The default number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** Provide a custom fetch implementation. Useful for platforms that don't have a built-in fetch or need a custom implementation. */
+ fetch?: typeof fetch;
+ fetcher?: core.FetchFunction;
+ /** Configure logging for the client. */
+ logging?: core.logging.LogConfig | core.logging.Logger;
+ /** Default options for SSE stream reconnection behavior. Has no effect on non-resumable endpoints. */
+ stream?: { reconnectionEnabled?: boolean; maxReconnectionAttempts?: number };
+}
+
+export interface BaseRequestOptions {
+ /** The maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** The number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** A hook to abort the request. */
+ abortSignal?: AbortSignal;
+ /** Additional query string parameters to include in the request. */
+ queryParams?: Record<string, unknown>;
+ /** A dictionary containing additional parameters to spread into the request's body. */
+ additionalBodyParameters?: Record<string, unknown>;
+ /** Additional headers to include in the request. */
+ headers?: Record<string, string | core.Supplier<string | null | undefined> | null | undefined>;
+ /** Options for SSE stream reconnection behavior. Has no effect on non-resumable endpoints. */
+ stream?: { reconnectionEnabled?: boolean; maxReconnectionAttempts?: number };
+}
+
+export type NormalizedClientOptions<T extends BaseClientOptions = BaseClientOptions> = T & {
+ logging: core.logging.Logger;
+};
+
+export function normalizeClientOptions<T extends BaseClientOptions = BaseClientOptions>(
+ options: T,
+): NormalizedClientOptions<T> {
+ const headers = mergeHeaders(
+ {
+ "X-Fern-Language": "JavaScript",
+ "X-Fern-SDK-Name": "trueharness",
+ "X-Fern-SDK-Version": "0.0.0",
+ "User-Agent": "trueharness/0.0.0",
+ "X-Fern-Runtime": core.RUNTIME.type,
+ "X-Fern-Runtime-Version": core.RUNTIME.version,
+ },
+ options?.headers,
+ );
+
+ return {
+ ...options,
+ logging: core.logging.createLogger(options?.logging),
+ headers,
+ } as NormalizedClientOptions<T>;
+}
diff --git a/packages/sdk/src/Client.ts b/packages/sdk/src/Client.ts
new file mode 100644
index 000000000..e543a13fd
--- /dev/null
+++ b/packages/sdk/src/Client.ts
@@ -0,0 +1,79 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import { McpServersClient } from "./api/resources/mcpServers/client/Client.js";
+import { ModelsClient } from "./api/resources/models/client/Client.js";
+import { ServerClient } from "./api/resources/server/client/Client.js";
+import { SessionsClient } from "./api/resources/sessions/client/Client.js";
+import { SkillsClient } from "./api/resources/skills/client/Client.js";
+import type { BaseClientOptions, BaseRequestOptions } from "./BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "./BaseClient.js";
+import * as core from "./core/index.js";
+
+export declare namespace TrueHarness {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class TrueHarness {
+ protected readonly _options: NormalizedClientOptions<TrueHarness.Options>;
+ protected _server: ServerClient | undefined;
+ protected _mcpServers: McpServersClient | undefined;
+ protected _models: ModelsClient | undefined;
+ protected _sessions: SessionsClient | undefined;
+ protected _skills: SkillsClient | undefined;
+
+ constructor(options: TrueHarness.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ public get server(): ServerClient {
+ return (this._server ??= new ServerClient(this._options));
+ }
+
+ public get mcpServers(): McpServersClient {
+ return (this._mcpServers ??= new McpServersClient(this._options));
+ }
+
+ public get models(): ModelsClient {
+ return (this._models ??= new ModelsClient(this._options));
+ }
+
+ public get sessions(): SessionsClient {
+ return (this._sessions ??= new SessionsClient(this._options));
+ }
+
+ public get skills(): SkillsClient {
+ return (this._skills ??= new SkillsClient(this._options));
+ }
+
+ /**
+ * Make a passthrough request using the SDK's configured auth, retry, logging, etc.
+ * This is useful for making requests to endpoints not yet supported in the SDK.
+ * The input can be a URL string, URL object, or Request object. Relative paths are resolved against the configured base URL.
+ *
+ * @param {Request | string | URL} input - The URL, path, or Request object.
+ * @param {RequestInit} init - Standard fetch RequestInit options.
+ * @param {core.PassthroughRequest.RequestOptions} requestOptions - Per-request overrides (timeout, retries, headers, abort signal).
+ * @returns {Promise<Response>} A standard Response object.
+ */
+ public async fetch(
+ input: Request | string | URL,
+ init?: RequestInit,
+ requestOptions?: core.PassthroughRequest.RequestOptions,
+ ): Promise<Response> {
+ return core.makePassthroughRequest(
+ input,
+ init,
+ {
+ baseUrl: this._options.baseUrl ?? this._options.environment,
+ headers: this._options.headers,
+ timeoutInSeconds: this._options.timeoutInSeconds,
+ maxRetries: this._options.maxRetries,
+ fetch: this._options.fetch,
+ logging: this._options.logging,
+ },
+ requestOptions,
+ );
+ }
+}
diff --git a/packages/sdk/src/api/errors/BadGatewayError.ts b/packages/sdk/src/api/errors/BadGatewayError.ts
new file mode 100644
index 000000000..edd457719
--- /dev/null
+++ b/packages/sdk/src/api/errors/BadGatewayError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class BadGatewayError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "BadGatewayError",
+ statusCode: 502,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "BadGatewayError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/BadRequestError.ts b/packages/sdk/src/api/errors/BadRequestError.ts
new file mode 100644
index 000000000..ba3649881
--- /dev/null
+++ b/packages/sdk/src/api/errors/BadRequestError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class BadRequestError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "BadRequestError",
+ statusCode: 400,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "BadRequestError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/NotFoundError.ts b/packages/sdk/src/api/errors/NotFoundError.ts
new file mode 100644
index 000000000..d0ea22587
--- /dev/null
+++ b/packages/sdk/src/api/errors/NotFoundError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class NotFoundError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "NotFoundError",
+ statusCode: 404,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "NotFoundError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/PreconditionFailedError.ts b/packages/sdk/src/api/errors/PreconditionFailedError.ts
new file mode 100644
index 000000000..9671dcafd
--- /dev/null
+++ b/packages/sdk/src/api/errors/PreconditionFailedError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class PreconditionFailedError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "PreconditionFailedError",
+ statusCode: 412,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "PreconditionFailedError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/UnauthorizedError.ts b/packages/sdk/src/api/errors/UnauthorizedError.ts
new file mode 100644
index 000000000..88ce2d9e5
--- /dev/null
+++ b/packages/sdk/src/api/errors/UnauthorizedError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class UnauthorizedError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "UnauthorizedError",
+ statusCode: 401,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "UnauthorizedError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/UnprocessableEntityError.ts b/packages/sdk/src/api/errors/UnprocessableEntityError.ts
new file mode 100644
index 000000000..101cf1533
--- /dev/null
+++ b/packages/sdk/src/api/errors/UnprocessableEntityError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../../core/index.js";
+import * as errors from "../../errors/index.js";
+import type * as TrueHarness from "../index.js";
+
+export class UnprocessableEntityError extends errors.TrueHarnessError {
+ public declare readonly body: TrueHarness.RequestErrorResponse;
+
+ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {
+ super({
+ message: "UnprocessableEntityError",
+ statusCode: 422,
+ body: body,
+ rawResponse: rawResponse,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "UnprocessableEntityError";
+ }
+}
diff --git a/packages/sdk/src/api/errors/index.ts b/packages/sdk/src/api/errors/index.ts
new file mode 100644
index 000000000..925fe86d6
--- /dev/null
+++ b/packages/sdk/src/api/errors/index.ts
@@ -0,0 +1,6 @@
+export * from "./BadGatewayError.js";
+export * from "./BadRequestError.js";
+export * from "./NotFoundError.js";
+export * from "./PreconditionFailedError.js";
+export * from "./UnauthorizedError.js";
+export * from "./UnprocessableEntityError.js";
diff --git a/packages/sdk/src/api/index.ts b/packages/sdk/src/api/index.ts
new file mode 100644
index 000000000..6ed44b0bf
--- /dev/null
+++ b/packages/sdk/src/api/index.ts
@@ -0,0 +1,3 @@
+export * from "./errors/index.js";
+export * from "./resources/index.js";
+export * from "./types/index.js";
diff --git a/packages/sdk/src/api/resources/index.ts b/packages/sdk/src/api/resources/index.ts
new file mode 100644
index 000000000..3d67338a4
--- /dev/null
+++ b/packages/sdk/src/api/resources/index.ts
@@ -0,0 +1,6 @@
+export * as mcpServers from "./mcpServers/index.js";
+export * as models from "./models/index.js";
+export * as server from "./server/index.js";
+export * from "./sessions/client/requests/index.js";
+export * as sessions from "./sessions/index.js";
+export * as skills from "./skills/index.js";
diff --git a/packages/sdk/src/api/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/mcpServers/client/Client.ts
new file mode 100644
index 000000000..d6a06f359
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/client/Client.ts
@@ -0,0 +1,186 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import * as TrueHarness from "../../../index.js";
+
+export declare namespace McpServersClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class McpServersClient {
+ protected readonly _options: NormalizedClientOptions<McpServersClient.Options>;
+
+ constructor(options: McpServersClient.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ /**
+ * MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.
+ *
+ * @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.mcpServers.list()
+ */
+ public list(
+ requestOptions?: McpServersClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.ListMcpServersResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
+ }
+
+ private async __list(
+ requestOptions?: McpServersClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.ListMcpServersResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/mcp-servers",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListMcpServersResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/mcp-servers");
+ }
+
+ /**
+ * All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.
+ *
+ * @param {string} name - MCP server name from mcp.yaml.
+ * @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.UnauthorizedError}
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link TrueHarness.BadGatewayError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.mcpServers.listTools("name")
+ */
+ public listTools(
+ name: string,
+ requestOptions?: McpServersClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.ListMcpToolsResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__listTools(name, requestOptions));
+ }
+
+ private async __listTools(
+ name: string,
+ requestOptions?: McpServersClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.ListMcpToolsResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/mcp-servers/${core.url.encodePathParam(name)}/tools`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListMcpToolsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 401:
+ throw new TrueHarness.UnauthorizedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 502:
+ throw new TrueHarness.BadGatewayError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/mcp-servers/{name}/tools");
+ }
+}
diff --git a/packages/sdk/src/api/resources/mcpServers/client/index.ts b/packages/sdk/src/api/resources/mcpServers/client/index.ts
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/packages/sdk/src/api/resources/mcpServers/exports.ts b/packages/sdk/src/api/resources/mcpServers/exports.ts
new file mode 100644
index 000000000..3a0df5f61
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { McpServersClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/mcpServers/index.ts b/packages/sdk/src/api/resources/mcpServers/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/models/client/Client.ts b/packages/sdk/src/api/resources/models/client/Client.ts
new file mode 100644
index 000000000..0de585374
--- /dev/null
+++ b/packages/sdk/src/api/resources/models/client/Client.ts
@@ -0,0 +1,84 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import type * as TrueHarness from "../../../index.js";
+
+export declare namespace ModelsClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class ModelsClient {
+ protected readonly _options: NormalizedClientOptions<ModelsClient.Options>;
+
+ constructor(options: ModelsClient.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ /**
+ * Models declared in models.yaml, reachable through the OpenAI-compatible API at the file's base_url.
+ *
+ * @param {ModelsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.models.list()
+ */
+ public list(
+ requestOptions?: ModelsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.ListModelsResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
+ }
+
+ private async __list(
+ requestOptions?: ModelsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.ListModelsResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/models",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListModelsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/models");
+ }
+}
diff --git a/packages/sdk/src/api/resources/models/client/index.ts b/packages/sdk/src/api/resources/models/client/index.ts
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/sdk/src/api/resources/models/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/packages/sdk/src/api/resources/models/exports.ts b/packages/sdk/src/api/resources/models/exports.ts
new file mode 100644
index 000000000..32c5deac0
--- /dev/null
+++ b/packages/sdk/src/api/resources/models/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { ModelsClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/models/index.ts b/packages/sdk/src/api/resources/models/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/api/resources/models/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/server/client/Client.ts b/packages/sdk/src/api/resources/server/client/Client.ts
new file mode 100644
index 000000000..78783ce54
--- /dev/null
+++ b/packages/sdk/src/api/resources/server/client/Client.ts
@@ -0,0 +1,84 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import type * as TrueHarness from "../../../index.js";
+
+export declare namespace ServerClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class ServerClient {
+ protected readonly _options: NormalizedClientOptions<ServerClient.Options>;
+
+ constructor(options: ServerClient.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ /**
+ * Report optional runtime capabilities available in this server deployment.
+ *
+ * @param {ServerClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.server.getCapabilities()
+ */
+ public getCapabilities(
+ requestOptions?: ServerClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.GetCapabilitiesResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__getCapabilities(requestOptions));
+ }
+
+ private async __getCapabilities(
+ requestOptions?: ServerClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.GetCapabilitiesResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/capabilities",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.GetCapabilitiesResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/capabilities");
+ }
+}
diff --git a/packages/sdk/src/api/resources/server/client/index.ts b/packages/sdk/src/api/resources/server/client/index.ts
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/sdk/src/api/resources/server/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/packages/sdk/src/api/resources/server/exports.ts b/packages/sdk/src/api/resources/server/exports.ts
new file mode 100644
index 000000000..8f4a0a141
--- /dev/null
+++ b/packages/sdk/src/api/resources/server/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { ServerClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/server/index.ts b/packages/sdk/src/api/resources/server/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/api/resources/server/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/sessions/client/Client.ts b/packages/sdk/src/api/resources/sessions/client/Client.ts
new file mode 100644
index 000000000..61541fcca
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/Client.ts
@@ -0,0 +1,1116 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { mergeAdditionalBodyParameters } from "../../../../core/requestBody.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import * as TrueHarness from "../../../index.js";
+
+export declare namespace SessionsClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class SessionsClient {
+ protected readonly _options: NormalizedClientOptions<SessionsClient.Options>;
+
+ constructor(options: SessionsClient.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ /**
+ * List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.
+ *
+ * @param {TrueHarness.ListSessionsRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.list()
+ */
+ public async list(
+ request: TrueHarness.ListSessionsRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.Page<TrueHarness.Session, TrueHarness.ListSessionsResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueHarness.ListSessionsRequest,
+ ): Promise<core.WithRawResponse<TrueHarness.ListSessionsResponse>> => {
+ const { limit = 10, order, pageToken, startTimestamp, endTimestamp } = request;
+ const _queryParams: Record<string, unknown> = {
+ limit,
+ order:
+ order != null
+ ? serializers.ListSessionsOrder.jsonOrThrow(order, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ })
+ : undefined,
+ page_token: pageToken,
+ start_timestamp: startTimestamp,
+ end_timestamp: endTimestamp,
+ };
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ requestOptions?.headers,
+ );
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/sessions",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListSessionsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/sessions");
+ },
+ );
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueHarness.Session, TrueHarness.ListSessionsResponse>({
+ response: dataWithRawResponse.data,
+ rawResponse: dataWithRawResponse.rawResponse,
+ hasNextPage: (response) =>
+ response?.pagination.nextPageToken != null &&
+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
+ getItems: (response) => response?.data ?? [],
+ loadPage: (response) => {
+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
+ },
+ });
+ }
+
+ /**
+ * Create a session holding an inline agent spec. Turns are executed against this spec.
+ *
+ * @param {TrueHarness.CreateSessionRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link TrueHarness.UnprocessableEntityError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.create({
+ * agentSpec: {
+ * model: {
+ * name: "name"
+ * }
+ * }
+ * })
+ */
+ public create(
+ request: TrueHarness.CreateSessionRequest,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.GetSessionResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
+ }
+
+ private async __create(
+ request: TrueHarness.CreateSessionRequest,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.GetSessionResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/sessions",
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.CreateSessionRequest.jsonOrThrow(request, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ }),
+ requestOptions?.additionalBodyParameters,
+ ),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.GetSessionResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 422:
+ throw new TrueHarness.UnprocessableEntityError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/sessions");
+ }
+
+ /**
+ * Fetch a session by ID.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.get("sessionId")
+ */
+ public get(
+ sessionId: string,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.GetSessionResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__get(sessionId, requestOptions));
+ }
+
+ private async __get(
+ sessionId: string,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.GetSessionResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.GetSessionResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/sessions/{sessionId}");
+ }
+
+ /**
+ * Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {TrueHarness.UpdateSessionRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link TrueHarness.UnprocessableEntityError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.update("sessionId")
+ */
+ public update(
+ sessionId: string,
+ request: TrueHarness.UpdateSessionRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.GetSessionResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__update(sessionId, request, requestOptions));
+ }
+
+ private async __update(
+ sessionId: string,
+ request: TrueHarness.UpdateSessionRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.GetSessionResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}`,
+ ),
+ method: "PATCH",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.UpdateSessionRequest.jsonOrThrow(request, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ }),
+ requestOptions?.additionalBodyParameters,
+ ),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.GetSessionResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 422:
+ throw new TrueHarness.UnprocessableEntityError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "PATCH", "/v1/sessions/{sessionId}");
+ }
+
+ /**
+ * Cancel the running last turn for a session.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {TrueHarness.CancelSessionRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link TrueHarness.PreconditionFailedError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.cancel("sessionId")
+ */
+ public cancel(
+ sessionId: string,
+ request: TrueHarness.CancelSessionRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.CancelSessionResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__cancel(sessionId, request, requestOptions));
+ }
+
+ private async __cancel(
+ sessionId: string,
+ request: TrueHarness.CancelSessionRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.CancelSessionResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/cancel`,
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.CancelSessionRequest.jsonOrThrow(request, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ }),
+ requestOptions?.additionalBodyParameters,
+ ),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.CancelSessionResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 412:
+ throw new TrueHarness.PreconditionFailedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "POST",
+ "/v1/sessions/{sessionId}/cancel",
+ );
+ }
+
+ /**
+ * List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {TrueHarness.ListEventsSessionsRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.listEvents("sessionId")
+ */
+ public async listEvents(
+ sessionId: string,
+ request: TrueHarness.ListEventsSessionsRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.Page<TrueHarness.SessionEventItem, TrueHarness.ListSessionEventsResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueHarness.ListEventsSessionsRequest,
+ ): Promise<core.WithRawResponse<TrueHarness.ListSessionEventsResponse>> => {
+ const { pageToken, lastTurnId, limit = 100 } = request;
+ const _queryParams: Record<string, unknown> = {
+ page_token: pageToken,
+ last_turn_id: lastTurnId,
+ limit,
+ };
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ requestOptions?.headers,
+ );
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/events`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListSessionEventsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "GET",
+ "/v1/sessions/{sessionId}/events",
+ );
+ },
+ );
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueHarness.SessionEventItem, TrueHarness.ListSessionEventsResponse>({
+ response: dataWithRawResponse.data,
+ rawResponse: dataWithRawResponse.rawResponse,
+ hasNextPage: (response) =>
+ response?.pagination.nextPageToken != null &&
+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
+ getItems: (response) => response?.data ?? [],
+ loadPage: (response) => {
+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
+ },
+ });
+ }
+
+ /**
+ * List turns for a session (newest first by default), token-paginated.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {TrueHarness.ListTurnsSessionsRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.listTurns("sessionId")
+ */
+ public async listTurns(
+ sessionId: string,
+ request: TrueHarness.ListTurnsSessionsRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.Page<TrueHarness.Turn, TrueHarness.ListTurnsResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueHarness.ListTurnsSessionsRequest,
+ ): Promise<core.WithRawResponse<TrueHarness.ListTurnsResponse>> => {
+ const { limit = 10, pageToken } = request;
+ const _queryParams: Record<string, unknown> = {
+ limit,
+ page_token: pageToken,
+ };
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ requestOptions?.headers,
+ );
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/turns`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListTurnsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "GET",
+ "/v1/sessions/{sessionId}/turns",
+ );
+ },
+ );
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueHarness.Turn, TrueHarness.ListTurnsResponse>({
+ response: dataWithRawResponse.data,
+ rawResponse: dataWithRawResponse.rawResponse,
+ hasNextPage: (response) =>
+ response?.pagination.nextPageToken != null &&
+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
+ getItems: (response) => response?.data ?? [],
+ loadPage: (response) => {
+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
+ },
+ });
+ }
+
+ /**
+ * Create a turn within a session and stream its execution as Server-Sent Events.
+ * Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`).
+ */
+ public createTurn(
+ sessionId: string,
+ request: TrueHarness.CreateTurnRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<core.Stream<TrueHarness.TurnStreamingEvent>> {
+ return core.HttpResponsePromise.fromPromise(this.__createTurn(sessionId, request, requestOptions));
+ }
+
+ private async __createTurn(
+ sessionId: string,
+ request: TrueHarness.CreateTurnRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<core.Stream<TrueHarness.TurnStreamingEvent>>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)<ReadableStream>({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/turns`,
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.CreateTurnRequest.jsonOrThrow(request, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ }),
+ requestOptions?.additionalBodyParameters,
+ ),
+ responseType: "sse",
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: new core.Stream({
+ stream: _response.body,
+ parse: async (data) => {
+ return serializers.TurnStreamingEvent.parseOrThrow(data, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ });
+ },
+ signal: requestOptions?.abortSignal,
+ eventShape: {
+ type: "sse",
+ },
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 412:
+ throw new TrueHarness.PreconditionFailedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "POST",
+ "/v1/sessions/{sessionId}/turns",
+ );
+ }
+
+ /**
+ * Fetch a single turn by ID.
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {string} turnId - Turn identifier.
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.getTurn("sessionId", "turnId")
+ */
+ public getTurn(
+ sessionId: string,
+ turnId: string,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.GetTurnResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__getTurn(sessionId, turnId, requestOptions));
+ }
+
+ private async __getTurn(
+ sessionId: string,
+ turnId: string,
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.GetTurnResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/turns/${core.url.encodePathParam(turnId)}`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.GetTurnResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "GET",
+ "/v1/sessions/{sessionId}/turns/{turnId}",
+ );
+ }
+
+ /**
+ * Paginated persisted events for a turn (insertion order by default).
+ *
+ * @param {string} sessionId - Session identifier.
+ * @param {string} turnId - Turn identifier.
+ * @param {TrueHarness.ListTurnEventsSessionsRequest} request
+ * @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.BadRequestError}
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.sessions.listTurnEvents("sessionId", "turnId")
+ */
+ public async listTurnEvents(
+ sessionId: string,
+ turnId: string,
+ request: TrueHarness.ListTurnEventsSessionsRequest = {},
+ requestOptions?: SessionsClient.RequestOptions,
+ ): Promise<core.Page<TrueHarness.SessionEvent, TrueHarness.ListTurnEventsResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueHarness.ListTurnEventsSessionsRequest,
+ ): Promise<core.WithRawResponse<TrueHarness.ListTurnEventsResponse>> => {
+ const { limit = 25, pageToken, order } = request;
+ const _queryParams: Record<string, unknown> = {
+ limit,
+ page_token: pageToken,
+ order:
+ order != null
+ ? serializers.ListTurnEventsOrder.jsonOrThrow(order, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ })
+ : undefined,
+ };
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ this._options?.headers,
+ requestOptions?.headers,
+ );
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ `v1/sessions/${core.url.encodePathParam(sessionId)}/turns/${core.url.encodePathParam(turnId)}/events`,
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListTurnEventsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueHarness.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueHarness.NotFoundError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "GET",
+ "/v1/sessions/{sessionId}/turns/{turnId}/events",
+ );
+ },
+ );
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueHarness.SessionEvent, TrueHarness.ListTurnEventsResponse>({
+ response: dataWithRawResponse.data,
+ rawResponse: dataWithRawResponse.rawResponse,
+ hasNextPage: (response) =>
+ response?.pagination.nextPageToken != null &&
+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
+ getItems: (response) => response?.data ?? [],
+ loadPage: (response) => {
+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
+ },
+ });
+ }
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/index.ts b/packages/sdk/src/api/resources/sessions/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/CancelSessionRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/CancelSessionRequest.ts
new file mode 100644
index 000000000..6a6fabb0d
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/CancelSessionRequest.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {}
+ */
+export type CancelSessionRequest = {};
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts
new file mode 100644
index 000000000..6fd0540df
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts
@@ -0,0 +1,17 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../index.js";
+
+/**
+ * @example
+ * {
+ * agentSpec: {
+ * model: {
+ * name: "name"
+ * }
+ * }
+ * }
+ */
+export interface CreateSessionRequest {
+ agentSpec: TrueHarness.AgentSpec;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/CreateTurnRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/CreateTurnRequest.ts
new file mode 100644
index 000000000..4069168b9
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/CreateTurnRequest.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../index.js";
+
+/**
+ * @example
+ * {}
+ */
+export interface CreateTurnRequest {
+ input?: TrueHarness.TurnInputItem[];
+ previousTurnId?: TrueHarness.PreviousTurnIdInput | null;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListEventsSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListEventsSessionsRequest.ts
new file mode 100644
index 000000000..85b649636
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListEventsSessionsRequest.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {}
+ */
+export interface ListEventsSessionsRequest {
+ /** Pagination cursor from `pagination.next_page_token`. It retains the branch anchor turn and returns older events toward the session start. */
+ pageToken?: string;
+ /** Newest turn in the listing window (initial load only; ignored when `page_token` is set). Lists that turn and its ancestors, newest events first. Omit to use the session last turn. */
+ lastTurnId?: string;
+ /** Max events per response. Default 100, max 100. */
+ limit?: number;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
new file mode 100644
index 000000000..bdc6cb22b
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../index.js";
+
+/**
+ * @example
+ * {}
+ */
+export interface ListSessionsRequest {
+ /** Page size. Defaults to 10, max 100. */
+ limit?: number;
+ /** Sort sessions by creation time. Defaults to "desc". */
+ order?: TrueHarness.ListSessionsOrder;
+ /** Opaque token from a previous response `next_page_token`. */
+ pageToken?: string;
+ /** Inclusive lower bound on `created_at` (ISO-8601). */
+ startTimestamp?: string;
+ /** Inclusive upper bound on `created_at` (ISO-8601). */
+ endTimestamp?: string;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListTurnEventsSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListTurnEventsSessionsRequest.ts
new file mode 100644
index 000000000..07bce4b0e
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListTurnEventsSessionsRequest.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../index.js";
+
+/**
+ * @example
+ * {}
+ */
+export interface ListTurnEventsSessionsRequest {
+ /** Max events per response. Default 25, max 100. */
+ limit?: number;
+ /** Opaque token from a previous response `next_page_token`. */
+ pageToken?: string;
+ /** Sort events by insertion order. Defaults to "asc". */
+ order?: TrueHarness.ListTurnEventsOrder;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListTurnsSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListTurnsSessionsRequest.ts
new file mode 100644
index 000000000..6ee16708e
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListTurnsSessionsRequest.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {}
+ */
+export interface ListTurnsSessionsRequest {
+ /** Page size. Defaults to 10, max 100. */
+ limit?: number;
+ /** Opaque token from a previous response `next_page_token`. */
+ pageToken?: string;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts
new file mode 100644
index 000000000..d85dc3bae
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../index.js";
+
+/**
+ * @example
+ * {}
+ */
+export interface UpdateSessionRequest {
+ agentSpec?: TrueHarness.AgentSpec;
+}
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/index.ts b/packages/sdk/src/api/resources/sessions/client/requests/index.ts
new file mode 100644
index 000000000..8e2942151
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/client/requests/index.ts
@@ -0,0 +1,8 @@
+export type { CancelSessionRequest } from "./CancelSessionRequest.js";
+export type { CreateSessionRequest } from "./CreateSessionRequest.js";
+export type { CreateTurnRequest } from "./CreateTurnRequest.js";
+export type { ListEventsSessionsRequest } from "./ListEventsSessionsRequest.js";
+export type { ListSessionsRequest } from "./ListSessionsRequest.js";
+export type { ListTurnEventsSessionsRequest } from "./ListTurnEventsSessionsRequest.js";
+export type { ListTurnsSessionsRequest } from "./ListTurnsSessionsRequest.js";
+export type { UpdateSessionRequest } from "./UpdateSessionRequest.js";
diff --git a/packages/sdk/src/api/resources/sessions/exports.ts b/packages/sdk/src/api/resources/sessions/exports.ts
new file mode 100644
index 000000000..989fb8a75
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { SessionsClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/sessions/index.ts b/packages/sdk/src/api/resources/sessions/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/api/resources/sessions/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/skills/client/Client.ts b/packages/sdk/src/api/resources/skills/client/Client.ts
new file mode 100644
index 000000000..65b0932b4
--- /dev/null
+++ b/packages/sdk/src/api/resources/skills/client/Client.ts
@@ -0,0 +1,84 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import type * as TrueHarness from "../../../index.js";
+
+export declare namespace SkillsClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class SkillsClient {
+ protected readonly _options: NormalizedClientOptions<SkillsClient.Options>;
+
+ constructor(options: SkillsClient.Options) {
+ this._options = normalizeClientOptions(options);
+ }
+
+ /**
+ * Agent skills declared in skills.yaml.
+ *
+ * @param {SkillsClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.skills.list()
+ */
+ public list(
+ requestOptions?: SkillsClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.ListSkillsResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));
+ }
+
+ private async __list(
+ requestOptions?: SkillsClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueHarness.ListSkillsResponse>> {
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "v1/skills",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListSkillsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ throw new errors.TrueHarnessError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/skills");
+ }
+}
diff --git a/packages/sdk/src/api/resources/skills/client/index.ts b/packages/sdk/src/api/resources/skills/client/index.ts
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/sdk/src/api/resources/skills/client/index.ts
@@ -0,0 +1 @@
+export {};
diff --git a/packages/sdk/src/api/resources/skills/exports.ts b/packages/sdk/src/api/resources/skills/exports.ts
new file mode 100644
index 000000000..b13b787d5
--- /dev/null
+++ b/packages/sdk/src/api/resources/skills/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { SkillsClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/resources/skills/index.ts b/packages/sdk/src/api/resources/skills/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/api/resources/skills/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/api/types/ActionRequiredEvent.ts b/packages/sdk/src/api/types/ActionRequiredEvent.ts
new file mode 100644
index 000000000..a77414762
--- /dev/null
+++ b/packages/sdk/src/api/types/ActionRequiredEvent.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ActionRequiredEvent =
+ | TrueHarness.McpAuthRequiredEvent
+ | TrueHarness.ToolApprovalRequiredEvent
+ | TrueHarness.ToolResponseRequiredEvent;
diff --git a/packages/sdk/src/api/types/AgentInfo.ts b/packages/sdk/src/api/types/AgentInfo.ts
new file mode 100644
index 000000000..aa021cb62
--- /dev/null
+++ b/packages/sdk/src/api/types/AgentInfo.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface AgentInfo {
+ input: string;
+ model?: string;
+ name: string;
+ type: "dynamic";
+}
diff --git a/packages/sdk/src/api/types/AgentParent.ts b/packages/sdk/src/api/types/AgentParent.ts
new file mode 100644
index 000000000..95068fe93
--- /dev/null
+++ b/packages/sdk/src/api/types/AgentParent.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface AgentParent {
+ threadId: string;
+ toolCallId: string;
+}
diff --git a/packages/sdk/src/api/types/AgentSpec.ts b/packages/sdk/src/api/types/AgentSpec.ts
new file mode 100644
index 000000000..65aab7004
--- /dev/null
+++ b/packages/sdk/src/api/types/AgentSpec.ts
@@ -0,0 +1,17 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+/**
+ * Agent Definition
+ */
+export interface AgentSpec {
+ config?: TrueHarness.RuntimeConfig;
+ instructions?: string;
+ mcpServers?: TrueHarness.McpServer[];
+ messages?: TrueHarness.AgentSpecUserMessage[];
+ model: TrueHarness.Model;
+ responseFormat?: TrueHarness.ResponseFormat;
+ skills?: TrueHarness.SkillMount[];
+ variables?: Record<string, string>;
+}
diff --git a/packages/sdk/src/api/types/AgentSpecUserMessage.ts b/packages/sdk/src/api/types/AgentSpecUserMessage.ts
new file mode 100644
index 000000000..feda5f0e1
--- /dev/null
+++ b/packages/sdk/src/api/types/AgentSpecUserMessage.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface AgentSpecUserMessage {
+ content: string;
+ type: "user.message";
+}
diff --git a/packages/sdk/src/api/types/ApprovalAllow.ts b/packages/sdk/src/api/types/ApprovalAllow.ts
new file mode 100644
index 000000000..e35a741a4
--- /dev/null
+++ b/packages/sdk/src/api/types/ApprovalAllow.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ApprovalAllow {
+ status: "allow";
+}
diff --git a/packages/sdk/src/api/types/ApprovalDecision.ts b/packages/sdk/src/api/types/ApprovalDecision.ts
new file mode 100644
index 000000000..db07f1289
--- /dev/null
+++ b/packages/sdk/src/api/types/ApprovalDecision.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ApprovalDecision = TrueHarness.ApprovalAllow | TrueHarness.ApprovalDeny;
diff --git a/packages/sdk/src/api/types/ApprovalDeny.ts b/packages/sdk/src/api/types/ApprovalDeny.ts
new file mode 100644
index 000000000..690569d80
--- /dev/null
+++ b/packages/sdk/src/api/types/ApprovalDeny.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ApprovalDeny {
+ reason?: string;
+ status: "deny";
+}
diff --git a/packages/sdk/src/api/types/AskUserQuestionsConfig.ts b/packages/sdk/src/api/types/AskUserQuestionsConfig.ts
new file mode 100644
index 000000000..55a974aa2
--- /dev/null
+++ b/packages/sdk/src/api/types/AskUserQuestionsConfig.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface AskUserQuestionsConfig {
+ enabled?: boolean;
+}
diff --git a/packages/sdk/src/api/types/BaseMcpAuthRequiredEvent.ts b/packages/sdk/src/api/types/BaseMcpAuthRequiredEvent.ts
new file mode 100644
index 000000000..5496faa7e
--- /dev/null
+++ b/packages/sdk/src/api/types/BaseMcpAuthRequiredEvent.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface BaseMcpAuthRequiredEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ threadId: string | null;
+}
diff --git a/packages/sdk/src/api/types/BaseThreadDoneEvent.ts b/packages/sdk/src/api/types/BaseThreadDoneEvent.ts
new file mode 100644
index 000000000..905c67d00
--- /dev/null
+++ b/packages/sdk/src/api/types/BaseThreadDoneEvent.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface BaseThreadDoneEvent {
+ parent?: TrueHarness.AgentParent;
+ threadId: string;
+ title: string;
+}
diff --git a/packages/sdk/src/api/types/CancelSessionResponse.ts b/packages/sdk/src/api/types/CancelSessionResponse.ts
new file mode 100644
index 000000000..c80fc0911
--- /dev/null
+++ b/packages/sdk/src/api/types/CancelSessionResponse.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type CancelSessionResponse = {};
diff --git a/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCall.ts b/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCall.ts
new file mode 100644
index 000000000..692f9d311
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCall.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ChatCompletionChunkDeltaToolCall {
+ function?: TrueHarness.ChatCompletionChunkDeltaToolCallFunction;
+ id?: string;
+ index: number;
+ type?: "function";
+}
diff --git a/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCallFunction.ts b/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCallFunction.ts
new file mode 100644
index 000000000..42f259907
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionChunkDeltaToolCallFunction.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ChatCompletionChunkDeltaToolCallFunction {
+ arguments?: string;
+ name?: string;
+}
diff --git a/packages/sdk/src/api/types/ChatCompletionContentPartRefusal.ts b/packages/sdk/src/api/types/ChatCompletionContentPartRefusal.ts
new file mode 100644
index 000000000..89f40c259
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionContentPartRefusal.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ChatCompletionContentPartRefusal {
+ refusal: string;
+ type: "refusal";
+}
diff --git a/packages/sdk/src/api/types/ChatCompletionContentPartText.ts b/packages/sdk/src/api/types/ChatCompletionContentPartText.ts
new file mode 100644
index 000000000..19c8e828e
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionContentPartText.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ChatCompletionContentPartText {
+ text: string;
+ type: "text";
+}
diff --git a/packages/sdk/src/api/types/ChatCompletionMessageToolCall.ts b/packages/sdk/src/api/types/ChatCompletionMessageToolCall.ts
new file mode 100644
index 000000000..e3c30c92b
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionMessageToolCall.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ChatCompletionMessageToolCall {
+ function: TrueHarness.ChatCompletionMessageToolCallFunction;
+ id: string;
+ type: "function";
+}
diff --git a/packages/sdk/src/api/types/ChatCompletionMessageToolCallFunction.ts b/packages/sdk/src/api/types/ChatCompletionMessageToolCallFunction.ts
new file mode 100644
index 000000000..1ae19cd66
--- /dev/null
+++ b/packages/sdk/src/api/types/ChatCompletionMessageToolCallFunction.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ChatCompletionMessageToolCallFunction {
+ arguments: string;
+ name: string;
+}
diff --git a/packages/sdk/src/api/types/ContextManagementConfig.ts b/packages/sdk/src/api/types/ContextManagementConfig.ts
new file mode 100644
index 000000000..00bdc434c
--- /dev/null
+++ b/packages/sdk/src/api/types/ContextManagementConfig.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ContextManagementConfig {
+ compaction?: TrueHarness.ContextManagementConfigCompaction;
+ largeToolResponse?: TrueHarness.LargeToolResponseConfig;
+}
diff --git a/packages/sdk/src/api/types/ContextManagementConfigCompaction.ts b/packages/sdk/src/api/types/ContextManagementConfigCompaction.ts
new file mode 100644
index 000000000..091d3d6b3
--- /dev/null
+++ b/packages/sdk/src/api/types/ContextManagementConfigCompaction.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ContextManagementConfigCompaction {
+ compactionThresholdTokens?: number;
+ enabled?: boolean;
+}
diff --git a/packages/sdk/src/api/types/DynamicSubAgentsConfig.ts b/packages/sdk/src/api/types/DynamicSubAgentsConfig.ts
new file mode 100644
index 000000000..6748d2004
--- /dev/null
+++ b/packages/sdk/src/api/types/DynamicSubAgentsConfig.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface DynamicSubAgentsConfig {
+ enabled?: boolean;
+}
diff --git a/packages/sdk/src/api/types/ExtendedChunkDeltaToolCall.ts b/packages/sdk/src/api/types/ExtendedChunkDeltaToolCall.ts
new file mode 100644
index 000000000..3c602ea59
--- /dev/null
+++ b/packages/sdk/src/api/types/ExtendedChunkDeltaToolCall.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ExtendedChunkDeltaToolCall extends TrueHarness.ChatCompletionChunkDeltaToolCall {
+ providerSpecificFields?: Record<string, unknown>;
+ toolInfo?: TrueHarness.ToolInfo;
+}
diff --git a/packages/sdk/src/api/types/FileContent.ts b/packages/sdk/src/api/types/FileContent.ts
new file mode 100644
index 000000000..f65ce92f3
--- /dev/null
+++ b/packages/sdk/src/api/types/FileContent.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface FileContent {
+ /** Data URI: `data:<mime>;base64,<payload>`. MIME type is parsed from the URI. */
+ data: string;
+ name: string;
+ type: "file";
+}
diff --git a/packages/sdk/src/api/types/FinishReason.ts b/packages/sdk/src/api/types/FinishReason.ts
new file mode 100644
index 000000000..bf8b032aa
--- /dev/null
+++ b/packages/sdk/src/api/types/FinishReason.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export const FinishReason = {
+ Stop: "stop",
+ Length: "length",
+ ToolCalls: "tool_calls",
+ ContentFilter: "content_filter",
+ FunctionCall: "function_call",
+} as const;
+export type FinishReason = (typeof FinishReason)[keyof typeof FinishReason];
diff --git a/packages/sdk/src/api/types/GenerativeUiConfig.ts b/packages/sdk/src/api/types/GenerativeUiConfig.ts
new file mode 100644
index 000000000..f87d82473
--- /dev/null
+++ b/packages/sdk/src/api/types/GenerativeUiConfig.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface GenerativeUiConfig {
+ enabled?: boolean;
+}
diff --git a/packages/sdk/src/api/types/GetCapabilitiesResponse.ts b/packages/sdk/src/api/types/GetCapabilitiesResponse.ts
new file mode 100644
index 000000000..19b6c1ba5
--- /dev/null
+++ b/packages/sdk/src/api/types/GetCapabilitiesResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface GetCapabilitiesResponse {
+ data: TrueHarness.GetCapabilitiesResponseData;
+}
diff --git a/packages/sdk/src/api/types/GetCapabilitiesResponseData.ts b/packages/sdk/src/api/types/GetCapabilitiesResponseData.ts
new file mode 100644
index 000000000..53d2ac246
--- /dev/null
+++ b/packages/sdk/src/api/types/GetCapabilitiesResponseData.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface GetCapabilitiesResponseData {
+ sandbox: TrueHarness.GetCapabilitiesResponseDataSandbox;
+}
diff --git a/packages/sdk/src/api/types/GetCapabilitiesResponseDataSandbox.ts b/packages/sdk/src/api/types/GetCapabilitiesResponseDataSandbox.ts
new file mode 100644
index 000000000..2dd185a60
--- /dev/null
+++ b/packages/sdk/src/api/types/GetCapabilitiesResponseDataSandbox.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface GetCapabilitiesResponseDataSandbox {
+ /** Whether this server has a sandbox provider configured. */
+ enabled: boolean;
+}
diff --git a/packages/sdk/src/api/types/GetSessionResponse.ts b/packages/sdk/src/api/types/GetSessionResponse.ts
new file mode 100644
index 000000000..9a7349b4c
--- /dev/null
+++ b/packages/sdk/src/api/types/GetSessionResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface GetSessionResponse {
+ data: TrueHarness.Session;
+}
diff --git a/packages/sdk/src/api/types/GetTurnResponse.ts b/packages/sdk/src/api/types/GetTurnResponse.ts
new file mode 100644
index 000000000..8d93ef86c
--- /dev/null
+++ b/packages/sdk/src/api/types/GetTurnResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface GetTurnResponse {
+ data: TrueHarness.Turn;
+}
diff --git a/packages/sdk/src/api/types/LargeToolResponseConfig.ts b/packages/sdk/src/api/types/LargeToolResponseConfig.ts
new file mode 100644
index 000000000..1b7949cc4
--- /dev/null
+++ b/packages/sdk/src/api/types/LargeToolResponseConfig.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface LargeToolResponseConfig {
+ enabled?: boolean;
+}
diff --git a/packages/sdk/src/api/types/ListMcpServersResponse.ts b/packages/sdk/src/api/types/ListMcpServersResponse.ts
new file mode 100644
index 000000000..ebcac5ade
--- /dev/null
+++ b/packages/sdk/src/api/types/ListMcpServersResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListMcpServersResponse {
+ data: TrueHarness.McpServerEntry[];
+}
diff --git a/packages/sdk/src/api/types/ListMcpToolsResponse.ts b/packages/sdk/src/api/types/ListMcpToolsResponse.ts
new file mode 100644
index 000000000..c7dece6fb
--- /dev/null
+++ b/packages/sdk/src/api/types/ListMcpToolsResponse.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ListMcpToolsResponse {
+ /** MCP `tools/list` entries, passed through verbatim from the MCP server. */
+ data: Record<string, unknown>[];
+}
diff --git a/packages/sdk/src/api/types/ListModelsResponse.ts b/packages/sdk/src/api/types/ListModelsResponse.ts
new file mode 100644
index 000000000..4c3f817b8
--- /dev/null
+++ b/packages/sdk/src/api/types/ListModelsResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListModelsResponse {
+ data: TrueHarness.ModelEntry[];
+}
diff --git a/packages/sdk/src/api/types/ListSessionEventsResponse.ts b/packages/sdk/src/api/types/ListSessionEventsResponse.ts
new file mode 100644
index 000000000..65009e825
--- /dev/null
+++ b/packages/sdk/src/api/types/ListSessionEventsResponse.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListSessionEventsResponse {
+ data: TrueHarness.SessionEventItem[];
+ pagination: TrueHarness.TokenPagination;
+}
diff --git a/packages/sdk/src/api/types/ListSessionsOrder.ts b/packages/sdk/src/api/types/ListSessionsOrder.ts
new file mode 100644
index 000000000..b118cd32e
--- /dev/null
+++ b/packages/sdk/src/api/types/ListSessionsOrder.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** Sort sessions by creation time. Defaults to "desc". */
+export const ListSessionsOrder = {
+ Asc: "asc",
+ Desc: "desc",
+} as const;
+export type ListSessionsOrder = (typeof ListSessionsOrder)[keyof typeof ListSessionsOrder];
diff --git a/packages/sdk/src/api/types/ListSessionsResponse.ts b/packages/sdk/src/api/types/ListSessionsResponse.ts
new file mode 100644
index 000000000..e56a82007
--- /dev/null
+++ b/packages/sdk/src/api/types/ListSessionsResponse.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListSessionsResponse {
+ data: TrueHarness.Session[];
+ pagination: TrueHarness.TokenPagination;
+}
diff --git a/packages/sdk/src/api/types/ListSkillsResponse.ts b/packages/sdk/src/api/types/ListSkillsResponse.ts
new file mode 100644
index 000000000..d1d4f923a
--- /dev/null
+++ b/packages/sdk/src/api/types/ListSkillsResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListSkillsResponse {
+ data: TrueHarness.SkillEntry[];
+}
diff --git a/packages/sdk/src/api/types/ListTurnEventsOrder.ts b/packages/sdk/src/api/types/ListTurnEventsOrder.ts
new file mode 100644
index 000000000..259b1672c
--- /dev/null
+++ b/packages/sdk/src/api/types/ListTurnEventsOrder.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** Sort events by insertion order. Defaults to "asc". */
+export const ListTurnEventsOrder = {
+ Asc: "asc",
+ Desc: "desc",
+} as const;
+export type ListTurnEventsOrder = (typeof ListTurnEventsOrder)[keyof typeof ListTurnEventsOrder];
diff --git a/packages/sdk/src/api/types/ListTurnEventsResponse.ts b/packages/sdk/src/api/types/ListTurnEventsResponse.ts
new file mode 100644
index 000000000..93e9cc9b3
--- /dev/null
+++ b/packages/sdk/src/api/types/ListTurnEventsResponse.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListTurnEventsResponse {
+ data: TrueHarness.SessionEvent[];
+ pagination: TrueHarness.TokenPagination;
+}
diff --git a/packages/sdk/src/api/types/ListTurnsResponse.ts b/packages/sdk/src/api/types/ListTurnsResponse.ts
new file mode 100644
index 000000000..1a282e372
--- /dev/null
+++ b/packages/sdk/src/api/types/ListTurnsResponse.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ListTurnsResponse {
+ data: TrueHarness.Turn[];
+ pagination: TrueHarness.TokenPagination;
+}
diff --git a/packages/sdk/src/api/types/McpAuthRequiredEvent.ts b/packages/sdk/src/api/types/McpAuthRequiredEvent.ts
new file mode 100644
index 000000000..976baef05
--- /dev/null
+++ b/packages/sdk/src/api/types/McpAuthRequiredEvent.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface McpAuthRequiredEvent extends TrueHarness.BaseMcpAuthRequiredEvent {
+ mcpServers: TrueHarness.McpServerAuthInfo[];
+ type: "mcp.auth_required";
+}
diff --git a/packages/sdk/src/api/types/McpInitializeEvent.ts b/packages/sdk/src/api/types/McpInitializeEvent.ts
new file mode 100644
index 000000000..dfddf7af4
--- /dev/null
+++ b/packages/sdk/src/api/types/McpInitializeEvent.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface McpInitializeEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ mcpServers: TrueHarness.McpServerInitInfo[];
+ threadId: string;
+ type: "mcp.initialize";
+}
diff --git a/packages/sdk/src/api/types/McpServer.ts b/packages/sdk/src/api/types/McpServer.ts
new file mode 100644
index 000000000..e14baeb64
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServer.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface McpServer {
+ disableTools?: TrueHarness.McpServerDisableToolsItem[];
+ enableTools?: TrueHarness.McpServerEnableToolsItem[];
+ name: string;
+ preload?: boolean;
+ preloadTools?: TrueHarness.McpServerPreloadToolsItem[];
+ requireApprovalForTools?: TrueHarness.McpServerRequireApprovalForToolsItem[];
+}
diff --git a/packages/sdk/src/api/types/McpServerAuthInfo.ts b/packages/sdk/src/api/types/McpServerAuthInfo.ts
new file mode 100644
index 000000000..0e4043b34
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerAuthInfo.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface McpServerAuthInfo {
+ authUrl: string;
+ id: string;
+ name: string;
+}
diff --git a/packages/sdk/src/api/types/McpServerDisableToolsItem.ts b/packages/sdk/src/api/types/McpServerDisableToolsItem.ts
new file mode 100644
index 000000000..6c4b43993
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerDisableToolsItem.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type McpServerDisableToolsItem = "@all" | "@read-only" | string;
diff --git a/packages/sdk/src/api/types/McpServerEnableToolsItem.ts b/packages/sdk/src/api/types/McpServerEnableToolsItem.ts
new file mode 100644
index 000000000..4a00f30d9
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerEnableToolsItem.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type McpServerEnableToolsItem = "@all" | "@read-only" | string;
diff --git a/packages/sdk/src/api/types/McpServerEntry.ts b/packages/sdk/src/api/types/McpServerEntry.ts
new file mode 100644
index 000000000..739ada4ef
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerEntry.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface McpServerEntry {
+ name: string;
+ url: string;
+}
diff --git a/packages/sdk/src/api/types/McpServerInitInfo.ts b/packages/sdk/src/api/types/McpServerInitInfo.ts
new file mode 100644
index 000000000..2e8d571f4
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerInitInfo.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface McpServerInitInfo {
+ id: string;
+ name: string;
+ sessionId?: string;
+ transportType?: TrueHarness.McpServerInitInfoTransportType;
+}
diff --git a/packages/sdk/src/api/types/McpServerInitInfoTransportType.ts b/packages/sdk/src/api/types/McpServerInitInfoTransportType.ts
new file mode 100644
index 000000000..1f55335a2
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerInitInfoTransportType.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export const McpServerInitInfoTransportType = {
+ StreamableHttp: "streamable-http",
+ Sse: "sse",
+} as const;
+export type McpServerInitInfoTransportType =
+ (typeof McpServerInitInfoTransportType)[keyof typeof McpServerInitInfoTransportType];
diff --git a/packages/sdk/src/api/types/McpServerPreloadToolsItem.ts b/packages/sdk/src/api/types/McpServerPreloadToolsItem.ts
new file mode 100644
index 000000000..4e1374047
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerPreloadToolsItem.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type McpServerPreloadToolsItem = "@all" | "@read-only" | string;
diff --git a/packages/sdk/src/api/types/McpServerRequireApprovalForToolsItem.ts b/packages/sdk/src/api/types/McpServerRequireApprovalForToolsItem.ts
new file mode 100644
index 000000000..1299f0927
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerRequireApprovalForToolsItem.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type McpServerRequireApprovalForToolsItem = "@all" | "@write" | "@destructive" | string;
diff --git a/packages/sdk/src/api/types/McpToolInfo.ts b/packages/sdk/src/api/types/McpToolInfo.ts
new file mode 100644
index 000000000..da7b537a2
--- /dev/null
+++ b/packages/sdk/src/api/types/McpToolInfo.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface McpToolInfo {
+ name: string;
+ serverId: string;
+ serverName: string;
+ type: "mcp";
+}
diff --git a/packages/sdk/src/api/types/Model.ts b/packages/sdk/src/api/types/Model.ts
new file mode 100644
index 000000000..a4fac0dc9
--- /dev/null
+++ b/packages/sdk/src/api/types/Model.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface Model {
+ name: string;
+ params?: TrueHarness.ModelParams;
+}
diff --git a/packages/sdk/src/api/types/ModelEntry.ts b/packages/sdk/src/api/types/ModelEntry.ts
new file mode 100644
index 000000000..a853fcd13
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelEntry.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ModelEntry {
+ maxOutputTokens: number;
+ name: string;
+ reasoningEfforts?: string[];
+}
diff --git a/packages/sdk/src/api/types/ModelMessageDeltaEvent.ts b/packages/sdk/src/api/types/ModelMessageDeltaEvent.ts
new file mode 100644
index 000000000..187027ac9
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageDeltaEvent.ts
@@ -0,0 +1,17 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ModelMessageDeltaEvent {
+ content?: string | null;
+ createdAt?: string;
+ finishReason?: TrueHarness.FinishReason | null;
+ /** Unique identifier for the event */
+ id: string;
+ reasoningContent?: string;
+ refusal?: string | null;
+ threadId: string;
+ toolCalls?: TrueHarness.ExtendedChunkDeltaToolCall[];
+ type: "model.message.delta";
+ usage?: TrueHarness.ModelMessageUsage;
+}
diff --git a/packages/sdk/src/api/types/ModelMessageEvent.ts b/packages/sdk/src/api/types/ModelMessageEvent.ts
new file mode 100644
index 000000000..4967b8095
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageEvent.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ModelMessageEvent {
+ content?: TrueHarness.ModelMessageEventContent | null;
+ createdAt: string;
+ finishReason?: TrueHarness.FinishReason | null;
+ /** Unique identifier for the event */
+ id: string;
+ name?: string;
+ reasoningContent?: string;
+ refusal?: string | null;
+ threadId: string;
+ toolCalls?: TrueHarness.ToolCall[];
+ type: "model.message";
+ usage?: TrueHarness.ModelMessageUsage;
+}
diff --git a/packages/sdk/src/api/types/ModelMessageEventContent.ts b/packages/sdk/src/api/types/ModelMessageEventContent.ts
new file mode 100644
index 000000000..b8c259b7b
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageEventContent.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ModelMessageEventContent = string | TrueHarness.ModelMessageEventContentOneItem[];
diff --git a/packages/sdk/src/api/types/ModelMessageEventContentOneItem.ts b/packages/sdk/src/api/types/ModelMessageEventContentOneItem.ts
new file mode 100644
index 000000000..7a103ccfa
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageEventContentOneItem.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ModelMessageEventContentOneItem =
+ | TrueHarness.ChatCompletionContentPartText
+ | TrueHarness.ChatCompletionContentPartRefusal;
diff --git a/packages/sdk/src/api/types/ModelMessageUsage.ts b/packages/sdk/src/api/types/ModelMessageUsage.ts
new file mode 100644
index 000000000..91d89e6b6
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageUsage.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ModelMessageUsage {
+ cacheReadTokens?: number;
+ cacheWriteTokens?: number;
+ inputTokens: number;
+ inputTokensBreakdown: TrueHarness.ModelMessageUsageInputTokensBreakdown;
+ outputTokens: number;
+}
diff --git a/packages/sdk/src/api/types/ModelMessageUsageInputTokensBreakdown.ts b/packages/sdk/src/api/types/ModelMessageUsageInputTokensBreakdown.ts
new file mode 100644
index 000000000..1d82eb72e
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelMessageUsageInputTokensBreakdown.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ModelMessageUsageInputTokensBreakdown {
+ harness: number;
+ instructions: number;
+ messages: number;
+ skills: number;
+ toolDefinitions: number;
+}
diff --git a/packages/sdk/src/api/types/ModelParams.ts b/packages/sdk/src/api/types/ModelParams.ts
new file mode 100644
index 000000000..067081758
--- /dev/null
+++ b/packages/sdk/src/api/types/ModelParams.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ModelParams {
+ maxTokens?: number;
+ parallelToolCalls?: boolean;
+ reasoningEffort?: string;
+ temperature?: number;
+ topK?: number;
+ topP?: number;
+}
diff --git a/packages/sdk/src/api/types/PreviousTurnIdInput.ts b/packages/sdk/src/api/types/PreviousTurnIdInput.ts
new file mode 100644
index 000000000..b05dbd2a5
--- /dev/null
+++ b/packages/sdk/src/api/types/PreviousTurnIdInput.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * Defaults to 'auto' (chain to session last turn). Use 'null' for the session's first turn.
+ */
+export type PreviousTurnIdInput = "auto" | string;
diff --git a/packages/sdk/src/api/types/RawToolCall.ts b/packages/sdk/src/api/types/RawToolCall.ts
new file mode 100644
index 000000000..092fe5663
--- /dev/null
+++ b/packages/sdk/src/api/types/RawToolCall.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface RawToolCall extends TrueHarness.ChatCompletionMessageToolCall {
+ providerSpecificFields?: Record<string, unknown>;
+}
diff --git a/packages/sdk/src/api/types/RequestErrorResponse.ts b/packages/sdk/src/api/types/RequestErrorResponse.ts
new file mode 100644
index 000000000..ff20c054b
--- /dev/null
+++ b/packages/sdk/src/api/types/RequestErrorResponse.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface RequestErrorResponse {
+ error: TrueHarness.RequestErrorResponseError;
+}
diff --git a/packages/sdk/src/api/types/RequestErrorResponseError.ts b/packages/sdk/src/api/types/RequestErrorResponseError.ts
new file mode 100644
index 000000000..e693e6719
--- /dev/null
+++ b/packages/sdk/src/api/types/RequestErrorResponseError.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface RequestErrorResponseError {
+ code?: string | null;
+ message: string;
+ param?: string | null;
+ type?: string;
+}
diff --git a/packages/sdk/src/api/types/ResponseFormat.ts b/packages/sdk/src/api/types/ResponseFormat.ts
new file mode 100644
index 000000000..8eb79af18
--- /dev/null
+++ b/packages/sdk/src/api/types/ResponseFormat.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ResponseFormat =
+ | TrueHarness.ResponseFormatZero
+ | TrueHarness.ResponseFormatOne
+ | TrueHarness.ResponseFormatJsonSchema;
diff --git a/packages/sdk/src/api/types/ResponseFormatJsonSchema.ts b/packages/sdk/src/api/types/ResponseFormatJsonSchema.ts
new file mode 100644
index 000000000..87865ff0c
--- /dev/null
+++ b/packages/sdk/src/api/types/ResponseFormatJsonSchema.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ResponseFormatJsonSchema {
+ jsonSchema: TrueHarness.ResponseFormatJsonSchemaJsonSchema;
+ type: "json_schema";
+}
diff --git a/packages/sdk/src/api/types/ResponseFormatJsonSchemaJsonSchema.ts b/packages/sdk/src/api/types/ResponseFormatJsonSchemaJsonSchema.ts
new file mode 100644
index 000000000..289095861
--- /dev/null
+++ b/packages/sdk/src/api/types/ResponseFormatJsonSchemaJsonSchema.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ResponseFormatJsonSchemaJsonSchema {
+ description?: string;
+ name: string;
+ schema?: Record<string, unknown>;
+ strict?: boolean | null;
+}
diff --git a/packages/sdk/src/api/types/ResponseFormatOne.ts b/packages/sdk/src/api/types/ResponseFormatOne.ts
new file mode 100644
index 000000000..30a44a555
--- /dev/null
+++ b/packages/sdk/src/api/types/ResponseFormatOne.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ResponseFormatOne {
+ type: "json_object";
+}
diff --git a/packages/sdk/src/api/types/ResponseFormatZero.ts b/packages/sdk/src/api/types/ResponseFormatZero.ts
new file mode 100644
index 000000000..8b90fb2d7
--- /dev/null
+++ b/packages/sdk/src/api/types/ResponseFormatZero.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ResponseFormatZero {
+ type: "text";
+}
diff --git a/packages/sdk/src/api/types/RuntimeConfig.ts b/packages/sdk/src/api/types/RuntimeConfig.ts
new file mode 100644
index 000000000..81711994c
--- /dev/null
+++ b/packages/sdk/src/api/types/RuntimeConfig.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface RuntimeConfig {
+ askUserQuestions?: TrueHarness.AskUserQuestionsConfig;
+ contextManagement?: TrueHarness.ContextManagementConfig;
+ dynamicSubAgents?: TrueHarness.DynamicSubAgentsConfig;
+ generativeUi?: TrueHarness.GenerativeUiConfig;
+ iterationLimit?: number;
+ sandbox?: TrueHarness.SandboxConfig;
+}
diff --git a/packages/sdk/src/api/types/SandboxConfig.ts b/packages/sdk/src/api/types/SandboxConfig.ts
new file mode 100644
index 000000000..66c75244c
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxConfig.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface SandboxConfig {
+ enabled: boolean;
+ fileDownloads?: boolean;
+ networkPolicy?: TrueHarness.SandboxNetworkPolicy;
+}
diff --git a/packages/sdk/src/api/types/SandboxCreatedEvent.ts b/packages/sdk/src/api/types/SandboxCreatedEvent.ts
new file mode 100644
index 000000000..b3a312b39
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxCreatedEvent.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SandboxCreatedEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ sandboxId: string;
+ threadId: string | null;
+ type: "sandbox.created";
+}
diff --git a/packages/sdk/src/api/types/SandboxNetworkPolicy.ts b/packages/sdk/src/api/types/SandboxNetworkPolicy.ts
new file mode 100644
index 000000000..d13c45800
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxNetworkPolicy.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface SandboxNetworkPolicy {
+ authInject?: TrueHarness.SandboxNetworkPolicyAuthInjectItem[];
+}
diff --git a/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItem.ts b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItem.ts
new file mode 100644
index 000000000..475974a90
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItem.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface SandboxNetworkPolicyAuthInjectItem {
+ authData: TrueHarness.SandboxNetworkPolicyAuthInjectItemAuthData;
+ match: TrueHarness.SandboxNetworkPolicyAuthInjectItemMatch;
+ type: "git";
+}
diff --git a/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts
new file mode 100644
index 000000000..34f9e80c8
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SandboxNetworkPolicyAuthInjectItemAuthData {
+ password: string;
+ type: "basic";
+ username: string;
+}
diff --git a/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemMatch.ts b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemMatch.ts
new file mode 100644
index 000000000..352278363
--- /dev/null
+++ b/packages/sdk/src/api/types/SandboxNetworkPolicyAuthInjectItemMatch.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SandboxNetworkPolicyAuthInjectItemMatch {
+ hosts: string[];
+}
diff --git a/packages/sdk/src/api/types/Session.ts b/packages/sdk/src/api/types/Session.ts
new file mode 100644
index 000000000..8d4aff01c
--- /dev/null
+++ b/packages/sdk/src/api/types/Session.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface Session {
+ agentSpec: TrueHarness.AgentSpec;
+ createdAt: string;
+ id: string;
+ title: string | null;
+ updatedAt: string;
+}
diff --git a/packages/sdk/src/api/types/SessionEvent.ts b/packages/sdk/src/api/types/SessionEvent.ts
new file mode 100644
index 000000000..eea938991
--- /dev/null
+++ b/packages/sdk/src/api/types/SessionEvent.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type SessionEvent =
+ | TrueHarness.McpAuthRequiredEvent
+ | TrueHarness.McpInitializeEvent
+ | TrueHarness.ModelMessageEvent
+ | TrueHarness.SandboxCreatedEvent
+ | TrueHarness.ThreadCreatedEvent
+ | TrueHarness.ThreadDoneEvent
+ | TrueHarness.ToolApprovalRequiredEvent
+ | TrueHarness.ToolResponseEvent
+ | TrueHarness.ToolResponseRequiredEvent
+ | TrueHarness.TurnCreatedEvent
+ | TrueHarness.TurnDoneEvent;
diff --git a/packages/sdk/src/api/types/SessionEventItem.ts b/packages/sdk/src/api/types/SessionEventItem.ts
new file mode 100644
index 000000000..85686f6d2
--- /dev/null
+++ b/packages/sdk/src/api/types/SessionEventItem.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface SessionEventItem {
+ event: TrueHarness.SessionEvent;
+ turnId: string;
+}
diff --git a/packages/sdk/src/api/types/SkillEntry.ts b/packages/sdk/src/api/types/SkillEntry.ts
new file mode 100644
index 000000000..7a158e7ef
--- /dev/null
+++ b/packages/sdk/src/api/types/SkillEntry.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SkillEntry {
+ description: string;
+ name: string;
+ path?: string;
+ ref?: string;
+ url: string;
+}
diff --git a/packages/sdk/src/api/types/SkillMount.ts b/packages/sdk/src/api/types/SkillMount.ts
new file mode 100644
index 000000000..ed3a6d5da
--- /dev/null
+++ b/packages/sdk/src/api/types/SkillMount.ts
@@ -0,0 +1,15 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SkillMount {
+ /** Concise guidance for when the agent should use the skill. */
+ description: string;
+ /** Name for the skill, used as directory name in sandbox. */
+ name: string;
+ /** Path to the skill directory within the repository. Omit to use the repository root. */
+ path?: string;
+ /** Git ref — branch name, tag, or commit SHA. */
+ ref: string;
+ type: "git";
+ /** Full HTTPS URL of a GitHub or GitLab repository. */
+ url: string;
+}
diff --git a/packages/sdk/src/api/types/TextContent.ts b/packages/sdk/src/api/types/TextContent.ts
new file mode 100644
index 000000000..9faa22de9
--- /dev/null
+++ b/packages/sdk/src/api/types/TextContent.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface TextContent {
+ text: string;
+ type: "text";
+}
diff --git a/packages/sdk/src/api/types/ThreadCreatedEvent.ts b/packages/sdk/src/api/types/ThreadCreatedEvent.ts
new file mode 100644
index 000000000..8415902f4
--- /dev/null
+++ b/packages/sdk/src/api/types/ThreadCreatedEvent.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ThreadCreatedEvent {
+ agentInfo: TrueHarness.AgentInfo;
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ parent: TrueHarness.AgentParent;
+ threadId: string;
+ title: string;
+ type: "thread.created";
+}
diff --git a/packages/sdk/src/api/types/ThreadDoneEvent.ts b/packages/sdk/src/api/types/ThreadDoneEvent.ts
new file mode 100644
index 000000000..137cab120
--- /dev/null
+++ b/packages/sdk/src/api/types/ThreadDoneEvent.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ThreadDoneEvent extends TrueHarness.BaseThreadDoneEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ state: TrueHarness.ThreadState;
+ type: "thread.done";
+}
diff --git a/packages/sdk/src/api/types/ThreadState.ts b/packages/sdk/src/api/types/ThreadState.ts
new file mode 100644
index 000000000..4e14444ec
--- /dev/null
+++ b/packages/sdk/src/api/types/ThreadState.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ThreadState = TrueHarness.ThreadStateDone | TrueHarness.ThreadStateError;
diff --git a/packages/sdk/src/api/types/ThreadStateDone.ts b/packages/sdk/src/api/types/ThreadStateDone.ts
new file mode 100644
index 000000000..c39f6869b
--- /dev/null
+++ b/packages/sdk/src/api/types/ThreadStateDone.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ThreadStateDone {
+ output: TrueHarness.ModelMessageEvent;
+ status: "done";
+}
diff --git a/packages/sdk/src/api/types/ThreadStateError.ts b/packages/sdk/src/api/types/ThreadStateError.ts
new file mode 100644
index 000000000..9025ac327
--- /dev/null
+++ b/packages/sdk/src/api/types/ThreadStateError.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ThreadStateError {
+ error: string;
+ output?: TrueHarness.ModelMessageEvent;
+ status: "error";
+}
diff --git a/packages/sdk/src/api/types/TokenPagination.ts b/packages/sdk/src/api/types/TokenPagination.ts
new file mode 100644
index 000000000..3b859abdf
--- /dev/null
+++ b/packages/sdk/src/api/types/TokenPagination.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface TokenPagination {
+ limit: number;
+ nextPageToken?: string;
+ previousPageToken?: string;
+}
diff --git a/packages/sdk/src/api/types/ToolApprovalRequiredEvent.ts b/packages/sdk/src/api/types/ToolApprovalRequiredEvent.ts
new file mode 100644
index 000000000..b90c55d82
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolApprovalRequiredEvent.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ToolApprovalRequiredEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ threadId: string;
+ toolCalls: TrueHarness.ToolCallRef[];
+ type: "tool.approval_required";
+}
diff --git a/packages/sdk/src/api/types/ToolCall.ts b/packages/sdk/src/api/types/ToolCall.ts
new file mode 100644
index 000000000..604ee1ebc
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolCall.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ToolCall extends TrueHarness.RawToolCall {
+ toolInfo: TrueHarness.ToolInfo;
+}
diff --git a/packages/sdk/src/api/types/ToolCallRef.ts b/packages/sdk/src/api/types/ToolCallRef.ts
new file mode 100644
index 000000000..fcb0119ce
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolCallRef.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ToolCallRef {
+ id: string;
+ sourceEventId: string;
+}
diff --git a/packages/sdk/src/api/types/ToolInfo.ts b/packages/sdk/src/api/types/ToolInfo.ts
new file mode 100644
index 000000000..c1f0e4c51
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolInfo.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type ToolInfo = TrueHarness.McpToolInfo | TrueHarness.TrueFoundrySystemToolInfo;
diff --git a/packages/sdk/src/api/types/ToolResponseEvent.ts b/packages/sdk/src/api/types/ToolResponseEvent.ts
new file mode 100644
index 000000000..87fc64d11
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolResponseEvent.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface ToolResponseEvent {
+ content: string;
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ threadId: string;
+ toolCallId: string;
+ type: "tool.response";
+}
diff --git a/packages/sdk/src/api/types/ToolResponseRequiredEvent.ts b/packages/sdk/src/api/types/ToolResponseRequiredEvent.ts
new file mode 100644
index 000000000..4e7333bf3
--- /dev/null
+++ b/packages/sdk/src/api/types/ToolResponseRequiredEvent.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface ToolResponseRequiredEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ threadId: string;
+ toolCalls: TrueHarness.ToolCallRef[];
+ type: "tool.response_required";
+}
diff --git a/packages/sdk/src/api/types/TrueFoundrySystemToolInfo.ts b/packages/sdk/src/api/types/TrueFoundrySystemToolInfo.ts
new file mode 100644
index 000000000..ebe26f9cf
--- /dev/null
+++ b/packages/sdk/src/api/types/TrueFoundrySystemToolInfo.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface TrueFoundrySystemToolInfo {
+ name: string;
+ type: "truefoundry-system";
+}
diff --git a/packages/sdk/src/api/types/Turn.ts b/packages/sdk/src/api/types/Turn.ts
new file mode 100644
index 000000000..aabe929f9
--- /dev/null
+++ b/packages/sdk/src/api/types/Turn.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface Turn {
+ createdAt: string;
+ id: string;
+ input?: TrueHarness.TurnInputItem[];
+ previousTurnId: string | null;
+ sessionId: string;
+ state: TrueHarness.TurnState;
+}
diff --git a/packages/sdk/src/api/types/TurnCreatedEvent.ts b/packages/sdk/src/api/types/TurnCreatedEvent.ts
new file mode 100644
index 000000000..cc903e58b
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnCreatedEvent.ts
@@ -0,0 +1,15 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface TurnCreatedEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ input?: TrueHarness.TurnInputItem[];
+ previousTurnId: string | null;
+ state: TrueHarness.TurnStateRunning;
+ threadId: string | null;
+ turnId: string;
+ type: "turn.created";
+}
diff --git a/packages/sdk/src/api/types/TurnDoneEvent.ts b/packages/sdk/src/api/types/TurnDoneEvent.ts
new file mode 100644
index 000000000..451c04dec
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnDoneEvent.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface TurnDoneEvent {
+ createdAt: string;
+ /** Unique identifier for the event */
+ id: string;
+ state: TrueHarness.TurnDoneEventState;
+ threadId: string | null;
+ type: "turn.done";
+}
diff --git a/packages/sdk/src/api/types/TurnDoneEventState.ts b/packages/sdk/src/api/types/TurnDoneEventState.ts
new file mode 100644
index 000000000..3ae45c451
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnDoneEventState.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type TurnDoneEventState =
+ | TrueHarness.TurnStateCancelled
+ | TrueHarness.TurnStateDone
+ | TrueHarness.TurnStateError;
diff --git a/packages/sdk/src/api/types/TurnInputItem.ts b/packages/sdk/src/api/types/TurnInputItem.ts
new file mode 100644
index 000000000..c34f846b5
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnInputItem.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type TurnInputItem =
+ | TrueHarness.UserMessage
+ | TrueHarness.UserToolApprovalEvent
+ | TrueHarness.UserToolResponseEvent;
diff --git a/packages/sdk/src/api/types/TurnState.ts b/packages/sdk/src/api/types/TurnState.ts
new file mode 100644
index 000000000..53b9d7035
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnState.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type TurnState =
+ | TrueHarness.TurnStateCancelled
+ | TrueHarness.TurnStateDone
+ | TrueHarness.TurnStateError
+ | TrueHarness.TurnStateRunning;
diff --git a/packages/sdk/src/api/types/TurnStateCancelled.ts b/packages/sdk/src/api/types/TurnStateCancelled.ts
new file mode 100644
index 000000000..47e2c8a97
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStateCancelled.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface TurnStateCancelled {
+ completedAt: string;
+ reason: TrueHarness.TurnStateCancelledReason;
+ status: "cancelled";
+}
diff --git a/packages/sdk/src/api/types/TurnStateCancelledReason.ts b/packages/sdk/src/api/types/TurnStateCancelledReason.ts
new file mode 100644
index 000000000..bdcd0dfc1
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStateCancelledReason.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** Reason for the cancellation. */
+export const TurnStateCancelledReason = {
+ ServerExecutionTimeout: "server-execution-timeout",
+ ClientCancelled: "client-cancelled",
+ CancelledForNextTurn: "cancelled-for-next-turn",
+ Abandoned: "abandoned",
+} as const;
+export type TurnStateCancelledReason = (typeof TurnStateCancelledReason)[keyof typeof TurnStateCancelledReason];
diff --git a/packages/sdk/src/api/types/TurnStateDone.ts b/packages/sdk/src/api/types/TurnStateDone.ts
new file mode 100644
index 000000000..202a84fad
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStateDone.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface TurnStateDone {
+ completedAt: string;
+ output?: TrueHarness.ModelMessageEvent;
+ requiredActions: TrueHarness.ActionRequiredEvent[];
+ status: "done";
+}
diff --git a/packages/sdk/src/api/types/TurnStateError.ts b/packages/sdk/src/api/types/TurnStateError.ts
new file mode 100644
index 000000000..1b771ab0d
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStateError.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface TurnStateError {
+ completedAt: string;
+ message: string;
+ status: "error";
+}
diff --git a/packages/sdk/src/api/types/TurnStateRunning.ts b/packages/sdk/src/api/types/TurnStateRunning.ts
new file mode 100644
index 000000000..dcee0018b
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStateRunning.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface TurnStateRunning {
+ status: "running";
+}
diff --git a/packages/sdk/src/api/types/TurnStreamingEvent.ts b/packages/sdk/src/api/types/TurnStreamingEvent.ts
new file mode 100644
index 000000000..cdcb0515f
--- /dev/null
+++ b/packages/sdk/src/api/types/TurnStreamingEvent.ts
@@ -0,0 +1,17 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type TurnStreamingEvent =
+ | TrueHarness.McpAuthRequiredEvent
+ | TrueHarness.McpInitializeEvent
+ | TrueHarness.ModelMessageEvent
+ | TrueHarness.ModelMessageDeltaEvent
+ | TrueHarness.SandboxCreatedEvent
+ | TrueHarness.ThreadCreatedEvent
+ | TrueHarness.ThreadDoneEvent
+ | TrueHarness.ToolApprovalRequiredEvent
+ | TrueHarness.ToolResponseEvent
+ | TrueHarness.ToolResponseRequiredEvent
+ | TrueHarness.TurnCreatedEvent
+ | TrueHarness.TurnDoneEvent;
diff --git a/packages/sdk/src/api/types/UserMessage.ts b/packages/sdk/src/api/types/UserMessage.ts
new file mode 100644
index 000000000..bdf68832f
--- /dev/null
+++ b/packages/sdk/src/api/types/UserMessage.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface UserMessage {
+ content: TrueHarness.UserMessageContent;
+ type: "user.message";
+}
diff --git a/packages/sdk/src/api/types/UserMessageContent.ts b/packages/sdk/src/api/types/UserMessageContent.ts
new file mode 100644
index 000000000..82510fbfa
--- /dev/null
+++ b/packages/sdk/src/api/types/UserMessageContent.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type UserMessageContent = string | TrueHarness.UserMessageContentItem[];
diff --git a/packages/sdk/src/api/types/UserMessageContentItem.ts b/packages/sdk/src/api/types/UserMessageContentItem.ts
new file mode 100644
index 000000000..2b58e9d0f
--- /dev/null
+++ b/packages/sdk/src/api/types/UserMessageContentItem.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export type UserMessageContentItem = TrueHarness.FileContent | TrueHarness.TextContent;
diff --git a/packages/sdk/src/api/types/UserToolApprovalEvent.ts b/packages/sdk/src/api/types/UserToolApprovalEvent.ts
new file mode 100644
index 000000000..d55e604ce
--- /dev/null
+++ b/packages/sdk/src/api/types/UserToolApprovalEvent.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../index.js";
+
+export interface UserToolApprovalEvent {
+ approval: TrueHarness.ApprovalDecision;
+ threadId: string;
+ toolCallId: string;
+ type: "user.tool_approval";
+}
diff --git a/packages/sdk/src/api/types/UserToolResponseEvent.ts b/packages/sdk/src/api/types/UserToolResponseEvent.ts
new file mode 100644
index 000000000..aaf75109c
--- /dev/null
+++ b/packages/sdk/src/api/types/UserToolResponseEvent.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface UserToolResponseEvent {
+ content: string;
+ threadId: string;
+ toolCallId: string;
+ type: "user.tool_response";
+}
diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.ts
new file mode 100644
index 000000000..2706372a6
--- /dev/null
+++ b/packages/sdk/src/api/types/index.ts
@@ -0,0 +1,114 @@
+export * from "./ActionRequiredEvent.js";
+export * from "./AgentInfo.js";
+export * from "./AgentParent.js";
+export * from "./AgentSpec.js";
+export * from "./AgentSpecUserMessage.js";
+export * from "./ApprovalAllow.js";
+export * from "./ApprovalDecision.js";
+export * from "./ApprovalDeny.js";
+export * from "./AskUserQuestionsConfig.js";
+export * from "./BaseMcpAuthRequiredEvent.js";
+export * from "./BaseThreadDoneEvent.js";
+export * from "./CancelSessionResponse.js";
+export * from "./ChatCompletionChunkDeltaToolCall.js";
+export * from "./ChatCompletionChunkDeltaToolCallFunction.js";
+export * from "./ChatCompletionContentPartRefusal.js";
+export * from "./ChatCompletionContentPartText.js";
+export * from "./ChatCompletionMessageToolCall.js";
+export * from "./ChatCompletionMessageToolCallFunction.js";
+export * from "./ContextManagementConfig.js";
+export * from "./ContextManagementConfigCompaction.js";
+export * from "./DynamicSubAgentsConfig.js";
+export * from "./ExtendedChunkDeltaToolCall.js";
+export * from "./FileContent.js";
+export * from "./FinishReason.js";
+export * from "./GenerativeUiConfig.js";
+export * from "./GetCapabilitiesResponse.js";
+export * from "./GetCapabilitiesResponseData.js";
+export * from "./GetCapabilitiesResponseDataSandbox.js";
+export * from "./GetSessionResponse.js";
+export * from "./GetTurnResponse.js";
+export * from "./LargeToolResponseConfig.js";
+export * from "./ListMcpServersResponse.js";
+export * from "./ListMcpToolsResponse.js";
+export * from "./ListModelsResponse.js";
+export * from "./ListSessionEventsResponse.js";
+export * from "./ListSessionsOrder.js";
+export * from "./ListSessionsResponse.js";
+export * from "./ListSkillsResponse.js";
+export * from "./ListTurnEventsOrder.js";
+export * from "./ListTurnEventsResponse.js";
+export * from "./ListTurnsResponse.js";
+export * from "./McpAuthRequiredEvent.js";
+export * from "./McpInitializeEvent.js";
+export * from "./McpServer.js";
+export * from "./McpServerAuthInfo.js";
+export * from "./McpServerDisableToolsItem.js";
+export * from "./McpServerEnableToolsItem.js";
+export * from "./McpServerEntry.js";
+export * from "./McpServerInitInfo.js";
+export * from "./McpServerInitInfoTransportType.js";
+export * from "./McpServerPreloadToolsItem.js";
+export * from "./McpServerRequireApprovalForToolsItem.js";
+export * from "./McpToolInfo.js";
+export * from "./Model.js";
+export * from "./ModelEntry.js";
+export * from "./ModelMessageDeltaEvent.js";
+export * from "./ModelMessageEvent.js";
+export * from "./ModelMessageEventContent.js";
+export * from "./ModelMessageEventContentOneItem.js";
+export * from "./ModelMessageUsage.js";
+export * from "./ModelMessageUsageInputTokensBreakdown.js";
+export * from "./ModelParams.js";
+export * from "./PreviousTurnIdInput.js";
+export * from "./RawToolCall.js";
+export * from "./RequestErrorResponse.js";
+export * from "./RequestErrorResponseError.js";
+export * from "./ResponseFormat.js";
+export * from "./ResponseFormatJsonSchema.js";
+export * from "./ResponseFormatJsonSchemaJsonSchema.js";
+export * from "./ResponseFormatOne.js";
+export * from "./ResponseFormatZero.js";
+export * from "./RuntimeConfig.js";
+export * from "./SandboxConfig.js";
+export * from "./SandboxCreatedEvent.js";
+export * from "./SandboxNetworkPolicy.js";
+export * from "./SandboxNetworkPolicyAuthInjectItem.js";
+export * from "./SandboxNetworkPolicyAuthInjectItemAuthData.js";
+export * from "./SandboxNetworkPolicyAuthInjectItemMatch.js";
+export * from "./Session.js";
+export * from "./SessionEvent.js";
+export * from "./SessionEventItem.js";
+export * from "./SkillEntry.js";
+export * from "./SkillMount.js";
+export * from "./TextContent.js";
+export * from "./ThreadCreatedEvent.js";
+export * from "./ThreadDoneEvent.js";
+export * from "./ThreadState.js";
+export * from "./ThreadStateDone.js";
+export * from "./ThreadStateError.js";
+export * from "./TokenPagination.js";
+export * from "./ToolApprovalRequiredEvent.js";
+export * from "./ToolCall.js";
+export * from "./ToolCallRef.js";
+export * from "./ToolInfo.js";
+export * from "./ToolResponseEvent.js";
+export * from "./ToolResponseRequiredEvent.js";
+export * from "./TrueFoundrySystemToolInfo.js";
+export * from "./Turn.js";
+export * from "./TurnCreatedEvent.js";
+export * from "./TurnDoneEvent.js";
+export * from "./TurnDoneEventState.js";
+export * from "./TurnInputItem.js";
+export * from "./TurnState.js";
+export * from "./TurnStateCancelled.js";
+export * from "./TurnStateCancelledReason.js";
+export * from "./TurnStateDone.js";
+export * from "./TurnStateError.js";
+export * from "./TurnStateRunning.js";
+export * from "./TurnStreamingEvent.js";
+export * from "./UserMessage.js";
+export * from "./UserMessageContent.js";
+export * from "./UserMessageContentItem.js";
+export * from "./UserToolApprovalEvent.js";
+export * from "./UserToolResponseEvent.js";
diff --git a/packages/sdk/src/core/exports.ts b/packages/sdk/src/core/exports.ts
new file mode 100644
index 000000000..d27744915
--- /dev/null
+++ b/packages/sdk/src/core/exports.ts
@@ -0,0 +1,2 @@
+export * from "./logging/exports.js";
+export * from "./pagination/exports.js";
diff --git a/packages/sdk/src/core/fetcher/APIResponse.ts b/packages/sdk/src/core/fetcher/APIResponse.ts
new file mode 100644
index 000000000..97ab83c2b
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/APIResponse.ts
@@ -0,0 +1,23 @@
+import type { RawResponse } from "./RawResponse.js";
+
+/**
+ * The response of an API call.
+ * It is a successful response or a failed response.
+ */
+export type APIResponse<Success, Failure> = SuccessfulResponse<Success> | FailedResponse<Failure>;
+
+export interface SuccessfulResponse<T> {
+ ok: true;
+ body: T;
+ /**
+ * @deprecated Use `rawResponse` instead
+ */
+ headers?: Record<string, any>;
+ rawResponse: RawResponse;
+}
+
+export interface FailedResponse<T> {
+ ok: false;
+ error: T;
+ rawResponse: RawResponse;
+}
diff --git a/packages/sdk/src/core/fetcher/BinaryResponse.ts b/packages/sdk/src/core/fetcher/BinaryResponse.ts
new file mode 100644
index 000000000..b9e40fb62
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/BinaryResponse.ts
@@ -0,0 +1,34 @@
+export type BinaryResponse = {
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */
+ bodyUsed: Response["bodyUsed"];
+ /**
+ * Returns a ReadableStream of the response body.
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body)
+ */
+ stream: () => Response["body"];
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */
+ arrayBuffer: () => ReturnType<Response["arrayBuffer"]>;
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */
+ blob: () => ReturnType<Response["blob"]>;
+ /**
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes)
+ * Some versions of the Fetch API may not support this method.
+ */
+ bytes?(): Promise<Uint8Array>;
+};
+
+export function getBinaryResponse(response: Response): BinaryResponse {
+ const binaryResponse: BinaryResponse = {
+ get bodyUsed() {
+ return response.bodyUsed;
+ },
+ stream: () => response.body,
+ arrayBuffer: response.arrayBuffer.bind(response),
+ blob: response.blob.bind(response),
+ };
+ if ("bytes" in response && typeof response.bytes === "function") {
+ binaryResponse.bytes = response.bytes.bind(response);
+ }
+
+ return binaryResponse;
+}
diff --git a/packages/sdk/src/core/fetcher/EndpointMetadata.ts b/packages/sdk/src/core/fetcher/EndpointMetadata.ts
new file mode 100644
index 000000000..998d68f5c
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/EndpointMetadata.ts
@@ -0,0 +1,13 @@
+export type SecuritySchemeKey = string;
+/**
+ * A collection of security schemes, where the key is the name of the security scheme and the value is the list of scopes required for that scheme.
+ * All schemes in the collection must be satisfied for authentication to be successful.
+ */
+export type SecuritySchemeCollection = Record<SecuritySchemeKey, AuthScope[]>;
+export type AuthScope = string;
+export type EndpointMetadata = {
+ /**
+ * An array of security scheme collections. Each collection represents an alternative way to authenticate.
+ */
+ security?: SecuritySchemeCollection[];
+};
diff --git a/packages/sdk/src/core/fetcher/EndpointSupplier.ts b/packages/sdk/src/core/fetcher/EndpointSupplier.ts
new file mode 100644
index 000000000..aad81f0d9
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/EndpointSupplier.ts
@@ -0,0 +1,14 @@
+import type { EndpointMetadata } from "./EndpointMetadata.js";
+import type { Supplier } from "./Supplier.js";
+
+type EndpointSupplierFn<T> = (arg: { endpointMetadata?: EndpointMetadata }) => T | Promise<T>;
+export type EndpointSupplier<T> = Supplier<T> | EndpointSupplierFn<T>;
+export const EndpointSupplier = {
+ get: async <T>(supplier: EndpointSupplier<T>, arg: { endpointMetadata?: EndpointMetadata }): Promise<T> => {
+ if (typeof supplier === "function") {
+ return (supplier as EndpointSupplierFn<T>)(arg);
+ } else {
+ return supplier;
+ }
+ },
+};
diff --git a/packages/sdk/src/core/fetcher/Fetcher.ts b/packages/sdk/src/core/fetcher/Fetcher.ts
new file mode 100644
index 000000000..cd5c5793d
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/Fetcher.ts
@@ -0,0 +1,311 @@
+import { toJson } from "../json.js";
+import { createLogger, type LogConfig, type Logger } from "../logging/logger.js";
+import type { APIResponse } from "./APIResponse.js";
+import { createRequestUrl } from "./createRequestUrl.js";
+import type { EndpointMetadata } from "./EndpointMetadata.js";
+import { EndpointSupplier } from "./EndpointSupplier.js";
+import { getErrorResponseBody } from "./getErrorResponseBody.js";
+import { getFetchFn } from "./getFetchFn.js";
+import { getRequestBody } from "./getRequestBody.js";
+import { getResponseBody } from "./getResponseBody.js";
+import { Headers } from "./Headers.js";
+import { makeRequest } from "./makeRequest.js";
+import { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse.js";
+import { redactUrl, SENSITIVE_QUERY_PARAMS } from "./redactUrl.js";
+import { requestWithRetries } from "./requestWithRetries.js";
+
+export type FetchFunction = <R = unknown>(args: Fetcher.Args) => Promise<APIResponse<R, Fetcher.Error>>;
+
+export declare namespace Fetcher {
+ export interface Args {
+ url: string;
+ method: string;
+ contentType?: string;
+ headers?: Record<string, unknown>;
+ /**
+ * @deprecated Prefer `queryString` (produced by `core.url.queryBuilder()`).
+ * Retained for backwards compatibility with custom fetchers and callers that
+ * still construct request args with a query-parameter object.
+ */
+ queryParameters?: Record<string, unknown>;
+ queryString?: string;
+ body?: unknown;
+ timeoutMs?: number;
+ maxRetries?: number;
+ withCredentials?: boolean;
+ abortSignal?: AbortSignal;
+ requestType?: "json" | "file" | "bytes" | "form" | "other";
+ responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer" | "binary-response";
+ duplex?: "half";
+ endpointMetadata?: EndpointMetadata;
+ fetchFn?: typeof fetch;
+ logging?: LogConfig | Logger;
+ }
+
+ export type Error = FailedStatusCodeError | NonJsonError | BodyIsNullError | TimeoutError | UnknownError;
+
+ export interface FailedStatusCodeError {
+ reason: "status-code";
+ statusCode: number;
+ body: unknown;
+ }
+
+ export interface NonJsonError {
+ reason: "non-json";
+ statusCode: number;
+ rawBody: string;
+ }
+
+ export interface BodyIsNullError {
+ reason: "body-is-null";
+ statusCode: number;
+ }
+
+ export interface TimeoutError {
+ reason: "timeout";
+ cause?: unknown;
+ }
+
+ export interface UnknownError {
+ reason: "unknown";
+ errorMessage: string;
+ cause?: unknown;
+ }
+}
+
+const SENSITIVE_HEADERS = new Set([
+ "authorization",
+ "www-authenticate",
+ "x-api-key",
+ "api-key",
+ "apikey",
+ "x-api-token",
+ "x-auth-token",
+ "auth-token",
+ "cookie",
+ "set-cookie",
+ "proxy-authorization",
+ "proxy-authenticate",
+ "x-csrf-token",
+ "x-xsrf-token",
+ "x-session-token",
+ "x-access-token",
+]);
+
+function redactHeaders(headers: Headers | Record<string, string>): Record<string, string> {
+ const filtered: Record<string, string> = {};
+ for (const [key, value] of headers instanceof Headers ? headers.entries() : Object.entries(headers)) {
+ if (SENSITIVE_HEADERS.has(key.toLowerCase())) {
+ filtered[key] = "[REDACTED]";
+ } else {
+ filtered[key] = value;
+ }
+ }
+ return filtered;
+}
+
+function redactQueryParameters(
+ queryParameters: Record<string, unknown> | undefined,
+): Record<string, unknown> | undefined {
+ if (queryParameters == null) {
+ return undefined;
+ }
+ const redacted: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(queryParameters)) {
+ redacted[key] = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase()) ? "[REDACTED]" : value;
+ }
+ return redacted;
+}
+
+async function getHeaders(args: Fetcher.Args): Promise<Headers> {
+ const newHeaders: Headers = new Headers();
+
+ newHeaders.set(
+ "Accept",
+ args.responseType === "json"
+ ? "application/json"
+ : args.responseType === "text"
+ ? "text/plain"
+ : args.responseType === "sse"
+ ? "text/event-stream"
+ : "*/*",
+ );
+ if (args.body !== undefined && args.contentType != null) {
+ newHeaders.set("Content-Type", args.contentType);
+ }
+
+ if (args.headers == null) {
+ return newHeaders;
+ }
+
+ for (const [key, value] of Object.entries(args.headers)) {
+ const result = await EndpointSupplier.get(value, { endpointMetadata: args.endpointMetadata ?? {} });
+ if (typeof result === "string") {
+ newHeaders.set(key, result);
+ continue;
+ }
+ if (result == null) {
+ continue;
+ }
+ newHeaders.set(key, `${result}`);
+ }
+ return newHeaders;
+}
+
+export async function fetcherImpl<R = unknown>(args: Fetcher.Args): Promise<APIResponse<R, Fetcher.Error>> {
+ let url = args.url;
+ if (args.queryString != null && args.queryString.length > 0) {
+ url = `${url}?${args.queryString}`;
+ } else {
+ url = createRequestUrl(args.url, args.queryParameters);
+ }
+ const requestBody: BodyInit | undefined = await getRequestBody({
+ body: args.body,
+ type: args.requestType ?? "other",
+ });
+ const fetchFn = args.fetchFn ?? (await getFetchFn());
+ const headers = await getHeaders(args);
+ const logger = createLogger(args.logging);
+
+ if (logger.isDebug()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ headers: redactHeaders(headers),
+ queryParameters: redactQueryParameters(args.queryParameters),
+ hasBody: requestBody != null,
+ };
+ logger.debug("Making HTTP request", metadata);
+ }
+
+ try {
+ const response = await requestWithRetries(
+ async () =>
+ makeRequest(
+ fetchFn,
+ url,
+ args.method,
+ headers,
+ requestBody,
+ args.timeoutMs,
+ args.abortSignal,
+ args.withCredentials,
+ args.duplex,
+ args.responseType === "streaming" || args.responseType === "sse",
+ ),
+ args.maxRetries,
+ );
+
+ if (response.status >= 200 && response.status < 400) {
+ if (logger.isDebug()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ statusCode: response.status,
+ responseHeaders: redactHeaders(response.headers),
+ };
+ logger.debug("HTTP request succeeded", metadata);
+ }
+ const body = await getResponseBody(response, args.responseType);
+ return {
+ ok: true,
+ body: body as R,
+ headers: response.headers,
+ rawResponse: toRawResponse(response),
+ };
+ } else {
+ if (logger.isError()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ statusCode: response.status,
+ responseHeaders: redactHeaders(Object.fromEntries(response.headers.entries())),
+ };
+ logger.error("HTTP request failed with error status", metadata);
+ }
+ return {
+ ok: false,
+ error: {
+ reason: "status-code",
+ statusCode: response.status,
+ body: await getErrorResponseBody(response),
+ },
+ rawResponse: toRawResponse(response),
+ };
+ }
+ } catch (error) {
+ if (args.abortSignal?.aborted) {
+ if (logger.isError()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ };
+ logger.error("HTTP request was aborted", metadata);
+ }
+ return {
+ ok: false,
+ error: {
+ reason: "unknown",
+ errorMessage: "The user aborted a request",
+ cause: error,
+ },
+ rawResponse: abortRawResponse,
+ };
+ } else if (error instanceof Error && error.name === "AbortError") {
+ if (logger.isError()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ timeoutMs: args.timeoutMs,
+ };
+ logger.error("HTTP request timed out", metadata);
+ }
+ return {
+ ok: false,
+ error: {
+ reason: "timeout",
+ cause: error,
+ },
+ rawResponse: abortRawResponse,
+ };
+ } else if (error instanceof Error) {
+ if (logger.isError()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ errorMessage: error.message,
+ };
+ logger.error("HTTP request failed with error", metadata);
+ }
+ return {
+ ok: false,
+ error: {
+ reason: "unknown",
+ errorMessage: error.message,
+ cause: error,
+ },
+ rawResponse: unknownRawResponse,
+ };
+ }
+
+ if (logger.isError()) {
+ const metadata = {
+ method: args.method,
+ url: redactUrl(url),
+ error: toJson(error),
+ };
+ logger.error("HTTP request failed with unknown error", metadata);
+ }
+ return {
+ ok: false,
+ error: {
+ reason: "unknown",
+ errorMessage: toJson(error),
+ cause: error,
+ },
+ rawResponse: unknownRawResponse,
+ };
+ }
+}
+
+export const fetcher: FetchFunction = fetcherImpl;
diff --git a/packages/sdk/src/core/fetcher/Headers.ts b/packages/sdk/src/core/fetcher/Headers.ts
new file mode 100644
index 000000000..f02246c50
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/Headers.ts
@@ -0,0 +1,93 @@
+let Headers: typeof globalThis.Headers;
+
+if (typeof globalThis.Headers !== "undefined") {
+ Headers = globalThis.Headers;
+} else {
+ Headers = class Headers implements Headers {
+ private headers: Map<string, string[]>;
+
+ constructor(init?: HeadersInit) {
+ this.headers = new Map();
+
+ if (init) {
+ if (init instanceof Headers) {
+ init.forEach((value, key) => this.append(key, value));
+ } else if (Array.isArray(init)) {
+ for (const [key, value] of init) {
+ if (typeof key === "string" && typeof value === "string") {
+ this.append(key, value);
+ } else {
+ throw new TypeError("Each header entry must be a [string, string] tuple");
+ }
+ }
+ } else {
+ for (const [key, value] of Object.entries(init)) {
+ if (typeof value === "string") {
+ this.append(key, value);
+ } else {
+ throw new TypeError("Header values must be strings");
+ }
+ }
+ }
+ }
+ }
+
+ append(name: string, value: string): void {
+ const key = name.toLowerCase();
+ const existing = this.headers.get(key) || [];
+ this.headers.set(key, [...existing, value]);
+ }
+
+ delete(name: string): void {
+ const key = name.toLowerCase();
+ this.headers.delete(key);
+ }
+
+ get(name: string): string | null {
+ const key = name.toLowerCase();
+ const values = this.headers.get(key);
+ return values ? values.join(", ") : null;
+ }
+
+ has(name: string): boolean {
+ const key = name.toLowerCase();
+ return this.headers.has(key);
+ }
+
+ set(name: string, value: string): void {
+ const key = name.toLowerCase();
+ this.headers.set(key, [value]);
+ }
+
+ forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: unknown): void {
+ const boundCallback = thisArg ? callbackfn.bind(thisArg) : callbackfn;
+ this.headers.forEach((values, key) => boundCallback(values.join(", "), key, this));
+ }
+
+ getSetCookie(): string[] {
+ return this.headers.get("set-cookie") || [];
+ }
+
+ *entries(): IterableIterator<[string, string]> {
+ for (const [key, values] of this.headers.entries()) {
+ yield [key, values.join(", ")];
+ }
+ }
+
+ *keys(): IterableIterator<string> {
+ yield* this.headers.keys();
+ }
+
+ *values(): IterableIterator<string> {
+ for (const values of this.headers.values()) {
+ yield values.join(", ");
+ }
+ }
+
+ [Symbol.iterator](): IterableIterator<[string, string]> {
+ return this.entries();
+ }
+ };
+}
+
+export { Headers };
diff --git a/packages/sdk/src/core/fetcher/HttpResponsePromise.ts b/packages/sdk/src/core/fetcher/HttpResponsePromise.ts
new file mode 100644
index 000000000..692ca7d79
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/HttpResponsePromise.ts
@@ -0,0 +1,116 @@
+import type { WithRawResponse } from "./RawResponse.js";
+
+/**
+ * A promise that returns the parsed response and lets you retrieve the raw response too.
+ */
+export class HttpResponsePromise<T> extends Promise<T> {
+ private innerPromise: Promise<WithRawResponse<T>>;
+ private unwrappedPromise: Promise<T> | undefined;
+
+ private constructor(promise: Promise<WithRawResponse<T>>) {
+ // Initialize with a no-op to avoid premature parsing
+ super((resolve) => {
+ resolve(undefined as unknown as T);
+ });
+ this.innerPromise = promise;
+ }
+
+ /**
+ * Creates an `HttpResponsePromise` from a function that returns a promise.
+ *
+ * @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
+ * @param args - Arguments to pass to the function.
+ * @returns An `HttpResponsePromise` instance.
+ */
+ public static fromFunction<F extends (...args: never[]) => Promise<WithRawResponse<T>>, T>(
+ fn: F,
+ ...args: Parameters<F>
+ ): HttpResponsePromise<T> {
+ return new HttpResponsePromise<T>(fn(...args));
+ }
+
+ /**
+ * Creates a function that returns an `HttpResponsePromise` from a function that returns a promise.
+ *
+ * @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
+ * @returns A function that returns an `HttpResponsePromise` instance.
+ */
+ public static interceptFunction<
+ F extends (...args: never[]) => Promise<WithRawResponse<T>>,
+ T = Awaited<ReturnType<F>>["data"],
+ >(fn: F): (...args: Parameters<F>) => HttpResponsePromise<T> {
+ return (...args: Parameters<F>): HttpResponsePromise<T> => {
+ return HttpResponsePromise.fromPromise<T>(fn(...args));
+ };
+ }
+
+ /**
+ * Creates an `HttpResponsePromise` from an existing promise.
+ *
+ * @param promise - A promise resolving to a `WithRawResponse` object.
+ * @returns An `HttpResponsePromise` instance.
+ */
+ public static fromPromise<T>(promise: Promise<WithRawResponse<T>>): HttpResponsePromise<T> {
+ return new HttpResponsePromise<T>(promise);
+ }
+
+ /**
+ * Creates an `HttpResponsePromise` from an executor function.
+ *
+ * @param executor - A function that takes resolve and reject callbacks to create a promise.
+ * @returns An `HttpResponsePromise` instance.
+ */
+ public static fromExecutor<T>(
+ executor: (resolve: (value: WithRawResponse<T>) => void, reject: (reason?: unknown) => void) => void,
+ ): HttpResponsePromise<T> {
+ const promise = new Promise<WithRawResponse<T>>(executor);
+ return new HttpResponsePromise<T>(promise);
+ }
+
+ /**
+ * Creates an `HttpResponsePromise` from a resolved result.
+ *
+ * @param result - A `WithRawResponse` object to resolve immediately.
+ * @returns An `HttpResponsePromise` instance.
+ */
+ public static fromResult<T>(result: WithRawResponse<T>): HttpResponsePromise<T> {
+ const promise = Promise.resolve(result);
+ return new HttpResponsePromise<T>(promise);
+ }
+
+ private unwrap(): Promise<T> {
+ if (!this.unwrappedPromise) {
+ this.unwrappedPromise = this.innerPromise.then(({ data }) => data);
+ }
+ return this.unwrappedPromise;
+ }
+
+ /** @inheritdoc */
+ public override then<TResult1 = T, TResult2 = never>(
+ onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
+ onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
+ ): Promise<TResult1 | TResult2> {
+ return this.unwrap().then(onfulfilled, onrejected);
+ }
+
+ /** @inheritdoc */
+ public override catch<TResult = never>(
+ onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
+ ): Promise<T | TResult> {
+ return this.unwrap().catch(onrejected);
+ }
+
+ /** @inheritdoc */
+ public override finally(onfinally?: (() => void) | null): Promise<T> {
+ return this.unwrap().finally(onfinally);
+ }
+
+ /**
+ * Retrieves the data and raw response.
+ *
+ * @returns A promise resolving to a `WithRawResponse` object.
+ */
+ public async withRawResponse(): Promise<WithRawResponse<T>> {
+ return await this.innerPromise;
+ }
+}
diff --git a/packages/sdk/src/core/fetcher/RawResponse.ts b/packages/sdk/src/core/fetcher/RawResponse.ts
new file mode 100644
index 000000000..37fb44e2a
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/RawResponse.ts
@@ -0,0 +1,61 @@
+import { Headers } from "./Headers.js";
+
+/**
+ * The raw response from the fetch call excluding the body.
+ */
+export type RawResponse = Omit<
+ {
+ [K in keyof Response as Response[K] extends Function ? never : K]: Response[K]; // strips out functions
+ },
+ "ok" | "body" | "bodyUsed"
+>; // strips out body and bodyUsed
+
+/**
+ * A raw response indicating that the request was aborted.
+ */
+export const abortRawResponse: RawResponse = {
+ headers: new Headers(),
+ redirected: false,
+ status: 499,
+ statusText: "Client Closed Request",
+ type: "error",
+ url: "",
+} as const;
+
+/**
+ * A raw response indicating an unknown error.
+ */
+export const unknownRawResponse: RawResponse = {
+ headers: new Headers(),
+ redirected: false,
+ status: 0,
+ statusText: "Unknown Error",
+ type: "error",
+ url: "",
+} as const;
+
+/**
+ * Converts a `RawResponse` object into a `RawResponse` by extracting its properties,
+ * excluding the `body` and `bodyUsed` fields.
+ *
+ * @param response - The `RawResponse` object to convert.
+ * @returns A `RawResponse` object containing the extracted properties of the input response.
+ */
+export function toRawResponse(response: Response): RawResponse {
+ return {
+ headers: response.headers,
+ redirected: response.redirected,
+ status: response.status,
+ statusText: response.statusText,
+ type: response.type,
+ url: response.url,
+ };
+}
+
+/**
+ * Creates a `RawResponse` from a standard `Response` object.
+ */
+export interface WithRawResponse<T> {
+ readonly data: T;
+ readonly rawResponse: RawResponse;
+}
diff --git a/packages/sdk/src/core/fetcher/Supplier.ts b/packages/sdk/src/core/fetcher/Supplier.ts
new file mode 100644
index 000000000..867c931c0
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/Supplier.ts
@@ -0,0 +1,11 @@
+export type Supplier<T> = T | Promise<T> | (() => T | Promise<T>);
+
+export const Supplier = {
+ get: async <T>(supplier: Supplier<T>): Promise<T> => {
+ if (typeof supplier === "function") {
+ return (supplier as () => T)();
+ } else {
+ return supplier;
+ }
+ },
+};
diff --git a/packages/sdk/src/core/fetcher/createRequestUrl.ts b/packages/sdk/src/core/fetcher/createRequestUrl.ts
new file mode 100644
index 000000000..88e13265e
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/createRequestUrl.ts
@@ -0,0 +1,6 @@
+import { toQueryString } from "../url/qs.js";
+
+export function createRequestUrl(baseUrl: string, queryParameters?: Record<string, unknown>): string {
+ const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" });
+ return queryString ? `${baseUrl}?${queryString}` : baseUrl;
+}
diff --git a/packages/sdk/src/core/fetcher/getErrorResponseBody.ts b/packages/sdk/src/core/fetcher/getErrorResponseBody.ts
new file mode 100644
index 000000000..7cf4e623c
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/getErrorResponseBody.ts
@@ -0,0 +1,33 @@
+import { fromJson } from "../json.js";
+import { getResponseBody } from "./getResponseBody.js";
+
+export async function getErrorResponseBody(response: Response): Promise<unknown> {
+ let contentType = response.headers.get("Content-Type")?.toLowerCase();
+ if (contentType == null || contentType.length === 0) {
+ return getResponseBody(response);
+ }
+
+ if (contentType.indexOf(";") !== -1) {
+ contentType = contentType.split(";")[0]?.trim() ?? "";
+ }
+ switch (contentType) {
+ case "application/hal+json":
+ case "application/json":
+ case "application/ld+json":
+ case "application/problem+json":
+ case "application/vnd.api+json":
+ case "text/json": {
+ const text = await response.text();
+ return text.length > 0 ? fromJson(text) : undefined;
+ }
+ default:
+ if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) {
+ const text = await response.text();
+ return text.length > 0 ? fromJson(text) : undefined;
+ }
+
+ // Fallback to plain text if content type is not recognized
+ // Even if no body is present, the response will be an empty string
+ return await response.text();
+ }
+}
diff --git a/packages/sdk/src/core/fetcher/getFetchFn.ts b/packages/sdk/src/core/fetcher/getFetchFn.ts
new file mode 100644
index 000000000..9f845b956
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/getFetchFn.ts
@@ -0,0 +1,3 @@
+export async function getFetchFn(): Promise<typeof fetch> {
+ return fetch;
+}
diff --git a/packages/sdk/src/core/fetcher/getHeader.ts b/packages/sdk/src/core/fetcher/getHeader.ts
new file mode 100644
index 000000000..50f922b0e
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/getHeader.ts
@@ -0,0 +1,8 @@
+export function getHeader(headers: Record<string, any>, header: string): string | undefined {
+ for (const [headerKey, headerValue] of Object.entries(headers)) {
+ if (headerKey.toLowerCase() === header.toLowerCase()) {
+ return headerValue;
+ }
+ }
+ return undefined;
+}
diff --git a/packages/sdk/src/core/fetcher/getRequestBody.ts b/packages/sdk/src/core/fetcher/getRequestBody.ts
new file mode 100644
index 000000000..91d9d81f5
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/getRequestBody.ts
@@ -0,0 +1,20 @@
+import { toJson } from "../json.js";
+import { toQueryString } from "../url/qs.js";
+
+export declare namespace GetRequestBody {
+ interface Args {
+ body: unknown;
+ type: "json" | "file" | "bytes" | "form" | "other";
+ }
+}
+
+export async function getRequestBody({ body, type }: GetRequestBody.Args): Promise<BodyInit | undefined> {
+ if (type === "form") {
+ return toQueryString(body, { arrayFormat: "repeat", encode: true });
+ }
+ if (type.includes("json")) {
+ return toJson(body);
+ } else {
+ return body as BodyInit;
+ }
+}
diff --git a/packages/sdk/src/core/fetcher/getResponseBody.ts b/packages/sdk/src/core/fetcher/getResponseBody.ts
new file mode 100644
index 000000000..2e831e495
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/getResponseBody.ts
@@ -0,0 +1,70 @@
+import { fromJson } from "../json.js";
+import { getBinaryResponse } from "./BinaryResponse.js";
+
+// Pins the upstream Response so undici's FinalizationRegistry can't GC it and cancel the body stream.
+function retainResponse(target: object, response: Response): void {
+ Object.defineProperty(target, "__fern_response_ref", {
+ value: response,
+ enumerable: false,
+ configurable: true,
+ writable: false,
+ });
+}
+
+export async function getResponseBody(response: Response, responseType?: string): Promise<unknown> {
+ switch (responseType) {
+ case "binary-response":
+ return getBinaryResponse(response);
+ case "blob":
+ return await response.blob();
+ case "arrayBuffer":
+ return await response.arrayBuffer();
+ case "sse":
+ if (response.body == null) {
+ return {
+ ok: false,
+ error: {
+ reason: "body-is-null",
+ statusCode: response.status,
+ },
+ };
+ }
+ retainResponse(response.body, response);
+ return response.body;
+ case "streaming":
+ if (response.body == null) {
+ return {
+ ok: false,
+ error: {
+ reason: "body-is-null",
+ statusCode: response.status,
+ },
+ };
+ }
+
+ retainResponse(response.body, response);
+ return response.body;
+
+ case "text":
+ return await response.text();
+ }
+
+ // if responseType is "json" or not specified, try to parse as JSON
+ const text = await response.text();
+ if (text.length > 0) {
+ try {
+ const responseBody = fromJson(text);
+ return responseBody;
+ } catch (_err) {
+ return {
+ ok: false,
+ error: {
+ reason: "non-json",
+ statusCode: response.status,
+ rawBody: text,
+ },
+ };
+ }
+ }
+ return undefined;
+}
diff --git a/packages/sdk/src/core/fetcher/index.ts b/packages/sdk/src/core/fetcher/index.ts
new file mode 100644
index 000000000..bd5db362c
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/index.ts
@@ -0,0 +1,13 @@
+export type { APIResponse } from "./APIResponse.js";
+export type { BinaryResponse } from "./BinaryResponse.js";
+export type { EndpointMetadata } from "./EndpointMetadata.js";
+export { EndpointSupplier } from "./EndpointSupplier.js";
+export type { Fetcher, FetchFunction } from "./Fetcher.js";
+export { fetcher } from "./Fetcher.js";
+export { getHeader } from "./getHeader.js";
+export { HttpResponsePromise } from "./HttpResponsePromise.js";
+export type { PassthroughRequest } from "./makePassthroughRequest.js";
+export { makePassthroughRequest } from "./makePassthroughRequest.js";
+export type { RawResponse, WithRawResponse } from "./RawResponse.js";
+export { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse.js";
+export { Supplier } from "./Supplier.js";
diff --git a/packages/sdk/src/core/fetcher/makePassthroughRequest.ts b/packages/sdk/src/core/fetcher/makePassthroughRequest.ts
new file mode 100644
index 000000000..e8dceda93
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/makePassthroughRequest.ts
@@ -0,0 +1,211 @@
+import { createLogger, type LogConfig, type Logger } from "../logging/logger.js";
+import { join } from "../url/join.js";
+import { EndpointSupplier } from "./EndpointSupplier.js";
+import { getFetchFn } from "./getFetchFn.js";
+import { makeRequest } from "./makeRequest.js";
+import { redactUrl } from "./redactUrl.js";
+import { requestWithRetries } from "./requestWithRetries.js";
+import { Supplier } from "./Supplier.js";
+
+export declare namespace PassthroughRequest {
+ /**
+ * Per-request options that can override the SDK client defaults.
+ */
+ export interface RequestOptions {
+ /** Override the default timeout for this request (in seconds). */
+ timeoutInSeconds?: number;
+ /** Override the default number of retries for this request. */
+ maxRetries?: number;
+ /** Additional headers to include in this request. */
+ headers?: Record<string, string>;
+ /** Abort signal for this request. */
+ abortSignal?: AbortSignal;
+ }
+
+ /**
+ * SDK client configuration used by the passthrough fetch method.
+ */
+ export interface ClientOptions {
+ /** The base URL or environment for the client. */
+ environment?: Supplier<string>;
+ /** Override the base URL. */
+ baseUrl?: Supplier<string>;
+ /** Default headers to include in requests. */
+ headers?: Record<string, unknown>;
+ /** Default maximum time to wait for a response in seconds. */
+ timeoutInSeconds?: number;
+ /** Default number of times to retry the request. Defaults to 2. */
+ maxRetries?: number;
+ /** A custom fetch function. */
+ fetch?: typeof fetch;
+ /** Logging configuration. */
+ logging?: LogConfig | Logger;
+ /** A function that returns auth headers. */
+ getAuthHeaders?: () => Promise<Record<string, string>>;
+ }
+}
+
+/**
+ * Makes a passthrough HTTP request using the SDK's configuration (auth, retry, logging, etc.)
+ * while mimicking the standard `fetch` API.
+ *
+ * @param input - The URL, path, or Request object. If a relative path, it will be resolved against the configured base URL.
+ * @param init - Standard RequestInit options (method, headers, body, signal, etc.)
+ * @param clientOptions - SDK client options (auth, default headers, logging, etc.)
+ * @param requestOptions - Per-request overrides (timeout, retries, extra headers, abort signal).
+ * @returns A standard Response object.
+ */
+export async function makePassthroughRequest(
+ input: Request | string | URL,
+ init: RequestInit | undefined,
+ clientOptions: PassthroughRequest.ClientOptions,
+ requestOptions?: PassthroughRequest.RequestOptions,
+): Promise<Response> {
+ const logger = createLogger(clientOptions.logging);
+
+ // Extract URL and default init properties from Request object if provided
+ let url: string;
+ let effectiveInit: RequestInit | undefined = init;
+ if (input instanceof Request) {
+ url = input.url;
+ // If no explicit init provided, extract properties from the Request object
+ if (init == null) {
+ effectiveInit = {
+ method: input.method,
+ headers: Object.fromEntries(input.headers.entries()),
+ body: input.body,
+ signal: input.signal,
+ credentials: input.credentials,
+ cache: input.cache as RequestCache,
+ redirect: input.redirect,
+ referrer: input.referrer,
+ integrity: input.integrity,
+ mode: input.mode,
+ };
+ }
+ } else {
+ url = input instanceof URL ? input.toString() : input;
+ }
+
+ // Resolve the base URL
+ const baseUrl =
+ (clientOptions.baseUrl != null ? await Supplier.get(clientOptions.baseUrl) : undefined) ??
+ (clientOptions.environment != null ? await Supplier.get(clientOptions.environment) : undefined);
+
+ // Determine the full URL
+ let fullUrl: string;
+ if (url.startsWith("http://") || url.startsWith("https://")) {
+ fullUrl = url;
+ } else if (baseUrl != null) {
+ fullUrl = join(baseUrl, url);
+ } else {
+ fullUrl = url;
+ }
+
+ // Merge headers: SDK default headers -> auth headers -> user-provided headers
+ const mergedHeaders: Record<string, string> = {};
+
+ // Apply SDK default headers (resolve suppliers)
+ if (clientOptions.headers != null) {
+ for (const [key, value] of Object.entries(clientOptions.headers)) {
+ const resolved = await EndpointSupplier.get(value, { endpointMetadata: {} });
+ if (resolved != null) {
+ mergedHeaders[key.toLowerCase()] = `${resolved}`;
+ }
+ }
+ }
+
+ // Apply auth headers, but only when the resolved URL targets the configured base URL.
+ // This prevents the SDK's credentials from leaking to an unrelated host when a caller
+ // passes an absolute cross-origin URL into the passthrough fetch escape hatch.
+ if (clientOptions.getAuthHeaders != null && targetsBaseUrl(fullUrl, baseUrl)) {
+ const authHeaders = await clientOptions.getAuthHeaders();
+ for (const [key, value] of Object.entries(authHeaders)) {
+ mergedHeaders[key.toLowerCase()] = value;
+ }
+ }
+
+ // Apply user-provided headers from init
+ if (effectiveInit?.headers != null) {
+ const initHeaders =
+ effectiveInit.headers instanceof Headers
+ ? Object.fromEntries(effectiveInit.headers.entries())
+ : Array.isArray(effectiveInit.headers)
+ ? Object.fromEntries(effectiveInit.headers)
+ : effectiveInit.headers;
+ for (const [key, value] of Object.entries(initHeaders)) {
+ if (value != null) {
+ mergedHeaders[key.toLowerCase()] = value;
+ }
+ }
+ }
+
+ // Apply per-request option headers (highest priority)
+ if (requestOptions?.headers != null) {
+ for (const [key, value] of Object.entries(requestOptions.headers)) {
+ mergedHeaders[key.toLowerCase()] = value;
+ }
+ }
+
+ const method = effectiveInit?.method ?? "GET";
+ const body = effectiveInit?.body;
+ const timeoutInSeconds = requestOptions?.timeoutInSeconds ?? clientOptions.timeoutInSeconds;
+ const timeoutMs = timeoutInSeconds != null ? timeoutInSeconds * 1000 : undefined;
+ const maxRetries = requestOptions?.maxRetries ?? clientOptions.maxRetries;
+ const abortSignal = requestOptions?.abortSignal ?? effectiveInit?.signal ?? undefined;
+ const fetchFn = clientOptions.fetch ?? (await getFetchFn());
+
+ if (logger.isDebug()) {
+ logger.debug("Making passthrough HTTP request", {
+ method,
+ url: redactUrl(fullUrl),
+ hasBody: body != null,
+ });
+ }
+
+ const response = await requestWithRetries(
+ async () =>
+ makeRequest(
+ fetchFn,
+ fullUrl,
+ method,
+ mergedHeaders,
+ body ?? undefined,
+ timeoutMs,
+ abortSignal,
+ effectiveInit?.credentials === "include",
+ undefined, // duplex
+ false, // disableCache
+ ),
+ maxRetries,
+ );
+
+ if (logger.isDebug()) {
+ logger.debug("Passthrough HTTP request completed", {
+ method,
+ url: redactUrl(fullUrl),
+ statusCode: response.status,
+ });
+ }
+
+ return response;
+}
+
+/**
+ * Returns true when the resolved request URL points at the same origin as the
+ * configured base URL. Relative paths are always joined onto the base URL, so
+ * they resolve to the base origin and return true. Absolute URLs only match when
+ * their origin equals the base origin. When there is no base URL to compare
+ * against, or either value is not a parseable absolute URL, this returns false so
+ * auth headers are not attached.
+ */
+function targetsBaseUrl(fullUrl: string, baseUrl: string | undefined): boolean {
+ if (baseUrl == null) {
+ return false;
+ }
+ try {
+ return new URL(fullUrl).origin === new URL(baseUrl).origin;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/sdk/src/core/fetcher/makeRequest.ts b/packages/sdk/src/core/fetcher/makeRequest.ts
new file mode 100644
index 000000000..360a86df4
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/makeRequest.ts
@@ -0,0 +1,70 @@
+import { anySignal, getTimeoutSignal } from "./signals.js";
+
+/**
+ * Cached result of checking whether the current runtime supports
+ * the `cache` option in `Request`. Some runtimes (e.g. Cloudflare Workers)
+ * throw a TypeError when this option is used.
+ */
+let _cacheNoStoreSupported: boolean | undefined;
+export function isCacheNoStoreSupported(): boolean {
+ if (_cacheNoStoreSupported != null) {
+ return _cacheNoStoreSupported;
+ }
+ try {
+ new Request("http://localhost", { cache: "no-store" });
+ _cacheNoStoreSupported = true;
+ } catch {
+ _cacheNoStoreSupported = false;
+ }
+ return _cacheNoStoreSupported;
+}
+
+/**
+ * Reset the cached result of `isCacheNoStoreSupported`. Exposed for testing only.
+ */
+export function resetCacheNoStoreSupported(): void {
+ _cacheNoStoreSupported = undefined;
+}
+
+export const makeRequest = async (
+ fetchFn: (url: string, init: RequestInit) => Promise<Response>,
+ url: string,
+ method: string,
+ headers: Headers | Record<string, string>,
+ requestBody: BodyInit | undefined,
+ timeoutMs?: number,
+ abortSignal?: AbortSignal,
+ withCredentials?: boolean,
+ duplex?: "half",
+ disableCache?: boolean,
+): Promise<Response> => {
+ const signals: AbortSignal[] = [];
+
+ let timeoutAbortId: ReturnType<typeof setTimeout> | undefined;
+ if (timeoutMs != null) {
+ const { signal, abortId } = getTimeoutSignal(timeoutMs);
+ timeoutAbortId = abortId;
+ signals.push(signal);
+ }
+
+ if (abortSignal != null) {
+ signals.push(abortSignal);
+ }
+ const newSignals = anySignal(signals);
+ const response = await fetchFn(url, {
+ method: method,
+ headers,
+ body: requestBody,
+ signal: newSignals,
+ credentials: withCredentials ? "include" : undefined,
+ // @ts-ignore
+ duplex,
+ ...(disableCache && isCacheNoStoreSupported() ? { cache: "no-store" as RequestCache } : {}),
+ });
+
+ if (timeoutAbortId != null) {
+ clearTimeout(timeoutAbortId);
+ }
+
+ return response;
+};
diff --git a/packages/sdk/src/core/fetcher/redactUrl.ts b/packages/sdk/src/core/fetcher/redactUrl.ts
new file mode 100644
index 000000000..3c2e897a6
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/redactUrl.ts
@@ -0,0 +1,102 @@
+export const SENSITIVE_QUERY_PARAMS: Set<string> = new Set([
+ "api_key",
+ "api-key",
+ "apikey",
+ "token",
+ "access_token",
+ "access-token",
+ "auth_token",
+ "auth-token",
+ "password",
+ "passwd",
+ "secret",
+ "api_secret",
+ "api-secret",
+ "apisecret",
+ "key",
+ "session",
+ "session_id",
+ "session-id",
+]);
+
+export function redactUrl(url: string): string {
+ const protocolIndex = url.indexOf("://");
+ if (protocolIndex === -1) return url;
+
+ const afterProtocol = protocolIndex + 3;
+
+ // Find the first delimiter that marks the end of the authority section
+ const pathStart = url.indexOf("/", afterProtocol);
+ let queryStart = url.indexOf("?", afterProtocol);
+ let fragmentStart = url.indexOf("#", afterProtocol);
+
+ const firstDelimiter = Math.min(
+ pathStart === -1 ? url.length : pathStart,
+ queryStart === -1 ? url.length : queryStart,
+ fragmentStart === -1 ? url.length : fragmentStart,
+ );
+
+ // Find the LAST @ before the delimiter (handles multiple @ in credentials)
+ let atIndex = -1;
+ for (let i = afterProtocol; i < firstDelimiter; i++) {
+ if (url[i] === "@") {
+ atIndex = i;
+ }
+ }
+
+ if (atIndex !== -1) {
+ url = `${url.slice(0, afterProtocol)}[REDACTED]@${url.slice(atIndex + 1)}`;
+ }
+
+ // Recalculate queryStart since url might have changed
+ queryStart = url.indexOf("?");
+ if (queryStart === -1) return url;
+
+ fragmentStart = url.indexOf("#", queryStart);
+ const queryEnd = fragmentStart !== -1 ? fragmentStart : url.length;
+ const queryString = url.slice(queryStart + 1, queryEnd);
+
+ if (queryString.length === 0) return url;
+
+ // FAST PATH: Quick check if any sensitive keywords present
+ // Using indexOf is faster than regex for simple substring matching
+ const lower = queryString.toLowerCase();
+ const hasSensitive =
+ lower.includes("token") ||
+ lower.includes("key") ||
+ lower.includes("password") ||
+ lower.includes("passwd") ||
+ lower.includes("secret") ||
+ lower.includes("session") ||
+ lower.includes("auth");
+
+ if (!hasSensitive) {
+ return url;
+ }
+
+ // SLOW PATH: Parse and redact
+ const redactedParams: string[] = [];
+ const params = queryString.split("&");
+
+ for (const param of params) {
+ const equalIndex = param.indexOf("=");
+ if (equalIndex === -1) {
+ redactedParams.push(param);
+ continue;
+ }
+
+ const key = param.slice(0, equalIndex);
+ let shouldRedact = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase());
+
+ if (!shouldRedact && key.includes("%")) {
+ try {
+ const decodedKey = decodeURIComponent(key);
+ shouldRedact = SENSITIVE_QUERY_PARAMS.has(decodedKey.toLowerCase());
+ } catch {}
+ }
+
+ redactedParams.push(shouldRedact ? `${key}=[REDACTED]` : param);
+ }
+
+ return url.slice(0, queryStart + 1) + redactedParams.join("&") + url.slice(queryEnd);
+}
diff --git a/packages/sdk/src/core/fetcher/requestWithRetries.ts b/packages/sdk/src/core/fetcher/requestWithRetries.ts
new file mode 100644
index 000000000..5e66b9330
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/requestWithRetries.ts
@@ -0,0 +1,68 @@
+const INITIAL_RETRY_DELAY = 1000; // in milliseconds
+const MAX_RETRY_DELAY = 60000; // in milliseconds
+const DEFAULT_MAX_RETRIES = 2;
+const JITTER_FACTOR = 0.2; // 20% random jitter
+
+function isRetryableStatusCode(statusCode: number): boolean {
+ return [408, 429].includes(statusCode) || statusCode >= 500;
+}
+
+function addPositiveJitter(delay: number): number {
+ const jitterMultiplier = 1 + Math.random() * JITTER_FACTOR;
+ return delay * jitterMultiplier;
+}
+
+function addSymmetricJitter(delay: number): number {
+ const jitterMultiplier = 1 + (Math.random() - 0.5) * JITTER_FACTOR;
+ return delay * jitterMultiplier;
+}
+
+function getRetryDelayFromHeaders(response: Response, retryAttempt: number): number {
+ const retryAfter = response.headers.get("Retry-After");
+ if (retryAfter) {
+ const retryAfterSeconds = parseInt(retryAfter, 10);
+ if (!Number.isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {
+ return Math.min(retryAfterSeconds * 1000, MAX_RETRY_DELAY);
+ }
+
+ const retryAfterDate = new Date(retryAfter);
+ if (!Number.isNaN(retryAfterDate.getTime())) {
+ const delay = retryAfterDate.getTime() - Date.now();
+ if (delay > 0) {
+ return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY);
+ }
+ }
+ }
+
+ const rateLimitReset = response.headers.get("X-RateLimit-Reset");
+ if (rateLimitReset) {
+ const resetTime = parseInt(rateLimitReset, 10);
+ if (!Number.isNaN(resetTime)) {
+ const delay = resetTime * 1000 - Date.now();
+ if (delay > 0) {
+ return addPositiveJitter(Math.min(delay, MAX_RETRY_DELAY));
+ }
+ }
+ }
+
+ return addSymmetricJitter(Math.min(INITIAL_RETRY_DELAY * 2 ** retryAttempt, MAX_RETRY_DELAY));
+}
+
+export async function requestWithRetries(
+ requestFn: () => Promise<Response>,
+ maxRetries: number = DEFAULT_MAX_RETRIES,
+): Promise<Response> {
+ let response: Response = await requestFn();
+
+ for (let i = 0; i < maxRetries; ++i) {
+ if (isRetryableStatusCode(response.status)) {
+ const delay = getRetryDelayFromHeaders(response, i);
+
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ response = await requestFn();
+ } else {
+ break;
+ }
+ }
+ return response!;
+}
diff --git a/packages/sdk/src/core/fetcher/signals.ts b/packages/sdk/src/core/fetcher/signals.ts
new file mode 100644
index 000000000..ba74c4d02
--- /dev/null
+++ b/packages/sdk/src/core/fetcher/signals.ts
@@ -0,0 +1,35 @@
+const TIMEOUT = "timeout";
+
+export function getTimeoutSignal(timeoutMs: number): { signal: AbortSignal; abortId: ReturnType<typeof setTimeout> } {
+ const controller = new AbortController();
+ const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
+ return { signal: controller.signal, abortId };
+}
+
+export function anySignal(...args: AbortSignal[] | [AbortSignal[]]): AbortSignal {
+ const signals = (args.length === 1 && Array.isArray(args[0]) ? args[0] : args) as AbortSignal[];
+
+ const controller = new AbortController();
+
+ for (const signal of signals) {
+ if (signal.aborted) {
+ controller.abort((signal as any)?.reason);
+ return controller.signal;
+ }
+
+ signal.addEventListener("abort", () => controller.abort((signal as any)?.reason), {
+ signal: controller.signal,
+ });
+
+ // Re-check after adding listener: the signal may have aborted
+ // between the initial `signal.aborted` check and the `addEventListener`
+ // call above. If it did, the abort event was already dispatched and
+ // the listener will never fire — we must manually abort.
+ if (signal.aborted) {
+ controller.abort((signal as any)?.reason);
+ return controller.signal;
+ }
+ }
+
+ return controller.signal;
+}
diff --git a/packages/sdk/src/core/headers.ts b/packages/sdk/src/core/headers.ts
new file mode 100644
index 000000000..be45c4552
--- /dev/null
+++ b/packages/sdk/src/core/headers.ts
@@ -0,0 +1,33 @@
+export function mergeHeaders(...headersArray: (Record<string, unknown> | null | undefined)[]): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+
+ for (const [key, value] of headersArray
+ .filter((headers) => headers != null)
+ .flatMap((headers) => Object.entries(headers))) {
+ const insensitiveKey = key.toLowerCase();
+ if (value != null) {
+ result[insensitiveKey] = value;
+ } else if (insensitiveKey in result) {
+ delete result[insensitiveKey];
+ }
+ }
+
+ return result;
+}
+
+export function mergeOnlyDefinedHeaders(
+ ...headersArray: (Record<string, unknown> | null | undefined)[]
+): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+
+ for (const [key, value] of headersArray
+ .filter((headers) => headers != null)
+ .flatMap((headers) => Object.entries(headers))) {
+ const insensitiveKey = key.toLowerCase();
+ if (value != null) {
+ result[insensitiveKey] = value;
+ }
+ }
+
+ return result;
+}
diff --git a/packages/sdk/src/core/index.ts b/packages/sdk/src/core/index.ts
new file mode 100644
index 000000000..3e14a6db2
--- /dev/null
+++ b/packages/sdk/src/core/index.ts
@@ -0,0 +1,8 @@
+export * from "./fetcher/index.js";
+export * as logging from "./logging/index.js";
+export * from "./pagination/index.js";
+export * from "./runtime/index.js";
+export * as serialization from "./schemas/index.js";
+export * from "./stream/index.js";
+export * as url from "./url/index.js";
+export * from "./utils/index.js";
diff --git a/packages/sdk/src/core/json.ts b/packages/sdk/src/core/json.ts
new file mode 100644
index 000000000..c052f3249
--- /dev/null
+++ b/packages/sdk/src/core/json.ts
@@ -0,0 +1,27 @@
+/**
+ * Serialize a value to JSON
+ * @param value A JavaScript value, usually an object or array, to be converted.
+ * @param replacer A function that transforms the results.
+ * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
+ * @returns JSON string
+ */
+export const toJson = (
+ value: unknown,
+ replacer?: (this: unknown, key: string, value: unknown) => unknown,
+ space?: string | number,
+): string => {
+ return JSON.stringify(value, replacer, space);
+};
+
+/**
+ * Parse JSON string to object, array, or other type
+ * @param text A valid JSON string.
+ * @param reviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.
+ * @returns Parsed object, array, or other type
+ */
+export function fromJson<T = unknown>(
+ text: string,
+ reviver?: (this: unknown, key: string, value: unknown) => unknown,
+): T {
+ return JSON.parse(text, reviver);
+}
diff --git a/packages/sdk/src/core/logging/exports.ts b/packages/sdk/src/core/logging/exports.ts
new file mode 100644
index 000000000..88f6c00db
--- /dev/null
+++ b/packages/sdk/src/core/logging/exports.ts
@@ -0,0 +1,19 @@
+import * as logger from "./logger.js";
+
+export namespace logging {
+ /**
+ * Configuration for logger instances.
+ */
+ export type LogConfig = logger.LogConfig;
+ export type LogLevel = logger.LogLevel;
+ export const LogLevel: typeof logger.LogLevel = logger.LogLevel;
+ export type ILogger = logger.ILogger;
+ /**
+ * Console logger implementation that outputs to the console.
+ */
+ export type ConsoleLogger = logger.ConsoleLogger;
+ /**
+ * Console logger implementation that outputs to the console.
+ */
+ export const ConsoleLogger: typeof logger.ConsoleLogger = logger.ConsoleLogger;
+}
diff --git a/packages/sdk/src/core/logging/index.ts b/packages/sdk/src/core/logging/index.ts
new file mode 100644
index 000000000..d81cc32c4
--- /dev/null
+++ b/packages/sdk/src/core/logging/index.ts
@@ -0,0 +1 @@
+export * from "./logger.js";
diff --git a/packages/sdk/src/core/logging/logger.ts b/packages/sdk/src/core/logging/logger.ts
new file mode 100644
index 000000000..a3f3673cd
--- /dev/null
+++ b/packages/sdk/src/core/logging/logger.ts
@@ -0,0 +1,203 @@
+export const LogLevel = {
+ Debug: "debug",
+ Info: "info",
+ Warn: "warn",
+ Error: "error",
+} as const;
+export type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];
+const logLevelMap: Record<LogLevel, number> = {
+ [LogLevel.Debug]: 1,
+ [LogLevel.Info]: 2,
+ [LogLevel.Warn]: 3,
+ [LogLevel.Error]: 4,
+};
+
+export interface ILogger {
+ /**
+ * Logs a debug message.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ debug(message: string, ...args: unknown[]): void;
+ /**
+ * Logs an info message.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ info(message: string, ...args: unknown[]): void;
+ /**
+ * Logs a warning message.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ warn(message: string, ...args: unknown[]): void;
+ /**
+ * Logs an error message.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ error(message: string, ...args: unknown[]): void;
+}
+
+/**
+ * Configuration for logger initialization.
+ */
+export interface LogConfig {
+ /**
+ * Minimum log level to output.
+ * @default LogLevel.Info
+ */
+ level?: LogLevel;
+ /**
+ * Logger implementation to use.
+ * @default new ConsoleLogger()
+ */
+ logger?: ILogger;
+ /**
+ * Whether logging should be silenced.
+ * @default true
+ */
+ silent?: boolean;
+}
+
+/**
+ * Default console-based logger implementation.
+ */
+export class ConsoleLogger implements ILogger {
+ debug(message: string, ...args: unknown[]): void {
+ console.debug(message, ...args);
+ }
+ info(message: string, ...args: unknown[]): void {
+ console.info(message, ...args);
+ }
+ warn(message: string, ...args: unknown[]): void {
+ console.warn(message, ...args);
+ }
+ error(message: string, ...args: unknown[]): void {
+ console.error(message, ...args);
+ }
+}
+
+/**
+ * Logger class that provides level-based logging functionality.
+ */
+export class Logger {
+ private readonly level: number;
+ private readonly logger: ILogger;
+ private readonly silent: boolean;
+
+ /**
+ * Creates a new logger instance.
+ * @param config - Logger configuration
+ */
+ constructor(config: Required<LogConfig>) {
+ this.level = logLevelMap[config.level];
+ this.logger = config.logger;
+ this.silent = config.silent;
+ }
+
+ /**
+ * Checks if a log level should be output based on configuration.
+ * @param level - The log level to check
+ * @returns True if the level should be logged
+ */
+ public shouldLog(level: LogLevel): boolean {
+ return !this.silent && this.level <= logLevelMap[level];
+ }
+
+ /**
+ * Checks if debug logging is enabled.
+ * @returns True if debug logs should be output
+ */
+ public isDebug(): boolean {
+ return this.shouldLog(LogLevel.Debug);
+ }
+
+ /**
+ * Logs a debug message if debug logging is enabled.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ public debug(message: string, ...args: unknown[]): void {
+ if (this.isDebug()) {
+ this.logger.debug(message, ...args);
+ }
+ }
+
+ /**
+ * Checks if info logging is enabled.
+ * @returns True if info logs should be output
+ */
+ public isInfo(): boolean {
+ return this.shouldLog(LogLevel.Info);
+ }
+
+ /**
+ * Logs an info message if info logging is enabled.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ public info(message: string, ...args: unknown[]): void {
+ if (this.isInfo()) {
+ this.logger.info(message, ...args);
+ }
+ }
+
+ /**
+ * Checks if warning logging is enabled.
+ * @returns True if warning logs should be output
+ */
+ public isWarn(): boolean {
+ return this.shouldLog(LogLevel.Warn);
+ }
+
+ /**
+ * Logs a warning message if warning logging is enabled.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ public warn(message: string, ...args: unknown[]): void {
+ if (this.isWarn()) {
+ this.logger.warn(message, ...args);
+ }
+ }
+
+ /**
+ * Checks if error logging is enabled.
+ * @returns True if error logs should be output
+ */
+ public isError(): boolean {
+ return this.shouldLog(LogLevel.Error);
+ }
+
+ /**
+ * Logs an error message if error logging is enabled.
+ * @param message - The message to log
+ * @param args - Additional arguments to log
+ */
+ public error(message: string, ...args: unknown[]): void {
+ if (this.isError()) {
+ this.logger.error(message, ...args);
+ }
+ }
+}
+
+export function createLogger(config?: LogConfig | Logger): Logger {
+ if (config == null) {
+ return defaultLogger;
+ }
+ if (config instanceof Logger) {
+ return config;
+ }
+ config = config ?? {};
+ config.level ??= LogLevel.Info;
+ config.logger ??= new ConsoleLogger();
+ config.silent ??= true;
+ return new Logger(config as Required<LogConfig>);
+}
+
+const defaultLogger: Logger = new Logger({
+ level: LogLevel.Info,
+ logger: new ConsoleLogger(),
+ silent: true,
+});
diff --git a/packages/sdk/src/core/pagination/Page.ts b/packages/sdk/src/core/pagination/Page.ts
new file mode 100644
index 000000000..0321a3c04
--- /dev/null
+++ b/packages/sdk/src/core/pagination/Page.ts
@@ -0,0 +1,76 @@
+import type { HttpResponsePromise, RawResponse } from "../fetcher/index.js";
+
+/**
+ * A page of results from a paginated API.
+ *
+ * @template T The type of the items in the page.
+ * @template R The type of the API response.
+ */
+export class Page<T, R = unknown> implements AsyncIterable<T> {
+ public data: T[];
+ public rawResponse: RawResponse;
+ public response: R;
+
+ private _hasNextPage: (response: R) => boolean;
+ private getItems: (response: R) => T[];
+ private loadNextPage: (response: R) => HttpResponsePromise<R>;
+
+ constructor({
+ response,
+ rawResponse,
+ hasNextPage,
+ getItems,
+ loadPage,
+ }: {
+ response: R;
+ rawResponse: RawResponse;
+ hasNextPage: (response: R) => boolean;
+ getItems: (response: R) => T[];
+ loadPage: (response: R) => HttpResponsePromise<R>;
+ }) {
+ this.response = response;
+ this.rawResponse = rawResponse;
+ this.data = getItems(response);
+ this._hasNextPage = hasNextPage;
+ this.getItems = getItems;
+ this.loadNextPage = loadPage;
+ }
+
+ /**
+ * Retrieves the next page
+ * @returns this
+ */
+ public async getNextPage(): Promise<this> {
+ const { data, rawResponse } = await this.loadNextPage(this.response).withRawResponse();
+ this.response = data;
+ this.rawResponse = rawResponse;
+ this.data = this.getItems(this.response);
+ return this;
+ }
+
+ /**
+ * @returns whether there is a next page to load
+ */
+ public hasNextPage(): boolean {
+ return this._hasNextPage(this.response);
+ }
+
+ private async *iterMessages(): AsyncGenerator<T, void> {
+ for (const item of this.data) {
+ yield item;
+ }
+
+ while (this.hasNextPage()) {
+ await this.getNextPage();
+ for (const item of this.data) {
+ yield item;
+ }
+ }
+ }
+
+ async *[Symbol.asyncIterator](): AsyncIterator<T, void, unknown> {
+ for await (const message of this.iterMessages()) {
+ yield message;
+ }
+ }
+}
diff --git a/packages/sdk/src/core/pagination/exports.ts b/packages/sdk/src/core/pagination/exports.ts
new file mode 100644
index 000000000..d3acc60b0
--- /dev/null
+++ b/packages/sdk/src/core/pagination/exports.ts
@@ -0,0 +1 @@
+export type { Page } from "./Page.js";
diff --git a/packages/sdk/src/core/pagination/index.ts b/packages/sdk/src/core/pagination/index.ts
new file mode 100644
index 000000000..7781cbd6e
--- /dev/null
+++ b/packages/sdk/src/core/pagination/index.ts
@@ -0,0 +1 @@
+export { Page } from "./Page.js";
diff --git a/packages/sdk/src/core/requestBody.ts b/packages/sdk/src/core/requestBody.ts
new file mode 100644
index 000000000..d58ef590c
--- /dev/null
+++ b/packages/sdk/src/core/requestBody.ts
@@ -0,0 +1,26 @@
+/**
+ * Spreads caller-supplied `additionalBodyParameters` (from `requestOptions.additionalBodyParameters`)
+ * on top of the request body. Caller-supplied properties win over the endpoint body. When no
+ * additional body parameters are provided, the original body is returned unchanged so serialization
+ * is unaffected.
+ *
+ * The merge only applies to plain-object (JSON object) bodies. When the body is `null`/`undefined`
+ * the additional parameters become the body; when the body is an array or a primitive JSON value it
+ * is returned unchanged, since object properties cannot be spread into it. This mirrors the Python
+ * SDK, which only merges additional body parameters into mapping bodies.
+ */
+export function mergeAdditionalBodyParameters(
+ body: unknown,
+ additionalBodyParameters: Record<string, unknown> | undefined,
+): unknown {
+ if (additionalBodyParameters == null) {
+ return body;
+ }
+ if (body == null) {
+ return { ...additionalBodyParameters };
+ }
+ if (typeof body === "object" && !Array.isArray(body)) {
+ return { ...body, ...additionalBodyParameters };
+ }
+ return body;
+}
diff --git a/packages/sdk/src/core/runtime/index.ts b/packages/sdk/src/core/runtime/index.ts
new file mode 100644
index 000000000..85a327200
--- /dev/null
+++ b/packages/sdk/src/core/runtime/index.ts
@@ -0,0 +1 @@
+export { getUserAgent, RUNTIME } from "./runtime.js";
diff --git a/packages/sdk/src/core/runtime/runtime.ts b/packages/sdk/src/core/runtime/runtime.ts
new file mode 100644
index 000000000..d367ce6b9
--- /dev/null
+++ b/packages/sdk/src/core/runtime/runtime.ts
@@ -0,0 +1,231 @@
+interface DenoGlobal {
+ version: {
+ deno: string;
+ };
+ build?: {
+ os?: string;
+ arch?: string;
+ };
+}
+
+interface BunGlobal {
+ version: string;
+}
+
+declare const Deno: DenoGlobal | undefined;
+declare const Bun: BunGlobal | undefined;
+declare const EdgeRuntime: string | undefined;
+declare const self: typeof globalThis.self & {
+ importScripts?: unknown;
+};
+
+/**
+ * A constant that indicates which environment and version the SDK is running in.
+ */
+export const RUNTIME: Runtime = evaluateRuntime();
+
+export interface Runtime {
+ type: "browser" | "web-worker" | "deno" | "bun" | "node" | "react-native" | "unknown" | "workerd" | "edge-runtime";
+ version?: string;
+ parsedVersion?: number;
+ /**
+ * The operating system the SDK is running on, when it can be determined
+ * (e.g. "linux", "darwin", "win32" on server runtimes). Undefined in
+ * environments where the OS is not observable (e.g. browsers).
+ */
+ os?: string;
+ /**
+ * The CPU architecture the SDK is running on, when it can be determined
+ * (e.g. "x64", "arm64" on server runtimes). Undefined in environments where
+ * the architecture is not observable (e.g. browsers).
+ */
+ arch?: string;
+}
+
+function evaluateRuntime(): Runtime {
+ /**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+ if (isBrowser) {
+ return {
+ type: "browser",
+ version: window.navigator.userAgent,
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is Cloudflare.
+ * https://developers.cloudflare.com/workers/runtime-apis/web-standards/#navigatoruseragent
+ */
+ const isCloudflare = typeof globalThis !== "undefined" && globalThis?.navigator?.userAgent === "Cloudflare-Workers";
+ if (isCloudflare) {
+ return {
+ type: "workerd",
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is Edge Runtime.
+ * https://vercel.com/docs/functions/runtimes/edge-runtime#check-if-you're-running-on-the-edge-runtime
+ */
+ const isEdgeRuntime = typeof EdgeRuntime === "string";
+ if (isEdgeRuntime) {
+ return {
+ type: "edge-runtime",
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+ const isWebWorker =
+ typeof self === "object" &&
+ typeof self?.importScripts === "function" &&
+ (self.constructor?.name === "DedicatedWorkerGlobalScope" ||
+ self.constructor?.name === "ServiceWorkerGlobalScope" ||
+ self.constructor?.name === "SharedWorkerGlobalScope");
+ if (isWebWorker) {
+ return {
+ type: "web-worker",
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is Deno.
+ * FYI Deno spoofs process.versions.node, see https://deno.land/[email protected]/node/process.ts?s=versions
+ */
+ const isDeno =
+ typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
+ if (isDeno) {
+ return {
+ type: "deno",
+ version: Deno.version.deno,
+ os: Deno.build?.os,
+ arch: Deno.build?.arch,
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+ const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+ if (isBun) {
+ return {
+ type: "bun",
+ version: Bun.version,
+ os: typeof process !== "undefined" ? process.platform : undefined,
+ arch: typeof process !== "undefined" ? process.arch : undefined,
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ * This check should come before Node.js detection since React Native may have a process polyfill.
+ * https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+ */
+ const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
+ if (isReactNative) {
+ return {
+ type: "react-native",
+ };
+ }
+
+ /**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ *
+ * We assign `process` to a local variable first to avoid being flagged by
+ * bundlers that perform static analysis on `process.versions` (e.g. Next.js
+ * Edge Runtime warns about Node.js APIs even when they are guarded).
+ */
+ const _process = typeof process !== "undefined" ? process : undefined;
+ const isNode = typeof _process !== "undefined" && typeof _process.versions?.node === "string";
+ if (isNode) {
+ return {
+ type: "node",
+ version: _process.versions.node,
+ parsedVersion: Number(_process.versions.node.split(".")[0]),
+ os: _process.platform,
+ arch: _process.arch,
+ };
+ }
+
+ return {
+ type: "unknown",
+ };
+}
+
+/**
+ * Display names for the language runtimes whose version is meaningful to encode
+ * in a User-Agent. Environments where a version string is not useful (e.g.
+ * browsers, where `version` is the full navigator UA) are intentionally mapped
+ * to `undefined` so they are omitted from the User-Agent.
+ */
+const RUNTIME_DISPLAY_NAMES: Record<Runtime["type"], string | undefined> = {
+ node: "Node",
+ deno: "Deno",
+ bun: "Bun",
+ browser: undefined,
+ "web-worker": undefined,
+ "react-native": undefined,
+ workerd: undefined,
+ "edge-runtime": undefined,
+ unknown: undefined,
+};
+
+/**
+ * CPU architecture aliases that all refer to 64-bit x86. They are normalized to
+ * the single canonical token `x86_64` so the User-Agent architecture label is
+ * consistent regardless of which runtime reports it (Node reports `x64`, others
+ * report `amd64` or `x86_64`).
+ */
+const X86_64_ARCH_ALIASES = new Set(["x64", "amd64", "x86_64"]);
+
+/**
+ * Normalizes a CPU architecture token, collapsing the 64-bit x86 aliases
+ * (`x64`, `amd64`, `x86_64`) to `x86_64`. Other architectures are returned
+ * unchanged.
+ */
+function normalizeArch(arch: string | undefined): string | undefined {
+ if (arch == null) {
+ return arch;
+ }
+ return X86_64_ARCH_ALIASES.has(arch.toLowerCase()) ? "x86_64" : arch;
+}
+
+/**
+ * Percent-encodes the `@` and `/` characters in an npm package name so the
+ * User-Agent product token stays within the RFC 7230 token grammar. The
+ * original scoped package name can be recovered by URL-decoding (e.g.
+ * `@dummy/sdk` becomes `%40dummy%2Fsdk`).
+ */
+function encodeProductName(sdkName: string): string {
+ return sdkName.replace(/@/g, "%40").replace(/\//g, "%2F");
+}
+
+/**
+ * Builds a structured User-Agent string of the form
+ * `{sdkName}/{sdkVersion} ({os}; {arch}) {runtime}/{runtimeVersion}`
+ * where the platform group and runtime segment are omitted gracefully when the
+ * underlying values cannot be determined (e.g. in a browser).
+ */
+export function getUserAgent(sdkName: string, sdkVersion: string): string {
+ let userAgent = `${encodeProductName(sdkName)}/${sdkVersion}`;
+
+ const platform = [RUNTIME.os, normalizeArch(RUNTIME.arch)].filter(
+ (part): part is string => part != null && part.length > 0,
+ );
+ if (platform.length > 0) {
+ userAgent += ` (${platform.join("; ")})`;
+ }
+
+ const runtimeName = RUNTIME_DISPLAY_NAMES[RUNTIME.type];
+ if (runtimeName != null) {
+ userAgent += ` ${runtimeName}`;
+ if (RUNTIME.version != null && RUNTIME.version.length > 0) {
+ userAgent += `/${RUNTIME.version}`;
+ }
+ }
+
+ return userAgent;
+}
diff --git a/packages/sdk/src/core/schemas/Schema.ts b/packages/sdk/src/core/schemas/Schema.ts
new file mode 100644
index 000000000..4cd8b1d95
--- /dev/null
+++ b/packages/sdk/src/core/schemas/Schema.ts
@@ -0,0 +1,103 @@
+import type { SchemaUtils } from "./builders/index.js";
+
+export type Schema<Raw = unknown, Parsed = unknown> = BaseSchema<Raw, Parsed> & SchemaUtils<Raw, Parsed>;
+
+export type inferRaw<S extends Schema> = S extends Schema<infer Raw, any> ? Raw : never;
+export type inferParsed<S extends Schema> = S extends Schema<any, infer Parsed> ? Parsed : never;
+
+export interface BaseSchema<Raw, Parsed> {
+ parse: (raw: unknown, opts?: SchemaOptions) => MaybeValid<Parsed>;
+ json: (parsed: unknown, opts?: SchemaOptions) => MaybeValid<Raw>;
+ getType: () => SchemaType | SchemaType;
+}
+
+export const SchemaType = {
+ BIGINT: "bigint",
+ DATE: "date",
+ ENUM: "enum",
+ LIST: "list",
+ STRING_LITERAL: "stringLiteral",
+ BOOLEAN_LITERAL: "booleanLiteral",
+ OBJECT: "object",
+ ANY: "any",
+ BOOLEAN: "boolean",
+ NUMBER: "number",
+ STRING: "string",
+ UNKNOWN: "unknown",
+ NEVER: "never",
+ RECORD: "record",
+ SET: "set",
+ UNION: "union",
+ UNDISCRIMINATED_UNION: "undiscriminatedUnion",
+ NULLABLE: "nullable",
+ OPTIONAL: "optional",
+ OPTIONAL_NULLABLE: "optionalNullable",
+} as const;
+
+export type SchemaType = (typeof SchemaType)[keyof typeof SchemaType];
+
+export type MaybeValid<T> = Valid<T> | Invalid;
+
+export interface Valid<T> {
+ ok: true;
+ value: T;
+}
+
+export interface Invalid {
+ ok: false;
+ errors: ValidationError[];
+}
+
+export interface ValidationError {
+ path: string[];
+ message: string;
+}
+
+export interface SchemaOptions {
+ /**
+ * how to handle unrecognized keys in objects
+ *
+ * @default "fail"
+ */
+ unrecognizedObjectKeys?: "fail" | "passthrough" | "strip";
+
+ /**
+ * whether to fail when an unrecognized discriminant value is
+ * encountered in a union
+ *
+ * @default false
+ */
+ allowUnrecognizedUnionMembers?: boolean;
+
+ /**
+ * whether to fail when an unrecognized enum value is encountered
+ *
+ * @default false
+ */
+ allowUnrecognizedEnumValues?: boolean;
+
+ /**
+ * whether to allow data that doesn't conform to the schema.
+ * invalid data is passed through without transformation.
+ *
+ * when this is enabled, .parse() and .json() will always
+ * return `ok: true`. `.parseOrThrow()` and `.jsonOrThrow()`
+ * will never fail.
+ *
+ * @default false
+ */
+ skipValidation?: boolean;
+
+ /**
+ * each validation failure contains a "path" property, which is
+ * the breadcrumbs to the offending node in the JSON. you can supply
+ * a prefix that is prepended to all the errors' paths. this can be
+ * helpful for zurg's internal debug logging.
+ */
+ breadcrumbsPrefix?: string[];
+
+ /**
+ * whether to send 'null' for optional properties explicitly set to 'undefined'.
+ */
+ omitUndefined?: boolean;
+}
diff --git a/packages/sdk/src/core/schemas/builders/bigint/bigint.ts b/packages/sdk/src/core/schemas/builders/bigint/bigint.ts
new file mode 100644
index 000000000..2c7c74c54
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/bigint/bigint.ts
@@ -0,0 +1,55 @@
+import { type BaseSchema, type Schema, SchemaType } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+
+export function bigint(): Schema<bigint | number, bigint> {
+ const baseSchema: BaseSchema<bigint | number, bigint> = {
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof raw === "bigint") {
+ return {
+ ok: true,
+ value: raw,
+ };
+ }
+ if (typeof raw === "number") {
+ return {
+ ok: true,
+ value: BigInt(raw),
+ };
+ }
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(raw, "bigint | number"),
+ },
+ ],
+ };
+ },
+ json: (bigint, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof bigint !== "bigint") {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(bigint, "bigint"),
+ },
+ ],
+ };
+ }
+ return {
+ ok: true,
+ value: bigint,
+ };
+ },
+ getType: () => SchemaType.BIGINT,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/bigint/index.ts b/packages/sdk/src/core/schemas/builders/bigint/index.ts
new file mode 100644
index 000000000..13cc76e25
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/bigint/index.ts
@@ -0,0 +1 @@
+export { bigint } from "./bigint.js";
diff --git a/packages/sdk/src/core/schemas/builders/date/date.ts b/packages/sdk/src/core/schemas/builders/date/date.ts
new file mode 100644
index 000000000..f02e3367f
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/date/date.ts
@@ -0,0 +1,65 @@
+import { type BaseSchema, type Schema, SchemaType } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+
+// https://stackoverflow.com/questions/12756159/regex-and-iso8601-formatted-datetime
+const ISO_8601_REGEX =
+ /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
+
+export function date(): Schema<string, Date> {
+ const baseSchema: BaseSchema<string, Date> = {
+ parse: (raw, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof raw !== "string") {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(raw, "string"),
+ },
+ ],
+ };
+ }
+ if (!ISO_8601_REGEX.test(raw)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(raw, "ISO 8601 date string"),
+ },
+ ],
+ };
+ }
+ return {
+ ok: true,
+ value: new Date(raw),
+ };
+ },
+ json: (date, { breadcrumbsPrefix = [] } = {}) => {
+ if (date instanceof Date) {
+ return {
+ ok: true,
+ value: date.toISOString(),
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(date, "Date object"),
+ },
+ ],
+ };
+ }
+ },
+ getType: () => SchemaType.DATE,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/date/index.ts b/packages/sdk/src/core/schemas/builders/date/index.ts
new file mode 100644
index 000000000..e22a2f16b
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/date/index.ts
@@ -0,0 +1 @@
+export { date } from "./date.js";
diff --git a/packages/sdk/src/core/schemas/builders/enum/enum.ts b/packages/sdk/src/core/schemas/builders/enum/enum.ts
new file mode 100644
index 000000000..2f2777cf1
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/enum/enum.ts
@@ -0,0 +1,50 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export function enum_<U extends string, E extends U[]>(values: E): Schema<E[number], E[number]> {
+ const validValues = new Set<string>(values);
+
+ const schemaCreator = createIdentitySchemaCreator(
+ SchemaType.ENUM,
+ (value, { allowUnrecognizedEnumValues, breadcrumbsPrefix = [] } = {}) => {
+ if (typeof value !== "string") {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "string"),
+ },
+ ],
+ };
+ }
+
+ if (!validValues.has(value) && !allowUnrecognizedEnumValues) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "enum"),
+ },
+ ],
+ };
+ }
+
+ return {
+ ok: true,
+ value: value as U,
+ };
+ },
+ );
+
+ return schemaCreator();
+}
+
+export function forwardCompatibleEnum_<U extends string, E extends U[]>(values: E): Schema<E[number], string> {
+ return enum_(values).transform<string>({
+ transform: (val) => val,
+ untransform: (val) => val,
+ });
+}
diff --git a/packages/sdk/src/core/schemas/builders/enum/index.ts b/packages/sdk/src/core/schemas/builders/enum/index.ts
new file mode 100644
index 000000000..2ff90af36
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/enum/index.ts
@@ -0,0 +1 @@
+export { enum_, forwardCompatibleEnum_ } from "./enum.js";
diff --git a/packages/sdk/src/core/schemas/builders/index.ts b/packages/sdk/src/core/schemas/builders/index.ts
new file mode 100644
index 000000000..ddb9b3c94
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/index.ts
@@ -0,0 +1,14 @@
+export * from "./bigint/index.js";
+export * from "./date/index.js";
+export * from "./enum/index.js";
+export * from "./lazy/index.js";
+export * from "./list/index.js";
+export * from "./literals/index.js";
+export * from "./object/index.js";
+export * from "./object-like/index.js";
+export * from "./primitives/index.js";
+export * from "./record/index.js";
+export * from "./schema-utils/index.js";
+export * from "./set/index.js";
+export * from "./undiscriminated-union/index.js";
+export * from "./union/index.js";
diff --git a/packages/sdk/src/core/schemas/builders/lazy/index.ts b/packages/sdk/src/core/schemas/builders/lazy/index.ts
new file mode 100644
index 000000000..e8ca40992
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/lazy/index.ts
@@ -0,0 +1,3 @@
+export type { SchemaGetter } from "./lazy.js";
+export { lazy } from "./lazy.js";
+export { lazyObject } from "./lazyObject.js";
diff --git a/packages/sdk/src/core/schemas/builders/lazy/lazy.ts b/packages/sdk/src/core/schemas/builders/lazy/lazy.ts
new file mode 100644
index 000000000..37f288716
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/lazy/lazy.ts
@@ -0,0 +1,32 @@
+import type { BaseSchema, Schema } from "../../Schema.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+
+export type SchemaGetter<SchemaType extends Schema<any, any>> = () => SchemaType;
+
+export function lazy<Raw, Parsed>(getter: SchemaGetter<Schema<Raw, Parsed>>): Schema<Raw, Parsed> {
+ const baseSchema = constructLazyBaseSchema(getter);
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+export function constructLazyBaseSchema<Raw, Parsed>(
+ getter: SchemaGetter<Schema<Raw, Parsed>>,
+): BaseSchema<Raw, Parsed> {
+ return {
+ parse: (raw, opts) => getMemoizedSchema(getter).parse(raw, opts),
+ json: (parsed, opts) => getMemoizedSchema(getter).json(parsed, opts),
+ getType: () => getMemoizedSchema(getter).getType(),
+ };
+}
+
+type MemoizedGetter<SchemaType extends Schema<any, any>> = SchemaGetter<SchemaType> & { __zurg_memoized?: SchemaType };
+
+export function getMemoizedSchema<SchemaType extends Schema<any, any>>(getter: SchemaGetter<SchemaType>): SchemaType {
+ const castedGetter = getter as MemoizedGetter<SchemaType>;
+ if (castedGetter.__zurg_memoized == null) {
+ castedGetter.__zurg_memoized = getter();
+ }
+ return castedGetter.__zurg_memoized;
+}
diff --git a/packages/sdk/src/core/schemas/builders/lazy/lazyObject.ts b/packages/sdk/src/core/schemas/builders/lazy/lazyObject.ts
new file mode 100644
index 000000000..192c90e5c
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/lazy/lazyObject.ts
@@ -0,0 +1,20 @@
+import { getObjectUtils } from "../object/index.js";
+import type { BaseObjectSchema, ObjectSchema } from "../object/types.js";
+import { getObjectLikeUtils } from "../object-like/index.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import { constructLazyBaseSchema, getMemoizedSchema, type SchemaGetter } from "./lazy.js";
+
+export function lazyObject<Raw, Parsed>(getter: SchemaGetter<ObjectSchema<Raw, Parsed>>): ObjectSchema<Raw, Parsed> {
+ const baseSchema: BaseObjectSchema<Raw, Parsed> = {
+ ...constructLazyBaseSchema(getter),
+ _getRawProperties: () => getMemoizedSchema(getter)._getRawProperties(),
+ _getParsedProperties: () => getMemoizedSchema(getter)._getParsedProperties(),
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ ...getObjectLikeUtils(baseSchema),
+ ...getObjectUtils(baseSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/list/index.ts b/packages/sdk/src/core/schemas/builders/list/index.ts
new file mode 100644
index 000000000..021f1e4df
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/list/index.ts
@@ -0,0 +1 @@
+export { list } from "./list.js";
diff --git a/packages/sdk/src/core/schemas/builders/list/list.ts b/packages/sdk/src/core/schemas/builders/list/list.ts
new file mode 100644
index 000000000..b3c0bdfcb
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/list/list.ts
@@ -0,0 +1,63 @@
+import { type BaseSchema, type MaybeValid, type Schema, SchemaType, type ValidationError } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+
+export function list<Raw, Parsed>(schema: Schema<Raw, Parsed>): Schema<Raw[], Parsed[]> {
+ const baseSchema: BaseSchema<Raw[], Parsed[]> = {
+ parse: (raw, opts) =>
+ validateAndTransformArray(raw, (item, index) =>
+ schema.parse(item, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `[${index}]`],
+ }),
+ ),
+ json: (parsed, opts) =>
+ validateAndTransformArray(parsed, (item, index) =>
+ schema.json(item, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `[${index}]`],
+ }),
+ ),
+ getType: () => SchemaType.LIST,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+function validateAndTransformArray<Raw, Parsed>(
+ value: unknown,
+ transformItem: (item: Raw, index: number) => MaybeValid<Parsed>,
+): MaybeValid<Parsed[]> {
+ if (!Array.isArray(value)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ message: getErrorMessageForIncorrectType(value, "list"),
+ path: [],
+ },
+ ],
+ };
+ }
+
+ const result: Parsed[] = [];
+ const errors: ValidationError[] = [];
+
+ for (let i = 0; i < value.length; i++) {
+ const item = transformItem(value[i], i);
+ if (item.ok) {
+ result.push(item.value);
+ } else {
+ errors.push(...item.errors);
+ }
+ }
+
+ if (errors.length === 0) {
+ return { ok: true, value: result };
+ }
+ return { ok: false, errors };
+}
diff --git a/packages/sdk/src/core/schemas/builders/literals/booleanLiteral.ts b/packages/sdk/src/core/schemas/builders/literals/booleanLiteral.ts
new file mode 100644
index 000000000..db5d2c7a7
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/literals/booleanLiteral.ts
@@ -0,0 +1,29 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export function booleanLiteral<V extends boolean>(literal: V): Schema<V, V> {
+ const schemaCreator = createIdentitySchemaCreator(
+ SchemaType.BOOLEAN_LITERAL,
+ (value, { breadcrumbsPrefix = [] } = {}) => {
+ if (value === literal) {
+ return {
+ ok: true,
+ value: literal,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, `${literal.toString()}`),
+ },
+ ],
+ };
+ }
+ },
+ );
+
+ return schemaCreator();
+}
diff --git a/packages/sdk/src/core/schemas/builders/literals/index.ts b/packages/sdk/src/core/schemas/builders/literals/index.ts
new file mode 100644
index 000000000..4a4ab39d9
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/literals/index.ts
@@ -0,0 +1,2 @@
+export { booleanLiteral } from "./booleanLiteral.js";
+export { stringLiteral } from "./stringLiteral.js";
diff --git a/packages/sdk/src/core/schemas/builders/literals/stringLiteral.ts b/packages/sdk/src/core/schemas/builders/literals/stringLiteral.ts
new file mode 100644
index 000000000..ce6e20caf
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/literals/stringLiteral.ts
@@ -0,0 +1,29 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export function stringLiteral<V extends string>(literal: V): Schema<V, V> {
+ const schemaCreator = createIdentitySchemaCreator(
+ SchemaType.STRING_LITERAL,
+ (value, { breadcrumbsPrefix = [] } = {}) => {
+ if (value === literal) {
+ return {
+ ok: true,
+ value: literal,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, `"${literal}"`),
+ },
+ ],
+ };
+ }
+ },
+ );
+
+ return schemaCreator();
+}
diff --git a/packages/sdk/src/core/schemas/builders/object-like/getObjectLikeUtils.ts b/packages/sdk/src/core/schemas/builders/object-like/getObjectLikeUtils.ts
new file mode 100644
index 000000000..5fdc8023b
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object-like/getObjectLikeUtils.ts
@@ -0,0 +1,81 @@
+import type { BaseSchema } from "../../Schema.js";
+import { filterObject } from "../../utils/filterObject.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { isPlainObject } from "../../utils/isPlainObject.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import type { ObjectLikeSchema, ObjectLikeUtils } from "./types.js";
+
+// eslint-disable-next-line @typescript-eslint/unbound-method
+const _hasOwn = Object.prototype.hasOwnProperty;
+
+export function getObjectLikeUtils<Raw, Parsed>(schema: BaseSchema<Raw, Parsed>): ObjectLikeUtils<Raw, Parsed> {
+ return {
+ withParsedProperties: (properties) => withParsedProperties(schema, properties),
+ };
+}
+
+/**
+ * object-like utils are defined in one file to resolve issues with circular imports
+ */
+
+export function withParsedProperties<RawObjectShape, ParsedObjectShape, Properties>(
+ objectLike: BaseSchema<RawObjectShape, ParsedObjectShape>,
+ properties: { [K in keyof Properties]: Properties[K] | ((parsed: ParsedObjectShape) => Properties[K]) },
+): ObjectLikeSchema<RawObjectShape, ParsedObjectShape & Properties> {
+ const objectSchema: BaseSchema<RawObjectShape, ParsedObjectShape & Properties> = {
+ parse: (raw, opts) => {
+ const parsedObject = objectLike.parse(raw, opts);
+ if (!parsedObject.ok) {
+ return parsedObject;
+ }
+
+ const additionalProperties: Record<string, any> = {};
+ for (const key in properties) {
+ if (_hasOwn.call(properties, key)) {
+ const value = properties[key as keyof Properties];
+ additionalProperties[key] =
+ typeof value === "function" ? (value as Function)(parsedObject.value) : value;
+ }
+ }
+
+ return {
+ ok: true,
+ value: {
+ ...parsedObject.value,
+ ...(additionalProperties as Properties),
+ },
+ };
+ },
+
+ json: (parsed, opts) => {
+ if (!isPlainObject(parsed)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: opts?.breadcrumbsPrefix ?? [],
+ message: getErrorMessageForIncorrectType(parsed, "object"),
+ },
+ ],
+ };
+ }
+
+ // strip out added properties
+ const addedPropertyKeys = new Set(Object.keys(properties));
+ const parsedWithoutAddedProperties = filterObject(
+ parsed,
+ Object.keys(parsed).filter((key) => !addedPropertyKeys.has(key)),
+ );
+
+ return objectLike.json(parsedWithoutAddedProperties as ParsedObjectShape, opts);
+ },
+
+ getType: () => objectLike.getType(),
+ };
+
+ return {
+ ...objectSchema,
+ ...getSchemaUtils(objectSchema),
+ ...getObjectLikeUtils(objectSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/object-like/index.ts b/packages/sdk/src/core/schemas/builders/object-like/index.ts
new file mode 100644
index 000000000..2451ef7d0
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object-like/index.ts
@@ -0,0 +1,2 @@
+export { getObjectLikeUtils, withParsedProperties } from "./getObjectLikeUtils.js";
+export type { ObjectLikeSchema, ObjectLikeUtils } from "./types.js";
diff --git a/packages/sdk/src/core/schemas/builders/object-like/types.ts b/packages/sdk/src/core/schemas/builders/object-like/types.ts
new file mode 100644
index 000000000..44b966910
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object-like/types.ts
@@ -0,0 +1,13 @@
+import type { BaseSchema, Schema } from "../../Schema.js";
+
+export type ObjectLikeSchema<Raw, Parsed> = Schema<Raw, Parsed> &
+ BaseSchema<Raw, Parsed> &
+ ObjectLikeUtils<Raw, Parsed>;
+
+export interface ObjectLikeUtils<Raw, Parsed> {
+ withParsedProperties: <T extends Record<string, any>>(
+ properties: {
+ [K in keyof T]: T[K] | ((parsed: Parsed) => T[K]);
+ },
+ ) => ObjectLikeSchema<Raw, Parsed & T>;
+}
diff --git a/packages/sdk/src/core/schemas/builders/object/index.ts b/packages/sdk/src/core/schemas/builders/object/index.ts
new file mode 100644
index 000000000..c6611aaac
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object/index.ts
@@ -0,0 +1,22 @@
+export { getObjectUtils, object } from "./object.js";
+export type {
+ inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas,
+ inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas,
+} from "./objectWithoutOptionalProperties.js";
+export { objectWithoutOptionalProperties } from "./objectWithoutOptionalProperties.js";
+export type { Property } from "./property.js";
+export { isProperty, property } from "./property.js";
+export type {
+ BaseObjectSchema,
+ inferObjectSchemaFromPropertySchemas,
+ inferParsedObject,
+ inferParsedObjectFromPropertySchemas,
+ inferParsedPropertySchema,
+ inferRawKey,
+ inferRawObject,
+ inferRawObjectFromPropertySchemas,
+ inferRawPropertySchema,
+ ObjectSchema,
+ ObjectUtils,
+ PropertySchemas,
+} from "./types.js";
diff --git a/packages/sdk/src/core/schemas/builders/object/object.ts b/packages/sdk/src/core/schemas/builders/object/object.ts
new file mode 100644
index 000000000..0db7f49aa
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object/object.ts
@@ -0,0 +1,468 @@
+import { type MaybeValid, type Schema, SchemaType, type ValidationError } from "../../Schema.js";
+import { entries } from "../../utils/entries.js";
+import { filterObject } from "../../utils/filterObject.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { isPlainObject } from "../../utils/isPlainObject.js";
+import { keys } from "../../utils/keys.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { partition } from "../../utils/partition.js";
+import { getObjectLikeUtils } from "../object-like/index.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import { isProperty } from "./property.js";
+import type {
+ BaseObjectSchema,
+ inferObjectSchemaFromPropertySchemas,
+ inferParsedObjectFromPropertySchemas,
+ inferRawObjectFromPropertySchemas,
+ ObjectSchema,
+ ObjectUtils,
+ PropertySchemas,
+} from "./types.js";
+
+// eslint-disable-next-line @typescript-eslint/unbound-method
+const _hasOwn = Object.prototype.hasOwnProperty;
+
+interface ObjectPropertyWithRawKey {
+ rawKey: string;
+ parsedKey: string;
+ valueSchema: Schema<any, any>;
+}
+
+export function object<ParsedKeys extends string, T extends PropertySchemas<ParsedKeys>>(
+ schemas: T,
+): inferObjectSchemaFromPropertySchemas<T> {
+ // All property metadata is lazily computed on first use.
+ // This keeps schema construction free of iteration, which matters when
+ // many schemas are defined but only some are exercised at runtime.
+ // Required-key computation is also deferred because lazy() schemas may
+ // not be resolved at construction time.
+
+ let _rawKeyToProperty: Record<string, ObjectPropertyWithRawKey> | undefined;
+
+ function getRawKeyToProperty(): Record<string, ObjectPropertyWithRawKey> {
+ if (_rawKeyToProperty == null) {
+ _rawKeyToProperty = {};
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
+ const rawKey = isProperty(schemaOrObjectProperty)
+ ? schemaOrObjectProperty.rawKey
+ : (parsedKey as string);
+ const valueSchema: Schema<any, any> = isProperty(schemaOrObjectProperty)
+ ? schemaOrObjectProperty.valueSchema
+ : schemaOrObjectProperty;
+
+ _rawKeyToProperty[rawKey] = {
+ rawKey,
+ parsedKey: parsedKey as string,
+ valueSchema,
+ };
+ }
+ }
+ return _rawKeyToProperty;
+ }
+
+ let _parseRequiredKeys: string[] | undefined;
+ let _jsonRequiredKeys: string[] | undefined;
+ let _parseRequiredKeysSet: Set<string> | undefined;
+ let _jsonRequiredKeysSet: Set<string> | undefined;
+
+ function getParseRequiredKeys(): string[] {
+ if (_parseRequiredKeys == null) {
+ _parseRequiredKeys = [];
+ _jsonRequiredKeys = [];
+ for (const [parsedKey, schemaOrObjectProperty] of entries(schemas)) {
+ const rawKey = isProperty(schemaOrObjectProperty)
+ ? schemaOrObjectProperty.rawKey
+ : (parsedKey as string);
+ const valueSchema: Schema<any, any> = isProperty(schemaOrObjectProperty)
+ ? schemaOrObjectProperty.valueSchema
+ : schemaOrObjectProperty;
+ if (isSchemaRequired(valueSchema)) {
+ _parseRequiredKeys.push(rawKey);
+ _jsonRequiredKeys.push(parsedKey as string);
+ }
+ }
+ _parseRequiredKeysSet = new Set(_parseRequiredKeys);
+ _jsonRequiredKeysSet = new Set(_jsonRequiredKeys);
+ }
+ return _parseRequiredKeys;
+ }
+
+ function getJsonRequiredKeys(): string[] {
+ if (_jsonRequiredKeys == null) {
+ getParseRequiredKeys();
+ }
+ return _jsonRequiredKeys!;
+ }
+
+ function getParseRequiredKeysSet(): Set<string> {
+ if (_parseRequiredKeysSet == null) {
+ getParseRequiredKeys();
+ }
+ return _parseRequiredKeysSet!;
+ }
+
+ function getJsonRequiredKeysSet(): Set<string> {
+ if (_jsonRequiredKeysSet == null) {
+ getParseRequiredKeys();
+ }
+ return _jsonRequiredKeysSet!;
+ }
+
+ const baseSchema: BaseObjectSchema<
+ inferRawObjectFromPropertySchemas<T>,
+ inferParsedObjectFromPropertySchemas<T>
+ > = {
+ _getRawProperties: () =>
+ Object.entries(schemas).map(([parsedKey, propertySchema]) =>
+ isProperty(propertySchema) ? propertySchema.rawKey : parsedKey,
+ ) as unknown as (keyof inferRawObjectFromPropertySchemas<T>)[],
+ _getParsedProperties: () => keys(schemas) as unknown as (keyof inferParsedObjectFromPropertySchemas<T>)[],
+
+ parse: (raw, opts) => {
+ const breadcrumbsPrefix = opts?.breadcrumbsPrefix ?? [];
+ return validateAndTransformObject({
+ value: raw,
+ requiredKeys: getParseRequiredKeys(),
+ requiredKeysSet: getParseRequiredKeysSet(),
+ getProperty: (rawKey) => {
+ const property = getRawKeyToProperty()[rawKey];
+ if (property == null) {
+ return undefined;
+ }
+ return {
+ transformedKey: property.parsedKey,
+ transform: (propertyValue) => {
+ const childBreadcrumbs = [...breadcrumbsPrefix, rawKey];
+ return property.valueSchema.parse(propertyValue, {
+ ...opts,
+ breadcrumbsPrefix: childBreadcrumbs,
+ });
+ },
+ };
+ },
+ unrecognizedObjectKeys: opts?.unrecognizedObjectKeys,
+ skipValidation: opts?.skipValidation,
+ breadcrumbsPrefix,
+ omitUndefined: opts?.omitUndefined,
+ });
+ },
+
+ json: (parsed, opts) => {
+ const breadcrumbsPrefix = opts?.breadcrumbsPrefix ?? [];
+ return validateAndTransformObject({
+ value: parsed,
+ requiredKeys: getJsonRequiredKeys(),
+ requiredKeysSet: getJsonRequiredKeysSet(),
+ getProperty: (
+ parsedKey,
+ ): { transformedKey: string; transform: (propertyValue: object) => MaybeValid<any> } | undefined => {
+ const property = schemas[parsedKey as keyof T];
+
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ if (property == null) {
+ return undefined;
+ }
+
+ if (isProperty(property)) {
+ return {
+ transformedKey: property.rawKey,
+ transform: (propertyValue) => {
+ const childBreadcrumbs = [...breadcrumbsPrefix, parsedKey];
+ return property.valueSchema.json(propertyValue, {
+ ...opts,
+ breadcrumbsPrefix: childBreadcrumbs,
+ });
+ },
+ };
+ } else {
+ return {
+ transformedKey: parsedKey,
+ transform: (propertyValue) => {
+ const childBreadcrumbs = [...breadcrumbsPrefix, parsedKey];
+ return property.json(propertyValue, {
+ ...opts,
+ breadcrumbsPrefix: childBreadcrumbs,
+ });
+ },
+ };
+ }
+ },
+ unrecognizedObjectKeys: opts?.unrecognizedObjectKeys,
+ skipValidation: opts?.skipValidation,
+ breadcrumbsPrefix,
+ omitUndefined: opts?.omitUndefined,
+ });
+ },
+
+ getType: () => SchemaType.OBJECT,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ ...getObjectLikeUtils(baseSchema),
+ ...getObjectUtils(baseSchema),
+ };
+}
+
+function validateAndTransformObject<Transformed>({
+ value,
+ requiredKeys,
+ requiredKeysSet,
+ getProperty,
+ unrecognizedObjectKeys = "fail",
+ skipValidation = false,
+ breadcrumbsPrefix = [],
+}: {
+ value: unknown;
+ requiredKeys: string[];
+ requiredKeysSet: Set<string>;
+ getProperty: (
+ preTransformedKey: string,
+ ) => { transformedKey: string; transform: (propertyValue: object) => MaybeValid<any> } | undefined;
+ unrecognizedObjectKeys: "fail" | "passthrough" | "strip" | undefined;
+ skipValidation: boolean | undefined;
+ breadcrumbsPrefix: string[] | undefined;
+ omitUndefined: boolean | undefined;
+}): MaybeValid<Transformed> {
+ if (!isPlainObject(value)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "object"),
+ },
+ ],
+ };
+ }
+
+ // Track which required keys have been seen.
+ // Use a counter instead of copying the Set to avoid per-call allocation.
+ let missingRequiredCount = requiredKeys.length;
+ const errors: ValidationError[] = [];
+ const transformed: Record<string | number | symbol, any> = {};
+
+ for (const preTransformedKey in value) {
+ if (!_hasOwn.call(value, preTransformedKey)) {
+ continue;
+ }
+ const preTransformedItemValue = value[preTransformedKey];
+ const property = getProperty(preTransformedKey);
+
+ if (property != null) {
+ if (missingRequiredCount > 0 && requiredKeysSet.has(preTransformedKey)) {
+ missingRequiredCount--;
+ }
+
+ const value = property.transform(preTransformedItemValue as object);
+ if (value.ok) {
+ transformed[property.transformedKey] = value.value;
+ } else {
+ transformed[preTransformedKey] = preTransformedItemValue;
+ errors.push(...value.errors);
+ }
+ } else {
+ switch (unrecognizedObjectKeys) {
+ case "fail":
+ errors.push({
+ path: [...breadcrumbsPrefix, preTransformedKey],
+ message: `Unexpected key "${preTransformedKey}"`,
+ });
+ break;
+ case "strip":
+ break;
+ case "passthrough":
+ transformed[preTransformedKey] = preTransformedItemValue;
+ break;
+ }
+ }
+ }
+
+ if (missingRequiredCount > 0) {
+ for (const key of requiredKeys) {
+ if (!(key in (value as Record<string, unknown>))) {
+ errors.push({
+ path: breadcrumbsPrefix,
+ message: `Missing required key "${key}"`,
+ });
+ }
+ }
+ }
+
+ if (errors.length === 0 || skipValidation) {
+ return {
+ ok: true,
+ value: transformed as Transformed,
+ };
+ } else {
+ return {
+ ok: false,
+ errors,
+ };
+ }
+}
+
+export function getObjectUtils<Raw, Parsed>(schema: BaseObjectSchema<Raw, Parsed>): ObjectUtils<Raw, Parsed> {
+ return {
+ extend: <RawExtension, ParsedExtension>(extension: ObjectSchema<RawExtension, ParsedExtension>) => {
+ const baseSchema: BaseObjectSchema<Raw & RawExtension, Parsed & ParsedExtension> = {
+ _getParsedProperties: () => [...schema._getParsedProperties(), ...extension._getParsedProperties()],
+ _getRawProperties: () => [...schema._getRawProperties(), ...extension._getRawProperties()],
+ parse: (raw, opts) => {
+ return validateAndTransformExtendedObject({
+ extensionKeys: extension._getRawProperties(),
+ value: raw,
+ transformBase: (rawBase) => schema.parse(rawBase, opts),
+ transformExtension: (rawExtension) => extension.parse(rawExtension, opts),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ json: (parsed, opts) => {
+ return validateAndTransformExtendedObject({
+ extensionKeys: extension._getParsedProperties(),
+ value: parsed,
+ transformBase: (parsedBase) => schema.json(parsedBase, opts),
+ transformExtension: (parsedExtension) => extension.json(parsedExtension, opts),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ getType: () => SchemaType.OBJECT,
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ ...getObjectLikeUtils(baseSchema),
+ ...getObjectUtils(baseSchema),
+ };
+ },
+ passthrough: () => {
+ const knownRawKeys = new Set<string>(schema._getRawProperties() as string[]);
+ const knownParsedKeys = new Set<string>(schema._getParsedProperties() as string[]);
+ const baseSchema: BaseObjectSchema<Raw & { [key: string]: unknown }, Parsed & { [key: string]: unknown }> =
+ {
+ _getParsedProperties: () => schema._getParsedProperties(),
+ _getRawProperties: () => schema._getRawProperties(),
+ parse: (raw, opts) => {
+ const transformed = schema.parse(raw, { ...opts, unrecognizedObjectKeys: "passthrough" });
+ if (!transformed.ok) {
+ return transformed;
+ }
+ const extraProperties: Record<string, unknown> = {};
+ if (typeof raw === "object" && raw != null) {
+ for (const [key, value] of Object.entries(raw)) {
+ if (!knownRawKeys.has(key)) {
+ extraProperties[key] = value;
+ }
+ }
+ }
+ return {
+ ok: true,
+ value: {
+ ...extraProperties,
+ ...transformed.value,
+ },
+ };
+ },
+ json: (parsed, opts) => {
+ const transformed = schema.json(parsed, { ...opts, unrecognizedObjectKeys: "passthrough" });
+ if (!transformed.ok) {
+ return transformed;
+ }
+ const extraProperties: Record<string, unknown> = {};
+ if (typeof parsed === "object" && parsed != null) {
+ for (const [key, value] of Object.entries(parsed)) {
+ if (!knownParsedKeys.has(key)) {
+ extraProperties[key] = value;
+ }
+ }
+ }
+ return {
+ ok: true,
+ value: {
+ ...extraProperties,
+ ...transformed.value,
+ },
+ };
+ },
+ getType: () => SchemaType.OBJECT,
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ ...getObjectLikeUtils(baseSchema),
+ ...getObjectUtils(baseSchema),
+ };
+ },
+ };
+}
+
+function validateAndTransformExtendedObject<PreTransformedExtension, TransformedBase, TransformedExtension>({
+ extensionKeys,
+ value,
+ transformBase,
+ transformExtension,
+ breadcrumbsPrefix = [],
+}: {
+ extensionKeys: (keyof PreTransformedExtension)[];
+ value: unknown;
+ transformBase: (value: object) => MaybeValid<TransformedBase>;
+ transformExtension: (value: object) => MaybeValid<TransformedExtension>;
+ breadcrumbsPrefix?: string[];
+}): MaybeValid<TransformedBase & TransformedExtension> {
+ if (!isPlainObject(value)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "object"),
+ },
+ ],
+ };
+ }
+
+ const extensionPropertiesSet = new Set(extensionKeys);
+ const [extensionProperties, baseProperties] = partition(keys(value), (key) =>
+ extensionPropertiesSet.has(key as keyof PreTransformedExtension),
+ );
+
+ const transformedBase = transformBase(filterObject(value, baseProperties));
+ const transformedExtension = transformExtension(filterObject(value, extensionProperties));
+
+ if (transformedBase.ok && transformedExtension.ok) {
+ return {
+ ok: true,
+ value: {
+ ...transformedBase.value,
+ ...transformedExtension.value,
+ },
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ ...(transformedBase.ok ? [] : transformedBase.errors),
+ ...(transformedExtension.ok ? [] : transformedExtension.errors),
+ ],
+ };
+ }
+}
+
+function isSchemaRequired(schema: Schema<any, any>): boolean {
+ return !isSchemaOptional(schema);
+}
+
+function isSchemaOptional(schema: Schema<any, any>): boolean {
+ switch (schema.getType()) {
+ case SchemaType.ANY:
+ case SchemaType.UNKNOWN:
+ case SchemaType.OPTIONAL:
+ case SchemaType.OPTIONAL_NULLABLE:
+ return true;
+ default:
+ return false;
+ }
+}
diff --git a/packages/sdk/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts b/packages/sdk/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts
new file mode 100644
index 000000000..4d39c862f
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object/objectWithoutOptionalProperties.ts
@@ -0,0 +1,23 @@
+import { object } from "./object.js";
+import type {
+ inferParsedPropertySchema,
+ inferRawObjectFromPropertySchemas,
+ ObjectSchema,
+ PropertySchemas,
+} from "./types.js";
+
+export function objectWithoutOptionalProperties<ParsedKeys extends string, T extends PropertySchemas<ParsedKeys>>(
+ schemas: T,
+): inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas<T> {
+ return object(schemas) as unknown as inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas<T>;
+}
+
+export type inferObjectWithoutOptionalPropertiesSchemaFromPropertySchemas<T extends PropertySchemas<keyof T>> =
+ ObjectSchema<
+ inferRawObjectFromPropertySchemas<T>,
+ inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas<T>
+ >;
+
+export type inferParsedObjectWithoutOptionalPropertiesFromPropertySchemas<T extends PropertySchemas<keyof T>> = {
+ [K in keyof T]: inferParsedPropertySchema<T[K]>;
+};
diff --git a/packages/sdk/src/core/schemas/builders/object/property.ts b/packages/sdk/src/core/schemas/builders/object/property.ts
new file mode 100644
index 000000000..d1f9f386a
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object/property.ts
@@ -0,0 +1,23 @@
+import type { Schema } from "../../Schema.js";
+
+export function property<RawKey extends string, RawValue, ParsedValue>(
+ rawKey: RawKey,
+ valueSchema: Schema<RawValue, ParsedValue>,
+): Property<RawKey, RawValue, ParsedValue> {
+ return {
+ rawKey,
+ valueSchema,
+ isProperty: true,
+ };
+}
+
+export interface Property<RawKey extends string, RawValue, ParsedValue> {
+ rawKey: RawKey;
+ valueSchema: Schema<RawValue, ParsedValue>;
+ isProperty: true;
+}
+
+export function isProperty<O extends Property<any, any, any>>(maybeProperty: unknown): maybeProperty is O {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ return (maybeProperty as O).isProperty;
+}
diff --git a/packages/sdk/src/core/schemas/builders/object/types.ts b/packages/sdk/src/core/schemas/builders/object/types.ts
new file mode 100644
index 000000000..384ae873f
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/object/types.ts
@@ -0,0 +1,58 @@
+import type { BaseSchema, inferParsed, inferRaw, Schema } from "../../Schema.js";
+import type { addQuestionMarksToNullableProperties } from "../../utils/addQuestionMarksToNullableProperties.js";
+import type { ObjectLikeUtils } from "../object-like/index.js";
+import type { SchemaUtils } from "../schema-utils/index.js";
+import type { Property } from "./property.js";
+
+export type ObjectSchema<Raw, Parsed> = BaseObjectSchema<Raw, Parsed> &
+ ObjectLikeUtils<Raw, Parsed> &
+ ObjectUtils<Raw, Parsed> &
+ SchemaUtils<Raw, Parsed>;
+
+export interface BaseObjectSchema<Raw, Parsed> extends BaseSchema<Raw, Parsed> {
+ _getRawProperties: () => (keyof Raw)[];
+ _getParsedProperties: () => (keyof Parsed)[];
+}
+
+export interface ObjectUtils<Raw, Parsed> {
+ extend: <RawExtension, ParsedExtension>(
+ schemas: ObjectSchema<RawExtension, ParsedExtension>,
+ ) => ObjectSchema<Raw & RawExtension, Parsed & ParsedExtension>;
+ passthrough: () => ObjectSchema<Raw & { [key: string]: unknown }, Parsed & { [key: string]: unknown }>;
+}
+
+export type inferRawObject<O extends ObjectSchema<any, any>> = O extends ObjectSchema<infer Raw, any> ? Raw : never;
+
+export type inferParsedObject<O extends ObjectSchema<any, any>> =
+ O extends ObjectSchema<any, infer Parsed> ? Parsed : never;
+
+export type inferObjectSchemaFromPropertySchemas<T extends PropertySchemas<keyof T>> = ObjectSchema<
+ inferRawObjectFromPropertySchemas<T>,
+ inferParsedObjectFromPropertySchemas<T>
+>;
+
+export type inferRawObjectFromPropertySchemas<T extends PropertySchemas<keyof T>> =
+ addQuestionMarksToNullableProperties<{
+ [ParsedKey in keyof T as inferRawKey<ParsedKey, T[ParsedKey]>]: inferRawPropertySchema<T[ParsedKey]>;
+ }>;
+
+export type inferParsedObjectFromPropertySchemas<T extends PropertySchemas<keyof T>> =
+ addQuestionMarksToNullableProperties<{
+ [K in keyof T]: inferParsedPropertySchema<T[K]>;
+ }>;
+
+export type PropertySchemas<ParsedKeys extends string | number | symbol> = Record<
+ ParsedKeys,
+ Property<any, any, any> | Schema<any, any>
+>;
+
+export type inferRawPropertySchema<P extends Property<any, any, any> | Schema<any, any>> =
+ P extends Property<any, infer Raw, any> ? Raw : P extends Schema<any, any> ? inferRaw<P> : never;
+
+export type inferParsedPropertySchema<P extends Property<any, any, any> | Schema<any, any>> =
+ P extends Property<any, any, infer Parsed> ? Parsed : P extends Schema<any, any> ? inferParsed<P> : never;
+
+export type inferRawKey<
+ ParsedKey extends string | number | symbol,
+ P extends Property<any, any, any> | Schema<any, any>,
+> = P extends Property<infer Raw, any, any> ? Raw : ParsedKey;
diff --git a/packages/sdk/src/core/schemas/builders/primitives/any.ts b/packages/sdk/src/core/schemas/builders/primitives/any.ts
new file mode 100644
index 000000000..bc4d47fab
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/any.ts
@@ -0,0 +1,7 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+
+export const any: () => Schema<any, any> = createIdentitySchemaCreator<any>(SchemaType.ANY, (value) => ({
+ ok: true,
+ value,
+}));
diff --git a/packages/sdk/src/core/schemas/builders/primitives/boolean.ts b/packages/sdk/src/core/schemas/builders/primitives/boolean.ts
new file mode 100644
index 000000000..78c3c3628
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/boolean.ts
@@ -0,0 +1,25 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export const boolean: () => Schema<boolean, boolean> = createIdentitySchemaCreator<boolean>(
+ SchemaType.BOOLEAN,
+ (value, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof value === "boolean") {
+ return {
+ ok: true,
+ value,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "boolean"),
+ },
+ ],
+ };
+ }
+ },
+);
diff --git a/packages/sdk/src/core/schemas/builders/primitives/index.ts b/packages/sdk/src/core/schemas/builders/primitives/index.ts
new file mode 100644
index 000000000..7a3ee0154
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/index.ts
@@ -0,0 +1,6 @@
+export { any } from "./any.js";
+export { boolean } from "./boolean.js";
+export { never } from "./never.js";
+export { number } from "./number.js";
+export { string } from "./string.js";
+export { unknown } from "./unknown.js";
diff --git a/packages/sdk/src/core/schemas/builders/primitives/never.ts b/packages/sdk/src/core/schemas/builders/primitives/never.ts
new file mode 100644
index 000000000..91f85d74c
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/never.ts
@@ -0,0 +1,15 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+
+export const never: () => Schema<never, never> = createIdentitySchemaCreator<never>(
+ SchemaType.NEVER,
+ (_value, { breadcrumbsPrefix = [] } = {}) => ({
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: "Expected never",
+ },
+ ],
+ }),
+);
diff --git a/packages/sdk/src/core/schemas/builders/primitives/number.ts b/packages/sdk/src/core/schemas/builders/primitives/number.ts
new file mode 100644
index 000000000..6f16cd462
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/number.ts
@@ -0,0 +1,25 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export const number: () => Schema<number, number> = createIdentitySchemaCreator<number>(
+ SchemaType.NUMBER,
+ (value, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof value === "number") {
+ return {
+ ok: true,
+ value,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "number"),
+ },
+ ],
+ };
+ }
+ },
+);
diff --git a/packages/sdk/src/core/schemas/builders/primitives/string.ts b/packages/sdk/src/core/schemas/builders/primitives/string.ts
new file mode 100644
index 000000000..b29d72ae7
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/string.ts
@@ -0,0 +1,25 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+
+export const string: () => Schema<string, string> = createIdentitySchemaCreator<string>(
+ SchemaType.STRING,
+ (value, { breadcrumbsPrefix = [] } = {}) => {
+ if (typeof value === "string") {
+ return {
+ ok: true,
+ value,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "string"),
+ },
+ ],
+ };
+ }
+ },
+);
diff --git a/packages/sdk/src/core/schemas/builders/primitives/unknown.ts b/packages/sdk/src/core/schemas/builders/primitives/unknown.ts
new file mode 100644
index 000000000..045141603
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/primitives/unknown.ts
@@ -0,0 +1,7 @@
+import { type Schema, SchemaType } from "../../Schema.js";
+import { createIdentitySchemaCreator } from "../../utils/createIdentitySchemaCreator.js";
+
+export const unknown: () => Schema<unknown, unknown> = createIdentitySchemaCreator<unknown>(
+ SchemaType.UNKNOWN,
+ (value) => ({ ok: true, value }),
+);
diff --git a/packages/sdk/src/core/schemas/builders/record/index.ts b/packages/sdk/src/core/schemas/builders/record/index.ts
new file mode 100644
index 000000000..44b8c334d
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/record/index.ts
@@ -0,0 +1,2 @@
+export { partialRecord, record } from "./record.js";
+export type { BasePartialRecordSchema, BaseRecordSchema, PartialRecordSchema, RecordSchema } from "./types.js";
diff --git a/packages/sdk/src/core/schemas/builders/record/record.ts b/packages/sdk/src/core/schemas/builders/record/record.ts
new file mode 100644
index 000000000..b9801fdd5
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/record/record.ts
@@ -0,0 +1,170 @@
+import { type MaybeValid, type Schema, SchemaType, type ValidationError } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { isPlainObject } from "../../utils/isPlainObject.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import type { BasePartialRecordSchema, BaseRecordSchema, PartialRecordSchema, RecordSchema } from "./types.js";
+
+// eslint-disable-next-line @typescript-eslint/unbound-method
+const _hasOwn = Object.prototype.hasOwnProperty;
+
+export function record<RawKey extends string | number, RawValue, ParsedValue, ParsedKey extends string | number>(
+ keySchema: Schema<RawKey, ParsedKey>,
+ valueSchema: Schema<RawValue, ParsedValue>,
+): RecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> {
+ const baseSchema: BaseRecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> = {
+ parse: (raw, opts) => {
+ return validateAndTransformRecord({
+ value: raw,
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
+ transformKey: (key) =>
+ keySchema.parse(key, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`],
+ }),
+ transformValue: (value, key) =>
+ valueSchema.parse(value, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`],
+ }),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ json: (parsed, opts) => {
+ return validateAndTransformRecord({
+ value: parsed,
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
+ transformKey: (key) =>
+ keySchema.json(key, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`],
+ }),
+ transformValue: (value, key) =>
+ valueSchema.json(value, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`],
+ }),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ getType: () => SchemaType.RECORD,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+export function partialRecord<RawKey extends string | number, RawValue, ParsedValue, ParsedKey extends string | number>(
+ keySchema: Schema<RawKey, ParsedKey>,
+ valueSchema: Schema<RawValue, ParsedValue>,
+): PartialRecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> {
+ const baseSchema: BasePartialRecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> = {
+ parse: (raw, opts) => {
+ return validateAndTransformRecord({
+ value: raw,
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
+ transformKey: (key) =>
+ keySchema.parse(key, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`],
+ }),
+ transformValue: (value, key) =>
+ valueSchema.parse(value, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`],
+ }),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ json: (parsed, opts) => {
+ return validateAndTransformRecord({
+ value: parsed,
+ isKeyNumeric: keySchema.getType() === SchemaType.NUMBER,
+ transformKey: (key) =>
+ keySchema.json(key, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key} (key)`],
+ }),
+ transformValue: (value, key) =>
+ valueSchema.json(value, {
+ ...opts,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), `${key}`],
+ }),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ getType: () => SchemaType.RECORD,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+function validateAndTransformRecord<TransformedKey extends string | number, TransformedValue>({
+ value,
+ isKeyNumeric,
+ transformKey,
+ transformValue,
+ breadcrumbsPrefix = [],
+}: {
+ value: unknown;
+ isKeyNumeric: boolean;
+ transformKey: (key: string | number) => MaybeValid<TransformedKey>;
+ transformValue: (value: unknown, key: string | number) => MaybeValid<TransformedValue>;
+ breadcrumbsPrefix: string[] | undefined;
+}): MaybeValid<Record<TransformedKey, TransformedValue>> {
+ if (!isPlainObject(value)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "object"),
+ },
+ ],
+ };
+ }
+
+ const result = {} as Record<TransformedKey, TransformedValue>;
+ const errors: ValidationError[] = [];
+
+ for (const stringKey in value) {
+ if (!_hasOwn.call(value, stringKey)) {
+ continue;
+ }
+ const entryValue = (value as Record<string, unknown>)[stringKey];
+ if (entryValue === undefined) {
+ continue;
+ }
+
+ let key: string | number = stringKey;
+ if (isKeyNumeric) {
+ const numberKey = stringKey.length > 0 ? Number(stringKey) : NaN;
+ if (!Number.isNaN(numberKey)) {
+ key = numberKey;
+ }
+ }
+ const transformedKey = transformKey(key);
+ const transformedValue = transformValue(entryValue, key);
+
+ if (transformedKey.ok && transformedValue.ok) {
+ result[transformedKey.value] = transformedValue.value;
+ } else {
+ if (!transformedKey.ok) {
+ errors.push(...transformedKey.errors);
+ }
+ if (!transformedValue.ok) {
+ errors.push(...transformedValue.errors);
+ }
+ }
+ }
+
+ if (errors.length === 0) {
+ return { ok: true, value: result };
+ }
+ return { ok: false, errors };
+}
diff --git a/packages/sdk/src/core/schemas/builders/record/types.ts b/packages/sdk/src/core/schemas/builders/record/types.ts
new file mode 100644
index 000000000..fa7623853
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/record/types.ts
@@ -0,0 +1,32 @@
+import type { BaseSchema } from "../../Schema.js";
+import type { SchemaUtils } from "../schema-utils/index.js";
+
+export type RecordSchema<
+ RawKey extends string | number,
+ RawValue,
+ ParsedKey extends string | number,
+ ParsedValue,
+> = BaseRecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> &
+ SchemaUtils<Record<RawKey, RawValue>, Record<ParsedKey, ParsedValue>>;
+
+export type BaseRecordSchema<
+ RawKey extends string | number,
+ RawValue,
+ ParsedKey extends string | number,
+ ParsedValue,
+> = BaseSchema<Record<RawKey, RawValue>, Record<ParsedKey, ParsedValue>>;
+
+export type PartialRecordSchema<
+ RawKey extends string | number,
+ RawValue,
+ ParsedKey extends string | number,
+ ParsedValue,
+> = BasePartialRecordSchema<RawKey, RawValue, ParsedKey, ParsedValue> &
+ SchemaUtils<Record<RawKey, RawValue>, Partial<Record<ParsedKey, ParsedValue>>>;
+
+export type BasePartialRecordSchema<
+ RawKey extends string | number,
+ RawValue,
+ ParsedKey extends string | number,
+ ParsedValue,
+> = BaseSchema<Record<RawKey, RawValue>, Partial<Record<ParsedKey, ParsedValue>>>;
diff --git a/packages/sdk/src/core/schemas/builders/schema-utils/JsonError.ts b/packages/sdk/src/core/schemas/builders/schema-utils/JsonError.ts
new file mode 100644
index 000000000..daff49ed6
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/schema-utils/JsonError.ts
@@ -0,0 +1,10 @@
+import type { ValidationError } from "../../Schema.js";
+import { stringifyValidationError } from "./stringifyValidationErrors.js";
+
+export class JsonError extends Error {
+ constructor(public readonly errors: ValidationError[]) {
+ super(errors.map(stringifyValidationError).join("; "));
+ Object.setPrototypeOf(this, JsonError.prototype);
+ this.name = "JsonError";
+ }
+}
diff --git a/packages/sdk/src/core/schemas/builders/schema-utils/ParseError.ts b/packages/sdk/src/core/schemas/builders/schema-utils/ParseError.ts
new file mode 100644
index 000000000..b880e63ca
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/schema-utils/ParseError.ts
@@ -0,0 +1,10 @@
+import type { ValidationError } from "../../Schema.js";
+import { stringifyValidationError } from "./stringifyValidationErrors.js";
+
+export class ParseError extends Error {
+ constructor(public readonly errors: ValidationError[]) {
+ super(errors.map(stringifyValidationError).join("; "));
+ Object.setPrototypeOf(this, ParseError.prototype);
+ this.name = "ParseError";
+ }
+}
diff --git a/packages/sdk/src/core/schemas/builders/schema-utils/getSchemaUtils.ts b/packages/sdk/src/core/schemas/builders/schema-utils/getSchemaUtils.ts
new file mode 100644
index 000000000..3ceaf4e01
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/schema-utils/getSchemaUtils.ts
@@ -0,0 +1,181 @@
+import { type BaseSchema, type Schema, type SchemaOptions, SchemaType } from "../../Schema.js";
+import { JsonError } from "./JsonError.js";
+import { ParseError } from "./ParseError.js";
+
+export interface SchemaUtils<Raw, Parsed> {
+ nullable: () => Schema<Raw | null, Parsed | null>;
+ optional: () => Schema<Raw | null | undefined, Parsed | undefined>;
+ optionalNullable: () => Schema<Raw | null | undefined, Parsed | null | undefined>;
+ transform: <Transformed>(transformer: SchemaTransformer<Parsed, Transformed>) => Schema<Raw, Transformed>;
+ parseOrThrow: (raw: unknown, opts?: SchemaOptions) => Parsed;
+ jsonOrThrow: (raw: unknown, opts?: SchemaOptions) => Raw;
+}
+
+export interface SchemaTransformer<Parsed, Transformed> {
+ transform: (parsed: Parsed) => Transformed;
+ untransform: (transformed: any) => Parsed;
+}
+
+export function getSchemaUtils<Raw, Parsed>(schema: BaseSchema<Raw, Parsed>): SchemaUtils<Raw, Parsed> {
+ return {
+ nullable: () => nullable(schema),
+ optional: () => optional(schema),
+ optionalNullable: () => optionalNullable(schema),
+ transform: (transformer) => transform(schema, transformer),
+ parseOrThrow: (raw, opts) => {
+ const parsed = schema.parse(raw, opts);
+ if (parsed.ok) {
+ return parsed.value;
+ }
+ throw new ParseError(parsed.errors);
+ },
+ jsonOrThrow: (parsed, opts) => {
+ const raw = schema.json(parsed, opts);
+ if (raw.ok) {
+ return raw.value;
+ }
+ throw new JsonError(raw.errors);
+ },
+ };
+}
+
+/**
+ * schema utils are defined in one file to resolve issues with circular imports
+ */
+
+export function nullable<Raw, Parsed>(schema: BaseSchema<Raw, Parsed>): Schema<Raw | null, Parsed | null> {
+ const baseSchema: BaseSchema<Raw | null, Parsed | null> = {
+ parse: (raw, opts) => {
+ if (raw == null) {
+ return {
+ ok: true,
+ value: null,
+ };
+ }
+ return schema.parse(raw, opts);
+ },
+ json: (parsed, opts) => {
+ if (parsed == null) {
+ return {
+ ok: true,
+ value: null,
+ };
+ }
+ return schema.json(parsed, opts);
+ },
+ getType: () => SchemaType.NULLABLE,
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+export function optional<Raw, Parsed>(
+ schema: BaseSchema<Raw, Parsed>,
+): Schema<Raw | null | undefined, Parsed | undefined> {
+ const baseSchema: BaseSchema<Raw | null | undefined, Parsed | undefined> = {
+ parse: (raw, opts) => {
+ if (raw == null) {
+ return {
+ ok: true,
+ value: undefined,
+ };
+ }
+ return schema.parse(raw, opts);
+ },
+ json: (parsed, opts) => {
+ if (opts?.omitUndefined && parsed === undefined) {
+ return {
+ ok: true,
+ value: undefined,
+ };
+ }
+ if (parsed == null) {
+ return {
+ ok: true,
+ value: null,
+ };
+ }
+ return schema.json(parsed, opts);
+ },
+ getType: () => SchemaType.OPTIONAL,
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+export function optionalNullable<Raw, Parsed>(
+ schema: BaseSchema<Raw, Parsed>,
+): Schema<Raw | null | undefined, Parsed | null | undefined> {
+ const baseSchema: BaseSchema<Raw | null | undefined, Parsed | null | undefined> = {
+ parse: (raw, opts) => {
+ if (raw === undefined) {
+ return {
+ ok: true,
+ value: undefined,
+ };
+ }
+ if (raw === null) {
+ return {
+ ok: true,
+ value: null,
+ };
+ }
+ return schema.parse(raw, opts);
+ },
+ json: (parsed, opts) => {
+ if (parsed === undefined) {
+ return {
+ ok: true,
+ value: undefined,
+ };
+ }
+ if (parsed === null) {
+ return {
+ ok: true,
+ value: null,
+ };
+ }
+ return schema.json(parsed, opts);
+ },
+ getType: () => SchemaType.OPTIONAL_NULLABLE,
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+export function transform<Raw, Parsed, Transformed>(
+ schema: BaseSchema<Raw, Parsed>,
+ transformer: SchemaTransformer<Parsed, Transformed>,
+): Schema<Raw, Transformed> {
+ const baseSchema: BaseSchema<Raw, Transformed> = {
+ parse: (raw, opts) => {
+ const parsed = schema.parse(raw, opts);
+ if (!parsed.ok) {
+ return parsed;
+ }
+ return {
+ ok: true,
+ value: transformer.transform(parsed.value),
+ };
+ },
+ json: (transformed, opts) => {
+ const parsed = transformer.untransform(transformed);
+ return schema.json(parsed, opts);
+ },
+ getType: () => schema.getType(),
+ };
+
+ return {
+ ...baseSchema,
+ ...getSchemaUtils(baseSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/schema-utils/index.ts b/packages/sdk/src/core/schemas/builders/schema-utils/index.ts
new file mode 100644
index 000000000..efb3b0c46
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/schema-utils/index.ts
@@ -0,0 +1,4 @@
+export type { SchemaUtils } from "./getSchemaUtils.js";
+export { getSchemaUtils, optional, transform } from "./getSchemaUtils.js";
+export { JsonError } from "./JsonError.js";
+export { ParseError } from "./ParseError.js";
diff --git a/packages/sdk/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts b/packages/sdk/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts
new file mode 100644
index 000000000..d36a4900c
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/schema-utils/stringifyValidationErrors.ts
@@ -0,0 +1,8 @@
+import type { ValidationError } from "../../Schema.js";
+
+export function stringifyValidationError(error: ValidationError): string {
+ if (error.path.length === 0) {
+ return error.message;
+ }
+ return `${error.path.join(" -> ")}: ${error.message}`;
+}
diff --git a/packages/sdk/src/core/schemas/builders/set/index.ts b/packages/sdk/src/core/schemas/builders/set/index.ts
new file mode 100644
index 000000000..c72be55e9
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/set/index.ts
@@ -0,0 +1 @@
+export { set } from "./set.js";
diff --git a/packages/sdk/src/core/schemas/builders/set/set.ts b/packages/sdk/src/core/schemas/builders/set/set.ts
new file mode 100644
index 000000000..2013cdb47
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/set/set.ts
@@ -0,0 +1,43 @@
+import { type BaseSchema, type Schema, SchemaType } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { list } from "../list/index.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+
+export function set<Raw, Parsed>(schema: Schema<Raw, Parsed>): Schema<Raw[], Set<Parsed>> {
+ const listSchema = list(schema);
+ const baseSchema: BaseSchema<Raw[], Set<Parsed>> = {
+ parse: (raw, opts) => {
+ const parsedList = listSchema.parse(raw, opts);
+ if (parsedList.ok) {
+ return {
+ ok: true,
+ value: new Set(parsedList.value),
+ };
+ } else {
+ return parsedList;
+ }
+ },
+ json: (parsed, opts) => {
+ if (!(parsed instanceof Set)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: opts?.breadcrumbsPrefix ?? [],
+ message: getErrorMessageForIncorrectType(parsed, "Set"),
+ },
+ ],
+ };
+ }
+ const jsonList = listSchema.json([...parsed], opts);
+ return jsonList;
+ },
+ getType: () => SchemaType.SET,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/undiscriminated-union/index.ts b/packages/sdk/src/core/schemas/builders/undiscriminated-union/index.ts
new file mode 100644
index 000000000..c8318222b
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/undiscriminated-union/index.ts
@@ -0,0 +1,6 @@
+export type {
+ inferParsedUnidiscriminatedUnionSchema,
+ inferRawUnidiscriminatedUnionSchema,
+ UndiscriminatedUnionSchema,
+} from "./types.js";
+export { undiscriminatedUnion } from "./undiscriminatedUnion.js";
diff --git a/packages/sdk/src/core/schemas/builders/undiscriminated-union/types.ts b/packages/sdk/src/core/schemas/builders/undiscriminated-union/types.ts
new file mode 100644
index 000000000..0d5096fab
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/undiscriminated-union/types.ts
@@ -0,0 +1,10 @@
+import type { inferParsed, inferRaw, Schema } from "../../Schema.js";
+
+export type UndiscriminatedUnionSchema<Schemas extends [...Schema[]]> = Schema<
+ inferRawUnidiscriminatedUnionSchema<Schemas>,
+ inferParsedUnidiscriminatedUnionSchema<Schemas>
+>;
+
+export type inferRawUnidiscriminatedUnionSchema<Schemas extends [...Schema[]]> = inferRaw<Schemas[number]>;
+
+export type inferParsedUnidiscriminatedUnionSchema<Schemas extends [...Schema[]]> = inferParsed<Schemas[number]>;
diff --git a/packages/sdk/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts b/packages/sdk/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts
new file mode 100644
index 000000000..07591b4d3
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/undiscriminated-union/undiscriminatedUnion.ts
@@ -0,0 +1,67 @@
+import {
+ type BaseSchema,
+ type MaybeValid,
+ type Schema,
+ type SchemaOptions,
+ SchemaType,
+ type ValidationError,
+} from "../../Schema.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import type { inferParsedUnidiscriminatedUnionSchema, inferRawUnidiscriminatedUnionSchema } from "./types.js";
+
+export function undiscriminatedUnion<Schemas extends [Schema<any, any>, ...Schema<any, any>[]]>(
+ schemas: Schemas,
+): Schema<inferRawUnidiscriminatedUnionSchema<Schemas>, inferParsedUnidiscriminatedUnionSchema<Schemas>> {
+ const baseSchema: BaseSchema<
+ inferRawUnidiscriminatedUnionSchema<Schemas>,
+ inferParsedUnidiscriminatedUnionSchema<Schemas>
+ > = {
+ parse: (raw, opts) => {
+ return validateAndTransformUndiscriminatedUnion<inferParsedUnidiscriminatedUnionSchema<Schemas>>(
+ (schema, opts) => schema.parse(raw, opts),
+ schemas,
+ opts,
+ );
+ },
+ json: (parsed, opts) => {
+ return validateAndTransformUndiscriminatedUnion<inferRawUnidiscriminatedUnionSchema<Schemas>>(
+ (schema, opts) => schema.json(parsed, opts),
+ schemas,
+ opts,
+ );
+ },
+ getType: () => SchemaType.UNDISCRIMINATED_UNION,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+}
+
+function validateAndTransformUndiscriminatedUnion<Transformed>(
+ transform: (schema: Schema<any, any>, opts: SchemaOptions) => MaybeValid<Transformed>,
+ schemas: Schema<any, any>[],
+ opts: SchemaOptions | undefined,
+): MaybeValid<Transformed> {
+ const errors: ValidationError[] = [];
+ for (const [index, schema] of schemas.entries()) {
+ const transformed = transform(schema, { ...opts, skipValidation: false });
+ if (transformed.ok) {
+ return transformed;
+ } else {
+ for (const error of transformed.errors) {
+ errors.push({
+ path: error.path,
+ message: `[Variant ${index}] ${error.message}`,
+ });
+ }
+ }
+ }
+
+ return {
+ ok: false,
+ errors,
+ };
+}
diff --git a/packages/sdk/src/core/schemas/builders/union/discriminant.ts b/packages/sdk/src/core/schemas/builders/union/discriminant.ts
new file mode 100644
index 000000000..73cd62ade
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/union/discriminant.ts
@@ -0,0 +1,14 @@
+export function discriminant<RawDiscriminant extends string, ParsedDiscriminant extends string>(
+ parsedDiscriminant: ParsedDiscriminant,
+ rawDiscriminant: RawDiscriminant,
+): Discriminant<RawDiscriminant, ParsedDiscriminant> {
+ return {
+ parsedDiscriminant,
+ rawDiscriminant,
+ };
+}
+
+export interface Discriminant<RawDiscriminant extends string, ParsedDiscriminant extends string> {
+ parsedDiscriminant: ParsedDiscriminant;
+ rawDiscriminant: RawDiscriminant;
+}
diff --git a/packages/sdk/src/core/schemas/builders/union/index.ts b/packages/sdk/src/core/schemas/builders/union/index.ts
new file mode 100644
index 000000000..6bc29ba9e
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/union/index.ts
@@ -0,0 +1,10 @@
+export type { Discriminant } from "./discriminant.js";
+export { discriminant } from "./discriminant.js";
+export type {
+ inferParsedDiscriminant,
+ inferParsedUnion,
+ inferRawDiscriminant,
+ inferRawUnion,
+ UnionSubtypes,
+} from "./types.js";
+export { union } from "./union.js";
diff --git a/packages/sdk/src/core/schemas/builders/union/types.ts b/packages/sdk/src/core/schemas/builders/union/types.ts
new file mode 100644
index 000000000..7bfdd636d
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/union/types.ts
@@ -0,0 +1,26 @@
+import type { inferParsedObject, inferRawObject, ObjectSchema } from "../object/index.js";
+import type { Discriminant } from "./discriminant.js";
+
+export type UnionSubtypes<DiscriminantValues extends string | number | symbol> = {
+ [K in DiscriminantValues]: ObjectSchema<any, any>;
+};
+
+export type inferRawUnion<D extends string | Discriminant<any, any>, U extends UnionSubtypes<keyof U>> = {
+ [K in keyof U]: Record<inferRawDiscriminant<D>, K> & inferRawObject<U[K]>;
+}[keyof U];
+
+export type inferParsedUnion<D extends string | Discriminant<any, any>, U extends UnionSubtypes<keyof U>> = {
+ [K in keyof U]: Record<inferParsedDiscriminant<D>, K> & inferParsedObject<U[K]>;
+}[keyof U];
+
+export type inferRawDiscriminant<D extends string | Discriminant<any, any>> = D extends string
+ ? D
+ : D extends Discriminant<infer Raw, any>
+ ? Raw
+ : never;
+
+export type inferParsedDiscriminant<D extends string | Discriminant<any, any>> = D extends string
+ ? D
+ : D extends Discriminant<any, infer Parsed>
+ ? Parsed
+ : never;
diff --git a/packages/sdk/src/core/schemas/builders/union/union.ts b/packages/sdk/src/core/schemas/builders/union/union.ts
new file mode 100644
index 000000000..fa993fdc0
--- /dev/null
+++ b/packages/sdk/src/core/schemas/builders/union/union.ts
@@ -0,0 +1,185 @@
+import { type BaseSchema, type MaybeValid, SchemaType } from "../../Schema.js";
+import { getErrorMessageForIncorrectType } from "../../utils/getErrorMessageForIncorrectType.js";
+import { isPlainObject } from "../../utils/isPlainObject.js";
+import { keys } from "../../utils/keys.js";
+import { maybeSkipValidation } from "../../utils/maybeSkipValidation.js";
+import { enum_ } from "../enum/index.js";
+import type { ObjectSchema } from "../object/index.js";
+import { getObjectLikeUtils, type ObjectLikeSchema } from "../object-like/index.js";
+import { getSchemaUtils } from "../schema-utils/index.js";
+import type { Discriminant } from "./discriminant.js";
+import type {
+ inferParsedDiscriminant,
+ inferParsedUnion,
+ inferRawDiscriminant,
+ inferRawUnion,
+ UnionSubtypes,
+} from "./types.js";
+
+// eslint-disable-next-line @typescript-eslint/unbound-method
+const _hasOwn = Object.prototype.hasOwnProperty;
+
+export function union<D extends string | Discriminant<any, any>, U extends UnionSubtypes<any>>(
+ discriminant: D,
+ union: U,
+): ObjectLikeSchema<inferRawUnion<D, U>, inferParsedUnion<D, U>> {
+ const rawDiscriminant =
+ typeof discriminant === "string" ? discriminant : (discriminant.rawDiscriminant as inferRawDiscriminant<D>);
+ const parsedDiscriminant =
+ typeof discriminant === "string"
+ ? discriminant
+ : (discriminant.parsedDiscriminant as inferParsedDiscriminant<D>);
+
+ const discriminantValueSchema = enum_(keys(union) as string[]);
+
+ const baseSchema: BaseSchema<inferRawUnion<D, U>, inferParsedUnion<D, U>> = {
+ parse: (raw, opts) => {
+ return transformAndValidateUnion({
+ value: raw,
+ discriminant: rawDiscriminant,
+ transformedDiscriminant: parsedDiscriminant,
+ transformDiscriminantValue: (discriminantValue) =>
+ discriminantValueSchema.parse(discriminantValue, {
+ allowUnrecognizedEnumValues: opts?.allowUnrecognizedUnionMembers,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), rawDiscriminant],
+ }),
+ getAdditionalPropertiesSchema: (discriminantValue) => union[discriminantValue],
+ allowUnrecognizedUnionMembers: opts?.allowUnrecognizedUnionMembers,
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) =>
+ additionalPropertiesSchema.parse(additionalProperties, opts),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ json: (parsed, opts) => {
+ return transformAndValidateUnion({
+ value: parsed,
+ discriminant: parsedDiscriminant,
+ transformedDiscriminant: rawDiscriminant,
+ transformDiscriminantValue: (discriminantValue) =>
+ discriminantValueSchema.json(discriminantValue, {
+ allowUnrecognizedEnumValues: opts?.allowUnrecognizedUnionMembers,
+ breadcrumbsPrefix: [...(opts?.breadcrumbsPrefix ?? []), parsedDiscriminant],
+ }),
+ getAdditionalPropertiesSchema: (discriminantValue) => union[discriminantValue],
+ allowUnrecognizedUnionMembers: opts?.allowUnrecognizedUnionMembers,
+ transformAdditionalProperties: (additionalProperties, additionalPropertiesSchema) =>
+ additionalPropertiesSchema.json(additionalProperties, opts),
+ breadcrumbsPrefix: opts?.breadcrumbsPrefix,
+ });
+ },
+ getType: () => SchemaType.UNION,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ ...getObjectLikeUtils(baseSchema),
+ };
+}
+
+function transformAndValidateUnion<
+ TransformedDiscriminant extends string,
+ TransformedDiscriminantValue extends string,
+ TransformedAdditionalProperties,
+>({
+ value,
+ discriminant,
+ transformedDiscriminant,
+ transformDiscriminantValue,
+ getAdditionalPropertiesSchema,
+ allowUnrecognizedUnionMembers = false,
+ transformAdditionalProperties,
+ breadcrumbsPrefix = [],
+}: {
+ value: unknown;
+ discriminant: string;
+ transformedDiscriminant: TransformedDiscriminant;
+ transformDiscriminantValue: (discriminantValue: unknown) => MaybeValid<TransformedDiscriminantValue>;
+ getAdditionalPropertiesSchema: (discriminantValue: string) => ObjectSchema<any, any> | undefined;
+ allowUnrecognizedUnionMembers: boolean | undefined;
+ transformAdditionalProperties: (
+ additionalProperties: unknown,
+ additionalPropertiesSchema: ObjectSchema<any, any>,
+ ) => MaybeValid<TransformedAdditionalProperties>;
+ breadcrumbsPrefix: string[] | undefined;
+}): MaybeValid<Record<TransformedDiscriminant, TransformedDiscriminantValue> & TransformedAdditionalProperties> {
+ if (!isPlainObject(value)) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: getErrorMessageForIncorrectType(value, "object"),
+ },
+ ],
+ };
+ }
+
+ const discriminantValue = value[discriminant];
+ const additionalProperties: Record<string, unknown> = {};
+ for (const key in value) {
+ if (_hasOwn.call(value, key) && key !== discriminant) {
+ additionalProperties[key] = value[key];
+ }
+ }
+
+ if (discriminantValue == null) {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: breadcrumbsPrefix,
+ message: `Missing discriminant ("${discriminant}")`,
+ },
+ ],
+ };
+ }
+
+ const transformedDiscriminantValue = transformDiscriminantValue(discriminantValue);
+ if (!transformedDiscriminantValue.ok) {
+ return {
+ ok: false,
+ errors: transformedDiscriminantValue.errors,
+ };
+ }
+
+ const additionalPropertiesSchema = getAdditionalPropertiesSchema(transformedDiscriminantValue.value);
+
+ if (additionalPropertiesSchema == null) {
+ if (allowUnrecognizedUnionMembers) {
+ return {
+ ok: true,
+ value: {
+ [transformedDiscriminant]: transformedDiscriminantValue.value,
+ ...additionalProperties,
+ } as Record<TransformedDiscriminant, TransformedDiscriminantValue> & TransformedAdditionalProperties,
+ };
+ } else {
+ return {
+ ok: false,
+ errors: [
+ {
+ path: [...breadcrumbsPrefix, discriminant],
+ message: "Unexpected discriminant value",
+ },
+ ],
+ };
+ }
+ }
+
+ const transformedAdditionalProperties = transformAdditionalProperties(
+ additionalProperties,
+ additionalPropertiesSchema,
+ );
+ if (!transformedAdditionalProperties.ok) {
+ return transformedAdditionalProperties;
+ }
+
+ return {
+ ok: true,
+ value: {
+ [transformedDiscriminant]: discriminantValue,
+ ...transformedAdditionalProperties.value,
+ } as Record<TransformedDiscriminant, TransformedDiscriminantValue> & TransformedAdditionalProperties,
+ };
+}
diff --git a/packages/sdk/src/core/schemas/index.ts b/packages/sdk/src/core/schemas/index.ts
new file mode 100644
index 000000000..befac2e3b
--- /dev/null
+++ b/packages/sdk/src/core/schemas/index.ts
@@ -0,0 +1,2 @@
+export * from "./builders/index.js";
+export type { inferParsed, inferRaw, Schema, SchemaOptions } from "./Schema.js";
diff --git a/packages/sdk/src/core/schemas/utils/MaybePromise.ts b/packages/sdk/src/core/schemas/utils/MaybePromise.ts
new file mode 100644
index 000000000..9cd354b34
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/MaybePromise.ts
@@ -0,0 +1 @@
+export type MaybePromise<T> = T | Promise<T>;
diff --git a/packages/sdk/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts b/packages/sdk/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts
new file mode 100644
index 000000000..59f9e6588
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/addQuestionMarksToNullableProperties.ts
@@ -0,0 +1,9 @@
+export type addQuestionMarksToNullableProperties<T> = {
+ [K in OptionalKeys<T>]?: T[K];
+} & Pick<T, RequiredKeys<T>>;
+
+export type OptionalKeys<T> = {
+ [K in keyof T]-?: undefined extends T[K] ? K : never;
+}[keyof T];
+
+export type RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;
diff --git a/packages/sdk/src/core/schemas/utils/createIdentitySchemaCreator.ts b/packages/sdk/src/core/schemas/utils/createIdentitySchemaCreator.ts
new file mode 100644
index 000000000..9aa4ed502
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/createIdentitySchemaCreator.ts
@@ -0,0 +1,21 @@
+import { getSchemaUtils } from "../builders/schema-utils/index.js";
+import type { BaseSchema, MaybeValid, Schema, SchemaOptions, SchemaType } from "../Schema.js";
+import { maybeSkipValidation } from "./maybeSkipValidation.js";
+
+export function createIdentitySchemaCreator<T>(
+ schemaType: SchemaType,
+ validate: (value: unknown, opts?: SchemaOptions) => MaybeValid<T>,
+): () => Schema<T, T> {
+ return () => {
+ const baseSchema: BaseSchema<T, T> = {
+ parse: validate,
+ json: validate,
+ getType: () => schemaType,
+ };
+
+ return {
+ ...maybeSkipValidation(baseSchema),
+ ...getSchemaUtils(baseSchema),
+ };
+ };
+}
diff --git a/packages/sdk/src/core/schemas/utils/entries.ts b/packages/sdk/src/core/schemas/utils/entries.ts
new file mode 100644
index 000000000..2d5c93d65
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/entries.ts
@@ -0,0 +1,3 @@
+export function entries<T extends object>(object: T): [keyof T, T[keyof T]][] {
+ return Object.entries(object) as [keyof T, T[keyof T]][];
+}
diff --git a/packages/sdk/src/core/schemas/utils/filterObject.ts b/packages/sdk/src/core/schemas/utils/filterObject.ts
new file mode 100644
index 000000000..70527d100
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/filterObject.ts
@@ -0,0 +1,13 @@
+export function filterObject<T extends object, K extends keyof T>(obj: T, keysToInclude: K[]): Pick<T, K> {
+ const keysToIncludeSet = new Set(keysToInclude);
+ return Object.entries(obj).reduce(
+ (acc, [key, value]) => {
+ if (keysToIncludeSet.has(key as K)) {
+ acc[key as K] = value as T[K];
+ }
+ return acc;
+ // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter
+ },
+ {} as Pick<T, K>,
+ );
+}
diff --git a/packages/sdk/src/core/schemas/utils/getErrorMessageForIncorrectType.ts b/packages/sdk/src/core/schemas/utils/getErrorMessageForIncorrectType.ts
new file mode 100644
index 000000000..1a5c31027
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/getErrorMessageForIncorrectType.ts
@@ -0,0 +1,25 @@
+export function getErrorMessageForIncorrectType(value: unknown, expectedType: string): string {
+ return `Expected ${expectedType}. Received ${getTypeAsString(value)}.`;
+}
+
+function getTypeAsString(value: unknown): string {
+ if (Array.isArray(value)) {
+ return "list";
+ }
+ if (value === null) {
+ return "null";
+ }
+ if (value instanceof BigInt) {
+ return "BigInt";
+ }
+ switch (typeof value) {
+ case "string":
+ return `"${value}"`;
+ case "bigint":
+ case "number":
+ case "boolean":
+ case "undefined":
+ return `${value}`;
+ }
+ return typeof value;
+}
diff --git a/packages/sdk/src/core/schemas/utils/isPlainObject.ts b/packages/sdk/src/core/schemas/utils/isPlainObject.ts
new file mode 100644
index 000000000..32a17e05f
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/isPlainObject.ts
@@ -0,0 +1,14 @@
+// borrowed from https://github.com/lodash/lodash/blob/master/isPlainObject.js
+export function isPlainObject(value: unknown): value is Record<string, unknown> {
+ if (typeof value !== "object" || value === null) {
+ return false;
+ }
+
+ const proto = Object.getPrototypeOf(value);
+ if (proto === null) {
+ return true;
+ }
+
+ // Check that the prototype chain has exactly one level (i.e., proto is Object.prototype)
+ return Object.getPrototypeOf(proto) === null;
+}
diff --git a/packages/sdk/src/core/schemas/utils/keys.ts b/packages/sdk/src/core/schemas/utils/keys.ts
new file mode 100644
index 000000000..2e0930e2d
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/keys.ts
@@ -0,0 +1,3 @@
+export function keys<T extends object>(object: T): (keyof T)[] {
+ return Object.keys(object) as (keyof T)[];
+}
diff --git a/packages/sdk/src/core/schemas/utils/maybeSkipValidation.ts b/packages/sdk/src/core/schemas/utils/maybeSkipValidation.ts
new file mode 100644
index 000000000..f32d45251
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/maybeSkipValidation.ts
@@ -0,0 +1,38 @@
+import type { BaseSchema, MaybeValid, SchemaOptions } from "../Schema.js";
+
+export function maybeSkipValidation<S extends BaseSchema<Raw, Parsed>, Raw, Parsed>(schema: S): S {
+ return {
+ ...schema,
+ json: transformAndMaybeSkipValidation(schema.json),
+ parse: transformAndMaybeSkipValidation(schema.parse),
+ };
+}
+
+function transformAndMaybeSkipValidation<T>(
+ transform: (value: unknown, opts?: SchemaOptions) => MaybeValid<T>,
+): (value: unknown, opts?: SchemaOptions) => MaybeValid<T> {
+ return (value, opts): MaybeValid<T> => {
+ const transformed = transform(value, opts);
+ const { skipValidation = false } = opts ?? {};
+ if (!transformed.ok && skipValidation) {
+ // biome-ignore lint/suspicious/noConsole: allow console
+ console.warn(
+ [
+ "Failed to validate.",
+ ...transformed.errors.map(
+ (error) =>
+ " - " +
+ (error.path.length > 0 ? `${error.path.join(".")}: ${error.message}` : error.message),
+ ),
+ ].join("\n"),
+ );
+
+ return {
+ ok: true,
+ value: value as T,
+ };
+ } else {
+ return transformed;
+ }
+ };
+}
diff --git a/packages/sdk/src/core/schemas/utils/partition.ts b/packages/sdk/src/core/schemas/utils/partition.ts
new file mode 100644
index 000000000..f58d6f3d3
--- /dev/null
+++ b/packages/sdk/src/core/schemas/utils/partition.ts
@@ -0,0 +1,12 @@
+export function partition<T>(items: readonly T[], predicate: (item: T) => boolean): [T[], T[]] {
+ const trueItems: T[] = [],
+ falseItems: T[] = [];
+ for (const item of items) {
+ if (predicate(item)) {
+ trueItems.push(item);
+ } else {
+ falseItems.push(item);
+ }
+ }
+ return [trueItems, falseItems];
+}
diff --git a/packages/sdk/src/core/stream/Stream.ts b/packages/sdk/src/core/stream/Stream.ts
new file mode 100644
index 000000000..c8acd4431
--- /dev/null
+++ b/packages/sdk/src/core/stream/Stream.ts
@@ -0,0 +1,518 @@
+import { fromJson } from "../json.js";
+import { RUNTIME } from "../runtime/index.js";
+
+export declare namespace Stream {
+ interface Args {
+ /**
+ * The HTTP response stream to read from.
+ */
+
+ stream: ReadableStream;
+
+ /**
+ * The event shape to use for parsing the stream data.
+ */
+ eventShape: JsonEvent | SseEvent;
+ /**
+ * An abort signal to stop the stream.
+ */
+ signal?: AbortSignal;
+ /**
+ * Whether transparent mid-stream reconnection is enabled on resumable
+ * SSE endpoints. Defaults to true. Has no effect on non-resumable endpoints.
+ */
+ reconnectionEnabled?: boolean;
+ /**
+ * Maximum number of consecutive failed reconnect attempts on resumable SSE
+ * endpoints before giving up. The counter resets to zero each time a
+ * reconnected stream successfully yields at least one event (i.e. makes
+ * progress). Has no effect on non-resumable endpoints.
+ */
+ maxReconnectionAttempts?: number;
+ /**
+ * A function that re-issues the HTTP request with the Last-Event-ID header
+ * and returns the new response body stream. Required for reconnection to work.
+ */
+
+ reconnect?: (lastEventId: string) => Promise<ReadableStream>;
+ }
+
+ interface JsonEvent {
+ type: "json";
+ messageTerminator: string;
+ }
+
+ interface SseEvent {
+ type: "sse";
+ streamTerminator?: string;
+ eventDiscriminator?: string;
+ resumable?: boolean;
+ }
+}
+
+export interface ServerSentEvent<T> {
+ data: T;
+ id?: string;
+ retry?: number;
+ event?: string;
+}
+
+const DATA_PREFIX = "data:";
+const EVENT_PREFIX = "event:";
+const ID_PREFIX = "id:";
+const RETRY_PREFIX = "retry:";
+
+const DEFAULT_MAX_RECONNECTION_ATTEMPTS = 5;
+const DEFAULT_RECONNECT_DELAY_MS = 1_000;
+const MAX_RECONNECT_DELAY_MS = 30_000;
+
+export class Stream<T> implements AsyncIterable<T> {
+ private stream: ReadableStream;
+
+ private parse: (val: unknown) => Promise<T>;
+ /**
+ * The prefix to use for each message. For example,
+ * for SSE, the prefix is "data: ".
+ */
+ private prefix: string | undefined;
+ private messageTerminator: string;
+ private streamTerminator: string | undefined;
+ private eventDiscriminator: string | undefined;
+ private resumable: boolean;
+ private reconnectionEnabled: boolean;
+ private maxReconnectionAttempts: number;
+
+ private reconnect: ((lastEventId: string) => Promise<ReadableStream>) | undefined;
+
+ private controller: AbortController = new AbortController();
+ private decoder: TextDecoder | undefined;
+ private externalSignal: AbortSignal | undefined;
+ private onExternalAbort: (() => void) | undefined;
+
+ constructor({
+ stream,
+ parse,
+ eventShape,
+ signal,
+ reconnectionEnabled,
+ maxReconnectionAttempts,
+ reconnect,
+ }: Stream.Args & { parse: (val: unknown) => Promise<T> }) {
+ this.stream = stream;
+ this.parse = parse;
+ if (eventShape.type === "sse") {
+ this.prefix = DATA_PREFIX;
+ this.messageTerminator = "\n";
+ this.streamTerminator = eventShape.streamTerminator;
+ this.eventDiscriminator = eventShape.eventDiscriminator;
+ this.resumable = eventShape.resumable ?? false;
+ } else {
+ this.messageTerminator = eventShape.messageTerminator;
+ this.resumable = false;
+ }
+ this.reconnectionEnabled = reconnectionEnabled ?? true;
+ this.maxReconnectionAttempts = maxReconnectionAttempts ?? DEFAULT_MAX_RECONNECTION_ATTEMPTS;
+ this.reconnect = reconnect;
+ if (signal != null) {
+ this.externalSignal = signal;
+ this.onExternalAbort = () => this.controller.abort();
+ signal.addEventListener("abort", this.onExternalAbort, { once: true });
+ }
+
+ // Initialize shared TextDecoder
+ if (typeof TextDecoder !== "undefined") {
+ this.decoder = new TextDecoder("utf-8");
+ }
+ }
+
+ private async *iterMessages(): AsyncGenerator<ServerSentEvent<T>, void> {
+ if (this.eventDiscriminator != null) {
+ yield* this.iterSseEvents();
+ } else {
+ yield* this.iterDataMessages();
+ }
+ }
+
+ private async *iterDataMessages(): AsyncGenerator<ServerSentEvent<T>, void> {
+ let reconnectAttempts = 0;
+ let currentStream = this.stream;
+ let lastId: string | undefined;
+ // The id of the most recently *dispatched* event. Per the WHATWG
+ // EventSource spec, the "last event ID" is only committed when an event
+ // is dispatched, not when the `id:` line is parsed. Reconnecting with a
+ // parsed-but-undispatched id would skip an event that was never yielded
+ // (e.g. if the connection drops after `id:` but before the event's
+ // terminating blank line), so reconnection uses lastDispatchedId.
+ let lastDispatchedId: string | undefined;
+ let lastRetry: number | undefined;
+
+ while (true) {
+ const stream = readableStreamAsyncIterable<any>(currentStream);
+ let buf = "";
+ let dataValue: string | undefined;
+
+ for await (const chunk of stream) {
+ buf += this.decodeChunk(chunk);
+
+ let terminatorIndex: number;
+ while ((terminatorIndex = buf.indexOf(this.messageTerminator)) >= 0) {
+ const line = buf.slice(0, terminatorIndex);
+ buf = buf.slice(terminatorIndex + this.messageTerminator.length);
+
+ if (!line.trim()) {
+ if (this.prefix != null && dataValue != null) {
+ if (this.streamTerminator != null && dataValue.includes(this.streamTerminator)) {
+ return;
+ }
+ const data = await this.parse(fromJson(dataValue));
+ yield { data, id: lastId, retry: lastRetry, event: undefined };
+ lastDispatchedId = lastId;
+ reconnectAttempts = 0;
+ dataValue = undefined;
+ }
+ continue;
+ }
+
+ if (line.startsWith(ID_PREFIX)) {
+ const idValue = line.slice(ID_PREFIX.length).trim();
+ if (!idValue.includes("\0")) {
+ lastId = idValue;
+ }
+ continue;
+ }
+ if (line.startsWith(RETRY_PREFIX)) {
+ const retryValue = line.slice(RETRY_PREFIX.length).trim();
+ const parsed = parseInt(retryValue, 10);
+ if (!Number.isNaN(parsed) && String(parsed) === retryValue) {
+ lastRetry = parsed;
+ }
+ continue;
+ }
+
+ if (this.prefix != null) {
+ const prefixIndex = line.indexOf(this.prefix);
+ if (prefixIndex === -1) {
+ continue;
+ }
+ const val = line.slice(prefixIndex + this.prefix.length).trim();
+ dataValue = dataValue != null ? `${dataValue}\n${val}` : val;
+ } else {
+ if (this.streamTerminator != null && line.includes(this.streamTerminator)) {
+ return;
+ }
+ const data = await this.parse(fromJson(line));
+ yield { data, id: lastId, retry: lastRetry, event: undefined };
+ lastDispatchedId = lastId;
+ reconnectAttempts = 0;
+ }
+ }
+ }
+
+ if (this.prefix != null && dataValue != null) {
+ if (this.streamTerminator != null && dataValue.includes(this.streamTerminator)) {
+ return;
+ }
+ const data = await this.parse(fromJson(dataValue));
+ yield { data, id: lastId, retry: lastRetry, event: undefined };
+ lastDispatchedId = lastId;
+ reconnectAttempts = 0;
+ }
+
+ if (!this.shouldReconnect(lastDispatchedId, reconnectAttempts)) {
+ return;
+ }
+
+ reconnectAttempts++;
+ await this.delayReconnect(lastRetry);
+ if (this.controller.signal.aborted) {
+ return;
+ }
+ // Re-check after async delay; needed for TypeScript narrowing.
+ const reconnectFn = this.reconnect;
+ if (reconnectFn == null || lastDispatchedId == null) {
+ return;
+ }
+ try {
+ const reconnected = await reconnectFn(lastDispatchedId);
+ if (reconnected == null) {
+ currentStream = this.createEmptyStream();
+ continue;
+ }
+ currentStream = reconnected;
+ } catch {
+ // Failed reconnect (e.g. HTTP error); assign an empty stream
+ // so the next iteration is a safe no-op before shouldReconnect.
+ currentStream = this.createEmptyStream();
+ }
+ }
+ }
+
+ private async *iterSseEvents(): AsyncGenerator<ServerSentEvent<T>, void> {
+ let reconnectAttempts = 0;
+ let currentStream = this.stream;
+ let lastId: string | undefined;
+ // See iterDataMessages: reconnection uses the last *dispatched* id (per
+ // the EventSource spec), not the last *parsed* id, to avoid skipping an
+ // event that was never yielded when a drop lands mid-event.
+ let lastDispatchedId: string | undefined;
+ let lastRetry: number | undefined;
+
+ while (true) {
+ const stream = readableStreamAsyncIterable<any>(currentStream);
+ let buf = "";
+ let eventType: string | undefined;
+ let dataValue: string | undefined;
+
+ for await (const chunk of stream) {
+ buf += this.decodeChunk(chunk);
+
+ let terminatorIndex: number;
+ while ((terminatorIndex = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, terminatorIndex).replace(/\r$/, "");
+ buf = buf.slice(terminatorIndex + 1);
+
+ if (!line.trim()) {
+ if (dataValue != null) {
+ const data = await this.dispatchSseEvent(dataValue, eventType);
+ if (data == null) {
+ return;
+ }
+ yield { data, id: lastId, retry: lastRetry, event: eventType };
+ lastDispatchedId = lastId;
+ reconnectAttempts = 0;
+ }
+ eventType = undefined;
+ dataValue = undefined;
+ continue;
+ }
+
+ if (line.startsWith(EVENT_PREFIX)) {
+ eventType = line.slice(EVENT_PREFIX.length).trim();
+ } else if (line.startsWith(DATA_PREFIX)) {
+ const val = line.slice(DATA_PREFIX.length).trim();
+ dataValue = dataValue != null ? `${dataValue}\n${val}` : val;
+ } else if (line.startsWith(ID_PREFIX)) {
+ const idValue = line.slice(ID_PREFIX.length).trim();
+ if (!idValue.includes("\0")) {
+ lastId = idValue;
+ }
+ } else if (line.startsWith(RETRY_PREFIX)) {
+ const retryValue = line.slice(RETRY_PREFIX.length).trim();
+ const parsed = parseInt(retryValue, 10);
+ if (!Number.isNaN(parsed) && String(parsed) === retryValue) {
+ lastRetry = parsed;
+ }
+ }
+ }
+ }
+
+ if (dataValue != null) {
+ const data = await this.dispatchSseEvent(dataValue, eventType);
+ if (data != null) {
+ yield { data, id: lastId, retry: lastRetry, event: eventType };
+ lastDispatchedId = lastId;
+ reconnectAttempts = 0;
+ }
+ }
+
+ if (!this.shouldReconnect(lastDispatchedId, reconnectAttempts)) {
+ return;
+ }
+
+ reconnectAttempts++;
+ await this.delayReconnect(lastRetry);
+ if (this.controller.signal.aborted) {
+ return;
+ }
+ // Re-check after async delay; needed for TypeScript narrowing.
+ const reconnectFn = this.reconnect;
+ if (reconnectFn == null || lastDispatchedId == null) {
+ return;
+ }
+ try {
+ const reconnected = await reconnectFn(lastDispatchedId);
+ if (reconnected == null) {
+ currentStream = this.createEmptyStream();
+ continue;
+ }
+ currentStream = reconnected;
+ } catch {
+ // Failed reconnect (e.g. HTTP error); assign an empty stream
+ // so the next iteration is a safe no-op before shouldReconnect.
+ currentStream = this.createEmptyStream();
+ }
+ }
+ }
+
+ /**
+ * Parses and returns a single SSE event, or returns null if the event is a stream terminator.
+ */
+ private async dispatchSseEvent(dataValue: string, eventType: string | undefined): Promise<T | null> {
+ if (this.streamTerminator != null && dataValue.includes(this.streamTerminator)) {
+ return null;
+ }
+ return this.parse(this.injectDiscriminator(fromJson(dataValue), eventType));
+ }
+
+ /**
+ * Determines whether a reconnection attempt should be made.
+ */
+ private shouldReconnect(lastId: string | undefined, reconnectAttempts: number): boolean {
+ if (!this.resumable) {
+ return false;
+ }
+ if (this.streamTerminator == null) {
+ // Without a terminator the client cannot distinguish a completed
+ // stream from a dropped connection, so reconnection is disabled.
+ return false;
+ }
+ // NOTE: When a terminator IS configured but the server never sends it
+ // (e.g. it drops the connection after emitting events every time),
+ // maxReconnectionAttempts is a per-consecutive-failure cap — each
+ // yielded event resets the counter. This matches EventSource semantics
+ // but means such a server can cause unbounded reconnections. Callers
+ // concerned about this should impose a wall-clock budget externally.
+ if (!this.reconnectionEnabled) {
+ return false;
+ }
+ if (this.reconnect == null) {
+ return false;
+ }
+ if (lastId == null || lastId === "") {
+ return false;
+ }
+ if (reconnectAttempts >= this.maxReconnectionAttempts) {
+ return false;
+ }
+ if (this.controller.signal.aborted) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Delays before reconnecting, using a server-sent retry directive if provided
+ * (clamped to MAX_RECONNECT_DELAY_MS), otherwise falling back to
+ * DEFAULT_RECONNECT_DELAY_MS. The delay is abortable: if the stream's abort
+ * signal fires during the wait, the promise resolves immediately.
+ */
+ private async delayReconnect(lastRetry: number | undefined): Promise<void> {
+ const base = lastRetry != null && lastRetry > 0 ? lastRetry : DEFAULT_RECONNECT_DELAY_MS;
+ const delay = Math.min(base, MAX_RECONNECT_DELAY_MS);
+ const signal = this.controller.signal;
+ if (signal.aborted) {
+ return;
+ }
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve();
+ }, delay);
+ const onAbort = (): void => {
+ clearTimeout(timer);
+ resolve();
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+ }
+
+ private createEmptyStream(): ReadableStream {
+ return new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ });
+ }
+
+ private removeAbortListener(): void {
+ if (this.externalSignal != null && this.onExternalAbort != null) {
+ this.externalSignal.removeEventListener("abort", this.onExternalAbort);
+ this.onExternalAbort = undefined;
+ }
+ }
+
+ public withMetadata(): AsyncIterable<ServerSentEvent<T>> {
+ const self = this;
+ return {
+ async *[Symbol.asyncIterator]() {
+ try {
+ yield* self.iterMessages();
+ } finally {
+ self.removeAbortListener();
+ }
+ },
+ };
+ }
+
+ private injectDiscriminator(parsed: unknown, eventType: string | undefined): unknown {
+ if (this.eventDiscriminator == null || eventType == null) {
+ return parsed;
+ }
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return parsed;
+ }
+ const obj = parsed as Record<string, unknown>;
+ if (this.eventDiscriminator in obj) {
+ return parsed;
+ }
+ return { [this.eventDiscriminator]: eventType, ...obj };
+ }
+
+ async *[Symbol.asyncIterator](): AsyncIterator<T, void, unknown> {
+ try {
+ for await (const event of this.iterMessages()) {
+ yield event.data;
+ }
+ } finally {
+ this.removeAbortListener();
+ }
+ }
+
+ private decodeChunk(chunk: any): string {
+ let decoded = "";
+ // If TextDecoder is available, use the streaming decoder instance
+ if (this.decoder != null) {
+ decoded += this.decoder.decode(chunk, { stream: true });
+ }
+ // Buffer is present in Node.js environment
+ else if (RUNTIME.type === "node" && typeof chunk !== "undefined") {
+ decoded += Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ }
+ return decoded;
+ }
+}
+
+/**
+ * Browser polyfill for ReadableStream
+ */
+// biome-ignore lint/suspicious/noExplicitAny: allow explicit any
+export function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
+ if (stream[Symbol.asyncIterator]) {
+ return stream;
+ }
+
+ const reader = stream.getReader();
+ return {
+ async next() {
+ try {
+ const result = await reader.read();
+ if (result?.done) {
+ reader.releaseLock();
+ } // release lock when stream becomes closed
+ return result;
+ } catch (e) {
+ reader.releaseLock(); // release lock when stream becomes errored
+ throw e;
+ }
+ },
+ async return() {
+ const cancelPromise = reader.cancel();
+ reader.releaseLock();
+ await cancelPromise;
+ return { done: true, value: undefined };
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ },
+ };
+}
diff --git a/packages/sdk/src/core/stream/index.ts b/packages/sdk/src/core/stream/index.ts
new file mode 100644
index 000000000..76f074e78
--- /dev/null
+++ b/packages/sdk/src/core/stream/index.ts
@@ -0,0 +1,2 @@
+export type { ServerSentEvent } from "./Stream.js";
+export { Stream } from "./Stream.js";
diff --git a/packages/sdk/src/core/url/QueryStringBuilder.ts b/packages/sdk/src/core/url/QueryStringBuilder.ts
new file mode 100644
index 000000000..b045221c3
--- /dev/null
+++ b/packages/sdk/src/core/url/QueryStringBuilder.ts
@@ -0,0 +1,87 @@
+import { toQueryString } from "./qs.js";
+
+/**
+ * Creates a fluent builder for constructing URL query strings.
+ *
+ * Each `.add()` call serializes its value immediately (like C#'s builder),
+ * so no format tracking is needed — the style is applied at add-time.
+ *
+ * Usage (generated code):
+ *
+ * const qs = core.url.queryBuilder()
+ * .add("limit", limit)
+ * .add("tags", tags, { style: "comma" }) // explode: false
+ * .mergeAdditional(requestOptions?.queryParams)
+ * .build();
+ */
+export function queryBuilder(): QueryStringBuilder {
+ return new QueryStringBuilder();
+}
+
+class QueryStringBuilder {
+ private parts: Map<string, string> = new Map();
+
+ /**
+ * Adds a query parameter, serializing it immediately.
+ *
+ * By default arrays use "repeat" format (`key=a&key=b`).
+ * Pass `{ style: "comma" }` for OpenAPI `explode: false` parameters
+ * to get comma-separated values (`key=a,b,c`).
+ *
+ * Null / undefined values are silently skipped.
+ */
+ add(key: string, value: unknown, options?: { style?: "comma" }): this {
+ if (value === undefined || value === null) {
+ return this;
+ }
+ const serialized = toQueryString(
+ { [key]: value },
+ { arrayFormat: options?.style === "comma" ? "comma" : "repeat" },
+ );
+ if (serialized.length > 0) {
+ this.parts.set(key, serialized);
+ }
+ return this;
+ }
+
+ /**
+ * Adds multiple query parameters at once from a record.
+ * All parameters use the default "repeat" array format.
+ * Null / undefined values are silently skipped.
+ */
+ addMany(params: Record<string, unknown>): this {
+ if (params != null) {
+ for (const [key, value] of Object.entries(params)) {
+ this.add(key, value);
+ }
+ }
+ return this;
+ }
+
+ /**
+ * Merges additional query parameters supplied at call-time via
+ * `requestOptions.queryParams`. Overrides existing keys (last-write-wins).
+ */
+ mergeAdditional(additionalParams?: Record<string, unknown>): this {
+ if (additionalParams != null) {
+ for (const [key, value] of Object.entries(additionalParams)) {
+ if (value === undefined || value === null) {
+ continue;
+ }
+ const serialized = toQueryString({ [key]: value }, { arrayFormat: "repeat" });
+ if (serialized.length > 0) {
+ this.parts.set(key, serialized);
+ }
+ }
+ }
+ return this;
+ }
+
+ /**
+ * Returns the assembled query string (without the leading `?`).
+ * Returns an empty string when no parameters were added.
+ */
+ build(): string {
+ return [...this.parts.values()].join("&");
+ }
+}
diff --git a/packages/sdk/src/core/url/encodePathParam.ts b/packages/sdk/src/core/url/encodePathParam.ts
new file mode 100644
index 000000000..19b901244
--- /dev/null
+++ b/packages/sdk/src/core/url/encodePathParam.ts
@@ -0,0 +1,18 @@
+export function encodePathParam(param: unknown): string {
+ if (param === null) {
+ return "null";
+ }
+ const typeofParam = typeof param;
+ switch (typeofParam) {
+ case "undefined":
+ return "undefined";
+ case "string":
+ case "number":
+ case "boolean":
+ break;
+ default:
+ param = String(param);
+ break;
+ }
+ return encodeURIComponent(param as string | number | boolean);
+}
diff --git a/packages/sdk/src/core/url/index.ts b/packages/sdk/src/core/url/index.ts
new file mode 100644
index 000000000..ca9d4fbd1
--- /dev/null
+++ b/packages/sdk/src/core/url/index.ts
@@ -0,0 +1,4 @@
+export { encodePathParam } from "./encodePathParam.js";
+export { join } from "./join.js";
+export { queryBuilder } from "./QueryStringBuilder.js";
+export { toQueryString } from "./qs.js";
diff --git a/packages/sdk/src/core/url/join.ts b/packages/sdk/src/core/url/join.ts
new file mode 100644
index 000000000..7ca7daef0
--- /dev/null
+++ b/packages/sdk/src/core/url/join.ts
@@ -0,0 +1,79 @@
+export function join(base: string, ...segments: string[]): string {
+ if (!base) {
+ return "";
+ }
+
+ if (segments.length === 0) {
+ return base;
+ }
+
+ if (base.includes("://")) {
+ let url: URL;
+ try {
+ url = new URL(base);
+ } catch {
+ return joinPath(base, ...segments);
+ }
+
+ const lastSegment = segments[segments.length - 1];
+ const shouldPreserveTrailingSlash = lastSegment?.endsWith("/");
+
+ for (const segment of segments) {
+ const cleanSegment = trimSlashes(segment);
+ if (cleanSegment) {
+ url.pathname = joinPathSegments(url.pathname, cleanSegment);
+ }
+ }
+
+ if (shouldPreserveTrailingSlash && !url.pathname.endsWith("/")) {
+ url.pathname += "/";
+ }
+
+ return url.toString();
+ }
+
+ return joinPath(base, ...segments);
+}
+
+function joinPath(base: string, ...segments: string[]): string {
+ if (segments.length === 0) {
+ return base;
+ }
+
+ let result = base;
+
+ const lastSegment = segments[segments.length - 1];
+ const shouldPreserveTrailingSlash = lastSegment?.endsWith("/");
+
+ for (const segment of segments) {
+ const cleanSegment = trimSlashes(segment);
+ if (cleanSegment) {
+ result = joinPathSegments(result, cleanSegment);
+ }
+ }
+
+ if (shouldPreserveTrailingSlash && !result.endsWith("/")) {
+ result += "/";
+ }
+
+ return result;
+}
+
+function joinPathSegments(left: string, right: string): string {
+ if (left.endsWith("/")) {
+ return left + right;
+ }
+ return `${left}/${right}`;
+}
+
+function trimSlashes(str: string): string {
+ if (!str) return str;
+
+ let start = 0;
+ let end = str.length;
+
+ if (str.startsWith("/")) start = 1;
+ if (str.endsWith("/")) end = str.length - 1;
+
+ return start === 0 && end === str.length ? str : str.slice(start, end);
+}
diff --git a/packages/sdk/src/core/url/qs.ts b/packages/sdk/src/core/url/qs.ts
new file mode 100644
index 000000000..aebb95a38
--- /dev/null
+++ b/packages/sdk/src/core/url/qs.ts
@@ -0,0 +1,87 @@
+type ArrayFormat = "indices" | "repeat" | "comma";
+
+interface QueryStringOptions {
+ arrayFormat?: ArrayFormat;
+ encode?: boolean;
+}
+
+const defaultQsOptions: Required<QueryStringOptions> = {
+ arrayFormat: "indices",
+ encode: true,
+} as const;
+
+function encodeValue(value: unknown, shouldEncode: boolean): string {
+ if (value === undefined) {
+ return "";
+ }
+ if (value === null) {
+ return "";
+ }
+ const stringValue = String(value);
+ return shouldEncode ? encodeURIComponent(stringValue) : stringValue;
+}
+
+function stringifyObject(obj: Record<string, unknown>, prefix = "", options: Required<QueryStringOptions>): string[] {
+ const parts: string[] = [];
+
+ for (const [key, value] of Object.entries(obj)) {
+ const fullKey = prefix ? `${prefix}[${key}]` : key;
+
+ if (value == null) {
+ continue;
+ }
+
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ continue;
+ }
+ const effectiveFormat = options.arrayFormat;
+ if (effectiveFormat === "comma") {
+ const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey;
+ const encodedValues = value
+ .filter((item) => item !== undefined && item !== null)
+ .map((item) => encodeValue(item, options.encode));
+ if (encodedValues.length > 0) {
+ parts.push(`${encodedKey}=${encodedValues.join(",")}`);
+ }
+ } else {
+ for (let i = 0; i < value.length; i++) {
+ const item = value[i];
+ if (item == null) {
+ continue;
+ }
+ if (typeof item === "object" && !Array.isArray(item) && item !== null) {
+ const arrayKey = effectiveFormat === "indices" ? `${fullKey}[${i}]` : fullKey;
+ parts.push(...stringifyObject(item as Record<string, unknown>, arrayKey, options));
+ } else {
+ const arrayKey = effectiveFormat === "indices" ? `${fullKey}[${i}]` : fullKey;
+ const encodedKey = options.encode ? encodeURIComponent(arrayKey) : arrayKey;
+ parts.push(`${encodedKey}=${encodeValue(item, options.encode)}`);
+ }
+ }
+ }
+ } else if (typeof value === "object" && value !== null) {
+ if (Object.keys(value as Record<string, unknown>).length === 0) {
+ continue;
+ }
+ parts.push(...stringifyObject(value as Record<string, unknown>, fullKey, options));
+ } else {
+ const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey;
+ parts.push(`${encodedKey}=${encodeValue(value, options.encode)}`);
+ }
+ }
+
+ return parts;
+}
+
+export function toQueryString(obj: unknown, options?: QueryStringOptions): string {
+ if (obj == null || typeof obj !== "object") {
+ return "";
+ }
+
+ const parts = stringifyObject(obj as Record<string, unknown>, "", {
+ ...defaultQsOptions,
+ ...options,
+ });
+ return parts.join("&");
+}
diff --git a/packages/sdk/src/core/utils/index.ts b/packages/sdk/src/core/utils/index.ts
new file mode 100644
index 000000000..11ff8f251
--- /dev/null
+++ b/packages/sdk/src/core/utils/index.ts
@@ -0,0 +1 @@
+export { setObjectProperty } from "./setObjectProperty.js";
diff --git a/packages/sdk/src/core/utils/setObjectProperty.ts b/packages/sdk/src/core/utils/setObjectProperty.ts
new file mode 100644
index 000000000..5528af248
--- /dev/null
+++ b/packages/sdk/src/core/utils/setObjectProperty.ts
@@ -0,0 +1,43 @@
+/**
+ * Sets the value at path of object. If a portion of path doesn’t exist it’s created. This is
+ * inspired by Lodash's set function, but is simplified to accommodate our use case.
+ * For more details, see https://lodash.com/docs/4.17.15#set.
+ *
+ * @param object The object to modify.
+ * @param path The path of the property to set.
+ * @param value The value to set.
+ * @return Returns object.
+ */
+export function setObjectProperty<T extends object>(object: T, path: string, value: any): T {
+ if (object == null) {
+ return object;
+ }
+
+ const keys: string[] = path.split(".");
+ if (keys.length === 0) {
+ // Invalid path; do nothing.
+ return object;
+ }
+
+ let current: Record<string, any> = object;
+ for (let i = 0; i < keys.length - 1; i++) {
+ const key = keys[i];
+ if (key == null) {
+ // Unreachable.
+ continue;
+ }
+ if (!current[key] || typeof current[key] !== "object") {
+ current[key] = {};
+ }
+ current = current[key] as Record<string, any>;
+ }
+
+ const lastKey = keys[keys.length - 1];
+ if (lastKey == null) {
+ // Unreachable.
+ return object;
+ }
+
+ current[lastKey] = value;
+ return object;
+}
diff --git a/packages/sdk/src/errors/TrueHarnessError.ts b/packages/sdk/src/errors/TrueHarnessError.ts
new file mode 100644
index 000000000..2fb22c414
--- /dev/null
+++ b/packages/sdk/src/errors/TrueHarnessError.ts
@@ -0,0 +1,68 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../core/index.js";
+import { toJson } from "../core/json.js";
+
+export class TrueHarnessError extends Error {
+ public readonly statusCode?: number;
+ public readonly body?: unknown;
+ public readonly rawResponse?: core.RawResponse;
+ public readonly cause?: unknown;
+
+ constructor({
+ message,
+ statusCode,
+ body,
+ rawResponse,
+ cause,
+ }: {
+ message?: string;
+ statusCode?: number;
+ body?: unknown;
+ rawResponse?: core.RawResponse;
+ cause?: unknown;
+ }) {
+ super(buildMessage({ message, statusCode, body }));
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "TrueHarnessError";
+ this.statusCode = statusCode;
+ this.body = body;
+ this.rawResponse = rawResponse;
+ if (cause != null) {
+ this.cause = cause;
+ }
+ }
+
+ public get requestId(): string | undefined {
+ return this.rawResponse?.headers?.get("x-request-id") ?? undefined;
+ }
+}
+
+function buildMessage({
+ message,
+ statusCode,
+ body,
+}: {
+ message: string | undefined;
+ statusCode: number | undefined;
+ body: unknown | undefined;
+}): string {
+ const lines: string[] = [];
+ if (message != null) {
+ lines.push(message);
+ }
+
+ if (statusCode != null) {
+ lines.push(`Status code: ${statusCode.toString()}`);
+ }
+
+ if (body != null) {
+ lines.push(`Body: ${toJson(body, undefined, 2)}`);
+ }
+
+ return lines.join("\n");
+}
diff --git a/packages/sdk/src/errors/TrueHarnessTimeoutError.ts b/packages/sdk/src/errors/TrueHarnessTimeoutError.ts
new file mode 100644
index 000000000..03a2b79dc
--- /dev/null
+++ b/packages/sdk/src/errors/TrueHarnessTimeoutError.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import * as errors from "./index.js";
+
+export class TrueHarnessTimeoutError extends errors.TrueHarnessError {
+ constructor(message: string, opts?: { cause?: unknown }) {
+ super({
+ message: message,
+ cause: opts?.cause,
+ });
+ Object.setPrototypeOf(this, new.target.prototype);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+ this.name = "TrueHarnessTimeoutError";
+ }
+}
diff --git a/packages/sdk/src/errors/handleNonStatusCodeError.ts b/packages/sdk/src/errors/handleNonStatusCodeError.ts
new file mode 100644
index 000000000..b954e9002
--- /dev/null
+++ b/packages/sdk/src/errors/handleNonStatusCodeError.ts
@@ -0,0 +1,40 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as core from "../core/index.js";
+import * as errors from "./index.js";
+
+export function handleNonStatusCodeError(
+ error: core.Fetcher.Error,
+ rawResponse: core.RawResponse,
+ method: string,
+ path: string,
+): never {
+ switch (error.reason) {
+ case "non-json":
+ throw new errors.TrueHarnessError({
+ statusCode: error.statusCode,
+ body: error.rawBody,
+ rawResponse: rawResponse,
+ });
+ case "body-is-null":
+ throw new errors.TrueHarnessError({
+ statusCode: error.statusCode,
+ rawResponse: rawResponse,
+ });
+ case "timeout":
+ throw new errors.TrueHarnessTimeoutError(`Timeout exceeded when calling ${method} ${path}.`, {
+ cause: error.cause,
+ });
+ case "unknown":
+ throw new errors.TrueHarnessError({
+ message: error.errorMessage,
+ rawResponse: rawResponse,
+ cause: error.cause,
+ });
+ default:
+ throw new errors.TrueHarnessError({
+ message: "Unknown error",
+ rawResponse: rawResponse,
+ });
+ }
+}
diff --git a/packages/sdk/src/errors/index.ts b/packages/sdk/src/errors/index.ts
new file mode 100644
index 000000000..8eac0abf1
--- /dev/null
+++ b/packages/sdk/src/errors/index.ts
@@ -0,0 +1,2 @@
+export { TrueHarnessError } from "./TrueHarnessError.js";
+export { TrueHarnessTimeoutError } from "./TrueHarnessTimeoutError.js";
diff --git a/packages/sdk/src/exports.ts b/packages/sdk/src/exports.ts
new file mode 100644
index 000000000..7b70ee14f
--- /dev/null
+++ b/packages/sdk/src/exports.ts
@@ -0,0 +1 @@
+export * from "./core/exports.js";
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
new file mode 100644
index 000000000..f814cc3a5
--- /dev/null
+++ b/packages/sdk/src/index.ts
@@ -0,0 +1,5 @@
+export * as TrueHarness from "./api/index.js";
+export type { BaseClientOptions, BaseRequestOptions } from "./BaseClient.js";
+export { TrueHarnessError, TrueHarnessTimeoutError } from "./errors/index.js";
+export * from "./exports.js";
+export * as serialization from "./serialization/index.js";
diff --git a/packages/sdk/src/serialization/index.ts b/packages/sdk/src/serialization/index.ts
new file mode 100644
index 000000000..ba75aa09d
--- /dev/null
+++ b/packages/sdk/src/serialization/index.ts
@@ -0,0 +1,2 @@
+export * from "./resources/index.js";
+export * from "./types/index.js";
diff --git a/packages/sdk/src/serialization/resources/index.ts b/packages/sdk/src/serialization/resources/index.ts
new file mode 100644
index 000000000..e34ab841f
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/index.ts
@@ -0,0 +1,2 @@
+export * from "./sessions/client/requests/index.js";
+export * as sessions from "./sessions/index.js";
diff --git a/packages/sdk/src/serialization/resources/sessions/client/index.ts b/packages/sdk/src/serialization/resources/sessions/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/CancelSessionRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/CancelSessionRequest.ts
new file mode 100644
index 000000000..2b6ed4fbf
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/CancelSessionRequest.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+
+export const CancelSessionRequest: core.serialization.Schema<
+ serializers.CancelSessionRequest.Raw,
+ TrueHarness.CancelSessionRequest
+> = core.serialization.object({});
+
+export declare namespace CancelSessionRequest {
+ export type Raw = {};
+}
diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts
new file mode 100644
index 000000000..51187b15e
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+import { AgentSpec } from "../../../../types/AgentSpec.js";
+
+export const CreateSessionRequest: core.serialization.Schema<
+ serializers.CreateSessionRequest.Raw,
+ TrueHarness.CreateSessionRequest
+> = core.serialization.object({
+ agentSpec: core.serialization.property("agent_spec", AgentSpec),
+});
+
+export declare namespace CreateSessionRequest {
+ export interface Raw {
+ agent_spec: AgentSpec.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/CreateTurnRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateTurnRequest.ts
new file mode 100644
index 000000000..76bac5804
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateTurnRequest.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+import { PreviousTurnIdInput } from "../../../../types/PreviousTurnIdInput.js";
+import { TurnInputItem } from "../../../../types/TurnInputItem.js";
+
+export const CreateTurnRequest: core.serialization.Schema<
+ serializers.CreateTurnRequest.Raw,
+ TrueHarness.CreateTurnRequest
+> = core.serialization.object({
+ input: core.serialization.list(TurnInputItem).optional(),
+ previousTurnId: core.serialization.property("previous_turn_id", PreviousTurnIdInput.optionalNullable()),
+});
+
+export declare namespace CreateTurnRequest {
+ export interface Raw {
+ input?: TurnInputItem.Raw[] | null;
+ previous_turn_id?: (PreviousTurnIdInput.Raw | null | undefined) | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts
new file mode 100644
index 000000000..69eb106b0
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+import { AgentSpec } from "../../../../types/AgentSpec.js";
+
+export const UpdateSessionRequest: core.serialization.Schema<
+ serializers.UpdateSessionRequest.Raw,
+ TrueHarness.UpdateSessionRequest
+> = core.serialization.object({
+ agentSpec: core.serialization.property("agent_spec", AgentSpec.optional()),
+});
+
+export declare namespace UpdateSessionRequest {
+ export interface Raw {
+ agent_spec?: AgentSpec.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/index.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/index.ts
new file mode 100644
index 000000000..7a69e2918
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/index.ts
@@ -0,0 +1,4 @@
+export { CancelSessionRequest } from "./CancelSessionRequest.js";
+export { CreateSessionRequest } from "./CreateSessionRequest.js";
+export { CreateTurnRequest } from "./CreateTurnRequest.js";
+export { UpdateSessionRequest } from "./UpdateSessionRequest.js";
diff --git a/packages/sdk/src/serialization/resources/sessions/index.ts b/packages/sdk/src/serialization/resources/sessions/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/sdk/src/serialization/resources/sessions/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/sdk/src/serialization/types/ActionRequiredEvent.ts b/packages/sdk/src/serialization/types/ActionRequiredEvent.ts
new file mode 100644
index 000000000..78866571f
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ActionRequiredEvent.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpAuthRequiredEvent } from "./McpAuthRequiredEvent.js";
+import { ToolApprovalRequiredEvent } from "./ToolApprovalRequiredEvent.js";
+import { ToolResponseRequiredEvent } from "./ToolResponseRequiredEvent.js";
+
+export const ActionRequiredEvent: core.serialization.Schema<
+ serializers.ActionRequiredEvent.Raw,
+ TrueHarness.ActionRequiredEvent
+> = core.serialization.undiscriminatedUnion([
+ McpAuthRequiredEvent,
+ ToolApprovalRequiredEvent,
+ ToolResponseRequiredEvent,
+]);
+
+export declare namespace ActionRequiredEvent {
+ export type Raw = McpAuthRequiredEvent.Raw | ToolApprovalRequiredEvent.Raw | ToolResponseRequiredEvent.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/AgentInfo.ts b/packages/sdk/src/serialization/types/AgentInfo.ts
new file mode 100644
index 000000000..242446082
--- /dev/null
+++ b/packages/sdk/src/serialization/types/AgentInfo.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const AgentInfo: core.serialization.ObjectSchema<serializers.AgentInfo.Raw, TrueHarness.AgentInfo> =
+ core.serialization.object({
+ input: core.serialization.string(),
+ model: core.serialization.string().optional(),
+ name: core.serialization.string(),
+ type: core.serialization.stringLiteral("dynamic"),
+ });
+
+export declare namespace AgentInfo {
+ export interface Raw {
+ input: string;
+ model?: string | null;
+ name: string;
+ type: "dynamic";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/AgentParent.ts b/packages/sdk/src/serialization/types/AgentParent.ts
new file mode 100644
index 000000000..5f30075c5
--- /dev/null
+++ b/packages/sdk/src/serialization/types/AgentParent.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const AgentParent: core.serialization.ObjectSchema<serializers.AgentParent.Raw, TrueHarness.AgentParent> =
+ core.serialization.object({
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCallId: core.serialization.property("tool_call_id", core.serialization.string()),
+ });
+
+export declare namespace AgentParent {
+ export interface Raw {
+ thread_id: string;
+ tool_call_id: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/AgentSpec.ts b/packages/sdk/src/serialization/types/AgentSpec.ts
new file mode 100644
index 000000000..5f14ff318
--- /dev/null
+++ b/packages/sdk/src/serialization/types/AgentSpec.ts
@@ -0,0 +1,36 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { AgentSpecUserMessage } from "./AgentSpecUserMessage.js";
+import { McpServer } from "./McpServer.js";
+import { Model } from "./Model.js";
+import { ResponseFormat } from "./ResponseFormat.js";
+import { RuntimeConfig } from "./RuntimeConfig.js";
+import { SkillMount } from "./SkillMount.js";
+
+export const AgentSpec: core.serialization.ObjectSchema<serializers.AgentSpec.Raw, TrueHarness.AgentSpec> =
+ core.serialization.object({
+ config: RuntimeConfig.optional(),
+ instructions: core.serialization.string().optional(),
+ mcpServers: core.serialization.property("mcp_servers", core.serialization.list(McpServer).optional()),
+ messages: core.serialization.list(AgentSpecUserMessage).optional(),
+ model: Model,
+ responseFormat: core.serialization.property("response_format", ResponseFormat.optional()),
+ skills: core.serialization.list(SkillMount).optional(),
+ variables: core.serialization.record(core.serialization.string(), core.serialization.string()).optional(),
+ });
+
+export declare namespace AgentSpec {
+ export interface Raw {
+ config?: RuntimeConfig.Raw | null;
+ instructions?: string | null;
+ mcp_servers?: McpServer.Raw[] | null;
+ messages?: AgentSpecUserMessage.Raw[] | null;
+ model: Model.Raw;
+ response_format?: ResponseFormat.Raw | null;
+ skills?: SkillMount.Raw[] | null;
+ variables?: Record<string, string> | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/AgentSpecUserMessage.ts b/packages/sdk/src/serialization/types/AgentSpecUserMessage.ts
new file mode 100644
index 000000000..45d72f7dd
--- /dev/null
+++ b/packages/sdk/src/serialization/types/AgentSpecUserMessage.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const AgentSpecUserMessage: core.serialization.ObjectSchema<
+ serializers.AgentSpecUserMessage.Raw,
+ TrueHarness.AgentSpecUserMessage
+> = core.serialization.object({
+ content: core.serialization.string(),
+ type: core.serialization.stringLiteral("user.message"),
+});
+
+export declare namespace AgentSpecUserMessage {
+ export interface Raw {
+ content: string;
+ type: "user.message";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ApprovalAllow.ts b/packages/sdk/src/serialization/types/ApprovalAllow.ts
new file mode 100644
index 000000000..476e26b7a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ApprovalAllow.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ApprovalAllow: core.serialization.ObjectSchema<serializers.ApprovalAllow.Raw, TrueHarness.ApprovalAllow> =
+ core.serialization.object({
+ status: core.serialization.stringLiteral("allow"),
+ });
+
+export declare namespace ApprovalAllow {
+ export interface Raw {
+ status: "allow";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ApprovalDecision.ts b/packages/sdk/src/serialization/types/ApprovalDecision.ts
new file mode 100644
index 000000000..9db0e319c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ApprovalDecision.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ApprovalAllow } from "./ApprovalAllow.js";
+import { ApprovalDeny } from "./ApprovalDeny.js";
+
+export const ApprovalDecision: core.serialization.Schema<
+ serializers.ApprovalDecision.Raw,
+ TrueHarness.ApprovalDecision
+> = core.serialization.undiscriminatedUnion([ApprovalAllow, ApprovalDeny]);
+
+export declare namespace ApprovalDecision {
+ export type Raw = ApprovalAllow.Raw | ApprovalDeny.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/ApprovalDeny.ts b/packages/sdk/src/serialization/types/ApprovalDeny.ts
new file mode 100644
index 000000000..27f0d2e78
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ApprovalDeny.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ApprovalDeny: core.serialization.ObjectSchema<serializers.ApprovalDeny.Raw, TrueHarness.ApprovalDeny> =
+ core.serialization.object({
+ reason: core.serialization.string().optional(),
+ status: core.serialization.stringLiteral("deny"),
+ });
+
+export declare namespace ApprovalDeny {
+ export interface Raw {
+ reason?: string | null;
+ status: "deny";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/AskUserQuestionsConfig.ts b/packages/sdk/src/serialization/types/AskUserQuestionsConfig.ts
new file mode 100644
index 000000000..8ad1c0faa
--- /dev/null
+++ b/packages/sdk/src/serialization/types/AskUserQuestionsConfig.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const AskUserQuestionsConfig: core.serialization.ObjectSchema<
+ serializers.AskUserQuestionsConfig.Raw,
+ TrueHarness.AskUserQuestionsConfig
+> = core.serialization.object({
+ enabled: core.serialization.boolean().optional(),
+});
+
+export declare namespace AskUserQuestionsConfig {
+ export interface Raw {
+ enabled?: boolean | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/BaseMcpAuthRequiredEvent.ts b/packages/sdk/src/serialization/types/BaseMcpAuthRequiredEvent.ts
new file mode 100644
index 000000000..6c6487e1d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/BaseMcpAuthRequiredEvent.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const BaseMcpAuthRequiredEvent: core.serialization.ObjectSchema<
+ serializers.BaseMcpAuthRequiredEvent.Raw,
+ TrueHarness.BaseMcpAuthRequiredEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ threadId: core.serialization.property("thread_id", core.serialization.string().nullable()),
+});
+
+export declare namespace BaseMcpAuthRequiredEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ thread_id?: string | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/BaseThreadDoneEvent.ts b/packages/sdk/src/serialization/types/BaseThreadDoneEvent.ts
new file mode 100644
index 000000000..36ff86e67
--- /dev/null
+++ b/packages/sdk/src/serialization/types/BaseThreadDoneEvent.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { AgentParent } from "./AgentParent.js";
+
+export const BaseThreadDoneEvent: core.serialization.ObjectSchema<
+ serializers.BaseThreadDoneEvent.Raw,
+ TrueHarness.BaseThreadDoneEvent
+> = core.serialization.object({
+ parent: AgentParent.optional(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ title: core.serialization.string(),
+});
+
+export declare namespace BaseThreadDoneEvent {
+ export interface Raw {
+ parent?: AgentParent.Raw | null;
+ thread_id: string;
+ title: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/CancelSessionResponse.ts b/packages/sdk/src/serialization/types/CancelSessionResponse.ts
new file mode 100644
index 000000000..630e3fda0
--- /dev/null
+++ b/packages/sdk/src/serialization/types/CancelSessionResponse.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const CancelSessionResponse: core.serialization.ObjectSchema<
+ serializers.CancelSessionResponse.Raw,
+ TrueHarness.CancelSessionResponse
+> = core.serialization.object({});
+
+export declare namespace CancelSessionResponse {
+ export type Raw = {};
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCall.ts b/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCall.ts
new file mode 100644
index 000000000..2f2db4dac
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCall.ts
@@ -0,0 +1,25 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ChatCompletionChunkDeltaToolCallFunction } from "./ChatCompletionChunkDeltaToolCallFunction.js";
+
+export const ChatCompletionChunkDeltaToolCall: core.serialization.ObjectSchema<
+ serializers.ChatCompletionChunkDeltaToolCall.Raw,
+ TrueHarness.ChatCompletionChunkDeltaToolCall
+> = core.serialization.object({
+ function: ChatCompletionChunkDeltaToolCallFunction.optional(),
+ id: core.serialization.string().optional(),
+ index: core.serialization.number(),
+ type: core.serialization.stringLiteral("function").optional(),
+});
+
+export declare namespace ChatCompletionChunkDeltaToolCall {
+ export interface Raw {
+ function?: ChatCompletionChunkDeltaToolCallFunction.Raw | null;
+ id?: string | null;
+ index: number;
+ type?: "function" | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCallFunction.ts b/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCallFunction.ts
new file mode 100644
index 000000000..f74e5c3fd
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionChunkDeltaToolCallFunction.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ChatCompletionChunkDeltaToolCallFunction: core.serialization.ObjectSchema<
+ serializers.ChatCompletionChunkDeltaToolCallFunction.Raw,
+ TrueHarness.ChatCompletionChunkDeltaToolCallFunction
+> = core.serialization.object({
+ arguments: core.serialization.string().optional(),
+ name: core.serialization.string().optional(),
+});
+
+export declare namespace ChatCompletionChunkDeltaToolCallFunction {
+ export interface Raw {
+ arguments?: string | null;
+ name?: string | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionContentPartRefusal.ts b/packages/sdk/src/serialization/types/ChatCompletionContentPartRefusal.ts
new file mode 100644
index 000000000..c2d1f4ab8
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionContentPartRefusal.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ChatCompletionContentPartRefusal: core.serialization.ObjectSchema<
+ serializers.ChatCompletionContentPartRefusal.Raw,
+ TrueHarness.ChatCompletionContentPartRefusal
+> = core.serialization.object({
+ refusal: core.serialization.string(),
+ type: core.serialization.stringLiteral("refusal"),
+});
+
+export declare namespace ChatCompletionContentPartRefusal {
+ export interface Raw {
+ refusal: string;
+ type: "refusal";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionContentPartText.ts b/packages/sdk/src/serialization/types/ChatCompletionContentPartText.ts
new file mode 100644
index 000000000..6fe0a6c38
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionContentPartText.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ChatCompletionContentPartText: core.serialization.ObjectSchema<
+ serializers.ChatCompletionContentPartText.Raw,
+ TrueHarness.ChatCompletionContentPartText
+> = core.serialization.object({
+ text: core.serialization.string(),
+ type: core.serialization.stringLiteral("text"),
+});
+
+export declare namespace ChatCompletionContentPartText {
+ export interface Raw {
+ text: string;
+ type: "text";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionMessageToolCall.ts b/packages/sdk/src/serialization/types/ChatCompletionMessageToolCall.ts
new file mode 100644
index 000000000..4173fd2ab
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionMessageToolCall.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ChatCompletionMessageToolCallFunction } from "./ChatCompletionMessageToolCallFunction.js";
+
+export const ChatCompletionMessageToolCall: core.serialization.ObjectSchema<
+ serializers.ChatCompletionMessageToolCall.Raw,
+ TrueHarness.ChatCompletionMessageToolCall
+> = core.serialization.object({
+ function: ChatCompletionMessageToolCallFunction,
+ id: core.serialization.string(),
+ type: core.serialization.stringLiteral("function"),
+});
+
+export declare namespace ChatCompletionMessageToolCall {
+ export interface Raw {
+ function: ChatCompletionMessageToolCallFunction.Raw;
+ id: string;
+ type: "function";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ChatCompletionMessageToolCallFunction.ts b/packages/sdk/src/serialization/types/ChatCompletionMessageToolCallFunction.ts
new file mode 100644
index 000000000..232b0ec00
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ChatCompletionMessageToolCallFunction.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ChatCompletionMessageToolCallFunction: core.serialization.ObjectSchema<
+ serializers.ChatCompletionMessageToolCallFunction.Raw,
+ TrueHarness.ChatCompletionMessageToolCallFunction
+> = core.serialization.object({
+ arguments: core.serialization.string(),
+ name: core.serialization.string(),
+});
+
+export declare namespace ChatCompletionMessageToolCallFunction {
+ export interface Raw {
+ arguments: string;
+ name: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ContextManagementConfig.ts b/packages/sdk/src/serialization/types/ContextManagementConfig.ts
new file mode 100644
index 000000000..83d361380
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ContextManagementConfig.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ContextManagementConfigCompaction } from "./ContextManagementConfigCompaction.js";
+import { LargeToolResponseConfig } from "./LargeToolResponseConfig.js";
+
+export const ContextManagementConfig: core.serialization.ObjectSchema<
+ serializers.ContextManagementConfig.Raw,
+ TrueHarness.ContextManagementConfig
+> = core.serialization.object({
+ compaction: ContextManagementConfigCompaction.optional(),
+ largeToolResponse: core.serialization.property("large_tool_response", LargeToolResponseConfig.optional()),
+});
+
+export declare namespace ContextManagementConfig {
+ export interface Raw {
+ compaction?: ContextManagementConfigCompaction.Raw | null;
+ large_tool_response?: LargeToolResponseConfig.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ContextManagementConfigCompaction.ts b/packages/sdk/src/serialization/types/ContextManagementConfigCompaction.ts
new file mode 100644
index 000000000..0c1b1f0ff
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ContextManagementConfigCompaction.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ContextManagementConfigCompaction: core.serialization.ObjectSchema<
+ serializers.ContextManagementConfigCompaction.Raw,
+ TrueHarness.ContextManagementConfigCompaction
+> = core.serialization.object({
+ compactionThresholdTokens: core.serialization.property(
+ "compaction_threshold_tokens",
+ core.serialization.number().optional(),
+ ),
+ enabled: core.serialization.boolean().optional(),
+});
+
+export declare namespace ContextManagementConfigCompaction {
+ export interface Raw {
+ compaction_threshold_tokens?: number | null;
+ enabled?: boolean | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/DynamicSubAgentsConfig.ts b/packages/sdk/src/serialization/types/DynamicSubAgentsConfig.ts
new file mode 100644
index 000000000..f9d676df1
--- /dev/null
+++ b/packages/sdk/src/serialization/types/DynamicSubAgentsConfig.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const DynamicSubAgentsConfig: core.serialization.ObjectSchema<
+ serializers.DynamicSubAgentsConfig.Raw,
+ TrueHarness.DynamicSubAgentsConfig
+> = core.serialization.object({
+ enabled: core.serialization.boolean().optional(),
+});
+
+export declare namespace DynamicSubAgentsConfig {
+ export interface Raw {
+ enabled?: boolean | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ExtendedChunkDeltaToolCall.ts b/packages/sdk/src/serialization/types/ExtendedChunkDeltaToolCall.ts
new file mode 100644
index 000000000..5ebb1d53f
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ExtendedChunkDeltaToolCall.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ChatCompletionChunkDeltaToolCall } from "./ChatCompletionChunkDeltaToolCall.js";
+import { ToolInfo } from "./ToolInfo.js";
+
+export const ExtendedChunkDeltaToolCall: core.serialization.ObjectSchema<
+ serializers.ExtendedChunkDeltaToolCall.Raw,
+ TrueHarness.ExtendedChunkDeltaToolCall
+> = core.serialization
+ .object({
+ providerSpecificFields: core.serialization.property(
+ "provider_specific_fields",
+ core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional(),
+ ),
+ toolInfo: core.serialization.property("tool_info", ToolInfo.optional()),
+ })
+ .extend(ChatCompletionChunkDeltaToolCall);
+
+export declare namespace ExtendedChunkDeltaToolCall {
+ export interface Raw extends ChatCompletionChunkDeltaToolCall.Raw {
+ provider_specific_fields?: Record<string, unknown> | null;
+ tool_info?: ToolInfo.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/FileContent.ts b/packages/sdk/src/serialization/types/FileContent.ts
new file mode 100644
index 000000000..92b2c3b07
--- /dev/null
+++ b/packages/sdk/src/serialization/types/FileContent.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const FileContent: core.serialization.ObjectSchema<serializers.FileContent.Raw, TrueHarness.FileContent> =
+ core.serialization.object({
+ data: core.serialization.string(),
+ name: core.serialization.string(),
+ type: core.serialization.stringLiteral("file"),
+ });
+
+export declare namespace FileContent {
+ export interface Raw {
+ data: string;
+ name: string;
+ type: "file";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/FinishReason.ts b/packages/sdk/src/serialization/types/FinishReason.ts
new file mode 100644
index 000000000..0c8ffb41d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/FinishReason.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const FinishReason: core.serialization.Schema<serializers.FinishReason.Raw, TrueHarness.FinishReason> =
+ core.serialization.enum_(["stop", "length", "tool_calls", "content_filter", "function_call"]);
+
+export declare namespace FinishReason {
+ export type Raw = "stop" | "length" | "tool_calls" | "content_filter" | "function_call";
+}
diff --git a/packages/sdk/src/serialization/types/GenerativeUiConfig.ts b/packages/sdk/src/serialization/types/GenerativeUiConfig.ts
new file mode 100644
index 000000000..b84d1b65c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GenerativeUiConfig.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const GenerativeUiConfig: core.serialization.ObjectSchema<
+ serializers.GenerativeUiConfig.Raw,
+ TrueHarness.GenerativeUiConfig
+> = core.serialization.object({
+ enabled: core.serialization.boolean().optional(),
+});
+
+export declare namespace GenerativeUiConfig {
+ export interface Raw {
+ enabled?: boolean | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/GetCapabilitiesResponse.ts b/packages/sdk/src/serialization/types/GetCapabilitiesResponse.ts
new file mode 100644
index 000000000..9d684a589
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GetCapabilitiesResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { GetCapabilitiesResponseData } from "./GetCapabilitiesResponseData.js";
+
+export const GetCapabilitiesResponse: core.serialization.ObjectSchema<
+ serializers.GetCapabilitiesResponse.Raw,
+ TrueHarness.GetCapabilitiesResponse
+> = core.serialization.object({
+ data: GetCapabilitiesResponseData,
+});
+
+export declare namespace GetCapabilitiesResponse {
+ export interface Raw {
+ data: GetCapabilitiesResponseData.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/GetCapabilitiesResponseData.ts b/packages/sdk/src/serialization/types/GetCapabilitiesResponseData.ts
new file mode 100644
index 000000000..b25c64271
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GetCapabilitiesResponseData.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { GetCapabilitiesResponseDataSandbox } from "./GetCapabilitiesResponseDataSandbox.js";
+
+export const GetCapabilitiesResponseData: core.serialization.ObjectSchema<
+ serializers.GetCapabilitiesResponseData.Raw,
+ TrueHarness.GetCapabilitiesResponseData
+> = core.serialization.object({
+ sandbox: GetCapabilitiesResponseDataSandbox,
+});
+
+export declare namespace GetCapabilitiesResponseData {
+ export interface Raw {
+ sandbox: GetCapabilitiesResponseDataSandbox.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/GetCapabilitiesResponseDataSandbox.ts b/packages/sdk/src/serialization/types/GetCapabilitiesResponseDataSandbox.ts
new file mode 100644
index 000000000..58a3f7da9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GetCapabilitiesResponseDataSandbox.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const GetCapabilitiesResponseDataSandbox: core.serialization.ObjectSchema<
+ serializers.GetCapabilitiesResponseDataSandbox.Raw,
+ TrueHarness.GetCapabilitiesResponseDataSandbox
+> = core.serialization.object({
+ enabled: core.serialization.boolean(),
+});
+
+export declare namespace GetCapabilitiesResponseDataSandbox {
+ export interface Raw {
+ enabled: boolean;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/GetSessionResponse.ts b/packages/sdk/src/serialization/types/GetSessionResponse.ts
new file mode 100644
index 000000000..bd109a003
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GetSessionResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { Session } from "./Session.js";
+
+export const GetSessionResponse: core.serialization.ObjectSchema<
+ serializers.GetSessionResponse.Raw,
+ TrueHarness.GetSessionResponse
+> = core.serialization.object({
+ data: Session,
+});
+
+export declare namespace GetSessionResponse {
+ export interface Raw {
+ data: Session.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/GetTurnResponse.ts b/packages/sdk/src/serialization/types/GetTurnResponse.ts
new file mode 100644
index 000000000..68dc1fbb3
--- /dev/null
+++ b/packages/sdk/src/serialization/types/GetTurnResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { Turn } from "./Turn.js";
+
+export const GetTurnResponse: core.serialization.ObjectSchema<
+ serializers.GetTurnResponse.Raw,
+ TrueHarness.GetTurnResponse
+> = core.serialization.object({
+ data: Turn,
+});
+
+export declare namespace GetTurnResponse {
+ export interface Raw {
+ data: Turn.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/LargeToolResponseConfig.ts b/packages/sdk/src/serialization/types/LargeToolResponseConfig.ts
new file mode 100644
index 000000000..5f6abee75
--- /dev/null
+++ b/packages/sdk/src/serialization/types/LargeToolResponseConfig.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const LargeToolResponseConfig: core.serialization.ObjectSchema<
+ serializers.LargeToolResponseConfig.Raw,
+ TrueHarness.LargeToolResponseConfig
+> = core.serialization.object({
+ enabled: core.serialization.boolean().optional(),
+});
+
+export declare namespace LargeToolResponseConfig {
+ export interface Raw {
+ enabled?: boolean | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListMcpServersResponse.ts b/packages/sdk/src/serialization/types/ListMcpServersResponse.ts
new file mode 100644
index 000000000..d14522406
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListMcpServersResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpServerEntry } from "./McpServerEntry.js";
+
+export const ListMcpServersResponse: core.serialization.ObjectSchema<
+ serializers.ListMcpServersResponse.Raw,
+ TrueHarness.ListMcpServersResponse
+> = core.serialization.object({
+ data: core.serialization.list(McpServerEntry),
+});
+
+export declare namespace ListMcpServersResponse {
+ export interface Raw {
+ data: McpServerEntry.Raw[];
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListMcpToolsResponse.ts b/packages/sdk/src/serialization/types/ListMcpToolsResponse.ts
new file mode 100644
index 000000000..30c624336
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListMcpToolsResponse.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ListMcpToolsResponse: core.serialization.ObjectSchema<
+ serializers.ListMcpToolsResponse.Raw,
+ TrueHarness.ListMcpToolsResponse
+> = core.serialization.object({
+ data: core.serialization.list(core.serialization.record(core.serialization.string(), core.serialization.unknown())),
+});
+
+export declare namespace ListMcpToolsResponse {
+ export interface Raw {
+ data: Record<string, unknown>[];
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListModelsResponse.ts b/packages/sdk/src/serialization/types/ListModelsResponse.ts
new file mode 100644
index 000000000..6c9348a74
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListModelsResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelEntry } from "./ModelEntry.js";
+
+export const ListModelsResponse: core.serialization.ObjectSchema<
+ serializers.ListModelsResponse.Raw,
+ TrueHarness.ListModelsResponse
+> = core.serialization.object({
+ data: core.serialization.list(ModelEntry),
+});
+
+export declare namespace ListModelsResponse {
+ export interface Raw {
+ data: ModelEntry.Raw[];
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListSessionEventsResponse.ts b/packages/sdk/src/serialization/types/ListSessionEventsResponse.ts
new file mode 100644
index 000000000..2634f8ec8
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListSessionEventsResponse.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SessionEventItem } from "./SessionEventItem.js";
+import { TokenPagination } from "./TokenPagination.js";
+
+export const ListSessionEventsResponse: core.serialization.ObjectSchema<
+ serializers.ListSessionEventsResponse.Raw,
+ TrueHarness.ListSessionEventsResponse
+> = core.serialization.object({
+ data: core.serialization.list(SessionEventItem),
+ pagination: TokenPagination,
+});
+
+export declare namespace ListSessionEventsResponse {
+ export interface Raw {
+ data: SessionEventItem.Raw[];
+ pagination: TokenPagination.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListSessionsOrder.ts b/packages/sdk/src/serialization/types/ListSessionsOrder.ts
new file mode 100644
index 000000000..5a33b62a9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListSessionsOrder.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ListSessionsOrder: core.serialization.Schema<
+ serializers.ListSessionsOrder.Raw,
+ TrueHarness.ListSessionsOrder
+> = core.serialization.enum_(["asc", "desc"]);
+
+export declare namespace ListSessionsOrder {
+ export type Raw = "asc" | "desc";
+}
diff --git a/packages/sdk/src/serialization/types/ListSessionsResponse.ts b/packages/sdk/src/serialization/types/ListSessionsResponse.ts
new file mode 100644
index 000000000..d4c5ee696
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListSessionsResponse.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { Session } from "./Session.js";
+import { TokenPagination } from "./TokenPagination.js";
+
+export const ListSessionsResponse: core.serialization.ObjectSchema<
+ serializers.ListSessionsResponse.Raw,
+ TrueHarness.ListSessionsResponse
+> = core.serialization.object({
+ data: core.serialization.list(Session),
+ pagination: TokenPagination,
+});
+
+export declare namespace ListSessionsResponse {
+ export interface Raw {
+ data: Session.Raw[];
+ pagination: TokenPagination.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListSkillsResponse.ts b/packages/sdk/src/serialization/types/ListSkillsResponse.ts
new file mode 100644
index 000000000..be6ecb499
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListSkillsResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SkillEntry } from "./SkillEntry.js";
+
+export const ListSkillsResponse: core.serialization.ObjectSchema<
+ serializers.ListSkillsResponse.Raw,
+ TrueHarness.ListSkillsResponse
+> = core.serialization.object({
+ data: core.serialization.list(SkillEntry),
+});
+
+export declare namespace ListSkillsResponse {
+ export interface Raw {
+ data: SkillEntry.Raw[];
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListTurnEventsOrder.ts b/packages/sdk/src/serialization/types/ListTurnEventsOrder.ts
new file mode 100644
index 000000000..c4cc03da7
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListTurnEventsOrder.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ListTurnEventsOrder: core.serialization.Schema<
+ serializers.ListTurnEventsOrder.Raw,
+ TrueHarness.ListTurnEventsOrder
+> = core.serialization.enum_(["asc", "desc"]);
+
+export declare namespace ListTurnEventsOrder {
+ export type Raw = "asc" | "desc";
+}
diff --git a/packages/sdk/src/serialization/types/ListTurnEventsResponse.ts b/packages/sdk/src/serialization/types/ListTurnEventsResponse.ts
new file mode 100644
index 000000000..f42112d28
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListTurnEventsResponse.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SessionEvent } from "./SessionEvent.js";
+import { TokenPagination } from "./TokenPagination.js";
+
+export const ListTurnEventsResponse: core.serialization.ObjectSchema<
+ serializers.ListTurnEventsResponse.Raw,
+ TrueHarness.ListTurnEventsResponse
+> = core.serialization.object({
+ data: core.serialization.list(SessionEvent),
+ pagination: TokenPagination,
+});
+
+export declare namespace ListTurnEventsResponse {
+ export interface Raw {
+ data: SessionEvent.Raw[];
+ pagination: TokenPagination.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ListTurnsResponse.ts b/packages/sdk/src/serialization/types/ListTurnsResponse.ts
new file mode 100644
index 000000000..4e6c3fefc
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ListTurnsResponse.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TokenPagination } from "./TokenPagination.js";
+import { Turn } from "./Turn.js";
+
+export const ListTurnsResponse: core.serialization.ObjectSchema<
+ serializers.ListTurnsResponse.Raw,
+ TrueHarness.ListTurnsResponse
+> = core.serialization.object({
+ data: core.serialization.list(Turn),
+ pagination: TokenPagination,
+});
+
+export declare namespace ListTurnsResponse {
+ export interface Raw {
+ data: Turn.Raw[];
+ pagination: TokenPagination.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpAuthRequiredEvent.ts b/packages/sdk/src/serialization/types/McpAuthRequiredEvent.ts
new file mode 100644
index 000000000..cf182e5c8
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpAuthRequiredEvent.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { BaseMcpAuthRequiredEvent } from "./BaseMcpAuthRequiredEvent.js";
+import { McpServerAuthInfo } from "./McpServerAuthInfo.js";
+
+export const McpAuthRequiredEvent: core.serialization.ObjectSchema<
+ serializers.McpAuthRequiredEvent.Raw,
+ TrueHarness.McpAuthRequiredEvent
+> = core.serialization
+ .object({
+ mcpServers: core.serialization.property("mcp_servers", core.serialization.list(McpServerAuthInfo)),
+ type: core.serialization.stringLiteral("mcp.auth_required"),
+ })
+ .extend(BaseMcpAuthRequiredEvent);
+
+export declare namespace McpAuthRequiredEvent {
+ export interface Raw extends BaseMcpAuthRequiredEvent.Raw {
+ mcp_servers: McpServerAuthInfo.Raw[];
+ type: "mcp.auth_required";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpInitializeEvent.ts b/packages/sdk/src/serialization/types/McpInitializeEvent.ts
new file mode 100644
index 000000000..d2910027a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpInitializeEvent.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpServerInitInfo } from "./McpServerInitInfo.js";
+
+export const McpInitializeEvent: core.serialization.ObjectSchema<
+ serializers.McpInitializeEvent.Raw,
+ TrueHarness.McpInitializeEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ mcpServers: core.serialization.property("mcp_servers", core.serialization.list(McpServerInitInfo)),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("mcp.initialize"),
+});
+
+export declare namespace McpInitializeEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ mcp_servers: McpServerInitInfo.Raw[];
+ thread_id: string;
+ type: "mcp.initialize";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServer.ts b/packages/sdk/src/serialization/types/McpServer.ts
new file mode 100644
index 000000000..5bc6b45c3
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServer.ts
@@ -0,0 +1,42 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpServerDisableToolsItem } from "./McpServerDisableToolsItem.js";
+import { McpServerEnableToolsItem } from "./McpServerEnableToolsItem.js";
+import { McpServerPreloadToolsItem } from "./McpServerPreloadToolsItem.js";
+import { McpServerRequireApprovalForToolsItem } from "./McpServerRequireApprovalForToolsItem.js";
+
+export const McpServer: core.serialization.ObjectSchema<serializers.McpServer.Raw, TrueHarness.McpServer> =
+ core.serialization.object({
+ disableTools: core.serialization.property(
+ "disable_tools",
+ core.serialization.list(McpServerDisableToolsItem).optional(),
+ ),
+ enableTools: core.serialization.property(
+ "enable_tools",
+ core.serialization.list(McpServerEnableToolsItem).optional(),
+ ),
+ name: core.serialization.string(),
+ preload: core.serialization.boolean().optional(),
+ preloadTools: core.serialization.property(
+ "preload_tools",
+ core.serialization.list(McpServerPreloadToolsItem).optional(),
+ ),
+ requireApprovalForTools: core.serialization.property(
+ "require_approval_for_tools",
+ core.serialization.list(McpServerRequireApprovalForToolsItem).optional(),
+ ),
+ });
+
+export declare namespace McpServer {
+ export interface Raw {
+ disable_tools?: McpServerDisableToolsItem.Raw[] | null;
+ enable_tools?: McpServerEnableToolsItem.Raw[] | null;
+ name: string;
+ preload?: boolean | null;
+ preload_tools?: McpServerPreloadToolsItem.Raw[] | null;
+ require_approval_for_tools?: McpServerRequireApprovalForToolsItem.Raw[] | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServerAuthInfo.ts b/packages/sdk/src/serialization/types/McpServerAuthInfo.ts
new file mode 100644
index 000000000..c013123cb
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerAuthInfo.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerAuthInfo: core.serialization.ObjectSchema<
+ serializers.McpServerAuthInfo.Raw,
+ TrueHarness.McpServerAuthInfo
+> = core.serialization.object({
+ authUrl: core.serialization.property("auth_url", core.serialization.string()),
+ id: core.serialization.string(),
+ name: core.serialization.string(),
+});
+
+export declare namespace McpServerAuthInfo {
+ export interface Raw {
+ auth_url: string;
+ id: string;
+ name: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServerDisableToolsItem.ts b/packages/sdk/src/serialization/types/McpServerDisableToolsItem.ts
new file mode 100644
index 000000000..87b8a4fd5
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerDisableToolsItem.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerDisableToolsItem: core.serialization.Schema<
+ serializers.McpServerDisableToolsItem.Raw,
+ TrueHarness.McpServerDisableToolsItem
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.stringLiteral("@all"),
+ core.serialization.stringLiteral("@read-only"),
+ core.serialization.string(),
+]);
+
+export declare namespace McpServerDisableToolsItem {
+ export type Raw = "@all" | "@read-only" | string;
+}
diff --git a/packages/sdk/src/serialization/types/McpServerEnableToolsItem.ts b/packages/sdk/src/serialization/types/McpServerEnableToolsItem.ts
new file mode 100644
index 000000000..d7692b310
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerEnableToolsItem.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerEnableToolsItem: core.serialization.Schema<
+ serializers.McpServerEnableToolsItem.Raw,
+ TrueHarness.McpServerEnableToolsItem
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.stringLiteral("@all"),
+ core.serialization.stringLiteral("@read-only"),
+ core.serialization.string(),
+]);
+
+export declare namespace McpServerEnableToolsItem {
+ export type Raw = "@all" | "@read-only" | string;
+}
diff --git a/packages/sdk/src/serialization/types/McpServerEntry.ts b/packages/sdk/src/serialization/types/McpServerEntry.ts
new file mode 100644
index 000000000..105e11008
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerEntry.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerEntry: core.serialization.ObjectSchema<
+ serializers.McpServerEntry.Raw,
+ TrueHarness.McpServerEntry
+> = core.serialization.object({
+ name: core.serialization.string(),
+ url: core.serialization.string(),
+});
+
+export declare namespace McpServerEntry {
+ export interface Raw {
+ name: string;
+ url: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServerInitInfo.ts b/packages/sdk/src/serialization/types/McpServerInitInfo.ts
new file mode 100644
index 000000000..dcd289e9d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerInitInfo.ts
@@ -0,0 +1,25 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpServerInitInfoTransportType } from "./McpServerInitInfoTransportType.js";
+
+export const McpServerInitInfo: core.serialization.ObjectSchema<
+ serializers.McpServerInitInfo.Raw,
+ TrueHarness.McpServerInitInfo
+> = core.serialization.object({
+ id: core.serialization.string(),
+ name: core.serialization.string(),
+ sessionId: core.serialization.property("session_id", core.serialization.string().optional()),
+ transportType: core.serialization.property("transport_type", McpServerInitInfoTransportType.optional()),
+});
+
+export declare namespace McpServerInitInfo {
+ export interface Raw {
+ id: string;
+ name: string;
+ session_id?: string | null;
+ transport_type?: McpServerInitInfoTransportType.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServerInitInfoTransportType.ts b/packages/sdk/src/serialization/types/McpServerInitInfoTransportType.ts
new file mode 100644
index 000000000..c2f1521d3
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerInitInfoTransportType.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerInitInfoTransportType: core.serialization.Schema<
+ serializers.McpServerInitInfoTransportType.Raw,
+ TrueHarness.McpServerInitInfoTransportType
+> = core.serialization.enum_(["streamable-http", "sse"]);
+
+export declare namespace McpServerInitInfoTransportType {
+ export type Raw = "streamable-http" | "sse";
+}
diff --git a/packages/sdk/src/serialization/types/McpServerPreloadToolsItem.ts b/packages/sdk/src/serialization/types/McpServerPreloadToolsItem.ts
new file mode 100644
index 000000000..6ed7e9f92
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerPreloadToolsItem.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerPreloadToolsItem: core.serialization.Schema<
+ serializers.McpServerPreloadToolsItem.Raw,
+ TrueHarness.McpServerPreloadToolsItem
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.stringLiteral("@all"),
+ core.serialization.stringLiteral("@read-only"),
+ core.serialization.string(),
+]);
+
+export declare namespace McpServerPreloadToolsItem {
+ export type Raw = "@all" | "@read-only" | string;
+}
diff --git a/packages/sdk/src/serialization/types/McpServerRequireApprovalForToolsItem.ts b/packages/sdk/src/serialization/types/McpServerRequireApprovalForToolsItem.ts
new file mode 100644
index 000000000..08a87e01d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerRequireApprovalForToolsItem.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpServerRequireApprovalForToolsItem: core.serialization.Schema<
+ serializers.McpServerRequireApprovalForToolsItem.Raw,
+ TrueHarness.McpServerRequireApprovalForToolsItem
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.stringLiteral("@all"),
+ core.serialization.stringLiteral("@write"),
+ core.serialization.stringLiteral("@destructive"),
+ core.serialization.string(),
+]);
+
+export declare namespace McpServerRequireApprovalForToolsItem {
+ export type Raw = "@all" | "@write" | "@destructive" | string;
+}
diff --git a/packages/sdk/src/serialization/types/McpToolInfo.ts b/packages/sdk/src/serialization/types/McpToolInfo.ts
new file mode 100644
index 000000000..717e88d22
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpToolInfo.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const McpToolInfo: core.serialization.ObjectSchema<serializers.McpToolInfo.Raw, TrueHarness.McpToolInfo> =
+ core.serialization.object({
+ name: core.serialization.string(),
+ serverId: core.serialization.property("server_id", core.serialization.string()),
+ serverName: core.serialization.property("server_name", core.serialization.string()),
+ type: core.serialization.stringLiteral("mcp"),
+ });
+
+export declare namespace McpToolInfo {
+ export interface Raw {
+ name: string;
+ server_id: string;
+ server_name: string;
+ type: "mcp";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/Model.ts b/packages/sdk/src/serialization/types/Model.ts
new file mode 100644
index 000000000..b39df0f83
--- /dev/null
+++ b/packages/sdk/src/serialization/types/Model.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelParams } from "./ModelParams.js";
+
+export const Model: core.serialization.ObjectSchema<serializers.Model.Raw, TrueHarness.Model> =
+ core.serialization.object({
+ name: core.serialization.string(),
+ params: ModelParams.optional(),
+ });
+
+export declare namespace Model {
+ export interface Raw {
+ name: string;
+ params?: ModelParams.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelEntry.ts b/packages/sdk/src/serialization/types/ModelEntry.ts
new file mode 100644
index 000000000..44a4c85e1
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelEntry.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ModelEntry: core.serialization.ObjectSchema<serializers.ModelEntry.Raw, TrueHarness.ModelEntry> =
+ core.serialization.object({
+ maxOutputTokens: core.serialization.property("max_output_tokens", core.serialization.number()),
+ name: core.serialization.string(),
+ reasoningEfforts: core.serialization.property(
+ "reasoning_efforts",
+ core.serialization.list(core.serialization.string()).optional(),
+ ),
+ });
+
+export declare namespace ModelEntry {
+ export interface Raw {
+ max_output_tokens: number;
+ name: string;
+ reasoning_efforts?: string[] | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageDeltaEvent.ts b/packages/sdk/src/serialization/types/ModelMessageDeltaEvent.ts
new file mode 100644
index 000000000..49833adea
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageDeltaEvent.ts
@@ -0,0 +1,42 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ExtendedChunkDeltaToolCall } from "./ExtendedChunkDeltaToolCall.js";
+import { FinishReason } from "./FinishReason.js";
+import { ModelMessageUsage } from "./ModelMessageUsage.js";
+
+export const ModelMessageDeltaEvent: core.serialization.ObjectSchema<
+ serializers.ModelMessageDeltaEvent.Raw,
+ TrueHarness.ModelMessageDeltaEvent
+> = core.serialization.object({
+ content: core.serialization.string().optionalNullable(),
+ createdAt: core.serialization.property("created_at", core.serialization.string().optional()),
+ finishReason: core.serialization.property("finish_reason", FinishReason.optionalNullable()),
+ id: core.serialization.string(),
+ reasoningContent: core.serialization.property("reasoning_content", core.serialization.string().optional()),
+ refusal: core.serialization.string().optionalNullable(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCalls: core.serialization.property(
+ "tool_calls",
+ core.serialization.list(ExtendedChunkDeltaToolCall).optional(),
+ ),
+ type: core.serialization.stringLiteral("model.message.delta"),
+ usage: ModelMessageUsage.optional(),
+});
+
+export declare namespace ModelMessageDeltaEvent {
+ export interface Raw {
+ content?: (string | null | undefined) | null;
+ created_at?: string | null;
+ finish_reason?: (FinishReason.Raw | null | undefined) | null;
+ id: string;
+ reasoning_content?: string | null;
+ refusal?: (string | null | undefined) | null;
+ thread_id: string;
+ tool_calls?: ExtendedChunkDeltaToolCall.Raw[] | null;
+ type: "model.message.delta";
+ usage?: ModelMessageUsage.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageEvent.ts b/packages/sdk/src/serialization/types/ModelMessageEvent.ts
new file mode 100644
index 000000000..dbcfabb05
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageEvent.ts
@@ -0,0 +1,42 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { FinishReason } from "./FinishReason.js";
+import { ModelMessageEventContent } from "./ModelMessageEventContent.js";
+import { ModelMessageUsage } from "./ModelMessageUsage.js";
+import { ToolCall } from "./ToolCall.js";
+
+export const ModelMessageEvent: core.serialization.ObjectSchema<
+ serializers.ModelMessageEvent.Raw,
+ TrueHarness.ModelMessageEvent
+> = core.serialization.object({
+ content: ModelMessageEventContent.optionalNullable(),
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ finishReason: core.serialization.property("finish_reason", FinishReason.optionalNullable()),
+ id: core.serialization.string(),
+ name: core.serialization.string().optional(),
+ reasoningContent: core.serialization.property("reasoning_content", core.serialization.string().optional()),
+ refusal: core.serialization.string().optionalNullable(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCall).optional()),
+ type: core.serialization.stringLiteral("model.message"),
+ usage: ModelMessageUsage.optional(),
+});
+
+export declare namespace ModelMessageEvent {
+ export interface Raw {
+ content?: (ModelMessageEventContent.Raw | null | undefined) | null;
+ created_at: string;
+ finish_reason?: (FinishReason.Raw | null | undefined) | null;
+ id: string;
+ name?: string | null;
+ reasoning_content?: string | null;
+ refusal?: (string | null | undefined) | null;
+ thread_id: string;
+ tool_calls?: ToolCall.Raw[] | null;
+ type: "model.message";
+ usage?: ModelMessageUsage.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageEventContent.ts b/packages/sdk/src/serialization/types/ModelMessageEventContent.ts
new file mode 100644
index 000000000..b265b5e54
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageEventContent.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelMessageEventContentOneItem } from "./ModelMessageEventContentOneItem.js";
+
+export const ModelMessageEventContent: core.serialization.Schema<
+ serializers.ModelMessageEventContent.Raw,
+ TrueHarness.ModelMessageEventContent
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.string(),
+ core.serialization.list(ModelMessageEventContentOneItem),
+]);
+
+export declare namespace ModelMessageEventContent {
+ export type Raw = string | ModelMessageEventContentOneItem.Raw[];
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageEventContentOneItem.ts b/packages/sdk/src/serialization/types/ModelMessageEventContentOneItem.ts
new file mode 100644
index 000000000..9e2363f94
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageEventContentOneItem.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ChatCompletionContentPartRefusal } from "./ChatCompletionContentPartRefusal.js";
+import { ChatCompletionContentPartText } from "./ChatCompletionContentPartText.js";
+
+export const ModelMessageEventContentOneItem: core.serialization.Schema<
+ serializers.ModelMessageEventContentOneItem.Raw,
+ TrueHarness.ModelMessageEventContentOneItem
+> = core.serialization.undiscriminatedUnion([ChatCompletionContentPartText, ChatCompletionContentPartRefusal]);
+
+export declare namespace ModelMessageEventContentOneItem {
+ export type Raw = ChatCompletionContentPartText.Raw | ChatCompletionContentPartRefusal.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageUsage.ts b/packages/sdk/src/serialization/types/ModelMessageUsage.ts
new file mode 100644
index 000000000..622520117
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageUsage.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelMessageUsageInputTokensBreakdown } from "./ModelMessageUsageInputTokensBreakdown.js";
+
+export const ModelMessageUsage: core.serialization.ObjectSchema<
+ serializers.ModelMessageUsage.Raw,
+ TrueHarness.ModelMessageUsage
+> = core.serialization.object({
+ cacheReadTokens: core.serialization.property("cache_read_tokens", core.serialization.number().optional()),
+ cacheWriteTokens: core.serialization.property("cache_write_tokens", core.serialization.number().optional()),
+ inputTokens: core.serialization.property("input_tokens", core.serialization.number()),
+ inputTokensBreakdown: core.serialization.property("input_tokens_breakdown", ModelMessageUsageInputTokensBreakdown),
+ outputTokens: core.serialization.property("output_tokens", core.serialization.number()),
+});
+
+export declare namespace ModelMessageUsage {
+ export interface Raw {
+ cache_read_tokens?: number | null;
+ cache_write_tokens?: number | null;
+ input_tokens: number;
+ input_tokens_breakdown: ModelMessageUsageInputTokensBreakdown.Raw;
+ output_tokens: number;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelMessageUsageInputTokensBreakdown.ts b/packages/sdk/src/serialization/types/ModelMessageUsageInputTokensBreakdown.ts
new file mode 100644
index 000000000..42c1a3100
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelMessageUsageInputTokensBreakdown.ts
@@ -0,0 +1,26 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ModelMessageUsageInputTokensBreakdown: core.serialization.ObjectSchema<
+ serializers.ModelMessageUsageInputTokensBreakdown.Raw,
+ TrueHarness.ModelMessageUsageInputTokensBreakdown
+> = core.serialization.object({
+ harness: core.serialization.number(),
+ instructions: core.serialization.number(),
+ messages: core.serialization.number(),
+ skills: core.serialization.number(),
+ toolDefinitions: core.serialization.property("tool_definitions", core.serialization.number()),
+});
+
+export declare namespace ModelMessageUsageInputTokensBreakdown {
+ export interface Raw {
+ harness: number;
+ instructions: number;
+ messages: number;
+ skills: number;
+ tool_definitions: number;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ModelParams.ts b/packages/sdk/src/serialization/types/ModelParams.ts
new file mode 100644
index 000000000..ab79f4bdc
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ModelParams.ts
@@ -0,0 +1,26 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ModelParams: core.serialization.ObjectSchema<serializers.ModelParams.Raw, TrueHarness.ModelParams> =
+ core.serialization.object({
+ maxTokens: core.serialization.property("max_tokens", core.serialization.number().optional()),
+ parallelToolCalls: core.serialization.property("parallel_tool_calls", core.serialization.boolean().optional()),
+ reasoningEffort: core.serialization.property("reasoning_effort", core.serialization.string().optional()),
+ temperature: core.serialization.number().optional(),
+ topK: core.serialization.property("top_k", core.serialization.number().optional()),
+ topP: core.serialization.property("top_p", core.serialization.number().optional()),
+ });
+
+export declare namespace ModelParams {
+ export interface Raw {
+ max_tokens?: number | null;
+ parallel_tool_calls?: boolean | null;
+ reasoning_effort?: string | null;
+ temperature?: number | null;
+ top_k?: number | null;
+ top_p?: number | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/PreviousTurnIdInput.ts b/packages/sdk/src/serialization/types/PreviousTurnIdInput.ts
new file mode 100644
index 000000000..b5bc193e2
--- /dev/null
+++ b/packages/sdk/src/serialization/types/PreviousTurnIdInput.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const PreviousTurnIdInput: core.serialization.Schema<
+ serializers.PreviousTurnIdInput.Raw,
+ TrueHarness.PreviousTurnIdInput
+> = core.serialization.undiscriminatedUnion([core.serialization.stringLiteral("auto"), core.serialization.string()]);
+
+export declare namespace PreviousTurnIdInput {
+ export type Raw = "auto" | string;
+}
diff --git a/packages/sdk/src/serialization/types/RawToolCall.ts b/packages/sdk/src/serialization/types/RawToolCall.ts
new file mode 100644
index 000000000..8ff1d71e7
--- /dev/null
+++ b/packages/sdk/src/serialization/types/RawToolCall.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ChatCompletionMessageToolCall } from "./ChatCompletionMessageToolCall.js";
+
+export const RawToolCall: core.serialization.ObjectSchema<serializers.RawToolCall.Raw, TrueHarness.RawToolCall> =
+ core.serialization
+ .object({
+ providerSpecificFields: core.serialization.property(
+ "provider_specific_fields",
+ core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional(),
+ ),
+ })
+ .extend(ChatCompletionMessageToolCall);
+
+export declare namespace RawToolCall {
+ export interface Raw extends ChatCompletionMessageToolCall.Raw {
+ provider_specific_fields?: Record<string, unknown> | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/RequestErrorResponse.ts b/packages/sdk/src/serialization/types/RequestErrorResponse.ts
new file mode 100644
index 000000000..c04808c46
--- /dev/null
+++ b/packages/sdk/src/serialization/types/RequestErrorResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { RequestErrorResponseError } from "./RequestErrorResponseError.js";
+
+export const RequestErrorResponse: core.serialization.ObjectSchema<
+ serializers.RequestErrorResponse.Raw,
+ TrueHarness.RequestErrorResponse
+> = core.serialization.object({
+ error: RequestErrorResponseError,
+});
+
+export declare namespace RequestErrorResponse {
+ export interface Raw {
+ error: RequestErrorResponseError.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/RequestErrorResponseError.ts b/packages/sdk/src/serialization/types/RequestErrorResponseError.ts
new file mode 100644
index 000000000..2b88dd89a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/RequestErrorResponseError.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const RequestErrorResponseError: core.serialization.ObjectSchema<
+ serializers.RequestErrorResponseError.Raw,
+ TrueHarness.RequestErrorResponseError
+> = core.serialization.object({
+ code: core.serialization.string().optionalNullable(),
+ message: core.serialization.string(),
+ param: core.serialization.string().optionalNullable(),
+ type: core.serialization.string().optional(),
+});
+
+export declare namespace RequestErrorResponseError {
+ export interface Raw {
+ code?: (string | null | undefined) | null;
+ message: string;
+ param?: (string | null | undefined) | null;
+ type?: string | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ResponseFormat.ts b/packages/sdk/src/serialization/types/ResponseFormat.ts
new file mode 100644
index 000000000..b5fe393cf
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ResponseFormat.ts
@@ -0,0 +1,15 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ResponseFormatJsonSchema } from "./ResponseFormatJsonSchema.js";
+import { ResponseFormatOne } from "./ResponseFormatOne.js";
+import { ResponseFormatZero } from "./ResponseFormatZero.js";
+
+export const ResponseFormat: core.serialization.Schema<serializers.ResponseFormat.Raw, TrueHarness.ResponseFormat> =
+ core.serialization.undiscriminatedUnion([ResponseFormatZero, ResponseFormatOne, ResponseFormatJsonSchema]);
+
+export declare namespace ResponseFormat {
+ export type Raw = ResponseFormatZero.Raw | ResponseFormatOne.Raw | ResponseFormatJsonSchema.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/ResponseFormatJsonSchema.ts b/packages/sdk/src/serialization/types/ResponseFormatJsonSchema.ts
new file mode 100644
index 000000000..b1bd95ce5
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ResponseFormatJsonSchema.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ResponseFormatJsonSchemaJsonSchema } from "./ResponseFormatJsonSchemaJsonSchema.js";
+
+export const ResponseFormatJsonSchema: core.serialization.ObjectSchema<
+ serializers.ResponseFormatJsonSchema.Raw,
+ TrueHarness.ResponseFormatJsonSchema
+> = core.serialization.object({
+ jsonSchema: core.serialization.property("json_schema", ResponseFormatJsonSchemaJsonSchema),
+ type: core.serialization.stringLiteral("json_schema"),
+});
+
+export declare namespace ResponseFormatJsonSchema {
+ export interface Raw {
+ json_schema: ResponseFormatJsonSchemaJsonSchema.Raw;
+ type: "json_schema";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ResponseFormatJsonSchemaJsonSchema.ts b/packages/sdk/src/serialization/types/ResponseFormatJsonSchemaJsonSchema.ts
new file mode 100644
index 000000000..08bca9b45
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ResponseFormatJsonSchemaJsonSchema.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ResponseFormatJsonSchemaJsonSchema: core.serialization.ObjectSchema<
+ serializers.ResponseFormatJsonSchemaJsonSchema.Raw,
+ TrueHarness.ResponseFormatJsonSchemaJsonSchema
+> = core.serialization.object({
+ description: core.serialization.string().optional(),
+ name: core.serialization.string(),
+ schema: core.serialization.record(core.serialization.string(), core.serialization.unknown()).optional(),
+ strict: core.serialization.boolean().optionalNullable(),
+});
+
+export declare namespace ResponseFormatJsonSchemaJsonSchema {
+ export interface Raw {
+ description?: string | null;
+ name: string;
+ schema?: Record<string, unknown> | null;
+ strict?: (boolean | null | undefined) | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ResponseFormatOne.ts b/packages/sdk/src/serialization/types/ResponseFormatOne.ts
new file mode 100644
index 000000000..13c06c3f4
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ResponseFormatOne.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ResponseFormatOne: core.serialization.ObjectSchema<
+ serializers.ResponseFormatOne.Raw,
+ TrueHarness.ResponseFormatOne
+> = core.serialization.object({
+ type: core.serialization.stringLiteral("json_object"),
+});
+
+export declare namespace ResponseFormatOne {
+ export interface Raw {
+ type: "json_object";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ResponseFormatZero.ts b/packages/sdk/src/serialization/types/ResponseFormatZero.ts
new file mode 100644
index 000000000..fcd44b6f4
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ResponseFormatZero.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ResponseFormatZero: core.serialization.ObjectSchema<
+ serializers.ResponseFormatZero.Raw,
+ TrueHarness.ResponseFormatZero
+> = core.serialization.object({
+ type: core.serialization.stringLiteral("text"),
+});
+
+export declare namespace ResponseFormatZero {
+ export interface Raw {
+ type: "text";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/RuntimeConfig.ts b/packages/sdk/src/serialization/types/RuntimeConfig.ts
new file mode 100644
index 000000000..2097854dd
--- /dev/null
+++ b/packages/sdk/src/serialization/types/RuntimeConfig.ts
@@ -0,0 +1,31 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { AskUserQuestionsConfig } from "./AskUserQuestionsConfig.js";
+import { ContextManagementConfig } from "./ContextManagementConfig.js";
+import { DynamicSubAgentsConfig } from "./DynamicSubAgentsConfig.js";
+import { GenerativeUiConfig } from "./GenerativeUiConfig.js";
+import { SandboxConfig } from "./SandboxConfig.js";
+
+export const RuntimeConfig: core.serialization.ObjectSchema<serializers.RuntimeConfig.Raw, TrueHarness.RuntimeConfig> =
+ core.serialization.object({
+ askUserQuestions: core.serialization.property("ask_user_questions", AskUserQuestionsConfig.optional()),
+ contextManagement: core.serialization.property("context_management", ContextManagementConfig.optional()),
+ dynamicSubAgents: core.serialization.property("dynamic_sub_agents", DynamicSubAgentsConfig.optional()),
+ generativeUi: core.serialization.property("generative_ui", GenerativeUiConfig.optional()),
+ iterationLimit: core.serialization.property("iteration_limit", core.serialization.number().optional()),
+ sandbox: SandboxConfig.optional(),
+ });
+
+export declare namespace RuntimeConfig {
+ export interface Raw {
+ ask_user_questions?: AskUserQuestionsConfig.Raw | null;
+ context_management?: ContextManagementConfig.Raw | null;
+ dynamic_sub_agents?: DynamicSubAgentsConfig.Raw | null;
+ generative_ui?: GenerativeUiConfig.Raw | null;
+ iteration_limit?: number | null;
+ sandbox?: SandboxConfig.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxConfig.ts b/packages/sdk/src/serialization/types/SandboxConfig.ts
new file mode 100644
index 000000000..27346dd51
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxConfig.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SandboxNetworkPolicy } from "./SandboxNetworkPolicy.js";
+
+export const SandboxConfig: core.serialization.ObjectSchema<serializers.SandboxConfig.Raw, TrueHarness.SandboxConfig> =
+ core.serialization.object({
+ enabled: core.serialization.boolean(),
+ fileDownloads: core.serialization.property("file_downloads", core.serialization.boolean().optional()),
+ networkPolicy: core.serialization.property("network_policy", SandboxNetworkPolicy.optional()),
+ });
+
+export declare namespace SandboxConfig {
+ export interface Raw {
+ enabled: boolean;
+ file_downloads?: boolean | null;
+ network_policy?: SandboxNetworkPolicy.Raw | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxCreatedEvent.ts b/packages/sdk/src/serialization/types/SandboxCreatedEvent.ts
new file mode 100644
index 000000000..44d41e08c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxCreatedEvent.ts
@@ -0,0 +1,26 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SandboxCreatedEvent: core.serialization.ObjectSchema<
+ serializers.SandboxCreatedEvent.Raw,
+ TrueHarness.SandboxCreatedEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ sandboxId: core.serialization.property("sandbox_id", core.serialization.string()),
+ threadId: core.serialization.property("thread_id", core.serialization.string().nullable()),
+ type: core.serialization.stringLiteral("sandbox.created"),
+});
+
+export declare namespace SandboxCreatedEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ sandbox_id: string;
+ thread_id?: string | null;
+ type: "sandbox.created";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxNetworkPolicy.ts b/packages/sdk/src/serialization/types/SandboxNetworkPolicy.ts
new file mode 100644
index 000000000..eb7d4b759
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxNetworkPolicy.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SandboxNetworkPolicyAuthInjectItem } from "./SandboxNetworkPolicyAuthInjectItem.js";
+
+export const SandboxNetworkPolicy: core.serialization.ObjectSchema<
+ serializers.SandboxNetworkPolicy.Raw,
+ TrueHarness.SandboxNetworkPolicy
+> = core.serialization.object({
+ authInject: core.serialization.property(
+ "auth_inject",
+ core.serialization.list(SandboxNetworkPolicyAuthInjectItem).optional(),
+ ),
+});
+
+export declare namespace SandboxNetworkPolicy {
+ export interface Raw {
+ auth_inject?: SandboxNetworkPolicyAuthInjectItem.Raw[] | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItem.ts b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItem.ts
new file mode 100644
index 000000000..ab3cd6176
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItem.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SandboxNetworkPolicyAuthInjectItemAuthData } from "./SandboxNetworkPolicyAuthInjectItemAuthData.js";
+import { SandboxNetworkPolicyAuthInjectItemMatch } from "./SandboxNetworkPolicyAuthInjectItemMatch.js";
+
+export const SandboxNetworkPolicyAuthInjectItem: core.serialization.ObjectSchema<
+ serializers.SandboxNetworkPolicyAuthInjectItem.Raw,
+ TrueHarness.SandboxNetworkPolicyAuthInjectItem
+> = core.serialization.object({
+ authData: core.serialization.property("auth_data", SandboxNetworkPolicyAuthInjectItemAuthData),
+ match: SandboxNetworkPolicyAuthInjectItemMatch,
+ type: core.serialization.stringLiteral("git"),
+});
+
+export declare namespace SandboxNetworkPolicyAuthInjectItem {
+ export interface Raw {
+ auth_data: SandboxNetworkPolicyAuthInjectItemAuthData.Raw;
+ match: SandboxNetworkPolicyAuthInjectItemMatch.Raw;
+ type: "git";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts
new file mode 100644
index 000000000..82d64f664
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemAuthData.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SandboxNetworkPolicyAuthInjectItemAuthData: core.serialization.ObjectSchema<
+ serializers.SandboxNetworkPolicyAuthInjectItemAuthData.Raw,
+ TrueHarness.SandboxNetworkPolicyAuthInjectItemAuthData
+> = core.serialization.object({
+ password: core.serialization.string(),
+ type: core.serialization.stringLiteral("basic"),
+ username: core.serialization.string(),
+});
+
+export declare namespace SandboxNetworkPolicyAuthInjectItemAuthData {
+ export interface Raw {
+ password: string;
+ type: "basic";
+ username: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemMatch.ts b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemMatch.ts
new file mode 100644
index 000000000..c2b87170c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SandboxNetworkPolicyAuthInjectItemMatch.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SandboxNetworkPolicyAuthInjectItemMatch: core.serialization.ObjectSchema<
+ serializers.SandboxNetworkPolicyAuthInjectItemMatch.Raw,
+ TrueHarness.SandboxNetworkPolicyAuthInjectItemMatch
+> = core.serialization.object({
+ hosts: core.serialization.list(core.serialization.string()),
+});
+
+export declare namespace SandboxNetworkPolicyAuthInjectItemMatch {
+ export interface Raw {
+ hosts: string[];
+ }
+}
diff --git a/packages/sdk/src/serialization/types/Session.ts b/packages/sdk/src/serialization/types/Session.ts
new file mode 100644
index 000000000..18f859e8e
--- /dev/null
+++ b/packages/sdk/src/serialization/types/Session.ts
@@ -0,0 +1,25 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { AgentSpec } from "./AgentSpec.js";
+
+export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, TrueHarness.Session> =
+ core.serialization.object({
+ agentSpec: core.serialization.property("agent_spec", AgentSpec),
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ title: core.serialization.string().nullable(),
+ updatedAt: core.serialization.property("updated_at", core.serialization.string()),
+ });
+
+export declare namespace Session {
+ export interface Raw {
+ agent_spec: AgentSpec.Raw;
+ created_at: string;
+ id: string;
+ title?: string | null;
+ updated_at: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SessionEvent.ts b/packages/sdk/src/serialization/types/SessionEvent.ts
new file mode 100644
index 000000000..f6c371c75
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SessionEvent.ts
@@ -0,0 +1,46 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpAuthRequiredEvent } from "./McpAuthRequiredEvent.js";
+import { McpInitializeEvent } from "./McpInitializeEvent.js";
+import { ModelMessageEvent } from "./ModelMessageEvent.js";
+import { SandboxCreatedEvent } from "./SandboxCreatedEvent.js";
+import { ThreadCreatedEvent } from "./ThreadCreatedEvent.js";
+import { ThreadDoneEvent } from "./ThreadDoneEvent.js";
+import { ToolApprovalRequiredEvent } from "./ToolApprovalRequiredEvent.js";
+import { ToolResponseEvent } from "./ToolResponseEvent.js";
+import { ToolResponseRequiredEvent } from "./ToolResponseRequiredEvent.js";
+import { TurnCreatedEvent } from "./TurnCreatedEvent.js";
+import { TurnDoneEvent } from "./TurnDoneEvent.js";
+
+export const SessionEvent: core.serialization.Schema<serializers.SessionEvent.Raw, TrueHarness.SessionEvent> =
+ core.serialization.undiscriminatedUnion([
+ McpAuthRequiredEvent,
+ McpInitializeEvent,
+ ModelMessageEvent,
+ SandboxCreatedEvent,
+ ThreadCreatedEvent,
+ ThreadDoneEvent,
+ ToolApprovalRequiredEvent,
+ ToolResponseEvent,
+ ToolResponseRequiredEvent,
+ TurnCreatedEvent,
+ TurnDoneEvent,
+ ]);
+
+export declare namespace SessionEvent {
+ export type Raw =
+ | McpAuthRequiredEvent.Raw
+ | McpInitializeEvent.Raw
+ | ModelMessageEvent.Raw
+ | SandboxCreatedEvent.Raw
+ | ThreadCreatedEvent.Raw
+ | ThreadDoneEvent.Raw
+ | ToolApprovalRequiredEvent.Raw
+ | ToolResponseEvent.Raw
+ | ToolResponseRequiredEvent.Raw
+ | TurnCreatedEvent.Raw
+ | TurnDoneEvent.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/SessionEventItem.ts b/packages/sdk/src/serialization/types/SessionEventItem.ts
new file mode 100644
index 000000000..2f984040f
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SessionEventItem.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { SessionEvent } from "./SessionEvent.js";
+
+export const SessionEventItem: core.serialization.ObjectSchema<
+ serializers.SessionEventItem.Raw,
+ TrueHarness.SessionEventItem
+> = core.serialization.object({
+ event: SessionEvent,
+ turnId: core.serialization.property("turn_id", core.serialization.string()),
+});
+
+export declare namespace SessionEventItem {
+ export interface Raw {
+ event: SessionEvent.Raw;
+ turn_id: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SkillEntry.ts b/packages/sdk/src/serialization/types/SkillEntry.ts
new file mode 100644
index 000000000..ebb1ca565
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SkillEntry.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SkillEntry: core.serialization.ObjectSchema<serializers.SkillEntry.Raw, TrueHarness.SkillEntry> =
+ core.serialization.object({
+ description: core.serialization.string(),
+ name: core.serialization.string(),
+ path: core.serialization.string().optional(),
+ ref: core.serialization.string().optional(),
+ url: core.serialization.string(),
+ });
+
+export declare namespace SkillEntry {
+ export interface Raw {
+ description: string;
+ name: string;
+ path?: string | null;
+ ref?: string | null;
+ url: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/SkillMount.ts b/packages/sdk/src/serialization/types/SkillMount.ts
new file mode 100644
index 000000000..625b0aa8f
--- /dev/null
+++ b/packages/sdk/src/serialization/types/SkillMount.ts
@@ -0,0 +1,26 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SkillMount: core.serialization.ObjectSchema<serializers.SkillMount.Raw, TrueHarness.SkillMount> =
+ core.serialization.object({
+ description: core.serialization.string(),
+ name: core.serialization.string(),
+ path: core.serialization.string().optional(),
+ ref: core.serialization.string(),
+ type: core.serialization.stringLiteral("git"),
+ url: core.serialization.string(),
+ });
+
+export declare namespace SkillMount {
+ export interface Raw {
+ description: string;
+ name: string;
+ path?: string | null;
+ ref: string;
+ type: "git";
+ url: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TextContent.ts b/packages/sdk/src/serialization/types/TextContent.ts
new file mode 100644
index 000000000..6e7c9f973
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TextContent.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TextContent: core.serialization.ObjectSchema<serializers.TextContent.Raw, TrueHarness.TextContent> =
+ core.serialization.object({
+ text: core.serialization.string(),
+ type: core.serialization.stringLiteral("text"),
+ });
+
+export declare namespace TextContent {
+ export interface Raw {
+ text: string;
+ type: "text";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ThreadCreatedEvent.ts b/packages/sdk/src/serialization/types/ThreadCreatedEvent.ts
new file mode 100644
index 000000000..71774b2a9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ThreadCreatedEvent.ts
@@ -0,0 +1,32 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { AgentInfo } from "./AgentInfo.js";
+import { AgentParent } from "./AgentParent.js";
+
+export const ThreadCreatedEvent: core.serialization.ObjectSchema<
+ serializers.ThreadCreatedEvent.Raw,
+ TrueHarness.ThreadCreatedEvent
+> = core.serialization.object({
+ agentInfo: core.serialization.property("agent_info", AgentInfo),
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ parent: AgentParent,
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ title: core.serialization.string(),
+ type: core.serialization.stringLiteral("thread.created"),
+});
+
+export declare namespace ThreadCreatedEvent {
+ export interface Raw {
+ agent_info: AgentInfo.Raw;
+ created_at: string;
+ id: string;
+ parent: AgentParent.Raw;
+ thread_id: string;
+ title: string;
+ type: "thread.created";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ThreadDoneEvent.ts b/packages/sdk/src/serialization/types/ThreadDoneEvent.ts
new file mode 100644
index 000000000..a47097600
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ThreadDoneEvent.ts
@@ -0,0 +1,28 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { BaseThreadDoneEvent } from "./BaseThreadDoneEvent.js";
+import { ThreadState } from "./ThreadState.js";
+
+export const ThreadDoneEvent: core.serialization.ObjectSchema<
+ serializers.ThreadDoneEvent.Raw,
+ TrueHarness.ThreadDoneEvent
+> = core.serialization
+ .object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ state: ThreadState,
+ type: core.serialization.stringLiteral("thread.done"),
+ })
+ .extend(BaseThreadDoneEvent);
+
+export declare namespace ThreadDoneEvent {
+ export interface Raw extends BaseThreadDoneEvent.Raw {
+ created_at: string;
+ id: string;
+ state: ThreadState.Raw;
+ type: "thread.done";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ThreadState.ts b/packages/sdk/src/serialization/types/ThreadState.ts
new file mode 100644
index 000000000..f859edff9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ThreadState.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ThreadStateDone } from "./ThreadStateDone.js";
+import { ThreadStateError } from "./ThreadStateError.js";
+
+export const ThreadState: core.serialization.Schema<serializers.ThreadState.Raw, TrueHarness.ThreadState> =
+ core.serialization.undiscriminatedUnion([ThreadStateDone, ThreadStateError]);
+
+export declare namespace ThreadState {
+ export type Raw = ThreadStateDone.Raw | ThreadStateError.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/ThreadStateDone.ts b/packages/sdk/src/serialization/types/ThreadStateDone.ts
new file mode 100644
index 000000000..6128614c6
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ThreadStateDone.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelMessageEvent } from "./ModelMessageEvent.js";
+
+export const ThreadStateDone: core.serialization.ObjectSchema<
+ serializers.ThreadStateDone.Raw,
+ TrueHarness.ThreadStateDone
+> = core.serialization.object({
+ output: ModelMessageEvent,
+ status: core.serialization.stringLiteral("done"),
+});
+
+export declare namespace ThreadStateDone {
+ export interface Raw {
+ output: ModelMessageEvent.Raw;
+ status: "done";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ThreadStateError.ts b/packages/sdk/src/serialization/types/ThreadStateError.ts
new file mode 100644
index 000000000..fa46ee001
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ThreadStateError.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ModelMessageEvent } from "./ModelMessageEvent.js";
+
+export const ThreadStateError: core.serialization.ObjectSchema<
+ serializers.ThreadStateError.Raw,
+ TrueHarness.ThreadStateError
+> = core.serialization.object({
+ error: core.serialization.string(),
+ output: ModelMessageEvent.optional(),
+ status: core.serialization.stringLiteral("error"),
+});
+
+export declare namespace ThreadStateError {
+ export interface Raw {
+ error: string;
+ output?: ModelMessageEvent.Raw | null;
+ status: "error";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TokenPagination.ts b/packages/sdk/src/serialization/types/TokenPagination.ts
new file mode 100644
index 000000000..d70595cf8
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TokenPagination.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TokenPagination: core.serialization.ObjectSchema<
+ serializers.TokenPagination.Raw,
+ TrueHarness.TokenPagination
+> = core.serialization.object({
+ limit: core.serialization.number(),
+ nextPageToken: core.serialization.property("next_page_token", core.serialization.string().optional()),
+ previousPageToken: core.serialization.property("previous_page_token", core.serialization.string().optional()),
+});
+
+export declare namespace TokenPagination {
+ export interface Raw {
+ limit: number;
+ next_page_token?: string | null;
+ previous_page_token?: string | null;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ToolApprovalRequiredEvent.ts b/packages/sdk/src/serialization/types/ToolApprovalRequiredEvent.ts
new file mode 100644
index 000000000..4165c8aec
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolApprovalRequiredEvent.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ToolCallRef } from "./ToolCallRef.js";
+
+export const ToolApprovalRequiredEvent: core.serialization.ObjectSchema<
+ serializers.ToolApprovalRequiredEvent.Raw,
+ TrueHarness.ToolApprovalRequiredEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCallRef)),
+ type: core.serialization.stringLiteral("tool.approval_required"),
+});
+
+export declare namespace ToolApprovalRequiredEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ thread_id: string;
+ tool_calls: ToolCallRef.Raw[];
+ type: "tool.approval_required";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ToolCall.ts b/packages/sdk/src/serialization/types/ToolCall.ts
new file mode 100644
index 000000000..831933999
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolCall.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { RawToolCall } from "./RawToolCall.js";
+import { ToolInfo } from "./ToolInfo.js";
+
+export const ToolCall: core.serialization.ObjectSchema<serializers.ToolCall.Raw, TrueHarness.ToolCall> =
+ core.serialization
+ .object({
+ toolInfo: core.serialization.property("tool_info", ToolInfo),
+ })
+ .extend(RawToolCall);
+
+export declare namespace ToolCall {
+ export interface Raw extends RawToolCall.Raw {
+ tool_info: ToolInfo.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ToolCallRef.ts b/packages/sdk/src/serialization/types/ToolCallRef.ts
new file mode 100644
index 000000000..ce108579c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolCallRef.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ToolCallRef: core.serialization.ObjectSchema<serializers.ToolCallRef.Raw, TrueHarness.ToolCallRef> =
+ core.serialization.object({
+ id: core.serialization.string(),
+ sourceEventId: core.serialization.property("source_event_id", core.serialization.string()),
+ });
+
+export declare namespace ToolCallRef {
+ export interface Raw {
+ id: string;
+ source_event_id: string;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ToolInfo.ts b/packages/sdk/src/serialization/types/ToolInfo.ts
new file mode 100644
index 000000000..2769890f6
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolInfo.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpToolInfo } from "./McpToolInfo.js";
+import { TrueFoundrySystemToolInfo } from "./TrueFoundrySystemToolInfo.js";
+
+export const ToolInfo: core.serialization.Schema<serializers.ToolInfo.Raw, TrueHarness.ToolInfo> =
+ core.serialization.undiscriminatedUnion([McpToolInfo, TrueFoundrySystemToolInfo]);
+
+export declare namespace ToolInfo {
+ export type Raw = McpToolInfo.Raw | TrueFoundrySystemToolInfo.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/ToolResponseEvent.ts b/packages/sdk/src/serialization/types/ToolResponseEvent.ts
new file mode 100644
index 000000000..d6860459a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolResponseEvent.ts
@@ -0,0 +1,28 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ToolResponseEvent: core.serialization.ObjectSchema<
+ serializers.ToolResponseEvent.Raw,
+ TrueHarness.ToolResponseEvent
+> = core.serialization.object({
+ content: core.serialization.string(),
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCallId: core.serialization.property("tool_call_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("tool.response"),
+});
+
+export declare namespace ToolResponseEvent {
+ export interface Raw {
+ content: string;
+ created_at: string;
+ id: string;
+ thread_id: string;
+ tool_call_id: string;
+ type: "tool.response";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/ToolResponseRequiredEvent.ts b/packages/sdk/src/serialization/types/ToolResponseRequiredEvent.ts
new file mode 100644
index 000000000..278536819
--- /dev/null
+++ b/packages/sdk/src/serialization/types/ToolResponseRequiredEvent.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ToolCallRef } from "./ToolCallRef.js";
+
+export const ToolResponseRequiredEvent: core.serialization.ObjectSchema<
+ serializers.ToolResponseRequiredEvent.Raw,
+ TrueHarness.ToolResponseRequiredEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCalls: core.serialization.property("tool_calls", core.serialization.list(ToolCallRef)),
+ type: core.serialization.stringLiteral("tool.response_required"),
+});
+
+export declare namespace ToolResponseRequiredEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ thread_id: string;
+ tool_calls: ToolCallRef.Raw[];
+ type: "tool.response_required";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TrueFoundrySystemToolInfo.ts b/packages/sdk/src/serialization/types/TrueFoundrySystemToolInfo.ts
new file mode 100644
index 000000000..b02f160bb
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TrueFoundrySystemToolInfo.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TrueFoundrySystemToolInfo: core.serialization.ObjectSchema<
+ serializers.TrueFoundrySystemToolInfo.Raw,
+ TrueHarness.TrueFoundrySystemToolInfo
+> = core.serialization.object({
+ name: core.serialization.string(),
+ type: core.serialization.stringLiteral("truefoundry-system"),
+});
+
+export declare namespace TrueFoundrySystemToolInfo {
+ export interface Raw {
+ name: string;
+ type: "truefoundry-system";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/Turn.ts b/packages/sdk/src/serialization/types/Turn.ts
new file mode 100644
index 000000000..88173b1cb
--- /dev/null
+++ b/packages/sdk/src/serialization/types/Turn.ts
@@ -0,0 +1,27 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnInputItem } from "./TurnInputItem.js";
+import { TurnState } from "./TurnState.js";
+
+export const Turn: core.serialization.ObjectSchema<serializers.Turn.Raw, TrueHarness.Turn> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ input: core.serialization.list(TurnInputItem).optional(),
+ previousTurnId: core.serialization.property("previous_turn_id", core.serialization.string().nullable()),
+ sessionId: core.serialization.property("session_id", core.serialization.string()),
+ state: TurnState,
+});
+
+export declare namespace Turn {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ input?: TurnInputItem.Raw[] | null;
+ previous_turn_id?: string | null;
+ session_id: string;
+ state: TurnState.Raw;
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnCreatedEvent.ts b/packages/sdk/src/serialization/types/TurnCreatedEvent.ts
new file mode 100644
index 000000000..48a9e1179
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnCreatedEvent.ts
@@ -0,0 +1,34 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnInputItem } from "./TurnInputItem.js";
+import { TurnStateRunning } from "./TurnStateRunning.js";
+
+export const TurnCreatedEvent: core.serialization.ObjectSchema<
+ serializers.TurnCreatedEvent.Raw,
+ TrueHarness.TurnCreatedEvent
+> = core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ input: core.serialization.list(TurnInputItem).optional(),
+ previousTurnId: core.serialization.property("previous_turn_id", core.serialization.string().nullable()),
+ state: TurnStateRunning,
+ threadId: core.serialization.property("thread_id", core.serialization.string().nullable()),
+ turnId: core.serialization.property("turn_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("turn.created"),
+});
+
+export declare namespace TurnCreatedEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ input?: TurnInputItem.Raw[] | null;
+ previous_turn_id?: string | null;
+ state: TurnStateRunning.Raw;
+ thread_id?: string | null;
+ turn_id: string;
+ type: "turn.created";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnDoneEvent.ts b/packages/sdk/src/serialization/types/TurnDoneEvent.ts
new file mode 100644
index 000000000..2e5013afa
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnDoneEvent.ts
@@ -0,0 +1,25 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnDoneEventState } from "./TurnDoneEventState.js";
+
+export const TurnDoneEvent: core.serialization.ObjectSchema<serializers.TurnDoneEvent.Raw, TrueHarness.TurnDoneEvent> =
+ core.serialization.object({
+ createdAt: core.serialization.property("created_at", core.serialization.string()),
+ id: core.serialization.string(),
+ state: TurnDoneEventState,
+ threadId: core.serialization.property("thread_id", core.serialization.string().nullable()),
+ type: core.serialization.stringLiteral("turn.done"),
+ });
+
+export declare namespace TurnDoneEvent {
+ export interface Raw {
+ created_at: string;
+ id: string;
+ state: TurnDoneEventState.Raw;
+ thread_id?: string | null;
+ type: "turn.done";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnDoneEventState.ts b/packages/sdk/src/serialization/types/TurnDoneEventState.ts
new file mode 100644
index 000000000..f86cfbb4a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnDoneEventState.ts
@@ -0,0 +1,17 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnStateCancelled } from "./TurnStateCancelled.js";
+import { TurnStateDone } from "./TurnStateDone.js";
+import { TurnStateError } from "./TurnStateError.js";
+
+export const TurnDoneEventState: core.serialization.Schema<
+ serializers.TurnDoneEventState.Raw,
+ TrueHarness.TurnDoneEventState
+> = core.serialization.undiscriminatedUnion([TurnStateCancelled, TurnStateDone, TurnStateError]);
+
+export declare namespace TurnDoneEventState {
+ export type Raw = TurnStateCancelled.Raw | TurnStateDone.Raw | TurnStateError.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/TurnInputItem.ts b/packages/sdk/src/serialization/types/TurnInputItem.ts
new file mode 100644
index 000000000..d8f09b7f9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnInputItem.ts
@@ -0,0 +1,15 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { UserMessage } from "./UserMessage.js";
+import { UserToolApprovalEvent } from "./UserToolApprovalEvent.js";
+import { UserToolResponseEvent } from "./UserToolResponseEvent.js";
+
+export const TurnInputItem: core.serialization.Schema<serializers.TurnInputItem.Raw, TrueHarness.TurnInputItem> =
+ core.serialization.undiscriminatedUnion([UserMessage, UserToolApprovalEvent, UserToolResponseEvent]);
+
+export declare namespace TurnInputItem {
+ export type Raw = UserMessage.Raw | UserToolApprovalEvent.Raw | UserToolResponseEvent.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/TurnState.ts b/packages/sdk/src/serialization/types/TurnState.ts
new file mode 100644
index 000000000..fdd999f0e
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnState.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnStateCancelled } from "./TurnStateCancelled.js";
+import { TurnStateDone } from "./TurnStateDone.js";
+import { TurnStateError } from "./TurnStateError.js";
+import { TurnStateRunning } from "./TurnStateRunning.js";
+
+export const TurnState: core.serialization.Schema<serializers.TurnState.Raw, TrueHarness.TurnState> =
+ core.serialization.undiscriminatedUnion([TurnStateCancelled, TurnStateDone, TurnStateError, TurnStateRunning]);
+
+export declare namespace TurnState {
+ export type Raw = TurnStateCancelled.Raw | TurnStateDone.Raw | TurnStateError.Raw | TurnStateRunning.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/TurnStateCancelled.ts b/packages/sdk/src/serialization/types/TurnStateCancelled.ts
new file mode 100644
index 000000000..70999a8c7
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStateCancelled.ts
@@ -0,0 +1,23 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { TurnStateCancelledReason } from "./TurnStateCancelledReason.js";
+
+export const TurnStateCancelled: core.serialization.ObjectSchema<
+ serializers.TurnStateCancelled.Raw,
+ TrueHarness.TurnStateCancelled
+> = core.serialization.object({
+ completedAt: core.serialization.property("completed_at", core.serialization.string()),
+ reason: TurnStateCancelledReason,
+ status: core.serialization.stringLiteral("cancelled"),
+});
+
+export declare namespace TurnStateCancelled {
+ export interface Raw {
+ completed_at: string;
+ reason: TurnStateCancelledReason.Raw;
+ status: "cancelled";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnStateCancelledReason.ts b/packages/sdk/src/serialization/types/TurnStateCancelledReason.ts
new file mode 100644
index 000000000..ac472dff9
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStateCancelledReason.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TurnStateCancelledReason: core.serialization.Schema<
+ serializers.TurnStateCancelledReason.Raw,
+ TrueHarness.TurnStateCancelledReason
+> = core.serialization.enum_(["server-execution-timeout", "client-cancelled", "cancelled-for-next-turn", "abandoned"]);
+
+export declare namespace TurnStateCancelledReason {
+ export type Raw = "server-execution-timeout" | "client-cancelled" | "cancelled-for-next-turn" | "abandoned";
+}
diff --git a/packages/sdk/src/serialization/types/TurnStateDone.ts b/packages/sdk/src/serialization/types/TurnStateDone.ts
new file mode 100644
index 000000000..1e670d715
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStateDone.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ActionRequiredEvent } from "./ActionRequiredEvent.js";
+import { ModelMessageEvent } from "./ModelMessageEvent.js";
+
+export const TurnStateDone: core.serialization.ObjectSchema<serializers.TurnStateDone.Raw, TrueHarness.TurnStateDone> =
+ core.serialization.object({
+ completedAt: core.serialization.property("completed_at", core.serialization.string()),
+ output: ModelMessageEvent.optional(),
+ requiredActions: core.serialization.property("required_actions", core.serialization.list(ActionRequiredEvent)),
+ status: core.serialization.stringLiteral("done"),
+ });
+
+export declare namespace TurnStateDone {
+ export interface Raw {
+ completed_at: string;
+ output?: ModelMessageEvent.Raw | null;
+ required_actions: ActionRequiredEvent.Raw[];
+ status: "done";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnStateError.ts b/packages/sdk/src/serialization/types/TurnStateError.ts
new file mode 100644
index 000000000..1adf1b7e3
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStateError.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TurnStateError: core.serialization.ObjectSchema<
+ serializers.TurnStateError.Raw,
+ TrueHarness.TurnStateError
+> = core.serialization.object({
+ completedAt: core.serialization.property("completed_at", core.serialization.string()),
+ message: core.serialization.string(),
+ status: core.serialization.stringLiteral("error"),
+});
+
+export declare namespace TurnStateError {
+ export interface Raw {
+ completed_at: string;
+ message: string;
+ status: "error";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnStateRunning.ts b/packages/sdk/src/serialization/types/TurnStateRunning.ts
new file mode 100644
index 000000000..ee6f47044
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStateRunning.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const TurnStateRunning: core.serialization.ObjectSchema<
+ serializers.TurnStateRunning.Raw,
+ TrueHarness.TurnStateRunning
+> = core.serialization.object({
+ status: core.serialization.stringLiteral("running"),
+});
+
+export declare namespace TurnStateRunning {
+ export interface Raw {
+ status: "running";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/TurnStreamingEvent.ts b/packages/sdk/src/serialization/types/TurnStreamingEvent.ts
new file mode 100644
index 000000000..009153783
--- /dev/null
+++ b/packages/sdk/src/serialization/types/TurnStreamingEvent.ts
@@ -0,0 +1,51 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { McpAuthRequiredEvent } from "./McpAuthRequiredEvent.js";
+import { McpInitializeEvent } from "./McpInitializeEvent.js";
+import { ModelMessageDeltaEvent } from "./ModelMessageDeltaEvent.js";
+import { ModelMessageEvent } from "./ModelMessageEvent.js";
+import { SandboxCreatedEvent } from "./SandboxCreatedEvent.js";
+import { ThreadCreatedEvent } from "./ThreadCreatedEvent.js";
+import { ThreadDoneEvent } from "./ThreadDoneEvent.js";
+import { ToolApprovalRequiredEvent } from "./ToolApprovalRequiredEvent.js";
+import { ToolResponseEvent } from "./ToolResponseEvent.js";
+import { ToolResponseRequiredEvent } from "./ToolResponseRequiredEvent.js";
+import { TurnCreatedEvent } from "./TurnCreatedEvent.js";
+import { TurnDoneEvent } from "./TurnDoneEvent.js";
+
+export const TurnStreamingEvent: core.serialization.Schema<
+ serializers.TurnStreamingEvent.Raw,
+ TrueHarness.TurnStreamingEvent
+> = core.serialization.undiscriminatedUnion([
+ McpAuthRequiredEvent,
+ McpInitializeEvent,
+ ModelMessageEvent,
+ ModelMessageDeltaEvent,
+ SandboxCreatedEvent,
+ ThreadCreatedEvent,
+ ThreadDoneEvent,
+ ToolApprovalRequiredEvent,
+ ToolResponseEvent,
+ ToolResponseRequiredEvent,
+ TurnCreatedEvent,
+ TurnDoneEvent,
+]);
+
+export declare namespace TurnStreamingEvent {
+ export type Raw =
+ | McpAuthRequiredEvent.Raw
+ | McpInitializeEvent.Raw
+ | ModelMessageEvent.Raw
+ | ModelMessageDeltaEvent.Raw
+ | SandboxCreatedEvent.Raw
+ | ThreadCreatedEvent.Raw
+ | ThreadDoneEvent.Raw
+ | ToolApprovalRequiredEvent.Raw
+ | ToolResponseEvent.Raw
+ | ToolResponseRequiredEvent.Raw
+ | TurnCreatedEvent.Raw
+ | TurnDoneEvent.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/UserMessage.ts b/packages/sdk/src/serialization/types/UserMessage.ts
new file mode 100644
index 000000000..a3dfe46bd
--- /dev/null
+++ b/packages/sdk/src/serialization/types/UserMessage.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { UserMessageContent } from "./UserMessageContent.js";
+
+export const UserMessage: core.serialization.ObjectSchema<serializers.UserMessage.Raw, TrueHarness.UserMessage> =
+ core.serialization.object({
+ content: UserMessageContent,
+ type: core.serialization.stringLiteral("user.message"),
+ });
+
+export declare namespace UserMessage {
+ export interface Raw {
+ content: UserMessageContent.Raw;
+ type: "user.message";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/UserMessageContent.ts b/packages/sdk/src/serialization/types/UserMessageContent.ts
new file mode 100644
index 000000000..40169103d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/UserMessageContent.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { UserMessageContentItem } from "./UserMessageContentItem.js";
+
+export const UserMessageContent: core.serialization.Schema<
+ serializers.UserMessageContent.Raw,
+ TrueHarness.UserMessageContent
+> = core.serialization.undiscriminatedUnion([
+ core.serialization.string(),
+ core.serialization.list(UserMessageContentItem),
+]);
+
+export declare namespace UserMessageContent {
+ export type Raw = string | UserMessageContentItem.Raw[];
+}
diff --git a/packages/sdk/src/serialization/types/UserMessageContentItem.ts b/packages/sdk/src/serialization/types/UserMessageContentItem.ts
new file mode 100644
index 000000000..db12fede3
--- /dev/null
+++ b/packages/sdk/src/serialization/types/UserMessageContentItem.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { FileContent } from "./FileContent.js";
+import { TextContent } from "./TextContent.js";
+
+export const UserMessageContentItem: core.serialization.Schema<
+ serializers.UserMessageContentItem.Raw,
+ TrueHarness.UserMessageContentItem
+> = core.serialization.undiscriminatedUnion([FileContent, TextContent]);
+
+export declare namespace UserMessageContentItem {
+ export type Raw = FileContent.Raw | TextContent.Raw;
+}
diff --git a/packages/sdk/src/serialization/types/UserToolApprovalEvent.ts b/packages/sdk/src/serialization/types/UserToolApprovalEvent.ts
new file mode 100644
index 000000000..0b2f5531a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/UserToolApprovalEvent.ts
@@ -0,0 +1,25 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ApprovalDecision } from "./ApprovalDecision.js";
+
+export const UserToolApprovalEvent: core.serialization.ObjectSchema<
+ serializers.UserToolApprovalEvent.Raw,
+ TrueHarness.UserToolApprovalEvent
+> = core.serialization.object({
+ approval: ApprovalDecision,
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCallId: core.serialization.property("tool_call_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("user.tool_approval"),
+});
+
+export declare namespace UserToolApprovalEvent {
+ export interface Raw {
+ approval: ApprovalDecision.Raw;
+ thread_id: string;
+ tool_call_id: string;
+ type: "user.tool_approval";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/UserToolResponseEvent.ts b/packages/sdk/src/serialization/types/UserToolResponseEvent.ts
new file mode 100644
index 000000000..baefd0454
--- /dev/null
+++ b/packages/sdk/src/serialization/types/UserToolResponseEvent.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueHarness from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const UserToolResponseEvent: core.serialization.ObjectSchema<
+ serializers.UserToolResponseEvent.Raw,
+ TrueHarness.UserToolResponseEvent
+> = core.serialization.object({
+ content: core.serialization.string(),
+ threadId: core.serialization.property("thread_id", core.serialization.string()),
+ toolCallId: core.serialization.property("tool_call_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("user.tool_response"),
+});
+
+export declare namespace UserToolResponseEvent {
+ export interface Raw {
+ content: string;
+ thread_id: string;
+ tool_call_id: string;
+ type: "user.tool_response";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.ts
new file mode 100644
index 000000000..2706372a6
--- /dev/null
+++ b/packages/sdk/src/serialization/types/index.ts
@@ -0,0 +1,114 @@
+export * from "./ActionRequiredEvent.js";
+export * from "./AgentInfo.js";
+export * from "./AgentParent.js";
+export * from "./AgentSpec.js";
+export * from "./AgentSpecUserMessage.js";
+export * from "./ApprovalAllow.js";
+export * from "./ApprovalDecision.js";
+export * from "./ApprovalDeny.js";
+export * from "./AskUserQuestionsConfig.js";
+export * from "./BaseMcpAuthRequiredEvent.js";
+export * from "./BaseThreadDoneEvent.js";
+export * from "./CancelSessionResponse.js";
+export * from "./ChatCompletionChunkDeltaToolCall.js";
+export * from "./ChatCompletionChunkDeltaToolCallFunction.js";
+export * from "./ChatCompletionContentPartRefusal.js";
+export * from "./ChatCompletionContentPartText.js";
+export * from "./ChatCompletionMessageToolCall.js";
+export * from "./ChatCompletionMessageToolCallFunction.js";
+export * from "./ContextManagementConfig.js";
+export * from "./ContextManagementConfigCompaction.js";
+export * from "./DynamicSubAgentsConfig.js";
+export * from "./ExtendedChunkDeltaToolCall.js";
+export * from "./FileContent.js";
+export * from "./FinishReason.js";
+export * from "./GenerativeUiConfig.js";
+export * from "./GetCapabilitiesResponse.js";
+export * from "./GetCapabilitiesResponseData.js";
+export * from "./GetCapabilitiesResponseDataSandbox.js";
+export * from "./GetSessionResponse.js";
+export * from "./GetTurnResponse.js";
+export * from "./LargeToolResponseConfig.js";
+export * from "./ListMcpServersResponse.js";
+export * from "./ListMcpToolsResponse.js";
+export * from "./ListModelsResponse.js";
+export * from "./ListSessionEventsResponse.js";
+export * from "./ListSessionsOrder.js";
+export * from "./ListSessionsResponse.js";
+export * from "./ListSkillsResponse.js";
+export * from "./ListTurnEventsOrder.js";
+export * from "./ListTurnEventsResponse.js";
+export * from "./ListTurnsResponse.js";
+export * from "./McpAuthRequiredEvent.js";
+export * from "./McpInitializeEvent.js";
+export * from "./McpServer.js";
+export * from "./McpServerAuthInfo.js";
+export * from "./McpServerDisableToolsItem.js";
+export * from "./McpServerEnableToolsItem.js";
+export * from "./McpServerEntry.js";
+export * from "./McpServerInitInfo.js";
+export * from "./McpServerInitInfoTransportType.js";
+export * from "./McpServerPreloadToolsItem.js";
+export * from "./McpServerRequireApprovalForToolsItem.js";
+export * from "./McpToolInfo.js";
+export * from "./Model.js";
+export * from "./ModelEntry.js";
+export * from "./ModelMessageDeltaEvent.js";
+export * from "./ModelMessageEvent.js";
+export * from "./ModelMessageEventContent.js";
+export * from "./ModelMessageEventContentOneItem.js";
+export * from "./ModelMessageUsage.js";
+export * from "./ModelMessageUsageInputTokensBreakdown.js";
+export * from "./ModelParams.js";
+export * from "./PreviousTurnIdInput.js";
+export * from "./RawToolCall.js";
+export * from "./RequestErrorResponse.js";
+export * from "./RequestErrorResponseError.js";
+export * from "./ResponseFormat.js";
+export * from "./ResponseFormatJsonSchema.js";
+export * from "./ResponseFormatJsonSchemaJsonSchema.js";
+export * from "./ResponseFormatOne.js";
+export * from "./ResponseFormatZero.js";
+export * from "./RuntimeConfig.js";
+export * from "./SandboxConfig.js";
+export * from "./SandboxCreatedEvent.js";
+export * from "./SandboxNetworkPolicy.js";
+export * from "./SandboxNetworkPolicyAuthInjectItem.js";
+export * from "./SandboxNetworkPolicyAuthInjectItemAuthData.js";
+export * from "./SandboxNetworkPolicyAuthInjectItemMatch.js";
+export * from "./Session.js";
+export * from "./SessionEvent.js";
+export * from "./SessionEventItem.js";
+export * from "./SkillEntry.js";
+export * from "./SkillMount.js";
+export * from "./TextContent.js";
+export * from "./ThreadCreatedEvent.js";
+export * from "./ThreadDoneEvent.js";
+export * from "./ThreadState.js";
+export * from "./ThreadStateDone.js";
+export * from "./ThreadStateError.js";
+export * from "./TokenPagination.js";
+export * from "./ToolApprovalRequiredEvent.js";
+export * from "./ToolCall.js";
+export * from "./ToolCallRef.js";
+export * from "./ToolInfo.js";
+export * from "./ToolResponseEvent.js";
+export * from "./ToolResponseRequiredEvent.js";
+export * from "./TrueFoundrySystemToolInfo.js";
+export * from "./Turn.js";
+export * from "./TurnCreatedEvent.js";
+export * from "./TurnDoneEvent.js";
+export * from "./TurnDoneEventState.js";
+export * from "./TurnInputItem.js";
+export * from "./TurnState.js";
+export * from "./TurnStateCancelled.js";
+export * from "./TurnStateCancelledReason.js";
+export * from "./TurnStateDone.js";
+export * from "./TurnStateError.js";
+export * from "./TurnStateRunning.js";
+export * from "./TurnStreamingEvent.js";
+export * from "./UserMessage.js";
+export * from "./UserMessageContent.js";
+export * from "./UserMessageContentItem.js";
+export * from "./UserToolApprovalEvent.js";
+export * from "./UserToolResponseEvent.js";
diff --git a/packages/sdk/src/version.ts b/packages/sdk/src/version.ts
new file mode 100644
index 000000000..25f8b6cbd
--- /dev/null
+++ b/packages/sdk/src/version.ts
@@ -0,0 +1 @@
+export const SDK_VERSION = "0.0.0";
diff --git a/packages/sdk/tests/custom.test.ts b/packages/sdk/tests/custom.test.ts
new file mode 100644
index 000000000..7f5e031c8
--- /dev/null
+++ b/packages/sdk/tests/custom.test.ts
@@ -0,0 +1,13 @@
+/**
+ * This is a custom test file, if you wish to add more tests
+ * to your SDK.
+ * Be sure to mark this file in `.fernignore`.
+ *
+ * If you include example requests/responses in your fern definition,
+ * you will have tests automatically generated for you.
+ */
+describe("test", () => {
+ it("default", () => {
+ expect(true).toBe(true);
+ });
+});
diff --git a/packages/sdk/tests/mock-server/MockServer.ts b/packages/sdk/tests/mock-server/MockServer.ts
new file mode 100644
index 000000000..954872157
--- /dev/null
+++ b/packages/sdk/tests/mock-server/MockServer.ts
@@ -0,0 +1,29 @@
+import type { RequestHandlerOptions } from "msw";
+import type { SetupServer } from "msw/node";
+
+import { mockEndpointBuilder } from "./mockEndpointBuilder";
+
+export interface MockServerOptions {
+ baseUrl: string;
+ server: SetupServer;
+}
+
+export class MockServer {
+ private readonly server: SetupServer;
+ public readonly baseUrl: string;
+
+ constructor({ baseUrl, server }: MockServerOptions) {
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
+ this.server = server;
+ }
+
+ public mockEndpoint(options?: RequestHandlerOptions): ReturnType<typeof mockEndpointBuilder> {
+ const builder = mockEndpointBuilder({
+ once: options?.once ?? true,
+ onBuild: (handler) => {
+ this.server.use(handler);
+ },
+ }).baseUrl(this.baseUrl);
+ return builder;
+ }
+}
diff --git a/packages/sdk/tests/mock-server/MockServerPool.ts b/packages/sdk/tests/mock-server/MockServerPool.ts
new file mode 100644
index 000000000..d7d891a2d
--- /dev/null
+++ b/packages/sdk/tests/mock-server/MockServerPool.ts
@@ -0,0 +1,106 @@
+import { setupServer } from "msw/node";
+
+import { fromJson, toJson } from "../../src/core/json";
+import { MockServer } from "./MockServer";
+import { randomBaseUrl } from "./randomBaseUrl";
+
+const mswServer = setupServer();
+interface MockServerOptions {
+ baseUrl?: string;
+}
+
+async function formatHttpRequest(request: Request, id?: string): Promise<string> {
+ try {
+ const clone = request.clone();
+ const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n");
+
+ let body = "";
+ try {
+ const contentType = clone.headers.get("content-type");
+ if (contentType?.includes("application/json")) {
+ body = toJson(fromJson(await clone.text()), undefined, 2);
+ } else if (clone.body) {
+ body = await clone.text();
+ }
+ } catch (_e) {
+ body = "(unable to parse body)";
+ }
+
+ const title = id ? `### Request ${id} ###\n` : "";
+ const firstLine = `${title}${request.method} ${request.url.toString()} HTTP/1.1`;
+
+ return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`;
+ } catch (e) {
+ return `Error formatting request: ${e}`;
+ }
+}
+
+async function formatHttpResponse(response: Response, id?: string): Promise<string> {
+ try {
+ const clone = response.clone();
+ const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n");
+
+ let body = "";
+ try {
+ const contentType = clone.headers.get("content-type");
+ if (contentType?.includes("application/json")) {
+ body = toJson(fromJson(await clone.text()), undefined, 2);
+ } else if (clone.body) {
+ body = await clone.text();
+ }
+ } catch (_e) {
+ body = "(unable to parse body)";
+ }
+
+ const title = id ? `### Response for ${id} ###\n` : "";
+ const firstLine = `${title}HTTP/1.1 ${response.status} ${response.statusText}`;
+
+ return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`;
+ } catch (e) {
+ return `Error formatting response: ${e}`;
+ }
+}
+
+class MockServerPool {
+ private servers: MockServer[] = [];
+
+ public createServer(options?: Partial<MockServerOptions>): MockServer {
+ const baseUrl = options?.baseUrl || randomBaseUrl();
+ const server = new MockServer({ baseUrl, server: mswServer });
+ this.servers.push(server);
+ return server;
+ }
+
+ public getServers(): MockServer[] {
+ return [...this.servers];
+ }
+
+ public listen(): void {
+ const onUnhandledRequest = process.env.LOG_LEVEL === "debug" ? "warn" : "bypass";
+ mswServer.listen({ onUnhandledRequest });
+
+ if (process.env.LOG_LEVEL === "debug") {
+ mswServer.events.on("request:start", async ({ request, requestId }) => {
+ const formattedRequest = await formatHttpRequest(request, requestId);
+ console.debug(`request:start\n${formattedRequest}`);
+ });
+
+ mswServer.events.on("request:unhandled", async ({ request, requestId }) => {
+ const formattedRequest = await formatHttpRequest(request, requestId);
+ console.debug(`request:unhandled\n${formattedRequest}`);
+ });
+
+ mswServer.events.on("response:mocked", async ({ request, response, requestId }) => {
+ const formattedResponse = await formatHttpResponse(response, requestId);
+ console.debug(`response:mocked\n${formattedResponse}`);
+ });
+ }
+ }
+
+ public close(): void {
+ this.servers = [];
+ mswServer.close();
+ }
+}
+
+export const mockServerPool: MockServerPool = new MockServerPool();
diff --git a/packages/sdk/tests/mock-server/mockEndpointBuilder.ts b/packages/sdk/tests/mock-server/mockEndpointBuilder.ts
new file mode 100644
index 000000000..3e8540a3b
--- /dev/null
+++ b/packages/sdk/tests/mock-server/mockEndpointBuilder.ts
@@ -0,0 +1,234 @@
+import { type DefaultBodyType, type HttpHandler, HttpResponse, type HttpResponseResolver, http } from "msw";
+
+import { url } from "../../src/core";
+import { toJson } from "../../src/core/json";
+import { type WithFormUrlEncodedOptions, withFormUrlEncoded } from "./withFormUrlEncoded";
+import { withHeaders } from "./withHeaders";
+import { type WithJsonOptions, withJson } from "./withJson";
+
+type HttpMethod = "all" | "get" | "post" | "put" | "delete" | "patch" | "options" | "head";
+
+interface MethodStage {
+ baseUrl(baseUrl: string): MethodStage;
+ all(path: string): RequestHeadersStage;
+ get(path: string): RequestHeadersStage;
+ post(path: string): RequestHeadersStage;
+ put(path: string): RequestHeadersStage;
+ delete(path: string): RequestHeadersStage;
+ patch(path: string): RequestHeadersStage;
+ options(path: string): RequestHeadersStage;
+ head(path: string): RequestHeadersStage;
+}
+
+interface RequestHeadersStage extends RequestBodyStage, ResponseStage {
+ header(name: string, value: string): RequestHeadersStage;
+ headers(headers: Record<string, string>): RequestBodyStage;
+}
+
+interface RequestBodyStage extends ResponseStage {
+ jsonBody(body: unknown, options?: WithJsonOptions): ResponseStage;
+ formUrlEncodedBody(body: unknown, options?: WithFormUrlEncodedOptions): ResponseStage;
+}
+
+interface ResponseStage {
+ respondWith(): ResponseStatusStage;
+}
+interface ResponseStatusStage {
+ statusCode(statusCode: number): ResponseHeaderStage;
+}
+
+interface ResponseHeaderStage extends ResponseBodyStage, BuildStage {
+ header(name: string, value: string): ResponseHeaderStage;
+ headers(headers: Record<string, string>): ResponseHeaderStage;
+}
+
+interface ResponseBodyStage {
+ jsonBody(body: unknown): BuildStage;
+ sseBody(body: string): BuildStage;
+}
+
+interface BuildStage {
+ build(): HttpHandler;
+}
+
+export interface HttpHandlerBuilderOptions {
+ onBuild?: (handler: HttpHandler) => void;
+ once?: boolean;
+}
+
+class RequestBuilder implements MethodStage, RequestHeadersStage, RequestBodyStage, ResponseStage {
+ private method: HttpMethod = "get";
+ private _baseUrl: string = "";
+ private path: string = "/";
+ private readonly predicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[] = [];
+ private readonly handlerOptions?: HttpHandlerBuilderOptions;
+
+ constructor(options?: HttpHandlerBuilderOptions) {
+ this.handlerOptions = options;
+ }
+
+ baseUrl(baseUrl: string): MethodStage {
+ this._baseUrl = baseUrl;
+ return this;
+ }
+
+ all(path: string): RequestHeadersStage {
+ this.method = "all";
+ this.path = path;
+ return this;
+ }
+
+ get(path: string): RequestHeadersStage {
+ this.method = "get";
+ this.path = path;
+ return this;
+ }
+
+ post(path: string): RequestHeadersStage {
+ this.method = "post";
+ this.path = path;
+ return this;
+ }
+
+ put(path: string): RequestHeadersStage {
+ this.method = "put";
+ this.path = path;
+ return this;
+ }
+
+ delete(path: string): RequestHeadersStage {
+ this.method = "delete";
+ this.path = path;
+ return this;
+ }
+
+ patch(path: string): RequestHeadersStage {
+ this.method = "patch";
+ this.path = path;
+ return this;
+ }
+
+ options(path: string): RequestHeadersStage {
+ this.method = "options";
+ this.path = path;
+ return this;
+ }
+
+ head(path: string): RequestHeadersStage {
+ this.method = "head";
+ this.path = path;
+ return this;
+ }
+
+ header(name: string, value: string): RequestHeadersStage {
+ this.predicates.push((resolver) => withHeaders({ [name]: value }, resolver));
+ return this;
+ }
+
+ headers(headers: Record<string, string>): RequestBodyStage {
+ this.predicates.push((resolver) => withHeaders(headers, resolver));
+ return this;
+ }
+
+ jsonBody(body: unknown, options?: WithJsonOptions): ResponseStage {
+ if (body === undefined) {
+ throw new Error("Undefined is not valid JSON. Do not call jsonBody if you want an empty body.");
+ }
+ this.predicates.push((resolver) => withJson(body, resolver, options));
+ return this;
+ }
+
+ formUrlEncodedBody(body: unknown, options?: WithFormUrlEncodedOptions): ResponseStage {
+ if (body === undefined) {
+ throw new Error(
+ "Undefined is not valid for form-urlencoded. Do not call formUrlEncodedBody if you want an empty body.",
+ );
+ }
+ this.predicates.push((resolver) => withFormUrlEncoded(body, resolver, options));
+ return this;
+ }
+
+ respondWith(): ResponseStatusStage {
+ return new ResponseBuilder(this.method, this.buildUrl(), this.predicates, this.handlerOptions);
+ }
+
+ private buildUrl(): string {
+ return url.join(this._baseUrl, this.path);
+ }
+}
+
+class ResponseBuilder implements ResponseStatusStage, ResponseHeaderStage, ResponseBodyStage, BuildStage {
+ private readonly method: HttpMethod;
+ private readonly url: string;
+ private readonly requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[];
+ private readonly handlerOptions?: HttpHandlerBuilderOptions;
+
+ private responseStatusCode: number = 200;
+ private responseHeaders: Record<string, string> = {};
+ private responseBody: DefaultBodyType = undefined;
+
+ constructor(
+ method: HttpMethod,
+ url: string,
+ requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[],
+ options?: HttpHandlerBuilderOptions,
+ ) {
+ this.method = method;
+ this.url = url;
+ this.requestPredicates = requestPredicates;
+ this.handlerOptions = options;
+ }
+
+ public statusCode(code: number): ResponseHeaderStage {
+ this.responseStatusCode = code;
+ return this;
+ }
+
+ public header(name: string, value: string): ResponseHeaderStage {
+ this.responseHeaders[name] = value;
+ return this;
+ }
+
+ public headers(headers: Record<string, string>): ResponseHeaderStage {
+ this.responseHeaders = { ...this.responseHeaders, ...headers };
+ return this;
+ }
+
+ public jsonBody(body: unknown): BuildStage {
+ if (body === undefined) {
+ throw new Error("Undefined is not valid JSON. Do not call jsonBody if you expect an empty body.");
+ }
+ this.responseBody = toJson(body);
+ return this;
+ }
+
+ public sseBody(body: string): BuildStage {
+ this.responseHeaders["Content-Type"] = "text/event-stream";
+ this.responseBody = body;
+ return this;
+ }
+
+ public build(): HttpHandler {
+ const responseResolver: HttpResponseResolver = () => {
+ const response = new HttpResponse(this.responseBody, {
+ status: this.responseStatusCode,
+ headers: this.responseHeaders,
+ });
+ // if no Content-Type header is set, delete the default text content type that is set
+ if (Object.keys(this.responseHeaders).some((key) => key.toLowerCase() === "content-type") === false) {
+ response.headers.delete("Content-Type");
+ }
+ return response;
+ };
+
+ const finalResolver = this.requestPredicates.reduceRight((acc, predicate) => predicate(acc), responseResolver);
+
+ const handler = http[this.method](this.url, finalResolver, this.handlerOptions);
+ this.handlerOptions?.onBuild?.(handler);
+ return handler;
+ }
+}
+
+export function mockEndpointBuilder(options?: HttpHandlerBuilderOptions): MethodStage {
+ return new RequestBuilder(options);
+}
diff --git a/packages/sdk/tests/mock-server/randomBaseUrl.ts b/packages/sdk/tests/mock-server/randomBaseUrl.ts
new file mode 100644
index 000000000..031aa6408
--- /dev/null
+++ b/packages/sdk/tests/mock-server/randomBaseUrl.ts
@@ -0,0 +1,4 @@
+export function randomBaseUrl(): string {
+ const randomString = Math.random().toString(36).substring(2, 15);
+ return `http://${randomString}.localhost`;
+}
diff --git a/packages/sdk/tests/mock-server/setup.ts b/packages/sdk/tests/mock-server/setup.ts
new file mode 100644
index 000000000..aeb3a95af
--- /dev/null
+++ b/packages/sdk/tests/mock-server/setup.ts
@@ -0,0 +1,10 @@
+import { afterAll, beforeAll } from "vitest";
+
+import { mockServerPool } from "./MockServerPool";
+
+beforeAll(() => {
+ mockServerPool.listen();
+});
+afterAll(() => {
+ mockServerPool.close();
+});
diff --git a/packages/sdk/tests/mock-server/withFormUrlEncoded.ts b/packages/sdk/tests/mock-server/withFormUrlEncoded.ts
new file mode 100644
index 000000000..2b23448e3
--- /dev/null
+++ b/packages/sdk/tests/mock-server/withFormUrlEncoded.ts
@@ -0,0 +1,104 @@
+import { type HttpResponseResolver, passthrough } from "msw";
+
+import { toJson } from "../../src/core/json";
+
+export interface WithFormUrlEncodedOptions {
+ /**
+ * List of field names to ignore when comparing request bodies.
+ * This is useful for pagination cursor fields that change between requests.
+ */
+ ignoredFields?: string[];
+}
+
+/**
+ * Creates a request matcher that validates if the request form-urlencoded body exactly matches the expected object
+ * @param expectedBody - The exact body object to match against
+ * @param resolver - Response resolver to execute if body matches
+ * @param options - Optional configuration including fields to ignore
+ */
+export function withFormUrlEncoded(
+ expectedBody: unknown,
+ resolver: HttpResponseResolver,
+ options?: WithFormUrlEncodedOptions,
+): HttpResponseResolver {
+ const ignoredFields = options?.ignoredFields ?? [];
+ return async (args) => {
+ const { request } = args;
+
+ let clonedRequest: Request;
+ let bodyText: string | undefined;
+ let actualBody: Record<string, string>;
+ try {
+ clonedRequest = request.clone();
+ bodyText = await clonedRequest.text();
+ if (bodyText === "") {
+ // Empty body is valid if expected body is also empty
+ const isExpectedEmpty =
+ expectedBody != null &&
+ typeof expectedBody === "object" &&
+ Object.keys(expectedBody as Record<string, unknown>).length === 0;
+ if (!isExpectedEmpty) {
+ console.error("Request body is empty, expected a form-urlencoded body.");
+ return passthrough();
+ }
+ actualBody = {};
+ } else {
+ const params = new URLSearchParams(bodyText);
+ actualBody = {};
+ for (const [key, value] of params.entries()) {
+ actualBody[key] = value;
+ }
+ }
+ } catch (error) {
+ console.error(`Error processing form-urlencoded request body:\n\tError: ${error}\n\tBody: ${bodyText}`);
+ return passthrough();
+ }
+
+ const mismatches = findMismatches(actualBody, expectedBody);
+ const filteredMismatches = Object.keys(mismatches).filter((key) => !ignoredFields.includes(key));
+ if (filteredMismatches.length > 0) {
+ console.error("Form-urlencoded body mismatch:", toJson(mismatches, undefined, 2));
+ return passthrough();
+ }
+
+ return resolver(args);
+ };
+}
+
+function findMismatches(actual: any, expected: any): Record<string, { actual: any; expected: any }> {
+ const mismatches: Record<string, { actual: any; expected: any }> = {};
+
+ if (typeof actual !== typeof expected) {
+ return { value: { actual, expected } };
+ }
+
+ if (typeof actual !== "object" || actual === null || expected === null) {
+ if (actual !== expected) {
+ return { value: { actual, expected } };
+ }
+ return {};
+ }
+
+ const actualKeys = Object.keys(actual);
+ const expectedKeys = Object.keys(expected);
+
+ const allKeys = new Set([...actualKeys, ...expectedKeys]);
+
+ for (const key of allKeys) {
+ if (!expectedKeys.includes(key)) {
+ if (actual[key] === undefined) {
+ continue;
+ }
+ mismatches[key] = { actual: actual[key], expected: undefined };
+ } else if (!actualKeys.includes(key)) {
+ if (expected[key] === undefined) {
+ continue;
+ }
+ mismatches[key] = { actual: undefined, expected: expected[key] };
+ } else if (actual[key] !== expected[key]) {
+ mismatches[key] = { actual: actual[key], expected: expected[key] };
+ }
+ }
+
+ return mismatches;
+}
diff --git a/packages/sdk/tests/mock-server/withHeaders.ts b/packages/sdk/tests/mock-server/withHeaders.ts
new file mode 100644
index 000000000..6599d2b4a
--- /dev/null
+++ b/packages/sdk/tests/mock-server/withHeaders.ts
@@ -0,0 +1,70 @@
+import { type HttpResponseResolver, passthrough } from "msw";
+
+/**
+ * Creates a request matcher that validates if request headers match specified criteria
+ * @param expectedHeaders - Headers to match against
+ * @param resolver - Response resolver to execute if headers match
+ */
+export function withHeaders(
+ expectedHeaders: Record<string, string | RegExp | ((value: string) => boolean)>,
+ resolver: HttpResponseResolver,
+): HttpResponseResolver {
+ return (args) => {
+ const { request } = args;
+ const { headers } = request;
+
+ const mismatches: Record<
+ string,
+ { actual: string | null; expected: string | RegExp | ((value: string) => boolean) }
+ > = {};
+
+ for (const [key, expectedValue] of Object.entries(expectedHeaders)) {
+ const actualValue = headers.get(key);
+
+ if (actualValue === null) {
+ mismatches[key] = { actual: null, expected: expectedValue };
+ continue;
+ }
+
+ if (typeof expectedValue === "function") {
+ if (!expectedValue(actualValue)) {
+ mismatches[key] = { actual: actualValue, expected: expectedValue };
+ }
+ } else if (expectedValue instanceof RegExp) {
+ if (!expectedValue.test(actualValue)) {
+ mismatches[key] = { actual: actualValue, expected: expectedValue };
+ }
+ } else if (expectedValue !== actualValue) {
+ mismatches[key] = { actual: actualValue, expected: expectedValue };
+ }
+ }
+
+ if (Object.keys(mismatches).length > 0) {
+ const formattedMismatches = formatHeaderMismatches(mismatches);
+ console.error("Header mismatch:", formattedMismatches);
+ return passthrough();
+ }
+
+ return resolver(args);
+ };
+}
+
+function formatHeaderMismatches(
+ mismatches: Record<string, { actual: string | null; expected: string | RegExp | ((value: string) => boolean) }>,
+): Record<string, { actual: string | null; expected: string }> {
+ const formatted: Record<string, { actual: string | null; expected: string }> = {};
+
+ for (const [key, { actual, expected }] of Object.entries(mismatches)) {
+ formatted[key] = {
+ actual,
+ expected:
+ expected instanceof RegExp
+ ? expected.toString()
+ : typeof expected === "function"
+ ? "[Function]"
+ : expected,
+ };
+ }
+
+ return formatted;
+}
diff --git a/packages/sdk/tests/mock-server/withJson.ts b/packages/sdk/tests/mock-server/withJson.ts
new file mode 100644
index 000000000..3e8800a0c
--- /dev/null
+++ b/packages/sdk/tests/mock-server/withJson.ts
@@ -0,0 +1,173 @@
+import { type HttpResponseResolver, passthrough } from "msw";
+
+import { fromJson, toJson } from "../../src/core/json";
+
+export interface WithJsonOptions {
+ /**
+ * List of field names to ignore when comparing request bodies.
+ * This is useful for pagination cursor fields that change between requests.
+ */
+ ignoredFields?: string[];
+}
+
+/**
+ * Creates a request matcher that validates if the request JSON body exactly matches the expected object
+ * @param expectedBody - The exact body object to match against
+ * @param resolver - Response resolver to execute if body matches
+ * @param options - Optional configuration including fields to ignore
+ */
+export function withJson(
+ expectedBody: unknown,
+ resolver: HttpResponseResolver,
+ options?: WithJsonOptions,
+): HttpResponseResolver {
+ const ignoredFields = options?.ignoredFields ?? [];
+ return async (args) => {
+ const { request } = args;
+
+ let clonedRequest: Request;
+ let bodyText: string | undefined;
+ let actualBody: unknown;
+ try {
+ clonedRequest = request.clone();
+ bodyText = await clonedRequest.text();
+ if (bodyText === "") {
+ console.error("Request body is empty, expected a JSON object.");
+ return passthrough();
+ }
+ actualBody = fromJson(bodyText);
+ } catch (error) {
+ console.error(`Error processing request body:\n\tError: ${error}\n\tBody: ${bodyText}`);
+ return passthrough();
+ }
+
+ const mismatches = findMismatches(actualBody, expectedBody);
+ const filteredMismatches = Object.keys(mismatches).filter((key) => !ignoredFields.includes(key));
+ if (filteredMismatches.length > 0) {
+ console.error("JSON body mismatch:", toJson(mismatches, undefined, 2));
+ return passthrough();
+ }
+
+ return resolver(args);
+ };
+}
+
+function findMismatches(actual: any, expected: any): Record<string, { actual: any; expected: any }> {
+ const mismatches: Record<string, { actual: any; expected: any }> = {};
+
+ if (typeof actual !== typeof expected) {
+ if (areEquivalent(actual, expected)) {
+ return {};
+ }
+ return { value: { actual, expected } };
+ }
+
+ if (typeof actual !== "object" || actual === null || expected === null) {
+ if (actual !== expected) {
+ if (areEquivalent(actual, expected)) {
+ return {};
+ }
+ return { value: { actual, expected } };
+ }
+ return {};
+ }
+
+ if (Array.isArray(actual) && Array.isArray(expected)) {
+ if (actual.length !== expected.length) {
+ return { length: { actual: actual.length, expected: expected.length } };
+ }
+
+ const arrayMismatches: Record<string, { actual: any; expected: any }> = {};
+ for (let i = 0; i < actual.length; i++) {
+ const itemMismatches = findMismatches(actual[i], expected[i]);
+ if (Object.keys(itemMismatches).length > 0) {
+ for (const [mismatchKey, mismatchValue] of Object.entries(itemMismatches)) {
+ arrayMismatches[`[${i}]${mismatchKey === "value" ? "" : `.${mismatchKey}`}`] = mismatchValue;
+ }
+ }
+ }
+ return arrayMismatches;
+ }
+
+ const actualKeys = Object.keys(actual);
+ const expectedKeys = Object.keys(expected);
+
+ const allKeys = new Set([...actualKeys, ...expectedKeys]);
+
+ for (const key of allKeys) {
+ if (!expectedKeys.includes(key)) {
+ if (actual[key] === undefined) {
+ continue; // Skip undefined values in actual
+ }
+ mismatches[key] = { actual: actual[key], expected: undefined };
+ } else if (!actualKeys.includes(key)) {
+ if (expected[key] === undefined) {
+ continue; // Skip undefined values in expected
+ }
+ mismatches[key] = { actual: undefined, expected: expected[key] };
+ } else if (
+ typeof actual[key] === "object" &&
+ actual[key] !== null &&
+ typeof expected[key] === "object" &&
+ expected[key] !== null
+ ) {
+ const nestedMismatches = findMismatches(actual[key], expected[key]);
+ if (Object.keys(nestedMismatches).length > 0) {
+ for (const [nestedKey, nestedValue] of Object.entries(nestedMismatches)) {
+ mismatches[`${key}${nestedKey === "value" ? "" : `.${nestedKey}`}`] = nestedValue;
+ }
+ }
+ } else if (actual[key] !== expected[key]) {
+ if (areEquivalent(actual[key], expected[key])) {
+ continue;
+ }
+ mismatches[key] = { actual: actual[key], expected: expected[key] };
+ }
+ }
+
+ return mismatches;
+}
+
+function areEquivalent(actual: unknown, expected: unknown): boolean {
+ if (actual === expected) {
+ return true;
+ }
+ if (isEquivalentBigInt(actual, expected)) {
+ return true;
+ }
+ if (isEquivalentDatetime(actual, expected)) {
+ return true;
+ }
+ return false;
+}
+
+function isEquivalentBigInt(actual: unknown, expected: unknown) {
+ if (typeof actual === "number") {
+ actual = BigInt(actual);
+ }
+ if (typeof expected === "number") {
+ expected = BigInt(expected);
+ }
+ if (typeof actual === "bigint" && typeof expected === "bigint") {
+ return actual === expected;
+ }
+ return false;
+}
+
+function isEquivalentDatetime(str1: unknown, str2: unknown): boolean {
+ if (typeof str1 !== "string" || typeof str2 !== "string") {
+ return false;
+ }
+ const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;
+ if (!isoDatePattern.test(str1) || !isoDatePattern.test(str2)) {
+ return false;
+ }
+
+ try {
+ const date1 = new Date(str1).getTime();
+ const date2 = new Date(str2).getTime();
+ return date1 === date2;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/sdk/tests/setup.ts b/packages/sdk/tests/setup.ts
new file mode 100644
index 000000000..a5651f81b
--- /dev/null
+++ b/packages/sdk/tests/setup.ts
@@ -0,0 +1,80 @@
+import { expect } from "vitest";
+
+interface CustomMatchers<R = unknown> {
+ toContainHeaders(expectedHeaders: Record<string, string>): R;
+}
+
+declare module "vitest" {
+ interface Assertion<T = any> extends CustomMatchers<T> {}
+ interface AsymmetricMatchersContaining extends CustomMatchers {}
+}
+
+expect.extend({
+ toContainHeaders(actual: unknown, expectedHeaders: Record<string, string>) {
+ const isHeaders = actual instanceof Headers;
+ const isPlainObject = typeof actual === "object" && actual !== null && !Array.isArray(actual);
+
+ if (!isHeaders && !isPlainObject) {
+ throw new TypeError("Received value must be an instance of Headers or a plain object!");
+ }
+
+ if (typeof expectedHeaders !== "object" || expectedHeaders === null || Array.isArray(expectedHeaders)) {
+ throw new TypeError("Expected headers must be a plain object!");
+ }
+
+ const missingHeaders: string[] = [];
+ const mismatchedHeaders: Array<{ key: string; expected: string; actual: string | null }> = [];
+
+ for (const [key, value] of Object.entries(expectedHeaders)) {
+ let actualValue: string | null = null;
+
+ if (isHeaders) {
+ // Headers.get() is already case-insensitive
+ actualValue = (actual as Headers).get(key);
+ } else {
+ // For plain objects, do case-insensitive lookup
+ const actualObj = actual as Record<string, string>;
+ const lowerKey = key.toLowerCase();
+ const foundKey = Object.keys(actualObj).find((k) => k.toLowerCase() === lowerKey);
+ actualValue = foundKey ? actualObj[foundKey] : null;
+ }
+
+ if (actualValue === null || actualValue === undefined) {
+ missingHeaders.push(key);
+ } else if (actualValue !== value) {
+ mismatchedHeaders.push({ key, expected: value, actual: actualValue });
+ }
+ }
+
+ const pass = missingHeaders.length === 0 && mismatchedHeaders.length === 0;
+
+ const actualType = isHeaders ? "Headers" : "object";
+
+ if (pass) {
+ return {
+ message: () => `expected ${actualType} not to contain ${this.utils.printExpected(expectedHeaders)}`,
+ pass: true,
+ };
+ } else {
+ const messages: string[] = [];
+
+ if (missingHeaders.length > 0) {
+ messages.push(`Missing headers: ${this.utils.printExpected(missingHeaders.join(", "))}`);
+ }
+
+ if (mismatchedHeaders.length > 0) {
+ const mismatches = mismatchedHeaders.map(
+ ({ key, expected, actual }) =>
+ `${key}: expected ${this.utils.printExpected(expected)} but got ${this.utils.printReceived(actual)}`,
+ );
+ messages.push(mismatches.join("\n"));
+ }
+
+ return {
+ message: () =>
+ `expected ${actualType} to contain ${this.utils.printExpected(expectedHeaders)}\n\n${messages.join("\n")}`,
+ pass: false,
+ };
+ }
+ },
+});
diff --git a/packages/sdk/tests/tsconfig.json b/packages/sdk/tests/tsconfig.json
new file mode 100644
index 000000000..ac39744de
--- /dev/null
+++ b/packages/sdk/tests/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "../tsconfig.base.json",
+ "compilerOptions": {
+ "outDir": null,
+ "rootDir": "..",
+ "types": ["vitest/globals"]
+ },
+ "include": ["../src", "../tests"],
+ "exclude": []
+}
diff --git a/packages/sdk/tests/unit/fetcher/Fetcher.test.ts b/packages/sdk/tests/unit/fetcher/Fetcher.test.ts
new file mode 100644
index 000000000..6c1762422
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/Fetcher.test.ts
@@ -0,0 +1,262 @@
+import fs from "fs";
+import { join } from "path";
+import stream from "stream";
+import type { BinaryResponse } from "../../../src/core";
+import { type Fetcher, fetcherImpl } from "../../../src/core/fetcher/Fetcher";
+
+describe("Test fetcherImpl", () => {
+ it("should handle successful request", async () => {
+ const mockArgs: Fetcher.Args = {
+ url: "https://httpbin.org/post",
+ method: "POST",
+ headers: { "X-Test": "x-test-header" },
+ body: { data: "test" },
+ contentType: "application/json",
+ requestType: "json",
+ maxRetries: 0,
+ responseType: "json",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ data: "test" }), {
+ status: 200,
+ statusText: "OK",
+ }),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.body).toEqual({ data: "test" });
+ }
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ "https://httpbin.org/post",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ body: JSON.stringify({ data: "test" }),
+ }),
+ );
+ });
+
+ it("should send octet stream", async () => {
+ const url = "https://httpbin.org/post/file";
+ const mockArgs: Fetcher.Args = {
+ url,
+ method: "POST",
+ headers: { "X-Test": "x-test-header" },
+ contentType: "application/octet-stream",
+ requestType: "bytes",
+ maxRetries: 0,
+ responseType: "json",
+ body: fs.createReadStream(join(__dirname, "test-file.txt")),
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ data: "test" }), {
+ status: 200,
+ statusText: "OK",
+ }),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ body: expect.any(fs.ReadStream),
+ }),
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.body).toEqual({ data: "test" });
+ }
+ });
+
+ it("should receive file as stream", async () => {
+ const url = "https://httpbin.org/post/file";
+ const mockArgs: Fetcher.Args = {
+ url,
+ method: "GET",
+ headers: { "X-Test": "x-test-header" },
+ maxRetries: 0,
+ responseType: "binary-response",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(
+ stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream,
+ {
+ status: 200,
+ statusText: "OK",
+ },
+ ),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({
+ method: "GET",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ }),
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const body = result.body as BinaryResponse;
+ expect(body).toBeDefined();
+ expect(body.bodyUsed).toBe(false);
+ expect(typeof body.stream).toBe("function");
+ const stream = body.stream();
+ expect(stream).toBeInstanceOf(ReadableStream);
+ const readableStream = stream as ReadableStream;
+ const reader = readableStream.getReader();
+ const { value } = await reader.read();
+ const decoder = new TextDecoder();
+ const streamContent = decoder.decode(value);
+ expect(streamContent.trim()).toBe("This is a test file!");
+ expect(body.bodyUsed).toBe(true);
+ }
+ });
+
+ it("should receive file as blob", async () => {
+ const url = "https://httpbin.org/post/file";
+ const mockArgs: Fetcher.Args = {
+ url,
+ method: "GET",
+ headers: { "X-Test": "x-test-header" },
+ maxRetries: 0,
+ responseType: "binary-response",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(
+ stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream,
+ {
+ status: 200,
+ statusText: "OK",
+ },
+ ),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({
+ method: "GET",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ }),
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const body = result.body as BinaryResponse;
+ expect(body).toBeDefined();
+ expect(body.bodyUsed).toBe(false);
+ expect(typeof body.blob).toBe("function");
+ const blob = await body.blob();
+ expect(blob).toBeInstanceOf(Blob);
+ const reader = blob.stream().getReader();
+ const { value } = await reader.read();
+ const decoder = new TextDecoder();
+ const streamContent = decoder.decode(value);
+ expect(streamContent.trim()).toBe("This is a test file!");
+ expect(body.bodyUsed).toBe(true);
+ }
+ });
+
+ it("should receive file as arraybuffer", async () => {
+ const url = "https://httpbin.org/post/file";
+ const mockArgs: Fetcher.Args = {
+ url,
+ method: "GET",
+ headers: { "X-Test": "x-test-header" },
+ maxRetries: 0,
+ responseType: "binary-response",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(
+ stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream,
+ {
+ status: 200,
+ statusText: "OK",
+ },
+ ),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({
+ method: "GET",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ }),
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const body = result.body as BinaryResponse;
+ expect(body).toBeDefined();
+ expect(body.bodyUsed).toBe(false);
+ expect(typeof body.arrayBuffer).toBe("function");
+ const arrayBuffer = await body.arrayBuffer();
+ expect(arrayBuffer).toBeInstanceOf(ArrayBuffer);
+ const decoder = new TextDecoder();
+ const streamContent = decoder.decode(new Uint8Array(arrayBuffer));
+ expect(streamContent.trim()).toBe("This is a test file!");
+ expect(body.bodyUsed).toBe(true);
+ }
+ });
+
+ it("should receive file as bytes", async () => {
+ const url = "https://httpbin.org/post/file";
+ const mockArgs: Fetcher.Args = {
+ url,
+ method: "GET",
+ headers: { "X-Test": "x-test-header" },
+ maxRetries: 0,
+ responseType: "binary-response",
+ };
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(
+ stream.Readable.toWeb(fs.createReadStream(join(__dirname, "test-file.txt"))) as ReadableStream,
+ {
+ status: 200,
+ statusText: "OK",
+ },
+ ),
+ );
+
+ const result = await fetcherImpl(mockArgs);
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ url,
+ expect.objectContaining({
+ method: "GET",
+ headers: expect.toContainHeaders({ "X-Test": "x-test-header" }),
+ }),
+ );
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ const body = result.body as BinaryResponse;
+ expect(body).toBeDefined();
+ expect(body.bodyUsed).toBe(false);
+ expect(typeof body.bytes).toBe("function");
+ if (!body.bytes) {
+ return;
+ }
+ const bytes = await body.bytes();
+ expect(bytes).toBeInstanceOf(Uint8Array);
+ const decoder = new TextDecoder();
+ const streamContent = decoder.decode(bytes);
+ expect(streamContent.trim()).toBe("This is a test file!");
+ expect(body.bodyUsed).toBe(true);
+ }
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/HttpResponsePromise.test.ts b/packages/sdk/tests/unit/fetcher/HttpResponsePromise.test.ts
new file mode 100644
index 000000000..2ec008e58
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/HttpResponsePromise.test.ts
@@ -0,0 +1,143 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { HttpResponsePromise } from "../../../src/core/fetcher/HttpResponsePromise";
+import type { RawResponse, WithRawResponse } from "../../../src/core/fetcher/RawResponse";
+
+describe("HttpResponsePromise", () => {
+ const mockRawResponse: RawResponse = {
+ headers: new Headers(),
+ redirected: false,
+ status: 200,
+ statusText: "OK",
+ type: "basic" as ResponseType,
+ url: "https://example.com",
+ };
+ const mockData = { id: "123", name: "test" };
+ const mockWithRawResponse: WithRawResponse<typeof mockData> = {
+ data: mockData,
+ rawResponse: mockRawResponse,
+ };
+
+ describe("fromFunction", () => {
+ it("should create an HttpResponsePromise from a function", async () => {
+ const mockFn = vi
+ .fn<(arg1: string, arg2: string) => Promise<WithRawResponse<typeof mockData>>>()
+ .mockResolvedValue(mockWithRawResponse);
+
+ const responsePromise = HttpResponsePromise.fromFunction(mockFn, "arg1", "arg2");
+
+ const result = await responsePromise;
+ expect(result).toEqual(mockData);
+ expect(mockFn).toHaveBeenCalledWith("arg1", "arg2");
+
+ const resultWithRawResponse = await responsePromise.withRawResponse();
+ expect(resultWithRawResponse).toEqual({
+ data: mockData,
+ rawResponse: mockRawResponse,
+ });
+ });
+ });
+
+ describe("fromPromise", () => {
+ it("should create an HttpResponsePromise from a promise", async () => {
+ const promise = Promise.resolve(mockWithRawResponse);
+
+ const responsePromise = HttpResponsePromise.fromPromise(promise);
+
+ const result = await responsePromise;
+ expect(result).toEqual(mockData);
+
+ const resultWithRawResponse = await responsePromise.withRawResponse();
+ expect(resultWithRawResponse).toEqual({
+ data: mockData,
+ rawResponse: mockRawResponse,
+ });
+ });
+ });
+
+ describe("fromExecutor", () => {
+ it("should create an HttpResponsePromise from an executor function", async () => {
+ const responsePromise = HttpResponsePromise.fromExecutor((resolve) => {
+ resolve(mockWithRawResponse);
+ });
+
+ const result = await responsePromise;
+ expect(result).toEqual(mockData);
+
+ const resultWithRawResponse = await responsePromise.withRawResponse();
+ expect(resultWithRawResponse).toEqual({
+ data: mockData,
+ rawResponse: mockRawResponse,
+ });
+ });
+ });
+
+ describe("fromResult", () => {
+ it("should create an HttpResponsePromise from a result", async () => {
+ const responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse);
+
+ const result = await responsePromise;
+ expect(result).toEqual(mockData);
+
+ const resultWithRawResponse = await responsePromise.withRawResponse();
+ expect(resultWithRawResponse).toEqual({
+ data: mockData,
+ rawResponse: mockRawResponse,
+ });
+ });
+ });
+
+ describe("Promise methods", () => {
+ let responsePromise: HttpResponsePromise<typeof mockData>;
+
+ beforeEach(() => {
+ responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse);
+ });
+
+ it("should support then() method", async () => {
+ const result = await responsePromise.then((data) => ({
+ ...data,
+ modified: true,
+ }));
+
+ expect(result).toEqual({
+ ...mockData,
+ modified: true,
+ });
+ });
+
+ it("should support catch() method", async () => {
+ const errorResponsePromise = HttpResponsePromise.fromExecutor((_, reject) => {
+ reject(new Error("Test error"));
+ });
+
+ const catchSpy = vi.fn();
+ await errorResponsePromise.catch(catchSpy);
+
+ expect(catchSpy).toHaveBeenCalled();
+ const error = catchSpy.mock.calls[0]?.[0];
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toBe("Test error");
+ });
+
+ it("should support finally() method", async () => {
+ const finallySpy = vi.fn();
+ await responsePromise.finally(finallySpy);
+
+ expect(finallySpy).toHaveBeenCalled();
+ });
+ });
+
+ describe("withRawResponse", () => {
+ it("should return both data and raw response", async () => {
+ const responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse);
+
+ const result = await responsePromise.withRawResponse();
+
+ expect(result).toEqual({
+ data: mockData,
+ rawResponse: mockRawResponse,
+ });
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/RawResponse.test.ts b/packages/sdk/tests/unit/fetcher/RawResponse.test.ts
new file mode 100644
index 000000000..375ee3f38
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/RawResponse.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+
+import { toRawResponse } from "../../../src/core/fetcher/RawResponse";
+
+describe("RawResponse", () => {
+ describe("toRawResponse", () => {
+ it("should convert Response to RawResponse by removing body, bodyUsed, and ok properties", () => {
+ const mockHeaders = new Headers({ "content-type": "application/json" });
+ const mockResponse = {
+ body: "test body",
+ bodyUsed: false,
+ ok: true,
+ headers: mockHeaders,
+ redirected: false,
+ status: 200,
+ statusText: "OK",
+ type: "basic" as ResponseType,
+ url: "https://example.com",
+ };
+
+ const result = toRawResponse(mockResponse as unknown as Response);
+
+ expect("body" in result).toBe(false);
+ expect("bodyUsed" in result).toBe(false);
+ expect("ok" in result).toBe(false);
+ expect(result.headers).toBe(mockHeaders);
+ expect(result.redirected).toBe(false);
+ expect(result.status).toBe(200);
+ expect(result.statusText).toBe("OK");
+ expect(result.type).toBe("basic");
+ expect(result.url).toBe("https://example.com");
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/createRequestUrl.test.ts b/packages/sdk/tests/unit/fetcher/createRequestUrl.test.ts
new file mode 100644
index 000000000..7787e5530
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/createRequestUrl.test.ts
@@ -0,0 +1,167 @@
+import { createRequestUrl } from "../../../src/core/fetcher/createRequestUrl";
+
+describe("Test createRequestUrl", () => {
+ const BASE_URL = "https://api.example.com";
+
+ interface TestCase {
+ description: string;
+ baseUrl: string;
+ queryParams?: Record<string, any>;
+ expected: string;
+ }
+
+ const testCases: TestCase[] = [
+ {
+ description: "should return the base URL when no query parameters are provided",
+ baseUrl: BASE_URL,
+ expected: BASE_URL,
+ },
+ {
+ description: "should append simple query parameters",
+ baseUrl: BASE_URL,
+ queryParams: { key: "value", another: "param" },
+ expected: "https://api.example.com?key=value&another=param",
+ },
+ {
+ description: "should handle array query parameters",
+ baseUrl: BASE_URL,
+ queryParams: { items: ["a", "b", "c"] },
+ expected: "https://api.example.com?items=a&items=b&items=c",
+ },
+ {
+ description: "should handle object query parameters",
+ baseUrl: BASE_URL,
+ queryParams: { filter: { name: "John", age: 30 } },
+ expected: "https://api.example.com?filter%5Bname%5D=John&filter%5Bage%5D=30",
+ },
+ {
+ description: "should handle mixed types of query parameters",
+ baseUrl: BASE_URL,
+ queryParams: {
+ simple: "value",
+ array: ["x", "y"],
+ object: { key: "value" },
+ },
+ expected: "https://api.example.com?simple=value&array=x&array=y&object%5Bkey%5D=value",
+ },
+ {
+ description: "should handle empty query parameters object",
+ baseUrl: BASE_URL,
+ queryParams: {},
+ expected: BASE_URL,
+ },
+ {
+ description: "should encode special characters in query parameters",
+ baseUrl: BASE_URL,
+ queryParams: { special: "a&b=c d" },
+ expected: "https://api.example.com?special=a%26b%3Dc%20d",
+ },
+ {
+ description: "should handle numeric values",
+ baseUrl: BASE_URL,
+ queryParams: { count: 42, price: 19.99, active: 1, inactive: 0 },
+ expected: "https://api.example.com?count=42&price=19.99&active=1&inactive=0",
+ },
+ {
+ description: "should handle boolean values",
+ baseUrl: BASE_URL,
+ queryParams: { enabled: true, disabled: false },
+ expected: "https://api.example.com?enabled=true&disabled=false",
+ },
+ {
+ description: "should handle null and undefined values",
+ baseUrl: BASE_URL,
+ queryParams: {
+ valid: "value",
+ nullValue: null,
+ undefinedValue: undefined,
+ emptyString: "",
+ },
+ expected: "https://api.example.com?valid=value&emptyString=",
+ },
+ {
+ description: "should handle deeply nested objects",
+ baseUrl: BASE_URL,
+ queryParams: {
+ user: {
+ profile: {
+ name: "John",
+ settings: { theme: "dark" },
+ },
+ },
+ },
+ expected:
+ "https://api.example.com?user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark",
+ },
+ {
+ description: "should handle arrays of objects",
+ baseUrl: BASE_URL,
+ queryParams: {
+ users: [
+ { name: "John", age: 30 },
+ { name: "Jane", age: 25 },
+ ],
+ },
+ expected:
+ "https://api.example.com?users%5Bname%5D=John&users%5Bage%5D=30&users%5Bname%5D=Jane&users%5Bage%5D=25",
+ },
+ {
+ description: "should handle mixed arrays",
+ baseUrl: BASE_URL,
+ queryParams: {
+ mixed: ["string", 42, true, { key: "value" }],
+ },
+ expected: "https://api.example.com?mixed=string&mixed=42&mixed=true&mixed%5Bkey%5D=value",
+ },
+ {
+ description: "should handle empty arrays",
+ baseUrl: BASE_URL,
+ queryParams: { emptyArray: [] },
+ expected: BASE_URL,
+ },
+ {
+ description: "should handle empty objects",
+ baseUrl: BASE_URL,
+ queryParams: { emptyObject: {} },
+ expected: BASE_URL,
+ },
+ {
+ description: "should handle special characters in keys",
+ baseUrl: BASE_URL,
+ queryParams: { "key with spaces": "value", "key[with]brackets": "value" },
+ expected: "https://api.example.com?key%20with%20spaces=value&key%5Bwith%5Dbrackets=value",
+ },
+ {
+ description: "should handle URL with existing query parameters",
+ baseUrl: "https://api.example.com?existing=param",
+ queryParams: { new: "value" },
+ expected: "https://api.example.com?existing=param?new=value",
+ },
+ {
+ description: "should handle complex nested structures",
+ baseUrl: BASE_URL,
+ queryParams: {
+ filters: {
+ status: ["active", "pending"],
+ category: {
+ type: "electronics",
+ subcategories: ["phones", "laptops"],
+ },
+ },
+ sort: { field: "name", direction: "asc" },
+ },
+ expected:
+ "https://api.example.com?filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc",
+ },
+ ];
+
+ testCases.forEach(({ description, baseUrl, queryParams, expected }) => {
+ it(description, () => {
+ expect(createRequestUrl(baseUrl, queryParams)).toBe(expected);
+ });
+ });
+
+ it("should default to repeat format for arrays", () => {
+ expect(createRequestUrl(BASE_URL, { items: ["a", "b"] })).toBe("https://api.example.com?items=a&items=b");
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/getRequestBody.test.ts b/packages/sdk/tests/unit/fetcher/getRequestBody.test.ts
new file mode 100644
index 000000000..8a6c3a57e
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/getRequestBody.test.ts
@@ -0,0 +1,129 @@
+import { getRequestBody } from "../../../src/core/fetcher/getRequestBody";
+import { RUNTIME } from "../../../src/core/runtime";
+
+describe("Test getRequestBody", () => {
+ interface TestCase {
+ description: string;
+ input: any;
+ type: "json" | "form" | "file" | "bytes" | "other";
+ expected: any;
+ skipCondition?: () => boolean;
+ }
+
+ const testCases: TestCase[] = [
+ {
+ description: "should stringify body if not FormData in Node environment",
+ input: { key: "value" },
+ type: "json",
+ expected: '{"key":"value"}',
+ skipCondition: () => RUNTIME.type !== "node",
+ },
+ {
+ description: "should stringify body if not FormData in browser environment",
+ input: { key: "value" },
+ type: "json",
+ expected: '{"key":"value"}',
+ skipCondition: () => RUNTIME.type !== "browser",
+ },
+ {
+ description: "should return the Uint8Array",
+ input: new Uint8Array([1, 2, 3]),
+ type: "bytes",
+ expected: new Uint8Array([1, 2, 3]),
+ },
+ {
+ description: "should serialize objects for form-urlencoded content type",
+ input: { username: "johndoe", email: "[email protected]" },
+ type: "form",
+ expected: "username=johndoe&email=john%40example.com",
+ },
+ {
+ description: "should serialize complex nested objects and arrays for form-urlencoded content type",
+ input: {
+ user: {
+ profile: {
+ name: "John Doe",
+ settings: {
+ theme: "dark",
+ notifications: true,
+ },
+ },
+ tags: ["admin", "user"],
+ contacts: [
+ { type: "email", value: "[email protected]" },
+ { type: "phone", value: "+1234567890" },
+ ],
+ },
+ filters: {
+ status: ["active", "pending"],
+ metadata: {
+ created: "2024-01-01",
+ categories: ["electronics", "books"],
+ },
+ },
+ preferences: ["notifications", "updates"],
+ },
+ type: "form",
+ expected:
+ "user%5Bprofile%5D%5Bname%5D=John%20Doe&" +
+ "user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark&" +
+ "user%5Bprofile%5D%5Bsettings%5D%5Bnotifications%5D=true&" +
+ "user%5Btags%5D=admin&" +
+ "user%5Btags%5D=user&" +
+ "user%5Bcontacts%5D%5Btype%5D=email&" +
+ "user%5Bcontacts%5D%5Bvalue%5D=john%40example.com&" +
+ "user%5Bcontacts%5D%5Btype%5D=phone&" +
+ "user%5Bcontacts%5D%5Bvalue%5D=%2B1234567890&" +
+ "filters%5Bstatus%5D=active&" +
+ "filters%5Bstatus%5D=pending&" +
+ "filters%5Bmetadata%5D%5Bcreated%5D=2024-01-01&" +
+ "filters%5Bmetadata%5D%5Bcategories%5D=electronics&" +
+ "filters%5Bmetadata%5D%5Bcategories%5D=books&" +
+ "preferences=notifications&" +
+ "preferences=updates",
+ },
+ {
+ description: "should return the input for pre-serialized form-urlencoded strings",
+ input: "key=value&another=param",
+ type: "other",
+ expected: "key=value&another=param",
+ },
+ {
+ description: "should JSON stringify objects",
+ input: { key: "value" },
+ type: "json",
+ expected: '{"key":"value"}',
+ },
+ ];
+
+ testCases.forEach(({ description, input, type, expected, skipCondition }) => {
+ it(description, async () => {
+ if (skipCondition?.()) {
+ return;
+ }
+
+ const result = await getRequestBody({
+ body: input,
+ type,
+ });
+
+ if (input instanceof Uint8Array) {
+ expect(result).toBe(input);
+ } else {
+ expect(result).toBe(expected);
+ }
+ });
+ });
+
+ it("should return FormData in browser environment", async () => {
+ if (RUNTIME.type === "browser") {
+ const formData = new FormData();
+ formData.append("key", "value");
+ const result = await getRequestBody({
+ body: formData,
+ type: "file",
+ });
+ expect(result).toBe(formData);
+ }
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/getResponseBody.test.ts b/packages/sdk/tests/unit/fetcher/getResponseBody.test.ts
new file mode 100644
index 000000000..64ed7461e
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/getResponseBody.test.ts
@@ -0,0 +1,123 @@
+import { getResponseBody } from "../../../src/core/fetcher/getResponseBody";
+
+import { RUNTIME } from "../../../src/core/runtime";
+
+describe("Test getResponseBody", () => {
+ interface SimpleTestCase {
+ description: string;
+ responseData: string | Record<string, any>;
+ responseType?: "blob" | "sse" | "streaming" | "text";
+ expected: any;
+ skipCondition?: () => boolean;
+ }
+
+ const simpleTestCases: SimpleTestCase[] = [
+ {
+ description: "should handle text response type",
+ responseData: "test text",
+ responseType: "text",
+ expected: "test text",
+ },
+ {
+ description: "should handle JSON response",
+ responseData: { key: "value" },
+ expected: { key: "value" },
+ },
+ {
+ description: "should handle empty response",
+ responseData: "",
+ expected: undefined,
+ },
+ {
+ description: "should handle non-JSON response",
+ responseData: "invalid json",
+ expected: {
+ ok: false,
+ error: {
+ reason: "non-json",
+ statusCode: 200,
+ rawBody: "invalid json",
+ },
+ },
+ },
+ ];
+
+ simpleTestCases.forEach(({ description, responseData, responseType, expected, skipCondition }) => {
+ it(description, async () => {
+ if (skipCondition?.()) {
+ return;
+ }
+
+ const mockResponse = new Response(
+ typeof responseData === "string" ? responseData : JSON.stringify(responseData),
+ );
+ const result = await getResponseBody(mockResponse, responseType);
+ expect(result).toEqual(expected);
+ });
+ });
+
+ it("should handle blob response type", async () => {
+ const mockBlob = new Blob(["test"], { type: "text/plain" });
+ const mockResponse = new Response(mockBlob);
+ const result = await getResponseBody(mockResponse, "blob");
+ // @ts-expect-error
+ expect(result.constructor.name).toBe("Blob");
+ });
+
+ it("should handle sse response type", async () => {
+ if (RUNTIME.type === "node") {
+ const mockStream = new ReadableStream();
+ const mockResponse = new Response(mockStream);
+ const result = await getResponseBody(mockResponse, "sse");
+ expect(result).toBe(mockStream);
+ }
+ });
+
+ it("should retain a reference to the parent Response for sse responses", async () => {
+ if (RUNTIME.type === "node") {
+ const mockStream = new ReadableStream();
+ const mockResponse = new Response(mockStream);
+ const result = (await getResponseBody(mockResponse, "sse")) as ReadableStream & {
+ __fern_response_ref?: Response;
+ };
+ // Pins the parent Response so undici's FinalizationRegistry can't GC it and cancel the stream.
+ expect(result.__fern_response_ref).toBe(mockResponse);
+ // The pin must be non-enumerable so it does not leak through JSON.stringify or Object.keys.
+ const descriptor = Object.getOwnPropertyDescriptor(result, "__fern_response_ref");
+ expect(descriptor?.enumerable).toBe(false);
+ }
+ });
+
+ it("should handle streaming response type", async () => {
+ const encoder = new TextEncoder();
+ const testData = "test stream data";
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode(testData));
+ controller.close();
+ },
+ });
+
+ const mockResponse = new Response(mockStream);
+ const result = (await getResponseBody(mockResponse, "streaming")) as ReadableStream;
+
+ expect(result).toBeInstanceOf(ReadableStream);
+
+ const reader = result.getReader();
+ const decoder = new TextDecoder();
+ const { value } = await reader.read();
+ const streamContent = decoder.decode(value);
+ expect(streamContent).toBe(testData);
+ });
+
+ it("should retain a reference to the parent Response for streaming responses", async () => {
+ const mockStream = new ReadableStream();
+ const mockResponse = new Response(mockStream);
+ const result = (await getResponseBody(mockResponse, "streaming")) as ReadableStream & {
+ __fern_response_ref?: Response;
+ };
+ expect(result.__fern_response_ref).toBe(mockResponse);
+ const descriptor = Object.getOwnPropertyDescriptor(result, "__fern_response_ref");
+ expect(descriptor?.enumerable).toBe(false);
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/logging.test.ts b/packages/sdk/tests/unit/fetcher/logging.test.ts
new file mode 100644
index 000000000..366c9b6ce
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/logging.test.ts
@@ -0,0 +1,517 @@
+import { fetcherImpl } from "../../../src/core/fetcher/Fetcher";
+
+function createMockLogger() {
+ return {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+function mockSuccessResponse(data: unknown = { data: "test" }, status = 200, statusText = "OK") {
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(data), {
+ status,
+ statusText,
+ }),
+ );
+}
+
+function mockErrorResponse(data: unknown = { error: "Error" }, status = 404, statusText = "Not Found") {
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(data), {
+ status,
+ statusText,
+ }),
+ );
+}
+
+describe("Fetcher Logging Integration", () => {
+ describe("Request Logging", () => {
+ it("should log successful request at debug level", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: { test: "data" },
+ contentType: "application/json",
+ requestType: "json",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ method: "POST",
+ url: "https://example.com/api",
+ headers: expect.toContainHeaders({
+ "Content-Type": "application/json",
+ }),
+ hasBody: true,
+ }),
+ );
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "HTTP request succeeded",
+ expect.objectContaining({
+ method: "POST",
+ url: "https://example.com/api",
+ statusCode: 200,
+ }),
+ );
+ });
+
+ it("should not log debug messages at info level for successful requests", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "info",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).not.toHaveBeenCalled();
+ });
+
+ it("should log request with body flag", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "POST",
+ body: { data: "test" },
+ contentType: "application/json",
+ requestType: "json",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ hasBody: true,
+ }),
+ );
+ });
+
+ it("should log request without body flag", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ hasBody: false,
+ }),
+ );
+ });
+
+ it("should not log when silent mode is enabled", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: true,
+ },
+ });
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).not.toHaveBeenCalled();
+ expect(mockLogger.warn).not.toHaveBeenCalled();
+ expect(mockLogger.error).not.toHaveBeenCalled();
+ });
+
+ it("should not log when no logging config is provided", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ });
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("Error Logging", () => {
+ it("should log 4xx errors at error level", async () => {
+ const mockLogger = createMockLogger();
+ mockErrorResponse({ error: "Not found" }, 404, "Not Found");
+
+ const result = await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(result.ok).toBe(false);
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request failed with error status",
+ expect.objectContaining({
+ method: "GET",
+ url: "https://example.com/api",
+ statusCode: 404,
+ }),
+ );
+ });
+
+ it("should log 5xx errors at error level", async () => {
+ const mockLogger = createMockLogger();
+ mockErrorResponse({ error: "Internal error" }, 500, "Internal Server Error");
+
+ const result = await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(result.ok).toBe(false);
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request failed with error status",
+ expect.objectContaining({
+ method: "GET",
+ url: "https://example.com/api",
+ statusCode: 500,
+ }),
+ );
+ });
+
+ it("should log aborted request errors", async () => {
+ const mockLogger = createMockLogger();
+
+ const abortController = new AbortController();
+ abortController.abort();
+
+ global.fetch = vi.fn().mockRejectedValue(new Error("Aborted"));
+
+ const result = await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ abortSignal: abortController.signal,
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(result.ok).toBe(false);
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request was aborted",
+ expect.objectContaining({
+ method: "GET",
+ url: "https://example.com/api",
+ }),
+ );
+ });
+
+ it("should log timeout errors", async () => {
+ const mockLogger = createMockLogger();
+
+ const timeoutError = new Error("Request timeout");
+ timeoutError.name = "AbortError";
+
+ global.fetch = vi.fn().mockRejectedValue(timeoutError);
+
+ const result = await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(result.ok).toBe(false);
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request timed out",
+ expect.objectContaining({
+ method: "GET",
+ url: "https://example.com/api",
+ timeoutMs: undefined,
+ }),
+ );
+ });
+
+ it("should log unknown errors", async () => {
+ const mockLogger = createMockLogger();
+
+ const unknownError = new Error("Unknown error");
+
+ global.fetch = vi.fn().mockRejectedValue(unknownError);
+
+ const result = await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(result.ok).toBe(false);
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request failed with error",
+ expect.objectContaining({
+ method: "GET",
+ url: "https://example.com/api",
+ errorMessage: "Unknown error",
+ }),
+ );
+ });
+ });
+
+ describe("Logging with Redaction", () => {
+ it("should redact sensitive data in error logs", async () => {
+ const mockLogger = createMockLogger();
+ mockErrorResponse({ error: "Unauthorized" }, 401, "Unauthorized");
+
+ await fetcherImpl({
+ url: "https://example.com/api?api_key=secret",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request failed with error status",
+ expect.objectContaining({
+ url: "https://example.com/api?api_key=[REDACTED]",
+ }),
+ );
+ });
+ });
+
+ describe("Different HTTP Methods", () => {
+ it("should log GET requests", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ method: "GET",
+ }),
+ );
+ });
+
+ it("should log POST requests", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse({ data: "test" }, 201, "Created");
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "POST",
+ body: { data: "test" },
+ contentType: "application/json",
+ requestType: "json",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ method: "POST",
+ }),
+ );
+ });
+
+ it("should log PUT requests", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "PUT",
+ body: { data: "test" },
+ contentType: "application/json",
+ requestType: "json",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ method: "PUT",
+ }),
+ );
+ });
+
+ it("should log DELETE requests", async () => {
+ const mockLogger = createMockLogger();
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(null, {
+ status: 200,
+ statusText: "OK",
+ }),
+ );
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "DELETE",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ method: "DELETE",
+ }),
+ );
+ });
+ });
+
+ describe("Status Code Logging", () => {
+ it("should log 2xx success status codes", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse({ data: "test" }, 201, "Created");
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "POST",
+ body: { data: "test" },
+ contentType: "application/json",
+ requestType: "json",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "HTTP request succeeded",
+ expect.objectContaining({
+ statusCode: 201,
+ }),
+ );
+ });
+
+ it("should log 3xx redirect status codes as success", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse({ data: "test" }, 301, "Moved Permanently");
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "HTTP request succeeded",
+ expect.objectContaining({
+ statusCode: 301,
+ }),
+ );
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/makePassthroughRequest.test.ts b/packages/sdk/tests/unit/fetcher/makePassthroughRequest.test.ts
new file mode 100644
index 000000000..07cb84673
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/makePassthroughRequest.test.ts
@@ -0,0 +1,504 @@
+import type { Mock } from "vitest";
+import { makePassthroughRequest } from "../../../src/core/fetcher/makePassthroughRequest";
+
+describe("makePassthroughRequest", () => {
+ let mockFetch: Mock;
+
+ beforeEach(() => {
+ mockFetch = vi.fn();
+ mockFetch.mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 }));
+ });
+
+ describe("URL resolution", () => {
+ it("should use absolute URL directly", async () => {
+ await makePassthroughRequest("https://api.example.com/v1/users", undefined, {
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://api.example.com/v1/users");
+ });
+
+ it("should resolve relative path against baseUrl", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ baseUrl: "https://api.example.com",
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://api.example.com/v1/users");
+ });
+
+ it("should resolve relative path against environment when baseUrl is not set", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ environment: "https://env.example.com",
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://env.example.com/v1/users");
+ });
+
+ it("should prefer baseUrl over environment", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ baseUrl: "https://base.example.com",
+ environment: "https://env.example.com",
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://base.example.com/v1/users");
+ });
+
+ it("should pass relative URL through as-is when no baseUrl or environment", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("/v1/users");
+ });
+
+ it("should resolve baseUrl supplier", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ baseUrl: () => "https://dynamic.example.com",
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://dynamic.example.com/v1/users");
+ });
+
+ it("should ignore absolute URL even when baseUrl is set", async () => {
+ await makePassthroughRequest("https://other.example.com/path", undefined, {
+ baseUrl: "https://base.example.com",
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://other.example.com/path");
+ });
+
+ it("should accept a URL object", async () => {
+ await makePassthroughRequest(new URL("https://api.example.com/v1/users"), undefined, {
+ fetch: mockFetch,
+ });
+ const [calledUrl] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://api.example.com/v1/users");
+ });
+ });
+
+ describe("header merge order", () => {
+ it("should merge headers in correct priority: SDK defaults < auth < init < requestOptions", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ {
+ headers: { "X-Custom": "from-init", Authorization: "from-init" },
+ },
+ {
+ baseUrl: "https://api.example.com",
+ headers: {
+ "X-Custom": "from-sdk",
+ "X-SDK-Only": "sdk-value",
+ Authorization: "from-sdk",
+ },
+ getAuthHeaders: async () => ({
+ Authorization: "Bearer auth-token",
+ "X-Auth-Only": "auth-value",
+ }),
+ fetch: mockFetch,
+ },
+ {
+ headers: { Authorization: "from-request-options" },
+ },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ const headers = calledOptions.headers;
+
+ // requestOptions.headers wins for Authorization (highest priority)
+ expect(headers.authorization).toBe("from-request-options");
+ // init.headers wins over SDK defaults for X-Custom
+ expect(headers["x-custom"]).toBe("from-init");
+ // SDK-only header is preserved
+ expect(headers["x-sdk-only"]).toBe("sdk-value");
+ // Auth-only header is preserved
+ expect(headers["x-auth-only"]).toBe("auth-value");
+ });
+
+ it("should lowercase all header keys", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ {
+ headers: { "Content-Type": "application/json" },
+ },
+ {
+ headers: { "X-Fern-Language": "JavaScript" },
+ fetch: mockFetch,
+ },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ const headers = calledOptions.headers;
+ expect(headers["content-type"]).toBe("application/json");
+ expect(headers["x-fern-language"]).toBe("JavaScript");
+ expect(headers["Content-Type"]).toBeUndefined();
+ expect(headers["X-Fern-Language"]).toBeUndefined();
+ });
+
+ it("should handle Headers object in init", async () => {
+ const initHeaders = new Headers();
+ initHeaders.set("X-From-Headers-Object", "value");
+ await makePassthroughRequest("https://api.example.com", { headers: initHeaders }, { fetch: mockFetch });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers["x-from-headers-object"]).toBe("value");
+ });
+
+ it("should handle array-style headers in init", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { headers: [["X-Array-Header", "array-value"]] },
+ { fetch: mockFetch },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers["x-array-header"]).toBe("array-value");
+ });
+
+ it("should skip null SDK default header values", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ headers: { "X-Present": "value", "X-Null": null },
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers["x-present"]).toBe("value");
+ expect(calledOptions.headers["x-null"]).toBeUndefined();
+ });
+ });
+
+ describe("auth headers", () => {
+ it("should include auth headers when getAuthHeaders is provided", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBe("Bearer my-token");
+ });
+
+ it("should work without auth headers", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBeUndefined();
+ });
+
+ it("should allow init headers to override auth headers", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { headers: { Authorization: "Bearer override" } },
+ {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer sdk-auth" }),
+ fetch: mockFetch,
+ },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBe("Bearer override");
+ });
+ });
+
+ describe("auth header origin scoping", () => {
+ it("should attach auth headers to relative paths resolved against baseUrl", async () => {
+ await makePassthroughRequest("/v1/users", undefined, {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBe("Bearer my-token");
+ });
+
+ it("should attach auth headers to same-origin absolute URLs", async () => {
+ await makePassthroughRequest("https://api.example.com/v1/users", undefined, {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBe("Bearer my-token");
+ });
+
+ it("should attach auth headers when the absolute URL matches the environment origin", async () => {
+ await makePassthroughRequest("https://env.example.com/v1/users", undefined, {
+ environment: "https://env.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBe("Bearer my-token");
+ });
+
+ it("should NOT attach auth headers to a cross-origin absolute URL", async () => {
+ await makePassthroughRequest("https://evil.example.com/steal", undefined, {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBeUndefined();
+ });
+
+ it("should NOT attach auth headers to a cross-origin URL differing only by port", async () => {
+ await makePassthroughRequest("https://api.example.com:9999/steal", undefined, {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBeUndefined();
+ });
+
+ it("should NOT attach auth headers when no baseUrl or environment is configured", async () => {
+ await makePassthroughRequest("https://api.example.com/v1/users", undefined, {
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBeUndefined();
+ });
+
+ it("should still allow explicit init headers on cross-origin requests", async () => {
+ await makePassthroughRequest(
+ "https://evil.example.com/steal",
+ { headers: { "X-Custom": "keep-me" } },
+ {
+ baseUrl: "https://api.example.com",
+ getAuthHeaders: async () => ({ Authorization: "Bearer my-token" }),
+ fetch: mockFetch,
+ },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers.authorization).toBeUndefined();
+ expect(calledOptions.headers["x-custom"]).toBe("keep-me");
+ });
+ });
+
+ describe("method and body", () => {
+ it("should default to GET when no method specified", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.method).toBe("GET");
+ });
+
+ it("should use the method from init", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { method: "POST", body: JSON.stringify({ key: "value" }) },
+ { fetch: mockFetch },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.method).toBe("POST");
+ expect(calledOptions.body).toBe(JSON.stringify({ key: "value" }));
+ });
+
+ it("should pass body as undefined when not provided", async () => {
+ await makePassthroughRequest("https://api.example.com", { method: "GET" }, { fetch: mockFetch });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.body).toBeUndefined();
+ });
+ });
+
+ describe("timeout and retries", () => {
+ it("should use requestOptions timeout over client timeout", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ undefined,
+ { timeoutInSeconds: 30, fetch: mockFetch },
+ { timeoutInSeconds: 10 },
+ );
+ // The timeout is passed to makeRequest which converts to ms
+ // We verify via the signal timing behavior (indirectly tested through makeRequest)
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("should use client timeout when requestOptions timeout is not set", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ timeoutInSeconds: 30,
+ fetch: mockFetch,
+ });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("should use requestOptions maxRetries over client maxRetries", async () => {
+ mockFetch.mockResolvedValue(new Response("", { status: 502 }));
+ vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ await makePassthroughRequest(
+ "https://api.example.com",
+ undefined,
+ { maxRetries: 5, fetch: mockFetch },
+ { maxRetries: 1 },
+ );
+ // 1 initial + 1 retry = 2 calls
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+
+ vi.restoreAllMocks();
+ });
+ });
+
+ describe("abort signal", () => {
+ it("should use requestOptions.abortSignal over init.signal", async () => {
+ const initController = new AbortController();
+ const requestController = new AbortController();
+
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { signal: initController.signal },
+ { fetch: mockFetch },
+ { abortSignal: requestController.signal },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ // The signal passed to makeRequest is combined with timeout signal via anySignal,
+ // but the requestOptions.abortSignal should be the one that's used (not init.signal)
+ expect(calledOptions.signal).toBeDefined();
+ });
+
+ it("should use init.signal when requestOptions.abortSignal is not set", async () => {
+ const initController = new AbortController();
+
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { signal: initController.signal },
+ { fetch: mockFetch },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.signal).toBeDefined();
+ });
+ });
+
+ describe("credentials", () => {
+ it("should pass credentials include when set", async () => {
+ await makePassthroughRequest("https://api.example.com", { credentials: "include" }, { fetch: mockFetch });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.credentials).toBe("include");
+ });
+
+ it("should not pass credentials when not set to include", async () => {
+ await makePassthroughRequest(
+ "https://api.example.com",
+ { credentials: "same-origin" },
+ {
+ fetch: mockFetch,
+ },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.credentials).toBeUndefined();
+ });
+ });
+
+ describe("response", () => {
+ it("should return the Response object from fetch", async () => {
+ const mockResponse = new Response(JSON.stringify({ data: "test" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ mockFetch.mockResolvedValue(mockResponse);
+
+ const response = await makePassthroughRequest("https://api.example.com", undefined, {
+ fetch: mockFetch,
+ });
+ expect(response).toBe(mockResponse);
+ expect(response.status).toBe(200);
+ });
+
+ it("should return error responses without throwing", async () => {
+ const errorResponse = new Response("Not Found", { status: 404 });
+ mockFetch.mockResolvedValue(errorResponse);
+
+ const response = await makePassthroughRequest("https://api.example.com", undefined, {
+ fetch: mockFetch,
+ });
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe("Request object input", () => {
+ it("should extract URL from Request object", async () => {
+ const request = new Request("https://api.example.com/v1/resource", { method: "POST" });
+ await makePassthroughRequest(request, undefined, {
+ fetch: mockFetch,
+ });
+ const [calledUrl, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe("https://api.example.com/v1/resource");
+ expect(calledOptions.method).toBe("POST");
+ });
+
+ it("should extract headers from Request object when no init provided", async () => {
+ const request = new Request("https://api.example.com", {
+ headers: { "X-From-Request": "request-value" },
+ });
+ await makePassthroughRequest(request, undefined, {
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers["x-from-request"]).toBe("request-value");
+ });
+
+ it("should use explicit init over Request object properties", async () => {
+ const request = new Request("https://api.example.com", {
+ method: "POST",
+ headers: { "X-From-Request": "request-value" },
+ });
+ await makePassthroughRequest(
+ request,
+ { method: "PUT", headers: { "X-From-Init": "init-value" } },
+ { fetch: mockFetch },
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.method).toBe("PUT");
+ expect(calledOptions.headers["x-from-init"]).toBe("init-value");
+ // Request headers should NOT be present since explicit init was provided
+ expect(calledOptions.headers["x-from-request"]).toBeUndefined();
+ });
+ });
+
+ describe("SDK default header suppliers", () => {
+ it("should resolve supplier functions for SDK default headers", async () => {
+ await makePassthroughRequest("https://api.example.com", undefined, {
+ headers: {
+ "X-Static": "static-value",
+ "X-Dynamic": () => "dynamic-value",
+ },
+ fetch: mockFetch,
+ });
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.headers["x-static"]).toBe("static-value");
+ expect(calledOptions.headers["x-dynamic"]).toBe("dynamic-value");
+ });
+ });
+
+ describe("debug logging", () => {
+ it("should redact credentials in the logged request URL", async () => {
+ const mockLogger = {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+ await makePassthroughRequest("https://user:[email protected]/v1/users?token=secret", undefined, {
+ fetch: mockFetch,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ const loggedUrls = mockLogger.debug.mock.calls.map(([, meta]) => (meta as { url: string }).url);
+ expect(loggedUrls.length).toBeGreaterThan(0);
+ for (const loggedUrl of loggedUrls) {
+ expect(loggedUrl).toBe("https://[REDACTED]@api.example.com/v1/users?token=[REDACTED]");
+ expect(loggedUrl).not.toContain("password");
+ expect(loggedUrl).not.toContain("secret");
+ }
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/makeRequest.test.ts b/packages/sdk/tests/unit/fetcher/makeRequest.test.ts
new file mode 100644
index 000000000..bde194554
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/makeRequest.test.ts
@@ -0,0 +1,158 @@
+import type { Mock } from "vitest";
+import {
+ isCacheNoStoreSupported,
+ makeRequest,
+ resetCacheNoStoreSupported,
+} from "../../../src/core/fetcher/makeRequest";
+
+describe("Test makeRequest", () => {
+ const mockPostUrl = "https://httpbin.org/post";
+ const mockGetUrl = "https://httpbin.org/get";
+ const mockHeaders = { "Content-Type": "application/json" };
+ const mockBody = JSON.stringify({ key: "value" });
+
+ let mockFetch: Mock;
+
+ beforeEach(() => {
+ mockFetch = vi.fn();
+ mockFetch.mockResolvedValue(new Response(JSON.stringify({ test: "successful" }), { status: 200 }));
+ resetCacheNoStoreSupported();
+ });
+
+ it("should handle POST request correctly", async () => {
+ const response = await makeRequest(mockFetch, mockPostUrl, "POST", mockHeaders, mockBody);
+ const responseBody = await response.json();
+ expect(responseBody).toEqual({ test: "successful" });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const [calledUrl, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe(mockPostUrl);
+ expect(calledOptions).toEqual(
+ expect.objectContaining({
+ method: "POST",
+ headers: mockHeaders,
+ body: mockBody,
+ credentials: undefined,
+ }),
+ );
+ expect(calledOptions.signal).toBeDefined();
+ expect(calledOptions.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it("should handle GET request correctly", async () => {
+ const response = await makeRequest(mockFetch, mockGetUrl, "GET", mockHeaders, undefined);
+ const responseBody = await response.json();
+ expect(responseBody).toEqual({ test: "successful" });
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const [calledUrl, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledUrl).toBe(mockGetUrl);
+ expect(calledOptions).toEqual(
+ expect.objectContaining({
+ method: "GET",
+ headers: mockHeaders,
+ body: undefined,
+ credentials: undefined,
+ }),
+ );
+ expect(calledOptions.signal).toBeDefined();
+ expect(calledOptions.signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it("should not include cache option when disableCache is not set", async () => {
+ await makeRequest(mockFetch, mockGetUrl, "GET", mockHeaders, undefined);
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.cache).toBeUndefined();
+ });
+
+ it("should not include cache option when disableCache is false", async () => {
+ await makeRequest(
+ mockFetch,
+ mockGetUrl,
+ "GET",
+ mockHeaders,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ false,
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.cache).toBeUndefined();
+ });
+
+ it("should include cache: no-store when disableCache is true and runtime supports it", async () => {
+ // In Node.js test environment, Request supports the cache option
+ expect(isCacheNoStoreSupported()).toBe(true);
+ await makeRequest(
+ mockFetch,
+ mockGetUrl,
+ "GET",
+ mockHeaders,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ true,
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.cache).toBe("no-store");
+ });
+
+ it("should cache the result of isCacheNoStoreSupported", () => {
+ const first = isCacheNoStoreSupported();
+ const second = isCacheNoStoreSupported();
+ expect(first).toBe(second);
+ });
+
+ it("should reset cache detection state with resetCacheNoStoreSupported", () => {
+ // First call caches the result
+ const first = isCacheNoStoreSupported();
+ expect(first).toBe(true);
+
+ // Reset clears the cache
+ resetCacheNoStoreSupported();
+
+ // After reset, it should re-detect (and still return true in Node.js)
+ const second = isCacheNoStoreSupported();
+ expect(second).toBe(true);
+ });
+
+ it("should not include cache option when runtime does not support it (e.g. Cloudflare Workers)", async () => {
+ // Mock Request constructor to throw when cache option is passed,
+ // simulating runtimes like Cloudflare Workers
+ const OriginalRequest = globalThis.Request;
+ globalThis.Request = class MockRequest {
+ constructor(_url: string, init?: RequestInit) {
+ if (init?.cache != null) {
+ throw new TypeError("The 'cache' field on 'RequestInitializerDict' is not implemented.");
+ }
+ }
+ } as unknown as typeof Request;
+
+ try {
+ // Reset so the detection runs fresh with the mocked Request
+ resetCacheNoStoreSupported();
+ expect(isCacheNoStoreSupported()).toBe(false);
+
+ await makeRequest(
+ mockFetch,
+ mockGetUrl,
+ "GET",
+ mockHeaders,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ true,
+ );
+ const [, calledOptions] = mockFetch.mock.calls[0];
+ expect(calledOptions.cache).toBeUndefined();
+ } finally {
+ // Restore original Request
+ globalThis.Request = OriginalRequest;
+ resetCacheNoStoreSupported();
+ }
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/redacting.test.ts b/packages/sdk/tests/unit/fetcher/redacting.test.ts
new file mode 100644
index 000000000..685f1ddaf
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/redacting.test.ts
@@ -0,0 +1,1221 @@
+import { fetcherImpl } from "../../../src/core/fetcher/Fetcher";
+
+function createMockLogger() {
+ return {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+function mockSuccessResponse(data: unknown = { data: "test" }, status = 200, statusText = "OK") {
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(data), {
+ status,
+ statusText,
+ }),
+ );
+}
+
+describe("Redacting Logic", () => {
+ describe("Header Redaction", () => {
+ it("should redact authorization header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { Authorization: "Bearer secret-token-12345" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ Authorization: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact api-key header (case-insensitive)", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "X-API-KEY": "secret-api-key" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "X-API-KEY": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact cookie header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { Cookie: "session=abc123; token=xyz789" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ Cookie: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact x-auth-token header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "x-auth-token": "auth-token-12345" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "x-auth-token": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact proxy-authorization header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "Proxy-Authorization": "Basic credentials" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "Proxy-Authorization": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact x-csrf-token header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "X-CSRF-Token": "csrf-token-abc" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "X-CSRF-Token": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact www-authenticate header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "WWW-Authenticate": "Bearer realm=example" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "WWW-Authenticate": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact x-session-token header", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: { "X-Session-Token": "session-token-xyz" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "X-Session-Token": "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should not redact non-sensitive headers", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ "User-Agent": "Test/1.0",
+ Accept: "application/json",
+ },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ "Content-Type": "application/json",
+ "User-Agent": "Test/1.0",
+ Accept: "application/json",
+ }),
+ }),
+ );
+ });
+
+ it("should redact multiple sensitive headers at once", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ headers: {
+ Authorization: "Bearer token",
+ "X-API-Key": "api-key",
+ Cookie: "session=123",
+ "Content-Type": "application/json",
+ },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ headers: expect.toContainHeaders({
+ Authorization: "[REDACTED]",
+ "X-API-Key": "[REDACTED]",
+ Cookie: "[REDACTED]",
+ "Content-Type": "application/json",
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("Response Header Redaction", () => {
+ it("should redact Set-Cookie in response headers", async () => {
+ const mockLogger = createMockLogger();
+
+ const mockHeaders = new Headers();
+ mockHeaders.set("Set-Cookie", "session=abc123; HttpOnly; Secure");
+ mockHeaders.set("Content-Type", "application/json");
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ data: "test" }), {
+ status: 200,
+ statusText: "OK",
+ headers: mockHeaders,
+ }),
+ );
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "HTTP request succeeded",
+ expect.objectContaining({
+ responseHeaders: expect.toContainHeaders({
+ "set-cookie": "[REDACTED]",
+ "content-type": "application/json",
+ }),
+ }),
+ );
+ });
+
+ it("should redact authorization in response headers", async () => {
+ const mockLogger = createMockLogger();
+
+ const mockHeaders = new Headers();
+ mockHeaders.set("Authorization", "Bearer token-123");
+ mockHeaders.set("Content-Type", "application/json");
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ data: "test" }), {
+ status: 200,
+ statusText: "OK",
+ headers: mockHeaders,
+ }),
+ );
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "HTTP request succeeded",
+ expect.objectContaining({
+ responseHeaders: expect.toContainHeaders({
+ authorization: "[REDACTED]",
+ "content-type": "application/json",
+ }),
+ }),
+ );
+ });
+
+ it("should redact response headers in error responses", async () => {
+ const mockLogger = createMockLogger();
+
+ const mockHeaders = new Headers();
+ mockHeaders.set("WWW-Authenticate", "Bearer realm=example");
+ mockHeaders.set("Content-Type", "application/json");
+
+ global.fetch = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ error: "Unauthorized" }), {
+ status: 401,
+ statusText: "Unauthorized",
+ headers: mockHeaders,
+ }),
+ );
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "error",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.error).toHaveBeenCalledWith(
+ "HTTP request failed with error status",
+ expect.objectContaining({
+ responseHeaders: expect.toContainHeaders({
+ "www-authenticate": "[REDACTED]",
+ "content-type": "application/json",
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("Query Parameter Redaction", () => {
+ it("should redact api_key query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { api_key: "secret-key" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ api_key: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact token query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { token: "secret-token" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ token: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact access_token query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { access_token: "secret-access-token" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ access_token: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact password query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { password: "secret-password" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ password: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact secret query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { secret: "secret-value" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ secret: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should redact session_id query parameter", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { session_id: "session-123" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ session_id: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+
+ it("should not redact non-sensitive query parameters", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: {
+ page: "1",
+ limit: "10",
+ sort: "name",
+ },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ page: "1",
+ limit: "10",
+ sort: "name",
+ }),
+ }),
+ );
+ });
+
+ it("should not redact parameters containing 'auth' substring like 'author'", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: {
+ author: "john",
+ authenticate: "false",
+ authorization_level: "user",
+ },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ author: "john",
+ authenticate: "false",
+ authorization_level: "user",
+ }),
+ }),
+ );
+ });
+
+ it("should handle undefined query parameters", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: undefined,
+ }),
+ );
+ });
+
+ it("should redact case-insensitive query parameters", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryParameters: { API_KEY: "secret-key", Token: "secret-token" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ queryParameters: expect.objectContaining({
+ API_KEY: "[REDACTED]",
+ Token: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("Query String Redaction", () => {
+ it("should redact api_key in queryString via URL", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryString: "api_key=secret-key&page=1",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?api_key=[REDACTED]&page=1",
+ }),
+ );
+ });
+
+ it("should redact multiple sensitive params in queryString", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryString: "token=t&password=p&page=1",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?token=[REDACTED]&password=[REDACTED]&page=1",
+ }),
+ );
+ });
+
+ it("should not redact non-sensitive params in queryString", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryString: "page=1&limit=10&sort=name",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?page=1&limit=10&sort=name",
+ }),
+ );
+ });
+
+ it("should prefer queryString over queryParameters when both provided", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ queryString: "page=1",
+ queryParameters: { api_key: "secret-key" },
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?page=1",
+ queryParameters: expect.objectContaining({
+ api_key: "[REDACTED]",
+ }),
+ }),
+ );
+ });
+ });
+
+ describe("URL Redaction", () => {
+ it("should redact credentials in URL", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://user:[email protected]/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://[REDACTED]@example.com/api",
+ }),
+ );
+ });
+
+ it("should redact api_key in query string", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?api_key=secret-key&page=1",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?api_key=[REDACTED]&page=1",
+ }),
+ );
+ });
+
+ it("should redact token in query string", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?token=secret-token",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?token=[REDACTED]",
+ }),
+ );
+ });
+
+ it("should redact password in query string", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?username=user&password=secret",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?username=user&password=[REDACTED]",
+ }),
+ );
+ });
+
+ it("should not redact non-sensitive query strings", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?page=1&limit=10&sort=name",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?page=1&limit=10&sort=name",
+ }),
+ );
+ });
+
+ it("should not redact URL parameters containing 'auth' substring like 'author'", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?author=john&authenticate=false&page=1",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?author=john&authenticate=false&page=1",
+ }),
+ );
+ });
+
+ it("should handle URL with fragment", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?token=secret#section",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?token=[REDACTED]#section",
+ }),
+ );
+ });
+
+ it("should redact URL-encoded query parameters", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?api%5Fkey=secret",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?api%5Fkey=[REDACTED]",
+ }),
+ );
+ });
+
+ it("should handle URL without query string", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api",
+ }),
+ );
+ });
+
+ it("should handle empty query string", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?",
+ }),
+ );
+ });
+
+ it("should redact multiple sensitive parameters in URL", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?api_key=secret1&token=secret2&page=1",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?api_key=[REDACTED]&token=[REDACTED]&page=1",
+ }),
+ );
+ });
+
+ it("should redact both credentials and query parameters", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://user:[email protected]/api?token=secret",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://[REDACTED]@example.com/api?token=[REDACTED]",
+ }),
+ );
+ });
+
+ it("should use fast path for URLs without sensitive keywords", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?page=1&limit=10&sort=name&filter=value",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?page=1&limit=10&sort=name&filter=value",
+ }),
+ );
+ });
+
+ it("should handle query parameter without value", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/api?flag&token=secret",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/api?flag&token=[REDACTED]",
+ }),
+ );
+ });
+
+ it("should handle URL with multiple @ symbols in credentials", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://[REDACTED]@host.com/api",
+ }),
+ );
+ });
+
+ it("should handle URL with @ in query parameter but not in credentials", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://example.com/[email protected]",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://example.com/[email protected]",
+ }),
+ );
+ });
+
+ it("should handle URL with both credentials and @ in path", async () => {
+ const mockLogger = createMockLogger();
+ mockSuccessResponse();
+
+ await fetcherImpl({
+ url: "https://user:[email protected]/users/@username",
+ method: "GET",
+ responseType: "json",
+ maxRetries: 0,
+ logging: {
+ level: "debug",
+ logger: mockLogger,
+ silent: false,
+ },
+ });
+
+ expect(mockLogger.debug).toHaveBeenCalledWith(
+ "Making HTTP request",
+ expect.objectContaining({
+ url: "https://[REDACTED]@example.com/users/@username",
+ }),
+ );
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/requestWithRetries.test.ts b/packages/sdk/tests/unit/fetcher/requestWithRetries.test.ts
new file mode 100644
index 000000000..7c98c0abf
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/requestWithRetries.test.ts
@@ -0,0 +1,282 @@
+import type { Mock, MockInstance } from "vitest";
+import { requestWithRetries } from "../../../src/core/fetcher/requestWithRetries";
+
+describe("requestWithRetries", () => {
+ let mockFetch: Mock;
+ let originalMathRandom: typeof Math.random;
+ let setTimeoutSpy: MockInstance;
+
+ beforeEach(() => {
+ mockFetch = vi.fn();
+ originalMathRandom = Math.random;
+
+ Math.random = vi.fn(() => 0.5);
+
+ vi.useFakeTimers({
+ toFake: [
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "setImmediate",
+ "clearImmediate",
+ "Date",
+ "performance",
+ "requestAnimationFrame",
+ "cancelAnimationFrame",
+ "requestIdleCallback",
+ "cancelIdleCallback",
+ ],
+ });
+ });
+
+ afterEach(() => {
+ Math.random = originalMathRandom;
+ vi.clearAllMocks();
+ vi.clearAllTimers();
+ });
+
+ it("should retry on retryable status codes (legacy mode)", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ const retryableStatuses = [408, 429, 500, 501, 502, 503, 504, 505];
+ let callCount = 0;
+
+ mockFetch.mockImplementation(async () => {
+ if (callCount < retryableStatuses.length) {
+ return new Response("", { status: retryableStatuses[callCount++] });
+ }
+ return new Response("", { status: 200 });
+ });
+
+ const responsePromise = requestWithRetries(() => mockFetch(), retryableStatuses.length);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(retryableStatuses.length + 1);
+ expect(response.status).toBe(200);
+ });
+
+ it("should retry on 500 Internal Server Error in legacy mode", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(new Response("", { status: 500 }))
+ .mockResolvedValueOnce(new Response("", { status: 200 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 3);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(response.status).toBe(200);
+ });
+
+ it("should respect maxRetries limit", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ const maxRetries = 2;
+ mockFetch.mockResolvedValue(new Response("", { status: 503 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), maxRetries);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(maxRetries + 1);
+ expect(response.status).toBe(503);
+ });
+
+ it("should retry on status 599 (upper boundary of retryable 5xx in legacy mode)", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(new Response("", { status: 599 }))
+ .mockResolvedValueOnce(new Response("", { status: 200 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 3);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(response.status).toBe(200);
+ });
+
+ it("should not retry on non-retryable client error (400)", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch.mockResolvedValueOnce(new Response("", { status: 400 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 3);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(response.status).toBe(400);
+ });
+
+ it("should not retry on success status codes", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ const successStatuses = [200, 201, 202];
+
+ for (const status of successStatuses) {
+ mockFetch.mockReset();
+ setTimeoutSpy.mockClear();
+ mockFetch.mockResolvedValueOnce(new Response("", { status }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 3);
+ await vi.runAllTimersAsync();
+ await responsePromise;
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ expect(setTimeoutSpy).not.toHaveBeenCalled();
+ }
+ });
+
+ interface RetryHeaderTestCase {
+ description: string;
+ headerName: string;
+ headerValue: string | (() => string);
+ expectedDelayMin: number;
+ expectedDelayMax: number;
+ }
+
+ const retryHeaderTests: RetryHeaderTestCase[] = [
+ {
+ description: "should respect retry-after header with seconds value",
+ headerName: "retry-after",
+ headerValue: "5",
+ expectedDelayMin: 4000,
+ expectedDelayMax: 6000,
+ },
+ {
+ description: "should respect retry-after header with HTTP date value",
+ headerName: "retry-after",
+ headerValue: () => new Date(Date.now() + 3000).toUTCString(),
+ expectedDelayMin: 2000,
+ expectedDelayMax: 4000,
+ },
+ {
+ description: "should respect x-ratelimit-reset header",
+ headerName: "x-ratelimit-reset",
+ headerValue: () => Math.floor((Date.now() + 4000) / 1000).toString(),
+ expectedDelayMin: 3000,
+ expectedDelayMax: 6000,
+ },
+ ];
+
+ retryHeaderTests.forEach(({ description, headerName, headerValue, expectedDelayMin, expectedDelayMax }) => {
+ it(description, async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ const value = typeof headerValue === "function" ? headerValue() : headerValue;
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response("", {
+ status: 429,
+ headers: new Headers({ [headerName]: value }),
+ }),
+ )
+ .mockResolvedValueOnce(new Response("", { status: 200 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 1);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), expect.any(Number));
+ const actualDelay = setTimeoutSpy.mock.calls[0][1];
+ expect(actualDelay).toBeGreaterThan(expectedDelayMin);
+ expect(actualDelay).toBeLessThan(expectedDelayMax);
+ expect(response.status).toBe(200);
+ });
+ });
+
+ it("should apply correct exponential backoff with jitter", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch.mockResolvedValue(new Response("", { status: 502 }));
+ const maxRetries = 3;
+ const expectedDelays = [1000, 2000, 4000];
+
+ const responsePromise = requestWithRetries(() => mockFetch(), maxRetries);
+ await vi.runAllTimersAsync();
+ await responsePromise;
+
+ expect(setTimeoutSpy).toHaveBeenCalledTimes(expectedDelays.length);
+
+ expectedDelays.forEach((delay, index) => {
+ expect(setTimeoutSpy).toHaveBeenNthCalledWith(index + 1, expect.any(Function), delay);
+ });
+
+ expect(mockFetch).toHaveBeenCalledTimes(maxRetries + 1);
+ });
+
+ it("should handle concurrent retries independently", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(new Response("", { status: 502 }))
+ .mockResolvedValueOnce(new Response("", { status: 502 }))
+ .mockResolvedValueOnce(new Response("", { status: 200 }))
+ .mockResolvedValueOnce(new Response("", { status: 200 }));
+
+ const promise1 = requestWithRetries(() => mockFetch(), 1);
+ const promise2 = requestWithRetries(() => mockFetch(), 1);
+
+ await vi.runAllTimersAsync();
+ const [response1, response2] = await Promise.all([promise1, promise2]);
+
+ expect(response1.status).toBe(200);
+ expect(response2.status).toBe(200);
+ });
+
+ it("should cap delay at MAX_RETRY_DELAY for large header values", async () => {
+ setTimeoutSpy = vi.spyOn(global, "setTimeout").mockImplementation((callback: (args: void) => void) => {
+ process.nextTick(callback);
+ return null as any;
+ });
+
+ mockFetch
+ .mockResolvedValueOnce(
+ new Response("", {
+ status: 429,
+ headers: new Headers({ "retry-after": "120" }), // 120 seconds = 120000ms > MAX_RETRY_DELAY (60000ms)
+ }),
+ )
+ .mockResolvedValueOnce(new Response("", { status: 200 }));
+
+ const responsePromise = requestWithRetries(() => mockFetch(), 1);
+ await vi.runAllTimersAsync();
+ const response = await responsePromise;
+
+ expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 60000);
+ expect(response.status).toBe(200);
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/signals.test.ts b/packages/sdk/tests/unit/fetcher/signals.test.ts
new file mode 100644
index 000000000..c71761723
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/signals.test.ts
@@ -0,0 +1,114 @@
+import { anySignal, getTimeoutSignal } from "../../../src/core/fetcher/signals";
+
+describe("Test getTimeoutSignal", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("should return an object with signal and abortId", () => {
+ const { signal, abortId } = getTimeoutSignal(1000);
+
+ expect(signal).toBeDefined();
+ expect(abortId).toBeDefined();
+ expect(signal).toBeInstanceOf(AbortSignal);
+ expect(signal.aborted).toBe(false);
+ });
+
+ it("should create a signal that aborts after the specified timeout", () => {
+ const timeoutMs = 5000;
+ const { signal } = getTimeoutSignal(timeoutMs);
+
+ expect(signal.aborted).toBe(false);
+
+ vi.advanceTimersByTime(timeoutMs - 1);
+ expect(signal.aborted).toBe(false);
+
+ vi.advanceTimersByTime(1);
+ expect(signal.aborted).toBe(true);
+ });
+});
+
+describe("Test anySignal", () => {
+ it("should return an AbortSignal", () => {
+ const signal = anySignal(new AbortController().signal);
+ expect(signal).toBeInstanceOf(AbortSignal);
+ });
+
+ it("should abort when any of the input signals is aborted", () => {
+ const controller1 = new AbortController();
+ const controller2 = new AbortController();
+ const signal = anySignal(controller1.signal, controller2.signal);
+
+ expect(signal.aborted).toBe(false);
+ controller1.abort();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it("should handle an array of signals", () => {
+ const controller1 = new AbortController();
+ const controller2 = new AbortController();
+ const signal = anySignal([controller1.signal, controller2.signal]);
+
+ expect(signal.aborted).toBe(false);
+ controller2.abort();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it("should abort immediately if one of the input signals is already aborted", () => {
+ const controller1 = new AbortController();
+ const controller2 = new AbortController();
+ controller1.abort();
+
+ const signal = anySignal(controller1.signal, controller2.signal);
+ expect(signal.aborted).toBe(true);
+ });
+
+ it("should detect a signal that aborts between the initial aborted check and the event listener registration", () => {
+ const ctrlA = new AbortController();
+ const ctrlB = new AbortController();
+
+ const originalAddEventListener = ctrlA.signal.addEventListener.bind(ctrlA.signal);
+ const originalRemoveEventListener = ctrlA.signal.removeEventListener.bind(ctrlA.signal);
+
+ let abortedAccessCount = 0;
+ const proxy = new Proxy(ctrlA.signal, {
+ get(target, prop, receiver) {
+ if (prop === "aborted") {
+ abortedAccessCount++;
+ if (abortedAccessCount === 1) return false;
+ return Reflect.get(target, prop, receiver);
+ }
+ if (prop === "addEventListener") {
+ return (...args: Parameters<typeof originalAddEventListener>) => {
+ if (abortedAccessCount >= 1 && args[0] === "abort") {
+ ctrlA.abort("too-late");
+ }
+ return originalAddEventListener(...args);
+ };
+ }
+ if (prop === "removeEventListener") {
+ return originalRemoveEventListener;
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ });
+
+ const combined = anySignal(proxy, ctrlB.signal);
+
+ expect(combined.aborted).toBe(true);
+ expect(combined.reason).toBe("too-late");
+ });
+
+ it("should forward the abort reason from a source signal", () => {
+ const controller = new AbortController();
+ const combined = anySignal(controller.signal);
+
+ controller.abort("test-reason");
+ expect(combined.aborted).toBe(true);
+ expect(combined.reason).toBe("test-reason");
+ });
+});
diff --git a/packages/sdk/tests/unit/fetcher/test-file.txt b/packages/sdk/tests/unit/fetcher/test-file.txt
new file mode 100644
index 000000000..c66d471e3
--- /dev/null
+++ b/packages/sdk/tests/unit/fetcher/test-file.txt
@@ -0,0 +1 @@
+This is a test file!
diff --git a/packages/sdk/tests/unit/logging/logger.test.ts b/packages/sdk/tests/unit/logging/logger.test.ts
new file mode 100644
index 000000000..2e0b5fe50
--- /dev/null
+++ b/packages/sdk/tests/unit/logging/logger.test.ts
@@ -0,0 +1,454 @@
+import { ConsoleLogger, createLogger, Logger, LogLevel } from "../../../src/core/logging/logger";
+
+function createMockLogger() {
+ return {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ };
+}
+
+describe("Logger", () => {
+ describe("LogLevel", () => {
+ it("should have correct log levels", () => {
+ expect(LogLevel.Debug).toBe("debug");
+ expect(LogLevel.Info).toBe("info");
+ expect(LogLevel.Warn).toBe("warn");
+ expect(LogLevel.Error).toBe("error");
+ });
+ });
+
+ describe("ConsoleLogger", () => {
+ let consoleLogger: ConsoleLogger;
+ let consoleSpy: {
+ debug: ReturnType<typeof vi.spyOn>;
+ info: ReturnType<typeof vi.spyOn>;
+ warn: ReturnType<typeof vi.spyOn>;
+ error: ReturnType<typeof vi.spyOn>;
+ };
+
+ beforeEach(() => {
+ consoleLogger = new ConsoleLogger();
+ consoleSpy = {
+ debug: vi.spyOn(console, "debug").mockImplementation(() => {}),
+ info: vi.spyOn(console, "info").mockImplementation(() => {}),
+ warn: vi.spyOn(console, "warn").mockImplementation(() => {}),
+ error: vi.spyOn(console, "error").mockImplementation(() => {}),
+ };
+ });
+
+ afterEach(() => {
+ consoleSpy.debug.mockRestore();
+ consoleSpy.info.mockRestore();
+ consoleSpy.warn.mockRestore();
+ consoleSpy.error.mockRestore();
+ });
+
+ it("should log debug messages", () => {
+ consoleLogger.debug("debug message", { data: "test" });
+ expect(consoleSpy.debug).toHaveBeenCalledWith("debug message", { data: "test" });
+ });
+
+ it("should log info messages", () => {
+ consoleLogger.info("info message", { data: "test" });
+ expect(consoleSpy.info).toHaveBeenCalledWith("info message", { data: "test" });
+ });
+
+ it("should log warn messages", () => {
+ consoleLogger.warn("warn message", { data: "test" });
+ expect(consoleSpy.warn).toHaveBeenCalledWith("warn message", { data: "test" });
+ });
+
+ it("should log error messages", () => {
+ consoleLogger.error("error message", { data: "test" });
+ expect(consoleSpy.error).toHaveBeenCalledWith("error message", { data: "test" });
+ });
+
+ it("should handle multiple arguments", () => {
+ consoleLogger.debug("message", "arg1", "arg2", { key: "value" });
+ expect(consoleSpy.debug).toHaveBeenCalledWith("message", "arg1", "arg2", { key: "value" });
+ });
+ });
+
+ describe("Logger with level filtering", () => {
+ let mockLogger: {
+ debug: ReturnType<typeof vi.fn>;
+ info: ReturnType<typeof vi.fn>;
+ warn: ReturnType<typeof vi.fn>;
+ error: ReturnType<typeof vi.fn>;
+ };
+
+ beforeEach(() => {
+ mockLogger = createMockLogger();
+ });
+
+ describe("Debug level", () => {
+ it("should log all levels when set to debug", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("debug");
+ logger.info("info");
+ logger.warn("warn");
+ logger.error("error");
+
+ expect(mockLogger.debug).toHaveBeenCalledWith("debug");
+ expect(mockLogger.info).toHaveBeenCalledWith("info");
+ expect(mockLogger.warn).toHaveBeenCalledWith("warn");
+ expect(mockLogger.error).toHaveBeenCalledWith("error");
+ });
+
+ it("should report correct level checks", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger.isDebug()).toBe(true);
+ expect(logger.isInfo()).toBe(true);
+ expect(logger.isWarn()).toBe(true);
+ expect(logger.isError()).toBe(true);
+ });
+ });
+
+ describe("Info level", () => {
+ it("should log info, warn, and error when set to info", () => {
+ const logger = new Logger({
+ level: LogLevel.Info,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("debug");
+ logger.info("info");
+ logger.warn("warn");
+ logger.error("error");
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).toHaveBeenCalledWith("info");
+ expect(mockLogger.warn).toHaveBeenCalledWith("warn");
+ expect(mockLogger.error).toHaveBeenCalledWith("error");
+ });
+
+ it("should report correct level checks", () => {
+ const logger = new Logger({
+ level: LogLevel.Info,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger.isDebug()).toBe(false);
+ expect(logger.isInfo()).toBe(true);
+ expect(logger.isWarn()).toBe(true);
+ expect(logger.isError()).toBe(true);
+ });
+ });
+
+ describe("Warn level", () => {
+ it("should log warn and error when set to warn", () => {
+ const logger = new Logger({
+ level: LogLevel.Warn,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("debug");
+ logger.info("info");
+ logger.warn("warn");
+ logger.error("error");
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).not.toHaveBeenCalled();
+ expect(mockLogger.warn).toHaveBeenCalledWith("warn");
+ expect(mockLogger.error).toHaveBeenCalledWith("error");
+ });
+
+ it("should report correct level checks", () => {
+ const logger = new Logger({
+ level: LogLevel.Warn,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger.isDebug()).toBe(false);
+ expect(logger.isInfo()).toBe(false);
+ expect(logger.isWarn()).toBe(true);
+ expect(logger.isError()).toBe(true);
+ });
+ });
+
+ describe("Error level", () => {
+ it("should only log error when set to error", () => {
+ const logger = new Logger({
+ level: LogLevel.Error,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("debug");
+ logger.info("info");
+ logger.warn("warn");
+ logger.error("error");
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).not.toHaveBeenCalled();
+ expect(mockLogger.warn).not.toHaveBeenCalled();
+ expect(mockLogger.error).toHaveBeenCalledWith("error");
+ });
+
+ it("should report correct level checks", () => {
+ const logger = new Logger({
+ level: LogLevel.Error,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger.isDebug()).toBe(false);
+ expect(logger.isInfo()).toBe(false);
+ expect(logger.isWarn()).toBe(false);
+ expect(logger.isError()).toBe(true);
+ });
+ });
+
+ describe("Silent mode", () => {
+ it("should not log anything when silent is true", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: true,
+ });
+
+ logger.debug("debug");
+ logger.info("info");
+ logger.warn("warn");
+ logger.error("error");
+
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ expect(mockLogger.info).not.toHaveBeenCalled();
+ expect(mockLogger.warn).not.toHaveBeenCalled();
+ expect(mockLogger.error).not.toHaveBeenCalled();
+ });
+
+ it("should report all level checks as false when silent", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: true,
+ });
+
+ expect(logger.isDebug()).toBe(false);
+ expect(logger.isInfo()).toBe(false);
+ expect(logger.isWarn()).toBe(false);
+ expect(logger.isError()).toBe(false);
+ });
+ });
+
+ describe("shouldLog", () => {
+ it("should correctly determine if level should be logged", () => {
+ const logger = new Logger({
+ level: LogLevel.Info,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger.shouldLog(LogLevel.Debug)).toBe(false);
+ expect(logger.shouldLog(LogLevel.Info)).toBe(true);
+ expect(logger.shouldLog(LogLevel.Warn)).toBe(true);
+ expect(logger.shouldLog(LogLevel.Error)).toBe(true);
+ });
+
+ it("should return false for all levels when silent", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: true,
+ });
+
+ expect(logger.shouldLog(LogLevel.Debug)).toBe(false);
+ expect(logger.shouldLog(LogLevel.Info)).toBe(false);
+ expect(logger.shouldLog(LogLevel.Warn)).toBe(false);
+ expect(logger.shouldLog(LogLevel.Error)).toBe(false);
+ });
+ });
+
+ describe("Multiple arguments", () => {
+ it("should pass multiple arguments to logger", () => {
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("message", "arg1", { key: "value" }, 123);
+ expect(mockLogger.debug).toHaveBeenCalledWith("message", "arg1", { key: "value" }, 123);
+ });
+ });
+ });
+
+ describe("createLogger", () => {
+ it("should return default logger when no config provided", () => {
+ const logger = createLogger();
+ expect(logger).toBeInstanceOf(Logger);
+ });
+
+ it("should return same logger instance when Logger is passed", () => {
+ const customLogger = new Logger({
+ level: LogLevel.Debug,
+ logger: new ConsoleLogger(),
+ silent: false,
+ });
+
+ const result = createLogger(customLogger);
+ expect(result).toBe(customLogger);
+ });
+
+ it("should create logger with custom config", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = createLogger({
+ level: LogLevel.Warn,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ expect(logger).toBeInstanceOf(Logger);
+ logger.warn("test");
+ expect(mockLogger.warn).toHaveBeenCalledWith("test");
+ });
+
+ it("should use default values for missing config", () => {
+ const logger = createLogger({});
+ expect(logger).toBeInstanceOf(Logger);
+ });
+
+ it("should override default level", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = createLogger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("test");
+ expect(mockLogger.debug).toHaveBeenCalledWith("test");
+ });
+
+ it("should override default silent mode", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = createLogger({
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.info("test");
+ expect(mockLogger.info).toHaveBeenCalledWith("test");
+ });
+
+ it("should use provided logger implementation", () => {
+ const customLogger = createMockLogger();
+
+ const logger = createLogger({
+ logger: customLogger,
+ level: LogLevel.Debug,
+ silent: false,
+ });
+
+ logger.debug("test");
+ expect(customLogger.debug).toHaveBeenCalledWith("test");
+ });
+
+ it("should default to silent: true", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = createLogger({
+ logger: mockLogger,
+ level: LogLevel.Debug,
+ });
+
+ logger.debug("test");
+ expect(mockLogger.debug).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("Default logger", () => {
+ it("should have silent: true by default", () => {
+ const logger = createLogger();
+ expect(logger.shouldLog(LogLevel.Info)).toBe(false);
+ });
+
+ it("should not log when using default logger", () => {
+ const logger = createLogger();
+
+ logger.info("test");
+ expect(logger.isInfo()).toBe(false);
+ });
+ });
+
+ describe("Edge cases", () => {
+ it("should handle empty message", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("");
+ expect(mockLogger.debug).toHaveBeenCalledWith("");
+ });
+
+ it("should handle no arguments", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ logger.debug("message");
+ expect(mockLogger.debug).toHaveBeenCalledWith("message");
+ });
+
+ it("should handle complex objects", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = new Logger({
+ level: LogLevel.Debug,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ const complexObject = {
+ nested: { key: "value" },
+ array: [1, 2, 3],
+ fn: () => "test",
+ };
+
+ logger.debug("message", complexObject);
+ expect(mockLogger.debug).toHaveBeenCalledWith("message", complexObject);
+ });
+
+ it("should handle errors as arguments", () => {
+ const mockLogger = createMockLogger();
+
+ const logger = new Logger({
+ level: LogLevel.Error,
+ logger: mockLogger,
+ silent: false,
+ });
+
+ const error = new Error("Test error");
+ logger.error("Error occurred", error);
+ expect(mockLogger.error).toHaveBeenCalledWith("Error occurred", error);
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/bigint/bigint.test.ts b/packages/sdk/tests/unit/schemas/bigint/bigint.test.ts
new file mode 100644
index 000000000..498f143c7
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/bigint/bigint.test.ts
@@ -0,0 +1,46 @@
+import { bigint } from "../../../../src/core/schemas/builders/bigint";
+import { itJson, itParse, itSchema } from "../utils/itSchema";
+import { itValidateJson, itValidateParse } from "../utils/itValidate";
+
+describe("bigint", () => {
+ itSchema("converts between raw bigint and parsed bigint", bigint(), {
+ raw: BigInt("9007199254740992"),
+ parsed: BigInt("9007199254740992"),
+ });
+
+ itParse("converts between raw number and parsed bigint", bigint(), {
+ raw: 10,
+ parsed: BigInt("10"),
+ });
+
+ itParse("converts between raw number and parsed bigint", bigint(), {
+ raw: BigInt("10"),
+ parsed: BigInt("10"),
+ });
+
+ itJson("converts raw bigint to parsed bigint", bigint(), {
+ parsed: BigInt("10"),
+ raw: BigInt("10"),
+ });
+
+ itValidateParse("string", bigint(), "42", [
+ {
+ message: 'Expected bigint | number. Received "42".',
+ path: [],
+ },
+ ]);
+
+ itValidateJson("number", bigint(), 42, [
+ {
+ message: "Expected bigint. Received 42.",
+ path: [],
+ },
+ ]);
+
+ itValidateJson("string", bigint(), "42", [
+ {
+ message: 'Expected bigint. Received "42".',
+ path: [],
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/date/date.test.ts b/packages/sdk/tests/unit/schemas/date/date.test.ts
new file mode 100644
index 000000000..2790268a0
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/date/date.test.ts
@@ -0,0 +1,31 @@
+import { date } from "../../../../src/core/schemas/builders/date";
+import { itSchema } from "../utils/itSchema";
+import { itValidateJson, itValidateParse } from "../utils/itValidate";
+
+describe("date", () => {
+ itSchema("converts between raw ISO string and parsed Date", date(), {
+ raw: "2022-09-29T05:41:21.939Z",
+ parsed: new Date("2022-09-29T05:41:21.939Z"),
+ });
+
+ itValidateParse("non-string", date(), 42, [
+ {
+ message: "Expected string. Received 42.",
+ path: [],
+ },
+ ]);
+
+ itValidateParse("non-ISO", date(), "hello world", [
+ {
+ message: 'Expected ISO 8601 date string. Received "hello world".',
+ path: [],
+ },
+ ]);
+
+ itValidateJson("non-Date", date(), "hello", [
+ {
+ message: 'Expected Date object. Received "hello".',
+ path: [],
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/enum/enum.test.ts b/packages/sdk/tests/unit/schemas/enum/enum.test.ts
new file mode 100644
index 000000000..d1707325b
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/enum/enum.test.ts
@@ -0,0 +1,30 @@
+import { enum_ } from "../../../../src/core/schemas/builders/enum";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("enum", () => {
+ itSchemaIdentity(enum_(["A", "B", "C"]), "A");
+
+ itSchemaIdentity(enum_(["A", "B", "C"]), "D" as any, {
+ opts: { allowUnrecognizedEnumValues: true },
+ });
+
+ itValidate("invalid enum", enum_(["A", "B", "C"]), "D", [
+ {
+ message: 'Expected enum. Received "D".',
+ path: [],
+ },
+ ]);
+
+ itValidate(
+ "non-string",
+ enum_(["A", "B", "C"]),
+ [],
+ [
+ {
+ message: "Expected string. Received list.",
+ path: [],
+ },
+ ],
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/lazy/lazy.test.ts b/packages/sdk/tests/unit/schemas/lazy/lazy.test.ts
new file mode 100644
index 000000000..a82ace4a0
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/lazy/lazy.test.ts
@@ -0,0 +1,57 @@
+import { lazy, list, object, string } from "../../../../src/core/schemas/builders";
+import type { Schema } from "../../../../src/core/schemas/Schema";
+import { itSchemaIdentity } from "../utils/itSchema";
+
+describe("lazy", () => {
+ it("doesn't run immediately", () => {
+ let wasRun = false;
+ lazy(() => {
+ wasRun = true;
+ return string();
+ });
+ expect(wasRun).toBe(false);
+ });
+
+ it("only runs first time", async () => {
+ let count = 0;
+ const schema = lazy(() => {
+ count++;
+ return string();
+ });
+ await schema.parse("hello");
+ await schema.json("world");
+ expect(count).toBe(1);
+ });
+
+ itSchemaIdentity(
+ lazy(() => object({})),
+ { foo: "hello" },
+ {
+ title: "passes opts through",
+ opts: { unrecognizedObjectKeys: "passthrough" },
+ },
+ );
+
+ itSchemaIdentity(
+ lazy(() => object({ foo: string() })),
+ { foo: "hello" },
+ );
+
+ // eslint-disable-next-line vi/expect-expect
+ it("self-referencial schema doesn't compile", () => {
+ () => {
+ // @ts-expect-error
+ const a = lazy(() => object({ foo: a }));
+ };
+ });
+
+ // eslint-disable-next-line vi/expect-expect
+ it("self-referencial compiles with explicit type", () => {
+ () => {
+ interface TreeNode {
+ children: TreeNode[];
+ }
+ const TreeNode: Schema<TreeNode, TreeNode> = lazy(() => object({ children: list(TreeNode) }));
+ };
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/lazy/lazyObject.test.ts b/packages/sdk/tests/unit/schemas/lazy/lazyObject.test.ts
new file mode 100644
index 000000000..9b443671a
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/lazy/lazyObject.test.ts
@@ -0,0 +1,18 @@
+import { lazyObject, number, object, string } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+
+describe("lazy", () => {
+ itSchemaIdentity(
+ lazyObject(() => object({ foo: string() })),
+ { foo: "hello" },
+ );
+
+ itSchemaIdentity(
+ lazyObject(() => object({ foo: string() })).extend(object({ bar: number() })),
+ {
+ foo: "hello",
+ bar: 42,
+ },
+ { title: "returned schema has object utils" },
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/lazy/recursive/a.ts b/packages/sdk/tests/unit/schemas/lazy/recursive/a.ts
new file mode 100644
index 000000000..8b7d5e40c
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/lazy/recursive/a.ts
@@ -0,0 +1,7 @@
+import { object } from "../../../../../src/core/schemas/builders/object";
+import { schemaB } from "./b";
+
+// @ts-expect-error
+export const schemaA = object({
+ b: schemaB,
+});
diff --git a/packages/sdk/tests/unit/schemas/lazy/recursive/b.ts b/packages/sdk/tests/unit/schemas/lazy/recursive/b.ts
new file mode 100644
index 000000000..fb219d54c
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/lazy/recursive/b.ts
@@ -0,0 +1,8 @@
+import { object } from "../../../../../src/core/schemas/builders/object";
+import { optional } from "../../../../../src/core/schemas/builders/schema-utils";
+import { schemaA } from "./a";
+
+// @ts-expect-error
+export const schemaB = object({
+ a: optional(schemaA),
+});
diff --git a/packages/sdk/tests/unit/schemas/list/list.test.ts b/packages/sdk/tests/unit/schemas/list/list.test.ts
new file mode 100644
index 000000000..108789b73
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/list/list.test.ts
@@ -0,0 +1,41 @@
+import { list, object, property, string } from "../../../../src/core/schemas/builders";
+import { itSchema, itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("list", () => {
+ itSchemaIdentity(list(string()), ["hello", "world"], {
+ title: "functions as identity when item type is primitive",
+ });
+
+ itSchema(
+ "converts objects correctly",
+ list(
+ object({
+ helloWorld: property("hello_world", string()),
+ }),
+ ),
+ {
+ raw: [{ hello_world: "123" }],
+ parsed: [{ helloWorld: "123" }],
+ },
+ );
+
+ itValidate("not a list", list(string()), 42, [
+ {
+ path: [],
+ message: "Expected list. Received 42.",
+ },
+ ]);
+
+ itValidate(
+ "invalid item type",
+ list(string()),
+ [42],
+ [
+ {
+ path: ["[0]"],
+ message: "Expected string. Received 42.",
+ },
+ ],
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/literals/stringLiteral.test.ts b/packages/sdk/tests/unit/schemas/literals/stringLiteral.test.ts
new file mode 100644
index 000000000..fa6c88873
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/literals/stringLiteral.test.ts
@@ -0,0 +1,21 @@
+import { stringLiteral } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("stringLiteral", () => {
+ itSchemaIdentity(stringLiteral("A"), "A");
+
+ itValidate("incorrect string", stringLiteral("A"), "B", [
+ {
+ path: [],
+ message: 'Expected "A". Received "B".',
+ },
+ ]);
+
+ itValidate("non-string", stringLiteral("A"), 42, [
+ {
+ path: [],
+ message: 'Expected "A". Received 42.',
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/object-like/withParsedProperties.test.ts b/packages/sdk/tests/unit/schemas/object-like/withParsedProperties.test.ts
new file mode 100644
index 000000000..b18bc9d3e
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/object-like/withParsedProperties.test.ts
@@ -0,0 +1,57 @@
+import { object, property, string, stringLiteral } from "../../../../src/core/schemas/builders";
+
+describe("withParsedProperties", () => {
+ it("Added properties included on parsed object", async () => {
+ const schema = object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }).withParsedProperties({
+ printFoo: (parsed) => () => parsed.foo,
+ printHelloWorld: () => () => "Hello world",
+ helloWorld: "Hello world",
+ });
+
+ const parsed = await schema.parse({ raw_foo: "value of foo", bar: "bar" });
+ if (!parsed.ok) {
+ throw new Error("Failed to parse");
+ }
+ expect(parsed.value.printFoo()).toBe("value of foo");
+ expect(parsed.value.printHelloWorld()).toBe("Hello world");
+ expect(parsed.value.helloWorld).toBe("Hello world");
+ });
+
+ it("Added property is removed on raw object", async () => {
+ const schema = object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }).withParsedProperties({
+ printFoo: (parsed) => () => parsed.foo,
+ });
+
+ const original = { raw_foo: "value of foo", bar: "bar" } as const;
+ const parsed = await schema.parse(original);
+ if (!parsed.ok) {
+ throw new Error("Failed to parse()");
+ }
+
+ const raw = await schema.json(parsed.value);
+
+ if (!raw.ok) {
+ throw new Error("Failed to json()");
+ }
+
+ expect(raw.value).toEqual(original);
+ });
+
+ describe("compile", () => {
+ // eslint-disable-next-line vi/expect-expect
+ it("doesn't compile with non-object schema", () => {
+ () =>
+ object({
+ foo: string(),
+ })
+ // @ts-expect-error
+ .withParsedProperties(42);
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/object/extend.test.ts b/packages/sdk/tests/unit/schemas/object/extend.test.ts
new file mode 100644
index 000000000..b6c2920f4
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/object/extend.test.ts
@@ -0,0 +1,89 @@
+import { boolean, object, property, string, stringLiteral } from "../../../../src/core/schemas/builders";
+import { itSchema, itSchemaIdentity } from "../utils/itSchema";
+
+describe("extend", () => {
+ itSchemaIdentity(
+ object({
+ foo: string(),
+ }).extend(
+ object({
+ bar: stringLiteral("bar"),
+ }),
+ ),
+ {
+ foo: "",
+ bar: "bar",
+ } as const,
+ {
+ title: "extended properties are included in schema",
+ },
+ );
+
+ itSchemaIdentity(
+ object({
+ foo: string(),
+ })
+ .extend(
+ object({
+ bar: stringLiteral("bar"),
+ }),
+ )
+ .extend(
+ object({
+ baz: boolean(),
+ }),
+ ),
+ {
+ foo: "",
+ bar: "bar",
+ baz: true,
+ } as const,
+ {
+ title: "extensions can be extended",
+ },
+ );
+
+ itSchema(
+ "converts nested object",
+ object({
+ item: object({
+ helloWorld: property("hello_world", string()),
+ }),
+ }).extend(
+ object({
+ goodbye: property("goodbye_raw", string()),
+ }),
+ ),
+ {
+ raw: { item: { hello_world: "yo" }, goodbye_raw: "peace" },
+ parsed: { item: { helloWorld: "yo" }, goodbye: "peace" },
+ },
+ );
+
+ itSchema(
+ "extensions work with raw/parsed property name conversions",
+ object({
+ item: property("item_raw", string()),
+ }).extend(
+ object({
+ goodbye: property("goodbye_raw", string()),
+ }),
+ ),
+ {
+ raw: { item_raw: "hi", goodbye_raw: "peace" },
+ parsed: { item: "hi", goodbye: "peace" },
+ },
+ );
+
+ describe("compile", () => {
+ // eslint-disable-next-line vi/expect-expect
+ it("doesn't compile with non-object schema", () => {
+ () =>
+ object({
+ foo: string(),
+ })
+ // @ts-expect-error
+ .extend([]);
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/object/object.test.ts b/packages/sdk/tests/unit/schemas/object/object.test.ts
new file mode 100644
index 000000000..a8d9fe0a1
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/object/object.test.ts
@@ -0,0 +1,255 @@
+import { any, number, object, property, string, stringLiteral, unknown } from "../../../../src/core/schemas/builders";
+import { itJson, itParse, itSchema, itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("object", () => {
+ itSchemaIdentity(
+ object({
+ foo: string(),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ foo: "",
+ bar: "bar",
+ },
+ {
+ title: "functions as identity when values are primitives and property() isn't used",
+ },
+ );
+
+ itSchema(
+ "uses raw key from property()",
+ object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ raw: { raw_foo: "foo", bar: "bar" },
+ parsed: { foo: "foo", bar: "bar" },
+ },
+ );
+
+ itSchema(
+ "keys with unknown type can be omitted",
+ object({
+ foo: unknown(),
+ }),
+ {
+ raw: {},
+ parsed: {},
+ },
+ );
+
+ itSchema(
+ "keys with any type can be omitted",
+ object({
+ foo: any(),
+ }),
+ {
+ raw: {},
+ parsed: {},
+ },
+ );
+
+ describe("unrecognizedObjectKeys", () => {
+ describe("parse", () => {
+ itParse(
+ 'includes unknown values when unrecognizedObjectKeys === "passthrough"',
+ object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ raw: {
+ raw_foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ parsed: {
+ foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ opts: {
+ unrecognizedObjectKeys: "passthrough",
+ },
+ },
+ );
+
+ itParse(
+ 'strips unknown values when unrecognizedObjectKeys === "strip"',
+ object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ raw: {
+ raw_foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ parsed: {
+ foo: "foo",
+ bar: "bar",
+ },
+ opts: {
+ unrecognizedObjectKeys: "strip",
+ },
+ },
+ );
+ });
+
+ describe("json", () => {
+ itJson(
+ 'includes unknown values when unrecognizedObjectKeys === "passthrough"',
+ object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ raw: {
+ raw_foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ parsed: {
+ foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ opts: {
+ unrecognizedObjectKeys: "passthrough",
+ },
+ },
+ );
+
+ itJson(
+ 'strips unknown values when unrecognizedObjectKeys === "strip"',
+ object({
+ foo: property("raw_foo", string()),
+ bar: stringLiteral("bar"),
+ }),
+ {
+ raw: {
+ raw_foo: "foo",
+ bar: "bar",
+ },
+ parsed: {
+ foo: "foo",
+ bar: "bar",
+ // @ts-expect-error
+ baz: "yoyo",
+ },
+ opts: {
+ unrecognizedObjectKeys: "strip",
+ },
+ },
+ );
+ });
+ });
+
+ describe("nullish properties", () => {
+ itSchema("missing properties are not added", object({ foo: property("raw_foo", string().optional()) }), {
+ raw: {},
+ parsed: {},
+ });
+
+ itSchema("undefined properties are not dropped", object({ foo: property("raw_foo", string().optional()) }), {
+ raw: { raw_foo: null },
+ parsed: { foo: undefined },
+ });
+
+ itSchema("null properties are not dropped", object({ foo: property("raw_foo", string().optional()) }), {
+ raw: { raw_foo: null },
+ parsed: { foo: undefined },
+ });
+
+ describe("extensions", () => {
+ itSchema(
+ "undefined properties are not dropped",
+ object({}).extend(object({ foo: property("raw_foo", string().optional()) })),
+ {
+ raw: { raw_foo: null },
+ parsed: { foo: undefined },
+ },
+ );
+
+ describe("parse()", () => {
+ itParse(
+ "null properties are not dropped",
+ object({}).extend(object({ foo: property("raw_foo", string().optional()) })),
+ {
+ raw: { raw_foo: null },
+ parsed: { foo: undefined },
+ },
+ );
+ });
+ });
+ });
+
+ itValidate(
+ "missing property",
+ object({
+ foo: string(),
+ bar: stringLiteral("bar"),
+ }),
+ { foo: "hello" },
+ [
+ {
+ path: [],
+ message: 'Missing required key "bar"',
+ },
+ ],
+ );
+
+ itValidate(
+ "extra property",
+ object({
+ foo: string(),
+ bar: stringLiteral("bar"),
+ }),
+ { foo: "hello", bar: "bar", baz: 42 },
+ [
+ {
+ path: ["baz"],
+ message: 'Unexpected key "baz"',
+ },
+ ],
+ );
+
+ itValidate(
+ "not an object",
+ object({
+ foo: string(),
+ bar: stringLiteral("bar"),
+ }),
+ [],
+ [
+ {
+ path: [],
+ message: "Expected object. Received list.",
+ },
+ ],
+ );
+
+ itValidate(
+ "nested validation error",
+ object({
+ foo: object({
+ bar: number(),
+ }),
+ }),
+ { foo: { bar: "hello" } },
+ [
+ {
+ path: ["foo", "bar"],
+ message: 'Expected number. Received "hello".',
+ },
+ ],
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/object/objectWithoutOptionalProperties.test.ts b/packages/sdk/tests/unit/schemas/object/objectWithoutOptionalProperties.test.ts
new file mode 100644
index 000000000..efcd83afa
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/object/objectWithoutOptionalProperties.test.ts
@@ -0,0 +1,21 @@
+import { objectWithoutOptionalProperties, string, stringLiteral } from "../../../../src/core/schemas/builders";
+import { itSchema } from "../utils/itSchema";
+
+describe("objectWithoutOptionalProperties", () => {
+ itSchema(
+ "all properties are required",
+ objectWithoutOptionalProperties({
+ foo: string(),
+ bar: stringLiteral("bar").optional(),
+ }),
+ {
+ raw: {
+ foo: "hello",
+ },
+ // @ts-expect-error
+ parsed: {
+ foo: "hello",
+ },
+ },
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/object/passthrough.test.ts b/packages/sdk/tests/unit/schemas/object/passthrough.test.ts
new file mode 100644
index 000000000..c8770fca1
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/object/passthrough.test.ts
@@ -0,0 +1,87 @@
+import { object, string, stringLiteral } from "../../../../src/core/schemas/builders";
+import { itJson, itParse, itSchema } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("passthrough", () => {
+ const baseSchema = object({
+ foo: string(),
+ bar: stringLiteral("bar"),
+ });
+
+ describe("parse", () => {
+ itParse("includes unknown values", baseSchema.passthrough(), {
+ raw: {
+ foo: "hello",
+ bar: "bar",
+ baz: "extra",
+ },
+ parsed: {
+ foo: "hello",
+ bar: "bar",
+ baz: "extra",
+ },
+ });
+
+ itValidate(
+ "preserves schema validation",
+ baseSchema.passthrough(),
+ {
+ foo: 123,
+ bar: "bar",
+ baz: "extra",
+ },
+ [
+ {
+ path: ["foo"],
+ message: "Expected string. Received 123.",
+ },
+ ],
+ );
+ });
+
+ describe("json", () => {
+ itJson("includes unknown values", baseSchema.passthrough(), {
+ raw: {
+ foo: "hello",
+ bar: "bar",
+
+ baz: "extra",
+ },
+ parsed: {
+ foo: "hello",
+ bar: "bar",
+
+ baz: "extra",
+ },
+ });
+
+ itValidate(
+ "preserves schema validation",
+ baseSchema.passthrough(),
+ {
+ foo: "hello",
+ bar: "wrong",
+ baz: "extra",
+ },
+ [
+ {
+ path: ["bar"],
+ message: 'Expected "bar". Received "wrong".',
+ },
+ ],
+ );
+ });
+
+ itSchema("preserves schema validation in both directions", baseSchema.passthrough(), {
+ raw: {
+ foo: "hello",
+ bar: "bar",
+ extra: 42,
+ },
+ parsed: {
+ foo: "hello",
+ bar: "bar",
+ extra: 42,
+ },
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/any.test.ts b/packages/sdk/tests/unit/schemas/primitives/any.test.ts
new file mode 100644
index 000000000..1adbbe2a8
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/any.test.ts
@@ -0,0 +1,6 @@
+import { any } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+
+describe("any", () => {
+ itSchemaIdentity(any(), true);
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/boolean.test.ts b/packages/sdk/tests/unit/schemas/primitives/boolean.test.ts
new file mode 100644
index 000000000..897a8295d
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/boolean.test.ts
@@ -0,0 +1,14 @@
+import { boolean } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("boolean", () => {
+ itSchemaIdentity(boolean(), true);
+
+ itValidate("non-boolean", boolean(), {}, [
+ {
+ path: [],
+ message: "Expected boolean. Received object.",
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/never.test.ts b/packages/sdk/tests/unit/schemas/primitives/never.test.ts
new file mode 100644
index 000000000..1d18eba05
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/never.test.ts
@@ -0,0 +1,54 @@
+import { never } from "../../../../src/core/schemas/builders";
+
+describe("never", () => {
+ it("always fails to parse", () => {
+ const schema = never();
+ const result = schema.parse("test");
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]?.message).toBe("Expected never");
+ }
+ });
+
+ it("always fails to json", () => {
+ const schema = never();
+ const result = schema.json("test");
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]?.message).toBe("Expected never");
+ }
+ });
+
+ it("fails with any value including undefined", () => {
+ const schema = never();
+ expect(schema.parse(undefined).ok).toBe(false);
+ expect(schema.parse(null).ok).toBe(false);
+ expect(schema.parse(0).ok).toBe(false);
+ expect(schema.parse("").ok).toBe(false);
+ expect(schema.parse({}).ok).toBe(false);
+ expect(schema.parse([]).ok).toBe(false);
+ });
+
+ it("works when called without options parameter", () => {
+ const schema = never();
+ // This tests that the default = {} parameter works correctly
+ const result = schema.parse("test");
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]?.message).toBe("Expected never");
+ expect(result.errors[0]?.path).toEqual([]);
+ }
+ });
+
+ it("succeeds with skipValidation", () => {
+ const schema = never();
+ const result = schema.parse("test", { skipValidation: true });
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.value).toBe("test");
+ }
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/number.test.ts b/packages/sdk/tests/unit/schemas/primitives/number.test.ts
new file mode 100644
index 000000000..2d01415a6
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/number.test.ts
@@ -0,0 +1,14 @@
+import { number } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("number", () => {
+ itSchemaIdentity(number(), 42);
+
+ itValidate("non-number", number(), "hello", [
+ {
+ path: [],
+ message: 'Expected number. Received "hello".',
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/string.test.ts b/packages/sdk/tests/unit/schemas/primitives/string.test.ts
new file mode 100644
index 000000000..57b236878
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/string.test.ts
@@ -0,0 +1,14 @@
+import { string } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("string", () => {
+ itSchemaIdentity(string(), "hello");
+
+ itValidate("non-string", string(), 42, [
+ {
+ path: [],
+ message: "Expected string. Received 42.",
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/primitives/unknown.test.ts b/packages/sdk/tests/unit/schemas/primitives/unknown.test.ts
new file mode 100644
index 000000000..4d17a7dbd
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/primitives/unknown.test.ts
@@ -0,0 +1,6 @@
+import { unknown } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+
+describe("unknown", () => {
+ itSchemaIdentity(unknown(), true);
+});
diff --git a/packages/sdk/tests/unit/schemas/record/record.test.ts b/packages/sdk/tests/unit/schemas/record/record.test.ts
new file mode 100644
index 000000000..e07f3e7cb
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/record/record.test.ts
@@ -0,0 +1,34 @@
+import { number, record, string } from "../../../../src/core/schemas/builders";
+import { itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("record", () => {
+ itSchemaIdentity(record(string(), string()), { hello: "world" });
+ itSchemaIdentity(record(number(), string()), { 42: "world" });
+
+ itValidate(
+ "non-record",
+ record(number(), string()),
+ [],
+ [
+ {
+ path: [],
+ message: "Expected object. Received list.",
+ },
+ ],
+ );
+
+ itValidate("invalid key type", record(number(), string()), { hello: "world" }, [
+ {
+ path: ["hello (key)"],
+ message: 'Expected number. Received "hello".',
+ },
+ ]);
+
+ itValidate("invalid value type", record(string(), number()), { hello: "world" }, [
+ {
+ path: ["hello"],
+ message: 'Expected number. Received "world".',
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/schema-utils/getSchemaUtils.test.ts b/packages/sdk/tests/unit/schemas/schema-utils/getSchemaUtils.test.ts
new file mode 100644
index 000000000..822c3ca4e
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/schema-utils/getSchemaUtils.test.ts
@@ -0,0 +1,83 @@
+import { object, string } from "../../../../src/core/schemas/builders";
+import { itSchema } from "../utils/itSchema";
+
+describe("getSchemaUtils", () => {
+ describe("optional()", () => {
+ itSchema("optional fields allow original schema", string().optional(), {
+ raw: "hello",
+ parsed: "hello",
+ });
+
+ itSchema("optional fields are not required", string().optional(), {
+ raw: null,
+ parsed: undefined,
+ });
+ });
+
+ describe("transform()", () => {
+ itSchema(
+ "transform and untransform run correctly",
+ string().transform({
+ transform: (x) => `${x}X`,
+ untransform: (x) => (x as string).slice(0, -1),
+ }),
+ {
+ raw: "hello",
+ parsed: "helloX",
+ },
+ );
+ });
+
+ describe("parseOrThrow()", () => {
+ it("parses valid value", async () => {
+ const value = string().parseOrThrow("hello");
+ expect(value).toBe("hello");
+ });
+
+ it("throws on invalid value", async () => {
+ const value = () => object({ a: string(), b: string() }).parseOrThrow({ a: 24 });
+ expect(value).toThrowError('a: Expected string. Received 24.; Missing required key "b"');
+ });
+ });
+
+ describe("jsonOrThrow()", () => {
+ it("serializes valid value", async () => {
+ const value = string().jsonOrThrow("hello");
+ expect(value).toBe("hello");
+ });
+
+ it("throws on invalid value", async () => {
+ const value = () => object({ a: string(), b: string() }).jsonOrThrow({ a: 24 });
+ expect(value).toThrowError('a: Expected string. Received 24.; Missing required key "b"');
+ });
+ });
+
+ describe("omitUndefined", () => {
+ it("serializes undefined as null", async () => {
+ const value = object({
+ a: string().optional(),
+ b: string().optional(),
+ }).jsonOrThrow({
+ a: "hello",
+ b: undefined,
+ });
+ expect(value).toEqual({ a: "hello", b: null });
+ });
+
+ it("omits undefined values", async () => {
+ const value = object({
+ a: string().optional(),
+ b: string().optional(),
+ }).jsonOrThrow(
+ {
+ a: "hello",
+ b: undefined,
+ },
+ {
+ omitUndefined: true,
+ },
+ );
+ expect(value).toEqual({ a: "hello" });
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/schema.test.ts b/packages/sdk/tests/unit/schemas/schema.test.ts
new file mode 100644
index 000000000..13842ff40
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/schema.test.ts
@@ -0,0 +1,78 @@
+import {
+ boolean,
+ discriminant,
+ list,
+ number,
+ object,
+ string,
+ stringLiteral,
+ union,
+} from "../../../src/core/schemas/builders";
+import { booleanLiteral } from "../../../src/core/schemas/builders/literals/booleanLiteral";
+import { property } from "../../../src/core/schemas/builders/object/property";
+import { itSchema } from "./utils/itSchema";
+
+describe("Schema", () => {
+ itSchema(
+ "large nested object",
+ object({
+ a: string(),
+ b: stringLiteral("b value"),
+ c: property(
+ "raw_c",
+ list(
+ object({
+ animal: union(discriminant("type", "_type"), {
+ dog: object({ value: boolean() }),
+ cat: object({ value: property("raw_cat", number()) }),
+ }),
+ }),
+ ),
+ ),
+ d: property("raw_d", boolean()),
+ e: booleanLiteral(true),
+ }),
+ {
+ raw: {
+ a: "hello",
+ b: "b value",
+ raw_c: [
+ {
+ animal: {
+ _type: "dog",
+ value: true,
+ },
+ },
+ {
+ animal: {
+ _type: "cat",
+ raw_cat: 42,
+ },
+ },
+ ],
+ raw_d: false,
+ e: true,
+ },
+ parsed: {
+ a: "hello",
+ b: "b value",
+ c: [
+ {
+ animal: {
+ type: "dog",
+ value: true,
+ },
+ },
+ {
+ animal: {
+ type: "cat",
+ value: 42,
+ },
+ },
+ ],
+ d: false,
+ e: true,
+ },
+ },
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/set/set.test.ts b/packages/sdk/tests/unit/schemas/set/set.test.ts
new file mode 100644
index 000000000..53a1652c8
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/set/set.test.ts
@@ -0,0 +1,48 @@
+import { set, string } from "../../../../src/core/schemas/builders";
+import { itSchema } from "../utils/itSchema";
+import { itValidateJson, itValidateParse } from "../utils/itValidate";
+
+describe("set", () => {
+ itSchema("converts between raw list and parsed Set", set(string()), {
+ raw: ["A", "B"],
+ parsed: new Set(["A", "B"]),
+ });
+
+ itValidateParse("not a list", set(string()), 42, [
+ {
+ path: [],
+ message: "Expected list. Received 42.",
+ },
+ ]);
+
+ itValidateJson(
+ "not a Set",
+ set(string()),
+ [],
+ [
+ {
+ path: [],
+ message: "Expected Set. Received list.",
+ },
+ ],
+ );
+
+ itValidateParse(
+ "invalid item type",
+ set(string()),
+ [42],
+ [
+ {
+ path: ["[0]"],
+ message: "Expected string. Received 42.",
+ },
+ ],
+ );
+
+ itValidateJson("invalid item type", set(string()), new Set([42]), [
+ {
+ path: ["[0]"],
+ message: "Expected string. Received 42.",
+ },
+ ]);
+});
diff --git a/packages/sdk/tests/unit/schemas/skipValidation.test.ts b/packages/sdk/tests/unit/schemas/skipValidation.test.ts
new file mode 100644
index 000000000..328355594
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/skipValidation.test.ts
@@ -0,0 +1,44 @@
+/* eslint-disable no-console */
+import { boolean, number, object, property, string, undiscriminatedUnion } from "../../../src/core/schemas/builders";
+
+describe("skipValidation", () => {
+ it("allows data that doesn't conform to the schema", async () => {
+ const warningLogs: string[] = [];
+ const originalConsoleWarn = console.warn;
+ console.warn = (...args) => warningLogs.push(args.join(" "));
+
+ const schema = object({
+ camelCase: property("snake_case", string()),
+ numberProperty: number(),
+ requiredProperty: boolean(),
+ anyPrimitive: undiscriminatedUnion([string(), number(), boolean()]),
+ });
+
+ const parsed = await schema.parse(
+ {
+ snake_case: "hello",
+ numberProperty: "oops",
+ anyPrimitive: true,
+ },
+ {
+ skipValidation: true,
+ },
+ );
+
+ expect(parsed).toEqual({
+ ok: true,
+ value: {
+ camelCase: "hello",
+ numberProperty: "oops",
+ anyPrimitive: true,
+ },
+ });
+
+ expect(warningLogs).toEqual([
+ `Failed to validate.
+ - numberProperty: Expected number. Received "oops".`,
+ ]);
+
+ console.warn = originalConsoleWarn;
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/undiscriminated-union/undiscriminatedUnion.test.ts b/packages/sdk/tests/unit/schemas/undiscriminated-union/undiscriminatedUnion.test.ts
new file mode 100644
index 000000000..01dcadbba
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/undiscriminated-union/undiscriminatedUnion.test.ts
@@ -0,0 +1,44 @@
+import { number, object, property, string, undiscriminatedUnion } from "../../../../src/core/schemas/builders";
+import { itSchema, itSchemaIdentity } from "../utils/itSchema";
+
+describe("undiscriminatedUnion", () => {
+ itSchemaIdentity(undiscriminatedUnion([string(), number()]), "hello world");
+
+ itSchemaIdentity(undiscriminatedUnion([object({ hello: string() }), object({ goodbye: string() })]), {
+ goodbye: "foo",
+ });
+
+ itSchema(
+ "Correctly transforms",
+ undiscriminatedUnion([object({ hello: string() }), object({ helloWorld: property("hello_world", string()) })]),
+ {
+ raw: { hello_world: "foo " },
+ parsed: { helloWorld: "foo " },
+ },
+ );
+
+ it("Returns errors for all variants", async () => {
+ const result = await undiscriminatedUnion([string(), number()]).parse(true);
+ if (result.ok) {
+ throw new Error("Unexpectedly passed validation");
+ }
+ expect(result.errors).toEqual([
+ {
+ message: "[Variant 0] Expected string. Received true.",
+ path: [],
+ },
+ {
+ message: "[Variant 1] Expected number. Received true.",
+ path: [],
+ },
+ ]);
+ });
+
+ describe("compile", () => {
+ // eslint-disable-next-line vi/expect-expect
+ it("doesn't compile with zero members", () => {
+ // @ts-expect-error
+ () => undiscriminatedUnion([]);
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/schemas/union/union.test.ts b/packages/sdk/tests/unit/schemas/union/union.test.ts
new file mode 100644
index 000000000..1f5d7a8fa
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/union/union.test.ts
@@ -0,0 +1,113 @@
+import { boolean, discriminant, number, object, string, union } from "../../../../src/core/schemas/builders";
+import { itSchema, itSchemaIdentity } from "../utils/itSchema";
+import { itValidate } from "../utils/itValidate";
+
+describe("union", () => {
+ itSchemaIdentity(
+ union("type", {
+ lion: object({
+ meows: boolean(),
+ }),
+ giraffe: object({
+ heightInInches: number(),
+ }),
+ }),
+ { type: "lion", meows: true },
+ { title: "doesn't transform discriminant when it's a string" },
+ );
+
+ itSchema(
+ "transforms discriminant when it's a discriminant()",
+ union(discriminant("type", "_type"), {
+ lion: object({ meows: boolean() }),
+ giraffe: object({ heightInInches: number() }),
+ }),
+ {
+ raw: { _type: "lion", meows: true },
+ parsed: { type: "lion", meows: true },
+ },
+ );
+
+ describe("allowUnrecognizedUnionMembers", () => {
+ itSchema(
+ "transforms discriminant & passes through values when discriminant value is unrecognized",
+ union(discriminant("type", "_type"), {
+ lion: object({ meows: boolean() }),
+ giraffe: object({ heightInInches: number() }),
+ }),
+ {
+ // @ts-expect-error
+ raw: { _type: "moose", isAMoose: true },
+ // @ts-expect-error
+ parsed: { type: "moose", isAMoose: true },
+ opts: {
+ allowUnrecognizedUnionMembers: true,
+ },
+ },
+ );
+ });
+
+ describe("withParsedProperties", () => {
+ it("Added property is included on parsed object", async () => {
+ const schema = union("type", {
+ lion: object({}),
+ tiger: object({ value: string() }),
+ }).withParsedProperties({
+ printType: (parsed) => () => parsed.type,
+ });
+
+ const parsed = await schema.parse({ type: "lion" });
+ if (!parsed.ok) {
+ throw new Error("Failed to parse");
+ }
+ expect(parsed.value.printType()).toBe("lion");
+ });
+ });
+
+ itValidate(
+ "non-object",
+ union("type", {
+ lion: object({}),
+ tiger: object({ value: string() }),
+ }),
+ [],
+ [
+ {
+ path: [],
+ message: "Expected object. Received list.",
+ },
+ ],
+ );
+
+ itValidate(
+ "missing discriminant",
+ union("type", {
+ lion: object({}),
+ tiger: object({ value: string() }),
+ }),
+ {},
+ [
+ {
+ path: [],
+ message: 'Missing discriminant ("type")',
+ },
+ ],
+ );
+
+ itValidate(
+ "unrecognized discriminant value",
+ union("type", {
+ lion: object({}),
+ tiger: object({ value: string() }),
+ }),
+ {
+ type: "bear",
+ },
+ [
+ {
+ path: ["type"],
+ message: 'Expected enum. Received "bear".',
+ },
+ ],
+ );
+});
diff --git a/packages/sdk/tests/unit/schemas/utils/itSchema.ts b/packages/sdk/tests/unit/schemas/utils/itSchema.ts
new file mode 100644
index 000000000..25b13e643
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/utils/itSchema.ts
@@ -0,0 +1,78 @@
+/* eslint-disable vi/no-export */
+import type { Schema, SchemaOptions } from "../../../../src/core/schemas/Schema";
+
+export function itSchemaIdentity<T>(
+ schema: Schema<T, T>,
+ value: T,
+ { title = "functions as identity", opts }: { title?: string; opts?: SchemaOptions } = {},
+): void {
+ itSchema(title, schema, { raw: value, parsed: value, opts });
+}
+
+export function itSchema<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ {
+ raw,
+ parsed,
+ opts,
+ only = false,
+ }: {
+ raw: Raw;
+ parsed: Parsed;
+ opts?: SchemaOptions;
+ only?: boolean;
+ },
+): void {
+ // eslint-disable-next-line vi/valid-title
+ (only ? describe.only : describe)(title, () => {
+ itParse("parse()", schema, { raw, parsed, opts });
+ itJson("json()", schema, { raw, parsed, opts });
+ });
+}
+
+export function itParse<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ {
+ raw,
+ parsed,
+ opts,
+ }: {
+ raw: Raw;
+ parsed: Parsed;
+ opts?: SchemaOptions;
+ },
+): void {
+ // eslint-disable-next-line vi/valid-title
+ it(title, () => {
+ const maybeValid = schema.parse(raw, opts);
+ if (!maybeValid.ok) {
+ throw new Error(`Failed to parse() ${JSON.stringify(maybeValid.errors, undefined, 4)}`);
+ }
+ expect(maybeValid.value).toStrictEqual(parsed);
+ });
+}
+
+export function itJson<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ {
+ raw,
+ parsed,
+ opts,
+ }: {
+ raw: Raw;
+ parsed: Parsed;
+ opts?: SchemaOptions;
+ },
+): void {
+ // eslint-disable-next-line vi/valid-title
+ it(title, () => {
+ const maybeValid = schema.json(parsed, opts);
+ if (!maybeValid.ok) {
+ throw new Error(`Failed to json() ${JSON.stringify(maybeValid.errors, undefined, 4)}`);
+ }
+ expect(maybeValid.value).toStrictEqual(raw);
+ });
+}
diff --git a/packages/sdk/tests/unit/schemas/utils/itValidate.ts b/packages/sdk/tests/unit/schemas/utils/itValidate.ts
new file mode 100644
index 000000000..60bc56c12
--- /dev/null
+++ b/packages/sdk/tests/unit/schemas/utils/itValidate.ts
@@ -0,0 +1,56 @@
+/* eslint-disable vi/no-export */
+import type { Schema, SchemaOptions, ValidationError } from "../../../../src/core/schemas/Schema";
+
+export function itValidate<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ input: unknown,
+ errors: ValidationError[],
+ opts?: SchemaOptions,
+): void {
+ // eslint-disable-next-line vi/valid-title
+ describe("parse()", () => {
+ itValidateParse(title, schema, input, errors, opts);
+ });
+ describe("json()", () => {
+ itValidateJson(title, schema, input, errors, opts);
+ });
+}
+
+export function itValidateParse<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ raw: unknown,
+ errors: ValidationError[],
+ opts?: SchemaOptions,
+): void {
+ describe("parse", () => {
+ // eslint-disable-next-line vi/valid-title
+ it(title, async () => {
+ const maybeValid = await schema.parse(raw, opts);
+ if (maybeValid.ok) {
+ throw new Error("Value passed validation");
+ }
+ expect(maybeValid.errors).toStrictEqual(errors);
+ });
+ });
+}
+
+export function itValidateJson<Raw, Parsed>(
+ title: string,
+ schema: Schema<Raw, Parsed>,
+ parsed: unknown,
+ errors: ValidationError[],
+ opts?: SchemaOptions,
+): void {
+ describe("json", () => {
+ // eslint-disable-next-line vi/valid-title
+ it(title, async () => {
+ const maybeValid = await schema.json(parsed, opts);
+ if (maybeValid.ok) {
+ throw new Error("Value passed validation");
+ }
+ expect(maybeValid.errors).toStrictEqual(errors);
+ });
+ });
+}
diff --git a/packages/sdk/tests/unit/stream/Stream.test.ts b/packages/sdk/tests/unit/stream/Stream.test.ts
new file mode 100644
index 000000000..90f7b8871
--- /dev/null
+++ b/packages/sdk/tests/unit/stream/Stream.test.ts
@@ -0,0 +1,1569 @@
+import { type ServerSentEvent, Stream } from "../../../src/core/stream/Stream";
+
+describe("Stream", () => {
+ describe("JSON streaming", () => {
+ it("should parse single JSON message", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should parse multiple JSON messages", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n{"value": 2}\n{"value": 3}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ });
+
+ it("should handle messages split across chunks", async () => {
+ const mockStream = createReadableStream(['{"val', 'ue": 1}\n{"value":', " 2}\n"]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ });
+
+ it("should skip empty lines", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n\n\n{"value": 2}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ });
+
+ it("should handle custom message terminator", async () => {
+ const mockStream = createReadableStream(['{"value": 1}|||{"value": 2}|||']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "|||" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ });
+ });
+
+ describe("SSE streaming", () => {
+ it("should parse SSE data with prefix", async () => {
+ const mockStream = createReadableStream(['data: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should parse multiple SSE events", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"value": 1}\n\ndata: {"value": 2}\n\ndata: {"value": 3}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ });
+
+ it("should stop at stream terminator", async () => {
+ const mockStream = createReadableStream(['data: {"value": 1}\n\ndata: [DONE]\n\ndata: {"value": 2}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should skip lines without data prefix", async () => {
+ const mockStream = createReadableStream([
+ 'event: message\ndata: {"value": 1}\nid: 123\n\ndata: {"value": 2}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ });
+
+ it("should capture id when it appears after data line", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"type":"model.message","thread_id":"main"}\nid: 2\n\ndata: {"content":"Hi","type":"model.message.delta"}\nid: 3\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([
+ { type: "model.message", thread_id: "main" },
+ { content: "Hi", type: "model.message.delta" },
+ ]);
+ });
+
+ it("should handle multiline data with id after last data line", async () => {
+ const mockStream = createReadableStream(['data: {"delta":\ndata: "hello"}\nid: 42\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ delta: "hello" }]);
+ });
+
+ it("should handle id after data without trailing blank line", async () => {
+ const mockStream = createReadableStream(['data: {"value": 1}\nid: last-event\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should handle stream terminator with id after data", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"value": 1}\nid: 1\n\ndata: [DONE]\nid: 2\n\ndata: {"value": 3}\nid: 3\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+ });
+
+ describe("SSE event-level discrimination (inject discriminator)", () => {
+ it("should inject event type as discriminator into JSON data", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\ndata: {"content": "hello"}\n\nevent: completion\ndata: {"content": "world"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([
+ { type: "completion", content: "hello" },
+ { type: "completion", content: "world" },
+ ]);
+ });
+
+ it("should inject different event types for mixed events", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\ndata: {"content": "hi"}\n\nevent: error\ndata: {"message": "fail"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "event" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([
+ { event: "completion", content: "hi" },
+ { event: "error", message: "fail" },
+ ]);
+ });
+
+ it("should not inject if data already contains discriminator key", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\ndata: {"type": "existing", "content": "hello"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "existing", content: "hello" }]);
+ });
+
+ it("should not false-positive when discriminator key appears inside a value", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\ndata: {"description": "type: foo", "content": "hello"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "completion", description: "type: foo", content: "hello" }]);
+ });
+
+ it("should not inject if no event field is present", async () => {
+ const mockStream = createReadableStream(['data: {"content": "hello"}\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ content: "hello" }]);
+ });
+
+ it("should handle empty JSON object", async () => {
+ const mockStream = createReadableStream(["event: heartbeat\ndata: {}\n\n"]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "heartbeat" }]);
+ });
+
+ it("should stop at stream terminator", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\ndata: {"content": "hi"}\n\nevent: done\ndata: [DONE]\n\nevent: completion\ndata: {"content": "bye"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type", streamTerminator: "[DONE]" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "completion", content: "hi" }]);
+ });
+
+ it("should concatenate multiline data fields", async () => {
+ const mockStream = createReadableStream(['event: completion\ndata: {"delta":\ndata: "hello"}\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "completion", delta: "hello" }]);
+ });
+
+ it("should handle events split across chunks", async () => {
+ const mockStream = createReadableStream(["event: comple", 'tion\ndata: {"con', 'tent": "hi"}\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "completion", content: "hi" }]);
+ });
+
+ it("should handle last event without trailing blank line", async () => {
+ const mockStream = createReadableStream(['event: completion\ndata: {"content": "hi"}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "completion", content: "hi" }]);
+ });
+
+ it("should handle CRLF line endings", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\r\ndata: {"content": "hi"}\r\n\r\nevent: completion\r\ndata: {"content": "world"}\r\n\r\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([
+ { type: "completion", content: "hi" },
+ { type: "completion", content: "world" },
+ ]);
+ });
+
+ it("should inject empty string discriminator when event field is present but empty", async () => {
+ const mockStream = createReadableStream(['event: \ndata: {"content": "hello"}\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ type: "", content: "hello" }]);
+ });
+ });
+
+ describe("withMetadata()", () => {
+ it("should yield ServerSentEvent with per-event id and retry", async () => {
+ const mockStream = createReadableStream([
+ 'id: evt-1\nretry: 5000\ndata: {"value": 1}\n\nid: evt-2\ndata: {"value": 2}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { value: 1 }, id: "evt-1", retry: 5000, event: undefined },
+ { data: { value: 2 }, id: "evt-2", retry: 5000, event: undefined },
+ ]);
+ });
+
+ it("should persist id across events per SSE spec", async () => {
+ const mockStream = createReadableStream(['id: evt-1\ndata: {"value": 1}\n\ndata: {"value": 2}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { value: 1 }, id: "evt-1", retry: undefined, event: undefined },
+ { data: { value: 2 }, id: "evt-1", retry: undefined, event: undefined },
+ ]);
+ });
+
+ it("should ignore id field containing null character", async () => {
+ const mockStream = createReadableStream([
+ 'id: valid\ndata: {"value": 1}\n\nid: bad\0id\ndata: {"value": 2}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.id).toBe("valid");
+ expect(events[1]?.id).toBe("valid");
+ });
+
+ it("should ignore retry field with non-integer value", async () => {
+ const mockStream = createReadableStream(['retry: abc\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.retry).toBeUndefined();
+ });
+
+ it("should include event type and metadata with discriminator", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\nid: msg-001\nretry: 3000\ndata: {"content": "hello"}\n\nevent: completion\nid: msg-002\ndata: {"content": "world"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { type: "completion", content: "hello" }, id: "msg-001", retry: 3000, event: "completion" },
+ { data: { type: "completion", content: "world" }, id: "msg-002", retry: 3000, event: "completion" },
+ ]);
+ });
+
+ it("should persist id across discriminated events per SSE spec", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\nid: msg-001\ndata: {"content": "first"}\n\nevent: completion\ndata: {"content": "second"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.id).toBe("msg-001");
+ expect(events[1]?.id).toBe("msg-001");
+ });
+
+ it("should yield undefined metadata for JSON streams", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([{ data: { value: 1 }, id: undefined, retry: undefined, event: undefined }]);
+ });
+
+ it("should stop at stream terminator via withMetadata (non-discriminator)", async () => {
+ const mockStream = createReadableStream([
+ 'id: evt-1\ndata: {"value": 1}\n\ndata: [DONE]\n\ndata: {"value": 2}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([{ data: { value: 1 }, id: "evt-1", retry: undefined, event: undefined }]);
+ });
+
+ it("should stop at stream terminator via withMetadata (discriminator)", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\nid: msg-001\ndata: {"content": "hi"}\n\nevent: done\ndata: [DONE]\n\nevent: completion\ndata: {"content": "bye"}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type", streamTerminator: "[DONE]" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { type: "completion", content: "hi" }, id: "msg-001", retry: undefined, event: "completion" },
+ ]);
+ });
+
+ it("should reject retry with decimal value", async () => {
+ const mockStream = createReadableStream(['retry: 3.5\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.retry).toBeUndefined();
+ });
+
+ it("should accept retry value of zero", async () => {
+ const mockStream = createReadableStream(['retry: 0\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.retry).toBe(0);
+ });
+
+ it("should set empty string id when id field has no value", async () => {
+ const mockStream = createReadableStream(['id:\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.id).toBe("");
+ });
+
+ it("should yield undefined event field for non-discriminator SSE even with event lines", async () => {
+ const mockStream = createReadableStream(['event: completion\nid: evt-1\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.event).toBeUndefined();
+ expect(events[0]?.id).toBe("evt-1");
+ expect(events[0]?.data).toEqual({ value: 1 });
+ });
+
+ it("should preserve metadata across chunked data", async () => {
+ const mockStream = createReadableStream(["id: ev", "t-1\nretry: 30", '00\ndata: {"val', 'ue": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([{ data: { value: 1 }, id: "evt-1", retry: 3000, event: undefined }]);
+ });
+
+ it("should update id between events in discriminator path", async () => {
+ const mockStream = createReadableStream([
+ 'event: msg\nid: first\ndata: {"n": 1}\n\nevent: msg\nid: second\ndata: {"n": 2}\n\nevent: msg\ndata: {"n": 3}\n\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.id).toBe("first");
+ expect(events[1]?.id).toBe("second");
+ expect(events[2]?.id).toBe("second");
+ });
+
+ it("should attach metadata on last event without trailing blank line", async () => {
+ const mockStream = createReadableStream([
+ 'event: completion\nid: last-1\nretry: 1000\ndata: {"content": "hi"}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse", eventDiscriminator: "type" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { type: "completion", content: "hi" }, id: "last-1", retry: 1000, event: "completion" },
+ ]);
+ });
+
+ it("should capture id after data line (customer scenario)", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"type":"model.message","thread_id":"main","created_at":"2026-06-26T06:58:53.649Z","id":"01kw1bjtjg1702sn5tf5esqwbm"}\nid: 2\n\ndata: {"content":"Hi","type":"model.message.delta","id":"01kw1bjtjg1702sn5tf5esqwbm","thread_id":"main","created_at":"2026-06-26T06:58:59.691Z"}\nid: 3\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ {
+ data: {
+ type: "model.message",
+ thread_id: "main",
+ created_at: "2026-06-26T06:58:53.649Z",
+ id: "01kw1bjtjg1702sn5tf5esqwbm",
+ },
+ id: "2",
+ retry: undefined,
+ event: undefined,
+ },
+ {
+ data: {
+ content: "Hi",
+ type: "model.message.delta",
+ id: "01kw1bjtjg1702sn5tf5esqwbm",
+ thread_id: "main",
+ created_at: "2026-06-26T06:58:59.691Z",
+ },
+ id: "3",
+ retry: undefined,
+ event: undefined,
+ },
+ ]);
+ });
+
+ it("should capture retry after data line", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"value": 1}\nretry: 5000\n\ndata: {"value": 2}\nretry: 3000\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { value: 1 }, id: undefined, retry: 5000, event: undefined },
+ { data: { value: 2 }, id: undefined, retry: 3000, event: undefined },
+ ]);
+ });
+
+ it("should capture both id and retry after data line", async () => {
+ const mockStream = createReadableStream([
+ 'data: {"value": 1}\nid: evt-1\nretry: 2000\n\ndata: {"value": 2}\nid: evt-2\nretry: 4000\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([
+ { data: { value: 1 }, id: "evt-1", retry: 2000, event: undefined },
+ { data: { value: 2 }, id: "evt-2", retry: 4000, event: undefined },
+ ]);
+ });
+
+ it("should handle chunked boundary splitting data and id lines", async () => {
+ const mockStream = createReadableStream(['data: {"value": 1}\n', "id: chunked-", "id\n\n"]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<{ value: number }>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([{ data: { value: 1 }, id: "chunked-id", retry: undefined, event: undefined }]);
+ });
+
+ it("should handle multiline data followed by id", async () => {
+ const mockStream = createReadableStream(['data: {"delta":\ndata: "hello"}\nid: multi-42\n\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events).toEqual([{ data: { delta: "hello" }, id: "multi-42", retry: undefined, event: undefined }]);
+ });
+
+ it("should handle mixed id ordering across events", async () => {
+ const mockStream = createReadableStream([
+ 'id: before-data\ndata: {"n": 1}\n\ndata: {"n": 2}\nid: after-data\n\ndata: {"n": 3}\n',
+ ]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val,
+ eventShape: { type: "sse" },
+ });
+
+ const events: ServerSentEvent<unknown>[] = [];
+ for await (const event of stream.withMetadata()) {
+ events.push(event);
+ }
+
+ expect(events[0]?.id).toBe("before-data");
+ expect(events[1]?.id).toBe("after-data");
+ expect(events[2]?.id).toBe("after-data");
+ });
+
+ it("should not affect default iteration which still yields T", async () => {
+ const mockStream = createReadableStream(['id: evt-1\nretry: 3000\ndata: {"value": 1}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+ });
+
+ describe("encoding and decoding", () => {
+ it("should decode UTF-8 text using TextDecoder", async () => {
+ const encoder = new TextEncoder();
+ const mockStream = createReadableStream([encoder.encode('{"text": "café"}\n')]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { text: string },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ text: "café" }]);
+ });
+
+ it("should decode emoji correctly", async () => {
+ const encoder = new TextEncoder();
+ const mockStream = createReadableStream([encoder.encode('{"emoji": "🎉"}\n')]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { emoji: string },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ emoji: "🎉" }]);
+ });
+
+ it("should handle binary data chunks", async () => {
+ const encoder = new TextEncoder();
+ const mockStream = createReadableStream([encoder.encode('{"val'), encoder.encode('ue": 1}\n')]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should handle multi-byte UTF-8 characters split across chunk boundaries", async () => {
+ // Test string with Japanese (3 bytes), Russian (2 bytes), German (2 bytes), and Chinese (3 bytes)
+ const testString = '{"text": "こんにちは Привет Größe 你好"}\n';
+ const fullBytes = new TextEncoder().encode(testString);
+
+ // Split the bytes in the middle of multi-byte characters
+ // Japanese "こ" starts at byte 11, is 3 bytes (E3 81 93)
+ // Split after first byte of "こ" to test mid-character splitting
+ const splitPoint = 12; // This splits "こ" in the middle
+ const chunk1 = fullBytes.slice(0, splitPoint);
+ const chunk2 = fullBytes.slice(splitPoint);
+
+ const mockStream = createReadableStream([chunk1, chunk2]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { text: string },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ text: "こんにちは Привет Größe 你好" }]);
+ });
+ });
+
+ describe("abort signal", () => {
+ it("should handle abort signal", async () => {
+ const controller = new AbortController();
+ const mockStream = createReadableStream(['{"value": 1}\n{"value": 2}\n{"value": 3}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ signal: controller.signal,
+ });
+
+ const messages: unknown[] = [];
+ let count = 0;
+ for await (const message of stream) {
+ messages.push(message);
+ count++;
+ if (count === 2) {
+ controller.abort();
+ break;
+ }
+ }
+
+ expect(messages.length).toBe(2);
+ });
+ });
+
+ describe("async iteration", () => {
+ it("should support async iterator protocol", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n{"value": 2}\n']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const iterator = stream[Symbol.asyncIterator]();
+ const first = await iterator.next();
+ expect(first.done).toBe(false);
+ expect(first.value).toEqual({ value: 1 });
+
+ const second = await iterator.next();
+ expect(second.done).toBe(false);
+ expect(second.value).toEqual({ value: 2 });
+
+ const third = await iterator.next();
+ expect(third.done).toBe(true);
+ });
+ });
+
+ describe("edge cases", () => {
+ it("should handle empty stream", async () => {
+ const mockStream = createReadableStream([]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([]);
+ });
+
+ it("should handle stream with only whitespace", async () => {
+ const mockStream = createReadableStream([" \n\n\t\n "]);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([]);
+ });
+
+ it("should handle incomplete message at end of stream", async () => {
+ const mockStream = createReadableStream(['{"value": 1}\n{"incomplete']);
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "json", messageTerminator: "\n" },
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+ });
+
+ describe("SSE stream reconnection", () => {
+ it("should reconnect on premature EOF when resumable", async () => {
+ const firstStream = createReadableStream([
+ 'id: 1\ndata: {"value": 1}\n\n',
+ 'id: 2\ndata: {"value": 2}\n\n',
+ ]);
+ const secondStream = createReadableStream(['id: 3\ndata: {"value": 3}\n\n', "data: [DONE]\n\n"]);
+
+ let reconnectCallCount = 0;
+ let lastReceivedEventId: string | undefined;
+ const reconnect = async (lastEventId: string) => {
+ reconnectCallCount++;
+ lastReceivedEventId = lastEventId;
+ return secondStream;
+ };
+
+ const stream = new Stream({
+ stream: firstStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ expect(reconnectCallCount).toBe(1);
+ expect(lastReceivedEventId).toBe("2");
+ });
+
+ it("should reconnect using the last dispatched id, not a parsed-but-undispatched id", async () => {
+ // evt-1 is fully dispatched; evt-2's id: line is parsed but the
+ // stream ends before evt-2's data + blank line, so evt-2 is never
+ // yielded. Reconnection must resume from evt-1 (the last dispatched
+ // id), otherwise evt-2 would be silently skipped.
+ const firstStream = createReadableStream(['id: evt-1\ndata: {"value": 1}\n\n', "id: evt-2\n"]);
+ const secondStream = createReadableStream(['id: evt-2\ndata: {"value": 2}\n\n', "data: [DONE]\n\n"]);
+
+ let reconnectCallCount = 0;
+ let lastReceivedEventId: string | undefined;
+ const reconnect = async (lastEventId: string) => {
+ reconnectCallCount++;
+ lastReceivedEventId = lastEventId;
+ return secondStream;
+ };
+
+ const stream = new Stream({
+ stream: firstStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ expect(reconnectCallCount).toBe(1);
+ expect(lastReceivedEventId).toBe("evt-1");
+ });
+
+ it("should not reconnect when reconnectionEnabled is false", async () => {
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: false,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+
+ it("should not reconnect when not resumable", async () => {
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: false },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+
+ it("should respect maxReconnectionAttempts", async () => {
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ // Return a stream that immediately ends without data (server down)
+ return createReadableStream([]);
+ };
+
+ const firstStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ const stream = new Stream({
+ stream: firstStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 3,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ // First stream yields 1, then reconnection attempts get empty streams
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(3);
+ });
+
+ it("should not reconnect when stream ends with terminator", async () => {
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n', "data: [DONE]\n\n"]);
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+
+ it("should not reconnect without a reconnect function", async () => {
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ });
+
+ it("should not reconnect without a lastId", async () => {
+ const mockStream = createReadableStream(['data: {"value": 1}\n\n']);
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+ });
+
+ describe("SSE stream reconnection - abort during delay", () => {
+ it("should stop promptly when aborted during reconnect delay", async () => {
+ const firstStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const abortController = new AbortController();
+ const stream = new Stream({
+ stream: firstStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ signal: abortController.signal,
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ const startTime = Date.now();
+
+ // Abort after a short delay (while the stream is in its reconnect delay)
+ setTimeout(() => abortController.abort(), 50);
+
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ const elapsed = Date.now() - startTime;
+ // Should have stopped well before the default 1000ms reconnect delay completes.
+ // Use a generous upper bound to avoid flakiness on slow CI runners.
+ expect(elapsed).toBeLessThan(800);
+ expect(messages).toEqual([{ value: 1 }]);
+ // reconnect should NOT have been called since we aborted during the delay
+ expect(reconnectCallCount).toBe(0);
+ });
+ });
+
+ describe("SSE stream reconnection - backoff with progress", () => {
+ it("should apply default backoff even when server sends no retry directive", async () => {
+ // Server yields 1 event then drops on each connection (no retry: field)
+ const streams = [
+ createReadableStream(['id: 1\ndata: {"value": 1}\n\n']),
+ createReadableStream(['id: 2\ndata: {"value": 2}\n\n']),
+ createReadableStream(['id: 3\ndata: {"value": 3}\n\ndata: [DONE]\n\n']),
+ ];
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ const s = streams[reconnectCallCount];
+ if (s == null) {
+ throw new Error(`unexpected reconnect call ${reconnectCallCount}`);
+ }
+ return s;
+ };
+
+ const startTime = Date.now();
+ const first = streams[0];
+ if (first == null) {
+ throw new Error("missing first stream");
+ }
+ const stream = new Stream({
+ stream: first,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ expect(reconnectCallCount).toBe(2);
+ // Total elapsed time should be at least 2 * DEFAULT_RECONNECT_DELAY_MS (~1000ms each).
+ // Use a slightly relaxed lower bound to tolerate timer jitter on slow CI.
+ const totalElapsed = Date.now() - startTime;
+ expect(totalElapsed).toBeGreaterThanOrEqual(1500);
+ });
+
+ it("should respect maxReconnectionAttempts even when each reconnect yields data", async () => {
+ // Server yields 1 event per connection, then drops (no terminator, no retry).
+ // reconnectAttempts resets on progress, so the cap is per-consecutive-failed-reconnects.
+ // With data yielded each time, reconnects reset and should keep going until terminator.
+ const streams = [
+ createReadableStream(['id: 1\ndata: {"value": 1}\n\n']),
+ createReadableStream(['id: 2\ndata: {"value": 2}\n\n']),
+ createReadableStream(['id: 3\ndata: {"value": 3}\n\ndata: [DONE]\n\n']),
+ ];
+
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ const s = streams[reconnectCallCount];
+ if (s == null) {
+ throw new Error(`unexpected reconnect call ${reconnectCallCount}`);
+ }
+ return s;
+ };
+
+ const first = streams[0];
+ if (first == null) {
+ throw new Error("missing first stream");
+ }
+ const stream = new Stream({
+ stream: first,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 1,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ // Even with maxReconnectionAttempts=1, since each reconnect yields data
+ // the counter resets; all 3 events are received.
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ expect(reconnectCallCount).toBe(2);
+ });
+ });
+
+ describe("SSE stream reconnection - terminator stops without extra reconnect", () => {
+ it("should stop immediately on terminator with zero reconnect calls", async () => {
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(["data: [DONE]\n\n"]);
+ };
+
+ const mockStream = createReadableStream([
+ 'id: 1\ndata: {"value": 1}\n\n',
+ 'id: 2\ndata: {"value": 2}\n\n',
+ "data: [DONE]\n\n",
+ ]);
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+
+ it("should stop immediately on terminator mid-stream without extra reconnect", async () => {
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(['id: 99\ndata: {"value": 99}\n\ndata: [DONE]\n\n']);
+ };
+
+ // Terminator arrives in the middle of a stream that still has more data buffered
+ const mockStream = createReadableStream([
+ 'id: 1\ndata: {"value": 1}\n\n',
+ 'id: 2\ndata: {"value": 2}\n\n',
+ "id: 3\ndata: [DONE]\n\n",
+ 'id: 4\ndata: {"value": 4}\n\n',
+ ]);
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ // Should stop at [DONE] and not yield event 4 or attempt reconnection
+ expect(messages).toEqual([{ value: 1 }, { value: 2 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+ });
+
+ describe("SSE stream reconnection - no terminator prevents reconnect", () => {
+ it("should not attempt reconnection when no streamTerminator is configured", async () => {
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ return createReadableStream(['id: 2\ndata: {"value": 2}\n\n']);
+ };
+
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 5,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ // Without a streamTerminator, shouldReconnect returns false
+ // to avoid a reconnect storm.
+ expect(messages).toEqual([{ value: 1 }]);
+ expect(reconnectCallCount).toBe(0);
+ });
+ });
+
+ describe("SSE stream reconnection - null reconnect body", () => {
+ it("should treat null reconnect body as a failed attempt", async () => {
+ let reconnectCallCount = 0;
+ const reconnect = async (_lastEventId: string) => {
+ reconnectCallCount++;
+ // @ts-expect-error Intentionally returning null to test null-body handling
+ return null;
+ };
+
+ const mockStream = createReadableStream(['id: 1\ndata: {"value": 1}\n\n']);
+
+ const stream = new Stream({
+ stream: mockStream,
+ parse: async (val: unknown) => val as { value: number },
+ eventShape: { type: "sse", streamTerminator: "[DONE]", resumable: true },
+ reconnectionEnabled: true,
+ maxReconnectionAttempts: 2,
+ reconnect,
+ });
+
+ const messages: unknown[] = [];
+ for await (const message of stream) {
+ messages.push(message);
+ }
+
+ expect(messages).toEqual([{ value: 1 }]);
+ // Both reconnect attempts returned null, exhausting maxReconnectionAttempts
+ expect(reconnectCallCount).toBe(2);
+ });
+ });
+});
+
+// Helper function to create a ReadableStream from string chunks
+function createReadableStream(chunks: (string | Uint8Array)[]): ReadableStream {
+ // For standard type, return ReadableStream
+ let index = 0;
+ return new ReadableStream({
+ pull(controller) {
+ if (index < chunks.length) {
+ const chunk = chunks[index++];
+ controller.enqueue(typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk);
+ } else {
+ controller.close();
+ }
+ },
+ });
+}
diff --git a/packages/sdk/tests/unit/url/QueryStringBuilder.test.ts b/packages/sdk/tests/unit/url/QueryStringBuilder.test.ts
new file mode 100644
index 000000000..1afa2d222
--- /dev/null
+++ b/packages/sdk/tests/unit/url/QueryStringBuilder.test.ts
@@ -0,0 +1,236 @@
+import { queryBuilder } from "../../../src/core/url/QueryStringBuilder";
+
+describe("QueryStringBuilder", () => {
+ describe("add() — default repeat format", () => {
+ it("adds a scalar string value", () => {
+ const qs = queryBuilder().add("key", "value").build();
+ expect(qs).toBe("key=value");
+ });
+
+ it("adds a scalar number value", () => {
+ const qs = queryBuilder().add("limit", 10).build();
+ expect(qs).toBe("limit=10");
+ });
+
+ it("adds a boolean value", () => {
+ const qs = queryBuilder().add("active", true).build();
+ expect(qs).toBe("active=true");
+ });
+
+ it("skips undefined values", () => {
+ const qs = queryBuilder().add("key", undefined).build();
+ expect(qs).toBe("");
+ });
+
+ it("skips null values", () => {
+ const qs = queryBuilder().add("key", null).build();
+ expect(qs).toBe("");
+ });
+
+ it("repeats array elements as separate key=value pairs", () => {
+ const qs = queryBuilder().add("color", ["red", "blue", "green"]).build();
+ expect(qs).toBe("color=red&color=blue&color=green");
+ });
+
+ it("skips undefined items within arrays", () => {
+ const qs = queryBuilder().add("color", ["red", undefined, "blue"]).build();
+ expect(qs).toBe("color=red&color=blue");
+ });
+
+ it("returns empty string for empty array", () => {
+ const qs = queryBuilder().add("color", []).build();
+ expect(qs).toBe("");
+ });
+
+ it("encodes special characters in keys and values", () => {
+ const qs = queryBuilder().add("my key", "hello world").build();
+ expect(qs).toBe("my%20key=hello%20world");
+ });
+
+ it("handles nested objects", () => {
+ const qs = queryBuilder().add("filter", { status: "active" }).build();
+ expect(qs).toBe("filter%5Bstatus%5D=active");
+ });
+ });
+
+ describe("add() — comma style", () => {
+ it("joins array values with literal commas", () => {
+ const qs = queryBuilder().add("tags", ["a", "b", "c"], { style: "comma" }).build();
+ expect(qs).toBe("tags=a,b,c");
+ });
+
+ it("handles single-element array", () => {
+ const qs = queryBuilder().add("tags", ["only"], { style: "comma" }).build();
+ expect(qs).toBe("tags=only");
+ });
+
+ it("returns empty string for empty array", () => {
+ const qs = queryBuilder().add("tags", [], { style: "comma" }).build();
+ expect(qs).toBe("");
+ });
+
+ it("skips undefined values", () => {
+ const qs = queryBuilder().add("tags", undefined, { style: "comma" }).build();
+ expect(qs).toBe("");
+ });
+
+ it("skips null values", () => {
+ const qs = queryBuilder().add("tags", null, { style: "comma" }).build();
+ expect(qs).toBe("");
+ });
+
+ it("treats scalar values same as default add()", () => {
+ const qs = queryBuilder().add("tag", "single", { style: "comma" }).build();
+ expect(qs).toBe("tag=single");
+ });
+
+ it("encodes commas within individual values as %2C", () => {
+ const qs = queryBuilder().add("items", ["a,b", "c"], { style: "comma" }).build();
+ expect(qs).toBe("items=a%2Cb,c");
+ });
+
+ it("encodes special characters in values", () => {
+ const qs = queryBuilder().add("tags", ["hello world", "foo&bar"], { style: "comma" }).build();
+ expect(qs).toBe("tags=hello%20world,foo%26bar");
+ });
+ });
+
+ describe("chaining", () => {
+ it("chains multiple add() calls", () => {
+ const qs = queryBuilder().add("limit", 10).add("offset", 20).build();
+ expect(qs).toBe("limit=10&offset=20");
+ });
+
+ it("chains add() with default and comma styles", () => {
+ const qs = queryBuilder()
+ .add("limit", 10)
+ .add("tags", ["ACCESS_GRANTED", "COPY", "DELETE"], { style: "comma" })
+ .add("active", true)
+ .build();
+ expect(qs).toBe("limit=10&tags=ACCESS_GRANTED,COPY,DELETE&active=true");
+ });
+
+ it("skips undefined/null params in chain without breaking", () => {
+ const qs = queryBuilder()
+ .add("a", "1")
+ .add("b", undefined)
+ .add("c", null, { style: "comma" })
+ .add("d", "4")
+ .build();
+ expect(qs).toBe("a=1&d=4");
+ });
+ });
+
+ describe("addMany()", () => {
+ it("adds all params from a record", () => {
+ const qs = queryBuilder().addMany({ limit: 10, offset: 20, name: "test" }).build();
+ expect(qs).toBe("limit=10&offset=20&name=test");
+ });
+
+ it("skips null and undefined values", () => {
+ const qs = queryBuilder().addMany({ a: "1", b: null, c: undefined, d: "4" }).build();
+ expect(qs).toBe("a=1&d=4");
+ });
+
+ it("handles empty record", () => {
+ const qs = queryBuilder().addMany({}).build();
+ expect(qs).toBe("");
+ });
+
+ it("works with comma-style override after addMany", () => {
+ const params = { limit: 10, tags: ["a", "b"], active: true };
+ const qs = queryBuilder().addMany(params).add("tags", params.tags, { style: "comma" }).build();
+ expect(qs).toBe("limit=10&tags=a,b&active=true");
+ });
+
+ it("handles array values with default repeat format", () => {
+ const qs = queryBuilder()
+ .addMany({ ids: [1, 2, 3] })
+ .build();
+ expect(qs).toBe("ids=1&ids=2&ids=3");
+ });
+ });
+
+ describe("mergeAdditional()", () => {
+ it("appends additional params", () => {
+ const qs = queryBuilder().add("limit", 10).mergeAdditional({ extra: "value" }).build();
+ expect(qs).toBe("limit=10&extra=value");
+ });
+
+ it("overrides existing keys (last-write-wins)", () => {
+ const qs = queryBuilder().add("limit", 10).mergeAdditional({ limit: 20 }).build();
+ expect(qs).toBe("limit=20");
+ });
+
+ it("handles undefined additional params", () => {
+ const qs = queryBuilder().add("limit", 10).mergeAdditional(undefined).build();
+ expect(qs).toBe("limit=10");
+ });
+
+ it("skips undefined values in additional params", () => {
+ const qs = queryBuilder().add("limit", 10).mergeAdditional({ extra: undefined }).build();
+ expect(qs).toBe("limit=10");
+ });
+
+ it("skips null values in additional params", () => {
+ const qs = queryBuilder().add("limit", 10).mergeAdditional({ extra: null }).build();
+ expect(qs).toBe("limit=10");
+ });
+
+ it("handles array values in additional params using repeat format", () => {
+ const qs = queryBuilder()
+ .mergeAdditional({ ids: [1, 2, 3] })
+ .build();
+ expect(qs).toBe("ids=1&ids=2&ids=3");
+ });
+
+ it("overrides a comma-style param with repeat format", () => {
+ const qs = queryBuilder()
+ .add("tags", ["a", "b"], { style: "comma" })
+ .mergeAdditional({ tags: ["x", "y"] })
+ .build();
+ expect(qs).toBe("tags=x&tags=y");
+ });
+ });
+
+ describe("build()", () => {
+ it("returns empty string when no params added", () => {
+ const qs = queryBuilder().build();
+ expect(qs).toBe("");
+ });
+
+ it("does not include leading ?", () => {
+ const qs = queryBuilder().add("key", "value").build();
+ expect(qs).not.toContain("?");
+ });
+ });
+
+ describe("end-to-end scenarios", () => {
+ it("matches expected query-parameters-openapi output pattern", () => {
+ const params: Record<string, unknown> = {
+ limit: 1,
+ id: "d5e9c84f-c2b2-4bf4-b4b0-7ffd7a9ffc32",
+ date: "2023-01-15",
+ deadline: "2024-01-15T09:30:00.000Z",
+ bytes: "SGVsbG8gd29ybGQh",
+ user: "user",
+ userList: ["user"],
+ optionalString: "optionalString",
+ nestedUser: "nestedUser",
+ excludeUser: "excludeUser",
+ filter: "filter",
+ tags: ["tags"],
+ optionalTags: undefined,
+ };
+ const qs = queryBuilder()
+ .addMany(params)
+ .add("tags", params.tags, { style: "comma" })
+ .add("optionalTags", params.optionalTags, { style: "comma" })
+ .mergeAdditional(undefined)
+ .build();
+ expect(qs).toContain("limit=1");
+ expect(qs).toContain("tags=tags");
+ expect(qs).not.toContain("optionalTags");
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/url/join.test.ts b/packages/sdk/tests/unit/url/join.test.ts
new file mode 100644
index 000000000..123488f08
--- /dev/null
+++ b/packages/sdk/tests/unit/url/join.test.ts
@@ -0,0 +1,284 @@
+import { join } from "../../../src/core/url/index";
+
+describe("join", () => {
+ interface TestCase {
+ description: string;
+ base: string;
+ segments: string[];
+ expected: string;
+ }
+
+ describe("basic functionality", () => {
+ const basicTests: TestCase[] = [
+ { description: "should return empty string for empty base", base: "", segments: [], expected: "" },
+ {
+ description: "should return empty string for empty base with path",
+ base: "",
+ segments: ["path"],
+ expected: "",
+ },
+ {
+ description: "should handle single segment",
+ base: "base",
+ segments: ["segment"],
+ expected: "base/segment",
+ },
+ {
+ description: "should handle single segment with trailing slash on base",
+ base: "base/",
+ segments: ["segment"],
+ expected: "base/segment",
+ },
+ {
+ description: "should handle single segment with leading slash",
+ base: "base",
+ segments: ["/segment"],
+ expected: "base/segment",
+ },
+ {
+ description: "should handle single segment with both slashes",
+ base: "base/",
+ segments: ["/segment"],
+ expected: "base/segment",
+ },
+ {
+ description: "should handle multiple segments",
+ base: "base",
+ segments: ["path1", "path2", "path3"],
+ expected: "base/path1/path2/path3",
+ },
+ {
+ description: "should handle multiple segments with slashes",
+ base: "base/",
+ segments: ["/path1/", "/path2/", "/path3/"],
+ expected: "base/path1/path2/path3/",
+ },
+ ];
+
+ basicTests.forEach(({ description, base, segments, expected }) => {
+ it(description, () => {
+ expect(join(base, ...segments)).toBe(expected);
+ });
+ });
+ });
+
+ describe("URL handling", () => {
+ const urlTests: TestCase[] = [
+ {
+ description: "should handle absolute URLs",
+ base: "https://example.com",
+ segments: ["api", "v1"],
+ expected: "https://example.com/api/v1",
+ },
+ {
+ description: "should handle absolute URLs with slashes",
+ base: "https://example.com/",
+ segments: ["/api/", "/v1/"],
+ expected: "https://example.com/api/v1/",
+ },
+ {
+ description: "should handle absolute URLs with base path",
+ base: "https://example.com/base",
+ segments: ["api", "v1"],
+ expected: "https://example.com/base/api/v1",
+ },
+ {
+ description: "should preserve URL query parameters",
+ base: "https://example.com?query=1",
+ segments: ["api"],
+ expected: "https://example.com/api?query=1",
+ },
+ {
+ description: "should preserve URL fragments",
+ base: "https://example.com#fragment",
+ segments: ["api"],
+ expected: "https://example.com/api#fragment",
+ },
+ {
+ description: "should preserve URL query and fragments",
+ base: "https://example.com?query=1#fragment",
+ segments: ["api"],
+ expected: "https://example.com/api?query=1#fragment",
+ },
+ {
+ description: "should handle http protocol",
+ base: "http://example.com",
+ segments: ["api"],
+ expected: "http://example.com/api",
+ },
+ {
+ description: "should handle ftp protocol",
+ base: "ftp://example.com",
+ segments: ["files"],
+ expected: "ftp://example.com/files",
+ },
+ {
+ description: "should handle ws protocol",
+ base: "ws://example.com",
+ segments: ["socket"],
+ expected: "ws://example.com/socket",
+ },
+ {
+ description: "should fallback to path joining for malformed URLs",
+ base: "not-a-url://",
+ segments: ["path"],
+ expected: "not-a-url:///path",
+ },
+ ];
+
+ urlTests.forEach(({ description, base, segments, expected }) => {
+ it(description, () => {
+ expect(join(base, ...segments)).toBe(expected);
+ });
+ });
+ });
+
+ describe("edge cases", () => {
+ const edgeCaseTests: TestCase[] = [
+ {
+ description: "should handle empty segments",
+ base: "base",
+ segments: ["", "path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle null segments",
+ base: "base",
+ segments: [null as any, "path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle undefined segments",
+ base: "base",
+ segments: [undefined as any, "path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle segments with only single slash",
+ base: "base",
+ segments: ["/", "path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle segments with only double slash",
+ base: "base",
+ segments: ["//", "path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle base paths with trailing slashes",
+ base: "base/",
+ segments: ["path"],
+ expected: "base/path",
+ },
+ {
+ description: "should handle complex nested paths",
+ base: "api/v1/",
+ segments: ["/users/", "/123/", "/profile"],
+ expected: "api/v1/users/123/profile",
+ },
+ ];
+
+ edgeCaseTests.forEach(({ description, base, segments, expected }) => {
+ it(description, () => {
+ expect(join(base, ...segments)).toBe(expected);
+ });
+ });
+ });
+
+ describe("real-world scenarios", () => {
+ const realWorldTests: TestCase[] = [
+ {
+ description: "should handle API endpoint construction",
+ base: "https://api.example.com/v1",
+ segments: ["users", "123", "posts"],
+ expected: "https://api.example.com/v1/users/123/posts",
+ },
+ {
+ description: "should handle file path construction",
+ base: "/var/www",
+ segments: ["html", "assets", "images"],
+ expected: "/var/www/html/assets/images",
+ },
+ {
+ description: "should handle relative path construction",
+ base: "../parent",
+ segments: ["child", "grandchild"],
+ expected: "../parent/child/grandchild",
+ },
+ {
+ description: "should handle Windows-style paths",
+ base: "C:\\Users",
+ segments: ["Documents", "file.txt"],
+ expected: "C:\\Users/Documents/file.txt",
+ },
+ ];
+
+ realWorldTests.forEach(({ description, base, segments, expected }) => {
+ it(description, () => {
+ expect(join(base, ...segments)).toBe(expected);
+ });
+ });
+ });
+
+ describe("performance scenarios", () => {
+ it("should handle many segments efficiently", () => {
+ const segments = Array(100).fill("segment");
+ const result = join("base", ...segments);
+ expect(result).toBe(`base/${segments.join("/")}`);
+ });
+
+ it("should handle long URLs", () => {
+ const longPath = "a".repeat(1000);
+ expect(join("https://example.com", longPath)).toBe(`https://example.com/${longPath}`);
+ });
+ });
+
+ describe("trailing slash preservation", () => {
+ const trailingSlashTests: TestCase[] = [
+ {
+ description:
+ "should preserve trailing slash on final result when base has trailing slash and no segments",
+ base: "https://api.example.com/",
+ segments: [],
+ expected: "https://api.example.com/",
+ },
+ {
+ description: "should preserve trailing slash on v1 path",
+ base: "https://api.example.com/v1/",
+ segments: [],
+ expected: "https://api.example.com/v1/",
+ },
+ {
+ description: "should preserve trailing slash when last segment has trailing slash",
+ base: "https://api.example.com",
+ segments: ["users/"],
+ expected: "https://api.example.com/users/",
+ },
+ {
+ description: "should preserve trailing slash with relative path",
+ base: "api/v1",
+ segments: ["users/"],
+ expected: "api/v1/users/",
+ },
+ {
+ description: "should preserve trailing slash with multiple segments",
+ base: "https://api.example.com",
+ segments: ["v1", "collections/"],
+ expected: "https://api.example.com/v1/collections/",
+ },
+ {
+ description: "should preserve trailing slash with base path",
+ base: "base",
+ segments: ["path1", "path2/"],
+ expected: "base/path1/path2/",
+ },
+ ];
+
+ trailingSlashTests.forEach(({ description, base, segments, expected }) => {
+ it(description, () => {
+ expect(join(base, ...segments)).toBe(expected);
+ });
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/url/qs.test.ts b/packages/sdk/tests/unit/url/qs.test.ts
new file mode 100644
index 000000000..54d2d9ce3
--- /dev/null
+++ b/packages/sdk/tests/unit/url/qs.test.ts
@@ -0,0 +1,374 @@
+import { toQueryString } from "../../../src/core/url/index";
+
+describe("Test qs toQueryString", () => {
+ interface BasicTestCase {
+ description: string;
+ input: any;
+ expected: string;
+ }
+
+ describe("Basic functionality", () => {
+ const basicTests: BasicTestCase[] = [
+ { description: "should return empty string for null", input: null, expected: "" },
+ { description: "should return empty string for undefined", input: undefined, expected: "" },
+ { description: "should return empty string for string primitive", input: "hello", expected: "" },
+ { description: "should return empty string for number primitive", input: 42, expected: "" },
+ { description: "should return empty string for true boolean", input: true, expected: "" },
+ { description: "should return empty string for false boolean", input: false, expected: "" },
+ { description: "should handle empty objects", input: {}, expected: "" },
+ {
+ description: "should handle simple key-value pairs",
+ input: { name: "John", age: 30 },
+ expected: "name=John&age=30",
+ },
+ ];
+
+ basicTests.forEach(({ description, input, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Array handling", () => {
+ interface ArrayTestCase {
+ description: string;
+ input: any;
+ options?: { arrayFormat?: "repeat" | "indices" | "comma" };
+ expected: string;
+ }
+
+ const arrayTests: ArrayTestCase[] = [
+ {
+ description: "should handle arrays with indices format (default)",
+ input: { items: ["a", "b", "c"] },
+ expected: "items%5B0%5D=a&items%5B1%5D=b&items%5B2%5D=c",
+ },
+ {
+ description: "should handle arrays with repeat format",
+ input: { items: ["a", "b", "c"] },
+ options: { arrayFormat: "repeat" },
+ expected: "items=a&items=b&items=c",
+ },
+ {
+ description: "should handle empty arrays",
+ input: { items: [] },
+ expected: "",
+ },
+ {
+ description: "should handle arrays with mixed types",
+ input: { mixed: ["string", 42, true, false] },
+ expected: "mixed%5B0%5D=string&mixed%5B1%5D=42&mixed%5B2%5D=true&mixed%5B3%5D=false",
+ },
+ {
+ description: "should handle arrays with objects",
+ input: { users: [{ name: "John" }, { name: "Jane" }] },
+ expected: "users%5B0%5D%5Bname%5D=John&users%5B1%5D%5Bname%5D=Jane",
+ },
+ {
+ description: "should handle arrays with objects in repeat format",
+ input: { users: [{ name: "John" }, { name: "Jane" }] },
+ options: { arrayFormat: "repeat" },
+ expected: "users%5Bname%5D=John&users%5Bname%5D=Jane",
+ },
+ ];
+
+ arrayTests.forEach(({ description, input, options, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input, options)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Nested objects", () => {
+ const nestedTests: BasicTestCase[] = [
+ {
+ description: "should handle nested objects",
+ input: { user: { name: "John", age: 30 } },
+ expected: "user%5Bname%5D=John&user%5Bage%5D=30",
+ },
+ {
+ description: "should handle deeply nested objects",
+ input: { user: { profile: { name: "John", settings: { theme: "dark" } } } },
+ expected: "user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark",
+ },
+ {
+ description: "should handle empty nested objects",
+ input: { user: {} },
+ expected: "",
+ },
+ ];
+
+ nestedTests.forEach(({ description, input, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Encoding", () => {
+ interface EncodingTestCase {
+ description: string;
+ input: any;
+ options?: { encode?: boolean };
+ expected: string;
+ }
+
+ const encodingTests: EncodingTestCase[] = [
+ {
+ description: "should encode by default",
+ input: { name: "John Doe", email: "[email protected]" },
+ expected: "name=John%20Doe&email=john%40example.com",
+ },
+ {
+ description: "should not encode when encode is false",
+ input: { name: "John Doe", email: "[email protected]" },
+ options: { encode: false },
+ expected: "name=John Doe&[email protected]",
+ },
+ {
+ description: "should encode special characters in keys",
+ input: { "user name": "John", "email[primary]": "[email protected]" },
+ expected: "user%20name=John&email%5Bprimary%5D=john%40example.com",
+ },
+ {
+ description: "should not encode special characters in keys when encode is false",
+ input: { "user name": "John", "email[primary]": "[email protected]" },
+ options: { encode: false },
+ expected: "user name=John&email[primary][email protected]",
+ },
+ ];
+
+ encodingTests.forEach(({ description, input, options, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input, options)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Mixed scenarios", () => {
+ interface MixedTestCase {
+ description: string;
+ input: any;
+ options?: { arrayFormat?: "repeat" | "indices" | "comma" };
+ expected: string;
+ }
+
+ const mixedTests: MixedTestCase[] = [
+ {
+ description: "should handle complex nested structures",
+ input: {
+ filters: {
+ status: ["active", "pending"],
+ category: {
+ type: "electronics",
+ subcategories: ["phones", "laptops"],
+ },
+ },
+ sort: { field: "name", direction: "asc" },
+ },
+ expected:
+ "filters%5Bstatus%5D%5B0%5D=active&filters%5Bstatus%5D%5B1%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D%5B0%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D%5B1%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc",
+ },
+ {
+ description: "should handle complex nested structures with repeat format",
+ input: {
+ filters: {
+ status: ["active", "pending"],
+ category: {
+ type: "electronics",
+ subcategories: ["phones", "laptops"],
+ },
+ },
+ sort: { field: "name", direction: "asc" },
+ },
+ options: { arrayFormat: "repeat" },
+ expected:
+ "filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc",
+ },
+ {
+ description: "should handle arrays with null/undefined values",
+ input: { items: ["a", null, "c", undefined, "e"] },
+ expected: "items%5B0%5D=a&items%5B2%5D=c&items%5B4%5D=e",
+ },
+ {
+ description: "should handle objects with null/undefined values",
+ input: { name: "John", age: null, email: undefined, active: true },
+ expected: "name=John&active=true",
+ },
+ ];
+
+ mixedTests.forEach(({ description, input, options, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input, options)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Edge cases", () => {
+ const edgeCaseTests: BasicTestCase[] = [
+ {
+ description: "should handle numeric keys",
+ input: { "0": "zero", "1": "one" },
+ expected: "0=zero&1=one",
+ },
+ {
+ description: "should handle boolean values in objects",
+ input: { enabled: true, disabled: false },
+ expected: "enabled=true&disabled=false",
+ },
+ {
+ description: "should handle empty strings",
+ input: { name: "", description: "test" },
+ expected: "name=&description=test",
+ },
+ {
+ description: "should handle zero values",
+ input: { count: 0, price: 0.0 },
+ expected: "count=0&price=0",
+ },
+ {
+ description: "should handle arrays with empty strings",
+ input: { items: ["a", "", "c"] },
+ expected: "items%5B0%5D=a&items%5B1%5D=&items%5B2%5D=c",
+ },
+ ];
+
+ edgeCaseTests.forEach(({ description, input, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Comma array format", () => {
+ interface CommaTestCase {
+ description: string;
+ input: any;
+ options?: { arrayFormat?: "comma"; encode?: boolean };
+ expected: string;
+ }
+
+ const commaTests: CommaTestCase[] = [
+ {
+ description: "should join array values with commas",
+ input: { event_type: ["ACCESS_GRANTED", "COPY", "DELETE"] },
+ options: { arrayFormat: "comma" },
+ expected: "event_type=ACCESS_GRANTED,COPY,DELETE",
+ },
+ {
+ description: "should handle single-element array",
+ input: { event_type: ["ACCESS_GRANTED"] },
+ options: { arrayFormat: "comma" },
+ expected: "event_type=ACCESS_GRANTED",
+ },
+ {
+ description: "should handle empty array",
+ input: { event_type: [] },
+ options: { arrayFormat: "comma" },
+ expected: "",
+ },
+ {
+ description: "should not percent-encode commas",
+ input: { items: ["a", "b", "c"] },
+ options: { arrayFormat: "comma" },
+ expected: "items=a,b,c",
+ },
+ {
+ description: "should encode values but not commas",
+ input: { items: ["a b", "c d"] },
+ options: { arrayFormat: "comma" },
+ expected: "items=a%20b,c%20d",
+ },
+ {
+ description: "should not encode when encode is false",
+ input: { items: ["a b", "c d"] },
+ options: { arrayFormat: "comma", encode: false },
+ expected: "items=a b,c d",
+ },
+ {
+ description: "should handle mixed parameters with comma and non-array values",
+ input: { event_type: ["ACCESS_GRANTED", "COPY", "DELETE"], limit: 10, offset: 0 },
+ options: { arrayFormat: "comma" },
+ expected: "event_type=ACCESS_GRANTED,COPY,DELETE&limit=10&offset=0",
+ },
+ {
+ description: "should handle numeric array values",
+ input: { ids: [1, 2, 3] },
+ options: { arrayFormat: "comma" },
+ expected: "ids=1,2,3",
+ },
+ {
+ description: "should handle boolean array values",
+ input: { flags: [true, false, true] },
+ options: { arrayFormat: "comma" },
+ expected: "flags=true,false,true",
+ },
+ {
+ description: "should skip null values in comma format",
+ input: { items: ["a", null, "c"] },
+ options: { arrayFormat: "comma" },
+ expected: "items=a,c",
+ },
+ {
+ description: "should skip undefined values in comma format",
+ input: { items: ["a", undefined, "c"] },
+ options: { arrayFormat: "comma" },
+ expected: "items=a,c",
+ },
+ {
+ description: "should produce empty string for all-null array in comma format",
+ input: { items: [null, undefined] },
+ options: { arrayFormat: "comma" },
+ expected: "",
+ },
+ {
+ description: "should encode commas within values while keeping separator commas literal",
+ input: { items: ["a,b", "c"] },
+ options: { arrayFormat: "comma" },
+ expected: "items=a%2Cb,c",
+ },
+ ];
+
+ commaTests.forEach(({ description, input, options, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input, options)).toBe(expected);
+ });
+ });
+ });
+
+ describe("Options combinations", () => {
+ interface OptionsTestCase {
+ description: string;
+ input: any;
+ options?: { arrayFormat?: "repeat" | "indices" | "comma"; encode?: boolean };
+ expected: string;
+ }
+
+ const optionsTests: OptionsTestCase[] = [
+ {
+ description: "should respect both arrayFormat and encode options",
+ input: { items: ["a & b", "c & d"] },
+ options: { arrayFormat: "repeat", encode: false },
+ expected: "items=a & b&items=c & d",
+ },
+ {
+ description: "should use default options when none provided",
+ input: { items: ["a", "b"] },
+ expected: "items%5B0%5D=a&items%5B1%5D=b",
+ },
+ {
+ description: "should merge provided options with defaults",
+ input: { items: ["a", "b"], name: "John Doe" },
+ options: { encode: false },
+ expected: "items[0]=a&items[1]=b&name=John Doe",
+ },
+ ];
+
+ optionsTests.forEach(({ description, input, options, expected }) => {
+ it(description, () => {
+ expect(toQueryString(input, options)).toBe(expected);
+ });
+ });
+ });
+});
diff --git a/packages/sdk/tests/unit/utils/setObjectProperty.test.ts b/packages/sdk/tests/unit/utils/setObjectProperty.test.ts
new file mode 100644
index 000000000..29f8e638d
--- /dev/null
+++ b/packages/sdk/tests/unit/utils/setObjectProperty.test.ts
@@ -0,0 +1,76 @@
+import { setObjectProperty } from "../../../src/core/utils/setObjectProperty";
+
+interface TestCase {
+ description: string;
+ giveObject: object;
+ givePath: string;
+ giveValue: any;
+ wantObject: object;
+}
+
+describe("Test setObjectProperty", () => {
+ const testCases: TestCase[] = [
+ {
+ description: "empty",
+ giveObject: {},
+ givePath: "",
+ giveValue: 0,
+ wantObject: { "": 0 },
+ },
+ {
+ description: "top-level primitive",
+ giveObject: {},
+ givePath: "age",
+ giveValue: 42,
+ wantObject: { age: 42 },
+ },
+ {
+ description: "top-level object",
+ giveObject: {},
+ givePath: "name",
+ giveValue: { first: "John", last: "Doe" },
+ wantObject: { name: { first: "John", last: "Doe" } },
+ },
+ {
+ description: "top-level array",
+ giveObject: {},
+ givePath: "values",
+ giveValue: [1, 2, 3],
+ wantObject: { values: [1, 2, 3] },
+ },
+ {
+ description: "nested object property",
+ giveObject: {
+ name: {
+ first: "John",
+ },
+ },
+ givePath: "name.last",
+ giveValue: "Doe",
+ wantObject: { name: { first: "John", last: "Doe" } },
+ },
+ {
+ description: "deeply nested object property",
+ giveObject: {
+ info: {
+ address: {
+ street: "123 Main St.",
+ },
+ age: 42,
+ name: {
+ last: "Doe",
+ },
+ },
+ },
+ givePath: "info.name.first",
+ giveValue: "John",
+ wantObject: {
+ info: { age: 42, address: { street: "123 Main St." }, name: { first: "John", last: "Doe" } },
+ },
+ },
+ ];
+ test.each(testCases)("$description", ({ giveObject, givePath, giveValue, wantObject }) => {
+ const result = setObjectProperty(giveObject, givePath, giveValue);
+ expect(result).toEqual(wantObject);
+ });
+});
diff --git a/packages/sdk/tests/wire/.gitkeep b/packages/sdk/tests/wire/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/sdk/tests/wire/mcpServers.test.ts b/packages/sdk/tests/wire/mcpServers.test.ts
new file mode 100644
index 000000000..5ea5ba678
--- /dev/null
+++ b/packages/sdk/tests/wire/mcpServers.test.ts
@@ -0,0 +1,107 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import * as TrueHarnessTypes from "../../src/api/index";
+import { TrueHarness } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("McpServersClient", () => {
+ test("list", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { data: [{ name: "name", url: "url" }] };
+
+ server.mockEndpoint().get("/v1/mcp-servers").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+
+ const response = await client.mcpServers.list();
+ expect(response).toEqual({
+ data: [
+ {
+ name: "name",
+ url: "url",
+ },
+ ],
+ });
+ });
+
+ test("list_tools (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { data: [{ key: "value" }] };
+
+ server
+ .mockEndpoint()
+ .get("/v1/mcp-servers/name/tools")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.mcpServers.listTools("name");
+ expect(response).toEqual({
+ data: [
+ {
+ key: "value",
+ },
+ ],
+ });
+ });
+
+ test("list_tools (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/mcp-servers/name/tools")
+ .respondWith()
+ .statusCode(401)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.mcpServers.listTools("name");
+ }).rejects.toThrow(TrueHarnessTypes.UnauthorizedError);
+ });
+
+ test("list_tools (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/mcp-servers/name/tools")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.mcpServers.listTools("name");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("list_tools (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/mcp-servers/name/tools")
+ .respondWith()
+ .statusCode(502)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.mcpServers.listTools("name");
+ }).rejects.toThrow(TrueHarnessTypes.BadGatewayError);
+ });
+});
diff --git a/packages/sdk/tests/wire/models.test.ts b/packages/sdk/tests/wire/models.test.ts
new file mode 100644
index 000000000..0e8f87c1c
--- /dev/null
+++ b/packages/sdk/tests/wire/models.test.ts
@@ -0,0 +1,28 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import { TrueHarness } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("ModelsClient", () => {
+ test("list", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [{ max_output_tokens: 1, name: "name", reasoning_efforts: ["reasoning_efforts"] }],
+ };
+
+ server.mockEndpoint().get("/v1/models").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+
+ const response = await client.models.list();
+ expect(response).toEqual({
+ data: [
+ {
+ maxOutputTokens: 1,
+ name: "name",
+ reasoningEfforts: ["reasoning_efforts"],
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/sdk/tests/wire/server.test.ts b/packages/sdk/tests/wire/server.test.ts
new file mode 100644
index 000000000..46b5807ca
--- /dev/null
+++ b/packages/sdk/tests/wire/server.test.ts
@@ -0,0 +1,24 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import { TrueHarness } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("ServerClient", () => {
+ test("get_capabilities", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { data: { sandbox: { enabled: true } } };
+
+ server.mockEndpoint().get("/v1/capabilities").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+
+ const response = await client.server.getCapabilities();
+ expect(response).toEqual({
+ data: {
+ sandbox: {
+ enabled: true,
+ },
+ },
+ });
+ });
+});
diff --git a/packages/sdk/tests/wire/sessions.test.ts b/packages/sdk/tests/wire/sessions.test.ts
new file mode 100644
index 000000000..2c08ef288
--- /dev/null
+++ b/packages/sdk/tests/wire/sessions.test.ts
@@ -0,0 +1,942 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import * as TrueHarnessTypes from "../../src/api/index";
+import { TrueHarness } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("SessionsClient", () => {
+ test("list (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [
+ {
+ agent_spec: { model: { name: "name" } },
+ created_at: "created_at",
+ id: "id",
+ title: "title",
+ updated_at: "updated_at",
+ },
+ ],
+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },
+ };
+
+ server
+ .mockEndpoint({ once: false })
+ .get("/v1/sessions")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const expected = {
+ data: [
+ {
+ agentSpec: {
+ model: {
+ name: "name",
+ },
+ },
+ createdAt: "created_at",
+ id: "id",
+ title: "title",
+ updatedAt: "updated_at",
+ },
+ ],
+ pagination: {
+ limit: 1,
+ nextPageToken: "next_page_token",
+ previousPageToken: "previous_page_token",
+ },
+ };
+ const page = await client.sessions.list();
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
+ });
+
+ test("list (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server.mockEndpoint().get("/v1/sessions").respondWith().statusCode(400).jsonBody(rawResponseBody).build();
+
+ await expect(async () => {
+ return await client.sessions.list();
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("create (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = { agent_spec: { model: { name: "name" } } };
+ const rawResponseBody = {
+ data: {
+ agent_spec: {
+ instructions: "instructions",
+ mcp_servers: [{ name: "name" }],
+ messages: [{ content: "content", type: "user.message" }],
+ model: { name: "name" },
+ response_format: { type: "text" },
+ skills: [{ description: "description", name: "name", ref: "ref", type: "git", url: "url" }],
+ variables: { key: "value" },
+ },
+ created_at: "created_at",
+ id: "id",
+ title: "title",
+ updated_at: "updated_at",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.create({
+ agentSpec: {
+ model: {
+ name: "name",
+ },
+ },
+ });
+ expect(response).toEqual({
+ data: {
+ agentSpec: {
+ instructions: "instructions",
+ mcpServers: [
+ {
+ name: "name",
+ },
+ ],
+ messages: [
+ {
+ content: "content",
+ type: "user.message",
+ },
+ ],
+ model: {
+ name: "name",
+ },
+ responseFormat: {
+ type: "text",
+ },
+ skills: [
+ {
+ description: "description",
+ name: "name",
+ ref: "ref",
+ type: "git",
+ url: "url",
+ },
+ ],
+ variables: {
+ key: "value",
+ },
+ },
+ createdAt: "created_at",
+ id: "id",
+ title: "title",
+ updatedAt: "updated_at",
+ },
+ });
+ });
+
+ test("create (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = { agent_spec: { model: { name: "x" } } };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.create({
+ agentSpec: {
+ model: {
+ name: "x",
+ },
+ },
+ });
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("create (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = { agent_spec: { model: { name: "x" } } };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(422)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.create({
+ agentSpec: {
+ model: {
+ name: "x",
+ },
+ },
+ });
+ }).rejects.toThrow(TrueHarnessTypes.UnprocessableEntityError);
+ });
+
+ test("get (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: {
+ agent_spec: {
+ instructions: "instructions",
+ mcp_servers: [{ name: "name" }],
+ messages: [{ content: "content", type: "user.message" }],
+ model: { name: "name" },
+ response_format: { type: "text" },
+ skills: [{ description: "description", name: "name", ref: "ref", type: "git", url: "url" }],
+ variables: { key: "value" },
+ },
+ created_at: "created_at",
+ id: "id",
+ title: "title",
+ updated_at: "updated_at",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.get("sessionId");
+ expect(response).toEqual({
+ data: {
+ agentSpec: {
+ instructions: "instructions",
+ mcpServers: [
+ {
+ name: "name",
+ },
+ ],
+ messages: [
+ {
+ content: "content",
+ type: "user.message",
+ },
+ ],
+ model: {
+ name: "name",
+ },
+ responseFormat: {
+ type: "text",
+ },
+ skills: [
+ {
+ description: "description",
+ name: "name",
+ ref: "ref",
+ type: "git",
+ url: "url",
+ },
+ ],
+ variables: {
+ key: "value",
+ },
+ },
+ createdAt: "created_at",
+ id: "id",
+ title: "title",
+ updatedAt: "updated_at",
+ },
+ });
+ });
+
+ test("get (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.get("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("update (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = {
+ data: {
+ agent_spec: {
+ instructions: "instructions",
+ mcp_servers: [{ name: "name" }],
+ messages: [{ content: "content", type: "user.message" }],
+ model: { name: "name" },
+ response_format: { type: "text" },
+ skills: [{ description: "description", name: "name", ref: "ref", type: "git", url: "url" }],
+ variables: { key: "value" },
+ },
+ created_at: "created_at",
+ id: "id",
+ title: "title",
+ updated_at: "updated_at",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .patch("/v1/sessions/sessionId")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.update("sessionId");
+ expect(response).toEqual({
+ data: {
+ agentSpec: {
+ instructions: "instructions",
+ mcpServers: [
+ {
+ name: "name",
+ },
+ ],
+ messages: [
+ {
+ content: "content",
+ type: "user.message",
+ },
+ ],
+ model: {
+ name: "name",
+ },
+ responseFormat: {
+ type: "text",
+ },
+ skills: [
+ {
+ description: "description",
+ name: "name",
+ ref: "ref",
+ type: "git",
+ url: "url",
+ },
+ ],
+ variables: {
+ key: "value",
+ },
+ },
+ createdAt: "created_at",
+ id: "id",
+ title: "title",
+ updatedAt: "updated_at",
+ },
+ });
+ });
+
+ test("update (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .patch("/v1/sessions/sessionId")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.update("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("update (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .patch("/v1/sessions/sessionId")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.update("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("update (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .patch("/v1/sessions/sessionId")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(422)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.update("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.UnprocessableEntityError);
+ });
+
+ test("cancel (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = {};
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/cancel")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.cancel("sessionId");
+ expect(response).toEqual({});
+ });
+
+ test("cancel (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/cancel")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.cancel("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("cancel (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/cancel")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(412)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.cancel("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.PreconditionFailedError);
+ });
+
+ test("list_events (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [
+ {
+ event: {
+ created_at: "created_at",
+ id: "id",
+ thread_id: null,
+ mcp_servers: [{ auth_url: "auth_url", id: "id", name: "name" }],
+ type: "mcp.auth_required",
+ },
+ turn_id: "turn_id",
+ },
+ ],
+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },
+ };
+
+ server
+ .mockEndpoint({ once: false })
+ .get("/v1/sessions/sessionId/events")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const expected = {
+ data: [
+ {
+ event: {
+ createdAt: "created_at",
+ id: "id",
+ threadId: null,
+ mcpServers: [
+ {
+ authUrl: "auth_url",
+ id: "id",
+ name: "name",
+ },
+ ],
+ type: "mcp.auth_required",
+ },
+ turnId: "turn_id",
+ },
+ ],
+ pagination: {
+ limit: 1,
+ nextPageToken: "next_page_token",
+ previousPageToken: "previous_page_token",
+ },
+ };
+ const page = await client.sessions.listEvents("sessionId");
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
+ });
+
+ test("list_events (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/events")
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listEvents("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("list_events (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/events")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listEvents("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("list_turns (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [
+ {
+ created_at: "created_at",
+ id: "id",
+ input: [{ content: "content", type: "user.message" }],
+ previous_turn_id: "previous_turn_id",
+ session_id: "session_id",
+ state: { completed_at: "completed_at", reason: "server-execution-timeout", status: "cancelled" },
+ },
+ ],
+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },
+ };
+
+ server
+ .mockEndpoint({ once: false })
+ .get("/v1/sessions/sessionId/turns")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const expected = {
+ data: [
+ {
+ createdAt: "created_at",
+ id: "id",
+ input: [
+ {
+ content: "content",
+ type: "user.message",
+ },
+ ],
+ previousTurnId: "previous_turn_id",
+ sessionId: "session_id",
+ state: {
+ completedAt: "completed_at",
+ reason: "server-execution-timeout",
+ status: "cancelled",
+ },
+ },
+ ],
+ pagination: {
+ limit: 1,
+ nextPageToken: "next_page_token",
+ previousPageToken: "previous_page_token",
+ },
+ };
+ const page = await client.sessions.listTurns("sessionId");
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
+ });
+
+ test("list_turns (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns")
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurns("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("list_turns (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurns("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("create_turn (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody =
+ 'event: \ndata: {"created_at":"created_at","id":"id","thread_id":"thread_id","mcp_servers":[{"auth_url":"auth_url","id":"id","name":"name"}],"type":"mcp.auth_required"}\n\n';
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .sseBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.createTurn("sessionId");
+ const events: unknown[] = [];
+ for await (const event of response) {
+ events.push(event);
+ }
+ expect(events).toEqual([
+ {
+ createdAt: "created_at",
+ id: "id",
+ threadId: "thread_id",
+ mcpServers: [
+ {
+ authUrl: "auth_url",
+ id: "id",
+ name: "name",
+ },
+ ],
+ type: "mcp.auth_required",
+ },
+ ]);
+ });
+
+ test("create_turn (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.createTurn("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("create_turn (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.createTurn("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("create_turn (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/v1/sessions/sessionId/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(412)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.createTurn("sessionId");
+ }).rejects.toThrow(TrueHarnessTypes.PreconditionFailedError);
+ });
+
+ test("get_turn (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: {
+ created_at: "created_at",
+ id: "id",
+ input: [{ content: "content", type: "user.message" }],
+ previous_turn_id: "previous_turn_id",
+ session_id: "session_id",
+ state: { completed_at: "completed_at", reason: "server-execution-timeout", status: "cancelled" },
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns/turnId")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.sessions.getTurn("sessionId", "turnId");
+ expect(response).toEqual({
+ data: {
+ createdAt: "created_at",
+ id: "id",
+ input: [
+ {
+ content: "content",
+ type: "user.message",
+ },
+ ],
+ previousTurnId: "previous_turn_id",
+ sessionId: "session_id",
+ state: {
+ completedAt: "completed_at",
+ reason: "server-execution-timeout",
+ status: "cancelled",
+ },
+ },
+ });
+ });
+
+ test("get_turn (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns/turnId")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.getTurn("sessionId", "turnId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+
+ test("list_turn_events (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [
+ {
+ created_at: "created_at",
+ id: "id",
+ thread_id: "thread_id",
+ mcp_servers: [{ auth_url: "auth_url", id: "id", name: "name" }],
+ type: "mcp.auth_required",
+ },
+ ],
+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },
+ };
+
+ server
+ .mockEndpoint({ once: false })
+ .get("/v1/sessions/sessionId/turns/turnId/events")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const expected = {
+ data: [
+ {
+ createdAt: "created_at",
+ id: "id",
+ threadId: "thread_id",
+ mcpServers: [
+ {
+ authUrl: "auth_url",
+ id: "id",
+ name: "name",
+ },
+ ],
+ type: "mcp.auth_required",
+ },
+ ],
+ pagination: {
+ limit: 1,
+ nextPageToken: "next_page_token",
+ previousPageToken: "previous_page_token",
+ },
+ };
+ const page = await client.sessions.listTurnEvents("sessionId", "turnId");
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
+ });
+
+ test("list_turn_events (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns/turnId/events")
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurnEvents("sessionId", "turnId");
+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);
+ });
+
+ test("list_turn_events (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .get("/v1/sessions/sessionId/turns/turnId/events")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurnEvents("sessionId", "turnId");
+ }).rejects.toThrow(TrueHarnessTypes.NotFoundError);
+ });
+});
diff --git a/packages/sdk/tests/wire/skills.test.ts b/packages/sdk/tests/wire/skills.test.ts
new file mode 100644
index 000000000..074668816
--- /dev/null
+++ b/packages/sdk/tests/wire/skills.test.ts
@@ -0,0 +1,30 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import { TrueHarness } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("SkillsClient", () => {
+ test("list", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [{ description: "description", name: "name", path: "path", ref: "ref", url: "url" }],
+ };
+
+ server.mockEndpoint().get("/v1/skills").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+
+ const response = await client.skills.list();
+ expect(response).toEqual({
+ data: [
+ {
+ description: "description",
+ name: "name",
+ path: "path",
+ ref: "ref",
+ url: "url",
+ },
+ ],
+ });
+ });
+});
diff --git a/packages/sdk/tsconfig.base.json b/packages/sdk/tsconfig.base.json
new file mode 100644
index 000000000..93a92c063
--- /dev/null
+++ b/packages/sdk/tsconfig.base.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "extendedDiagnostics": true,
+ "strict": true,
+ "target": "ES6",
+ "moduleResolution": "node",
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "isolatedModules": true,
+ "isolatedDeclarations": true
+ },
+ "include": ["src"],
+ "exclude": []
+}
diff --git a/packages/sdk/tsconfig.cjs.json b/packages/sdk/tsconfig.cjs.json
new file mode 100644
index 000000000..5c11446f5
--- /dev/null
+++ b/packages/sdk/tsconfig.cjs.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.base.json",
+ "compilerOptions": {
+ "module": "CommonJS",
+ "outDir": "dist/cjs"
+ },
+ "include": ["src"],
+ "exclude": []
+}
diff --git a/packages/sdk/tsconfig.esm.json b/packages/sdk/tsconfig.esm.json
new file mode 100644
index 000000000..021e74d21
--- /dev/null
+++ b/packages/sdk/tsconfig.esm.json
@@ -0,0 +1,11 @@
+{
+ "extends": "./tsconfig.base.json",
+ "compilerOptions": {
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "outDir": "dist/esm",
+ "verbatimModuleSyntax": true
+ },
+ "include": ["src"],
+ "exclude": []
+}
diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json
new file mode 100644
index 000000000..d77fdf00d
--- /dev/null
+++ b/packages/sdk/tsconfig.json
@@ -0,0 +1,3 @@
+{
+ "extends": "./tsconfig.cjs.json"
+}
diff --git a/packages/sdk/vitest.config.mts b/packages/sdk/vitest.config.mts
new file mode 100644
index 000000000..0dee5a752
--- /dev/null
+++ b/packages/sdk/vitest.config.mts
@@ -0,0 +1,32 @@
+import { defineConfig } from "vitest/config";
+export default defineConfig({
+ test: {
+ typecheck: {
+ enabled: true,
+ tsconfig: "./tests/tsconfig.json",
+ },
+ projects: [
+ {
+ test: {
+ globals: true,
+ name: "unit",
+ environment: "node",
+ root: "./tests",
+ include: ["**/*.test.{js,ts,jsx,tsx}"],
+ exclude: ["wire/**"],
+ setupFiles: ["./setup.ts"],
+ },
+ },
+ {
+ test: {
+ globals: true,
+ name: "wire",
+ environment: "node",
+ root: "./tests/wire",
+ setupFiles: ["../setup.ts", "../mock-server/setup.ts"],
+ },
+ },
+ ],
+ passWithNoTests: true,
+ },
+});
diff --git a/packages/server/.env.test b/packages/server/.env.test
index 925d119e8..b71dd426c 100644
--- a/packages/server/.env.test
+++ b/packages/server/.env.test
@@ -6,3 +6,4 @@ POSTGRES_HOST=localhost
POSTGRES_PORT=5432
REDIS_URL=redis://localhost:6379
MODEL_API_KEY=test
+REGISTRY_DIR=registry-example
diff --git a/packages/server/package.json b/packages/server/package.json
index 23bf3be45..e1d22d740 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -11,6 +11,7 @@
"dev": "tsx --env-file=.env src/main.ts",
"migrate": "tsx --env-file=.env src/db/migrate-cli.ts",
"typecheck": "tsc --noEmit",
+ "openapi:write": "tsx --env-file=.env.test scripts/write-openapi.ts",
"test": "tsx --env-file=.env.test --test src/**/*.test.ts",
"test:store": "jest --config jest.store.config.cjs",
"start": "node dist/main.js"
diff --git a/packages/server/scripts/write-openapi.ts b/packages/server/scripts/write-openapi.ts
new file mode 100644
index 000000000..558f85ed1
--- /dev/null
+++ b/packages/server/scripts/write-openapi.ts
@@ -0,0 +1,58 @@
+/**
+ * Writes the server's OpenAPI document to `fern/openapi/openapi.json` for Fern.
+ *
+ * The real app is built in-process and asked for its document, so the committed
+ * spec cannot drift from what the server serves. Nothing listens or dials out:
+ * `.env.test` supplies dummy connection strings and the registry fixtures.
+ */
+import { InMemorySessionStore, Sessions } from '@truefoundry/utils/agent-session';
+import { RequestReplyRouter } from '@truefoundry/utils/request-reply';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { createClient, type RedisClientType } from 'redis';
+import winston from 'winston';
+import { buildOpenApiDocument, createServerApp } from '../src/app';
+import { ActiveTurnRegistry } from '../src/runtime/activeTurns';
+import { McpStore } from '../src/store/McpStore';
+import { ModelStore } from '../src/store/ModelStore';
+import { SkillStore } from '../src/store/SkillStore';
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null;
+}
+
+/**
+ * Sorts object keys so the committed document depends only on the API, not on
+ * the order Zod happened to register schemas in. Arrays keep their order, since
+ * position carries meaning in `required`, `enum` and `anyOf`.
+ */
+function canonicalise(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(canonicalise);
+ if (!isRecord(value)) return value;
+ return Object.fromEntries(
+ Object.keys(value)
+ .sort()
+ .map(key => [key, canonicalise(value[key])]),
+ );
+}
+
+// Unconnected stand-ins suffice: route registration never reads a dependency.
+const sessionStore = new InMemorySessionStore();
+const redis: RedisClientType = createClient();
+const app = createServerApp({
+ modelStore: ModelStore.load(),
+ mcpStore: McpStore.load(),
+ skillStore: SkillStore.load(),
+ sessionStore,
+ sessions: new Sessions({ sessionStore }),
+ activeTurns: new ActiveTurnRegistry(),
+ redis,
+ requestReplyRouter: new RequestReplyRouter(),
+ logger: winston.createLogger({ silent: true }),
+});
+
+const document = buildOpenApiDocument(app);
+const outputPath = path.join(import.meta.dirname, '../../../fern/openapi/openapi.json');
+mkdirSync(path.dirname(outputPath), { recursive: true });
+writeFileSync(outputPath, `${JSON.stringify(canonicalise(document), null, 2)}\n`);
+console.log(`Wrote ${String(Object.keys(document.paths ?? {}).length)} paths to ${outputPath}`);
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 6cc486525..73d188f39 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -20,8 +20,8 @@ import type { McpStore } from './store/McpStore';
import type { ModelStore } from './store/ModelStore';
import type { SkillStore } from './store/SkillStore';
-export const openApiDocConfig = {
- openapi: '3.0.0',
+const openApiDocConfig = {
+ openapi: '3.1.0',
info: {
title: 'Agent Server',
description: 'Agent server exposing models, MCP servers and skills from local YAML config.',
@@ -29,6 +29,11 @@ export const openApiDocConfig = {
},
};
+/** Single source for both the served document and the one the SDK is built from. */
+export function buildOpenApiDocument(app: OpenAPIHono) {
+ return app.getOpenAPI31Document(openApiDocConfig);
+}
+
export interface ServerDeps {
modelStore: ModelStore;
mcpStore: McpStore;
@@ -80,7 +85,7 @@ export function createServerApp(deps: ServerDeps) {
);
app.get('/docs', swaggerUI({ url: '/openapi.json' }));
- app.get('/openapi.json', c => c.json(app.getOpenAPIDocument(openApiDocConfig)));
+ app.get('/openapi.json', c => c.json(buildOpenApiDocument(app)));
app.notFound(c => c.json({ error: { message: `Route not found: ${c.req.method} ${c.req.path}` } }, 404));
diff --git a/packages/server/src/routes/capabilityRoutes.ts b/packages/server/src/routes/capabilityRoutes.ts
index 9a926ab7a..59224606c 100644
--- a/packages/server/src/routes/capabilityRoutes.ts
+++ b/packages/server/src/routes/capabilityRoutes.ts
@@ -15,6 +15,8 @@ export const getCapabilitiesRoute = createRoute({
path: '/',
tags: ['Capabilities'],
summary: 'Get server capabilities',
+ 'x-fern-sdk-group-name': ['server'],
+ 'x-fern-sdk-method-name': 'get_capabilities',
description: 'Report optional runtime capabilities available in this server deployment.',
responses: {
200: {
diff --git a/packages/server/src/routes/fernExtensions.ts b/packages/server/src/routes/fernExtensions.ts
new file mode 100644
index 000000000..9aa530dcd
--- /dev/null
+++ b/packages/server/src/routes/fernExtensions.ts
@@ -0,0 +1,6 @@
+/** Every paginated endpoint on this server shares one opaque-token contract. */
+export const TOKEN_PAGINATION = {
+ cursor: '$request.page_token',
+ next_cursor: '$response.pagination.next_page_token',
+ results: '$response.data',
+};
diff --git a/packages/server/src/routes/mcpRoutes.ts b/packages/server/src/routes/mcpRoutes.ts
index 43b19460a..d07b604ed 100644
--- a/packages/server/src/routes/mcpRoutes.ts
+++ b/packages/server/src/routes/mcpRoutes.ts
@@ -16,6 +16,8 @@ export const listMcpServersRoute = createRoute({
tags: [MCP_SERVERS_TAG],
summary: 'List MCP servers',
description: 'MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.',
+ 'x-fern-sdk-group-name': ['mcp_servers'],
+ 'x-fern-sdk-method-name': 'list',
responses: {
200: {
content: { 'application/json': { schema: ListMcpServersResponseSchema } },
@@ -46,6 +48,8 @@ export const listMcpToolsRoute = createRoute({
path: '/{name}/tools',
tags: [MCP_SERVERS_TAG],
summary: 'List tools of an MCP server',
+ 'x-fern-sdk-group-name': ['mcp_servers'],
+ 'x-fern-sdk-method-name': 'list_tools',
description:
'All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.',
request: {
diff --git a/packages/server/src/routes/modelRoutes.ts b/packages/server/src/routes/modelRoutes.ts
index 5cb5cd251..c1c92714d 100644
--- a/packages/server/src/routes/modelRoutes.ts
+++ b/packages/server/src/routes/modelRoutes.ts
@@ -12,6 +12,8 @@ export const listModelsRoute = createRoute({
path: '/',
tags: ['Models'],
summary: 'List models',
+ 'x-fern-sdk-group-name': ['models'],
+ 'x-fern-sdk-method-name': 'list',
description: "Models declared in models.yaml, reachable through the OpenAI-compatible API at the file's base_url.",
responses: {
200: {
diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.ts
index 748f9ca7b..dd4386991 100644
--- a/packages/server/src/routes/sessionRoutes.ts
+++ b/packages/server/src/routes/sessionRoutes.ts
@@ -13,6 +13,7 @@ import {
UpdateSessionRequestSchema,
} from '../schemas/session';
import { CancelSessionRequestSchema, CancelSessionResponseSchema } from '../schemas/turn';
+import { TOKEN_PAGINATION } from './fernExtensions';
const SESSIONS_TAG = 'Sessions';
@@ -26,6 +27,8 @@ export const createSessionRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Create a session',
description: 'Create a session holding an inline agent spec. Turns are executed against this spec.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'create',
request: {
body: {
content: { 'application/json': { schema: CreateSessionRequestSchema } },
@@ -55,6 +58,8 @@ export const getSessionRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Get a session',
description: 'Fetch a session by ID.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'get',
request: {
params: SessionIdParamsSchema,
},
@@ -76,6 +81,8 @@ export const updateSessionRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Update a session',
description: "Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.",
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'update',
request: {
params: SessionIdParamsSchema,
body: {
@@ -111,6 +118,9 @@ export const listSessionsRoute = createRoute({
summary: 'List sessions',
description:
'List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'list',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
query: ListSessionsRequestQuerySchema,
},
@@ -132,6 +142,8 @@ export const cancelSessionRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Cancel a running turn in a session',
description: 'Cancel the running last turn for a session.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'cancel',
request: {
params: SessionIdParamsSchema,
body: {
@@ -163,6 +175,9 @@ export const listSessionEventsRoute = createRoute({
summary: 'List session events',
description:
'List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'list_events',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
params: SessionIdParamsSchema,
query: ListSessionEventsRequestQuerySchema,
diff --git a/packages/server/src/routes/skillRoutes.ts b/packages/server/src/routes/skillRoutes.ts
index 699787529..2ee505d0c 100644
--- a/packages/server/src/routes/skillRoutes.ts
+++ b/packages/server/src/routes/skillRoutes.ts
@@ -12,6 +12,8 @@ export const listSkillsRoute = createRoute({
path: '/',
tags: ['Skills'],
summary: 'List skills',
+ 'x-fern-sdk-group-name': ['skills'],
+ 'x-fern-sdk-method-name': 'list',
description: 'Agent skills declared in skills.yaml.',
responses: {
200: {
diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.ts
index 206b025af..5da36a7b1 100644
--- a/packages/server/src/routes/turnRoutes.ts
+++ b/packages/server/src/routes/turnRoutes.ts
@@ -15,6 +15,7 @@ import {
ListTurnsResponseSchema,
SubscribeTurnRequestSchema,
} from '../schemas/turn';
+import { TOKEN_PAGINATION } from './fernExtensions';
import { SessionIdParamsSchema } from './sessionRoutes';
const SESSIONS_TAG = 'Sessions';
@@ -29,6 +30,9 @@ export const listTurnsRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'List turns in a session',
description: 'List turns for a session (newest first by default), token-paginated.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'list_turns',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
params: SessionIdParamsSchema,
query: ListTurnsRequestQuerySchema,
@@ -55,6 +59,8 @@ export const getTurnRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Get a turn',
description: 'Fetch a single turn by ID.',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'get_turn',
request: {
params: TurnIdParamsSchema,
},
@@ -76,6 +82,9 @@ export const listTurnEventsRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'List turn events',
description: 'Paginated persisted events for a turn (insertion order by default).',
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'list_turn_events',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
params: TurnIdParamsSchema,
query: ListTurnEventsRequestQuerySchema,
@@ -103,6 +112,10 @@ export const createAndExecuteTurnRoute = createRoute({
summary: 'Create and execute a turn in a session',
description: `Create a turn within a session and stream its execution as Server-Sent Events.
Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto\`).`,
+ 'x-fern-sdk-group-name': ['sessions'],
+ 'x-fern-sdk-method-name': 'create_turn',
+ // Not resumable: subscribeTurnRoute, which would reattach, is not registered.
+ 'x-fern-streaming': { format: 'sse', resumable: false },
request: {
params: SessionIdParamsSchema,
body: {
diff --git a/packages/server/src/store/schemas.ts b/packages/server/src/store/schemas.ts
index 2aebfa804..b7d51e804 100644
--- a/packages/server/src/store/schemas.ts
+++ b/packages/server/src/store/schemas.ts
@@ -2,8 +2,10 @@
* Zod schemas for the YAML config files (models.yaml, mcp.yaml, skills.yaml).
* Validation is strict: unknown keys, duplicate names, or missing fields make
* the server fail at startup.
+ *
+ * TODO: settle the `.openapi()` names below; they become the SDK's exported types.
*/
-import { z } from 'zod';
+import { z } from '@hono/zod-openapi';
import { normalizeEnvName } from '../config';
/** Adds a validation issue if two entries share a name. */
@@ -48,7 +50,8 @@ export const ModelEntrySchema = z
reasoning_efforts: z.array(z.string().min(1)).min(1).optional(),
max_output_tokens: z.number().int().positive(),
})
- .strict();
+ .strict()
+ .openapi('ModelEntry');
export const ModelsFileSchema = z
.object({
@@ -69,7 +72,8 @@ export const McpServerEntrySchema = z
name: z.string().min(1),
url: z.string().url(),
})
- .strict();
+ .strict()
+ .openapi('McpServerEntry');
export const McpFileSchema = z
.object({
@@ -93,7 +97,8 @@ export const SkillEntrySchema = z
// Shown to users and persisted in the selected skill mount for runtime prompting.
description: z.string().min(1),
})
- .strict();
+ .strict()
+ .openapi('SkillEntry');
export const SkillsFileSchema = z
.object({
diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json
index 6205946e9..4649792e3 100644
--- a/packages/server/tsconfig.json
+++ b/packages/server/tsconfig.json
@@ -4,7 +4,7 @@
"types": ["node"],
"noEmit": true
},
- "include": ["src/**/*", "tests/**/*", "tsup.config.ts"],
+ "include": ["src/**/*", "tests/**/*", "scripts/**/*", "tsup.config.ts"],
// Test bodies pull harness test sources across the package boundary, which needs
// that package's own compiler paths; support modules stay in-project.
"exclude": ["node_modules", "dist", "src/**/*.test.ts", "tests/**/*.test.ts"]
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 30402d25b..77b54cf0d 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,5 +1,7 @@
packages:
- packages/*
+ # Out of the workspace: its generated devDeps would break --frozen-lockfile in CI.
+ - '!packages/sdk'
minimumReleaseAge: 0
trustLockfile: true