The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: add agent sesison migrate endpoint (#487)
Sujai Kumar Gupta349e420dac2d
diff --git a/.changeset/20260908121652-regenerate-sdk-from-openapi.md b/.changeset/20260908121652-regenerate-sdk-from-openapi.mdnew file mode 100644index 000000000..efd8ff00f--- /dev/null+++ b/.changeset/20260908121652-regenerate-sdk-from-openapi.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge-sdk": patch+---++Regenerate SDK from updated OpenAPI spec.diff --git a/.changeset/internal-import-agents.md b/.changeset/internal-import-agents.mdnew file mode 100644index 000000000..ea2bf0098--- /dev/null+++ b/.changeset/internal-import-agents.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge": patch+---++Add internal POST /api/internal/import/agents and POST /sessions (snapshot) plus GET /checkpoint?tenant_id= for SF→TrueForge backfill. Import requires the service API key. Named session import links a local agent when present (or SF agent_id / dummy). Drafts use agent_spec; when SF also sends name/id those go in metadata. Checkpoint is per-tenant min created_at of imported sessions.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex c2dfa1fd7..b4d66e8eb 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -1674,6 +1674,382 @@],"type": "object"},+ "ImportAgentItem": {+ "additionalProperties": false,+ "properties": {+ "created_by_subject": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CreatedBySubject"+ },+ {+ "description": "Original creator to persist on the agent."+ }+ ]+ },+ "manifest": {+ "$ref": "#/components/schemas/AgentSpec"+ },+ "name": {+ "$ref": "#/components/schemas/ResourceName"+ },+ "tenant_id": {+ "description": "Tenant to create the agent under.",+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "name",+ "manifest",+ "tenant_id",+ "created_by_subject"+ ],+ "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": {@@ -5182,6 +5558,165 @@},"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-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-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-fern-ignore": true+ }+ },"/api/internal/list-permissions": {"post": {"description": "Return granted actions for each requested agent, schedule, or session id.",diff --git a/docs/openapi.json b/docs/openapi.jsonindex c2dfa1fd7..b4d66e8eb 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -1674,6 +1674,382 @@],"type": "object"},+ "ImportAgentItem": {+ "additionalProperties": false,+ "properties": {+ "created_by_subject": {+ "allOf": [+ {+ "$ref": "#/components/schemas/CreatedBySubject"+ },+ {+ "description": "Original creator to persist on the agent."+ }+ ]+ },+ "manifest": {+ "$ref": "#/components/schemas/AgentSpec"+ },+ "name": {+ "$ref": "#/components/schemas/ResourceName"+ },+ "tenant_id": {+ "description": "Tenant to create the agent under.",+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "name",+ "manifest",+ "tenant_id",+ "created_by_subject"+ ],+ "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": {@@ -5182,6 +5558,165 @@},"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-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-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-fern-ignore": true+ }+ },"/api/internal/list-permissions": {"post": {"description": "Return granted actions for each requested agent, schedule, or session id.",diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.tsindex c28cb1afe..5628637d1 100644--- a/packages/trueforge/scripts/write-openapi.ts+++ b/packages/trueforge/scripts/write-openapi.ts@@ -80,6 +80,7 @@ const app = createServerApp({sandboxCatalog: SandboxCatalog.load(),resolveSandboxProviderStore: () => new SqliteSandboxProviderStore(db),resolveAgentStore: () => agentStore,+ resolveImportAgentStore: () => agentStore,scheduleStore: new SqliteScheduleStore(db),sessionStore,sessionMetricsStore: new SqliteSessionMetricsStore(db),diff --git a/packages/trueforge/src/apis/agentImport.ts b/packages/trueforge/src/apis/agentImport.tsnew file mode 100644index 000000000..24e144f75--- /dev/null+++ b/packages/trueforge/src/apis/agentImport.ts@@ -0,0 +1,112 @@+/**+ * 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,+ manifest: agent.manifest,+ external_id: null,+ created_by_subject: agent.created_by_subject,+ });+ 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 4cf431e2c..26e9456a7 100644--- a/packages/trueforge/src/app.ts+++ b/packages/trueforge/src/app.ts@@ -10,6 +10,7 @@ import { HTTPException } from 'hono/http-exception';import type { Configuration } from 'openid-client';import type { RedisClientType } from 'redis';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';@@ -27,7 +28,7 @@ import { createTurnsRouter } from './apis/turns';import type { Authenticator } from './auth/authenticator';import type { Authorizer } from './auth/authorizer';import { resolveRequestContext } from './auth/identity';-import { createAdminAuthMiddleware, createAuthMiddleware } from './auth/middleware';+import { createAdminAuthMiddleware, createAuthMiddleware, truefoundryAdminMiddleware } from './auth/middleware';import type { McpCatalog } from './catalog/McpCatalog';import type { ModelCatalog } from './catalog/ModelCatalog';import type { SandboxCatalog } from './catalog/SandboxCatalog';@@ -178,6 +179,8 @@ 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).@@ -356,6 +359,16 @@ 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 64ee2bf65..03b3f3fdf 100644--- a/packages/trueforge/src/auth/middleware.ts+++ b/packages/trueforge/src/auth/middleware.ts@@ -2,6 +2,7 @@ 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';@@ -28,6 +29,29 @@ export function createAdminAuthMiddleware(authenticator: Authenticator): Middlew};}+/**+ * 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/postgres/session-store/PostgresSessionStore.ts b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.tsindex 1462a087f..a44502cc7 100644--- a/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts+++ b/packages/trueforge/src/db/postgres/session-store/PostgresSessionStore.ts@@ -1,3 +1,10 @@+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';@@ -32,8 +39,13 @@ 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 type { Database } from '../types';+import { sql } from 'kysely';+import type { ImportSessionRequest } from '../../../schemas/agentImport';+import { json, jsonUnknown } from '../sqlExpressions';+import type { Database, TurnCheckpoint, TurnThreadCheckpoint } from '../types';import { patchThreadCapabilityState as patchThreadCapabilityStateQuery } from './queries/capabilities';import {appendToEvents as appendToEventsQuery,@@ -66,6 +78,17 @@ import {updateTurnState as updateTurnStateQuery,} 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>;@@ -227,4 +250,201 @@ 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,+ 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);+ 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,+ 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/db/postgres/sqlExpressions.ts b/packages/trueforge/src/db/postgres/sqlExpressions.tsindex 3e92b773c..3c4cb514f 100644--- a/packages/trueforge/src/db/postgres/sqlExpressions.ts+++ b/packages/trueforge/src/db/postgres/sqlExpressions.ts@@ -9,6 +9,11 @@ export function json<T>(value: T): RawBuilder<T> {return sql`${JSON.stringify(value)}::jsonb`;}+/** Same as {@link json} for loosely typed import payloads. */+export function jsonUnknown<T>(value: unknown): RawBuilder<T> {+ return sql`${JSON.stringify(value)}::jsonb`;+}+/*** `jsonb_set(target, path, new_value)`.* `path` may be a text[] expression (`sql\`ARRAY['threads', ${id}]\``) or a literal pathdiff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex 237263b60..28ffb90c2 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -104,6 +104,8 @@ interface ServerPersistence<TTransaction> {resolveModelProviderStore: (c: Context, runAsAgent?: AgentRecord) => IModelProviderStore<TTransaction>;resolveMcpServerStore: (c?: Context, runAsAgent?: AgentRecord) => IMcpServerWithAuthStore<TTransaction>;resolveAgentStore: (c: Context) => IAgentStore<TTransaction>;+ /** Import agents: SF assume-user headers on the client; DB store when TrueFoundry mode is off. */+ resolveImportAgentStore: (serviceFoundryServerHeaders: Record<string, string>) => IAgentStore<TTransaction>;resolveSandboxProviderStore: (c: Context) => ISandboxProviderStore<TTransaction>;withTransaction: WithTransaction<TTransaction>;tokenStore: IOAuthTokenStore<TTransaction>;@@ -117,7 +119,10 @@ interface ServerPersistence<TTransaction> {}/** Shared ServiceFoundry HTTP client when TrueFoundry mode is on; otherwise undefined. */-function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFoundryServerClient | undefined {+function createServiceFoundryServerClient(+ logger: Logger,+ headers?: Record<string, string>,+): TrueFoundryServiceFoundryServerClient | undefined {if (!isTrueFoundryModeEnabled(configuration)) {return undefined;}@@ -134,6 +139,7 @@ function createServiceFoundryServerClient(logger: Logger): TrueFoundryServiceFouhttpAgentTimeoutMs: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_AGENT_TIMEOUT_MS,tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },apiKey,+ ...(headers !== undefined ? { headers } : {}),});}@@ -299,6 +305,7 @@ async function createStandalonePersistence(options: {resolveModelProviderStore: () => modelProviderStore,resolveMcpServerStore: () => mcpServerStore,resolveAgentStore: () => agentStore,+ resolveImportAgentStore: () => agentStore,resolveSandboxProviderStore: () => sandboxProviderStore,withTransaction: callback => db.transaction().execute(callback),tokenStore,@@ -384,6 +391,25 @@ 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: new PostgresSandboxProviderStore(db),});@@ -394,6 +420,7 @@ async function createDistributedPersistence(options: {resolveModelProviderStore,resolveMcpServerStore,resolveAgentStore,+ resolveImportAgentStore,resolveSandboxProviderStore,withTransaction: callback => db.transaction().execute(callback),tokenStore,@@ -416,6 +443,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<resolveModelProviderStore,resolveMcpServerStore,resolveAgentStore,+ resolveImportAgentStore,resolveSandboxProviderStore,withTransaction,tokenStore,@@ -476,6 +504,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<resolveModelProviderStore,resolveMcpServerStore,resolveAgentStore,+ resolveImportAgentStore,resolveSandboxProviderStore,withTransaction,tokenStore,diff --git a/packages/trueforge/src/routes/agentImportRoutes.ts b/packages/trueforge/src/routes/agentImportRoutes.tsnew file mode 100644index 000000000..0fd30b271--- /dev/null+++ b/packages/trueforge/src/routes/agentImportRoutes.ts@@ -0,0 +1,99 @@+/**+ * 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,+ 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,+ 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,+ 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.tsnew file mode 100644index 000000000..6cf9f749e--- /dev/null+++ b/packages/trueforge/src/schemas/agentImport.ts@@ -0,0 +1,154 @@+/**+ * 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 { 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',+ }),+ 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.'),+ })+ .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 914977971..d237ee568 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts@@ -145,7 +145,10 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>const failures = [asError(error)];if (externalId !== undefined) {try {- await this.#client.deleteRemoteAgent({ accessToken: await this.#resolveAccessToken(), externalId });+ await this.#client.deleteRemoteAgent({+ accessToken: await this.#resolveAccessToken(),+ externalId,+ });} catch (cleanupError) {failures.push(asError(cleanupError));}@@ -194,7 +197,10 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>try {await this.#client.putRemoteAgent({accessToken: await this.#resolveAccessToken(),- ...toPutRemoteAgentPayload({ name: previous.name, manifest: previous.manifest }),+ ...toPutRemoteAgentPayload({+ name: previous.name,+ manifest: previous.manifest,+ }),});} catch (restoreError) {throw new AggregateError(diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.tsindex 596ea98ce..a164b661f 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts@@ -105,6 +105,15 @@ 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> {@@ -129,6 +138,7 @@ export class TrueFoundryServiceFoundryServerClient {readonly #httpTimeoutMs: number;readonly #httpAgentTimeoutMs: number;readonly #apiKey: string;+ readonly #headers: Record<string, string>;constructor(input: {serviceFoundryServerUrl: string;@@ -138,6 +148,8 @@ 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(@@ -149,6 +161,7 @@ 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. */@@ -584,6 +597,7 @@ 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) {diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.tsindex 50028fb48..431517368 100644--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts@@ -308,7 +308,10 @@ describe('TrueFoundryAgentStore', () => {TXN,),).rejects.toThrow('db update failed');- expect(deleteRemoteAgent).toHaveBeenCalledWith({ accessToken: TOKEN, externalId: 'sf-1' });+ expect(deleteRemoteAgent).toHaveBeenCalledWith({+ accessToken: TOKEN,+ externalId: 'sf-1',+ });expect(deleteAgent).toHaveBeenCalledWith({ tenant_id: TENANT, id: local.id }, TXN);});@@ -580,7 +583,10 @@ describe('TrueFoundryAgentStore', () => {});await store.deleteAgent({ tenant_id: TENANT, id: previous.id });- expect(deleteRemoteAgent).toHaveBeenCalledWith({ accessToken: TOKEN, externalId: 'sf-1' });+ expect(deleteRemoteAgent).toHaveBeenCalledWith({+ accessToken: TOKEN,+ externalId: 'sf-1',+ });expect(deleteAgent).toHaveBeenCalledWith({ tenant_id: TENANT, id: previous.id }, TXN);expect(firstInvocationOrder(deleteRemoteAgent)).toBeLessThan(firstInvocationOrder(deleteAgent));});