The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Remove agent session migrations import apis (#1023)
Sujai Kumar Guptaee3cbc49456a
diff --git a/.changeset/remove-sf-trueforge-import.md b/.changeset/remove-sf-trueforge-import.mdnew file mode 100644index 000000000..591857b53--- /dev/null+++ b/.changeset/remove-sf-trueforge-import.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge': patch+---++Remove the internal ServiceFoundry agent and session import API used for the TrueFoundry to TrueForge backfill, including the unused managed-agent ID passed on agent create.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 40a8100b3..186354aad 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -1834,391 +1834,6 @@],"type": "object"},- "ImportAgentItem": {- "additionalProperties": false,- "properties": {- "created_by_subject": {- "allOf": [- {- "$ref": "#/components/schemas/CreatedBySubject"- },- {- "description": "Original creator to persist on the agent."- }- ]- },- "description": {- "maxLength": 1024,- "minLength": 1,- "type": "string"- },- "manifest": {- "$ref": "#/components/schemas/AgentSpec"- },- "name": {- "$ref": "#/components/schemas/ResourceName"- },- "tenant_id": {- "description": "Tenant to create the agent under.",- "minLength": 1,- "type": "string"- },- "truefoundry_managed_agent_id": {- "type": "string"- }- },- "required": [- "name",- "manifest",- "tenant_id",- "created_by_subject",- "truefoundry_managed_agent_id"- ],- "type": "object"- },- "ImportAgentItemResult": {- "additionalProperties": false,- "properties": {- "agent_id": {- "minLength": 1,- "type": "string"- },- "error": {- "type": "string"- },- "name": {- "minLength": 1,- "type": "string"- },- "status": {- "enum": [- "created",- "exists",- "failed"- ],- "type": "string"- },- "tenant_id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "name",- "tenant_id",- "status"- ],- "type": "object"- },- "ImportAgentsRequest": {- "additionalProperties": false,- "properties": {- "agents": {- "description": "Agents to create; each carries tenant_id and created_by_subject.",- "items": {- "$ref": "#/components/schemas/ImportAgentItem"- },- "type": "array"- }- },- "required": [- "agents"- ],- "type": "object"- },- "ImportAgentsResponse": {- "additionalProperties": false,- "properties": {- "data": {- "$ref": "#/components/schemas/ImportAgentsResult"- }- },- "required": [- "data"- ],- "type": "object"- },- "ImportAgentsResult": {- "additionalProperties": false,- "properties": {- "results": {- "items": {- "$ref": "#/components/schemas/ImportAgentItemResult"- },- "type": "array"- }- },- "required": [- "results"- ],- "type": "object"- },- "ImportSessionEvent": {- "additionalProperties": {},- "properties": {- "created_at": {- "minLength": 1,- "type": "string"- },- "id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "id",- "created_at"- ],- "type": "object"- },- "ImportSessionRequest": {- "properties": {- "session": {- "$ref": "#/components/schemas/ImportSessionSnapshot"- },- "turns": {- "items": {- "$ref": "#/components/schemas/ImportSessionTurn"- },- "minItems": 1,- "type": "array"- }- },- "required": [- "session",- "turns"- ],- "type": "object"- },- "ImportSessionResponse": {- "properties": {- "data": {- "$ref": "#/components/schemas/ImportSessionResult"- }- },- "required": [- "data"- ],- "type": "object"- },- "ImportSessionResult": {- "properties": {- "imported": {- "type": "boolean"- },- "session_id": {- "type": "string"- }- },- "required": [- "imported",- "session_id"- ],- "type": "object"- },- "ImportSessionSnapshot": {- "additionalProperties": {},- "properties": {- "agent_id": {- "minLength": 1,- "type": [- "string",- "null"- ]- },- "agent_name": {- "minLength": 1,- "type": [- "string",- "null"- ]- },- "agent_spec": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "created_at": {- "minLength": 1,- "type": "string"- },- "created_by_subject": {- "$ref": "#/components/schemas/CreatedBySubject"- },- "custom": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "last_activity_timestamp_ms": {- "type": "number"- },- "last_turn_id": {- "type": [- "string",- "null"- ]- },- "session_id": {- "minLength": 1,- "type": "string"- },- "tenant_id": {- "minLength": 1,- "type": "string"- },- "title": {- "type": [- "string",- "null"- ]- },- "updated_at": {- "minLength": 1,- "type": "string"- }- },- "required": [- "session_id",- "tenant_id",- "created_by_subject",- "title",- "last_turn_id",- "custom",- "last_activity_timestamp_ms",- "created_at",- "updated_at"- ],- "type": "object"- },- "ImportSessionThread": {- "additionalProperties": {},- "properties": {- "agent_info": {},- "capability_state": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "completion": {},- "context": {- "items": {},- "type": "array"- },- "current_context_usage": {},- "parent": {},- "thread_id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "thread_id",- "context",- "capability_state"- ],- "type": "object"- },- "ImportSessionTurn": {- "additionalProperties": {},- "properties": {- "ancestor_ids": {- "items": {- "type": "string"- },- "type": "array"- },- "checkpoint": {},- "created_at": {- "minLength": 1,- "type": "string"- },- "custom": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "events": {- "items": {- "$ref": "#/components/schemas/ImportSessionEvent"- },- "type": "array"- },- "first_turn_id": {- "minLength": 1,- "type": "string"- },- "input": {- "items": {},- "type": "array"- },- "previous_turn_id": {- "type": [- "string",- "null"- ]- },- "state": {},- "threads": {- "items": {- "$ref": "#/components/schemas/ImportSessionThread"- },- "type": "array"- },- "turn_id": {- "minLength": 1,- "type": "string"- },- "updated_at": {- "minLength": 1,- "type": "string"- }- },- "required": [- "turn_id",- "first_turn_id",- "previous_turn_id",- "ancestor_ids",- "input",- "custom",- "created_at",- "updated_at",- "threads",- "events"- ],- "type": "object"- },- "ImportSessionsCheckpointResponse": {- "additionalProperties": false,- "properties": {- "data": {- "properties": {- "created_at": {- "type": [- "string",- "null"- ]- }- },- "required": [- "created_at"- ],- "type": "object"- }- },- "required": [- "data"- ],- "type": "object"- },"InitialUserMessage": {"properties": {"content": {@@ -6610,168 +6225,6 @@},"openapi": "3.1.0","paths": {- "/api/internal/import/agents": {- "post": {- "description": "Ops/backfill only. Per-item created | exists | failed.",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportAgentsRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportAgentsResponse"- }- }- },- "description": "Per-agent create results."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid body."- }- },- "summary": "Import agents in bulk (create)",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },- "/api/internal/import/checkpoint": {- "get": {- "description": "Min created_at among imported sessions for one tenant (metadata.imported=true).",- "parameters": [- {- "description": "Tenant whose imported-session watermark to read.",- "in": "query",- "name": "tenant_id",- "required": true,- "schema": {- "description": "Tenant whose imported-session watermark to read.",- "minLength": 1,- "type": "string"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionsCheckpointResponse"- }- }- },- "description": "Per-tenant checkpoint watermark."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid query."- },- "500": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Internal server error."- }- },- "summary": "Session import checkpoint",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },- "/api/internal/import/sessions": {- "post": {- "description": "Ops/backfill only. Named sessions link agent_name to a local agent when present; otherwise a dummy agent_id. Drafts use agent_spec (SF name/id stashed in metadata when both present). 409 if session_id exists.",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionRequest"- }- }- },- "required": true- },- "responses": {- "201": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionResponse"- }- }- },- "description": "Imported."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid body or non-importable session (e.g. missing agent_id for unresolved named agent)."- },- "409": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionResponse"- }- }- },- "description": "Session already exists."- },- "500": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Internal server error."- }- },- "summary": "Import one historical session snapshot",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },"/api/internal/list-permissions": {"post": {"description": "Return granted actions for the requested resources.",diff --git a/docs/openapi.json b/docs/openapi.jsonindex 40a8100b3..186354aad 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -1834,391 +1834,6 @@],"type": "object"},- "ImportAgentItem": {- "additionalProperties": false,- "properties": {- "created_by_subject": {- "allOf": [- {- "$ref": "#/components/schemas/CreatedBySubject"- },- {- "description": "Original creator to persist on the agent."- }- ]- },- "description": {- "maxLength": 1024,- "minLength": 1,- "type": "string"- },- "manifest": {- "$ref": "#/components/schemas/AgentSpec"- },- "name": {- "$ref": "#/components/schemas/ResourceName"- },- "tenant_id": {- "description": "Tenant to create the agent under.",- "minLength": 1,- "type": "string"- },- "truefoundry_managed_agent_id": {- "type": "string"- }- },- "required": [- "name",- "manifest",- "tenant_id",- "created_by_subject",- "truefoundry_managed_agent_id"- ],- "type": "object"- },- "ImportAgentItemResult": {- "additionalProperties": false,- "properties": {- "agent_id": {- "minLength": 1,- "type": "string"- },- "error": {- "type": "string"- },- "name": {- "minLength": 1,- "type": "string"- },- "status": {- "enum": [- "created",- "exists",- "failed"- ],- "type": "string"- },- "tenant_id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "name",- "tenant_id",- "status"- ],- "type": "object"- },- "ImportAgentsRequest": {- "additionalProperties": false,- "properties": {- "agents": {- "description": "Agents to create; each carries tenant_id and created_by_subject.",- "items": {- "$ref": "#/components/schemas/ImportAgentItem"- },- "type": "array"- }- },- "required": [- "agents"- ],- "type": "object"- },- "ImportAgentsResponse": {- "additionalProperties": false,- "properties": {- "data": {- "$ref": "#/components/schemas/ImportAgentsResult"- }- },- "required": [- "data"- ],- "type": "object"- },- "ImportAgentsResult": {- "additionalProperties": false,- "properties": {- "results": {- "items": {- "$ref": "#/components/schemas/ImportAgentItemResult"- },- "type": "array"- }- },- "required": [- "results"- ],- "type": "object"- },- "ImportSessionEvent": {- "additionalProperties": {},- "properties": {- "created_at": {- "minLength": 1,- "type": "string"- },- "id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "id",- "created_at"- ],- "type": "object"- },- "ImportSessionRequest": {- "properties": {- "session": {- "$ref": "#/components/schemas/ImportSessionSnapshot"- },- "turns": {- "items": {- "$ref": "#/components/schemas/ImportSessionTurn"- },- "minItems": 1,- "type": "array"- }- },- "required": [- "session",- "turns"- ],- "type": "object"- },- "ImportSessionResponse": {- "properties": {- "data": {- "$ref": "#/components/schemas/ImportSessionResult"- }- },- "required": [- "data"- ],- "type": "object"- },- "ImportSessionResult": {- "properties": {- "imported": {- "type": "boolean"- },- "session_id": {- "type": "string"- }- },- "required": [- "imported",- "session_id"- ],- "type": "object"- },- "ImportSessionSnapshot": {- "additionalProperties": {},- "properties": {- "agent_id": {- "minLength": 1,- "type": [- "string",- "null"- ]- },- "agent_name": {- "minLength": 1,- "type": [- "string",- "null"- ]- },- "agent_spec": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "created_at": {- "minLength": 1,- "type": "string"- },- "created_by_subject": {- "$ref": "#/components/schemas/CreatedBySubject"- },- "custom": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "last_activity_timestamp_ms": {- "type": "number"- },- "last_turn_id": {- "type": [- "string",- "null"- ]- },- "session_id": {- "minLength": 1,- "type": "string"- },- "tenant_id": {- "minLength": 1,- "type": "string"- },- "title": {- "type": [- "string",- "null"- ]- },- "updated_at": {- "minLength": 1,- "type": "string"- }- },- "required": [- "session_id",- "tenant_id",- "created_by_subject",- "title",- "last_turn_id",- "custom",- "last_activity_timestamp_ms",- "created_at",- "updated_at"- ],- "type": "object"- },- "ImportSessionThread": {- "additionalProperties": {},- "properties": {- "agent_info": {},- "capability_state": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "completion": {},- "context": {- "items": {},- "type": "array"- },- "current_context_usage": {},- "parent": {},- "thread_id": {- "minLength": 1,- "type": "string"- }- },- "required": [- "thread_id",- "context",- "capability_state"- ],- "type": "object"- },- "ImportSessionTurn": {- "additionalProperties": {},- "properties": {- "ancestor_ids": {- "items": {- "type": "string"- },- "type": "array"- },- "checkpoint": {},- "created_at": {- "minLength": 1,- "type": "string"- },- "custom": {- "additionalProperties": {},- "type": [- "object",- "null"- ]- },- "events": {- "items": {- "$ref": "#/components/schemas/ImportSessionEvent"- },- "type": "array"- },- "first_turn_id": {- "minLength": 1,- "type": "string"- },- "input": {- "items": {},- "type": "array"- },- "previous_turn_id": {- "type": [- "string",- "null"- ]- },- "state": {},- "threads": {- "items": {- "$ref": "#/components/schemas/ImportSessionThread"- },- "type": "array"- },- "turn_id": {- "minLength": 1,- "type": "string"- },- "updated_at": {- "minLength": 1,- "type": "string"- }- },- "required": [- "turn_id",- "first_turn_id",- "previous_turn_id",- "ancestor_ids",- "input",- "custom",- "created_at",- "updated_at",- "threads",- "events"- ],- "type": "object"- },- "ImportSessionsCheckpointResponse": {- "additionalProperties": false,- "properties": {- "data": {- "properties": {- "created_at": {- "type": [- "string",- "null"- ]- }- },- "required": [- "created_at"- ],- "type": "object"- }- },- "required": [- "data"- ],- "type": "object"- },"InitialUserMessage": {"properties": {"content": {@@ -6610,168 +6225,6 @@},"openapi": "3.1.0","paths": {- "/api/internal/import/agents": {- "post": {- "description": "Ops/backfill only. Per-item created | exists | failed.",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportAgentsRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportAgentsResponse"- }- }- },- "description": "Per-agent create results."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid body."- }- },- "summary": "Import agents in bulk (create)",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },- "/api/internal/import/checkpoint": {- "get": {- "description": "Min created_at among imported sessions for one tenant (metadata.imported=true).",- "parameters": [- {- "description": "Tenant whose imported-session watermark to read.",- "in": "query",- "name": "tenant_id",- "required": true,- "schema": {- "description": "Tenant whose imported-session watermark to read.",- "minLength": 1,- "type": "string"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionsCheckpointResponse"- }- }- },- "description": "Per-tenant checkpoint watermark."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid query."- },- "500": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Internal server error."- }- },- "summary": "Session import checkpoint",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },- "/api/internal/import/sessions": {- "post": {- "description": "Ops/backfill only. Named sessions link agent_name to a local agent when present; otherwise a dummy agent_id. Drafts use agent_spec (SF name/id stashed in metadata when both present). 409 if session_id exists.",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionRequest"- }- }- },- "required": true- },- "responses": {- "201": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionResponse"- }- }- },- "description": "Imported."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Invalid body or non-importable session (e.g. missing agent_id for unresolved named agent)."- },- "409": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ImportSessionResponse"- }- }- },- "description": "Session already exists."- },- "500": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Internal server error."- }- },- "summary": "Import one historical session snapshot",- "tags": [- "Internal"- ],- "x-excluded": true,- "x-fern-ignore": true- }- },"/api/internal/list-permissions": {"post": {"description": "Return granted actions for the requested resources.",diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.tsindex 69a280743..c8e17f8a1 100644--- a/packages/trueforge/scripts/write-openapi.ts+++ b/packages/trueforge/scripts/write-openapi.ts@@ -86,7 +86,6 @@ const app = createServerApp({resolveSandboxProviderStore: () => sandboxProviderStore,resolveWebSearchProviderStore: () => webSearchProviderStore,resolveAgentStore: () => agentStore,- resolveImportAgentStore: () => agentStore,agentStore,sandboxEnvironmentStore,sandboxProviderStore,diff --git a/packages/trueforge/src/apis/agentImport.ts b/packages/trueforge/src/apis/agentImport.tsdeleted file mode 100644index 8f5c56ded..000000000--- a/packages/trueforge/src/apis/agentImport.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Internal import under /api/internal/import (agents + sessions + checkpoint).- */-import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import type { ISessionStore } from '@truefoundry/trueforge-core/agent-session';-import { HTTPException } from 'hono/http-exception';-import { AgentExternalIdConflictError, AgentNameConflictError, type IAgentStore } from '../db/agentStore';-import { PostgresSessionStore, SessionImportValidationError } from '../db/postgres/session-store/PostgresSessionStore';-import { getImportSessionsCheckpointRoute, importAgentsRoute, importSessionRoute } from '../routes/agentImportRoutes';-import type { ImportAgentItemResult } from '../schemas/agentImport';-import {- TFY_ASSUME_USER_HEADER,- tenantSystemAssumeUserHeader,-} from '../truefoundry/TrueFoundryServiceFoundryServerClient';--export interface AgentImportRouterDeps {- sessionStore: ISessionStore;- /** TrueFoundryAgentStore (or DB store) with SF client assume-user headers when needed. */- resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore;-}--function errorDetail(error: unknown): string {- if (!(error instanceof Error)) {- return String(error);- }- return error.stack ? `${error.message}\n${error.stack}` : error.message;-}--export function createAgentImportRouter(deps: AgentImportRouterDeps) {- const router = new OpenAPIHono();-- const importAgentsHandler: RouteHandler<typeof importAgentsRoute> = async c => {- const { agents } = c.req.valid('json');- const results: ImportAgentItemResult[] = [];- const first = agents[0];- if (first === undefined) {- return c.json({ data: { results } }, 200);- }-- const agentStore = deps.resolveImportAgentStore({- [TFY_ASSUME_USER_HEADER]: tenantSystemAssumeUserHeader(first.tenant_id),- });-- for (const agent of agents) {- try {- const created = await agentStore.createAgent({- tenant_id: agent.tenant_id,- name: agent.name,- description: agent.description ?? agent.name,- manifest: agent.manifest,- external_id: null,- created_by_subject: agent.created_by_subject,- custom: {- trueFoundryManagedAgentId: agent.truefoundry_managed_agent_id,- },- });- results.push({- name: created.name,- tenant_id: agent.tenant_id,- status: 'created',- agent_id: created.id,- });- } catch (error) {- if (error instanceof AgentNameConflictError || error instanceof AgentExternalIdConflictError) {- results.push({ name: agent.name, tenant_id: agent.tenant_id, status: 'exists' });- continue;- }- const message = error instanceof Error ? error.message : String(error);- results.push({ name: agent.name, tenant_id: agent.tenant_id, status: 'failed', error: message });- }- }-- return c.json({ data: { results } }, 200);- };-- const importSessionHandler: RouteHandler<typeof importSessionRoute> = async c => {- if (!(deps.sessionStore instanceof PostgresSessionStore)) {- throw new HTTPException(500, {- message: 'Session import requires Postgres (STANDALONE=false)',- });- }- const body = c.req.valid('json');- try {- const result = await deps.sessionStore.importSessionSnapshot(body);- if (!result.imported) {- return c.json({ data: result }, 409);- }- return c.json({ data: result }, 201);- } catch (error) {- if (error instanceof SessionImportValidationError) {- return c.json({ error: { message: error.message } }, 400);- }- throw new HTTPException(500, { message: errorDetail(error), cause: error });- }- };-- const checkpointHandler: RouteHandler<typeof getImportSessionsCheckpointRoute> = async c => {- if (!(deps.sessionStore instanceof PostgresSessionStore)) {- throw new HTTPException(500, {- message: 'Session import requires Postgres (STANDALONE=false)',- });- }- const { tenant_id } = c.req.valid('query');- try {- const data = await deps.sessionStore.getImportSessionsCheckpoint({ tenant_id });- return c.json({ data }, 200);- } catch (error) {- throw new HTTPException(500, { message: errorDetail(error), cause: error });- }- };-- router.openapi(importAgentsRoute, importAgentsHandler);- router.openapi(importSessionRoute, importSessionHandler);- router.openapi(getImportSessionsCheckpointRoute, checkpointHandler);- return router;-}diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.tsindex 97c17b7b3..1c0b0533e 100644--- a/packages/trueforge/src/app.ts+++ b/packages/trueforge/src/app.ts@@ -9,7 +9,6 @@ import { bodyLimit } from 'hono/body-limit';import { HTTPException } from 'hono/http-exception';import type { Configuration } from 'openid-client';import type { Logger } from 'winston';-import { createAgentImportRouter } from './apis/agentImport';import { createAgentsRouter } from './apis/agents';import { createAuthRouter } from './apis/auth';import { createCapabilitiesRouter } from './apis/capabilities';@@ -33,7 +32,6 @@ import {createAdminAuthMiddleware,createApiKeyAuthMiddleware,createAuthMiddleware,- truefoundryAdminMiddleware,tryAuthenticate,} from './auth/middleware';import type { McpCatalog } from './catalog/McpCatalog';@@ -192,8 +190,6 @@ export interface ServerDeps<TTransaction> {resolveMcpServerStore: (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;/** Per-request store: DB singleton, or a token-bound TrueFoundry decorator in TrueFoundry mode. */resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;- /** Import agents: store with SF client constructor assume-user headers (DB store when TrueFoundry mode is off). */- resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore<TTransaction>;/*** Per-request store: DB singleton, or the env-backed shared store in TrueFoundry mode* (`TRUEFOUNDRY_SANDBOX_*` + static SETTINGS JSON).@@ -424,16 +420,6 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {adminAuthMiddleware,),);- app.route(- '/api/internal/import',- withAuth(- createAgentImportRouter({- sessionStore: deps.sessionStore,- resolveImportAgentStore: deps.resolveImportAgentStore,- }),- truefoundryAdminMiddleware,- ),- );app.route('/api/internal/sessions',withAuth(diff --git a/packages/trueforge/src/auth/middleware.ts b/packages/trueforge/src/auth/middleware.tsindex e1c1dfcf8..aaa1aa159 100644--- a/packages/trueforge/src/auth/middleware.ts+++ b/packages/trueforge/src/auth/middleware.ts@@ -2,7 +2,6 @@ import type { Context, MiddlewareHandler } from 'hono';import { HTTPException } from 'hono/http-exception';import { jwtVerify } from 'jose';-import configuration from '../config';import type { Authenticator } from './authenticator';import { toRequestContext, type IdTokenClaims } from './claims';import { hasAdminRole, type RequestContext } from './identity';@@ -47,29 +46,6 @@ export function createApiKeyAuthMiddleware(apiKey: string): MiddlewareHandler {};}-/**- * Service-to-service API key auth for internal import.- * Sets request_context so resolveAgentStore can build TrueFoundryAgentStore- * (needs user_credential for ServiceFoundry put/delete). Body supplies tenant_id.- */-export const truefoundryAdminMiddleware: MiddlewareHandler = async (c, next) => {- const token = extractRequestToken(c);- if (configuration.STANDALONE) {- throw new HTTPException(403, { message: 'Service API key required' });- }- const apiKey = configuration.TRUEFOUNDRY_API_KEY;- if (apiKey === undefined || token === undefined || token !== apiKey) {- throw new HTTPException(403, { message: 'Service API key required' });- }- c.set('request_context', {- tenant_id: 'system',- subject: { id: 'tfy-system', type: 'serviceaccount', display_name: 'tfy-system' },- roles: [],- user_credential: apiKey,- });- return next();-};-/*** Soft OIDC probe for login/callback — not request-gate middleware.*diff --git a/packages/trueforge/src/db/agentStore.ts b/packages/trueforge/src/db/agentStore.tsindex ee7935c73..6509b6949 100644--- a/packages/trueforge/src/db/agentStore.ts+++ b/packages/trueforge/src/db/agentStore.ts@@ -71,7 +71,6 @@ export interface CreateAgentInput {manifest: AgentSpec;external_id: string | null;created_by_subject: CreatedBySubject;- custom?: Record<string, unknown>;}/**diff --git a/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.tsindex f4aa5fde4..f4316cbda 100644--- a/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts+++ b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts@@ -1,10 +1,3 @@-import {- AgentSpecSchema,- type AgentSpec,- type SessionMetadata,- type TurnInputItem,- type TurnState,-} from '@truefoundry/trueforge-core/agent-session';import type { SessionRecord } from '@truefoundry/trueforge-core/agent-session/models/SessionRecord';import type { TurnRecord } from '@truefoundry/trueforge-core/agent-session/models/TurnRecord';import type { PersistedTurnEvent, SessionEventItem } from '@truefoundry/trueforge-core/agent-session/schemas/events';@@ -41,13 +34,8 @@ import {decodeOffsetPageToken,encodeOffsetPageToken,} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';-import type { AgentInfo, ContextMessage, JsonValue } from '@truefoundry/trueforge-core/core';-import type { CurrentContextUsage } from '@truefoundry/trueforge-core/core/runtime/contextUsage';import type { Kysely } from 'kysely';-import { sql } from 'kysely';-import type { ImportSessionRequest } from '../../../schemas/agentImport';-import { json, jsonUnknown } from '../sqlExpressions';-import type { Database, TurnCheckpoint, TurnThreadCheckpoint } from '../types';+import type { Database } from '../types';import { patchThreadCapabilityState as patchThreadCapabilityStateQuery } from './queries/capabilities';import {appendToEvents as appendToEventsQuery,@@ -82,17 +70,6 @@ import {updateTurnTerminalState as updateTurnTerminalStateQuery,} from './queries/turns';-/** Prefix on session.agent_id when the SF agent is not yet imported locally. */-const IMPORT_UNRESOLVED_AGENT_ID_PREFIX = 'tfy-import:';--/** Client/data rejection for session import — map to HTTP 4xx (not retryable). */-export class SessionImportValidationError extends Error {- constructor(message: string) {- super(message);- this.name = 'SessionImportValidationError';- }-}-type SessionCustom = Record<string, never>;type TurnCustom = Record<string, never>;@@ -264,205 +241,4 @@ export class PostgresSessionStore implements ISessionStore<SessionCustom, TurnCulistSessionEvents(input: ListSessionEventsInput): Promise<{ data: SessionEventItem[]; pagination: TokenPagination }> {return listSessionEventsQuery(this.db, input);}-- // --- temporary SF→TrueForge migration (remove after backfill) ----- async getImportSessionsCheckpoint(input: { tenant_id: string }): Promise<{ created_at: string | null }> {- const row = await this.db- .selectFrom('session')- .select(sql<string | null>`min(created_at)`.as('created_at'))- .where('tenant_id', '=', input.tenant_id)- .where(sql<boolean>`metadata @> ${json({ imported: 'true' })}`)- .executeTakeFirst();- if (row?.created_at == null) {- return { created_at: null };- }- return { created_at: new Date(row.created_at).toISOString() };- }-- async importSessionSnapshot(input: ImportSessionRequest): Promise<{ imported: boolean; session_id: string }> {- const sessionId = input.session.session_id;- const agentName = input.session.agent_name;- const agentSpec = input.session.agent_spec;- const sfAgentId = input.session.agent_id;- const hasName = typeof agentName === 'string' && agentName.length > 0;- const hasSpec = agentSpec != null;- const hasSfAgentId = typeof sfAgentId === 'string' && sfAgentId.length > 0;-- if (!hasName && !hasSpec) {- throw new SessionImportValidationError('Provide agent_name and/or agent_spec');- }-- let agentId: string | null = null;- let resolvedAgentName: string | null = null;- let resolvedAgentSpec: AgentSpec | null = null;- const metadata: SessionMetadata = { imported: 'true' };-- if (hasSpec) {- // Draft XOR: agent_spec on columns. SF may also send name/id — stash in metadata.- const parsedSpec = AgentSpecSchema.safeParse(agentSpec);- if (!parsedSpec.success) {- // Ops must fix the transformed spec; do not persist — session reads parse with AgentSpecSchema.- throw new Error(`Invalid agent_spec for session import: ${parsedSpec.error.message}`);- }- resolvedAgentSpec = parsedSpec.data;- if (hasName) {- metadata['agent_name'] = agentName;- }- if (hasSfAgentId) {- metadata['agent_id'] = sfAgentId;- }- } else if (hasName) {- const agent = await this.db- .selectFrom('agent')- .select(['id', 'name'])- .where('tenant_id', '=', input.session.tenant_id)- .where('name', '=', agentName)- .executeTakeFirst();- if (agent !== undefined) {- agentId = agent.id;- resolvedAgentName = agent.name;- } else {- if (!hasSfAgentId) {- throw new SessionImportValidationError(- `Named session import requires agent_id when agent "${agentName}" does not exist locally`,- );- }- // Stale ref until the agent is imported; prefix so it never collides with a TrueForge ULID.- agentId = `${IMPORT_UNRESOLVED_AGENT_ID_PREFIX}${sfAgentId}`;- resolvedAgentName = agentName;- metadata['agent_id'] = sfAgentId;- }- }-- return this.db.transaction().execute(async trx => {- const { session, turns } = input;- // ON CONFLICT DO NOTHING + RETURNING yields no row when session_id already exists- // (does not select the existing row) → inserted === undefined → imported: false.- const inserted = await trx- .insertInto('session')- .values({- tenant_id: session.tenant_id,- session_id: sessionId,- created_by_subject: json(session.created_by_subject),- source: null,- agent_id: agentId,- agent_name: resolvedAgentName,- agent_spec: resolvedAgentSpec !== null ? jsonUnknown<AgentSpec>(resolvedAgentSpec) : null,- title: session.title,- shared: false,- last_turn_id: session.last_turn_id,- custom: session.custom !== null ? json(session.custom) : null,- metadata: json(metadata),- external_id: null,- metrics: json({ total_duration_ms: 0, total_turns: turns.length }),- last_activity_timestamp_ms: session.last_activity_timestamp_ms,- created_at: new Date(session.created_at),- updated_at: new Date(session.updated_at),- })- .onConflict(oc => oc.column('session_id').doNothing())- .returning('session_id')- .executeTakeFirst();- if (inserted === undefined) {- return { imported: false, session_id: sessionId };- }-- for (const turn of turns) {- const turnId = turn.turn_id;- const updatedAt = new Date(turn.updated_at);- // import: source_turn_ids can be in a different format. source executors are gone; do not parse turn_id.- const activeExecutorId = 'default';- await trx- .insertInto('turn')- .values({- session_id: sessionId,- turn_id: turnId,- first_turn_id: turn.first_turn_id,- previous_turn_id: turn.previous_turn_id,- ancestor_ids: turn.ancestor_ids,- active_executor_id: activeExecutorId,- input: jsonUnknown<TurnInputItem[]>(turn.input),- state: jsonUnknown<TurnState>(turn.state),- checkpoint: jsonUnknown<TurnCheckpoint>(turn.checkpoint ?? { mcp_servers: null, sandbox_info: null }),- custom: turn.custom !== null ? json(turn.custom) : null,- created_at: new Date(turn.created_at),- updated_at: updatedAt,- })- .execute();-- for (const thread of turn.threads) {- const threadId = thread.thread_id;- const contextIds: number[] = [];- if (thread.context.length > 0) {- const rows = await trx- .insertInto('thread_context_log')- .values(- thread.context.map(msg => ({- session_id: sessionId,- thread_id: threadId,- turn_id: turnId,- body: jsonUnknown<ContextMessage>(msg),- created_at: updatedAt,- })),- )- .returning(['append_id'])- .execute();- for (const row of rows) {- contextIds.push(row.append_id);- }- }-- await trx- .insertInto('turn_thread')- .values({- session_id: sessionId,- turn_id: turnId,- thread_id: threadId,- checkpoint: jsonUnknown<TurnThreadCheckpoint>({- parent: thread.parent,- completion: thread.completion,- }),- agent_info: thread.agent_info !== null ? jsonUnknown<AgentInfo>(thread.agent_info) : null,- current_context_usage: jsonUnknown<CurrentContextUsage>(thread.current_context_usage),- context_ids: contextIds,- updated_at: updatedAt,- })- .execute();-- if (thread.capability_state !== null && Object.keys(thread.capability_state).length > 0) {- await trx- .insertInto('thread_capability_state')- .values(- Object.entries(thread.capability_state).map(([key, state]) => ({- session_id: sessionId,- turn_id: turnId,- thread_id: threadId,- key,- state: jsonUnknown<JsonValue>(state),- updated_at: updatedAt,- })),- )- .execute();- }- }-- if (turn.events.length > 0) {- await trx- .insertInto('session_event')- .values(- turn.events.map(event => ({- session_id: sessionId,- turn_id: turnId,- event_id: event.id,- event: jsonUnknown<PersistedTurnEvent>(event),- created_at: new Date(event.created_at),- })),- )- .execute();- }- }-- return { imported: true, session_id: sessionId };- });- }}diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex 0a0f0fe19..a62c53c8c 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -168,8 +168,6 @@ interface ServerPersistence<TTransaction> {/** Per-request store: DB git skills, or TrueFoundry registry catalog in TrueFoundry mode. */resolveSkillStore: (rc: RequestContext) => ISkillStore<TTransaction>;resolveAgentStore: (rc: RequestContext) => IAgentStore<TTransaction>;- /** Import agents: SF assume-user headers on the client; DB store when TrueFoundry mode is off. */- resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore<TTransaction>;/** extra pre-resolved stores for scheduled runs */agentStore: IAgentStore<TTransaction>;sandboxEnvironmentStore: ISandboxEnvironmentStore<TTransaction>;@@ -184,10 +182,7 @@ interface ServerPersistence<TTransaction> {}/** Shared ServiceFoundry HTTP client when TrueFoundry mode is on; otherwise undefined. */-function createServiceFoundryServerClient(- logger: Logger,- headers?: Record<string, string>,-): TrueFoundryServiceFoundryServerClient | undefined {+function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFoundryServerClient | undefined {if (!isTrueFoundryModeEnabled(configuration)) {return undefined;}@@ -204,7 +199,6 @@ function createServiceFoundryServerClient(httpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },apiKey,- ...(headers !== undefined ? { headers } : {}),});}@@ -415,7 +409,6 @@ async function createStandalonePersistence(options: {resolveWebSearchProviderStore: () => webSearchProviderStore,resolveSkillStore: () => skillStore,resolveAgentStore: () => agentStore,- resolveImportAgentStore: () => agentStore,agentStore,sandboxEnvironmentStore,sandboxProviderStore,@@ -533,25 +526,6 @@ async function createDistributedPersistence(options: {db,client: serviceFoundryClient,});- const resolveImportAgentStore = (- serviceFoundryServerHeaders: Record<string, string>,- ): IAgentStore<Transaction<PostgresDatabase>> => {- const client = createServiceFoundryServerClient(logger, serviceFoundryServerHeaders);- if (client === undefined) {- return agentStore;- }- return new TrueFoundryAgentStore({- inner: agentStore,- client,- context: {- tenant_id: 'system',- subject: { id: 'tfy-system', type: 'serviceaccount', display_name: 'tfy-system' },- roles: [],- user_credential: client.apiKey,- },- db,- });- };const resolveSandboxProviderStore = buildResolveSandboxProviderStore({persistenceStore: sandboxProviderStore,});@@ -575,7 +549,6 @@ async function createDistributedPersistence(options: {resolveWebSearchProviderStore,resolveSkillStore,resolveAgentStore,- resolveImportAgentStore,agentStore,sandboxEnvironmentStore,sandboxProviderStore: resolveSandboxProviderStore(STANDALONE_REQUEST_CONTEXT),@@ -609,7 +582,6 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<tokenStore,scheduleStore,mcpOAuthStore,- resolveImportAgentStore,agentStore,sandboxEnvironmentStore,turnSkillsResolverStore,@@ -716,7 +688,6 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<resolveModelProviderStore,resolveMcpServerStore,resolveAgentStore,- resolveImportAgentStore,resolveSandboxProviderStore,resolveWebSearchProviderStore,resolveSkillStore,diff --git a/packages/trueforge/src/routes/agentImportRoutes.ts b/packages/trueforge/src/routes/agentImportRoutes.tsdeleted file mode 100644index a560cd138..000000000--- a/packages/trueforge/src/routes/agentImportRoutes.ts+++ /dev/null@@ -1,102 +0,0 @@-/**- * Ops import routes mounted at /api/internal/import.- */-import { createRoute } from '@hono/zod-openapi';-import {- ImportAgentsRequestSchema,- ImportAgentsResponseSchema,- ImportSessionRequestSchema,- ImportSessionResponseSchema,- ImportSessionsCheckpointQuerySchema,- ImportSessionsCheckpointResponseSchema,-} from '../schemas/agentImport';-import { RequestErrorResponseSchema } from '../schemas/errors';-import { OpenApiTag } from './openapiTags';--export const importAgentsRoute = createRoute({- method: 'post',- path: '/agents',- tags: [OpenApiTag.INTERNAL],- summary: 'Import agents in bulk (create)',- description: 'Ops/backfill only. Per-item created | exists | failed.',- 'x-fern-ignore': true,- 'x-excluded': true,- request: {- body: {- content: { 'application/json': { schema: ImportAgentsRequestSchema } },- required: true,- },- },- responses: {- 200: {- content: { 'application/json': { schema: ImportAgentsResponseSchema } },- description: 'Per-agent create results.',- },- 400: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Invalid body.',- },- },-});--export const importSessionRoute = createRoute({- method: 'post',- path: '/sessions',- tags: [OpenApiTag.INTERNAL],- summary: 'Import one historical session snapshot',- description:- 'Ops/backfill only. Named sessions link agent_name to a local agent when present; otherwise a dummy agent_id. Drafts use agent_spec (SF name/id stashed in metadata when both present). 409 if session_id exists.',- 'x-fern-ignore': true,- 'x-excluded': true,- request: {- body: {- content: { 'application/json': { schema: ImportSessionRequestSchema } },- required: true,- },- },- responses: {- 201: {- content: { 'application/json': { schema: ImportSessionResponseSchema } },- description: 'Imported.',- },- 400: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Invalid body or non-importable session (e.g. missing agent_id for unresolved named agent).',- },- 409: {- content: { 'application/json': { schema: ImportSessionResponseSchema } },- description: 'Session already exists.',- },- 500: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Internal server error.',- },- },-});--export const getImportSessionsCheckpointRoute = createRoute({- method: 'get',- path: '/checkpoint',- tags: [OpenApiTag.INTERNAL],- summary: 'Session import checkpoint',- description: 'Min created_at among imported sessions for one tenant (metadata.imported=true).',- 'x-fern-ignore': true,- 'x-excluded': true,- request: {- query: ImportSessionsCheckpointQuerySchema,- },- responses: {- 200: {- content: { 'application/json': { schema: ImportSessionsCheckpointResponseSchema } },- description: 'Per-tenant checkpoint watermark.',- },- 400: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Invalid query.',- },- 500: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Internal server error.',- },- },-});diff --git a/packages/trueforge/src/schemas/agentImport.ts b/packages/trueforge/src/schemas/agentImport.tsdeleted file mode 100644index 3e05086f4..000000000--- a/packages/trueforge/src/schemas/agentImport.ts+++ /dev/null@@ -1,157 +0,0 @@-/**- * Wire schemas for POST /api/internal/import/agents and /sessions (+ GET /checkpoint).- */-import { z } from '@hono/zod-openapi';-import { AgentSpecSchema, CreatedBySubjectSchema } from '@truefoundry/trueforge-core/agent-session';-import { AgentDescriptionSchema } from './agent';-import { NameSchema } from './common';--const RESERVED_AGENT_NAMES = new Set(['tfg', 'trueforge']);--/** One import row: same fields as create-agent, plus explicit tenant and creator. */-export const ImportAgentItemSchema = z- .object({- name: NameSchema.refine(name => !RESERVED_AGENT_NAMES.has(name), {- message: 'Agent name is reserved, cannot be used',- }),- description: AgentDescriptionSchema.optional(),- manifest: AgentSpecSchema,- tenant_id: z.string().min(1).describe('Tenant to create the agent under.'),- created_by_subject: CreatedBySubjectSchema.describe('Original creator to persist on the agent.'),- truefoundry_managed_agent_id: z.string(),- })- .strict()- .openapi('ImportAgentItem');--export const ImportAgentsRequestSchema = z- .object({- agents: z.array(ImportAgentItemSchema).describe('Agents to create; each carries tenant_id and created_by_subject.'),- })- .strict()- .openapi('ImportAgentsRequest');--export const ImportAgentItemResultSchema = z- .object({- name: z.string().min(1),- tenant_id: z.string().min(1),- status: z.enum(['created', 'exists', 'failed']),- agent_id: z.string().min(1).optional(),- error: z.string().optional(),- })- .strict()- .openapi('ImportAgentItemResult');--export const ImportAgentsResultSchema = z- .object({- results: z.array(ImportAgentItemResultSchema),- })- .strict()- .openapi('ImportAgentsResult');--export const ImportAgentsResponseSchema = z- .object({- data: ImportAgentsResultSchema,- })- .strict()- .openapi('ImportAgentsResponse');--export type ImportAgentItem = z.infer<typeof ImportAgentItemSchema>;-export type ImportAgentsRequest = z.infer<typeof ImportAgentsRequestSchema>;-export type ImportAgentItemResult = z.infer<typeof ImportAgentItemResultSchema>;-export type ImportAgentsResponse = z.infer<typeof ImportAgentsResponseSchema>;--export const ImportSessionSnapshotSchema = z- .object({- session_id: z.string().min(1),- tenant_id: z.string().min(1),- created_by_subject: CreatedBySubjectSchema,- agent_name: z.string().min(1).nullable().optional(),- agent_id: z.string().min(1).nullable().optional(),- agent_spec: z.record(z.string(), z.unknown()).nullable().optional(),- title: z.string().nullable(),- last_turn_id: z.string().nullable(),- custom: z.record(z.string(), z.unknown()).nullable(),- last_activity_timestamp_ms: z.number(),- created_at: z.string().min(1),- updated_at: z.string().min(1),- })- .loose()- .openapi('ImportSessionSnapshot');--export const ImportSessionThreadSchema = z- .object({- thread_id: z.string().min(1),- context: z.array(z.unknown()),- current_context_usage: z.unknown(),- parent: z.unknown().nullable(),- completion: z.unknown().nullable(),- agent_info: z.unknown().nullable(),- capability_state: z.record(z.string(), z.unknown()).nullable(),- })- .loose()- .openapi('ImportSessionThread');--export const ImportSessionEventSchema = z- .object({- id: z.string().min(1),- created_at: z.string().min(1),- })- .loose()- .openapi('ImportSessionEvent');--export const ImportSessionTurnSchema = z- .object({- turn_id: z.string().min(1),- first_turn_id: z.string().min(1),- previous_turn_id: z.string().nullable(),- ancestor_ids: z.array(z.string()),- input: z.array(z.unknown()),- state: z.unknown(),- checkpoint: z.unknown(),- custom: z.record(z.string(), z.unknown()).nullable(),- created_at: z.string().min(1),- updated_at: z.string().min(1),- threads: z.array(ImportSessionThreadSchema),- events: z.array(ImportSessionEventSchema),- })- .loose()- .openapi('ImportSessionTurn');--/** Loose session snapshot for ops backfill. */-export const ImportSessionRequestSchema = z- .object({- session: ImportSessionSnapshotSchema,- turns: z.array(ImportSessionTurnSchema).min(1),- })- .openapi('ImportSessionRequest');--export const ImportSessionResultSchema = z- .object({- imported: z.boolean(),- session_id: z.string(),- })- .openapi('ImportSessionResult');--export const ImportSessionResponseSchema = z- .object({ data: ImportSessionResultSchema })- .openapi('ImportSessionResponse');--export const ImportSessionsCheckpointQuerySchema = z- .object({- tenant_id: z.string().min(1).describe('Tenant whose imported-session watermark to read.'),- })- .strict()- .openapi('ImportSessionsCheckpointQuery');--export const ImportSessionsCheckpointResponseSchema = z- .object({- data: z.object({- created_at: z.string().nullable(),- }),- })- .strict()- .openapi('ImportSessionsCheckpointResponse');--export type ImportSessionRequest = z.infer<typeof ImportSessionRequestSchema>;-export type ImportSessionResult = z.infer<typeof ImportSessionResultSchema>;-export type ImportSessionsCheckpointQuery = z.infer<typeof ImportSessionsCheckpointQuerySchema>;diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.tsindex c7882a006..c6b7464ad 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts@@ -34,19 +34,16 @@ function toPutRemoteAgentPayload({name,description,manifest,- trueFoundryManagedAgentId,}: {name: string;description: string;manifest: AgentSpec;- trueFoundryManagedAgentId?: string;}): Omit<PutRemoteAgentInput, 'accessToken'> {return {name,description: (description || name).slice(0, AGENT_DESCRIPTION_MAX_LENGTH),model: manifest.model.name,mcp_servers: (manifest.mcp_servers ?? []).map(server => server.name),- ...(trueFoundryManagedAgentId ? { trueFoundryManagedAgentId } : {}),};}@@ -156,14 +153,12 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>let externalId: string | undefined;try {- const trueFoundryManagedAgentId = input.custom?.['trueFoundryManagedAgentId'] as string | undefined;({ externalId } = await this.#client.putRemoteAgent({accessToken: await this.#resolveAccessToken(),...toPutRemoteAgentPayload({name: input.name,description: input.description,manifest: input.manifest,- ...(trueFoundryManagedAgentId ? { trueFoundryManagedAgentId } : {}),}),}));const updated = await this.#inner.updateAgent(diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.tsindex 1526d7896..95cfa0b63 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts@@ -115,7 +115,6 @@ export interface PutRemoteAgentInput {description: string;model: string;mcp_servers: string[];- trueFoundryManagedAgentId?: string;}export interface PutRemoteAgentResult {@@ -127,15 +126,6 @@ export interface DeleteRemoteAgentInput {externalId: string;}-/** SF admin assume-user: `serviceaccount/{tenant}/truefoundry/tfy-system`. */-export const TFY_ASSUME_USER_HEADER = 'x-tfy-assume-user';-const TFY_SYSTEM_ASSUME_SUBJECT = 'truefoundry';-const TFY_SYSTEM_CONTROLLER = 'tfy-system';--export function tenantSystemAssumeUserHeader(tenantName: string): string {- return `serviceaccount/${tenantName}/${TFY_SYSTEM_ASSUME_SUBJECT}/${TFY_SYSTEM_CONTROLLER}`;-}-async function readServiceFoundryErrorMessage(response: Awaited<ReturnType<typeof undiciFetch>>,): Promise<string | undefined> {@@ -160,7 +150,6 @@ export class TrueFoundryServiceFoundryServerClient {readonly #httpTimeoutMs: number;readonly #httpAgentTimeoutMs: number;readonly #apiKey: string;- readonly #headers: Record<string, string>;readonly #controlPlaneUrlByTenant = new LRUCache<string, string>({max: TENANT_CONTROL_PLANE_URL_CACHE_MAX,ttl: TENANT_CONTROL_PLANE_URL_TTL_MS,@@ -174,8 +163,6 @@ export class TrueFoundryServiceFoundryServerClient {httpAgentTimeoutMs: number;/** Service API key for vend-token and other privileged SFY calls. */apiKey: string;- /** Extra headers on every request (e.g. `x-tfy-assume-user` for import). */- headers?: Record<string, string>;}) {const tls = input.tls;this.#baseUrl = normalizeInternalTlsUrl({ url: input.serviceFoundryServerUrl, enabled: tls.enabled }).replace(@@ -187,7 +174,6 @@ export class TrueFoundryServiceFoundryServerClient {this.#httpTimeoutMs = input.httpTimeoutMs;this.#httpAgentTimeoutMs = input.httpAgentTimeoutMs;this.#apiKey = input.apiKey;- this.#headers = input.headers ?? {};}/** Service API key (`TRUEFOUNDRY_API_KEY`); callers pass it explicitly when needed. */@@ -268,7 +254,6 @@ export class TrueFoundryServiceFoundryServerClient {/** PUT `/internal/tfg/agents` — create/reuse remote agent + sync model/MCP grants. */async putRemoteAgent(input: PutRemoteAgentInput): Promise<PutRemoteAgentResult> {- const hasTrueFoundryManagedAgentId = input.trueFoundryManagedAgentId !== undefined;const payload = await this.#requestJson({url: this.#url(TFG_AGENTS_PATH),accessToken: input.accessToken,@@ -279,7 +264,6 @@ export class TrueFoundryServiceFoundryServerClient {description: input.description,model: input.model,mcp_servers: input.mcp_servers,- ...(hasTrueFoundryManagedAgentId ? { trueFoundryManagedAgentId: input.trueFoundryManagedAgentId } : {}),},});const parsed = PutRemoteAgentResponseSchema.safeParse(payload);@@ -685,7 +669,6 @@ export class TrueFoundryServiceFoundryServerClient {const headers: Record<string, string> = {accept: 'application/json',authorization: `Bearer ${input.accessToken}`,- ...this.#headers,};let body: string | undefined;if (input.body !== undefined) {