mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-16 17:09:09 +00:00
feat(api): add /v1/me/sessions self-service API key endpoints (#14840)
Adds `GET /v1/me/sessions` and `GET /v1/me/sessions/{id}`. With them, an API key holder can list their own coding-agent sessions and inspect one session's requests, including token breakdowns where cache reads and writes are separated from uncached input. The endpoints are built on the agent-session attribution from #14833 and documented in the OpenAPI spec, with the agent skill catalogs regenerated.
Migration train repair: merged the release tip after #14771, #14862 and #14833 landed. The stacked copies of the self-service settings migration (233) and the agent-session migrations (234/235), together with their compatibility renames, tests and the migration counts (232), resolve to the landed release state. The obsolete `KNOWN_GAPS` entry for 228 is dropped because 228 now exists. `openapi.yaml` keeps both the `AgentSession*` schemas and the release's `ImportedApiKey` schema. This PR adds no migration.
Thanks @fouadSalkini.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
- **feat(api):** add `/v1/me/sessions` self-service API key endpoints to list and inspect agent sessions with project, client, date, and sorting filters ([#14840](https://github.com/diegosouzapw/OmniRoute/pull/14840)) — thanks @fouadSalkini
|
||||
@@ -15777,6 +15777,131 @@ paths:
|
||||
description: The key lacks the self:usage scope
|
||||
"500":
|
||||
description: Status could not be built
|
||||
/api/v1/me/sessions:
|
||||
get:
|
||||
tags:
|
||||
- V1 Me
|
||||
summary: "GET me › sessions"
|
||||
description: >-
|
||||
List agent sessions opened by the calling API key (also served at /v1/me/sessions).
|
||||
Authenticate with `Authorization: Bearer <key>`; requires scope `self:usage`. Every
|
||||
filter applies on top of the calling key, so other keys' sessions are never listed.
|
||||
Session `costUsd` is the list-price cost of the session's requests; flat-rate providers
|
||||
are not counted as $0. It has the same meaning as `/v1/me/status` `listPriceUsd`, except
|
||||
that sessions are priced when each request is recorded and status with the current
|
||||
prices, so the two differ if prices changed in between. `unpricedCount` counts the
|
||||
requests that used tokens but had no known price and are therefore missing from
|
||||
`costUsd`, like status `unpricedRequests`.
|
||||
security:
|
||||
- BearerAuth: []
|
||||
parameters:
|
||||
- name: clientSessionId
|
||||
in: query
|
||||
description: >-
|
||||
Only the session with this client session id (the id the coding agent sends, for
|
||||
example `x-claude-code-session-id`), compared after trimming. A key has at most one
|
||||
session per client session id, so the list holds zero or one session.
|
||||
schema: { type: string, minLength: 1, maxLength: 128 }
|
||||
- name: project
|
||||
in: query
|
||||
description: Only sessions with this project name.
|
||||
schema: { type: string, minLength: 1 }
|
||||
- name: client
|
||||
in: query
|
||||
description: Only sessions from this client, for example `claude-code` or `codex`.
|
||||
schema: { type: string, minLength: 1 }
|
||||
- name: from
|
||||
in: query
|
||||
description: Only sessions last seen at or after this time.
|
||||
schema: { type: string, format: date-time }
|
||||
- name: to
|
||||
in: query
|
||||
description: Only sessions last seen at or before this time.
|
||||
schema: { type: string, format: date-time }
|
||||
- name: sort
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
enum: [lastSeen, firstSeen, requests, tokens, cost]
|
||||
default: lastSeen
|
||||
- name: order
|
||||
in: query
|
||||
schema: { type: string, enum: [asc, desc], default: desc }
|
||||
- name: limit
|
||||
in: query
|
||||
schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
|
||||
- name: offset
|
||||
in: query
|
||||
schema: { type: integer, minimum: 0, default: 0 }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
sessions:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
clientSessionId: { type: [string, "null"] }
|
||||
tokens: { $ref: "#/components/schemas/AgentSessionTokens" }
|
||||
costUsd:
|
||||
type: number
|
||||
description: >-
|
||||
List-price cost of the session's requests in USD, same meaning as
|
||||
`/v1/me/status` `listPriceUsd`.
|
||||
unpricedCount:
|
||||
type: integer
|
||||
description: Requests that used tokens but had no known price.
|
||||
total: { type: integer, description: Number of matching sessions. }
|
||||
limit: { type: integer }
|
||||
offset: { type: integer }
|
||||
"400":
|
||||
description: Invalid query parameters
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
description: The key lacks the self:usage scope
|
||||
"500":
|
||||
description: Sessions could not be listed
|
||||
/api/v1/me/sessions/{id}:
|
||||
get:
|
||||
tags:
|
||||
- V1 Me
|
||||
summary: "GET me › sessions › <id>"
|
||||
description: Get details and recent requests of a session owned by the calling API key.
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/ResourceId"
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
session:
|
||||
type: object
|
||||
properties:
|
||||
tokens: { $ref: "#/components/schemas/AgentSessionTokens" }
|
||||
recentRequests:
|
||||
type: array
|
||||
description: Latest requests of the session, newest first.
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
timestamp: { type: string, format: date-time }
|
||||
provider: { type: [string, "null"] }
|
||||
model: { type: [string, "null"] }
|
||||
tokens: { $ref: "#/components/schemas/AgentSessionRequestTokens" }
|
||||
latencyMs: { type: integer }
|
||||
status: { type: [string, "null"] }
|
||||
success: { type: boolean }
|
||||
"404":
|
||||
description: Session not found
|
||||
/api/v1/models/{model}:
|
||||
get:
|
||||
tags:
|
||||
@@ -17009,6 +17134,45 @@ components:
|
||||
requestId: 0a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d
|
||||
|
||||
schemas:
|
||||
AgentSessionTokens:
|
||||
type: object
|
||||
description: >-
|
||||
Token counters of an agent session. `input` includes the cache reads and writes, as
|
||||
providers report prompt tokens; do not add `cacheRead` or `cacheCreation` to it. The
|
||||
three disjoint parts of the input are `uncachedInput`, `cacheRead` and `cacheCreation`.
|
||||
Requests recorded before the usage extractor fix (#14878) by some non-streaming
|
||||
Claude-format providers stored input without its cached part, so for them `input` and
|
||||
`uncachedInput` may be under-reported.
|
||||
required: [input, uncachedInput, cacheRead, cacheCreation, output, reasoning, total]
|
||||
properties:
|
||||
input: { type: integer, description: Input tokens including cache reads and writes. }
|
||||
uncachedInput:
|
||||
type: integer
|
||||
description: >-
|
||||
Input that was neither read from nor written to the prompt cache:
|
||||
input - cacheRead - cacheCreation, clamped at 0.
|
||||
cacheRead: { type: integer, description: Input tokens read from the prompt cache. }
|
||||
cacheCreation: { type: integer, description: Input tokens written to the prompt cache. }
|
||||
output: { type: integer, description: Output tokens, reasoning included. }
|
||||
reasoning: { type: integer, description: Reasoning tokens, already part of output. }
|
||||
total:
|
||||
type: integer
|
||||
description: input + output (cache reads and writes are already part of input).
|
||||
AgentSessionRequestTokens:
|
||||
type: object
|
||||
description: >-
|
||||
Token counters of one request, with the meaning of AgentSessionTokens, so the requests
|
||||
of a session add up to the session.
|
||||
required: [input, uncachedInput, cacheRead, cacheCreation, output, reasoning]
|
||||
properties:
|
||||
input: { type: integer, description: Input tokens including cache reads and writes. }
|
||||
uncachedInput:
|
||||
type: integer
|
||||
description: input - cacheRead - cacheCreation, clamped at 0.
|
||||
cacheRead: { type: integer }
|
||||
cacheCreation: { type: integer }
|
||||
output: { type: integer, description: Output tokens, reasoning included. }
|
||||
reasoning: { type: integer }
|
||||
ImportedApiKey:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
||||
@@ -104,6 +104,8 @@ All requests require a valid Bearer token or session cookie. Obtain a token via
|
||||
- [`PUT /api/v1/management/proxies/bulk-assign`](references/endpoints.md#put-apiv1managementproxiesbulk-assign)
|
||||
- [`GET /api/v1/management/proxies/health`](references/endpoints.md#get-apiv1managementproxieshealth)
|
||||
- [`GET /api/v1/me/status`](references/endpoints.md#get-apiv1mestatus)
|
||||
- [`GET /api/v1/me/sessions`](references/endpoints.md#get-apiv1mesessions)
|
||||
- [`GET /api/v1/me/sessions/{id}`](references/endpoints.md#get-apiv1mesessionsid)
|
||||
- [`GET /api/v1/muse-code/models`](references/endpoints.md#get-apiv1muse-codemodels)
|
||||
- [`GET /api/v1/music/generations`](references/endpoints.md#get-apiv1musicgenerations)
|
||||
- [`POST /api/v1/music/generations`](references/endpoints.md#post-apiv1musicgenerations)
|
||||
|
||||
@@ -93,6 +93,8 @@
|
||||
- [`PUT /api/v1/management/proxies/bulk-assign`](#put-apiv1managementproxiesbulk-assign)
|
||||
- [`GET /api/v1/management/proxies/health`](#get-apiv1managementproxieshealth)
|
||||
- [`GET /api/v1/me/status`](#get-apiv1mestatus)
|
||||
- [`GET /api/v1/me/sessions`](#get-apiv1mesessions)
|
||||
- [`GET /api/v1/me/sessions/{id}`](#get-apiv1mesessionsid)
|
||||
- [`GET /api/v1/muse-code/models`](#get-apiv1muse-codemodels)
|
||||
- [`GET /api/v1/music/generations`](#get-apiv1musicgenerations)
|
||||
- [`POST /api/v1/music/generations`](#post-apiv1musicgenerations)
|
||||
@@ -1136,6 +1138,28 @@ curl http://localhost:20128/api/v1/me/status \
|
||||
-H "Authorization: Bearer $OMNIROUTE_TOKEN"
|
||||
```
|
||||
|
||||
### GET /api/v1/me/sessions
|
||||
|
||||
GET me › sessions
|
||||
|
||||
List agent sessions opened by the calling API key (also served at /v1/me/sessions). Authenticate with `Authorization: Bearer <key>`; requires scope `self:usage`. Every filter applies on top of the calling key, so other keys' sessions are never listed. Session `costUsd` is the list-price cost of the session's requests; flat-rate providers are not counted as $0. It has the same meaning as `/v1/me/status` `listPriceUsd`, except that sessions are priced when each request is recorded and status with the current prices, so the two differ if prices changed in between. `unpricedCount` counts the requests that used tokens but had no known price and are therefore missing from `costUsd`, like status `unpricedRequests`.
|
||||
|
||||
```bash
|
||||
curl http://localhost:20128/api/v1/me/sessions \
|
||||
-H "Authorization: Bearer $OMNIROUTE_TOKEN"
|
||||
```
|
||||
|
||||
### GET /api/v1/me/sessions/{id}
|
||||
|
||||
GET me › sessions › <id>
|
||||
|
||||
Get details and recent requests of a session owned by the calling API key.
|
||||
|
||||
```bash
|
||||
curl http://localhost:20128/api/v1/me/sessions/{id} \
|
||||
-H "Authorization: Bearer $OMNIROUTE_TOKEN"
|
||||
```
|
||||
|
||||
### GET /api/v1/muse-code/models
|
||||
|
||||
GET muse code › models
|
||||
|
||||
55
src/app/api/v1/me/sessions/[id]/route.ts
Normal file
55
src/app/api/v1/me/sessions/[id]/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { buildApiKeySelfServiceSessionDetail } from "@/lib/usage/apiKeySelfService";
|
||||
import { hasSelfUsageScope } from "@/shared/constants/selfServiceScopes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function extractBearerToken(request: Request): string | null {
|
||||
const authorization = request.headers.get("Authorization") ?? "";
|
||||
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
||||
const token = match?.[1]?.trim();
|
||||
return token ? token : null;
|
||||
}
|
||||
|
||||
function authError(status = 401) {
|
||||
return NextResponse.json({ error: status === 401 ? "Unauthorized" : "Forbidden" }, { status });
|
||||
}
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const apiKey = extractBearerToken(request);
|
||||
if (!apiKey) return authError(401);
|
||||
|
||||
const { validateApiKey, getApiKeyMetadata } = await import("@/lib/db/apiKeys");
|
||||
|
||||
const valid = await validateApiKey(apiKey);
|
||||
if (!valid) return authError(401);
|
||||
|
||||
const metadata = await getApiKeyMetadata(apiKey);
|
||||
if (!metadata || metadata.id === "env-key") return authError(401);
|
||||
|
||||
if (!hasSelfUsageScope(metadata.scopes)) return authError(403);
|
||||
|
||||
const { id } = await context.params;
|
||||
if (!id || typeof id !== "string") {
|
||||
return NextResponse.json({ error: "Session ID required" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const detail = await buildApiKeySelfServiceSessionDetail(
|
||||
{ id: metadata.id, scopes: metadata.scopes },
|
||||
id
|
||||
);
|
||||
|
||||
if (!detail) {
|
||||
return NextResponse.json({ error: "Session not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(detail);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "missing_self_usage_scope") {
|
||||
return authError(403);
|
||||
}
|
||||
return NextResponse.json({ error: "Failed to fetch session detail" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
80
src/app/api/v1/me/sessions/route.ts
Normal file
80
src/app/api/v1/me/sessions/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { buildApiKeySelfServiceSessions } from "@/lib/usage/apiKeySelfService";
|
||||
import { hasSelfUsageScope } from "@/shared/constants/selfServiceScopes";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function extractBearerToken(request: Request): string | null {
|
||||
const authorization = request.headers.get("Authorization") ?? "";
|
||||
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
||||
const token = match?.[1]?.trim();
|
||||
return token ? token : null;
|
||||
}
|
||||
|
||||
function authError(status = 401) {
|
||||
return NextResponse.json({ error: status === 401 ? "Unauthorized" : "Forbidden" }, { status });
|
||||
}
|
||||
|
||||
const isoTimestamp = z
|
||||
.string()
|
||||
.datetime({ offset: true })
|
||||
.transform((value) => new Date(value).toISOString());
|
||||
|
||||
// The proxy records at most this many characters of a client session id (agentContext.ts).
|
||||
const MAX_CLIENT_SESSION_ID_CHARS = 128;
|
||||
|
||||
const sessionsQuerySchema = z.object({
|
||||
project: z.string().trim().min(1).optional(),
|
||||
client: z.string().trim().min(1).optional(),
|
||||
clientSessionId: z.string().trim().min(1).max(MAX_CLIENT_SESSION_ID_CHARS).optional(),
|
||||
from: isoTimestamp.optional(),
|
||||
to: isoTimestamp.optional(),
|
||||
sort: z.enum(["lastSeen", "firstSeen", "requests", "tokens", "cost"]).optional(),
|
||||
order: z.enum(["asc", "desc"]).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const apiKey = extractBearerToken(request);
|
||||
if (!apiKey) return authError(401);
|
||||
|
||||
const { validateApiKey, getApiKeyMetadata } = await import("@/lib/db/apiKeys");
|
||||
|
||||
const valid = await validateApiKey(apiKey);
|
||||
if (!valid) return authError(401);
|
||||
|
||||
const metadata = await getApiKeyMetadata(apiKey);
|
||||
if (!metadata || metadata.id === "env-key") return authError(401);
|
||||
|
||||
if (!hasSelfUsageScope(metadata.scopes)) return authError(403);
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const rawParams = Object.fromEntries(
|
||||
Object.keys(sessionsQuerySchema.shape).map((key) => [key, searchParams.get(key) ?? undefined])
|
||||
);
|
||||
|
||||
const parsed = sessionsQuerySchema.safeParse(rawParams);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid query parameters", details: parsed.error.issues },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await buildApiKeySelfServiceSessions(
|
||||
{ id: metadata.id, scopes: metadata.scopes },
|
||||
parsed.data
|
||||
);
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "missing_self_usage_scope") {
|
||||
return authError(403);
|
||||
}
|
||||
return NextResponse.json({ error: "Failed to list sessions" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,10 @@ import type { SqliteAdapter } from "./adapters/types";
|
||||
export const AGENT_SESSION_IDLE_WINDOW_MS = 30 * 60 * 1000;
|
||||
|
||||
// A type alias (not an interface) so it stays assignable to the cost calculator's token record.
|
||||
// `input` includes cache reads and writes, the way the usage extractors report prompt tokens and
|
||||
// the cost calculator prices them; `output` includes reasoning. Requests recorded before the usage
|
||||
// extractor fix (#14878) by some non-streaming Claude-format providers stored input without its
|
||||
// cached part, so their input and uncached input may be under-reported; they are not guessed at.
|
||||
export type AgentSessionTokens = {
|
||||
input: number;
|
||||
output: number;
|
||||
@@ -40,7 +44,10 @@ function newSessionId(): string {
|
||||
return `as_${randomUUID().replace(/-/g, "").slice(0, 32)}`;
|
||||
}
|
||||
|
||||
/** Scoped to the API key, so one key can never write into another key's session. */
|
||||
/**
|
||||
* Scoped to the API key, so one key can never write into another key's session. The list filter
|
||||
* by client session id looks rows up by this id, so changing it hides existing sessions there.
|
||||
*/
|
||||
function clientSessionRowId(apiKeyId: string | null, clientSessionId: string): string {
|
||||
const digest = createHash("sha256")
|
||||
.update(`${apiKeyId ?? ""}\x1f${clientSessionId}`)
|
||||
@@ -142,3 +149,250 @@ export function recordAgentSessionUsage(db: SqliteAdapter, usage: AgentSessionUs
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
export interface AgentSessionRecord {
|
||||
id: string;
|
||||
apiKeyId: string | null;
|
||||
apiKeyName: string | null;
|
||||
client: string | null;
|
||||
clientSessionId: string | null;
|
||||
projectName: string | null;
|
||||
projectRepo: string | null;
|
||||
projectPath: string | null;
|
||||
projectSource: string | null;
|
||||
gitBranch: string | null;
|
||||
firstSeenAt: string;
|
||||
lastSeenAt: string;
|
||||
requestCount: number;
|
||||
errorCount: number;
|
||||
tokens: {
|
||||
/** Input including cache reads and writes. */
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheCreation: number;
|
||||
reasoning: number;
|
||||
/** Input that was neither read from nor written to the prompt cache, clamped at 0. */
|
||||
uncachedInput: number;
|
||||
/** input + output: cache reads and writes are already part of input. */
|
||||
total: number;
|
||||
};
|
||||
costUsd: number;
|
||||
unpricedCount: number;
|
||||
lastProvider: string | null;
|
||||
lastModel: string | null;
|
||||
lastConnectionId?: string | null;
|
||||
}
|
||||
|
||||
export interface ListAgentSessionsFilter {
|
||||
apiKeyId?: string | null;
|
||||
projectName?: string | null;
|
||||
client?: string | null;
|
||||
/** The client's own session id (agent_sessions.client_session_id). */
|
||||
clientSessionId?: string | null;
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
sort?: "lastSeen" | "firstSeen" | "requests" | "tokens" | "cost";
|
||||
order?: "asc" | "desc";
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export interface AgentSessionRecentUsage {
|
||||
id: number;
|
||||
timestamp: string;
|
||||
provider: string | null;
|
||||
model: string | null;
|
||||
/** Same meaning as the session tokens, so request rows add up to their session. */
|
||||
tokens: {
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead: number;
|
||||
cacheCreation: number;
|
||||
reasoning: number;
|
||||
uncachedInput: number;
|
||||
};
|
||||
latencyMs: number;
|
||||
ttftMs: number;
|
||||
status: string | null;
|
||||
success: boolean;
|
||||
connectionId?: string | null;
|
||||
}
|
||||
|
||||
/** Input that was neither read from nor written to the prompt cache (input includes both). */
|
||||
function uncachedInput(input: number, cacheRead: number, cacheCreation: number): number {
|
||||
return Math.max(0, input - cacheRead - cacheCreation);
|
||||
}
|
||||
|
||||
function textOrNull(value: unknown): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function countOf(value: unknown): number {
|
||||
return Number(value ?? 0);
|
||||
}
|
||||
|
||||
function rowToAgentSessionRecord(row: Record<string, unknown>): AgentSessionRecord {
|
||||
const input = countOf(row.tokens_input);
|
||||
const output = countOf(row.tokens_output);
|
||||
const cacheRead = countOf(row.tokens_cache_read);
|
||||
const cacheCreation = countOf(row.tokens_cache_creation);
|
||||
return {
|
||||
id: String(row.id),
|
||||
apiKeyId: textOrNull(row.api_key_id),
|
||||
apiKeyName: textOrNull(row.api_key_name),
|
||||
client: textOrNull(row.client),
|
||||
clientSessionId: textOrNull(row.client_session_id),
|
||||
projectName: textOrNull(row.project_name),
|
||||
projectRepo: textOrNull(row.project_repo),
|
||||
projectPath: textOrNull(row.project_path),
|
||||
projectSource: textOrNull(row.project_source),
|
||||
gitBranch: textOrNull(row.git_branch),
|
||||
firstSeenAt: String(row.first_seen_at),
|
||||
lastSeenAt: String(row.last_seen_at),
|
||||
requestCount: countOf(row.request_count),
|
||||
errorCount: countOf(row.error_count),
|
||||
tokens: {
|
||||
input,
|
||||
output,
|
||||
cacheRead,
|
||||
cacheCreation,
|
||||
reasoning: countOf(row.tokens_reasoning),
|
||||
uncachedInput: uncachedInput(input, cacheRead, cacheCreation),
|
||||
// Input already includes cache reads and writes; adding them again double counts.
|
||||
total: input + output,
|
||||
},
|
||||
costUsd: countOf(row.cost_usd),
|
||||
unpricedCount: countOf(row.unpriced_count),
|
||||
lastProvider: textOrNull(row.last_provider),
|
||||
lastModel: textOrNull(row.last_model),
|
||||
lastConnectionId: textOrNull(row.last_connection_id),
|
||||
};
|
||||
}
|
||||
|
||||
const SORT_COLUMNS: Record<string, string> = {
|
||||
lastSeen: "last_seen_at",
|
||||
firstSeen: "first_seen_at",
|
||||
requests: "request_count",
|
||||
tokens: "(tokens_input + tokens_output)",
|
||||
cost: "cost_usd",
|
||||
};
|
||||
|
||||
/** WHERE clause and bound params for the list filter (absent fields do not filter). */
|
||||
function buildSessionFilterSql(filter: ListAgentSessionsFilter): {
|
||||
whereClause: string;
|
||||
params: unknown[];
|
||||
} {
|
||||
const conditions: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
const add = (condition: string, value: unknown) => {
|
||||
conditions.push(condition);
|
||||
params.push(value);
|
||||
};
|
||||
|
||||
if (filter.apiKeyId === null) conditions.push("api_key_id IS NULL");
|
||||
else if (filter.apiKeyId !== undefined) add("api_key_id = ?", filter.apiKeyId);
|
||||
if (filter.projectName) add("project_name = ?", filter.projectName);
|
||||
if (filter.client) add("client = ?", filter.client);
|
||||
if (filter.clientSessionId) {
|
||||
add("client_session_id = ?", filter.clientSessionId);
|
||||
// A key's session for a client session id is stored under clientSessionRowId, so the
|
||||
// primary key finds it without scanning the key's other sessions.
|
||||
if (filter.apiKeyId !== undefined) {
|
||||
add("id = ?", clientSessionRowId(filter.apiKeyId, filter.clientSessionId));
|
||||
}
|
||||
}
|
||||
if (filter.from) add("last_seen_at >= ?", filter.from);
|
||||
if (filter.to) add("last_seen_at <= ?", filter.to);
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
||||
return { whereClause, params };
|
||||
}
|
||||
|
||||
export function listAgentSessions(
|
||||
db: SqliteAdapter,
|
||||
filter: ListAgentSessionsFilter = {}
|
||||
): { sessions: AgentSessionRecord[]; total: number } {
|
||||
const { whereClause, params } = buildSessionFilterSql(filter);
|
||||
const sortCol = SORT_COLUMNS[filter.sort || "lastSeen"] || "last_seen_at";
|
||||
const sortOrder = filter.order?.toLowerCase() === "asc" ? "ASC" : "DESC";
|
||||
|
||||
const limit = Math.max(1, Math.min(Number(filter.limit) || 20, 100));
|
||||
const offset = Math.max(0, Number(filter.offset) || 0);
|
||||
|
||||
const countRow = db
|
||||
.prepare(`SELECT COUNT(*) as count FROM agent_sessions ${whereClause}`)
|
||||
.get(...params) as { count: number } | undefined;
|
||||
const total = Number(countRow?.count ?? 0);
|
||||
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT * FROM agent_sessions
|
||||
${whereClause}
|
||||
ORDER BY ${sortCol} ${sortOrder}, id DESC
|
||||
LIMIT ? OFFSET ?`
|
||||
)
|
||||
.all(...params, limit, offset) as Record<string, unknown>[];
|
||||
|
||||
return {
|
||||
sessions: rows.map(rowToAgentSessionRecord),
|
||||
total,
|
||||
};
|
||||
}
|
||||
|
||||
export function getAgentSessionById(
|
||||
db: SqliteAdapter,
|
||||
id: string,
|
||||
apiKeyId?: string
|
||||
): AgentSessionRecord | null {
|
||||
const query = apiKeyId
|
||||
? "SELECT * FROM agent_sessions WHERE id = ? AND api_key_id = ?"
|
||||
: "SELECT * FROM agent_sessions WHERE id = ?";
|
||||
const params = apiKeyId ? [id, apiKeyId] : [id];
|
||||
const row = db.prepare(query).get(...params) as Record<string, unknown> | undefined;
|
||||
return row ? rowToAgentSessionRecord(row) : null;
|
||||
}
|
||||
|
||||
export function getAgentSessionRecentUsage(
|
||||
db: SqliteAdapter,
|
||||
sessionId: string,
|
||||
limit = 50
|
||||
): AgentSessionRecentUsage[] {
|
||||
const boundedLimit = Math.max(1, Math.min(limit, 100));
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT id, timestamp, provider, model, tokens_input, tokens_output,
|
||||
tokens_cache_read, tokens_cache_creation, tokens_reasoning,
|
||||
latency_ms, ttft_ms, status, success, connection_id
|
||||
FROM usage_history
|
||||
WHERE agent_session_id = ?
|
||||
ORDER BY timestamp DESC, id DESC
|
||||
LIMIT ?`
|
||||
)
|
||||
.all(sessionId, boundedLimit) as Record<string, unknown>[];
|
||||
|
||||
return rows.map((row) => {
|
||||
const input = Number(row.tokens_input ?? 0);
|
||||
const cacheRead = Number(row.tokens_cache_read ?? 0);
|
||||
const cacheCreation = Number(row.tokens_cache_creation ?? 0);
|
||||
return {
|
||||
id: Number(row.id),
|
||||
timestamp: String(row.timestamp),
|
||||
provider: typeof row.provider === "string" ? row.provider : null,
|
||||
model: typeof row.model === "string" ? row.model : null,
|
||||
tokens: {
|
||||
input,
|
||||
output: Number(row.tokens_output ?? 0),
|
||||
cacheRead,
|
||||
cacheCreation,
|
||||
reasoning: Number(row.tokens_reasoning ?? 0),
|
||||
uncachedInput: uncachedInput(input, cacheRead, cacheCreation),
|
||||
},
|
||||
latencyMs: Number(row.latency_ms ?? 0),
|
||||
ttftMs: Number(row.ttft_ms ?? 0),
|
||||
status: typeof row.status === "string" ? row.status : null,
|
||||
success: row.success === 1 || row.success === true,
|
||||
connectionId: typeof row.connection_id === "string" ? row.connection_id : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -438,6 +438,97 @@ export async function buildApiKeySelfServiceStatus(
|
||||
};
|
||||
}
|
||||
|
||||
export interface SelfServiceSessionsQuery {
|
||||
project?: string | null;
|
||||
client?: string | null;
|
||||
clientSessionId?: string | null;
|
||||
from?: string | null;
|
||||
to?: string | null;
|
||||
sort?: "lastSeen" | "firstSeen" | "requests" | "tokens" | "cost";
|
||||
order?: "asc" | "desc";
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
export async function buildApiKeySelfServiceSessions(
|
||||
metadata: { id: string; scopes: string[] },
|
||||
query: SelfServiceSessionsQuery = {},
|
||||
deps: { getDbInstance?: () => unknown } = {}
|
||||
) {
|
||||
if (!hasSelfUsageScope(metadata.scopes)) {
|
||||
throw new Error("missing_self_usage_scope");
|
||||
}
|
||||
|
||||
const { getDbInstance: defaultGetDbInstance } = await import("../db/core");
|
||||
const db = (
|
||||
deps.getDbInstance ? deps.getDbInstance() : defaultGetDbInstance()
|
||||
) as import("../db/adapters/types").SqliteAdapter;
|
||||
const { listAgentSessions } = await import("../db/agentSessions");
|
||||
|
||||
const allowConnections = hasSelfAccountQuotaScope(metadata.scopes);
|
||||
|
||||
const { sessions, total } = listAgentSessions(db, {
|
||||
apiKeyId: metadata.id,
|
||||
projectName: query.project || undefined,
|
||||
client: query.client || undefined,
|
||||
clientSessionId: query.clientSessionId || undefined,
|
||||
from: query.from || undefined,
|
||||
to: query.to || undefined,
|
||||
sort: query.sort,
|
||||
order: query.order,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
|
||||
const sanitizedSessions = sessions.map(({ lastConnectionId, ...session }) => ({
|
||||
...session,
|
||||
...(allowConnections && { lastConnectionId }),
|
||||
}));
|
||||
|
||||
return {
|
||||
sessions: sanitizedSessions,
|
||||
total,
|
||||
limit: query.limit ?? 20,
|
||||
offset: query.offset ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildApiKeySelfServiceSessionDetail(
|
||||
metadata: { id: string; scopes: string[] },
|
||||
sessionId: string,
|
||||
deps: { getDbInstance?: () => unknown } = {}
|
||||
) {
|
||||
if (!hasSelfUsageScope(metadata.scopes)) {
|
||||
throw new Error("missing_self_usage_scope");
|
||||
}
|
||||
|
||||
const { getDbInstance: defaultGetDbInstance } = await import("../db/core");
|
||||
const db = (
|
||||
deps.getDbInstance ? deps.getDbInstance() : defaultGetDbInstance()
|
||||
) as import("../db/adapters/types").SqliteAdapter;
|
||||
const { getAgentSessionById, getAgentSessionRecentUsage } = await import("../db/agentSessions");
|
||||
|
||||
const session = getAgentSessionById(db, sessionId, metadata.id);
|
||||
if (!session) return null;
|
||||
|
||||
const allowConnections = hasSelfAccountQuotaScope(metadata.scopes);
|
||||
const recentUsage = getAgentSessionRecentUsage(db, sessionId, 50);
|
||||
|
||||
const { lastConnectionId, ...sanitizedSession } = session;
|
||||
const sanitizedUsage = recentUsage.map(({ connectionId, ...item }) => ({
|
||||
...item,
|
||||
...(allowConnections && { connectionId }),
|
||||
}));
|
||||
|
||||
return {
|
||||
session: {
|
||||
...sanitizedSession,
|
||||
...(allowConnections && { lastConnectionId }),
|
||||
},
|
||||
recentRequests: sanitizedUsage,
|
||||
};
|
||||
}
|
||||
|
||||
/** Providers of the connections a key can reach (admin self-service settings UI). */
|
||||
export async function listApiKeyReachableProviders(
|
||||
allowedConnections: string[],
|
||||
|
||||
@@ -13,6 +13,7 @@ process.env.DATA_DIR = TEST_DATA_DIR;
|
||||
|
||||
const core = await import("../../src/lib/db/core.ts");
|
||||
const settingsDb = await import("../../src/lib/db/settings.ts");
|
||||
const agentSessionsDb = await import("../../src/lib/db/agentSessions.ts");
|
||||
const usageHistory = await import("../../src/lib/usage/usageHistory.ts");
|
||||
|
||||
test.after(() => {
|
||||
@@ -191,6 +192,92 @@ test("traffic without an agent identity creates no session", async () => {
|
||||
assert.deepEqual(usageSessionIds("key-frank"), [null, null]);
|
||||
});
|
||||
|
||||
test("session token totals count cached input once, and the tokens sort follows them", async () => {
|
||||
// Stored input already includes cache reads and writes, so the total is input + output.
|
||||
await recordUsage({
|
||||
apiKeyId: "key-grace",
|
||||
agentContext: agentContext({ clientSessionId: "sess-grace-plain" }),
|
||||
timestamp: "2026-09-25T14:00:00.000Z",
|
||||
tokens: { input: 1000, output: 500, cacheRead: 0, cacheCreation: 0 },
|
||||
});
|
||||
await recordUsage({
|
||||
apiKeyId: "key-grace",
|
||||
agentContext: agentContext({ clientSessionId: "sess-grace-cached" }),
|
||||
timestamp: "2026-09-25T14:01:00.000Z",
|
||||
tokens: { input: 1200, output: 100, cacheRead: 900, cacheCreation: 200 },
|
||||
});
|
||||
|
||||
const db = core.getDbInstance();
|
||||
const byTokens = (order: "asc" | "desc") =>
|
||||
agentSessionsDb
|
||||
.listAgentSessions(db, { apiKeyId: "key-grace", sort: "tokens", order })
|
||||
.sessions.map((session) => [session.clientSessionId, session.tokens.total]);
|
||||
|
||||
assert.deepEqual(byTokens("desc"), [
|
||||
["sess-grace-plain", 1500],
|
||||
["sess-grace-cached", 1300],
|
||||
]);
|
||||
assert.deepEqual(byTokens("asc"), [
|
||||
["sess-grace-cached", 1300],
|
||||
["sess-grace-plain", 1500],
|
||||
]);
|
||||
});
|
||||
|
||||
test("the uncached input is input minus cache reads and writes, clamped at 0 and never corrected", async () => {
|
||||
// Stored input includes cache reads and writes. Three one-request sessions probe the boundary.
|
||||
const cases = [
|
||||
{
|
||||
id: "sess-ivan-normal",
|
||||
tokens: { input: 10000, output: 50, cacheRead: 9000, cacheCreation: 900 },
|
||||
},
|
||||
{
|
||||
id: "sess-ivan-equal",
|
||||
tokens: { input: 9900, output: 50, cacheRead: 9000, cacheCreation: 900 },
|
||||
},
|
||||
// A row recorded without its cache (before the usage extractor fix) is not guessed at: the
|
||||
// uncached input clamps to 0 and the stored input and total stay as recorded.
|
||||
{
|
||||
id: "sess-ivan-short",
|
||||
tokens: { input: 100, output: 50, cacheRead: 9000, cacheCreation: 900 },
|
||||
},
|
||||
];
|
||||
for (const [index, { id, tokens }] of cases.entries()) {
|
||||
await recordUsage({
|
||||
apiKeyId: "key-ivan",
|
||||
agentContext: agentContext({ clientSessionId: id }),
|
||||
timestamp: `2026-09-25T15:0${index}:00.000Z`,
|
||||
tokens,
|
||||
});
|
||||
}
|
||||
|
||||
const db = core.getDbInstance();
|
||||
const sessions = agentSessionsDb.listAgentSessions(db, { apiKeyId: "key-ivan", limit: 10 });
|
||||
const byClientId = new Map(sessions.sessions.map((s) => [s.clientSessionId, s]));
|
||||
const split = (id: string) => {
|
||||
const { input, uncachedInput, total } = byClientId.get(id)!.tokens;
|
||||
return { input, uncachedInput, total };
|
||||
};
|
||||
assert.deepEqual(split("sess-ivan-normal"), { input: 10000, uncachedInput: 100, total: 10050 });
|
||||
assert.deepEqual(split("sess-ivan-equal"), { input: 9900, uncachedInput: 0, total: 9950 });
|
||||
assert.deepEqual(split("sess-ivan-short"), { input: 100, uncachedInput: 0, total: 150 });
|
||||
|
||||
// Each request carries the same split, so the request rows add up to the session.
|
||||
const normal = byClientId.get("sess-ivan-normal")!;
|
||||
const [request] = agentSessionsDb.getAgentSessionRecentUsage(db, normal.id);
|
||||
assert.deepEqual(request.tokens, {
|
||||
input: 10000,
|
||||
uncachedInput: 100,
|
||||
cacheRead: 9000,
|
||||
cacheCreation: 900,
|
||||
output: 50,
|
||||
reasoning: 0,
|
||||
});
|
||||
const short = byClientId.get("sess-ivan-short")!;
|
||||
const [shortRequest] = agentSessionsDb.getAgentSessionRecentUsage(db, short.id);
|
||||
assert.equal(shortRequest.tokens.input, 100);
|
||||
assert.equal(shortRequest.tokens.uncachedInput, 0);
|
||||
});
|
||||
|
||||
test("a failing agent-session write never drops the usage_history row", async () => {
|
||||
const db = core.getDbInstance();
|
||||
// Simulate agent_sessions being unavailable (missing table / failed migration).
|
||||
|
||||
475
tests/unit/api-key-self-service-sessions.test.ts
Normal file
475
tests/unit/api-key-self-service-sessions.test.ts
Normal file
@@ -0,0 +1,475 @@
|
||||
// Unit tests for API key self-service sessions endpoints:
|
||||
// GET /v1/me/sessions and GET /v1/me/sessions/[id].
|
||||
// Verifies filtering, pagination, sorting, privacy (connection stripping), and tenant isolation.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-self-sessions-"));
|
||||
process.env.DATA_DIR = TEST_DATA_DIR;
|
||||
process.env.API_KEY_SECRET = "test-secret-at-least-32-chars-long-0123456789";
|
||||
|
||||
const core = await import("../../src/lib/db/core.ts");
|
||||
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
|
||||
const agentSessionsDb = await import("../../src/lib/db/agentSessions.ts");
|
||||
const usageHistory = await import("../../src/lib/usage/usageHistory.ts");
|
||||
const { buildApiKeySelfServiceSessions, buildApiKeySelfServiceSessionDetail } =
|
||||
await import("../../src/lib/usage/apiKeySelfService.ts");
|
||||
const { GET: getSessionsRoute } = await import("../../src/app/api/v1/me/sessions/route.ts");
|
||||
const { GET: getSessionDetailRoute } =
|
||||
await import("../../src/app/api/v1/me/sessions/[id]/route.ts");
|
||||
const { SELF_USAGE_SCOPE, SELF_ACCOUNT_QUOTA_SCOPE } =
|
||||
await import("../../src/shared/constants/selfServiceScopes.ts");
|
||||
|
||||
test.after(() => {
|
||||
core.resetDbInstance();
|
||||
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
||||
});
|
||||
|
||||
let keyAliceToken = "";
|
||||
let keyAliceId = "";
|
||||
let _keyBobToken = "";
|
||||
let keyBobId = "";
|
||||
let keyNoScopeToken = "";
|
||||
let sessionAlice1 = "";
|
||||
let _sessionAlice2 = "";
|
||||
let sessionBob = "";
|
||||
|
||||
test.before(async () => {
|
||||
// Create API keys
|
||||
const aliceKey = await apiKeysDb.createApiKey("Alice Key", "test-machine", [SELF_USAGE_SCOPE]);
|
||||
keyAliceToken = aliceKey.key;
|
||||
keyAliceId = aliceKey.id;
|
||||
|
||||
const bobKey = await apiKeysDb.createApiKey("Bob Key", "test-machine", [SELF_USAGE_SCOPE]);
|
||||
_keyBobToken = bobKey.key;
|
||||
keyBobId = bobKey.id;
|
||||
|
||||
const noScopeKey = await apiKeysDb.createApiKey("No Scope Key", "test-machine", []);
|
||||
keyNoScopeToken = noScopeKey.key;
|
||||
|
||||
// Record sessions for Alice
|
||||
await usageHistory.saveRequestUsage({
|
||||
provider: "openai",
|
||||
model: "gpt-4o",
|
||||
tokens: { input: 100, output: 50 },
|
||||
success: true,
|
||||
latencyMs: 100,
|
||||
timestamp: "2026-09-25T10:00:00.000Z",
|
||||
connectionId: "conn-secret-1",
|
||||
apiKeyId: keyAliceId,
|
||||
apiKeyName: "Alice Key",
|
||||
agentContext: {
|
||||
client: "claude-code",
|
||||
clientSessionId: "alice-sess-1",
|
||||
projectName: "billing-api",
|
||||
projectRepo: "github.com/acme/billing",
|
||||
projectPath: "/home/alice/billing",
|
||||
projectSource: "path",
|
||||
gitBranch: "main",
|
||||
},
|
||||
});
|
||||
|
||||
await usageHistory.saveRequestUsage({
|
||||
provider: "anthropic",
|
||||
model: "claude-sonnet-5",
|
||||
tokens: { input: 500, output: 200 },
|
||||
success: true,
|
||||
latencyMs: 200,
|
||||
timestamp: "2026-09-25T11:00:00.000Z",
|
||||
connectionId: "conn-secret-2",
|
||||
apiKeyId: keyAliceId,
|
||||
apiKeyName: "Alice Key",
|
||||
agentContext: {
|
||||
client: "codex",
|
||||
clientSessionId: "alice-sess-2",
|
||||
projectName: "frontend",
|
||||
projectRepo: "github.com/acme/frontend",
|
||||
projectPath: "/home/alice/frontend",
|
||||
projectSource: "path",
|
||||
gitBranch: "feat/ui",
|
||||
},
|
||||
});
|
||||
|
||||
// Record session for Bob
|
||||
await usageHistory.saveRequestUsage({
|
||||
provider: "openai",
|
||||
model: "gpt-4o",
|
||||
tokens: { input: 50, output: 25 },
|
||||
success: true,
|
||||
latencyMs: 50,
|
||||
timestamp: "2026-09-25T12:00:00.000Z",
|
||||
connectionId: "conn-secret-bob",
|
||||
apiKeyId: keyBobId,
|
||||
apiKeyName: "Bob Key",
|
||||
agentContext: {
|
||||
client: "claude-code",
|
||||
clientSessionId: "bob-sess-1",
|
||||
projectName: "billing-api",
|
||||
projectRepo: "github.com/acme/billing",
|
||||
projectPath: "/home/bob/billing",
|
||||
projectSource: "path",
|
||||
gitBranch: "fix/bug",
|
||||
},
|
||||
});
|
||||
|
||||
const db = core.getDbInstance();
|
||||
const aliceSessions = agentSessionsDb.listAgentSessions(db, { apiKeyId: keyAliceId });
|
||||
sessionAlice1 = aliceSessions.sessions.find((s) => s.clientSessionId === "alice-sess-1")!.id;
|
||||
_sessionAlice2 = aliceSessions.sessions.find((s) => s.clientSessionId === "alice-sess-2")!.id;
|
||||
const bobSessions = agentSessionsDb.listAgentSessions(db, { apiKeyId: keyBobId });
|
||||
sessionBob = bobSessions.sessions[0].id;
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessions lists only calling key's sessions and strips connection IDs", async () => {
|
||||
const result = await buildApiKeySelfServiceSessions({
|
||||
id: keyAliceId,
|
||||
scopes: [SELF_USAGE_SCOPE],
|
||||
});
|
||||
|
||||
assert.equal(result.total, 2);
|
||||
assert.equal(result.sessions.length, 2);
|
||||
assert.ok(result.sessions.every((s) => s.apiKeyId === keyAliceId));
|
||||
|
||||
// Connection ID stripped without self:account-quota scope
|
||||
for (const s of result.sessions) {
|
||||
assert.equal("lastConnectionId" in s, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessions preserves connection IDs with self:account-quota scope", async () => {
|
||||
const result = await buildApiKeySelfServiceSessions({
|
||||
id: keyAliceId,
|
||||
scopes: [SELF_USAGE_SCOPE, SELF_ACCOUNT_QUOTA_SCOPE],
|
||||
});
|
||||
|
||||
assert.equal(result.total, 2);
|
||||
const s1 = result.sessions.find((s) => s.clientSessionId === "alice-sess-1");
|
||||
assert.ok(s1);
|
||||
assert.equal(s1.lastConnectionId, "conn-secret-1");
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessions filters by project and client", async () => {
|
||||
const byProject = await buildApiKeySelfServiceSessions(
|
||||
{ id: keyAliceId, scopes: [SELF_USAGE_SCOPE] },
|
||||
{ project: "billing-api" }
|
||||
);
|
||||
assert.equal(byProject.total, 1);
|
||||
assert.equal(byProject.sessions[0].projectName, "billing-api");
|
||||
|
||||
const byClient = await buildApiKeySelfServiceSessions(
|
||||
{ id: keyAliceId, scopes: [SELF_USAGE_SCOPE] },
|
||||
{ client: "codex" }
|
||||
);
|
||||
assert.equal(byClient.total, 1);
|
||||
assert.equal(byClient.sessions[0].client, "codex");
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessions throws without self:usage scope", async () => {
|
||||
await assert.rejects(
|
||||
() => buildApiKeySelfServiceSessions({ id: keyAliceId, scopes: [] }),
|
||||
/missing_self_usage_scope/
|
||||
);
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessionDetail returns session with recent requests", async () => {
|
||||
const detail = await buildApiKeySelfServiceSessionDetail(
|
||||
{ id: keyAliceId, scopes: [SELF_USAGE_SCOPE] },
|
||||
sessionAlice1
|
||||
);
|
||||
|
||||
assert.ok(detail);
|
||||
assert.equal(detail.session.id, sessionAlice1);
|
||||
assert.equal(detail.session.projectName, "billing-api");
|
||||
assert.equal("lastConnectionId" in detail.session, false);
|
||||
assert.ok(detail.recentRequests.length >= 1);
|
||||
assert.equal(detail.recentRequests[0].model, "gpt-4o");
|
||||
assert.equal("connectionId" in detail.recentRequests[0], false);
|
||||
});
|
||||
|
||||
test("buildApiKeySelfServiceSessionDetail refuses access to another key's session", async () => {
|
||||
const detail = await buildApiKeySelfServiceSessionDetail(
|
||||
{ id: keyAliceId, scopes: [SELF_USAGE_SCOPE] },
|
||||
sessionBob
|
||||
);
|
||||
assert.equal(detail, null);
|
||||
});
|
||||
|
||||
test("route GET /v1/me/sessions requires authentication and self:usage scope", async () => {
|
||||
// No auth header -> 401
|
||||
const resNoAuth = await getSessionsRoute(new Request("http://localhost/api/v1/me/sessions"));
|
||||
assert.equal(resNoAuth.status, 401);
|
||||
|
||||
// Missing scope -> 403
|
||||
const resNoScope = await getSessionsRoute(
|
||||
new Request("http://localhost/api/v1/me/sessions", {
|
||||
headers: { Authorization: `Bearer ${keyNoScopeToken}` },
|
||||
})
|
||||
);
|
||||
assert.equal(resNoScope.status, 403);
|
||||
});
|
||||
|
||||
test("route GET /v1/me/sessions validates query params and returns session list", async () => {
|
||||
// Bad limit -> 400
|
||||
const resBadLimit = await getSessionsRoute(
|
||||
new Request("http://localhost/api/v1/me/sessions?limit=500", {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
})
|
||||
);
|
||||
assert.equal(resBadLimit.status, 400);
|
||||
|
||||
// Valid query -> 200
|
||||
const resValid = await getSessionsRoute(
|
||||
new Request("http://localhost/api/v1/me/sessions?project=billing-api&limit=10", {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
})
|
||||
);
|
||||
assert.equal(resValid.status, 200);
|
||||
const data = await resValid.json();
|
||||
assert.equal(data.total, 1);
|
||||
assert.equal(data.sessions[0].projectName, "billing-api");
|
||||
});
|
||||
|
||||
test("route GET /v1/me/sessions/[id] returns detail or 404 for foreign session", async () => {
|
||||
// Valid own session -> 200
|
||||
const resOwn = await getSessionDetailRoute(
|
||||
new Request(`http://localhost/api/v1/me/sessions/${sessionAlice1}`, {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
}),
|
||||
{ params: Promise.resolve({ id: sessionAlice1 }) }
|
||||
);
|
||||
assert.equal(resOwn.status, 200);
|
||||
const data = await resOwn.json();
|
||||
assert.equal(data.session.id, sessionAlice1);
|
||||
assert.equal(data.recentRequests.length, 1);
|
||||
|
||||
// Foreign session -> 404
|
||||
const resForeign = await getSessionDetailRoute(
|
||||
new Request(`http://localhost/api/v1/me/sessions/${sessionBob}`, {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
}),
|
||||
{ params: Promise.resolve({ id: sessionBob }) }
|
||||
);
|
||||
assert.equal(resForeign.status, 404);
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions normalizes timezone offset in from/to query params to UTC", async () => {
|
||||
// Alice has sessions at 10:00Z and 11:00Z.
|
||||
// 13:30+03:00 is 10:30Z, so it should exclude 10:00Z and include 11:00Z.
|
||||
const req = new Request(
|
||||
"http://localhost:20128/v1/me/sessions?from=" + encodeURIComponent("2026-09-25T13:30:00+03:00"),
|
||||
{ headers: { Authorization: "Bearer " + keyAliceToken } }
|
||||
);
|
||||
const res = await getSessionsRoute(req);
|
||||
assert.equal(res.status, 200);
|
||||
const data = (await res.json()) as {
|
||||
total: number;
|
||||
sessions: Array<{ clientSessionId: string }>;
|
||||
};
|
||||
assert.equal(data.total, 1);
|
||||
assert.equal(data.sessions[0].clientSessionId, "alice-sess-2");
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions returns an explicit token split with cached input counted once", async () => {
|
||||
// Stored input includes cache reads and writes; the response spells out the uncached part.
|
||||
await usageHistory.saveRequestUsage({
|
||||
provider: "anthropic",
|
||||
model: "claude-sonnet-5",
|
||||
tokens: { input: 10000, output: 40, cacheRead: 9000, cacheCreation: 900 },
|
||||
success: true,
|
||||
latencyMs: 100,
|
||||
timestamp: "2026-09-25T16:00:00.000Z",
|
||||
apiKeyId: keyAliceId,
|
||||
apiKeyName: "Alice Key",
|
||||
agentContext: {
|
||||
client: "claude-code",
|
||||
clientSessionId: "alice-sess-cache",
|
||||
projectName: "cache-demo",
|
||||
projectRepo: null,
|
||||
projectPath: "/home/alice/cache-demo",
|
||||
projectSource: "path",
|
||||
gitBranch: "main",
|
||||
},
|
||||
});
|
||||
|
||||
const res = await getSessionsRoute(
|
||||
new Request("http://localhost/api/v1/me/sessions?project=cache-demo", {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
})
|
||||
);
|
||||
assert.equal(res.status, 200);
|
||||
const data = (await res.json()) as {
|
||||
sessions: Array<{ id: string; tokens: Record<string, number> }>;
|
||||
};
|
||||
assert.deepEqual(data.sessions[0].tokens, {
|
||||
input: 10000,
|
||||
uncachedInput: 100,
|
||||
cacheRead: 9000,
|
||||
cacheCreation: 900,
|
||||
output: 40,
|
||||
reasoning: 0,
|
||||
total: 10040,
|
||||
});
|
||||
|
||||
const detailRes = await getSessionDetailRoute(
|
||||
new Request(`http://localhost/api/v1/me/sessions/${data.sessions[0].id}`, {
|
||||
headers: { Authorization: `Bearer ${keyAliceToken}` },
|
||||
}),
|
||||
{ params: Promise.resolve({ id: data.sessions[0].id }) }
|
||||
);
|
||||
const detail = (await detailRes.json()) as {
|
||||
recentRequests: Array<{ tokens: Record<string, number> }>;
|
||||
};
|
||||
assert.deepEqual(detail.recentRequests[0].tokens, {
|
||||
input: 10000,
|
||||
uncachedInput: 100,
|
||||
cacheRead: 9000,
|
||||
cacheCreation: 900,
|
||||
output: 40,
|
||||
reasoning: 0,
|
||||
});
|
||||
});
|
||||
|
||||
// clientSessionId filter. Carol and Dave both use the client session id "shared-sess", so the
|
||||
// filter has to stay scoped to the calling key even when the id itself collides.
|
||||
let keyCarolToken = "";
|
||||
let keyCarolId = "";
|
||||
let keyDaveToken = "";
|
||||
let keyDaveId = "";
|
||||
|
||||
async function recordClientSession(
|
||||
apiKey: { id: string; name: string },
|
||||
clientSessionId: string,
|
||||
timestamp: string
|
||||
) {
|
||||
await usageHistory.saveRequestUsage({
|
||||
provider: "openai",
|
||||
model: "gpt-4o",
|
||||
tokens: { input: 10, output: 5 },
|
||||
success: true,
|
||||
latencyMs: 10,
|
||||
timestamp,
|
||||
apiKeyId: apiKey.id,
|
||||
apiKeyName: apiKey.name,
|
||||
agentContext: {
|
||||
client: "claude-code",
|
||||
clientSessionId,
|
||||
projectName: "client-filter",
|
||||
projectRepo: null,
|
||||
projectPath: "/home/dev/client-filter",
|
||||
projectSource: "path",
|
||||
gitBranch: "main",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function listSessionsAs(token: string, query: string) {
|
||||
return getSessionsRoute(
|
||||
new Request(`http://localhost/api/v1/me/sessions?${query}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
type SessionListBody = {
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
sessions: Array<{ id: string; apiKeyId: string; clientSessionId: string }>;
|
||||
};
|
||||
|
||||
test.before(async () => {
|
||||
const carol = await apiKeysDb.createApiKey("Carol Key", "test-machine", [SELF_USAGE_SCOPE]);
|
||||
keyCarolToken = carol.key;
|
||||
keyCarolId = carol.id;
|
||||
const dave = await apiKeysDb.createApiKey("Dave Key", "test-machine", [SELF_USAGE_SCOPE]);
|
||||
keyDaveToken = dave.key;
|
||||
keyDaveId = dave.id;
|
||||
|
||||
const carolKey = { id: keyCarolId, name: "Carol Key" };
|
||||
const daveKey = { id: keyDaveId, name: "Dave Key" };
|
||||
await recordClientSession(carolKey, "shared-sess", "2026-09-26T10:00:00.000Z");
|
||||
await recordClientSession(carolKey, "carol-only", "2026-09-26T10:05:00.000Z");
|
||||
await recordClientSession(daveKey, "shared-sess", "2026-09-26T10:10:00.000Z");
|
||||
await recordClientSession(daveKey, "dave-only", "2026-09-26T10:15:00.000Z");
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions?clientSessionId returns the calling key's session with that id", async () => {
|
||||
const res = await listSessionsAs(keyCarolToken, "clientSessionId=carol-only");
|
||||
assert.equal(res.status, 200);
|
||||
const data = (await res.json()) as SessionListBody;
|
||||
assert.equal(data.total, 1);
|
||||
assert.equal(data.sessions.length, 1);
|
||||
assert.equal(data.sessions[0].clientSessionId, "carol-only");
|
||||
assert.equal(data.sessions[0].apiKeyId, keyCarolId);
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions?clientSessionId returns an empty list when nothing matches", async () => {
|
||||
const res = await listSessionsAs(keyCarolToken, "clientSessionId=unknown-sess");
|
||||
assert.equal(res.status, 200);
|
||||
const data = (await res.json()) as SessionListBody;
|
||||
assert.equal(data.total, 0);
|
||||
assert.deepEqual(data.sessions, []);
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions?clientSessionId never returns another key's session", async () => {
|
||||
const foreign = await listSessionsAs(keyCarolToken, "clientSessionId=dave-only");
|
||||
const foreignData = (await foreign.json()) as SessionListBody;
|
||||
assert.equal(foreignData.total, 0);
|
||||
assert.deepEqual(foreignData.sessions, []);
|
||||
|
||||
const carolShared = (await (
|
||||
await listSessionsAs(keyCarolToken, "clientSessionId=shared-sess")
|
||||
).json()) as SessionListBody;
|
||||
const daveShared = (await (
|
||||
await listSessionsAs(keyDaveToken, "clientSessionId=shared-sess")
|
||||
).json()) as SessionListBody;
|
||||
assert.equal(carolShared.total, 1);
|
||||
assert.equal(carolShared.sessions[0].apiKeyId, keyCarolId);
|
||||
assert.equal(daveShared.total, 1);
|
||||
assert.equal(daveShared.sessions[0].apiKeyId, keyDaveId);
|
||||
assert.notEqual(carolShared.sessions[0].id, daveShared.sessions[0].id);
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions validates clientSessionId", async () => {
|
||||
for (const value of ["", "%20%20", "x".repeat(129)]) {
|
||||
const res = await listSessionsAs(keyCarolToken, `clientSessionId=${value}`);
|
||||
assert.equal(res.status, 400, `clientSessionId=${value.slice(0, 20)}`);
|
||||
const body = (await res.json()) as { error: string };
|
||||
assert.equal(body.error, "Invalid query parameters");
|
||||
}
|
||||
|
||||
const longest = await listSessionsAs(keyCarolToken, `clientSessionId=${"x".repeat(128)}`);
|
||||
assert.equal(longest.status, 200);
|
||||
|
||||
const padded = await listSessionsAs(keyCarolToken, "clientSessionId=%20carol-only%20");
|
||||
const paddedData = (await padded.json()) as SessionListBody;
|
||||
assert.equal(paddedData.total, 1);
|
||||
assert.equal(paddedData.sessions[0].clientSessionId, "carol-only");
|
||||
});
|
||||
|
||||
test("GET /v1/me/sessions?clientSessionId keeps limit and offset", async () => {
|
||||
const firstPage = (await (
|
||||
await listSessionsAs(keyCarolToken, "clientSessionId=shared-sess&limit=1&offset=0")
|
||||
).json()) as SessionListBody;
|
||||
assert.equal(firstPage.total, 1);
|
||||
assert.equal(firstPage.sessions.length, 1);
|
||||
assert.equal(firstPage.limit, 1);
|
||||
|
||||
const pastEnd = (await (
|
||||
await listSessionsAs(keyCarolToken, "clientSessionId=shared-sess&limit=1&offset=1")
|
||||
).json()) as SessionListBody;
|
||||
assert.equal(pastEnd.total, 1);
|
||||
assert.deepEqual(pastEnd.sessions, []);
|
||||
assert.equal(pastEnd.offset, 1);
|
||||
});
|
||||
|
||||
test("listAgentSessions without an api key filters by client session id across keys", () => {
|
||||
const { sessions, total } = agentSessionsDb.listAgentSessions(core.getDbInstance(), {
|
||||
clientSessionId: "shared-sess",
|
||||
});
|
||||
assert.equal(total, 2);
|
||||
assert.deepEqual(sessions.map((s) => s.apiKeyId).sort(), [keyCarolId, keyDaveId].sort());
|
||||
});
|
||||
Reference in New Issue
Block a user