The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-2217: Expose tenant CREATE via list-permissions (#750)
Bhavesh Patel584e8159f5c8
diff --git a/.changeset/age-2217-tenant-list-permissions.md b/.changeset/age-2217-tenant-list-permissions.mdnew file mode 100644index 000000000..ae6a93b58--- /dev/null+++ b/.changeset/age-2217-tenant-list-permissions.md@@ -0,0 +1,6 @@+---+"@truefoundry/trueforge-ui": patch+"@truefoundry/trueforge": patch+---++Gate Save Agent (create) on tenant CREATE from list-permissions, keep Update Agent on agent MANAGE, unwrap `{ type, permissions }`, and bump `@truefoundry/assistant-ui-runtime` to `0.1.39`.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 8c0921f31..e9d988bef 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -2246,10 +2246,32 @@],"type": "object"},+ "ListPermissionsData": {+ "properties": {+ "permissions": {+ "additionalProperties": {+ "items": {+ "$ref": "#/components/schemas/ResourcePermission"+ },+ "type": "array"+ },+ "description": "For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` → `CREATE`).",+ "type": "object"+ },+ "type": {+ "$ref": "#/components/schemas/PermissionResourceType"+ }+ },+ "required": [+ "type",+ "permissions"+ ],+ "type": "object"+ },"ListPermissionsRequest": {"properties": {"resource_ids": {- "description": "Resource ids of `resource_type` to evaluate for the caller.",+ "description": "Resource ids of `resource_type` to evaluate.","items": {"minLength": 1,"type": "string"@@ -2270,14 +2292,7 @@"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"+ "$ref": "#/components/schemas/ListPermissionsData"}},"required": [@@ -3288,7 +3303,8 @@"enum": ["agent","schedule",- "session"+ "session",+ "tenant"],"type": "string"},@@ -3421,11 +3437,12 @@"type": "string"},"ResourcePermission": {- "description": "Granted action on a resource.",+ "description": "Granted action on a resource id or tenant entity kind.","enum": ["USE","MANAGE",- "DELETE"+ "DELETE",+ "CREATE"],"type": "string"},@@ -5811,7 +5828,7 @@},"/api/internal/list-permissions": {"post": {- "description": "Return granted actions for each requested agent, schedule, or session id.",+ "description": "Return granted actions for the requested resources.","requestBody": {"content": {"application/json": {@@ -5831,7 +5848,7 @@}}},- "description": "Permissions keyed by resource id."+ "description": "Permissions envelope: `{ type, permissions }`."},"400": {"content": {diff --git a/docs/openapi.json b/docs/openapi.jsonindex 8c0921f31..e9d988bef 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -2246,10 +2246,32 @@],"type": "object"},+ "ListPermissionsData": {+ "properties": {+ "permissions": {+ "additionalProperties": {+ "items": {+ "$ref": "#/components/schemas/ResourcePermission"+ },+ "type": "array"+ },+ "description": "For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` → `CREATE`).",+ "type": "object"+ },+ "type": {+ "$ref": "#/components/schemas/PermissionResourceType"+ }+ },+ "required": [+ "type",+ "permissions"+ ],+ "type": "object"+ },"ListPermissionsRequest": {"properties": {"resource_ids": {- "description": "Resource ids of `resource_type` to evaluate for the caller.",+ "description": "Resource ids of `resource_type` to evaluate.","items": {"minLength": 1,"type": "string"@@ -2270,14 +2292,7 @@"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"+ "$ref": "#/components/schemas/ListPermissionsData"}},"required": [@@ -3288,7 +3303,8 @@"enum": ["agent","schedule",- "session"+ "session",+ "tenant"],"type": "string"},@@ -3421,11 +3437,12 @@"type": "string"},"ResourcePermission": {- "description": "Granted action on a resource.",+ "description": "Granted action on a resource id or tenant entity kind.","enum": ["USE","MANAGE",- "DELETE"+ "DELETE",+ "CREATE"],"type": "string"},@@ -5811,7 +5828,7 @@},"/api/internal/list-permissions": {"post": {- "description": "Return granted actions for each requested agent, schedule, or session id.",+ "description": "Return granted actions for the requested resources.","requestBody": {"content": {"application/json": {@@ -5831,7 +5848,7 @@}}},- "description": "Permissions keyed by resource id."+ "description": "Permissions envelope: `{ type, permissions }`."},"400": {"content": {diff --git a/packages/frontend/package.json b/packages/frontend/package.jsonindex 08043834e..a9b717801 100644--- a/packages/frontend/package.json+++ b/packages/frontend/package.json@@ -26,7 +26,7 @@"@assistant-ui/core": "0.2.22","@assistant-ui/react": "0.14.27","@assistant-ui/store": "0.2.21",- "@truefoundry/assistant-ui-runtime": "0.1.38",+ "@truefoundry/assistant-ui-runtime": "0.1.39","@truefoundry/trueforge-sdk": "workspace:*","@truefoundry/trueforge-ui": "workspace:*","monaco-editor": "^0.52.0",diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.mdindex a831a70fe..7ce8fb760 100644--- a/packages/trueforge-sdk/reference.md+++ b/packages/trueforge-sdk/reference.md@@ -12,7 +12,7 @@<dl><dd>-Return granted actions for each requested agent, schedule, or session id.+Return granted actions for the requested resources.</dd></dl></dd>diff --git a/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts b/packages/trueforge-sdk/src/api/resources/internal/client/Client.tsindex 354019f9e..0faf09f27 100644--- a/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts+++ b/packages/trueforge-sdk/src/api/resources/internal/client/Client.ts@@ -48,7 +48,7 @@ export class InternalClient {}/**- * Return granted actions for each requested agent, schedule, or session id.+ * Return granted actions for the requested resources.** @param {TrueForge.ListPermissionsRequest} request* @param {InternalClient.RequestOptions} requestOptions - Request-specific configuration.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.tsindex cdb64d26a..9aef4c50e 100644--- a/packages/trueforge-sdk/src/api/resources/internal/client/requests/ListPermissionsRequest.ts+++ b/packages/trueforge-sdk/src/api/resources/internal/client/requests/ListPermissionsRequest.ts@@ -10,7 +10,7 @@ import type * as TrueForge from "../../../../index.js";* }*/export interface ListPermissionsRequest {- /** Resource ids of `resource_type` to evaluate for the caller. */+ /** Resource ids of `resource_type` to evaluate. */resourceIds: string[];resourceType: TrueForge.PermissionResourceType;}diff --git a/packages/trueforge-sdk/src/api/types/ListPermissionsData.ts b/packages/trueforge-sdk/src/api/types/ListPermissionsData.tsnew file mode 100644index 000000000..e66887730--- /dev/null+++ b/packages/trueforge-sdk/src/api/types/ListPermissionsData.ts@@ -0,0 +1,9 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface ListPermissionsData {+ /** For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` → `CREATE`). */+ permissions: Record<string, TrueForge.ResourcePermission[]>;+ type: TrueForge.PermissionResourceType;+}diff --git a/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts b/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.tsindex 43eeae2c7..14e7848c1 100644--- a/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts+++ b/packages/trueforge-sdk/src/api/types/ListPermissionsResponse.ts@@ -3,6 +3,5 @@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[]>;+ data: TrueForge.ListPermissionsData;}diff --git a/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts b/packages/trueforge-sdk/src/api/types/PermissionResourceType.tsindex 8c5f7f2d1..d6d2858ea 100644--- a/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts+++ b/packages/trueforge-sdk/src/api/types/PermissionResourceType.ts@@ -5,5 +5,6 @@ export const PermissionResourceType = {Agent: "agent",Schedule: "schedule",Session: "session",+ Tenant: "tenant",} 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.tsindex 9df249108..4f2389899 100644--- a/packages/trueforge-sdk/src/api/types/ResourcePermission.ts+++ b/packages/trueforge-sdk/src/api/types/ResourcePermission.ts@@ -1,9 +1,10 @@// This file was auto-generated by Fern from our API Definition.-/** Granted action on a resource. */+/** Granted action on a resource id or tenant entity kind. */export const ResourcePermission = {Use: "USE",Manage: "MANAGE",Delete: "DELETE",+ Create: "CREATE",} 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.tsindex fcc78f761..c88fa727c 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 "./ListPermissionsData.js";export * from "./ListPermissionsResponse.js";export * from "./ListScheduleRunsResponse.js";export * from "./ListSchedulesResponse.js";diff --git a/packages/trueforge-sdk/src/serialization/types/ListPermissionsData.ts b/packages/trueforge-sdk/src/serialization/types/ListPermissionsData.tsnew file mode 100644index 000000000..69814c4ba--- /dev/null+++ b/packages/trueforge-sdk/src/serialization/types/ListPermissionsData.ts@@ -0,0 +1,22 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { PermissionResourceType } from "./PermissionResourceType.js";+import { ResourcePermission } from "./ResourcePermission.js";++export const ListPermissionsData: core.serialization.ObjectSchema<+ serializers.ListPermissionsData.Raw,+ TrueForge.ListPermissionsData+> = core.serialization.object({+ permissions: core.serialization.record(core.serialization.string(), core.serialization.list(ResourcePermission)),+ type: PermissionResourceType,+});++export declare namespace ListPermissionsData {+ export interface Raw {+ permissions: Record<string, ResourcePermission.Raw[]>;+ type: PermissionResourceType.Raw;+ }+}diff --git a/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.tsindex 40ab93f25..5547d6706 100644--- a/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts+++ b/packages/trueforge-sdk/src/serialization/types/ListPermissionsResponse.ts@@ -3,17 +3,17 @@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";+import { ListPermissionsData } from "./ListPermissionsData.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)),+ data: ListPermissionsData,});export declare namespace ListPermissionsResponse {export interface Raw {- data: Record<string, ResourcePermission.Raw[]>;+ data: ListPermissionsData.Raw;}}diff --git a/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts b/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.tsindex 06acf3867..8f07f3c22 100644--- a/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts+++ b/packages/trueforge-sdk/src/serialization/types/PermissionResourceType.ts@@ -7,8 +7,8 @@ import type * as serializers from "../index.js";export const PermissionResourceType: core.serialization.Schema<serializers.PermissionResourceType.Raw,TrueForge.PermissionResourceType-> = core.serialization.enum_(["agent", "schedule", "session"]);+> = core.serialization.enum_(["agent", "schedule", "session", "tenant"]);export declare namespace PermissionResourceType {- export type Raw = "agent" | "schedule" | "session";+ export type Raw = "agent" | "schedule" | "session" | "tenant";}diff --git a/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts b/packages/trueforge-sdk/src/serialization/types/ResourcePermission.tsindex d8b3c4a51..3d0b164b9 100644--- a/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts+++ b/packages/trueforge-sdk/src/serialization/types/ResourcePermission.ts@@ -7,8 +7,8 @@ import type * as serializers from "../index.js";export const ResourcePermission: core.serialization.Schema<serializers.ResourcePermission.Raw,TrueForge.ResourcePermission-> = core.serialization.enum_(["USE", "MANAGE", "DELETE"]);+> = core.serialization.enum_(["USE", "MANAGE", "DELETE", "CREATE"]);export declare namespace ResourcePermission {- export type Raw = "USE" | "MANAGE" | "DELETE";+ export type Raw = "USE" | "MANAGE" | "DELETE" | "CREATE";}diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.tsindex fcc78f761..c88fa727c 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 "./ListPermissionsData.js";export * from "./ListPermissionsResponse.js";export * from "./ListScheduleRunsResponse.js";export * from "./ListSchedulesResponse.js";diff --git a/packages/trueforge-sdk/tests/wire/internal.test.ts b/packages/trueforge-sdk/tests/wire/internal.test.tsindex d2bcd38fc..88e3c1ac1 100644--- a/packages/trueforge-sdk/tests/wire/internal.test.ts+++ b/packages/trueforge-sdk/tests/wire/internal.test.ts@@ -9,7 +9,7 @@ describe("InternalClient", () => {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"] } };+ const rawResponseBody = { data: { permissions: { key: ["USE"] }, type: "agent" } };server.mockEndpoint()@@ -26,7 +26,10 @@ describe("InternalClient", () => {});expect(response).toEqual({data: {- key: ["USE"],+ permissions: {+ key: ["USE"],+ },+ type: "agent",},});});diff --git a/packages/trueforge-ui/package.json b/packages/trueforge-ui/package.jsonindex f03fadb58..da2d87645 100644--- a/packages/trueforge-ui/package.json+++ b/packages/trueforge-ui/package.json@@ -95,7 +95,7 @@"@openuidev/react-headless": "^0.9.4","@openuidev/react-lang": "^0.2.9","@openuidev/react-ui": "^0.13.2",- "@truefoundry/assistant-ui-runtime": "0.1.38",+ "@truefoundry/assistant-ui-runtime": "0.1.39","@truefoundry/trueforge-sdk": "workspace:*","chart.js": "^4.5.1","clsx": "^2.1.1",diff --git a/packages/trueforge-ui/src/atoms/SaveAgentButton.tsx b/packages/trueforge-ui/src/atoms/SaveAgentButton.tsxindex c764dfb3e..b4435789b 100644--- a/packages/trueforge-ui/src/atoms/SaveAgentButton.tsx+++ b/packages/trueforge-ui/src/atoms/SaveAgentButton.tsx@@ -7,6 +7,7 @@ import {} from '@truefoundry/assistant-ui-runtime';import { useRef, useState } from 'react';+import { useCanCreateAgent } from '../hooks/useCanCreateAgent.js';import { useSaveAgentVisible } from '../hooks/useChatChromeActionsVisible.js';import { useResourcePermissions } from '../hooks/useResourcePermissions.js';import { Icon } from '../icons/Icon.js';@@ -19,6 +20,8 @@ import { useOptionalAgentConfigInstructions } from './draft/AgentConfigInstructiimport { Button } from './primitives/Button.js';import { SideDrawer } from './primitives/SideDrawer.js';+const NO_CREATE_AGENT_PERMISSION_MESSAGE = 'No permission to create agents';+type SaveIntent = 'create' | 'update';function cloneAgentSpec(spec: AgentSpec): AgentSpec {@@ -79,6 +82,7 @@ function SaveAgentButtonContent({resourceIds: agentId == null ? [] : [agentId],});const canManageAgent = allows(agentId, 'MANAGE');+ const { canCreateAgent, loading: createAgentPermissionLoading } = useCanCreateAgent();const configInstructions = useOptionalAgentConfigInstructions();const SaveAgentForm = useSlot('SaveAgentForm');const PermissionGuard = useSlot('PermissionGuard');@@ -91,6 +95,13 @@ function SaveAgentButtonContent({const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ const isUpdateMode =+ shell?.mode.status === 'active' &&+ shell.mode.isMutable &&+ (shell.mode.agentName !== undefined || shell.mode.agentId !== undefined);+ const canCreate = canCreateAgent && !createAgentPermissionLoading;+ const canTrigger = isUpdateMode ? canManageAgent : canCreate;+const close = () => {if (saving) return;setOpen(false);@@ -101,7 +112,7 @@ function SaveAgentButtonContent({const show = async () => {if (agentSpecRef.current === null || builder === null) return;- if (agentId != null && !canManageAgent) return;+ if (isUpdateMode ? !canManageAgent : !canCreate) return;setError(null);configInstructions?.flush();await flushAgentSpec();@@ -120,7 +131,7 @@ function SaveAgentButtonContent({const save = async () => {if (builder === null || draftSpec === null) return;- if (intent === 'update' && !canManageAgent) return;+ if (intent === 'update' ? !canManageAgent : !canCreate) return;const normalizedName = name.trim();if (!normalizedName || !draftSpec.model.name.trim()) return;const normalizedDescription = description.trim();@@ -153,17 +164,16 @@ function SaveAgentButtonContent({}};- const isUpdateMode =- shell?.mode.status === 'active' &&- shell.mode.isMutable &&- (shell.mode.agentName !== undefined || shell.mode.agentId !== undefined);const triggerLabel = isUpdateMode && children === 'Save Agent' ? 'Update Agent' : children;if (!visible) return null;return (<>- <PermissionGuard allowed={canManageAgent}>+ <PermissionGuard+ allowed={canTrigger}+ deniedMessage={isUpdateMode ? undefined : NO_CREATE_AGENT_PERMISSION_MESSAGE}+ ><Button.Primarytype="button"size="large"diff --git a/packages/trueforge-ui/src/hooks/useCanCreateAgent.ts b/packages/trueforge-ui/src/hooks/useCanCreateAgent.tsnew file mode 100644index 000000000..fcf96862b--- /dev/null+++ b/packages/trueforge-ui/src/hooks/useCanCreateAgent.ts@@ -0,0 +1,50 @@+'use client';++import { useEffect, useState } from 'react';++import { useOptionalPermissionsServer } from '../server/ServerContext.js';++export type UseCanCreateAgentResult = {+ loading: boolean;+ /** False while loading, on error, or when CREATE is not granted (fail-closed). */+ canCreateAgent: boolean;+};++/**+ * Tenant-scoped create-agent grant via `list-permissions` (`resource_type: tenant`).+ * When no permissions server is configured (standalone without port), allows create.+ */+export function useCanCreateAgent(): UseCanCreateAgentResult {+ const server = useOptionalPermissionsServer();+ const [state, setState] = useState<{ loading: boolean; canCreateAgent: boolean }>({+ loading: server != null,+ canCreateAgent: server == null,+ });++ useEffect(() => {+ if (server == null) {+ setState({ loading: false, canCreateAgent: true });+ return;+ }++ let cancelled = false;+ setState({ loading: true, canCreateAgent: false });+ void server+ .listPermissions({ resourceType: 'tenant', resourceIds: [] })+ .then(response => {+ if (cancelled) return;+ const granted = response.data.permissions.agent ?? [];+ setState({ loading: false, canCreateAgent: granted.includes('CREATE') });+ })+ .catch(() => {+ if (cancelled) return;+ setState({ loading: false, canCreateAgent: false });+ });++ return () => {+ cancelled = true;+ };+ }, [server]);++ return state;+}diff --git a/packages/trueforge-ui/src/hooks/useResourcePermissions.ts b/packages/trueforge-ui/src/hooks/useResourcePermissions.tsindex 3b31beb48..ec2d7b425 100644--- a/packages/trueforge-ui/src/hooks/useResourcePermissions.ts+++ b/packages/trueforge-ui/src/hooks/useResourcePermissions.ts@@ -89,7 +89,7 @@ export function useResourcePermissions({server,resourceType,key: requestKey,- data: Object.assign({}, ...responses.map(response => response.data)),+ data: Object.assign({}, ...responses.map(response => response.data.permissions)),loading: false,error: null,});diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.tsindex 9065f5c83..121657190 100644--- a/packages/trueforge-ui/src/index.ts+++ b/packages/trueforge-ui/src/index.ts@@ -241,6 +241,8 @@ export { UserEditComposerContainer } from './containers/UserEditComposerContaineexport { UserMessageContainer } from './containers/UserMessageContainer.js';export { useApprovalNav } from './hooks/useApprovalNav.js';export type { ApprovalNavState } from './hooks/useApprovalNav.js';+export { useCanCreateAgent } from './hooks/useCanCreateAgent.js';+export type { UseCanCreateAgentResult } from './hooks/useCanCreateAgent.js';export { ComposerBusyProvider, useComposerBusyState } from './hooks/useComposerBusyState.js';export type { ComposerBusyState } from './hooks/useComposerBusyState.js';export { threadHasPendingMcpAuth, useComposerPauseView } from './hooks/useComposerPauseView.js';diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/permissionsServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/permissionsServer.tsindex 92514f682..7278a09fe 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/permissionsServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/permissionsServer.ts@@ -10,6 +10,6 @@ export type CreateHarnessPermissionsServerOptions = CreateTrueForgeClientOptionsexport function createHarnessPermissionsServer(options: CreateHarnessPermissionsServerOptions = {}): PermissionsServer {const client = options.client ?? createTrueForgeClient(options);return {- listPermissions: request => client.internal.listPermissions(request),+ listPermissions: async request => client.internal.listPermissions(request),};}diff --git a/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx b/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsxindex 31b0931b7..ddd8bedb0 100644--- a/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentDetailsPage.test.tsx@@ -225,7 +225,9 @@ describe('AgentDetailsPage', () => {renderPage({serverOverrides: {permissions: {- listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({ data: { 'agent-1': ['USE'] } })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: { 'agent-1': ['USE'] } },+ })),},},});diff --git a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsxindex d4a604a66..d127739ce 100644--- a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx@@ -242,7 +242,9 @@ describe('AgentsLibrary', () => {},]),permissions: {- listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({ data: { 'shared-id': ['USE'] } })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: { 'shared-id': ['USE'] } },+ })),},sessions: createMockAgentSessionsServer(),schedules: createMockScheduleServer(),diff --git a/packages/trueforge-ui/test/atoms/SaveAgentButton.test.tsx b/packages/trueforge-ui/test/atoms/SaveAgentButton.test.tsxindex 6b64f4112..63df30f3e 100644--- a/packages/trueforge-ui/test/atoms/SaveAgentButton.test.tsx+++ b/packages/trueforge-ui/test/atoms/SaveAgentButton.test.tsx@@ -10,7 +10,13 @@ import {} from '@/atoms/draft/AgentConfigInstructionsContext.js';import { ServerProvider } from '@/server/ServerContext.js';import { ShellModeProvider, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';-import type { AgentSpec, AgentUIServer, SaveAgentRequest, SaveAgentResult } from '@/server/types.js';+import type {+ AgentSpec,+ AgentUIServer,+ ListPermissionsResponse,+ SaveAgentRequest,+ SaveAgentResult,+} from '@/server/types.js';import { SlotsProvider } from '@/theme/SlotsProvider.js';import { createMockAgentUIServer } from '../server/mockServer.js';@@ -520,4 +526,59 @@ describe('SaveAgentButton', () => {expect(within(dialog).getByLabelText('Agent name')).toHaveValue('writer');expect(within(dialog).getByLabelText('Description')).toHaveValue('Existing agent summary.');});++ it('enables Save Agent when tenant CREATE is granted', async () => {+ renderButton({+ serverOverrides: {+ permissions: {+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'tenant', permissions: { agent: ['CREATE'] } },+ })),+ },+ },+ });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save Agent' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ expect(await screen.findByRole('dialog', { name: 'Save agent' })).toBeInTheDocument();+ });++ it('disables Save Agent without tenant CREATE and shows a permission tooltip', async () => {+ renderButton({+ serverOverrides: {+ permissions: {+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'tenant', permissions: { agent: [] } },+ })),+ },+ },+ });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save Agent' })).toBeDisabled());+ const trigger = screen.getByRole('button', { name: 'Save Agent' });+ fireEvent.mouseEnter(trigger.parentElement ?? trigger);+ expect(screen.getByRole('tooltip')).toHaveTextContent('No permission to create agents');+ });++ it('keeps Update Agent enabled for MANAGE without tenant CREATE', async () => {+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'writer' }));+ renderButton({+ saveAgent,+ children: <BoundMutableSaveButton agentId="writer" agentName="writer" description="Writes docs." />,+ serverOverrides: {+ permissions: {+ listPermissions: vi.fn(async ({ resourceType }): Promise<ListPermissionsResponse> =>+ resourceType === 'tenant'+ ? { data: { type: 'tenant', permissions: { agent: [] } } }+ : { data: { type: 'agent', permissions: { writer: ['MANAGE'] } } },+ ),+ },+ },+ });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Update Agent' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Update Agent' }));+ const dialog = await screen.findByRole('dialog', { name: 'Update agent' });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));+ await waitFor(() =>+ expect(saveAgent).toHaveBeenCalledWith(expect.objectContaining({ agentName: 'writer', intent: 'update' })),+ );+ });});diff --git a/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsxindex 8cca05502..9568b4635 100644--- a/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx+++ b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx@@ -7,7 +7,14 @@ import { ScheduleFormDrawer } from '@/atoms/schedules/ScheduleFormDrawer.js';import { ToasterProvider } from '@/containers/ToasterContainer.js';import { ServerProvider } from '@/server/ServerContext.js';import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';-import type { AgentUIServer, ConnectorBase, PermissionsServer, Schedule, ScheduleServer } from '@/server/types.js';+import type {+ AgentUIServer,+ ConnectorBase,+ ListPermissionsResponse,+ PermissionsServer,+ Schedule,+ ScheduleServer,+} from '@/server/types.js';import { SlotsProvider } from '@/theme/SlotsProvider.js';import { createMockAgentUIServer, createMockCatalog } from '../../server/mockServer.js';@@ -245,7 +252,9 @@ describe('ScheduleFormDrawer', () => {renderDrawer({scheduleServer: mockScheduleServer({ createSchedule }),permissions: {- listPermissions: vi.fn(async () => ({ data: { 'demo-agent': [] } })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: { 'demo-agent': [] } },+ })),},initialAgentId: 'demo-agent',});diff --git a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsxindex 43adb739e..1f71e4e42 100644--- a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx@@ -119,7 +119,9 @@ describe('SchedulesPage', () => {const { scheduleServer } = renderPage(sampleSchedules, {}, undefined, undefined, {agentId: 'demo-agent',permissions: {- listPermissions: vi.fn(async () => ({ data: { s1: [] } })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'schedule', permissions: { s1: [] } },+ })),},});@@ -140,7 +142,10 @@ describe('SchedulesPage', () => {agentId: 'demo-agent',permissions: {listPermissions: vi.fn(async ({ resourceType }): Promise<ListPermissionsResponse> => ({- data: resourceType === 'agent' ? { 'demo-agent': ['USE'] } : { s1: [] },+ data:+ resourceType === 'agent'+ ? { type: 'agent', permissions: { 'demo-agent': ['USE'] } }+ : { type: resourceType, permissions: { s1: [] } },})),},});@@ -153,7 +158,10 @@ describe('SchedulesPage', () => {it('leaves Create enabled for All agents and gates USE when a specific agent is selected', async () => {const listPermissions = vi.fn(async ({ resourceType }): Promise<ListPermissionsResponse> => ({- data: resourceType === 'agent' ? { 'demo-agent': [] } : {},+ data:+ resourceType === 'agent'+ ? { type: 'agent', permissions: { 'demo-agent': [] } }+ : { type: resourceType, permissions: {} },}));renderPage(sampleSchedules, {}, undefined, undefined, {permissions: { listPermissions },diff --git a/packages/trueforge-ui/test/containers/useResolvedServer.test.tsx b/packages/trueforge-ui/test/containers/useResolvedServer.test.tsxindex 40d41c11c..018ca5af8 100644--- a/packages/trueforge-ui/test/containers/useResolvedServer.test.tsx+++ b/packages/trueforge-ui/test/containers/useResolvedServer.test.tsx@@ -3,14 +3,18 @@ import { renderHook, waitFor } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import { useResolvedServer } from '@/containers/useResolvedServer.js';-import type { PermissionsServer } from '@/server/types.js';+import type { ListPermissionsResponse, PermissionsServer } from '@/server/types.js';import { createMockAgentUIServer, createMockCatalog } from '../server/mockServer.js';const permissions: PermissionsServer = {- listPermissions: vi.fn(async () => ({ data: {} })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: {} },+ })),};const defaultHarnessPermissions: PermissionsServer = {- listPermissions: vi.fn(async () => ({ data: {} })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: {} },+ })),};const mockCreateTrueForgeAgentUIServer = vi.fn((options?: { permissions?: PermissionsServer }) =>diff --git a/packages/trueforge-ui/test/hooks/useCanCreateAgent.test.tsx b/packages/trueforge-ui/test/hooks/useCanCreateAgent.test.tsxnew file mode 100644index 000000000..50784bb80--- /dev/null+++ b/packages/trueforge-ui/test/hooks/useCanCreateAgent.test.tsx@@ -0,0 +1,69 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { describe, expect, it, vi } from 'vitest';++import { useCanCreateAgent } from '@/hooks/useCanCreateAgent.js';+import { ServerProvider } from '@/server/ServerContext.js';+import type { ListPermissionsResponse } from '@/server/types.js';+import { createMockAgentUIServer } from '../server/mockServer.js';++describe('useCanCreateAgent', () => {+ it('allows create when no permissions port is configured', () => {+ const { result } = renderHook(() => useCanCreateAgent());+ expect(result.current).toEqual({ loading: false, canCreateAgent: true });+ });++ it('fails closed until tenant CREATE loads', async () => {+ let resolvePermissions: ((value: ListPermissionsResponse) => void) | undefined;+ const listPermissions = vi.fn(+ () =>+ new Promise<ListPermissionsResponse>(resolve => {+ resolvePermissions = resolve;+ }),+ );+ const server = createMockAgentUIServer({ permissions: { listPermissions } });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <ServerProvider server={server}>{children}</ServerProvider>+ );+ const { result } = renderHook(() => useCanCreateAgent(), { wrapper });++ expect(result.current).toEqual({ loading: true, canCreateAgent: false });+ expect(listPermissions).toHaveBeenCalledWith({ resourceType: 'tenant', resourceIds: [] });++ await act(async () => {+ resolvePermissions?.({ data: { type: 'tenant', permissions: { agent: ['CREATE'] } } });+ });+ await waitFor(() => expect(result.current).toEqual({ loading: false, canCreateAgent: true }));+ });++ it('denies create when CREATE is absent', async () => {+ const server = createMockAgentUIServer({+ permissions: {+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'tenant', permissions: { agent: [] } },+ })),+ },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <ServerProvider server={server}>{children}</ServerProvider>+ );+ const { result } = renderHook(() => useCanCreateAgent(), { wrapper });+ await waitFor(() => expect(result.current).toEqual({ loading: false, canCreateAgent: false }));+ });++ it('denies create when the permissions request fails', async () => {+ const server = createMockAgentUIServer({+ permissions: {+ listPermissions: vi.fn(async () => {+ throw new Error('unavailable');+ }),+ },+ });+ const wrapper = ({ children }: { children: ReactNode }) => (+ <ServerProvider server={server}>{children}</ServerProvider>+ );+ const { result } = renderHook(() => useCanCreateAgent(), { wrapper });+ await waitFor(() => expect(result.current).toEqual({ loading: false, canCreateAgent: false }));+ });+});diff --git a/packages/trueforge-ui/test/hooks/useResourcePermissions.test.tsx b/packages/trueforge-ui/test/hooks/useResourcePermissions.test.tsxindex baffb8912..13a927d27 100644--- a/packages/trueforge-ui/test/hooks/useResourcePermissions.test.tsx+++ b/packages/trueforge-ui/test/hooks/useResourcePermissions.test.tsx@@ -9,7 +9,7 @@ import {useResourcePermissions,} from '@/hooks/useResourcePermissions.js';import { ServerProvider } from '@/server/ServerContext.js';-import type { ListPermissionsResponse, ResourcePermission } from '@/server/types.js';+import type { ListPermissionsResponse } from '@/server/types.js';import { createMockAgentUIServer } from '../server/mockServer.js';describe('useResourcePermissions', () => {@@ -21,10 +21,10 @@ describe('useResourcePermissions', () => {});it('fails closed until grants load and denies missing ids', async () => {- let resolvePermissions: ((value: { data: Record<string, ResourcePermission[]> }) => void) | undefined;+ let resolvePermissions: ((value: ListPermissionsResponse) => void) | undefined;const listPermissions = vi.fn(() =>- new Promise<{ data: Record<string, ResourcePermission[]> }>(resolve => {+ new Promise<ListPermissionsResponse>(resolve => {resolvePermissions = resolve;}),);@@ -39,7 +39,7 @@ describe('useResourcePermissions', () => {expect(result.current.allows('agent-1', 'MANAGE')).toBe(false);await act(async () => {- resolvePermissions?.({ data: { 'agent-1': ['USE', 'MANAGE'] } });+ resolvePermissions?.({ data: { type: 'agent', permissions: { 'agent-1': ['USE', 'MANAGE'] } } });});await waitFor(() => expect(result.current.loading).toBe(false));expect(result.current.allows('agent-1', 'USE')).toBe(true);@@ -49,9 +49,14 @@ describe('useResourcePermissions', () => {});it('chunks requests at 100 ids and fails closed on errors', async () => {- const listPermissions = vi.fn(async ({ resourceIds }: { resourceIds: string[] }) => ({- data: Object.fromEntries(resourceIds.map(resourceId => [resourceId, ['DELETE' as const]])),- }));+ const listPermissions = vi.fn(+ async ({ resourceIds }: { resourceIds: string[] }): Promise<ListPermissionsResponse> => ({+ data: {+ type: 'session',+ permissions: Object.fromEntries(resourceIds.map(resourceId => [resourceId, ['DELETE']])),+ },+ }),+ );const server = createMockAgentUIServer({ permissions: { listPermissions } });const wrapper = ({ children }: { children: ReactNode }) => (<ServerProvider server={server}>{children}</ServerProvider>@@ -73,15 +78,15 @@ describe('useResourcePermissions', () => {it('keeps known grants while an expanded request loads and fails', async () => {let rejectExpanded: ((reason: unknown) => void) | undefined;- const knownResponse: { data: Record<string, ResourcePermission[]> } = {- data: { known: ['MANAGE'] },+ const knownResponse: ListPermissionsResponse = {+ data: { type: 'session', permissions: { known: ['MANAGE'] } },};const listPermissions = vi.fn().mockResolvedValueOnce(knownResponse).mockImplementationOnce(() =>- new Promise<{ data: Record<string, ResourcePermission[]> }>((_resolve, reject) => {+ new Promise<ListPermissionsResponse>((_resolve, reject) => {rejectExpanded = reject;}),);diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.tsindex dfa78f4a3..8747f20cb 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import { createTrueForgeAgentUIServer } from '@/plugins/trueforge-agent-server-adapter/index.js';import { createHarnessPermissionsServer } from '@/plugins/trueforge-agent-server-adapter/permissionsServer.js';-import type { PermissionsServer } from '@/server/types.js';+import type { ListPermissionsResponse, PermissionsServer } from '@/server/types.js';describe('createHarnessPermissionsServer', () => {it('delegates list requests to the generated internal SDK client', async () => {@@ -10,7 +10,7 @@ describe('createHarnessPermissionsServer', () => {expect(String(input)).toBe('https://trueforge.test/api/internal/list-permissions');expect(init?.method).toBe('POST');expect(init?.body).toBe(JSON.stringify({ resource_type: 'agent', resource_ids: ['agent-1'] }));- return Response.json({ data: { 'agent-1': ['USE'] } });+ return Response.json({ data: { type: 'agent', permissions: { 'agent-1': ['USE'] } } });});const server = createHarnessPermissionsServer({baseUrl: 'https://trueforge.test',@@ -19,7 +19,7 @@ describe('createHarnessPermissionsServer', () => {});await expect(server.listPermissions({ resourceType: 'agent', resourceIds: ['agent-1'] })).resolves.toEqual({- data: { 'agent-1': ['USE'] },+ data: { type: 'agent', permissions: { 'agent-1': ['USE'] } },});expect(fetchMock).toHaveBeenCalledOnce();});@@ -33,7 +33,9 @@ describe('createTrueForgeAgentUIServer permissions', () => {it('preserves an explicit permissions port', () => {const permissions: PermissionsServer = {- listPermissions: vi.fn(async () => ({ data: {} })),+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'agent', permissions: {} },+ })),};const server = createTrueForgeAgentUIServer({ fetch: vi.fn(), permissions });expect(server.permissions).toBe(permissions);diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.tsindex 61e39a1ad..86436adc3 100644--- a/packages/trueforge-ui/test/publicUiExports.test.ts+++ b/packages/trueforge-ui/test/publicUiExports.test.ts@@ -188,6 +188,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['useAuiState','useBrand','useBrandName',+ 'useCanCreateAgent','useCatalogServer','useComposerBusyState','useComposerPauseView',diff --git a/packages/trueforge/src/apis/permissions.ts b/packages/trueforge/src/apis/permissions.tsindex 562ceffa0..3443cc816 100644--- a/packages/trueforge/src/apis/permissions.ts+++ b/packages/trueforge/src/apis/permissions.ts@@ -26,7 +26,9 @@ export function createPermissionsRouter<TTransaction>(deps: PermissionsRouterDepconst { resource_type: resourceType, resource_ids: resourceIds } = body;let input: GetPermissionsInput;- if (resourceType === 'agent') {+ if (resourceType === 'tenant') {+ input = { resourceType: 'tenant', requestContext, resourceIds };+ } else if (resourceType === 'agent') {input = {resourceType: 'agent',requestContext,diff --git a/packages/trueforge/src/auth/authorizer.ts b/packages/trueforge/src/auth/authorizer.tsindex 8182bc360..c7724baf9 100644--- a/packages/trueforge/src/auth/authorizer.ts+++ b/packages/trueforge/src/auth/authorizer.ts@@ -5,9 +5,11 @@ import {AGENT_OWNER_PERMISSIONS,AGENT_USE_PERMISSIONS,emptyPermissionsByResourceId,+ listPermissionsData,SCHEDULE_OWNER_PERMISSIONS,SESSION_OWNER_PERMISSIONS,- type ResourcePermission,+ TENANT_CREATE_AGENT_PERMISSIONS,+ type ListPermissionsData,} from '../schemas/permissions';import type { RequestContext } from './identity';@@ -23,12 +25,13 @@ interface GetPermissionsBase {export type GetPermissionsInput =| (GetPermissionsBase & { resourceType: 'agent'; store: IAgentStore })| (GetPermissionsBase & { resourceType: 'schedule'; store: IScheduleStore })- | (GetPermissionsBase & { resourceType: 'session'; store: ISessionStore });+ | (GetPermissionsBase & { resourceType: 'session'; store: ISessionStore })+ | (GetPermissionsBase & { resourceType: 'tenant' });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[]>>;+ getPermissions(input: GetPermissionsInput): Promise<ListPermissionsData>;}/** Standalone and OIDC: tenant-local agents. Read/use are unconstrained; manage/delete are creator-only. */@@ -44,7 +47,11 @@ 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[]>> {+ async getPermissions(input: GetPermissionsInput): Promise<ListPermissionsData> {+ if (input.resourceType === 'tenant') {+ return listPermissionsData('tenant', { agent: [...TENANT_CREATE_AGENT_PERMISSIONS] });+ }+const data = emptyPermissionsByResourceId(input.resourceIds);if (input.resourceType === 'agent') {@@ -57,7 +64,7 @@ export class TrueForgeAuthorizer implements Authorizer {for (const id of input.resourceIds) {data[id] = owned.has(id) ? [...AGENT_OWNER_PERMISSIONS] : [...AGENT_USE_PERMISSIONS];}- return data;+ return listPermissionsData('agent', data);}if (input.resourceType === 'schedule') {@@ -69,7 +76,7 @@ export class TrueForgeAuthorizer implements Authorizer {for (const id of ownedIds) {data[id] = [...SCHEDULE_OWNER_PERMISSIONS];}- return data;+ return listPermissionsData('schedule', data);}const ownedIds = await input.store.getOwnedIds({@@ -80,6 +87,6 @@ export class TrueForgeAuthorizer implements Authorizer {for (const id of ownedIds) {data[id] = [...SESSION_OWNER_PERMISSIONS];}- return data;+ return listPermissionsData('session', data);}}diff --git a/packages/trueforge/src/routes/permissionRoutes.ts b/packages/trueforge/src/routes/permissionRoutes.tsindex d3325fa45..fe29561dc 100644--- a/packages/trueforge/src/routes/permissionRoutes.ts+++ b/packages/trueforge/src/routes/permissionRoutes.ts@@ -11,7 +11,7 @@ export const listPermissionsRoute = createRoute({path: '/list-permissions',tags: [OpenApiTag.INTERNAL],summary: 'List permissions for resources',- description: 'Return granted actions for each requested agent, schedule, or session id.',+ description: 'Return granted actions for the requested resources.','x-fern-sdk-group-name': ['internal'],'x-fern-sdk-method-name': 'list_permissions',request: {@@ -23,7 +23,7 @@ export const listPermissionsRoute = createRoute({responses: {200: {content: { 'application/json': { schema: ListPermissionsResponseSchema } },- description: 'Permissions keyed by resource id.',+ description: 'Permissions envelope: `{ type, permissions }`.',},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },diff --git a/packages/trueforge/src/schemas/permissions.ts b/packages/trueforge/src/schemas/permissions.tsindex a53039b50..68e91cd04 100644--- a/packages/trueforge/src/schemas/permissions.ts+++ b/packages/trueforge/src/schemas/permissions.ts@@ -2,7 +2,7 @@import { z } from '@hono/zod-openapi';export const PermissionResourceTypeSchema = z- .enum(['agent', 'schedule', 'session'])+ .enum(['agent', 'schedule', 'session', 'tenant']).describe('Resource type to evaluate permissions for.').openapi('PermissionResourceType');@@ -21,27 +21,39 @@ export const SessionResourcePermissionSchema = z.describe('Granted action on a session.').openapi('SessionResourcePermission');+/** Tenant-scoped create actions (keys are entity kinds, e.g. `agent`). */+export const TenantScopedResourcePermissionSchema = z+ .enum(['CREATE'])+ .describe('Granted create action on a tenant-scoped entity kind.')+ .openapi('TenantScopedResourcePermission');+/** Any permission that may appear in a list-permissions response. */export const ResourcePermissionSchema = z- .enum(['USE', 'MANAGE', 'DELETE'])- .describe('Granted action on a resource.')+ .enum(['USE', 'MANAGE', 'DELETE', 'CREATE'])+ .describe('Granted action on a resource id or tenant entity kind.').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.'),+ resource_ids: z.array(z.string().min(1)).max(100).describe('Resource ids of `resource_type` to evaluate.'),}).openapi('ListPermissionsRequest');-export const ListPermissionsResponseSchema = z+export const ListPermissionsDataSchema = z.object({- data: z+ type: PermissionResourceTypeSchema,+ permissions: z.record(z.string(), z.array(ResourcePermissionSchema))- .describe('Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`.'),+ .describe(+ 'For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` → `CREATE`).',+ ),+ })+ .openapi('ListPermissionsData');++export const ListPermissionsResponseSchema = z+ .object({+ data: ListPermissionsDataSchema,}).openapi('ListPermissionsResponse');@@ -49,16 +61,26 @@ export type PermissionResourceType = z.infer<typeof PermissionResourceTypeSchemaexport type AgentResourcePermission = z.infer<typeof AgentResourcePermissionSchema>;export type ScheduleResourcePermission = z.infer<typeof ScheduleResourcePermissionSchema>;export type SessionResourcePermission = z.infer<typeof SessionResourcePermissionSchema>;+export type TenantScopedResourcePermission = z.infer<typeof TenantScopedResourcePermissionSchema>;export type ResourcePermission = z.infer<typeof ResourcePermissionSchema>;export type ListPermissionsRequest = z.infer<typeof ListPermissionsRequestSchema>;+export type ListPermissionsData = z.infer<typeof ListPermissionsDataSchema>;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;+export const TENANT_CREATE_AGENT_PERMISSIONS = [TenantScopedResourcePermissionSchema.enum.CREATE] as const;/** 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[]]));}++export function listPermissionsData(+ type: PermissionResourceType,+ permissions: Record<string, ResourcePermission[]>,+): ListPermissionsData {+ return { type, permissions };+}diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts b/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.tsindex 0561d0231..f91e7a7ff 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryAuthorizer.ts@@ -3,11 +3,13 @@ import { HTTPException } from 'hono/http-exception';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 type { ListPermissionsData, ResourcePermission } from '../schemas/permissions';import {emptyPermissionsByResourceId,+ listPermissionsData,SCHEDULE_OWNER_PERMISSIONS,SESSION_OWNER_PERMISSIONS,+ TENANT_CREATE_AGENT_PERMISSIONS,} from '../schemas/permissions';import type { AgentPermission, TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';@@ -73,8 +75,17 @@ export class TrueFoundryAuthorizer implements Authorizer {return allowsAction(permissions[input.agent.external_id] ?? [], input.action);}- async getPermissions(input: GetPermissionsInput): Promise<Record<string, ResourcePermission[]>> {+ async getPermissions(input: GetPermissionsInput): Promise<ListPermissionsData> {const { requestContext, resourceIds } = input;++ if (input.resourceType === 'tenant') {+ const tenantPermissions = await this.#client.getTenantPermissions({+ accessToken: requireUserCredential(requestContext),+ });+ const agent = tenantPermissions.includes('CREATE_AGENT') ? [...TENANT_CREATE_AGENT_PERMISSIONS] : [];+ return listPermissionsData('tenant', { agent });+ }+const data = emptyPermissionsByResourceId(resourceIds);if (input.resourceType === 'agent') {@@ -83,7 +94,7 @@ export class TrueFoundryAuthorizer implements Authorizer {ids: resourceIds,});if (agents.length === 0) {- return data;+ return listPermissionsData('agent', data);}const permissions = await this.#client.getAgentPermissions({accessToken: requireUserCredential(requestContext),@@ -92,7 +103,7 @@ export class TrueFoundryAuthorizer implements Authorizer {for (const agent of agents) {data[agent.id] = toResourcePermissions(permissions[agent.external_id] ?? []);}- return data;+ return listPermissionsData('agent', data);}if (input.resourceType === 'schedule') {@@ -104,7 +115,7 @@ export class TrueFoundryAuthorizer implements Authorizer {for (const id of ownedIds) {data[id] = [...SCHEDULE_OWNER_PERMISSIONS];}- return data;+ return listPermissionsData('schedule', data);}const ownedIds = await input.store.getOwnedIds({@@ -115,6 +126,6 @@ export class TrueFoundryAuthorizer implements Authorizer {for (const id of ownedIds) {data[id] = [...SESSION_OWNER_PERMISSIONS];}- return data;+ return listPermissionsData('session', data);}}diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.tsindex fd28adfd4..d627f8d9d 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts@@ -531,6 +531,29 @@ export class TrueFoundryServiceFoundryServerClient {return parsed.data;}+ /**+ * `GET v1/authorize/permissions?resourceType=tenant&v2=true` — flat action list+ * (tenant + root-account merged), same as the platform FE Create Agent check.+ */+ async getTenantPermissions(input: { accessToken: string }): Promise<string[]> {+ const payload = await this.#requestJson({+ url: this.#url(AGENT_PERMISSIONS_PATH, { resourceType: 'tenant', v2: 'true' }),+ accessToken: input.accessToken,+ method: 'GET',+ });+ const parsed = z.array(z.string()).safeParse(payload);+ if (!parsed.success) {+ this.#logger.error('TrueFoundry ServiceFoundry tenant permissions response was malformed', {+ ...extractErrorLogFields(parsed.error),+ });+ throw new HTTPException(424, {+ message: 'TrueFoundry ServiceFoundry tenant permissions response was malformed',+ cause: parsed.error,+ });+ }+ return parsed.data;+ }+/*** Exchange a TrueFoundry API key for dual agent-scoped tokens.* Wire `actorToken` is the agent identity (`asAgent`); wire `subjectToken` is the user with agent in `act` (`asUser`).diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.tsindex dede2fedc..dbb83d6c6 100644--- a/packages/trueforge/tests/unit/apis/agents.test.ts+++ b/packages/trueforge/tests/unit/apis/agents.test.ts@@ -82,7 +82,10 @@ const deniedCanAccessAgent = jest.fn((_input: Parameters<Authorizer['canAccessAgconst denyAllAuthorizer: Authorizer = {listAgentAccess: deniedListAgentAccess,canAccessAgent: deniedCanAccessAgent,- getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: 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.tsindex 7be02cf23..af4b1bf1f 100644--- a/packages/trueforge/tests/unit/apis/schedules.test.ts+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts@@ -215,7 +215,10 @@ describe('schedule RBAC', () => {: { kind: 'agent_external_ids', agent_external_ids: [] },),canAccessAgent: () => Promise.resolve(false),- getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: Object.fromEntries(resourceIds.map(id => [id, []])),+ }),});asUser(BOB);expect((await app.request(`/${id}`)).status).toBe(200);@@ -383,7 +386,10 @@ 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, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: Object.fromEntries(resourceIds.map(id => [id, []])),+ }),};const { postJson } = await setup(denyAll);const res = await postJson('/', 'POST', scheduleBody);@@ -403,7 +409,10 @@ 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, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: 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.tsindex 2112b6fd1..2ed5ed6fa 100644--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts@@ -45,7 +45,10 @@ const deniedCanAccessAgent = jest.fn((_input: Parameters<Authorizer['canAccessAgconst denyAllAuthorizer: Authorizer = {listAgentAccess: () => Promise.resolve({ kind: 'agent_external_ids', agent_external_ids: [] }),canAccessAgent: deniedCanAccessAgent,- getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: Object.fromEntries(resourceIds.map(id => [id, []])),+ }),};describe('sessions HTTP agent binding', () => {@@ -268,7 +271,10 @@ 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, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: 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.tsindex 42c872ad9..d7e61d99d 100644--- a/packages/trueforge/tests/unit/apis/turns.test.ts+++ b/packages/trueforge/tests/unit/apis/turns.test.ts@@ -162,7 +162,10 @@ describe('turns', () => {: { kind: 'agent_external_ids', agent_external_ids: [] },),canAccessAgent: () => Promise.resolve(false),- getPermissions: async ({ resourceIds }) => Object.fromEntries(resourceIds.map(id => [id, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: Object.fromEntries(resourceIds.map(id => [id, []])),+ }),},}),);@@ -417,7 +420,10 @@ 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, []])),+ getPermissions: async ({ resourceType, resourceIds }) => ({+ type: resourceType,+ permissions: 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.tsindex 340eed69e..5b6627022 100644--- a/packages/trueforge/tests/unit/auth/authorizerPermissions.test.ts+++ b/packages/trueforge/tests/unit/auth/authorizerPermissions.test.ts@@ -34,8 +34,11 @@ describe('TrueForgeAuthorizer.getPermissions', () => {store: agentStore,}),).toEqual({- 'agent-1': ['USE', 'MANAGE', 'DELETE'],- 'agent-2': ['USE'],+ type: 'agent',+ permissions: {+ 'agent-1': ['USE', 'MANAGE', 'DELETE'],+ 'agent-2': ['USE'],+ },});expect(@@ -46,7 +49,10 @@ describe('TrueForgeAuthorizer.getPermissions', () => {store: agentStore,}),).toEqual({- 'agent-1': ['USE'],+ type: 'agent',+ permissions: {+ 'agent-1': ['USE'],+ },});});@@ -65,8 +71,11 @@ describe('TrueForgeAuthorizer.getPermissions', () => {store: scheduleStore,}),).toEqual({- 'sched-1': ['MANAGE', 'DELETE'],- 'sched-2': [],+ type: 'schedule',+ permissions: {+ 'sched-1': ['MANAGE', 'DELETE'],+ 'sched-2': [],+ },});expect(@@ -77,7 +86,23 @@ describe('TrueForgeAuthorizer.getPermissions', () => {store: scheduleStore,}),).toEqual({- 'sched-1': [],+ type: 'schedule',+ permissions: {+ 'sched-1': [],+ },+ });+ });++ it('always grants tenant agent CREATE in standalone mode', async () => {+ expect(+ await authorizer.getPermissions({+ resourceType: 'tenant',+ requestContext: ALICE,+ resourceIds: [],+ }),+ ).toEqual({+ type: 'tenant',+ permissions: { agent: ['CREATE'] },});});});diff --git a/packages/trueforge/tests/unit/auth/trueFoundryAuthorizerPermissions.test.ts b/packages/trueforge/tests/unit/auth/trueFoundryAuthorizerPermissions.test.tsnew file mode 100644index 000000000..e9e245487--- /dev/null+++ b/packages/trueforge/tests/unit/auth/trueFoundryAuthorizerPermissions.test.ts@@ -0,0 +1,49 @@+import type { RequestContext } from '../../../src/auth/identity';+import { TrueFoundryAuthorizer } from '../../../src/truefoundry/TrueFoundryAuthorizer';+import type { TrueFoundryServiceFoundryServerClient } from '../../../src/truefoundry/TrueFoundryServiceFoundryServerClient';++const ALICE: RequestContext = {+ tenant_id: 'default',+ subject: { id: 'alice', type: 'user', display_name: 'alice' },+ roles: [],+ user_credential: 'user-jwt',+};++describe('TrueFoundryAuthorizer.getPermissions tenant', () => {+ it('maps CREATE_AGENT to tenant agent CREATE', async () => {+ const client = {+ getTenantPermissions: jest.fn(async () => ['CREATE_AGENT', 'CREATE_WORKSPACE']),+ } as unknown as TrueFoundryServiceFoundryServerClient;+ const authorizer = new TrueFoundryAuthorizer(client);++ await expect(+ authorizer.getPermissions({+ resourceType: 'tenant',+ requestContext: ALICE,+ resourceIds: [],+ }),+ ).resolves.toEqual({+ type: 'tenant',+ permissions: { agent: ['CREATE'] },+ });+ expect(client.getTenantPermissions).toHaveBeenCalledWith({ accessToken: 'user-jwt' });+ });++ it('returns empty agent grants when CREATE_AGENT is absent', async () => {+ const client = {+ getTenantPermissions: jest.fn(async () => ['CREATE_WORKSPACE']),+ } as unknown as TrueFoundryServiceFoundryServerClient;+ const authorizer = new TrueFoundryAuthorizer(client);++ await expect(+ authorizer.getPermissions({+ resourceType: 'tenant',+ requestContext: ALICE,+ resourceIds: [],+ }),+ ).resolves.toEqual({+ type: 'tenant',+ permissions: { agent: [] },+ });+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4c1f7623e..19bd91a16 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -69,8 +69,8 @@ importers:specifier: 0.2.21version: 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])'@truefoundry/assistant-ui-runtime':- specifier: 0.1.38- version: 0.1.38(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))+ specifier: 0.1.39+ version: 0.1.39(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))'@truefoundry/trueforge-sdk':specifier: workspace:*version: link:../trueforge-sdk@@ -369,8 +369,8 @@ importers:specifier: ^0.13.2version: 0.13.3(@openuidev/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected]))))(@openuidev/[email protected](@modelcontextprotocol/[email protected]([email protected])([email protected]))([email protected])([email protected]))(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))'@truefoundry/assistant-ui-runtime':- specifier: 0.1.38- version: 0.1.38(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))+ specifier: 0.1.39+ version: 0.1.39(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))'@truefoundry/trueforge-sdk':specifier: workspace:*version: link:../trueforge-sdk@@ -3651,8 +3651,8 @@ packages:'@types/react-dom':optional: true- '@truefoundry/[email protected]':- resolution: {integrity: sha512-7MyM2ulmp6jRpOMNJUDe9iFeiH62qqBCNtFBlkKt1+gIDRm/DCYNBZud0n6jVDDljlYV2v1SIeHKZ9GQbz9gEQ==}+ '@truefoundry/[email protected]':+ resolution: {integrity: sha512-8xJFNBJ7i7Oe/zMtU5be2JEMm61PRMEs6rh8aj7f021S2bB3zS42Hjjan5kJwlBl3nZNN8m5kMFlZ2QwjuFLGQ==}peerDependencies:'@types/react': '*'react: ^18 || ^19@@ -10911,7 +10911,7 @@ snapshots:'@types/react': 19.2.18'@types/react-dom': 19.2.5(@types/[email protected])- '@truefoundry/[email protected](@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))':+ '@truefoundry/[email protected](@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]([email protected])))':dependencies:'@assistant-ui/core': 0.2.22(@assistant-ui/[email protected](@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]))(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected]([email protected](@opentelemetry/[email protected])))([email protected])([email protected](@opentelemetry/[email protected]))([email protected](@types/[email protected])([email protected])([email protected]([email protected])))'@assistant-ui/store': 0.2.21(@assistant-ui/[email protected](@types/[email protected])([email protected]))(@types/[email protected])([email protected])diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex f368955ea..c8ad9525b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -17,7 +17,7 @@ allowBuilds:# Silence peer mismatches between trueforge-ui peers and the versions we pin.peerDependencyRules:allowedVersions:- '@truefoundry/assistant-ui-runtime': '0.1.34'+ '@truefoundry/assistant-ui-runtime': '0.1.39'# One Context module for assistant-ui (avoids "requires an AuiProvider").overrides:diff --git a/python/trueforge_sdk/reference.md b/python/trueforge_sdk/reference.mdindex 352def7b7..6fb8dd5dd 100644--- a/python/trueforge_sdk/reference.md+++ b/python/trueforge_sdk/reference.md@@ -12,7 +12,7 @@<dl><dd>-Return granted actions for each requested agent, schedule, or session id.+Return granted actions for the requested resources.</dd></dl></dd>@@ -55,7 +55,7 @@ client.internal.list_permissions(<dl><dd>-**resource_ids:** `typing.List[str]` — Resource ids of `resource_type` to evaluate for the caller.+**resource_ids:** `typing.List[str]` — Resource ids of `resource_type` to evaluate.</dd></dl>diff --git a/python/trueforge_sdk/src/trueforge_sdk/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/__init__.pyindex 47d8597df..f336deeec 100644--- a/python/trueforge_sdk/src/trueforge_sdk/__init__.py+++ b/python/trueforge_sdk/src/trueforge_sdk/__init__.py@@ -98,6 +98,7 @@ if typing.TYPE_CHECKING:ListMcpServerToolsResponse,ListMcpServersResponse,ListModelProvidersResponse,+ ListPermissionsData,ListPermissionsResponse,ListScheduleRunsResponse,ListSchedulesResponse,@@ -358,6 +359,7 @@ _dynamic_imports: typing.Dict[str, str] = {"ListMcpServerToolsResponse": ".types","ListMcpServersResponse": ".types","ListModelProvidersResponse": ".types",+ "ListPermissionsData": ".types","ListPermissionsResponse": ".types","ListScheduleRunsResponse": ".types","ListSchedulesResponse": ".types",@@ -640,6 +642,7 @@ __all__ = ["ListMcpServerToolsResponse","ListMcpServersResponse","ListModelProvidersResponse",+ "ListPermissionsData","ListPermissionsResponse","ListScheduleRunsResponse","ListSchedulesResponse",diff --git a/python/trueforge_sdk/src/trueforge_sdk/internal/client.py b/python/trueforge_sdk/src/trueforge_sdk/internal/client.pyindex 36f835c32..69c823dad 100644--- a/python/trueforge_sdk/src/trueforge_sdk/internal/client.py+++ b/python/trueforge_sdk/src/trueforge_sdk/internal/client.py@@ -47,12 +47,12 @@ class InternalClient:request_options: typing.Optional[RequestOptions] = None,) -> ListPermissionsResponse:"""- Return granted actions for each requested agent, schedule, or session id.+ Return granted actions for the requested resources.Parameters----------resource_ids : typing.Sequence[str]- Resource ids of `resource_type` to evaluate for the caller.+ Resource ids of `resource_type` to evaluate.resource_type : PermissionResourceType@@ -62,7 +62,7 @@ class InternalClient:Returns-------ListPermissionsResponse- Permissions keyed by resource id.+ Permissions envelope: `{ type, permissions }`.Examples--------@@ -143,12 +143,12 @@ class AsyncInternalClient:request_options: typing.Optional[RequestOptions] = None,) -> ListPermissionsResponse:"""- Return granted actions for each requested agent, schedule, or session id.+ Return granted actions for the requested resources.Parameters----------resource_ids : typing.Sequence[str]- Resource ids of `resource_type` to evaluate for the caller.+ Resource ids of `resource_type` to evaluate.resource_type : PermissionResourceType@@ -158,7 +158,7 @@ class AsyncInternalClient:Returns-------ListPermissionsResponse- Permissions keyed by resource id.+ Permissions envelope: `{ type, permissions }`.Examples--------diff --git a/python/trueforge_sdk/src/trueforge_sdk/internal/raw_client.py b/python/trueforge_sdk/src/trueforge_sdk/internal/raw_client.pyindex 7cb7947e6..335014346 100644--- a/python/trueforge_sdk/src/trueforge_sdk/internal/raw_client.py+++ b/python/trueforge_sdk/src/trueforge_sdk/internal/raw_client.py@@ -32,12 +32,12 @@ class RawInternalClient:request_options: typing.Optional[RequestOptions] = None,) -> HttpResponse[ListPermissionsResponse]:"""- Return granted actions for each requested agent, schedule, or session id.+ Return granted actions for the requested resources.Parameters----------resource_ids : typing.Sequence[str]- Resource ids of `resource_type` to evaluate for the caller.+ Resource ids of `resource_type` to evaluate.resource_type : PermissionResourceType@@ -47,7 +47,7 @@ class RawInternalClient:Returns-------HttpResponse[ListPermissionsResponse]- Permissions keyed by resource id.+ Permissions envelope: `{ type, permissions }`."""_response = self._client_wrapper.httpx_client.request("api/internal/list-permissions",@@ -116,12 +116,12 @@ class AsyncRawInternalClient:request_options: typing.Optional[RequestOptions] = None,) -> AsyncHttpResponse[ListPermissionsResponse]:"""- Return granted actions for each requested agent, schedule, or session id.+ Return granted actions for the requested resources.Parameters----------resource_ids : typing.Sequence[str]- Resource ids of `resource_type` to evaluate for the caller.+ Resource ids of `resource_type` to evaluate.resource_type : PermissionResourceType@@ -131,7 +131,7 @@ class AsyncRawInternalClient:Returns-------AsyncHttpResponse[ListPermissionsResponse]- Permissions keyed by resource id.+ Permissions envelope: `{ type, permissions }`."""_response = await self._client_wrapper.httpx_client.request("api/internal/list-permissions",diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.pyindex a77f06cbc..c242e7818 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py@@ -97,6 +97,7 @@ if typing.TYPE_CHECKING:from .list_mcp_server_tools_response import ListMcpServerToolsResponsefrom .list_mcp_servers_response import ListMcpServersResponsefrom .list_model_providers_response import ListModelProvidersResponse+ from .list_permissions_data import ListPermissionsDatafrom .list_permissions_response import ListPermissionsResponsefrom .list_schedule_runs_response import ListScheduleRunsResponsefrom .list_schedules_response import ListSchedulesResponse@@ -327,6 +328,7 @@ _dynamic_imports: typing.Dict[str, str] = {"ListMcpServerToolsResponse": ".list_mcp_server_tools_response","ListMcpServersResponse": ".list_mcp_servers_response","ListModelProvidersResponse": ".list_model_providers_response",+ "ListPermissionsData": ".list_permissions_data","ListPermissionsResponse": ".list_permissions_response","ListScheduleRunsResponse": ".list_schedule_runs_response","ListSchedulesResponse": ".list_schedules_response",@@ -581,6 +583,7 @@ __all__ = ["ListMcpServerToolsResponse","ListMcpServersResponse","ListModelProvidersResponse",+ "ListPermissionsData","ListPermissionsResponse","ListScheduleRunsResponse","ListSchedulesResponse",diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_data.py b/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_data.pynew file mode 100644index 000000000..ea978b7fc--- /dev/null+++ b/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_data.py@@ -0,0 +1,26 @@+# This file was auto-generated by Fern from our API Definition.++import typing++import pydantic+from ..core.pydantic_utilities import IS_PYDANTIC_V2+from ..core.unchecked_base_model import UncheckedBaseModel+from .permission_resource_type import PermissionResourceType+from .resource_permission import ResourcePermission+++class ListPermissionsData(UncheckedBaseModel):+ permissions: typing.Dict[str, typing.List[ResourcePermission]] = pydantic.Field()+ """+ For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` → `CREATE`).+ """++ type: PermissionResourceType++ if IS_PYDANTIC_V2:+ model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2+ else:++ class Config:+ smart_union = True+ extra = pydantic.Extra.allowdiff --git a/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_response.py b/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_response.pyindex 8ea35697b..4b9b7a9ab 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_response.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/list_permissions_response.py@@ -5,14 +5,11 @@ import typingimport pydanticfrom ..core.pydantic_utilities import IS_PYDANTIC_V2from ..core.unchecked_base_model import UncheckedBaseModel-from .resource_permission import ResourcePermission+from .list_permissions_data import ListPermissionsDataclass ListPermissionsResponse(UncheckedBaseModel):- data: typing.Dict[str, typing.List[ResourcePermission]] = pydantic.Field()- """- Permissions granted to the caller, keyed by resource id. Missing or inaccessible ids are `[]`.- """+ data: ListPermissionsDataif IS_PYDANTIC_V2:model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/permission_resource_type.py b/python/trueforge_sdk/src/trueforge_sdk/types/permission_resource_type.pyindex 59ca69be1..593e62999 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/permission_resource_type.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/permission_resource_type.py@@ -15,6 +15,7 @@ class PermissionResourceType(enum.StrEnum):AGENT = "agent"SCHEDULE = "schedule"SESSION = "session"+ TENANT = "tenant"_UNKNOWN = "__PERMISSIONRESOURCETYPE_UNKNOWN__""""This member is used for forward compatibility. If the value is not recognized by the enum, it will be stored here, and the raw value is accessible through `.value`.@@ -31,6 +32,7 @@ class PermissionResourceType(enum.StrEnum):agent: typing.Callable[[], T_Result],schedule: typing.Callable[[], T_Result],session: typing.Callable[[], T_Result],+ tenant: typing.Callable[[], T_Result],_unknown_member: typing.Callable[[str], T_Result],) -> T_Result:if self is PermissionResourceType.AGENT:@@ -39,4 +41,6 @@ class PermissionResourceType(enum.StrEnum):return schedule()if self is PermissionResourceType.SESSION:return session()+ if self is PermissionResourceType.TENANT:+ return tenant()return _unknown_member(self._value_)diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/resource_permission.py b/python/trueforge_sdk/src/trueforge_sdk/types/resource_permission.pyindex a26c3601e..0348f5d7d 100644--- a/python/trueforge_sdk/src/trueforge_sdk/types/resource_permission.py+++ b/python/trueforge_sdk/src/trueforge_sdk/types/resource_permission.py@@ -9,12 +9,13 @@ T_Result = typing.TypeVar("T_Result")class ResourcePermission(enum.StrEnum):"""- Granted action on a resource.+ Granted action on a resource id or tenant entity kind."""USE = "USE"MANAGE = "MANAGE"DELETE = "DELETE"+ CREATE = "CREATE"_UNKNOWN = "__RESOURCEPERMISSION_UNKNOWN__""""This member is used for forward compatibility. If the value is not recognized by the enum, it will be stored here, and the raw value is accessible through `.value`.@@ -31,6 +32,7 @@ class ResourcePermission(enum.StrEnum):use: typing.Callable[[], T_Result],manage: typing.Callable[[], T_Result],delete: typing.Callable[[], T_Result],+ create: typing.Callable[[], T_Result],_unknown_member: typing.Callable[[str], T_Result],) -> T_Result:if self is ResourcePermission.USE:@@ -39,4 +41,6 @@ class ResourcePermission(enum.StrEnum):return manage()if self is ResourcePermission.DELETE:return delete()+ if self is ResourcePermission.CREATE:+ return create()return _unknown_member(self._value_)