Skip to content

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

[Authz 6/6] Add internal endpoint for schedule execution w/ Trueforge Service Key (#627)

Chirag Jain4b120b867d47
diff --git a/.changeset/20260908071001-regenerate-sdk-from-openapi.md b/.changeset/20260908071001-regenerate-sdk-from-openapi.md
new file mode 100644
index 000000000..efd8ff00f
--- /dev/null
+++ b/.changeset/20260908071001-regenerate-sdk-from-openapi.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-sdk": patch
+---
+
+Regenerate SDK from updated OpenAPI spec.
diff --git a/.changeset/pre/interactive-turn-vend-token.md b/.changeset/pre/interactive-turn-vend-token.md
new file mode 100644
index 000000000..11e43da3e
--- /dev/null
+++ b/.changeset/pre/interactive-turn-vend-token.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge': patch
+---
+
+Use agent-scoped tokens for saved-agent turns in TrueFoundry mode while inline turns keep using the caller token.
diff --git a/.changeset/scheduled-turn-agent-token.md b/.changeset/scheduled-turn-agent-token.md
new file mode 100644
index 000000000..1e8e17eef
--- /dev/null
+++ b/.changeset/scheduled-turn-agent-token.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": minor
+---
+
+Schedule runs now execute through one internal API call authenticated with `TRUEFORGE_API_KEY`. The server loads the saved run, schedule, and agent, then uses one agent-scoped token for turn resources in TrueFoundry mode.
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index badb0e299..9958bc81f 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1228,6 +1228,21 @@
},
"type": "object"
},
+ "ExecuteScheduleRunRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "schedule_run_id": {
+ "description": "Immutable schedule run identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "schedule_run_id"
+ ],
+ "type": "object"
+ },
"ExtendedChunkDeltaToolCall": {
"allOf": [
{
@@ -5951,6 +5966,65 @@
"x-fern-sdk-method-name": "get_meters"
}
},
+ "/api/internal/schedules/runs/execute": {
+ "post": {
+ "description": "Execute a persisted schedule run using its saved schedule and agent.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ExecuteScheduleRunRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "Run executed or already has a turn."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid service credential."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Run, schedule, or agent not found."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The run cannot be executed."
+ }
+ },
+ "summary": "Execute a schedule run",
+ "tags": [
+ "Internal"
+ ],
+ "x-fern-sdk-group-name": [
+ "internal",
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "execute_run"
+ }
+ },
"/api/internal/sessions/get-or-create-by-external-id": {
"post": {
"description": "Idempotent get-or-create: returns the existing session for this `external_id`, or creates one",
diff --git a/docs/openapi.json b/docs/openapi.json
index badb0e299..9958bc81f 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1228,6 +1228,21 @@
},
"type": "object"
},
+ "ExecuteScheduleRunRequest": {
+ "additionalProperties": false,
+ "properties": {
+ "schedule_run_id": {
+ "description": "Immutable schedule run identifier.",
+ "maxLength": 64,
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "schedule_run_id"
+ ],
+ "type": "object"
+ },
"ExtendedChunkDeltaToolCall": {
"allOf": [
{
@@ -5951,6 +5966,65 @@
"x-fern-sdk-method-name": "get_meters"
}
},
+ "/api/internal/schedules/runs/execute": {
+ "post": {
+ "description": "Execute a persisted schedule run using its saved schedule and agent.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ExecuteScheduleRunRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "Run executed or already has a turn."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid service credential."
+ },
+ "404": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Run, schedule, or agent not found."
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "The run cannot be executed."
+ }
+ },
+ "summary": "Execute a schedule run",
+ "tags": [
+ "Internal"
+ ],
+ "x-fern-sdk-group-name": [
+ "internal",
+ "schedules"
+ ],
+ "x-fern-sdk-method-name": "execute_run"
+ }
+ },
"/api/internal/sessions/get-or-create-by-external-id": {
"post": {
"description": "Idempotent get-or-create: returns the existing session for this `external_id`, or creates one",
diff --git a/packages/trueforge-sdk/package.json b/packages/trueforge-sdk/package.json
index 04e716c66..3bbddba7d 100644
--- a/packages/trueforge-sdk/package.json
+++ b/packages/trueforge-sdk/package.json
@@ -198,6 +198,17 @@
},
"default": "./dist/cjs/api/resources/internal/resources/metrics/exports.js"
},
+ "./internal/schedules": {
+ "import": {
+ "types": "./dist/esm/api/resources/internal/resources/schedules/exports.d.mts",
+ "default": "./dist/esm/api/resources/internal/resources/schedules/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/internal/resources/schedules/exports.d.ts",
+ "default": "./dist/cjs/api/resources/internal/resources/schedules/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/internal/resources/schedules/exports.js"
+ },
"./internal/sessions": {
"import": {
"types": "./dist/esm/api/resources/internal/resources/sessions/exports.d.mts",
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index d35811b24..31ba5882c 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -2891,6 +2891,72 @@ await client.internal.metrics.getMeters({
</dl>
+</dd>
+</dl>
+</details>
+
+## Internal Schedules
+<details><summary><code>client.internal.schedules.<a href="/src/api/resources/internal/resources/schedules/client/Client.ts">executeRun</a>({ ...params }) -> void</code></summary>
+<dl>
+<dd>
+
+#### πŸ“ Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Execute a persisted schedule run using its saved schedule and agent.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### πŸ”Œ Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.internal.schedules.executeRun({
+ scheduleRunId: "schedule_run_id"
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### βš™οΈ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.internal.ExecuteScheduleRunRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `SchedulesClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
</dd>
</dl>
</details>
diff --git a/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts b/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts
index d47c23433..354019f9e 100644
--- a/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts
@@ -11,6 +11,7 @@ import * as serializers from "../../../../serialization/index.js";
import * as TrueForge from "../../../index.js";
import { AgentsClient } from "../resources/agents/client/Client.js";
import { MetricsClient } from "../resources/metrics/client/Client.js";
+import { SchedulesClient } from "../resources/schedules/client/Client.js";
import { SessionsClient } from "../resources/sessions/client/Client.js";
export declare namespace InternalClient {
@@ -22,6 +23,7 @@ export declare namespace InternalClient {
export class InternalClient {
protected readonly _options: NormalizedClientOptionsWithAuth<InternalClient.Options>;
protected _metrics: MetricsClient | undefined;
+ protected _schedules: SchedulesClient | undefined;
protected _sessions: SessionsClient | undefined;
protected _agents: AgentsClient | undefined;
@@ -33,6 +35,10 @@ export class InternalClient {
return (this._metrics ??= new MetricsClient(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/internal/resources/index.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/index.ts
index 18d24fb89..3482fad64 100644
--- a/packages/trueforge-sdk/src/api/resources/internal/resources/index.ts
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/index.ts
@@ -2,5 +2,7 @@ export * from "./agents/client/requests/index.js";
export * as agents from "./agents/index.js";
export * from "./metrics/client/requests/index.js";
export * as metrics from "./metrics/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";
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/Client.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/Client.ts
new file mode 100644
index 000000000..a1714b16f
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/Client.ts
@@ -0,0 +1,141 @@
+// 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);
+ }
+
+ /**
+ * Execute a persisted schedule run using its saved schedule and agent.
+ *
+ * @param {TrueForge.internal.ExecuteScheduleRunRequest} request
+ * @param {SchedulesClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link TrueForge.NotFoundError}
+ * @throws {@link TrueForge.UnprocessableEntityError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.internal.schedules.executeRun({
+ * scheduleRunId: "schedule_run_id"
+ * })
+ */
+ public executeRun(
+ request: TrueForge.internal.ExecuteScheduleRunRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): core.HttpResponsePromise<void> {
+ return core.HttpResponsePromise.fromPromise(this.__executeRun(request, requestOptions));
+ }
+
+ private async __executeRun(
+ request: TrueForge.internal.ExecuteScheduleRunRequest,
+ requestOptions?: SchedulesClient.RequestOptions,
+ ): Promise<core.WithRawResponse<void>> {
+ 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/internal/schedules/runs/execute",
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.internal.ExecuteScheduleRunRequest.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: undefined, 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,
+ );
+ 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 422:
+ throw new TrueForge.UnprocessableEntityError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "POST",
+ "/api/internal/schedules/runs/execute",
+ );
+ }
+}
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/index.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts
new file mode 100644
index 000000000..ca6379314
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts
@@ -0,0 +1,12 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/**
+ * @example
+ * {
+ * scheduleRunId: "schedule_run_id"
+ * }
+ */
+export interface ExecuteScheduleRunRequest {
+ /** Immutable schedule run identifier. */
+ scheduleRunId: string;
+}
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/index.ts
new file mode 100644
index 000000000..4cf7d454e
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/client/requests/index.ts
@@ -0,0 +1 @@
+export type { ExecuteScheduleRunRequest } from "./ExecuteScheduleRunRequest.js";
diff --git a/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/exports.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/exports.ts
new file mode 100644
index 000000000..75e4547ce
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/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/internal/resources/schedules/index.ts b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/resources/schedules/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/index.ts
index e34ab841f..8a1a831cb 100644
--- a/packages/trueforge-sdk/src/serialization/resources/internal/resources/index.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/index.ts
@@ -1,2 +1,4 @@
+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";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts
new file mode 100644
index 000000000..058e4085f
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/ExecuteScheduleRunRequest.ts
@@ -0,0 +1,18 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../../../../api/index.js";
+import * as core from "../../../../../../../core/index.js";
+import type * as serializers from "../../../../../../index.js";
+
+export const ExecuteScheduleRunRequest: core.serialization.Schema<
+ serializers.internal.ExecuteScheduleRunRequest.Raw,
+ TrueForge.internal.ExecuteScheduleRunRequest
+> = core.serialization.object({
+ scheduleRunId: core.serialization.property("schedule_run_id", core.serialization.string()),
+});
+
+export declare namespace ExecuteScheduleRunRequest {
+ export interface Raw {
+ schedule_run_id: string;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/index.ts
new file mode 100644
index 000000000..fc9973163
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/client/requests/index.ts
@@ -0,0 +1 @@
+export { ExecuteScheduleRunRequest } from "./ExecuteScheduleRunRequest.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/index.ts
new file mode 100644
index 000000000..914b8c3c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/resources/schedules/index.ts
@@ -0,0 +1 @@
+export * from "./client/index.js";
diff --git a/packages/trueforge-sdk/tests/wire/internal/schedules.test.ts b/packages/trueforge-sdk/tests/wire/internal/schedules.test.ts
new file mode 100644
index 000000000..b6c6339a6
--- /dev/null
+++ b/packages/trueforge-sdk/tests/wire/internal/schedules.test.ts
@@ -0,0 +1,92 @@
+// 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("execute_run (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { schedule_run_id: "schedule_run_id" };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/schedules/runs/execute")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .build();
+
+ const response = await client.internal.schedules.executeRun({
+ scheduleRunId: "schedule_run_id",
+ });
+ expect(response).toEqual(undefined);
+ });
+
+ test("execute_run (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { schedule_run_id: "x" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/schedules/runs/execute")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(401)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.internal.schedules.executeRun({
+ scheduleRunId: "x",
+ });
+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
+ });
+
+ test("execute_run (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { schedule_run_id: "x" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/schedules/runs/execute")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.internal.schedules.executeRun({
+ scheduleRunId: "x",
+ });
+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);
+ });
+
+ test("execute_run (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { schedule_run_id: "x" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/schedules/runs/execute")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(422)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.internal.schedules.executeRun({
+ scheduleRunId: "x",
+ });
+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
+ });
+});
diff --git a/packages/trueforge/.env.example b/packages/trueforge/.env.example
index 1dccca6ff..dd2e4f184 100644
--- a/packages/trueforge/.env.example
+++ b/packages/trueforge/.env.example
@@ -124,12 +124,15 @@ REDIS_URL=redis://localhost:6379
## strips it (e.g. https://host/custom/proxy/path β†’ assets/API/routes under /custom/proxy/path).
# PUBLIC_BASE_URL=http://localhost:3000
-## Base URL the dedicated controller process (dist/controller-main.js) uses to
-## reach the server API. Only used when running the controller as its own process
-## (STANDALONE=false). Defaults to http://localhost:$PORT; point it at the server
-## Service in a split server/controller deployment.
+## Base URL the controller uses to reach the server API (HTTP schedule handoff).
+## Dedicated controller (STANDALONE=false) and standalone loopback both use this.
+## Defaults to http://localhost:$PORT; point it at the server Service in a split deployment.
# SERVER_URL=http://localhost:8790
+## Service credential for controller β†’ /api/internal/schedules.
+## Required when STANDALONE=false. Standalone defaults to `trueforge-standalone` (local only).
+# TRUEFORGE_API_KEY=
+
## ---------------------------------------------------------------------------
## MCP knobs.
## ---------------------------------------------------------------------------
diff --git a/packages/trueforge/jest.store.postgres.config.cjs b/packages/trueforge/jest.store.postgres.config.cjs
index 15bff1310..2879c1232 100644
--- a/packages/trueforge/jest.store.postgres.config.cjs
+++ b/packages/trueforge/jest.store.postgres.config.cjs
@@ -22,7 +22,8 @@ module.exports = {
'^@truefoundry/trueforge-core/core$': '<rootDir>/../trueforge-core/src/core/index.ts',
'^@truefoundry/trueforge-core/core/(.*)$': '<rootDir>/../trueforge-core/src/core/$1',
},
- transformIgnorePatterns: ['/node_modules/(?!.*kysely)'],
+ // App modules (e.g. scheduleDispatch β†’ config β†’ env-paths) pull ESM packages under pnpm.
+ transformIgnorePatterns: [],
testTimeout: 120_000,
maxWorkers: '50%',
roots: ['<rootDir>/tests/db', '<rootDir>/src'],
diff --git a/packages/trueforge/jest.store.sqlite.config.cjs b/packages/trueforge/jest.store.sqlite.config.cjs
index b9e0eff78..5d5beb855 100644
--- a/packages/trueforge/jest.store.sqlite.config.cjs
+++ b/packages/trueforge/jest.store.sqlite.config.cjs
@@ -21,7 +21,8 @@ module.exports = {
'^@truefoundry/trueforge-core/core$': '<rootDir>/../trueforge-core/src/core/index.ts',
'^@truefoundry/trueforge-core/core/(.*)$': '<rootDir>/../trueforge-core/src/core/$1',
},
- transformIgnorePatterns: ['/node_modules/(?!.*kysely)'],
+ // App modules (e.g. scheduleDispatch β†’ config β†’ env-paths) pull ESM packages under pnpm.
+ transformIgnorePatterns: [],
testTimeout: 120_000,
maxWorkers: '50%',
roots: ['<rootDir>/tests/db', '<rootDir>/src'],
diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts
index 5628637d1..69c19657d 100644
--- a/packages/trueforge/scripts/write-openapi.ts
+++ b/packages/trueforge/scripts/write-openapi.ts
@@ -63,25 +63,28 @@ const db = createSqliteDb(':memory:');
const tokenStore = new SqliteOAuthTokenStore(db);
const agentStore = new SqliteAgentStore(db);
const skillStore = new SqliteSkillStore(db);
+const sandboxProviderStore = new SqliteSandboxProviderStore(db);
const app = createServerApp({
modelCatalog: ModelCatalog.load(),
- resolveModelProviderStore: () => new SqliteModelProviderStore(db),
- withTransaction: callback => db.transaction().execute(callback),
mcpCatalog: McpCatalog.load(),
+ skillCatalog: SkillCatalog.load(),
+ sandboxCatalog: SandboxCatalog.load(),
+ resolveModelProviderStore: () => new SqliteModelProviderStore(db),
resolveMcpServerStore: () =>
new McpServerWithAuthStore({
store: new SqliteMcpServerStore(db),
tokenStore,
clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
}),
- tokenStore,
- skillCatalog: SkillCatalog.load(),
resolveSkillStore: () => skillStore,
- sandboxCatalog: SandboxCatalog.load(),
- resolveSandboxProviderStore: () => new SqliteSandboxProviderStore(db),
+ resolveSandboxProviderStore: () => sandboxProviderStore,
resolveAgentStore: () => agentStore,
resolveImportAgentStore: () => agentStore,
+ agentStore,
+ turnSkillsResolverStore: skillStore,
+ withTransaction: callback => db.transaction().execute(callback),
scheduleStore: new SqliteScheduleStore(db),
+ tokenStore,
sessionStore,
sessionMetricsStore: new SqliteSessionMetricsStore(db),
sessions: new Sessions({ sessionStore }),
diff --git a/packages/trueforge/src/apis/schedules.ts b/packages/trueforge/src/apis/schedules.ts
index 1953659e7..da3dcc62d 100644
--- a/packages/trueforge/src/apis/schedules.ts
+++ b/packages/trueforge/src/apis/schedules.ts
@@ -2,31 +2,56 @@
* Schedules API (mounted at /api/v1/schedules).
*/
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
-import { InvalidPageTokenError, type Sessions } from '@truefoundry/trueforge-core/agent-session';
+import {
+ InvalidPageTokenError,
+ type Sessions,
+ type TurnStreamingEvent,
+} from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
+import type { Logger } from 'winston';
import type { Authorizer } from '../auth/authorizer';
-import { createdBySubjectFromRequestContext, type RequestContext, type ResolveRequestContext } from '../auth/identity';
-import { ScheduleAgentNotFoundError, scheduleRunFailureReason, startScheduleRun } from '../controller/scheduleDispatch';
+import {
+ createdBySubjectFromRequestContext,
+ requestContextFromCreatedBySubject,
+ type RequestContext,
+ type ResolveRequestContext,
+} from '../auth/identity';
+import {
+ loadScheduleDispatchItem,
+ ScheduleAgentNotFoundError,
+ ScheduleNotFoundError,
+ scheduleRunFailureReason,
+ ScheduleRunNotFoundError,
+ startScheduleRun,
+} from '../controller/scheduleDispatch';
import type { AgentRecord, IAgentStore } from '../db/agentStore';
+import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';
+import type { IModelProviderStore } from '../db/modelProviderStore';
+import type { ISandboxProviderStore } from '../db/sandboxProviderStore';
import {
manualRunName,
ScheduleNameConflictError,
ScheduleRunConflictError,
type IScheduleStore,
+ type ScheduleDispatchItem,
type ScheduleRecord,
type ScheduleRunRecord,
} from '../db/scheduleStore';
+import type { ISkillStore } from '../db/skillStore';
import type { WithTransaction } from '../db/transaction';
import {
createScheduleRoute,
createScheduleRunRoute,
deleteScheduleRoute,
+ executeScheduleRunRoute,
getScheduleRoute,
listScheduleRunsRoute,
listSchedulesRoute,
putScheduleRoute,
} from '../routes/scheduleRoutes';
+import type { ActiveTurnRegistry } from '../runtime/activeTurns';
import { minIntervalSeconds, nextTriggerAfter } from '../runtime/cron';
+import type { EventSubscriptionRegistry } from '../runtime/event-subscription';
import {
InvalidCronError,
SCHEDULE_MIN_INTERVAL_SECONDS,
@@ -35,18 +60,67 @@ import {
type ScheduleRun,
} from '../schemas/schedule';
import { agentIfAccessible, canReadAgentBoundResource, resolveManagedAgentIds } from './agentAccess';
-import { getTurnExecutionError, startTurnInProcess, type BeginTurnExecutionDeps } from './turns';
+import { getTurnExecutionError, startTurnInProcess } from './turns';
-export interface SchedulesRouterDeps<TTransaction> {
+/** Runtime + Context store resolvers needed to start a schedule turn. */
+export interface ScheduleTurnExecutionDeps<TTransaction> {
scheduleStore: IScheduleStore<TTransaction>;
- resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
sessions: Sessions;
- resolveTurnDeps: (c: Context, runAsAgent?: AgentRecord) => BeginTurnExecutionDeps;
+ activeTurns: ActiveTurnRegistry;
+ eventSubscriptions: EventSubscriptionRegistry<TurnStreamingEvent>;
+ logger: Logger;
+ resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;
+ resolveMcpServerStore: (c: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;
+ resolveSandboxProviderStore: (c: Context) => ISandboxProviderStore<TTransaction>;
+ /** Persistence agent store (schedule agent binding is not caller-scoped). */
+ agentStore: IAgentStore<TTransaction>;
+ turnSkillsResolverStore: Pick<ISkillStore, 'resolveTurnSkills'>;
+}
+
+export interface SchedulesRouterDeps<TTransaction> extends ScheduleTurnExecutionDeps<TTransaction> {
+ resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
resolveRequestContext: ResolveRequestContext;
authorizer: Authorizer;
}
+/**
+ * Prepare and start a schedule run using Context-based store resolvers. Caller must set
+ * `request_context` (typically via {@link requestContextFromCreatedBySubject})
+ * before calling.
+ */
+export async function startScheduleRunOnRequest<TTransaction>(params: {
+ c: Context;
+ item: ScheduleDispatchItem;
+ deps: ScheduleTurnExecutionDeps<TTransaction>;
+}): Promise<void> {
+ const { c, item, deps } = params;
+ const prepared = await startScheduleRun({
+ item,
+ sessions: deps.sessions,
+ agentStore: deps.agentStore,
+ });
+ if (prepared === undefined) {
+ return;
+ }
+ await startTurnInProcess({
+ session: prepared.session,
+ input: prepared.input,
+ previous_turn_id: prepared.previous_turn_id,
+ userRef: prepared.userRef,
+ deps: {
+ activeTurns: deps.activeTurns,
+ eventSubscriptions: deps.eventSubscriptions,
+ agentStore: deps.agentStore,
+ modelProviderStore: deps.resolveModelProviderStore(c, prepared.agent),
+ mcpServerStore: deps.resolveMcpServerStore(c, prepared.agent),
+ sandboxProviderStore: deps.resolveSandboxProviderStore(c),
+ skillStore: deps.turnSkillsResolverStore,
+ logger: deps.logger,
+ },
+ });
+}
+
function toWireSchedule(record: ScheduleRecord): Schedule {
return {
id: record.id,
@@ -111,6 +185,40 @@ function isScheduleOwner(requestContext: Pick<RequestContext, 'subject'>, create
return requestContext.subject.id === created_by_subject_id;
}
+export function createScheduleExecutionRouter<TTransaction>(deps: ScheduleTurnExecutionDeps<TTransaction>) {
+ const handler: RouteHandler<typeof executeScheduleRunRoute> = async c => {
+ const { schedule_run_id: scheduleRunId } = c.req.valid('json');
+ try {
+ const item = await loadScheduleDispatchItem({
+ scheduleRunId,
+ scheduleStore: deps.scheduleStore,
+ });
+ c.set(
+ 'request_context',
+ requestContextFromCreatedBySubject({
+ tenant_id: item.schedule.tenant_id,
+ created_by_subject: item.schedule.created_by_subject,
+ }),
+ );
+ await startScheduleRunOnRequest({ c, item, deps });
+ } catch (error) {
+ if (
+ error instanceof ScheduleRunNotFoundError ||
+ error instanceof ScheduleNotFoundError ||
+ error instanceof ScheduleAgentNotFoundError
+ ) {
+ return c.json({ error: { message: error.message } }, 404);
+ }
+ throw error;
+ }
+ return c.body(null, 204);
+ };
+
+ const router = new OpenAPIHono();
+ router.openapi(executeScheduleRunRoute, handler);
+ return router;
+}
+
export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listSchedulesRoute> = async c => {
const { agent_names: agentNames, limit, page_token: pageToken, created_by_me: createdByMe } = c.req.valid('query');
@@ -229,14 +337,7 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
}
try {
- await startScheduleRun({
- item: { run, schedule },
- sessions: deps.sessions,
- agentStore: deps.resolveAgentStore(c),
- startTurn: async turnParams => {
- await startTurnInProcess({ ...turnParams, deps: deps.resolveTurnDeps(c, agent) });
- },
- });
+ await startScheduleRunOnRequest({ c, item: { run, schedule }, deps });
} catch (error) {
await deps.scheduleStore.updateRunStatus({
tenant_id: requestContext.tenant_id,
@@ -245,7 +346,11 @@ export function createSchedulesRouter<TTransaction>(deps: SchedulesRouterDeps<TT
reason: scheduleRunFailureReason(error),
});
- if (error instanceof ScheduleAgentNotFoundError) {
+ if (
+ error instanceof ScheduleRunNotFoundError ||
+ error instanceof ScheduleNotFoundError ||
+ error instanceof ScheduleAgentNotFoundError
+ ) {
return c.json({ error: { message: error.message } }, 404);
}
const turnError = getTurnExecutionError(error);
diff --git a/packages/trueforge/src/apis/skills.ts b/packages/trueforge/src/apis/skills.ts
index e98e9df61..85947d564 100644
--- a/packages/trueforge/src/apis/skills.ts
+++ b/packages/trueforge/src/apis/skills.ts
@@ -108,7 +108,8 @@ export function createAvailableSkillsRouter<TTransaction>(deps: SkillsRouterDeps
router.openapi(listSkillVersionsRoute, async c => {
const { name } = c.req.valid('query');
- return c.json({ data: await deps.resolveSkillStore(c).listSkillVersions({ name }) }, 200);
+ const skillVersions = await deps.resolveSkillStore(c).listSkillVersions({ name });
+ return c.json({ data: skillVersions }, 200);
});
return router;
diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts
index f362f9b0a..07d6e5c95 100644
--- a/packages/trueforge/src/apis/turns.ts
+++ b/packages/trueforge/src/apis/turns.ts
@@ -123,11 +123,11 @@ export interface TurnsRouterDeps {
* so TrueFoundry mode stays token-bound for models, MCP, and skills.
*/
export type BeginTurnExecutionDeps = Pick<TurnsRouterDeps, 'activeTurns' | 'eventSubscriptions' | 'logger'> & {
- skillStore: ISkillStore;
+ agentStore: IAgentStore;
modelProviderStore: IModelProviderStore;
mcpServerStore: IMcpServerWithAuthStore;
- agentStore: IAgentStore;
sandboxProviderStore: ISandboxProviderStore;
+ skillStore: Pick<ISkillStore, 'resolveTurnSkills'>;
};
/**
@@ -136,7 +136,7 @@ export type BeginTurnExecutionDeps = Pick<TurnsRouterDeps, 'activeTurns' | 'even
*/
function createTurnResolver(deps: {
mcpServerStore: IMcpServerWithAuthStore;
- skillStore: ISkillStore;
+ skillStore: Pick<ISkillStore, 'resolveTurnSkills'>;
sandboxProviderStore: ISandboxProviderStore;
agentStore: IAgentStore;
modelProviderStore: IModelProviderStore;
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index 26e9456a7..a89ecfedb 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -19,7 +19,7 @@ import { createMcpOAuthRouter } from './apis/mcpOAuth';
import { createMcpServersRouter } from './apis/mcpServers';
import { createModelsRouter } from './apis/models';
import { createPermissionsRouter } from './apis/permissions';
-import { createSchedulesRouter } from './apis/schedules';
+import { createScheduleExecutionRouter, createSchedulesRouter } from './apis/schedules';
import { createInternalMetricsRouter } from './apis/sessionMetrics';
import { createInternalSessionsRouter, createSessionsRouter } from './apis/sessions';
import { createSettingsRouter } from './apis/settings';
@@ -28,7 +28,12 @@ import { createTurnsRouter } from './apis/turns';
import type { Authenticator } from './auth/authenticator';
import type { Authorizer } from './auth/authorizer';
import { resolveRequestContext } from './auth/identity';
-import { createAdminAuthMiddleware, createAuthMiddleware, truefoundryAdminMiddleware } from './auth/middleware';
+import {
+ createAdminAuthMiddleware,
+ createApiKeyAuthMiddleware,
+ createAuthMiddleware,
+ truefoundryAdminMiddleware,
+} from './auth/middleware';
import type { McpCatalog } from './catalog/McpCatalog';
import type { ModelCatalog } from './catalog/ModelCatalog';
import type { SandboxCatalog } from './catalog/SandboxCatalog';
@@ -40,6 +45,7 @@ import type { IModelProviderStore } from './db/modelProviderStore';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
import type { IScheduleStore } from './db/scheduleStore';
import type { ISessionMetricsStore } from './db/sessionMetricsStore';
+import type { ISkillStore } from './db/skillStore';
import type { WithTransaction } from './db/transaction';
import { createClientCertificateMiddleware } from './http/tls';
import type { IOAuthTokenStore } from './mcp/auth/types';
@@ -186,11 +192,17 @@ export interface ServerDeps<TTransaction> {
* (`TRUEFOUNDRY_SANDBOX_*` + static SETTINGS JSON).
*/
resolveSandboxProviderStore: (c: Context) => ISandboxProviderStore<TTransaction>;
+ /** Per-request store: DB git skills, or TrueFoundry registry catalog in TrueFoundry mode. */
+ resolveSkillStore: ResolveSkillStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
scheduleStore: IScheduleStore<TTransaction>;
sessionStore: ISessionStore;
sessionMetricsStore: ISessionMetricsStore;
+ /** Persistence agent store (schedule runs resolve the bound agent without an HTTP caller). */
+ agentStore: IAgentStore<TTransaction>;
+ /** Resolve turn skills - persistence store or TrueFoundry resolve with Service API key (schedule runs do have any caller token). */
+ turnSkillsResolverStore: Pick<ISkillStore<TTransaction>, 'resolveTurnSkills'>;
sessions: Sessions;
activeTurns: ActiveTurnRegistry;
/** Primary Redis client (server-owned); undefined in standalone mode. */
@@ -206,15 +218,26 @@ export interface ServerDeps<TTransaction> {
authenticator: Authenticator;
/** Startup-selected agent authorization policy. */
authorizer: Authorizer;
- /** Per-request store: DB git skills, or SFY registry catalog in TrueFoundry mode. */
- resolveSkillStore: ResolveSkillStore<TTransaction>;
}
export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
const app = new OpenAPIHono({ defaultHook: zodValidationHook });
const authMiddleware = createAuthMiddleware(deps.authenticator);
const adminAuthMiddleware = createAdminAuthMiddleware(deps.authenticator);
+ const scheduleExecutionAuthMiddleware = createApiKeyAuthMiddleware(configuration.TRUEFORGE_API_KEY);
const authEnabled = getTrueForgeAuthMode() !== TrueForgeAuthMode.Standalone;
+ const scheduleTurnDeps = {
+ scheduleStore: deps.scheduleStore,
+ sessions: deps.sessions,
+ agentStore: deps.agentStore,
+ eventSubscriptions: deps.eventSubscriptions,
+ logger: deps.logger,
+ resolveModelProviderStore: deps.resolveModelProviderStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
+ resolveSandboxProviderStore: deps.resolveSandboxProviderStore,
+ activeTurns: deps.activeTurns,
+ turnSkillsResolverStore: deps.turnSkillsResolverStore,
+ };
if (configuration.ACCESS_LOGS) {
app.use('*', createAccessLogMiddleware(deps.logger));
@@ -319,23 +342,16 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
authMiddleware,
),
);
+ app.route(
+ '/api/internal/schedules',
+ withAuth(createScheduleExecutionRouter(scheduleTurnDeps), scheduleExecutionAuthMiddleware),
+ );
app.route(
'/api/v1/schedules',
withAuth(
createSchedulesRouter({
- scheduleStore: deps.scheduleStore,
+ ...scheduleTurnDeps,
resolveAgentStore: deps.resolveAgentStore,
- sessions: deps.sessions,
- resolveTurnDeps: (c, runAsAgent) => ({
- activeTurns: deps.activeTurns,
- eventSubscriptions: deps.eventSubscriptions,
- modelProviderStore: deps.resolveModelProviderStore(c, runAsAgent),
- mcpServerStore: deps.resolveMcpServerStore(c, runAsAgent),
- skillStore: deps.resolveSkillStore(c),
- agentStore: deps.resolveAgentStore(c),
- sandboxProviderStore: deps.resolveSandboxProviderStore(c),
- logger: deps.logger,
- }),
withTransaction: deps.withTransaction,
resolveRequestContext,
authorizer: deps.authorizer,
diff --git a/packages/trueforge/src/auth/identity.ts b/packages/trueforge/src/auth/identity.ts
index 9a55ab5a6..3ff6d9745 100644
--- a/packages/trueforge/src/auth/identity.ts
+++ b/packages/trueforge/src/auth/identity.ts
@@ -1,7 +1,13 @@
import type { CreatedBySubject } from '@truefoundry/trueforge-core/agent-session';
import type { Context } from 'hono';
-import configuration, { getTrueForgeAuthMode, isOidcConfigured, TrueForgeAuthMode } from '../config';
+import configuration, {
+ getTrueForgeAuthMode,
+ isOidcConfigured,
+ isTrueFoundryModeEnabled,
+ TrueForgeAuthMode,
+} from '../config';
+import { createTrueFoundryRequestContext } from '../truefoundry/accessToken';
/** Standalone / default TrueForge admin role string. */
export const STANDALONE_ADMIN_ROLE = 'admin';
@@ -71,6 +77,32 @@ export function hasAdminRole(requestContext: Pick<RequestContext, 'roles'>): boo
}
}
+/** Subject rebuilt from a stored creator snapshot, for work that runs without a live request. */
+export function requestSubjectFromCreatedBySubject(subject: CreatedBySubject): RequestSubject {
+ return {
+ id: subject.subject_id,
+ type: subject.subject_type,
+ display_name: subject.subject_display_name,
+ };
+}
+
+/**
+ * Request identity for store resolvers and other work that runs as a persisted creator
+ * (schedule dispatch, etc.), not as the live HTTP caller.
+ */
+export function requestContextFromCreatedBySubject(params: {
+ tenant_id: string;
+ created_by_subject: CreatedBySubject;
+}): RequestContext {
+ const base: RequestContext = {
+ tenant_id: params.tenant_id,
+ subject: requestSubjectFromCreatedBySubject(params.created_by_subject),
+ roles: [],
+ user_credential: null,
+ };
+ return isTrueFoundryModeEnabled(configuration) ? createTrueFoundryRequestContext(base) : base;
+}
+
/** Persistable creator snapshot derived from the authenticated request. */
export function createdBySubjectFromRequestContext(ctx: RequestContext): CreatedBySubject {
return {
diff --git a/packages/trueforge/src/auth/middleware.ts b/packages/trueforge/src/auth/middleware.ts
index 03b3f3fdf..ef0539346 100644
--- a/packages/trueforge/src/auth/middleware.ts
+++ b/packages/trueforge/src/auth/middleware.ts
@@ -7,9 +7,9 @@ import type { Authenticator } from './authenticator';
import { toRequestContext, type IdTokenClaims } from './claims';
import { hasAdminRole, type RequestContext } from './identity';
import { getOidcVerify } from './oidc';
-import { extractRequestToken } from './token';
+import { extractRequestToken, readBearerToken } from './token';
-export { extractRequestToken, readBearerToken } from './token';
+export { extractRequestToken, readBearerToken };
export function createAuthMiddleware(authenticator: Authenticator): MiddlewareHandler {
return async (c, next) => {
@@ -29,6 +29,17 @@ export function createAdminAuthMiddleware(authenticator: Authenticator): Middlew
};
}
+/** Bearer API-key gate for service-only routes. */
+export function createApiKeyAuthMiddleware(apiKey: string): MiddlewareHandler {
+ return async (c, next) => {
+ const token = readBearerToken(c);
+ if (token === undefined || token !== apiKey) {
+ throw new HTTPException(401, { message: 'Invalid service credential' });
+ }
+ return next();
+ };
+}
+
/**
* Service-to-service API key auth for internal import.
* Sets request_context so resolveAgentStore can build TrueFoundryAgentStore
diff --git a/packages/trueforge/src/config.ts b/packages/trueforge/src/config.ts
index 780e06b4f..0b9af11dd 100644
--- a/packages/trueforge/src/config.ts
+++ b/packages/trueforge/src/config.ts
@@ -38,6 +38,11 @@ const DEFAULT_POSTGRES_DB = 'trueforge';
const DEFAULT_POSTGRES_HOST = 'localhost';
const DEFAULT_POSTGRES_PORT = 5432;
const DEFAULT_REDIS_URL = 'redis://localhost:6379';
+/**
+ * Fixed local service credential when `STANDALONE=true` and `TRUEFORGE_API_KEY` is unset.
+ * Local testing only β€” not for distributed deployments.
+ */
+export const STANDALONE_TRUEFORGE_API_KEY = 'trueforge-standalone';
const DEFAULT_OIDC_USER_REFERENCE_CLAIM = 'sub';
const DEFAULT_OIDC_USER_DISPLAY_NAME_CLAIM = 'name';
@@ -515,15 +520,20 @@ export interface SharedServerConfiguration {
*/
PUBLIC_BASE_URL: string;
/**
- * Base URL the controller uses to reach the server's HTTP API when it runs as its
- * own process (`STANDALONE=false`, `dist/controller-main.js`). The control loops call
- * the server over HTTP(S); when `TRUEFORGE_MTLS_ENABLED` is true the controller upgrades an
- * `http://` URL to `https://` and presents the client cert. Env: `SERVER_URL`.
- * Default: `http://localhost:$PORT`, so in-cluster deployments MUST point this at
- * the server Service. Unused in standalone mode, where the server process owns the
- * controller and targets itself on localhost.
+ * Base URL the controller uses to reach the server's HTTP API. Dedicated controller
+ * (`STANDALONE=false`, `dist/controller-main.js`) and the in-process standalone controller
+ * both call the server over HTTP(S) at this URL (loopback in standalone). When
+ * `TRUEFORGE_MTLS_ENABLED` is true the controller upgrades an `http://` URL to `https://`
+ * and presents the client cert. Env: `SERVER_URL`.
+ * Default: `http://localhost:$PORT`; in-cluster deployments MUST point this at the server Service.
*/
SERVER_URL: string;
+ /**
+ * Service credential for controller calls.
+ * Env: `TRUEFORGE_API_KEY`. Required and non-empty when `STANDALONE=false`.
+ * Standalone defaults to {@link STANDALONE_TRUEFORGE_API_KEY} (local testing only).
+ */
+ TRUEFORGE_API_KEY: string;
/**
* Mutual TLS for this process's HTTPS listener and controller→server. When true, serves HTTPS
* with client-cert enforcement (except `/healthz`) and the controller presents a client cert.
@@ -749,6 +759,9 @@ const shared: SharedServerConfiguration = {
PUBLIC_BASE_URL: parsePublicBaseUrl(getEnv('PUBLIC_BASE_URL', { defaultValue: '' })),
SERVER_URL:
getEnv('SERVER_URL', { defaultValue: `http://localhost:${String(port)}` }) ?? `http://localhost:${String(port)}`,
+ TRUEFORGE_API_KEY: standalone
+ ? (getEnv('TRUEFORGE_API_KEY', { defaultValue: STANDALONE_TRUEFORGE_API_KEY }) ?? STANDALONE_TRUEFORGE_API_KEY)
+ : (getEnv('TRUEFORGE_API_KEY', { required: true }) ?? ''),
TRUEFORGE_MTLS_ENABLED: parseBoolean({
envKey: 'TRUEFORGE_MTLS_ENABLED',
raw: getEnv('TRUEFORGE_MTLS_ENABLED'),
@@ -905,6 +918,10 @@ if (isTrueFoundryModeEnabled(configuration)) {
}
}
+if (!configuration.STANDALONE && configuration.TRUEFORGE_API_KEY.trim() === '') {
+ throw new Error('TRUEFORGE_API_KEY must not be empty when STANDALONE=false.');
+}
+
/**
* Effective public application URL. Empty `PUBLIC_BASE_URL` stays empty
* (callers that need a callback origin throw).
diff --git a/packages/trueforge/src/controller-main.ts b/packages/trueforge/src/controller-main.ts
index 0fb07018e..238d704bc 100644
--- a/packages/trueforge/src/controller-main.ts
+++ b/packages/trueforge/src/controller-main.ts
@@ -4,8 +4,8 @@
* Runs the periodic control loops (schedule dispatch, …) as a dedicated,
* single-replica process for distributed mode (`STANDALONE=false`). The controller
* must run in exactly ONE process per database (see `controller/Controller.ts`);
- * in standalone mode the server process already owns it, so this entry refuses to
- * start there.
+ * in standalone mode the server process already owns it (HTTP loopback to itself), so this
+ * entry refuses to start there.
*
* Migrations are owned by the server (`main.ts`). This process only connects to the
* already-migrated database; the loops have per-pass error boundaries, so they retry
@@ -41,22 +41,15 @@ try {
idleInTransactionSessionTimeoutMs: configuration.POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS,
});
- const mtls = {
- enabled: configuration.TRUEFORGE_MTLS_ENABLED,
- dir: configuration.TRUEFORGE_MTLS_CERTS_DIR,
- };
-
logger.info('Controller starting', {
serverUrl: configuration.SERVER_URL,
- mTlsEnabled: mtls.enabled,
+ mTlsEnabled: configuration.TRUEFORGE_MTLS_ENABLED,
});
runController({
scheduleStore: new PostgresScheduleStore(db),
withTransaction: callback => db.transaction().execute(callback),
logger,
- baseUrl: configuration.SERVER_URL,
- tls: mtls,
gracefulTimeoutSeconds: configuration.GRACEFUL_TIMEOUT_SECONDS,
onStopped: () => db.destroy(),
});
diff --git a/packages/trueforge/src/controller.ts b/packages/trueforge/src/controller.ts
index 68d210ec8..61c13c8ee 100644
--- a/packages/trueforge/src/controller.ts
+++ b/packages/trueforge/src/controller.ts
@@ -1,43 +1,28 @@
-import { TrueForge } from '@truefoundry/trueforge-sdk';
import type { Logger } from 'winston';
import { Controller } from './controller/Controller';
import { scheduleDispatchLoop } from './controller/scheduleDispatch';
import type { IScheduleStore } from './db/scheduleStore';
import type { WithTransaction } from './db/transaction';
-import { createTlsFetch, normalizeTlsUrl, type TlsOptions } from './http/tls';
-
-function createScheduleApiClient(params: { baseUrl: string; tls: TlsOptions }): TrueForge {
- const baseUrl = normalizeTlsUrl({ url: params.baseUrl, enabled: params.tls.enabled });
- const fetchImpl = createTlsFetch(params.tls);
- return new TrueForge({
- baseUrl,
- auth: false,
- ...(fetchImpl !== undefined ? { fetch: fetchImpl } : {}),
- });
-}
/**
- * The loops the controller runs.
+ * Controller whose schedule loop hands runs to the server over HTTP
+ * (`SERVER_URL` + `TRUEFORGE_API_KEY` from process config). Standalone uses
+ * loopback; distributed uses the dedicated controller against the server Service.
*/
export function createController<TTransaction>(params: {
scheduleStore: IScheduleStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
- baseUrl: string;
- tls?: TlsOptions;
}): Controller {
- const { scheduleStore, withTransaction, logger, baseUrl } = params;
- const tls = params.tls ?? { enabled: false, dir: '' };
return new Controller({
loops: [
scheduleDispatchLoop({
- scheduleStore,
- client: createScheduleApiClient({ baseUrl, tls }),
- withTransaction,
- logger,
+ scheduleStore: params.scheduleStore,
+ withTransaction: params.withTransaction,
+ logger: params.logger,
}),
],
- logger,
+ logger: params.logger,
});
}
@@ -48,8 +33,6 @@ export function runController<TTransaction>(params: {
scheduleStore: IScheduleStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
- baseUrl: string;
- tls?: TlsOptions;
gracefulTimeoutSeconds: number;
/** Releases what the caller opened for the loops, e.g. its database pool. */
onStopped?: () => Promise<void>;
diff --git a/packages/trueforge/src/controller/scheduleDispatch.ts b/packages/trueforge/src/controller/scheduleDispatch.ts
index 98b554285..4c4a1bc9d 100644
--- a/packages/trueforge/src/controller/scheduleDispatch.ts
+++ b/packages/trueforge/src/controller/scheduleDispatch.ts
@@ -1,7 +1,8 @@
import type { SessionHandle, Sessions, TurnInputItem } from '@truefoundry/trueforge-core/agent-session';
-import type { TrueForge } from '@truefoundry/trueforge-sdk';
+import { TrueForge } from '@truefoundry/trueforge-sdk';
import type { Logger } from 'winston';
-import type { IAgentStore } from '../db/agentStore';
+import configuration from '../config';
+import type { AgentRecord, IAgentStore } from '../db/agentStore';
import {
cronRunName,
type IScheduleStore,
@@ -9,6 +10,7 @@ import {
type ScheduleRunRecord,
} from '../db/scheduleStore';
import type { WithTransaction } from '../db/transaction';
+import { createTlsFetch, normalizeTlsUrl } from '../http/tls';
import { nextTriggerAfter } from '../runtime/cron';
import { InvalidCronError, type ScheduleRunStatus } from '../schemas/schedule';
import type { ControlLoop } from './Controller';
@@ -39,7 +41,23 @@ const SCHEDULE_DISPATCH_INTERVAL_MS = 60_000;
/** The loop's name. */
const SCHEDULE_DISPATCH_LOOP_NAME = 'schedule-dispatch';
-type ScheduleRunApiClient = Pick<TrueForge, 'sessions' | 'internal'>;
+export type ScheduleRunExecutor = (scheduleRunId: string) => Promise<void>;
+
+/** HTTP handoff to `POST /api/internal/schedules/runs/execute` (dedicated controller or standalone loopback). */
+export function createHttpScheduleRunExecutor(): ScheduleRunExecutor {
+ const tls = {
+ enabled: configuration.TRUEFORGE_MTLS_ENABLED,
+ dir: configuration.TRUEFORGE_MTLS_CERTS_DIR,
+ };
+ const tlsFetch = createTlsFetch(tls);
+ const client = new TrueForge({
+ baseUrl: normalizeTlsUrl({ url: configuration.SERVER_URL, enabled: tls.enabled }),
+ token: configuration.TRUEFORGE_API_KEY,
+ timeoutInSeconds: 60,
+ ...(tlsFetch === undefined ? {} : { fetch: tlsFetch }),
+ });
+ return scheduleRunId => client.internal.schedules.executeRun({ scheduleRunId });
+}
/** Schedule's bound agent name is missing from the agent store. */
export class ScheduleAgentNotFoundError extends Error {
@@ -52,55 +70,48 @@ export class ScheduleAgentNotFoundError extends Error {
}
}
-/**
- * Hands a due schedule run to the API:
- * 1. Get or create a session keyed by `run.id`.
- * 2. Create a non-streaming turn only when that session has no turns.
- *
- * This call is hence idempotent.
- */
-function executeScheduledRun(client: ScheduleRunApiClient): (item: ScheduleDispatchItem) => Promise<void> {
- return async ({ run, schedule }) => {
- const { data: session } = await client.internal.sessions.getOrCreateByExternalId({
- externalId: run.id,
- agent: { name: schedule.agent_name },
- source: { type: 'schedule', id: schedule.id, runId: run.id },
- });
-
- const turns = await client.sessions.listTurns(session.id, { limit: 1 });
- if (turns.data.length > 0) {
- return;
- }
+/** Requested schedule run does not exist. */
+export class ScheduleRunNotFoundError extends Error {
+ constructor(scheduleRunId: string, options?: ErrorOptions) {
+ super(`Schedule run not found: ${scheduleRunId}`, options);
+ this.name = 'ScheduleRunNotFoundError';
+ }
+}
- await client.sessions.createTurn(session.id, {
- input: [{ type: 'user.message', content: schedule.manifest.task }],
- previousTurnId: 'none',
- });
- };
+/** Schedule referenced by a run no longer exists. */
+export class ScheduleNotFoundError extends Error {
+ constructor(scheduleId: string, options?: ErrorOptions) {
+ super(`Schedule not found: ${scheduleId}`, options);
+ this.name = 'ScheduleNotFoundError';
+ }
}
/**
* Start a schedule run in-process: get-or-create a session keyed by `run.id`,
- * then create a non-streaming turn with the schedule task when that session has
- * none. Idempotent on retry. Session owner and turn `userRef` are the schedule
- * creator so ownership stays with the schedule even when an admin triggers run-now.
+ * then prepare a non-streaming turn with the schedule task when that session has
+ * none. Idempotent on retry β€” returns `undefined` when a turn already exists.
+ * Session owner and turn `userRef` are the schedule creator so ownership stays
+ * with the schedule even when an admin triggers run-now.
+ *
+ * Callers start the turn (e.g. via `startTurnInProcess`) with request-scoped stores.
*/
+export interface PreparedScheduleTurn {
+ session: SessionHandle;
+ input: TurnInputItem[];
+ previous_turn_id: string;
+ userRef: string;
+ agent: AgentRecord;
+}
+
export async function startScheduleRun(params: {
item: ScheduleDispatchItem;
sessions: Sessions;
agentStore: IAgentStore;
- startTurn: (params: {
- session: SessionHandle;
- input: TurnInputItem[];
- previous_turn_id: string;
- userRef: string;
- }) => Promise<void>;
-}): Promise<void> {
+}): Promise<PreparedScheduleTurn | undefined> {
const {
item: { run, schedule },
sessions,
agentStore,
- startTurn,
} = params;
const named = await agentStore.getAgent({ tenant_id: schedule.tenant_id, name: schedule.agent_name });
@@ -119,15 +130,33 @@ export async function startScheduleRun(params: {
// idempotency check
const { data: turns } = await session.listTurns({ limit: 1 });
if (turns.length > 0) {
- return;
+ return undefined;
}
- await startTurn({
+ return {
session,
input: [{ type: 'user.message', content: schedule.manifest.task }],
previous_turn_id: 'none',
userRef: schedule.created_by_subject.subject_id,
- });
+ agent: named,
+ };
+}
+
+/** Loads trusted schedule context from a run id. */
+export async function loadScheduleDispatchItem<TTransaction>(params: {
+ scheduleRunId: string;
+ scheduleStore: IScheduleStore<TTransaction>;
+}): Promise<ScheduleDispatchItem> {
+ const { scheduleRunId, scheduleStore } = params;
+ const run = await scheduleStore.getRunById({ id: scheduleRunId });
+ if (run === undefined) {
+ throw new ScheduleRunNotFoundError(scheduleRunId);
+ }
+ const schedule = await scheduleStore.getSchedule({ tenant_id: run.tenant_id, id: run.schedule_id });
+ if (schedule === undefined) {
+ throw new ScheduleNotFoundError(run.schedule_id);
+ }
+ return { run, schedule };
}
/**
@@ -308,18 +337,18 @@ export async function dispatchScheduledRuns<TTransaction>(params: {
export function scheduleDispatchLoop<TTransaction>(params: {
scheduleStore: IScheduleStore<TTransaction>;
- client: ScheduleRunApiClient;
logger: Logger;
withTransaction: WithTransaction<TTransaction>;
}): ControlLoop {
- const { scheduleStore, client, withTransaction, logger } = params;
+ const { scheduleStore, withTransaction, logger } = params;
+ const executeRun = createHttpScheduleRunExecutor();
return {
name: SCHEDULE_DISPATCH_LOOP_NAME,
intervalMs: SCHEDULE_DISPATCH_INTERVAL_MS,
async tick(signal: AbortSignal): Promise<void> {
const result = await dispatchScheduledRuns({
store: scheduleStore,
- onTriggered: executeScheduledRun(client),
+ onTriggered: item => executeRun(item.run.id),
logger,
withTransaction,
signal,
diff --git a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
index 3cd91dff6..ae7b5a98f 100644
--- a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -16,6 +16,7 @@ import {
type CreateScheduleRunInput,
type DeleteScheduleInput,
type GetOwnedIdsInput,
+ type GetRunByIdInput,
type GetRunInput,
type GetScheduledRunForInput,
type GetScheduleInput,
@@ -288,6 +289,15 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
return row === undefined ? undefined : toRunRecord(row);
}
+ async getRunById(
+ input: GetRunByIdInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db.selectFrom('schedule_run').selectAll().where('id', '=', input.id).executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
async getScheduledRunFor(
input: GetScheduledRunForInput,
transaction?: Transaction<Database>,
diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.ts
index 541037202..dc850d6dd 100644
--- a/packages/trueforge/src/db/scheduleStore.ts
+++ b/packages/trueforge/src/db/scheduleStore.ts
@@ -173,6 +173,11 @@ export interface GetRunInput {
id: string;
}
+export interface GetRunByIdInput {
+ /** Globally unique immutable run id. */
+ id: string;
+}
+
export interface GetScheduledRunForInput {
tenant_id: string;
schedule_id: string;
@@ -259,6 +264,8 @@ export interface IScheduleStore<TTransaction = never> {
// --- schedule_run ---
/** One run by immutable id. */
getRun(input: GetRunInput, transaction?: TTransaction): Promise<ScheduleRunRecord | undefined>;
+ /** Internal execution lookup when the run id is the only trusted input. */
+ getRunById(input: GetRunByIdInput, transaction?: TTransaction): Promise<ScheduleRunRecord | undefined>;
/** A schedule's single pending (`scheduled`) run, if it has one. */
getScheduledRunFor(
input: GetScheduledRunForInput,
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
index d6973040b..ab57e1a27 100644
--- a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -21,6 +21,7 @@ import {
type CreateScheduleRunInput,
type DeleteScheduleInput,
type GetOwnedIdsInput,
+ type GetRunByIdInput,
type GetRunInput,
type GetScheduledRunForInput,
type GetScheduleInput,
@@ -341,6 +342,15 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
return row === undefined ? undefined : toRunRecord(row);
}
+ async getRunById(
+ input: GetRunByIdInput,
+ transaction?: Transaction<Database>,
+ ): Promise<ScheduleRunRecord | undefined> {
+ const db = transaction ?? this.#db;
+ const row = await db.selectFrom('schedule_run').select(runColumns).where('id', '=', input.id).executeTakeFirst();
+ return row === undefined ? undefined : toRunRecord(row);
+ }
+
async getScheduledRunFor(
input: GetScheduledRunForInput,
transaction?: Transaction<Database>,
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 28ffb90c2..62b786166 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -56,11 +56,10 @@ import type { Kysely, Transaction } from 'kysely';
import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
-import type { ResolveSkillStore } from './apis/skills';
import { createServerApp } from './app';
import { TrueForgeAuthorizer, type Authorizer } from './auth/authorizer';
import { createAuthenticator } from './auth/createAuthenticator';
-import { resolveRequestContext } from './auth/identity';
+import { resolveRequestContext, type RequestContext } from './auth/identity';
import { initOidc } from './auth/oidc';
import { McpCatalog } from './catalog/McpCatalog';
import { ModelCatalog } from './catalog/ModelCatalog';
@@ -88,34 +87,46 @@ import { PACKAGE_VERSION } from './packageVersion';
import { ActiveTurnRegistry } from './runtime/activeTurns';
import { EventSubscriptionRegistry } from './runtime/event-subscription';
import { printStandaloneStartupBanner } from './startupBanner';
-import { parsePerServerMcpHeaders, X_TFG_MCP_HEADERS } from './truefoundry/perServerMcpHeaders';
+import {
+ parsePerServerMcpHeaders,
+ X_TFG_MCP_HEADERS,
+ type PerServerMcpHeaders,
+} from './truefoundry/perServerMcpHeaders';
import { TrueFoundryAgentStore } from './truefoundry/TrueFoundryAgentStore';
import { TrueFoundryAuthorizer } from './truefoundry/TrueFoundryAuthorizer';
import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore';
import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore';
import { TrueFoundrySandboxProviderStore } from './truefoundry/TrueFoundrySandboxProviderStore';
import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundryServiceFoundryServerClient';
-import { TrueFoundrySkillStore } from './truefoundry/TrueFoundrySkillStore';
+import { TrueFoundryAdminSkillStore, TrueFoundrySkillStore } from './truefoundry/TrueFoundrySkillStore';
/** Persistence + optional Redis wired for the selected topology. */
interface ServerPersistence<TTransaction> {
+ withTransaction: WithTransaction<TTransaction>;
sessionStore: ISessionStore;
sessionMetricsStore: ISessionMetricsStore;
- resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;
- resolveMcpServerStore: (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;
- resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
- /** Import agents: SF assume-user headers on the client; DB store when TrueFoundry mode is off. */
- resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore<TTransaction>;
- resolveSandboxProviderStore: (c: Context) => ISandboxProviderStore<TTransaction>;
- withTransaction: WithTransaction<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
scheduleStore: IScheduleStore<TTransaction>;
+ mcpOAuthStore: IMcpServerWithAuthStore<TTransaction>;
+ resolveModelProviderStore: (rc: RequestContext, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;
+ resolveMcpServerStore: (
+ rc: RequestContext,
+ runAsAgent?: AgentRecord,
+ perServerHeaders?: PerServerMcpHeaders,
+ ) => IMcpServerWithAuthStore<TTransaction>;
+ resolveSandboxProviderStore: (rc: RequestContext) => ISandboxProviderStore<TTransaction>;
+ /** Per-request store: DB git skills, or TrueFoundry registry catalog in TrueFoundry mode. */
+ resolveSkillStore: (rc: RequestContext) => ISkillStore<TTransaction>;
+ resolveAgentStore: (rc: RequestContext) => IAgentStore<TTransaction>;
+ /** Import agents: SF assume-user headers on the client; DB store when TrueFoundry mode is off. */
+ resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore<TTransaction>;
+ /** extra pre-resolved stores for scheduled runs */
+ agentStore: IAgentStore<TTransaction>;
+ turnSkillsResolverStore: Pick<ISkillStore<TTransaction>, 'resolveTurnSkills'>;
destroyDb: () => Promise<void>;
redis: RedisClientType | undefined;
/** One shared client for TrueFoundry store resolvers + auth; undefined when TrueFoundry mode is off. */
serviceFoundryClient: TrueFoundryServiceFoundryServerClient | undefined;
- /** Per-request store: DB git skills, or SFY registry catalog in TrueFoundry mode. */
- resolveSkillStore: ResolveSkillStore<TTransaction>;
}
/** Shared ServiceFoundry HTTP client when TrueFoundry mode is on; otherwise undefined. */
@@ -147,18 +158,29 @@ function createServiceFoundryServerClient(
function buildResolveSkillStore<TTransaction>(options: {
persistenceStore: ISkillStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
-}): ResolveSkillStore<TTransaction> {
+}): (requestContext: RequestContext) => ISkillStore<TTransaction> {
const { persistenceStore, client } = options;
if (client === undefined) {
return () => persistenceStore;
}
- return c =>
+ return requestContext =>
new TrueFoundrySkillStore<TTransaction>({
client,
- context: resolveRequestContext(c),
+ context: requestContext,
});
}
+function buildTurnSkillsResolverStore<TTransaction>(options: {
+ persistenceStore: ISkillStore<TTransaction>;
+ client: TrueFoundryServiceFoundryServerClient | undefined;
+}): Pick<ISkillStore<TTransaction>, 'resolveTurnSkills'> {
+ const { persistenceStore, client } = options;
+ if (client) {
+ return new TrueFoundryAdminSkillStore({ client });
+ }
+ return persistenceStore;
+}
+
/**
* Per-request model-provider store over a shared ServiceFoundry client, else {@link persistenceStore}.
* `runAsAgent` is set only when a turn should use a saved agent's token.
@@ -167,14 +189,13 @@ function buildResolveModelProviderStore<TTransaction>(options: {
persistenceStore: IModelProviderStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
logger: Logger;
-}): (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction> {
- return (c: Context, runAsAgent?: AgentRecord) => {
+}): (rc: RequestContext, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction> {
+ return (rc, runAsAgent) => {
const { persistenceStore, client } = options;
if (client) {
- const requestContext = resolveRequestContext(c);
return new TrueFoundryModelProviderStore<TTransaction>({
client,
- context: requestContext,
+ requestContext: rc,
agent: runAsAgent,
logger: options.logger,
});
@@ -184,33 +205,34 @@ function buildResolveModelProviderStore<TTransaction>(options: {
}
/**
- * Per-request MCP store over ServiceFoundry. Without request context (scheduler / OAuth callback)
- * falls back to the local with-auth store. `runAsAgent` selects a saved agent's token for turns.
+ * Per-request MCP store over ServiceFoundry. `runAsAgent` selects a saved agent's token for turns.
*/
function buildResolveMcpServerStore<TTransaction>(options: {
persistenceStore: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
client: TrueFoundryServiceFoundryServerClient | undefined;
logger: Logger;
-}): (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction> {
- return (c?: Context, runAsAgent?: AgentRecord) => {
- const { persistenceStore, tokenStore, client } = options;
- if (c && client) {
- const requestContext = resolveRequestContext(c);
- const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
+}): (
+ rc: RequestContext,
+ runAsAgent?: AgentRecord,
+ perServerHeaders?: PerServerMcpHeaders,
+) => IMcpServerWithAuthStore<TTransaction> {
+ const withAuthMcpPersistenceStore = new McpServerWithAuthStore<TTransaction>({
+ store: options.persistenceStore,
+ tokenStore: options.tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
+ return (rc, runAsAgent, perServerHeaders) => {
+ const { client } = options;
+ if (client) {
return new TrueFoundryMcpServerStore<TTransaction>({
client,
- context: requestContext,
+ requestContext: rc,
agent: runAsAgent,
logger: options.logger,
- perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},
+ ...(perServerHeaders === undefined ? {} : { perServerHeaders }),
});
}
- const withAuthMcpPersistenceStore = new McpServerWithAuthStore<TTransaction>({
- store: persistenceStore,
- tokenStore,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- });
return withAuthMcpPersistenceStore;
};
}
@@ -220,14 +242,14 @@ function buildResolveAgentStore(options: {
persistenceStore: PostgresAgentStore;
db: Kysely<PostgresDatabase>;
client: TrueFoundryServiceFoundryServerClient | undefined;
-}): (c: Context) => IAgentStore<Transaction<PostgresDatabase>> {
+}): (rc: RequestContext) => IAgentStore<Transaction<PostgresDatabase>> {
const { persistenceStore, client, db } = options;
- return (c: Context) => {
+ return rc => {
if (client) {
return new TrueFoundryAgentStore({
inner: persistenceStore,
client,
- context: resolveRequestContext(c),
+ context: rc,
db,
});
}
@@ -241,13 +263,12 @@ function buildResolveAgentStore(options: {
*/
function buildResolveSandboxProviderStore<TTransaction>(options: {
persistenceStore: ISandboxProviderStore<TTransaction>;
-}): (c: Context) => ISandboxProviderStore<TTransaction> {
+}): (rc: RequestContext) => ISandboxProviderStore<TTransaction> {
const { persistenceStore } = options;
- if (!isTrueFoundryModeEnabled(configuration)) {
- return () => persistenceStore;
+ if (isTrueFoundryModeEnabled(configuration)) {
+ return () => new TrueFoundrySandboxProviderStore<TTransaction>();
}
- const trueFoundryStore = new TrueFoundrySandboxProviderStore<TTransaction>();
- return () => trueFoundryStore;
+ return () => persistenceStore;
}
/** SQLite stores; Redis unused (executor peering disabled). */
@@ -300,20 +321,23 @@ async function createStandalonePersistence(options: {
const sandboxProviderStore = new SqliteSandboxProviderStore(db);
const skillStore = new SqliteSkillStore(db);
return {
+ withTransaction: callback => db.transaction().execute(callback),
sessionStore: new SqliteSessionStore(db),
sessionMetricsStore: new SqliteSessionMetricsStore(db),
+ mcpOAuthStore: mcpServerStore,
+ tokenStore,
+ scheduleStore: new SqliteScheduleStore(db),
resolveModelProviderStore: () => modelProviderStore,
resolveMcpServerStore: () => mcpServerStore,
+ resolveSandboxProviderStore: () => sandboxProviderStore,
+ resolveSkillStore: () => skillStore,
resolveAgentStore: () => agentStore,
resolveImportAgentStore: () => agentStore,
- resolveSandboxProviderStore: () => sandboxProviderStore,
- withTransaction: callback => db.transaction().execute(callback),
- tokenStore,
- scheduleStore: new SqliteScheduleStore(db),
+ agentStore,
+ turnSkillsResolverStore: skillStore,
destroyDb: () => db.destroy(),
redis: undefined,
serviceFoundryClient: undefined,
- resolveSkillStore: () => skillStore,
};
}
@@ -369,12 +393,22 @@ async function createDistributedPersistence(options: {
await migrateToLatest(db);
logger.info('Distributed mode: postgres');
logger.info(`Executor id: ${executorId}`);
-
+ const serviceFoundryClient = createServiceFoundryServerClient(logger);
const tokenStore = new PostgresOAuthTokenStore(db);
- const agentStore = new PostgresAgentStore(db);
const modelProviderStore = new PostgresModelProviderStore(db);
const mcpServerStore = new PostgresMcpServerStore(db);
- const serviceFoundryClient = createServiceFoundryServerClient(logger);
+ const mcpServerWithAuthStore = new McpServerWithAuthStore({
+ store: mcpServerStore,
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
+ const sandboxProviderStore = new PostgresSandboxProviderStore(db);
+ const skillStore = new PostgresSkillStore(db);
+ const agentStore = new PostgresAgentStore(db);
+ const turnSkillsResolverStore = buildTurnSkillsResolverStore({
+ persistenceStore: skillStore,
+ client: serviceFoundryClient,
+ });
const resolveModelProviderStore = buildResolveModelProviderStore({
persistenceStore: modelProviderStore,
client: serviceFoundryClient,
@@ -411,52 +445,54 @@ async function createDistributedPersistence(options: {
});
};
const resolveSandboxProviderStore = buildResolveSandboxProviderStore({
- persistenceStore: new PostgresSandboxProviderStore(db),
+ persistenceStore: sandboxProviderStore,
+ });
+ const resolveSkillStore = buildResolveSkillStore({
+ persistenceStore: skillStore,
+ client: serviceFoundryClient,
});
- const skillStore = new PostgresSkillStore(db);
return {
+ withTransaction: callback => db.transaction().execute(callback),
sessionStore: new PostgresSessionStore(db),
sessionMetricsStore: new PostgresSessionMetricsStore(db),
+ mcpOAuthStore: mcpServerWithAuthStore,
+ tokenStore,
+ scheduleStore: new PostgresScheduleStore(db),
resolveModelProviderStore,
resolveMcpServerStore,
+ resolveSandboxProviderStore,
+ resolveSkillStore,
resolveAgentStore,
resolveImportAgentStore,
- resolveSandboxProviderStore,
- withTransaction: callback => db.transaction().execute(callback),
- tokenStore,
- scheduleStore: new PostgresScheduleStore(db),
+ agentStore,
+ turnSkillsResolverStore,
destroyDb: () => db.destroy(),
redis: await connectRedis({ url: redisUrl, logger }),
serviceFoundryClient,
- resolveSkillStore: buildResolveSkillStore({
- persistenceStore: skillStore,
- client: serviceFoundryClient,
- }),
};
}
/** Keeps `TTransaction` concrete when wiring a single persistence topology into the app. */
async function createServerRuntime<TTransaction>(persistence: ServerPersistence<TTransaction>, logger: Logger) {
const {
+ withTransaction,
sessionStore,
sessionMetricsStore,
- resolveModelProviderStore,
- resolveMcpServerStore,
- resolveAgentStore,
- resolveImportAgentStore,
- resolveSandboxProviderStore,
- withTransaction,
tokenStore,
scheduleStore,
+ mcpOAuthStore,
+ resolveImportAgentStore,
+ agentStore,
+ turnSkillsResolverStore,
destroyDb,
redis,
serviceFoundryClient,
- resolveSkillStore,
} = persistence;
const activeTurns = new ActiveTurnRegistry();
const requestReplyRouter = new RequestReplyRouter();
const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(redis);
+ const sessions = new Sessions({ sessionStore });
const oidc = isOidcConfigured(configuration) ? configuration.OIDC : undefined;
if (oidc) {
@@ -486,16 +522,33 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
authorizer = new TrueForgeAuthorizer();
}
- // Standalone is one process, so it owns the control loops too.
+ // Standalone owns the control loops in-process; they hand off via HTTP loopback
+ // (same transport as the dedicated controller in distributed mode).
const controller = configuration.STANDALONE
? createController({
scheduleStore,
withTransaction,
logger,
- baseUrl: `http://localhost:${String(configuration.PORT)}`,
})
: undefined;
+ // Hono handlers get Context; persistence resolvers take RequestContext.
+ const resolveModelProviderStore = (c: Context, runAsAgent?: AgentRecord) =>
+ persistence.resolveModelProviderStore(resolveRequestContext(c), runAsAgent);
+ const resolveMcpServerStore = (c?: Context, runAsAgent?: AgentRecord) => {
+ if (c === undefined) {
+ return mcpOAuthStore;
+ }
+ const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
+ return persistence.resolveMcpServerStore(
+ resolveRequestContext(c),
+ runAsAgent,
+ rawPerServerHeaders === undefined ? undefined : parsePerServerMcpHeaders(rawPerServerHeaders),
+ );
+ };
+ const resolveAgentStore = (c: Context) => persistence.resolveAgentStore(resolveRequestContext(c));
+ const resolveSandboxProviderStore = (c: Context) => persistence.resolveSandboxProviderStore(resolveRequestContext(c));
+ const resolveSkillStore = (c: Context) => persistence.resolveSkillStore(resolveRequestContext(c));
const app = createServerApp({
modelCatalog: ModelCatalog.load(),
mcpCatalog: McpCatalog.load(),
@@ -506,12 +559,15 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
resolveAgentStore,
resolveImportAgentStore,
resolveSandboxProviderStore,
+ resolveSkillStore,
withTransaction,
tokenStore,
scheduleStore,
+ agentStore,
+ turnSkillsResolverStore,
sessionStore,
sessionMetricsStore,
- sessions: new Sessions({ sessionStore }),
+ sessions,
activeTurns,
redis,
requestReplyRouter,
@@ -520,7 +576,6 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
oidcClient,
authenticator,
authorizer,
- resolveSkillStore,
});
return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
diff --git a/packages/trueforge/src/routes/scheduleRoutes.ts b/packages/trueforge/src/routes/scheduleRoutes.ts
index 9a08971f4..ca4b4b9a6 100644
--- a/packages/trueforge/src/routes/scheduleRoutes.ts
+++ b/packages/trueforge/src/routes/scheduleRoutes.ts
@@ -10,6 +10,7 @@ import {
CreateScheduleRunRequestSchema,
CreateScheduleRunResponseSchema,
DeleteScheduleResponseSchema,
+ ExecuteScheduleRunRequestSchema,
GetScheduleResponseSchema,
ListScheduleRunsResponseSchema,
ListSchedulesResponseSchema,
@@ -170,6 +171,37 @@ export const createScheduleRunRoute = createRoute({
},
});
+export const executeScheduleRunRoute = createRoute({
+ method: 'post',
+ path: '/runs/execute',
+ tags: [OpenApiTag.INTERNAL],
+ summary: 'Execute a schedule run',
+ description: 'Execute a persisted schedule run using its saved schedule and agent.',
+ 'x-fern-sdk-group-name': ['internal', 'schedules'],
+ 'x-fern-sdk-method-name': 'execute_run',
+ request: {
+ body: {
+ content: { 'application/json': { schema: ExecuteScheduleRunRequestSchema } },
+ required: true,
+ },
+ },
+ responses: {
+ 204: { description: 'Run executed or already has a turn.' },
+ 401: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid service credential.',
+ },
+ 404: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Run, schedule, or agent not found.',
+ },
+ 422: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'The run cannot be executed.',
+ },
+ },
+});
+
export const createScheduleRoute = createRoute({
method: 'post',
path: '/',
diff --git a/packages/trueforge/src/schemas/schedule.ts b/packages/trueforge/src/schemas/schedule.ts
index 83dfaa1d8..2c50910ef 100644
--- a/packages/trueforge/src/schemas/schedule.ts
+++ b/packages/trueforge/src/schemas/schedule.ts
@@ -175,11 +175,19 @@ export const CreateScheduleRunResponseSchema = z
.object({ data: ScheduleRunSchema })
.openapi('CreateScheduleRunResponse');
+export const ExecuteScheduleRunRequestSchema = z
+ .object({
+ schedule_run_id: z.string().min(1).max(64).describe('Immutable schedule run identifier.'),
+ })
+ .strict()
+ .openapi('ExecuteScheduleRunRequest');
+
export type ScheduleStatus = z.infer<typeof ScheduleStatusSchema>;
export type ScheduleRunStatus = z.infer<typeof ScheduleRunStatusSchema>;
export type ScheduleManifest = z.infer<typeof ScheduleManifestSchema>;
export type Schedule = z.infer<typeof ScheduleSchema>;
export type ScheduleRun = z.infer<typeof ScheduleRunSchema>;
+export type ExecuteScheduleRunRequest = z.infer<typeof ExecuteScheduleRunRequestSchema>;
export type CreateScheduleRequest = z.infer<typeof CreateScheduleRequestSchema>;
export type UpdateScheduleRequest = z.infer<typeof UpdateScheduleRequestSchema>;
export type CreateScheduleRunRequest = z.infer<typeof CreateScheduleRunRequestSchema>;
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
index 0adaed9e8..fd02feae1 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -70,19 +70,19 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServ
constructor(input: {
client: TrueFoundryMcpApiClient;
- context: RequestContext;
+ requestContext: RequestContext;
agent: AgentRecord | undefined;
- logger: Pick<Logger, 'info'>;
perServerHeaders?: PerServerMcpHeaders;
+ logger: Logger;
}) {
this.#client = input.client;
this.#resolveAccessToken = accessTokenForRequest({
client: input.client,
- context: asTrueFoundryRequestContext(input.context),
+ requestContext: asTrueFoundryRequestContext(input.requestContext),
agent: input.agent,
logger: input.logger,
});
- this.#subject = input.context.subject;
+ this.#subject = input.requestContext.subject;
this.#perServerHeaders = input.perServerHeaders ?? {};
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
index cd5cee912..6b308c26f 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryModelProviderStore.ts
@@ -23,14 +23,14 @@ export class TrueFoundryModelProviderStore<TTransaction = never> implements IMod
constructor(input: {
client: TrueFoundryServiceFoundryServerClient;
- context: RequestContext;
+ requestContext: RequestContext;
agent: AgentRecord | undefined;
logger: Logger;
}) {
this.#client = input.client;
this.#resolveAccessToken = accessTokenForRequest({
client: input.client,
- context: asTrueFoundryRequestContext(input.context),
+ requestContext: asTrueFoundryRequestContext(input.requestContext),
agent: input.agent,
logger: input.logger,
});
diff --git a/packages/trueforge/src/truefoundry/TrueFoundrySkillStore.ts b/packages/trueforge/src/truefoundry/TrueFoundrySkillStore.ts
index 8a2fe83c3..02c77725f 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundrySkillStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundrySkillStore.ts
@@ -44,14 +44,76 @@ function toRegistryRecord(tenant_id: string, skill: SfyRegistrySkill): SkillReco
};
}
+export class TrueFoundryAdminSkillStore<TTransaction = never> implements Pick<
+ ISkillStore<TTransaction>,
+ 'resolveTurnSkills'
+> {
+ readonly #client: TrueFoundrySkillApiClient;
+
+ constructor(input: { client: TrueFoundrySkillApiClient }) {
+ this.#client = input.client;
+ }
+
+ async resolveTurnSkills(input: AgentSkillsInput): Promise<SkillMount[]> {
+ const { skills } = input;
+ if (skills.length === 0) {
+ return [];
+ }
+
+ // Runtime resolve uses the service API key, not the caller token.
+ const resolved = await this.#client.resolveAgentSkillVersions({
+ accessToken: this.#client.apiKey,
+ skills: skills.map(skill => ({
+ fqn: skill.name,
+ include_skill_md_content: skill.preload,
+ include_presigned_url: true,
+ })),
+ });
+
+ const byFqn = new Map(resolved.map(row => [row.fqn, row]));
+ return skills.map(skill => {
+ const row = byFqn.get(skill.name);
+ if (row === undefined) {
+ throw new HTTPException(422, {
+ message: `Unknown skill "${skill.name}" β€” not configured`,
+ });
+ }
+ if (row.presigned_url === undefined) {
+ throw new HTTPException(422, {
+ message: `Skill "${skill.name}" did not return a presigned URL`,
+ });
+ }
+ const skillMdContent = skill.preload ? (row.skill_md_content ?? null) : null;
+ if (skill.preload && (skillMdContent === null || skillMdContent.length === 0)) {
+ throw new HTTPException(422, {
+ message: `Skill "${skill.name}" did not return SKILL.md for preload`,
+ });
+ }
+ return {
+ type: 'registry' as const,
+ name: row.name,
+ description: row.description,
+ fqn: row.fqn,
+ preload: skill.preload,
+ skillMdContent,
+ presignedUrl: row.presigned_url,
+ };
+ });
+ }
+}
+
/** Read-only TrueFoundry registry skill catalog; writes are managed by TrueFoundry.
* Catalog / save validate use the caller JWT; turn mounts use the service API key.
*/
-export class TrueFoundrySkillStore<TTransaction = never> implements ISkillStore<TTransaction> {
+export class TrueFoundrySkillStore<TTransaction = never>
+ extends TrueFoundryAdminSkillStore<TTransaction>
+ implements ISkillStore<TTransaction>
+{
readonly #client: TrueFoundrySkillApiClient;
readonly #resolveAccessToken: ResolveAccessToken;
constructor(input: { client: TrueFoundrySkillApiClient; context: RequestContext }) {
+ super(input);
this.#client = input.client;
this.#resolveAccessToken = callerAccessToken(input.context);
}
@@ -141,51 +203,4 @@ export class TrueFoundrySkillStore<TTransaction = never> implements ISkillStore<
seenNames.add(row.name);
}
}
-
- async resolveTurnSkills(input: AgentSkillsInput): Promise<SkillMount[]> {
- const { skills } = input;
- if (skills.length === 0) {
- return [];
- }
-
- // Runtime resolve uses the service API key, not the caller token.
- const resolved = await this.#client.resolveAgentSkillVersions({
- accessToken: this.#client.apiKey,
- skills: skills.map(skill => ({
- fqn: skill.name,
- include_skill_md_content: skill.preload,
- include_presigned_url: true,
- })),
- });
-
- const byFqn = new Map(resolved.map(row => [row.fqn, row]));
- return skills.map(skill => {
- const row = byFqn.get(skill.name);
- if (row === undefined) {
- throw new HTTPException(422, {
- message: `Unknown skill "${skill.name}" β€” not configured`,
- });
- }
- if (row.presigned_url === undefined) {
- throw new HTTPException(422, {
- message: `Skill "${skill.name}" did not return a presigned URL`,
- });
- }
- const skillMdContent = skill.preload ? (row.skill_md_content ?? null) : null;
- if (skill.preload && (skillMdContent === null || skillMdContent.length === 0)) {
- throw new HTTPException(422, {
- message: `Skill "${skill.name}" did not return SKILL.md for preload`,
- });
- }
- return {
- type: 'registry' as const,
- name: row.name,
- description: row.description,
- fqn: row.fqn,
- preload: skill.preload,
- skillMdContent,
- presignedUrl: row.presigned_url,
- };
- });
- }
}
diff --git a/packages/trueforge/src/truefoundry/accessToken.ts b/packages/trueforge/src/truefoundry/accessToken.ts
index cb006e384..a32931755 100644
--- a/packages/trueforge/src/truefoundry/accessToken.ts
+++ b/packages/trueforge/src/truefoundry/accessToken.ts
@@ -45,11 +45,11 @@ export function asTrueFoundryRequestContext(context: RequestContext): TrueFoundr
*/
export function agentAccessToken(input: {
client: AgentTokenVendor;
- context: RequestContext;
+ requestContext: Pick<RequestContext, 'tenant_id' | 'subject'>;
agent: AgentRecord;
logger: Pick<Logger, 'info'>;
}): ResolveAccessToken {
- const { client, context } = input;
+ const { client, requestContext: context } = input;
const agentId = requireTrueFoundryAgentExternalId(input.agent);
let pending: Promise<string> | undefined;
return () => {
@@ -86,22 +86,22 @@ export function callerAccessToken(context: RequestContext): ResolveAccessToken {
*/
export function accessTokenForRequest(input: {
client: AgentTokenVendor;
- context: TrueFoundryRequestContext;
+ requestContext: TrueFoundryRequestContext;
agent: AgentRecord | undefined;
logger: Pick<Logger, 'info'>;
}): ResolveAccessToken {
if (input.agent === undefined) {
- return callerAccessToken(input.context);
+ return callerAccessToken(input.requestContext);
}
const agentId = requireTrueFoundryAgentExternalId(input.agent);
- const cache = input.context[accessTokenCache];
+ const cache = input.requestContext[accessTokenCache];
const existing = cache.get(agentId);
if (existing !== undefined) {
return existing;
}
const resolveAgentAccessToken = agentAccessToken({
client: input.client,
- context: input.context,
+ requestContext: input.requestContext,
agent: input.agent,
logger: input.logger,
});
diff --git a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
index 1ad2981a4..488fe53d3 100644
--- a/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
+++ b/packages/trueforge/tests/db/scheduleStoreContractSuite.ts
@@ -65,6 +65,10 @@ export function runScheduleStoreContractSuite(deps: {
}),
);
expect(await store.getScheduledRunFor({ tenant_id: TENANT, schedule_id: schedule.id })).toEqual(pendingRun);
+ if (pendingRun === undefined) {
+ throw new Error('Expected active schedule to create a pending run');
+ }
+ expect(await store.getRunById({ id: pendingRun.id })).toEqual(pendingRun);
});
it('create paused leaves no pending run', async () => {
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index 79ac96159..a9da14a3e 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -1,6 +1,12 @@
import { OpenAPIHono } from '@hono/zod-openapi';
-import { AgentSpecSchema } from '@truefoundry/trueforge-core/agent-session';
-import { createSchedulesRouter } from '../../../src/apis/schedules';
+import {
+ AgentSpecSchema,
+ InMemorySessionStore,
+ Sessions,
+ type TurnStreamingEvent,
+} from '@truefoundry/trueforge-core/agent-session';
+import winston from 'winston';
+import { createScheduleExecutionRouter, createSchedulesRouter } from '../../../src/apis/schedules';
import { TrueForgeAuthorizer, type Authorizer } from '../../../src/auth/authorizer';
import type { RequestContext } from '../../../src/auth/identity';
import { ScheduleAgentNotFoundError, startScheduleRun } from '../../../src/controller/scheduleDispatch';
@@ -8,20 +14,25 @@ import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
import { SqliteScheduleStore } from '../../../src/db/sqlite/schedule-store/SqliteScheduleStore';
+import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';
+import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription';
import {
CreateScheduleRunResponseSchema,
ListScheduleRunsResponseSchema,
ListSchedulesResponseSchema,
} from '../../../src/schemas/schedule';
-jest.mock('../../../src/controller/scheduleDispatch', () => ({
- ...jest.requireActual<typeof import('../../../src/controller/scheduleDispatch')>(
+jest.mock('../../../src/controller/scheduleDispatch', () => {
+ const actual = jest.requireActual<typeof import('../../../src/controller/scheduleDispatch')>(
'../../../src/controller/scheduleDispatch',
- ),
- startScheduleRun: jest.fn().mockResolvedValue(undefined),
-}));
+ );
+ return {
+ ...actual,
+ startScheduleRun: jest.fn().mockResolvedValue(undefined),
+ };
+});
-const mockedStartScheduleRun = jest.mocked(startScheduleRun);
+const mockedStartScheduleRun = startScheduleRun as jest.MockedFunction<typeof startScheduleRun>;
const ALICE: RequestContext = {
tenant_id: 'default',
@@ -48,6 +59,22 @@ const scheduleBody = {
manifest: { task: 'Say hi', cron: '0 13 * * *', timezone: 'UTC' },
};
+function stubTurnExecutionDeps(agentStore: SqliteAgentStore, scheduleStore: SqliteScheduleStore) {
+ const sessionStore = new InMemorySessionStore();
+ return {
+ scheduleStore,
+ sessions: new Sessions({ sessionStore }),
+ agentStore,
+ activeTurns: new ActiveTurnRegistry(),
+ eventSubscriptions: new EventSubscriptionRegistry<TurnStreamingEvent>(undefined),
+ logger: winston.createLogger({ silent: true }),
+ resolveModelProviderStore: () => ({}) as never,
+ resolveMcpServerStore: () => ({}) as never,
+ turnSkillsResolverStore: { resolveTurnSkills: async () => [] },
+ resolveSandboxProviderStore: () => ({}) as never,
+ };
+}
+
async function setup(authorizer: Authorizer = new TrueForgeAuthorizer()) {
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
@@ -67,25 +94,14 @@ async function setup(authorizer: Authorizer = new TrueForgeAuthorizer()) {
let current: RequestContext = ALICE;
let currentAuthorizer = authorizer;
+ mockedStartScheduleRun.mockReset();
+ mockedStartScheduleRun.mockResolvedValue(undefined);
const app = new OpenAPIHono();
app.route(
'/',
createSchedulesRouter({
- scheduleStore,
+ ...stubTurnExecutionDeps(agentStore, scheduleStore),
resolveAgentStore: () => agentStore,
- sessions: {
- getOrCreateByExternalId: () => Promise.reject(new Error('sessions stub: unexpected call')),
- } as never,
- resolveTurnDeps: () => ({
- activeTurns: {} as never,
- eventSubscriptions: {} as never,
- modelProviderStore: {} as never,
- mcpServerStore: {} as never,
- skillStore: {} as never,
- agentStore,
- sandboxProviderStore: {} as never,
- logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() } as never,
- }),
withTransaction: callback => db.transaction().execute(callback),
resolveRequestContext: () => current,
authorizer: {
@@ -277,11 +293,6 @@ describe('schedule list agent_names filter', () => {
});
describe('create schedule run', () => {
- beforeEach(() => {
- mockedStartScheduleRun.mockReset();
- mockedStartScheduleRun.mockResolvedValue(undefined);
- });
-
it('creates a triggered run with a manual-* name and leaves the cron pending run alone', async () => {
const { asUser, postJson, scheduleStore } = await setup();
@@ -312,10 +323,7 @@ describe('create schedule run', () => {
expect(mockedStartScheduleRun).toHaveBeenCalledWith(
expect.objectContaining({
- item: expect.objectContaining({
- run: expect.objectContaining({ id: body.data.id }),
- schedule: expect.objectContaining({ id: scheduleId }),
- }),
+ item: expect.objectContaining({ run: expect.objectContaining({ id: body.data.id }) }),
}),
);
@@ -346,8 +354,8 @@ describe('create schedule run', () => {
});
it('marks the run failed and returns 404 when startScheduleRun reports a missing agent', async () => {
- mockedStartScheduleRun.mockRejectedValue(new ScheduleAgentNotFoundError('reporter'));
const { asUser, postJson, scheduleStore } = await setup();
+ mockedStartScheduleRun.mockRejectedValue(new ScheduleAgentNotFoundError('reporter'));
asUser(ALICE);
const created = await postJson('/', 'POST', scheduleBody);
@@ -411,3 +419,82 @@ describe('create schedule run', () => {
expect(canAccessAgent.mock.calls.map(([input]) => input.action)).toEqual(['use']);
});
});
+
+describe('internal schedule execution', () => {
+ it('executes the persisted run id', async () => {
+ mockedStartScheduleRun.mockReset();
+ mockedStartScheduleRun.mockResolvedValue(undefined);
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const agentStore = new SqliteAgentStore(db);
+ const scheduleStore = new SqliteScheduleStore(db);
+ const agent = await agentStore.createAgent({
+ tenant_id: 'default',
+ created_by_subject: {
+ subject_id: 'alice',
+ subject_type: 'user',
+ subject_display_name: 'alice',
+ },
+ name: 'reporter',
+ manifest: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' }, instructions: 'test' }),
+ external_id: 'reporter-external-id',
+ });
+ const { schedule } = await scheduleStore.createScheduleAndRun({
+ tenant_id: 'default',
+ agent_id: agent.id,
+ agent_name: agent.name,
+ name: 'daily-report',
+ manifest: { task: 'Say hi', cron: '0 13 * * *', timezone: 'UTC', status: 'active' },
+ created_by_subject: {
+ subject_id: 'alice',
+ subject_type: 'user',
+ subject_display_name: 'alice',
+ },
+ runFrom: new Date(),
+ });
+ const run = await scheduleStore.createRun({
+ tenant_id: 'default',
+ schedule_id: schedule.id,
+ name: 'manual-test',
+ scheduled_for: new Date(),
+ status: 'triggered',
+ created_by_subject: {
+ subject_id: 'alice',
+ subject_type: 'user',
+ subject_display_name: 'alice',
+ },
+ triggered_at: new Date(),
+ });
+ const app = createScheduleExecutionRouter(stubTurnExecutionDeps(agentStore, scheduleStore));
+
+ const response = await app.request('/runs/execute', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ schedule_run_id: run.id }),
+ });
+
+ expect(response.status).toBe(204);
+ expect(mockedStartScheduleRun).toHaveBeenCalledWith(
+ expect.objectContaining({ item: expect.objectContaining({ run: expect.objectContaining({ id: run.id }) }) }),
+ );
+ });
+
+ it('maps an unknown run to 404', async () => {
+ mockedStartScheduleRun.mockReset();
+ mockedStartScheduleRun.mockResolvedValue(undefined);
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const agentStore = new SqliteAgentStore(db);
+ const scheduleStore = new SqliteScheduleStore(db);
+ const app = createScheduleExecutionRouter(stubTurnExecutionDeps(agentStore, scheduleStore));
+
+ const response = await app.request('/runs/execute', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ schedule_run_id: 'missing' }),
+ });
+
+ expect(response.status).toBe(404);
+ expect(mockedStartScheduleRun).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/trueforge/tests/unit/auth/identity.test.ts b/packages/trueforge/tests/unit/auth/identity.test.ts
index 2152cf21d..12a4062fb 100644
--- a/packages/trueforge/tests/unit/auth/identity.test.ts
+++ b/packages/trueforge/tests/unit/auth/identity.test.ts
@@ -1,5 +1,10 @@
import { Hono } from 'hono';
-import { hasAdminRole, resolveRequestContext, STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
+import {
+ hasAdminRole,
+ requestContextFromCreatedBySubject,
+ resolveRequestContext,
+ STANDALONE_REQUEST_CONTEXT,
+} from '../../../src/auth/identity';
describe('STANDALONE_REQUEST_CONTEXT', () => {
it('has the fixed standalone identity shape', () => {
@@ -16,6 +21,23 @@ describe('STANDALONE_REQUEST_CONTEXT', () => {
});
});
+describe('requestContextFromCreatedBySubject', () => {
+ it('builds request identity from a persisted creator snapshot', () => {
+ const rc = requestContextFromCreatedBySubject({
+ tenant_id: 'acme',
+ created_by_subject: {
+ subject_id: 'alice',
+ subject_type: 'user',
+ subject_display_name: 'Alice',
+ },
+ });
+ expect(rc.tenant_id).toBe('acme');
+ expect(rc.subject).toEqual({ id: 'alice', type: 'user', display_name: 'Alice' });
+ expect(rc.roles).toEqual([]);
+ expect(rc.user_credential).toBeNull();
+ });
+});
+
describe('hasAdminRole', () => {
// Unit tests run under STANDALONE=true (.env.test) β†’ mode Standalone.
it('treats admin as admin and other roles as non-admin in standalone', () => {
diff --git a/packages/trueforge/tests/unit/auth/middleware.test.ts b/packages/trueforge/tests/unit/auth/middleware.test.ts
index 296dedce4..5e14c50c6 100644
--- a/packages/trueforge/tests/unit/auth/middleware.test.ts
+++ b/packages/trueforge/tests/unit/auth/middleware.test.ts
@@ -4,7 +4,11 @@ import { exportJWK, generateKeyPair, SignJWT } from 'jose';
import type { Configuration } from 'openid-client';
import type { Authenticator } from '../../../src/auth/authenticator';
import { STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity';
-import { createAdminAuthMiddleware, createAuthMiddleware } from '../../../src/auth/middleware';
+import {
+ createAdminAuthMiddleware,
+ createApiKeyAuthMiddleware,
+ createAuthMiddleware,
+} from '../../../src/auth/middleware';
import { disableOidcAuth, enableOidcAuth, initOidc } from '../../../src/auth/oidc';
import { OidcAuthenticator } from '../../../src/auth/oidcAuthenticator';
import { StandaloneAuthenticator } from '../../../src/auth/standaloneAuthenticator';
@@ -379,3 +383,37 @@ describe('createAuthMiddleware / createAdminAuthMiddleware', () => {
});
});
});
+
+describe('createApiKeyAuthMiddleware', () => {
+ function createServiceApp(apiKey: string) {
+ const app = new OpenAPIHono();
+ app.onError((error, c) => {
+ if (error instanceof HTTPException) {
+ return c.json({ error: { message: error.message } }, error.status);
+ }
+ throw error;
+ });
+ app.use('*', createApiKeyAuthMiddleware(apiKey));
+ app.post('/', c => c.body(null, 204));
+ return app;
+ }
+
+ it('accepts the configured bearer API key', async () => {
+ const response = await createServiceApp('service-key').request('/', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer service-key' },
+ });
+ expect(response.status).toBe(204);
+ });
+
+ it.each([
+ ['missing header', undefined],
+ ['wrong key', 'Bearer wrong-key'],
+ ])('rejects %s', async (_name, authorization) => {
+ const response = await createServiceApp('service-key').request('/', {
+ method: 'POST',
+ ...(authorization === undefined ? {} : { headers: { Authorization: authorization } }),
+ });
+ expect(response.status).toBe(401);
+ });
+});
diff --git a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
index 6d7fffefa..64e765534 100644
--- a/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
+++ b/packages/trueforge/tests/unit/controller/scheduleDispatch.test.ts
@@ -1,7 +1,11 @@
+import configuration, { STANDALONE_TRUEFORGE_API_KEY } from '../../../src/config';
import {
+ createHttpScheduleRunExecutor,
+ loadScheduleDispatchItem,
ScheduleAgentNotFoundError,
scheduleDispatchLoop,
scheduleRunFailureReason,
+ ScheduleRunNotFoundError,
startScheduleRun,
} from '../../../src/controller/scheduleDispatch';
import type { ScheduleDispatchItem, ScheduleRunRecord } from '../../../src/db/scheduleStore';
@@ -68,25 +72,12 @@ function fakeStore(dispatchItem: ScheduleDispatchItem) {
};
}
-/**
- * Mirrors how the SDK splits these calls: get-or-create is only on `internal.sessions`,
- * turns only on the public `sessions`. Giving each client just its own methods means a call
- * routed to the wrong one throws instead of silently resolving.
- */
-async function tickDispatch(mocks: {
- getOrCreateByExternalId: jest.Mock;
- listTurns: jest.Mock;
- createTurn: jest.Mock;
-}) {
+async function tickDispatch() {
const dispatchItem = item();
const store = fakeStore(dispatchItem);
const logger = fakeLogger();
const loop = scheduleDispatchLoop({
scheduleStore: store as never,
- client: {
- sessions: { listTurns: mocks.listTurns, createTurn: mocks.createTurn },
- internal: { sessions: { getOrCreateByExternalId: mocks.getOrCreateByExternalId } },
- } as never,
logger: logger as never,
withTransaction: async callback => callback({} as never),
});
@@ -94,46 +85,47 @@ async function tickDispatch(mocks: {
return { store, logger };
}
-describe('scheduleDispatchLoop', () => {
- it('creates a session and turn through the API client', async () => {
- const getOrCreateByExternalId = jest.fn().mockResolvedValue({ data: { id: 'sess-1' } });
- const listTurns = jest.fn().mockResolvedValue({ data: [] });
- const createTurn = jest.fn().mockResolvedValue({ data: { id: 'turn-1' } });
+describe('schedule execution HTTP transport', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
- await tickDispatch({ getOrCreateByExternalId, listTurns, createTurn });
+ it('sends one API-key authenticated request with the run id', async () => {
+ const request = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }));
+ const executeRun = createHttpScheduleRunExecutor();
- expect(getOrCreateByExternalId).toHaveBeenCalledWith({
- externalId: 'run-1',
- agent: { name: 'reporter' },
- source: { type: 'schedule', id: 'sched-1', runId: 'run-1' },
- });
- expect(listTurns).toHaveBeenCalledWith('sess-1', { limit: 1 });
- expect(createTurn).toHaveBeenCalledWith('sess-1', {
- input: [{ type: 'user.message', content: 'Write the report' }],
- previousTurnId: 'none',
- });
+ await executeRun('run-1');
+
+ expect(request).toHaveBeenCalledTimes(1);
+ const [url, init] = request.mock.calls[0] ?? [];
+ expect(String(url)).toBe(`${configuration.SERVER_URL}/api/internal/schedules/runs/execute`);
+ expect(init?.method).toBe('POST');
+ expect(new Headers(init?.headers).get('authorization')).toBe(`Bearer ${STANDALONE_TRUEFORGE_API_KEY}`);
+ expect(init?.body).toBe(JSON.stringify({ schedule_run_id: 'run-1' }));
+ });
+});
+
+describe('scheduleDispatchLoop', () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
});
- it('does not call create-turn when the session already has a turn', async () => {
- const getOrCreateByExternalId = jest.fn().mockResolvedValue({ data: { id: 'sess-1' } });
- const listTurns = jest.fn().mockResolvedValue({ data: [{ id: 'turn-1' }] });
- const createTurn = jest.fn();
+ it('hands the persisted run id to the execution endpoint', async () => {
+ const request = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(null, { status: 204 }));
- await tickDispatch({ getOrCreateByExternalId, listTurns, createTurn });
+ await tickDispatch();
- expect(createTurn).not.toHaveBeenCalled();
+ expect(request).toHaveBeenCalledTimes(1);
+ const [url, init] = request.mock.calls[0] ?? [];
+ expect(String(url)).toBe(`${configuration.SERVER_URL}/api/internal/schedules/runs/execute`);
+ expect(init?.body).toBe(JSON.stringify({ schedule_run_id: 'run-1' }));
});
- it('propagates API failures without attempting a turn', async () => {
- const getOrCreateByExternalId = jest.fn().mockRejectedValue(new Error('Agent not found: reporter'));
- const createTurn = jest.fn();
- const { logger } = await tickDispatch({
- getOrCreateByExternalId,
- listTurns: jest.fn(),
- createTurn,
- });
+ it('marks HTTP execution failures as failed', async () => {
+ jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('request failed', { status: 500 }));
+
+ const { logger } = await tickDispatch();
- expect(createTurn).not.toHaveBeenCalled();
expect(logger.error).toHaveBeenCalledWith(
'Failed to hand off triggered run',
expect.objectContaining({ run_id: 'run-1' }),
@@ -142,25 +134,17 @@ describe('scheduleDispatchLoop', () => {
});
describe('startScheduleRun', () => {
- const startTurn = jest.fn().mockResolvedValue({ id: 'turn-1' });
-
- beforeEach(() => {
- startTurn.mockClear();
- startTurn.mockResolvedValue({ id: 'turn-1' });
- });
-
- it('get-or-creates a session and starts a turn with the schedule task', async () => {
+ it('get-or-creates a session and returns a prepared turn with the schedule task', async () => {
const dispatchItem = item();
const listTurns = jest.fn().mockResolvedValue({ data: [] });
const session = { listTurns };
const getOrCreateByExternalId = jest.fn().mockResolvedValue({ session, created: true });
const getAgent = jest.fn().mockResolvedValue({ id: 'agent-1', name: 'reporter' });
- await startScheduleRun({
+ const prepared = await startScheduleRun({
item: dispatchItem,
sessions: { getOrCreateByExternalId } as never,
agentStore: { getAgent } as never,
- startTurn,
});
expect(getAgent).toHaveBeenCalledWith({ tenant_id: 'default', name: 'reporter' });
@@ -171,15 +155,16 @@ describe('startScheduleRun', () => {
agent: { type: 'reference', id: 'agent-1', name: 'reporter' },
source: { type: 'schedule', id: 'sched-1', run_id: 'run-1' },
});
- expect(startTurn).toHaveBeenCalledWith({
+ expect(prepared).toEqual({
session,
input: [{ type: 'user.message', content: 'Write the report' }],
previous_turn_id: 'none',
userRef: 'tester',
+ agent: { id: 'agent-1', name: 'reporter' },
});
});
- it('does not start a turn when the session already has one', async () => {
+ it('returns undefined when the session already has a turn', async () => {
const listTurns = jest.fn().mockResolvedValue({ data: [{ turn_id: 'turn-1' }] });
const getOrCreateByExternalId = jest.fn().mockResolvedValue({
session: { listTurns },
@@ -187,14 +172,13 @@ describe('startScheduleRun', () => {
});
const getAgent = jest.fn().mockResolvedValue({ id: 'agent-1', name: 'reporter' });
- await startScheduleRun({
+ const prepared = await startScheduleRun({
item: item(),
sessions: { getOrCreateByExternalId } as never,
agentStore: { getAgent } as never,
- startTurn,
});
- expect(startTurn).not.toHaveBeenCalled();
+ expect(prepared).toBeUndefined();
});
it('throws when the schedule agent is missing', async () => {
@@ -203,9 +187,38 @@ describe('startScheduleRun', () => {
item: item(),
sessions: { getOrCreateByExternalId: jest.fn() } as never,
agentStore: { getAgent: jest.fn().mockResolvedValue(undefined) } as never,
- startTurn,
}),
).rejects.toBeInstanceOf(ScheduleAgentNotFoundError);
- expect(startTurn).not.toHaveBeenCalled();
+ });
+});
+
+describe('loadScheduleDispatchItem', () => {
+ it('loads run context by id', async () => {
+ const dispatchItem = item();
+ const scheduleStore = {
+ getRunById: jest.fn().mockResolvedValue(dispatchItem.run),
+ getSchedule: jest.fn().mockResolvedValue(dispatchItem.schedule),
+ };
+
+ await expect(
+ loadScheduleDispatchItem({
+ scheduleRunId: 'run-1',
+ scheduleStore: scheduleStore as never,
+ }),
+ ).resolves.toEqual(dispatchItem);
+
+ expect(scheduleStore.getRunById).toHaveBeenCalledWith({ id: 'run-1' });
+ expect(scheduleStore.getSchedule).toHaveBeenCalledWith({ tenant_id: 'default', id: 'sched-1' });
+ });
+
+ it('rejects an unknown run id before loading a schedule', async () => {
+ const getSchedule = jest.fn();
+ await expect(
+ loadScheduleDispatchItem({
+ scheduleRunId: 'missing',
+ scheduleStore: { getRunById: jest.fn().mockResolvedValue(undefined), getSchedule } as never,
+ }),
+ ).rejects.toBeInstanceOf(ScheduleRunNotFoundError);
+ expect(getSchedule).not.toHaveBeenCalled();
});
});
diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
index 5b2229562..733532622 100644
--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts
@@ -1,3 +1,4 @@
+import { createLogger } from 'winston';
import { getPublicBaseUrl } from '../../../src/config';
import { McpServerNotFoundError, type McpServerRecord } from '../../../src/db/mcpServerStore';
import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken';
@@ -52,14 +53,14 @@ function createStore(input?: {
client.deleteMcpAuth.mockResolvedValue(undefined);
const store = new TrueFoundryMcpServerStore({
client,
- context: createTrueFoundryRequestContext({
+ requestContext: createTrueFoundryRequestContext({
tenant_id: TENANT,
subject: input?.subject ?? { id: 'user-1', type: 'user', display_name: 'user-1' },
roles: [],
user_credential: input?.accessToken ?? ACCESS_TOKEN,
}),
agent: undefined,
- logger: { info: jest.fn() },
+ logger: createLogger({ silent: true }),
});
return { store, client };
}
diff --git a/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts b/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts
index 124e2a100..5e1b0d981 100644
--- a/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/accessToken.test.ts
@@ -46,7 +46,9 @@ describe('agentAccessToken', () => {
const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
const logger = { info: jest.fn() };
- await expect(agentAccessToken({ client, context: CONTEXT, agent: AGENT, logger })()).resolves.toBe('agent-token');
+ await expect(agentAccessToken({ client, requestContext: CONTEXT, agent: AGENT, logger })()).resolves.toBe(
+ 'agent-token',
+ );
expect(logger.info).toHaveBeenCalledWith('Exchanging user context for agent access token', {
subject: 'user-1',
agentId: 'ext-agent',
@@ -60,7 +62,7 @@ describe('agentAccessToken', () => {
it('vends once and reuses the token for later calls', async () => {
const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
- const resolve = agentAccessToken({ client, context: CONTEXT, agent: AGENT, logger: LOGGER });
+ const resolve = agentAccessToken({ client, requestContext: CONTEXT, agent: AGENT, logger: LOGGER });
await expect(Promise.all([resolve(), resolve()])).resolves.toEqual(['agent-token', 'agent-token']);
await expect(resolve()).resolves.toBe('agent-token');
@@ -71,7 +73,7 @@ describe('agentAccessToken', () => {
const client = {
vendToken: jest.fn().mockRejectedValueOnce(new Error('vend failed')).mockResolvedValue('agent-token'),
};
- const resolve = agentAccessToken({ client, context: CONTEXT, agent: AGENT, logger: LOGGER });
+ const resolve = agentAccessToken({ client, requestContext: CONTEXT, agent: AGENT, logger: LOGGER });
await expect(resolve()).rejects.toThrow('vend failed');
await expect(resolve()).resolves.toBe('agent-token');
@@ -84,7 +86,7 @@ describe('agentAccessToken', () => {
expect(() =>
agentAccessToken({
client,
- context: CONTEXT,
+ requestContext: CONTEXT,
agent: { ...AGENT, external_id: null },
logger: LOGGER,
}),
@@ -104,9 +106,9 @@ describe('accessTokenForRequest', () => {
const client = { vendToken: jest.fn() };
const context = createTrueFoundryRequestContext(CONTEXT);
- await expect(accessTokenForRequest({ client, context, agent: undefined, logger: LOGGER })()).resolves.toBe(
- 'caller-token',
- );
+ await expect(
+ accessTokenForRequest({ client, requestContext: context, agent: undefined, logger: LOGGER })(),
+ ).resolves.toBe('caller-token');
expect(client.vendToken).not.toHaveBeenCalled();
});
@@ -114,9 +116,9 @@ describe('accessTokenForRequest', () => {
const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
const context = createTrueFoundryRequestContext(CONTEXT);
- await expect(accessTokenForRequest({ client, context, agent: AGENT, logger: LOGGER })()).resolves.toBe(
- 'agent-token',
- );
+ await expect(
+ accessTokenForRequest({ client, requestContext: context, agent: AGENT, logger: LOGGER })(),
+ ).resolves.toBe('agent-token');
expect(client.vendToken).toHaveBeenCalledTimes(1);
});
@@ -124,9 +126,9 @@ describe('accessTokenForRequest', () => {
const client = { vendToken: jest.fn().mockResolvedValue('agent-token') };
const context = createTrueFoundryRequestContext(CONTEXT);
- const model = accessTokenForRequest({ client, context, agent: AGENT, logger: LOGGER });
- const mcp = accessTokenForRequest({ client, context, agent: AGENT, logger: LOGGER });
- const skill = accessTokenForRequest({ client, context, agent: AGENT, logger: LOGGER });
+ const model = accessTokenForRequest({ client, requestContext: context, agent: AGENT, logger: LOGGER });
+ const mcp = accessTokenForRequest({ client, requestContext: context, agent: AGENT, logger: LOGGER });
+ const skill = accessTokenForRequest({ client, requestContext: context, agent: AGENT, logger: LOGGER });
expect(model).toBe(mcp);
expect(mcp).toBe(skill);
@@ -144,10 +146,10 @@ describe('accessTokenForRequest', () => {
const secondRequest = createTrueFoundryRequestContext(CONTEXT);
await expect(
- accessTokenForRequest({ client, context: firstRequest, agent: AGENT, logger: LOGGER })(),
+ accessTokenForRequest({ client, requestContext: firstRequest, agent: AGENT, logger: LOGGER })(),
).resolves.toBe('agent-token');
await expect(
- accessTokenForRequest({ client, context: secondRequest, agent: AGENT, logger: LOGGER })(),
+ accessTokenForRequest({ client, requestContext: secondRequest, agent: AGENT, logger: LOGGER })(),
).resolves.toBe('agent-token');
expect(client.vendToken).toHaveBeenCalledTimes(2);
});
diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
index f6927ede5..021e221fb 100644
--- a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
+++ b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
@@ -1,4 +1,5 @@
import { HTTPException } from 'hono/http-exception';
+import { createLogger } from 'winston';
import type { McpServerRecord } from '../../../src/db/mcpServerStore';
import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken';
import { parsePerServerMcpHeaders } from '../../../src/truefoundry/perServerMcpHeaders';
@@ -44,14 +45,14 @@ const record = (name: string): McpServerRecord => ({
const storeWith = (perServerHeaders: Record<string, Record<string, string>>): TrueFoundryMcpServerStore =>
new TrueFoundryMcpServerStore({
client: unusedClient(),
- context: createTrueFoundryRequestContext({
+ requestContext: createTrueFoundryRequestContext({
tenant_id: 'default',
subject: { id: 'user-1', type: 'user', display_name: 'user-1' },
roles: [],
user_credential: 'caller-token',
}),
agent: undefined,
- logger: { info: jest.fn() },
+ logger: createLogger({ silent: true }),
perServerHeaders,
});