Skip to content

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

chore: add pagination to list runs API (#649)

Srajan Asthana2b6c566f8785
diff --git a/.changeset/paginate-list-schedule-runs.md b/.changeset/paginate-list-schedule-runs.md
new file mode 100644
index 000000000..061fa33b1
--- /dev/null
+++ b/.changeset/paginate-list-schedule-runs.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+Paginate `GET /api/v1/schedules/{schedule_id}/runs` with `limit` / `page_token` and a `pagination` envelope.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 2483e5ef6..d363e49a2 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1772,10 +1772,14 @@
"$ref": "#/components/schemas/ScheduleRun"
},
"type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
}
},
"required": [
- "data"
+ "data",
+ "pagination"
],
"type": "object"
},
@@ -6808,6 +6812,29 @@
"minLength": 1,
"type": "string"
}
+ },
+ {
+ "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": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
}
],
"responses": {
@@ -6819,7 +6846,17 @@
}
}
},
- "description": "Runs of the schedule."
+ "description": "Paginated runs of the schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid query parameters or page token."
},
"403": {
"content": {
@@ -6846,6 +6883,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 2483e5ef6..d363e49a2 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1772,10 +1772,14 @@
"$ref": "#/components/schemas/ScheduleRun"
},
"type": "array"
+ },
+ "pagination": {
+ "$ref": "#/components/schemas/TokenPagination"
}
},
"required": [
- "data"
+ "data",
+ "pagination"
],
"type": "object"
},
@@ -6808,6 +6812,29 @@
"minLength": 1,
"type": "string"
}
+ },
+ {
+ "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": "page_token",
+ "required": false,
+ "schema": {
+ "description": "Opaque token from a previous response `next_page_token`.",
+ "type": "string"
+ }
}
],
"responses": {
@@ -6819,7 +6846,17 @@
}
}
},
- "description": "Runs of the schedule."
+ "description": "Paginated runs of the schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid query parameters or page token."
},
"403": {
"content": {
@@ -6846,6 +6883,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 901600cf5..9eaf05a3b 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -1159,7 +1159,7 @@ await client.schedules.delete("schedule_id");
</dl>
</details>
-<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">listRuns</a>(schedule_id) -> TrueForge.ListScheduleRunsResponse</code></summary>
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">listRuns</a>(schedule_id, { ...params }) -> core.Page&lt;TrueForge.ScheduleRun, TrueForge.ListScheduleRunsResponse&gt;</code></summary>
<dl>
<dd>
@@ -1210,6 +1210,14 @@ await client.schedules.listRuns("schedule_id");
<dl>
<dd>
+**request:** `TrueForge.ListRunsSchedulesRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
**requestOptions:** `SchedulesClient.RequestOptions`
</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 d14d741bb..1199f6e37 100644
--- a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
@@ -755,8 +755,10 @@ export class SchedulesClient {
* List runs of a schedule, newest `scheduled_for` first. Available to its creator or a manager of its agent.
*
* @param {string} schedule_id - Immutable schedule identifier.
+ * @param {TrueForge.ListRunsSchedulesRequest} request
* @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
@@ -765,89 +767,119 @@ export class SchedulesClient {
* @example
* await client.schedules.listRuns("schedule_id")
*/
- public listRuns(
- schedule_id: string,
- requestOptions?: SchedulesClient.RequestOptions,
- ): core.HttpResponsePromise<TrueForge.ListScheduleRunsResponse> {
- return core.HttpResponsePromise.fromPromise(this.__listRuns(schedule_id, requestOptions));
- }
-
- private async __listRuns(
+ public async listRuns(
schedule_id: string,
+ request: TrueForge.ListRunsSchedulesRequest = {},
requestOptions?: SchedulesClient.RequestOptions,
- ): Promise<core.WithRawResponse<TrueForge.ListScheduleRunsResponse>> {
- 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/${core.url.encodePathParam(schedule_id)}/runs`,
- ),
- method: "GET",
- headers: _headers,
- queryString: core.url.queryBuilder().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.ListScheduleRunsResponse.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 403:
- throw new TrueForge.ForbiddenError(
- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
- unrecognizedObjectKeys: "passthrough",
- allowUnrecognizedUnionMembers: true,
- allowUnrecognizedEnumValues: true,
- skipValidation: true,
- breadcrumbsPrefix: ["response"],
- }),
- _response.rawResponse,
- );
- case 404:
- throw new TrueForge.NotFoundError(
- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ ): Promise<core.Page<TrueForge.ScheduleRun, TrueForge.ListScheduleRunsResponse>> {
+ const list = core.HttpResponsePromise.interceptFunction(
+ async (
+ request: TrueForge.ListRunsSchedulesRequest,
+ ): Promise<core.WithRawResponse<TrueForge.ListScheduleRunsResponse>> => {
+ const { limit = 25, pageToken } = request;
+ const _queryParams: Record<string, unknown> = {
+ limit,
+ page_token: pageToken,
+ };
+ 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/${core.url.encodePathParam(schedule_id)}/runs`,
+ ),
+ 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.ListScheduleRunsResponse.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/{schedule_id}/runs",
+ };
+ }
+ 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 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 404:
+ throw new TrueForge.NotFoundError(
+ 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/{schedule_id}/runs",
+ );
+ },
);
+ const dataWithRawResponse = await list(request).withRawResponse();
+ return new core.Page<TrueForge.ScheduleRun, TrueForge.ListScheduleRunsResponse>({
+ 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/ListRunsSchedulesRequest.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListRunsSchedulesRequest.ts
new file mode 100644
index 000000000..22b789f4f
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListRunsSchedulesRequest.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {}
+ */
+export interface ListRunsSchedulesRequest {
+ /** Page size. Defaults to 25 */
+ limit?: number;
+ /** Opaque token from a previous response `next_page_token`. */
+ pageToken?: string;
+}
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/index.ts
index 2bf48c23f..f2cef622a 100644
--- a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/index.ts
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/index.ts
@@ -1,4 +1,5 @@
export type { CreateScheduleRequest } from "./CreateScheduleRequest.js";
export type { CreateScheduleRunRequest } from "./CreateScheduleRunRequest.js";
+export type { ListRunsSchedulesRequest } from "./ListRunsSchedulesRequest.js";
export type { ListSchedulesRequest } from "./ListSchedulesRequest.js";
export type { UpdateScheduleRequest } from "./UpdateScheduleRequest.js";
diff --git a/packages/trueforge-sdk/src/api/types/ListScheduleRunsResponse.ts b/packages/trueforge-sdk/src/api/types/ListScheduleRunsResponse.ts
index c38fec21a..a5a530764 100644
--- a/packages/trueforge-sdk/src/api/types/ListScheduleRunsResponse.ts
+++ b/packages/trueforge-sdk/src/api/types/ListScheduleRunsResponse.ts
@@ -4,4 +4,5 @@ import type * as TrueForge from "../index.js";
export interface ListScheduleRunsResponse {
data: TrueForge.ScheduleRun[];
+ pagination: TrueForge.TokenPagination;
}
diff --git a/packages/trueforge-sdk/src/serialization/types/ListScheduleRunsResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListScheduleRunsResponse.ts
index 893ebea3d..d3afbb2ca 100644
--- a/packages/trueforge-sdk/src/serialization/types/ListScheduleRunsResponse.ts
+++ b/packages/trueforge-sdk/src/serialization/types/ListScheduleRunsResponse.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 { ScheduleRun } from "./ScheduleRun.js";
+import { TokenPagination } from "./TokenPagination.js";
export const ListScheduleRunsResponse: core.serialization.ObjectSchema<
serializers.ListScheduleRunsResponse.Raw,
TrueForge.ListScheduleRunsResponse
> = core.serialization.object({
data: core.serialization.list(ScheduleRun),
+ pagination: TokenPagination,
});
export declare namespace ListScheduleRunsResponse {
export interface Raw {
data: ScheduleRun.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 deaa5e6b3..0519b0944 100644
--- a/packages/trueforge-sdk/tests/wire/schedules.test.ts
+++ b/packages/trueforge-sdk/tests/wire/schedules.test.ts
@@ -730,18 +730,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()
+ .mockEndpoint({ once: false })
.get("/api/v1/schedules/schedule_id/runs")
.respondWith()
.statusCode(200)
.jsonBody(rawResponseBody)
.build();
- const response = await client.schedules.listRuns("schedule_id");
- expect(response).toEqual({
+ const expected = {
data: [
{
createdAt: new Date("2024-01-15T09:30:00.000Z"),
@@ -760,7 +760,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.listRuns("schedule_id");
+
+ expect(expected.data).toEqual(page.data);
+ expect(page.hasNextPage()).toBe(true);
+ const nextPage = await page.getNextPage();
+ expect(expected.data).toEqual(nextPage.data);
});
test("list_runs (2)", async () => {
@@ -769,6 +780,25 @@ describe("SchedulesClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/schedules/schedule_id/runs")
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.listRuns("schedule_id");
+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);
+ });
+
+ test("list_runs (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/schedule_id/runs")
@@ -782,7 +812,7 @@ describe("SchedulesClient", () => {
}).rejects.toThrow(TrueForgeTypes.ForbiddenError);
});
- test("list_runs (3)", async () => {
+ test("list_runs (4)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index 2bc40fb4d..1953659e7 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -144,6 +144,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
const listRunsHandler: RouteHandler<typeof listScheduleRunsRoute> = async c => {
const { schedule_id: scheduleId } = c.req.valid('param');
+ const { limit, page_token: pageToken } = c.req.valid('query');
const requestContext = deps.resolveRequestContext(c);
const schedule = await deps.scheduleStore.getSchedule({
tenant_id: requestContext.tenant_id,
@@ -163,11 +164,20 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
) {
return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
}
- const records = await deps.scheduleStore.listRuns({
- tenant_id: requestContext.tenant_id,
- schedule_id: scheduleId,
- });
- return c.json({ data: records.map(toWireScheduleRun) }, 200);
+ try {
+ const { data, pagination } = await deps.scheduleStore.listRuns({
+ tenant_id: requestContext.tenant_id,
+ schedule_id: scheduleId,
+ limit,
+ page_token: pageToken,
+ });
+ return c.json({ data: data.map(toWireScheduleRun), pagination }, 200);
+ } catch (error) {
+ if (error instanceof InvalidPageTokenError) {
+ return c.json({ error: { message: error.message } }, 400);
+ }
+ throw error;
+ }
};
const createScheduleRunHandler: RouteHandler<typeof createScheduleRunRoute> = 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 310c6a83b..da57a074a 100644
--- a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -241,7 +241,11 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
return { data: data.map(toScheduleRecord), pagination };
}
- async listRuns(input: ListRunsInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord[]> {
+ async listRuns(
+ input: ListRunsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<{ data: ScheduleRunRecord[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
const db = transaction ?? this.#db;
const rows = await db
.selectFrom('schedule_run')
@@ -250,8 +254,11 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
.where('schedule_id', '=', input.schedule_id)
.orderBy('scheduled_for', 'desc')
.orderBy('id')
+ .limit(input.limit + 1)
+ .offset(offset)
.execute();
- return rows.map(toRunRecord);
+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);
+ return { data: data.map(toRunRecord), pagination };
}
async getRun(input: GetRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord | undefined> {
diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.ts
index a5af138f4..6ecf37d4e 100644
--- a/packages/trueforge/src/db/scheduleStore.ts
+++ b/packages/trueforge/src/db/scheduleStore.ts
@@ -108,6 +108,8 @@ export interface ListSchedulesInput {
export interface ListRunsInput {
tenant_id: string;
schedule_id: string;
+ limit: number;
+ page_token: string | undefined;
}
export interface GetScheduleInput {
@@ -272,5 +274,8 @@ export interface IScheduleStore<TTransaction = never> {
/**
* Runs of one schedule (any status), newest `scheduled_for` first.
*/
- listRuns(input: ListRunsInput, transaction?: TTransaction): Promise<ScheduleRunRecord[]>;
+ listRuns(
+ input: ListRunsInput,
+ transaction?: TTransaction,
+ ): Promise<{ data: ScheduleRunRecord[]; pagination: TokenPagination }>;
}
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
index ca0880107..dac5ba855 100644
--- a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -294,7 +294,11 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
return { data: data.map(toScheduleRecord), pagination };
}
- async listRuns(input: ListRunsInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord[]> {
+ async listRuns(
+ input: ListRunsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<{ data: ScheduleRunRecord[]; pagination: TokenPagination }> {
+ const offset = decodeOffsetPageToken(input.page_token);
const db = transaction ?? this.#db;
const rows = await db
.selectFrom('schedule_run')
@@ -303,8 +307,11 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
.where('schedule_id', '=', input.schedule_id)
.orderBy('scheduled_for', 'desc')
.orderBy('id')
+ .limit(input.limit + 1)
+ .offset(offset)
.execute();
- return rows.map(toRunRecord);
+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);
+ return { data: data.map(toRunRecord), pagination };
}
async getRun(input: GetRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord | undefined> {
diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.ts
index 04c45e1db..9a08971f4 100644
--- a/packages/trueforge/src/routes/scheduleRoutes.ts
+++ b/packages/trueforge/src/routes/scheduleRoutes.ts
@@ -51,6 +51,20 @@ export const ListSchedulesQuerySchema = z
})
.openapi('ListSchedulesQuery');
+export const ListScheduleRunsQuerySchema = z
+ .object({
+ 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`.'),
+ })
+ .openapi('ListScheduleRunsQuery');
+
export const listSchedulesRoute = createRoute({
method: 'get',
path: '/',
@@ -88,13 +102,19 @@ export const listScheduleRunsRoute = createRoute({
'List runs of a schedule, newest `scheduled_for` first. Available to its creator or a manager of its agent.',
'x-fern-sdk-group-name': ['schedules'],
'x-fern-sdk-method-name': 'list_runs',
+ 'x-fern-pagination': TOKEN_PAGINATION,
request: {
params: ScheduleIdParamsSchema,
+ query: ListScheduleRunsQuerySchema,
},
responses: {
200: {
content: { 'application/json': { schema: ListScheduleRunsResponseSchema } },
- description: 'Runs of the schedule.',
+ description: 'Paginated runs of the schedule.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid query parameters or page token.',
},
403: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/schemas/schedule.ts b/packages/trueforge/src/schemas/schedule.ts
index 712d6b286..83dfaa1d8 100644
--- a/packages/trueforge/src/schemas/schedule.ts
+++ b/packages/trueforge/src/schemas/schedule.ts
@@ -154,7 +154,10 @@ export const ScheduleRunSchema = z
.openapi('ScheduleRun');
export const ListScheduleRunsResponseSchema = z
- .object({ data: z.array(ScheduleRunSchema) })
+ .object({
+ data: z.array(ScheduleRunSchema),
+ pagination: TokenPaginationSchema,
+ })
.openapi('ListScheduleRunsResponse');
/**
diff --git a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
index 707873f7e..1ad2981a4 100644
--- a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
+++ b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
@@ -731,12 +731,53 @@ export function runScheduleStoreContractSuite(deps: {
created_by_subject: USER_SUBJECT,
});
- const forA = await store.listRuns({ tenant_id: TENANT, schedule_id: scheduleA.id });
- expect(forA.map(row => row.id)).toEqual([newer.id, older.id]);
- expect(forA.every(row => row.schedule_id === scheduleA.id)).toBe(true);
+ const forA = await store.listRuns({
+ tenant_id: TENANT,
+ schedule_id: scheduleA.id,
+ limit: 25,
+ page_token: undefined,
+ });
+ expect(forA.data.map(row => row.id)).toEqual([newer.id, older.id]);
+ expect(forA.data.every(row => row.schedule_id === scheduleA.id)).toBe(true);
+ expect(forA.pagination.next_page_token).toBeUndefined();
- const forB = await store.listRuns({ tenant_id: TENANT, schedule_id: scheduleB.id });
- expect(forB.map(row => row.id)).toEqual([otherScheduleRun.id]);
+ const forB = await store.listRuns({
+ tenant_id: TENANT,
+ schedule_id: scheduleB.id,
+ limit: 25,
+ page_token: undefined,
+ });
+ expect(forB.data.map(row => row.id)).toEqual([otherScheduleRun.id]);
+
+ const midSlot = new Date('2026-08-27T11:00:00.000Z');
+ const mid = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: scheduleA.id,
+ name: cronRunName(midSlot),
+ scheduled_for: midSlot,
+ status: 'triggered',
+ created_by_subject: USER_SUBJECT,
+ });
+
+ const page1 = await store.listRuns({
+ tenant_id: TENANT,
+ schedule_id: scheduleA.id,
+ limit: 2,
+ page_token: undefined,
+ });
+ expect(page1.data.map(row => row.id)).toEqual([newer.id, mid.id]);
+ expect(page1.pagination.limit).toBe(2);
+ expect(page1.pagination.next_page_token).toEqual(expect.any(String));
+
+ const page2 = await store.listRuns({
+ tenant_id: TENANT,
+ schedule_id: scheduleA.id,
+ limit: 2,
+ page_token: page1.pagination.next_page_token,
+ });
+ expect(page2.data.map(row => row.id)).toEqual([older.id]);
+ expect(page2.pagination.previous_page_token).toEqual(expect.any(String));
+ expect(page2.pagination.next_page_token).toBeUndefined();
});
it('updateRunStatus stamps triggered_at only for triggered; returns undefined when gone', async () => {
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index 3c0137a28..5f9dfd87d 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -142,12 +142,21 @@ describe('schedule RBAC', () => {
expect(ListSchedulesResponseSchema.parse(await aliceList.json()).data).toHaveLength(1);
const aliceRuns = await app.request(`/${id}/runs`);
expect(aliceRuns.status).toBe(200);
- expect(ListScheduleRunsResponseSchema.parse(await aliceRuns.json()).data).toEqual([
- expect.objectContaining({ schedule_id: id }),
- ]);
+ const aliceRunsBody = ListScheduleRunsResponseSchema.parse(await aliceRuns.json());
+ expect(aliceRunsBody.data).toEqual([expect.objectContaining({ schedule_id: id })]);
+ expect(aliceRunsBody.pagination.next_page_token).toBeUndefined();
expect((await app.request(`/${id}`, { method: 'DELETE' })).status).toBe(200);
});
+ it('rejects an invalid page_token when listing runs', async () => {
+ const { app, asUser, postJson } = await setup();
+ asUser(ALICE);
+ const created = await postJson('/', 'POST', scheduleBody);
+ const { id } = ((await created.json()) as { data: { id: string } }).data;
+ const res = await app.request(`/${id}/runs?page_token=not-a-token`);
+ expect(res.status).toBe(400);
+ });
+
it('does not leak existence: a missing schedule is 404, not 403', async () => {
const { app, asUser, postJson } = await setup();
asUser(BOB);
@@ -312,8 +321,13 @@ describe('create schedule run', () => {
expect(pendingAfter?.id).toBe(pendingBefore?.id);
expect(pendingAfter?.status).toBe('scheduled');
- const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
- expect(runs.map(r => r.status).sort()).toEqual(['scheduled', 'triggered']);
+ const runs = await scheduleStore.listRuns({
+ tenant_id: 'default',
+ schedule_id: scheduleId,
+ limit: 25,
+ page_token: undefined,
+ });
+ expect(runs.data.map(r => r.status).sort()).toEqual(['scheduled', 'triggered']);
});
it('does not let an OIDC settings admin trigger another creator schedule', async () => {
@@ -341,8 +355,13 @@ describe('create schedule run', () => {
expect(res.status).toBe(404);
expect(((await res.json()) as { error: { message: string } }).error.message).toBe('Agent not found: reporter');
- const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
- const runNow = runs.find(r => r.name.startsWith('manual-'));
+ const runs = await scheduleStore.listRuns({
+ tenant_id: 'default',
+ schedule_id: scheduleId,
+ limit: 25,
+ page_token: undefined,
+ });
+ const runNow = runs.data.find(r => r.name.startsWith('manual-'));
expect(runNow?.status).toBe('failed');
expect(runNow?.reason).toBe('Agent not found: reporter');
});
@@ -378,8 +397,13 @@ describe('create schedule run', () => {
expect(((await res.json()) as { error: { message: string } }).error.message).toBe('Agent not found: reporter');
expect(mockedStartScheduleRun).not.toHaveBeenCalled();
- const runs = await scheduleStore.listRuns({ tenant_id: 'default', schedule_id: scheduleId });
- expect(runs.some(r => r.name.startsWith('manual-'))).toBe(false);
+ const runs = await scheduleStore.listRuns({
+ tenant_id: 'default',
+ schedule_id: scheduleId,
+ limit: 25,
+ page_token: undefined,
+ });
+ expect(runs.data.some(r => r.name.startsWith('manual-'))).toBe(false);
expect(canAccessAgent.mock.calls.map(([input]) => input.action)).toEqual(['use']);
});
});