Skip to content

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

feat: list schedules should take multiple agents as filter + add pagination (#534)

Srajan Asthana3bc2ed809183
diff --git a/.changeset/schedule-list-pagination.md b/.changeset/schedule-list-pagination.md
new file mode 100644
index 000000000..0dd67dcce
--- /dev/null
+++ b/.changeset/schedule-list-pagination.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+List schedules is token-paginated (`limit` / `page_token`) and filters by comma-separated `agent_names`.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 18bd31b3f..d960966e2 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1701,10 +1701,14 @@
"$ref": "#/components/schemas/Schedule"
},
"type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
}
},
"required": [
- "data"
+ "data",
+ "pagination"
],
"type": "object"
},
@@ -5778,14 +5782,39 @@
},
"/api/v1/schedules": {
"get": {
- "description": "List schedules for the tenant, newest first. Optionally filter by `agent_name`.",
+ "description": "List schedules for the tenant, newest first. Optionally filter by `agent_names`.",
"parameters": [
{
+ "description": "Page size. Defaults to 25",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 25,
+ "description": "Page size. Defaults to 25",
+ "maximum": 25,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "description": "Opaque token from a previous response `next_page_token`.",
"in": "query",
- "name": "agent_name",
+ "name": "page_token",
"required": false,
"schema": {
- "$ref": "#/components/schemas/ResourceName"
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Filter by one or more agent names (comma-separated). When set, at least one name is required.",
+ "in": "query",
+ "name": "agent_names",
+ "required": false,
+ "schema": {
+ "description": "Filter by one or more agent names (comma-separated). When set, at least one name is required.",
+ "type": "string"
}
}
],
@@ -5798,7 +5827,17 @@
}
}
},
- "description": "Matching schedules."
+ "description": "Paginated matching schedules."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid query parameters or page token."
},
"401": {
"content": {
@@ -5815,6 +5854,11 @@
"tags": [
"Schedules"
],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
"x-fern-sdk-group-name": [
"schedules"
],
diff --git a/docs/openapi.json b/docs/openapi.json
index 18bd31b3f..d960966e2 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1701,10 +1701,14 @@
"$ref": "#/components/schemas/Schedule"
},
"type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
}
},
"required": [
- "data"
+ "data",
+ "pagination"
],
"type": "object"
},
@@ -5778,14 +5782,39 @@
},
"/api/v1/schedules": {
"get": {
- "description": "List schedules for the tenant, newest first. Optionally filter by `agent_name`.",
+ "description": "List schedules for the tenant, newest first. Optionally filter by `agent_names`.",
"parameters": [
{
+ "description": "Page size. Defaults to 25",
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 25,
+ "description": "Page size. Defaults to 25",
+ "maximum": 25,
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "description": "Opaque token from a previous response `next_page_token`.",
"in": "query",
- "name": "agent_name",
+ "name": "page_token",
"required": false,
"schema": {
- "$ref": "#/components/schemas/ResourceName"
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
+ },
+ {
+ "description": "Filter by one or more agent names (comma-separated). When set, at least one name is required.",
+ "in": "query",
+ "name": "agent_names",
+ "required": false,
+ "schema": {
+ "description": "Filter by one or more agent names (comma-separated). When set, at least one name is required.",
+ "type": "string"
}
}
],
@@ -5798,7 +5827,17 @@
}
}
},
- "description": "Matching schedules."
+ "description": "Paginated matching schedules."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid query parameters or page token."
},
"401": {
"content": {
@@ -5815,6 +5854,11 @@
"tags": [
"Schedules"
],
+ "x-fern-pagination": {
+ "cursor": "$request.page_token",
+ "next_cursor": "$response.pagination.next_page_token",
+ "results": "$response.data"
+ },
"x-fern-sdk-group-name": [
"schedules"
],
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 65bd6ed2f..e86590731 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -750,7 +750,7 @@ await client.models.list();
</details>
## Schedules
-<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">list</a>({ ...params }) -> TrueForge.ListSchedulesResponse</code></summary>
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">list</a>({ ...params }) -> core.Page&lt;TrueForge.Schedule, TrueForge.ListSchedulesResponse&gt;</code></summary>
<dl>
<dd>
@@ -762,7 +762,7 @@ await client.models.list();
<dl>
<dd>
-List schedules for the tenant, newest first. Optionally filter by `agent_name`.
+List schedules for the tenant, newest first. Optionally filter by `agent_names`.
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
index 420656b67..cb4816f03 100644
--- a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
@@ -24,11 +24,12 @@ export class SchedulesClient {
}
/**
- * List schedules for the tenant, newest first. Optionally filter by `agent_name`.
+ * List schedules for the tenant, newest first. Optionally filter by `agent_names`.
*
* @param {TrueForge.ListSchedulesRequest} request
* @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.UnauthorizedError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -36,82 +37,104 @@ export class SchedulesClient {
* @example
* await client.schedules.list()
*/
- public list(
+ public async list(
request: TrueForge.ListSchedulesRequest = {},
requestOptions?: SchedulesClient.RequestOptions,
- ): core.HttpResponsePromise<TrueForge.ListSchedulesResponse> {
- return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions));
- }
-
- private async __list(
- request: TrueForge.ListSchedulesRequest = {},
- requestOptions?: SchedulesClient.RequestOptions,
- ): Promise<core.WithRawResponse<TrueForge.ListSchedulesResponse>> {
- const { agentName } = request;
- const _queryParams: Record<string, unknown> = {
- agent_name: agentName,
- };
- const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
- _authRequest.headers,
- this._options?.headers,
- requestOptions?.headers,
- );
- const _response = await (this._options.fetcher ?? core.fetcher)({
- url: core.url.join(
- (await core.Supplier.get(this._options.baseUrl)) ??
- (await core.Supplier.get(this._options.environment)),
- "api/v1/schedules",
- ),
- method: "GET",
- headers: _headers,
- queryString: core.url
- .queryBuilder()
- .addMany(_queryParams)
- .mergeAdditional(requestOptions?.queryParams)
- .build(),
- timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
- maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
- abortSignal: requestOptions?.abortSignal,
- fetchFn: this._options?.fetch,
- logging: this._options.logging,
- });
- if (_response.ok) {
- return {
- data: serializers.ListSchedulesResponse.parseOrThrow(_response.body, {
- unrecognizedObjectKeys: "passthrough",
- allowUnrecognizedUnionMembers: true,
- allowUnrecognizedEnumValues: true,
- skipValidation: true,
- breadcrumbsPrefix: ["response"],
- }),
- rawResponse: _response.rawResponse,
- };
- }
-
- if (_response.error.reason === "status-code") {
- switch (_response.error.statusCode) {
- case 401:
- throw new TrueForge.UnauthorizedError(
- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ ): Promise<core.Page<TrueForge.Schedule, TrueForge.ListSchedulesResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueForge.ListSchedulesRequest,
+ ): Promise<core.WithRawResponse<TrueForge.ListSchedulesResponse>> => {
+ const { limit = 25, pageToken, agentNames } = request;
+ const _queryParams: Record<string, unknown> = {
+ limit,
+ page_token: pageToken,
+ agent_names: agentNames,
+ };
+ const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
+ _authRequest.headers,
+ this._options?.headers,
+ requestOptions?.headers,
+ );
+ const _response = await (this._options.fetcher ?? core.fetcher)({
+ url: core.url.join(
+ (await core.Supplier.get(this._options.baseUrl)) ??
+ (await core.Supplier.get(this._options.environment)),
+ "api/v1/schedules",
+ ),
+ method: "GET",
+ headers: _headers,
+ queryString: core.url
+ .queryBuilder()
+ .addMany(_queryParams)
+ .mergeAdditional(requestOptions?.queryParams)
+ .build(),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListSchedulesResponse.parseOrThrow(_response.body, {
unrecognizedObjectKeys: "passthrough",
allowUnrecognizedUnionMembers: true,
allowUnrecognizedEnumValues: true,
skipValidation: true,
breadcrumbsPrefix: ["response"],
}),
- _response.rawResponse,
- );
- default:
- throw new errors.TrueForgeError({
- statusCode: _response.error.statusCode,
- body: _response.error.body,
rawResponse: _response.rawResponse,
- });
- }
- }
-
- return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/schedules");
+ };
+ }
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueForge.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 401:
+ throw new TrueForge.UnauthorizedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/schedules");
+ },
+ );
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueForge.Schedule, TrueForge.ListSchedulesResponse>({
+ response: dataWithRawResponse.data,
+ rawResponse: dataWithRawResponse.rawResponse,
+ hasNextPage: (response) =>
+ response?.pagination.nextPageToken != null &&
+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
+ getItems: (response) => response?.data ?? [],
+ loadPage: (response) => {
+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
+ },
+ });
}
/**
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListSchedulesRequest.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListSchedulesRequest.ts
index 9cdfd1c37..4bb5272d3 100644
--- a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListSchedulesRequest.ts
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListSchedulesRequest.ts
@@ -1,11 +1,14 @@
// This file was auto-generated by Fern from our API Definition.
-import type * as TrueForge from "../../../../index.js";
-
/**
* @example
* {}
*/
export interface ListSchedulesRequest {
- agentName?: TrueForge.ResourceName;
+ /** Page size. Defaults to 25 */
+ limit?: number;
+ /** Opaque token from a previous response `next_page_token`. */
+ pageToken?: string;
+ /** Filter by one or more agent names (comma-separated). When set, at least one name is required. */
+ agentNames?: string;
}
diff --git a/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts b/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts
index 547843582..423d2a0a1 100644
--- a/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts
+++ b/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts
@@ -4,4 +4,5 @@ import type * as TrueForge from "../index.js";
export interface ListSchedulesResponse {
data: TrueForge.Schedule[];
+ pagination: TrueForge.TokenPagination;
}
diff --git a/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.ts
index f911bbefa..889483773 100644
--- a/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.ts
+++ b/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.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 { Schedule } from "./Schedule.js";
+import { TokenPagination } from "./TokenPagination.js";
export const ListSchedulesResponse: core.serialization.ObjectSchema<
serializers.ListSchedulesResponse.Raw,
TrueForge.ListSchedulesResponse
> = core.serialization.object({
data: core.serialization.list(Schedule),
+ pagination: TokenPagination,
});
export declare namespace ListSchedulesResponse {
export interface Raw {
data: Schedule.Raw[];
+ pagination: TokenPagination.Raw;
}
}
diff --git a/packages/trueforge-sdk/tests/wire/schedules.test.ts b/packages/trueforge-sdk/tests/wire/schedules.test.ts
index dc549b39b..ab1a8509d 100644
--- a/packages/trueforge-sdk/tests/wire/schedules.test.ts
+++ b/packages/trueforge-sdk/tests/wire/schedules.test.ts
@@ -21,12 +21,18 @@ describe("SchedulesClient", () => {
updated_at: "2024-01-15T09:30:00Z",
},
],
+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },
};
- server.mockEndpoint().get("/api/v1/schedules").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+ server
+ .mockEndpoint({ once: false })
+ .get("/api/v1/schedules")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
- const response = await client.schedules.list();
- expect(response).toEqual({
+ const expected = {
data: [
{
agentName: "agent_name",
@@ -41,7 +47,18 @@ describe("SchedulesClient", () => {
updatedAt: new Date("2024-01-15T09:30:00.000Z"),
},
],
- });
+ pagination: {
+ limit: 1,
+ nextPageToken: "next_page_token",
+ previousPageToken: "previous_page_token",
+ },
+ };
+ const page = await client.schedules.list();
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
});
test("list (2)", async () => {
@@ -50,6 +67,19 @@ describe("SchedulesClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server.mockEndpoint().get("/api/v1/schedules").respondWith().statusCode(400).jsonBody(rawResponseBody).build();
+
+ await expect(async () => {
+ return await client.schedules.list();
+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);
+ });
+
+ test("list (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server.mockEndpoint().get("/api/v1/schedules").respondWith().statusCode(401).jsonBody(rawResponseBody).build();
await expect(async () => {
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index 028c9c459..ca57d7215 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -2,6 +2,7 @@
* Schedules API (mounted at /api/v1/schedules).
*/
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
+import { InvalidPageTokenError } from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
import type { UserContext } from '../auth/identity';
import type { IAgentStore } from '../db/agentStore';
@@ -109,16 +110,25 @@ function canAccessSchedule(user: UserContext, createdBy: string): boolean {
export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listSchedulesRoute> = async c => {
- const { agent_name: agentName } = c.req.valid('query');
+ const { agent_names: agentNames, limit, page_token: pageToken } = c.req.valid('query');
const user = deps.resolveUserContext(c);
// Admins see every schedule; a regular user is scoped to their own via the
// store's `created_by` filter (never a client-supplied param).
- const records = await deps.scheduleStore.listSchedules({
- tenant_id: TENANT_ID,
- agent_name: agentName,
- created_by: user.role === 'admin' ? undefined : user.userRef,
- });
- return c.json({ data: records.map(toWireSchedule) }, 200);
+ try {
+ const { data, pagination } = await deps.scheduleStore.listSchedules({
+ tenant_id: TENANT_ID,
+ limit,
+ page_token: pageToken,
+ agent_names: agentNames,
+ created_by: user.role === 'admin' ? undefined : user.userRef,
+ });
+ return c.json({ data: data.map(toWireSchedule), pagination }, 200);
+ } catch (error) {
+ if (error instanceof InvalidPageTokenError) {
+ return c.json({ error: { message: error.message } }, 400);
+ }
+ throw error;
+ }
};
const listRunsHandler: RouteHandler<typeof listScheduleRunsRoute> = async c => {
diff --git a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
index f81bb8672..e32a1af7f 100644
--- a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -1,3 +1,8 @@
+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';
+import {
+ decodeOffsetPageToken,
+ paginateOffsetRows,
+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';
import type { Kysely, Selectable, Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import { newId } from '../../../utils/id';
@@ -212,17 +217,27 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
await db.deleteFrom('schedule').where('tenant_id', '=', input.tenant_id).where('id', '=', input.id).execute();
}
- async listSchedules(input: ListSchedulesInput, transaction?: Transaction<Database>): Promise<ScheduleRecord[]> {
+ async listSchedules(
+ input: ListSchedulesInput,
+ transaction?: Transaction<Database>,
+ ): Promise<{ data: ScheduleRecord[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
const db = transaction ?? this.#db;
let query = db.selectFrom('schedule').selectAll().where('tenant_id', '=', input.tenant_id);
- if (input.agent_name !== undefined) {
- query = query.where('agent_name', '=', input.agent_name);
+ if (input.agent_names !== undefined) {
+ query = query.where('agent_name', 'in', [...input.agent_names]);
}
if (input.created_by !== undefined) {
query = query.where('created_by', '=', input.created_by);
}
- const rows = await query.orderBy('created_at', 'desc').orderBy('id').execute();
- return rows.map(toScheduleRecord);
+ const rows = await query
+ .orderBy('created_at', 'desc')
+ .orderBy('id')
+ .limit(input.limit + 1)
+ .offset(offset)
+ .execute();
+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);
+ return { data: data.map(toScheduleRecord), pagination };
}
async listRuns(input: ListRunsInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord[]> {
diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.ts
index ddcba646e..217c2cbf9 100644
--- a/packages/trueforge/src/db/scheduleStore.ts
+++ b/packages/trueforge/src/db/scheduleStore.ts
@@ -13,6 +13,7 @@
*
* Implementations: PostgresScheduleStore and SqliteScheduleStore.
*/
+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';
import {
ScheduleManifestSchema,
type ScheduleManifest,
@@ -83,8 +84,10 @@ export function parseStoredScheduleManifest(manifest: unknown): ScheduleManifest
export interface ListSchedulesInput {
tenant_id: string;
- /** When set, only schedules bound to this agent name are returned. */
- agent_name?: string | undefined;
+ limit: number;
+ page_token: string | undefined;
+ /** When set, only schedules for these agent names */
+ agent_names: readonly string[] | undefined;
created_by?: string | undefined;
}
@@ -222,7 +225,10 @@ export interface IScheduleStore<TTransaction = never> {
): Promise<ScheduleWriteResult | undefined>;
/** Deletes by immutable id; runs cascade. Idempotent if already missing. */
deleteSchedule(input: DeleteScheduleInput, transaction?: TTransaction): Promise<void>;
- listSchedules(input: ListSchedulesInput, transaction?: TTransaction): Promise<ScheduleRecord[]>;
+ listSchedules(
+ input: ListSchedulesInput,
+ transaction?: TTransaction,
+ ): Promise<{ data: ScheduleRecord[]; pagination: TokenPagination }>;
// --- schedule_run ---
/** One run by immutable id. */
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
index 22b8c6de5..83c901d93 100644
--- a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -1,3 +1,8 @@
+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';
+import {
+ decodeOffsetPageToken,
+ paginateOffsetRows,
+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';
import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import type { ScheduleManifest, ScheduleRunStatus, ScheduleStatus } from '../../../schemas/schedule';
@@ -250,17 +255,27 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
await db.deleteFrom('schedule').where('tenant_id', '=', input.tenant_id).where('id', '=', input.id).execute();
}
- async listSchedules(input: ListSchedulesInput, transaction?: Transaction<Database>): Promise<ScheduleRecord[]> {
+ async listSchedules(
+ input: ListSchedulesInput,
+ transaction?: Transaction<Database>,
+ ): Promise<{ data: ScheduleRecord[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
const db = transaction ?? this.#db;
let query = db.selectFrom('schedule').select(scheduleColumns).where('tenant_id', '=', input.tenant_id);
- if (input.agent_name !== undefined) {
- query = query.where('agent_name', '=', input.agent_name);
+ if (input.agent_names !== undefined) {
+ query = query.where('agent_name', 'in', [...input.agent_names]);
}
if (input.created_by !== undefined) {
query = query.where('created_by', '=', input.created_by);
}
- const rows = await query.orderBy('created_at', 'desc').orderBy('id').execute();
- return rows.map(toScheduleRecord);
+ const rows = await query
+ .orderBy('created_at', 'desc')
+ .orderBy('id')
+ .limit(input.limit + 1)
+ .offset(offset)
+ .execute();
+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);
+ return { data: data.map(toScheduleRecord), pagination };
}
async listRuns(input: ListRunsInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord[]> {
diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.ts
index 7fa082ec5..038b579ed 100644
--- a/packages/trueforge/src/routes/scheduleRoutes.ts
+++ b/packages/trueforge/src/routes/scheduleRoutes.ts
@@ -3,7 +3,7 @@
* Handlers are registered in apis/schedules.ts.
*/
import { createRoute, z } from '@hono/zod-openapi';
-import { NameSchema } from '../schemas/common';
+import { NameSchema, PAGE_LIMIT, parseCommaSeparatedQuery } from '../schemas/common';
import { RequestErrorResponseSchema } from '../schemas/errors';
import {
CreateScheduleRequestSchema,
@@ -13,6 +13,7 @@ import {
ListSchedulesResponseSchema,
UpdateScheduleRequestSchema,
} from '../schemas/schedule';
+import { TOKEN_PAGINATION } from './fernExtensions';
import { OpenApiTag } from './openapiTags';
export const ScheduleIdParamsSchema = z.object({
@@ -21,7 +22,25 @@ export const ScheduleIdParamsSchema = z.object({
export const ListSchedulesQuerySchema = z
.object({
- agent_name: NameSchema.optional(),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(PAGE_LIMIT)
+ .optional()
+ .default(PAGE_LIMIT)
+ .describe(`Page size. Defaults to ${String(PAGE_LIMIT)}`),
+ page_token: z.string().optional().describe('Opaque token from a previous response `next_page_token`.'),
+ // comma-separated string -> array of names
+ agent_names: z
+ .string()
+ .optional()
+ .openapi({
+ type: 'string',
+ description: 'Filter by one or more agent names (comma-separated). When set, at least one name is required.',
+ })
+ .transform(value => parseCommaSeparatedQuery(value))
+ .pipe(z.array(NameSchema).min(1).optional()),
})
.openapi('ListSchedulesQuery');
@@ -30,16 +49,21 @@ export const listSchedulesRoute = createRoute({
path: '/',
tags: [OpenApiTag.SCHEDULES],
summary: 'List schedules',
- description: 'List schedules for the tenant, newest first. Optionally filter by `agent_name`.',
+ description: 'List schedules for the tenant, newest first. Optionally filter by `agent_names`.',
'x-fern-sdk-group-name': ['schedules'],
'x-fern-sdk-method-name': 'list',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
query: ListSchedulesQuerySchema,
},
responses: {
200: {
content: { 'application/json': { schema: ListSchedulesResponseSchema } },
- description: 'Matching schedules.',
+ description: 'Paginated matching schedules.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid query parameters or page token.',
},
401: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/schemas/common.ts b/packages/trueforge/src/schemas/common.ts
index f16f4b43f..d96e14a65 100644
--- a/packages/trueforge/src/schemas/common.ts
+++ b/packages/trueforge/src/schemas/common.ts
@@ -19,7 +19,6 @@ export const NameSchema = z
export type ResourceName = z.infer<typeof NameSchema>;
-/** Sessions and turns list page size (default = max). */
export const PAGE_LIMIT = 25;
/** Session/turn event list page size (default = max). */
export const EVENTS_PAGE_LIMIT = 100;
@@ -51,3 +50,16 @@ export function uniqueTypes(entries: { type: string }[], ctx: z.RefinementCtx):
seen.add(entry.type);
}
}
+
+/**
+ * Normalize a CSV query value (`?foo=a,b`) into a string list.
+ */
+export function parseCommaSeparatedQuery(val: unknown): string[] | undefined {
+ if (typeof val !== 'string') {
+ return undefined;
+ }
+ return val
+ .split(',')
+ .map(part => part.trim())
+ .filter(part => part.length > 0);
+}
diff --git a/packages/trueforge/src/schemas/schedule.ts b/packages/trueforge/src/schemas/schedule.ts
index b02acd343..bcc8eb5d1 100644
--- a/packages/trueforge/src/schemas/schedule.ts
+++ b/packages/trueforge/src/schemas/schedule.ts
@@ -1,4 +1,5 @@
import { z } from '@hono/zod-openapi';
+import { TokenPaginationSchema } from '@truefoundry/trueforge-core/agent-session';
import { NameSchema } from './common';
/**
@@ -119,7 +120,12 @@ export const UpdateScheduleRequestSchema = z
.openapi('UpdateScheduleRequest');
export const GetScheduleResponseSchema = z.object({ data: ScheduleSchema }).openapi('GetScheduleResponse');
-export const ListSchedulesResponseSchema = z.object({ data: z.array(ScheduleSchema) }).openapi('ListSchedulesResponse');
+export const ListSchedulesResponseSchema = z
+ .object({
+ data: z.array(ScheduleSchema),
+ pagination: TokenPaginationSchema,
+ })
+ .openapi('ListSchedulesResponse');
export const DeleteScheduleResponseSchema = z.object({}).openapi('DeleteScheduleResponse');
/**
diff --git a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
index ab67e9ca0..b83a627e0 100644
--- a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
+++ b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
@@ -476,7 +476,7 @@ export function runScheduleStoreContractSuite(deps: {
).rejects.toThrow();
});
- it('listSchedules returns newest first and filters by agent_name', async () => {
+ it('listSchedules returns newest first and filters by agent_names', async () => {
const store = deps.getScheduleStore();
const agentA = await seedAgent();
const agentB = await seedAgent();
@@ -509,22 +509,67 @@ export function runScheduleStoreContractSuite(deps: {
runFrom: new Date(),
});
- const forA = await store.listSchedules({ tenant_id: TENANT, agent_name: agentA.name });
- expect(forA.map(row => row.id)).toEqual([newer.schedule.id, older.schedule.id]);
- expect(forA.every(row => row.agent_name === agentA.name)).toBe(true);
+ const forA = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 25,
+ page_token: undefined,
+ agent_names: [agentA.name],
+ });
+ expect(forA.data.map(row => row.id)).toEqual([newer.schedule.id, older.schedule.id]);
+ expect(forA.data.every(row => row.agent_name === agentA.name)).toBe(true);
+ expect(forA.pagination.next_page_token).toBeUndefined();
+
+ const forB = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 25,
+ page_token: undefined,
+ agent_names: [agentB.name],
+ });
+ expect(forB.data.map(row => row.id)).toEqual([otherAgent.schedule.id]);
- const forB = await store.listSchedules({ tenant_id: TENANT, agent_name: agentB.name });
- expect(forB.map(row => row.id)).toEqual([otherAgent.schedule.id]);
+ const forBoth = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 25,
+ page_token: undefined,
+ agent_names: [agentA.name, agentB.name],
+ });
+ expect(forBoth.data.map(row => row.id)).toEqual([otherAgent.schedule.id, newer.schedule.id, older.schedule.id]);
- const all = await store.listSchedules({ tenant_id: TENANT });
- expect(all.map(row => row.id)).toEqual(
+ const all = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 25,
+ page_token: undefined,
+ agent_names: undefined,
+ });
+ expect(all.data.map(row => row.id)).toEqual(
expect.arrayContaining([newer.schedule.id, older.schedule.id, otherAgent.schedule.id]),
);
- const indexNewer = all.findIndex(row => row.id === newer.schedule.id);
- const indexOlder = all.findIndex(row => row.id === older.schedule.id);
+ const indexNewer = all.data.findIndex(row => row.id === newer.schedule.id);
+ const indexOlder = all.data.findIndex(row => row.id === older.schedule.id);
expect(indexNewer).toBeGreaterThanOrEqual(0);
expect(indexOlder).toBeGreaterThanOrEqual(0);
expect(indexNewer).toBeLessThan(indexOlder);
+
+ const page1 = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 2,
+ page_token: undefined,
+ agent_names: undefined,
+ });
+ expect(page1.data).toHaveLength(2);
+ expect(page1.pagination.limit).toBe(2);
+ expect(page1.pagination.next_page_token).toEqual(expect.any(String));
+
+ const page2 = await store.listSchedules({
+ tenant_id: TENANT,
+ limit: 2,
+ page_token: page1.pagination.next_page_token,
+ agent_names: undefined,
+ });
+ expect(page2.data).toHaveLength(1);
+ expect(page1.data.map(row => row.id)).not.toContain(page2.data[0]?.id);
+ expect(page2.pagination.previous_page_token).toEqual(expect.any(String));
+ expect(page2.pagination.next_page_token).toBeUndefined();
});
it('listRuns returns newest scheduled_for first and filters by schedule_id', async () => {
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index efe2c9de1..5a304e347 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -151,3 +151,53 @@ describe('schedule RBAC — creator-scoped, admin sees all', () => {
expect((await app.request(`/${aliceId}/runs`)).status).toBe(403);
});
});
+
+describe('schedule list agent_names filter', () => {
+ it('filters by a single agent_names value and by comma-separated agent_names', async () => {
+ const { app, asUser, agentStore, postJson } = await setup();
+ await agentStore.createAgent({
+ tenant_id: TENANT_ID,
+ name: 'reporter-two',
+ manifest: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' }, instructions: 'test' }),
+ });
+
+ asUser(ALICE);
+ const aliceCreated = await postJson('/', 'POST', scheduleBody);
+ const aliceId = ((await aliceCreated.json()) as { data: { id: string } }).data.id;
+ const secondCreated = await postJson('/', 'POST', {
+ ...scheduleBody,
+ agent_name: 'reporter-two',
+ name: 'daily-report-two',
+ });
+ const secondId = ((await secondCreated.json()) as { data: { id: string } }).data.id;
+
+ const single = await app.request('/?agent_names=reporter');
+ expect(single.status).toBe(200);
+ expect(ListSchedulesResponseSchema.parse(await single.json()).data.map(row => row.id)).toEqual([aliceId]);
+
+ const multi = await app.request('/?agent_names=reporter,reporter-two');
+ expect(multi.status).toBe(200);
+ expect(
+ ListSchedulesResponseSchema.parse(await multi.json())
+ .data.map(row => row.id)
+ .sort(),
+ ).toEqual([aliceId, secondId].sort());
+
+ const withGaps = await app.request('/?agent_names=reporter,,reporter-two');
+ expect(withGaps.status).toBe(200);
+ expect(
+ ListSchedulesResponseSchema.parse(await withGaps.json())
+ .data.map(row => row.id)
+ .sort(),
+ ).toEqual([aliceId, secondId].sort());
+
+ const omitted = await app.request('/');
+ expect(ListSchedulesResponseSchema.parse(await omitted.json()).data).toHaveLength(2);
+
+ // Present but empty / comma-only values fail validation.
+ for (const query of ['/?agent_names=', '/?agent_names=,,,', '/?agent_names=%20,%20']) {
+ const empty = await app.request(query);
+ expect(empty.status).toBe(400);
+ }
+ });
+});
diff --git a/packages/trueforge/tests/unit/schemas/parseCommaSeparatedQuery.test.ts b/packages/trueforge/tests/unit/schemas/parseCommaSeparatedQuery.test.ts
new file mode 100644
index 000000000..7a9b6a889
--- /dev/null
+++ b/packages/trueforge/tests/unit/schemas/parseCommaSeparatedQuery.test.ts
@@ -0,0 +1,20 @@
+import { parseCommaSeparatedQuery } from '../../../src/schemas/common';
+
+describe('parseCommaSeparatedQuery', () => {
+ it('returns undefined when absent or non-string', () => {
+ expect(parseCommaSeparatedQuery(undefined)).toBeUndefined();
+ expect(parseCommaSeparatedQuery(['a', 'b'])).toBeUndefined();
+ });
+
+ it('returns an empty array when the string has no non-empty segments', () => {
+ expect(parseCommaSeparatedQuery('')).toEqual([]);
+ expect(parseCommaSeparatedQuery(' ')).toEqual([]);
+ expect(parseCommaSeparatedQuery(',,,')).toEqual([]);
+ expect(parseCommaSeparatedQuery(' , , ')).toEqual([]);
+ });
+
+ it('splits on commas, trims, and drops empty segments', () => {
+ expect(parseCommaSeparatedQuery('reporter,,reporter-two')).toEqual(['reporter', 'reporter-two']);
+ expect(parseCommaSeparatedQuery(' a , b ')).toEqual(['a', 'b']);
+ });
+});