The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: API to trigger a manual run (#538)
Srajan Asthana8e647574d445
diff --git a/.changeset/schedule-manual-run.md b/.changeset/schedule-manual-run.mdnew file mode 100644index 000000000..467e62a3d--- /dev/null+++ b/.changeset/schedule-manual-run.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge": patch+---++Add POST /api/v1/schedules/runs to trigger an immediate schedule rundiff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex d960966e2..17bb1b0f0 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -1012,6 +1012,33 @@],"type": "object"},+ "CreateScheduleRunRequest": {+ "additionalProperties": false,+ "description": "Trigger an immediate run for the given schedule. The task is taken from the schedule manifest.",+ "properties": {+ "schedule_id": {+ "description": "Immutable schedule identifier.",+ "maxLength": 64,+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "schedule_id"+ ],+ "type": "object"+ },+ "CreateScheduleRunResponse": {+ "properties": {+ "data": {+ "$ref": "#/components/schemas/ScheduleRun"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"CreateSessionAgent": {"anyOf": [{@@ -5918,6 +5945,91 @@"x-fern-sdk-method-name": "create"}},+ "/api/v1/schedules/runs": {+ "post": {+ "description": "Start a schedule run immediately using the schedule task. Does not replace or advance the cron pending run.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateScheduleRunRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateScheduleRunResponse"+ }+ }+ },+ "description": "Run created."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request or turn input."+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The caller is not the schedule creator."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Schedule or agent not found."+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Run name conflict (retry)."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The run cannot be started (e.g. agent resources unavailable)."+ }+ },+ "summary": "Trigger a schedule run",+ "tags": [+ "Schedules"+ ],+ "x-fern-sdk-group-name": [+ "schedules"+ ],+ "x-fern-sdk-method-name": "create_run"+ }+ },"/api/v1/schedules/{schedule_id}": {"delete": {"description": "Delete a schedule and its runs. Idempotent.",diff --git a/docs/openapi.json b/docs/openapi.jsonindex d960966e2..17bb1b0f0 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -1012,6 +1012,33 @@],"type": "object"},+ "CreateScheduleRunRequest": {+ "additionalProperties": false,+ "description": "Trigger an immediate run for the given schedule. The task is taken from the schedule manifest.",+ "properties": {+ "schedule_id": {+ "description": "Immutable schedule identifier.",+ "maxLength": 64,+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "schedule_id"+ ],+ "type": "object"+ },+ "CreateScheduleRunResponse": {+ "properties": {+ "data": {+ "$ref": "#/components/schemas/ScheduleRun"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"CreateSessionAgent": {"anyOf": [{@@ -5918,6 +5945,91 @@"x-fern-sdk-method-name": "create"}},+ "/api/v1/schedules/runs": {+ "post": {+ "description": "Start a schedule run immediately using the schedule task. Does not replace or advance the cron pending run.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateScheduleRunRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateScheduleRunResponse"+ }+ }+ },+ "description": "Run created."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request or turn input."+ },+ "403": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The caller is not the schedule creator."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Schedule or agent not found."+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Run name conflict (retry)."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The run cannot be started (e.g. agent resources unavailable)."+ }+ },+ "summary": "Trigger a schedule run",+ "tags": [+ "Schedules"+ ],+ "x-fern-sdk-group-name": [+ "schedules"+ ],+ "x-fern-sdk-method-name": "create_run"+ }+ },"/api/v1/schedules/{schedule_id}": {"delete": {"description": "Delete a schedule and its runs. Idempotent.",diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.mdindex e86590731..0294f494b 100644--- a/packages/trueforge-sdk/reference.md+++ b/packages/trueforge-sdk/reference.md@@ -879,6 +879,71 @@ await client.schedules.create({</dl>+</dd>+</dl>+</details>++<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">createRun</a>({ ...params }) -> TrueForge.CreateScheduleRunResponse</code></summary>+<dl>+<dd>++#### π Description++<dl>+<dd>++<dl>+<dd>++Start a schedule run immediately using the schedule task. Does not replace or advance the cron pending run.+</dd>+</dl>+</dd>+</dl>++#### π Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.schedules.createRun({+ scheduleId: "schedule_id"+});++```+</dd>+</dl>+</dd>+</dl>++#### βοΈ Parameters++<dl>+<dd>++<dl>+<dd>++**request:** `TrueForge.CreateScheduleRunRequest`++</dd>+</dl>++<dl>+<dd>++**requestOptions:** `SchedulesClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>++</dd></dl></details>diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.tsindex cb4816f03..00a56f546 100644--- a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts@@ -250,6 +250,150 @@ export class SchedulesClient {return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/schedules");}+ /**+ * Start a schedule run immediately using the schedule task. Does not replace or advance the cron pending run.+ *+ * @param {TrueForge.CreateScheduleRunRequest} request+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.ForbiddenError}+ * @throws {@link TrueForge.NotFoundError}+ * @throws {@link TrueForge.ConflictError}+ * @throws {@link TrueForge.UnprocessableEntityError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.schedules.createRun({+ * scheduleId: "schedule_id"+ * })+ */+ public createRun(+ request: TrueForge.CreateScheduleRunRequest,+ requestOptions?: SchedulesClient.RequestOptions,+ ): core.HttpResponsePromise<TrueForge.CreateScheduleRunResponse> {+ return core.HttpResponsePromise.fromPromise(this.__createRun(request, requestOptions));+ }++ private async __createRun(+ request: TrueForge.CreateScheduleRunRequest,+ requestOptions?: SchedulesClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.CreateScheduleRunResponse>> {+ 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/runs",+ ),+ method: "POST",+ headers: _headers,+ contentType: "application/json",+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ requestType: "json",+ body: mergeAdditionalBodyParameters(+ serializers.CreateScheduleRunRequest.jsonOrThrow(request, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ omitUndefined: true,+ }),+ requestOptions?.additionalBodyParameters,+ ),+ 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.CreateScheduleRunResponse.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 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,+ );+ case 409:+ throw new TrueForge.ConflictError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ 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, "POST", "/api/v1/schedules/runs");+ }+/*** Get a schedule by id.*diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRunRequest.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRunRequest.tsnew file mode 100644index 000000000..6ae12e4b9--- /dev/null+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRunRequest.ts@@ -0,0 +1,12 @@+// This file was auto-generated by Fern from our API Definition.++/**+ * @example+ * {+ * scheduleId: "schedule_id"+ * }+ */+export interface CreateScheduleRunRequest {+ /** Immutable schedule identifier. */+ scheduleId: 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.tsindex 7dddd3f34..2bf48c23f 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,3 +1,4 @@export type { CreateScheduleRequest } from "./CreateScheduleRequest.js";+export type { CreateScheduleRunRequest } from "./CreateScheduleRunRequest.js";export type { ListSchedulesRequest } from "./ListSchedulesRequest.js";export type { UpdateScheduleRequest } from "./UpdateScheduleRequest.js";diff --git a/packages/trueforge-sdk/src/api/types/CreateScheduleRunResponse.ts b/packages/trueforge-sdk/src/api/types/CreateScheduleRunResponse.tsnew file mode 100644index 000000000..6aa67119b--- /dev/null+++ b/packages/trueforge-sdk/src/api/types/CreateScheduleRunResponse.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface CreateScheduleRunResponse {+ data: TrueForge.ScheduleRun;+}diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.tsindex 1175f7407..afe4c7cd4 100644--- a/packages/trueforge-sdk/src/api/types/index.ts+++ b/packages/trueforge-sdk/src/api/types/index.ts@@ -41,6 +41,7 @@ export * from "./ConfiguredModelProvider.js";export * from "./ConfiguredSandboxProvider.js";export * from "./ConfiguredSkill.js";export * from "./ContextManagementConfig.js";+export * from "./CreateScheduleRunResponse.js";export * from "./CreateSessionAgent.js";export * from "./CronExpression.js";export * from "./CustomModelProvider.js";diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRunRequest.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRunRequest.tsnew file mode 100644index 000000000..b5b17546c--- /dev/null+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRunRequest.ts@@ -0,0 +1,18 @@+// 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 CreateScheduleRunRequest: core.serialization.Schema<+ serializers.CreateScheduleRunRequest.Raw,+ TrueForge.CreateScheduleRunRequest+> = core.serialization.object({+ scheduleId: core.serialization.property("schedule_id", core.serialization.string()),+});++export declare namespace CreateScheduleRunRequest {+ export interface Raw {+ schedule_id: string;+ }+}diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/index.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/index.tsindex da06a3f81..0745bccd9 100644--- a/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/index.ts+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/index.ts@@ -1,2 +1,3 @@export { CreateScheduleRequest } from "./CreateScheduleRequest.js";+export { CreateScheduleRunRequest } from "./CreateScheduleRunRequest.js";export { UpdateScheduleRequest } from "./UpdateScheduleRequest.js";diff --git a/packages/trueforge-sdk/src/serialization/types/CreateScheduleRunResponse.ts b/packages/trueforge-sdk/src/serialization/types/CreateScheduleRunResponse.tsnew file mode 100644index 000000000..2c66c0d2a--- /dev/null+++ b/packages/trueforge-sdk/src/serialization/types/CreateScheduleRunResponse.ts@@ -0,0 +1,19 @@+// 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";+import { ScheduleRun } from "./ScheduleRun.js";++export const CreateScheduleRunResponse: core.serialization.ObjectSchema<+ serializers.CreateScheduleRunResponse.Raw,+ TrueForge.CreateScheduleRunResponse+> = core.serialization.object({+ data: ScheduleRun,+});++export declare namespace CreateScheduleRunResponse {+ export interface Raw {+ data: ScheduleRun.Raw;+ }+}diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.tsindex 1175f7407..afe4c7cd4 100644--- a/packages/trueforge-sdk/src/serialization/types/index.ts+++ b/packages/trueforge-sdk/src/serialization/types/index.ts@@ -41,6 +41,7 @@ export * from "./ConfiguredModelProvider.js";export * from "./ConfiguredSandboxProvider.js";export * from "./ConfiguredSkill.js";export * from "./ContextManagementConfig.js";+export * from "./CreateScheduleRunResponse.js";export * from "./CreateSessionAgent.js";export * from "./CronExpression.js";export * from "./CustomModelProvider.js";diff --git a/packages/trueforge-sdk/tests/wire/schedules.test.ts b/packages/trueforge-sdk/tests/wire/schedules.test.tsindex ab1a8509d..8cbd16e20 100644--- a/packages/trueforge-sdk/tests/wire/schedules.test.ts+++ b/packages/trueforge-sdk/tests/wire/schedules.test.ts@@ -192,6 +192,161 @@ describe("SchedulesClient", () => {}).rejects.toThrow(TrueForgeTypes.ConflictError);});+ test("create_run (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "schedule_id" };+ const rawResponseBody = {+ data: {+ created_at: "2024-01-15T09:30:00Z",+ id: "id",+ name: "name",+ schedule_id: "schedule_id",+ scheduled_for: "2024-01-15T09:30:00Z",+ status: "scheduled",+ triggered_at: "2024-01-15T09:30:00Z",+ triggered_by: "triggered_by",+ updated_at: "2024-01-15T09:30:00Z",+ },+ };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();++ const response = await client.schedules.createRun({+ scheduleId: "schedule_id",+ });+ expect(response).toEqual({+ data: {+ createdAt: new Date("2024-01-15T09:30:00.000Z"),+ id: "id",+ name: "name",+ scheduleId: "schedule_id",+ scheduledFor: new Date("2024-01-15T09:30:00.000Z"),+ status: "scheduled",+ triggeredAt: new Date("2024-01-15T09:30:00.000Z"),+ triggeredBy: "triggered_by",+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),+ },+ });+ });++ test("create_run (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "x" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.schedules.createRun({+ scheduleId: "x",+ });+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("create_run (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "x" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(403)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.schedules.createRun({+ scheduleId: "x",+ });+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);+ });++ test("create_run (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "x" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(404)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.schedules.createRun({+ scheduleId: "x",+ });+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);+ });++ test("create_run (5)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "x" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(409)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.schedules.createRun({+ scheduleId: "x",+ });+ }).rejects.toThrow(TrueForgeTypes.ConflictError);+ });++ test("create_run (6)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });+ const rawRequestBody = { schedule_id: "x" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/schedules/runs")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.schedules.createRun({+ scheduleId: "x",+ });+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });+test("get (1)", 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.tsindex ca57d7215..68a3b4183 100644--- a/packages/trueforge/src/apis/schedules.ts+++ b/packages/trueforge/src/apis/schedules.ts@@ -2,11 +2,13 @@* Schedules API (mounted at /api/v1/schedules).*/import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import { InvalidPageTokenError } from '@truefoundry/trueforge-core/agent-session';+import { InvalidPageTokenError, type Sessions } from '@truefoundry/trueforge-core/agent-session';import type { Context } from 'hono';import type { UserContext } from '../auth/identity';+import { ScheduleAgentNotFoundError, startScheduleRun } from '../controller/scheduleDispatch';import type { IAgentStore } from '../db/agentStore';import {+ manualRunName,ScheduleNameConflictError,ScheduleRunConflictError,type IScheduleStore,@@ -16,6 +18,7 @@ import {import type { WithTransaction } from '../db/transaction';import {createScheduleRoute,+ createScheduleRunRoute,deleteScheduleRoute,getScheduleRoute,listScheduleRunsRoute,@@ -31,10 +34,13 @@ import {type ScheduleRun,} from '../schemas/schedule';import { TENANT_ID } from './sessions';+import { getTurnExecutionError, startTurnInProcess, type BeginTurnExecutionDeps } from './turns';export interface SchedulesRouterDeps<TTransaction> {scheduleStore: IScheduleStore<TTransaction>;agentStore: IAgentStore<TTransaction>;+ sessions: Sessions;+ turnDeps: BeginTurnExecutionDeps;withTransaction: WithTransaction<TTransaction>;resolveUserContext: (c: Context) => UserContext;}@@ -144,6 +150,67 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTreturn c.json({ data: records.map(toWireScheduleRun) }, 200);};+ const createScheduleRunHandler: RouteHandler<typeof createScheduleRunRoute> = async c => {+ const { schedule_id: scheduleId } = c.req.valid('json');+ const user = deps.resolveUserContext(c);++ const schedule = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId });+ if (schedule === undefined) {+ return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);+ }+ if (!canAccessSchedule(user, schedule.created_by)) {+ return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);+ }++ const now = new Date();+ let run: ScheduleRunRecord;+ try {+ run = await deps.scheduleStore.createRun({+ tenant_id: TENANT_ID,+ schedule_id: schedule.id,+ name: manualRunName(),+ scheduled_for: now,+ status: 'triggered',+ triggered_by: user.userRef,+ triggered_at: now,+ });+ } catch (error) {+ if (error instanceof ScheduleRunConflictError) {+ return c.json({ error: { message: `${error.message}. Retry the request.` } }, 409);+ }+ throw error;+ }++ try {+ await startScheduleRun({+ item: { run, schedule },+ sessions: deps.sessions,+ agentStore: deps.agentStore,+ startTurn: async turnParams => {+ await startTurnInProcess({ ...turnParams, deps: deps.turnDeps });+ },+ });+ } catch (error) {+ await deps.scheduleStore.updateRunStatus({+ tenant_id: TENANT_ID,+ id: run.id,+ status: 'failed',+ });++ if (error instanceof ScheduleAgentNotFoundError) {+ return c.json({ error: { message: error.message } }, 404);+ }+ const turnError = getTurnExecutionError(error);+ if (turnError) {+ return c.json({ error: { message: turnError.message } }, turnError.status);+ }+ throw error;+ }++ const latest = await deps.scheduleStore.getRun({ tenant_id: TENANT_ID, id: run.id });+ return c.json({ data: toWireScheduleRun(latest ?? run) }, 201);+ };+const createHandler: RouteHandler<typeof createScheduleRoute> = async c => {const body = c.req.valid('json');const user = deps.resolveUserContext(c);@@ -267,6 +334,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTconst router = new OpenAPIHono();router.openapi(listSchedulesRoute, listHandler);router.openapi(listScheduleRunsRoute, listRunsHandler);+ router.openapi(createScheduleRunRoute, createScheduleRunHandler);router.openapi(createScheduleRoute, createHandler);router.openapi(getScheduleRoute, getHandler);router.openapi(putScheduleRoute, putHandler);diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.tsindex c6a154a3e..2ef791bac 100644--- a/packages/trueforge/src/apis/turns.ts+++ b/packages/trueforge/src/apis/turns.ts@@ -9,6 +9,8 @@ import {SessionStoreConflictError,SessionStoreNotFoundError,TurnResourceResolver,+ type SessionHandle,+ type TurnHandle,type TurnInputItem,type TurnRecordWithoutSnapshot,} from '@truefoundry/trueforge-core/agent-session';@@ -115,6 +117,20 @@ export interface TurnsRouterDeps {resolveUserContext: ResolveUserContext;}+/** Deps needed to create a turn and drain events in-process (no HTTP). */+export type BeginTurnExecutionDeps = Pick<+ TurnsRouterDeps,+ | 'activeTurns'+ | 'eventSubscriptions'+ | 'modelProviderStore'+ | 'mcpServerStore'+ | 'tokenStore'+ | 'skillStore'+ | 'agentStore'+ | 'sandboxProviderStore'+ | 'logger'+>;+/*** Builds the per-turn resolver. Agent / MCP / sandbox / LLM lookups are wired* the same way: async factories over the corresponding stores.@@ -334,6 +350,151 @@ export async function drainTurnEvents(input: {}}+/** Inputs for {@link drainTurnEvents} produced by {@link beginTurnExecution}. */+export interface TurnEventDrainInput {+ trackedStream: AsyncIterable<TurnStreamingEvent>;+ turnEventStream: EventSubscription<TurnStreamingEvent>;+ sessionId: string;+ turnId: string;+ maxExecutionTimer: NodeJS.Timeout;+ logger: Logger;+}++/**+ * Shared create-turn engine: persist the turn, start execution, and return the+ * drain inputs. Does not wait for events and does not write HTTP/SSE.+ */+export async function beginTurnExecution(params: {+ session: SessionHandle;+ input: TurnInputItem[] | undefined;+ previous_turn_id: string | undefined;+ userRef: string;+ deps: BeginTurnExecutionDeps;+}): Promise<{ turn: TurnHandle; drainInput: TurnEventDrainInput }> {+ const { session, input, previous_turn_id: previousTurnId, userRef, deps } = params;+ const sessionId = session.session_id;++ const abortController = new AbortController();+ const resolver = createTurnResolver({+ mcpServerStore: deps.mcpServerStore,+ tokenStore: deps.tokenStore,+ skillStore: deps.skillStore,+ sandboxProviderStore: deps.sandboxProviderStore,+ agentStore: deps.agentStore,+ modelProviderStore: deps.modelProviderStore,+ logger: deps.logger,+ signal: abortController.signal,+ userRef,+ sessionId,+ });++ // First turn only: derive the title from the first user message. The store+ // never overwrites an existing title.+ const title = session.record.last_turn_id ? undefined : deriveSessionTitle(input);++ const turn = await session.createTurn({+ turn_id: mintPeeredTurnId(configuration.EXECUTOR_ID),+ input,+ previous_turn_id: previousTurnId,+ signal: abortController.signal,+ resolver,+ update_session_title_if_not_exist: title,+ });++ const maxExecutionTimer = setTimeout(() => {+ if (!abortController.signal.aborted) {+ abortController.abort(CancellationReason.ServerExecutionTimeout);+ }+ }, configuration.SERVER_EXECUTION_TIMEOUT_SECONDS * 1000);+ maxExecutionTimer.unref();++ const trackedStream = deps.activeTurns.track({+ sessionId,+ turnId: turn.id,+ abortController,+ stream: turn.stream(),+ });++ // Held for the whole turn; the stream's sequence counter dies with it.+ const turnEventStream = deps.eventSubscriptions.get(turnStreamId(TENANT_ID, sessionId, turn.id));++ return {+ turn,+ drainInput: {+ trackedStream,+ turnEventStream,+ sessionId,+ turnId: turn.id,+ maxExecutionTimer,+ logger: deps.logger,+ },+ };+}++/**+ * Non-stream create-turn: begin execution and resolve once the first event is+ * dual-written so immediate subscribe cannot 412. Same as `stream: false`.+ */+export async function startTurnInProcess(params: {+ session: SessionHandle;+ input: TurnInputItem[] | undefined;+ previous_turn_id: string | undefined;+ userRef: string;+ deps: BeginTurnExecutionDeps;+}): Promise<TurnHandle> {+ const { turn, drainInput } = await beginTurnExecution(params);++ // Same unawaited drain scheduling as Hono streamSSE's run(cb).+ const { promise: firstEventDualWritten, resolve: markFirstEventDualWritten } = Promise.withResolvers<undefined>();+ void drainTurnEvents({+ ...drainInput,+ onEvent: () => {+ markFirstEventDualWritten(undefined);+ return Promise.resolve();+ },+ }).finally(() => {+ markFirstEventDualWritten(undefined);+ });+ await firstEventDualWritten;+ return turn;+}++/** Mapped client error from turn execution; undefined means rethrow. */+export interface TurnExecutionError {+ status: 400 | 404 | 422;+ message: string;+}++/**+ * Resolve turn-start failures to HTTP status + message.+ * Returns undefined when the caller should rethrow (unexpected / 5xx).+ */+export function getTurnExecutionError(error: unknown): TurnExecutionError | undefined {+ if (error instanceof HTTPException) {+ if (error.status === 400 || error.status === 404 || error.status === 422) {+ return { status: error.status, message: error.message };+ }+ return undefined;+ }+ if (error instanceof SessionStoreNotFoundError) {+ return { status: 404, message: error.message };+ }+ if (error instanceof AgentHarnessError && !(error instanceof McpConnectionError)) {+ switch (error.code) {+ case 'invalid_file_input':+ return { status: 400, message: error.message };+ case 'invalid_send_input':+ case 'agent_sandbox_required':+ case 'tool_name_collision':+ return { status: 422, message: error.message };+ case 'capability_state_error':+ case 'mcp_connection_failed':+ return undefined;+ }+ }+ return undefined;+}+/*** Resume cursor: `Last-Event-ID` header wins over the body value because the* header is updated by the SDK on every reconnect to reflect the last delivered@@ -505,117 +666,51 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {return c.json({ error: { message: FORBIDDEN_CREATE_TURN } }, 403);}- const abortController = new AbortController();- const resolver = createTurnResolver({- mcpServerStore: deps.mcpServerStore,- tokenStore: deps.tokenStore,- skillStore: deps.skillStore,- sandboxProviderStore: deps.sandboxProviderStore,- agentStore: deps.agentStore,- modelProviderStore: deps.modelProviderStore,- logger: deps.logger,- signal: abortController.signal,- userRef: deps.resolveUserContext(c).userRef,- sessionId,- });-- // First turn only: derive the title from the first user message. The store- // never overwrites an existing title.- const title = session.record.last_turn_id ? undefined : deriveSessionTitle(body.input);+ const userRef = deps.resolveUserContext(c).userRef;+ const turnParams = {+ session,+ input: body.input,+ previous_turn_id: body.previous_turn_id,+ userRef,+ deps,+ };- let turn;try {- turn = await session.createTurn({- turn_id: mintPeeredTurnId(configuration.EXECUTOR_ID),- input: body.input,- previous_turn_id: body.previous_turn_id,- signal: abortController.signal,- resolver,- update_session_title_if_not_exist: title,+ // Non-stream: wait for first dual-write, return JSON (also used by schedule run-now).+ if (!body.stream) {+ const turn = await startTurnInProcess(turnParams);+ return c.json({ data: toWireTurn(turn.record) }, 200);+ }++ // Stream: same engine; HTTP handler owns writing each event to SSE.+ const { drainInput } = await beginTurnExecution(turnParams);+ let shouldWriteToSSEStream = true;+ return streamSSE(c, async stream => {+ stream.onAbort(() => {+ shouldWriteToSSEStream = false;+ });+ await drainTurnEvents({+ ...drainInput,+ onEvent: async (event, sequenceNumber) => {+ if (!stream.closed && !stream.aborted && shouldWriteToSSEStream) {+ try {+ await stream.writeSSE(turnEventSsePayload(event, sequenceNumber));+ } catch (error) {+ deps.logger.error('SSE stream write error', extractErrorLogFields(error));+ shouldWriteToSSEStream = false;+ }+ }+ },+ });+ await stream.close();});} catch (error) {- if (error instanceof SessionStoreNotFoundError) {- return c.json({ error: { message: error.message } }, 404);- }- if (error instanceof AgentHarnessError && !(error instanceof McpConnectionError)) {- switch (error.code) {- case 'invalid_file_input':- return c.json({ error: { message: error.message } }, 400);- case 'invalid_send_input':- case 'agent_sandbox_required':- case 'tool_name_collision':- return c.json({ error: { message: error.message } }, 422);- case 'capability_state_error':- case 'mcp_connection_failed':- throw error;- }+ const turnError = getTurnExecutionError(error);+ if (turnError) {+ return c.json({ error: { message: turnError.message } }, turnError.status);}throw error;}-- const maxExecutionTimer = setTimeout(() => {- if (!abortController.signal.aborted) {- abortController.abort(CancellationReason.ServerExecutionTimeout);- }- }, configuration.SERVER_EXECUTION_TIMEOUT_SECONDS * 1000);- maxExecutionTimer.unref();-- const trackedStream = deps.activeTurns.track({- sessionId,- turnId: turn.id,- abortController,- stream: turn.stream(),- });-- // Held for the whole turn; the stream's sequence counter dies with it.- const turnEventStream = deps.eventSubscriptions.get(turnStreamId(TENANT_ID, sessionId, turn.id));- const drainInput = {- trackedStream,- turnEventStream,- sessionId,- turnId: turn.id,- maxExecutionTimer,- logger: deps.logger,- };-- // Non-stream: same unawaited drain scheduling as Hono streamSSE's run(cb).- // Wait until the first dual-write (turn.created) so immediate subscribeToTurn- // cannot 412 before the resumable stream exists.- if (!body.stream) {- const { promise: firstEventDualWritten, resolve: markFirstEventDualWritten } = Promise.withResolvers<undefined>();- void drainTurnEvents({- ...drainInput,- onEvent: () => {- markFirstEventDualWritten(undefined);- return Promise.resolve();- },- }).finally(() => {- markFirstEventDualWritten(undefined);- });- await firstEventDualWritten;- return c.json({ data: toWireTurn(turn.record) }, 200);- }-- let shouldWriteToSSEStream = true;- return streamSSE(c, async stream => {- stream.onAbort(() => {- shouldWriteToSSEStream = false;- });- await drainTurnEvents({- ...drainInput,- onEvent: async (event, sequenceNumber) => {- if (!stream.closed && !stream.aborted && shouldWriteToSSEStream) {- try {- await stream.writeSSE(turnEventSsePayload(event, sequenceNumber));- } catch (error) {- deps.logger.error('SSE stream write error', extractErrorLogFields(error));- shouldWriteToSSEStream = false;- }- }- },- });- await stream.close();- });};const subscribeTurnHandler: RouteHandler<typeof subscribeTurnRoute> = async c => {diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.tsindex 28677b50c..ecc99ef7d 100644--- a/packages/trueforge/src/app.ts+++ b/packages/trueforge/src/app.ts@@ -260,6 +260,18 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {createSchedulesRouter({scheduleStore: deps.scheduleStore,agentStore: deps.agentStore,+ sessions: deps.sessions,+ turnDeps: {+ activeTurns: deps.activeTurns,+ eventSubscriptions: deps.eventSubscriptions,+ modelProviderStore: deps.modelProviderStore,+ mcpServerStore: deps.mcpServerStore,+ tokenStore: deps.tokenStore,+ skillStore: deps.skillStore,+ agentStore: deps.agentStore,+ sandboxProviderStore: deps.sandboxProviderStore,+ logger: deps.logger,+ },withTransaction: deps.withTransaction,resolveUserContext,}),diff --git a/packages/trueforge/src/controller/scheduleDispatch.ts b/packages/trueforge/src/controller/scheduleDispatch.tsindex 6b1160b62..fa92d2f2e 100644--- a/packages/trueforge/src/controller/scheduleDispatch.ts+++ b/packages/trueforge/src/controller/scheduleDispatch.ts@@ -1,5 +1,7 @@+import type { SessionHandle, Sessions, TurnInputItem } from '@truefoundry/trueforge-core/agent-session';import type { TrueForge } from '@truefoundry/trueforge-sdk';import type { Logger } from 'winston';+import type { IAgentStore } from '../db/agentStore';import {cronRunName,type IScheduleStore,@@ -34,6 +36,17 @@ const SCHEDULE_DISPATCH_LOOP_NAME = 'schedule-dispatch';type ScheduleRunApiClient = Pick<TrueForge, 'sessions' | 'internal'>;+/** Schedule's bound agent name is missing from the agent store. */+export class ScheduleAgentNotFoundError extends Error {+ readonly agent_name: string;++ constructor(agent_name: string, options?: ErrorOptions) {+ super(`Agent not found: ${agent_name}`, options);+ this.name = 'ScheduleAgentNotFoundError';+ this.agent_name = agent_name;+ }+}+/*** Hands a due schedule run to the API:* 1. Get or create a session keyed by `run.id`.@@ -60,6 +73,56 @@ function executeScheduledRun(client: ScheduleRunApiClient): (item: ScheduleDispa};}+/**+ * Start a schedule run in-process: get-or-create a session keyed by `run.id`,+ * then create a non-streaming turn with the schedule task when that session has+ * none. Idempotent on retry. Session owner and turn `userRef` are the schedule+ * creator so ownership stays with the schedule even when an admin triggers run-now.+ */+export async function startScheduleRun(params: {+ item: ScheduleDispatchItem;+ sessions: Sessions;+ agentStore: IAgentStore;+ startTurn: (params: {+ session: SessionHandle;+ input: TurnInputItem[];+ previous_turn_id: string;+ userRef: string;+ }) => Promise<void>;+}): Promise<void> {+ const {+ item: { run, schedule },+ sessions,+ agentStore,+ startTurn,+ } = params;++ const named = await agentStore.getAgent({ tenant_id: schedule.tenant_id, name: schedule.agent_name });+ if (named === undefined) {+ throw new ScheduleAgentNotFoundError(schedule.agent_name);+ }++ const { session } = await sessions.getOrCreateByExternalId({+ tenant_id: schedule.tenant_id,+ external_id: run.id,+ created_by: schedule.created_by,+ agent: { type: 'reference', id: named.id, name: named.name },+ });++ // idempotency check+ const { data: turns } = await session.listTurns({ limit: 1 });+ if (turns.length > 0) {+ return;+ }++ await startTurn({+ session,+ input: [{ type: 'user.message', content: schedule.manifest.task }],+ previous_turn_id: 'none',+ userRef: schedule.created_by,+ });+}+/*** Mark the current run with `status`, then add the schedule's next scheduled run* if the schedule is still active and its cron still has a later trigger time.diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.tsindex 217c2cbf9..a7483a9ff 100644--- a/packages/trueforge/src/db/scheduleStore.ts+++ b/packages/trueforge/src/db/scheduleStore.ts@@ -14,6 +14,7 @@* Implementations: PostgresScheduleStore and SqliteScheduleStore.*/import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import { randomUUID } from 'node:crypto';import {ScheduleManifestSchema,type ScheduleManifest,@@ -29,6 +30,11 @@ export function cronRunName(scheduledFor: Date): string {return `sched-${String(Math.floor(scheduledFor.getTime() / 1000))}`;}+/** Unique run name for an immediate (run-now) trigger. */+export function manualRunName(): string {+ return `manual-${randomUUID()}`;+}+export interface ScheduleRecord {id: string;tenant_id: string;diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.tsindex 038b579ed..1a85405a0 100644--- a/packages/trueforge/src/routes/scheduleRoutes.ts+++ b/packages/trueforge/src/routes/scheduleRoutes.ts@@ -7,6 +7,8 @@ import { NameSchema, PAGE_LIMIT, parseCommaSeparatedQuery } from '../schemas/comimport { RequestErrorResponseSchema } from '../schemas/errors';import {CreateScheduleRequestSchema,+ CreateScheduleRunRequestSchema,+ CreateScheduleRunResponseSchema,DeleteScheduleResponseSchema,GetScheduleResponseSchema,ListScheduleRunsResponseSchema,@@ -100,6 +102,49 @@ export const listScheduleRunsRoute = createRoute({},});+export const createScheduleRunRoute = createRoute({+ method: 'post',+ path: '/runs',+ tags: [OpenApiTag.SCHEDULES],+ summary: 'Trigger a schedule run',+ description:+ 'Start a schedule run immediately using the schedule task. Does not replace or advance the cron pending run.',+ 'x-fern-sdk-group-name': ['schedules'],+ 'x-fern-sdk-method-name': 'create_run',+ request: {+ body: {+ content: { 'application/json': { schema: CreateScheduleRunRequestSchema } },+ required: true,+ },+ },+ responses: {+ 201: {+ content: { 'application/json': { schema: CreateScheduleRunResponseSchema } },+ description: 'Run created.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request or turn input.',+ },+ 403: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The caller is not the schedule creator.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Schedule or agent not found.',+ },+ 409: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Run name conflict (retry).',+ },+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The run cannot be started (e.g. agent resources unavailable).',+ },+ },+});+export const createScheduleRoute = createRoute({method: 'post',path: '/',diff --git a/packages/trueforge/src/schemas/schedule.ts b/packages/trueforge/src/schemas/schedule.tsindex bcc8eb5d1..bf6b0c399 100644--- a/packages/trueforge/src/schemas/schedule.ts+++ b/packages/trueforge/src/schemas/schedule.ts@@ -156,6 +156,21 @@ export const ListScheduleRunsResponseSchema = z.object({ data: z.array(ScheduleRunSchema) }).openapi('ListScheduleRunsResponse');+/**+ * Identify the schedule to run. Task always comes from the schedule manifest.+ */+export const CreateScheduleRunRequestSchema = z+ .object({+ schedule_id: z.string().min(1).max(64).describe('Immutable schedule identifier.'),+ })+ .strict()+ .describe('Trigger an immediate run for the given schedule. The task is taken from the schedule manifest.')+ .openapi('CreateScheduleRunRequest');++export const CreateScheduleRunResponseSchema = z+ .object({ data: ScheduleRunSchema })+ .openapi('CreateScheduleRunResponse');+export type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;export type ScheduleRunStatus = z.infer<typeof ScheduleRunStatusSchema>;export type ScheduleManifest = z.infer<typeof ScheduleManifestSchema>;@@ -163,3 +178,4 @@ export type Schedule = z.infer<typeof ScheduleSchema>;export type ScheduleRun = z.infer<typeof ScheduleRunSchema>;export type CreateScheduleRequest = z.infer<typeof CreateScheduleRequestSchema>;export type UpdateScheduleRequest = z.infer<typeof UpdateScheduleRequestSchema>;+export type CreateScheduleRunRequest = z.infer<typeof CreateScheduleRunRequestSchema>;diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.tsindex 5a304e347..abdfff846 100644--- a/packages/trueforge/tests/unit/apis/schedules.test.ts+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts@@ -3,11 +3,25 @@ import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';import { createSchedulesRouter } from '../../../src/apis/schedules';import { TENANT_ID } from '../../../src/apis/sessions';import type { UserContext } from '../../../src/auth/identity';+import { ScheduleAgentNotFoundError, startScheduleRun } from '../../../src/controller/scheduleDispatch';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteScheduleStore } from '../../../src/db/sqlite/schedule-store/SqliteScheduleStore';-import { ListScheduleRunsResponseSchema, ListSchedulesResponseSchema } from '../../../src/schemas/schedule';+import {+ CreateScheduleRunResponseSchema,+ ListScheduleRunsResponseSchema,+ ListSchedulesResponseSchema,+} from '../../../src/schemas/schedule';++jest.mock('../../../src/controller/scheduleDispatch', () => ({+ ...jest.requireActual<typeof import('../../../src/controller/scheduleDispatch')>(+ '../../../src/controller/scheduleDispatch',+ ),+ startScheduleRun: jest.fn().mockResolvedValue(undefined),+}));++const mockedStartScheduleRun = jest.mocked(startScheduleRun);const ALICE: UserContext = { userRef: 'alice', role: 'user' };const BOB: UserContext = { userRef: 'bob', role: 'user' };@@ -37,6 +51,20 @@ async function setup() {createSchedulesRouter({scheduleStore,agentStore,+ sessions: {+ getOrCreateByExternalId: () => Promise.reject(new Error('sessions stub: unexpected call')),+ } as never,+ turnDeps: {+ activeTurns: {} as never,+ eventSubscriptions: {} as never,+ modelProviderStore: {} as never,+ mcpServerStore: {} as never,+ tokenStore: {} as never,+ skillStore: {} as never,+ agentStore,+ sandboxProviderStore: {} as never,+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() } as never,+ },withTransaction: callback => db.transaction().execute(callback),resolveUserContext: () => current,}),@@ -48,11 +76,11 @@ async function setup() {const postJson = (path: string, method: string, body: unknown) =>app.request(path, { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });- return { app, asUser, postJson, agentStore };+ return { app, asUser, postJson, agentStore, scheduleStore };}describe('schedule RBAC β creator-scoped, admin sees all', () => {- it("hides another user's schedule from get, update, delete, and list", async () => {+ it("hides another user's schedule from get, update, delete, list, and run trigger", async () => {const { app, asUser, postJson } = await setup();asUser(ALICE);@@ -70,6 +98,8 @@ describe('schedule RBAC β creator-scoped, admin sees all', () => {expect(ListSchedulesResponseSchema.parse(await bobList.json()).data).toEqual([]);expect((await app.request(`/${id}/runs`)).status).toBe(403);+ expect((await postJson('/runs', 'POST', { schedule_id: id })).status).toBe(403);+ expect(mockedStartScheduleRun).not.toHaveBeenCalled();});it('lets the creator see and manage their own schedule', async () => {@@ -91,10 +121,11 @@ describe('schedule RBAC β creator-scoped, admin sees all', () => {});it('does not leak existence: a missing schedule is 404, not 403', async () => {- const { app, asUser } = await setup();+ const { app, asUser, postJson } = await setup();asUser(BOB);expect((await app.request('/01jqzz000000000000000nope')).status).toBe(404);expect((await app.request('/01jqzz000000000000000nope/runs')).status).toBe(404);+ expect((await postJson('/runs', 'POST', { schedule_id: '01jqzz000000000000000nope' })).status).toBe(404);});it("lets an admin see and manage any user's schedule", async () => {@@ -201,3 +232,82 @@ describe('schedule list agent_names filter', () => {}});});++describe('create schedule run', () => {+ beforeEach(() => {+ mockedStartScheduleRun.mockReset();+ mockedStartScheduleRun.mockResolvedValue(undefined);+ });++ it('creates a triggered run with a manual-* name and leaves the cron pending run alone', async () => {+ const { asUser, postJson, scheduleStore } = await setup();++ asUser(ALICE);+ const created = await postJson('/', 'POST', scheduleBody);+ const { id: scheduleId } = ((await created.json()) as { data: { id: string } }).data;++ const pendingBefore = await scheduleStore.getScheduledRunFor({ tenant_id: TENANT_ID, schedule_id: scheduleId });+ expect(pendingBefore?.status).toBe('scheduled');++ const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });+ expect(res.status).toBe(201);+ const body = CreateScheduleRunResponseSchema.parse(await res.json());+ expect(body.data).toEqual(+ expect.objectContaining({+ schedule_id: scheduleId,+ status: 'triggered',+ triggered_by: 'alice',+ name: expect.stringMatching(/^manual-/),+ }),+ );+ expect(body.data.triggered_at).not.toBeNull();++ expect(mockedStartScheduleRun).toHaveBeenCalledWith(+ expect.objectContaining({+ item: expect.objectContaining({+ run: expect.objectContaining({ id: body.data.id }),+ schedule: expect.objectContaining({ id: scheduleId }),+ }),+ }),+ );++ const pendingAfter = await scheduleStore.getScheduledRunFor({ tenant_id: TENANT_ID, schedule_id: scheduleId });+ expect(pendingAfter?.id).toBe(pendingBefore?.id);+ expect(pendingAfter?.status).toBe('scheduled');++ const runs = await scheduleStore.listRuns({ tenant_id: TENANT_ID, schedule_id: scheduleId });+ expect(runs.map(r => r.status).sort()).toEqual(['scheduled', 'triggered']);+ });++ it('lets an admin trigger a run owned by another user', async () => {+ const { asUser, postJson } = await setup();++ asUser(ALICE);+ const created = await postJson('/', 'POST', scheduleBody);+ const { id: scheduleId } = ((await created.json()) as { data: { id: string } }).data;++ asUser(ADMIN);+ const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });+ expect(res.status).toBe(201);+ const body = CreateScheduleRunResponseSchema.parse(await res.json());+ expect(body.data.triggered_by).toBe('root');+ expect(mockedStartScheduleRun).toHaveBeenCalled();+ });++ it('marks the run failed and returns 404 when startScheduleRun reports a missing agent', async () => {+ mockedStartScheduleRun.mockRejectedValue(new ScheduleAgentNotFoundError('reporter'));+ const { asUser, postJson, scheduleStore } = await setup();++ asUser(ALICE);+ const created = await postJson('/', 'POST', scheduleBody);+ const { id: scheduleId } = ((await created.json()) as { data: { id: string } }).data;++ const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });+ 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: TENANT_ID, schedule_id: scheduleId });+ const runNow = runs.find(r => r.name.startsWith('manual-'));+ expect(runNow?.status).toBe('failed');+ });+});diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.tsindex 0a00896ab..fdcf61cfc 100644--- a/packages/trueforge/tests/unit/apis/turns.test.ts+++ b/packages/trueforge/tests/unit/apis/turns.test.ts@@ -132,6 +132,7 @@ describe('turns', () => {const sessions = {get: () =>Promise.resolve({+ session_id: 's1',spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),record: { last_turn_id: null, created_by: LOCAL_USER_CONTEXT.userRef },createTurn: () =>diff --git a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.tsindex be9ccd5c2..d65f2d91b 100644--- a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts+++ b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts@@ -1,4 +1,8 @@-import { scheduleDispatchLoop } from '../../../src/controller/scheduleDispatch';+import {+ ScheduleAgentNotFoundError,+ scheduleDispatchLoop,+ startScheduleRun,+} from '../../../src/controller/scheduleDispatch';import type { ScheduleDispatchItem, ScheduleRunRecord } from '../../../src/db/scheduleStore';import { ScheduleManifestSchema } from '../../../src/schemas/schedule';@@ -120,3 +124,71 @@ describe('scheduleDispatchLoop', () => {);});});++describe('startScheduleRun', () => {+ const startTurn = jest.fn().mockResolvedValue({ id: 'turn-1' });++ beforeEach(() => {+ startTurn.mockClear();+ startTurn.mockResolvedValue({ id: 'turn-1' });+ });++ it('get-or-creates a session and starts a turn with the schedule task', async () => {+ const dispatchItem = item();+ const listTurns = jest.fn().mockResolvedValue({ data: [] });+ const session = { listTurns };+ const getOrCreateByExternalId = jest.fn().mockResolvedValue({ session, created: true });+ const getAgent = jest.fn().mockResolvedValue({ id: 'agent-1', name: 'reporter' });++ await startScheduleRun({+ item: dispatchItem,+ sessions: { getOrCreateByExternalId } as never,+ agentStore: { getAgent } as never,+ startTurn,+ });++ expect(getAgent).toHaveBeenCalledWith({ tenant_id: 'default', name: 'reporter' });+ expect(getOrCreateByExternalId).toHaveBeenCalledWith({+ tenant_id: 'default',+ external_id: 'run-1',+ created_by: 'tester',+ agent: { type: 'reference', id: 'agent-1', name: 'reporter' },+ });+ expect(startTurn).toHaveBeenCalledWith({+ session,+ input: [{ type: 'user.message', content: 'Write the report' }],+ previous_turn_id: 'none',+ userRef: 'tester',+ });+ });++ it('does not start a turn when the session already has one', async () => {+ const listTurns = jest.fn().mockResolvedValue({ data: [{ turn_id: 'turn-1' }] });+ const getOrCreateByExternalId = jest.fn().mockResolvedValue({+ session: { listTurns },+ created: false,+ });+ const getAgent = jest.fn().mockResolvedValue({ id: 'agent-1', name: 'reporter' });++ await startScheduleRun({+ item: item(),+ sessions: { getOrCreateByExternalId } as never,+ agentStore: { getAgent } as never,+ startTurn,+ });++ expect(startTurn).not.toHaveBeenCalled();+ });++ it('throws when the schedule agent is missing', async () => {+ await expect(+ startScheduleRun({+ item: item(),+ sessions: { getOrCreateByExternalId: jest.fn() } as never,+ agentStore: { getAgent: jest.fn().mockResolvedValue(undefined) } as never,+ startTurn,+ }),+ ).rejects.toBeInstanceOf(ScheduleAgentNotFoundError);+ expect(startTurn).not.toHaveBeenCalled();+ });+});