Skip to content

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

end: add run details on session (#593)

Heer Ambavi11865b434ca1
diff --git a/.changeset/session-source.md b/.changeset/session-source.md
new file mode 100644
index 000000000..ee18adff4
--- /dev/null
+++ b/.changeset/session-source.md
@@ -0,0 +1,7 @@
+---
+"@truefoundry/trueforge": patch
+"@truefoundry/trueforge-core": patch
+"@truefoundry/trueforge-sdk": patch
+---
+
+Add optional session `source`. Persist as nullable JSONB with a list filter index; expose on session responses and list via `source_type` / `source_id`. Schedule dispatch sets source on create; public create/update do not accept it.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 9d18df50e..6c5443586 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1440,6 +1440,9 @@
"maxLength": 128,
"minLength": 1,
"type": "string"
+ },
+ "source": {
+ "$ref": "#/components/schemas/SessionSourceSchedule"
}
},
"required": [
@@ -3286,6 +3289,9 @@
"metrics": {
"$ref": "#/components/schemas/SessionMetrics"
},
+ "source": {
+ "$ref": "#/components/schemas/SessionSource"
+ },
"title": {
"description": "Optional human-readable title; null until set.",
"type": [
@@ -3306,7 +3312,8 @@
"created_at",
"updated_at",
"metrics",
- "metadata"
+ "metadata",
+ "source"
],
"type": "object"
},
@@ -3701,6 +3708,73 @@
],
"type": "object"
},
+ "SessionSource": {
+ "additionalProperties": false,
+ "description": "How this session was created (e.g. a schedule run). Null for interactive sessions.",
+ "properties": {
+ "id": {
+ "description": "Schedule id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "run_id": {
+ "description": "Schedule run id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "description": "Session was created by a schedule run.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "run_id"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "SessionSourceSchedule": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "description": "Schedule id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "run_id": {
+ "description": "Schedule run id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "description": "Session was created by a schedule run.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "run_id"
+ ],
+ "type": "object"
+ },
+ "SessionSourceType": {
+ "description": "When set, returns only sessions created by this source type.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ },
"SettingsCapability": {
"properties": {
"enabled": {
@@ -6773,7 +6847,7 @@
},
"/api/v1/sessions": {
"get": {
- "description": "List the caller's sessions (newest first by default).",
+ "description": "List the sessions (newest first by default).",
"parameters": [
{
"description": "Page size. Defaults to 25, max 25.",
@@ -6850,6 +6924,26 @@
"description": "When true, only sessions created by the authenticated subject.",
"type": "boolean"
}
+ },
+ {
+ "description": "When set, returns only sessions created by this source type.",
+ "in": "query",
+ "name": "source_type",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/SessionSourceType"
+ }
+ },
+ {
+ "description": "When set, returns only sessions from this specific source. Requires source_type.",
+ "in": "query",
+ "name": "source_id",
+ "required": false,
+ "schema": {
+ "description": "When set, returns only sessions from this specific source. Requires source_type.",
+ "minLength": 1,
+ "type": "string"
+ }
}
],
"responses": {
diff --git a/docs/openapi.json b/docs/openapi.json
index 9d18df50e..6c5443586 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1440,6 +1440,9 @@
"maxLength": 128,
"minLength": 1,
"type": "string"
+ },
+ "source": {
+ "$ref": "#/components/schemas/SessionSourceSchedule"
}
},
"required": [
@@ -3286,6 +3289,9 @@
"metrics": {
"$ref": "#/components/schemas/SessionMetrics"
},
+ "source": {
+ "$ref": "#/components/schemas/SessionSource"
+ },
"title": {
"description": "Optional human-readable title; null until set.",
"type": [
@@ -3306,7 +3312,8 @@
"created_at",
"updated_at",
"metrics",
- "metadata"
+ "metadata",
+ "source"
],
"type": "object"
},
@@ -3701,6 +3708,73 @@
],
"type": "object"
},
+ "SessionSource": {
+ "additionalProperties": false,
+ "description": "How this session was created (e.g. a schedule run). Null for interactive sessions.",
+ "properties": {
+ "id": {
+ "description": "Schedule id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "run_id": {
+ "description": "Schedule run id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "description": "Session was created by a schedule run.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "run_id"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "SessionSourceSchedule": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "description": "Schedule id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "run_id": {
+ "description": "Schedule run id.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "type": {
+ "description": "Session was created by a schedule run.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "id",
+ "run_id"
+ ],
+ "type": "object"
+ },
+ "SessionSourceType": {
+ "description": "When set, returns only sessions created by this source type.",
+ "enum": [
+ "schedule"
+ ],
+ "type": "string"
+ },
"SettingsCapability": {
"properties": {
"enabled": {
@@ -6773,7 +6847,7 @@
},
"/api/v1/sessions": {
"get": {
- "description": "List the caller's sessions (newest first by default).",
+ "description": "List the sessions (newest first by default).",
"parameters": [
{
"description": "Page size. Defaults to 25, max 25.",
@@ -6850,6 +6924,26 @@
"description": "When true, only sessions created by the authenticated subject.",
"type": "boolean"
}
+ },
+ {
+ "description": "When set, returns only sessions created by this source type.",
+ "in": "query",
+ "name": "source_type",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/SessionSourceType"
+ }
+ },
+ {
+ "description": "When set, returns only sessions from this specific source. Requires source_type.",
+ "in": "query",
+ "name": "source_id",
+ "required": false,
+ "schema": {
+ "description": "When set, returns only sessions from this specific source. Requires source_type.",
+ "minLength": 1,
+ "type": "string"
+ }
}
],
"responses": {
diff --git a/packages/trueforge-core/src/agent-session/Sessions.ts b/packages/trueforge-core/src/agent-session/Sessions.ts
index 8eed66638..7e5cdd417 100644
--- a/packages/trueforge-core/src/agent-session/Sessions.ts
+++ b/packages/trueforge-core/src/agent-session/Sessions.ts
@@ -12,12 +12,16 @@ import type {
} from './store/ISessionStore';
import { SessionExternalIdConflictError } from './store/SessionStoreErrors';
+/**
+ * Domain create input: same as {@link CreateSessionInput}, but `custom`,
+ * `metadata`, and `source` are optional — {@link Sessions.create} defaults them
+ * (`null` / `{}` / `null`). The store contract requires those fields explicitly.
+ */
export type SessionsCreateInput<TSessionCustom extends object> = Omit<
CreateSessionInput<TSessionCustom>,
- 'custom' | 'metadata'
+ 'custom' | 'metadata' | 'source'
> & {
- custom?: TSessionCustom | undefined;
- metadata?: CreateSessionInput<TSessionCustom>['metadata'] | undefined;
+ [K in 'custom' | 'metadata' | 'source']?: CreateSessionInput<TSessionCustom>[K] | undefined;
};
export class Sessions<
@@ -38,6 +42,7 @@ export class Sessions<
...input,
custom: input.custom ?? null,
metadata: input.metadata ?? {},
+ source: input.source ?? null,
});
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 95a78881f..4a6a8471a 100644
--- a/packages/trueforge-core/src/agent-session/index.ts
+++ b/packages/trueforge-core/src/agent-session/index.ts
@@ -21,8 +21,22 @@ export {
} from './schemas/turn';
export type { TerminalTurnState, Turn, TurnInputItem, TurnMetrics, TurnState } from './schemas/turn';
-export { SessionMetadataSchema, SessionMetricsSchema, SessionSchema } from './schemas/session';
-export type { Session, SessionAgent, SessionMetadata, SessionMetrics } from './schemas/session';
+export {
+ SessionMetadataSchema,
+ SessionMetricsSchema,
+ SessionSchema,
+ SessionSourceScheduleSchema,
+ SessionSourceSchema,
+ SessionSourceTypeSchema,
+} from './schemas/session';
+export type {
+ Session,
+ SessionAgent,
+ SessionMetadata,
+ SessionMetrics,
+ SessionSource,
+ SessionSourceType,
+} from './schemas/session';
export { CreatedBySubjectSchema } from './schemas/subject';
export type { CreatedBySubject } from './schemas/subject';
diff --git a/packages/trueforge-core/src/agent-session/models/SessionRecord.ts b/packages/trueforge-core/src/agent-session/models/SessionRecord.ts
index 28442240b..80876cabc 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, SessionMetadata, SessionMetrics } from '../schemas/session';
+import type { SessionAgent, SessionMetadata, SessionMetrics, SessionSource } from '../schemas/session';
import type { CreatedBySubject } from '../schemas/subject';
/**
@@ -22,6 +22,10 @@ export interface SessionRecord<TCustom extends object = Record<string, never>> {
* Null means the session has no external id.
*/
external_id: string | null;
+ /**
+ * How the session was created. Null for interactive sessions.
+ */
+ source: SessionSource | null;
/**
* Session tip — used for `previous_turn_id: 'auto'` resolution and turn
* listing anchors. Advanced only by `createTurn` (atomic link).
diff --git a/packages/trueforge-core/src/agent-session/schemas/session.ts b/packages/trueforge-core/src/agent-session/schemas/session.ts
index e5efa4973..215adad7d 100644
--- a/packages/trueforge-core/src/agent-session/schemas/session.ts
+++ b/packages/trueforge-core/src/agent-session/schemas/session.ts
@@ -69,6 +69,32 @@ export const SessionAgentSchema = z
.discriminatedUnion('type', [SessionAgentReferenceSchema, SessionAgentInlineSchema])
.openapi('SessionAgent');
+export const SessionSourceTypeSchema = z.enum(['schedule']).openapi('SessionSourceType');
+
+export type SessionSourceType = z.infer<typeof SessionSourceTypeSchema>;
+
+function sessionSourceScheduleObject() {
+ return z
+ .object({
+ type: z.literal(SessionSourceTypeSchema.enum.schedule).describe('Session was created by a schedule run.'),
+ id: z.string().min(1).describe('Schedule id.'),
+ run_id: z.string().min(1).describe('Schedule run id.'),
+ })
+ .strict();
+}
+
+export const SessionSourceScheduleSchema = sessionSourceScheduleObject().openapi('SessionSourceSchedule');
+
+/**
+ * How a session was created. Same shape as {@link SessionSourceScheduleSchema} today;
+ * switch to `discriminatedUnion('type', …)` when a second source arm lands.
+ */
+export const SessionSourceSchema = sessionSourceScheduleObject()
+ .describe('How this session was created (e.g. a schedule run). Null for interactive sessions.')
+ .openapi('SessionSource');
+
+export type SessionSource = z.infer<typeof SessionSourceSchema>;
+
export const SessionSchema = z
.object({
id: z.string().describe('Unique session id.'),
@@ -79,6 +105,7 @@ export const SessionSchema = z
updated_at: z.string().describe('ISO 8601 last-update timestamp.'),
metrics: SessionMetricsSchema,
metadata: SessionMetadataSchema,
+ source: SessionSourceSchema.nullable(),
})
.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 b6997acf0..8b03baae2 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_subject' | 'external_id' | 'metadata'
+ 'tenant_id' | 'session_id' | 'agent' | 'created_by_subject' | 'external_id' | 'metadata' | 'source'
> & {
custom: TSessionCustom | null;
};
@@ -71,6 +71,13 @@ export interface ListSessionsInput {
agent_ids: readonly string[];
}
| undefined;
+ /** When set, only sessions whose `source.type` matches. */
+ source_type: string | undefined;
+ /**
+ * When set, only sessions whose `source.id` matches.
+ * Requires `source_type`.
+ */
+ source_id: string | undefined;
}
/** Turn row fields without assembled snapshot (create input / listTurns). */
@@ -262,8 +269,9 @@ export interface ISessionStore<
* keyset cursor on `(updated_at, session_id)`. `start_timestamp` /
* `end_timestamp` are inclusive instant bounds on `created_at`. Optional
* `agent_id` filters ref-bound sessions. `created_by_or_agent_ids` matches
- * rows created by its subject OR bound to one of its agent ids. Does **not**
- * bump `last_activity_timestamp_ms` (read path).
+ * rows created by its subject OR bound to one of its agent ids; optional
+ * `source_type` / `source_id` filter by JSON `source` (expression-indexed,
+ * no scalar columns). Does **not** bump `last_activity_timestamp_ms` (read path).
*/
listSessions(
input: ListSessionsInput,
diff --git a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
index 9744ebef8..cd22e8f97 100644
--- a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
+++ b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
@@ -192,6 +192,7 @@ export class InMemorySessionStore<
title: null,
last_turn_id: null,
external_id: externalId,
+ source: input.source !== null ? deepCopy(input.source) : null,
created_at: now,
updated_at: now,
last_activity_timestamp_ms: Date.now(),
@@ -283,6 +284,12 @@ export class InMemorySessionStore<
continue;
}
}
+ if (input.source_type !== undefined && stored.record.source?.type !== input.source_type) {
+ continue;
+ }
+ if (input.source_id !== undefined && stored.record.source?.id !== input.source_id) {
+ continue;
+ }
const createdAt = stored.record.created_at.getTime();
if (input.start_timestamp !== undefined && createdAt < input.start_timestamp.getTime()) {
continue;
diff --git a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
index 2bf60a084..cf4a1b4d7 100644
--- a/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
+++ b/packages/trueforge-core/tests/agent-session/store/storeContractSuite.ts
@@ -88,6 +88,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
}
@@ -172,6 +173,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
expect(session).toBeDefined();
expect(mustGet(session).tenant_id).toBe(tenant);
expect(mustGet(session).created_by_subject.subject_id).toBe('user-1');
+ expect(mustGet(session).source).toBeNull();
expect(mustGet(session).agent).toMatchObject({
type: 'inline',
spec: { model: { name: 'test-provider/test-model' } },
@@ -199,6 +201,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const session = mustGet(await store.getSession({ tenant_id: tenant, session_id: 'created-by-session' }));
expect(session.created_by_subject).toEqual({
@@ -216,6 +219,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
end_timestamp: undefined,
agent_id: undefined,
created_by_or_agent_ids: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(listed.data.map(s => s.session_id)).toContain('created-by-session');
expect(listed.data.find(s => s.session_id === 'created-by-session')?.created_by_subject.subject_id).toBe(
@@ -233,6 +238,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await seedSession(store);
@@ -248,6 +254,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(filtered.data.map(row => row.session_id)).toEqual(['named-1']);
});
@@ -262,6 +270,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await expect(
@@ -317,6 +326,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata,
external_id: null,
+ source: null,
});
expect(mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId })).metadata).toEqual(metadata);
@@ -332,6 +342,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: { a: '1' },
external_id: null,
+ source: null,
});
await store.updateSession({
@@ -384,6 +395,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
}),
).rejects.toBeInstanceOf(SessionStoreConflictError);
});
@@ -405,6 +417,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: 'run-1',
+ source: null,
});
const byId = await store.getSession({ tenant_id: tenant, session_id: sessionId });
expect(mustGet(byId).external_id).toBe('run-1');
@@ -424,6 +437,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: 'shared-key',
+ source: null,
});
// Specifically the external-id arm, not just any conflict: get-or-create
// treats this rejection as its normal repeat-call path.
@@ -436,6 +450,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: 'shared-key',
+ source: null,
}),
).rejects.toBeInstanceOf(SessionExternalIdConflictError);
@@ -447,6 +462,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: 'shared-key',
+ source: null,
});
await store.createSession({
tenant_id: tenant,
@@ -456,6 +472,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createSession({
tenant_id: tenant,
@@ -465,6 +482,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
});
@@ -478,6 +496,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: 'run-1',
+ source: null,
});
const first = await store.getSessionByExternalId({ tenant_id: tenant, external_id: 'run-1' });
await new Promise(r => setTimeout(r, 5));
@@ -498,6 +517,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createTurn(
@@ -585,6 +605,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(listed.data).toHaveLength(0);
@@ -683,6 +705,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createTurn(makeCreateTurnInput({ sessionId: nested, turnId: 'turn-1' }));
const nestedKeys = { session_id: nested, turn_id: 'turn-1' };
@@ -814,6 +837,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await new Promise(r => setTimeout(r, 2));
}
@@ -830,6 +854,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const desc = await store.listSessions({
@@ -841,6 +866,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(desc.data.map(s => s.session_id)).toEqual(['sc', 'sb', 'sa']);
@@ -853,6 +880,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: 'asc',
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(asc.data.map(s => s.session_id)).toEqual(['sa', 'sb', 'sc']);
});
@@ -870,6 +899,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(first.data).toHaveLength(2);
expect(first.pagination.next_page_token).toBeDefined();
@@ -882,6 +913,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(second.data.map(s => s.session_id)).toEqual(['sa']);
expect(second.pagination.next_page_token).toBeUndefined();
@@ -895,6 +928,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: 'asc',
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
const middleSession = all.data[1];
if (!middleSession) {
@@ -910,6 +945,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
page_token: undefined,
start_timestamp: middleCreatedAt,
end_timestamp: middleCreatedAt,
+ source_type: undefined,
+ source_id: undefined,
});
expect(bounded.data.map(s => s.session_id)).toEqual(['sb']);
});
@@ -933,6 +970,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
};
const desc = await store.listSessions({ ...listArgs, limit: 10, page_token: undefined });
expect(desc.data.map(s => s.session_id)).toEqual(['sa', 'sc', 'sb']);
@@ -959,6 +998,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: 'desc' as const,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
};
const full = await store.listSessions({ ...listArgs, limit: 10, page_token: undefined });
const page1 = await store.listSessions({ ...listArgs, limit: 2, page_token: undefined });
@@ -985,6 +1026,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createSession({
tenant_id: tenant,
@@ -994,6 +1036,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createSession({
tenant_id: tenant,
@@ -1003,6 +1046,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await store.createSession({
tenant_id: tenant,
@@ -1012,6 +1056,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const aliceOnly = await store.listSessions({
@@ -1026,6 +1071,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(aliceOnly.data.map(s => s.session_id)).toEqual(['alice-session']);
expect(aliceOnly.data[0]?.created_by_subject.subject_id).toBe('alice');
@@ -1042,6 +1089,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: 'asc',
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(aliceOrManaged.data.map(s => s.session_id)).toEqual(['alice-session', 'managed-session']);
@@ -1057,6 +1106,8 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
});
expect(managedAgentOnly.data.map(s => s.session_id)).toEqual(['managed-session']);
@@ -1072,6 +1123,93 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
order: undefined,
start_timestamp: undefined,
end_timestamp: undefined,
+ source_type: undefined,
+ source_id: undefined,
+ });
+ expect(unmatched.data).toEqual([]);
+ });
+
+ it('persists schedule source and listSessions filters by source_type / source_id', async () => {
+ const store = createStore();
+ const scheduleSource = {
+ type: 'schedule' as const,
+ id: 'sched-1',
+ run_id: 'run-1',
+ };
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: 'from-schedule',
+ created_by_subject: { subject_id: 'user-1', subject_type: 'user', subject_display_name: 'user-1' },
+ agent: { type: 'inline', spec: makeAgentSpec() },
+ custom: null,
+ metadata: {},
+ external_id: 'run-1',
+ source: scheduleSource,
+ });
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: 'from-other-schedule',
+ created_by_subject: { subject_id: 'user-1', subject_type: 'user', subject_display_name: 'user-1' },
+ agent: { type: 'inline', spec: makeAgentSpec() },
+ custom: null,
+ metadata: {},
+ external_id: 'run-2',
+ source: { type: 'schedule', id: 'sched-2', run_id: 'run-2' },
+ });
+ await store.createSession({
+ tenant_id: tenant,
+ session_id: 'interactive',
+ created_by_subject: { subject_id: 'user-1', subject_type: 'user', subject_display_name: 'user-1' },
+ agent: { type: 'inline', spec: makeAgentSpec() },
+ custom: null,
+ metadata: {},
+ external_id: null,
+ source: null,
+ });
+
+ const byId = mustGet(await store.getSession({ tenant_id: tenant, session_id: 'from-schedule' }));
+ expect(byId.source).toEqual(scheduleSource);
+
+ const byType = await store.listSessions({
+ agent_id: undefined,
+ created_by_or_agent_ids: undefined,
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ source_type: 'schedule',
+ source_id: undefined,
+ });
+ expect(byType.data.map(s => s.session_id).sort()).toEqual(['from-other-schedule', 'from-schedule']);
+
+ const bySourceId = await store.listSessions({
+ agent_id: undefined,
+ created_by_or_agent_ids: undefined,
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ source_type: 'schedule',
+ source_id: 'sched-1',
+ });
+ expect(bySourceId.data.map(s => s.session_id)).toEqual(['from-schedule']);
+ expect(bySourceId.data[0]?.source).toEqual(scheduleSource);
+
+ const unmatched = await store.listSessions({
+ agent_id: undefined,
+ created_by_or_agent_ids: undefined,
+ tenant_id: tenant,
+ limit: 10,
+ page_token: undefined,
+ order: undefined,
+ start_timestamp: undefined,
+ end_timestamp: undefined,
+ source_type: 'schedule',
+ source_id: 'missing-sched',
});
expect(unmatched.data).toEqual([]);
});
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 26b25f48b..901600cf5 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -1235,7 +1235,7 @@ await client.schedules.listRuns("schedule_id");
<dl>
<dd>
-List the caller's sessions (newest first by default).
+List the sessions (newest first by default).
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts
index 2d0744219..191d86c8a 100644
--- a/packages/trueforge-sdk/src/api/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts
@@ -15,4 +15,5 @@ export interface GetOrCreateSessionByExternalIdRequest {
agent: TrueForge.CreateSessionAgent;
/** Caller-supplied id unique within the tenant. */
externalId: string;
+ source?: TrueForge.SessionSourceSchedule;
}
diff --git a/packages/trueforge-sdk/src/api/resources/sessions/client/Client.ts b/packages/trueforge-sdk/src/api/resources/sessions/client/Client.ts
index b5fdd7780..ea143e750 100644
--- a/packages/trueforge-sdk/src/api/resources/sessions/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/sessions/client/Client.ts
@@ -24,7 +24,7 @@ export class SessionsClient {
}
/**
- * List the caller's sessions (newest first by default).
+ * List the sessions (newest first by default).
*
* @param {TrueForge.ListSessionsRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -44,7 +44,17 @@ export class SessionsClient {
async (
request: TrueForge.ListSessionsRequest,
): Promise<core.WithRawResponse<TrueForge.ListSessionsResponse>> => {
- const { limit = 25, order, pageToken, startTimestamp, endTimestamp, agentId, createdByMe } = request;
+ const {
+ limit = 25,
+ order,
+ pageToken,
+ startTimestamp,
+ endTimestamp,
+ agentId,
+ createdByMe,
+ sourceType,
+ sourceId,
+ } = request;
const _queryParams: Record<string, unknown> = {
limit,
order:
@@ -61,6 +71,16 @@ export class SessionsClient {
end_timestamp: endTimestamp != null ? endTimestamp?.toISOString() : undefined,
agent_id: agentId,
created_by_me: createdByMe,
+ source_type:
+ sourceType != null
+ ? serializers.SessionSourceType.jsonOrThrow(sourceType, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ })
+ : undefined,
+ source_id: sourceId,
};
const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
diff --git a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
index ce257215a..c5ae193a9 100644
--- a/packages/trueforge-sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
@@ -21,4 +21,8 @@ export interface ListSessionsRequest {
agentId?: string;
/** When true, only sessions created by the authenticated subject. */
createdByMe?: boolean;
+ /** When set, returns only sessions created by this source type. */
+ sourceType?: TrueForge.SessionSourceType;
+ /** When set, returns only sessions from this specific source. Requires source_type. */
+ sourceId?: string;
}
diff --git a/packages/trueforge-sdk/src/api/types/Session.ts b/packages/trueforge-sdk/src/api/types/Session.ts
index 512819d8e..eaf080418 100644
--- a/packages/trueforge-sdk/src/api/types/Session.ts
+++ b/packages/trueforge-sdk/src/api/types/Session.ts
@@ -11,6 +11,7 @@ export interface Session {
id: string;
metadata: TrueForge.SessionMetadata;
metrics: TrueForge.SessionMetrics;
+ source: TrueForge.SessionSource | null;
/** Optional human-readable title; null until set. */
title: string | null;
/** ISO 8601 last-update timestamp. */
diff --git a/packages/trueforge-sdk/src/api/types/SessionSource.ts b/packages/trueforge-sdk/src/api/types/SessionSource.ts
new file mode 100644
index 000000000..8b4981e07
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/SessionSource.ts
@@ -0,0 +1,13 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * How this session was created (e.g. a schedule run). Null for interactive sessions.
+ */
+export interface SessionSource {
+ /** Schedule id. */
+ id: string;
+ /** Schedule run id. */
+ runId: string;
+ /** Session was created by a schedule run. */
+ type: "schedule";
+}
diff --git a/packages/trueforge-sdk/src/api/types/SessionSourceSchedule.ts b/packages/trueforge-sdk/src/api/types/SessionSourceSchedule.ts
new file mode 100644
index 000000000..5ae9a4f6b
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/SessionSourceSchedule.ts
@@ -0,0 +1,10 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface SessionSourceSchedule {
+ /** Schedule id. */
+ id: string;
+ /** Schedule run id. */
+ runId: string;
+ /** Session was created by a schedule run. */
+ type: "schedule";
+}
diff --git a/packages/trueforge-sdk/src/api/types/SessionSourceType.ts b/packages/trueforge-sdk/src/api/types/SessionSourceType.ts
new file mode 100644
index 000000000..e86f46ac5
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/SessionSourceType.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * When set, returns only sessions created by this source type.
+ */
+export type SessionSourceType = "schedule";
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index 727e1bd19..c1114ffdd 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -172,6 +172,9 @@ export * from "./SessionMetricsMeter.js";
export * from "./SessionMetricsMeterName.js";
export * from "./SessionMetricsMeterResponse.js";
export * from "./SessionMetricsPoint.js";
+export * from "./SessionSource.js";
+export * from "./SessionSourceSchedule.js";
+export * from "./SessionSourceType.js";
export * from "./SettingsCapability.js";
export * from "./Skill.js";
export * from "./SkillCapability.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts
index a5eb94c45..94361c4df 100644
--- a/packages/trueforge-sdk/src/serialization/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/sessions/client/requests/GetOrCreateSessionByExternalIdRequest.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 { CreateSessionAgent } from "../../../../../../types/CreateSessionAgent.js";
+import { SessionSourceSchedule } from "../../../../../../types/SessionSourceSchedule.js";
export const GetOrCreateSessionByExternalIdRequest: core.serialization.Schema<
serializers.internal.GetOrCreateSessionByExternalIdRequest.Raw,
@@ -11,11 +12,13 @@ export const GetOrCreateSessionByExternalIdRequest: core.serialization.Schema<
> = core.serialization.object({
agent: CreateSessionAgent,
externalId: core.serialization.property("external_id", core.serialization.string()),
+ source: SessionSourceSchedule.optional(),
});
export declare namespace GetOrCreateSessionByExternalIdRequest {
export interface Raw {
agent: CreateSessionAgent.Raw;
external_id: string;
+ source?: SessionSourceSchedule.Raw | null;
}
}
diff --git a/packages/trueforge-sdk/src/serialization/types/Session.ts b/packages/trueforge-sdk/src/serialization/types/Session.ts
index 7b69a33b6..14bc19586 100644
--- a/packages/trueforge-sdk/src/serialization/types/Session.ts
+++ b/packages/trueforge-sdk/src/serialization/types/Session.ts
@@ -7,6 +7,7 @@ import { CreatedBySubject } from "./CreatedBySubject.js";
import { SessionAgent } from "./SessionAgent.js";
import { SessionMetadata } from "./SessionMetadata.js";
import { SessionMetrics } from "./SessionMetrics.js";
+import { SessionSource } from "./SessionSource.js";
export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, TrueForge.Session> =
core.serialization.object({
@@ -16,6 +17,7 @@ export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, T
id: core.serialization.string(),
metadata: SessionMetadata,
metrics: SessionMetrics,
+ source: SessionSource.nullable(),
title: core.serialization.string().nullable(),
updatedAt: core.serialization.property("updated_at", core.serialization.string()),
});
@@ -28,6 +30,7 @@ export declare namespace Session {
id: string;
metadata: SessionMetadata.Raw;
metrics: SessionMetrics.Raw;
+ source?: SessionSource.Raw | null;
title?: string | null;
updated_at: string;
}
diff --git a/packages/trueforge-sdk/src/serialization/types/SessionSource.ts b/packages/trueforge-sdk/src/serialization/types/SessionSource.ts
new file mode 100644
index 000000000..543f50b7c
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/SessionSource.ts
@@ -0,0 +1,20 @@
+// 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 SessionSource: core.serialization.ObjectSchema<serializers.SessionSource.Raw, TrueForge.SessionSource> =
+ core.serialization.object({
+ id: core.serialization.string(),
+ runId: core.serialization.property("run_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("schedule"),
+ });
+
+export declare namespace SessionSource {
+ export interface Raw {
+ id: string;
+ run_id: string;
+ type: "schedule";
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/SessionSourceSchedule.ts b/packages/trueforge-sdk/src/serialization/types/SessionSourceSchedule.ts
new file mode 100644
index 000000000..b2a61765d
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/SessionSourceSchedule.ts
@@ -0,0 +1,22 @@
+// 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 SessionSourceSchedule: core.serialization.ObjectSchema<
+ serializers.SessionSourceSchedule.Raw,
+ TrueForge.SessionSourceSchedule
+> = core.serialization.object({
+ id: core.serialization.string(),
+ runId: core.serialization.property("run_id", core.serialization.string()),
+ type: core.serialization.stringLiteral("schedule"),
+});
+
+export declare namespace SessionSourceSchedule {
+ export interface Raw {
+ id: string;
+ run_id: string;
+ type: "schedule";
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/SessionSourceType.ts b/packages/trueforge-sdk/src/serialization/types/SessionSourceType.ts
new file mode 100644
index 000000000..f5a68e153
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/SessionSourceType.ts
@@ -0,0 +1,14 @@
+// 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 SessionSourceType: core.serialization.Schema<
+ serializers.SessionSourceType.Raw,
+ TrueForge.SessionSourceType
+> = core.serialization.stringLiteral("schedule");
+
+export declare namespace SessionSourceType {
+ export type Raw = "schedule";
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index 727e1bd19..c1114ffdd 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -172,6 +172,9 @@ export * from "./SessionMetricsMeter.js";
export * from "./SessionMetricsMeterName.js";
export * from "./SessionMetricsMeterResponse.js";
export * from "./SessionMetricsPoint.js";
+export * from "./SessionSource.js";
+export * from "./SessionSourceSchedule.js";
+export * from "./SessionSourceType.js";
export * from "./SettingsCapability.js";
export * from "./Skill.js";
export * from "./SkillCapability.js";
diff --git a/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts b/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
index a41678bbe..12a3e51d6 100644
--- a/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
+++ b/packages/trueforge-sdk/tests/wire/internal/sessions.test.ts
@@ -21,6 +21,7 @@ describe("SessionsClient", () => {
id: "id",
metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
+ source: { id: "id", run_id: "run_id", type: "schedule" },
title: "title",
updated_at: "updated_at",
},
@@ -66,6 +67,11 @@ describe("SessionsClient", () => {
totalDurationMs: 1,
totalTurns: 1,
},
+ source: {
+ id: "id",
+ runId: "run_id",
+ type: "schedule",
+ },
title: "title",
updatedAt: "updated_at",
},
diff --git a/packages/trueforge-sdk/tests/wire/sessions.test.ts b/packages/trueforge-sdk/tests/wire/sessions.test.ts
index 8eb56f9f9..d9344b4d4 100644
--- a/packages/trueforge-sdk/tests/wire/sessions.test.ts
+++ b/packages/trueforge-sdk/tests/wire/sessions.test.ts
@@ -22,6 +22,7 @@ describe("SessionsClient", () => {
id: "id",
metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
+ source: { id: "id", run_id: "run_id", type: "schedule" },
title: "title",
updated_at: "updated_at",
},
@@ -63,6 +64,11 @@ describe("SessionsClient", () => {
totalDurationMs: 1,
totalTurns: 1,
},
+ source: {
+ id: "id",
+ runId: "run_id",
+ type: "schedule",
+ },
title: "title",
updatedAt: "updated_at",
},
@@ -110,6 +116,7 @@ describe("SessionsClient", () => {
id: "id",
metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
+ source: { id: "id", run_id: "run_id", type: "schedule" },
title: "title",
updated_at: "updated_at",
},
@@ -154,6 +161,11 @@ describe("SessionsClient", () => {
totalDurationMs: 1,
totalTurns: 1,
},
+ source: {
+ id: "id",
+ runId: "run_id",
+ type: "schedule",
+ },
title: "title",
updatedAt: "updated_at",
},
@@ -248,6 +260,7 @@ describe("SessionsClient", () => {
id: "id",
metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
+ source: { id: "id", run_id: "run_id", type: "schedule" },
title: "title",
updated_at: "updated_at",
},
@@ -287,6 +300,11 @@ describe("SessionsClient", () => {
totalDurationMs: 1,
totalTurns: 1,
},
+ source: {
+ id: "id",
+ runId: "run_id",
+ type: "schedule",
+ },
title: "title",
updatedAt: "updated_at",
},
@@ -376,6 +394,7 @@ describe("SessionsClient", () => {
id: "id",
metadata: { key: "value" },
metrics: { total_cost_in_usd: 1.1, total_duration_ms: 1, total_turns: 1 },
+ source: { id: "id", run_id: "run_id", type: "schedule" },
title: "title",
updated_at: "updated_at",
},
@@ -416,6 +435,11 @@ describe("SessionsClient", () => {
totalDurationMs: 1,
totalTurns: 1,
},
+ source: {
+ id: "id",
+ runId: "run_id",
+ type: "schedule",
+ },
title: "title",
updatedAt: "updated_at",
},
diff --git a/packages/trueforge/src/apis/sessions.ts b/packages/trueforge/src/apis/sessions.ts
index 0c952a21e..d5d771c67 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 {
updated_at: record.updated_at.toISOString(),
metrics: record.metrics,
metadata: record.metadata,
+ source: record.source,
};
}
@@ -297,6 +298,7 @@ function createGetOrCreateSessionByExternalIdHandler(
external_id: body.external_id,
created_by_subject: createdBySubjectFromRequestContext(requestContext),
agent,
+ source: body.source ?? null,
});
if (
!created &&
@@ -502,6 +504,8 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
page_token: query.page_token,
start_timestamp: query.start_timestamp,
end_timestamp: query.end_timestamp,
+ source_type: query.source_type,
+ source_id: query.source_id,
});
return c.json({ data: data.map(toWireSession), pagination }, 200);
} catch (error) {
diff --git a/packages/trueforge/src/controller/scheduleDispatch.ts b/packages/trueforge/src/controller/scheduleDispatch.ts
index a4ec54af5..c3320f3a3 100644
--- a/packages/trueforge/src/controller/scheduleDispatch.ts
+++ b/packages/trueforge/src/controller/scheduleDispatch.ts
@@ -59,6 +59,7 @@ function executeScheduledRun(client: ScheduleRunApiClient): (item: ScheduleDispa
const { data: session } = await client.internal.sessions.getOrCreateByExternalId({
externalId: run.id,
agent: { name: schedule.agent_name },
+ source: { type: 'schedule', id: schedule.id, runId: run.id },
});
const turns = await client.sessions.listTurns(session.id, { limit: 1 });
@@ -107,6 +108,7 @@ export async function startScheduleRun(params: {
external_id: run.id,
created_by_subject: schedule.created_by_subject,
agent: { type: 'reference', id: named.id, name: named.name },
+ source: { type: 'schedule', id: schedule.id, run_id: run.id },
});
// idempotency check
diff --git a/packages/trueforge/src/db/createdBySubject.ts b/packages/trueforge/src/db/createdBySubject.ts
deleted file mode 100644
index 2ce4679c6..000000000
--- a/packages/trueforge/src/db/createdBySubject.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { CreatedBySubjectSchema, type CreatedBySubject } from '@truefoundry/trueforge-core/agent-session';
-
-/** Re-parse persisted creator JSON so store readers validate on read. */
-export function parseStoredCreatedBySubject(value: unknown): CreatedBySubject {
- return CreatedBySubjectSchema.parse(value);
-}
diff --git a/packages/trueforge/src/db/indexes.ts b/packages/trueforge/src/db/indexes.ts
index c91707fbe..e08f53919 100644
--- a/packages/trueforge/src/db/indexes.ts
+++ b/packages/trueforge/src/db/indexes.ts
@@ -1,15 +1,21 @@
/** Partial unique index on `session (tenant_id, external_id) WHERE external_id IS NOT NULL`. */
export const SESSION_EXTERNAL_ID_UQ = 'session_external_id_uq';
+/** `(tenant_id, created_by_subject.subject_id)` on session. */
+export const SESSION_CREATED_BY_SUBJECT_ID_IDX = 'session_created_by_subject_id_idx';
+
+/**
+ * `(tenant_id, source.type, source.id)` on session — list filter by source.
+ * Partial WHERE source IS NOT NULL (interactive sessions omit source).
+ */
+export const SESSION_SOURCE_IDX = 'session_source_idx';
+
/** Partial unique index on `agent (tenant_id, external_id) WHERE external_id IS NOT NULL`. */
export const AGENT_EXTERNAL_ID_UQ = 'agent_external_id_uq';
/** `(tenant_id, created_by_subject.subject_id)` on agent. */
export const AGENT_CREATED_BY_SUBJECT_ID_IDX = 'agent_created_by_subject_id_idx';
-/** `(tenant_id, created_by_subject.subject_id)` on session. */
-export const SESSION_CREATED_BY_SUBJECT_ID_IDX = 'session_created_by_subject_id_idx';
-
/** `(tenant_id, created_by_subject.subject_id)` on schedule. */
export const SCHEDULE_CREATED_BY_SUBJECT_ID_IDX = 'schedule_created_by_subject_id_idx';
diff --git a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
index 9003e2adb..38f68fded 100644
--- a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
+++ b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
@@ -1,3 +1,4 @@
+import { CreatedBySubjectSchema } from '@truefoundry/trueforge-core/agent-session';
import type { Kysely, Selectable, Transaction } from 'kysely';
import { newId } from '../../../utils/id';
import {
@@ -12,7 +13,6 @@ import {
type ListAgentsInput,
type UpdateAgentInput,
} from '../../agentStore';
-import { parseStoredCreatedBySubject } from '../../createdBySubject';
import { AGENT_EXTERNAL_ID_UQ } from '../../indexes';
import { isPgConstraint, isUniqueViolation } from '../client';
import { json, now } from '../sqlExpressions';
@@ -25,7 +25,7 @@ function toRecord(row: Selectable<AgentTable>): AgentRecord {
name: row.name,
manifest: parseStoredAgentSpec(row.manifest),
external_id: row.external_id,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
created_at: row.created_at.toISOString(),
updated_at: row.updated_at.toISOString(),
};
diff --git a/packages/trueforge/src/db/postgres/migrations/20260904_000002_session_source.ts b/packages/trueforge/src/db/postgres/migrations/20260904_000002_session_source.ts
new file mode 100644
index 000000000..5ee6df721
--- /dev/null
+++ b/packages/trueforge/src/db/postgres/migrations/20260904_000002_session_source.ts
@@ -0,0 +1,28 @@
+import { sql, type Kysely } from 'kysely';
+import { SESSION_SOURCE_IDX } from '../../indexes';
+
+/**
+ * Add nullable JSONB `source` on session (schedule provenance).
+ * Expression index for list filters; no denormalized scalar filter columns.
+ * Runs inside the Migrator's transaction — do not nest `db.transaction()`.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`
+ SET LOCAL lock_timeout = '5s';
+
+ ALTER TABLE session
+ ADD COLUMN source jsonb;
+ CREATE INDEX ${sql.raw(SESSION_SOURCE_IDX)}
+ ON session (tenant_id, (source->>'type'), (source->>'id'))
+ WHERE source IS NOT NULL;
+ `.execute(db);
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`
+ SET LOCAL lock_timeout = '5s';
+
+ DROP INDEX IF EXISTS ${sql.raw(SESSION_SOURCE_IDX)};
+ ALTER TABLE session DROP COLUMN IF EXISTS source;
+ `.execute(db);
+}
diff --git a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
index 248b04812..212241ede 100644
--- a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -1,4 +1,4 @@
-import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';
+import { CreatedBySubjectSchema, type TokenPagination } from '@truefoundry/trueforge-core/agent-session';
import {
decodeOffsetPageToken,
paginateOffsetRows,
@@ -6,7 +6,6 @@ import {
import type { Kysely, Selectable, Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import { newId } from '../../../utils/id';
-import { parseStoredCreatedBySubject } from '../../createdBySubject';
import {
cronRunName,
parseStoredScheduleManifest,
@@ -42,7 +41,7 @@ function toScheduleRecord(row: Selectable<ScheduleTable>): ScheduleRecord {
name: row.name,
manifest: parseStoredScheduleManifest(row.manifest),
status: row.status,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
created_at: row.created_at.toISOString(),
updated_at: row.updated_at.toISOString(),
};
@@ -56,7 +55,7 @@ function toRunRecord(row: Selectable<ScheduleRunTable>): ScheduleRunRecord {
name: row.name,
scheduled_for: row.scheduled_for.toISOString(),
status: row.status,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
triggered_at: row.triggered_at === null ? null : row.triggered_at.toISOString(),
created_at: row.created_at.toISOString(),
updated_at: row.updated_at.toISOString(),
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 8ec0ddb97..6a42edb5d 100644
--- a/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
@@ -1,10 +1,13 @@
-import type {
- AgentSpec,
- CreatedBySubject,
- SessionMetadata,
- SessionMetrics,
+import {
+ CreatedBySubjectSchema,
+ SessionMetadataSchema,
+ SessionSourceSchema,
+ type AgentSpec,
+ type CreatedBySubject,
+ type SessionMetadata,
+ type SessionMetrics,
+ type SessionSource,
} 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,
@@ -25,7 +28,6 @@ import {
SessionStoreInvariantError,
} from '@truefoundry/trueforge-core/agent-session/store/SessionStoreErrors';
import { sql, type Kysely } from 'kysely';
-import { parseStoredCreatedBySubject } from '../../../createdBySubject';
import { SESSION_EXTERNAL_ID_UQ } from '../../../indexes';
import { sessionAgentFromColumns, sessionAgentToColumns } from '../../../sessionAgentColumns';
import { isPgConstraint, isUniqueViolation } from '../../client';
@@ -57,6 +59,7 @@ function mapRowToSessionRecord(row: {
tenant_id: string;
session_id: string;
created_by_subject: CreatedBySubject;
+ source: SessionSource | null;
agent_id: string | null;
agent_name: string | null;
agent_spec: AgentSpec | null;
@@ -73,7 +76,8 @@ function mapRowToSessionRecord(row: {
return {
tenant_id: row.tenant_id,
session_id: row.session_id,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
+ source: SessionSourceSchema.nullable().parse(row.source),
agent: sessionAgentFromColumns({
session_id: row.session_id,
agent_id: row.agent_id,
@@ -103,6 +107,7 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn
tenant_id: input.tenant_id,
session_id: input.session_id,
created_by_subject: json(input.created_by_subject),
+ source: input.source !== null ? json(input.source) : null,
agent_id: columns.agent_id,
agent_name: columns.agent_name,
agent_spec: columns.agent_spec !== null ? json(columns.agent_spec) : null,
@@ -247,6 +252,12 @@ export async function listSessions(
query = query.where('agent_id', '=', input.agent_id);
}
query = whereCreatedByOrAgentIds(query, input.created_by_or_agent_ids);
+ if (input.source_type !== undefined) {
+ query = query.where(sql`source->>'type'`, '=', input.source_type);
+ }
+ if (input.source_id !== undefined) {
+ query = query.where(sql`source->>'id'`, '=', input.source_id);
+ }
if (input.start_timestamp !== undefined) {
query = query.where('created_at', '>=', input.start_timestamp);
}
diff --git a/packages/trueforge/src/db/postgres/types.ts b/packages/trueforge/src/db/postgres/types.ts
index 0335b4b17..7c1423ef7 100644
--- a/packages/trueforge/src/db/postgres/types.ts
+++ b/packages/trueforge/src/db/postgres/types.ts
@@ -8,6 +8,7 @@ import type {
PersistedTurnEvent,
SessionMetadata,
SessionMetrics,
+ SessionSource,
TurnInputItem,
TurnState,
} from '@truefoundry/trueforge-core/agent-session';
@@ -56,6 +57,10 @@ export interface SessionTable {
session_id: string;
/** Caller identity that created the session (immutable after create). */
created_by_subject: JSONColumnType<CreatedBySubject, CreatedBySubject, CreatedBySubject>;
+ /**
+ * Null for interactive sessions.
+ */
+ source: JSONColumnType<SessionSource, SessionSource | null, SessionSource | null> | null;
/**
* Named registry binding; XOR with `agent_spec`
* (CHECK session_agent_xor_check).
diff --git a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
index 3cedfebc1..e4bd2463c 100644
--- a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
+++ b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
@@ -1,4 +1,8 @@
-import type { AgentSpec, CreatedBySubject } from '@truefoundry/trueforge-core/agent-session';
+import {
+ CreatedBySubjectSchema,
+ type AgentSpec,
+ type CreatedBySubject,
+} from '@truefoundry/trueforge-core/agent-session';
import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
import { newId } from '../../../utils/id';
import {
@@ -13,7 +17,6 @@ import {
type ListAgentsInput,
type UpdateAgentInput,
} from '../../agentStore';
-import { parseStoredCreatedBySubject } from '../../createdBySubject';
import { isUniqueViolation } from '../client';
import { jsonbBind, jsonText, nowIso } from '../sqlExpressions';
import type { Database } from '../types';
@@ -45,7 +48,7 @@ function toRecord(row: {
return {
...row,
manifest: parseStoredAgentSpec(row.manifest),
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
};
}
diff --git a/packages/trueforge/src/db/sqlite/client.ts b/packages/trueforge/src/db/sqlite/client.ts
index 209745d8b..91578047d 100644
--- a/packages/trueforge/src/db/sqlite/client.ts
+++ b/packages/trueforge/src/db/sqlite/client.ts
@@ -146,6 +146,7 @@ const JSON_RESULT_COLUMNS = new Set([
'token',
'auth_data',
'created_by_subject',
+ 'source',
]);
/** Top-level row field only — `$[0]."body"`, not `$[0]."body"."content"`. */
diff --git a/packages/trueforge/src/db/sqlite/migrations/20260904_000002_session_source.ts b/packages/trueforge/src/db/sqlite/migrations/20260904_000002_session_source.ts
new file mode 100644
index 000000000..89d880394
--- /dev/null
+++ b/packages/trueforge/src/db/sqlite/migrations/20260904_000002_session_source.ts
@@ -0,0 +1,26 @@
+import { sql, type Kysely } from 'kysely';
+import { SESSION_SOURCE_IDX } from '../../indexes';
+
+/**
+ * Add nullable JSONB `source` on session. Mirrors
+ * db/postgres/migrations/20260904_000002_session_source.ts.
+ * Nullable ADD COLUMN needs no table rebuild.
+ * Kysely does not wrap SQLite migrations — keep ADD COLUMN + index atomic.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await sql`ALTER TABLE session ADD COLUMN source BLOB`.execute(trx);
+ await sql`
+ CREATE INDEX ${sql.raw(SESSION_SOURCE_IDX)}
+ ON session (tenant_id, json_extract(source, '$.type'), json_extract(source, '$.id'))
+ WHERE source IS NOT NULL
+ `.execute(trx);
+ });
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await sql`DROP INDEX IF EXISTS ${sql.raw(SESSION_SOURCE_IDX)}`.execute(trx);
+ await sql`ALTER TABLE session DROP COLUMN source`.execute(trx);
+ });
+}
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
index 810cab204..b8b1bb57e 100644
--- a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -1,4 +1,8 @@
-import type { CreatedBySubject, TokenPagination } from '@truefoundry/trueforge-core/agent-session';
+import {
+ CreatedBySubjectSchema,
+ type CreatedBySubject,
+ type TokenPagination,
+} from '@truefoundry/trueforge-core/agent-session';
import {
decodeOffsetPageToken,
paginateOffsetRows,
@@ -7,7 +11,6 @@ import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import type { ScheduleManifest, ScheduleRunStatus, ScheduleStatus } from '../../../schemas/schedule';
import { newId } from '../../../utils/id';
-import { parseStoredCreatedBySubject } from '../../createdBySubject';
import {
cronRunName,
parseStoredScheduleManifest,
@@ -95,14 +98,14 @@ function toScheduleRecord(row: ScheduleRow): ScheduleRecord {
return {
...row,
manifest: parseStoredScheduleManifest(row.manifest),
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
};
}
function toRunRecord(row: RunRow): ScheduleRunRecord {
return {
...row,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
};
}
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 46d48ef70..6eca1db0b 100644
--- a/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
@@ -1,10 +1,13 @@
-import type {
- AgentSpec,
- CreatedBySubject,
- SessionMetadata,
- SessionMetrics,
+import {
+ CreatedBySubjectSchema,
+ SessionMetadataSchema,
+ SessionSourceSchema,
+ type AgentSpec,
+ type CreatedBySubject,
+ type SessionMetadata,
+ type SessionMetrics,
+ type SessionSource,
} 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,
@@ -25,7 +28,6 @@ import {
SessionStoreInvariantError,
} from '@truefoundry/trueforge-core/agent-session/store/SessionStoreErrors';
import { sql, type Kysely } from 'kysely';
-import { parseStoredCreatedBySubject } from '../../../createdBySubject';
import { sessionAgentFromColumns, sessionAgentToColumns } from '../../../sessionAgentColumns';
import { isUniqueViolation } from '../../client';
import { jsonbBind, jsonText, nowIso, whereCreatedByOrAgentIds } from '../../sqlExpressions';
@@ -56,6 +58,7 @@ function mapRowToSessionRecord(row: {
tenant_id: string;
session_id: string;
created_by_subject: CreatedBySubject;
+ source: SessionSource | null;
agent_id: string | null;
agent_name: string | null;
agent_spec: AgentSpec | null;
@@ -72,7 +75,8 @@ function mapRowToSessionRecord(row: {
return {
tenant_id: row.tenant_id,
session_id: row.session_id,
- created_by_subject: parseStoredCreatedBySubject(row.created_by_subject),
+ created_by_subject: CreatedBySubjectSchema.parse(row.created_by_subject),
+ source: SessionSourceSchema.nullable().parse(row.source),
agent: sessionAgentFromColumns({
session_id: row.session_id,
agent_id: row.agent_id,
@@ -96,6 +100,7 @@ function sessionSelectColumns() {
'tenant_id' as const,
'session_id' as const,
jsonText<CreatedBySubject>(sql.ref('created_by_subject')).as('created_by_subject'),
+ jsonText<SessionSource | null>(sql.ref('source')).as('source'),
'agent_id' as const,
'agent_name' as const,
jsonText<AgentSpec | null>(sql.ref('agent_spec')).as('agent_spec'),
@@ -122,6 +127,7 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn
tenant_id: input.tenant_id,
session_id: input.session_id,
created_by_subject: jsonbBind(input.created_by_subject),
+ source: input.source !== null ? jsonbBind(input.source) : null,
agent_id: columns.agent_id,
agent_name: columns.agent_name,
agent_spec: columns.agent_spec !== null ? jsonbBind(columns.agent_spec) : null,
@@ -263,6 +269,12 @@ export async function listSessions(
query = query.where('agent_id', '=', input.agent_id);
}
query = whereCreatedByOrAgentIds(query, input.created_by_or_agent_ids);
+ if (input.source_type !== undefined) {
+ query = query.where(sql`json_extract(source, '$.type')`, '=', input.source_type);
+ }
+ if (input.source_id !== undefined) {
+ query = query.where(sql`json_extract(source, '$.id')`, '=', input.source_id);
+ }
if (input.start_timestamp !== undefined) {
query = query.where('created_at', '>=', input.start_timestamp.toISOString());
}
diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.ts
index dd8bcec58..a6adab314 100644
--- a/packages/trueforge/src/db/sqlite/types.ts
+++ b/packages/trueforge/src/db/sqlite/types.ts
@@ -11,6 +11,7 @@ import type {
PersistedTurnEvent,
SessionMetadata,
SessionMetrics,
+ SessionSource,
TurnInputItem,
TurnState,
} from '@truefoundry/trueforge-core/agent-session';
@@ -59,6 +60,8 @@ export interface SessionTable {
session_id: string;
/** Caller identity that created the session (immutable after create). */
created_by_subject: JsonbColumn<CreatedBySubject>;
+ /** Optional provenance (e.g. schedule). Null for interactive sessions. */
+ source: JsonbColumn<SessionSource> | null;
/** Named registry binding; XOR with `agent_spec`. */
agent_id: string | null;
/**
diff --git a/packages/trueforge/src/routes/sessionRoutes.ts b/packages/trueforge/src/routes/sessionRoutes.ts
index 87f3972a3..2a8636eae 100644
--- a/packages/trueforge/src/routes/sessionRoutes.ts
+++ b/packages/trueforge/src/routes/sessionRoutes.ts
@@ -202,7 +202,7 @@ export const listSessionsRoute = createRoute({
path: '/',
tags: [OpenApiTag.AGENT_SESSIONS],
summary: 'List sessions',
- description: "List the caller's sessions (newest first by default).",
+ description: 'List the sessions (newest first by default).',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'list',
'x-fern-pagination': TOKEN_PAGINATION,
diff --git a/packages/trueforge/src/schemas/session.ts b/packages/trueforge/src/schemas/session.ts
index 96eac8594..2aa41b27d 100644
--- a/packages/trueforge/src/schemas/session.ts
+++ b/packages/trueforge/src/schemas/session.ts
@@ -4,6 +4,8 @@ import {
AgentSpecSchema,
SessionMetadataSchema,
SessionSchema,
+ SessionSourceScheduleSchema,
+ SessionSourceTypeSchema,
TokenPaginationSchema,
} from '@truefoundry/trueforge-core/agent-session';
import { NameSchema, PAGE_LIMIT } from './common';
@@ -43,6 +45,8 @@ export const GetOrCreateSessionByExternalIdRequestSchema = z
.object({
external_id: z.string().min(1).max(128).describe('Caller-supplied id unique within the tenant.'),
agent: CreateSessionAgentSchema,
+ /** Internal-only provenance; not on public create/update. */
+ source: SessionSourceScheduleSchema.optional(),
})
.strict()
.openapi('GetOrCreateSessionByExternalIdRequest');
@@ -97,6 +101,18 @@ export const ListSessionsRequestQuerySchema = z
.optional()
.describe('When true, only sessions created by the authenticated subject.')
.openapi({ type: 'boolean' }),
+ source_type: SessionSourceTypeSchema.optional().describe(
+ 'When set, returns only sessions created by this source type.',
+ ),
+ source_id: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('When set, returns only sessions from this specific source. Requires source_type.'),
+ })
+ .refine(q => q.source_id === undefined || q.source_type !== undefined, {
+ message: 'source_id requires source_type',
+ path: ['source_id'],
})
.openapi('ListSessionsRequestQuery');
diff --git a/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts b/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
index 5dc79a1fd..a3d1fdab1 100644
--- a/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
+++ b/packages/trueforge/tests/db/session-metrics/metricsContractSuite.ts
@@ -34,6 +34,7 @@ export function runSessionMetricsStoreContractSuite(
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await sessionStore.createSession({
tenant_id: tenant,
@@ -43,6 +44,7 @@ export function runSessionMetricsStoreContractSuite(
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await sessionStore.createTurn(makeCreateTurnInput({ sessionId: 'metrics-session', turnId: 'metrics-turn' }));
const turn = mustGet(await sessionStore.getTurn({ session_id: 'metrics-session', turn_id: 'metrics-turn' }));
@@ -132,6 +134,7 @@ export function runSessionMetricsStoreContractSuite(
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
for (const [index, durationMs] of definition.turnDurations.entries()) {
const turnId = `${definition.id}-turn-${String(index)}`;
@@ -182,6 +185,7 @@ export function runSessionMetricsStoreContractSuite(
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await sessionStore.createSession({
tenant_id: tenant,
@@ -191,6 +195,7 @@ export function runSessionMetricsStoreContractSuite(
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await sessionStore.createTurn(makeCreateTurnInput({ sessionId: 'inflight-session', turnId: 'inflight-turn' }));
await sessionStore.createTurn(makeCreateTurnInput({ sessionId: 'completed-session', turnId: 'completed-turn' }));
diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
index 03ebf907e..e86368a2f 100644
--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
@@ -94,6 +94,7 @@ describe('public CRUD after session deletion', () => {
custom: null,
metadata: {},
external_id: null,
+ source: 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 96ab1ae02..2cb81736d 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -199,6 +199,7 @@ describe('sessions HTTP agent binding', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
await sessionStore.createSession({
tenant_id: 'default',
@@ -208,6 +209,7 @@ describe('sessions HTTP agent binding', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const start = new Date(Date.now() - 60 * 60 * 1000);
const end = new Date(Date.now() + 60 * 60 * 1000);
@@ -252,6 +254,7 @@ describe('sessions HTTP agent binding', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const managerAuthorizer: Authorizer = {
listAgentAccess: input =>
@@ -350,6 +353,7 @@ describe('sessions HTTP agent binding', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const created = await app.request('/', jsonInit('POST', { agent: { spec: inlineSpec } }));
@@ -543,6 +547,7 @@ describe('sessions HTTP agent binding', () => {
custom: null,
metadata: {},
external_id: 'run-theirs',
+ source: null,
});
const forbidden = await app.request(
'/api/internal/sessions/get-or-create-by-external-id',
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index c64080a2b..418a8331f 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -54,6 +54,7 @@ describe('turns', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const tokenStore = new SqliteOAuthTokenStore(db);
@@ -131,6 +132,7 @@ describe('turns', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const app = new OpenAPIHono();
app.route(
@@ -443,6 +445,7 @@ describe('turns', () => {
custom: null,
metadata: {},
external_id: null,
+ source: null,
});
const tokenStore = new SqliteOAuthTokenStore(db);
const app = new OpenAPIHono();
diff --git a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
index 3ce42a034..51de78ce2 100644
--- a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
+++ b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
@@ -91,6 +91,7 @@ describe('scheduleDispatchLoop', () => {
expect(getOrCreateByExternalId).toHaveBeenCalledWith({
externalId: 'run-1',
agent: { name: 'reporter' },
+ source: { type: 'schedule', id: 'sched-1', runId: 'run-1' },
});
expect(listTurns).toHaveBeenCalledWith('sess-1', { limit: 1 });
expect(createTurn).toHaveBeenCalledWith('sess-1', {
@@ -154,6 +155,7 @@ describe('startScheduleRun', () => {
external_id: 'run-1',
created_by_subject: { subject_id: 'tester', subject_type: 'user', subject_display_name: 'tester' },
agent: { type: 'reference', id: 'agent-1', name: 'reporter' },
+ source: { type: 'schedule', id: 'sched-1', run_id: 'run-1' },
});
expect(startTurn).toHaveBeenCalledWith({
session,