Skip to content

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

feat: Schedules (#472)

Heer Ambavia3a13956e99c
diff --git a/.changeset/20260827190410-regenerate-sdk-from-openapi.md b/.changeset/20260827190410-regenerate-sdk-from-openapi.md
new file mode 100644
index 000000000..efd8ff00f
--- /dev/null
+++ b/.changeset/20260827190410-regenerate-sdk-from-openapi.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-sdk": patch
+---
+
+Regenerate SDK from updated OpenAPI spec.
diff --git a/.changeset/cron-schedules.md b/.changeset/cron-schedules.md
new file mode 100644
index 000000000..f7217946a
--- /dev/null
+++ b/.changeset/cron-schedules.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": minor
+---
+
+Adds first-class cron schedules for existing agents: persist them, manage them via /api/v1/schedules, validate cron policy at write time, and advance due runs through a single-dispatcher claim path.
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index a1e852ef1..016c6349c 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -17,7 +17,7 @@ updates:
exclude-paths:
- packages/trueforge-sdk/**
ignore:
- - dependency-name: "*"
+ - dependency-name: '*'
update-types:
- version-update:semver-major
groups:
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 8ba3cb9fc..aeed990c5 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -926,6 +926,26 @@
],
"type": "object"
},
+ "CreateScheduleRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "agent_name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ },
+ "required": [
+ "agent_name",
+ "name",
+ "manifest"
+ ],
+ "type": "object"
+ },
"CreateSessionAgent": {
"anyOf": [
{
@@ -980,6 +1000,11 @@
},
"type": "object"
},
+ "CronExpression": {
+ "description": "Standard 5-field cron expression, evaluated in `timezone`.",
+ "pattern": "^[\\d*,\\-/]+(?:\\s+[\\d*,\\-/]+){4}$",
+ "type": "string"
+ },
"CustomModelProvider": {
"additionalProperties": false,
"properties": {
@@ -1036,6 +1061,10 @@
"properties": {},
"type": "object"
},
+ "DeleteScheduleResponse": {
+ "properties": {},
+ "type": "object"
+ },
"DynamicSubAgentsConfig": {
"default": {
"enabled": true
@@ -1274,6 +1303,17 @@
],
"type": "object"
},
+ "GetScheduleResponse": {
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/Schedule"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"GetSessionResponse": {
"properties": {
"data": {
@@ -1511,6 +1551,20 @@
],
"type": "object"
},
+ "ListSchedulesResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/Schedule"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"ListSessionEventsResponse": {
"properties": {
"data": {
@@ -2798,6 +2852,76 @@
],
"type": "object"
},
+ "Schedule": {
+ "additionalProperties": false,
+ "properties": {
+ "agent_name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "created_at": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "created_by": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "updated_at": {
+ "format": "date-time",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "agent_name",
+ "name",
+ "manifest",
+ "created_by",
+ "created_at",
+ "updated_at"
+ ],
+ "type": "object"
+ },
+ "ScheduleManifest": {
+ "additionalProperties": false,
+ "properties": {
+ "cron": {
+ "$ref": "#/components/schemas/CronExpression"
+ },
+ "status": {
+ "$ref": "#/components/schemas/ScheduleStatus"
+ },
+ "task": {
+ "description": "First user message sent to the agent on every run.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "timezone": {
+ "$ref": "#/components/schemas/Timezone"
+ }
+ },
+ "required": [
+ "task",
+ "cron"
+ ],
+ "type": "object"
+ },
+ "ScheduleStatus": {
+ "default": "active",
+ "enum": [
+ "active",
+ "paused"
+ ],
+ "type": "string"
+ },
"Session": {
"properties": {
"agent": {
@@ -3247,6 +3371,12 @@
],
"type": "object"
},
+ "Timezone": {
+ "default": "UTC",
+ "description": "IANA time zone the cron expression is evaluated in.",
+ "minLength": 1,
+ "type": "string"
+ },
"TogetherAIModelProvider": {
"additionalProperties": false,
"properties": {
@@ -3972,6 +4102,22 @@
],
"type": "object"
},
+ "UpdateScheduleRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ },
+ "required": [
+ "name",
+ "manifest"
+ ],
+ "type": "object"
+ },
"UpdateSessionRequest": {
"additionalProperties": false,
"properties": {
@@ -5250,6 +5396,277 @@
"x-fern-sdk-method-name": "list"
}
},
+ "/api/v1/schedules": {
+ "get": {
+ "description": "List schedules for the tenant, newest first. Optionally filter by `agent_name`.",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "agent_name",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListSchedulesResponse"
+ }
+ }
+ },
+ "description": "Matching schedules."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unauthenticated."
+ }
+ },
+ "summary": "List schedules",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "list"
+ },
+ "post": {
+ "description": "Create a schedule for an existing agent (by name) and add its first pending run when active.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateScheduleRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "Created schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unknown agent or invalid cron."
+ },
+ "409": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The schedule was modified concurrently (usually the controller advancing it). Retry."
+ }
+ },
+ "summary": "Create a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "create"
+ }
+ },
+ "/api/v1/schedules/{schedule_id}": {
+ "delete": {
+ "description": "Delete a schedule and its runs. Idempotent.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeleteScheduleResponse"
+ }
+ }
+ },
+ "description": "Deleted."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unauthenticated."
+ }
+ },
+ "summary": "Delete a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "delete"
+ },
+ "get": {
+ "description": "Get a schedule by id.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "The schedule."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Not found."
+ }
+ },
+ "summary": "Get a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "get"
+ },
+ "put": {
+ "description": "Replace name and manifest; replaces or drops the pending run when status/cron/timezone change.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateScheduleRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "Updated schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid cron."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Not found."
+ },
+ "409": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The schedule was modified concurrently (usually the controller advancing it). Retry."
+ }
+ },
+ "summary": "Update a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "update"
+ }
+ },
"/api/v1/sessions": {
"get": {
"description": "List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.",
@@ -7094,6 +7511,9 @@
{
"name": "Agents"
},
+ {
+ "name": "Schedules"
+ },
{
"name": "Agent Sessions"
}
diff --git a/docs/openapi.json b/docs/openapi.json
index 8ba3cb9fc..aeed990c5 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -926,6 +926,26 @@
],
"type": "object"
},
+ "CreateScheduleRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "agent_name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ },
+ "required": [
+ "agent_name",
+ "name",
+ "manifest"
+ ],
+ "type": "object"
+ },
"CreateSessionAgent": {
"anyOf": [
{
@@ -980,6 +1000,11 @@
},
"type": "object"
},
+ "CronExpression": {
+ "description": "Standard 5-field cron expression, evaluated in `timezone`.",
+ "pattern": "^[\\d*,\\-/]+(?:\\s+[\\d*,\\-/]+){4}$",
+ "type": "string"
+ },
"CustomModelProvider": {
"additionalProperties": false,
"properties": {
@@ -1036,6 +1061,10 @@
"properties": {},
"type": "object"
},
+ "DeleteScheduleResponse": {
+ "properties": {},
+ "type": "object"
+ },
"DynamicSubAgentsConfig": {
"default": {
"enabled": true
@@ -1274,6 +1303,17 @@
],
"type": "object"
},
+ "GetScheduleResponse": {
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/Schedule"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"GetSessionResponse": {
"properties": {
"data": {
@@ -1511,6 +1551,20 @@
],
"type": "object"
},
+ "ListSchedulesResponse": {
+ "properties": {
+ "data": {
+ "items": {
+ "$ref": "#/components/schemas/Schedule"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"ListSessionEventsResponse": {
"properties": {
"data": {
@@ -2798,6 +2852,76 @@
],
"type": "object"
},
+ "Schedule": {
+ "additionalProperties": false,
+ "properties": {
+ "agent_name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "created_at": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "created_by": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ },
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ },
+ "updated_at": {
+ "format": "date-time",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "agent_name",
+ "name",
+ "manifest",
+ "created_by",
+ "created_at",
+ "updated_at"
+ ],
+ "type": "object"
+ },
+ "ScheduleManifest": {
+ "additionalProperties": false,
+ "properties": {
+ "cron": {
+ "$ref": "#/components/schemas/CronExpression"
+ },
+ "status": {
+ "$ref": "#/components/schemas/ScheduleStatus"
+ },
+ "task": {
+ "description": "First user message sent to the agent on every run.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "timezone": {
+ "$ref": "#/components/schemas/Timezone"
+ }
+ },
+ "required": [
+ "task",
+ "cron"
+ ],
+ "type": "object"
+ },
+ "ScheduleStatus": {
+ "default": "active",
+ "enum": [
+ "active",
+ "paused"
+ ],
+ "type": "string"
+ },
"Session": {
"properties": {
"agent": {
@@ -3247,6 +3371,12 @@
],
"type": "object"
},
+ "Timezone": {
+ "default": "UTC",
+ "description": "IANA time zone the cron expression is evaluated in.",
+ "minLength": 1,
+ "type": "string"
+ },
"TogetherAIModelProvider": {
"additionalProperties": false,
"properties": {
@@ -3972,6 +4102,22 @@
],
"type": "object"
},
+ "UpdateScheduleRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "manifest": {
+ "$ref": "#/components/schemas/ScheduleManifest"
+ },
+ "name": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ },
+ "required": [
+ "name",
+ "manifest"
+ ],
+ "type": "object"
+ },
"UpdateSessionRequest": {
"additionalProperties": false,
"properties": {
@@ -5250,6 +5396,277 @@
"x-fern-sdk-method-name": "list"
}
},
+ "/api/v1/schedules": {
+ "get": {
+ "description": "List schedules for the tenant, newest first. Optionally filter by `agent_name`.",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "agent_name",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ResourceName"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListSchedulesResponse"
+ }
+ }
+ },
+ "description": "Matching schedules."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unauthenticated."
+ }
+ },
+ "summary": "List schedules",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "list"
+ },
+ "post": {
+ "description": "Create a schedule for an existing agent (by name) and add its first pending run when active.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateScheduleRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "Created schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unknown agent or invalid cron."
+ },
+ "409": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The schedule was modified concurrently (usually the controller advancing it). Retry."
+ }
+ },
+ "summary": "Create a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "create"
+ }
+ },
+ "/api/v1/schedules/{schedule_id}": {
+ "delete": {
+ "description": "Delete a schedule and its runs. Idempotent.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeleteScheduleResponse"
+ }
+ }
+ },
+ "description": "Deleted."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Unauthenticated."
+ }
+ },
+ "summary": "Delete a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "delete"
+ },
+ "get": {
+ "description": "Get a schedule by id.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "The schedule."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Not found."
+ }
+ },
+ "summary": "Get a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "get"
+ },
+ "put": {
+ "description": "Replace name and manifest; replaces or drops the pending run when status/cron/timezone change.",
+ "parameters": [
+ {
+ "description": "Immutable schedule identifier.",
+ "in": "path",
+ "name": "schedule_id",
+ "required": true,
+ "schema": {
+ "description": "Immutable schedule identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateScheduleRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetScheduleResponse"
+ }
+ }
+ },
+ "description": "Updated schedule."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid cron."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Not found."
+ },
+ "409": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The schedule was modified concurrently (usually the controller advancing it). Retry."
+ }
+ },
+ "summary": "Update a schedule",
+ "tags": [
+ "Schedules"
+ ],
+ "x-fern-sdk-group-name": [
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "update"
+ }
+ },
"/api/v1/sessions": {
"get": {
"description": "List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.",
@@ -7094,6 +7511,9 @@
{
"name": "Agents"
},
+ {
+ "name": "Schedules"
+ },
{
"name": "Agent Sessions"
}
diff --git a/packages/trueforge-sdk/package.json b/packages/trueforge-sdk/package.json
index 81ca6b06c..05c2fdca6 100644
--- a/packages/trueforge-sdk/package.json
+++ b/packages/trueforge-sdk/package.json
@@ -84,6 +84,17 @@
},
"default": "./dist/cjs/api/resources/models/exports.js"
},
+ "./schedules": {
+ "import": {
+ "types": "./dist/esm/api/resources/schedules/exports.d.mts",
+ "default": "./dist/esm/api/resources/schedules/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/schedules/exports.d.ts",
+ "default": "./dist/cjs/api/resources/schedules/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/schedules/exports.js"
+ },
"./sessions": {
"import": {
"types": "./dist/esm/api/resources/sessions/exports.d.mts",
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 2787f170e..fe2cd9282 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -745,6 +745,343 @@ await client.models.list();
</dl>
+</dd>
+</dl>
+</details>
+
+## Schedules
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">list</a>({ ...params }) -> TrueForge.ListSchedulesResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+List schedules for the tenant, newest first. Optionally filter by `agent_name`.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.schedules.list();
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.ListSchedulesRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">create</a>({ ...params }) -> TrueForge.GetScheduleResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Create a schedule for an existing agent (by name) and add its first pending run when active.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.schedules.create({
+ agentName: "agent_name",
+ manifest: {
+ cron: "cron",
+ task: "task"
+ },
+ name: "name"
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.CreateScheduleRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">get</a>(schedule_id) -> TrueForge.GetScheduleResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Get a schedule by id.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.schedules.get("schedule_id");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**schedule_id:** `string` — Immutable schedule identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">update</a>(schedule_id, { ...params }) -> TrueForge.GetScheduleResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Replace name and manifest; replaces or drops the pending run when status/cron/timezone change.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.schedules.update("schedule_id", {
+ manifest: {
+ cron: "cron",
+ task: "task"
+ },
+ name: "name"
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**schedule_id:** `string` — Immutable schedule identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.UpdateScheduleRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.schedules.<a href="/src/api/resources/schedules/client/Client.ts">delete</a>(schedule_id) -> TrueForge.DeleteScheduleResponse</code></summary>
+<dl>
+<dd>
+
+#### 📝 Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Delete a schedule and its runs. Idempotent.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### 🔌 Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.schedules.delete("schedule_id");
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### ⚙️ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**schedule_id:** `string` — Immutable schedule identifier.
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
</dd>
</dl>
</details>
diff --git a/packages/trueforge-sdk/src/Client.ts b/packages/trueforge-sdk/src/Client.ts
index b3a61d0af..ed658f25b 100644
--- a/packages/trueforge-sdk/src/Client.ts
+++ b/packages/trueforge-sdk/src/Client.ts
@@ -5,6 +5,7 @@ import { AuthClient } from "./api/resources/auth/client/Client.js";
import { CatalogsClient } from "./api/resources/catalogs/client/Client.js";
import { McpServersClient } from "./api/resources/mcpServers/client/Client.js";
import { ModelsClient } from "./api/resources/models/client/Client.js";
+import { SchedulesClient } from "./api/resources/schedules/client/Client.js";
import { ServerClient } from "./api/resources/server/client/Client.js";
import { SessionsClient } from "./api/resources/sessions/client/Client.js";
import { SettingsClient } from "./api/resources/settings/client/Client.js";
@@ -26,6 +27,7 @@ export class TrueForge {
protected _server: ServerClient | undefined;
protected _mcpServers: McpServersClient | undefined;
protected _models: ModelsClient | undefined;
+ protected _schedules: SchedulesClient | undefined;
protected _sessions: SessionsClient | undefined;
protected _skills: SkillsClient | undefined;
protected _catalogs: CatalogsClient | undefined;
@@ -55,6 +57,10 @@ export class TrueForge {
return (this._models ??= new ModelsClient(this._options));
}
+ public get schedules(): SchedulesClient {
+ return (this._schedules ??= new SchedulesClient(this._options));
+ }
+
public get sessions(): SessionsClient {
return (this._sessions ??= new SessionsClient(this._options));
}
diff --git a/packages/trueforge-sdk/src/api/resources/index.ts b/packages/trueforge-sdk/src/api/resources/index.ts
index a54d0ff18..e5ee899b1 100644
--- a/packages/trueforge-sdk/src/api/resources/index.ts
+++ b/packages/trueforge-sdk/src/api/resources/index.ts
@@ -5,6 +5,8 @@ export * as catalogs from "./catalogs/index.js";
export * from "./mcpServers/client/requests/index.js";
export * as mcpServers from "./mcpServers/index.js";
export * as models from "./models/index.js";
+export * from "./schedules/client/requests/index.js";
+export * as schedules from "./schedules/index.js";
export * as server from "./server/index.js";
export * from "./sessions/client/requests/index.js";
export * as sessions from "./sessions/index.js";
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
new file mode 100644
index 000000000..e8ffbebb6
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/Client.ts
@@ -0,0 +1,537 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
+import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js";
+import { mergeHeaders } from "../../../../core/headers.js";
+import * as core from "../../../../core/index.js";
+import { mergeAdditionalBodyParameters } from "../../../../core/requestBody.js";
+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
+import * as errors from "../../../../errors/index.js";
+import * as serializers from "../../../../serialization/index.js";
+import * as TrueForge from "../../../index.js";
+
+export declare namespace SchedulesClient {
+ export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
+}
+
+export class SchedulesClient {
+ protected readonly _options: NormalizedClientOptionsWithAuth<SchedulesClient.Options>;
+
+ constructor(options: SchedulesClient.Options) {
+ this._options = normalizeClientOptionsWithAuth(options);
+ }
+
+ /**
+ * List schedules for the tenant, newest first. Optionally filter by `agent_name`.
+ *
+ * @param {TrueForge.ListSchedulesRequest} request
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.schedules.list()
+ */
+ public 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, {
+ 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");
+ }
+
+ /**
+ * Create a schedule for an existing agent (by name) and add its first pending run when active.
+ *
+ * @param {TrueForge.CreateScheduleRequest} request
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ConflictError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.schedules.create({
+ * agentName: "agent_name",
+ * manifest: {
+ * cron: "cron",
+ * task: "task"
+ * },
+ * name: "name"
+ * })
+ */
+ public create(
+ request: TrueForge.CreateScheduleRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueForge.GetScheduleResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
+ }
+
+ private async __create(
+ request: TrueForge.CreateScheduleRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueForge.GetScheduleResponse>> {
+ 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: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.CreateScheduleRequest.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.GetScheduleResponse.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 409:
+ throw new TrueForge.ConflictError(
+ 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");
+ }
+
+ /**
+ * Get a schedule by id.
+ *
+ * @param {string} schedule_id - Immutable schedule identifier.
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.NotFoundError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.schedules.get("schedule_id")
+ */
+ public get(
+ schedule_id: string,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueForge.GetScheduleResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__get(schedule_id, requestOptions));
+ }
+
+ private async __get(
+ schedule_id: string,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueForge.GetScheduleResponse>> {
+ 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)}`,
+ ),
+ 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.GetScheduleResponse.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 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}",
+ );
+ }
+
+ /**
+ * Replace name and manifest; replaces or drops the pending run when status/cron/timezone change.
+ *
+ * @param {string} schedule_id - Immutable schedule identifier.
+ * @param {TrueForge.UpdateScheduleRequest} request
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.NotFoundError}
+ * @throws {@link TrueForge.ConflictError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.schedules.update("schedule_id", {
+ * manifest: {
+ * cron: "cron",
+ * task: "task"
+ * },
+ * name: "name"
+ * })
+ */
+ public update(
+ schedule_id: string,
+ request: TrueForge.UpdateScheduleRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueForge.GetScheduleResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__update(schedule_id, request, requestOptions));
+ }
+
+ private async __update(
+ schedule_id: string,
+ request: TrueForge.UpdateScheduleRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueForge.GetScheduleResponse>> {
+ 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)}`,
+ ),
+ method: "PUT",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.UpdateScheduleRequest.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.GetScheduleResponse.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 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,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "PUT",
+ "/api/v1/schedules/{schedule_id}",
+ );
+ }
+
+ /**
+ * Delete a schedule and its runs. Idempotent.
+ *
+ * @param {string} schedule_id - Immutable schedule identifier.
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.schedules.delete("schedule_id")
+ */
+ public delete(
+ schedule_id: string,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueForge.DeleteScheduleResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__delete(schedule_id, requestOptions));
+ }
+
+ private async __delete(
+ schedule_id: string,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueForge.DeleteScheduleResponse>> {
+ 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)}`,
+ ),
+ method: "DELETE",
+ 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.DeleteScheduleResponse.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, {
+ 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,
+ "DELETE",
+ "/api/v1/schedules/{schedule_id}",
+ );
+ }
+}
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/index.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRequest.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRequest.ts
new file mode 100644
index 000000000..0eead5748
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/CreateScheduleRequest.ts
@@ -0,0 +1,20 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../index.js";
+
+/**
+ * @example
+ * {
+ * agentName: "agent_name",
+ * manifest: {
+ * cron: "cron",
+ * task: "task"
+ * },
+ * name: "name"
+ * }
+ */
+export interface CreateScheduleRequest {
+ agentName: TrueForge.ResourceName;
+ manifest: TrueForge.ScheduleManifest;
+ name: TrueForge.ResourceName;
+}
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
new file mode 100644
index 000000000..9cdfd1c37
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/ListSchedulesRequest.ts
@@ -0,0 +1,11 @@
+// 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;
+}
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/client/requests/UpdateScheduleRequest.ts b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/UpdateScheduleRequest.ts
new file mode 100644
index 000000000..3761fdb3d
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/UpdateScheduleRequest.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../index.js";
+
+/**
+ * @example
+ * {
+ * manifest: {
+ * cron: "cron",
+ * task: "task"
+ * },
+ * name: "name"
+ * }
+ */
+export interface UpdateScheduleRequest {
+ manifest: TrueForge.ScheduleManifest;
+ name: TrueForge.ResourceName;
+}
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
new file mode 100644
index 000000000..7dddd3f34
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/client/requests/index.ts
@@ -0,0 +1,3 @@
+export type { CreateScheduleRequest } from "./CreateScheduleRequest.js";
+export type { ListSchedulesRequest } from "./ListSchedulesRequest.js";
+export type { UpdateScheduleRequest } from "./UpdateScheduleRequest.js";
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/exports.ts b/packages/trueforge-sdk/src/api/resources/schedules/exports.ts
new file mode 100644
index 000000000..75e4547ce
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/exports.ts
@@ -0,0 +1,4 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export { SchedulesClient } from "./client/Client.js";
+export * from "./client/index.js";
diff --git a/packages/trueforge-sdk/src/api/resources/schedules/index.ts b/packages/trueforge-sdk/src/api/resources/schedules/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/schedules/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/trueforge-sdk/src/api/types/CronExpression.ts b/packages/trueforge-sdk/src/api/types/CronExpression.ts
new file mode 100644
index 000000000..d9095f354
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/CronExpression.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * Standard 5-field cron expression, evaluated in `timezone`.
+ */
+export type CronExpression = string;
diff --git a/packages/trueforge-sdk/src/api/types/DeleteScheduleResponse.ts b/packages/trueforge-sdk/src/api/types/DeleteScheduleResponse.ts
new file mode 100644
index 000000000..d74480f2e
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/DeleteScheduleResponse.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type DeleteScheduleResponse = {};
diff --git a/packages/trueforge-sdk/src/api/types/GetScheduleResponse.ts b/packages/trueforge-sdk/src/api/types/GetScheduleResponse.ts
new file mode 100644
index 000000000..9968d967c
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/GetScheduleResponse.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 GetScheduleResponse {
+ data: TrueForge.Schedule;
+}
diff --git a/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts b/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.ts
new file mode 100644
index 000000000..547843582
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/ListSchedulesResponse.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 ListSchedulesResponse {
+ data: TrueForge.Schedule[];
+}
diff --git a/packages/trueforge-sdk/src/api/types/Schedule.ts b/packages/trueforge-sdk/src/api/types/Schedule.ts
new file mode 100644
index 000000000..5d79a4fad
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/Schedule.ts
@@ -0,0 +1,13 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../index.js";
+
+export interface Schedule {
+ agentName: TrueForge.ResourceName;
+ createdAt: Date;
+ createdBy: string;
+ id: string;
+ manifest: TrueForge.ScheduleManifest;
+ name: TrueForge.ResourceName;
+ updatedAt: Date;
+}
diff --git a/packages/trueforge-sdk/src/api/types/ScheduleManifest.ts b/packages/trueforge-sdk/src/api/types/ScheduleManifest.ts
new file mode 100644
index 000000000..14b508607
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/ScheduleManifest.ts
@@ -0,0 +1,11 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../index.js";
+
+export interface ScheduleManifest {
+ cron: TrueForge.CronExpression;
+ status?: TrueForge.ScheduleStatus;
+ /** First user message sent to the agent on every run. */
+ task: string;
+ timezone?: TrueForge.Timezone;
+}
diff --git a/packages/trueforge-sdk/src/api/types/ScheduleStatus.ts b/packages/trueforge-sdk/src/api/types/ScheduleStatus.ts
new file mode 100644
index 000000000..5c681387e
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/ScheduleStatus.ts
@@ -0,0 +1,7 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export const ScheduleStatus = {
+ Active: "active",
+ Paused: "paused",
+} as const;
+export type ScheduleStatus = (typeof ScheduleStatus)[keyof typeof ScheduleStatus];
diff --git a/packages/trueforge-sdk/src/api/types/Timezone.ts b/packages/trueforge-sdk/src/api/types/Timezone.ts
new file mode 100644
index 000000000..d45cfb30c
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/Timezone.ts
@@ -0,0 +1,6 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * IANA time zone the cron expression is evaluated in.
+ */
+export type Timezone = string;
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index 6b493fd5a..0405043db 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -39,9 +39,11 @@ export * from "./ConfiguredSandboxProvider.js";
export * from "./ConfiguredSkill.js";
export * from "./ContextManagementConfig.js";
export * from "./CreateSessionAgent.js";
+export * from "./CronExpression.js";
export * from "./CustomModelProvider.js";
export * from "./DaytonaSandboxProviderAuth.js";
export * from "./DeleteAgentResponse.js";
+export * from "./DeleteScheduleResponse.js";
export * from "./DynamicSubAgentsConfig.js";
export * from "./ExtendedChunkDeltaToolCall.js";
export * from "./FileContent.js";
@@ -58,6 +60,7 @@ export * from "./GetModelProviderCatalogResponse.js";
export * from "./GetModelProviderResponse.js";
export * from "./GetSandboxProviderCatalogResponse.js";
export * from "./GetSandboxProviderResponse.js";
+export * from "./GetScheduleResponse.js";
export * from "./GetSessionResponse.js";
export * from "./GetSkillCatalogResponse.js";
export * from "./GetSkillResponse.js";
@@ -73,6 +76,7 @@ export * from "./ListAvailableSkillsResponse.js";
export * from "./ListMcpServersResponse.js";
export * from "./ListMcpServerToolsResponse.js";
export * from "./ListModelProvidersResponse.js";
+export * from "./ListSchedulesResponse.js";
export * from "./ListSessionEventsResponse.js";
export * from "./ListSessionsOrder.js";
export * from "./ListSessionsResponse.js";
@@ -129,6 +133,9 @@ export * from "./SandboxCapability.js";
export * from "./SandboxConfig.js";
export * from "./SandboxCreatedEvent.js";
export * from "./SandboxProviderManifest.js";
+export * from "./Schedule.js";
+export * from "./ScheduleManifest.js";
+export * from "./ScheduleStatus.js";
export * from "./Session.js";
export * from "./SessionAgent.js";
export * from "./SessionAgentInline.js";
@@ -148,6 +155,7 @@ export * from "./ThreadDoneEvent.js";
export * from "./ThreadState.js";
export * from "./ThreadStateDone.js";
export * from "./ThreadStateError.js";
+export * from "./Timezone.js";
export * from "./TogetherAiModelProvider.js";
export * from "./TokenPagination.js";
export * from "./ToolApprovalRequiredEvent.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/index.ts b/packages/trueforge-sdk/src/serialization/resources/index.ts
index 843403a46..38709c072 100644
--- a/packages/trueforge-sdk/src/serialization/resources/index.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/index.ts
@@ -1,5 +1,7 @@
export * from "./agents/client/requests/index.js";
export * as agents from "./agents/index.js";
+export * from "./schedules/client/requests/index.js";
+export * as schedules from "./schedules/index.js";
export * from "./sessions/client/requests/index.js";
export * as sessions from "./sessions/index.js";
export * as settings from "./settings/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/client/index.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRequest.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRequest.ts
new file mode 100644
index 000000000..8c408e2ee
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/CreateScheduleRequest.ts
@@ -0,0 +1,24 @@
+// 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 { ResourceName } from "../../../../types/ResourceName.js";
+import { ScheduleManifest } from "../../../../types/ScheduleManifest.js";
+
+export const CreateScheduleRequest: core.serialization.Schema<
+ serializers.CreateScheduleRequest.Raw,
+ TrueForge.CreateScheduleRequest
+> = core.serialization.object({
+ agentName: core.serialization.property("agent_name", ResourceName),
+ manifest: ScheduleManifest,
+ name: ResourceName,
+});
+
+export declare namespace CreateScheduleRequest {
+ export interface Raw {
+ agent_name: ResourceName.Raw;
+ manifest: ScheduleManifest.Raw;
+ name: ResourceName.Raw;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/UpdateScheduleRequest.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/UpdateScheduleRequest.ts
new file mode 100644
index 000000000..5eec71019
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/UpdateScheduleRequest.ts
@@ -0,0 +1,22 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+import { ResourceName } from "../../../../types/ResourceName.js";
+import { ScheduleManifest } from "../../../../types/ScheduleManifest.js";
+
+export const UpdateScheduleRequest: core.serialization.Schema<
+ serializers.UpdateScheduleRequest.Raw,
+ TrueForge.UpdateScheduleRequest
+> = core.serialization.object({
+ manifest: ScheduleManifest,
+ name: ResourceName,
+});
+
+export declare namespace UpdateScheduleRequest {
+ export interface Raw {
+ manifest: ScheduleManifest.Raw;
+ name: ResourceName.Raw;
+ }
+}
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.ts
new file mode 100644
index 000000000..da06a3f81
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/client/requests/index.ts
@@ -0,0 +1,2 @@
+export { CreateScheduleRequest } from "./CreateScheduleRequest.js";
+export { UpdateScheduleRequest } from "./UpdateScheduleRequest.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/schedules/index.ts b/packages/trueforge-sdk/src/serialization/resources/schedules/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/schedules/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/types/CronExpression.ts b/packages/trueforge-sdk/src/serialization/types/CronExpression.ts
new file mode 100644
index 000000000..97c8748eb
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/CronExpression.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const CronExpression: core.serialization.Schema<serializers.CronExpression.Raw, TrueForge.CronExpression> =
+ core.serialization.string();
+
+export declare namespace CronExpression {
+ export type Raw = string;
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/DeleteScheduleResponse.ts b/packages/trueforge-sdk/src/serialization/types/DeleteScheduleResponse.ts
new file mode 100644
index 000000000..7370a33e7
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/DeleteScheduleResponse.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const DeleteScheduleResponse: core.serialization.ObjectSchema<
+ serializers.DeleteScheduleResponse.Raw,
+ TrueForge.DeleteScheduleResponse
+> = core.serialization.object({});
+
+export declare namespace DeleteScheduleResponse {
+ export type Raw = {};
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/GetScheduleResponse.ts b/packages/trueforge-sdk/src/serialization/types/GetScheduleResponse.ts
new file mode 100644
index 000000000..8ad072ec4
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/GetScheduleResponse.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 { Schedule } from "./Schedule.js";
+
+export const GetScheduleResponse: core.serialization.ObjectSchema<
+ serializers.GetScheduleResponse.Raw,
+ TrueForge.GetScheduleResponse
+> = core.serialization.object({
+ data: Schedule,
+});
+
+export declare namespace GetScheduleResponse {
+ export interface Raw {
+ data: Schedule.Raw;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.ts
new file mode 100644
index 000000000..f911bbefa
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/ListSchedulesResponse.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 { Schedule } from "./Schedule.js";
+
+export const ListSchedulesResponse: core.serialization.ObjectSchema<
+ serializers.ListSchedulesResponse.Raw,
+ TrueForge.ListSchedulesResponse
+> = core.serialization.object({
+ data: core.serialization.list(Schedule),
+});
+
+export declare namespace ListSchedulesResponse {
+ export interface Raw {
+ data: Schedule.Raw[];
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/Schedule.ts b/packages/trueforge-sdk/src/serialization/types/Schedule.ts
new file mode 100644
index 000000000..ad0f46e3d
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/Schedule.ts
@@ -0,0 +1,30 @@
+// 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 { ResourceName } from "./ResourceName.js";
+import { ScheduleManifest } from "./ScheduleManifest.js";
+
+export const Schedule: core.serialization.ObjectSchema<serializers.Schedule.Raw, TrueForge.Schedule> =
+ core.serialization.object({
+ agentName: core.serialization.property("agent_name", ResourceName),
+ createdAt: core.serialization.property("created_at", core.serialization.date()),
+ createdBy: core.serialization.property("created_by", core.serialization.string()),
+ id: core.serialization.string(),
+ manifest: ScheduleManifest,
+ name: ResourceName,
+ updatedAt: core.serialization.property("updated_at", core.serialization.date()),
+ });
+
+export declare namespace Schedule {
+ export interface Raw {
+ agent_name: ResourceName.Raw;
+ created_at: string;
+ created_by: string;
+ id: string;
+ manifest: ScheduleManifest.Raw;
+ name: ResourceName.Raw;
+ updated_at: string;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/ScheduleManifest.ts b/packages/trueforge-sdk/src/serialization/types/ScheduleManifest.ts
new file mode 100644
index 000000000..63e017799
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/ScheduleManifest.ts
@@ -0,0 +1,27 @@
+// 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 { CronExpression } from "./CronExpression.js";
+import { ScheduleStatus } from "./ScheduleStatus.js";
+import { Timezone } from "./Timezone.js";
+
+export const ScheduleManifest: core.serialization.ObjectSchema<
+ serializers.ScheduleManifest.Raw,
+ TrueForge.ScheduleManifest
+> = core.serialization.object({
+ cron: CronExpression,
+ status: ScheduleStatus.optional(),
+ task: core.serialization.string(),
+ timezone: Timezone.optional(),
+});
+
+export declare namespace ScheduleManifest {
+ export interface Raw {
+ cron: CronExpression.Raw;
+ status?: ScheduleStatus.Raw | null;
+ task: string;
+ timezone?: Timezone.Raw | null;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/ScheduleStatus.ts b/packages/trueforge-sdk/src/serialization/types/ScheduleStatus.ts
new file mode 100644
index 000000000..d03db3143
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/ScheduleStatus.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ScheduleStatus: core.serialization.Schema<serializers.ScheduleStatus.Raw, TrueForge.ScheduleStatus> =
+ core.serialization.enum_(["active", "paused"]);
+
+export declare namespace ScheduleStatus {
+ export type Raw = "active" | "paused";
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/Timezone.ts b/packages/trueforge-sdk/src/serialization/types/Timezone.ts
new file mode 100644
index 000000000..e83baab39
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/Timezone.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const Timezone: core.serialization.Schema<serializers.Timezone.Raw, TrueForge.Timezone> =
+ core.serialization.string();
+
+export declare namespace Timezone {
+ export type Raw = string;
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index 6b493fd5a..0405043db 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -39,9 +39,11 @@ export * from "./ConfiguredSandboxProvider.js";
export * from "./ConfiguredSkill.js";
export * from "./ContextManagementConfig.js";
export * from "./CreateSessionAgent.js";
+export * from "./CronExpression.js";
export * from "./CustomModelProvider.js";
export * from "./DaytonaSandboxProviderAuth.js";
export * from "./DeleteAgentResponse.js";
+export * from "./DeleteScheduleResponse.js";
export * from "./DynamicSubAgentsConfig.js";
export * from "./ExtendedChunkDeltaToolCall.js";
export * from "./FileContent.js";
@@ -58,6 +60,7 @@ export * from "./GetModelProviderCatalogResponse.js";
export * from "./GetModelProviderResponse.js";
export * from "./GetSandboxProviderCatalogResponse.js";
export * from "./GetSandboxProviderResponse.js";
+export * from "./GetScheduleResponse.js";
export * from "./GetSessionResponse.js";
export * from "./GetSkillCatalogResponse.js";
export * from "./GetSkillResponse.js";
@@ -73,6 +76,7 @@ export * from "./ListAvailableSkillsResponse.js";
export * from "./ListMcpServersResponse.js";
export * from "./ListMcpServerToolsResponse.js";
export * from "./ListModelProvidersResponse.js";
+export * from "./ListSchedulesResponse.js";
export * from "./ListSessionEventsResponse.js";
export * from "./ListSessionsOrder.js";
export * from "./ListSessionsResponse.js";
@@ -129,6 +133,9 @@ export * from "./SandboxCapability.js";
export * from "./SandboxConfig.js";
export * from "./SandboxCreatedEvent.js";
export * from "./SandboxProviderManifest.js";
+export * from "./Schedule.js";
+export * from "./ScheduleManifest.js";
+export * from "./ScheduleStatus.js";
export * from "./Session.js";
export * from "./SessionAgent.js";
export * from "./SessionAgentInline.js";
@@ -148,6 +155,7 @@ export * from "./ThreadDoneEvent.js";
export * from "./ThreadState.js";
export * from "./ThreadStateDone.js";
export * from "./ThreadStateError.js";
+export * from "./Timezone.js";
export * from "./TogetherAiModelProvider.js";
export * from "./TokenPagination.js";
export * from "./ToolApprovalRequiredEvent.js";
diff --git a/packages/trueforge-sdk/tests/wire/schedules.test.ts b/packages/trueforge-sdk/tests/wire/schedules.test.ts
new file mode 100644
index 000000000..63eb1a553
--- /dev/null
+++ b/packages/trueforge-sdk/tests/wire/schedules.test.ts
@@ -0,0 +1,391 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import * as TrueForgeTypes from "../../src/api/index";
+import { TrueForge } from "../../src/Client";
+import { mockServerPool } from "../mock-server/MockServerPool";
+
+describe("SchedulesClient", () => {
+ test("list (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = {
+ data: [
+ {
+ agent_name: "agent_name",
+ created_at: "2024-01-15T09:30:00Z",
+ created_by: "created_by",
+ id: "id",
+ manifest: { cron: "cron", task: "task" },
+ name: "name",
+ updated_at: "2024-01-15T09:30:00Z",
+ },
+ ],
+ };
+
+ server.mockEndpoint().get("/api/v1/schedules").respondWith().statusCode(200).jsonBody(rawResponseBody).build();
+
+ const response = await client.schedules.list();
+ expect(response).toEqual({
+ data: [
+ {
+ agentName: "agent_name",
+ createdAt: new Date("2024-01-15T09:30:00.000Z"),
+ createdBy: "created_by",
+ id: "id",
+ manifest: {
+ cron: "cron",
+ task: "task",
+ },
+ name: "name",
+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),
+ },
+ ],
+ });
+ });
+
+ test("list (2)", 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 () => {
+ return await client.schedules.list();
+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
+ });
+
+ test("create (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { agent_name: "agent_name", manifest: { cron: "cron", task: "task" }, name: "name" };
+ const rawResponseBody = {
+ data: {
+ agent_name: "agent_name",
+ created_at: "2024-01-15T09:30:00Z",
+ created_by: "created_by",
+ id: "id",
+ manifest: { cron: "cron", status: "active", task: "task", timezone: "timezone" },
+ name: "name",
+ updated_at: "2024-01-15T09:30:00Z",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .post("/api/v1/schedules")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.schedules.create({
+ agentName: "agent_name",
+ manifest: {
+ cron: "cron",
+ task: "task",
+ },
+ name: "name",
+ });
+ expect(response).toEqual({
+ data: {
+ agentName: "agent_name",
+ createdAt: new Date("2024-01-15T09:30:00.000Z"),
+ createdBy: "created_by",
+ id: "id",
+ manifest: {
+ cron: "cron",
+ status: "active",
+ task: "task",
+ timezone: "timezone",
+ },
+ name: "name",
+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),
+ },
+ });
+ });
+
+ test("create (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { agent_name: "xy", manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/v1/schedules")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.create({
+ agentName: "xy",
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);
+ });
+
+ test("create (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { agent_name: "xy", manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/v1/schedules")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(409)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.create({
+ agentName: "xy",
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.ConflictError);
+ });
+
+ test("get (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = {
+ data: {
+ agent_name: "agent_name",
+ created_at: "2024-01-15T09:30:00Z",
+ created_by: "created_by",
+ id: "id",
+ manifest: { cron: "cron", status: "active", task: "task", timezone: "timezone" },
+ name: "name",
+ updated_at: "2024-01-15T09:30:00Z",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .get("/api/v1/schedules/schedule_id")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.schedules.get("schedule_id");
+ expect(response).toEqual({
+ data: {
+ agentName: "agent_name",
+ createdAt: new Date("2024-01-15T09:30:00.000Z"),
+ createdBy: "created_by",
+ id: "id",
+ manifest: {
+ cron: "cron",
+ status: "active",
+ task: "task",
+ timezone: "timezone",
+ },
+ name: "name",
+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),
+ },
+ });
+ });
+
+ test("get (2)", 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")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.get("schedule_id");
+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);
+ });
+
+ test("update (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { cron: "cron", task: "task" }, name: "name" };
+ const rawResponseBody = {
+ data: {
+ agent_name: "agent_name",
+ created_at: "2024-01-15T09:30:00Z",
+ created_by: "created_by",
+ id: "id",
+ manifest: { cron: "cron", status: "active", task: "task", timezone: "timezone" },
+ name: "name",
+ updated_at: "2024-01-15T09:30:00Z",
+ },
+ };
+
+ server
+ .mockEndpoint()
+ .put("/api/v1/schedules/schedule_id")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.schedules.update("schedule_id", {
+ manifest: {
+ cron: "cron",
+ task: "task",
+ },
+ name: "name",
+ });
+ expect(response).toEqual({
+ data: {
+ agentName: "agent_name",
+ createdAt: new Date("2024-01-15T09:30:00.000Z"),
+ createdBy: "created_by",
+ id: "id",
+ manifest: {
+ cron: "cron",
+ status: "active",
+ task: "task",
+ timezone: "timezone",
+ },
+ name: "name",
+ updatedAt: new Date("2024-01-15T09:30:00.000Z"),
+ },
+ });
+ });
+
+ test("update (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .put("/api/v1/schedules/schedule_id")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.update("schedule_id", {
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);
+ });
+
+ test("update (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .put("/api/v1/schedules/schedule_id")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.update("schedule_id", {
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);
+ });
+
+ test("update (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { cron: "cron", task: "x" }, name: "xy" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .put("/api/v1/schedules/schedule_id")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(409)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.update("schedule_id", {
+ manifest: {
+ cron: "cron",
+ task: "x",
+ },
+ name: "xy",
+ });
+ }).rejects.toThrow(TrueForgeTypes.ConflictError);
+ });
+
+ test("delete (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = {};
+
+ server
+ .mockEndpoint()
+ .delete("/api/v1/schedules/schedule_id")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.schedules.delete("schedule_id");
+ expect(response).toEqual({});
+ });
+
+ test("delete (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .delete("/api/v1/schedules/schedule_id")
+ .respondWith()
+ .statusCode(401)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.schedules.delete("schedule_id");
+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
+ });
+});
diff --git a/packages/trueforge/package.json b/packages/trueforge/package.json
index 3e4357057..78f0635b7 100644
--- a/packages/trueforge/package.json
+++ b/packages/trueforge/package.json
@@ -63,6 +63,7 @@
"@modelcontextprotocol/sdk": "^1.30.0",
"@truefoundry/trueforge-core": "workspace:*",
"better-sqlite3": "^13.0.3",
+ "cron-parser": "^5.4.0",
"env-paths": "^4.0.0",
"hono": "^4.13.5",
"jose": "^6.2.10",
diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts
index 8f340d2f5..afb058658 100644
--- a/packages/trueforge/scripts/write-openapi.ts
+++ b/packages/trueforge/scripts/write-openapi.ts
@@ -23,6 +23,7 @@ import { createSqliteDb } from '../src/db/sqlite/client';
import { SqliteMcpServerStore } from '../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
import { SqliteModelProviderStore } from '../src/db/sqlite/model-provider-store/SqliteModelProviderStore';
import { SqliteSandboxProviderStore } from '../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';
+import { SqliteScheduleStore } from '../src/db/sqlite/schedule-store/SqliteScheduleStore';
import { SqliteSkillStore } from '../src/db/sqlite/skill-store/SqliteSkillStore';
import { SqliteOAuthTokenStore } from '../src/db/sqlite/token-store/SqliteOAuthTokenStore';
import { ActiveTurnRegistry } from '../src/runtime/activeTurns';
@@ -66,6 +67,7 @@ const app = createServerApp({
sandboxCatalog: SandboxCatalog.load(),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
agentStore: new SqliteAgentStore(db),
+ scheduleStore: new SqliteScheduleStore(db),
sessionStore,
sessions: new Sessions({ sessionStore }),
activeTurns: new ActiveTurnRegistry(),
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
new file mode 100644
index 000000000..6b3078f2f
--- /dev/null
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -0,0 +1,187 @@
+/**
+ * Schedules API (mounted at /api/v1/schedules).
+ */
+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
+import type { Context } from 'hono';
+import type { UserContext } from '../auth/identity';
+import type { IAgentStore } from '../db/agentStore';
+import { ScheduleRunConflictError, type IScheduleStore, type ScheduleRecord } from '../db/scheduleStore';
+import type { WithTransaction } from '../db/transaction';
+import {
+ createScheduleRoute,
+ deleteScheduleRoute,
+ getScheduleRoute,
+ listSchedulesRoute,
+ putScheduleRoute,
+} from '../routes/scheduleRoutes';
+import { minIntervalSeconds, nextTriggerAfter } from '../runtime/cron';
+import {
+ InvalidCronError,
+ SCHEDULE_MIN_INTERVAL_SECONDS,
+ type Schedule,
+ type ScheduleManifest,
+} from '../schemas/schedule';
+import { TENANT_ID } from './sessions';
+
+export interface SchedulesRouterDeps<TTransaction> {
+ scheduleStore: IScheduleStore<TTransaction>;
+ agentStore: IAgentStore<TTransaction>;
+ withTransaction: WithTransaction<TTransaction>;
+ resolveUserContext: (c: Context) => UserContext;
+}
+
+function toWireSchedule(record: ScheduleRecord): Schedule {
+ return {
+ id: record.id,
+ agent_name: record.agent_name,
+ name: record.name,
+ manifest: record.manifest,
+ created_by: record.created_by,
+ created_at: record.created_at,
+ updated_at: record.updated_at,
+ };
+}
+
+export function validateManifest(manifest: Pick<ScheduleManifest, 'cron' | 'timezone'>, from: Date = new Date()): void {
+ // Reject if the cron has no upcoming trigger time (impossible / exhausted calendar).
+ // 5-field cron has no year, so a valid expression always recurs — no one-shot check.
+ try {
+ nextTriggerAfter({ cron: manifest.cron, timezone: manifest.timezone, from });
+ } catch (error) {
+ throw new InvalidCronError(`Cron expression "${manifest.cron}" has no next trigger time in ${manifest.timezone}`, {
+ cause: error,
+ });
+ }
+
+ // Reject expressions that trigger < SCHEDULE_MIN_INTERVAL_SECONDS seconds apart.
+ let tightest: number;
+ try {
+ tightest = minIntervalSeconds(manifest, from);
+ } catch (error) {
+ throw new InvalidCronError(`Cron expression "${manifest.cron}" has no next trigger time in ${manifest.timezone}`, {
+ cause: error,
+ });
+ }
+
+ if (tightest < SCHEDULE_MIN_INTERVAL_SECONDS) {
+ throw new InvalidCronError(
+ `Cron expression "${manifest.cron}" triggers every ${String(tightest)}s; the minimum interval is ${String(
+ SCHEDULE_MIN_INTERVAL_SECONDS,
+ )}s`,
+ );
+ }
+}
+
+export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTransaction>) {
+ const listHandler: RouteHandler<typeof listSchedulesRoute> = async c => {
+ const { agent_name: agentName } = c.req.valid('query');
+ const records = await deps.scheduleStore.listSchedules({
+ tenant_id: TENANT_ID,
+ agent_name: agentName,
+ });
+ return c.json({ data: records.map(toWireSchedule) }, 200);
+ };
+
+ const createHandler: RouteHandler<typeof createScheduleRoute> = async c => {
+ const body = c.req.valid('json');
+ const user = deps.resolveUserContext(c);
+
+ validateManifest(body.manifest);
+
+ const agent = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, name: body.agent_name });
+ if (agent === undefined) {
+ return c.json({ error: { message: `Agent not found: ${body.agent_name}` } }, 400);
+ }
+
+ let record: ScheduleRecord;
+ try {
+ record = await deps.withTransaction(async transaction => {
+ const { schedule } = await deps.scheduleStore.createScheduleAndRun(
+ {
+ tenant_id: TENANT_ID,
+ agent_name: agent.name,
+ name: body.name,
+ manifest: body.manifest,
+ created_by: user.userRef,
+ runFrom: new Date(),
+ },
+ transaction,
+ );
+ return schedule;
+ });
+ } catch (error) {
+ if (error instanceof ScheduleRunConflictError) {
+ return c.json({ error: { message: `${error.message}. Retry the request.` } }, 409);
+ }
+ throw error;
+ }
+
+ return c.json({ data: toWireSchedule(record) }, 201);
+ };
+
+ const getHandler: RouteHandler<typeof getScheduleRoute> = async c => {
+ const { schedule_id: scheduleId } = c.req.valid('param');
+ const record = await deps.scheduleStore.getSchedule({ tenant_id: TENANT_ID, id: scheduleId, forUpdate: false });
+ if (record === undefined) {
+ return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
+ }
+ return c.json({ data: toWireSchedule(record) }, 200);
+ };
+
+ /**
+ * Replaces the whole document, like every other manifest PUT in this server: an
+ * omitted optional field is not "left alone", it returns to its default — omitting
+ * `status` re-activates a paused schedule, omitting `timezone` moves it to UTC.
+ * Read-modify-write if that is not what you want.
+ *
+ * Agent binding is immutable — a schedule that should point at a different agent is
+ * a different schedule. `name` is editable (display only; not unique).
+ */
+ const putHandler: RouteHandler<typeof putScheduleRoute> = async c => {
+ const { schedule_id: scheduleId } = c.req.valid('param');
+ const body = c.req.valid('json');
+
+ validateManifest(body.manifest);
+
+ let record: ScheduleRecord | undefined;
+ try {
+ record = await deps.withTransaction(async transaction => {
+ const result = await deps.scheduleStore.updateScheduleAndRun(
+ {
+ tenant_id: TENANT_ID,
+ id: scheduleId,
+ name: body.name,
+ manifest: body.manifest,
+ runFrom: new Date(),
+ },
+ transaction,
+ );
+ return result?.schedule;
+ });
+ } catch (error) {
+ if (error instanceof ScheduleRunConflictError) {
+ return c.json({ error: { message: `${error.message}. Retry the request.` } }, 409);
+ }
+ throw error;
+ }
+
+ if (record === undefined) {
+ return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
+ }
+ return c.json({ data: toWireSchedule(record) }, 200);
+ };
+
+ const deleteHandler: RouteHandler<typeof deleteScheduleRoute> = async c => {
+ const { schedule_id: scheduleId } = c.req.valid('param');
+ await deps.scheduleStore.deleteSchedule({ tenant_id: TENANT_ID, id: scheduleId });
+ return c.json({}, 200);
+ };
+
+ const router = new OpenAPIHono();
+ router.openapi(listSchedulesRoute, listHandler);
+ router.openapi(createScheduleRoute, createHandler);
+ router.openapi(getScheduleRoute, getHandler);
+ router.openapi(putScheduleRoute, putHandler);
+ router.openapi(deleteScheduleRoute, deleteHandler);
+ return router;
+}
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index 59229ba10..bb71b9779 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -17,6 +17,7 @@ import { createCatalogRouter } from './apis/catalog';
import { createMcpOAuthRouter } from './apis/mcpOAuth';
import { createMcpServersRouter } from './apis/mcpServers';
import { createModelsRouter } from './apis/models';
+import { createSchedulesRouter } from './apis/schedules';
import { createSessionsRouter } from './apis/sessions';
import { createSettingsRouter } from './apis/settings';
import { createAvailableSkillsRouter } from './apis/skills';
@@ -32,6 +33,7 @@ import type { IAgentStore } from './db/agentStore';
import type { IMcpServerStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
+import type { IScheduleStore } from './db/scheduleStore';
import type { ISkillStore } from './db/skillStore';
import type { WithTransaction } from './db/transaction';
import type { IOAuthTokenStore } from './mcp/auth/types';
@@ -39,6 +41,7 @@ import { PACKAGE_VERSION } from './packageVersion';
import { OPENAPI_DOCUMENT_TAGS } from './routes/openapiTags';
import type { ActiveTurnRegistry } from './runtime/activeTurns';
import type { EventSubscriptionRegistry } from './runtime/event-subscription';
+import { InvalidCronError } from './schemas/schedule';
import { zodErrorResponse, zodValidationHook } from './zodErrorResponse';
const BEARER_AUTH_SCHEME = 'BearerAuth';
@@ -57,6 +60,9 @@ export function createAppErrorHandler(params: { logger: Logger }): ErrorHandler
if (error instanceof z.ZodError) {
return zodErrorResponse(c, error);
}
+ if (error instanceof InvalidCronError) {
+ return c.json({ error: { message: error.message } }, 400);
+ }
if (error instanceof HTTPException) {
if (error.status >= 500) {
params.logger.error('Server API error', {
@@ -147,6 +153,7 @@ export interface ServerDeps<TTransaction> {
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
agentStore: IAgentStore<TTransaction>;
+ scheduleStore: IScheduleStore<TTransaction>;
sessionStore: ISessionStore;
sessions: Sessions;
activeTurns: ActiveTurnRegistry;
@@ -244,6 +251,17 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
}),
),
);
+ app.route(
+ '/api/v1/schedules',
+ withAuth(
+ createSchedulesRouter({
+ scheduleStore: deps.scheduleStore,
+ agentStore: deps.agentStore,
+ withTransaction: deps.withTransaction,
+ resolveUserContext,
+ }),
+ ),
+ );
app.route(
'/api/v1/settings',
withAdminAuth(
diff --git a/packages/trueforge/src/controller.ts b/packages/trueforge/src/controller.ts
new file mode 100644
index 000000000..443a4f2d7
--- /dev/null
+++ b/packages/trueforge/src/controller.ts
@@ -0,0 +1,100 @@
+/**
+ * Controller entry point — the control loops as their own process.
+ *
+ * Distributed mode only. Server replicas run no loops, so this deployment is the sole
+ * controller for the database. Loops assume no peer runs alongside them,
+ * so it MUST have exactly one replica.
+ *
+ * In standalone mode the controller runs inside the server instead — one process owns
+ * everything, and this entry point refuses to start.
+ */
+import { extractErrorLogFields } from '@truefoundry/trueforge-core/core';
+
+let configuration: typeof import('./config').default;
+
+try {
+ ({ default: configuration } = await import('./config'));
+} catch (error) {
+ console.error(
+ 'Failed to start controller: Failed to load configuration:',
+ error instanceof Error ? error.message : error,
+ );
+ process.exit(1);
+}
+
+import { Controller } from './controller/Controller';
+import { createScheduleDispatchLoop, logTriggeredRun } from './controller/scheduleDispatch';
+import { createDb } from './db/postgres/client';
+import { PostgresScheduleStore } from './db/postgres/schedule-store/PostgresScheduleStore';
+import { createServerLogger } from './logger';
+import { PACKAGE_VERSION } from './packageVersion';
+
+try {
+ const logger = createServerLogger({
+ level: configuration.LOG_LEVEL,
+ standalone: configuration.STANDALONE,
+ version: PACKAGE_VERSION,
+ });
+
+ // Narrow through a const: the config union is keyed on STANDALONE, and only the
+ // distributed variant carries the Postgres connection settings.
+ const config = configuration;
+ if (config.STANDALONE) {
+ throw new Error(
+ 'The controller process is for distributed mode only. ' +
+ 'In standalone mode the server runs the control loops in-process.',
+ );
+ }
+
+ const db = createDb({
+ connectionString: config.DATABASE_URL,
+ poolMax: config.DATABASE_POOL_MAX,
+ statementTimeoutMs: config.POSTGRES_STATEMENT_TIMEOUT_MS,
+ idleInTransactionSessionTimeoutMs: config.POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS,
+ });
+ const controller = new Controller({
+ loops: [
+ createScheduleDispatchLoop({
+ scheduleStore: new PostgresScheduleStore(db),
+ withTransaction: callback => db.transaction().execute(callback),
+ onTriggered: logTriggeredRun(logger),
+ logger,
+ }),
+ ],
+ logger,
+ });
+
+ logger.info('TrueForge controller starting', { mode: 'distributed' });
+ controller.start();
+
+ let shuttingDown = false;
+ const shutdown = async (signal: NodeJS.Signals) => {
+ if (shuttingDown) {
+ return;
+ }
+ shuttingDown = true;
+ logger.info(`Received ${signal}, stopping control loops`);
+
+ // Start the deadline at the top of shutdown; unref so this timer alone cannot keep the process
+ // alive. Passes only hold short transactions, so this should never elapse.
+ setTimeout(() => {
+ logger.warn(`Controller drain timed out after ${String(configuration.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`);
+ process.exit(1);
+ }, configuration.GRACEFUL_TIMEOUT_SECONDS * 1000).unref();
+
+ await controller.stop();
+ await db.destroy().catch((error: unknown) => {
+ logger.warn('Error closing the database pool during shutdown', extractErrorLogFields(error));
+ });
+ process.exit(0);
+ };
+ process.on('SIGTERM', signal => {
+ void shutdown(signal);
+ });
+ process.on('SIGINT', signal => {
+ void shutdown(signal);
+ });
+} catch (error) {
+ console.error('Failed to start controller:', error instanceof Error ? error.message : error);
+ process.exit(1);
+}
diff --git a/packages/trueforge/src/controller/Controller.ts b/packages/trueforge/src/controller/Controller.ts
new file mode 100644
index 000000000..ec89c7cc8
--- /dev/null
+++ b/packages/trueforge/src/controller/Controller.ts
@@ -0,0 +1,133 @@
+/**
+ * The controller: a set of periodic control loops and the timers that drive them.
+ *
+ * Loops are independent — each has its own interval, its own re-entrancy guard, and
+ * its own error boundary, so a slow or failing loop cannot stall another.
+ *
+ * The controller runs in exactly ONE process per database. In standalone mode that is
+ * the server itself; when `STANDALONE=false` it is the dedicated single-replica
+ * process in `src/controller.ts`. Loops are written assuming this.
+ */
+import type { Logger } from 'winston';
+
+/** Reason passed to {@link AbortController.abort} when {@link Controller.stop} runs. */
+export const CONTROLLER_STOPPED = 'controller-stopped';
+
+/** One periodic unit of work. */
+export interface ControlLoop {
+ /** Stable identifier; appears in logs and keys the controller's per-loop state. */
+ readonly name: string;
+ /** Gap between passes. Each loop chooses its own. */
+ readonly intervalMs: number;
+ /**
+ * One pass. May throw — the controller logs it and keeps ticking, so a pass must
+ * leave nothing half-applied that a later pass cannot recover from.
+ */
+ tick(signal: AbortSignal): Promise<void>;
+}
+
+interface LoopState {
+ timer: NodeJS.Timeout | undefined;
+ /** In-flight pass, if any. Also the re-entrancy guard. */
+ pass: Promise<void> | undefined;
+}
+
+export class Controller {
+ readonly #loops: readonly ControlLoop[];
+ readonly #logger: Logger;
+ readonly #state = new Map<string, LoopState>();
+ readonly #abortController = new AbortController();
+
+ constructor(params: { loops: readonly ControlLoop[]; logger: Logger }) {
+ const names = new Set<string>();
+ for (const loop of params.loops) {
+ if (names.has(loop.name)) {
+ throw new Error(`Duplicate control loop name: ${loop.name}`);
+ }
+ names.add(loop.name);
+ }
+ this.#loops = params.loops;
+ this.#logger = params.logger;
+ }
+
+ /** Shared abort signal; aborted by {@link stop}. */
+ get signal(): AbortSignal {
+ return this.#abortController.signal;
+ }
+
+ /**
+ * Starts every loop, each with an immediate first pass so a restart does not leave
+ * work waiting a full interval.
+ */
+ start(): void {
+ if (this.#abortController.signal.aborted || this.#state.size > 0) {
+ return;
+ }
+ for (const loop of this.#loops) {
+ const state: LoopState = { timer: undefined, pass: undefined };
+ this.#state.set(loop.name, state);
+ state.timer = setInterval(() => {
+ void this.#tick(loop);
+ }, loop.intervalMs);
+ void this.#tick(loop);
+ }
+ this.#logger.info('Controller started', { loops: this.#loops.map(loop => loop.name) });
+ }
+
+ /**
+ * Stops every loop: clears timers, aborts the shared signal, then waits for
+ * in-flight passes to finish. Idempotent.
+ */
+ async stop(): Promise<void> {
+ if (this.#abortController.signal.aborted) {
+ return;
+ }
+ this.#abortController.abort(CONTROLLER_STOPPED);
+ const passes: Promise<void>[] = [];
+ for (const state of this.#state.values()) {
+ if (state.timer) {
+ clearInterval(state.timer);
+ state.timer = undefined;
+ }
+ if (state.pass) {
+ passes.push(state.pass);
+ }
+ }
+ await Promise.all(passes);
+ this.#logger.info('Controller stopped');
+ }
+
+ /**
+ * One pass of one loop: never throws, never overlaps itself.
+ *
+ * A pass that outlives its interval skips the next tick rather than running twice.
+ * Whatever it did not finish is picked up by the following pass — the same path a
+ * restart takes.
+ */
+ async #tick(loop: ControlLoop): Promise<void> {
+ const state = this.#state.get(loop.name);
+ const { signal } = this.#abortController;
+ // `state` is always set before the first #tick for that loop; guard is for types.
+ if (!state || signal.aborted || state.pass) {
+ return;
+ }
+
+ const pass = (async () => {
+ try {
+ await loop.tick(signal);
+ } catch (error) {
+ if (signal.aborted) {
+ return;
+ }
+ this.#logger.error('Control loop pass failed', { loop: loop.name, error });
+ }
+ })();
+
+ state.pass = pass;
+ try {
+ await pass;
+ } finally {
+ state.pass = undefined;
+ }
+ }
+}
diff --git a/packages/trueforge/src/controller/scheduleDispatch.ts b/packages/trueforge/src/controller/scheduleDispatch.ts
new file mode 100644
index 000000000..b86afd7e1
--- /dev/null
+++ b/packages/trueforge/src/controller/scheduleDispatch.ts
@@ -0,0 +1,251 @@
+import type { Logger } from 'winston';
+import {
+ cronRunName,
+ type IScheduleStore,
+ type ScheduleDispatchItem,
+ type ScheduleRunRecord,
+ type ScheduleRunStatus,
+} from '../db/scheduleStore';
+import type { WithTransaction } from '../db/transaction';
+import { nextTriggerAfter } from '../runtime/cron';
+import { InvalidCronError } from '../schemas/schedule';
+import type { ControlLoop } from './Controller';
+
+/**
+ * Rows examined per pass.
+ *
+ * TODO(controller): a backlog larger than this is left for the next tick rather
+ * than drained in a loop. Fine while the tick is short relative to the minimum
+ * interval; revisit if either changes.
+ */
+export const DISPATCH_BATCH_LIMIT = 20;
+
+/**
+ * Gap between loop passes.
+ *
+ * Well below the minimum schedule interval, so a run is picked up within a tick of
+ * `scheduled_for` passing, and cheap: an idle pass is one indexed query against
+ * `schedule_run_scheduled_for_idx`.
+ */
+const SCHEDULE_DISPATCH_INTERVAL_MS = 60_000;
+
+/** The loop's name. */
+const SCHEDULE_DISPATCH_LOOP_NAME = 'schedule-dispatch';
+
+/**
+ * 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.
+ *
+ * ## LOCK ORDERING
+ * The schedule row is locked FIRST, before the run row is touched. `updateScheduleAndRun`
+ * (the PUT path) does the same: it locks the schedule, then deletes and inserts runs.
+ * Both transactions therefore take schedule-then-run, and serialize cleanly.
+ *
+ */
+async function finishScheduledRun<TTransaction>(params: {
+ store: IScheduleStore<TTransaction>;
+ run: ScheduleRunRecord;
+ now: Date;
+ status: ScheduleRunStatus;
+ withTransaction: WithTransaction<TTransaction>;
+}): Promise<void> {
+ const { store, withTransaction, run, status, now } = params;
+ await withTransaction(async txn => {
+ const latest = await store.getSchedule({ tenant_id: run.tenant_id, id: run.schedule_id, forUpdate: true }, txn);
+
+ const updated = await store.updateRunStatus({ tenant_id: run.tenant_id, id: run.id, status }, txn);
+ if (updated === undefined) {
+ return;
+ }
+
+ if (latest?.status !== 'active') {
+ return;
+ }
+
+ // `now` selected this run (`scheduled_for <= now`), so anchoring here gives a
+ // trigger time strictly later than the run being finished.
+ const advanceFrom = new Date(Math.max(Date.parse(run.scheduled_for), now.getTime()));
+
+ let nextTrigger: Date;
+ try {
+ nextTrigger = nextTriggerAfter({
+ cron: latest.manifest.cron,
+ timezone: latest.manifest.timezone,
+ from: advanceFrom,
+ });
+ } catch (error) {
+ if (!(error instanceof InvalidCronError)) {
+ throw error;
+ }
+ // No later trigger time (calendar dead end). Ideally should not happen.
+ // Still finish the current row; just do not add another.
+ return;
+ }
+
+ await store.createRun(
+ {
+ tenant_id: latest.tenant_id,
+ schedule_id: latest.id,
+ name: cronRunName(nextTrigger),
+ scheduled_for: nextTrigger,
+ status: 'scheduled',
+ triggered_by: latest.created_by,
+ },
+ txn,
+ );
+ });
+}
+
+/**
+ * Schedule dispatch: turn `scheduled` runs with `scheduled_for <= now` into
+ * triggered runs and add each schedule's next scheduled run.
+ *
+ * ## IDEMPOTENCY
+ * If the process dies between steps, the same scheduled run is seen again on
+ * the next tick — so `onTriggered` should ideally be idempotent (or otherwise safe to
+ * call more than once).
+ *
+ * ## RACE conditions with the schedule API
+ *
+ * Dispatch and the API both write `schedule_run`. Cases below can drop a pending
+ * run or leave an orphan session; that is accepted where noted. Two rules keep
+ * pending rows from doubling: the schedule is re-read INSIDE the finish
+ * transaction, and `schedule_run_pending_uq` index rejects a second `scheduled` row.
+ *
+ * - **pause**: drops the pending run in its own transaction, and stops the advance.
+ * It never cancels a row that still exists: whatever pause did not delete is
+ * executed (or recorded `missed`) so history has no unexplained gap.
+ * If pause commits first, the row is gone and there is nothing to run.
+ * If dispatch commits first, the run triggers and pause deletes the pending row
+ * dispatch just added, so triggering stops from the next tick — at most one extra run.
+ * - **resume **: no race condition; resume just adds a run.
+ * - **cron expression change**: deletes the pending run and inserts a fresh one from the new cron.
+ * If put commits first, the pending run is replaced; finish does not insert again.
+ * Missing triggered history for that run is accepted.
+ * If dispatch commits first, the run triggers and put deletes the pending row dispatch just added,
+ * then inserts a fresh one. So the run that already handed off is kept; the next pending is put's.
+ * - **delete**: cascades the runs away. Dispatch either sees the schedule gone
+ * or holds the row and delete waits. A run already handed to the executor keeps going
+ * and leaves an orphan session; the run row is gone, which is accepted.
+ *
+ * ## CONCURRENCY
+ * NOT concurrency safe by design: call this from exactly ONE process.
+ */
+export async function dispatchScheduledRuns<TTransaction>(params: {
+ store: IScheduleStore<TTransaction>;
+ onTriggered: (item: ScheduleDispatchItem) => void | Promise<void>;
+ logger: Logger;
+ withTransaction: WithTransaction<TTransaction>;
+ /** When aborted, stop before the next run; the current run still finishes. */
+ signal?: AbortSignal;
+}): Promise<{ dispatched: number; failed: number }> {
+ const { store, withTransaction, onTriggered, logger, signal } = params;
+ // ONE clock for the whole pass: it selects the runs, judges lateness, and anchors
+ // the next trigger time.
+ const now = new Date();
+ const scheduled = await store.listScheduledRuns({ limit: DISPATCH_BATCH_LIMIT, until: now });
+
+ let dispatched = 0;
+ let failed = 0;
+ for (const run of scheduled) {
+ if (signal?.aborted) {
+ break;
+ }
+ try {
+ const schedule = await store.getSchedule({
+ tenant_id: run.tenant_id,
+ id: run.schedule_id,
+ forUpdate: false,
+ });
+ // Only a deleted schedule stops a row here. `paused` deliberately does NOT:
+ // status decides whether the schedule gains a NEW row, never whether an
+ // existing one runs. A row that exists was added while the schedule was
+ // active, so it is honoured.
+ if (schedule === undefined) {
+ continue;
+ }
+
+ try {
+ await onTriggered({ run, schedule });
+ } catch (error) {
+ logger.error('Failed to hand off triggered run', {
+ schedule_id: schedule.id,
+ run_id: run.id,
+ error,
+ });
+ await finishScheduledRun({
+ store,
+ run,
+ now,
+ status: 'failed',
+ withTransaction,
+ });
+ failed += 1;
+ continue;
+ }
+
+ await finishScheduledRun({
+ store,
+ run,
+ now,
+ status: 'triggered',
+ withTransaction,
+ });
+ dispatched += 1;
+ } catch (error) {
+ logger.error('Failed to process scheduled run', {
+ schedule_id: run.schedule_id,
+ run_id: run.id,
+ error,
+ });
+ }
+ }
+
+ return { dispatched, failed };
+}
+
+/**
+ * Stand-in until the run executor lands: records the hand-off and drops it.
+ *
+ * Called before the row is marked `triggered`; if nothing commits afterward the
+ * same scheduled row will be offered again on the next pass.
+ *
+ * TODO(executor): replace with the real executor. Note it runs in the controller's
+ * process, so the dedicated deployment will need everything a turn needs — model
+ * provider credentials, MCP egress, sandbox access — not just database reach.
+ */
+export function logTriggeredRun(logger: Logger): (item: ScheduleDispatchItem) => void | Promise<void> {
+ return item => {
+ logger.warn('Schedule run triggered but no executor is configured; run will not execute', {
+ schedule_id: item.schedule.id,
+ run_id: item.run.id,
+ agent_name: item.schedule.agent_name,
+ scheduled_for: item.run.scheduled_for,
+ });
+ };
+}
+
+export function createScheduleDispatchLoop<TTransaction>(params: {
+ scheduleStore: IScheduleStore<TTransaction>;
+ onTriggered: (item: ScheduleDispatchItem) => void | Promise<void>;
+ logger: Logger;
+ withTransaction: WithTransaction<TTransaction>;
+}): ControlLoop {
+ const { scheduleStore, withTransaction, onTriggered, logger } = params;
+ return {
+ name: SCHEDULE_DISPATCH_LOOP_NAME,
+ intervalMs: SCHEDULE_DISPATCH_INTERVAL_MS,
+ async tick(signal: AbortSignal): Promise<void> {
+ const result = await dispatchScheduledRuns({
+ store: scheduleStore,
+ onTriggered,
+ logger,
+ withTransaction,
+ signal,
+ });
+ if (result.dispatched > 0 || result.failed > 0) {
+ logger.debug('Scheduled runs dispatched or failed', result);
+ }
+ },
+ };
+}
diff --git a/packages/trueforge/src/db/postgres/migrations/20260827_000001_schedule.ts b/packages/trueforge/src/db/postgres/migrations/20260827_000001_schedule.ts
new file mode 100644
index 000000000..1bd046cdc
--- /dev/null
+++ b/packages/trueforge/src/db/postgres/migrations/20260827_000001_schedule.ts
@@ -0,0 +1,100 @@
+import { sql, type Kysely } from 'kysely';
+
+/**
+ * Scheduled agents: `schedule` + `schedule_run`.
+ *
+ * - `schedule`: immutable application-generated `id` (ULID) as PK. Spec lives in
+ * Zod-validated `manifest` jsonb (same pattern as `agent`). Bound by agent
+ * name: FK `(tenant_id, agent_name)` → `agent(tenant_id, name)` ON DELETE CASCADE
+ * (agent names are unique and immutable within a tenant).
+ * - `schedule_run`: one row per run, past or pending. The single pending run is a
+ * row like any other (`status = 'scheduled'`), which is what makes "next trigger
+ * time" a plain query instead of a computation.
+ *
+ * Three deliberate index choices:
+ * - `schedule_run_scheduled_for_idx` is PARTIAL on `status = 'scheduled'`. The table is
+ * overwhelmingly terminal rows, so an unfiltered scheduled_for index would get steadily
+ * more expensive as history grows, for no benefit.
+ * - `schedule_run_pending_uq` enforces AT MOST ONE pending run per schedule. This
+ * is the resume-vs-trigger race expressed as a constraint instead of code.
+ * - `schedule_run_name_idx` makes a repeated trigger idempotent: one trigger time maps to
+ * exactly one row (`sched-<unixSeconds>`), so a duplicated dispatch cannot
+ * double-insert.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+
+ await db.schema
+ .createTable('schedule')
+ .addColumn('id', 'text', col => col.notNull())
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ .addColumn('agent_name', 'text', col => col.notNull())
+ .addColumn('name', 'text', col => col.notNull())
+ .addColumn('manifest', 'jsonb', col => col.notNull())
+ .addColumn('status', 'text', col => col.notNull())
+ .addColumn('created_by', 'text', col => col.notNull())
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('schedule_pkey', ['id'])
+ .addForeignKeyConstraint(
+ 'schedule_agent_name_fk',
+ ['tenant_id', 'agent_name'],
+ 'agent',
+ ['tenant_id', 'name'],
+ cb => cb.onDelete('cascade'),
+ )
+ .execute();
+
+ // Schedules are listed per agent (the agent detail page) far more than globally.
+ await db.schema.createIndex('schedule_agent_idx').on('schedule').columns(['tenant_id', 'agent_name']).execute();
+
+ await db.schema
+ .createTable('schedule_run')
+ .addColumn('id', 'text', col => col.notNull())
+ .addColumn('tenant_id', 'text', col => col.notNull())
+ .addColumn('schedule_id', 'text', col => col.notNull().references('schedule.id').onDelete('cascade'))
+ .addColumn('name', 'text', col => col.notNull())
+ .addColumn('scheduled_for', 'timestamptz', col => col.notNull())
+ .addColumn('status', sql`varchar(16)`, col => col.notNull())
+ .addColumn('triggered_by', 'text', col => col.notNull())
+ .addColumn('triggered_at', 'timestamptz')
+ .addColumn('created_at', 'timestamptz', col => col.notNull())
+ .addColumn('updated_at', 'timestamptz', col => col.notNull())
+ .addPrimaryKeyConstraint('schedule_run_pkey', ['id'])
+ .execute();
+
+ // A run row takes two or three small bounded updates in its life
+ // (scheduled -> triggered -> terminal); leave HOT headroom for them.
+ await sql`ALTER TABLE schedule_run SET (fillfactor = 85)`.execute(db);
+
+ await db.schema
+ .createIndex('schedule_run_name_idx')
+ .on('schedule_run')
+ .columns(['tenant_id', 'schedule_id', 'name'])
+ .unique()
+ .execute();
+
+ await sql`
+ CREATE INDEX schedule_run_scheduled_for_idx
+ ON schedule_run (scheduled_for)
+ WHERE status = 'scheduled'
+ `.execute(db);
+
+ await sql`
+ CREATE UNIQUE INDEX schedule_run_pending_uq
+ ON schedule_run (schedule_id)
+ WHERE status = 'scheduled'
+ `.execute(db);
+
+ // Run history: newest first within one schedule.
+ await sql`
+ CREATE INDEX schedule_run_list_idx
+ ON schedule_run (schedule_id, scheduled_for DESC)
+ `.execute(db);
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);
+ await db.schema.dropTable('schedule_run').ifExists().cascade().execute();
+ await db.schema.dropTable('schedule').ifExists().cascade().execute();
+}
diff --git a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
new file mode 100644
index 000000000..c28a2aad7
--- /dev/null
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -0,0 +1,275 @@
+import type { Kysely, Selectable, Transaction } from 'kysely';
+import { ulid } from 'ulid';
+import { nextTriggerAfter } from '../../../runtime/cron';
+import {
+ cronRunName,
+ parseStoredScheduleManifest,
+ ScheduleRunConflictError,
+ shouldSyncPendingRun,
+ type CreateScheduleInput,
+ type CreateScheduleRunInput,
+ type DeleteScheduleInput,
+ type GetRunInput,
+ type GetScheduledRunForInput,
+ type GetScheduleInput,
+ type IScheduleStore,
+ type ListScheduledRunsInput,
+ type ListSchedulesInput,
+ type ScheduleRecord,
+ type ScheduleRunRecord,
+ type ScheduleWriteResult,
+ type UpdateScheduleInput,
+ type UpdateScheduleRunStatusInput,
+} from '../../scheduleStore';
+import { isUniqueViolation } from '../client';
+import { json, now } from '../sqlExpressions';
+import type { Database, ScheduleRunTable, ScheduleTable } from '../types';
+
+function toScheduleRecord(row: Selectable<ScheduleTable>): ScheduleRecord {
+ return {
+ id: row.id,
+ tenant_id: row.tenant_id,
+ agent_name: row.agent_name,
+ name: row.name,
+ manifest: parseStoredScheduleManifest(row.manifest),
+ status: row.status,
+ created_by: row.created_by,
+ created_at: row.created_at.toISOString(),
+ updated_at: row.updated_at.toISOString(),
+ };
+}
+
+function toRunRecord(row: Selectable<ScheduleRunTable>): ScheduleRunRecord {
+ return {
+ id: row.id,
+ tenant_id: row.tenant_id,
+ schedule_id: row.schedule_id,
+ name: row.name,
+ scheduled_for: row.scheduled_for.toISOString(),
+ status: row.status,
+ triggered_by: row.triggered_by,
+ triggered_at: row.triggered_at === null ? null : row.triggered_at.toISOString(),
+ created_at: row.created_at.toISOString(),
+ updated_at: row.updated_at.toISOString(),
+ };
+}
+
+export class PostgresScheduleStore implements IScheduleStore<Transaction<Database>> {
+ readonly #db: Kysely<Database>;
+
+ constructor(db: Kysely<Database>) {
+ this.#db = db;
+ }
+
+ async #syncPendingRun(
+ schedule: ScheduleRecord,
+ from: Date,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ // Clear the pending run, if any; whether a replacement follows depends on status.
+ await db
+ .deleteFrom('schedule_run')
+ .where('tenant_id', '=', schedule.tenant_id)
+ .where('schedule_id', '=', schedule.id)
+ .where('status', '=', 'scheduled')
+ .execute();
+ if (schedule.status !== 'active') {
+ return undefined;
+ }
+ const nextTrigger = nextTriggerAfter({
+ cron: schedule.manifest.cron,
+ timezone: schedule.manifest.timezone,
+ from,
+ });
+ return this.createRun(
+ {
+ tenant_id: schedule.tenant_id,
+ schedule_id: schedule.id,
+ name: cronRunName(nextTrigger),
+ scheduled_for: nextTrigger,
+ status: 'scheduled',
+ triggered_by: schedule.created_by,
+ },
+ transaction,
+ );
+ }
+
+ async getSchedule(input: GetScheduleInput, transaction?: Transaction<Database>): Promise<ScheduleRecord | undefined> {
+ const db = transaction ?? this.#db;
+ let query = db
+ .selectFrom('schedule')
+ .selectAll()
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id);
+ if (input.forUpdate === true) {
+ query = query.forUpdate();
+ }
+ const row = await query.executeTakeFirst();
+ return row === undefined ? undefined : toScheduleRecord(row);
+ }
+
+ async createScheduleAndRun(
+ input: CreateScheduleInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleWriteResult> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .insertInto('schedule')
+ .values({
+ id: ulid().toLowerCase(),
+ tenant_id: input.tenant_id,
+ agent_name: input.agent_name,
+ name: input.name,
+ manifest: json(input.manifest),
+ // Column mirrors the manifest so the dispatch scan and API reads share one value.
+ status: input.manifest.status,
+ created_by: input.created_by,
+ created_at: now(),
+ updated_at: now(),
+ })
+ .returningAll()
+ .executeTakeFirstOrThrow();
+ const schedule = toScheduleRecord(row);
+ const pendingRun = await this.#syncPendingRun(schedule, input.runFrom, transaction);
+ return { schedule, pendingRun };
+ }
+
+ async updateScheduleAndRun(
+ input: UpdateScheduleInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleWriteResult | undefined> {
+ // Lock first: this transaction writes the schedule AND its runs, and every such
+ // transaction must take the schedule lock before touching a run row.
+ const previous = await this.getSchedule({ tenant_id: input.tenant_id, id: input.id, forUpdate: true }, transaction);
+ if (previous === undefined) {
+ return undefined;
+ }
+
+ const db = transaction ?? this.#db;
+ const row = await db
+ .updateTable('schedule')
+ .set({ name: input.name, manifest: json(input.manifest), status: input.manifest.status, updated_at: now() })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .returningAll()
+ .executeTakeFirst();
+ if (row === undefined) {
+ return undefined;
+ }
+ const schedule = toScheduleRecord(row);
+ if (!shouldSyncPendingRun(previous, schedule)) {
+ const pendingRun = await this.getScheduledRunFor(
+ { tenant_id: schedule.tenant_id, schedule_id: schedule.id },
+ transaction,
+ );
+ return { schedule, pendingRun };
+ }
+ const pendingRun = await this.#syncPendingRun(schedule, input.runFrom, transaction);
+ return { schedule, pendingRun };
+ }
+
+ async deleteSchedule(input: DeleteScheduleInput, transaction?: Transaction<Database>): Promise<void> {
+ const db = transaction ?? this.#db;
+ await db.deleteFrom('schedule').where('tenant_id', '=', input.tenant_id).where('id', '=', input.id).execute();
+ }
+
+ async listSchedules(input: ListSchedulesInput, transaction?: Transaction<Database>): Promise<ScheduleRecord[]> {
+ 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);
+ }
+ const rows = await query.orderBy('created_at', 'desc').orderBy('id').execute();
+ return rows.map(toScheduleRecord);
+ }
+
+ async getRun(input: GetRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .selectFrom('schedule_run')
+ .selectAll()
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async getScheduledRunFor(
+ input: GetScheduledRunForInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .selectFrom('schedule_run')
+ .selectAll()
+ .where('tenant_id', '=', input.tenant_id)
+ .where('schedule_id', '=', input.schedule_id)
+ .where('status', '=', 'scheduled')
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async createRun(input: CreateScheduleRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord> {
+ const db = transaction ?? this.#db;
+ try {
+ const row = await db
+ .insertInto('schedule_run')
+ .values({
+ id: ulid().toLowerCase(),
+ tenant_id: input.tenant_id,
+ schedule_id: input.schedule_id,
+ name: input.name,
+ scheduled_for: input.scheduled_for,
+ status: input.status,
+ triggered_by: input.triggered_by,
+ triggered_at: null,
+ created_at: now(),
+ updated_at: now(),
+ })
+ .returningAll()
+ .executeTakeFirstOrThrow();
+ return toRunRecord(row);
+ } catch (error) {
+ if (isUniqueViolation(error)) {
+ throw new ScheduleRunConflictError(`Schedule run already exists: ${input.name}`, { cause: error });
+ }
+ throw error;
+ }
+ }
+
+ async updateRunStatus(
+ input: UpdateScheduleRunStatusInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const patch =
+ input.status === 'triggered'
+ ? { status: input.status, triggered_at: now(), updated_at: now() }
+ : { status: input.status, updated_at: now() };
+ const row = await db
+ .updateTable('schedule_run')
+ .set(patch)
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .returningAll()
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async listScheduledRuns(
+ input: ListScheduledRunsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord[]> {
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('schedule_run')
+ .selectAll()
+ .where('status', '=', 'scheduled')
+ .where('scheduled_for', '<=', input.until)
+ .orderBy('scheduled_for')
+ .limit(input.limit)
+ .execute();
+ return rows.map(toRunRecord);
+ }
+}
diff --git a/packages/trueforge/src/db/postgres/types.ts b/packages/trueforge/src/db/postgres/types.ts
index de09dc3c1..83241364a 100644
--- a/packages/trueforge/src/db/postgres/types.ts
+++ b/packages/trueforge/src/db/postgres/types.ts
@@ -22,8 +22,10 @@ import type { ColumnType, Generated, JSONColumnType } from 'kysely';
import type { McpServerManifest } from '../../schemas/mcpServer';
import type { ModelProviderManifest } from '../../schemas/modelProvider';
import type { SandboxBuildMetadata, SandboxBuildStatus, SandboxProviderManifest } from '../../schemas/sandboxProvider';
+import type { ScheduleManifest, ScheduleStatus } from '../../schemas/schedule';
import type { SkillManifest } from '../../schemas/skill';
import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpServerStore';
+import type { ScheduleRunStatus } from '../scheduleStore';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -368,6 +370,52 @@ export interface AgentTable {
updated_at: Date;
}
+/**
+ * Configured schedules — immutable ULID `id` PK.
+ * PRIMARY KEY (id)
+ * CREATE INDEX schedule_agent_idx ON schedule (tenant_id, agent_name)
+ * FK (tenant_id, agent_name) → agent(tenant_id, name) ON DELETE CASCADE
+ */
+export interface ScheduleTable {
+ /** application-generated (ulid); FK target for schedule_run */
+ id: string;
+ tenant_id: string;
+ /** FK with tenant_id → agent(tenant_id, name). Immutable; agent version resolves at run time. */
+ agent_name: string;
+ /** Display label; not unique. */
+ name: string;
+ /** ScheduleManifest document ({ task, cron, timezone }); replaced whole on update */
+ manifest: JSONColumnType<ScheduleManifest, ScheduleManifest, ScheduleManifest>;
+ /** `paused` stops triggering and drops the pending run; in-flight runs continue */
+ status: ScheduleStatus;
+ /** Identity every run of this schedule executes as (`UserContext.userRef`) */
+ created_by: string;
+ created_at: Date;
+ updated_at: Date;
+}
+
+/**
+ * One row per run, pending or historical.
+ * PRIMARY KEY (id)
+ */
+export interface ScheduleRunTable {
+ /** application-generated (ulid) */
+ id: string;
+ tenant_id: string;
+ /** FK -> schedule.id, ON DELETE CASCADE */
+ schedule_id: string;
+ /** unique per trigger time: `sched-<unixSeconds>` for cron, `manual-<token>` for run-now */
+ name: string;
+ scheduled_for: Date;
+ /** `scheduled` | `triggered` | `failed` | `missed` — varchar(16) */
+ status: ScheduleRunStatus;
+ /** `UserContext.userRef` of who triggered the run */
+ triggered_by: string;
+ triggered_at: Date | null;
+ created_at: Date;
+ updated_at: Date;
+}
+
/**
* PRIMARY KEY (id)
* UNIQUE (tenant_id, name) — the natural lookup key.
@@ -436,6 +484,8 @@ export interface OAuthPendingAuthorizationTable {
* itself — the documented, bounded cost of the raw-array model. `model_provider`,
* `skill`, `sandbox_provider`, `agent`, `mcp_server`, and the two `oauth_*` tables
* are low-write, low-volume (one row per tenant/resource, or short-lived).
+ * `schedule` is low-write; `schedule_run` takes a handful of bounded updates per
+ * trigger and is otherwise append-only.
*
* Canonical Kysely database.
*/
@@ -450,6 +500,8 @@ export interface Database {
skill: SkillTable;
sandbox_provider: SandboxProviderTable;
agent: AgentTable;
+ schedule: ScheduleTable;
+ schedule_run: ScheduleRunTable;
mcp_server: McpServerTable;
oauth_token: OAuthTokenTable;
oauth_pending_authorization: OAuthPendingAuthorizationTable;
diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.ts
new file mode 100644
index 000000000..bae9d4ddc
--- /dev/null
+++ b/packages/trueforge/src/db/scheduleStore.ts
@@ -0,0 +1,225 @@
+/**
+ * DB-backed schedules and their runs: one `schedule` row per cron binding, plus a
+ * `schedule_run` row per run (pending or historical).
+ *
+ * One store covers both tables because they are never used apart — the dispatch
+ * path needs a scheduled run and its schedule in the same query, and every schedule
+ * mutation touches the pending run in the same transaction.
+ *
+ * Transactions are route-owned (see `WithTransaction`): a store method never opens
+ * one. Create/resume/manifest-edit must pass the same transaction to the schedule
+ * write and the run write, or a schedule can end up active with no pending run —
+ * the silent-dead-schedule failure mode.
+ *
+ * Implementations: PostgresScheduleStore and SqliteScheduleStore.
+ */
+import { ScheduleManifestSchema, type ScheduleManifest, type ScheduleStatus } from '../schemas/schedule';
+
+/**
+ * Run lifecycle.
+ * - `scheduled` the one pending run; at most one per schedule, enforced by
+ * `schedule_run_pending_uq`
+ * - `triggered` taken by dispatch via `updateRunStatus`
+ * - `failed` errored, or hand-off to the executor failed
+ */
+export type ScheduleRunStatus = 'scheduled' | 'triggered' | 'failed';
+
+/**
+ * `sched-<unixSeconds>` or `manual-<token>` — one name per trigger time, which is what makes
+ * `schedule_run_name_idx` reject a duplicated trigger.
+ */
+export function cronRunName(scheduledFor: Date): string {
+ return `sched-${String(Math.floor(scheduledFor.getTime() / 1000))}`;
+}
+
+export interface ScheduleRecord {
+ id: string;
+ tenant_id: string;
+ /** Immutable FK to `agent.name` (with tenant); agent version resolves at run time. */
+ agent_name: string;
+ /** Display label; not unique. */
+ name: string;
+ manifest: ScheduleManifest;
+ status: ScheduleStatus;
+ /** userRef every run of this schedule executes as. */
+ created_by: string;
+ /** ISO-8601 UTC instant. */
+ created_at: string;
+ /** ISO-8601 UTC instant. */
+ updated_at: string;
+}
+
+export interface ScheduleRunRecord {
+ id: string;
+ tenant_id: string;
+ schedule_id: string;
+ name: string;
+ /** ISO-8601 UTC instant this run was scheduled for. Preserved even when `missed`. */
+ scheduled_for: string;
+ status: ScheduleRunStatus;
+ /** userRef the run executes as. */
+ triggered_by: string;
+ triggered_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+/** Schedule row plus the pending run after a create/update that syncs it. */
+export interface ScheduleWriteResult {
+ schedule: ScheduleRecord;
+ /** Set when the schedule is active; otherwise undefined (paused adds no pending run). */
+ pendingRun: ScheduleRunRecord | undefined;
+}
+
+/** A scheduled run plus the schedule that owns it. */
+export interface ScheduleDispatchItem {
+ run: ScheduleRunRecord;
+ schedule: ScheduleRecord;
+}
+
+/**
+ * Re-parse persisted manifest JSON so schema defaults materialize. Rows written
+ * before a manifest field existed omit it on disk; readers must not assume presence.
+ */
+export function parseStoredScheduleManifest(manifest: unknown): ScheduleManifest {
+ return ScheduleManifestSchema.parse(manifest);
+}
+
+export interface ListSchedulesInput {
+ tenant_id: string;
+ /** When set, only schedules bound to this agent name are returned. */
+ agent_name?: string | undefined;
+}
+
+export interface GetScheduleInput {
+ tenant_id: string;
+ id: string;
+ /** Whether to take a row lock on the schedule (`SELECT ... FOR UPDATE`). */
+ forUpdate: boolean | undefined;
+}
+
+export interface CreateScheduleInput {
+ tenant_id: string;
+ agent_name: string;
+ name: string;
+ manifest: ScheduleManifest;
+ created_by: string;
+ /** Instant used to compute the first pending run when status is active. */
+ runFrom: Date;
+}
+
+/** Replaces `name` + `manifest` for an existing schedule keyed by immutable id. */
+export interface UpdateScheduleInput {
+ tenant_id: string;
+ id: string;
+ name: string;
+ manifest: ScheduleManifest;
+ /**
+ * Instant used to compute the next pending run when a sync runs (status/cron/timezone
+ * change) and the schedule is active.
+ */
+ runFrom: Date;
+}
+export interface DeleteScheduleInput {
+ tenant_id: string;
+ id: string;
+}
+
+export interface CreateScheduleRunInput {
+ tenant_id: string;
+ schedule_id: string;
+ name: string;
+ scheduled_for: Date;
+ triggered_by: string;
+ status: ScheduleRunStatus;
+}
+
+export interface ListScheduledRunsInput {
+ until: Date;
+ limit: number;
+}
+
+export interface GetRunInput {
+ tenant_id: string;
+ /** Immutable run id. */
+ id: string;
+}
+
+export interface GetScheduledRunForInput {
+ tenant_id: string;
+ schedule_id: string;
+}
+
+export interface UpdateScheduleRunStatusInput {
+ tenant_id: string;
+ id: string;
+ status: ScheduleRunStatus;
+}
+
+export class ScheduleRunConflictError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = 'ScheduleRunConflictError';
+ }
+}
+
+/**
+ * Pending run is replaced only when `status`, `cron`, or `timezone` change.
+ * `name` and `task` edits leave the pending row alone.
+ */
+export function shouldSyncPendingRun(
+ previous: Pick<ScheduleRecord, 'status' | 'manifest'>,
+ next: Pick<ScheduleRecord, 'status' | 'manifest'>,
+): boolean {
+ return (
+ previous.status !== next.status ||
+ previous.manifest.cron !== next.manifest.cron ||
+ previous.manifest.timezone !== next.manifest.timezone
+ );
+}
+
+export interface IScheduleStore<TTransaction = never> {
+ // --- schedule ---
+ getSchedule(input: GetScheduleInput, transaction?: TTransaction): Promise<ScheduleRecord | undefined>;
+ /**
+ * Inserts a schedule (`status` mirrors `manifest.status`) and syncs the pending run
+ * in the same call: active adds the next run from `runFrom`; paused adds nothing.
+ */
+ createScheduleAndRun(input: CreateScheduleInput, transaction?: TTransaction): Promise<ScheduleWriteResult>;
+ /**
+ * Updates a schedule, then syncs the pending run only when `status`, `cron`, or
+ * `timezone` change. `name` / `task` edits leave the pending row alone.
+ * Returns undefined if the schedule is gone.
+ */
+ updateScheduleAndRun(
+ input: UpdateScheduleInput,
+ transaction?: TTransaction,
+ ): 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[]>;
+
+ // --- schedule_run ---
+ /** One run by immutable id. */
+ getRun(input: GetRunInput, transaction?: TTransaction): Promise<ScheduleRunRecord | undefined>;
+ /** A schedule's single pending (`scheduled`) run, if it has one. */
+ getScheduledRunFor(
+ input: GetScheduledRunForInput,
+ transaction?: TTransaction,
+ ): Promise<ScheduleRunRecord | undefined>;
+ /** Inserts a run. Throws {@link ScheduleRunConflictError} on either unique index. */
+ createRun(input: CreateScheduleRunInput, transaction?: TTransaction): Promise<ScheduleRunRecord>;
+ /**
+ * Status transition. Stamps `triggered_at` when moving to `triggered`.
+ * Returns undefined when the row is gone (e.g. pause deleted it).
+ */
+ updateRunStatus(
+ input: UpdateScheduleRunStatusInput,
+ transaction?: TTransaction,
+ ): Promise<ScheduleRunRecord | undefined>;
+ /**
+ * `scheduled` runs with `scheduled_for <= now`, oldest first.
+ * Triggered / terminal rows are never returned.
+ */
+ listScheduledRuns(input: ListScheduledRunsInput, transaction?: TTransaction): Promise<ScheduleRunRecord[]>;
+}
diff --git a/packages/trueforge/src/db/sqlite/migrations/20260827_000001_schedule.ts b/packages/trueforge/src/db/sqlite/migrations/20260827_000001_schedule.ts
new file mode 100644
index 000000000..ecebfe358
--- /dev/null
+++ b/packages/trueforge/src/db/sqlite/migrations/20260827_000001_schedule.ts
@@ -0,0 +1,84 @@
+import { sql, type Kysely } from 'kysely';
+
+/**
+ * Scheduled agents for SQLite — mirrors
+ * db/postgres/migrations/20260827_000001_schedule.ts, including the composite
+ * FK to `agent(tenant_id, name)` and both partial indexes.
+ *
+ * SQLite differences: `manifest` is BLOB JSONB, timestamps are ISO TEXT, tables
+ * are STRICT. No parent table is rebuilt here, so no `PRAGMA foreign_keys`
+ * toggle is needed — the migration owns its own transaction because Kysely's
+ * Migrator does not wrap SQLite migrations.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await sql`
+ CREATE TABLE schedule (
+ id TEXT NOT NULL,
+ tenant_id TEXT NOT NULL,
+ agent_name TEXT NOT NULL,
+ name TEXT NOT NULL,
+ manifest BLOB NOT NULL,
+ status TEXT NOT NULL CHECK (length(status) <= 16),
+ created_by TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (id),
+ FOREIGN KEY (tenant_id, agent_name) REFERENCES agent (tenant_id, name) ON DELETE CASCADE
+ ) STRICT
+ `.execute(trx);
+
+ await sql`
+ CREATE INDEX schedule_agent_idx
+ ON schedule (tenant_id, agent_name)
+ `.execute(trx);
+
+ await sql`
+ CREATE TABLE schedule_run (
+ id TEXT NOT NULL,
+ tenant_id TEXT NOT NULL,
+ schedule_id TEXT NOT NULL REFERENCES schedule (id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ scheduled_for TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (length(status) <= 16),
+ triggered_by TEXT NOT NULL,
+ triggered_at TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (id)
+ ) STRICT
+ `.execute(trx);
+
+ await sql`
+ CREATE UNIQUE INDEX schedule_run_name_idx
+ ON schedule_run (tenant_id, schedule_id, name)
+ `.execute(trx);
+
+ // Partial: the table is overwhelmingly terminal rows.
+ await sql`
+ CREATE INDEX schedule_run_scheduled_for_idx
+ ON schedule_run (scheduled_for)
+ WHERE status = 'scheduled'
+ `.execute(trx);
+
+ // At most one pending run per schedule — the resume-vs-trigger race as a constraint.
+ await sql`
+ CREATE UNIQUE INDEX schedule_run_pending_uq
+ ON schedule_run (schedule_id)
+ WHERE status = 'scheduled'
+ `.execute(trx);
+
+ // Run history: newest first within one schedule.
+ await sql`
+ CREATE INDEX schedule_run_list_idx
+ ON schedule_run (schedule_id, scheduled_for DESC)
+ `.execute(trx);
+ });
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await db.transaction().execute(async trx => {
+ await sql`DROP TABLE IF EXISTS schedule_run`.execute(trx);
+ await sql`DROP TABLE IF EXISTS schedule`.execute(trx);
+ });
+}
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
new file mode 100644
index 000000000..5369c4e6b
--- /dev/null
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -0,0 +1,321 @@
+import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
+import { ulid } from 'ulid';
+import { nextTriggerAfter } from '../../../runtime/cron';
+import type { ScheduleManifest, ScheduleStatus } from '../../../schemas/schedule';
+import {
+ cronRunName,
+ parseStoredScheduleManifest,
+ ScheduleRunConflictError,
+ shouldSyncPendingRun,
+ type CreateScheduleInput,
+ type CreateScheduleRunInput,
+ type DeleteScheduleInput,
+ type GetRunInput,
+ type GetScheduledRunForInput,
+ type GetScheduleInput,
+ type IScheduleStore,
+ type ListScheduledRunsInput,
+ type ListSchedulesInput,
+ type ScheduleRecord,
+ type ScheduleRunRecord,
+ type ScheduleRunStatus,
+ type ScheduleWriteResult,
+ type UpdateScheduleInput,
+ type UpdateScheduleRunStatusInput,
+} from '../../scheduleStore';
+import { isUniqueViolation } from '../client';
+import { jsonbBind, jsonText, nowIso } from '../sqlExpressions';
+import type { Database } from '../types';
+
+/** Column list projecting the JSONB manifest as parsed JSON (see JSON_RESULT_COLUMNS). */
+function scheduleColumns(eb: ExpressionBuilder<Database, 'schedule'>) {
+ return [
+ 'id' as const,
+ 'tenant_id' as const,
+ 'agent_name' as const,
+ 'name' as const,
+ jsonText<ScheduleManifest>(eb.ref('manifest')).as('manifest'),
+ 'status' as const,
+ 'created_by' as const,
+ 'created_at' as const,
+ 'updated_at' as const,
+ ];
+}
+
+const RUN_COLUMNS = [
+ 'id',
+ 'tenant_id',
+ 'schedule_id',
+ 'name',
+ 'scheduled_for',
+ 'status',
+ 'triggered_by',
+ 'triggered_at',
+ 'created_at',
+ 'updated_at',
+] as const;
+
+interface ScheduleRow {
+ id: string;
+ tenant_id: string;
+ agent_name: string;
+ name: string;
+ manifest: ScheduleManifest;
+ status: ScheduleStatus;
+ created_by: string;
+ created_at: string;
+ updated_at: string;
+}
+
+interface RunRow {
+ id: string;
+ tenant_id: string;
+ schedule_id: string;
+ name: string;
+ scheduled_for: string;
+ status: ScheduleRunStatus;
+ triggered_by: string;
+ triggered_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+function toScheduleRecord(row: ScheduleRow): ScheduleRecord {
+ return { ...row, manifest: parseStoredScheduleManifest(row.manifest) };
+}
+
+function toRunRecord(row: RunRow): ScheduleRunRecord {
+ return { ...row };
+}
+
+export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>> {
+ readonly #db: Kysely<Database>;
+
+ constructor(db: Kysely<Database>) {
+ this.#db = db;
+ }
+
+ /**
+ * `input.forUpdate` is intentionally ignored: SQLite has no `SELECT ... FOR UPDATE`
+ * and does not need one — a write transaction holds the whole database, so the
+ * lock ordering Postgres needs is already guaranteed.
+ */
+ async getSchedule(input: GetScheduleInput, transaction?: Transaction<Database>): Promise<ScheduleRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .selectFrom('schedule')
+ .select(scheduleColumns)
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .executeTakeFirst();
+ return row === undefined ? undefined : toScheduleRecord(row);
+ }
+
+ async createScheduleAndRun(
+ input: CreateScheduleInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleWriteResult> {
+ const db = transaction ?? this.#db;
+ const timestamp = nowIso();
+ const row = await db
+ .insertInto('schedule')
+ .values({
+ id: ulid().toLowerCase(),
+ tenant_id: input.tenant_id,
+ agent_name: input.agent_name,
+ name: input.name,
+ manifest: jsonbBind(input.manifest),
+ // Column mirrors the manifest so the dispatch scan and API reads share one value.
+ status: input.manifest.status,
+ created_by: input.created_by,
+ created_at: timestamp,
+ updated_at: timestamp,
+ })
+ .returning(scheduleColumns)
+ .executeTakeFirstOrThrow();
+ const schedule = toScheduleRecord(row);
+ const pendingRun = await this.#syncPendingRun(schedule, input.runFrom, transaction);
+ return { schedule, pendingRun };
+ }
+
+ async updateScheduleAndRun(
+ input: UpdateScheduleInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleWriteResult | undefined> {
+ // Lock first: this transaction writes the schedule AND its runs, and every such
+ // transaction must take the schedule lock before touching a run row (see the
+ // lock-ordering note in `controller/scheduleDispatch.ts`). A no-op here; Postgres
+ // is where it matters.
+ const previous = await this.getSchedule({ tenant_id: input.tenant_id, id: input.id, forUpdate: true }, transaction);
+ if (previous === undefined) {
+ return undefined;
+ }
+
+ const db = transaction ?? this.#db;
+ const row = await db
+ .updateTable('schedule')
+ .set({
+ name: input.name,
+ manifest: jsonbBind(input.manifest),
+ status: input.manifest.status,
+ updated_at: nowIso(),
+ })
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .returning(scheduleColumns)
+ .executeTakeFirst();
+ if (row === undefined) {
+ return undefined;
+ }
+ const schedule = toScheduleRecord(row);
+ if (!shouldSyncPendingRun(previous, schedule)) {
+ const pendingRun = await this.getScheduledRunFor(
+ { tenant_id: schedule.tenant_id, schedule_id: schedule.id },
+ transaction,
+ );
+ return { schedule, pendingRun };
+ }
+ const pendingRun = await this.#syncPendingRun(schedule, input.runFrom, transaction);
+ return { schedule, pendingRun };
+ }
+
+ async #syncPendingRun(
+ schedule: ScheduleRecord,
+ from: Date,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ // Clear the pending run, if any; whether a replacement follows depends on status.
+ await db
+ .deleteFrom('schedule_run')
+ .where('tenant_id', '=', schedule.tenant_id)
+ .where('schedule_id', '=', schedule.id)
+ .where('status', '=', 'scheduled')
+ .execute();
+ if (schedule.status !== 'active') {
+ return undefined;
+ }
+ const nextTrigger = nextTriggerAfter({
+ cron: schedule.manifest.cron,
+ timezone: schedule.manifest.timezone,
+ from,
+ });
+ return this.createRun(
+ {
+ tenant_id: schedule.tenant_id,
+ schedule_id: schedule.id,
+ name: cronRunName(nextTrigger),
+ scheduled_for: nextTrigger,
+ status: 'scheduled',
+ triggered_by: schedule.created_by,
+ },
+ transaction,
+ );
+ }
+
+ async deleteSchedule(input: DeleteScheduleInput, transaction?: Transaction<Database>): Promise<void> {
+ const db = transaction ?? this.#db;
+ await db.deleteFrom('schedule').where('tenant_id', '=', input.tenant_id).where('id', '=', input.id).execute();
+ }
+
+ async listSchedules(input: ListSchedulesInput, transaction?: Transaction<Database>): Promise<ScheduleRecord[]> {
+ 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);
+ }
+ const rows = await query.orderBy('created_at', 'desc').orderBy('id').execute();
+ return rows.map(toScheduleRecord);
+ }
+
+ async getRun(input: GetRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .selectFrom('schedule_run')
+ .select(RUN_COLUMNS)
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async getScheduledRunFor(
+ input: GetScheduledRunForInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db
+ .selectFrom('schedule_run')
+ .select(RUN_COLUMNS)
+ .where('tenant_id', '=', input.tenant_id)
+ .where('schedule_id', '=', input.schedule_id)
+ .where('status', '=', 'scheduled')
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async createRun(input: CreateScheduleRunInput, transaction?: Transaction<Database>): Promise<ScheduleRunRecord> {
+ const db = transaction ?? this.#db;
+ const timestamp = nowIso();
+ try {
+ const row = await db
+ .insertInto('schedule_run')
+ .values({
+ id: ulid().toLowerCase(),
+ tenant_id: input.tenant_id,
+ schedule_id: input.schedule_id,
+ name: input.name,
+ scheduled_for: input.scheduled_for.toISOString(),
+ status: input.status,
+ triggered_by: input.triggered_by,
+ triggered_at: null,
+ created_at: timestamp,
+ updated_at: timestamp,
+ })
+ .returning(RUN_COLUMNS)
+ .executeTakeFirstOrThrow();
+ return toRunRecord(row);
+ } catch (error) {
+ if (isUniqueViolation(error)) {
+ throw new ScheduleRunConflictError(`Schedule run already exists: ${input.name}`, { cause: error });
+ }
+ throw error;
+ }
+ }
+
+ async updateRunStatus(
+ input: UpdateScheduleRunStatusInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const timestamp = nowIso();
+ const patch =
+ input.status === 'triggered'
+ ? { status: input.status, triggered_at: timestamp, updated_at: timestamp }
+ : { status: input.status, updated_at: timestamp };
+ const row = await db
+ .updateTable('schedule_run')
+ .set(patch)
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', '=', input.id)
+ .returning(RUN_COLUMNS)
+ .executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
+ async listScheduledRuns(
+ input: ListScheduledRunsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord[]> {
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('schedule_run')
+ .select(RUN_COLUMNS)
+ .where('status', '=', 'scheduled')
+ .where('scheduled_for', '<=', input.until.toISOString())
+ .orderBy('scheduled_for')
+ .limit(input.limit)
+ .execute();
+ return rows.map(toRunRecord);
+ }
+}
diff --git a/packages/trueforge/src/db/sqlite/types.ts b/packages/trueforge/src/db/sqlite/types.ts
index 4da8ba290..0a3972c45 100644
--- a/packages/trueforge/src/db/sqlite/types.ts
+++ b/packages/trueforge/src/db/sqlite/types.ts
@@ -25,8 +25,10 @@ import type { ColumnType, Generated, JSONColumnType } from 'kysely';
import type { McpServerManifest } from '../../schemas/mcpServer';
import type { ModelProviderManifest } from '../../schemas/modelProvider';
import type { SandboxBuildMetadata, SandboxBuildStatus, SandboxProviderManifest } from '../../schemas/sandboxProvider';
+import type { ScheduleManifest, ScheduleStatus } from '../../schemas/schedule';
import type { SkillManifest } from '../../schemas/skill';
import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpServerStore';
+import type { ScheduleRunStatus } from '../scheduleStore';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -218,6 +220,51 @@ export interface AgentTable {
updated_at: string;
}
+/**
+ * Configured schedules.
+ * PRIMARY KEY (id).
+ * FK (tenant_id, agent_name) → agent(tenant_id, name) ON DELETE CASCADE.
+ */
+export interface ScheduleTable {
+ /** application-generated (ulid); FK target for schedule_run */
+ id: string;
+ tenant_id: string;
+ /** FK with tenant_id → agent(tenant_id, name). Immutable; agent version resolves at run time. */
+ agent_name: string;
+ /** Display label; not unique. */
+ name: string;
+ /** ScheduleManifest document ({ task, cron, timezone }); replaced whole on update */
+ manifest: JsonbColumn<ScheduleManifest>;
+ /** `paused` stops triggering and drops the pending run; in-flight runs continue */
+ status: ScheduleStatus;
+ /** Identity every run of this schedule executes as (`UserContext.userRef`) */
+ created_by: string;
+ created_at: string;
+ updated_at: string;
+}
+
+/**
+ * One row per schedule run, pending or historical — mirrors the Postgres `schedule_run`
+ * PRIMARY KEY (id); UNIQUE (tenant_id, schedule_id, name).
+ */
+export interface ScheduleRunTable {
+ /** application-generated (ulid) */
+ id: string;
+ tenant_id: string;
+ /** FK -> schedule.id, ON DELETE CASCADE */
+ schedule_id: string;
+ /** the run name: `sched-<unixSeconds>` for cron, `manual-<token>` for run-now */
+ name: string;
+ scheduled_for: string;
+ /** `scheduled` | `triggered` | `failed` | `missed` — length ≤ 16 */
+ status: ScheduleRunStatus;
+ /** `UserContext.userRef` of who triggered the run */
+ triggered_by: string;
+ triggered_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
/**
* PRIMARY KEY (id)
* UNIQUE (tenant_id, name) — the natural lookup key;
@@ -280,6 +327,8 @@ export interface Database {
skill: SkillTable;
sandbox_provider: SandboxProviderTable;
agent: AgentTable;
+ schedule: ScheduleTable;
+ schedule_run: ScheduleRunTable;
mcp_server: McpServerTable;
oauth_token: OAuthTokenTable;
oauth_pending_authorization: OAuthPendingAuthorizationTable;
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index c1ffa761d..047d0f7a1 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -51,11 +51,14 @@ import { ModelCatalog } from './catalog/ModelCatalog';
import { SandboxCatalog } from './catalog/SandboxCatalog';
import { SkillCatalog } from './catalog/SkillCatalog';
import { type DistributedServerConfiguration } from './config';
+import { Controller } from './controller/Controller';
+import { createScheduleDispatchLoop, logTriggeredRun } from './controller/scheduleDispatch';
import type { IAgentStore } from './db/agentStore';
import type { IMcpServerStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
import type { Database as PostgresDatabase } from './db/postgres/types';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
+import type { IScheduleStore } from './db/scheduleStore';
import type { ISkillStore } from './db/skillStore';
import type { Database as SqliteDatabase } from './db/sqlite/types';
import type { WithTransaction } from './db/transaction';
@@ -77,6 +80,7 @@ interface ServerPersistence<TTransaction> {
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
agentStore: IAgentStore<TTransaction>;
+ scheduleStore: IScheduleStore<TTransaction>;
destroyDb: () => Promise<void>;
redis: RedisClientType | undefined;
}
@@ -99,6 +103,7 @@ async function createStandalonePersistence(options: {
import('./db/sqlite/skill-store/SqliteSkillStore'),
import('./db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore'),
import('./db/sqlite/agent-store/SqliteAgentStore'),
+ import('./db/sqlite/schedule-store/SqliteScheduleStore'),
]),
]);
const [
@@ -109,6 +114,7 @@ async function createStandalonePersistence(options: {
{ SqliteSkillStore },
{ SqliteSandboxProviderStore },
{ SqliteAgentStore },
+ { SqliteScheduleStore },
] = sqliteStores;
const db = createSqliteDb(sqlitePath);
@@ -125,6 +131,7 @@ async function createStandalonePersistence(options: {
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
agentStore: new SqliteAgentStore(db),
+ scheduleStore: new SqliteScheduleStore(db),
destroyDb: () => db.destroy(),
redis: undefined,
};
@@ -157,6 +164,7 @@ async function createDistributedPersistence(options: {
import('./db/postgres/skill-store/PostgresSkillStore'),
import('./db/postgres/sandbox-provider-store/PostgresSandboxProviderStore'),
import('./db/postgres/agent-store/PostgresAgentStore'),
+ import('./db/postgres/schedule-store/PostgresScheduleStore'),
]),
]);
const [
@@ -167,6 +175,7 @@ async function createDistributedPersistence(options: {
{ PostgresSkillStore },
{ PostgresSandboxProviderStore },
{ PostgresAgentStore },
+ { PostgresScheduleStore },
] = postgresStores;
const db = createDb({
@@ -188,6 +197,7 @@ async function createDistributedPersistence(options: {
skillStore: new PostgresSkillStore(db),
sandboxProviderStore: new PostgresSandboxProviderStore(db),
agentStore: new PostgresAgentStore(db),
+ scheduleStore: new PostgresScheduleStore(db),
destroyDb: () => db.destroy(),
redis: await connectRedis({ url: redisUrl, logger }),
};
@@ -204,6 +214,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
skillStore,
sandboxProviderStore,
agentStore,
+ scheduleStore,
destroyDb,
redis,
} = persistence;
@@ -220,6 +231,21 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
}
const oidcClient = await initOidc(oidc);
+ // Standalone is one process, so it owns the control loops too.
+ const controller = configuration.STANDALONE
+ ? new Controller({
+ loops: [
+ createScheduleDispatchLoop({
+ scheduleStore,
+ withTransaction,
+ onTriggered: logTriggeredRun(logger),
+ logger,
+ }),
+ ],
+ logger,
+ })
+ : undefined;
+
const app = createServerApp({
modelCatalog: ModelCatalog.load(),
mcpCatalog: McpCatalog.load(),
@@ -232,6 +258,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
skillStore,
sandboxProviderStore,
agentStore,
+ scheduleStore,
sessionStore,
sessions: new Sessions({ sessionStore }),
activeTurns,
@@ -242,7 +269,9 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
oidcClient,
});
- return { activeTurns, app, destroyDb, redis, requestReplyRouter };
+ controller?.start();
+
+ return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
}
try {
@@ -278,7 +307,7 @@ try {
logger.info('TrueForge starting', { mode: 'distributed' });
}
- const { activeTurns, app, destroyDb, redis, requestReplyRouter } = configuration.STANDALONE
+ const { activeTurns, app, controller, destroyDb, redis, requestReplyRouter } = configuration.STANDALONE
? await createServerRuntime(
await createStandalonePersistence({ sqlitePath: configuration.SQLITE_PATH, logger }),
logger,
@@ -354,6 +383,10 @@ try {
});
});
+ // Stop the control loops before draining; anything they already started drains
+ // with every other turn below.
+ await controller?.stop();
+
// Sets the registry's shutdown reason immediately so late track() (in-flight create-turn still
// inside session.createTurn) aborts as Abandoned; then drains the registry. await
// closed covers the gap where the registry is empty before that late track().
diff --git a/packages/trueforge/src/routes/openapiTags.ts b/packages/trueforge/src/routes/openapiTags.ts
index 549f94b58..64709378c 100644
--- a/packages/trueforge/src/routes/openapiTags.ts
+++ b/packages/trueforge/src/routes/openapiTags.ts
@@ -7,6 +7,7 @@ export enum OpenApiTag {
SKILLS = 'Skills',
SANDBOXES = 'Sandboxes',
AGENTS = 'Agents',
+ SCHEDULES = 'Schedules',
AGENT_SESSIONS = 'Agent Sessions',
}
@@ -19,5 +20,6 @@ export const OPENAPI_DOCUMENT_TAGS: { name: OpenApiTag }[] = [
{ name: OpenApiTag.SKILLS },
{ name: OpenApiTag.SANDBOXES },
{ name: OpenApiTag.AGENTS },
+ { name: OpenApiTag.SCHEDULES },
{ name: OpenApiTag.AGENT_SESSIONS },
];
diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.ts
new file mode 100644
index 000000000..c70fedea5
--- /dev/null
+++ b/packages/trueforge/src/routes/scheduleRoutes.ts
@@ -0,0 +1,159 @@
+/**
+ * Schedule route definitions (mounted at /api/v1/schedules).
+ * Handlers are registered in apis/schedules.ts.
+ */
+import { createRoute, z } from '@hono/zod-openapi';
+import { NameSchema } from '../schemas/common';
+import { RequestErrorResponseSchema } from '../schemas/errors';
+import {
+ CreateScheduleRequestSchema,
+ DeleteScheduleResponseSchema,
+ GetScheduleResponseSchema,
+ ListSchedulesResponseSchema,
+ UpdateScheduleRequestSchema,
+} from '../schemas/schedule';
+import { OpenApiTag } from './openapiTags';
+
+export const ScheduleIdParamsSchema = z.object({
+ schedule_id: z.string().min(1).max(64).describe('Immutable schedule identifier.'),
+});
+
+export const ListSchedulesQuerySchema = z
+ .object({
+ agent_name: NameSchema.optional(),
+ })
+ .openapi('ListSchedulesQuery');
+
+export const listSchedulesRoute = createRoute({
+ method: 'get',
+ path: '/',
+ tags: [OpenApiTag.SCHEDULES],
+ summary: 'List schedules',
+ description: 'List schedules for the tenant, newest first. Optionally filter by `agent_name`.',
+ 'x-fern-sdk-group-name': ['schedules'],
+ 'x-fern-sdk-method-name': 'list',
+ request: {
+ query: ListSchedulesQuerySchema,
+ },
+ responses: {
+ 200: {
+ content: { 'application/json': { schema: ListSchedulesResponseSchema } },
+ description: 'Matching schedules.',
+ },
+ 401: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unauthenticated.',
+ },
+ },
+});
+
+export const createScheduleRoute = createRoute({
+ method: 'post',
+ path: '/',
+ tags: [OpenApiTag.SCHEDULES],
+ summary: 'Create a schedule',
+ description: 'Create a schedule for an existing agent (by name) and add its first pending run when active.',
+ 'x-fern-sdk-group-name': ['schedules'],
+ 'x-fern-sdk-method-name': 'create',
+ request: {
+ body: {
+ content: { 'application/json': { schema: CreateScheduleRequestSchema } },
+ required: true,
+ },
+ },
+ responses: {
+ 201: {
+ content: { 'application/json': { schema: GetScheduleResponseSchema } },
+ description: 'Created schedule.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unknown agent or invalid cron.',
+ },
+ 409: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'The schedule was modified concurrently (usually the controller advancing it). Retry.',
+ },
+ },
+});
+
+export const getScheduleRoute = createRoute({
+ method: 'get',
+ path: '/{schedule_id}',
+ tags: [OpenApiTag.SCHEDULES],
+ summary: 'Get a schedule',
+ description: 'Get a schedule by id.',
+ 'x-fern-sdk-group-name': ['schedules'],
+ 'x-fern-sdk-method-name': 'get',
+ request: {
+ params: ScheduleIdParamsSchema,
+ },
+ responses: {
+ 200: {
+ content: { 'application/json': { schema: GetScheduleResponseSchema } },
+ description: 'The schedule.',
+ },
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Not found.',
+ },
+ },
+});
+
+export const putScheduleRoute = createRoute({
+ method: 'put',
+ path: '/{schedule_id}',
+ tags: [OpenApiTag.SCHEDULES],
+ summary: 'Update a schedule',
+ description: 'Replace name and manifest; replaces or drops the pending run when status/cron/timezone change.',
+ 'x-fern-sdk-group-name': ['schedules'],
+ 'x-fern-sdk-method-name': 'update',
+ request: {
+ params: ScheduleIdParamsSchema,
+ body: {
+ content: { 'application/json': { schema: UpdateScheduleRequestSchema } },
+ required: true,
+ },
+ },
+ responses: {
+ 200: {
+ content: { 'application/json': { schema: GetScheduleResponseSchema } },
+ description: 'Updated schedule.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid cron.',
+ },
+ 409: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'The schedule was modified concurrently (usually the controller advancing it). Retry.',
+ },
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Not found.',
+ },
+ },
+});
+
+export const deleteScheduleRoute = createRoute({
+ method: 'delete',
+ path: '/{schedule_id}',
+ tags: [OpenApiTag.SCHEDULES],
+ summary: 'Delete a schedule',
+ description: 'Delete a schedule and its runs. Idempotent.',
+ 'x-fern-sdk-group-name': ['schedules'],
+ 'x-fern-sdk-method-name': 'delete',
+ request: {
+ params: ScheduleIdParamsSchema,
+ },
+ responses: {
+ 200: {
+ content: { 'application/json': { schema: DeleteScheduleResponseSchema } },
+ description: 'Deleted.',
+ },
+ 401: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unauthenticated.',
+ },
+ },
+});
diff --git a/packages/trueforge/src/runtime/cron.ts b/packages/trueforge/src/runtime/cron.ts
new file mode 100644
index 000000000..76fc15e60
--- /dev/null
+++ b/packages/trueforge/src/runtime/cron.ts
@@ -0,0 +1,61 @@
+/**
+ * Cron evaluation for schedules.
+ *
+ * `cron-parser` is used for computation only; it owns no timers. Expressions are
+ * evaluated in the schedule's IANA zone. On a spring-forward gap, a time that
+ * does not exist (e.g. 02:30) maps onto the landing hour (03:30); fall-back
+ * repeats are not double-fired for a fixed hour. Callers that care about the
+ * exact UTC instant should prefer `timezone: "UTC"`.
+ */
+import { CronExpressionParser } from 'cron-parser';
+import { InvalidCronError, type ScheduleManifest } from '../schemas/schedule';
+
+/** How many consecutive triggers to sample when measuring the tightest gap. */
+const INTERVAL_PROBE_TRIGGERS = 5;
+
+/**
+ * Next trigger time strictly after `from`, in `timezone`.
+ *
+ * Throws {@link InvalidCronError} when the expression parses structurally
+ * but cannot produce a trigger time — e.g. `0 0 30 2 *`, February 30th.
+ */
+export function nextTriggerAfter(input: { cron: string; timezone: string; from: Date }): Date {
+ const { cron, timezone, from } = input;
+ try {
+ const interval = CronExpressionParser.parse(cron, {
+ currentDate: from,
+ tz: timezone,
+ });
+ return interval.next().toDate();
+ } catch (error) {
+ throw new InvalidCronError(`Cron expression "${cron}" has no next trigger time in ${timezone}`, { cause: error });
+ }
+}
+
+/**
+ * Tightest gap the expression can produce, in seconds, measured over the next
+ * {@link INTERVAL_PROBE_TRIGGERS} triggers.
+ *
+ * Sampling rather than analysis: a cron field can be irregular (`0 9,9 * * *`,
+ * `*\/7 * * * *`), and DST transitions can make some real gaps shorter than the
+ * nominal one. Probing the actual sequence is both simpler and more honest than
+ * reasoning about the fields.
+ */
+export function minIntervalSeconds(
+ manifest: Pick<ScheduleManifest, 'cron' | 'timezone'>,
+ from: Date = new Date(),
+): number {
+ const interval = CronExpressionParser.parse(manifest.cron, {
+ currentDate: from,
+ tz: manifest.timezone,
+ });
+
+ let previous = interval.next().toDate();
+ let tightest = Number.POSITIVE_INFINITY;
+ for (let i = 0; i < INTERVAL_PROBE_TRIGGERS; i++) {
+ const current = interval.next().toDate();
+ tightest = Math.min(tightest, (current.getTime() - previous.getTime()) / 1000);
+ previous = current;
+ }
+ return tightest;
+}
diff --git a/packages/trueforge/src/schemas/schedule.ts b/packages/trueforge/src/schemas/schedule.ts
new file mode 100644
index 000000000..d6523765f
--- /dev/null
+++ b/packages/trueforge/src/schemas/schedule.ts
@@ -0,0 +1,124 @@
+import { z } from '@hono/zod-openapi';
+import { NameSchema } from './common';
+
+/**
+ * Minimum gap between two triggers of one schedule.
+ */
+export const SCHEDULE_MIN_INTERVAL_SECONDS = 3600;
+
+/**
+ * Standard 5-field cron (minute hour day-of-month month day-of-week).
+ */
+const CRON_FIELD = String.raw`[\d*,\-/]+`;
+
+/** Cron expression cannot produce a valid upcoming trigger, or violates schedule policy. */
+export class InvalidCronError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = 'InvalidCronError';
+ }
+}
+
+export const CronExpressionSchema = z
+ .string()
+ .trim()
+ .regex(
+ new RegExp(`^${CRON_FIELD}(?:\\s+${CRON_FIELD}){4}$`),
+ 'must be a 5-field cron expression: minute hour day-of-month month day-of-week',
+ )
+ .describe('Standard 5-field cron expression, evaluated in `timezone`.')
+ .openapi('CronExpression');
+
+/**
+ * IANA zone name — never a fixed UTC offset, which cannot represent DST.
+ *
+ * Optional in the manifest; defaults to UTC, which is also the recommendation when
+ * the trigger instant matters more than the local hour.
+ *
+ * Cron is evaluated in this zone via `cron-parser`: a spring-forward gap maps a
+ * missing local time onto the landing hour, and fall-back does not double-fire a
+ * fixed hour. Prefer `UTC` when the trigger instant matters more than the local hour.
+ */
+export const TimezoneSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .refine(value => {
+ try {
+ new Intl.DateTimeFormat(undefined, { timeZone: value });
+ return true;
+ } catch {
+ return false;
+ }
+ }, 'must be a valid IANA time zone name, e.g. "America/New_York"')
+ .describe('IANA time zone the cron expression is evaluated in.')
+ .openapi('Timezone');
+
+/**
+ * Wire ISO-8601 instant on a response. Always UTC with milliseconds — every
+ * timestamp the server emits comes from `Date.prototype.toISOString()`.
+ */
+const IsoTimestamp = z.iso.datetime().openapi({ type: 'string', format: 'date-time' });
+
+export const ScheduleTaskSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .describe('First user message sent to the agent on every run.');
+
+export const ScheduleStatusSchema = z.enum(['active', 'paused']).openapi('ScheduleStatus');
+
+/**
+ * Schedule document persisted as `schedule.manifest`.
+ */
+export const ScheduleManifestObjectSchema = z
+ .object({
+ task: ScheduleTaskSchema,
+ cron: CronExpressionSchema,
+ timezone: TimezoneSchema.default('UTC'),
+ status: ScheduleStatusSchema.default('active'),
+ })
+ .strict();
+
+export const ScheduleManifestSchema = ScheduleManifestObjectSchema.openapi('ScheduleManifest');
+
+/** List/get/create/update response item. */
+export const ScheduleSchema = z
+ .object({
+ id: z.string(),
+ agent_name: NameSchema,
+ name: NameSchema,
+ manifest: ScheduleManifestSchema,
+ created_by: z.string(),
+ created_at: IsoTimestamp,
+ updated_at: IsoTimestamp,
+ })
+ .strict()
+ .openapi('Schedule');
+
+export const CreateScheduleRequestSchema = z
+ .object({
+ agent_name: NameSchema,
+ name: NameSchema,
+ manifest: ScheduleManifestSchema,
+ })
+ .strict()
+ .openapi('CreateScheduleRequest');
+
+export const UpdateScheduleRequestSchema = z
+ .object({
+ name: NameSchema,
+ manifest: ScheduleManifestSchema,
+ })
+ .strict()
+ .openapi('UpdateScheduleRequest');
+
+export const GetScheduleResponseSchema = z.object({ data: ScheduleSchema }).openapi('GetScheduleResponse');
+export const ListSchedulesResponseSchema = z.object({ data: z.array(ScheduleSchema) }).openapi('ListSchedulesResponse');
+export const DeleteScheduleResponseSchema = z.object({}).openapi('DeleteScheduleResponse');
+
+export type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;
+export type ScheduleManifest = z.infer<typeof ScheduleManifestSchema>;
+export type Schedule = z.infer<typeof ScheduleSchema>;
+export type CreateScheduleRequest = z.infer<typeof CreateScheduleRequestSchema>;
+export type UpdateScheduleRequest = z.infer<typeof UpdateScheduleRequestSchema>;
diff --git a/packages/trueforge/tests/db/postgres/schedule-store/contract.test.ts b/packages/trueforge/tests/db/postgres/schedule-store/contract.test.ts
new file mode 100644
index 000000000..493a3e5df
--- /dev/null
+++ b/packages/trueforge/tests/db/postgres/schedule-store/contract.test.ts
@@ -0,0 +1,44 @@
+import { sql } from 'kysely';
+
+import { PostgresAgentStore } from '../../../../src/db/postgres/agent-store/PostgresAgentStore';
+import { PostgresScheduleStore } from '../../../../src/db/postgres/schedule-store/PostgresScheduleStore';
+import { runScheduleStoreContractSuite } from '../../scheduleStoreContractSuite';
+import { createPostgresTestDatabase, type PostgresTestDatabase } from '../testDatabase';
+
+const describePg = process.env['PG_STORE_TESTS_ENABLED'] === '1' ? describe : describe.skip;
+
+describePg('PostgresScheduleStore (pending-run sync contract)', () => {
+ let env: PostgresTestDatabase | undefined;
+
+ beforeAll(async () => {
+ env = await createPostgresTestDatabase();
+ if (env === undefined) {
+ throw new Error('Postgres test environment unavailable despite globalSetup probe');
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await env?.teardown();
+ });
+
+ beforeEach(async () => {
+ if (env !== undefined) {
+ await sql`TRUNCATE TABLE agent CASCADE`.execute(env.db);
+ }
+ });
+
+ runScheduleStoreContractSuite({
+ getAgentStore: () => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return new PostgresAgentStore(env.db);
+ },
+ getScheduleStore: () => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return new PostgresScheduleStore(env.db);
+ },
+ });
+});
diff --git a/packages/trueforge/tests/db/postgres/schedule-store/dispatch.contract.test.ts b/packages/trueforge/tests/db/postgres/schedule-store/dispatch.contract.test.ts
new file mode 100644
index 000000000..10e200b6e
--- /dev/null
+++ b/packages/trueforge/tests/db/postgres/schedule-store/dispatch.contract.test.ts
@@ -0,0 +1,50 @@
+import { sql } from 'kysely';
+
+import { PostgresAgentStore } from '../../../../src/db/postgres/agent-store/PostgresAgentStore';
+import { PostgresScheduleStore } from '../../../../src/db/postgres/schedule-store/PostgresScheduleStore';
+import { runScheduleDispatchContractSuite } from '../../scheduleDispatchContractSuite';
+import { createPostgresTestDatabase, type PostgresTestDatabase } from '../testDatabase';
+
+const describePg = process.env['PG_STORE_TESTS_ENABLED'] === '1' ? describe : describe.skip;
+
+describePg('dispatchScheduledRuns (postgres contract)', () => {
+ let env: PostgresTestDatabase | undefined;
+
+ beforeAll(async () => {
+ env = await createPostgresTestDatabase();
+ if (env === undefined) {
+ throw new Error('Postgres test environment unavailable despite globalSetup probe');
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await env?.teardown();
+ });
+
+ beforeEach(async () => {
+ if (env !== undefined) {
+ await sql`TRUNCATE TABLE agent CASCADE`.execute(env.db);
+ }
+ });
+
+ runScheduleDispatchContractSuite({
+ getAgentStore: () => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return new PostgresAgentStore(env.db);
+ },
+ getScheduleStore: () => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return new PostgresScheduleStore(env.db);
+ },
+ withTransaction: callback => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ return env.db.transaction().execute(callback);
+ },
+ });
+});
diff --git a/packages/trueforge/tests/db/scheduleDispatchContractSuite.ts b/packages/trueforge/tests/db/scheduleDispatchContractSuite.ts
new file mode 100644
index 000000000..b62f3c78a
--- /dev/null
+++ b/packages/trueforge/tests/db/scheduleDispatchContractSuite.ts
@@ -0,0 +1,393 @@
+import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
+import { createLogger } from 'winston';
+
+import { dispatchScheduledRuns } from '../../src/controller/scheduleDispatch';
+import type { IAgentStore } from '../../src/db/agentStore';
+import {
+ type IScheduleStore,
+ type ScheduleDispatchItem,
+ type ScheduleRecord,
+ type ScheduleRunRecord,
+} from '../../src/db/scheduleStore';
+import type { WithTransaction } from '../../src/db/transaction';
+import { nextTriggerAfter } from '../../src/runtime/cron';
+import { ScheduleManifestSchema, type ScheduleManifest } from '../../src/schemas/schedule';
+
+const TENANT = 'default';
+/** Schedule creator. Every advanced run must be attributed to this identity. */
+const USER = 'tester';
+/** Distinct from {@link USER}, so `triggered_by` assertions cannot pass by aliasing. */
+const OTHER_ACTOR = 'someone-else';
+const CRON = '0 * * * *';
+/**
+ * Triggers every minute. Used where a past `scheduled_for` must produce a DIFFERENT
+ * next trigger time than `now` does — an hourly cron aliases the two unless the seeded time
+ * happens to straddle an hour boundary, which makes the assertion flaky rather
+ * than wrong. The one-hour minimum interval is an API-layer rule, not a store one.
+ */
+const MINUTELY_CRON = '* * * * *';
+const TIMEZONE = 'UTC';
+
+function manifest(overrides: Partial<ScheduleManifest> = {}): ScheduleManifest {
+ return ScheduleManifestSchema.parse({
+ task: 'Say hello',
+ cron: CRON,
+ timezone: TIMEZONE,
+ status: 'active',
+ ...overrides,
+ });
+}
+
+/** Next trigger time may land on either side of an hour boundary between seed and assert. */
+function expectNextTriggerIso(actual: string | undefined, fromMs: number, toMs: number): void {
+ const candidates = new Set([
+ nextTriggerAfter({ cron: CRON, timezone: TIMEZONE, from: new Date(fromMs) }).toISOString(),
+ nextTriggerAfter({ cron: CRON, timezone: TIMEZONE, from: new Date(toMs) }).toISOString(),
+ ]);
+ expect(actual !== undefined && candidates.has(actual)).toBe(true);
+}
+
+export function runScheduleDispatchContractSuite<TTransaction>(deps: {
+ getAgentStore: () => IAgentStore;
+ getScheduleStore: () => IScheduleStore<TTransaction>;
+ withTransaction: WithTransaction<TTransaction>;
+}): void {
+ const logger = createLogger({ silent: true });
+ let seq = 0;
+
+ async function seedAgent(): Promise<string> {
+ seq += 1;
+ const agent = await deps.getAgentStore().createAgent({
+ tenant_id: TENANT,
+ name: `agent-${String(Date.now())}-${String(seq)}`,
+ manifest: AgentSpecSchema.parse({
+ model: { name: 'anthropic/claude-sonnet-4-6' },
+ instructions: 'Be helpful.',
+ }),
+ });
+ return agent.name;
+ }
+
+ async function scheduledRunsFor(scheduleId: string): Promise<ScheduleRunRecord[]> {
+ const found = await deps.getScheduleStore().listScheduledRuns({ limit: 100, until: new Date() });
+ return found.filter(run => run.schedule_id === scheduleId);
+ }
+
+ /**
+ * Advances any run left ready by an earlier test.
+ */
+ async function drainScheduledRuns(): Promise<void> {
+ await dispatchScheduledRuns({
+ store: deps.getScheduleStore(),
+ withTransaction: deps.withTransaction,
+ onTriggered: () => undefined,
+ logger,
+ });
+ }
+
+ async function seedSchedule(params: {
+ status?: 'active' | 'paused';
+ scheduledFor: Date;
+ cron?: string;
+ triggeredBy?: string;
+ }): Promise<{ schedule: ScheduleRecord; run: ScheduleRunRecord }> {
+ const store = deps.getScheduleStore();
+ const agentName = await seedAgent();
+ const status = params.status ?? 'active';
+ const cron = params.cron ?? CRON;
+ const { schedule, pendingRun } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agentName,
+ name: `sched-${String(Date.now())}-${String(seq)}`,
+ manifest: manifest({ status, cron }),
+ created_by: USER,
+ // Far enough ahead so that it doesnt clash with actual test.
+ runFrom: new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000),
+ });
+ // Mark the auto-added pending run failed so the exact run can be added.
+ if (pendingRun !== undefined) {
+ await store.updateRunStatus({ tenant_id: TENANT, id: pendingRun.id, status: 'failed' });
+ }
+ const run = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: `test-${String(Date.now())}-${String(seq)}`,
+ scheduled_for: params.scheduledFor,
+ status: 'scheduled',
+ triggered_by: params.triggeredBy ?? USER,
+ });
+ return { schedule, run };
+ }
+
+ it('triggers a scheduled run and adds a next scheduled run', async () => {
+ const store = deps.getScheduleStore();
+ const pastScheduledFor = new Date(Date.now() - 60_000);
+ const { schedule, run } = await seedSchedule({
+ scheduledFor: pastScheduledFor,
+ triggeredBy: OTHER_ACTOR,
+ });
+ const triggered: ScheduleDispatchItem[] = [];
+ const before = Date.now();
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: item => {
+ expect(item.run.status).toBe('scheduled');
+ triggered.push(item);
+ },
+ logger,
+ });
+ const after = Date.now();
+
+ expect(result).toEqual({ dispatched: 1, failed: 0 });
+ expect(triggered).toHaveLength(1);
+ expect(triggered[0]?.run.id).toBe(run.id);
+ expect(triggered[0]?.schedule.id).toBe(schedule.id);
+
+ const updated = await store.getRun({ tenant_id: TENANT, id: run.id });
+ expect(updated).toEqual(
+ expect.objectContaining({
+ id: run.id,
+ status: 'triggered',
+ }),
+ );
+ expect(typeof updated?.triggered_at).toBe('string');
+
+ const next = await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id });
+ expect(next).toEqual(
+ expect.objectContaining({
+ schedule_id: schedule.id,
+ status: 'scheduled',
+ triggered_by: USER,
+ }),
+ );
+ expect(next?.id).not.toBe(run.id);
+ expectNextTriggerIso(next?.scheduled_for, before, after);
+ // Whatever the cron, the next run is never already ready to run.
+ expect(Date.parse(next?.scheduled_for ?? '')).toBeGreaterThan(before);
+ });
+
+ it('advances from now, not from the time it just ran (no backfill)', async () => {
+ const store = deps.getScheduleStore();
+ const staleSlot = new Date(Date.now() - 30 * 60_000);
+ const { schedule, run } = await seedSchedule({
+ scheduledFor: staleSlot,
+ cron: MINUTELY_CRON,
+ });
+ const before = Date.now();
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: () => undefined,
+ logger,
+ });
+ const after = Date.now();
+
+ expect(result).toEqual({ dispatched: 1, failed: 0 });
+
+ const next = await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id });
+ expect(next?.id).not.toBe(run.id);
+ expect(Date.parse(next?.scheduled_for ?? '')).toBeGreaterThan(before);
+ const candidates = new Set([
+ nextTriggerAfter({ cron: MINUTELY_CRON, timezone: TIMEZONE, from: new Date(before) }).toISOString(),
+ nextTriggerAfter({ cron: MINUTELY_CRON, timezone: TIMEZONE, from: new Date(after) }).toISOString(),
+ ]);
+ expect(next?.scheduled_for !== undefined && candidates.has(next.scheduled_for)).toBe(true);
+ });
+
+ it('marks the run failed when on error; the next scheduled run is added', async () => {
+ const store = deps.getScheduleStore();
+ const pastScheduledFor = new Date(Date.now() - 60_000);
+ const { schedule, run } = await seedSchedule({ scheduledFor: pastScheduledFor });
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: () => {
+ throw new Error('executor unavailable');
+ },
+ logger,
+ });
+
+ expect(result).toEqual({ dispatched: 0, failed: 1 });
+
+ const updated = await store.getRun({ tenant_id: TENANT, id: run.id });
+ expect(updated).toEqual(
+ expect.objectContaining({
+ id: run.id,
+ status: 'failed',
+ }),
+ );
+
+ const next = await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id });
+ expect(next).toEqual(
+ expect.objectContaining({
+ schedule_id: schedule.id,
+ status: 'scheduled',
+ }),
+ );
+ expect(next?.id).not.toBe(run.id);
+ });
+
+ it('runs an existing row on a paused schedule, but adds no next run', async () => {
+ const store = deps.getScheduleStore();
+ const { schedule, run } = await seedSchedule({
+ status: 'paused',
+ scheduledFor: new Date(Date.now() - 60_000),
+ });
+ const triggered: ScheduleDispatchItem[] = [];
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: item => {
+ triggered.push(item);
+ },
+ logger,
+ });
+
+ // `paused` withholds the advance; it never cancels a row that already exists.
+ expect(result).toEqual({ dispatched: 1, failed: 0 });
+ expect(triggered.map(item => item.run.id)).toEqual([run.id]);
+ const updated = await store.getRun({ tenant_id: TENANT, id: run.id });
+ expect(updated).toEqual(expect.objectContaining({ id: run.id, status: 'triggered' }));
+ expect(typeof updated?.triggered_at).toBe('string');
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ });
+
+ it('adds the next run from the cron when cron is updated', async () => {
+ const store = deps.getScheduleStore();
+ const pastScheduledFor = new Date(Date.now() - 60_000);
+ const { schedule, run } = await seedSchedule({ scheduledFor: pastScheduledFor });
+ const newCron = '15 * * * *';
+ const before = Date.now();
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: async item => {
+ const updated = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: item.schedule.id,
+ name: item.schedule.name,
+ manifest: manifest({ cron: newCron }),
+ runFrom: new Date(),
+ });
+ expect(updated).toBeDefined();
+ },
+ logger,
+ });
+ const after = Date.now();
+
+ expect(result).toEqual({ dispatched: 1, failed: 0 });
+ expect(await store.getRun({ tenant_id: TENANT, id: run.id })).toBeUndefined();
+
+ const next = await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id });
+ expect(next).toEqual(
+ expect.objectContaining({
+ schedule_id: schedule.id,
+ status: 'scheduled',
+ }),
+ );
+ const newCandidates = new Set([
+ nextTriggerAfter({ cron: newCron, timezone: TIMEZONE, from: new Date(before) }).toISOString(),
+ nextTriggerAfter({ cron: newCron, timezone: TIMEZONE, from: new Date(after) }).toISOString(),
+ ]);
+ expect(next?.scheduled_for !== undefined && newCandidates.has(next.scheduled_for)).toBe(true);
+
+ const oldCandidates = new Set([
+ nextTriggerAfter({ cron: CRON, timezone: TIMEZONE, from: new Date(before) }).toISOString(),
+ nextTriggerAfter({ cron: CRON, timezone: TIMEZONE, from: new Date(after) }).toISOString(),
+ ]);
+ expect(next?.scheduled_for !== undefined && oldCandidates.has(next.scheduled_for)).toBe(false);
+ });
+
+ it('pause in middle drops the pending run; a later pass does not add another', async () => {
+ const store = deps.getScheduleStore();
+ const pastScheduledFor = new Date(Date.now() - 60_000);
+ const { schedule, run } = await seedSchedule({ scheduledFor: pastScheduledFor });
+
+ const first = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: async item => {
+ expect(item.run.status).toBe('scheduled');
+ const paused = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: item.schedule.id,
+ name: item.schedule.name,
+ manifest: manifest({ status: 'paused' }),
+ runFrom: new Date(),
+ });
+ expect(paused).toBeDefined();
+ },
+ logger,
+ });
+
+ expect(first).toEqual({ dispatched: 1, failed: 0 });
+ expect(await store.getRun({ tenant_id: TENANT, id: run.id })).toBeUndefined();
+ expect(await store.getSchedule({ tenant_id: TENANT, id: schedule.id, forUpdate: false })).toEqual(
+ expect.objectContaining({ id: schedule.id, status: 'paused' }),
+ );
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ expect(await scheduledRunsFor(schedule.id)).toEqual([]);
+
+ const second = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: () => {
+ throw new Error('paused schedule must not hand off');
+ },
+ logger,
+ });
+
+ expect(second).toEqual({ dispatched: 0, failed: 0 });
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ expect(await scheduledRunsFor(schedule.id)).toEqual([]);
+ });
+
+ it("processes a whole batch oldest first, isolating one run's failure from the rest", async () => {
+ const store = deps.getScheduleStore();
+ // This test asserts on the pass result, so nothing else may be ready first.
+ await drainScheduledRuns();
+ expect(await store.listScheduledRuns({ limit: 100, until: new Date() })).toEqual([]);
+
+ const now = Date.now();
+ const thrower = await seedSchedule({ scheduledFor: new Date(now - 50 * 60_000) });
+ const healthy = await seedSchedule({ scheduledFor: new Date(now - 5 * 60_000) });
+ const handedOff: string[] = [];
+ const before = Date.now();
+
+ const result = await dispatchScheduledRuns({
+ store,
+ withTransaction: deps.withTransaction,
+ onTriggered: item => {
+ handedOff.push(item.run.id);
+ if (item.run.id === thrower.run.id) {
+ throw new Error('executor unavailable');
+ }
+ },
+ logger,
+ });
+
+ expect(result).toEqual({ dispatched: 1, failed: 1 });
+ expect(handedOff).toEqual([thrower.run.id, healthy.run.id]);
+
+ expect(await store.getRun({ tenant_id: TENANT, id: thrower.run.id })).toEqual(
+ expect.objectContaining({ status: 'failed', triggered_at: null }),
+ );
+ const healthyUpdated = await store.getRun({ tenant_id: TENANT, id: healthy.run.id });
+ expect(healthyUpdated).toEqual(expect.objectContaining({ status: 'triggered' }));
+ expect(typeof healthyUpdated?.triggered_at).toBe('string');
+
+ // Every schedule advances, whatever its run's outcome, and never onto a past time.
+ for (const seeded of [thrower, healthy]) {
+ const next = await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: seeded.schedule.id });
+ expect(next?.id).not.toBe(seeded.run.id);
+ expect(Date.parse(next?.scheduled_for ?? '')).toBeGreaterThan(before);
+ expect(await scheduledRunsFor(seeded.schedule.id)).toEqual([]);
+ }
+ });
+}
diff --git a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
new file mode 100644
index 000000000..95bf531cc
--- /dev/null
+++ b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
@@ -0,0 +1,531 @@
+import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
+import type { IAgentStore } from '../../src/db/agentStore';
+import { cronRunName, type IScheduleStore } from '../../src/db/scheduleStore';
+import { nextTriggerAfter } from '../../src/runtime/cron';
+import { ScheduleManifestSchema, type ScheduleManifest } from '../../src/schemas/schedule';
+
+const TENANT = 'default';
+const USER = 'tester';
+
+function manifest(overrides: Partial<ScheduleManifest> = {}): ScheduleManifest {
+ return ScheduleManifestSchema.parse({
+ task: 'Say hello',
+ cron: '0 13 * * 1-5',
+ timezone: 'UTC',
+ status: 'active',
+ ...overrides,
+ });
+}
+
+export function runScheduleStoreContractSuite(deps: {
+ getAgentStore: () => IAgentStore;
+ getScheduleStore: () => IScheduleStore;
+}): void {
+ async function seedAgent(): Promise<{ id: string; name: string }> {
+ const agent = await deps.getAgentStore().createAgent({
+ tenant_id: TENANT,
+ name: `agent-${String(Date.now())}-${String(Math.random()).slice(2, 8)}`,
+ manifest: AgentSpecSchema.parse({
+ model: { name: 'anthropic/claude-sonnet-4-6' },
+ instructions: 'Be helpful.',
+ }),
+ });
+ return { id: agent.id, name: agent.name };
+ }
+
+ it('create active schedule adds a pending run for the next cron trigger', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const runFrom = new Date('2026-08-27T10:00:00.000Z');
+ const m = manifest({ cron: '0 13 * * *', timezone: 'UTC' });
+
+ const { schedule, pendingRun } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'daily',
+ manifest: m,
+ created_by: USER,
+ runFrom,
+ });
+
+ expect(pendingRun).toEqual(
+ expect.objectContaining({
+ schedule_id: schedule.id,
+ status: 'scheduled',
+ triggered_by: USER,
+ scheduled_for: nextTriggerAfter({ cron: m.cron, timezone: m.timezone, from: runFrom }).toISOString(),
+ }),
+ );
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toEqual(pendingRun);
+ });
+
+ it('create paused leaves no pending run', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule, pendingRun } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'paused-at-create',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+
+ expect(pendingRun).toBeUndefined();
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ });
+
+ it('pause drops the pending run; resume re adds a pending run from the new now', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'toggle',
+ manifest: manifest({ cron: '0 * * * *', timezone: 'UTC' }),
+ created_by: USER,
+ runFrom: new Date('2026-08-27T10:15:00.000Z'),
+ });
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeDefined();
+
+ const paused = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: schedule.id,
+ name: 'toggle',
+ manifest: manifest({ cron: '0 * * * *', timezone: 'UTC', status: 'paused' }),
+ runFrom: new Date('2026-08-27T10:15:00.000Z'),
+ });
+ expect(paused).toBeDefined();
+ expect(paused?.pendingRun).toBeUndefined();
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+
+ const resumeFrom = new Date('2026-08-27T11:30:00.000Z');
+ const resumed = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: schedule.id,
+ name: 'toggle',
+ manifest: manifest({ cron: '0 * * * *', timezone: 'UTC', status: 'active' }),
+ runFrom: resumeFrom,
+ });
+ expect(resumed?.pendingRun?.scheduled_for).toBe(
+ nextTriggerAfter({ cron: '0 * * * *', timezone: 'UTC', from: resumeFrom }).toISOString(),
+ );
+ });
+
+ it('updating cron while active replaces the pending run with a new trigger time', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const runFrom = new Date('2026-08-27T08:00:00.000Z');
+ const { schedule, pendingRun: first } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'reclock',
+ manifest: manifest({ cron: '0 9 * * *', timezone: 'UTC' }),
+ created_by: USER,
+ runFrom,
+ });
+ expect(first?.scheduled_for).toBe(
+ nextTriggerAfter({ cron: '0 9 * * *', timezone: 'UTC', from: runFrom }).toISOString(),
+ );
+
+ const updated = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: schedule.id,
+ name: 'reclock',
+ manifest: manifest({ cron: '0 17 * * *', timezone: 'UTC' }),
+ runFrom,
+ });
+ expect(updated?.pendingRun?.id).not.toBe(first?.id);
+ expect(updated?.pendingRun?.scheduled_for).toBe(
+ nextTriggerAfter({ cron: '0 17 * * *', timezone: 'UTC', from: runFrom }).toISOString(),
+ );
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toEqual(
+ updated?.pendingRun,
+ );
+ });
+
+ it('updating name or task leaves the pending run unchanged', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const runFrom = new Date('2026-08-27T08:00:00.000Z');
+ const { schedule, pendingRun: first } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'label-only',
+ manifest: manifest({ cron: '0 9 * * *', timezone: 'UTC', task: 'old task' }),
+ created_by: USER,
+ runFrom,
+ });
+ expect(first).toBeDefined();
+
+ // A later runFrom would move the next trigger time if sync ran; it must not.
+ const updated = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: schedule.id,
+ name: 'renamed',
+ manifest: manifest({ cron: '0 9 * * *', timezone: 'UTC', task: 'new task' }),
+ runFrom: new Date('2026-08-27T12:00:00.000Z'),
+ });
+
+ expect(updated?.schedule.name).toBe('renamed');
+ expect(updated?.schedule.manifest.task).toBe('new task');
+ expect(updated?.pendingRun).toEqual(first);
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toEqual(first);
+ });
+
+ it('updating cron while paused leaves no pending run', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'paused-edit',
+ manifest: manifest({ status: 'paused', cron: '0 9 * * *' }),
+ created_by: USER,
+ runFrom: new Date('2026-08-27T08:00:00.000Z'),
+ });
+
+ const updated = await store.updateScheduleAndRun({
+ tenant_id: TENANT,
+ id: schedule.id,
+ name: 'paused-edit',
+ manifest: manifest({ status: 'paused', cron: '0 17 * * *' }),
+ runFrom: new Date('2026-08-27T08:00:00.000Z'),
+ });
+ expect(updated?.pendingRun).toBeUndefined();
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ });
+
+ it('listScheduledRuns returns only scheduled rows with scheduled_for <= now, not triggered', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const past = new Date(Date.now() - 60_000);
+ const future = new Date(Date.now() + 3_600_000);
+
+ async function pausedSchedule(name: string) {
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name,
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+ return schedule;
+ }
+
+ const readySchedule = await pausedSchedule('ready');
+ const triggeredSchedule = await pausedSchedule('already-triggered');
+ const futureSchedule = await pausedSchedule('future');
+
+ const readyRun = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: readySchedule.id,
+ name: cronRunName(past),
+ scheduled_for: past,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+
+ const triggeredSeed = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: triggeredSchedule.id,
+ name: cronRunName(past),
+ scheduled_for: past,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+ await store.updateRunStatus({
+ tenant_id: TENANT,
+ id: triggeredSeed.id,
+ status: 'triggered',
+ });
+
+ await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: futureSchedule.id,
+ name: cronRunName(future),
+ scheduled_for: future,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+
+ // `listScheduledRuns` is deliberately unscoped — dispatch sweeps every schedule —
+ // so narrow to this test's schedules. Asserting on the raw list would couple this
+ // test to whatever pending rows its neighbours left behind.
+ const ownIds = new Set([readySchedule.id, triggeredSchedule.id, futureSchedule.id]);
+ const found = await store.listScheduledRuns({ limit: 100, until: new Date() });
+ expect(found.filter(run => ownIds.has(run.schedule_id)).map(run => run.id)).toEqual([readyRun.id]);
+ });
+
+ it('deleteSchedule removes the schedule and cascades its runs', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const past = new Date(Date.now() - 60_000);
+ const future = new Date(Date.now() + 3_600_000);
+
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'to-delete',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+
+ const historical = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(past),
+ scheduled_for: past,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+ await store.updateRunStatus({
+ tenant_id: TENANT,
+ id: historical.id,
+ status: 'triggered',
+ });
+
+ const pending = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(future),
+ scheduled_for: future,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+
+ await store.deleteSchedule({ tenant_id: TENANT, id: schedule.id });
+
+ expect(await store.getSchedule({ tenant_id: TENANT, id: schedule.id, forUpdate: false })).toBeUndefined();
+ expect(await store.getRun({ tenant_id: TENANT, id: historical.id })).toBeUndefined();
+ expect(await store.getRun({ tenant_id: TENANT, id: pending.id })).toBeUndefined();
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ });
+
+ it('creating a schedule for an unknown agent fails', async () => {
+ const store = deps.getScheduleStore();
+ await expect(
+ store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: 'no-such-agent',
+ name: 'orphan',
+ manifest: manifest(),
+ created_by: USER,
+ runFrom: new Date(),
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('deleting an agent cascades its schedules and runs', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule, pendingRun } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'bound-to-agent',
+ manifest: manifest({ cron: '0 * * * *', timezone: 'UTC' }),
+ created_by: USER,
+ runFrom: new Date('2026-08-27T10:00:00.000Z'),
+ });
+ expect(pendingRun).toBeDefined();
+
+ await deps.getAgentStore().deleteAgent({ tenant_id: TENANT, id: agent.id });
+
+ expect(await store.getSchedule({ tenant_id: TENANT, id: schedule.id, forUpdate: false })).toBeUndefined();
+ expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toBeUndefined();
+ if (pendingRun === undefined) {
+ throw new Error('expected pending run before agent delete');
+ }
+ expect(await store.getRun({ tenant_id: TENANT, id: pendingRun.id })).toBeUndefined();
+ });
+
+ it('rejects a second schedule_run with the same name on one schedule', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'name-unique',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+
+ const triggersAt = new Date('2026-08-27T12:00:00.000Z');
+ const first = await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(triggersAt),
+ scheduled_for: triggersAt,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+ await store.updateRunStatus({ tenant_id: TENANT, id: first.id, status: 'triggered' });
+
+ await expect(
+ store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(triggersAt),
+ scheduled_for: triggersAt,
+ status: 'scheduled',
+ triggered_by: USER,
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('rejects a second pending schedule_run for the same schedule', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'one-pending',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+
+ const firstSlot = new Date('2026-08-27T12:00:00.000Z');
+ const secondSlot = new Date('2026-08-27T13:00:00.000Z');
+ await store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(firstSlot),
+ scheduled_for: firstSlot,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+
+ await expect(
+ store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(secondSlot),
+ scheduled_for: secondSlot,
+ status: 'scheduled',
+ triggered_by: USER,
+ }),
+ ).rejects.toThrow();
+ });
+
+ it('listSchedules returns newest first and filters by agent_name', async () => {
+ const store = deps.getScheduleStore();
+ const agentA = await seedAgent();
+ const agentB = await seedAgent();
+
+ const older = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agentA.name,
+ name: 'list-older',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+ // Distinct `created_at` so newest-first order is stable.
+ await new Promise(resolve => setTimeout(resolve, 5));
+ const newer = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agentA.name,
+ name: 'list-newer',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+ await new Promise(resolve => setTimeout(resolve, 5));
+ const otherAgent = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agentB.name,
+ name: 'list-other-agent',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ 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 forB = await store.listSchedules({ tenant_id: TENANT, agent_name: agentB.name });
+ expect(forB.map(row => row.id)).toEqual([otherAgent.schedule.id]);
+
+ const all = await store.listSchedules({ tenant_id: TENANT });
+ expect(all.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);
+ expect(indexNewer).toBeGreaterThanOrEqual(0);
+ expect(indexOlder).toBeGreaterThanOrEqual(0);
+ expect(indexNewer).toBeLessThan(indexOlder);
+ });
+
+ it('updateRunStatus stamps triggered_at only for triggered; returns undefined when gone', async () => {
+ const store = deps.getScheduleStore();
+ const agent = await seedAgent();
+ const { schedule } = await store.createScheduleAndRun({
+ tenant_id: TENANT,
+ agent_name: agent.name,
+ name: 'run-status',
+ manifest: manifest({ status: 'paused' }),
+ created_by: USER,
+ runFrom: new Date(),
+ });
+
+ async function seedScheduled(triggersAt: Date) {
+ return store.createRun({
+ tenant_id: TENANT,
+ schedule_id: schedule.id,
+ name: cronRunName(triggersAt),
+ scheduled_for: triggersAt,
+ status: 'scheduled',
+ triggered_by: USER,
+ });
+ }
+
+ const toTrigger = await seedScheduled(new Date('2026-08-27T10:00:00.000Z'));
+ expect(toTrigger.triggered_at).toBeNull();
+ const triggered = await store.updateRunStatus({
+ tenant_id: TENANT,
+ id: toTrigger.id,
+ status: 'triggered',
+ });
+ expect(triggered).toEqual(
+ expect.objectContaining({
+ id: toTrigger.id,
+ status: 'triggered',
+ }),
+ );
+ if (triggered === undefined) {
+ throw new Error('expected triggered run');
+ }
+ expect(typeof triggered.triggered_at).toBe('string');
+ expect(triggered.triggered_at).not.toBeNull();
+
+ // Pending unique allows only one scheduled row — finish triggered before seeding failed.
+ const toFail = await seedScheduled(new Date('2026-08-27T12:00:00.000Z'));
+ const failed = await store.updateRunStatus({
+ tenant_id: TENANT,
+ id: toFail.id,
+ status: 'failed',
+ });
+ expect(failed).toEqual(
+ expect.objectContaining({
+ id: toFail.id,
+ status: 'failed',
+ triggered_at: null,
+ }),
+ );
+
+ await store.deleteSchedule({ tenant_id: TENANT, id: schedule.id });
+ expect(
+ await store.updateRunStatus({
+ tenant_id: TENANT,
+ id: triggered.id,
+ status: 'failed',
+ }),
+ ).toBeUndefined();
+ });
+}
diff --git a/packages/trueforge/tests/db/sqlite/schedule-store/contract.test.ts b/packages/trueforge/tests/db/sqlite/schedule-store/contract.test.ts
new file mode 100644
index 000000000..274258e59
--- /dev/null
+++ b/packages/trueforge/tests/db/sqlite/schedule-store/contract.test.ts
@@ -0,0 +1,21 @@
+import { SqliteAgentStore } from '../../../../src/db/sqlite/agent-store/SqliteAgentStore';
+import { SqliteScheduleStore } from '../../../../src/db/sqlite/schedule-store/SqliteScheduleStore';
+import { runScheduleStoreContractSuite } from '../../scheduleStoreContractSuite';
+import { createSqliteTestDatabase, type SqliteTestDatabase } from '../testDatabase';
+
+describe('SqliteScheduleStore (pending-run sync contract)', () => {
+ let env: SqliteTestDatabase;
+
+ beforeEach(async () => {
+ env = await createSqliteTestDatabase();
+ }, 120_000);
+
+ afterEach(async () => {
+ await env?.teardown();
+ });
+
+ runScheduleStoreContractSuite({
+ getAgentStore: () => new SqliteAgentStore(env.db),
+ getScheduleStore: () => new SqliteScheduleStore(env.db),
+ });
+});
diff --git a/packages/trueforge/tests/db/sqlite/schedule-store/dispatch.contract.test.ts b/packages/trueforge/tests/db/sqlite/schedule-store/dispatch.contract.test.ts
new file mode 100644
index 000000000..9e3d55c4f
--- /dev/null
+++ b/packages/trueforge/tests/db/sqlite/schedule-store/dispatch.contract.test.ts
@@ -0,0 +1,22 @@
+import { SqliteAgentStore } from '../../../../src/db/sqlite/agent-store/SqliteAgentStore';
+import { SqliteScheduleStore } from '../../../../src/db/sqlite/schedule-store/SqliteScheduleStore';
+import { runScheduleDispatchContractSuite } from '../../scheduleDispatchContractSuite';
+import { createSqliteTestDatabase, type SqliteTestDatabase } from '../testDatabase';
+
+describe('dispatchScheduledRuns (sqlite contract)', () => {
+ let env: SqliteTestDatabase;
+
+ beforeEach(async () => {
+ env = await createSqliteTestDatabase();
+ }, 120_000);
+
+ afterEach(async () => {
+ await env?.teardown();
+ });
+
+ runScheduleDispatchContractSuite({
+ getAgentStore: () => new SqliteAgentStore(env.db),
+ getScheduleStore: () => new SqliteScheduleStore(env.db),
+ withTransaction: callback => env.db.transaction().execute(callback),
+ });
+});
diff --git a/packages/trueforge/tests/unit/runtime/cron.test.ts b/packages/trueforge/tests/unit/runtime/cron.test.ts
new file mode 100644
index 000000000..250e4dd6a
--- /dev/null
+++ b/packages/trueforge/tests/unit/runtime/cron.test.ts
@@ -0,0 +1,95 @@
+import { minIntervalSeconds, nextTriggerAfter } from '../../../src/runtime/cron';
+import { InvalidCronError } from '../../../src/schemas/schedule';
+
+const NEW_YORK = 'America/New_York';
+
+/** 13:00 New York on weekdays — the canonical "daily briefing" schedule. */
+const WEEKDAY_1PM = { cron: '0 13 * * 1-5', timezone: NEW_YORK };
+
+/** `HH:mm` of an instant as seen in New York. */
+function localWallClock(instant: Date): string {
+ return new Intl.DateTimeFormat('en-GB', {
+ timeZone: NEW_YORK,
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ }).format(instant);
+}
+
+/** `YYYY-MM-DD` of an instant as seen in New York. */
+function localDate(instant: Date): string {
+ return new Intl.DateTimeFormat('en-CA', { timeZone: NEW_YORK, dateStyle: 'short' }).format(instant);
+}
+
+describe('nextTriggerAfter', () => {
+ it('triggers at the wall-clock time in the schedule zone, not UTC', () => {
+ // 2026-08-27 is a Thursday; EDT is UTC-4, so 13:00 local is 17:00Z.
+ const next = nextTriggerAfter({
+ ...WEEKDAY_1PM,
+ from: new Date('2026-08-27T10:00:00.000Z'),
+ });
+ expect(next.toISOString()).toBe('2026-08-27T17:00:00.000Z');
+ });
+
+ it('skips the weekend for a weekday-only expression', () => {
+ // Friday after the trigger → next is Monday.
+ const next = nextTriggerAfter({
+ ...WEEKDAY_1PM,
+ from: new Date('2026-08-28T18:00:00.000Z'),
+ });
+ expect(next.toISOString()).toBe('2026-08-31T17:00:00.000Z');
+ });
+
+ it('is strictly after `from`, so a trigger cannot land on the instant it ran', () => {
+ const triggeredAt = new Date('2026-08-27T17:00:00.000Z');
+ expect(nextTriggerAfter({ ...WEEKDAY_1PM, from: triggeredAt }).getTime()).toBeGreaterThan(triggeredAt.getTime());
+ });
+
+ it('throws for an expression that can never trigger', () => {
+ // February 30th.
+ expect(() => nextTriggerAfter({ cron: '0 0 30 2 *', timezone: 'UTC', from: new Date() })).toThrow(InvalidCronError);
+ });
+
+ describe('DST', () => {
+ it('holds the local hour across the autumn transition', () => {
+ // 2026-11-01 is the US fall-back date. EDT (UTC-4) before, EST (UTC-5) after,
+ // so the same 13:00 local trigger moves from 17:00Z to 18:00Z.
+ const before = nextTriggerAfter({
+ ...WEEKDAY_1PM,
+ from: new Date('2026-10-30T00:00:00.000Z'),
+ });
+ expect(before.toISOString()).toBe('2026-10-30T17:00:00.000Z');
+
+ const after = nextTriggerAfter({
+ ...WEEKDAY_1PM,
+ from: new Date('2026-11-02T00:00:00.000Z'),
+ });
+ expect(after.toISOString()).toBe('2026-11-02T18:00:00.000Z');
+ });
+
+ it('maps a skipped spring-forward hour onto the landing hour', () => {
+ // 2026-03-08 springs forward: 02:00–03:00 never exists in New York.
+ // cron-parser fires at 03:30 that day rather than skipping.
+ const next = nextTriggerAfter({
+ cron: '30 2 * * *',
+ timezone: NEW_YORK,
+ from: new Date('2026-03-07T12:00:00.000Z'),
+ });
+ expect(localWallClock(next)).toBe('03:30');
+ expect(localDate(next)).toBe('2026-03-08');
+ });
+ });
+});
+
+describe('minIntervalSeconds', () => {
+ it('measures an hourly expression as one hour', () => {
+ expect(minIntervalSeconds({ cron: '0 * * * *', timezone: 'UTC' }, new Date('2026-08-27T00:00:00.000Z'))).toBe(3600);
+ });
+
+ it('reports the tightest gap, not the nominal one', () => {
+ // 09:00 and 09:30 daily: mostly ~23.5h apart, but 30 minutes once a day.
+ expect(minIntervalSeconds({ cron: '0,30 9 * * *', timezone: 'UTC' }, new Date('2026-08-27T00:00:00.000Z'))).toBe(
+ 1800,
+ );
+ });
+});
diff --git a/packages/trueforge/tests/unit/schemas/schedule.test.ts b/packages/trueforge/tests/unit/schemas/schedule.test.ts
new file mode 100644
index 000000000..51c6f12dd
--- /dev/null
+++ b/packages/trueforge/tests/unit/schemas/schedule.test.ts
@@ -0,0 +1,58 @@
+import { validateManifest } from '../../../src/apis/schedules';
+import { CronExpressionSchema, InvalidCronError, TimezoneSchema } from '../../../src/schemas/schedule';
+
+const WEEKDAY_1PM = { cron: '0 13 * * 1-5', timezone: 'America/New_York' };
+
+describe('CronExpressionSchema', () => {
+ it('rejects a non-5-field cron', () => {
+ expect(CronExpressionSchema.safeParse('0 13 * *').success).toBe(false);
+ expect(CronExpressionSchema.safeParse('not a cron').success).toBe(false);
+ });
+
+ it('accepts a 5-field cron', () => {
+ expect(CronExpressionSchema.safeParse('0 0 * * *').success).toBe(true);
+ });
+});
+
+describe('TimezoneSchema', () => {
+ it('rejects a non-IANA timezone', () => {
+ expect(TimezoneSchema.safeParse('UTC+5:30').success).toBe(false);
+ expect(TimezoneSchema.safeParse('Not/A_Zone').success).toBe(false);
+ });
+
+ it('accepts a valid IANA timezone', () => {
+ expect(TimezoneSchema.safeParse('America/New_York').success).toBe(true);
+ });
+});
+
+describe('validateManifest', () => {
+ it('accepts the minimum interval', () => {
+ expect(() => {
+ validateManifest({ cron: '0 * * * *', timezone: 'UTC' });
+ }).not.toThrow();
+ });
+
+ it('accepts a daily schedule', () => {
+ expect(() => {
+ validateManifest(WEEKDAY_1PM);
+ }).not.toThrow();
+ });
+
+ it('accepts a yearly cron', () => {
+ expect(() => {
+ validateManifest({ cron: '0 0 1 1 *', timezone: 'UTC' }, new Date('2026-08-27T12:00:00.000Z'));
+ }).not.toThrow();
+ });
+
+ it('rejects a cron tighter than one hour', () => {
+ expect(() => {
+ validateManifest({ cron: '*/5 * * * *', timezone: 'UTC' });
+ }).toThrow(InvalidCronError);
+ });
+
+ it('rejects a back-dated cron with no upcoming trigger time', () => {
+ expect(() => {
+ validateManifest({ cron: '0 0 30 2 *', timezone: 'UTC' });
+ }).toThrow(InvalidCronError);
+ });
+});
diff --git a/packages/trueforge/tsup.config.ts b/packages/trueforge/tsup.config.ts
index 6156c2f75..49c0fe815 100644
--- a/packages/trueforge/tsup.config.ts
+++ b/packages/trueforge/tsup.config.ts
@@ -36,6 +36,7 @@ export default defineConfig([
...shared,
entry: {
main: 'src/main.ts',
+ controller: 'src/controller.ts',
// Emit both engines under dist/{postgres,sqlite}/migrations/.
// Runtime selects migrations via STANDALONE (false → postgres, true → sqlite).
...migrationEntries('postgres'),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7a5eb34ab..f007777d0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -138,6 +138,9 @@ importers:
better-sqlite3:
specifier: ^13.0.3
version: 13.0.3
+ cron-parser:
+ specifier: ^5.4.0
+ version: 5.10.0
env-paths:
specifier: ^4.0.0
version: 4.0.0
@@ -4356,6 +4359,10 @@ packages:
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
hasBin: true
+ resolution: {integrity: sha512-izNAxJyRWUP8ljBoDSub5WyrVOUlT4SLGShswE7eoRBpp6QUsSycYxLBMJlbshgPBMcPT/nrfgjNY2918ayv2A==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -5670,6 +5677,10 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
@@ -11556,6 +11567,10 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ luxon: 3.7.2
+
dependencies:
path-key: 3.1.1
@@ -13247,6 +13262,8 @@ snapshots:
dependencies:
react: 19.2.8
+