Skip to content

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

feat: session metadata on create/update/read (#544)

Srajan Asthanab6540522a5fc
diff --git a/.changeset/session-metadata.md b/.changeset/session-metadata.md
new file mode 100644
index 000000000..22603d358
--- /dev/null
+++ b/.changeset/session-metadata.md
@@ -0,0 +1,7 @@
+---
+"@truefoundry/trueforge": patch
+"@truefoundry/trueforge-core": patch
+"@truefoundry/trueforge-sdk": patch
+---
+
+Add caller-owned session `metadata` (`Record<string, string>` with size limits) on create, update, and read. Persist as a new `session.metadata` jsonb column; leave session `custom` unchanged.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index c3968209a..bca5ab445 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1054,6 +1054,9 @@
"properties": {
"agent": {
"$ref": "#/components/schemas/CreateSessionAgent"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
}
},
"required": [
@@ -3189,6 +3192,9 @@
"description": "Unique session id.",
"type": "string"
},
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
+ },
"metrics": {
"$ref": "#/components/schemas/SessionMetrics"
},
@@ -3211,7 +3217,8 @@
"created_by",
"created_at",
"updated_at",
- "metrics"
+ "metrics",
+ "metadata"
],
"type": "object"
},
@@ -3375,6 +3382,15 @@
],
"type": "object"
},
+ "SessionMetadata": {
+ "additionalProperties": {
+ "description": "Metadata value; at most 128 characters.",
+ "maxLength": 128,
+ "type": "string"
+ },
+ "description": "Caller-owned session metadata",
+ "type": "object"
+ },
"SessionMetrics": {
"additionalProperties": false,
"description": "Rolled-up cost, duration, and turn counters for a session.",
@@ -4632,6 +4648,9 @@
"properties": {
"agent": {
"$ref": "#/components/schemas/SessionAgentSpecBody"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
}
},
"type": "object"
diff --git a/docs/openapi.json b/docs/openapi.json
index c3968209a..bca5ab445 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1054,6 +1054,9 @@
"properties": {
"agent": {
"$ref": "#/components/schemas/CreateSessionAgent"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
}
},
"required": [
@@ -3189,6 +3192,9 @@
"description": "Unique session id.",
"type": "string"
},
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
+ },
"metrics": {
"$ref": "#/components/schemas/SessionMetrics"
},
@@ -3211,7 +3217,8 @@
"created_by",
"created_at",
"updated_at",
- "metrics"
+ "metrics",
+ "metadata"
],
"type": "object"
},
@@ -3375,6 +3382,15 @@
],
"type": "object"
},
+ "SessionMetadata": {
+ "additionalProperties": {
+ "description": "Metadata value; at most 128 characters.",
+ "maxLength": 128,
+ "type": "string"
+ },
+ "description": "Caller-owned session metadata",
+ "type": "object"
+ },
"SessionMetrics": {
"additionalProperties": false,
"description": "Rolled-up cost, duration, and turn counters for a session.",
@@ -4632,6 +4648,9 @@
"properties": {
"agent": {
"$ref": "#/components/schemas/SessionAgentSpecBody"
+ },
+ "metadata": {
+ "$ref": "#/components/schemas/SessionMetadata"
}
},
"type": "object"
diff --git a/packages/trueforge-core/src/agent-session/SessionHandle.ts b/packages/trueforge-core/src/agent-session/SessionHandle.ts
index 23acbc0e7..1aad0297a 100644
--- a/packages/trueforge-core/src/agent-session/SessionHandle.ts
+++ b/packages/trueforge-core/src/agent-session/SessionHandle.ts
@@ -147,6 +147,10 @@ export class SessionHandle<
return this.session.custom;
}
+ get metadata(): SessionRecord<TSessionCustom>['metadata'] {
+ return this.session.metadata;
+ }
+
get record(): SessionRecord<TSessionCustom> {
return this.session;
}
diff --git a/packages/trueforge-core/src/agent-session/Sessions.ts b/packages/trueforge-core/src/agent-session/Sessions.ts
index 5d94a8b86..8eed66638 100644
--- a/packages/trueforge-core/src/agent-session/Sessions.ts
+++ b/packages/trueforge-core/src/agent-session/Sessions.ts
@@ -12,8 +12,12 @@ import type {
} from './store/ISessionStore';
import { SessionExternalIdConflictError } from './store/SessionStoreErrors';
-export type SessionsCreateInput<TSessionCustom extends object> = Omit<CreateSessionInput<TSessionCustom>, 'custom'> & {
+export type SessionsCreateInput<TSessionCustom extends object> = Omit<
+ CreateSessionInput<TSessionCustom>,
+ 'custom' | 'metadata'
+> & {
custom?: TSessionCustom | undefined;
+ metadata?: CreateSessionInput<TSessionCustom>['metadata'] | undefined;
};
export class Sessions<
@@ -33,6 +37,7 @@ export class Sessions<
await this.store.createSession({
...input,
custom: input.custom ?? null,
+ metadata: input.metadata ?? {},
});
const record = await this.store.getSession({
tenant_id: input.tenant_id,
diff --git a/packages/trueforge-core/src/agent-session/index.ts b/packages/trueforge-core/src/agent-session/index.ts
index 5da6e8278..f515621c5 100644
--- a/packages/trueforge-core/src/agent-session/index.ts
+++ b/packages/trueforge-core/src/agent-session/index.ts
@@ -21,8 +21,8 @@ export {
} from './schemas/turn';
export type { TerminalTurnState, Turn, TurnInputItem, TurnMetrics, TurnState } from './schemas/turn';
-export { SessionMetricsSchema, SessionSchema } from './schemas/session';
-export type { Session, SessionAgent, SessionMetrics } from './schemas/session';
+export { SessionMetadataSchema, SessionMetricsSchema, SessionSchema } from './schemas/session';
+export type { Session, SessionAgent, SessionMetadata, SessionMetrics } from './schemas/session';
export {
EventType,
diff --git a/packages/trueforge-core/src/agent-session/models/SessionRecord.ts b/packages/trueforge-core/src/agent-session/models/SessionRecord.ts
index 21497510b..0d48d08d5 100644
--- a/packages/trueforge-core/src/agent-session/models/SessionRecord.ts
+++ b/packages/trueforge-core/src/agent-session/models/SessionRecord.ts
@@ -1,4 +1,4 @@
-import type { SessionAgent, SessionMetrics } from '../schemas/session';
+import type { SessionAgent, SessionMetadata, SessionMetrics } from '../schemas/session';
/**
* Session persistence record. Agent binding is a single discriminated `agent`
@@ -36,5 +36,6 @@ export interface SessionRecord<TCustom extends object = Record<string, never>> {
*/
last_activity_timestamp_ms: number;
metrics: SessionMetrics;
+ metadata: SessionMetadata;
custom: TCustom | null;
}
diff --git a/packages/trueforge-core/src/agent-session/schemas/session.ts b/packages/trueforge-core/src/agent-session/schemas/session.ts
index 087cd0fd0..843736a58 100644
--- a/packages/trueforge-core/src/agent-session/schemas/session.ts
+++ b/packages/trueforge-core/src/agent-session/schemas/session.ts
@@ -5,6 +5,33 @@
import { z } from '@hono/zod-openapi';
import { AgentSpecSchema } from './agentSpec';
+/** Max key length for session metadata (aligned with LLM gateway HeaderMetadata). */
+const SESSION_METADATA_MAX_KEY_LENGTH = 32;
+/** Max value length for session metadata (aligned with LLM gateway HeaderMetadata). */
+const SESSION_METADATA_MAX_VALUE_LENGTH = 128;
+/** Max number of keys in session metadata. */
+const SESSION_METADATA_MAX_KEYS = 50;
+
+export const SessionMetadataSchema = z
+ .record(
+ z
+ .string()
+ .min(1)
+ .max(SESSION_METADATA_MAX_KEY_LENGTH)
+ .describe(`Metadata key; 1–${String(SESSION_METADATA_MAX_KEY_LENGTH)} characters.`),
+ z
+ .string()
+ .max(SESSION_METADATA_MAX_VALUE_LENGTH)
+ .describe(`Metadata value; at most ${String(SESSION_METADATA_MAX_VALUE_LENGTH)} characters.`),
+ )
+ .refine(m => Object.keys(m).length <= SESSION_METADATA_MAX_KEYS, {
+ message: `at most ${String(SESSION_METADATA_MAX_KEYS)} metadata keys`,
+ })
+ .describe('Caller-owned session metadata')
+ .openapi('SessionMetadata');
+
+export type SessionMetadata = z.infer<typeof SessionMetadataSchema>;
+
export const SessionMetricsSchema = z
.object({
total_cost_in_usd: z.number().nonnegative(),
@@ -51,6 +78,7 @@ export const SessionSchema = z
created_at: z.string().describe('ISO 8601 creation timestamp.'),
updated_at: z.string().describe('ISO 8601 last-update timestamp.'),
metrics: SessionMetricsSchema,
+ metadata: SessionMetadataSchema,
})
.openapi('Session');
diff --git a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts b/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
index 41bd1b60a..a19ddbcce 100644
--- a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
+++ b/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
@@ -19,7 +19,7 @@ import type { CancellationReason, TerminalTurnState } from '../schemas/turn';
*/
export type CreateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<
SessionRecord<TSessionCustom>,
- 'tenant_id' | 'session_id' | 'agent' | 'created_by' | 'external_id'
+ 'tenant_id' | 'session_id' | 'agent' | 'created_by' | 'external_id' | 'metadata'
> & {
custom: TSessionCustom | null;
};
@@ -27,6 +27,7 @@ export type CreateSessionInput<TSessionCustom extends object = Record<string, ne
/**
* PATCH fields for an existing session; `undefined` fields are left unchanged.
* `agent` may be set only on inline sessions, and only as an inline arm (`{ type: 'inline', spec }`).
+ * `metadata` when set fully replaces the stored map (`{}` clears).
*/
export type UpdateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<
SessionRecord<TSessionCustom>,
@@ -34,6 +35,7 @@ export type UpdateSessionInput<TSessionCustom extends object = Record<string, ne
> & {
agent: Extract<SessionRecord<TSessionCustom>['agent'], { type: 'inline' }> | undefined;
title: SessionRecord<TSessionCustom>['title'] | undefined;
+ metadata: SessionRecord<TSessionCustom>['metadata'] | undefined;
};
export interface GetSessionInput {
@@ -244,6 +246,7 @@ export interface ISessionStore<
* PATCH semantics — update only the provided fields:
* - agent: replace inline binding (inline sessions only; reference → invariant error).
* - title: set/replace the session title.
+ * - metadata: full replace of the caller-owned string map when set.
* Bumps `last_activity_timestamp_ms` (= now) in the same update.
*/
updateSession(input: UpdateSessionInput<TSessionCustom>): Promise<void>;
diff --git a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
index 3dc0e0f56..85492b46e 100644
--- a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
+++ b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
@@ -200,6 +200,7 @@ export class InMemorySessionStore<
total_duration_ms: 0,
total_turns: 0,
},
+ metadata: deepCopy(input.metadata),
custom: input.custom !== null ? deepCopy(input.custom) : null,
};
this.sessions.set(key, { record, turnIds: [] });
@@ -249,6 +250,9 @@ export class InMemorySessionStore<
if (input.title !== undefined) {
stored.record.title = input.title;
}
+ if (input.metadata !== undefined) {
+ stored.record.metadata = deepCopy(input.metadata);
+ }
const now = Date.now();
stored.record.updated_at = new Date(now);
stored.record.last_activity_timestamp_ms = now;
diff --git a/packages/trueforge-core/tests/agent-session/sessions.test.ts b/packages/trueforge-core/tests/agent-session/sessions.test.ts
index 0463110c8..1961de7e1 100644
--- a/packages/trueforge-core/tests/agent-session/sessions.test.ts
+++ b/packages/trueforge-core/tests/agent-session/sessions.test.ts
@@ -9,6 +9,41 @@ import { makeAgentSpec, makeTestResolver, mintTestTurnId } from './testHelpers';
describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
const tenant = 'tenant-1';
+ it('create/get persists metadata', async () => {
+ const store = new InMemorySessionStore();
+ const sessions = new Sessions({ sessionStore: store });
+ const created = await sessions.create({
+ tenant_id: tenant,
+ session_id: 's-meta',
+ created_by: 'user-1',
+ agent: { type: 'inline', spec: makeAgentSpec({ instructions: 'meta' }) },
+ metadata: { env: 'test' },
+ external_id: null,
+ });
+ expect(created.metadata).toEqual({ env: 'test' });
+
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: 's-meta',
+ agent: undefined,
+ title: undefined,
+ metadata: { env: 'prod' },
+ });
+ const afterReplace = await sessions.get({ tenant_id: tenant, session_id: 's-meta' });
+ expect(afterReplace?.metadata).toEqual({ env: 'prod' });
+
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: 's-meta',
+ agent: undefined,
+ title: 't',
+ metadata: undefined,
+ });
+ const afterOmit = await sessions.get({ tenant_id: tenant, session_id: 's-meta' });
+ expect(afterOmit?.record.title).toBe('t');
+ expect(afterOmit?.metadata).toEqual({ env: 'prod' });
+ });
+
it('create/get persists an inline value-agent session', async () => {
const store = new InMemorySessionStore<{ tag: string }>();
const sessions = new Sessions<{ tag: string }>({ sessionStore: store });
@@ -25,6 +60,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
spec: expect.objectContaining({ instructions: 'hydrate-me' }),
});
expect(created.custom).toEqual({ tag: 'a' });
+ expect(created.metadata).toEqual({});
const loaded = await sessions.get({ tenant_id: tenant, session_id: 's1' });
expect(loaded?.agent).toEqual({
diff --git a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
index 6633e3fa7..09be27fd7 100644
--- a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
+++ b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
@@ -86,6 +86,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: agentSpec },
custom: null,
+ metadata: {},
external_id: null,
});
}
@@ -192,6 +193,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: '[email protected]',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
const session = mustGet(await store.getSession({ tenant_id: tenant, session_id: 'created-by-session' }));
@@ -219,6 +221,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-abc', name: null },
custom: null,
+ metadata: {},
external_id: null,
});
await seedSession(store);
@@ -247,6 +250,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-abc', name: null },
custom: null,
+ metadata: {},
external_id: null,
});
@@ -256,6 +260,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: 'named-1',
agent: { type: 'inline', spec: makeAgentSpec({ instructions: 'nope' }) },
title: undefined,
+ metadata: undefined,
}),
).rejects.toBeInstanceOf(SessionStoreInvariantError);
});
@@ -280,6 +285,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: sessionId,
agent: { type: 'inline', spec: nextSpec },
title: 'Hello',
+ metadata: undefined,
});
const after = await store.getSession({ tenant_id: tenant, session_id: sessionId });
expect(mustGet(after).agent).toMatchObject({
@@ -290,6 +296,66 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);
});
+ it('createSession persists metadata for getSession', async () => {
+ const store = createStore();
+ const metadata = { env: 'prod', ticket: 'T-1' };
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ created_by: 'user-1',
+ agent: { type: 'inline', spec: makeAgentSpec() },
+ custom: null,
+ metadata,
+ external_id: null,
+ });
+
+ expect(mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId })).metadata).toEqual(metadata);
+ });
+
+ it('updateSession replaces metadata when set and leaves it when omitted', async () => {
+ const store = createStore();
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ created_by: 'user-1',
+ agent: { type: 'inline', spec: makeAgentSpec() },
+ custom: null,
+ metadata: { a: '1' },
+ external_id: null,
+ });
+
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ agent: undefined,
+ title: undefined,
+ metadata: { b: '2' },
+ });
+ expect(mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId })).metadata).toEqual({
+ b: '2',
+ });
+
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ agent: undefined,
+ title: 'keep-meta',
+ metadata: undefined,
+ });
+ const afterOmit = mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId }));
+ expect(afterOmit.title).toBe('keep-meta');
+ expect(afterOmit.metadata).toEqual({ b: '2' });
+
+ await store.updateSession({
+ tenant_id: tenant,
+ session_id: sessionId,
+ agent: undefined,
+ title: undefined,
+ metadata: {},
+ });
+ expect(mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId })).metadata).toEqual({});
+ });
+
it('createSession conflict when session already exists', async () => {
const store = createStore();
await seedSession(store);
@@ -306,6 +372,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
}),
).rejects.toBeInstanceOf(SessionStoreConflictError);
@@ -326,6 +393,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: 'run-1',
});
const byId = await store.getSession({ tenant_id: tenant, session_id: sessionId });
@@ -344,6 +412,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: 'shared-key',
});
// Specifically the external-id arm, not just any conflict: get-or-create
@@ -355,6 +424,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: 'shared-key',
}),
).rejects.toBeInstanceOf(SessionExternalIdConflictError);
@@ -365,6 +435,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: 'shared-key',
});
await store.createSession({
@@ -373,6 +444,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
await store.createSession({
@@ -381,6 +453,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
});
@@ -393,6 +466,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: 'run-1',
});
const first = await store.getSessionByExternalId({ tenant_id: tenant, external_id: 'run-1' });
@@ -412,6 +486,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
@@ -536,6 +611,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: sessionId,
agent: undefined,
title: 'new-title',
+ metadata: undefined,
}),
).rejects.toBeInstanceOf(SessionNotFoundError);
await expect(store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-2' }))).rejects.toBeInstanceOf(
@@ -595,6 +671,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
await store.createTurn(makeCreateTurnInput({ sessionId: nested, turnId: 'turn-1' }));
@@ -669,6 +746,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: missingSessionId,
agent: undefined,
title: 'new-title',
+ metadata: undefined,
}),
).rejects.toBeInstanceOf(SessionNotFoundError);
await expect(
@@ -724,6 +802,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
await new Promise(r => setTimeout(r, 2));
@@ -739,6 +818,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
@@ -833,6 +913,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: 'sa',
agent: undefined,
title: 'bumped',
+ metadata: undefined,
});
const listArgs = {
@@ -892,6 +973,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'alice',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
await store.createSession({
@@ -900,6 +982,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
created_by: 'bob',
agent: { type: 'inline', spec: makeAgentSpec() },
custom: null,
+ metadata: {},
external_id: null,
});
@@ -2031,6 +2114,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
session_id: sessionId,
agent: undefined,
title: jsonLooking,
+ metadata: undefined,
});
await store.createTurn(
makeCreateTurnInput({
diff --git a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts
index 043578697..44a0081eb 100644
--- a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts
@@ -12,4 +12,5 @@ import type * as TrueForge from "../../../../index.js";
*/
export interface CreateSessionRequest {
agent: TrueForge.CreateSessionAgent;
+ metadata?: TrueForge.SessionMetadata;
}
diff --git a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts
index cec02fa48..07a555dbd 100644
--- a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts
@@ -8,4 +8,5 @@ import type * as TrueForge from "../../../../index.js";
*/
export interface UpdateSessionRequest {
agent?: TrueForge.SessionAgentSpecBody;
+ metadata?: TrueForge.SessionMetadata;
}
diff --git a/packages/trueforge-sdk/src/api/types/Session.ts b/packages/trueforge-sdk/src/api/types/Session.ts
index cea66fa22..f6c10481d 100644
--- a/packages/trueforge-sdk/src/api/types/Session.ts
+++ b/packages/trueforge-sdk/src/api/types/Session.ts
@@ -10,6 +10,7 @@ export interface Session {
createdBy: string;
/** Unique session id. */
id: string;
+ metadata: TrueForge.SessionMetadata;
metrics: TrueForge.SessionMetrics;
/** Optional human-readable title; null until set. */
title: string | null;
diff --git a/packages/trueforge-sdk/src/api/types/SessionMetadata.ts b/packages/trueforge-sdk/src/api/types/SessionMetadata.ts
new file mode 100644
index 000000000..682b494c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/SessionMetadata.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * Caller-owned session metadata
+ */
+export type SessionMetadata = Record<string, string>;
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index c3101d56d..6e7605e40 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -156,6 +156,7 @@ export * from "./SessionAgentReference.js";
export * from "./SessionAgentSpecBody.js";
export * from "./SessionEvent.js";
export * from "./SessionEventItem.js";
+export * from "./SessionMetadata.js";
export * from "./SessionMetrics.js";
export * from "./SessionMetricsChart.js";
export * from "./SessionMetricsChartDataResponse.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts
index b347909ac..07c3d754f 100644
--- a/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts
@@ -4,16 +4,19 @@ import type * as TrueForge from "../../../../../api/index.js";
import * as core from "../../../../../core/index.js";
import type * as serializers from "../../../../index.js";
import { CreateSessionAgent } from "../../../../types/CreateSessionAgent.js";
+import { SessionMetadata } from "../../../../types/SessionMetadata.js";
export const CreateSessionRequest: core.serialization.Schema<
serializers.CreateSessionRequest.Raw,
TrueForge.CreateSessionRequest
> = core.serialization.object({
agent: CreateSessionAgent,
+ metadata: SessionMetadata.optional(),
});
export declare namespace CreateSessionRequest {
export interface Raw {
agent: CreateSessionAgent.Raw;
+ metadata?: SessionMetadata.Raw | null;
}
}
diff --git a/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts
index 4cbecfe69..baefd7753 100644
--- a/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts
@@ -4,16 +4,19 @@ import type * as TrueForge from "../../../../../api/index.js";
import * as core from "../../../../../core/index.js";
import type * as serializers from "../../../../index.js";
import { SessionAgentSpecBody } from "../../../../types/SessionAgentSpecBody.js";
+import { SessionMetadata } from "../../../../types/SessionMetadata.js";
export const UpdateSessionRequest: core.serialization.Schema<
serializers.UpdateSessionRequest.Raw,
TrueForge.UpdateSessionRequest
> = core.serialization.object({
agent: SessionAgentSpecBody.optional(),
+ metadata: SessionMetadata.optional(),
});
export declare namespace UpdateSessionRequest {
export interface Raw {
agent?: SessionAgentSpecBody.Raw | null;
+ metadata?: SessionMetadata.Raw | null;
}
}
diff --git a/packages/trueforge-sdk/src/serialization/types/Session.ts b/packages/trueforge-sdk/src/serialization/types/Session.ts
index cac861230..923f76f27 100644
--- a/packages/trueforge-sdk/src/serialization/types/Session.ts
+++ b/packages/trueforge-sdk/src/serialization/types/Session.ts
@@ -4,6 +4,7 @@ import type * as TrueForge from "../../api/index.js";
import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
import { SessionAgent } from "./SessionAgent.js";
+import { SessionMetadata } from "./SessionMetadata.js";
import { SessionMetrics } from "./SessionMetrics.js";
export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, TrueForge.Session> =
@@ -12,6 +13,7 @@ export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, T
createdAt: core.serialization.property("created_at", core.serialization.string()),
createdBy: core.serialization.property("created_by", core.serialization.string()),
id: core.serialization.string(),
+ metadata: SessionMetadata,
metrics: SessionMetrics,
title: core.serialization.string().nullable(),
updatedAt: core.serialization.property("updated_at", core.serialization.string()),
@@ -23,6 +25,7 @@ export declare namespace Session {
created_at: string;
created_by: string;
id: string;
+ metadata: SessionMetadata.Raw;
metrics: SessionMetrics.Raw;
title?: string | null;
updated_at: string;
diff --git a/packages/trueforge-sdk/src/serialization/types/SessionMetadata.ts b/packages/trueforge-sdk/src/serialization/types/SessionMetadata.ts
new file mode 100644
index 000000000..e0d13c56e
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/SessionMetadata.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const SessionMetadata: core.serialization.Schema<serializers.SessionMetadata.Raw, TrueForge.SessionMetadata> =
+ core.serialization.record(core.serialization.string(), core.serialization.string());
+
+export declare namespace SessionMetadata {
+ export type Raw = Record<string, string>;
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index c3101d56d..6e7605e40 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -156,6 +156,7 @@ export * from "./SessionAgentReference.js";
export * from "./SessionAgentSpecBody.js";
export * from "./SessionEvent.js";
export * from "./SessionEventItem.js";
+export * from "./SessionMetadata.js";
export * from "./SessionMetrics.js";
export * from "./SessionMetricsChart.js";
export * from "./SessionMetricsChartDataResponse.js";
diff --git a/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts b/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
index 65ec68a42..1938816ca 100644
--- a/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
+++ b/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
@@ -15,6 +15,7 @@ describe("SessionsClient", () => {
created_at: "created_at",
created_by: "created_by",
id: "id",
+ metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
title: "title",
updated_at: "updated_at",
@@ -49,6 +50,9 @@ describe("SessionsClient", () => {
createdAt: "created_at",
createdBy: "created_by",
id: "id",
+ metadata: {
+ key: "value",
+ },
metrics: {
totalCostInUsd: 1.1,
totalDurationMs: 1,
diff --git a/packages/trueforge-sdk/tests/wire/sessions.test.ts b/packages/trueforge-sdk/tests/wire/sessions.test.ts
index f76be0c4a..61c88dc19 100644
--- a/packages/trueforge-sdk/tests/wire/sessions.test.ts
+++ b/packages/trueforge-sdk/tests/wire/sessions.test.ts
@@ -16,6 +16,7 @@ describe("SessionsClient", () => {
created_at: "created_at",
created_by: "created_by",
id: "id",
+ metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
title: "title",
updated_at: "updated_at",
@@ -46,6 +47,9 @@ describe("SessionsClient", () => {
createdAt: "created_at",
createdBy: "created_by",
id: "id",
+ metadata: {
+ key: "value",
+ },
metrics: {
totalCostInUsd: 1.1,
totalDurationMs: 1,
@@ -92,6 +96,7 @@ describe("SessionsClient", () => {
created_at: "created_at",
created_by: "created_by",
id: "id",
+ metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
title: "title",
updated_at: "updated_at",
@@ -125,6 +130,9 @@ describe("SessionsClient", () => {
createdAt: "created_at",
createdBy: "created_by",
id: "id",
+ metadata: {
+ key: "value",
+ },
metrics: {
totalCostInUsd: 1.1,
totalDurationMs: 1,
@@ -218,6 +226,7 @@ describe("SessionsClient", () => {
created_at: "created_at",
created_by: "created_by",
id: "id",
+ metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
title: "title",
updated_at: "updated_at",
@@ -246,6 +255,9 @@ describe("SessionsClient", () => {
createdAt: "created_at",
createdBy: "created_by",
id: "id",
+ metadata: {
+ key: "value",
+ },
metrics: {
totalCostInUsd: 1.1,
totalDurationMs: 1,
@@ -334,6 +346,7 @@ describe("SessionsClient", () => {
created_at: "created_at",
created_by: "created_by",
id: "id",
+ metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
title: "title",
updated_at: "updated_at",
@@ -363,6 +376,9 @@ describe("SessionsClient", () => {
createdAt: "created_at",
createdBy: "created_by",
id: "id",
+ metadata: {
+ key: "value",
+ },
metrics: {
totalCostInUsd: 1.1,
totalDurationMs: 1,
diff --git a/packages/trueforge/src/apis/sessions.ts b/packages/trueforge/src/apis/sessions.ts
index f62695ba1..15204d93d 100644
--- a/packages/trueforge/src/apis/sessions.ts
+++ b/packages/trueforge/src/apis/sessions.ts
@@ -67,6 +67,7 @@ export function toWireSession(record: SessionRecord): Session {
created_at: record.created_at.toISOString(),
updated_at: record.updated_at.toISOString(),
metrics: record.metrics,
+ metadata: record.metadata,
};
}
@@ -305,6 +306,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
session_id: sessionId,
created_by: user.userRef,
agent: { type: 'reference', id: agent.id, name: agent.name },
+ metadata: body.metadata,
external_id: null,
});
return c.json({ data: toWireSession(session.record) }, 201);
@@ -324,6 +326,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
session_id: sessionId,
created_by: user.userRef,
agent: { type: 'inline', spec: body.agent.spec },
+ metadata: body.metadata,
external_id: null,
});
return c.json({ data: toWireSession(session.record) }, 201);
@@ -383,6 +386,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
session_id: sessionId,
agent: body.agent === undefined ? undefined : { type: 'inline', spec: body.agent.spec },
title: undefined,
+ metadata: body.metadata,
});
} catch (error) {
if (error instanceof SessionStoreNotFoundError) {
diff --git a/packages/trueforge/src/db/postgres/migrations/20260902_000001_session_metadata.ts b/packages/trueforge/src/db/postgres/migrations/20260902_000001_session_metadata.ts
new file mode 100644
index 000000000..d310c0273
--- /dev/null
+++ b/packages/trueforge/src/db/postgres/migrations/20260902_000001_session_metadata.ts
@@ -0,0 +1,18 @@
+import { sql, type Kysely } from 'kysely';
+
+/**
+ * Caller-owned session metadata (`Record<string, string>`).
+ * Keeps `custom` for a later purpose; does not rename or drop it.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+ await db.schema
+ .alterTable('session')
+ .addColumn('metadata', 'jsonb', col => col.notNull().defaultTo(sql`'{}'::jsonb`))
+ .execute();
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+ await db.schema.alterTable('session').dropColumn('metadata').execute();
+}
diff --git a/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts b/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
index 6daba7963..c08821e83 100644
--- a/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
@@ -1,4 +1,5 @@
-import type { AgentSpec, SessionMetrics } from '@truefoundry/trueforge-core/agent-session';
+import type { AgentSpec, SessionMetadata, SessionMetrics } from '@truefoundry/trueforge-core/agent-session';
+import { SessionMetadataSchema } from '@truefoundry/trueforge-core/agent-session';
import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/models/SessionRecord';
import type {
CreateSessionInput,
@@ -42,6 +43,10 @@ function parseSessionCustom(value: Record<string, unknown> | null): SessionCusto
return value;
}
+function parseSessionMetadata(value: unknown): SessionMetadata {
+ return SessionMetadataSchema.parse(value);
+}
+
function mapRowToSessionRecord(row: {
tenant_id: string;
session_id: string;
@@ -53,6 +58,7 @@ function mapRowToSessionRecord(row: {
last_turn_id: string | null;
external_id: string | null;
custom: Record<string, unknown> | null;
+ metadata: SessionMetadata;
metrics: SessionMetrics;
created_at: Date;
updated_at: Date;
@@ -72,6 +78,7 @@ function mapRowToSessionRecord(row: {
last_turn_id: row.last_turn_id,
external_id: row.external_id,
custom: parseSessionCustom(row.custom),
+ metadata: parseSessionMetadata(row.metadata),
metrics: row.metrics,
created_at: row.created_at,
updated_at: row.updated_at,
@@ -95,6 +102,7 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn
agent_spec: columns.agent_spec !== null ? json(columns.agent_spec) : null,
title: null,
custom: input.custom !== null ? json(input.custom) : null,
+ metadata: json(input.metadata),
external_id: input.external_id,
metrics: json({
total_cost_in_usd: 0,
@@ -164,6 +172,7 @@ export async function getSessionByExternalId(
export async function updateSession(db: Kysely<Database>, input: UpdateSessionInput<SessionCustom>): Promise<void> {
const agent = input.agent;
const title = input.title;
+ const metadata = input.metadata;
if (agent !== undefined) {
const existing = await getSession(db, { tenant_id: input.tenant_id, session_id: input.session_id });
@@ -193,6 +202,12 @@ export async function updateSession(db: Kysely<Database>, input: UpdateSessionIn
}
return qb.set({ title });
})
+ .$if(metadata !== undefined, qb => {
+ if (metadata === undefined) {
+ return qb;
+ }
+ return qb.set({ metadata: json(metadata) });
+ })
.where('tenant_id', '=', input.tenant_id)
.where('session_id', '=', input.session_id)
.executeTakeFirst();
diff --git a/packages/trueforge/src/db/postgres/types.ts b/packages/trueforge/src/db/postgres/types.ts
index 240f68acb..20d35853f 100644
--- a/packages/trueforge/src/db/postgres/types.ts
+++ b/packages/trueforge/src/db/postgres/types.ts
@@ -5,6 +5,7 @@
import type {
AgentSpec,
PersistedTurnEvent,
+ SessionMetadata,
SessionMetrics,
TurnInputItem,
TurnState,
@@ -87,6 +88,8 @@ export interface SessionTable {
external_id: string | null;
/** top: caller-owned opaque extension; never mixed with store state */
custom: JSONColumnType<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>> | null;
+ /** Caller-owned metadata; always present (DEFAULT '{}'). */
+ metadata: JSONColumnType<SessionMetadata, SessionMetadata, SessionMetadata>;
metrics: JSONColumnType<SessionMetrics, SessionMetrics, SessionMetrics>;
/** top: list ordering (indexed below) */
created_at: Date;
diff --git a/packages/trueforge/src/db/sqlite/client.ts b/packages/trueforge/src/db/sqlite/client.ts
index 038907679..b566ccfb4 100644
--- a/packages/trueforge/src/db/sqlite/client.ts
+++ b/packages/trueforge/src/db/sqlite/client.ts
@@ -124,6 +124,7 @@ function applyPragmas(database: Database.Database): void {
const JSON_RESULT_COLUMNS = new Set([
'agent_spec',
'custom',
+ 'metadata',
'metrics',
'ancestor_ids',
'input',
diff --git a/packages/trueforge/src/db/sqlite/migrations/20260902_000001_session_metadata.ts b/packages/trueforge/src/db/sqlite/migrations/20260902_000001_session_metadata.ts
new file mode 100644
index 000000000..167a9e7e0
--- /dev/null
+++ b/packages/trueforge/src/db/sqlite/migrations/20260902_000001_session_metadata.ts
@@ -0,0 +1,198 @@
+import { sql, type Kysely } from 'kysely';
+import { SESSION_EXTERNAL_ID_UQ } from '../../indexes';
+
+/**
+ * Caller-owned session metadata. Rebuilds `session` because ADD COLUMN cannot
+ * take DEFAULT (jsonb('{}')) (expression default). Keeps `custom` unchanged.
+ * DROP TABLE session needs FKs off; PRAGMA foreign_keys is a no-op inside a txn.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`PRAGMA foreign_keys = OFF`.execute(db);
+ try {
+ await db.transaction().execute(async trx => {
+ await sql`
+ CREATE TABLE session_new (
+ tenant_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_by TEXT NOT NULL DEFAULT '',
+ agent_id TEXT,
+ agent_name TEXT,
+ agent_spec BLOB,
+ title TEXT,
+ last_turn_id TEXT,
+ external_id TEXT,
+ custom BLOB,
+ metadata BLOB NOT NULL DEFAULT (jsonb('{}')),
+ metrics BLOB NOT NULL DEFAULT (jsonb('{"total_cost_in_usd":0,"total_duration_ms":0,"total_turns":0}')),
+ last_activity_timestamp_ms INTEGER NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (session_id),
+ CHECK (
+ (agent_id IS NOT NULL AND agent_spec IS NULL)
+ OR (agent_id IS NULL AND agent_spec IS NOT NULL)
+ )
+ ) STRICT
+ `.execute(trx);
+
+ await sql`
+ INSERT INTO session_new (
+ tenant_id,
+ session_id,
+ created_by,
+ agent_id,
+ agent_name,
+ agent_spec,
+ title,
+ last_turn_id,
+ external_id,
+ custom,
+ metadata,
+ metrics,
+ last_activity_timestamp_ms,
+ created_at,
+ updated_at
+ )
+ SELECT
+ tenant_id,
+ session_id,
+ created_by,
+ agent_id,
+ agent_name,
+ agent_spec,
+ title,
+ last_turn_id,
+ external_id,
+ custom,
+ jsonb('{}'),
+ metrics,
+ last_activity_timestamp_ms,
+ created_at,
+ updated_at
+ FROM session
+ `.execute(trx);
+
+ await sql`DROP TABLE session`.execute(trx);
+ await sql`ALTER TABLE session_new RENAME TO session`.execute(trx);
+ await sql`
+ CREATE INDEX session_list_idx
+ ON session (tenant_id, created_at, session_id)
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_agent_id_idx
+ ON session (tenant_id, agent_id)
+ WHERE agent_id IS NOT NULL
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_list_updated_at_idx
+ ON session (tenant_id, updated_at, session_id)
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_agent_created_at_idx
+ ON session (tenant_id, agent_id, created_at)
+ WHERE agent_id IS NOT NULL
+ `.execute(trx);
+ await sql`
+ CREATE UNIQUE INDEX ${sql.raw(SESSION_EXTERNAL_ID_UQ)}
+ ON session (tenant_id, external_id)
+ WHERE external_id IS NOT NULL
+ `.execute(trx);
+ });
+ } finally {
+ await sql`PRAGMA foreign_keys = ON`.execute(db);
+ }
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`PRAGMA foreign_keys = OFF`.execute(db);
+ try {
+ await db.transaction().execute(async trx => {
+ await sql`
+ CREATE TABLE session_old (
+ tenant_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ created_by TEXT NOT NULL DEFAULT '',
+ agent_id TEXT,
+ agent_name TEXT,
+ agent_spec BLOB,
+ title TEXT,
+ last_turn_id TEXT,
+ external_id TEXT,
+ custom BLOB,
+ metrics BLOB NOT NULL DEFAULT (jsonb('{"total_cost_in_usd":0,"total_duration_ms":0,"total_turns":0}')),
+ last_activity_timestamp_ms INTEGER NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (session_id),
+ CHECK (
+ (agent_id IS NOT NULL AND agent_spec IS NULL)
+ OR (agent_id IS NULL AND agent_spec IS NOT NULL)
+ )
+ ) STRICT
+ `.execute(trx);
+
+ await sql`
+ INSERT INTO session_old (
+ tenant_id,
+ session_id,
+ created_by,
+ agent_id,
+ agent_name,
+ agent_spec,
+ title,
+ last_turn_id,
+ external_id,
+ custom,
+ metrics,
+ last_activity_timestamp_ms,
+ created_at,
+ updated_at
+ )
+ SELECT
+ tenant_id,
+ session_id,
+ created_by,
+ agent_id,
+ agent_name,
+ agent_spec,
+ title,
+ last_turn_id,
+ external_id,
+ custom,
+ metrics,
+ last_activity_timestamp_ms,
+ created_at,
+ updated_at
+ FROM session
+ `.execute(trx);
+
+ await sql`DROP TABLE session`.execute(trx);
+ await sql`ALTER TABLE session_old RENAME TO session`.execute(trx);
+ await sql`
+ CREATE INDEX session_list_idx
+ ON session (tenant_id, created_at, session_id)
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_agent_id_idx
+ ON session (tenant_id, agent_id)
+ WHERE agent_id IS NOT NULL
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_list_updated_at_idx
+ ON session (tenant_id, updated_at, session_id)
+ `.execute(trx);
+ await sql`
+ CREATE INDEX session_agent_created_at_idx
+ ON session (tenant_id, agent_id, created_at)
+ WHERE agent_id IS NOT NULL
+ `.execute(trx);
+ await sql`
+ CREATE UNIQUE INDEX ${sql.raw(SESSION_EXTERNAL_ID_UQ)}
+ ON session (tenant_id, external_id)
+ WHERE external_id IS NOT NULL
+ `.execute(trx);
+ });
+ } finally {
+ await sql`PRAGMA foreign_keys = ON`.execute(db);
+ }
+}
diff --git a/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts b/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
index 784d292a9..4aac39f00 100644
--- a/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
@@ -1,4 +1,5 @@
-import type { AgentSpec, SessionMetrics } from '@truefoundry/trueforge-core/agent-session';
+import type { AgentSpec, SessionMetadata, SessionMetrics } from '@truefoundry/trueforge-core/agent-session';
+import { SessionMetadataSchema } from '@truefoundry/trueforge-core/agent-session';
import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/models/SessionRecord';
import type {
CreateSessionInput,
@@ -41,6 +42,10 @@ function parseSessionCustom(value: Record<string, unknown> | null): SessionCusto
return value;
}
+function parseSessionMetadata(value: unknown): SessionMetadata {
+ return SessionMetadataSchema.parse(value);
+}
+
function mapRowToSessionRecord(row: {
tenant_id: string;
session_id: string;
@@ -52,6 +57,7 @@ function mapRowToSessionRecord(row: {
last_turn_id: string | null;
external_id: string | null;
custom: Record<string, unknown> | null;
+ metadata: SessionMetadata;
metrics: SessionMetrics;
created_at: string;
updated_at: string;
@@ -71,6 +77,7 @@ function mapRowToSessionRecord(row: {
last_turn_id: row.last_turn_id,
external_id: row.external_id,
custom: parseSessionCustom(row.custom),
+ metadata: parseSessionMetadata(row.metadata),
metrics: row.metrics,
created_at: new Date(row.created_at),
updated_at: new Date(row.updated_at),
@@ -90,6 +97,7 @@ function sessionSelectColumns() {
'last_turn_id' as const,
'external_id' as const,
jsonText<Record<string, unknown> | null>(sql.ref('custom')).as('custom'),
+ jsonText<SessionMetadata>(sql.ref('metadata')).as('metadata'),
jsonText<SessionMetrics>(sql.ref('metrics')).as('metrics'),
'created_at' as const,
'updated_at' as const,
@@ -113,6 +121,7 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn
agent_spec: columns.agent_spec !== null ? jsonbBind(columns.agent_spec) : null,
title: null,
custom: input.custom !== null ? jsonbBind(input.custom) : null,
+ metadata: jsonbBind(input.metadata),
external_id: input.external_id,
metrics: jsonbBind({
total_cost_in_usd: 0,
@@ -192,6 +201,7 @@ export async function getSessionByExternalId(
export async function updateSession(db: Kysely<Database>, input: UpdateSessionInput<SessionCustom>): Promise<void> {
const agent = input.agent;
const title = input.title;
+ const metadata = input.metadata;
if (agent !== undefined) {
const existing = await getSession(db, { tenant_id: input.tenant_id, session_id: input.session_id });
@@ -218,6 +228,9 @@ export async function updateSession(db: Kysely<Database>, input: UpdateSessionIn
if (title !== undefined) {
qb = qb.set({ title });
}
+ if (metadata !== undefined) {
+ qb = qb.set({ metadata: jsonbBind(metadata) });
+ }
const result = await qb.executeTakeFirst();
diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.ts
index 4dc2d5468..522f9b71c 100644
--- a/packages/trueforge/src/db/sqlite/types.ts
+++ b/packages/trueforge/src/db/sqlite/types.ts
@@ -8,6 +8,7 @@
import type {
AgentSpec,
PersistedTurnEvent,
+ SessionMetadata,
SessionMetrics,
TurnInputItem,
TurnState,
@@ -72,6 +73,7 @@ export interface SessionTable {
/** Optional unique key within `tenant_id` when set. */
external_id: string | null;
custom: JsonbColumn<Record<string, unknown>> | null;
+ metadata: JsonbColumn<SessionMetadata>;
metrics: JsonbColumn<SessionMetrics>;
created_at: string;
updated_at: string;
diff --git a/packages/trueforge/src/schemas/session.ts b/packages/trueforge/src/schemas/session.ts
index ab4943fca..2dad089bb 100644
--- a/packages/trueforge/src/schemas/session.ts
+++ b/packages/trueforge/src/schemas/session.ts
@@ -1,6 +1,11 @@
/** Server session wire schemas. Core Session lives in agentSession. */
import { z } from '@hono/zod-openapi';
-import { AgentSpecSchema, SessionSchema, TokenPaginationSchema } from '@truefoundry/trueforge-core/agent-session';
+import {
+ AgentSpecSchema,
+ SessionMetadataSchema,
+ SessionSchema,
+ TokenPaginationSchema,
+} from '@truefoundry/trueforge-core/agent-session';
import { NameSchema, PAGE_LIMIT } from './common';
/** Create arm: bind by unique registry agent name. */
@@ -29,6 +34,7 @@ export function isSessionAgentNameRef(agent: CreateSessionAgent): agent is Sessi
export const CreateSessionRequestSchema = z
.object({
agent: CreateSessionAgentSchema,
+ metadata: SessionMetadataSchema.optional(),
})
.strict()
.openapi('CreateSessionRequest');
@@ -45,6 +51,7 @@ export const GetOrCreateSessionByExternalIdRequestSchema = z
export const UpdateSessionRequestSchema = z
.object({
agent: SessionAgentSpecBodySchema.optional(),
+ metadata: SessionMetadataSchema.optional(),
})
.strict()
.openapi('UpdateSessionRequest');
diff --git a/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts b/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
index f2c56be94..52e5a2b3e 100644
--- a/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
+++ b/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
@@ -32,6 +32,7 @@ export function runSessionMetricsStoreContractSuite(
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-abc', name: 'Agent ABC' },
custom: null,
+ metadata: {},
external_id: null,
});
await sessionStore.createSession({
@@ -40,6 +41,7 @@ export function runSessionMetricsStoreContractSuite(
created_by: 'user-2',
agent: { type: 'reference', id: 'agent-abc', name: 'Agent ABC' },
custom: null,
+ metadata: {},
external_id: null,
});
await sessionStore.createTurn(makeCreateTurnInput({ sessionId: 'metrics-session', turnId: 'metrics-turn' }));
@@ -119,6 +121,7 @@ export function runSessionMetricsStoreContractSuite(
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-distributions', name: 'Agent Distributions' },
custom: null,
+ metadata: {},
external_id: null,
});
for (const [index, durationMs] of definition.turnDurations.entries()) {
@@ -168,6 +171,7 @@ export function runSessionMetricsStoreContractSuite(
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-inflight', name: 'Agent InFlight' },
custom: null,
+ metadata: {},
external_id: null,
});
await sessionStore.createSession({
@@ -176,6 +180,7 @@ export function runSessionMetricsStoreContractSuite(
created_by: 'user-1',
agent: { type: 'reference', id: 'agent-inflight', name: 'Agent InFlight' },
custom: null,
+ metadata: {},
external_id: null,
});
await sessionStore.createTurn(makeCreateTurnInput({ sessionId: 'inflight-session', turnId: 'inflight-turn' }));
diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
index af1139c99..fcd5b3009 100644
--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
@@ -81,6 +81,7 @@ describe('public CRUD after session deletion', () => {
}),
},
custom: null,
+ metadata: {},
external_id: null,
});
expect((await app.request('/s1', { method: 'DELETE' })).status).toBe(204);
diff --git a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
index 44e34cfb5..e9175e694 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -160,6 +160,7 @@ describe('sessions HTTP agent binding', () => {
created_by: LOCAL_USER_CONTEXT.userRef,
agent: { type: 'reference', id: agent.id, name: agent.name },
custom: null,
+ metadata: {},
external_id: null,
});
await sessionStore.createSession({
@@ -168,6 +169,7 @@ describe('sessions HTTP agent binding', () => {
created_by: 'someone-else',
agent: { type: 'reference', id: agent.id, name: agent.name },
custom: null,
+ metadata: {},
external_id: null,
});
const start = new Date(Date.now() - 60 * 60 * 1000);
@@ -229,6 +231,7 @@ describe('sessions HTTP agent binding', () => {
created_by: 'someone-else',
agent: { type: 'inline', spec: inlineSpec },
custom: null,
+ metadata: {},
external_id: null,
});
@@ -306,6 +309,58 @@ describe('sessions HTTP agent binding', () => {
expect(patchedJson.data.agent.spec.instructions).toBe('updated');
});
+ it('create and PATCH round-trip session metadata', async () => {
+ const created = await app.request(
+ '/',
+ jsonInit('POST', { agent: { spec: inlineSpec }, metadata: { env: 'dev', ticket: 'T-1' } }),
+ );
+ expect(created.status).toBe(201);
+ const createdJson = (await created.json()) as {
+ data: { id: string; metadata: Record<string, string> };
+ };
+ expect(createdJson.data.metadata).toEqual({ env: 'dev', ticket: 'T-1' });
+
+ const omitPatch = await app.request(`/${createdJson.data.id}`, jsonInit('PATCH', {}));
+ expect(omitPatch.status).toBe(200);
+ const omitJson = (await omitPatch.json()) as { data: { metadata: Record<string, string> } };
+ expect(omitJson.data.metadata).toEqual({ env: 'dev', ticket: 'T-1' });
+
+ const replace = await app.request(`/${createdJson.data.id}`, jsonInit('PATCH', { metadata: { env: 'prod' } }));
+ expect(replace.status).toBe(200);
+ const replaceJson = (await replace.json()) as { data: { metadata: Record<string, string> } };
+ expect(replaceJson.data.metadata).toEqual({ env: 'prod' });
+
+ const clear = await app.request(`/${createdJson.data.id}`, jsonInit('PATCH', { metadata: {} }));
+ expect(clear.status).toBe(200);
+ const clearJson = (await clear.json()) as { data: { metadata: Record<string, string> } };
+ expect(clearJson.data.metadata).toEqual({});
+
+ const omittedCreate = await app.request('/', jsonInit('POST', { agent: { spec: inlineSpec } }));
+ expect(omittedCreate.status).toBe(201);
+ const omittedJson = (await omittedCreate.json()) as { data: { metadata: Record<string, string> } };
+ expect(omittedJson.data.metadata).toEqual({});
+ });
+
+ it('rejects invalid session metadata on create', async () => {
+ const tooLongKey = await app.request(
+ '/',
+ jsonInit('POST', {
+ agent: { spec: inlineSpec },
+ metadata: { ['k'.repeat(33)]: 'v' },
+ }),
+ );
+ expect(tooLongKey.status).toBe(400);
+
+ const tooLongValue = await app.request(
+ '/',
+ jsonInit('POST', {
+ agent: { spec: inlineSpec },
+ metadata: { k: 'v'.repeat(129) },
+ }),
+ );
+ expect(tooLongValue.status).toBe(400);
+ });
+
it('POST get-or-create-by-external-id is idempotent and 403s for another creator', async () => {
const publicPath = await app.request(
'/get-or-create-by-external-id',
@@ -343,6 +398,7 @@ describe('sessions HTTP agent binding', () => {
created_by: 'someone-else',
agent: { type: 'inline', spec: inlineSpec },
custom: null,
+ metadata: {},
external_id: 'run-theirs',
});
const forbidden = await app.request(
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index 3841cb327..7cb470978 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -41,6 +41,7 @@ describe('turns', () => {
}),
},
custom: null,
+ metadata: {},
external_id: null,
});