Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: API context auth, org projects route, and env-scoped trace chips (#1512)

Aman Agarwal328f9800ff61
diff --git a/docs/docs.json b/docs/docs.json
index 9952c71e..f1b2aafe 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -222,6 +222,24 @@
"pages": [
"latest/openlit/developer-resources/api-reference/endpoint/rule-engine/evaluate"
]
+ },
+ {
+ "group": "Manage Models",
+ "pages": [
+ "latest/openlit/developer-resources/api-reference/endpoint/manage-models/models",
+ "latest/openlit/developer-resources/api-reference/endpoint/manage-models/providers",
+ "latest/openlit/developer-resources/api-reference/endpoint/manage-models/export",
+ "latest/openlit/developer-resources/api-reference/endpoint/manage-models/import",
+ "latest/openlit/developer-resources/api-reference/endpoint/manage-models/public-pricing"
+ ]
+ },
+ {
+ "group": "API Keys",
+ "pages": [
+ "latest/openlit/developer-resources/api-reference/endpoint/api-keys/create",
+ "latest/openlit/developer-resources/api-reference/endpoint/api-keys/get",
+ "latest/openlit/developer-resources/api-reference/endpoint/api-keys/delete"
+ ]
}
]
}
diff --git a/docs/latest/openlit/developer-resources/api-reference/introduction.mdx b/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
index b39d0f9b..8560b3f5 100644
--- a/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
+++ b/docs/latest/openlit/developer-resources/api-reference/introduction.mdx
@@ -29,12 +29,41 @@ description: 'OpenAPI specification for API Endpoints in OpenLIT'
</Card>
</CardGroup>
+## Product surfaces
+
+In addition to the SDK-facing endpoints above, the OpenLIT client ships an interactive OpenAPI reference at **Settings → OpenAPI Spec** (`/openapi-spec`). That catalog also covers:
+
+- **AI Analysis** — `GET`/`POST /api/chat/improvement/{spanId}` for saved runs and streaming reviews of traces/spans
+- **Ask Otter** — `/api/chat/*` for config, conversations, streaming messages, SQL execute, widgets, and usage
+- **Telemetry** — logs, metrics, traces, exceptions, and span hierarchy APIs
+
+See [AI Analysis](/latest/openlit/observability/telemetry/ai-analysis) and [Chat with Otter](/latest/openlit/chat/overview) for product docs.
+
+## Request context headers
+
+OpenLIT scopes data by **Organisation → Project → Environment**. **Signal routing** (latest) picks the connector for each signal from the active project + environment.
+
+```http
+Authorization: Bearer <openlit-api-key>
+x-openlit-organisation-id: <organisation-id>
+x-openlit-project-id: <project-id>
+x-openlit-environment: production
+```
+
+### Non-SDK APIs (telemetry, Ask Otter, AI Analysis, …)
+
+Use signal routing headers only. Do **not** send `x-openlit-database-config-id`. The API key still binds a vault/credential database config (middleware injects `x-database-config-id`).
+
+### SDK-facing APIs (Prompt Hub, Vault, Rule Engine)
+
+Prefer signal routing (`project` + `environment`) to resolve the intelligence ClickHouse that stores prompts, secrets, and rules. Existing SDKs that only send `Authorization: Bearer …` keep working via the API key's bound database config. Those endpoints also accept an explicit `x-openlit-database-config-id` when it belongs to the same project as the key.
+
## Authentication
-Most SDK-facing endpoints (Prompt Hub, Vault, Rule Engine) use an Authorization header:
+All documented endpoints require an Authorization header:
```yaml
Authorization: Bearer <api-key>
```
-[Manage Models](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/models) UI APIs use a signed-in OpenLIT session instead. The [public pricing export](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/public-pricing) requires no auth.
\ No newline at end of file
+[Manage Models](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/models) UI pages also accept a signed-in OpenLIT session in the browser. The [public pricing export](/latest/openlit/developer-resources/api-reference/endpoint/manage-models/public-pricing) requires no auth.
diff --git a/src/client/public/openapi.yaml b/src/client/public/openapi.yaml
index 8560915c..48ae9082 100644
--- a/src/client/public/openapi.yaml
+++ b/src/client/public/openapi.yaml
@@ -3,14 +3,45 @@ info:
title: OpenLIT Client API
description: |
API specification for the OpenLIT client application.
- This includes telemetry retrieval APIs (authorized via browser session or `OPENLIT_API_KEY`), prompt hub management, rule engine evaluation, and other controller/platform APIs.
- version: 1.23.0
+ Authenticate every request with an OpenLIT API key
+ (`Authorization: Bearer openlit-...`).
+
+ ## Request context headers
+
+ OpenLIT scopes data by **Organisation → Project → Environment**.
+ **Signal routing** (latest) selects the connector for each signal from the
+ active project + environment. Prefer these headers on API calls:
+
+ - `x-openlit-organisation-id` — active organisation
+ - `x-openlit-project-id` — active project (bindings are project-scoped)
+ - `x-openlit-environment` — active environment (drives signal routing)
+
+ ### Non-SDK APIs (telemetry, Ask Otter, AI Analysis, …)
+ Use signal routing headers only. Do **not** send
+ `x-openlit-database-config-id`. The API key still binds a vault/credential
+ database config (middleware injects `x-database-config-id`).
+
+ ### SDK-facing APIs (Prompt Hub, Vault, Rule Engine evaluate)
+ Prefer signal routing (`project` + `environment`) to resolve the intelligence
+ ClickHouse that stores prompts, secrets, and rules. Existing SDKs that only
+ send `Authorization: Bearer …` keep working via the API key's bound database
+ config. Those endpoints also accept an explicit
+ `x-openlit-database-config-id` when it belongs to the same project as the key.
+
+ ## Authentication
+
+ All documented endpoints require Bearer API key auth (`ApiKeyAuth`).
+ version: 1.28.0
servers:
- url: http://localhost:3000
description: Local development server
tags:
- name: Telemetry
description: Telemetry retrieval and observability querying APIs
+ - name: AI Analysis
+ description: Structured AI review of traces and spans (strengths, improvements, cost, tokens, path)
+ - name: Ask Otter
+ description: Conversational assistant for telemetry investigation, SQL execution, and usage
- name: Prompt Hub
description: Manage and compile prompt templates
- name: Secret Vault
@@ -30,10 +61,13 @@ paths:
tags:
- Telemetry
summary: Query logs
- description: Retrieve a paginated list of telemetry logs matching the provided filters. Can be authenticated using session cookies or an API key.
+ description: Retrieve a paginated list of telemetry logs matching the provided filters. Requires an OpenLIT API key plus organisation/project/environment headers for signal routing.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -68,12 +102,14 @@ paths:
description: Retrieve detail of a specific log entry by its hash/row ID.
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
- description: The cityHash64 row ID of the log.
+ description: Path parameter. The cityHash64 row ID of the log.
schema:
type: string
responses:
@@ -97,7 +133,10 @@ paths:
description: Retrieve unique attribute keys for log attributes, resource attributes, and scope attributes.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -140,7 +179,10 @@ paths:
description: Retrieve configuration metadata such as available service names, severities, and total log rows.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -179,7 +221,10 @@ paths:
description: Retrieve a list of aggregated metrics matching the filters.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -213,12 +258,14 @@ paths:
description: Retrieve time-series graph points and detail records for a specific metric name.
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: name
in: path
required: true
- description: The name of the metric.
+ description: Path parameter. The name of the metric.
schema:
type: string
requestBody:
@@ -263,7 +310,10 @@ paths:
description: Retrieve unique attribute keys for metrics.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -304,7 +354,10 @@ paths:
description: Retrieve list of available services, metric names, types, and counts.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -347,12 +400,14 @@ paths:
description: Retrieve aggregated time-series summary bucketed counts and metrics (e.g. costs, latency, or token counts) for traces, exceptions, logs, or metrics.
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: signal
in: path
required: true
- description: The telemetry signal type.
+ description: Path parameter. The telemetry signal type.
schema:
type: string
enum: [traces, exceptions, logs, metrics]
@@ -396,10 +451,13 @@ paths:
tags:
- Telemetry
summary: Query traces list
- description: Retrieve a paginated list of trace spans matching the provided filters. Can be authenticated using session cookies or an API key.
+ description: Retrieve a paginated list of trace spans matching the provided filters. Requires an OpenLIT API key plus organisation/project/environment headers for signal routing.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -430,10 +488,13 @@ paths:
tags:
- Telemetry
summary: Query exceptions list
- description: Retrieve a paginated list of exceptions matching the provided filters. Can be authenticated using session cookies or an API key.
+ description: Retrieve a paginated list of exceptions matching the provided filters. Requires an OpenLIT API key plus organisation/project/environment headers for signal routing.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -467,12 +528,14 @@ paths:
description: Retrieve details of a specific trace span by its ID (along with optional evaluation summary data).
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
- description: The ID of the span.
+ description: Path parameter. The ID of the span.
schema:
type: string
responses:
@@ -495,12 +558,14 @@ paths:
description: Retrieve details of a trace (such as its root span or transaction info) using the Trace ID.
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
- description: The ID of the trace (Trace ID).
+ description: Path parameter. The ID of the trace (Trace ID).
schema:
type: string
responses:
@@ -523,12 +588,14 @@ paths:
description: Retrieve the tree hierarchy representation of all related spans (e.g. parents, subagents, child operations) associated with a trace span.
security:
- ApiKeyAuth: []
- - CookieAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
- description: The ID of the root/anchor span.
+ description: Path parameter. The ID of the root/anchor span.
schema:
type: string
responses:
@@ -550,7 +617,11 @@ paths:
summary: List all API Keys
description: Retrieve all API keys associated with the user's active database configuration.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
responses:
'200':
description: A list of API Keys.
@@ -566,7 +637,11 @@ paths:
summary: Generate an API Key
description: Create a new API key prefixed with `openlit-` linked to the active database configuration.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -603,11 +678,15 @@ paths:
summary: Delete an API Key
description: Mark an API key as deleted.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
- name: id
in: path
required: true
+ description: Path parameter. API key ID to delete.
schema:
type: string
responses:
@@ -629,7 +708,11 @@ paths:
summary: List database configurations
description: Retrieve database configurations the current user has access to.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
responses:
'200':
description: Database configurations list.
@@ -637,7 +720,11 @@ paths:
summary: Save database configuration
description: Create or update a ClickHouse database configuration connection parameters.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -669,7 +756,11 @@ paths:
summary: Create a prompt
description: Create a new prompt entry or version.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -687,7 +778,11 @@ paths:
summary: Retrieve a prompt by name or ID
description: Retrieve details of a prompt version.
security:
- - CookieAuth: []
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -706,13 +801,18 @@ paths:
tags:
- Prompt Hub
summary: Fetch compiled prompt
- description: Fetch and compile a prompt by name with dynamic variable interpolation. Does not require browser session cookie if authenticated by API key.
+ description: Fetch and compile a prompt by name with dynamic variable interpolation. Prefer project/environment signal routing for the intelligence ClickHouse; existing API-key-only clients and optional `x-openlit-database-config-id` remain supported.
security:
- ApiKeyAuth: []
parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectIdOptional'
+ - $ref: '#/components/parameters/OpenLitEnvironmentOptional'
+ - $ref: '#/components/parameters/OpenLitDatabaseConfigId'
- name: name
in: query
required: true
+ description: Query parameter. Prompt template identifier name.
schema:
type: string
responses:
@@ -724,9 +824,14 @@ paths:
tags:
- Secret Vault
summary: Fetch secrets from Vault
- description: Safely retrieve API keys or credentials stored in the OpenLIT Vault.
+ description: Safely retrieve API keys or credentials stored in the OpenLIT Vault. Prefer project/environment signal routing; existing API-key-only clients and optional `x-openlit-database-config-id` remain supported.
security:
- ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectIdOptional'
+ - $ref: '#/components/parameters/OpenLitEnvironmentOptional'
+ - $ref: '#/components/parameters/OpenLitDatabaseConfigId'
responses:
'200':
description: Key-value secrets retrieved.
@@ -736,9 +841,14 @@ paths:
tags:
- Rule Engine
summary: Evaluate rule engine config
- description: Evaluate rules (e.g. redaction, prompts, guardrails) against inputs.
+ description: Evaluate rules (e.g. redaction, prompts, guardrails) against inputs. Prefer project/environment signal routing; existing API-key-only clients and optional `x-openlit-database-config-id` remain supported.
security:
- ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectIdOptional'
+ - $ref: '#/components/parameters/OpenLitEnvironmentOptional'
+ - $ref: '#/components/parameters/OpenLitDatabaseConfigId'
responses:
'200':
description: Rules evaluated.
@@ -748,10 +858,13 @@ paths:
tags:
- Evaluation Engine
summary: Run offline LLM evaluation
- description: Run LLM evaluation (e.g. toxicity, hallucination, bias, pii) on user-provided prompt and response. Can be authenticated using session cookies or an API key.
+ description: Run LLM evaluation (e.g. toxicity, hallucination, bias, pii) on user-provided prompt and response. Requires an OpenLIT API key.
security:
- ApiKeyAuth: []
- - CookieAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
requestBody:
required: true
content:
@@ -778,22 +891,608 @@ paths:
description: Heartbeat and state synchronization endpoint for OpenLIT controllers.
security:
- ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
responses:
'200':
description: Acknowledged.
+
+ /api/chat/improvement/{spanId}:
+ get:
+ tags:
+ - AI Analysis
+ summary: Get AI Analysis runs for a trace or span
+ description: |
+ Retrieve saved AI Analysis runs for a trace hierarchy (`scope=trace`) or a single span (`scope=span`).
+ Requires an OpenLIT API key. Pass organisation, project, environment, and optionally `traceId`.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ - name: spanId
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Path parameter. Anchor span ID used to resolve the analysis target.
+ - name: scope
+ in: query
+ required: false
+ schema:
+ type: string
+ enum: [trace, span]
+ default: trace
+ description: Query parameter. Analyze the full hierarchy (`trace`) or only the given span (`span`).
+ - name: traceId
+ in: query
+ required: false
+ schema:
+ type: string
+ description: Query parameter. Optional Trace ID to disambiguate the hierarchy lookup.
+ responses:
+ '200':
+ description: Saved analysis runs for the target.
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AiAnalysisRunsResponse'
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ post:
+ tags:
+ - AI Analysis
+ summary: Run AI Analysis for a trace or span
+ description: |
+ Start a streaming AI Analysis run for a trace hierarchy or span.
+ Returns an NDJSON/text stream of progress and completed dimension findings.
+ Requires Chat Settings (provider + Vault API key) and an intelligence ClickHouse connector.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ - name: spanId
+ in: path
+ required: true
+ description: Path parameter. Anchor span ID used to resolve the analysis target.
+ schema:
+ type: string
+ - name: scope
+ in: query
+ required: false
+ description: Query parameter. Analyze the full hierarchy (`trace`) or only the given span (`span`).
+ schema:
+ type: string
+ enum: [trace, span]
+ default: trace
+ - name: traceId
+ in: query
+ required: false
+ description: Query parameter. Optional Trace ID to disambiguate the hierarchy lookup.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Streaming analysis progress and results.
+ content:
+ text/plain:
+ schema:
+ type: string
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/config:
+ get:
+ tags:
+ - Ask Otter
+ summary: Get Ask Otter chat configuration
+ description: Return the organisation chat provider/model/Vault binding (API key redacted).
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ responses:
+ '200':
+ description: Chat configuration.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ $ref: '#/components/schemas/ChatConfig'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ post:
+ tags:
+ - Ask Otter
+ summary: Upsert Ask Otter chat configuration
+ description: Save the AI provider, model, and Vault secret used by Ask Otter and AI Analysis.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [provider, model, vaultId]
+ properties:
+ provider:
+ type: string
+ example: openai
+ model:
+ type: string
+ example: gpt-4o
+ vaultId:
+ type: string
+ description: Vault secret ID that stores the provider API key.
+ meta:
+ type: string
+ description: Optional JSON string of provider-specific metadata.
+ example: '{}'
+ responses:
+ '200':
+ description: Configuration saved.
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/conversation:
+ get:
+ tags:
+ - Ask Otter
+ summary: List Ask Otter conversations
+ description: List chat conversations for the current user.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ responses:
+ '200':
+ description: Conversation list.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/ChatConversation'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ post:
+ tags:
+ - Ask Otter
+ summary: Create an Ask Otter conversation
+ description: Create a new conversation with optional title, provider, and model.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: false
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ title:
+ type: string
+ example: Investigate high cost traces
+ provider:
+ type: string
+ example: openai
+ model:
+ type: string
+ example: gpt-4o
+ responses:
+ '200':
+ description: Created conversation.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ $ref: '#/components/schemas/ChatConversation'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/conversation/{id}:
+ get:
+ tags:
+ - Ask Otter
+ summary: Get conversation with messages
+ description: Retrieve a conversation and its message history.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ - name: id
+ in: path
+ required: true
+ description: Path parameter. Conversation ID.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Conversation and messages.
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ delete:
+ tags:
+ - Ask Otter
+ summary: Delete a conversation
+ description: Delete a conversation and its messages.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ - name: id
+ in: path
+ required: true
+ description: Path parameter. Conversation ID to delete.
+ schema:
+ type: string
+ responses:
+ '200':
+ description: Conversation deleted.
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/message:
+ post:
+ tags:
+ - Ask Otter
+ summary: Send an Ask Otter message
+ description: |
+ Stream an assistant reply for a conversation. Returns NDJSON events
+ (`delta`, `step`, `done`, `error`). Requires an OpenLIT API key and Chat Settings.
+ Used by the Chat page, Memory Ask Otter panel, and Try in Chat from AI Analysis.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [conversationId, content]
+ properties:
+ conversationId:
+ type: string
+ content:
+ type: string
+ example: Analyze the slowest traces from the last 24 hours
+ responses:
+ '200':
+ description: NDJSON stream of assistant tokens and tool steps.
+ content:
+ application/x-ndjson:
+ schema:
+ type: string
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/message/execute:
+ post:
+ tags:
+ - Ask Otter
+ summary: Execute validated SQL from Ask Otter
+ description: |
+ Run a read-only SQL query proposed by Ask Otter against the intelligence ClickHouse connector.
+ Returns 409 when the active environment is not routed to a ClickHouse intelligence source.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [query]
+ properties:
+ messageId:
+ type: string
+ description: Optional chat message ID to attach query results to.
+ query:
+ type: string
+ example: SELECT SpanName, Duration FROM otel_traces LIMIT 10
+ responses:
+ '200':
+ description: Query rows and execution stats.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ type: object
+ stats:
+ type: object
+ properties:
+ rowsRead:
+ type: integer
+ executionTimeMs:
+ type: integer
+ bytesRead:
+ type: integer
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+ '409':
+ description: Native SQL chat unavailable for the routed intelligence source.
+
+ /api/chat/message/save-widget:
+ post:
+ tags:
+ - Ask Otter
+ summary: Save an Ask Otter query as a dashboard widget
+ description: Persist a validated chat SQL query as a dashboard widget.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [title, type, query]
+ properties:
+ title:
+ type: string
+ description:
+ type: string
+ type:
+ type: string
+ example: table
+ query:
+ type: string
+ properties:
+ type: object
+ boardId:
+ type: string
+ responses:
+ '200':
+ description: Widget saved.
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/chat/usage:
+ get:
+ tags:
+ - Ask Otter
+ summary: Get Ask Otter usage stats
+ description: Aggregate token and cost usage for Otter chat and analysis runs.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ - name: start
+ in: query
+ required: false
+ description: Query parameter. Inclusive start of the usage window (ISO-8601).
+ schema:
+ type: string
+ format: date-time
+ - name: end
+ in: query
+ required: false
+ description: Query parameter. Inclusive end of the usage window (ISO-8601).
+ schema:
+ type: string
+ format: date-time
+ responses:
+ '200':
+ description: Usage summary.
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
+ /api/prompt/improve:
+ post:
+ tags:
+ - Prompt Hub
+ summary: Improve a prompt with Otter
+ description: |
+ Ask Otter to propose precise prompt edits. Requires an OpenLIT API key and Chat Settings.
+ security:
+ - ApiKeyAuth: []
+ parameters:
+ - $ref: '#/components/parameters/OpenLitOrganisationId'
+ - $ref: '#/components/parameters/OpenLitProjectId'
+ - $ref: '#/components/parameters/OpenLitEnvironment'
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [prompt]
+ properties:
+ prompt:
+ type: string
+ promptId:
+ type: string
+ description: Optional Prompt Hub ID when improving a saved prompt.
+ criteria:
+ type: array
+ items:
+ type: string
+ description: Optional review criteria override.
+ responses:
+ '200':
+ description: Improvement suggestions.
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ data:
+ type: object
+ properties:
+ suggestions:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ dimension:
+ type: string
+ rationale:
+ type: string
+ original:
+ type: string
+ replacement:
+ type: string
+ provider:
+ type: string
+ model:
+ type: string
+ criteria:
+ type: array
+ items:
+ type: string
+ usage:
+ type: object
+ properties:
+ promptTokens:
+ type: integer
+ completionTokens:
+ type: integer
+ cost:
+ type: number
+ '400':
+ $ref: '#/components/responses/BadRequestError'
+ '401':
+ $ref: '#/components/responses/UnauthorizedError'
+
components:
+ parameters:
+ OpenLitOrganisationId:
+ name: x-openlit-organisation-id
+ in: header
+ required: false
+ description: |
+ Header parameter. Active organisation ID. Send with project and environment so the request
+ matches Organisation → Project → Environment signal routing.
+ schema:
+ type: string
+ example: org_01HXYZ
+ OpenLitProjectId:
+ name: x-openlit-project-id
+ in: header
+ required: true
+ description: |
+ Header parameter. Active project ID. Telemetry source bindings are project-scoped; required
+ for correct signal routing with `x-openlit-environment`.
+ schema:
+ type: string
+ example: proj_01HXYZ
+ OpenLitEnvironment:
+ name: x-openlit-environment
+ in: header
+ required: true
+ description: |
+ Header parameter. Active project environment (for example `production` or `staging`).
+ Required for signal routing (traces/logs/metrics/intelligence connectors),
+ AI Analysis, and Ask Otter SQL. Defaults to `production` on some routes
+ when omitted, which may hit the wrong source.
+ schema:
+ type: string
+ example: production
+ OpenLitProjectIdOptional:
+ name: x-openlit-project-id
+ in: header
+ required: false
+ description: |
+ Header parameter. Preferred with `x-openlit-environment` for signal routing. When omitted,
+ the API key's bound database config project is used for routing.
+ schema:
+ type: string
+ example: proj_01HXYZ
+ OpenLitEnvironmentOptional:
+ name: x-openlit-environment
+ in: header
+ required: false
+ description: |
+ Header parameter. Preferred for signal routing. When omitted, SDK endpoints fall back to
+ the API key's bound database config (legacy).
+ schema:
+ type: string
+ example: production
+ OpenLitDatabaseConfigId:
+ name: x-openlit-database-config-id
+ in: header
+ required: false
+ description: |
+ Header parameter. SDK-facing endpoints only. Optional explicit ClickHouse database config.
+ Must belong to the same project as the API key. Prefer signal routing
+ (`x-openlit-project-id` + `x-openlit-environment`) instead.
+ schema:
+ type: string
+ example: dbcfg_01HXYZ
securitySchemes:
- CookieAuth:
- type: apiKey
- in: cookie
- name: next-auth.session-token
- description: Standard NextAuth browser session token cookie.
ApiKeyAuth:
type: http
scheme: bearer
bearerFormat: OPENLIT_API_KEY
- description: Bearer token format (`Authorization: Bearer openlit-...`).
+ description: |
+ Required. Bearer token format (`Authorization: Bearer openlit-...`).
+ The key binds a database configuration; clients do not need to send
+ `x-openlit-database-config-id`.
schemas:
TimeLimit:
@@ -995,6 +1694,71 @@ components:
metadata:
type: object
+ AiAnalysisRunsResponse:
+ type: object
+ properties:
+ data:
+ type: object
+ nullable: true
+ properties:
+ rootSpanId:
+ type: string
+ runs:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ scope:
+ type: string
+ enum: [trace, span]
+ summary:
+ type: string
+ createdAt:
+ type: string
+ format: date-time
+
+ ChatConfig:
+ type: object
+ properties:
+ provider:
+ type: string
+ example: openai
+ model:
+ type: string
+ example: gpt-4o
+ vaultId:
+ type: string
+ meta:
+ type: string
+
+ ChatConversation:
+ type: object
+ properties:
+ id:
+ type: string
+ title:
+ type: string
+ provider:
+ type: string
+ model:
+ type: string
+ totalMessages:
+ type: integer
+ totalPromptTokens:
+ type: integer
+ totalCompletionTokens:
+ type: integer
+ totalCost:
+ type: number
+ createdAt:
+ type: string
+ format: date-time
+ updatedAt:
+ type: string
+ format: date-time
+
responses:
UnauthorizedError:
description: Authentication failed or credentials missing.
diff --git a/src/client/src/__tests__/app/api/prompt/improve/route.test.ts b/src/client/src/__tests__/app/api/prompt/improve/route.test.ts
index c6548d32..f368e4ed 100644
--- a/src/client/src/__tests__/app/api/prompt/improve/route.test.ts
+++ b/src/client/src/__tests__/app/api/prompt/improve/route.test.ts
@@ -4,6 +4,7 @@ jest.mock("@/lib/platform/chat/config", () => ({ getChatConfigWithApiKey: jest.f
jest.mock("@/lib/platform/chat/otter-runs", () => ({ saveOtterRun: jest.fn() }));
jest.mock("@/lib/platform/chat/stream", () => ({ getModelInstance: jest.fn() }));
jest.mock("@/lib/session", () => ({ getCurrentUser: jest.fn() }));
+jest.mock("@/lib/platform/api-keys", () => ({ getAPIKeyInfo: jest.fn() }));
jest.mock("@/utils/asaw", () =>
jest.fn(async (promise: Promise<any>) => {
try {
@@ -46,6 +47,9 @@ class TestResponse {
function makeRequest(body: Record<string, unknown>) {
return {
json: jest.fn().mockResolvedValue(body),
+ headers: {
+ get: jest.fn().mockReturnValue(null),
+ },
} as unknown as Request;
}
diff --git a/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts b/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts
index eac35b33..a106a581 100644
--- a/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts
+++ b/src/client/src/__tests__/app/api/vault/get-secrets/route.test.ts
@@ -1,6 +1,9 @@
jest.mock("@/lib/platform/vault", () => ({
getSecretsFromDatabaseId: jest.fn(),
}));
+jest.mock("@/helpers/server/sdk-intelligence", () => ({
+ resolveSdkIntelligenceDatabaseConfig: jest.fn(),
+}));
jest.mock("@/lib/posthog", () => ({
__esModule: true,
default: {
@@ -17,6 +20,7 @@ jest.mock("@/utils/asaw", () => jest.fn());
import { OPTIONS, POST } from "@/app/api/vault/get-secrets/route";
import { getSecretsFromDatabaseId } from "@/lib/platform/vault";
+import { resolveSdkIntelligenceDatabaseConfig } from "@/helpers/server/sdk-intelligence";
import asaw from "@/utils/asaw";
class TestHeaders {
@@ -134,6 +138,10 @@ describe("/api/vault/get-secrets CORS", () => {
});
it("does not block no-Origin API key clients", async () => {
+ (resolveSdkIntelligenceDatabaseConfig as jest.Mock).mockResolvedValue([
+ null,
+ { databaseConfigId: "db-1", via: "apiKey", apiKeyInfo: { id: "key-1" } },
+ ]);
(asaw as jest.Mock).mockResolvedValue([null, { OPENAI_API_KEY: "sk-test" }]);
const response = await POST(makeRequest({ body: { key: "OPENAI_API_KEY" } }));
@@ -144,6 +152,7 @@ describe("/api/vault/get-secrets CORS", () => {
apiKey: "openlit-test",
key: "OPENAI_API_KEY",
tags: undefined,
+ databaseConfigId: "db-1",
});
expect(body).toEqual({
err: null,
diff --git a/src/client/src/__tests__/components/openlit-context-ids.test.tsx b/src/client/src/__tests__/components/openlit-context-ids.test.tsx
new file mode 100644
index 00000000..5a8cf061
--- /dev/null
+++ b/src/client/src/__tests__/components/openlit-context-ids.test.tsx
@@ -0,0 +1,70 @@
+/**
+ * @jest-environment jsdom
+ */
+
+jest.mock("sonner", () => ({
+ toast: { success: jest.fn() },
+}));
+
+jest.mock("@/store", () => ({
+ useRootStore: jest.fn(),
+}));
+
+jest.mock("@/constants/messages", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ ORGANISATION_ID: "Organisation ID",
+ PROJECT_ID: "Project ID",
+ ENVIRONMENT_NAME: "Environment",
+ COPY_CONTEXT_VALUE: (label: string) => `Copy ${label}`,
+ COPIED_TO_CLIPBOARD: "Copied!",
+ })),
+}));
+
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { toast } from "sonner";
+import { useRootStore } from "@/store";
+import OpenLitContextIds from "@/components/(playground)/openlit-context-ids";
+
+describe("OpenLitContextIds", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ Object.assign(navigator, {
+ clipboard: { writeText: jest.fn().mockResolvedValue(undefined) },
+ });
+ });
+
+ it("renders organisation, project, and environment with copy actions", async () => {
+ (useRootStore as unknown as jest.Mock).mockImplementation((selector) =>
+ selector({
+ organisation: { current: { id: "org_abc123" } },
+ project: { current: { id: "proj_xyz789" }, currentEnvironment: "production" },
+ })
+ );
+
+ render(<OpenLitContextIds />);
+
+ expect(screen.getByText("Organisation ID")).toBeInTheDocument();
+ expect(screen.getByText("Project ID")).toBeInTheDocument();
+ expect(screen.getByText("Environment")).toBeInTheDocument();
+ expect(screen.getByText("production")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByLabelText("Copy Organisation ID"));
+ await waitFor(() => {
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith("org_abc123");
+ expect(toast.success).toHaveBeenCalledWith("Copied!");
+ });
+ });
+
+ it("hides when no context values are available", () => {
+ (useRootStore as unknown as jest.Mock).mockImplementation((selector) =>
+ selector({
+ organisation: { current: null },
+ project: { current: null, currentEnvironment: null },
+ })
+ );
+
+ const { container } = render(<OpenLitContextIds />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/src/client/src/__tests__/constants/api-reference.test.ts b/src/client/src/__tests__/constants/api-reference.test.ts
index bdf58397..04f49ac1 100644
--- a/src/client/src/__tests__/constants/api-reference.test.ts
+++ b/src/client/src/__tests__/constants/api-reference.test.ts
@@ -6,7 +6,7 @@ describe("API_REFERENCE_ENDPOINTS", () => {
expect(API_REFERENCE_ENDPOINTS.length).toBeGreaterThan(0);
});
- it("includes core telemetry and vault endpoints", () => {
+ it("includes core telemetry, vault, AI Analysis, and Ask Otter endpoints", () => {
const ids = API_REFERENCE_ENDPOINTS.map((endpoint) => endpoint.id);
expect(ids).toEqual(
expect.arrayContaining([
@@ -15,6 +15,11 @@ describe("API_REFERENCE_ENDPOINTS", () => {
"query-traces",
"get-secrets",
"create-prompt",
+ "get-ai-analysis",
+ "run-ai-analysis",
+ "send-otter-message",
+ "execute-otter-sql",
+ "improve-prompt-otter",
])
);
});
@@ -27,7 +32,14 @@ describe("API_REFERENCE_ENDPOINTS", () => {
expect(endpoint.summary.length).toBeGreaterThan(0);
expect(endpoint.description.length).toBeGreaterThan(0);
expect(typeof endpoint.curlExample).toBe("function");
- expect(endpoint.curlExample("test-key")).toContain("test-key");
+ const curl = endpoint.curlExample("test-key");
+ expect(curl).toContain("test-key");
+ expect(curl).toContain("Authorization: Bearer test-key");
+ expect(curl).toContain("x-openlit-organisation-id");
+ expect(curl).toContain("x-openlit-project-id");
+ expect(curl).toContain("x-openlit-environment");
+ expect(curl).not.toContain("x-openlit-database-config-id");
+ expect(curl).not.toContain("Cookie: next-auth.session-token");
}
});
});
diff --git a/src/client/src/__tests__/constants/route.test.ts b/src/client/src/__tests__/constants/route.test.ts
index 1230500d..54ba175c 100644
--- a/src/client/src/__tests__/constants/route.test.ts
+++ b/src/client/src/__tests__/constants/route.test.ts
@@ -1,6 +1,8 @@
import {
DEFAULT_LOGGED_IN_ROUTE,
ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN,
+ ALLOWED_OPENLIT_ROUTES_WITH_TOKEN,
+ ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN,
CRON_JOB_ROUTES,
ONBOARDING_WHITELIST_ROUTES,
ONBOARDING_WHITELIST_API_ROUTES,
@@ -27,6 +29,17 @@ describe('ALLOWED_OPENLIT_ROUTES_WITHOUT_TOKEN', () => {
});
});
+describe('ALLOWED_OPENLIT_ROUTES_WITH_TOKEN', () => {
+ it('includes API key and db-config routes for Bearer auth', () => {
+ expect(ALLOWED_OPENLIT_ROUTES_WITH_TOKEN).toContain('/api/api-key');
+ expect(ALLOWED_OPENLIT_ROUTES_WITH_TOKEN).toContain('/api/db-config');
+ });
+
+ it('includes API key prefix for delete-by-id', () => {
+ expect(ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN).toContain('/api/api-key/');
+ });
+});
+
describe('CRON_JOB_ROUTES', () => {
it('is an array', () => {
expect(Array.isArray(CRON_JOB_ROUTES)).toBe(true);
diff --git a/src/client/src/__tests__/helpers/client/connector-analytics.test.ts b/src/client/src/__tests__/helpers/client/connector-analytics.test.ts
index f2985235..34250d19 100644
--- a/src/client/src/__tests__/helpers/client/connector-analytics.test.ts
+++ b/src/client/src/__tests__/helpers/client/connector-analytics.test.ts
@@ -1,3 +1,11 @@
+jest.mock("@/lib/platform/connectors/datasource/registry", () => ({
+ getSourceTypeDescriptor: jest.fn(() => undefined),
+}));
+
+jest.mock("@/lib/platform/connectors/memory/registry", () => ({
+ getMemoryTypeDescriptor: jest.fn(() => undefined),
+}));
+
import {
BUILTIN_ROUTING_VALUE,
classifySignalRoutingChange,
diff --git a/src/client/src/__tests__/helpers/server/auth.test.ts b/src/client/src/__tests__/helpers/server/auth.test.ts
index d074bbae..c1e5c034 100644
--- a/src/client/src/__tests__/helpers/server/auth.test.ts
+++ b/src/client/src/__tests__/helpers/server/auth.test.ts
@@ -2,13 +2,23 @@ jest.mock("@/lib/session", () => ({
getCurrentUser: jest.fn(),
}));
+jest.mock("@/lib/platform/api-keys", () => ({
+ getAPIKeyInfo: jest.fn(),
+}));
+
import { getCurrentUser } from "@/lib/session";
-import { resolveDbConfigId } from "@/helpers/server/auth";
+import { getAPIKeyInfo } from "@/lib/platform/api-keys";
+import {
+ MIDDLEWARE_DATABASE_CONFIG_HEADER,
+ resolveDbConfigId,
+ resolveRequestAuth,
+} from "@/helpers/server/auth";
function makeRequest(headers: Record<string, string> = {}) {
return {
headers: {
- get: (name: string) => headers[name.toLowerCase()] ?? headers[name] ?? null,
+ get: (name: string) =>
+ headers[name.toLowerCase()] ?? headers[name] ?? null,
},
} as unknown as Request;
}
@@ -19,8 +29,11 @@ describe("resolveDbConfigId", () => {
});
it("prefers the x-database-config-id header", async () => {
+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([null, null]);
await expect(
- resolveDbConfigId(makeRequest({ "x-database-config-id": "db-header" }))
+ resolveDbConfigId(
+ makeRequest({ [MIDDLEWARE_DATABASE_CONFIG_HEADER]: "db-header" })
+ )
).resolves.toEqual([null, "db-header"]);
expect(getCurrentUser).not.toHaveBeenCalled();
});
@@ -41,3 +54,40 @@ describe("resolveDbConfigId", () => {
]);
});
});
+
+describe("resolveRequestAuth", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("resolves API key auth from middleware header and Bearer creator", async () => {
+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([
+ null,
+ { createdByUserId: "creator-1", databaseConfigId: "db-header" },
+ ]);
+ await expect(
+ resolveRequestAuth(
+ makeRequest({
+ [MIDDLEWARE_DATABASE_CONFIG_HEADER]: "db-header",
+ Authorization: "Bearer openlit-test",
+ })
+ )
+ ).resolves.toEqual([
+ null,
+ {
+ databaseConfigId: "db-header",
+ userId: "creator-1",
+ via: "apiKey",
+ },
+ ]);
+ expect(getCurrentUser).not.toHaveBeenCalled();
+ });
+
+ it("falls back to session when no middleware database config header", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue({ id: "u1" });
+ await expect(resolveRequestAuth(makeRequest())).resolves.toEqual([
+ null,
+ { databaseConfigId: undefined, userId: "u1", via: "session" },
+ ]);
+ });
+});
diff --git a/src/client/src/__tests__/helpers/server/connector-analytics.test.ts b/src/client/src/__tests__/helpers/server/connector-analytics.test.ts
index 59f5dac3..55a0fd38 100644
--- a/src/client/src/__tests__/helpers/server/connector-analytics.test.ts
+++ b/src/client/src/__tests__/helpers/server/connector-analytics.test.ts
@@ -3,6 +3,14 @@ jest.mock("@/lib/posthog", () => ({
default: { fireEvent: jest.fn() },
}));
+jest.mock("@/lib/platform/connectors/datasource/registry", () => ({
+ getSourceTypeDescriptor: jest.fn(() => undefined),
+}));
+
+jest.mock("@/lib/platform/connectors/memory/registry", () => ({
+ getMemoryTypeDescriptor: jest.fn(() => undefined),
+}));
+
import PostHogServer from "@/lib/posthog";
import { SERVER_EVENTS } from "@/constants/events";
import {
diff --git a/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts b/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts
new file mode 100644
index 00000000..94c74fa4
--- /dev/null
+++ b/src/client/src/__tests__/helpers/server/sdk-intelligence.test.ts
@@ -0,0 +1,104 @@
+jest.mock("@/lib/platform/api-keys", () => ({
+ getAPIKeyInfo: jest.fn(),
+}));
+jest.mock("@/lib/db-config", () => ({
+ getDBConfigByIdInternal: jest.fn(),
+}));
+jest.mock("@/lib/telemetry-source", () => ({
+ resolveSignalSource: jest.fn(),
+}));
+jest.mock("@/constants/messages", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ NO_API_KEY: "No API key",
+ })),
+}));
+
+import { getAPIKeyInfo } from "@/lib/platform/api-keys";
+import { getDBConfigByIdInternal } from "@/lib/db-config";
+import { resolveSignalSource } from "@/lib/telemetry-source";
+import { resolveSdkIntelligenceDatabaseConfig } from "@/helpers/server/sdk-intelligence";
+import { OPENLIT_CONTEXT_HEADERS } from "@/constants/openlit-context";
+
+function makeRequest(headers: Record<string, string> = {}) {
+ return {
+ headers: {
+ get: (name: string) =>
+ headers[name.toLowerCase()] ?? headers[name] ?? null,
+ },
+ } as unknown as Request;
+}
+
+describe("resolveSdkIntelligenceDatabaseConfig", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ (getAPIKeyInfo as jest.Mock).mockResolvedValue([
+ null,
+ { id: "key-1", databaseConfigId: "db-key", createdByUserId: "u1" },
+ ]);
+ });
+
+ it("prefers intelligence signal routing when environment is present", async () => {
+ (getDBConfigByIdInternal as jest.Mock).mockResolvedValue({
+ id: "db-key",
+ projectId: "proj-1",
+ });
+ (resolveSignalSource as jest.Mock).mockResolvedValue({
+ hasSource: true,
+ descriptor: {
+ type: "clickhouse",
+ dbConfigId: "db-intelligence",
+ },
+ });
+
+ await expect(
+ resolveSdkIntelligenceDatabaseConfig(
+ makeRequest({
+ [OPENLIT_CONTEXT_HEADERS.environment]: "staging",
+ [OPENLIT_CONTEXT_HEADERS.projectId]: "proj-1",
+ }),
+ "openlit-test"
+ )
+ ).resolves.toEqual([
+ null,
+ expect.objectContaining({
+ databaseConfigId: "db-intelligence",
+ via: "signalRouting",
+ }),
+ ]);
+ });
+
+ it("supports explicit database-config header when in the API key project", async () => {
+ (getDBConfigByIdInternal as jest.Mock)
+ .mockResolvedValueOnce({ id: "db-key", projectId: "proj-1" })
+ .mockResolvedValueOnce({ id: "db-other", projectId: "proj-1" });
+
+ await expect(
+ resolveSdkIntelligenceDatabaseConfig(
+ makeRequest({
+ [OPENLIT_CONTEXT_HEADERS.databaseConfigId]: "db-other",
+ }),
+ "openlit-test"
+ )
+ ).resolves.toEqual([
+ null,
+ expect.objectContaining({
+ databaseConfigId: "db-other",
+ via: "databaseConfigHeader",
+ }),
+ ]);
+ expect(resolveSignalSource).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the API key bound database config for existing SDKs", async () => {
+ await expect(
+ resolveSdkIntelligenceDatabaseConfig(makeRequest(), "openlit-test")
+ ).resolves.toEqual([
+ null,
+ expect.objectContaining({
+ databaseConfigId: "db-key",
+ via: "apiKey",
+ }),
+ ]);
+ });
+});
diff --git a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
index 40eae5bc..d38557b6 100644
--- a/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
+++ b/src/client/src/__tests__/lib/platform/api-keys/api-keys.test.ts
@@ -120,6 +120,27 @@ describe('getAllAPIKeys', () => {
expect(result).toEqual([{ name: 'key1', apiKey: 'openlit-abc' }]);
});
+ it('uses an explicit databaseConfigId without session db lookup', async () => {
+ (asaw as jest.Mock).mockResolvedValueOnce([
+ null,
+ [{ name: 'key1', apiKey: 'openlit-abc' }],
+ ]);
+ (prisma.aPIKeys.findMany as jest.Mock).mockResolvedValue([{ name: 'key1' }]);
+
+ await getAllAPIKeys('db-from-api-key');
+ expect(getDBConfigByUser).not.toHaveBeenCalled();
+ expect(prisma.aPIKeys.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: {
+ AND: [
+ { databaseConfigId: 'db-from-api-key' },
+ { isDeleted: false },
+ ],
+ },
+ })
+ );
+ });
+
it('throws when dbConfig is not found', async () => {
(asaw as jest.Mock).mockResolvedValueOnce([null, null]);
await expect(getAllAPIKeys()).rejects.toThrow('DB config not found');
diff --git a/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts b/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts
index 5f5d9ecf..c7756d57 100644
--- a/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts
+++ b/src/client/src/__tests__/lib/platform/llm/agent-loop.test.ts
@@ -54,6 +54,7 @@ describe("getAgentLoop", () => {
mockedResolve.mockResolvedValue({
isBuiltIn: true,
type: "clickhouse",
+ dbConfigId: "db-dev",
} as any);
});
@@ -69,17 +70,51 @@ describe("getAgentLoop", () => {
],
});
- const result = await getAgentLoop(params);
+ const result = await getAgentLoop({
+ ...params,
+ environment: "dev",
+ });
const row = result.data?.[0];
expect(row?.tool_traces).toBe(40);
expect(row?.loops).toBe(8);
expect(row?.loops_pct).toBe(20);
+ expect(mockedResolve).toHaveBeenCalledWith({
+ signal: "traces",
+ sourceId: undefined,
+ environment: "dev",
+ });
+ expect(mockedDataCollector).toHaveBeenCalledWith(
+ expect.objectContaining({ query: expect.any(String) }),
+ "query",
+ "db-dev"
+ );
const query = mockedDataCollector.mock.calls[0][0].query as string;
expect(query).toContain("tool_traces");
expect(query).toContain("uniqExactIf");
expect(query).toContain("gen_ai.tool.name");
});
+ it("prefers an explicit databaseConfigId over the resolved traces binding", async () => {
+ mockedResolve.mockResolvedValue({
+ isBuiltIn: true,
+ type: "clickhouse",
+ dbConfigId: "db-from-environment",
+ } as any);
+ mockedDataCollector.mockResolvedValue({ data: [{}] });
+
+ await getAgentLoop({
+ ...params,
+ environment: "dev",
+ databaseConfigId: "db-explicit",
+ });
+
+ expect(mockedDataCollector).toHaveBeenCalledWith(
+ expect.anything(),
+ "query",
+ "db-explicit"
+ );
+ });
+
it("returns unsupported when the source cannot sample traces", async () => {
mockedResolve.mockResolvedValue({
isBuiltIn: false,
diff --git a/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts b/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts
index 8d06a762..032e56d1 100644
--- a/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts
+++ b/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts
@@ -54,6 +54,7 @@ describe("getGenerationHealth", () => {
mockedResolve.mockResolvedValue({
isBuiltIn: true,
type: "clickhouse",
+ dbConfigId: "db-dev",
} as any);
});
@@ -81,7 +82,10 @@ describe("getGenerationHealth", () => {
],
});
- const result = await getGenerationHealth(params);
+ const result = await getGenerationHealth({
+ ...params,
+ environment: "dev",
+ });
const row = result.data?.[0];
expect(row?.llm_spans).toBe(100);
expect(row?.truncated).toBe(10);
@@ -89,6 +93,16 @@ describe("getGenerationHealth", () => {
expect(row?.truncated_pct).toBe(25);
expect(row?.swapped_pct).toBe(25);
expect(row?.empty_pct).toBe(5);
+ expect(mockedResolve).toHaveBeenCalledWith({
+ signal: "traces",
+ sourceId: undefined,
+ environment: "dev",
+ });
+ expect(mockedDataCollector).toHaveBeenCalledWith(
+ expect.objectContaining({ query: expect.any(String) }),
+ "query",
+ "db-dev"
+ );
const query = mockedDataCollector.mock.calls[0][0].query as string;
expect(query).toContain("finish_eligible");
expect(query).toContain("swap_eligible");
@@ -99,6 +113,27 @@ describe("getGenerationHealth", () => {
expect(query).not.toContain("operationType");
});
+ it("prefers an explicit databaseConfigId over the resolved traces binding", async () => {
+ mockedResolve.mockResolvedValue({
+ isBuiltIn: true,
+ type: "clickhouse",
+ dbConfigId: "db-from-environment",
+ } as any);
+ mockedDataCollector.mockResolvedValue({ data: [{}] });
+
+ await getGenerationHealth({
+ ...params,
+ environment: "dev",
+ databaseConfigId: "db-explicit",
+ });
+
+ expect(mockedDataCollector).toHaveBeenCalledWith(
+ expect.anything(),
+ "query",
+ "db-explicit"
+ );
+ });
+
it("returns unsupported when the source cannot sample traces", async () => {
mockedResolve.mockResolvedValue({
isBuiltIn: false,
diff --git a/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts b/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts
index ed7adb1a..86b92e9a 100644
--- a/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts
+++ b/src/client/src/__tests__/lib/platform/rule-engine/source.test.ts
@@ -46,7 +46,27 @@ describe("resolveRuleEngineDatabaseConfigId", () => {
});
});
- it("prefers the explicitly selected project ClickHouse", async () => {
+ it("uses environment binding even when an explicit ClickHouse header is present", async () => {
+ (resolveSignalSource as jest.Mock).mockResolvedValue({
+ hasSource: true,
+ descriptor: { type: "clickhouse", dbConfigId: "db-production" },
+ });
+
+ await expect(
+ resolveRuleEngineDatabaseConfigId(
+ requestWithContext({
+ environment: "production",
+ databaseConfigId: "db-selected",
+ })
+ )
+ ).resolves.toBe("db-production");
+ expect(resolveSignalSource).toHaveBeenCalledWith("intelligence", {
+ environment: "production",
+ });
+ expect(getDBConfigByUser).not.toHaveBeenCalled();
+ });
+
+ it("uses the explicitly selected project ClickHouse when no environment is set", async () => {
(getDBConfigByUser as jest.Mock).mockResolvedValue([
{ id: "db-selected" },
{ id: "db-other" },
@@ -55,7 +75,6 @@ describe("resolveRuleEngineDatabaseConfigId", () => {
await expect(
resolveRuleEngineDatabaseConfigId(
requestWithContext({
- environment: "production",
databaseConfigId: "db-selected",
})
)
diff --git a/src/client/src/__tests__/lib/platform/vault/vault.test.ts b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
index 951bf27e..98d6c32a 100644
--- a/src/client/src/__tests__/lib/platform/vault/vault.test.ts
+++ b/src/client/src/__tests__/lib/platform/vault/vault.test.ts
@@ -202,6 +202,24 @@ describe('getSecretById', () => {
const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
expect(query).not.toContain('EXCEPT value');
});
+
+ it('allows DB-scoped lookup without a session when databaseConfigId is set', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValueOnce(null);
+ await getSecretById('v1', 'db-1', false);
+ const [{ query }] = (dataCollector as jest.Mock).mock.calls[0];
+ expect(query).toContain("v.id = 'v1'");
+ expect(query).not.toContain('created_by');
+ expect(dataCollector).toHaveBeenCalledWith(
+ expect.anything(),
+ 'query',
+ 'db-1'
+ );
+ });
+
+ it('rejects unauthenticated lookups without databaseConfigId', async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValueOnce(null);
+ await expect(getSecretById('v1')).rejects.toThrow('Unauthorized');
+ });
});
describe('upsertSecret', () => {
diff --git a/src/client/src/__tests__/lib/rbac/route.test.ts b/src/client/src/__tests__/lib/rbac/route.test.ts
index 5a0dddad..a3b3fca7 100644
--- a/src/client/src/__tests__/lib/rbac/route.test.ts
+++ b/src/client/src/__tests__/lib/rbac/route.test.ts
@@ -106,6 +106,20 @@ describe("withDbConfigAccess", () => {
expect(handler).not.toHaveBeenCalled();
});
+ it("allows API key requests via middleware x-database-config-id without a session", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+ const wrapped = withDbConfigAccess(handler);
+
+ await wrapped(
+ jsonRequest({}, { "x-database-config-id": "api-key-db" }),
+ {}
+ );
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(getCurrentUser).not.toHaveBeenCalled();
+ expect(getDBConfigByIdForUser).not.toHaveBeenCalled();
+ });
+
it("returns 403 when no db config id and org has no current project", async () => {
(getCurrentUser as jest.Mock).mockResolvedValue({ id: "u1" });
(getCurrentOrganisation as jest.Mock).mockResolvedValue({ id: "org1" });
diff --git a/src/client/src/__tests__/utils/breadcrumbs.test.ts b/src/client/src/__tests__/utils/breadcrumbs.test.ts
index 6ff0128f..6ec6361b 100644
--- a/src/client/src/__tests__/utils/breadcrumbs.test.ts
+++ b/src/client/src/__tests__/utils/breadcrumbs.test.ts
@@ -195,6 +195,14 @@ describe('generatePageHeader', () => {
expect(header.breadcrumbs).toContainEqual({ title: 'Organisation', href: '/organisation' });
});
+ it('generates breadcrumbs for /organisation/projects under Settings', () => {
+ const header = generatePageHeader('/organisation/projects');
+ expect(header.title).toBe('Projects');
+ expect(header.breadcrumbs).toContainEqual({ title: 'Settings', href: '/settings' });
+ expect(header.breadcrumbs).toContainEqual({ title: 'Organisation', href: '/organisation' });
+ expect(header.breadcrumbs).toContainEqual({ title: 'Projects', href: '/organisation/projects' });
+ });
+
it('generates breadcrumbs for /settings/database-config', () => {
const header = generatePageHeader('/settings/database-config');
expect(header.title).toBe('Database Config');
diff --git a/src/client/src/app/(playground)/openapi-spec/page.tsx b/src/client/src/app/(playground)/openapi-spec/page.tsx
index b1974114..41af9efd 100644
--- a/src/client/src/app/(playground)/openapi-spec/page.tsx
+++ b/src/client/src/app/(playground)/openapi-spec/page.tsx
@@ -1,11 +1,14 @@
"use client";
import ApiReference from "@/components/(playground)/api-keys/api-reference";
import FeaturePageHeader from "@/components/(playground)/feature-page-header";
+import getMessage from "@/constants/messages";
import { ApiKey } from "@/types/api-key";
-import { BookText } from "lucide-react";
+import { BookText } from "lucide-react";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import OpenLitContextIds from "@/components/(playground)/openlit-context-ids";
export default function OpenApiPage() {
+ const messages = getMessage();
const { data } = useFetchWrapper<ApiKey[]>();
const userApiKey = data && data.length > 0 ? data[0].apiKey : undefined;
@@ -13,10 +16,11 @@ export default function OpenApiPage() {
return (
<div className="flex flex-col grow w-full h-full overflow-hidden">
<FeaturePageHeader
- eyebrow="Documentation"
- title="Open API Spec"
+ eyebrow={messages.AUTH_DOCUMENTATION}
+ title={messages.OPENAPI_SPEC_PAGE_TITLE}
icon={<BookText className="h-4 w-4" />}
tone="border-primary/20 bg-primary/10 text-primary dark:border-primary/30 dark:bg-primary/15"
+ actions={<OpenLitContextIds />}
/>
<div className="flex-1 w-full p-4 overflow-hidden grow overflow-hidden">
<ApiReference userApiKey={userApiKey} />
diff --git a/src/client/src/app/(playground)/organisation/page.tsx b/src/client/src/app/(playground)/organisation/page.tsx
index 89f63108..96469976 100644
--- a/src/client/src/app/(playground)/organisation/page.tsx
+++ b/src/client/src/app/(playground)/organisation/page.tsx
@@ -1,5 +1,14 @@
+import { redirect } from "next/navigation";
import OrganisationPage from "@/components/(playground)/organisation/organisation-page";
-export default function OrganisationRoutePage() {
+export default function OrganisationRoutePage({
+ searchParams,
+}: {
+ searchParams: { tab?: string };
+}) {
+ if (searchParams.tab === "projects") {
+ redirect("/organisation/projects");
+ }
+
return <OrganisationPage />;
}
diff --git a/src/client/src/app/(playground)/organisation/projects/page.tsx b/src/client/src/app/(playground)/organisation/projects/page.tsx
new file mode 100644
index 00000000..3bea40e9
--- /dev/null
+++ b/src/client/src/app/(playground)/organisation/projects/page.tsx
@@ -0,0 +1,5 @@
+import OrganisationPage from "@/components/(playground)/organisation/organisation-page";
+
+export default function OrganisationProjectsPage() {
+ return <OrganisationPage />;
+}
diff --git a/src/client/src/app/api/api-key/[id]/route.ts b/src/client/src/app/api/api-key/[id]/route.ts
index c317331a..d67806aa 100644
--- a/src/client/src/app/api/api-key/[id]/route.ts
+++ b/src/client/src/app/api/api-key/[id]/route.ts
@@ -1,15 +1,9 @@
import { withAudit } from "@/lib/audit/route";
-import { requireCurrentOrganisationPermission } from "@/lib/rbac/current";
+import { withCurrentOrganisationPermission } from "@/lib/rbac/current";
import { deleteAPIKey } from "@/lib/platform/api-keys/index";
import asaw from "@/utils/asaw";
-import { errorResponse } from "@/utils/api-response";
async function DELETEHandler(_: Request, context: any) {
- const [permissionErr] = await asaw(
- requireCurrentOrganisationPermission("api_key:delete")
- );
- if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
-
const { id } = context.params;
const [err, res] = await deleteAPIKey(id);
if (err) {
@@ -21,4 +15,6 @@ async function DELETEHandler(_: Request, context: any) {
return Response.json(res);
}
-export const DELETE = withAudit(DELETEHandler);
+export const DELETE = withAudit(
+ withCurrentOrganisationPermission("api_key:delete", DELETEHandler)
+);
diff --git a/src/client/src/app/api/api-key/route.ts b/src/client/src/app/api/api-key/route.ts
index 164a6630..a36d413b 100644
--- a/src/client/src/app/api/api-key/route.ts
+++ b/src/client/src/app/api/api-key/route.ts
@@ -1,25 +1,18 @@
import { withAudit } from "@/lib/audit/route";
-import { requireCurrentOrganisationPermission } from "@/lib/rbac/current";
+import { withCurrentOrganisationPermission } from "@/lib/rbac/current";
import { generateAPIKey, getAllAPIKeys } from "@/lib/platform/api-keys";
import asaw from "@/utils/asaw";
-import { errorResponse } from "@/utils/api-response";
+import { MIDDLEWARE_DATABASE_CONFIG_HEADER } from "@/constants/openlit-context";
-export async function GET() {
- const [permissionErr] = await asaw(
- requireCurrentOrganisationPermission("api_key:read")
- );
- if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
-
- const res: any = await getAllAPIKeys();
+async function GETHandler(request: Request) {
+ const databaseConfigId =
+ request.headers?.get?.(MIDDLEWARE_DATABASE_CONFIG_HEADER)?.trim() ||
+ undefined;
+ const res: any = await getAllAPIKeys(databaseConfigId);
return Response.json(res);
}
async function POSTHandler(request: Request) {
- const [permissionErr] = await asaw(
- requireCurrentOrganisationPermission("api_key:create")
- );
- if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
-
const formData = await request.json();
const name = formData.name;
@@ -34,4 +27,10 @@ async function POSTHandler(request: Request) {
return Response.json(res);
}
-export const POST = withAudit(POSTHandler);
+export const GET = withCurrentOrganisationPermission(
+ "api_key:read",
+ GETHandler
+);
+export const POST = withAudit(
+ withCurrentOrganisationPermission("api_key:create", POSTHandler)
+);
diff --git a/src/client/src/app/api/chat/config/route.ts b/src/client/src/app/api/chat/config/route.ts
index ed8ea4d6..b4cc790c 100644
--- a/src/client/src/app/api/chat/config/route.ts
+++ b/src/client/src/app/api/chat/config/route.ts
@@ -1,15 +1,15 @@
import { getChatConfig, upsertChatConfig } from "@/lib/platform/chat/config";
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { NextRequest } from "next/server";
import asaw from "@/utils/asaw";
-export async function GET() {
- const user = await getCurrentUser();
- if (!user) {
+export async function GET(request: NextRequest) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
- const { data, err } = await getChatConfig();
+ const { data, err } = await getChatConfig(auth.databaseConfigId);
if (err) {
return Response.json(err, { status: 400 });
@@ -19,8 +19,8 @@ export async function GET() {
}
export async function POST(request: NextRequest) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
@@ -33,12 +33,15 @@ export async function POST(request: NextRequest) {
}
const [err, data] = await asaw(
- upsertChatConfig({
- provider: formData.provider,
- model: formData.model,
- vaultId: formData.vaultId,
- meta: formData.meta || "{}",
- })
+ upsertChatConfig(
+ {
+ provider: formData.provider,
+ model: formData.model,
+ vaultId: formData.vaultId,
+ meta: formData.meta || "{}",
+ },
+ auth.databaseConfigId
+ )
);
if (err) {
diff --git a/src/client/src/app/api/chat/conversation/[id]/route.ts b/src/client/src/app/api/chat/conversation/[id]/route.ts
index 1ddb193d..87f282b9 100644
--- a/src/client/src/app/api/chat/conversation/[id]/route.ts
+++ b/src/client/src/app/api/chat/conversation/[id]/route.ts
@@ -2,20 +2,23 @@ import {
getConversationWithMessages,
deleteConversation,
} from "@/lib/platform/chat/conversation";
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { NextRequest } from "next/server";
export async function GET(
- _: NextRequest,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
const { id } = await params;
- const { data, err } = await getConversationWithMessages(id);
+ const { data, err } = await getConversationWithMessages(
+ id,
+ auth.databaseConfigId
+ );
if (err) {
return Response.json(err, { status: 400 });
@@ -25,16 +28,16 @@ export async function GET(
}
export async function DELETE(
- _: NextRequest,
+ request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
const { id } = await params;
- const { err } = await deleteConversation(id);
+ const { err } = await deleteConversation(id, auth.databaseConfigId);
if (err) {
return Response.json(err, { status: 400 });
diff --git a/src/client/src/app/api/chat/conversation/route.ts b/src/client/src/app/api/chat/conversation/route.ts
index a64cf672..5d8c030b 100644
--- a/src/client/src/app/api/chat/conversation/route.ts
+++ b/src/client/src/app/api/chat/conversation/route.ts
@@ -2,16 +2,16 @@ import {
getConversations,
createConversation,
} from "@/lib/platform/chat/conversation";
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { NextRequest } from "next/server";
-export async function GET() {
- const user = await getCurrentUser();
- if (!user) {
+export async function GET(request: NextRequest) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
- const { data, err } = await getConversations();
+ const { data, err } = await getConversations(auth.databaseConfigId);
if (err) {
return Response.json(err, { status: 400 });
@@ -21,8 +21,8 @@ export async function GET() {
}
export async function POST(request: NextRequest) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
@@ -31,7 +31,9 @@ export async function POST(request: NextRequest) {
const { data, err } = await createConversation(
body.title || "",
body.provider || "",
- body.model || ""
+ body.model || "",
+ undefined,
+ auth.databaseConfigId
);
if (err) {
diff --git a/src/client/src/app/api/chat/improvement/[spanId]/route.ts b/src/client/src/app/api/chat/improvement/[spanId]/route.ts
index e94acab3..a01dd30a 100644
--- a/src/client/src/app/api/chat/improvement/[spanId]/route.ts
+++ b/src/client/src/app/api/chat/improvement/[spanId]/route.ts
@@ -1,16 +1,17 @@
import { SERVER_EVENTS } from "@/constants/events";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { getDBConfigByUser } from "@/lib/db-config";
import {
getTraceImprovement,
streamTraceImprovementAnalysis,
} from "@/lib/platform/chat/improvement";
-import { getCurrentUser } from "@/lib/session";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
-async function getDatabaseConfigId() {
+async function resolveDatabaseConfigId(authDatabaseConfigId?: string) {
+ if (authDatabaseConfigId) return authDatabaseConfigId;
const [, dbConfig] = await asaw(getDBConfigByUser(true));
- return (dbConfig as any)?.id || "";
+ return (dbConfig as { id?: string } | null | undefined)?.id || "";
}
function logRoute(stage: string, payload: Record<string, unknown>) {
@@ -31,13 +32,13 @@ function getEnvironment(request: Request) {
}
function getTraceId(request: Request) {
- return new URL(request.url).searchParams.get("traceId") || undefined;
+ return new URL(request.url).searchParams.get("traceId") || undefined;
}
export async function GET(request: Request, context: any) {
const startTimestamp = Date.now();
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
logRoute("get_unauthorized", {});
PostHogServer.fireEvent({
event: SERVER_EVENTS.AI_ANALYSIS_GET_FAILURE,
@@ -58,12 +59,18 @@ export async function GET(request: Request, context: any) {
return Response.json("No span id provided", { status: 400 });
}
- const databaseConfigId = await getDatabaseConfigId();
+ const databaseConfigId = await resolveDatabaseConfigId(auth.databaseConfigId);
const scope = getScope(request);
const environment = getEnvironment(request);
const traceId = getTraceId(request);
logRoute("get_start", { spanId, traceId, scope, environment, databaseConfigId });
- const { data, err } = await getTraceImprovement(spanId, databaseConfigId, scope, environment, traceId);
+ const { data, err } = await getTraceImprovement(
+ spanId,
+ databaseConfigId,
+ scope,
+ environment,
+ traceId
+ );
if (err) {
logRoute("get_failed", { spanId, scope, err });
PostHogServer.fireEvent({
@@ -96,8 +103,8 @@ export async function GET(request: Request, context: any) {
export async function POST(request: Request, context: any) {
const startTimestamp = Date.now();
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
logRoute("post_unauthorized", {});
PostHogServer.fireEvent({
event: SERVER_EVENTS.AI_ANALYSIS_RUN_FAILURE,
@@ -118,7 +125,7 @@ export async function POST(request: Request, context: any) {
return Response.json("No span id provided", { status: 400 });
}
- const databaseConfigId = await getDatabaseConfigId();
+ const databaseConfigId = await resolveDatabaseConfigId(auth.databaseConfigId);
const scope = getScope(request);
const environment = getEnvironment(request);
const traceId = getTraceId(request);
diff --git a/src/client/src/app/api/chat/message/execute/route.ts b/src/client/src/app/api/chat/message/execute/route.ts
index d24a890b..1bd1b484 100644
--- a/src/client/src/app/api/chat/message/execute/route.ts
+++ b/src/client/src/app/api/chat/message/execute/route.ts
@@ -1,4 +1,4 @@
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { intelligenceDataCollector } from "@/lib/platform/common";
import { validateSQL } from "@/lib/platform/chat/sql-validator";
import { updateMessage } from "@/lib/platform/chat/conversation";
@@ -9,17 +9,19 @@ import { authorizeTelemetrySQLRouting } from "@/lib/platform/chat/telemetry-sql-
import { NextRequest } from "next/server";
export async function POST(request: NextRequest) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
// Natural-language SQL chat runs raw ClickHouse SQL, so it is only
// available through the ClickHouse connector routed for intelligence.
- const environment = request.headers.get(OPENLIT_CONTEXT_HEADERS.environment) || undefined;
+ const environment =
+ request.headers.get(OPENLIT_CONTEXT_HEADERS.environment) || undefined;
const chatSource = await isNativeSqlChatAvailable({
signal: "intelligence",
environment,
+ ...(auth.databaseConfigId ? { dbConfigId: auth.databaseConfigId } : {}),
});
if (!chatSource.available) {
return Response.json(
@@ -38,10 +40,7 @@ export async function POST(request: NextRequest) {
// Validate SQL
const validation = validateSQL(query);
if (!validation.valid) {
- return Response.json(
- { err: validation.error },
- { status: 400 }
- );
+ return Response.json({ err: validation.error }, { status: 400 });
}
const routing = await authorizeTelemetrySQLRouting(validation.query!, {
environment,
@@ -54,10 +53,14 @@ export async function POST(request: NextRequest) {
const startTime = Date.now();
// Execute with readonly mode
- const { data, err } = await intelligenceDataCollector({
- query: validation.query!,
- enable_readonly: true,
- }, "query", chatSource.databaseConfigId);
+ const { data, err } = await intelligenceDataCollector(
+ {
+ query: validation.query!,
+ enable_readonly: true,
+ },
+ "query",
+ chatSource.databaseConfigId
+ );
const executionTimeMs = Date.now() - startTime;
diff --git a/src/client/src/app/api/chat/message/route.ts b/src/client/src/app/api/chat/message/route.ts
index 9e801bfa..24967cec 100644
--- a/src/client/src/app/api/chat/message/route.ts
+++ b/src/client/src/app/api/chat/message/route.ts
@@ -1,5 +1,5 @@
import { SERVER_EVENTS } from "@/constants/events";
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { getDBConfigByUser } from "@/lib/db-config";
import { getChatConfigWithApiKey } from "@/lib/platform/chat/config";
import { streamChatMessage, formatStreamError } from "@/lib/platform/chat/stream";
@@ -8,10 +8,16 @@ import { NextRequest } from "next/server";
import asaw from "@/utils/asaw";
import { OPENLIT_CONTEXT_HEADERS } from "@/constants/openlit-context";
+async function resolveDatabaseConfigId(authDatabaseConfigId?: string) {
+ if (authDatabaseConfigId) return authDatabaseConfigId;
+ const [, dbConfig] = await asaw(getDBConfigByUser(true));
+ return (dbConfig as { id?: string } | null | undefined)?.id || "";
+}
+
export async function POST(request: NextRequest) {
const startTimestamp = Date.now();
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth?.userId) {
PostHogServer.fireEvent({
event: SERVER_EVENTS.OTTER_CHAT_MESSAGE_FAILURE,
startTimestamp,
@@ -32,7 +38,10 @@ export async function POST(request: NextRequest) {
return Response.json("Missing conversationId or content", { status: 400 });
}
- const { data: config, err: configErr } = await getChatConfigWithApiKey();
+ const dbConfigId = await resolveDatabaseConfigId(auth.databaseConfigId);
+ const { data: config, err: configErr } = await getChatConfigWithApiKey(
+ dbConfigId || undefined
+ );
if (configErr || !config) {
PostHogServer.fireEvent({
event: SERVER_EVENTS.OTTER_CHAT_MESSAGE_FAILURE,
@@ -45,9 +54,8 @@ export async function POST(request: NextRequest) {
);
}
- const [, dbConfig] = await asaw(getDBConfigByUser(true));
- const dbConfigId = (dbConfig as any)?.id || "";
- const environment = request.headers.get(OPENLIT_CONTEXT_HEADERS.environment) || undefined;
+ const environment =
+ request.headers.get(OPENLIT_CONTEXT_HEADERS.environment) || undefined;
try {
const encoder = new TextEncoder();
@@ -62,7 +70,7 @@ export async function POST(request: NextRequest) {
provider: config.provider,
apiKey: config.apiKey,
model: config.model,
- userId: user.id,
+ userId: auth.userId!,
dbConfigId,
environment,
onDelta: (text) => send({ type: "delta", text }),
diff --git a/src/client/src/app/api/chat/message/save-widget/route.ts b/src/client/src/app/api/chat/message/save-widget/route.ts
index 6a816aa5..c3960dde 100644
--- a/src/client/src/app/api/chat/message/save-widget/route.ts
+++ b/src/client/src/app/api/chat/message/save-widget/route.ts
@@ -1,10 +1,10 @@
-import { getCurrentUser } from "@/lib/session";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { saveQueryAsWidget } from "@/lib/platform/chat/save-widget";
import { NextRequest } from "next/server";
export async function POST(request: NextRequest) {
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
return Response.json("Unauthorized", { status: 401 });
}
diff --git a/src/client/src/app/api/chat/usage/route.ts b/src/client/src/app/api/chat/usage/route.ts
index 82049f8c..c10f4530 100644
--- a/src/client/src/app/api/chat/usage/route.ts
+++ b/src/client/src/app/api/chat/usage/route.ts
@@ -1,18 +1,19 @@
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { getDBConfigByUser } from "@/lib/db-config";
import { getOtterUsage } from "@/lib/platform/chat/usage";
-import { getCurrentUser } from "@/lib/session";
import asaw from "@/utils/asaw";
-async function getDatabaseConfigId() {
+async function resolveDatabaseConfigId(authDatabaseConfigId?: string) {
+ if (authDatabaseConfigId) return authDatabaseConfigId;
const [, dbConfig] = await asaw(getDBConfigByUser(true));
- return (dbConfig as any)?.id || "";
+ return (dbConfig as { id?: string } | null | undefined)?.id || "";
}
export async function GET(request: Request) {
- const user = await getCurrentUser();
- if (!user) return Response.json("Unauthorized", { status: 401 });
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) return Response.json("Unauthorized", { status: 401 });
- const databaseConfigId = await getDatabaseConfigId();
+ const databaseConfigId = await resolveDatabaseConfigId(auth.databaseConfigId);
const searchParams = new URL(request.url).searchParams;
const start = searchParams.get("start") || undefined;
const end = searchParams.get("end") || undefined;
diff --git a/src/client/src/app/api/db-config/route.ts b/src/client/src/app/api/db-config/route.ts
index 501afce1..f3a65b48 100644
--- a/src/client/src/app/api/db-config/route.ts
+++ b/src/client/src/app/api/db-config/route.ts
@@ -1,10 +1,18 @@
import { withAudit } from "@/lib/audit/route";
-import { requireCurrentOrganisationPermission } from "@/lib/rbac/current";
-import { getDBConfigByUser, upsertDBConfig } from "@/lib/db-config";
+import {
+ requireCurrentOrganisationPermission,
+ withCurrentOrganisationPermission,
+} from "@/lib/rbac/current";
+import {
+ getDBConfigByIdInternal,
+ getDBConfigByUser,
+ upsertDBConfig,
+} from "@/lib/db-config";
import asaw from "@/utils/asaw";
import { DatabaseConfig } from "@prisma/client";
import { errorResponse } from "@/utils/api-response";
import { createProjectEnvironment } from "@/lib/project-environment";
+import { MIDDLEWARE_DATABASE_CONFIG_HEADER } from "@/constants/openlit-context";
function stripSensitiveDbFields(config: any) {
if (!config) return config;
@@ -13,11 +21,20 @@ function stripSensitiveDbFields(config: any) {
return { ...rest, password: password ? "****" : "" };
}
-export async function GET() {
- const [permissionErr] = await asaw(
- requireCurrentOrganisationPermission("db_config:read")
- );
- if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
+async function GETHandler(request: Request) {
+ const apiKeyDatabaseConfigId =
+ request.headers?.get?.(MIDDLEWARE_DATABASE_CONFIG_HEADER)?.trim() ||
+ undefined;
+
+ if (apiKeyDatabaseConfigId) {
+ const [err, config]: any = await asaw(
+ getDBConfigByIdInternal({ id: apiKeyDatabaseConfigId })
+ );
+ if (err) {
+ return errorResponse(err, "Failed to fetch database configurations");
+ }
+ return Response.json(config ? [stripSensitiveDbFields(config)] : []);
+ }
const [err, res]: any = await asaw(getDBConfigByUser());
if (err)
@@ -33,12 +50,17 @@ export async function GET() {
async function POSTHandler(request: Request) {
const formData = await request.json();
const id = formData.id;
- const requiredPermission = id ? "db_config:update" : "db_config:create" as const;
+ const apiKeyDatabaseConfigId =
+ request.headers?.get?.(MIDDLEWARE_DATABASE_CONFIG_HEADER)?.trim() ||
+ undefined;
- const [permissionErr] = await asaw(
- requireCurrentOrganisationPermission(requiredPermission)
- );
- if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
+ if (!apiKeyDatabaseConfigId) {
+ const requiredPermission = id ? "db_config:update" : "db_config:create";
+ const [permissionErr] = await asaw(
+ requireCurrentOrganisationPermission(requiredPermission)
+ );
+ if (permissionErr) return errorResponse(permissionErr, "Forbidden", 403);
+ }
const dbConfig: Partial<DatabaseConfig> = {
name: formData.name,
@@ -69,4 +91,8 @@ async function POSTHandler(request: Request) {
return Response.json(res);
}
+export const GET = withCurrentOrganisationPermission(
+ "db_config:read",
+ GETHandler
+);
export const POST = withAudit(POSTHandler);
diff --git a/src/client/src/app/api/prompt/get-compiled/route.ts b/src/client/src/app/api/prompt/get-compiled/route.ts
index c8dfaa65..91358272 100644
--- a/src/client/src/app/api/prompt/get-compiled/route.ts
+++ b/src/client/src/app/api/prompt/get-compiled/route.ts
@@ -1,10 +1,14 @@
import { SERVER_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
import { PromptCompiledInput } from "@/constants/prompts";
+import { resolveSdkIntelligenceDatabaseConfig } from "@/helpers/server/sdk-intelligence";
import { getCompiledPrompt } from "@/lib/platform/prompt/compiled";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
+const CORS_HEADERS =
+ "Content-Type, Authorization, x-openlit-organisation-id, x-openlit-project-id, x-openlit-environment, x-openlit-database-config-id";
+
export async function POST(request: Request) {
const startTimestamp = Date.now();
const authorizationHeader = request.headers.get("Authorization") || "";
@@ -18,6 +22,17 @@ export async function POST(request: Request) {
});
}
+ const [resolveErr, resolved] = await resolveSdkIntelligenceDatabaseConfig(
+ request,
+ apiKey
+ );
+ if (resolveErr || !resolved) {
+ return Response.json({
+ err: resolveErr || getMessage().NO_API_KEY,
+ res: null,
+ });
+ }
+
const formData = await request.json();
const promptInput: PromptCompiledInput = {
@@ -29,6 +44,7 @@ export async function POST(request: Request) {
shouldCompile: !!formData.shouldCompile,
downloadMetaProperties: formData.metaProperties,
downloadSource: formData.source,
+ databaseConfigId: resolved.databaseConfigId,
};
const [err, res]: any = await asaw(getCompiledPrompt(promptInput));
@@ -38,6 +54,7 @@ export async function POST(request: Request) {
: SERVER_EVENTS.PROMPT_SDK_FETCH_SUCCESS,
properties: {
downloadSource: formData.source,
+ resolveVia: resolved.via,
},
startTimestamp,
});
@@ -54,7 +71,7 @@ export async function OPTIONS() {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
+ "Access-Control-Allow-Headers": CORS_HEADERS,
},
});
}
diff --git a/src/client/src/app/api/prompt/improve/route.ts b/src/client/src/app/api/prompt/improve/route.ts
index 8562fd9a..97371b69 100644
--- a/src/client/src/app/api/prompt/improve/route.ts
+++ b/src/client/src/app/api/prompt/improve/route.ts
@@ -1,12 +1,12 @@
import { generateText } from "ai";
import { SERVER_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
+import { resolveRequestAuth } from "@/helpers/server/auth";
import { getDBConfigByUser } from "@/lib/db-config";
import { getChatConfigWithApiKey } from "@/lib/platform/chat/config";
import { saveOtterRun } from "@/lib/platform/chat/otter-runs";
import { getModelInstance } from "@/lib/platform/chat/stream";
import PostHogServer from "@/lib/posthog";
-import { getCurrentUser } from "@/lib/session";
import asaw from "@/utils/asaw";
type PromptImprovementSuggestion = {
@@ -27,9 +27,10 @@ const DEFAULT_CRITERIA = [
m.PROMPT_OTTER_CRITERIA_AMBIGUITY,
];
-async function getDatabaseConfigId() {
+async function resolveDatabaseConfigId(authDatabaseConfigId?: string) {
+ if (authDatabaseConfigId) return authDatabaseConfigId;
const [, dbConfig] = await asaw(getDBConfigByUser(true));
- return (dbConfig as any)?.id || "";
+ return (dbConfig as { id?: string } | null | undefined)?.id || "";
}
function stripCodeFence(text: string) {
@@ -65,8 +66,8 @@ function estimateCost(promptTokens: number, completionTokens: number) {
export async function POST(request: Request) {
const startTimestamp = Date.now();
- const user = await getCurrentUser();
- if (!user) {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
PostHogServer.fireEvent({
event: SERVER_EVENTS.PROMPT_IMPROVEMENT_FAILURE,
startTimestamp,
@@ -91,7 +92,7 @@ export async function POST(request: Request) {
return Response.json({ err: m.PROMPT_HUB_CONTENT_REQUIRED }, { status: 400 });
}
- const databaseConfigId = await getDatabaseConfigId();
+ const databaseConfigId = await resolveDatabaseConfigId(auth.databaseConfigId);
const { data: config, err } = await getChatConfigWithApiKey(databaseConfigId);
if (err || !config) {
PostHogServer.fireEvent({
diff --git a/src/client/src/app/api/rule-engine/evaluate/route.ts b/src/client/src/app/api/rule-engine/evaluate/route.ts
index 031966b5..7d35ae8d 100644
--- a/src/client/src/app/api/rule-engine/evaluate/route.ts
+++ b/src/client/src/app/api/rule-engine/evaluate/route.ts
@@ -1,12 +1,15 @@
import { SERVER_EVENTS } from "@/constants/events";
import { EvaluateInput } from "@/types/rule-engine";
import { evaluateRules } from "@/lib/platform/rule-engine/evaluate";
-import { getAPIKeyInfo } from "@/lib/platform/api-keys";
import { getCurrentUser } from "@/lib/session";
import getMessage from "@/constants/messages";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
import { resolveRuleEngineDatabaseConfigId } from "@/lib/platform/rule-engine/source";
+import { resolveSdkIntelligenceDatabaseConfig } from "@/helpers/server/sdk-intelligence";
+
+const CORS_HEADERS =
+ "Content-Type, Authorization, x-openlit-organisation-id, x-openlit-project-id, x-openlit-environment, x-openlit-database-config-id";
export async function POST(request: Request) {
const startTimestamp = Date.now();
@@ -21,19 +24,39 @@ export async function POST(request: Request) {
return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });
}
- const [keyErr, apiInfo] = await getAPIKeyInfo({ apiKey });
- if (keyErr || !apiInfo?.databaseConfigId) {
- return Response.json({ err: getMessage().NO_API_KEY }, { status: 401 });
+ const [resolveErr, resolved] = await resolveSdkIntelligenceDatabaseConfig(
+ request,
+ apiKey
+ );
+ if (resolveErr || !resolved) {
+ return Response.json(
+ { err: resolveErr || getMessage().NO_API_KEY },
+ { status: 401 }
+ );
}
-
- databaseConfigId = apiInfo.databaseConfigId;
+ databaseConfigId = resolved.databaseConfigId;
} else {
// Session-based auth (dashboard usage)
const user = await getCurrentUser();
if (!user) {
- return Response.json({ err: getMessage().UNAUTHORIZED_USER }, { status: 401 });
+ return Response.json(
+ { err: getMessage().UNAUTHORIZED_USER },
+ { status: 401 }
+ );
+ }
+ try {
+ databaseConfigId = await resolveRuleEngineDatabaseConfigId(request);
+ } catch (error) {
+ return Response.json(
+ {
+ err:
+ error instanceof Error
+ ? error.message
+ : "Failed to resolve Rule Engine datasource",
+ },
+ { status: 400 }
+ );
}
- databaseConfigId = await resolveRuleEngineDatabaseConfigId(request);
}
// --- Parse request body ---
@@ -46,13 +69,17 @@ export async function POST(request: Request) {
// --- Validate entity_type ---
const VALID_ENTITY_TYPES = [
- "context", "prompt", "evaluation",
+ "context",
+ "prompt",
+ "evaluation",
// "dataset", "meta_config",
] as const;
const entityType = body?.entity_type;
if (!entityType || !VALID_ENTITY_TYPES.includes(entityType)) {
return Response.json(
- { err: `entity_type is required and must be one of: ${VALID_ENTITY_TYPES.join(", ")}` },
+ {
+ err: `entity_type is required and must be one of: ${VALID_ENTITY_TYPES.join(", ")}`,
+ },
{ status: 400 }
);
}
@@ -77,17 +104,15 @@ export async function POST(request: Request) {
if (typeof key !== "string") continue;
const trimmedKey = key.trim();
if (trimmedKey.length === 0 || trimmedKey.length > MAX_KEY_LENGTH) continue;
- if (
- typeof value === "string" &&
- value.length <= MAX_VALUE_LENGTH
- ) {
+ if (typeof value === "string" && value.length <= MAX_VALUE_LENGTH) {
fieldsMap.set(trimmedKey, value);
} else if (typeof value === "number" || typeof value === "boolean") {
fieldsMap.set(trimmedKey, value);
}
}
- const sanitizedFields: Record<string, string | number | boolean> = Object.fromEntries(fieldsMap);
+ const sanitizedFields: Record<string, string | number | boolean> =
+ Object.fromEntries(fieldsMap);
if (fieldsMap.size === 0) {
return Response.json(
@@ -107,12 +132,17 @@ export async function POST(request: Request) {
fields: sanitizedFields,
entity_type: entityType,
include_entity_data: body?.include_entity_data === true,
- entity_inputs: body?.entity_inputs && typeof body.entity_inputs === "object" && !Array.isArray(body.entity_inputs)
- ? body.entity_inputs
- : undefined,
+ entity_inputs:
+ body?.entity_inputs &&
+ typeof body.entity_inputs === "object" &&
+ !Array.isArray(body.entity_inputs)
+ ? body.entity_inputs
+ : undefined,
};
- const [err, res]: any = await asaw(evaluateRules(evaluateInput, databaseConfigId));
+ const [err, res]: any = await asaw(
+ evaluateRules(evaluateInput, databaseConfigId)
+ );
if (err) {
PostHogServer.fireEvent({
event: SERVER_EVENTS.RULE_EVALUATE_FAILURE,
@@ -135,7 +165,7 @@ export async function OPTIONS() {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
+ "Access-Control-Allow-Headers": CORS_HEADERS,
},
});
}
diff --git a/src/client/src/app/api/vault/get-secrets/route.ts b/src/client/src/app/api/vault/get-secrets/route.ts
index deb46031..e491865f 100644
--- a/src/client/src/app/api/vault/get-secrets/route.ts
+++ b/src/client/src/app/api/vault/get-secrets/route.ts
@@ -1,12 +1,14 @@
import { SERVER_EVENTS } from "@/constants/events";
import getMessage from "@/constants/messages";
import { SecretGetFiltersWithApiKey } from "@/types/vault";
+import { resolveSdkIntelligenceDatabaseConfig } from "@/helpers/server/sdk-intelligence";
import { getSecretsFromDatabaseId } from "@/lib/platform/vault";
import PostHogServer from "@/lib/posthog";
import asaw from "@/utils/asaw";
const CORS_METHODS = "POST, OPTIONS";
-const CORS_HEADERS = "Content-Type, Authorization";
+const CORS_HEADERS =
+ "Content-Type, Authorization, x-openlit-organisation-id, x-openlit-project-id, x-openlit-environment, x-openlit-database-config-id";
function getConfiguredAllowedOrigins() {
return [
@@ -42,7 +44,7 @@ function getCorsHeaders(origin: string) {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": CORS_METHODS,
"Access-Control-Allow-Headers": CORS_HEADERS,
- "Vary": "Origin",
+ Vary: "Origin",
};
}
@@ -69,12 +71,29 @@ export async function POST(request: Request) {
});
}
+ const [resolveErr, resolved] = await resolveSdkIntelligenceDatabaseConfig(
+ request,
+ apiKey
+ );
+ if (resolveErr || !resolved) {
+ return Response.json(
+ {
+ err: resolveErr || getMessage().NO_API_KEY,
+ res: null,
+ },
+ {
+ headers: corsOrigin ? getCorsHeaders(corsOrigin) : undefined,
+ }
+ );
+ }
+
const formData = await request.json();
const filters: SecretGetFiltersWithApiKey = {
apiKey,
key: formData.key,
tags: formData.tags,
+ databaseConfigId: resolved.databaseConfigId,
};
const [err, data]: any = await asaw(getSecretsFromDatabaseId(filters));
@@ -84,6 +103,7 @@ export async function POST(request: Request) {
: SERVER_EVENTS.VAULT_SECRET_SDK_FETCH_SUCCESS,
properties: {
downloadSource: formData.source,
+ resolveVia: resolved.via,
},
startTimestamp,
});
diff --git a/src/client/src/components/(playground)/api-keys/api-reference.tsx b/src/client/src/components/(playground)/api-keys/api-reference.tsx
index 01e88553..45759996 100644
--- a/src/client/src/components/(playground)/api-keys/api-reference.tsx
+++ b/src/client/src/components/(playground)/api-keys/api-reference.tsx
@@ -8,15 +8,41 @@ import getMessage from "@/constants/messages";
import { ApiEndpoint, API_REFERENCE_ENDPOINTS } from "@/constants/api-reference";
+type ParameterLocation = "header" | "path" | "query" | "body";
+
interface ParameterDoc {
name: string;
type: string;
required: boolean;
description: string;
+ /** Where the value is sent: HTTP header, URL path, query string, or JSON body. */
+ location: ParameterLocation;
allowedValues?: string[];
example?: string;
}
+const PARAMETER_LOCATION_LABEL: Record<ParameterLocation, string> = {
+ header: "Header",
+ path: "Path",
+ query: "Query",
+ body: "Body",
+};
+
+function asBodyParams(
+ docs: Omit<ParameterDoc, "location">[]
+): ParameterDoc[] {
+ return docs.map((doc) => ({ ...doc, location: "body" }));
+}
+
+function asPathParam(doc: Omit<ParameterDoc, "location">): ParameterDoc {
+ return { ...doc, location: "path" };
+}
+
+function asQueryParam(doc: Omit<ParameterDoc, "location">): ParameterDoc {
+ return { ...doc, location: "query" };
+}
+
+
interface ApiReferenceProps {
userApiKey?: string;
}
@@ -27,6 +53,85 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
const [copiedField, setCopiedField] = useState<string | null>(null);
const messages = getMessage();
+ const contextHeaderDocs: ParameterDoc[] = [
+ {
+ name: "x-openlit-organisation-id",
+ type: "string",
+ required: false,
+ location: "header",
+ description:
+ "Active organisation ID. Recommended for multi-organisation API-key clients.",
+ example: "org_01HXYZ",
+ },
+ {
+ name: "x-openlit-project-id",
+ type: "string",
+ required: true,
+ location: "header",
+ description:
+ "Active project ID. Telemetry source bindings are project-scoped.",
+ example: "proj_01HXYZ",
+ },
+ {
+ name: "x-openlit-environment",
+ type: "string",
+ required: true,
+ location: "header",
+ description:
+ "Active project environment (e.g. production). Required for signal routing of traces/logs/metrics/intelligence.",
+ example: "production",
+ },
+ ];
+
+ const withContextHeaders = (docs: ParameterDoc[]): ParameterDoc[] => [
+ ...contextHeaderDocs,
+ ...docs,
+ ];
+
+ const sdkContextHeaderDocs: ParameterDoc[] = [
+ {
+ name: "x-openlit-organisation-id",
+ type: "string",
+ required: false,
+ location: "header",
+ description:
+ "Active organisation ID. Recommended for multi-organisation API-key clients.",
+ example: "org_01HXYZ",
+ },
+ {
+ name: "x-openlit-project-id",
+ type: "string",
+ required: false,
+ location: "header",
+ description:
+ "Preferred with environment for intelligence signal routing. When omitted, the API key's project is used.",
+ example: "proj_01HXYZ",
+ },
+ {
+ name: "x-openlit-environment",
+ type: "string",
+ required: false,
+ location: "header",
+ description:
+ "Preferred for intelligence signal routing. When omitted, falls back to the API key's bound database config.",
+ example: "production",
+ },
+ {
+ name: "x-openlit-database-config-id",
+ type: "string",
+ required: false,
+ location: "header",
+ description:
+ "Optional explicit ClickHouse database config for SDK endpoints. Must belong to the same project as the API key. Prefer signal routing instead.",
+ example: "dbcfg_01HXYZ",
+ },
+ ];
+
+ const withSdkContextHeaders = (docs: ParameterDoc[]): ParameterDoc[] => [
+ ...sdkContextHeaderDocs,
+ ...docs,
+ ];
+
const getParameterDocs = (endpointId: string): ParameterDoc[] => {
if (
endpointId === "query-traces" ||
@@ -37,7 +142,7 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
) {
const isLog = endpointId === "query-logs";
const isMetric = endpointId === "query-metrics" || endpointId === "get-metric-detail";
- const docs: ParameterDoc[] = [
+ const docs: Omit<ParameterDoc, "location">[] = [
{
name: "timeLimit",
type: "object",
@@ -161,233 +266,249 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
example: "true",
});
- return docs;
+ return withContextHeaders(asBodyParams(docs));
}
if (endpointId === "get-log") {
- return [
- {
+ return withContextHeaders([
+ asPathParam({
name: "id",
type: "string",
required: true,
- description: "Path parameter. Unique hash/row identifier of the log record.",
+ description: "Unique hash/row identifier of the log record.",
example: "18446744073709551615",
- },
- ];
+ }),
+ ]);
}
if (endpointId === "get-compiled-prompt") {
- return [
- {
- name: "name",
- type: "string",
- required: true,
- description: "Query parameter. Prompt template identifier name.",
- example: "summarize-prompt",
- },
- ];
+ return withSdkContextHeaders(
+ asBodyParams([
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Prompt template identifier name.",
+ example: "summarize-prompt",
+ },
+ ])
+ );
}
if (endpointId === "get-secrets") {
- return [
- {
- name: "keys",
- type: "string",
- required: false,
- description: "Query parameter. Comma-separated list of keys to fetch from the vault.",
- example: "OPENAI_API_KEY,ANTHROPIC_API_KEY",
- },
- ];
+ return withSdkContextHeaders(
+ asBodyParams([
+ {
+ name: "keys",
+ type: "string",
+ required: false,
+ description: "Comma-separated list of keys to fetch from the vault.",
+ example: "OPENAI_API_KEY,ANTHROPIC_API_KEY",
+ },
+ ])
+ );
}
if (endpointId === "evaluate-rules") {
- return [
- {
- name: "entity_type",
- type: "string",
- required: true,
- description: "Type of rule engine entity to evaluate.",
- allowedValues: ["prompt", "span"],
- example: "prompt",
- },
- {
- name: "fields",
- type: "object",
- required: true,
- description: "Input fields to run redaction, guardrail, or format rules against.",
- example: "{ \"input_text\": \"...\" }",
- },
- ];
+ return withSdkContextHeaders(
+ asBodyParams([
+ {
+ name: "entity_type",
+ type: "string",
+ required: true,
+ description: "Type of rule engine entity to evaluate.",
+ allowedValues: ["prompt", "span"],
+ example: "prompt",
+ },
+ {
+ name: "fields",
+ type: "object",
+ required: true,
+ description: "Input fields to run redaction, guardrail, or format rules against.",
+ example: "{ \"input_text\": \"...\" }",
+ },
+ ])
+ );
}
if (endpointId === "controller-poll") {
- return [
- {
- name: "instance_id",
- type: "string",
- required: true,
- description: "Unique identifier for the polling client agent instance.",
- example: "client-instance-xyz-123",
- },
- {
- name: "config_hash",
- type: "string",
- required: false,
- description: "MD5 hash of the cached controller config on the client side.",
- example: "88863aa992efcc3c48bc625d97f26c51",
- },
- ];
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "instance_id",
+ type: "string",
+ required: true,
+ description: "Unique identifier for the polling client agent instance.",
+ example: "client-instance-xyz-123",
+ },
+ {
+ name: "config_hash",
+ type: "string",
+ required: false,
+ description: "MD5 hash of the cached controller config on the client side.",
+ example: "88863aa992efcc3c48bc625d97f26c51",
+ },
+ ])
+ );
}
if (endpointId === "evaluation-offline") {
- return [
- {
- name: "prompt",
- type: "string",
- required: true,
- description: "The prompt text to evaluate.",
- example: "I need to reset my password, my email is [email protected]",
- },
- {
- name: "response",
- type: "string",
- required: true,
- description: "The LLM generated response to evaluate.",
- example: "I can help with that. Please verify your identity.",
- },
- {
- name: "contexts",
- type: "string[]",
- required: false,
- description: "Retrieved context document texts used by the LLM.",
- example: '["User password reset procedure document."]',
- },
- {
- name: "eval_types",
- type: "string[]",
- required: false,
- description: "Scorers to execute. Can be toxicity, hallucination, bias, pii.",
- example: '["toxicity", "pii"]',
- },
- {
- name: "threshold_score",
- type: "number",
- required: false,
- description: "Minimum score required to trigger validation flags. Defaults to 0.5.",
- example: "0.5",
- },
- {
- name: "store_results",
- type: "boolean",
- required: false,
- description: "Persist the evaluation metrics run results to ClickHouse. Defaults to true.",
- example: "true",
- },
- {
- name: "run_id",
- type: "string",
- required: false,
- description: "Optional external execution or batch tracking ID.",
- example: "run-998877",
- },
- {
- name: "metadata",
- type: "object",
- required: false,
- description: "Custom metadata key-value properties dictionary (max 20 entries).",
- },
- {
- name: "attributes",
- type: "object",
- required: false,
- description: "Custom payload attributes dictionary.",
- },
- ];
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "prompt",
+ type: "string",
+ required: true,
+ description: "The prompt text to evaluate.",
+ example: "I need to reset my password, my email is [email protected]",
+ },
+ {
+ name: "response",
+ type: "string",
+ required: true,
+ description: "The LLM generated response to evaluate.",
+ example: "I can help with that. Please verify your identity.",
+ },
+ {
+ name: "contexts",
+ type: "string[]",
+ required: false,
+ description: "Retrieved context document texts used by the LLM.",
+ example: '["User password reset procedure document."]',
+ },
+ {
+ name: "eval_types",
+ type: "string[]",
+ required: false,
+ description: "Scorers to execute. Can be toxicity, hallucination, bias, pii.",
+ example: '["toxicity", "pii"]',
+ },
+ {
+ name: "threshold_score",
+ type: "number",
+ required: false,
+ description: "Minimum score required to trigger validation flags. Defaults to 0.5.",
+ example: "0.5",
+ },
+ {
+ name: "store_results",
+ type: "boolean",
+ required: false,
+ description: "Persist the evaluation metrics run results to ClickHouse. Defaults to true.",
+ example: "true",
+ },
+ {
+ name: "run_id",
+ type: "string",
+ required: false,
+ description: "Optional external execution or batch tracking ID.",
+ example: "run-998877",
+ },
+ {
+ name: "metadata",
+ type: "object",
+ required: false,
+ description: "Custom metadata key-value properties dictionary (max 20 entries).",
+ },
+ {
+ name: "attributes",
+ type: "object",
+ required: false,
+ description: "Custom payload attributes dictionary.",
+ },
+ ])
+ );
}
if (endpointId === "create-prompt") {
- return [
- {
- name: "name",
- type: "string",
- required: true,
- description: "Unique prompt identification name.",
- example: "rag-generation-prompt",
- },
- {
- name: "prompt",
- type: "string",
- required: true,
- description: "Prompt template string with support for variable placeholders.",
- example: "Answer the query: {{query}} using context: {{context}}",
- },
- {
- name: "version",
- type: "string",
- required: false,
- description: "Optional semantic version for this prompt release.",
- example: "1.0.0",
- },
- {
- name: "status",
- type: "string",
- required: false,
- description: "Release status of the prompt.",
- allowedValues: ["active", "draft", "retired"],
- example: "active",
- },
- {
- name: "tags",
- type: "string[]",
- required: false,
- description: "Labels to categorize the prompt.",
- example: '["production", "rag"]',
- },
- {
- name: "metaProperties",
- type: "object",
- required: false,
- description: "Arbitrary key-value metadata properties dict.",
- },
- ];
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Unique prompt identification name.",
+ example: "rag-generation-prompt",
+ },
+ {
+ name: "prompt",
+ type: "string",
+ required: true,
+ description: "Prompt template string with support for variable placeholders.",
+ example: "Answer the query: {{query}} using context: {{context}}",
+ },
+ {
+ name: "version",
+ type: "string",
+ required: false,
+ description: "Optional semantic version for this prompt release.",
+ example: "1.0.0",
+ },
+ {
+ name: "status",
+ type: "string",
+ required: false,
+ description: "Release status of the prompt.",
+ allowedValues: ["active", "draft", "retired"],
+ example: "active",
+ },
+ {
+ name: "tags",
+ type: "string[]",
+ required: false,
+ description: "Labels to categorize the prompt.",
+ example: '["production", "rag"]',
+ },
+ {
+ name: "metaProperties",
+ type: "object",
+ required: false,
+ description: "Arbitrary key-value metadata properties dict.",
+ },
+ ])
+ );
}
if (endpointId === "get-prompt") {
- return [
- {
- name: "name",
- type: "string",
- required: true,
- description: "Prompt identifier name to retrieve detail configurations for.",
- example: "summarize-prompt",
- },
- ];
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Prompt identifier name to retrieve detail configurations for.",
+ example: "summarize-prompt",
+ },
+ ])
+ );
}
if (endpointId === "upsert-secret") {
- return [
- {
- name: "key",
- type: "string",
- required: true,
- description: "Secret key name stored in the vault.",
- example: "OPENAI_API_KEY",
- },
- {
- name: "value",
- type: "string",
- required: true,
- description: "Unencrypted credentials value that will be encrypted on write.",
- example: "sk-proj-...",
- },
- {
- name: "tags",
- type: "string[]",
- required: false,
- description: "Secret classification labels.",
- example: '["production"]',
- },
- ];
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "key",
+ type: "string",
+ required: true,
+ description: "Secret key name stored in the vault.",
+ example: "OPENAI_API_KEY",
+ },
+ {
+ name: "value",
+ type: "string",
+ required: true,
+ description: "Unencrypted credentials value that will be encrypted on write.",
+ example: "sk-proj-...",
+ },
+ {
+ name: "tags",
+ type: "string[]",
+ required: false,
+ description: "Secret classification labels.",
+ example: '["production"]',
+ },
+ ])
+ );
}
if (
@@ -395,18 +516,90 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
endpointId === "get-trace-detail" ||
endpointId === "get-span-hierarchy"
) {
- return [
- {
+ return withContextHeaders([
+ asPathParam({
name: "id",
type: "string",
required: true,
- description: "Path parameter. Span ID, Trace ID, or Anchor Span ID to fetch.",
+ description: "Span ID, Trace ID, or Anchor Span ID to fetch.",
example: "557a2bd43ff129ad",
- },
- ];
+ }),
+ ]);
}
- return [];
+ if (
+ endpointId === "get-ai-analysis" ||
+ endpointId === "run-ai-analysis"
+ ) {
+ return withContextHeaders([
+ asPathParam({
+ name: "spanId",
+ type: "string",
+ required: true,
+ description: "Anchor span ID used to resolve the analysis target.",
+ example: "557a2bd43ff129ad",
+ }),
+ asQueryParam({
+ name: "scope",
+ type: "string",
+ required: false,
+ description: "Analyze the full hierarchy or only the given span.",
+ allowedValues: ["trace", "span"],
+ example: "trace",
+ }),
+ asQueryParam({
+ name: "traceId",
+ type: "string",
+ required: false,
+ description: "Optional Trace ID to disambiguate hierarchy lookup.",
+ example: "a1b2c3d4e5f6g7h8",
+ }),
+ ]);
+ }
+
+ if (endpointId === "send-otter-message") {
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "conversationId",
+ type: "string",
+ required: true,
+ description: "Conversation ID returned from POST /api/chat/conversation.",
+ example: "conv-1",
+ },
+ {
+ name: "content",
+ type: "string",
+ required: true,
+ description: "User message text for Ask Otter.",
+ example: "Analyze the slowest traces from the last 24 hours",
+ },
+ ])
+ );
+ }
+
+ if (endpointId === "execute-otter-sql") {
+ return withContextHeaders(
+ asBodyParams([
+ {
+ name: "query",
+ type: "string",
+ required: true,
+ description: "Validated read-only SQL to run against the intelligence ClickHouse connector.",
+ example: "SELECT SpanName, Duration FROM otel_traces LIMIT 10",
+ },
+ {
+ name: "messageId",
+ type: "string",
+ required: false,
+ description: "Optional chat message ID to attach query results to.",
+ example: "msg-1",
+ },
+ ])
+ );
+ }
+
+ return contextHeaderDocs;
};
const getEndpointGroup = (endpoint: ApiEndpoint): string => {
@@ -414,6 +607,12 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
if (path.startsWith("/api/telemetry") || path.startsWith("/api/metrics")) {
return "Telemetry";
}
+ if (path.startsWith("/api/chat/improvement")) {
+ return "AI Analysis";
+ }
+ if (path.startsWith("/api/chat")) {
+ return "Ask Otter";
+ }
if (path.startsWith("/api/prompt")) {
return "Prompt Hub";
}
@@ -437,6 +636,8 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
const groups = [
"Telemetry",
+ "AI Analysis",
+ "Ask Otter",
"Prompt Hub",
"Secret Vault",
"Rule Engine",
@@ -447,6 +648,8 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({
"Telemetry": true,
+ "AI Analysis": true,
+ "Ask Otter": true,
"Prompt Hub": true,
"Secret Vault": true,
"Rule Engine": true,
@@ -489,6 +692,10 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
<h3 className="font-semibold text-stone-900 dark:text-stone-100">{messages.INTERACTIVE_API_REFERENCE}</h3>
<span className="text-xs text-stone-500 dark:text-stone-400 ml-auto">
{messages.OPENAPI_SPEC_BEARER_AUTH}
+ {" · "}
+ <span className="text-stone-500 dark:text-stone-400">
+ {messages.OPENAPI_SPEC_CONTEXT_HEADERS_HINT}
+ </span>
</span>
</div>
@@ -594,6 +801,7 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
<thead>
<tr className="border-b border-stone-200 dark:border-stone-800 text-stone-500 font-medium">
<th className="pb-2 pr-4 font-mono text-[10px]">Parameter</th>
+ <th className="pb-2 pr-4 font-mono text-[10px]">In</th>
<th className="pb-2 pr-4 font-mono text-[10px]">Type</th>
<th className="pb-2 pr-4 font-mono text-[10px]">Required</th>
<th className="pb-2">Description</th>
@@ -601,10 +809,18 @@ export default function ApiReference({ userApiKey }: ApiReferenceProps) {
</thead>
<tbody>
{getParameterDocs(selectedEndpoint.id).map((doc) => (
- <tr key={doc.name} className="border-b border-stone-100 dark:border-stone-900/40 last:border-0 hover:bg-stone-50/50 dark:hover:bg-stone-900/20">
+ <tr key={`${doc.location}:${doc.name}`} className="border-b border-stone-100 dark:border-stone-900/40 last:border-0 hover:bg-stone-50/50 dark:hover:bg-stone-900/20">
<td className="py-2.5 pr-4 font-mono text-[11px] font-semibold text-stone-800 dark:text-stone-200">
{doc.name}
</td>
+ <td className="py-2.5 pr-4">
+ <Badge
+ variant="outline"
+ className="text-[9px] px-1.5 py-0 font-semibold border-stone-200 dark:border-stone-700 text-stone-600 dark:text-stone-300"
+ >
+ {PARAMETER_LOCATION_LABEL[doc.location]}
+ </Badge>
+ </td>
<td className="py-2.5 pr-4 font-mono text-[11px] text-stone-500">
{doc.type}
</td>
diff --git a/src/client/src/components/(playground)/context/header.tsx b/src/client/src/components/(playground)/context/header.tsx
index bf6e1f91..fbd12d72 100644
--- a/src/client/src/components/(playground)/context/header.tsx
+++ b/src/client/src/components/(playground)/context/header.tsx
@@ -1,4 +1,5 @@
"use client";
+import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { useRootStore } from "@/store";
import { getPingStatus } from "@/selectors/database-config";
@@ -12,11 +13,13 @@ export default function ContextHeader({
title,
extraButtons,
createNew = true,
+ leading,
}: {
className?: string;
title?: string;
extraButtons?: JSX.Element;
createNew?: boolean;
+ leading?: ReactNode;
}) {
const pingStatus = useRootStore(getPingStatus);
const m = getMessage();
@@ -32,5 +35,19 @@ export default function ContextHeader({
</Button>
) : null;
- return <FeaturePageHeader eyebrow={getMessage().SIDEBAR_DEVELOP} title={pageHeaderTitle} icon={<BookOpen className="h-4 w-4" />} tone="border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-900/70 dark:bg-blue-950/40 dark:text-blue-300" actions={<div className={className}>{extraButtons}{actions}</div>} />;
+ return (
+ <FeaturePageHeader
+ eyebrow={getMessage().SIDEBAR_DEVELOP}
+ title={pageHeaderTitle}
+ icon={<BookOpen className="h-4 w-4" />}
+ tone="border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-900/70 dark:bg-blue-950/40 dark:text-blue-300"
+ leading={leading}
+ actions={
+ <div className={className}>
+ {extraButtons}
+ {actions}
+ </div>
+ }
+ />
+ );
}
diff --git a/src/client/src/components/(playground)/header-project-switch.tsx b/src/client/src/components/(playground)/header-project-switch.tsx
index 1ba56ca3..2a22c50f 100644
--- a/src/client/src/components/(playground)/header-project-switch.tsx
+++ b/src/client/src/components/(playground)/header-project-switch.tsx
@@ -75,7 +75,7 @@ export default function HeaderProjectSwitch() {
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={() => {
- router.push("/organisation?tab=projects");
+ router.push("/organisation/projects");
}}
>
{messages.MANAGE_PROJECTS}
diff --git a/src/client/src/components/(playground)/observability/agent-loop-bar.tsx b/src/client/src/components/(playground)/observability/agent-loop-bar.tsx
index a348b541..70a56796 100644
--- a/src/client/src/components/(playground)/observability/agent-loop-bar.tsx
+++ b/src/client/src/components/(playground)/observability/agent-loop-bar.tsx
@@ -28,7 +28,7 @@ export default function AgentLoopBar() {
const pingStatus = useRootStore(getPingStatus);
const environment = useRootStore(getCurrentProjectEnvironment);
const updateFilter = useRootStore(getUpdateFilter);
- const { data, isFetched, isLoading, fireRequest } = useFetchWrapper();
+ const { data, isFetched, isLoading, fireRequest, reset } = useFetchWrapper();
const selected = Boolean(filter.selectedConfig.agentLoop);
const fetchData = useCallback(async () => {
@@ -43,6 +43,12 @@ export default function AgentLoopBar() {
});
}, [environment, filter, fireRequest]);
+ useEffect(() => {
+ // Drop previous environment's counts — do not keep production chips
+ // when the next environment's request fails or returns empty.
+ reset();
+ }, [environment, reset]);
+
useEffect(() => {
if (
filter.timeLimit.start &&
@@ -51,7 +57,7 @@ export default function AgentLoopBar() {
) {
fetchData();
}
- }, [filter, fetchData, pingStatus]);
+ }, [filter, fetchData, pingStatus, environment]);
const row = (data || {}) as AgentLoopRow;
if (row.unsupported) return null;
diff --git a/src/client/src/components/(playground)/observability/detail-shell.tsx b/src/client/src/components/(playground)/observability/detail-shell.tsx
index 78f51b2a..d70b9416 100644
--- a/src/client/src/components/(playground)/observability/detail-shell.tsx
+++ b/src/client/src/components/(playground)/observability/detail-shell.tsx
@@ -1,5 +1,3 @@
-"use client";
-
export default function DetailShell({
title,
leadingActions,
@@ -17,21 +15,29 @@ export default function DetailShell({
}) {
return (
<div className="flex flex-col w-full h-full overflow-auto rounded-md border border-stone-200 dark:border-stone-800 bg-white dark:bg-stone-950">
- <div className={`sticky top-0 z-10 flex flex-col border-b border-stone-200 bg-white/95 shadow-sm shadow-stone-200/40 backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-black/20 ${compact ? "gap-2 px-3 py-2" : "gap-3 px-4 py-3"}`}>
- <div className={`flex flex-col md:flex-row md:items-start md:justify-between ${compact ? "gap-2" : "gap-3"}`}>
+ <div
+ className={`sticky top-0 z-10 flex flex-col border-b border-stone-200 bg-white/95 shadow-sm shadow-stone-200/40 backdrop-blur dark:border-stone-800 dark:bg-stone-950/95 dark:shadow-black/20 ${compact ? "gap-2 px-3 py-2" : "gap-3 px-4 py-3"}`}
+ >
+ <div
+ className={`flex flex-col md:flex-row md:items-start md:justify-between ${compact ? "gap-2" : "gap-3"}`}
+ >
<div className="flex min-w-0 grow items-start gap-2">
{leadingActions && <div className="shrink-0">{leadingActions}</div>}
<div className="min-w-0 grow">
- <h1 className={`truncate font-semibold text-stone-950 dark:text-stone-50 ${compact ? "text-base md:text-lg" : "text-lg md:text-xl"}`}>
+ <h1
+ className={`truncate font-semibold text-stone-950 dark:text-stone-50 ${compact ? "text-base md:text-lg" : "text-lg md:text-xl"}`}
+ >
{title}
- </h1>
+ </h1>
</div>
</div>
{actions && <div className="shrink-0">{actions}</div>}
</div>
{headerMeta && <div>{headerMeta}</div>}
</div>
- <div className={`flex flex-col ${compact ? "gap-2 p-2" : "gap-4 p-4"}`}>{children}</div>
+ <div className={`flex flex-col ${compact ? "gap-2 p-2" : "gap-4 p-4"}`}>
+ {children}
+ </div>
</div>
);
}
diff --git a/src/client/src/components/(playground)/observability/generation-health-bar.tsx b/src/client/src/components/(playground)/observability/generation-health-bar.tsx
index 0cfac3d8..14789018 100644
--- a/src/client/src/components/(playground)/observability/generation-health-bar.tsx
+++ b/src/client/src/components/(playground)/observability/generation-health-bar.tsx
@@ -42,7 +42,7 @@ export default function GenerationHealthBar() {
const pingStatus = useRootStore(getPingStatus);
const environment = useRootStore(getCurrentProjectEnvironment);
const updateFilter = useRootStore(getUpdateFilter);
- const { data, isFetched, isLoading, fireRequest } = useFetchWrapper();
+ const { data, isFetched, isLoading, fireRequest, reset } = useFetchWrapper();
const selected = filter.selectedConfig.generationHealth || [];
const fetchData = useCallback(async () => {
@@ -57,6 +57,12 @@ export default function GenerationHealthBar() {
});
}, [environment, filter, fireRequest]);
+ useEffect(() => {
+ // Drop previous environment's counts — do not keep production chips
+ // when the next environment's request fails or returns empty.
+ reset();
+ }, [environment, reset]);
+
useEffect(() => {
if (
filter.timeLimit.start &&
@@ -65,7 +71,7 @@ export default function GenerationHealthBar() {
) {
fetchData();
}
- }, [filter, fetchData, pingStatus]);
+ }, [filter, fetchData, pingStatus, environment]);
const row = (data || {}) as GenerationHealthRow;
if (row.unsupported) return null;
diff --git a/src/client/src/components/(playground)/openground/header.tsx b/src/client/src/components/(playground)/openground/header.tsx
index 5d62b4ac..13d00ef2 100644
--- a/src/client/src/components/(playground)/openground/header.tsx
+++ b/src/client/src/components/(playground)/openground/header.tsx
@@ -26,7 +26,7 @@ export function OpengroundActions({
<div className={className}>
<Button variant="outline" size="sm" className="h-8" onClick={() => router.back()}>
<ArrowLeftIcon className="mr-1.5 size-3.5" />
- {getMessage().BACK}
+ {getMessage().BACK}
</Button>
{extraButton}
</div>
diff --git a/src/client/src/components/(playground)/openlit-context-ids.tsx b/src/client/src/components/(playground)/openlit-context-ids.tsx
new file mode 100644
index 00000000..d31bd535
--- /dev/null
+++ b/src/client/src/components/(playground)/openlit-context-ids.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import { Check, Copy } from "lucide-react";
+import { toast } from "sonner";
+import getMessage from "@/constants/messages";
+import { getCurrentOrganisation } from "@/selectors/organisation";
+import {
+ getCurrentProject,
+ getCurrentProjectEnvironment,
+} from "@/selectors/project";
+import { useRootStore } from "@/store";
+
+type ContextItem = {
+ label: string;
+ value?: string | null;
+};
+
+function truncateValue(value: string) {
+ if (value.length <= 22) return value;
+ return `${value.slice(0, 10)}…${value.slice(-6)}`;
+}
+
+function CopyableContextChip({ label, value }: ContextItem) {
+ const messages = getMessage();
+ const [copied, setCopied] = useState(false);
+
+ const onCopy = useCallback(() => {
+ if (!value) return;
+ void navigator.clipboard.writeText(value).then(
+ () => {
+ toast.success(messages.COPIED_TO_CLIPBOARD);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ },
+ () => undefined
+ );
+ }, [messages.COPIED_TO_CLIPBOARD, value]);
+
+ if (!value) return null;
+
+ return (
+ <span className="inline-flex max-w-full items-center gap-1 rounded-md border border-stone-200 bg-stone-50 px-1.5 py-0.5 text-[11px] text-stone-600 dark:border-stone-800 dark:bg-stone-900 dark:text-stone-300">
+ <span className="shrink-0 font-medium text-stone-500 dark:text-stone-400">
+ {label}
+ </span>
+ <span className="min-w-0 truncate font-mono text-stone-800 dark:text-stone-100" title={value}>
+ {truncateValue(value)}
+ </span>
+ <button
+ type="button"
+ className="shrink-0 rounded p-0.5 text-stone-400 hover:bg-stone-200/80 hover:text-stone-700 dark:hover:bg-stone-800 dark:hover:text-stone-200"
+ title={messages.COPY_CONTEXT_VALUE(label)}
+ aria-label={messages.COPY_CONTEXT_VALUE(label)}
+ onClick={onCopy}
+ >
+ {copied ? (
+ <Check className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
+ ) : (
+ <Copy className="h-3 w-3" />
+ )}
+ </button>
+ </span>
+ );
+}
+
+/**
+ * Compact, copyable Organisation → Project → Environment IDs for API clients
+ * (signal-routing headers). Hide when none of the values are available.
+ */
+export default function OpenLitContextIds({
+ className = "",
+}: {
+ className?: string;
+}) {
+ const messages = getMessage();
+ const organisation = useRootStore(getCurrentOrganisation);
+ const project = useRootStore(getCurrentProject);
+ const environment = useRootStore(getCurrentProjectEnvironment);
+
+ const items: ContextItem[] = [
+ { label: messages.ORGANISATION_ID, value: organisation?.id },
+ { label: messages.PROJECT_ID, value: project?.id },
+ { label: messages.ENVIRONMENT_NAME, value: environment || undefined },
+ ].filter((item) => Boolean(item.value));
+
+ if (items.length === 0) return null;
+
+ return (
+ <div
+ className={`flex flex-wrap items-center gap-1.5 ${className}`}
+ data-testid="openlit-context-ids"
+ >
+ {items.map((item) => (
+ <CopyableContextChip key={item.label} {...item} />
+ ))}
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/organisation/organisation-page.tsx b/src/client/src/components/(playground)/organisation/organisation-page.tsx
index 169393c3..b6129a33 100644
--- a/src/client/src/components/(playground)/organisation/organisation-page.tsx
+++ b/src/client/src/components/(playground)/organisation/organisation-page.tsx
@@ -3,7 +3,7 @@
import { useState, useEffect } from "react";
import { usePostHog } from "posthog-js/react";
import { CLIENT_EVENTS } from "@/constants/events";
-import { useRouter, useSearchParams } from "next/navigation";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -91,6 +91,7 @@ import {
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import CreateOrganisationDialog from "@/components/(playground)/sidebar/create-organisation-dialog";
+import OpenLitContextIds from "@/components/(playground)/openlit-context-ids";
import { cn } from "@/lib/utils";
import getMessage from "@/constants/messages";
import { escapeEmailForDisplay } from "@/utils/string";
@@ -124,6 +125,7 @@ interface Project {
export default function OrganisationSettingsPage() {
const posthog = usePostHog();
const router = useRouter();
+ const pathname = usePathname();
const searchParams = useSearchParams();
const messages = getMessage();
const currentOrg = useRootStore(getCurrentOrganisation);
@@ -147,7 +149,10 @@ export default function OrganisationSettingsPage() {
const [projectName, setProjectName] = useState("");
const [isProjectsLoading, setIsProjectsLoading] = useState(false);
const [isCreatingProject, setIsCreatingProject] = useState(false);
- const requestedTab = searchParams.get("tab") || "details";
+ const isProjectsRoute = pathname === "/organisation/projects";
+ const requestedTab = isProjectsRoute
+ ? "projects"
+ : searchParams.get("tab") || "details";
const availableTabs = orgPendingInvites.length > 0
? ["details", "projects", "members", "pending"]
: ["details", "projects", "members"];
@@ -155,14 +160,20 @@ export default function OrganisationSettingsPage() {
? requestedTab
: "details";
const handleTabChange = (tab: string) => {
+ if (tab === "projects") {
+ router.replace("/organisation/projects", { scroll: false });
+ return;
+ }
+
const params = new URLSearchParams(searchParams.toString());
- if (tab === "details") {
- params.delete("tab");
- } else {
+ params.delete("tab");
+ if (tab !== "details") {
params.set("tab", tab);
}
const query = params.toString();
- router.replace(query ? `/organisation?${query}` : "/organisation", { scroll: false });
+ router.replace(query ? `/organisation?${query}` : "/organisation", {
+ scroll: false,
+ });
};
const isCreator = currentOrg?.createdByUserId === currentUserId;
@@ -425,7 +436,8 @@ export default function OrganisationSettingsPage() {
</div>
</section>
- <div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
+ <div className="min-h-0 flex-1 overflow-y-auto p-4">
+ <OpenLitContextIds />
{pendingInvitations.length > 0 && (
<Card className="border-primary/20 bg-primary/5 dark:border-primary/30 dark:bg-primary/10">
<CardHeader className="pb-3">
@@ -466,11 +478,11 @@ export default function OrganisationSettingsPage() {
)}
{currentOrg && (
- <Tabs value={selectedTab} onValueChange={handleTabChange} className="w-full">
+ <Tabs value={selectedTab} onValueChange={handleTabChange} className="w-full mt-4">
<TabsContent value="details" className="space-y-4 mt-0">
{hasAdminPermissions ? (
- <div className="space-y-3 py-4">
+ <div className="space-y-3">
<div className="space-y-1.5">
<Label htmlFor="org-name" className="text-sm">
{messages.ORGANISATION_NAME}
@@ -612,7 +624,7 @@ export default function OrganisationSettingsPage() {
)}
</TabsContent>
- <TabsContent value="projects" className="mt-0 p-0 pt-2">
+ <TabsContent value="projects" className="mt-0 p-0">
<div className="mb-3 rounded-md border border-stone-200 bg-stone-50/60 p-3 dark:border-stone-800 dark:bg-stone-900/40">
<div className="mb-3 flex items-start justify-between gap-3">
<div>
@@ -739,7 +751,7 @@ export default function OrganisationSettingsPage() {
)}
</TabsContent>
- <TabsContent value="members" className="mt-0 p-0 pt-2">
+ <TabsContent value="members" className="mt-0 p-0">
{hasAdminPermissions ? (
<div className="space-y-1.5 mb-3">
<Label htmlFor="invite-email" className="text-sm">
@@ -915,7 +927,7 @@ export default function OrganisationSettingsPage() {
</TabsContent>
{orgPendingInvites.length > 0 && (
- <TabsContent value="pending" className="mt-0 p-4">
+ <TabsContent value="pending" className="mt-0 p-0">
<Table>
<TableHeader className="bg-stone-200/[0.5] text-stone-500 dark:bg-stone-800 dark:text-stone-400">
<TableRow className="text-xs">
diff --git a/src/client/src/components/(playground)/organisation/project-connectors-page.tsx b/src/client/src/components/(playground)/organisation/project-connectors-page.tsx
index 891b7225..d359e754 100644
--- a/src/client/src/components/(playground)/organisation/project-connectors-page.tsx
+++ b/src/client/src/components/(playground)/organisation/project-connectors-page.tsx
@@ -3,6 +3,7 @@
import { useEffect, useMemo } from "react";
import { Layers } from "lucide-react";
import DataSourcesPage from "@/components/(playground)/telemetry-source/data-sources-page";
+import OpenLitContextIds from "@/components/(playground)/openlit-context-ids";
import ProjectPageHeader from "./project-page-header";
import getMessage from "@/constants/messages";
import FeatureAccess from "@/components/rbac/feature-access";
@@ -37,10 +38,11 @@ export default function ProjectConnectorsPage({ projectId }: { projectId?: strin
<ProjectPageHeader project={project} />
<FeatureAccess access="connectors.read" requireProject>
<div className="flex min-h-0 w-full flex-col gap-4 p-4">
+ <OpenLitContextIds />
<section className="border border-primary/20 bg-primary/[0.04] p-4 dark:border-primary/30 dark:bg-primary/[0.08]">
<div className="flex items-start gap-3">
<Layers className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
- <div>
+ <div className="min-w-0 flex-1">
<h2 className="text-sm font-semibold text-stone-950 dark:text-stone-50">{messages.PROJECT_ENVIRONMENTS}: {environment}</h2>
<p className="mt-1 text-xs leading-5 text-muted-foreground">{messages.PROJECT_ENVIRONMENTS_DESCRIPTION}</p>
</div>
diff --git a/src/client/src/components/(playground)/organisation/project-page-header.tsx b/src/client/src/components/(playground)/organisation/project-page-header.tsx
index efd29879..00c1567e 100644
--- a/src/client/src/components/(playground)/organisation/project-page-header.tsx
+++ b/src/client/src/components/(playground)/organisation/project-page-header.tsx
@@ -52,7 +52,7 @@ export default function ProjectPageHeader({
<Button asChild size="sm" variant={pathname?.endsWith(`/project/${project?.id}`) && searchParams?.get("tab") !== "access" ? "default" : "outline"} className="h-8 gap-1.5 text-xs">
<Link href={`/organisation/project/${project?.id || ""}`}><FolderKanban className="h-3.5 w-3.5" />{messages.PROJECT_OVERVIEW}</Link>
</Button>
- <Button asChild size="sm" variant={pathname?.endsWith("/connectors") ? "default" : "outline"} className="h-8 gap-1.5 text-xs">
+ <Button asChild size="sm" variant={pathname?.includes(`/project/${project?.id}/environments`) || pathname?.includes(`/project/${project?.id}/connectors`) ? "default" : "outline"} className="h-8 gap-1.5 text-xs">
<Link href={`/organisation/project/${project?.id || ""}/environments`}><Settings2 className="h-3.5 w-3.5" />{messages.PROJECT_ENVIRONMENTS}</Link>
</Button>
</div>
diff --git a/src/client/src/components/(playground)/organisation/project-page.tsx b/src/client/src/components/(playground)/organisation/project-page.tsx
index 5167e0f1..aeecb915 100644
--- a/src/client/src/components/(playground)/organisation/project-page.tsx
+++ b/src/client/src/components/(playground)/organisation/project-page.tsx
@@ -1,7 +1,10 @@
"use client";
import { useEffect, useMemo, useState } from "react";
+import { Copy } from "lucide-react";
+import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
+import OpenLitContextIds from "@/components/(playground)/openlit-context-ids";
import ProjectPageHeader from "./project-page-header";
import { getCurrentOrganisation } from "@/selectors/organisation";
import { getCurrentProject, getProjectList } from "@/selectors/project";
@@ -16,16 +19,42 @@ export default function OrganisationProjectPage({ projectId }: { projectId: stri
const currentProject = useRootStore(getCurrentProject);
const [projectEnvironments, setProjectEnvironments] = useState<string[]>([]);
const project = useMemo(
- () => projects.find((item) => item.id === projectId) || (currentProject?.id === projectId ? currentProject : { id: projectId, organisationId: "", name: projectId, slug: "-", isDefault: false, isCurrent: false, createdAt: "" }),
+ () =>
+ projects.find((item) => item.id === projectId) ||
+ (currentProject?.id === projectId
+ ? currentProject
+ : {
+ id: projectId,
+ organisationId: "",
+ name: projectId,
+ slug: "-",
+ isDefault: false,
+ isCurrent: false,
+ createdAt: "",
+ }),
[currentProject, projectId, projects]
);
useEffect(() => {
if (currentOrg?.id) {
fetchProjectList(currentOrg.id);
- fetch("/api/project/environment").then((response) => response.ok ? response.json() : { environments: [] }).then((body) => {
- setProjectEnvironments(Array.from(new Set(["production", ...(body.environments || []).map((item: { name: string }) => item.name)])));
- }).catch(() => undefined);
+ fetch("/api/project/environment")
+ .then((response) =>
+ response.ok ? response.json() : { environments: [] }
+ )
+ .then((body) => {
+ setProjectEnvironments(
+ Array.from(
+ new Set([
+ "production",
+ ...(body.environments || []).map(
+ (item: { name: string }) => item.name
+ ),
+ ])
+ )
+ );
+ })
+ .catch(() => undefined);
}
}, [currentOrg?.id]);
@@ -40,20 +69,19 @@ export default function OrganisationProjectPage({ projectId }: { projectId: stri
new Date(project.createdAt)
)
: "-";
- const environments = Array.from(
- new Set([
- ...projectEnvironments,
- ])
- );
+ const environments = Array.from(new Set([...projectEnvironments]));
return (
<div className="flex h-full w-full flex-col overflow-auto text-stone-700 dark:text-stone-300">
<ProjectPageHeader project={project} />
<main className="flex w-full flex-col gap-4 p-4">
- <section className="border border-stone-200 bg-white p-5 dark:border-stone-800 dark:bg-stone-950">
+ <OpenLitContextIds />
+ <section className="border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">
<div className="flex flex-col gap-3 border-b border-stone-200 pb-4 dark:border-stone-800 md:flex-row md:items-start md:justify-between">
<div>
- <p className="text-xs uppercase tracking-wide text-muted-foreground">{messages.PROJECT_DETAILS}</p>
+ <p className="text-xs uppercase tracking-wide text-muted-foreground">
+ {messages.PROJECT_DETAILS}
+ </p>
<h2 className="mt-1 text-lg font-semibold text-stone-950 dark:text-stone-50">
{project?.name || messages.LOADING_PROJECT}
</h2>
@@ -63,41 +91,119 @@ export default function OrganisationProjectPage({ projectId }: { projectId: stri
</div>
<div className="flex flex-wrap gap-2">
{project?.isCurrent ? <Badge>{messages.CURRENT}</Badge> : null}
- {project?.isDefault ? <Badge variant="outline">{messages.DEFAULT_PROJECT}</Badge> : null}
+ {project?.isDefault ? (
+ <Badge variant="outline">{messages.DEFAULT_PROJECT}</Badge>
+ ) : null}
</div>
</div>
<div className="mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<Detail label={messages.PROJECT_NAME} value={project?.name || "-"} />
<Detail label={messages.SLUG} value={project?.slug || "-"} mono />
- <Detail label={messages.PROJECT_ENVIRONMENT} value={environments.length ? environments.join(", ") : "production"} />
+ <Detail
+ label={messages.PROJECT_ENVIRONMENT}
+ value={
+ environments.length ? environments.join(", ") : "production"
+ }
+ />
<Detail label={messages.CREATED_AT} value={createdAt} />
</div>
</section>
- <section className="grid gap-4 md:grid-cols-2">
- <InfoCard label={messages.PROJECT_ID} value={project?.id || "-"} mono />
- <InfoCard label={messages.PROJECT_CONNECTION_COUNT} value={`${environments.length}`} />
+ <section className="grid gap-4 md:grid-cols-3">
+ <CopyableInfoCard
+ label={messages.ORGANISATION_ID}
+ value={currentOrg?.id || ""}
+ />
+ <CopyableInfoCard
+ label={messages.PROJECT_ID}
+ value={project?.id || ""}
+ />
+ <InfoCard
+ label={messages.PROJECT_CONNECTION_COUNT}
+ value={`${environments.length}`}
+ />
</section>
</main>
</div>
);
}
-function Detail({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
+function Detail({
+ label,
+ value,
+ mono = false,
+}: {
+ label: string;
+ value: string;
+ mono?: boolean;
+}) {
return (
<div className="rounded-md border border-stone-200 bg-stone-50 p-3 dark:border-stone-800 dark:bg-stone-900/60">
- <p className="text-[11px] uppercase tracking-wide text-muted-foreground">{label}</p>
- <p className={`mt-1 truncate text-sm font-medium text-stone-950 dark:text-stone-50 ${mono ? "font-mono text-xs" : ""}`}>{value}</p>
+ <p className="text-[11px] uppercase tracking-wide text-muted-foreground">
+ {label}
+ </p>
+ <p
+ className={`mt-1 truncate text-sm font-medium text-stone-950 dark:text-stone-50 ${mono ? "font-mono text-xs" : ""}`}
+ >
+ {value}
+ </p>
</div>
);
}
-function InfoCard({ label, value, mono = false }: { label: string; value: string; mono?: boolean }) {
+function InfoCard({
+ label,
+ value,
+ mono = false,
+}: {
+ label: string;
+ value: string;
+ mono?: boolean;
+}) {
+ return (
+ <div className="border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">
+ <p className="text-xs text-muted-foreground">{label}</p>
+ <p
+ className={`mt-2 truncate text-sm text-stone-950 dark:text-stone-50 ${mono ? "font-mono text-xs" : "font-medium"}`}
+ >
+ {value}
+ </p>
+ </div>
+ );
+}
+
+function CopyableInfoCard({ label, value }: { label: string; value: string }) {
+ const messages = getMessage();
+ if (!value) {
+ return <InfoCard label={label} value="-" mono />;
+ }
+
return (
<div className="border border-stone-200 bg-white p-4 dark:border-stone-800 dark:bg-stone-950">
<p className="text-xs text-muted-foreground">{label}</p>
- <p className={`mt-2 truncate text-sm text-stone-950 dark:text-stone-50 ${mono ? "font-mono text-xs" : "font-medium"}`}>{value}</p>
+ <div className="mt-2 flex items-start gap-2">
+ <p
+ className="min-w-0 flex-1 break-all font-mono text-xs text-stone-950 dark:text-stone-50"
+ title={value}
+ >
+ {value}
+ </p>
+ <button
+ type="button"
+ className="shrink-0 rounded p-1 text-stone-400 hover:bg-stone-100 hover:text-stone-700 dark:hover:bg-stone-800 dark:hover:text-stone-200"
+ title={messages.COPY_CONTEXT_VALUE(label)}
+ aria-label={messages.COPY_CONTEXT_VALUE(label)}
+ onClick={() => {
+ void navigator.clipboard.writeText(value).then(
+ () => toast.success(messages.COPIED_TO_CLIPBOARD),
+ () => undefined
+ );
+ }}
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </button>
+ </div>
</div>
);
}
diff --git a/src/client/src/components/(playground)/sidebar/index.tsx b/src/client/src/components/(playground)/sidebar/index.tsx
index 8f767bad..3818384f 100644
--- a/src/client/src/components/(playground)/sidebar/index.tsx
+++ b/src/client/src/components/(playground)/sidebar/index.tsx
@@ -42,14 +42,17 @@ import { useSidebarLayout } from "../sidebar-layout-context";
const isActive = (pathname: string, item: SidebarActionItem, currentUrl: string) => {
if (!item.link) return false;
if (item.link.includes("?")) return currentUrl.startsWith(item.link);
- // Organisation owns `/organisation` except the Projects tab, which has its
- // own Settings entry (`/organisation?tab=projects`).
+ // Organisation owns `/organisation` except the Projects route, which has its
+ // own Settings entry (`/organisation/projects`).
if (item.link === "/organisation") {
return (
pathname.startsWith("/organisation") &&
- !currentUrl.includes("tab=projects")
+ !pathname.startsWith("/organisation/projects")
);
}
+ if (item.link === "/organisation/projects") {
+ return pathname.startsWith("/organisation/projects");
+ }
if (item.link === "/dashboards") return pathname.startsWith("/dashboards") || pathname.startsWith("/d/");
if (item.link === "/dashboard") return pathname.startsWith("/dashboard") && !pathname.startsWith("/dashboards");
return pathname.startsWith(item.link);
diff --git a/src/client/src/constants/api-reference.ts b/src/client/src/constants/api-reference.ts
index 3306f200..d157ad54 100644
--- a/src/client/src/constants/api-reference.ts
+++ b/src/client/src/constants/api-reference.ts
@@ -9,13 +9,33 @@ export interface ApiEndpoint {
curlExample: (apiKey: string) => string;
}
+/** Organisation → Project → Environment headers for signal-routed API-key calls. */
+export const OPENLIT_CONTEXT_CURL_HEADERS = ` -H "x-openlit-organisation-id: <organisation-id>" \\
+ -H "x-openlit-project-id: <project-id>" \\
+ -H "x-openlit-environment: production"`;
+
+/** Preferred SDK context: signal routing. Optional db-config header remains supported. */
+export const OPENLIT_SDK_CONTEXT_CURL_HEADERS = ` -H "x-openlit-organisation-id: <organisation-id>" \\
+ -H "x-openlit-project-id: <project-id>" \\
+ -H "x-openlit-environment: production"`;
+
+export function bearerAuthHeaders(apiKey: string) {
+ return ` -H "Authorization: Bearer ${apiKey}" \\
+${OPENLIT_CONTEXT_CURL_HEADERS}`;
+}
+
+export function bearerSdkAuthHeaders(apiKey: string) {
+ return ` -H "Authorization: Bearer ${apiKey}" \\
+${OPENLIT_SDK_CONTEXT_CURL_HEADERS}`;
+}
+
export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
{
id: "query-logs",
method: "POST",
path: "/api/telemetry/logs",
summary: "Query logs",
- description: "Retrieve a paginated list of telemetry logs matching the provided filters.",
+ description: "Retrieve a paginated list of telemetry logs matching the provided filters. Requires an OpenLIT API key plus organisation/project/environment headers for signal routing.",
requestBody: `{
"timeLimit": {
"type": "24H",
@@ -40,7 +60,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"total": 1
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/logs \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"timeLimit": {
@@ -72,7 +92,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
}
}`,
curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/logs/18446744073709551615 \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
},
{
id: "query-metrics",
@@ -105,7 +125,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"total": 1
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/metrics \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"timeLimit": {
@@ -140,7 +160,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"points": []
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/metrics/gen_ai.usage.total_tokens \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"timeLimit": {
@@ -156,25 +176,32 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
method: "GET",
path: "/api/prompt/get-compiled",
summary: "Fetch compiled prompt",
- description: "Fetch and compile a prompt by name with dynamic variable interpolation.",
- curlExample: (apiKey) => `curl -X GET "http://localhost:3000/api/prompt/get-compiled?name=summarize-prompt" \\
- -H "Authorization: Bearer ${apiKey}"`,
+ description:
+ "Fetch and compile a prompt by name. Prefer project/environment signal routing for the intelligence ClickHouse; API-key-only clients and optional x-openlit-database-config-id remain supported.",
+ curlExample: (apiKey) => `curl -X POST "http://localhost:3000/api/prompt/get-compiled" \\
+${bearerSdkAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{ "name": "summarize-prompt", "shouldCompile": true }'`,
},
{
id: "get-secrets",
method: "GET",
path: "/api/vault/get-secrets",
summary: "Fetch secrets from Vault",
- description: "Safely retrieve API keys or credentials stored in the OpenLIT Vault.",
- curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/vault/get-secrets \\
- -H "Authorization: Bearer ${apiKey}"`,
+ description:
+ "Retrieve Vault secrets. Prefer project/environment signal routing; API-key-only clients and optional x-openlit-database-config-id remain supported.",
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/vault/get-secrets \\
+${bearerSdkAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{ "key": "OPENAI_API_KEY" }'`,
},
{
id: "evaluate-rules",
method: "POST",
path: "/api/rule-engine/evaluate",
summary: "Evaluate rule engine config",
- description: "Evaluate rules (e.g. redaction, prompts, guardrails) against inputs.",
+ description:
+ "Evaluate rules against inputs. Prefer project/environment signal routing; API-key-only clients and optional x-openlit-database-config-id remain supported.",
requestBody: `{
"entity_type": "prompt",
"fields": {
@@ -186,7 +213,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"redactedText": "I need to reset my password, my email is [REDACTED]"
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/rule-engine/evaluate \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerSdkAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"entity_type": "prompt",
@@ -204,7 +231,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
requestBody: ``,
responseBody: `[]`,
curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/rule-engine/rules \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
},
{
id: "controller-poll",
@@ -224,7 +251,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"actions": []
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/controller/poll \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"instance_id": "controller-instance-abc",
@@ -271,7 +298,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"metadata": {}
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/evaluation/offline \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"prompt": "I need to reset my password, my email is [email protected]",
@@ -301,7 +328,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"success": true
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"name": "summarize-prompt",
@@ -325,7 +352,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"version": "1.0.0"
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt/get \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"name": "summarize-prompt"
@@ -340,7 +367,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
requestBody: ``,
responseBody: `[]`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt/get \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
},
{
id: "upsert-secret",
@@ -359,7 +386,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"tags": ["production"]
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/vault \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"key": "OPENAI_API_KEY",
@@ -372,7 +399,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
method: "POST",
path: "/api/telemetry/trace",
summary: "Query traces list",
- description: "Retrieve a paginated list of telemetry trace spans matching the provided filters. Pass `includeFilters=true` as a query parameter or `includeFilters: true` in the JSON body to retrieve inline pagination and dynamic filter metadata.",
+ description: "Retrieve a paginated list of telemetry trace spans matching the provided filters. Pass `includeFilters=true` as a query parameter or `includeFilters: true` in the JSON body to retrieve inline pagination and dynamic filter metadata. Requires an OpenLIT API key plus project/environment headers for signal routing.",
requestBody: `{
"timeLimit": {
"type": "24H",
@@ -411,7 +438,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
}
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/trace?includeFilters=true \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"timeLimit": {
@@ -466,7 +493,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
}
}`,
curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/telemetry/exception?includeFilters=true \\
- -H "Authorization: Bearer ${apiKey}" \\
+${bearerAuthHeaders(apiKey)} \\
-H "Content-Type: application/json" \\
-d '{
"timeLimit": {
@@ -489,7 +516,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"record": {}
}`,
curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/span/some-span-id \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
},
{
id: "get-trace-detail",
@@ -503,7 +530,7 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"record": {}
}`,
curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/trace/some-trace-id \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
},
{
id: "get-span-hierarchy",
@@ -517,6 +544,298 @@ export const API_REFERENCE_ENDPOINTS: ApiEndpoint[] = [
"record": {}
}`,
curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/telemetry/trace/span/some-span-id/heirarchy \\
- -H "Authorization: Bearer ${apiKey}"`,
+${bearerAuthHeaders(apiKey)}`,
+ },
+
+ {
+ id: "get-ai-analysis",
+ method: "GET",
+ path: "/api/chat/improvement/{spanId}",
+ summary: "Get AI Analysis runs",
+ description:
+ "Retrieve saved AI Analysis runs for a trace hierarchy (`scope=trace`) or a single span (`scope=span`). Requires an OpenLIT API key plus organisation/project/environment context headers for signal routing.",
+ responseBody: `{
+ "data": {
+ "rootSpanId": "557a2bd43ff129ad",
+ "runs": [
+ {
+ "id": "run-1",
+ "scope": "trace",
+ "summary": "Focused analysis completed across 6 dimension passes.",
+ "createdAt": "2026-09-02T12:00:00.000Z"
+ }
+ ]
+ }
+}`,
+ curlExample: (apiKey) => `curl -X GET "http://localhost:3000/api/chat/improvement/some-span-id?scope=trace&traceId=some-trace-id" \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "run-ai-analysis",
+ method: "POST",
+ path: "/api/chat/improvement/{spanId}",
+ summary: "Run AI Analysis",
+ description:
+ "Start a streaming AI Analysis for a trace or span. Requires an OpenLIT API key, Chat Settings, an intelligence ClickHouse connector, and organisation/project/environment context headers.",
+ responseBody: `progress events + completed dimension findings (text/plain stream)`,
+ curlExample: (apiKey) => `curl -X POST "http://localhost:3000/api/chat/improvement/some-span-id?scope=trace" \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "get-otter-config",
+ method: "GET",
+ path: "/api/chat/config",
+ summary: "Get Ask Otter config",
+ description: "Return the Ask Otter provider/model/Vault binding for the current organisation. Requires an OpenLIT API key plus organisation/project/environment context headers.",
+ responseBody: `{
+ "data": {
+ "provider": "openai",
+ "model": "gpt-4o",
+ "vaultId": "vault-secret-id",
+ "meta": "{}"
+ }
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/chat/config \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "upsert-otter-config",
+ method: "POST",
+ path: "/api/chat/config",
+ summary: "Upsert Ask Otter config",
+ description: "Save the AI provider, model, and Vault secret used by Ask Otter and AI Analysis.",
+ requestBody: `{
+ "provider": "openai",
+ "model": "gpt-4o",
+ "vaultId": "vault-secret-id",
+ "meta": "{}"
+}`,
+ responseBody: `{
+ "provider": "openai",
+ "model": "gpt-4o",
+ "vaultId": "vault-secret-id"
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/chat/config \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "provider": "openai",
+ "model": "gpt-4o",
+ "vaultId": "vault-secret-id"
+ }'`,
+ },
+ {
+ id: "list-otter-conversations",
+ method: "GET",
+ path: "/api/chat/conversation",
+ summary: "List Ask Otter conversations",
+ description: "List chat conversations for the current user.",
+ responseBody: `{
+ "data": [
+ {
+ "id": "conv-1",
+ "title": "Investigate high cost traces",
+ "provider": "openai",
+ "model": "gpt-4o",
+ "totalMessages": 4,
+ "totalCost": 0.012
+ }
+ ]
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/chat/conversation \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "create-otter-conversation",
+ method: "POST",
+ path: "/api/chat/conversation",
+ summary: "Create Ask Otter conversation",
+ description: "Create a new Ask Otter conversation with optional title, provider, and model.",
+ requestBody: `{
+ "title": "Investigate high cost traces",
+ "provider": "openai",
+ "model": "gpt-4o"
+}`,
+ responseBody: `{
+ "data": {
+ "id": "conv-1",
+ "title": "Investigate high cost traces",
+ "provider": "openai",
+ "model": "gpt-4o",
+ "totalMessages": 0
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/chat/conversation \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "title": "Investigate high cost traces",
+ "provider": "openai",
+ "model": "gpt-4o"
+ }'`,
+ },
+ {
+ id: "get-otter-conversation",
+ method: "GET",
+ path: "/api/chat/conversation/{id}",
+ summary: "Get Ask Otter conversation",
+ description: "Retrieve a conversation and its message history.",
+ responseBody: `{
+ "data": {
+ "id": "conv-1",
+ "title": "Investigate high cost traces",
+ "messages": [
+ {
+ "id": "msg-1",
+ "role": "user",
+ "content": "Analyze the slowest traces from the last 24 hours"
+ }
+ ]
+ }
+}`,
+ curlExample: (apiKey) => `curl -X GET http://localhost:3000/api/chat/conversation/conv-1 \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "delete-otter-conversation",
+ method: "DELETE",
+ path: "/api/chat/conversation/{id}",
+ summary: "Delete Ask Otter conversation",
+ description: "Delete a conversation and its messages.",
+ responseBody: `{
+ "data": "Conversation deleted"
+}`,
+ curlExample: (apiKey) => `curl -X DELETE http://localhost:3000/api/chat/conversation/conv-1 \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "send-otter-message",
+ method: "POST",
+ path: "/api/chat/message",
+ summary: "Send Ask Otter message",
+ description:
+ "Stream an assistant reply for a conversation (NDJSON events: delta, step, done, error). Requires organisation/project/environment context for connector routing.",
+ requestBody: `{
+ "conversationId": "conv-1",
+ "content": "Analyze the slowest traces from the last 24 hours"
+}`,
+ responseBody: `{"type":"step","status":"active","label":"Planning"}
+{"type":"delta","text":"Looking at recent high-latency traces..."}
+{"type":"done"}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/chat/message \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "conversationId": "conv-1",
+ "content": "Analyze the slowest traces from the last 24 hours"
+ }'`,
+ },
+ {
+ id: "execute-otter-sql",
+ method: "POST",
+ path: "/api/chat/message/execute",
+ summary: "Execute Ask Otter SQL",
+ description:
+ "Run a validated read-only SQL query from Ask Otter against the intelligence ClickHouse connector for the active environment. Returns 409 when native SQL chat is unavailable.",
+ requestBody: `{
+ "messageId": "msg-1",
+ "query": "SELECT SpanName, Duration FROM otel_traces LIMIT 10"
+}`,
+ responseBody: `{
+ "data": [],
+ "stats": {
+ "rowsRead": 0,
+ "executionTimeMs": 12,
+ "bytesRead": 0
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/chat/message/execute \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "messageId": "msg-1",
+ "query": "SELECT SpanName, Duration FROM otel_traces LIMIT 10"
+ }'`,
},
+ {
+ id: "save-otter-widget",
+ method: "POST",
+ path: "/api/chat/message/save-widget",
+ summary: "Save Ask Otter query as widget",
+ description: "Persist a chat SQL query as a dashboard widget.",
+ requestBody: `{
+ "title": "Slow spans",
+ "description": "Top latency spans",
+ "type": "table",
+ "query": "SELECT SpanName, Duration FROM otel_traces ORDER BY Duration DESC LIMIT 25",
+ "boardId": "board-1"
+}`,
+ responseBody: `{
+ "data": {
+ "id": "widget-1"
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/chat/message/save-widget \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "title": "Slow spans",
+ "type": "table",
+ "query": "SELECT SpanName, Duration FROM otel_traces ORDER BY Duration DESC LIMIT 25"
+ }'`,
+ },
+ {
+ id: "get-otter-usage",
+ method: "GET",
+ path: "/api/chat/usage",
+ summary: "Get Ask Otter usage",
+ description: "Aggregate token and cost usage for Otter chat and analysis runs.",
+ responseBody: `{
+ "data": {
+ "totalPromptTokens": 1200,
+ "totalCompletionTokens": 800,
+ "totalCost": 0.045
+ }
+}`,
+ curlExample: (apiKey) => `curl -X GET "http://localhost:3000/api/chat/usage?start=2026-09-01T00:00:00.000Z&end=2026-09-02T00:00:00.000Z" \\
+${bearerAuthHeaders(apiKey)}`,
+ },
+ {
+ id: "improve-prompt-otter",
+ method: "POST",
+ path: "/api/prompt/improve",
+ summary: "Improve prompt with Otter",
+ description: "Ask Otter to propose precise prompt edits. Requires an OpenLIT API key, Chat Settings, and organisation/project/environment context headers.",
+ requestBody: `{
+ "prompt": "You are a helpful assistant. Answer the user question.",
+ "promptId": "prompt-1",
+ "criteria": [
+ "Keep the prompt concise",
+ "Preserve template variables"
+ ]
+}`,
+ responseBody: `{
+ "data": {
+ "suggestions": [
+ {
+ "id": "add-output-format",
+ "dimension": "Output",
+ "rationale": "Make the expected response shape explicit.",
+ "original": "Answer the user question.",
+ "replacement": "Answer the user question as JSON with keys answer and confidence."
+ }
+ ],
+ "provider": "openai",
+ "model": "gpt-4o"
+ }
+}`,
+ curlExample: (apiKey) => `curl -X POST http://localhost:3000/api/prompt/improve \\
+${bearerAuthHeaders(apiKey)} \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "prompt": "You are a helpful assistant. Answer the user question.",
+ "promptId": "prompt-1"
+ }'`,
+ },
+
];
diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.ts
index 133ec41e..bd318b25 100644
--- a/src/client/src/constants/messages/en.ts
+++ b/src/client/src/constants/messages/en.ts
@@ -15,8 +15,12 @@ export const CREATE_NEW_KEY = "Create a new api key";
export const SETTINGS = "Settings";
export const OPENAPI_SPECIFICATION = "OpenAPI Specification";
export const OPENAPI_SPECIFICATION_UI = "OpenAPI Specification UI";
+export const OPENAPI_SPEC_NAV = "OpenAPI Spec";
+export const OPENAPI_SPEC_PAGE_TITLE = "Open API Spec";
export const INTERACTIVE_API_REFERENCE = "Interactive API Reference";
export const OPENAPI_SPEC_BEARER_AUTH = "OpenAPI 3.0 Spec • Bearer Auth Authorized";
+export const OPENAPI_SPEC_CONTEXT_HEADERS_HINT =
+ "org / project / environment headers required for signal routing";
export const REQUEST_CURL_EXAMPLE = "Request Curl Example";
export const COPY_SNIPPET = "Copy Snippet";
export const COPIED = "Copied";
@@ -1374,6 +1378,9 @@ export const PROJECT_DETAILS_DESCRIPTION =
"Review project identity, current status, and database configuration.";
export const PROJECT_ENVIRONMENT = "Environments";
export const PROJECT_ID = "Project ID";
+export const ORGANISATION_ID = "Organisation ID";
+export const ENVIRONMENT_NAME = "Environment";
+export const COPY_CONTEXT_VALUE = (label: string) => `Copy ${label}`;
export const PROJECT_CONNECTION_COUNT = "ClickHouse connections";
export const PROJECT_DATABASE_CONFIGS = "Database configurations";
export const PROJECT_DATABASE_CONFIGS_DESCRIPTION =
diff --git a/src/client/src/constants/openlit-context.ts b/src/client/src/constants/openlit-context.ts
index 9082afd9..e8b4a1a1 100644
--- a/src/client/src/constants/openlit-context.ts
+++ b/src/client/src/constants/openlit-context.ts
@@ -5,6 +5,9 @@ export const OPENLIT_CONTEXT_HEADERS = {
environment: "x-openlit-environment",
} as const;
+/** Middleware injects this after a successful Bearer API key verification. */
+export const MIDDLEWARE_DATABASE_CONFIG_HEADER = "x-database-config-id";
+
export function getRequestEnvironment(request: Request): string | undefined {
return request.headers.get(OPENLIT_CONTEXT_HEADERS.environment) || undefined;
}
diff --git a/src/client/src/constants/prompts.ts b/src/client/src/constants/prompts.ts
index e685b7fc..06baf47c 100644
--- a/src/client/src/constants/prompts.ts
+++ b/src/client/src/constants/prompts.ts
@@ -47,6 +47,8 @@ export type PromptCompiledInput = {
shouldCompile?: boolean;
downloadSource?: string;
downloadMetaProperties?: Record<string, unknown>;
+ /** Optional override from signal routing / explicit database-config header. */
+ databaseConfigId?: string;
};
export type SpecificPromptInput = {
diff --git a/src/client/src/constants/route.ts b/src/client/src/constants/route.ts
index e23059a8..064946b3 100644
--- a/src/client/src/constants/route.ts
+++ b/src/client/src/constants/route.ts
@@ -18,6 +18,8 @@ export const ALLOWED_OPENLIT_ROUTES_WITH_TOKEN = [
"/api/vault/get-secrets",
"/api/rule-engine/evaluate",
"/api/controller/poll",
+ "/api/api-key",
+ "/api/db-config",
];
export const ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN = [
@@ -28,6 +30,8 @@ export const ALLOWED_OPENLIT_ROUTE_PREFIXES_WITH_TOKEN = [
"/api/prompt/",
"/api/vault/",
"/api/metrics/",
+ "/api/chat/",
+ "/api/api-key/",
];
export const CRON_JOB_ROUTES = [
diff --git a/src/client/src/constants/sidebar.tsx b/src/client/src/constants/sidebar.tsx
index 17c4ae02..34e39d37 100644
--- a/src/client/src/constants/sidebar.tsx
+++ b/src/client/src/constants/sidebar.tsx
@@ -153,7 +153,7 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
{
icon: <FolderKanban className={ICON_CLASSES} />,
text: m.SIDEBAR_PROJECTS,
- link: "/organisation?tab=projects",
+ link: "/organisation/projects",
type: "action",
},
{
@@ -170,7 +170,7 @@ export const SIDEBAR_ITEMS: SidebarItemProps[] = [
},
{
icon: <BookOpen className={ICON_CLASSES} />,
- text: "OpenAPI Spec",
+ text: m.OPENAPI_SPEC_NAV,
link: "/openapi-spec",
type: "action",
},
diff --git a/src/client/src/helpers/server/auth.ts b/src/client/src/helpers/server/auth.ts
index 94e57916..b0011006 100644
--- a/src/client/src/helpers/server/auth.ts
+++ b/src/client/src/helpers/server/auth.ts
@@ -1,19 +1,75 @@
+import { getAPIKeyInfo } from "@/lib/platform/api-keys";
import { getCurrentUser } from "@/lib/session";
+import { MIDDLEWARE_DATABASE_CONFIG_HEADER } from "@/constants/openlit-context";
+
+export { MIDDLEWARE_DATABASE_CONFIG_HEADER };
+
+export type RequestAuth = {
+ /** Bound database config (API key) or undefined for session (caller may resolve current). */
+ databaseConfigId?: string;
+ /** Session user id, or the API key creator when authenticated via Bearer. */
+ userId?: string;
+ via: "apiKey" | "session";
+};
/**
* Resolves the database configuration ID from the request headers or the current user session.
+ * Prefer middleware-injected API key binding (`x-database-config-id`), then fall back to session.
* Returns a tuple of [error, databaseConfigId].
*/
-export async function resolveDbConfigId(request: Request): Promise<[string | null, string | undefined]> {
- const dbConfigId = request.headers.get("x-database-config-id");
- if (dbConfigId) {
- return [null, dbConfigId];
+export async function resolveDbConfigId(
+ request: Request
+): Promise<[string | null, string | undefined]> {
+ const [authErr, auth] = await resolveRequestAuth(request);
+ if (authErr || !auth) {
+ return [authErr || "Unauthorized", undefined];
+ }
+ return [null, auth.databaseConfigId];
+}
+
+/**
+ * Prefer API key (middleware `x-database-config-id` / Bearer), then session.
+ * Used by Ask Otter / AI Analysis and other dual-auth routes.
+ */
+export async function resolveRequestAuth(
+ request: Request
+): Promise<[string | null, RequestAuth | null]> {
+ const middlewareDbConfigId = request.headers
+ ?.get?.(MIDDLEWARE_DATABASE_CONFIG_HEADER)
+ ?.trim();
+ if (middlewareDbConfigId) {
+ let userId: string | undefined;
+ const authorizationHeader = request.headers?.get?.("Authorization") || "";
+ if (authorizationHeader.startsWith("Bearer ")) {
+ const apiKey = authorizationHeader.replace(/^Bearer /, "").trim();
+ if (apiKey) {
+ const [keyErr, apiInfo] = await getAPIKeyInfo({ apiKey });
+ if (!keyErr && apiInfo?.createdByUserId) {
+ userId = apiInfo.createdByUserId;
+ }
+ }
+ }
+ return [
+ null,
+ {
+ databaseConfigId: middlewareDbConfigId,
+ userId,
+ via: "apiKey",
+ },
+ ];
}
const user = await getCurrentUser();
if (!user) {
- return ["Unauthorized", undefined];
+ return ["Unauthorized", null];
}
- return [null, undefined];
+ return [
+ null,
+ {
+ databaseConfigId: undefined,
+ userId: user.id,
+ via: "session",
+ },
+ ];
}
diff --git a/src/client/src/helpers/server/sdk-intelligence.ts b/src/client/src/helpers/server/sdk-intelligence.ts
new file mode 100644
index 00000000..ce2bdc36
--- /dev/null
+++ b/src/client/src/helpers/server/sdk-intelligence.ts
@@ -0,0 +1,158 @@
+import getMessage from "@/constants/messages";
+import {
+ getRequestEnvironment,
+ MIDDLEWARE_DATABASE_CONFIG_HEADER,
+ OPENLIT_CONTEXT_HEADERS,
+} from "@/constants/openlit-context";
+import { getDBConfigByIdInternal } from "@/lib/db-config";
+import { getAPIKeyInfo, type APIKeyInfo } from "@/lib/platform/api-keys";
+import { resolveSignalSource } from "@/lib/telemetry-source";
+
+export type SdkIntelligenceResolveVia =
+ | "signalRouting"
+ | "databaseConfigHeader"
+ | "apiKey";
+
+export type SdkIntelligenceResolve = {
+ databaseConfigId: string;
+ via: SdkIntelligenceResolveVia;
+ apiKeyInfo: APIKeyInfo;
+};
+
+function firstHeader(request: Request, ...names: string[]) {
+ for (const name of names) {
+ const value = request.headers?.get?.(name)?.trim();
+ if (value) return value;
+ }
+ return undefined;
+}
+
+/**
+ * Resolve the ClickHouse that owns Prompt Hub / Vault / Rule Engine state for
+ * SDK-facing Bearer requests.
+ *
+ * Preference order (latest first):
+ * 1. Signal routing — `x-openlit-project-id` + `x-openlit-environment` (project
+ * may be inferred from the API key's bound database config)
+ * 2. Explicit `x-openlit-database-config-id` (validated against the API key's project)
+ * 3. Legacy API key database-config binding (existing SDKs keep working)
+ *
+ * Middleware-injected `x-database-config-id` alone is treated as the API-key
+ * binding, not as an explicit client database-config override.
+ */
+export async function resolveSdkIntelligenceDatabaseConfig(
+ request: Request,
+ apiKey: string
+): Promise<[string | null, SdkIntelligenceResolve | null]> {
+ const messages = getMessage();
+ const trimmedKey = apiKey.trim();
+ if (!trimmedKey) {
+ return [messages.NO_API_KEY, null];
+ }
+
+ const [keyErr, apiInfo] = await getAPIKeyInfo({ apiKey: trimmedKey });
+ if (keyErr || !apiInfo?.databaseConfigId) {
+ return [messages.NO_API_KEY, null];
+ }
+
+ const keyBoundDatabaseConfigId = apiInfo.databaseConfigId;
+ const projectIdHeader = firstHeader(
+ request,
+ OPENLIT_CONTEXT_HEADERS.projectId
+ );
+ const environment = getRequestEnvironment(request);
+ const clientDatabaseConfigId = firstHeader(
+ request,
+ OPENLIT_CONTEXT_HEADERS.databaseConfigId
+ );
+
+ if (environment) {
+ let projectId = projectIdHeader;
+ if (!projectId) {
+ const keyDatabase = await getDBConfigByIdInternal({
+ id: keyBoundDatabaseConfigId,
+ });
+ projectId = keyDatabase?.projectId || undefined;
+ }
+
+ if (projectId) {
+ const resolution = await resolveSignalSource("intelligence", {
+ projectId,
+ environment,
+ dbConfigId: keyBoundDatabaseConfigId,
+ });
+ const { descriptor } = resolution;
+ if (
+ resolution.hasSource &&
+ descriptor.type === "clickhouse" &&
+ descriptor.dbConfigId
+ ) {
+ return [
+ null,
+ {
+ databaseConfigId: descriptor.dbConfigId,
+ via: "signalRouting",
+ apiKeyInfo: apiInfo,
+ },
+ ];
+ }
+
+ return [
+ "Intelligence ClickHouse is not configured for the selected project environment.",
+ null,
+ ];
+ }
+ }
+
+ if (clientDatabaseConfigId) {
+ if (clientDatabaseConfigId === keyBoundDatabaseConfigId) {
+ return [
+ null,
+ {
+ databaseConfigId: clientDatabaseConfigId,
+ via: "databaseConfigHeader",
+ apiKeyInfo: apiInfo,
+ },
+ ];
+ }
+
+ const [keyDatabase, requestedDatabase] = await Promise.all([
+ getDBConfigByIdInternal({ id: keyBoundDatabaseConfigId }),
+ getDBConfigByIdInternal({ id: clientDatabaseConfigId }),
+ ]);
+ if (
+ keyDatabase?.projectId &&
+ requestedDatabase?.projectId &&
+ keyDatabase.projectId === requestedDatabase.projectId
+ ) {
+ return [
+ null,
+ {
+ databaseConfigId: clientDatabaseConfigId,
+ via: "databaseConfigHeader",
+ apiKeyInfo: apiInfo,
+ },
+ ];
+ }
+
+ return [
+ "The selected database configuration is not available for this API key.",
+ null,
+ ];
+ }
+
+ // Prefer middleware-injected binding when present; otherwise the key record.
+ const middlewareDatabaseConfigId = firstHeader(
+ request,
+ MIDDLEWARE_DATABASE_CONFIG_HEADER
+ );
+ return [
+ null,
+ {
+ databaseConfigId:
+ middlewareDatabaseConfigId || keyBoundDatabaseConfigId,
+ via: "apiKey",
+ apiKeyInfo: apiInfo,
+ },
+ ];
+}
diff --git a/src/client/src/lib/platform/api-keys/index.ts b/src/client/src/lib/platform/api-keys/index.ts
index 0895ce74..f9e942a3 100644
--- a/src/client/src/lib/platform/api-keys/index.ts
+++ b/src/client/src/lib/platform/api-keys/index.ts
@@ -87,18 +87,21 @@ export async function getAPIKeyInfo({ apiKey }: { apiKey: string }) {
);
}
-export async function getAllAPIKeys() {
- const [err, dbConfig] = await asaw(getDBConfigByUser(true));
- throwIfError(err, err);
-
- throwIfError(!dbConfig?.id, getMessage().DATABASE_CONFIG_NOT_FOUND);
+export async function getAllAPIKeys(databaseConfigId?: string) {
+ let resolvedDatabaseConfigId = databaseConfigId?.trim() || undefined;
+ if (!resolvedDatabaseConfigId) {
+ const [err, dbConfig] = await asaw(getDBConfigByUser(true));
+ throwIfError(err, err);
+ throwIfError(!dbConfig?.id, getMessage().DATABASE_CONFIG_NOT_FOUND);
+ resolvedDatabaseConfigId = dbConfig.id;
+ }
const [, data] = await asaw(
prisma.aPIKeys.findMany({
where: {
AND: [
{
- databaseConfigId: dbConfig?.id,
+ databaseConfigId: resolvedDatabaseConfigId,
},
{ isDeleted: false },
],
diff --git a/src/client/src/lib/platform/llm/agent-loop.ts b/src/client/src/lib/platform/llm/agent-loop.ts
index f6fabefb..879ae2d0 100644
--- a/src/client/src/lib/platform/llm/agent-loop.ts
+++ b/src/client/src/lib/platform/llm/agent-loop.ts
@@ -118,7 +118,11 @@ async function fromExternalSample(params: MetricParams): Promise<AgentLoopRow> {
}
}
-async function resolveExternalTraces(params: MetricParams) {
+/**
+ * Same source resolution as the traces list: environment / sourceId →
+ * traces binding → ClickHouse DatabaseConfig (or external adapter).
+ */
+async function resolveTracesSource(params: MetricParams) {
const { resolveTelemetrySourceDescriptor } =
await import("@/lib/telemetry-source");
const descriptor = await resolveTelemetrySourceDescriptor({
@@ -126,10 +130,14 @@ async function resolveExternalTraces(params: MetricParams) {
sourceId: params.sourceId,
environment: params.environment,
});
- if (descriptor.isBuiltIn || descriptor.type === "clickhouse") {
- return null;
- }
- return { descriptor };
+ const isClickHouse =
+ descriptor.isBuiltIn || descriptor.type === "clickhouse";
+ return {
+ descriptor,
+ isClickHouse,
+ databaseConfigId:
+ params.databaseConfigId || descriptor.dbConfigId || undefined,
+ };
}
function windowQuery(params: MetricParams) {
@@ -141,8 +149,8 @@ function windowQuery(params: MetricParams) {
export async function getAgentLoop(
params: MetricParams
): Promise<{ err?: unknown; data?: AgentLoopRow[] }> {
- const external = await resolveExternalTraces(params);
- if (external) {
+ const source = await resolveTracesSource(params);
+ if (!source.isClickHouse) {
try {
return { data: [await fromExternalSample(params)] };
} catch (err) {
@@ -164,7 +172,7 @@ export async function getAgentLoop(
const result = await dataCollector(
{ query },
"query",
- params.databaseConfigId
+ source.databaseConfigId
);
if (result.err) return { err: result.err, data: [] };
const rows = (result.data as Record<string, unknown>[]) || [];
diff --git a/src/client/src/lib/platform/llm/generation-health.ts b/src/client/src/lib/platform/llm/generation-health.ts
index 2b285d6f..db1cc1c1 100644
--- a/src/client/src/lib/platform/llm/generation-health.ts
+++ b/src/client/src/lib/platform/llm/generation-health.ts
@@ -286,7 +286,11 @@ async function fromExternalSample(params: MetricParams): Promise<GenerationHealt
}
}
-async function resolveExternalTraces(params: MetricParams) {
+/**
+ * Same source resolution as the traces list: environment / sourceId →
+ * traces binding → ClickHouse DatabaseConfig (or external adapter).
+ */
+async function resolveTracesSource(params: MetricParams) {
const { resolveTelemetrySourceDescriptor } =
await import("@/lib/telemetry-source");
const descriptor = await resolveTelemetrySourceDescriptor({
@@ -294,10 +298,14 @@ async function resolveExternalTraces(params: MetricParams) {
sourceId: params.sourceId,
environment: params.environment,
});
- if (descriptor.isBuiltIn || descriptor.type === "clickhouse") {
- return null;
- }
- return { descriptor };
+ const isClickHouse =
+ descriptor.isBuiltIn || descriptor.type === "clickhouse";
+ return {
+ descriptor,
+ isClickHouse,
+ databaseConfigId:
+ params.databaseConfigId || descriptor.dbConfigId || undefined,
+ };
}
function paramsWithoutHealthChips(params: MetricParams): MetricParams {
@@ -326,8 +334,8 @@ function windowQuery(params: MetricParams) {
export async function getGenerationHealth(
params: MetricParams
): Promise<{ err?: unknown; data?: GenerationHealthRow[] }> {
- const external = await resolveExternalTraces(params);
- if (external) {
+ const source = await resolveTracesSource(params);
+ if (!source.isClickHouse) {
try {
return { data: [await fromExternalSample(params)] };
} catch (err) {
@@ -358,7 +366,11 @@ export async function getGenerationHealth(
CROSS JOIN (${windowQuery(previousParams)}) AS previous_data
`;
- const result = await dataCollector({ query });
+ const result = await dataCollector(
+ { query },
+ "query",
+ source.databaseConfigId
+ );
if (result.err) return { err: result.err, data: [] };
const rows = (result.data as Record<string, unknown>[]) || [];
const current = rows[0] || {};
diff --git a/src/client/src/lib/platform/prompt/compiled.ts b/src/client/src/lib/platform/prompt/compiled.ts
index aaf4dd8c..16a8e1a2 100644
--- a/src/client/src/lib/platform/prompt/compiled.ts
+++ b/src/client/src/lib/platform/prompt/compiled.ts
@@ -36,13 +36,16 @@ export async function getCompiledPrompt(
err || getMessage().NO_API_KEY
);
+ const databaseConfigId =
+ promptCompiledInput.databaseConfigId || apiInfo?.databaseConfigId;
+
const { err: promptErr, data: promptData } = await getSpecificPrompt(
{
id: promptCompiledInput.id,
name: promptCompiledInput.name,
version: promptCompiledInput.version,
},
- apiInfo?.databaseConfigId
+ databaseConfigId
);
const promptObject = (promptData as any)?.[0] || {};
@@ -62,7 +65,7 @@ export async function getCompiledPrompt(
},
downloadSource: promptCompiledInput.downloadSource || "api",
},
- apiInfo?.databaseConfigId
+ databaseConfigId
);
promptObject.metaProperties = jsonParse(promptObject.metaProperties);
diff --git a/src/client/src/lib/platform/rule-engine/source.ts b/src/client/src/lib/platform/rule-engine/source.ts
index 69520494..2373e9e9 100644
--- a/src/client/src/lib/platform/rule-engine/source.ts
+++ b/src/client/src/lib/platform/rule-engine/source.ts
@@ -9,6 +9,26 @@ import { resolveSignalSource } from "@/lib/telemetry-source";
export async function resolveRuleEngineDatabaseConfigId(
request: Request
): Promise<string> {
+ const environment = getRequestEnvironment(request);
+
+ // Prefer signal routing (latest) when an environment is selected.
+ if (environment) {
+ const resolution = await resolveSignalSource("intelligence", {
+ environment,
+ });
+ const { descriptor } = resolution;
+ if (
+ resolution.hasSource &&
+ descriptor.type === "clickhouse" &&
+ descriptor.dbConfigId
+ ) {
+ return descriptor.dbConfigId;
+ }
+ throw new Error(
+ "Rule Engine requires a ClickHouse datasource for the selected environment."
+ );
+ }
+
const requestedId = request.headers.get(
OPENLIT_CONTEXT_HEADERS.databaseConfigId
);
@@ -28,9 +48,7 @@ export async function resolveRuleEngineDatabaseConfigId(
return selected.id;
}
- const resolution = await resolveSignalSource("intelligence", {
- environment: getRequestEnvironment(request),
- });
+ const resolution = await resolveSignalSource("intelligence", {});
const { descriptor } = resolution;
if (
diff --git a/src/client/src/lib/platform/traces/read.ts b/src/client/src/lib/platform/traces/read.ts
index 1558d525..3c9ca4f7 100644
--- a/src/client/src/lib/platform/traces/read.ts
+++ b/src/client/src/lib/platform/traces/read.ts
@@ -422,7 +422,14 @@ export async function listTraceRecords(params: MetricParams) {
!!frame.meta?.truncated || spans.length >= (params.limit || 25);
let records = spans.map((row) => denormalizeSpanToTraceRow(row));
if (usesSqlIssueFilters(descriptor)) {
- records = await attachClickHouseLoopHits(params, records);
+ records = await attachClickHouseLoopHits(
+ {
+ ...params,
+ databaseConfigId:
+ params.databaseConfigId || descriptor.dbConfigId,
+ },
+ records
+ );
} else if (spans.some(isTraceSummaryRow)) {
const trees = await treesForListedTraces(adapter, spans);
records = withLoopHits(records, trees);
diff --git a/src/client/src/lib/platform/vault/index.ts b/src/client/src/lib/platform/vault/index.ts
index 3573c0da..df157571 100644
--- a/src/client/src/lib/platform/vault/index.ts
+++ b/src/client/src/lib/platform/vault/index.ts
@@ -313,10 +313,12 @@ export async function getSecretsFromDatabaseId(
);
const apiInfoForSecrets = apiInfo as APIKeyInfo | null | undefined;
+ const databaseConfigId =
+ filters.databaseConfigId || apiInfoForSecrets?.databaseConfigId || undefined;
const { err: secretErr, data: secretData } = await getSecrets(
{
...filters,
- databaseConfigId: apiInfoForSecrets?.databaseConfigId || undefined,
+ databaseConfigId,
createdBy: apiInfoForSecrets?.createdByUser?.email,
},
{ selectValue: true }
@@ -349,8 +351,16 @@ export async function getSecretById(
if (!source) return { data: [] };
} else {
const user = await getCurrentUser();
- throwIfError(!user, getMessage().UNAUTHORIZED_USER);
- ownerCondition = ` AND ${getOwnerEmailCondition(user!, "v")}`;
+ if (user) {
+ ownerCondition = ` AND ${getOwnerEmailCondition(user, "v")}`;
+ } else if (databaseConfigId) {
+ // Trusted DB-scoped lookup (Bearer API key / middleware binding).
+ // The caller already resolved a database config; secrets are queried
+ // only against that ClickHouse instance.
+ ownerCondition = "";
+ } else {
+ throwIfError(true, getMessage().UNAUTHORIZED_USER);
+ }
}
const query = `SELECT * ${
!!excludeVaultValue ? "EXCEPT value" : ""
diff --git a/src/client/src/lib/rbac/route.ts b/src/client/src/lib/rbac/route.ts
index 670e0768..ec7e1138 100644
--- a/src/client/src/lib/rbac/route.ts
+++ b/src/client/src/lib/rbac/route.ts
@@ -31,6 +31,8 @@ function extractDatabaseConfigId(body: any, request: Request) {
typeof selectedConfig === "string" ? selectedConfig : undefined,
selectedConfig?.databaseConfigId,
selectedConfig?.dbConfigId,
+ // Middleware injects this after Bearer API key verification.
+ request.headers?.get?.("x-database-config-id"),
request.headers?.get?.(OPENLIT_CONTEXT_HEADERS.databaseConfigId)
);
}
@@ -55,6 +57,15 @@ export function withDbConfigAccess<THandler extends RouteHandler>(
): THandler {
return (async (request: Request, context: RouteContext = {}) => {
const messages = getMessage();
+
+ // API key first: middleware already verified Bearer and set x-database-config-id.
+ const apiKeyDatabaseConfigId = firstString(
+ request.headers?.get?.("x-database-config-id")
+ );
+ if (apiKeyDatabaseConfigId) {
+ return handler(request, context);
+ }
+
const user = await getCurrentUser();
if (!user) return Response.json({ error: messages.UNAUTHORIZED_USER }, { status: 401 });
diff --git a/src/client/src/lib/telemetry-source.ts b/src/client/src/lib/telemetry-source.ts
index 68877e8e..0bfef0e3 100644
--- a/src/client/src/lib/telemetry-source.ts
+++ b/src/client/src/lib/telemetry-source.ts
@@ -21,6 +21,8 @@ import {
getCurrentOrganisation,
getCurrentProjectForOrganisation,
} from "@/lib/organisation";
+import { OPENLIT_CONTEXT_HEADERS, MIDDLEWARE_DATABASE_CONFIG_HEADER } from "@/constants/openlit-context";
+import { headers } from "next/headers";
import type { DatabaseConfig, TelemetrySource } from "@prisma/client";
import type {
DataSourceAdapter,
@@ -88,11 +90,70 @@ export function toDescriptor(row: TelemetrySource): TelemetrySourceDescriptor {
};
}
+async function readRequestContextHeaders(): Promise<{
+ projectId?: string;
+ databaseConfigId?: string;
+}> {
+ try {
+ const headerStore = await headers();
+ return {
+ projectId:
+ headerStore.get(OPENLIT_CONTEXT_HEADERS.projectId)?.trim() ||
+ undefined,
+ databaseConfigId:
+ headerStore.get(MIDDLEWARE_DATABASE_CONFIG_HEADER)?.trim() ||
+ headerStore.get(OPENLIT_CONTEXT_HEADERS.databaseConfigId)?.trim() ||
+ undefined,
+ };
+ } catch {
+ return {};
+ }
+}
+
async function getCurrentProjectId(): Promise<string | null> {
- const currentOrg = await getCurrentOrganisation();
- if (!currentOrg?.id) return null;
- const currentProject = await getCurrentProjectForOrganisation(currentOrg.id);
- return currentProject?.id ?? null;
+ const requestContext = await readRequestContextHeaders();
+ if (requestContext.projectId) {
+ return requestContext.projectId;
+ }
+ if (requestContext.databaseConfigId) {
+ const databaseConfig = await getDBConfigByIdInternal({
+ id: requestContext.databaseConfigId,
+ });
+ if (databaseConfig?.projectId) {
+ return databaseConfig.projectId;
+ }
+ }
+
+ try {
+ const currentOrg = await getCurrentOrganisation();
+ if (!currentOrg?.id) return null;
+ const currentProject = await getCurrentProjectForOrganisation(currentOrg.id);
+ return currentProject?.id ?? null;
+ } catch {
+ return null;
+ }
+}
+
+async function resolveActiveCredentialDatabase(
+ options: ResolveTelemetrySourceOptions
+): Promise<DatabaseConfig | null | undefined> {
+ if (options.dbConfigId) {
+ return getDBConfigByIdInternal({ id: options.dbConfigId });
+ }
+ if (options.projectId !== undefined) {
+ return null;
+ }
+
+ const requestContext = await readRequestContextHeaders();
+ if (requestContext.databaseConfigId) {
+ return getDBConfigByIdInternal({ id: requestContext.databaseConfigId });
+ }
+
+ try {
+ return (await getDBConfigByUser(true)) as DatabaseConfig | null | undefined;
+ } catch {
+ return null;
+ }
}
export async function resolveBuiltInDescriptor(
@@ -230,11 +291,8 @@ export async function resolveSignalSource(
// leaves background/parallel reads unable to resolve authentication
// consistently. Background callers pass projectId + dbConfigId explicitly;
// interactive callers can safely resolve the current project-scoped DB.
- const activeDatabase =
- options.projectId === undefined && !options.dbConfigId
- ? ((await getDBConfigByUser(true)) as
- DatabaseConfig | null | undefined)
- : null;
+ // API-key callers use the middleware-bound database config as the vault.
+ const activeDatabase = await resolveActiveCredentialDatabase(options);
const credentialDatabaseConfigId =
options.dbConfigId || activeDatabase?.id;
const environment = normalizeEnvironment(options.environment || activeDatabase?.environment || "production");
diff --git a/src/client/src/utils/breadcrumbs.ts b/src/client/src/utils/breadcrumbs.ts
index 6f4502c9..6628b701 100644
--- a/src/client/src/utils/breadcrumbs.ts
+++ b/src/client/src/utils/breadcrumbs.ts
@@ -382,13 +382,22 @@ export const ROUTE_CONFIGS: RouteConfig[] = [
{ title: getMessage().ORGANISATION, href: "/organisation" },
],
},
+ {
+ regex: /^\/organisation\/projects\/?$/,
+ getTitle: () => getMessage().PROJECTS,
+ getBreadcrumbs: () => [
+ { title: "Settings", href: "/settings" },
+ { title: getMessage().ORGANISATION, href: "/organisation" },
+ { title: getMessage().PROJECTS, href: "/organisation/projects" },
+ ],
+ },
{
regex: /^\/organisation\/project\/[^/]+$/,
getTitle: () => "",
getBreadcrumbs: () => [
{ title: "Settings", href: "/settings" },
{ title: getMessage().ORGANISATION, href: "/organisation" },
- { title: getMessage().PROJECTS, href: "/organisation?tab=projects" },
+ { title: getMessage().PROJECTS, href: "/organisation/projects" },
],
},