Skip to content

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

add internal list-permissions endpoint (#596)

Sujai Kumar Gupta41112877b1a6
diff --git a/.changeset/list-permissions-api.md b/.changeset/list-permissions-api.md
new file mode 100644
index 000000000..ae4097038
--- /dev/null
+++ b/.changeset/list-permissions-api.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge': patch
+'@truefoundry/trueforge-core': patch
+---
+
+Add POST `/api/internal/list-permissions` via `Authorizer.getPermissions` (owner grants for schedules/sessions; agents include `USE`, with TrueFoundry agents mapped from SFY `USE_AGENT`/`MANAGE_AGENT`/`DELETE_AGENT`).
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index 8e7819783..5844a788e 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -1830,6 +1830,45 @@
],
"type": "object"
},
+ "ListPermissionsRequest": {
+ "properties": {
+ "resource_ids": {
+ "description": "Resource ids of `resource_type` to evaluate for the caller.",
+ "items": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "maxItems": 100,
+ "type": "array"
+ },
+ "resource_type": {
+ "$ref": "#/components/schemas/PermissionResourceType"
+ }
+ },
+ "required": [
+ "resource_type",
+ "resource_ids"
+ ],
+ "type": "object"
+ },
+ "ListPermissionsResponse": {
+ "properties": {
+ "data": {
+ "additionalProperties": {
+ "items": {
+ "$ref": "#/components/schemas/ResourcePermission"
+ },
+ "type": "array"
+ },
+ "description": "Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`.",
+ "type": "object"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"ListScheduleRunsResponse": {
"properties": {
"data": {
@@ -2849,6 +2888,15 @@
],
"type": "object"
},
+ "PermissionResourceType": {
+ "description": "Resource type to evaluate permissions for.",
+ "enum": [
+ "agent",
+ "schedule",
+ "session"
+ ],
+ "type": "string"
+ },
"PreviousTurnIdInput": {
"anyOf": [
{
@@ -2943,6 +2991,15 @@
"pattern": "^[a-z](?:[a-z0-9._-]{0,62}[a-z0-9])$",
"type": "string"
},
+ "ResourcePermission": {
+ "description": "Granted action on a resource.",
+ "enum": [
+ "USE",
+ "MANAGE",
+ "DELETE"
+ ],
+ "type": "string"
+ },
"ResponseFormat": {
"discriminator": {
"mapping": {
@@ -5125,6 +5182,61 @@
},
"openapi": "3.1.0",
"paths": {
+ "/api/internal/list-permissions": {
+ "post": {
+ "description": "Return granted actions for each requested agent, schedule, or session id.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListPermissionsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListPermissionsResponse"
+ }
+ }
+ },
+ "description": "Permissions keyed by resource id."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid request body."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid Bearer token or auth cookie"
+ }
+ },
+ "summary": "List permissions for resources",
+ "tags": [
+ "Internal"
+ ],
+ "x-fern-sdk-group-name": [
+ "internal"
+ ],
+ "x-fern-sdk-method-name": "list_permissions"
+ }
+ },
"/api/internal/metrics/charts": {
"get": {
"description": "List available session metric charts.",
diff --git a/docs/openapi.json b/docs/openapi.json
index 8e7819783..5844a788e 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -1830,6 +1830,45 @@
],
"type": "object"
},
+ "ListPermissionsRequest": {
+ "properties": {
+ "resource_ids": {
+ "description": "Resource ids of `resource_type` to evaluate for the caller.",
+ "items": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "maxItems": 100,
+ "type": "array"
+ },
+ "resource_type": {
+ "$ref": "#/components/schemas/PermissionResourceType"
+ }
+ },
+ "required": [
+ "resource_type",
+ "resource_ids"
+ ],
+ "type": "object"
+ },
+ "ListPermissionsResponse": {
+ "properties": {
+ "data": {
+ "additionalProperties": {
+ "items": {
+ "$ref": "#/components/schemas/ResourcePermission"
+ },
+ "type": "array"
+ },
+ "description": "Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`.",
+ "type": "object"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"ListScheduleRunsResponse": {
"properties": {
"data": {
@@ -2849,6 +2888,15 @@
],
"type": "object"
},
+ "PermissionResourceType": {
+ "description": "Resource type to evaluate permissions for.",
+ "enum": [
+ "agent",
+ "schedule",
+ "session"
+ ],
+ "type": "string"
+ },
"PreviousTurnIdInput": {
"anyOf": [
{
@@ -2943,6 +2991,15 @@
"pattern": "^[a-z](?:[a-z0-9._-]{0,62}[a-z0-9])$",
"type": "string"
},
+ "ResourcePermission": {
+ "description": "Granted action on a resource.",
+ "enum": [
+ "USE",
+ "MANAGE",
+ "DELETE"
+ ],
+ "type": "string"
+ },
"ResponseFormat": {
"discriminator": {
"mapping": {
@@ -5125,6 +5182,61 @@
},
"openapi": "3.1.0",
"paths": {
+ "/api/internal/list-permissions": {
+ "post": {
+ "description": "Return granted actions for each requested agent, schedule, or session id.",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListPermissionsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListPermissionsResponse"
+ }
+ }
+ },
+ "description": "Permissions keyed by resource id."
+ },
+ "400": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid request body."
+ },
+ "401": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Invalid Bearer token or auth cookie"
+ }
+ },
+ "summary": "List permissions for resources",
+ "tags": [
+ "Internal"
+ ],
+ "x-fern-sdk-group-name": [
+ "internal"
+ ],
+ "x-fern-sdk-method-name": "list_permissions"
+ }
+ },
"/api/internal/metrics/charts": {
"get": {
"description": "List available session metric charts.",
diff --git a/packages/trueforge-core/src/agent-session/index.ts b/packages/trueforge-core/src/agent-session/index.ts
index 4a6a8471a..ce973db0a 100644
--- a/packages/trueforge-core/src/agent-session/index.ts
+++ b/packages/trueforge-core/src/agent-session/index.ts
@@ -73,6 +73,7 @@ export type {
CreateTurnInput,
DeleteSessionInput,
FreezeAndGetTurnInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
GetTurnInput,
diff --git a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts b/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
index 7b2d5aa3e..b11a7ca1d 100644
--- a/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
+++ b/packages/trueforge-core/src/agent-session/store/ISessionStore.ts
@@ -44,6 +44,12 @@ export interface GetSessionInput {
session_id: string;
}
+export interface GetOwnedIdsInput {
+ tenant_id: string;
+ ids: readonly string[];
+ subject_id: string;
+}
+
export interface GetSessionByExternalIdInput {
tenant_id: string;
external_id: string;
@@ -255,6 +261,12 @@ export interface ISessionStore<
*/
getSession(input: GetSessionInput): Promise<SessionRecord<TSessionCustom> | undefined>;
+ /**
+ * Session ids among `ids` owned by `subject_id`. Empty `ids` β†’ `[]`.
+ * Does **not** bump `last_activity_timestamp_ms`.
+ */
+ getOwnedIds(input: GetOwnedIdsInput): Promise<readonly string[]>;
+
/**
* Lookup by tenant-scoped `external_id`. Missing or null external ids are not found.
* Does **not** bump `last_activity_timestamp_ms` (read path).
diff --git a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
index a63dddc80..a2e114b61 100644
--- a/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
+++ b/packages/trueforge-core/src/agent-session/store/InMemorySessionStore.ts
@@ -14,6 +14,7 @@ import type {
CreateTurnInput,
DeleteSessionInput,
FreezeAndGetTurnInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
GetTurnInput,
@@ -226,6 +227,24 @@ export class InMemorySessionStore<
return stored?.record.tenant_id === input.tenant_id ? deepCopy(stored.record) : undefined;
}
+ async getOwnedIds(input: GetOwnedIdsInput): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const wanted = new Set(input.ids);
+ const ids: string[] = [];
+ for (const stored of this.sessions.values()) {
+ if (
+ stored.record.tenant_id === input.tenant_id &&
+ wanted.has(stored.record.session_id) &&
+ stored.record.created_by_subject.subject_id === input.subject_id
+ ) {
+ ids.push(stored.record.session_id);
+ }
+ }
+ return ids;
+ }
+
async getSessionByExternalId(input: GetSessionByExternalIdInput): Promise<SessionRecord<TSessionCustom> | undefined> {
for (const stored of this.sessions.values()) {
if (stored.record.tenant_id === input.tenant_id && stored.record.external_id === input.external_id) {
diff --git a/packages/trueforge-sdk/README.md b/packages/trueforge-sdk/README.md
index 6b618b865..ebde28230 100644
--- a/packages/trueforge-sdk/README.md
+++ b/packages/trueforge-sdk/README.md
@@ -68,7 +68,7 @@ following namespace:
```typescript
import { TrueForge } from "@truefoundry/trueforge-sdk";
-const request: TrueForge.CreateAgentRequest = {
+const request: TrueForge.ListPermissionsRequest = {
...
};
```
@@ -504,9 +504,9 @@ const text = new TextDecoder().decode(bytes);
This SDK supports direct imports of subpackage clients, which allows JavaScript bundlers to tree-shake and include only the imported subpackage code. This results in much smaller bundle sizes.
```typescript
-import { AgentsClient } from '@truefoundry/trueforge-sdk/agents';
+import { InternalClient } from '@truefoundry/trueforge-sdk/internal';
-const client = new AgentsClient({...});
+const client = new InternalClient({...});
```
### Additional Headers
diff --git a/packages/trueforge-sdk/package.json b/packages/trueforge-sdk/package.json
index 717c68555..951b6f679 100644
--- a/packages/trueforge-sdk/package.json
+++ b/packages/trueforge-sdk/package.json
@@ -33,6 +33,17 @@
},
"default": "./dist/cjs/serialization/index.js"
},
+ "./internal": {
+ "import": {
+ "types": "./dist/esm/api/resources/internal/exports.d.mts",
+ "default": "./dist/esm/api/resources/internal/exports.mjs"
+ },
+ "require": {
+ "types": "./dist/cjs/api/resources/internal/exports.d.ts",
+ "default": "./dist/cjs/api/resources/internal/exports.js"
+ },
+ "default": "./dist/cjs/api/resources/internal/exports.js"
+ },
"./agents": {
"import": {
"types": "./dist/esm/api/resources/agents/exports.d.mts",
@@ -176,17 +187,6 @@
},
"default": "./dist/cjs/api/resources/catalogs/resources/skills/exports.js"
},
- "./internal": {
- "import": {
- "types": "./dist/esm/api/resources/internal/exports.d.mts",
- "default": "./dist/esm/api/resources/internal/exports.mjs"
- },
- "require": {
- "types": "./dist/cjs/api/resources/internal/exports.d.ts",
- "default": "./dist/cjs/api/resources/internal/exports.js"
- },
- "default": "./dist/cjs/api/resources/internal/exports.js"
- },
"./internal/metrics": {
"import": {
"types": "./dist/esm/api/resources/internal/resources/metrics/exports.d.mts",
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 41fe28921..43d993f88 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -1,4 +1,71 @@
# Reference
+## Internal
+<details><summary><code>client.internal.<a href="/src/api/resources/internal/client/Client.ts">listPermissions</a>({ ...params }) -> TrueForge.ListPermissionsResponse</code></summary>
+<dl>
+<dd>
+
+#### πŸ“ Description
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+Return granted actions for each requested agent, schedule, or session id.
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### πŸ”Œ Usage
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+```typescript
+await client.internal.listPermissions({
+ resourceIds: ["resource_ids"],
+ resourceType: "agent"
+});
+
+```
+</dd>
+</dl>
+</dd>
+</dl>
+
+#### βš™οΈ Parameters
+
+<dl>
+<dd>
+
+<dl>
+<dd>
+
+**request:** `TrueForge.ListPermissionsRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `InternalClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
+</dd>
+</dl>
+</details>
+
## Agents
<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">list</a>() -> TrueForge.ListAgentsResponse</code></summary>
<dl>
diff --git a/packages/trueforge-sdk/src/Client.ts b/packages/trueforge-sdk/src/Client.ts
index 6c3ca5450..d8dab2878 100644
--- a/packages/trueforge-sdk/src/Client.ts
+++ b/packages/trueforge-sdk/src/Client.ts
@@ -23,6 +23,7 @@ export declare namespace TrueForge {
export class TrueForge {
protected readonly _options: NormalizedClientOptionsWithAuth<TrueForge.Options>;
+ protected _internal: InternalClient | undefined;
protected _agents: AgentsClient | undefined;
protected _auth: AuthClient | undefined;
protected _server: ServerClient | undefined;
@@ -32,13 +33,16 @@ export class TrueForge {
protected _sessions: SessionsClient | undefined;
protected _skills: SkillsClient | undefined;
protected _catalogs: CatalogsClient | undefined;
- protected _internal: InternalClient | undefined;
protected _settings: SettingsClient | undefined;
constructor(options: TrueForge.Options) {
this._options = normalizeClientOptionsWithAuth(options);
}
+ public get internal(): InternalClient {
+ return (this._internal ??= new InternalClient(this._options));
+ }
+
public get agents(): AgentsClient {
return (this._agents ??= new AgentsClient(this._options));
}
@@ -75,10 +79,6 @@ export class TrueForge {
return (this._catalogs ??= new CatalogsClient(this._options));
}
- public get internal(): InternalClient {
- return (this._internal ??= new InternalClient(this._options));
- }
-
public get settings(): SettingsClient {
return (this._settings ??= new SettingsClient(this._options));
}
diff --git a/packages/trueforge-sdk/src/api/resources/index.ts b/packages/trueforge-sdk/src/api/resources/index.ts
index c337b9722..000fb4979 100644
--- a/packages/trueforge-sdk/src/api/resources/index.ts
+++ b/packages/trueforge-sdk/src/api/resources/index.ts
@@ -2,6 +2,7 @@ export * from "./agents/client/requests/index.js";
export * as agents from "./agents/index.js";
export * as auth from "./auth/index.js";
export * as catalogs from "./catalogs/index.js";
+export * from "./internal/client/requests/index.js";
export * as internal from "./internal/index.js";
export * from "./mcpServers/client/requests/index.js";
export * as mcpServers from "./mcpServers/index.js";
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 01a773804..d47c23433 100644
--- a/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts
@@ -1,13 +1,22 @@
// This file was auto-generated by Fern from our API Definition.
-import type { BaseClientOptions } from "../../../../BaseClient.js";
+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";
import { AgentsClient } from "../resources/agents/client/Client.js";
import { MetricsClient } from "../resources/metrics/client/Client.js";
import { SessionsClient } from "../resources/sessions/client/Client.js";
export declare namespace InternalClient {
export type Options = BaseClientOptions;
+
+ export interface RequestOptions extends BaseRequestOptions {}
}
export class InternalClient {
@@ -31,4 +40,118 @@ export class InternalClient {
public get agents(): AgentsClient {
return (this._agents ??= new AgentsClient(this._options));
}
+
+ /**
+ * Return granted actions for each requested agent, schedule, or session id.
+ *
+ * @param {TrueForge.ListPermissionsRequest} request
+ * @param {InternalClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.UnauthorizedError}
+ * @throws {@link errors.TrueForgeError}
+ * @throws {@link errors.TrueForgeTimeoutError}
+ *
+ * @example
+ * await client.internal.listPermissions({
+ * resourceIds: ["resource_ids"],
+ * resourceType: "agent"
+ * })
+ */
+ public listPermissions(
+ request: TrueForge.ListPermissionsRequest,
+ requestOptions?: InternalClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueForge.ListPermissionsResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__listPermissions(request, requestOptions));
+ }
+
+ private async __listPermissions(
+ request: TrueForge.ListPermissionsRequest,
+ requestOptions?: InternalClient.RequestOptions,
+ ): Promise<core.WithRawResponse<TrueForge.ListPermissionsResponse>> {
+ 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/list-permissions",
+ ),
+ method: "POST",
+ headers: _headers,
+ contentType: "application/json",
+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
+ requestType: "json",
+ body: mergeAdditionalBodyParameters(
+ serializers.ListPermissionsRequest.jsonOrThrow(request, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ omitUndefined: true,
+ }),
+ requestOptions?.additionalBodyParameters,
+ ),
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
+ abortSignal: requestOptions?.abortSignal,
+ fetchFn: this._options?.fetch,
+ logging: this._options.logging,
+ });
+ if (_response.ok) {
+ return {
+ data: serializers.ListPermissionsResponse.parseOrThrow(_response.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ rawResponse: _response.rawResponse,
+ };
+ }
+
+ if (_response.error.reason === "status-code") {
+ switch (_response.error.statusCode) {
+ case 400:
+ throw new TrueForge.BadRequestError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ case 401:
+ throw new TrueForge.UnauthorizedError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
+ }
+
+ return handleNonStatusCodeError(
+ _response.error,
+ _response.rawResponse,
+ "POST",
+ "/api/internal/list-permissions",
+ );
+ }
}
diff --git a/packages/trueforge-sdk/src/api/resources/internal/client/index.ts b/packages/trueforge-sdk/src/api/resources/internal/client/index.ts
index cb0ff5c3b..195f9aa8a 100644
--- a/packages/trueforge-sdk/src/api/resources/internal/client/index.ts
+++ b/packages/trueforge-sdk/src/api/resources/internal/client/index.ts
@@ -1 +1 @@
-export {};
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/api/resources/internal/client/requests/ListPermissionsRequest.ts b/packages/trueforge-sdk/src/api/resources/internal/client/requests/ListPermissionsRequest.ts
new file mode 100644
index 000000000..cdb64d26a
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/client/requests/ListPermissionsRequest.ts
@@ -0,0 +1,16 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../index.js";
+
+/**
+ * @example
+ * {
+ * resourceIds: ["resource_ids"],
+ * resourceType: "agent"
+ * }
+ */
+export interface ListPermissionsRequest {
+ /** Resource ids of `resource_type` to evaluate for the caller. */
+ resourceIds: string[];
+ resourceType: TrueForge.PermissionResourceType;
+}
diff --git a/packages/trueforge-sdk/src/api/resources/internal/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/internal/client/requests/index.ts
new file mode 100644
index 000000000..21bd7ad5d
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/resources/internal/client/requests/index.ts
@@ -0,0 +1 @@
+export type { ListPermissionsRequest } from "./ListPermissionsRequest.js";
diff --git a/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts b/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts
new file mode 100644
index 000000000..43eeae2c7
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts
@@ -0,0 +1,8 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../index.js";
+
+export interface ListPermissionsResponse {
+ /** Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`. */
+ data: Record<string, TrueForge.ResourcePermission[]>;
+}
diff --git a/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts b/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts
new file mode 100644
index 000000000..8c5f7f2d1
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** Resource type to evaluate permissions for. */
+export const PermissionResourceType = {
+ Agent: "agent",
+ Schedule: "schedule",
+ Session: "session",
+} as const;
+export type PermissionResourceType = (typeof PermissionResourceType)[keyof typeof PermissionResourceType];
diff --git a/packages/trueforge-sdk/src/api/types/ResourcePermission.ts b/packages/trueforge-sdk/src/api/types/ResourcePermission.ts
new file mode 100644
index 000000000..9df249108
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/ResourcePermission.ts
@@ -0,0 +1,9 @@
+// This file was auto-generated by Fern from our API Definition.
+
+/** Granted action on a resource. */
+export const ResourcePermission = {
+ Use: "USE",
+ Manage: "MANAGE",
+ Delete: "DELETE",
+} as const;
+export type ResourcePermission = (typeof ResourcePermission)[keyof typeof ResourcePermission];
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index 97e64b221..635efb65a 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -89,6 +89,7 @@ export * from "./ListAvailableSkillsResponse.js";
export * from "./ListMcpServersResponse.js";
export * from "./ListMcpServerToolsResponse.js";
export * from "./ListModelProvidersResponse.js";
+export * from "./ListPermissionsResponse.js";
export * from "./ListScheduleRunsResponse.js";
export * from "./ListSchedulesResponse.js";
export * from "./ListSessionEventsResponse.js";
@@ -134,12 +135,14 @@ export * from "./ModelProviderAuth.js";
export * from "./ModelProviderManifest.js";
export * from "./MoonshotModelProvider.js";
export * from "./OpenAiModelProvider.js";
+export * from "./PermissionResourceType.js";
export * from "./PreviousTurnIdInput.js";
export * from "./RawToolCall.js";
export * from "./ReasoningEffort.js";
export * from "./RequestErrorResponse.js";
export * from "./RequestErrorResponseError.js";
export * from "./ResourceName.js";
+export * from "./ResourcePermission.js";
export * from "./ResponseFormat.js";
export * from "./ResponseFormatJsonObject.js";
export * from "./ResponseFormatJsonSchema.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/index.ts b/packages/trueforge-sdk/src/serialization/resources/index.ts
index c0588507f..4d4bfd3a0 100644
--- a/packages/trueforge-sdk/src/serialization/resources/index.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/index.ts
@@ -1,5 +1,6 @@
export * from "./agents/client/requests/index.js";
export * as agents from "./agents/index.js";
+export * from "./internal/client/requests/index.js";
export * as internal from "./internal/index.js";
export * from "./schedules/client/requests/index.js";
export * as schedules from "./schedules/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/client/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/client/index.ts
new file mode 100644
index 000000000..195f9aa8a
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/client/index.ts
@@ -0,0 +1 @@
+export * from "./requests/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/ListPermissionsRequest.ts b/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/ListPermissionsRequest.ts
new file mode 100644
index 000000000..ec5c5aeb4
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/ListPermissionsRequest.ts
@@ -0,0 +1,21 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../../../../api/index.js";
+import * as core from "../../../../../core/index.js";
+import type * as serializers from "../../../../index.js";
+import { PermissionResourceType } from "../../../../types/PermissionResourceType.js";
+
+export const ListPermissionsRequest: core.serialization.Schema<
+ serializers.ListPermissionsRequest.Raw,
+ TrueForge.ListPermissionsRequest
+> = core.serialization.object({
+ resourceIds: core.serialization.property("resource_ids", core.serialization.list(core.serialization.string())),
+ resourceType: core.serialization.property("resource_type", PermissionResourceType),
+});
+
+export declare namespace ListPermissionsRequest {
+ export interface Raw {
+ resource_ids: string[];
+ resource_type: PermissionResourceType.Raw;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/index.ts
new file mode 100644
index 000000000..d49472ca1
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/client/requests/index.ts
@@ -0,0 +1 @@
+export { ListPermissionsRequest } from "./ListPermissionsRequest.js";
diff --git a/packages/trueforge-sdk/src/serialization/resources/internal/index.ts b/packages/trueforge-sdk/src/serialization/resources/internal/index.ts
index e445af0d8..9eb1192dc 100644
--- a/packages/trueforge-sdk/src/serialization/resources/internal/index.ts
+++ b/packages/trueforge-sdk/src/serialization/resources/internal/index.ts
@@ -1 +1,2 @@
+export * from "./client/index.js";
export * from "./resources/index.js";
diff --git a/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts
new file mode 100644
index 000000000..40ab93f25
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts
@@ -0,0 +1,19 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+import { ResourcePermission } from "./ResourcePermission.js";
+
+export const ListPermissionsResponse: core.serialization.ObjectSchema<
+ serializers.ListPermissionsResponse.Raw,
+ TrueForge.ListPermissionsResponse
+> = core.serialization.object({
+ data: core.serialization.record(core.serialization.string(), core.serialization.list(ResourcePermission)),
+});
+
+export declare namespace ListPermissionsResponse {
+ export interface Raw {
+ data: Record<string, ResourcePermission.Raw[]>;
+ }
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts b/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts
new file mode 100644
index 000000000..06acf3867
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const PermissionResourceType: core.serialization.Schema<
+ serializers.PermissionResourceType.Raw,
+ TrueForge.PermissionResourceType
+> = core.serialization.enum_(["agent", "schedule", "session"]);
+
+export declare namespace PermissionResourceType {
+ export type Raw = "agent" | "schedule" | "session";
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts b/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts
new file mode 100644
index 000000000..d8b3c4a51
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const ResourcePermission: core.serialization.Schema<
+ serializers.ResourcePermission.Raw,
+ TrueForge.ResourcePermission
+> = core.serialization.enum_(["USE", "MANAGE", "DELETE"]);
+
+export declare namespace ResourcePermission {
+ export type Raw = "USE" | "MANAGE" | "DELETE";
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index 97e64b221..635efb65a 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -89,6 +89,7 @@ export * from "./ListAvailableSkillsResponse.js";
export * from "./ListMcpServersResponse.js";
export * from "./ListMcpServerToolsResponse.js";
export * from "./ListModelProvidersResponse.js";
+export * from "./ListPermissionsResponse.js";
export * from "./ListScheduleRunsResponse.js";
export * from "./ListSchedulesResponse.js";
export * from "./ListSessionEventsResponse.js";
@@ -134,12 +135,14 @@ export * from "./ModelProviderAuth.js";
export * from "./ModelProviderManifest.js";
export * from "./MoonshotModelProvider.js";
export * from "./OpenAiModelProvider.js";
+export * from "./PermissionResourceType.js";
export * from "./PreviousTurnIdInput.js";
export * from "./RawToolCall.js";
export * from "./ReasoningEffort.js";
export * from "./RequestErrorResponse.js";
export * from "./RequestErrorResponseError.js";
export * from "./ResourceName.js";
+export * from "./ResourcePermission.js";
export * from "./ResponseFormat.js";
export * from "./ResponseFormatJsonObject.js";
export * from "./ResponseFormatJsonSchema.js";
diff --git a/packages/trueforge-sdk/tests/wire/internal.test.ts b/packages/trueforge-sdk/tests/wire/internal.test.ts
new file mode 100644
index 000000000..d2bcd38fc
--- /dev/null
+++ b/packages/trueforge-sdk/tests/wire/internal.test.ts
@@ -0,0 +1,79 @@
+// 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("InternalClient", () => {
+ test("list_permissions (1)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { resource_ids: ["resource_ids"], resource_type: "agent" };
+ const rawResponseBody = { data: { key: ["USE"] } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/list-permissions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.internal.listPermissions({
+ resourceIds: ["resource_ids"],
+ resourceType: "agent",
+ });
+ expect(response).toEqual({
+ data: {
+ key: ["USE"],
+ },
+ });
+ });
+
+ test("list_permissions (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { resource_ids: ["resource_ids", "resource_ids"], resource_type: "agent" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/list-permissions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(400)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.internal.listPermissions({
+ resourceIds: ["resource_ids", "resource_ids"],
+ resourceType: "agent",
+ });
+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);
+ });
+
+ test("list_permissions (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { resource_ids: ["resource_ids", "resource_ids"], resource_type: "agent" };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/internal/list-permissions")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(401)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.internal.listPermissions({
+ resourceIds: ["resource_ids", "resource_ids"],
+ resourceType: "agent",
+ });
+ }).rejects.toThrow(TrueForgeTypes.UnauthorizedError);
+ });
+});
diff --git a/packages/trueforge/src/apis/permissions.ts b/packages/trueforge/src/apis/permissions.ts
new file mode 100644
index 000000000..562ceffa0
--- /dev/null
+++ b/packages/trueforge/src/apis/permissions.ts
@@ -0,0 +1,59 @@
+/**
+ * Internal list-permissions API (mounted at /api/internal).
+ */
+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
+import type { ISessionStore } from '@truefoundry/trueforge-core/agent-session';
+import type { Context } from 'hono';
+import type { Authorizer, GetPermissionsInput } from '../auth/authorizer';
+import type { ResolveRequestContext } from '../auth/identity';
+import type { IAgentStore } from '../db/agentStore';
+import type { IScheduleStore } from '../db/scheduleStore';
+import { listPermissionsRoute } from '../routes/permissionRoutes';
+import type { ListPermissionsRequest } from '../schemas/permissions';
+
+export interface PermissionsRouterDeps<TTransaction> {
+ authorizer: Authorizer;
+ resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;
+ scheduleStore: IScheduleStore<TTransaction>;
+ sessionStore: ISessionStore;
+ resolveRequestContext: ResolveRequestContext;
+}
+
+export function createPermissionsRouter<TTransaction>(deps: PermissionsRouterDeps<TTransaction>) {
+ const listHandler: RouteHandler<typeof listPermissionsRoute> = async c => {
+ const body: ListPermissionsRequest = c.req.valid('json');
+ const requestContext = deps.resolveRequestContext(c);
+ const { resource_type: resourceType, resource_ids: resourceIds } = body;
+
+ let input: GetPermissionsInput;
+ if (resourceType === 'agent') {
+ input = {
+ resourceType: 'agent',
+ requestContext,
+ resourceIds,
+ store: deps.resolveAgentStore(c),
+ };
+ } else if (resourceType === 'schedule') {
+ input = {
+ resourceType: 'schedule',
+ requestContext,
+ resourceIds,
+ store: deps.scheduleStore,
+ };
+ } else {
+ input = {
+ resourceType: 'session',
+ requestContext,
+ resourceIds,
+ store: deps.sessionStore,
+ };
+ }
+
+ const data = await deps.authorizer.getPermissions(input);
+ return c.json({ data }, 200);
+ };
+
+ const router = new OpenAPIHono();
+ router.openapi(listPermissionsRoute, listHandler);
+ return router;
+}
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index 1d421f6c8..fa75cebed 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -17,6 +17,7 @@ import { createCatalogRouter } from './apis/catalog';
import { createMcpOAuthRouter } from './apis/mcpOAuth';
import { createMcpServersRouter } from './apis/mcpServers';
import { createModelsRouter } from './apis/models';
+import { createPermissionsRouter } from './apis/permissions';
import { createSchedulesRouter } from './apis/schedules';
import { createInternalMetricsRouter } from './apis/sessionMetrics';
import { createInternalSessionsRouter, createSessionsRouter } from './apis/sessions';
@@ -383,6 +384,19 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
authMiddleware,
),
);
+ app.route(
+ '/api/internal',
+ withAuth(
+ createPermissionsRouter({
+ authorizer: deps.authorizer,
+ resolveAgentStore: deps.resolveAgentStore,
+ scheduleStore: deps.scheduleStore,
+ sessionStore: deps.sessionStore,
+ resolveRequestContext,
+ }),
+ authMiddleware,
+ ),
+ );
app.route(
'/api/v1/sessions',
withAuth(
diff --git a/packages/trueforge/src/auth/authorizer.ts b/packages/trueforge/src/auth/authorizer.ts
index b181b88f8..8182bc360 100644
--- a/packages/trueforge/src/auth/authorizer.ts
+++ b/packages/trueforge/src/auth/authorizer.ts
@@ -1,13 +1,34 @@
-import type { AgentRecord } from '../db/agentStore';
+import type { ISessionStore } from '@truefoundry/trueforge-core/agent-session';
+import type { AgentRecord, IAgentStore } from '../db/agentStore';
+import type { IScheduleStore } from '../db/scheduleStore';
+import {
+ AGENT_OWNER_PERMISSIONS,
+ AGENT_USE_PERMISSIONS,
+ emptyPermissionsByResourceId,
+ SCHEDULE_OWNER_PERMISSIONS,
+ SESSION_OWNER_PERMISSIONS,
+ type ResourcePermission,
+} from '../schemas/permissions';
import type { RequestContext } from './identity';
export type AgentAction = 'read' | 'use' | 'manage' | 'delete';
export type AgentListAccess = { kind: 'all' } | { kind: 'agent_external_ids'; agent_external_ids: readonly string[] };
+interface GetPermissionsBase {
+ requestContext: RequestContext;
+ resourceIds: readonly string[];
+}
+
+export type GetPermissionsInput =
+ | (GetPermissionsBase & { resourceType: 'agent'; store: IAgentStore })
+ | (GetPermissionsBase & { resourceType: 'schedule'; store: IScheduleStore })
+ | (GetPermissionsBase & { resourceType: 'session'; store: ISessionStore });
+
export interface Authorizer {
listAgentAccess(input: { context: RequestContext; action: AgentAction }): Promise<AgentListAccess>;
canAccessAgent(input: { context: RequestContext; action: AgentAction; agent: AgentRecord }): Promise<boolean>;
+ getPermissions(input: GetPermissionsInput): Promise<Record<string, ResourcePermission[]>>;
}
/** Standalone and OIDC: tenant-local agents. Read/use are unconstrained; manage/delete are creator-only. */
@@ -22,4 +43,43 @@ export class TrueForgeAuthorizer implements Authorizer {
}
return Promise.resolve(input.agent.created_by_subject.subject_id === input.context.subject.id);
}
+
+ async getPermissions(input: GetPermissionsInput): Promise<Record<string, ResourcePermission[]>> {
+ const data = emptyPermissionsByResourceId(input.resourceIds);
+
+ if (input.resourceType === 'agent') {
+ const ownedIds = await input.store.getOwnedIds({
+ tenant_id: input.requestContext.tenant_id,
+ ids: input.resourceIds,
+ subject_id: input.requestContext.subject.id,
+ });
+ const owned = new Set(ownedIds);
+ for (const id of input.resourceIds) {
+ data[id] = owned.has(id) ? [...AGENT_OWNER_PERMISSIONS] : [...AGENT_USE_PERMISSIONS];
+ }
+ return data;
+ }
+
+ if (input.resourceType === 'schedule') {
+ const ownedIds = await input.store.getOwnedIds({
+ tenant_id: input.requestContext.tenant_id,
+ ids: input.resourceIds,
+ subject_id: input.requestContext.subject.id,
+ });
+ for (const id of ownedIds) {
+ data[id] = [...SCHEDULE_OWNER_PERMISSIONS];
+ }
+ return data;
+ }
+
+ const ownedIds = await input.store.getOwnedIds({
+ tenant_id: input.requestContext.tenant_id,
+ ids: input.resourceIds,
+ subject_id: input.requestContext.subject.id,
+ });
+ for (const id of ownedIds) {
+ data[id] = [...SESSION_OWNER_PERMISSIONS];
+ }
+ return data;
+ }
}
diff --git a/packages/trueforge/src/db/agentStore.ts b/packages/trueforge/src/db/agentStore.ts
index cbbe6f1fb..51f81d8af 100644
--- a/packages/trueforge/src/db/agentStore.ts
+++ b/packages/trueforge/src/db/agentStore.ts
@@ -37,6 +37,22 @@ export interface ListAgentsInput {
external_ids?: readonly string[];
}
+export interface GetOwnedIdsInput {
+ tenant_id: string;
+ ids: readonly string[];
+ subject_id: string;
+}
+
+export interface GetExternalIdsByIdsInput {
+ tenant_id: string;
+ ids: readonly string[];
+}
+
+export interface AgentExternalIdRow {
+ id: string;
+ external_id: string;
+}
+
export interface CreateAgentInput {
tenant_id: string;
name: ResourceName;
@@ -89,6 +105,13 @@ export class AgentExternalIdConflictError extends Error {
export interface IAgentStore<TTransaction = never> {
listAgents(input: ListAgentsInput, transaction?: TTransaction): Promise<AgentRecord[]>;
+ /** Ids among `ids` owned by `subject_id`. Empty `ids` β†’ `[]`. */
+ getOwnedIds(input: GetOwnedIdsInput, transaction?: TTransaction): Promise<readonly string[]>;
+ /** Agents with a non-null `external_id` among `ids`. Empty `ids` β†’ `[]`. */
+ getExternalIdsByIds(
+ input: GetExternalIdsByIdsInput,
+ transaction?: TTransaction,
+ ): Promise<readonly AgentExternalIdRow[]>;
getAgent(input: GetAgentInput, transaction?: TTransaction): Promise<AgentRecord | undefined>;
/** Inserts a new agent with a generated ULID. Throws AgentNameConflictError or AgentExternalIdConflictError on unique clash. */
createAgent(input: CreateAgentInput, transaction?: TTransaction): Promise<AgentRecord>;
diff --git a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
index 38f68fded..6f0ab7056 100644
--- a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
+++ b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts
@@ -1,14 +1,17 @@
import { CreatedBySubjectSchema } from '@truefoundry/trueforge-core/agent-session';
-import type { Kysely, Selectable, Transaction } from 'kysely';
+import { sql, type Kysely, type Selectable, type Transaction } from 'kysely';
import { newId } from '../../../utils/id';
import {
AgentExternalIdConflictError,
AgentNameConflictError,
parseStoredAgentSpec,
+ type AgentExternalIdRow,
type AgentRecord,
type CreateAgentInput,
type DeleteAgentInput,
type GetAgentInput,
+ type GetExternalIdsByIdsInput,
+ type GetOwnedIdsInput,
type IAgentStore,
type ListAgentsInput,
type UpdateAgentInput,
@@ -69,6 +72,39 @@ export class PostgresAgentStore implements IAgentStore<Transaction<Database>> {
return rows.map(toRecord);
}
+ async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('agent')
+ .select('id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where(sql`created_by_subject->>'subject_id'`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.id);
+ }
+
+ async getExternalIdsByIds(
+ input: GetExternalIdsByIdsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<readonly AgentExternalIdRow[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('agent')
+ .select(['id', 'external_id'])
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where('external_id', 'is not', null)
+ .execute();
+ return rows.flatMap(row => (row.external_id ? [{ id: row.id, external_id: row.external_id }] : []));
+ }
+
async getAgent(input: GetAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord | undefined> {
const db = transaction ?? this.#db;
let query = db.selectFrom('agent').selectAll().where('tenant_id', '=', input.tenant_id);
diff --git a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
index da57a074a..3cd91dff6 100644
--- a/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
+++ b/packages/trueforge/src/db/postgres/schedule-store/PostgresScheduleStore.ts
@@ -3,7 +3,7 @@ import {
decodeOffsetPageToken,
paginateOffsetRows,
} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';
-import type { Kysely, Selectable, Transaction } from 'kysely';
+import { sql, type Kysely, type Selectable, type Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import { newId } from '../../../utils/id';
import {
@@ -15,6 +15,7 @@ import {
type CreateScheduleInput,
type CreateScheduleRunInput,
type DeleteScheduleInput,
+ type GetOwnedIdsInput,
type GetRunInput,
type GetScheduledRunForInput,
type GetScheduleInput,
@@ -241,6 +242,21 @@ export class PostgresScheduleStore implements IScheduleStore<Transaction<Databas
return { data: data.map(toScheduleRecord), pagination };
}
+ async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('schedule')
+ .select('id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where(sql`created_by_subject->>'subject_id'`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.id);
+ }
+
async listRuns(
input: ListRunsInput,
transaction?: Transaction<Database>,
diff --git a/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts
index 4d4ec73ed..1462a087f 100644
--- a/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts
+++ b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts
@@ -10,6 +10,7 @@ import type {
CreateTurnInput,
DeleteSessionInput,
FreezeAndGetTurnInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
GetTurnInput,
@@ -42,6 +43,7 @@ import {
import {
createSession as createSessionQuery,
deleteSession as deleteSessionQuery,
+ getOwnedIds as getOwnedIdsQuery,
getSessionByExternalId as getSessionByExternalIdQuery,
getSession as getSessionQuery,
listSessions as listSessionsQuery,
@@ -104,6 +106,10 @@ export class PostgresSessionStore implements ISessionStore<SessionCustom, TurnCu
return getSessionQuery(this.db, input);
}
+ getOwnedIds(input: GetOwnedIdsInput): Promise<readonly string[]> {
+ return getOwnedIdsQuery(this.db, input);
+ }
+
getSessionByExternalId(input: GetSessionByExternalIdInput): Promise<SessionRecord<SessionCustom> | undefined> {
return getSessionByExternalIdQuery(this.db, input);
}
diff --git a/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts b/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
index 333bc7bca..6b45219ce 100644
--- a/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/postgres/session-store/queries/sessions.ts
@@ -12,6 +12,7 @@ import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/mo
import type {
CreateSessionInput,
DeleteSessionInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
ListSessionsInput,
@@ -161,6 +162,20 @@ export async function getSession(
return mapRowToSessionRecord(row);
}
+export async function getOwnedIds(db: Kysely<Database>, input: GetOwnedIdsInput): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const rows = await db
+ .selectFrom('session')
+ .select('session_id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', 'in', [...input.ids])
+ .where(sql`created_by_subject->>'subject_id'`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.session_id);
+}
+
export async function getSessionByExternalId(
db: Kysely<Database>,
input: GetSessionByExternalIdInput,
diff --git a/packages/trueforge/src/db/scheduleStore.ts b/packages/trueforge/src/db/scheduleStore.ts
index 6ecf37d4e..541037202 100644
--- a/packages/trueforge/src/db/scheduleStore.ts
+++ b/packages/trueforge/src/db/scheduleStore.ts
@@ -117,6 +117,12 @@ export interface GetScheduleInput {
id: string;
}
+export interface GetOwnedIdsInput {
+ tenant_id: string;
+ ids: readonly string[];
+ subject_id: string;
+}
+
export interface CreateScheduleInput {
tenant_id: string;
agent_id: string;
@@ -247,6 +253,8 @@ export interface IScheduleStore<TTransaction = never> {
input: ListSchedulesInput,
transaction?: TTransaction,
): Promise<{ data: ScheduleRecord[]; pagination: TokenPagination }>;
+ /** Ids among `ids` owned by `subject_id`. Empty `ids` β†’ `[]`. */
+ getOwnedIds(input: GetOwnedIdsInput, transaction?: TTransaction): Promise<readonly string[]>;
// --- schedule_run ---
/** One run by immutable id. */
diff --git a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
index e4bd2463c..80487cf54 100644
--- a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
+++ b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts
@@ -3,16 +3,19 @@ import {
type AgentSpec,
type CreatedBySubject,
} from '@truefoundry/trueforge-core/agent-session';
-import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
+import { sql, type ExpressionBuilder, type Kysely, type Transaction } from 'kysely';
import { newId } from '../../../utils/id';
import {
AgentExternalIdConflictError,
AgentNameConflictError,
parseStoredAgentSpec,
+ type AgentExternalIdRow,
type AgentRecord,
type CreateAgentInput,
type DeleteAgentInput,
type GetAgentInput,
+ type GetExternalIdsByIdsInput,
+ type GetOwnedIdsInput,
type IAgentStore,
type ListAgentsInput,
type UpdateAgentInput,
@@ -72,6 +75,39 @@ export class SqliteAgentStore implements IAgentStore<Transaction<Database>> {
return rows.map(toRecord);
}
+ async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('agent')
+ .select('id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where(sql`json_extract(created_by_subject, '$.subject_id')`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.id);
+ }
+
+ async getExternalIdsByIds(
+ input: GetExternalIdsByIdsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<readonly AgentExternalIdRow[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('agent')
+ .select(['id', 'external_id'])
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where('external_id', 'is not', null)
+ .execute();
+ return rows.flatMap(row => (row.external_id ? [{ id: row.id, external_id: row.external_id }] : []));
+ }
+
async getAgent(input: GetAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord | undefined> {
const db = transaction ?? this.#db;
let query = db.selectFrom('agent').select(recordColumns).where('tenant_id', '=', input.tenant_id);
diff --git a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
index dac5ba855..d6973040b 100644
--- a/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
+++ b/packages/trueforge/src/db/sqlite/schedule-store/SqliteScheduleStore.ts
@@ -7,7 +7,7 @@ import {
decodeOffsetPageToken,
paginateOffsetRows,
} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';
-import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';
+import { sql, type ExpressionBuilder, type Kysely, type Transaction } from 'kysely';
import { nextTriggerAfter } from '../../../runtime/cron';
import type { ScheduleManifest, ScheduleRunStatus, ScheduleStatus } from '../../../schemas/schedule';
import { newId } from '../../../utils/id';
@@ -20,6 +20,7 @@ import {
type CreateScheduleInput,
type CreateScheduleRunInput,
type DeleteScheduleInput,
+ type GetOwnedIdsInput,
type GetRunInput,
type GetScheduledRunForInput,
type GetScheduleInput,
@@ -294,6 +295,21 @@ export class SqliteScheduleStore implements IScheduleStore<Transaction<Database>
return { data: data.map(toScheduleRecord), pagination };
}
+ async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const db = transaction ?? this.#db;
+ const rows = await db
+ .selectFrom('schedule')
+ .select('id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('id', 'in', [...input.ids])
+ .where(sql`json_extract(created_by_subject, '$.subject_id')`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.id);
+ }
+
async listRuns(
input: ListRunsInput,
transaction?: Transaction<Database>,
diff --git a/packages/trueforge/src/db/sqlite/session-store/SqliteSessionStore.ts b/packages/trueforge/src/db/sqlite/session-store/SqliteSessionStore.ts
index 171e6e651..61425e954 100644
--- a/packages/trueforge/src/db/sqlite/session-store/SqliteSessionStore.ts
+++ b/packages/trueforge/src/db/sqlite/session-store/SqliteSessionStore.ts
@@ -10,6 +10,7 @@ import type {
CreateTurnInput,
DeleteSessionInput,
FreezeAndGetTurnInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
GetTurnInput,
@@ -42,6 +43,7 @@ import {
import {
createSession as createSessionQuery,
deleteSession as deleteSessionQuery,
+ getOwnedIds as getOwnedIdsQuery,
getSessionByExternalId as getSessionByExternalIdQuery,
getSession as getSessionQuery,
listSessions as listSessionsQuery,
@@ -102,6 +104,10 @@ export class SqliteSessionStore implements ISessionStore<SessionCustom, TurnCust
return getSessionQuery(this.db, input);
}
+ getOwnedIds(input: GetOwnedIdsInput): Promise<readonly string[]> {
+ return getOwnedIdsQuery(this.db, input);
+ }
+
getSessionByExternalId(input: GetSessionByExternalIdInput): Promise<SessionRecord<SessionCustom> | undefined> {
return getSessionByExternalIdQuery(this.db, input);
}
diff --git a/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts b/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
index 9dbd6bdce..25ae08540 100644
--- a/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
+++ b/packages/trueforge/src/db/sqlite/session-store/queries/sessions.ts
@@ -12,6 +12,7 @@ import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/mo
import type {
CreateSessionInput,
DeleteSessionInput,
+ GetOwnedIdsInput,
GetSessionByExternalIdInput,
GetSessionInput,
ListSessionsInput,
@@ -191,6 +192,20 @@ export async function getSession(
return mapRowToSessionRecord(row);
}
+export async function getOwnedIds(db: Kysely<Database>, input: GetOwnedIdsInput): Promise<readonly string[]> {
+ if (input.ids.length === 0) {
+ return [];
+ }
+ const rows = await db
+ .selectFrom('session')
+ .select('session_id')
+ .where('tenant_id', '=', input.tenant_id)
+ .where('session_id', 'in', [...input.ids])
+ .where(sql`json_extract(created_by_subject, '$.subject_id')`, '=', input.subject_id)
+ .execute();
+ return rows.map(row => row.session_id);
+}
+
export async function getSessionByExternalId(
db: Kysely<Database>,
input: GetSessionByExternalIdInput,
diff --git a/packages/trueforge/src/routes/permissionRoutes.ts b/packages/trueforge/src/routes/permissionRoutes.ts
new file mode 100644
index 000000000..d3325fa45
--- /dev/null
+++ b/packages/trueforge/src/routes/permissionRoutes.ts
@@ -0,0 +1,37 @@
+/**
+ * Internal permissions route definitions (mounted at /api/internal).
+ */
+import { createRoute } from '@hono/zod-openapi';
+import { RequestErrorResponseSchema } from '../schemas/errors';
+import { ListPermissionsRequestSchema, ListPermissionsResponseSchema } from '../schemas/permissions';
+import { OpenApiTag } from './openapiTags';
+
+export const listPermissionsRoute = createRoute({
+ method: 'post',
+ path: '/list-permissions',
+ tags: [OpenApiTag.INTERNAL],
+ summary: 'List permissions for resources',
+ description: 'Return granted actions for each requested agent, schedule, or session id.',
+ 'x-fern-sdk-group-name': ['internal'],
+ 'x-fern-sdk-method-name': 'list_permissions',
+ request: {
+ body: {
+ content: { 'application/json': { schema: ListPermissionsRequestSchema } },
+ required: true,
+ },
+ },
+ responses: {
+ 200: {
+ content: { 'application/json': { schema: ListPermissionsResponseSchema } },
+ description: 'Permissions keyed by resource id.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid request body.',
+ },
+ 401: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Invalid Bearer token or auth cookie',
+ },
+ },
+});
diff --git a/packages/trueforge/src/schemas/permissions.ts b/packages/trueforge/src/schemas/permissions.ts
new file mode 100644
index 000000000..a53039b50
--- /dev/null
+++ b/packages/trueforge/src/schemas/permissions.ts
@@ -0,0 +1,64 @@
+/** Wire schemas for POST /api/internal/list-permissions. */
+import { z } from '@hono/zod-openapi';
+
+export const PermissionResourceTypeSchema = z
+ .enum(['agent', 'schedule', 'session'])
+ .describe('Resource type to evaluate permissions for.')
+ .openapi('PermissionResourceType');
+
+export const AgentResourcePermissionSchema = z
+ .enum(['USE', 'MANAGE', 'DELETE'])
+ .describe('Granted action on an agent.')
+ .openapi('AgentResourcePermission');
+
+export const ScheduleResourcePermissionSchema = z
+ .enum(['MANAGE', 'DELETE'])
+ .describe('Granted action on a schedule.')
+ .openapi('ScheduleResourcePermission');
+
+export const SessionResourcePermissionSchema = z
+ .enum(['MANAGE', 'DELETE'])
+ .describe('Granted action on a session.')
+ .openapi('SessionResourcePermission');
+
+/** Any permission that may appear in a list-permissions response. */
+export const ResourcePermissionSchema = z
+ .enum(['USE', 'MANAGE', 'DELETE'])
+ .describe('Granted action on a resource.')
+ .openapi('ResourcePermission');
+
+export const ListPermissionsRequestSchema = z
+ .object({
+ resource_type: PermissionResourceTypeSchema,
+ resource_ids: z
+ .array(z.string().min(1))
+ .max(100)
+ .describe('Resource ids of `resource_type` to evaluate for the caller.'),
+ })
+ .openapi('ListPermissionsRequest');
+
+export const ListPermissionsResponseSchema = z
+ .object({
+ data: z
+ .record(z.string(), z.array(ResourcePermissionSchema))
+ .describe('Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`.'),
+ })
+ .openapi('ListPermissionsResponse');
+
+export type PermissionResourceType = z.infer<typeof PermissionResourceTypeSchema>;
+export type AgentResourcePermission = z.infer<typeof AgentResourcePermissionSchema>;
+export type ScheduleResourcePermission = z.infer<typeof ScheduleResourcePermissionSchema>;
+export type SessionResourcePermission = z.infer<typeof SessionResourcePermissionSchema>;
+export type ResourcePermission = z.infer<typeof ResourcePermissionSchema>;
+export type ListPermissionsRequest = z.infer<typeof ListPermissionsRequestSchema>;
+export type ListPermissionsResponse = z.infer<typeof ListPermissionsResponseSchema>;
+
+export const AGENT_USE_PERMISSIONS = [AgentResourcePermissionSchema.enum.USE] as const;
+export const AGENT_OWNER_PERMISSIONS = AgentResourcePermissionSchema.options;
+export const SCHEDULE_OWNER_PERMISSIONS = ScheduleResourcePermissionSchema.options;
+export const SESSION_OWNER_PERMISSIONS = SessionResourcePermissionSchema.options;
+
+/** Response scaffold: every requested id starts with no grants. */
+export function emptyPermissionsByResourceId(resourceIds: readonly string[]): Record<string, ResourcePermission[]> {
+ return Object.fromEntries(resourceIds.map(id => [id, [] as ResourcePermission[]]));
+}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
index c20266f8a..914977971 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts
@@ -2,10 +2,13 @@ import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
import { sql, type Kysely, type Transaction } from 'kysely';
import type { RequestContext } from '../auth/identity';
import {
+ type AgentExternalIdRow,
type AgentRecord,
type CreateAgentInput,
type DeleteAgentInput,
type GetAgentInput,
+ type GetExternalIdsByIdsInput,
+ type GetOwnedIdsInput,
type IAgentStore,
type ListAgentsInput,
type UpdateAgentInput,
@@ -87,6 +90,17 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>
return this.#inner.listAgents(input, transaction);
}
+ getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {
+ return this.#inner.getOwnedIds(input, transaction);
+ }
+
+ getExternalIdsByIds(
+ input: GetExternalIdsByIdsInput,
+ transaction?: Transaction<Database>,
+ ): Promise<readonly AgentExternalIdRow[]> {
+ return this.#inner.getExternalIdsByIds(input, transaction);
+ }
+
getAgent(input: GetAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord | undefined> {
return this.#inner.getAgent(input, transaction);
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts b/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts
index d6e852f98..0561d0231 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts
@@ -1,8 +1,14 @@
import { HTTPException } from 'hono/http-exception';
-import type { AgentAction, AgentListAccess, Authorizer } from '../auth/authorizer';
+import type { AgentAction, AgentListAccess, Authorizer, GetPermissionsInput } from '../auth/authorizer';
import type { RequestContext } from '../auth/identity';
import type { AgentRecord } from '../db/agentStore';
+import type { ResourcePermission } from '../schemas/permissions';
+import {
+ emptyPermissionsByResourceId,
+ SCHEDULE_OWNER_PERMISSIONS,
+ SESSION_OWNER_PERMISSIONS,
+} from '../schemas/permissions';
import type { AgentPermission, TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
const permissionByAction: Record<AgentAction, AgentPermission> = {
@@ -12,10 +18,24 @@ const permissionByAction: Record<AgentAction, AgentPermission> = {
delete: 'DELETE_AGENT',
};
+const resourcePermissionByAgentPermission = {
+ USE_AGENT: 'USE',
+ MANAGE_AGENT: 'MANAGE',
+ DELETE_AGENT: 'DELETE',
+} as const satisfies Partial<Record<AgentPermission, ResourcePermission>>;
+
+const mappableAgentPermissions = ['USE_AGENT', 'MANAGE_AGENT', 'DELETE_AGENT'] as const;
+
function allowsAction(permissions: readonly AgentPermission[], action: AgentAction): boolean {
return permissions.includes(permissionByAction[action]);
}
+function toResourcePermissions(permissions: readonly AgentPermission[]): ResourcePermission[] {
+ return mappableAgentPermissions
+ .filter(agentPermission => permissions.includes(agentPermission))
+ .map(agentPermission => resourcePermissionByAgentPermission[agentPermission]);
+}
+
function requireUserCredential(context: RequestContext): string {
if (context.user_credential === null) {
throw new HTTPException(401, { message: 'Authentication token required for agent authorization' });
@@ -52,4 +72,49 @@ export class TrueFoundryAuthorizer implements Authorizer {
});
return allowsAction(permissions[input.agent.external_id] ?? [], input.action);
}
+
+ async getPermissions(input: GetPermissionsInput): Promise<Record<string, ResourcePermission[]>> {
+ const { requestContext, resourceIds } = input;
+ const data = emptyPermissionsByResourceId(resourceIds);
+
+ if (input.resourceType === 'agent') {
+ const agents = await input.store.getExternalIdsByIds({
+ tenant_id: requestContext.tenant_id,
+ ids: resourceIds,
+ });
+ if (agents.length === 0) {
+ return data;
+ }
+ const permissions = await this.#client.getAgentPermissions({
+ accessToken: requireUserCredential(requestContext),
+ externalIds: agents.map(agent => agent.external_id),
+ });
+ for (const agent of agents) {
+ data[agent.id] = toResourcePermissions(permissions[agent.external_id] ?? []);
+ }
+ return data;
+ }
+
+ if (input.resourceType === 'schedule') {
+ const ownedIds = await input.store.getOwnedIds({
+ tenant_id: requestContext.tenant_id,
+ ids: resourceIds,
+ subject_id: requestContext.subject.id,
+ });
+ for (const id of ownedIds) {
+ data[id] = [...SCHEDULE_OWNER_PERMISSIONS];
+ }
+ return data;
+ }
+
+ const ownedIds = await input.store.getOwnedIds({
+ tenant_id: requestContext.tenant_id,
+ ids: resourceIds,
+ subject_id: requestContext.subject.id,
+ });
+ for (const id of ownedIds) {
+ data[id] = [...SESSION_OWNER_PERMISSIONS];
+ }
+ return data;
+ }
}
diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.ts
index e0da8cb45..43c08b50a 100644
--- a/packages/trueforge/tests/unit/apis/agents.test.ts
+++ b/packages/trueforge/tests/unit/apis/agents.test.ts
@@ -77,6 +77,7 @@ const deniedCanAccessAgent = jest.fn((_input: Parameters<Authorizer['canAccessAg
const denyAllAuthorizer: Authorizer = {
listAgentAccess: deniedListAgentAccess,
canAccessAgent: deniedCanAccessAgent,
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
};
describe('agents router', () => {
diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.ts
index 5f9dfd87d..79ac96159 100644
--- a/packages/trueforge/tests/unit/apis/schedules.test.ts
+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts
@@ -91,6 +91,7 @@ async function setup(authorizer: Authorizer = new TrueForgeAuthorizer()) {
authorizer: {
listAgentAccess: input => currentAuthorizer.listAgentAccess(input),
canAccessAgent: input => currentAuthorizer.canAccessAgent(input),
+ getPermissions: input => currentAuthorizer.getPermissions(input),
},
}),
);
@@ -197,6 +198,7 @@ describe('schedule RBAC', () => {
: { kind: 'agent_external_ids', agent_external_ids: [] },
),
canAccessAgent: () => Promise.resolve(false),
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
});
asUser(BOB);
expect((await app.request(`/${id}`)).status).toBe(200);
@@ -371,6 +373,7 @@ describe('create schedule run', () => {
const denyAll: Authorizer = {
listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
canAccessAgent,
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
};
const { postJson } = await setup(denyAll);
const res = await postJson('/', 'POST', scheduleBody);
@@ -390,6 +393,7 @@ describe('create schedule run', () => {
setAuthorizer({
listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
canAccessAgent,
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
});
const res = await postJson('/runs', 'POST', { schedule_id: scheduleId });
diff --git a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
index 7c4acee2a..f4b51c7aa 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -45,6 +45,7 @@ const deniedCanAccessAgent = jest.fn((_input: Parameters<Authorizer['canAccessAg
const denyAllAuthorizer: Authorizer = {
listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
canAccessAgent: deniedCanAccessAgent,
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
};
describe('sessions HTTP agent binding', () => {
@@ -264,6 +265,7 @@ describe('sessions HTTP agent binding', () => {
: { kind: 'agent_external_ids', agent_external_ids: [] },
),
canAccessAgent: () => Promise.resolve(false),
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
};
const managerDeps = {
...sessionDeps,
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index d6ada3ec2..354126efd 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -157,6 +157,7 @@ describe('turns', () => {
: { kind: 'agent_external_ids', agent_external_ids: [] },
),
canAccessAgent: () => Promise.resolve(false),
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
},
}),
);
@@ -411,6 +412,7 @@ describe('turns', () => {
const denyAllAuthorizer: Authorizer = {
listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),
canAccessAgent: deniedCanAccessAgent,
+ getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),
};
async function referencedAgentHarness(authorizer: Authorizer) {
diff --git a/packages/trueforge/tests/unit/auth/authorizerPermissions.test.ts b/packages/trueforge/tests/unit/auth/authorizerPermissions.test.ts
new file mode 100644
index 000000000..340eed69e
--- /dev/null
+++ b/packages/trueforge/tests/unit/auth/authorizerPermissions.test.ts
@@ -0,0 +1,83 @@
+import { TrueForgeAuthorizer } from '../../../src/auth/authorizer';
+import type { RequestContext } from '../../../src/auth/identity';
+import type { IAgentStore } from '../../../src/db/agentStore';
+import type { IScheduleStore } from '../../../src/db/scheduleStore';
+
+const ALICE: RequestContext = {
+ tenant_id: 'default',
+ subject: { id: 'alice', type: 'user', display_name: 'alice' },
+ roles: [],
+ user_credential: null,
+};
+const BOB: RequestContext = {
+ tenant_id: 'default',
+ subject: { id: 'bob', type: 'user', display_name: 'bob' },
+ roles: [],
+ user_credential: null,
+};
+
+describe('TrueForgeAuthorizer.getPermissions', () => {
+ const authorizer = new TrueForgeAuthorizer();
+
+ it('grants USE to everyone on agents and MANAGE/DELETE only to the owner', async () => {
+ const agentStore = {
+ getOwnedIds: jest.fn(async ({ subject_id }: { subject_id: string }) =>
+ subject_id === 'alice' ? ['agent-1'] : [],
+ ),
+ } as unknown as IAgentStore;
+
+ expect(
+ await authorizer.getPermissions({
+ resourceType: 'agent',
+ requestContext: ALICE,
+ resourceIds: ['agent-1', 'agent-2'],
+ store: agentStore,
+ }),
+ ).toEqual({
+ 'agent-1': ['USE', 'MANAGE', 'DELETE'],
+ 'agent-2': ['USE'],
+ });
+
+ expect(
+ await authorizer.getPermissions({
+ resourceType: 'agent',
+ requestContext: BOB,
+ resourceIds: ['agent-1'],
+ store: agentStore,
+ }),
+ ).toEqual({
+ 'agent-1': ['USE'],
+ });
+ });
+
+ it('grants MANAGE/DELETE only to schedule owners', async () => {
+ const scheduleStore = {
+ getOwnedIds: jest.fn(async ({ subject_id }: { subject_id: string }) =>
+ subject_id === 'alice' ? ['sched-1'] : [],
+ ),
+ } as unknown as IScheduleStore;
+
+ expect(
+ await authorizer.getPermissions({
+ resourceType: 'schedule',
+ requestContext: ALICE,
+ resourceIds: ['sched-1', 'sched-2'],
+ store: scheduleStore,
+ }),
+ ).toEqual({
+ 'sched-1': ['MANAGE', 'DELETE'],
+ 'sched-2': [],
+ });
+
+ expect(
+ await authorizer.getPermissions({
+ resourceType: 'schedule',
+ requestContext: BOB,
+ resourceIds: ['sched-1'],
+ store: scheduleStore,
+ }),
+ ).toEqual({
+ 'sched-1': [],
+ });
+ });
+});